genclass 0.3.6 → 0.3.7

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/genclass.mjs CHANGED
@@ -12,7 +12,7 @@ var __export = (target, all) => {
12
12
  var define_GENCLASS_BUILD_default;
13
13
  var init_define_GENCLASS_BUILD = __esm({
14
14
  "<define:__GENCLASS_BUILD__>"() {
15
- define_GENCLASS_BUILD_default = { version: "0.3.6", runtimeVersion: "0.3.0-beta.6", mcpVersion: "0.2.2", workflow: `# GenClass on your existing Playwright suite: no change to your tests or your playwright.config.
15
+ define_GENCLASS_BUILD_default = { version: "0.3.7", runtimeVersion: "0.3.0-beta.6", mcpVersion: "0.2.2", workflow: `# GenClass on your existing Playwright suite: no change to your tests or your playwright.config.
16
16
  # Copy to .github/workflows/genclass.yml.
17
17
  #
18
18
  # Assumes "npx playwright test" works on a fresh checkout with dependencies installed, which usually
@@ -228,6 +228,24 @@ var init_token = __esm({
228
228
  });
229
229
 
230
230
  // ../runtime/bin/lib/account.mjs
231
+ var account_exports = {};
232
+ __export(account_exports, {
233
+ CLIENT_NAME: () => CLIENT_NAME,
234
+ claimProject: () => claimProject,
235
+ cleanProject: () => cleanProject,
236
+ createAccountProject: () => createAccountProject,
237
+ credentialsPath: () => credentialsPath,
238
+ deleteCredentials: () => deleteCredentials,
239
+ failure: () => failure,
240
+ fetchMe: () => fetchMe,
241
+ pollDeviceLogin: () => pollDeviceLogin,
242
+ readCredentials: () => readCredentials,
243
+ readCredentialsFor: () => readCredentialsFor,
244
+ request: () => request,
245
+ revokeSession: () => revokeSession,
246
+ saveCredentials: () => saveCredentials,
247
+ startDeviceLogin: () => startDeviceLogin
248
+ });
231
249
  import { chmodSync, mkdirSync, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
232
250
  import { homedir } from "node:os";
233
251
  import { dirname, isAbsolute, join as join2 } from "node:path";
@@ -812,7 +830,7 @@ function walkSources(dir, max = 2e4) {
812
830
  return outFiles.sort();
813
831
  }
814
832
  function walkSkipped(dir, max = 2e4) {
815
- const seen = new Set(walkSources(dir));
833
+ const seen2 = new Set(walkSources(dir));
816
834
  const outFiles = [];
817
835
  const stack = [[dir, 0]];
818
836
  while (stack.length && outFiles.length < max) {
@@ -828,7 +846,7 @@ function walkSkipped(dir, max = 2e4) {
828
846
  if (!NEVER_SCAN.has(e.name) && depth < 30) stack.push([join4(d, e.name), depth + 1]);
829
847
  } else if (e.isFile() && SRC_EXT.test(e.name)) {
830
848
  const p = join4(d, e.name);
831
- if (seen.has(p)) continue;
849
+ if (seen2.has(p)) continue;
832
850
  try {
833
851
  if (statSync2(p).size <= 1e6) outFiles.push(p);
834
852
  } catch {
@@ -1268,14 +1286,14 @@ function markedRanges(parts) {
1268
1286
  function planRemoval(text) {
1269
1287
  const { lines: segs, problems: problems2 } = stripInline(text);
1270
1288
  const parts = segs.map((s) => s.text);
1271
- const marked = markedRanges(parts);
1272
- for (const p of marked.problems) problems2.push({ line: segs[p.line - 1].line, reason: p.reason });
1289
+ const marked2 = markedRanges(parts);
1290
+ for (const p of marked2.problems) problems2.push({ line: segs[p.line - 1].line, reason: p.reason });
1273
1291
  const flagged = new Set(problems2.map((p) => p.line));
1274
1292
  segs.forEach((s) => {
1275
1293
  if (s.text.includes(MARK_INLINE) && !flagged.has(s.line)) problems2.push({ line: s.line, reason: `the "${MARK_INLINE}" marker is not next to the element init added (edited?)` });
1276
1294
  });
1277
1295
  const drop = new Set(segs.flatMap((s, i) => s.drop ? [i] : []));
1278
- for (const [a, b] of marked.ranges) for (let x = a; x <= b; x++) drop.add(x);
1296
+ for (const [a, b] of marked2.ranges) for (let x = a; x <= b; x++) drop.add(x);
1279
1297
  const kept = [];
1280
1298
  for (let i = 0; i < parts.length; i++) {
1281
1299
  if (!drop.has(i)) {
@@ -2034,6 +2052,7 @@ __export(init_exports, {
2034
2052
  USAGE: () => USAGE,
2035
2053
  UsageError: () => UsageError,
2036
2054
  accountLabel: () => accountLabel,
2055
+ accountWhere: () => accountWhere,
2037
2056
  configOf: () => configOf,
2038
2057
  hostNotice: () => hostNotice,
2039
2058
  init: () => init,
@@ -2211,8 +2230,8 @@ function printMoneyAdvice(money, cfgFile) {
2211
2230
  }
2212
2231
  function printLittleToWatch(kind) {
2213
2232
  if (!kind) return;
2214
- const why = kind === "none" ? "No fetch, XHR, WebSocket or EventSource call was found in your sources" : "Your page has one script";
2215
- out(` ${c.bold("Note")} ${why}, so GenClass will have little to find here. For a mostly static site, try ${c.cyan(SCAN_CMD)}.`);
2233
+ const why2 = kind === "none" ? "No fetch, XHR, WebSocket or EventSource call was found in your sources" : "Your page has one script";
2234
+ out(` ${c.bold("Note")} ${why2}, so GenClass will have little to find here. For a mostly static site, try ${c.cyan(SCAN_CMD)}.`);
2216
2235
  out();
2217
2236
  }
2218
2237
  function printRecommendations(recs) {
@@ -2259,7 +2278,24 @@ function briefTelemetry(cfg) {
2259
2278
  }
2260
2279
  briefLines("Anonymous diagnostics are on: counts and decisions go to GenClass's maintainers, with no page text, cookies or IP addresses, and never from localhost.");
2261
2280
  out(` ${c.gray(`Off: ${CMD} init --no-telemetry`)}`);
2262
- out(` ${c.gray(`What is sent: ${TELEMETRY_URL}`)}`);
2281
+ out(` ${c.gray("What is sent:")}`);
2282
+ out(` ${c.gray(TELEMETRY_URL)}`);
2283
+ }
2284
+ function commandLine(label, cmd) {
2285
+ const cols2 = Math.max(40, Math.min(100, Number(process.stdout.columns) || 100));
2286
+ if (2 + label.length + 2 + cmd.length <= cols2) {
2287
+ out(` ${c.bold(label)} ${c.cyan(cmd)}`);
2288
+ return;
2289
+ }
2290
+ out(` ${c.bold(label)}`);
2291
+ let line = "";
2292
+ for (const w of cmd.split(" ")) {
2293
+ if (line && 4 + line.length + 1 + w.length > cols2) {
2294
+ out(` ${c.cyan(line)}`);
2295
+ line = w;
2296
+ } else line = line ? `${line} ${w}` : w;
2297
+ }
2298
+ if (line) out(` ${c.cyan(line)}`);
2263
2299
  }
2264
2300
  function briefLines(text, paint = c.gray) {
2265
2301
  const cols2 = Math.max(40, Math.min(100, Number(process.stdout.columns) || 100)) - 4;
@@ -2296,10 +2332,10 @@ function cspAdvice(project, files, cfg) {
2296
2332
  out(` script tag). If the worker is blocked, GenClass runs the model on the main thread; set`);
2297
2333
  out(` model: { inlineFallback: false } to skip the model instead.`);
2298
2334
  }
2299
- function planConfigSwitch(project, cwd, marked, cfg, readText2) {
2335
+ function planConfigSwitch(project, cwd, marked2, cfg, readText2) {
2300
2336
  const changes = [];
2301
2337
  const rel = (f) => posix2(relative3(cwd, f));
2302
- const cfgFile = marked.find((f) => /genclass\.config\.[cm]?[jt]s$/.test(f));
2338
+ const cfgFile = marked2.find((f) => /genclass\.config\.[cm]?[jt]s$/.test(f));
2303
2339
  if (cfgFile) {
2304
2340
  const before = readText2(cfgFile) ?? "";
2305
2341
  const after = updateConfigText(before, cfg);
@@ -2307,7 +2343,7 @@ function planConfigSwitch(project, cwd, marked, cfg, readText2) {
2307
2343
  return { changes, where: rel(cfgFile) };
2308
2344
  }
2309
2345
  let where = null;
2310
- for (const f of marked) {
2346
+ for (const f of marked2) {
2311
2347
  const before = readText2(f) ?? "";
2312
2348
  let after = before;
2313
2349
  if (/\.html?$/.test(f)) after = switchTagConfig(before, cfg);
@@ -2344,7 +2380,7 @@ async function switchModes(o, project, planned, install, spec, cwd, what, tk) {
2344
2380
  out(` ${c.bold("Changes")}`);
2345
2381
  out();
2346
2382
  for (const ch of changes) printChange({ ...ch, file: ch.rel });
2347
- if (install) out(` ${c.bold("Install")} ${c.cyan(installArgs(project.pm, spec).flat().join(" "))}`);
2383
+ if (install) commandLine("Install", installArgs(project.pm, spec).flat().join(" "));
2348
2384
  out();
2349
2385
  if (o.dryRun) {
2350
2386
  out(` ${c.gray("Dry run: nothing was written.")}`);
@@ -2402,15 +2438,15 @@ function withLocalDevice(cfg, project) {
2402
2438
  }
2403
2439
  return cfg;
2404
2440
  }
2405
- function planToken(o, project, cwd, marked, fresh) {
2441
+ function planToken(o, project, cwd, marked2, fresh) {
2406
2442
  if (o.noTelemetry) return { why: "--no-telemetry" };
2407
2443
  if (o.noToken) return { why: "--no-token" };
2408
- const inFiles = tokenInFiles(marked);
2444
+ const inFiles = tokenInFiles(marked2);
2409
2445
  const local = readLocal(cwd);
2410
2446
  if (o.token) return { token: o.token, write: o.token !== inFiles, source: "--token", local: local?.token === o.token ? local : null };
2411
2447
  if (inFiles) return { token: inFiles, write: false, source: "already in your setup", local: local?.token === inFiles ? local : null };
2412
2448
  if (local) return { token: local.token, write: true, source: LOCAL_FILE, local };
2413
- if (!o.telemetry && currentConfig(marked).telemetry === false) return { why: "telemetry is off in your setup" };
2449
+ if (!o.telemetry && currentConfig(marked2).telemetry === false) return { why: "telemetry is off in your setup" };
2414
2450
  if (!fresh) return { why: "none in your setup", hint: true };
2415
2451
  if (o.dryRun) return { why: "dry run", wouldCreate: true };
2416
2452
  return { pending: true, name: project.pkg?.name || project.name };
@@ -2430,7 +2466,7 @@ async function settleToken(tk, changes, replan) {
2430
2466
  function tokenRow(tk) {
2431
2467
  const name = c.bold(String(tk.name ?? "").slice(0, 80) || "unnamed");
2432
2468
  if (tk.pending && tk.account) {
2433
- row("Token", `a new app in your account (${accountLabel(tk.account.account)}) ${c.gray("once you apply these changes")}`);
2469
+ row("Token", `a new app in ${accountWhere(tk.account.account)} ${c.gray("once you apply these changes")}`);
2434
2470
  out(` ${actor} then sends this app's name (${name}) to ${c.cyan(hostUrl("/api/account/projects"))} with your`);
2435
2471
  out(` CLI session and gets back the app's public token. ${c.cyan("--no-token")}: no token, no network.`);
2436
2472
  return;
@@ -2442,7 +2478,7 @@ function tokenRow(tk) {
2442
2478
  return;
2443
2479
  }
2444
2480
  if (tk.token) {
2445
- const from = tk.source === "new" ? "created for this app at genclass.dev" : tk.source === "account" ? `a new app in your account (${accountLabel(tk.account?.account)})` : tk.source;
2481
+ const from = tk.source === "new" ? "created for this app at genclass.dev" : tk.source === "account" ? `a new app in ${accountWhere(tk.account?.account)}` : tk.source;
2446
2482
  row("Token", `${tk.token} ${c.gray(`(${from})`)}`);
2447
2483
  out(` Public (it ships in your page). The diagnostics above also feed this app's ${tk.app || tk.source === "account" ? "dashboard in your account" : "private dashboard"}.`);
2448
2484
  return;
@@ -2482,7 +2518,7 @@ function dashboardNotice(tk, cwd, applied, remind = false, saved = null) {
2482
2518
  if (!applied || !tk.token) return;
2483
2519
  const link2 = tk.created?.dashboardUrl ?? tk.app?.dashboard_url ?? hostUrl("/account");
2484
2520
  out(` ${c.bold("Your dashboard")} ${c.bold(c.cyan(link2))}`);
2485
- out(` ${c.gray(`In your GenClass account (${accountLabel(tk.account?.account)}): sign in at genclass.dev to open it.`)}`);
2521
+ out(` ${c.gray(`In ${HOST_CLI?.into ? HOST_CLI.into : `your GenClass account (${accountLabel(tk.account?.account)})`}: sign in at genclass.dev to open it.`)}`);
2486
2522
  for (const l of FREE_LINES) out(` ${c.gray(l)}`);
2487
2523
  out(` ${c.gray("It fills once your deployed app runs with telemetry on. Local hosts (localhost, *.local, *.test, private")}`);
2488
2524
  out(` ${c.gray("networks) do not send by default (telemetry: true opts them in), and visitors who opt out or send")}`);
@@ -2530,10 +2566,10 @@ function inspectProject(o) {
2530
2566
  const cwd = projectDir(o);
2531
2567
  const project = detectProject(cwd);
2532
2568
  const files = project.refused || !project.framework ? [] : walkSources(cwd);
2533
- const marked = files.filter((f) => hasMarker(readText(f) ?? ""));
2534
- const manual = marked.length ? [] : manualRefs(files);
2569
+ const marked2 = files.filter((f) => hasMarker(readText(f) ?? ""));
2570
+ const manual = marked2.length ? [] : manualRefs(files);
2535
2571
  const local = readLocal(cwd);
2536
- return { cwd, project, files, marked, handWritten: !marked.length && manual.length > 0, fresh: !marked.length && !manual.length, token: tokenInFiles(marked) ?? tokenInFiles(manual) ?? local?.token ?? null, local };
2572
+ return { cwd, project, files, marked: marked2, handWritten: !marked2.length && manual.length > 0, fresh: !marked2.length && !manual.length, token: tokenInFiles(marked2) ?? tokenInFiles(manual) ?? local?.token ?? null, local };
2537
2573
  }
2538
2574
  async function offerAccount(o, tk) {
2539
2575
  if (!tk.pending && !tk.wouldCreate) return tk;
@@ -2575,15 +2611,15 @@ async function init(o, ctx = {}) {
2575
2611
  if (project.pm) row("Packages", project.pm);
2576
2612
  }
2577
2613
  const files = walkSources(cwd);
2578
- const marked = files.filter((f) => hasMarker(readText(f) ?? ""));
2579
- const handWritten = !marked.length && manualRefs(files).length > 0;
2580
- const fresh = !marked.length && !manualRefs(files).length;
2614
+ const marked2 = files.filter((f) => hasMarker(readText(f) ?? ""));
2615
+ const handWritten = !marked2.length && manualRefs(files).length > 0;
2616
+ const fresh = !marked2.length && !manualRefs(files).length;
2581
2617
  let tk;
2582
2618
  if (handWritten) tk = { why: "GenClass is set up by hand here: pass token to GenClass.init()" };
2583
2619
  else if (ctx.create !== void 0 && !o.dryRun) tk = { pending: true, name: ctx.create, account: ctx.creds };
2584
2620
  else if (ctx.create !== void 0) tk = { why: "dry run", wouldCreate: true, account: ctx.creds, chosen: true };
2585
2621
  else {
2586
- tk = planToken(o, project, cwd, marked, fresh);
2622
+ tk = planToken(o, project, cwd, marked2, fresh);
2587
2623
  if (ctx.app && tk.token === ctx.app.token) tk = { ...tk, source: `your account's app "${ctx.app.name}"`, app: ctx.app, account: ctx.creds };
2588
2624
  }
2589
2625
  if (tk.write) cfg = { token: tk.token, ...cfg };
@@ -2593,16 +2629,16 @@ async function init(o, ctx = {}) {
2593
2629
  const install = needsPackage && !o.noInstall;
2594
2630
  if (older) row("Package", `${PKG} ${older} is older than this init (${VERSION2})${install ? "; init upgrades it" : ": upgrade it (--no-install)"}`, c.yellow(sym.warn));
2595
2631
  const spec = installSpec(o);
2596
- if (marked.length || manualRefs(files).length) {
2597
- const where = (marked.length ? marked : manualRefs(files)).map((f) => posix2(relative3(cwd, f)));
2598
- row("Setup", marked.length ? `already added by init in ${where.join(", ")}` : `GenClass is already imported in ${where.join(", ")}; init leaves your code alone`);
2599
- const switches = o.mode ? marked.map((f) => {
2632
+ if (marked2.length || manualRefs(files).length) {
2633
+ const where = (marked2.length ? marked2 : manualRefs(files)).map((f) => posix2(relative3(cwd, f)));
2634
+ row("Setup", marked2.length ? `already added by init in ${where.join(", ")}` : `GenClass is already imported in ${where.join(", ")}; init leaves your code alone`);
2635
+ const switches = o.mode ? marked2.map((f) => {
2600
2636
  const before = readText(f) ?? "";
2601
2637
  return { file: f, rel: posix2(relative3(cwd, f)), kind: "modify", before, after: switchMode(before, o.mode) };
2602
2638
  }).filter((ch) => ch.after !== ch.before) : [];
2603
- if (marked.length && !isEmptyConfig(cfg)) {
2639
+ if (marked2.length && !isEmptyConfig(cfg)) {
2604
2640
  const byFile = new Map(switches.map((ch) => [ch.file, ch]));
2605
- const sw = planConfigSwitch(project, cwd, marked, cfg, (f) => byFile.get(f)?.after ?? readText(f));
2641
+ const sw = planConfigSwitch(project, cwd, marked2, cfg, (f) => byFile.get(f)?.after ?? readText(f));
2606
2642
  for (const ch of sw.changes) {
2607
2643
  const prev = byFile.get(ch.file);
2608
2644
  byFile.set(ch.file, prev ? { ...ch, before: prev.before } : ch);
@@ -2611,7 +2647,7 @@ async function init(o, ctx = {}) {
2611
2647
  }
2612
2648
  const optionsChanged = switches.some((ch) => !o.mode || ch.kind === "create" || switchMode(ch.before, o.mode) !== ch.after);
2613
2649
  out();
2614
- telemetryNotice(isEmptyConfig(cfg) ? currentConfig(marked) : { ...currentConfig(marked), ...cfg }, null);
2650
+ telemetryNotice(isEmptyConfig(cfg) ? currentConfig(marked2) : { ...currentConfig(marked2), ...cfg }, null);
2615
2651
  tokenRow(tk);
2616
2652
  if (tk.token && !tk.app && !ctx.creds && readCredentials()) out(` ${c.gray(`Signed in: ${CMD} connect adds this app to your account if it is not there yet.`)}`);
2617
2653
  sinksNotice(cfg, null);
@@ -2624,7 +2660,7 @@ async function init(o, ctx = {}) {
2624
2660
  }
2625
2661
  if (!install) {
2626
2662
  if (older) out(` ${c.yellow(sym.warn)} --no-install: upgrade it yourself: ${c.cyan(installArgs(project.pm, spec).flat().join(" "))}`);
2627
- out(` ${c.green("Nothing to do.")}${marked.length ? ` To take it out: ${c.cyan(`${CMD} remove`)}` : ""}`);
2663
+ out(` ${c.green("Nothing to do.")}${marked2.length ? ` To take it out: ${c.cyan(`${CMD} remove`)}` : ""}`);
2628
2664
  out();
2629
2665
  dashboardNotice(tk, cwd, false, true);
2630
2666
  return 0;
@@ -2664,7 +2700,7 @@ async function init(o, ctx = {}) {
2664
2700
  briefTelemetry(cfg);
2665
2701
  } else telemetryNotice(cfg, cfgAt);
2666
2702
  if (!ctx.creds) tk = await offerAccount(o, tk);
2667
- if (brief && tk.pending && tk.account) briefLines(`The app goes into your account (${accountLabel(tk.account.account)}) as "${String(tk.name ?? "").slice(0, 80) || "unnamed"}".`);
2703
+ if (brief && tk.pending && tk.account) briefLines(`The app goes into ${accountWhere(tk.account.account)} as "${String(tk.name ?? "").slice(0, 80) || "unnamed"}".`);
2668
2704
  else tokenRow(tk);
2669
2705
  sinksNotice(cfg, cfgAt);
2670
2706
  cspAdvice(project, files, cfg);
@@ -2672,7 +2708,7 @@ async function init(o, ctx = {}) {
2672
2708
  out(` ${c.bold("Changes")}`);
2673
2709
  out();
2674
2710
  for (const ch of plan2.changes) printChange({ ...ch, file: ch.rel });
2675
- if (install) out(` ${c.bold("Install")} ${c.cyan(installArgs(project.pm, spec).flat().join(" "))}`);
2711
+ if (install) commandLine("Install", installArgs(project.pm, spec).flat().join(" "));
2676
2712
  else if (needsPackage) out(` ${c.yellow(sym.warn)} --no-install: ${older ? `upgrade ${PKG} yourself (${installArgs(project.pm, spec).flat().join(" ")})` : `add ${PKG} to your dependencies yourself`}.`);
2677
2713
  for (const n2 of plan2.notes ?? []) out(` ${c.yellow(sym.warn)} ${n2}`);
2678
2714
  out();
@@ -2864,7 +2900,7 @@ ${usage()}`);
2864
2900
  }
2865
2901
  return cmd === "remove" ? remove(o) : init(o);
2866
2902
  }
2867
- var MODES, REPO, TELEMETRY_URL, INTERCEPTION_URL, PRIVACY_URL, PRICING_URL, FREE_LINES, USAGE, UsageError, BOOL, VALUE, SINK_RE, PRO_SINK_RE, runCmd, posix2, REF_RE, PAYMENT_DEPS, MONEY_PATH, SCAN_CMD, SINK_WHAT, publicDir, describeConfig, withoutToken, accountLabel, actor, SAVED_WHERE, SELF, usage;
2903
+ var MODES, REPO, TELEMETRY_URL, INTERCEPTION_URL, PRIVACY_URL, PRICING_URL, FREE_LINES, USAGE, UsageError, BOOL, VALUE, SINK_RE, PRO_SINK_RE, runCmd, posix2, REF_RE, PAYMENT_DEPS, MONEY_PATH, SCAN_CMD, SINK_WHAT, publicDir, describeConfig, withoutToken, accountLabel, accountWhere, actor, SAVED_WHERE, SELF, usage;
2868
2904
  var init_init = __esm({
2869
2905
  "../runtime/bin/lib/init.mjs"() {
2870
2906
  "use strict";
@@ -2883,9 +2919,9 @@ var init_init = __esm({
2883
2919
  INTERCEPTION_URL = "https://genclass.dev/docs/interception";
2884
2920
  PRIVACY_URL = `${REPO}/PRIVACY.md`;
2885
2921
  PRICING_URL = "https://genclass.dev/pricing";
2886
- FREE_LINES = [
2887
- "Free for every app: what GenClass found, on which pages, and what it did, for the last 7 days. How visitors",
2888
- `use each page (analytics: true) shows on the Team plan. Print this link again any time: ${CMD} dashboard`
2922
+ FREE_LINES = HOST_CLI ? ["Every problem, the pages it happens on, a fix prompt for each and visitor analytics, in the terminal:", `${CMD} dashboard`] : [
2923
+ "Free shows this app's totals for the last 7 days. Every problem, the pages it happens on, a fix prompt for",
2924
+ `each and visitor analytics come with Pro (3 days free): ${PRICING_URL}. This link again: ${CMD} dashboard`
2889
2925
  ];
2890
2926
  USAGE = `Usage:
2891
2927
  genclass-runtime init [--mode observe|guard|heal] [--token <gc_...> | --no-token]
@@ -2908,7 +2944,7 @@ remove takes out exactly what init added (the lines and blocks marked "${MARK}
2908
2944
  approve the changes (or pass --yes), init creates one at genclass.dev (sending
2909
2945
  package.json's name), writes it into what it adds, and saves the token and your
2910
2946
  private dashboard link in ${LOCAL_FILE} (the dashboard is free; visitor analytics
2911
- come with the Team plan; \`dashboard\` prints the link again). Signed in (\`login\`), init first asks
2947
+ come with the Pro plan; \`dashboard\` prints the link again). Signed in (\`login\`), init first asks
2912
2948
  whether the new app goes into your GenClass account instead (--yes or --in-account: it does)
2913
2949
  --no-token no token, no network (no dashboard; you can add one later: ${START_URL})
2914
2950
  --no-telemetry turn off GenClass's anonymous diagnostics (on by default; see TELEMETRY.md and
@@ -3001,6 +3037,7 @@ remove takes out exactly what init added (the lines and blocks marked "${MARK}
3001
3037
  return rest;
3002
3038
  };
3003
3039
  accountLabel = (account) => account?.email || (account?.github_login ? `GitHub ${account.github_login}` : account?.id ? `account ${account.id}` : "your account");
3040
+ accountWhere = (account) => typeof HOST_CLI?.into === "string" && HOST_CLI.into ? HOST_CLI.into : `your account (${accountLabel(account)})`;
3004
3041
  actor = "init";
3005
3042
  SAVED_WHERE = {
3006
3043
  added: " (added to .gitignore)",
@@ -3013,1278 +3050,1381 @@ remove takes out exactly what init added (the lines and blocks marked "${MARK}
3013
3050
  }
3014
3051
  });
3015
3052
 
3016
- // ../runtime/bin/lib/login.mjs
3017
- var login_exports = {};
3018
- __export(login_exports, {
3019
- USAGE: () => USAGE2,
3020
- run: () => run2
3021
- });
3022
- import { spawn as spawn4 } from "node:child_process";
3023
- import { relative as relative4 } from "node:path";
3024
- function openBrowser(url, o) {
3025
- if (o.noBrowser || !process.stdout.isTTY) return false;
3026
- const env2 = process.env;
3027
- if (env2.SSH_CONNECTION || env2.SSH_TTY) return false;
3028
- if (process.platform === "linux" && !env2.DISPLAY && !env2.WAYLAND_DISPLAY) return false;
3029
- const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
3030
- try {
3031
- const child = spawn4(cmd, args, { stdio: "ignore", detached: true, shell: false });
3032
- child.on("error", () => out(` ${c.gray("Could not open a browser: open the link above yourself.")}`));
3033
- child.unref();
3034
- return true;
3035
- } catch {
3036
- return false;
3037
- }
3053
+ // src/api.mjs
3054
+ async function fetchOverview(creds, opts = {}) {
3055
+ const base2 = { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn };
3056
+ let r = await request("/api/cli/overview", base2);
3057
+ const full = r.ok;
3058
+ if (!r.ok && r.status === 404) r = await request("/api/me", base2);
3059
+ if (!r.ok) return { ok: false, status: r.status, reason: failure(r) };
3060
+ const j = r.json ?? {};
3061
+ const projects = (Array.isArray(j.projects) ? j.projects : []).map((p) => withPlan(cleanProject(p, creds.host), p, creds.host)).filter(Boolean);
3062
+ const tp = j.account?.team_plan;
3063
+ const account = j.account && typeof j.account === "object" ? { id: String(j.account.id ?? ""), email: str(j.account.email), github_login: str(j.account.github_login, 60), ...tp && typeof tp === "object" && str(tp.id, 40) ? { teamPlan: { id: str(tp.id, 40), name: str(tp.name, 40) ?? str(tp.id, 40) } } : {} } : creds.account;
3064
+ if (!full) return { ok: true, account, plan: null, suggestions: null, projects, github: null, billingUrl: null };
3065
+ const s = j.suggestions && typeof j.suggestions === "object" ? j.suggestions : null;
3066
+ const num = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3067
+ return {
3068
+ ok: true,
3069
+ account,
3070
+ // `via`: "team" for a member covered by a team's plan (a newer server says it; older ones do not)
3071
+ plan: j.plan && typeof j.plan === "object" && str(j.plan.id, 40) ? { id: str(j.plan.id, 40), name: str(j.plan.name, 40) ?? str(j.plan.id, 40), ...str(j.plan.via, 20) ? { via: str(j.plan.via, 20) } : {} } : null,
3072
+ suggestions: s ? { perDay: num(s.per_day), shown: num(s.shown), usedToday: num(s.used_today) ?? 0, model: s.model === true } : null,
3073
+ projects,
3074
+ github: j.github && typeof j.github === "object" ? { app: j.github.app === true, installUrl: sameOrigin2(j.github.install_url, creds.host), connectUrl: sameOrigin2(j.github.connect_url, creds.host) } : null,
3075
+ billingUrl: sameOrigin2(j.billing_url, creds.host),
3076
+ offer: offerOf(j.offer, creds.host),
3077
+ cli: cliOf(j.cli, creds.host)
3078
+ };
3038
3079
  }
3039
- function refuse(st) {
3040
- if (st.project.refused) {
3041
- out(` ${c.yellow(sym.warn)} Not a browser app GenClass can be added to (${st.project.refused}).`);
3042
- out(` Run ${c.cyan(`${CMD} connect`)} inside your web app's folder (or pass --cwd).`);
3043
- out();
3044
- return 1;
3045
- }
3046
- if (!st.project.framework) {
3047
- out(` ${c.yellow(sym.warn)} Could not recognise a web app in ${c.bold(st.cwd)}.`);
3048
- out(` Run ${c.cyan(`${CMD} connect`)} inside your web app's folder (or pass --cwd).`);
3049
- out();
3050
- return 1;
3051
- }
3052
- return null;
3080
+ function cliOf(v, host) {
3081
+ if (!v || typeof v !== "object" || typeof v.paid !== "boolean") return null;
3082
+ if (v.paid) return { paid: true, via: ["plan", "team", "open"].includes(v.via) ? v.via : null };
3083
+ const days = Number(v.trial_days);
3084
+ return {
3085
+ paid: false,
3086
+ plan: str(v.plan, 40) ?? "Pro",
3087
+ price: str(v.price, 60),
3088
+ trialDays: Number.isInteger(days) && days > 0 && days <= 730 ? days : null,
3089
+ checkoutUrl: sameOrigin2(v.checkout_url, host) ?? `${host}/account/billing`
3090
+ };
3053
3091
  }
3054
- function printManual(token) {
3055
- out(` GenClass is set up by hand in this project, so connect does not edit your code. Add the key yourself:`);
3056
- out(` ${c.cyan(`GenClass.init({ token: "${token}" })`)}`);
3057
- out(` or on the script tag ${c.cyan(`data-token="${token}"`)}, or in <head> ${c.cyan(`<meta name="genclass" content="token=${token}">`)},`);
3058
- out(` or set ${c.cyan(`window.GENCLASS_CONFIG = { token: "${token}" }`)} before the ${c.cyan(AUTO())} import runs.`);
3059
- out(` ${c.gray("The key needs @genclass/runtime 0.3.0-beta.0 or later (0.2.x has no token option).")}`);
3060
- out();
3092
+ function withPlan(app, p, host) {
3093
+ if (!app || !p?.plan || typeof p.plan !== "object" || !str(p.plan.id, 40)) return app;
3094
+ return { ...app, plan: { id: str(p.plan.id, 40), name: str(p.plan.name, 40) ?? str(p.plan.id, 40), source: str(p.plan.source, 20) }, needsPlan: p.needs_plan === true, planChosen: p.plan_chosen === true, planUrl: sameOrigin2(p.plan_url, host) };
3061
3095
  }
3062
- function claimFailed(r, pkgName) {
3063
- if (r.status === 401) return sessionGone();
3064
- const fresh = `${CMD} connect --name ${/^[A-Za-z0-9._@/-]+$/.test(pkgName) ? pkgName : JSON.stringify(pkgName)}`;
3065
- if (r.status === 409) {
3066
- err(` ${c.red(sym.cross)} That dashboard belongs to another GenClass account, so it was not added to this one.`);
3067
- err(` Sign in with that account (${c.cyan(`${CMD} logout`)}, then ${c.cyan("login")}), or give this folder a new app in your`);
3068
- err(` account with ${c.cyan(fresh)} (its key replaces the one in your setup).`);
3069
- return;
3070
- }
3071
- if (r.status === 404 || r.status === 400) {
3072
- err(` ${c.red(sym.cross)} ${apiHost()} does not know the dashboard link in ${LOCAL_FILE} (it may have been deleted).`);
3073
- err(` Give this folder a new app in your account with ${c.cyan(fresh)}`);
3074
- err(` (its key replaces the one in your setup).`);
3075
- return;
3076
- }
3077
- err(` ${c.red(sym.cross)} Could not add it (${r.reason}).`);
3078
- err(` Try again, or open ${c.cyan(hostUrl("/account"))} and paste the link from ${LOCAL_FILE} under "Add an existing dashboard".`);
3096
+ function offerOf(o, host) {
3097
+ if (!o || typeof o !== "object" || !o.plan || typeof o.plan !== "object") return null;
3098
+ const id = str(o.plan.id, 40);
3099
+ const price = str(o.price, 60);
3100
+ const checkoutUrl = sameOrigin2(o.checkout_url, host);
3101
+ if (!id || !price || !checkoutUrl) return null;
3102
+ const num = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3103
+ const f = o.free && typeof o.free === "object" ? o.free : {};
3104
+ return {
3105
+ plan: { id, name: str(o.plan.name, 40) ?? id },
3106
+ price,
3107
+ summary: str(o.summary, 200),
3108
+ features: (Array.isArray(o.features) ? o.features : []).filter((x) => typeof x === "string" && x.trim()).slice(0, 12).map((x) => x.slice(0, 120)),
3109
+ checkoutUrl,
3110
+ free: { name: str(f.name, 40) ?? "Free", apps: num(f.apps), historyDays: num(f.history_days), suggestionsShown: num(f.suggestions_shown), liveFixes: num(f.live_fixes) },
3111
+ trialDays: num(o.trial_days),
3112
+ appsPerUnit: num(o.apps_per_unit)
3113
+ };
3079
3114
  }
3080
- async function connectApp(o, creds, st, me) {
3081
- me ??= await fetchMe(creds);
3082
- if (!me.ok) {
3083
- if (me.status === 401) sessionGone();
3084
- else err(` ${c.red(sym.cross)} Could not read your apps at ${apiHost()} (${me.reason}).`);
3085
- out();
3086
- return 1;
3087
- }
3088
- const apps2 = me.projects;
3089
- const pkgName = String(st.project.pkg?.name || st.project.name || "app").slice(0, 80);
3090
- const inFiles = tokenInFiles(st.marked);
3091
- const current = st.token ? apps2.find((a) => a.token === st.token) : null;
3092
- if (current && !o.app && !o.name) {
3093
- row("App", `${c.bold(current.name)} ${c.gray(`(already in your account; project key ${current.token})`)}`);
3094
- if (st.handWritten) {
3095
- out();
3096
- printManual(current.token);
3097
- return 0;
3115
+ async function fetchRepoStatus(creds, repo, opts = {}) {
3116
+ const r = await request(`/api/cli/github?repo=${encodeURIComponent(repo)}`, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3117
+ if (!r.ok) return { ok: false, status: r.status, reason: why(r), ...r.status === 404 ? { missing: true } : {}, ...proOf(r, creds.host) };
3118
+ const j = r.json ?? {};
3119
+ return {
3120
+ ok: true,
3121
+ known: j.known === true,
3122
+ installed: typeof j.installed === "boolean" ? j.installed : null,
3123
+ evidence: j.evidence === true,
3124
+ prs: Number.isFinite(Number(j.prs)) ? Math.max(0, Number(j.prs)) : 0,
3125
+ last: str(j.last, 40),
3126
+ private: j.private === true,
3127
+ needsPlan: j.needs_plan === true,
3128
+ paused: j.paused === true,
3129
+ connectUrl: sameOrigin2(j.connect_url, creds.host),
3130
+ installUrl: sameOrigin2(j.install_url, creds.host)
3131
+ };
3132
+ }
3133
+ async function requestPlan(creds, digest, opts = {}) {
3134
+ const r = await request("/api/cli/suggest", { method: "POST", token: creds.access_token, host: creds.host, body: digest, fetchFn: opts.fetchFn, timeoutMs: opts.timeoutMs ?? 12e4 });
3135
+ if (!r.ok) return { ok: false, status: r.status, reason: why(r), ...r.status === 404 ? { missing: true } : {}, ...proOf(r, creds.host) };
3136
+ const j = r.json ?? {};
3137
+ const items = (Array.isArray(j.items) ? j.items : []).filter((i) => i && typeof i === "object" && /^[a-z0-9-]{1,40}$/.test(String(i.id ?? ""))).slice(0, 80).map((i) => ({ id: String(i.id), why: str(i.why, 600), step: str(i.step, 400), prompt: str(i.prompt, 1200) }));
3138
+ return {
3139
+ ok: true,
3140
+ source: j.source === "model" ? "model" : "checks",
3141
+ plan: j.plan && typeof j.plan === "object" && str(j.plan.id, 40) ? { id: str(j.plan.id, 40), name: str(j.plan.name, 40) ?? str(j.plan.id, 40) } : null,
3142
+ total: Number.isFinite(Number(j.total)) ? Number(j.total) : items.length,
3143
+ items,
3144
+ locked: Number.isFinite(Number(j.locked)) ? Math.max(0, Number(j.locked)) : 0,
3145
+ lockedIds: (Array.isArray(j.locked_ids) ? j.locked_ids : []).filter((x) => typeof x === "string" && /^[a-z0-9-]{1,40}$/.test(x)).slice(0, 80),
3146
+ upgradeUrl: sameOrigin2(j.upgrade_url, creds.host),
3147
+ remainingToday: Number.isFinite(Number(j.remaining_today)) && j.remaining_today !== null ? Number(j.remaining_today) : null,
3148
+ limited: j.limited === true,
3149
+ /** the model's own ideas (not measured) and website designs: Pro gets them, Free their counts */
3150
+ ideas: (Array.isArray(j.ideas) ? j.ideas : []).filter((i) => i && typeof i === "object" && str(i.title, 120)).slice(0, 20).map((i) => ({ title: str(i.title, 120), why: str(i.why, 600), step: str(i.step, 400), prompt: str(i.prompt, 1200) })),
3151
+ designs: (Array.isArray(j.designs) ? j.designs : []).filter((d) => d && typeof d === "object" && str(d.title, 120) && /^https:\/\/[a-z0-9.-]+\.[a-z]{2,}(\/\S*)?$/i.test(String(d.inspired_by ?? "")) && str(d.prompt, 4e3)).slice(0, 4).map((d) => ({ title: str(d.title, 120), inspiredBy: String(d.inspired_by).slice(0, 200), why: str(d.why, 600), prompt: str(d.prompt, 4e3) })),
3152
+ ideasLocked: Number.isFinite(Number(j.ideas_locked)) ? Math.max(0, Number(j.ideas_locked)) : 0,
3153
+ designsLocked: Number.isFinite(Number(j.designs_locked)) ? Math.max(0, Number(j.designs_locked)) : 0,
3154
+ /** this answer was kept from an earlier run (Free sees its first one again until it pays) */
3155
+ cachedAt: str(j.cached_at, 40),
3156
+ upgradePlan: j.upgrade_plan && typeof j.upgrade_plan === "object" ? { plan: str(j.upgrade_plan.name, 40), price: str(j.upgrade_plan.price, 60), trialDays: Number.isInteger(j.upgrade_plan.trial_days) && j.upgrade_plan.trial_days > 0 ? j.upgrade_plan.trial_days : null } : null
3157
+ };
3158
+ }
3159
+ async function signInIsOld(creds, opts = {}) {
3160
+ const ask3 = (path) => request(path, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3161
+ const old = (r) => !r.ok && r.status === 403 && r.json?.reauth === true;
3162
+ const newest = await ask3("/api/cli/account");
3163
+ if (old(newest)) return true;
3164
+ if (newest.ok || newest.status !== 404) return false;
3165
+ return old(await ask3("/api/cli/app?id=-&range=24h"));
3166
+ }
3167
+ function lockOf(l, host) {
3168
+ if (!l || typeof l !== "object") return null;
3169
+ const days = Number(l.trial_days);
3170
+ return { plan: str(l.plan, 40), trialDays: Number.isInteger(days) && days > 0 ? days : null, price: str(l.price, 60), upgradeUrl: sameOrigin2(l.upgrade_url, host) };
3171
+ }
3172
+ function liveUsage(u) {
3173
+ if (!u || typeof u !== "object" || !Number.isFinite(Number(u.used))) return null;
3174
+ const lim = u.limit === null || u.limit === void 0 || !Number.isFinite(Number(u.limit)) ? null : Math.max(0, Math.round(Number(u.limit)));
3175
+ return { used: Math.max(0, Math.round(Number(u.used))), limit: lim, observeOnly: u.observe_only === true, resets: str(u.resets, 40) };
3176
+ }
3177
+ async function fetchApp(creds, id, range = "7d", opts = {}) {
3178
+ const r = await request(`/api/cli/app?id=${encodeURIComponent(id)}&range=${encodeURIComponent(range)}`, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3179
+ if (!r.ok) return { ok: false, status: r.status, reason: why(r), ...r.status === 404 ? { missing: true } : {}, ...proOf(r, creds.host), ...r.json?.reauth === true ? { reauth: true } : {}, ...r.json?.locked === true ? { locked: true, upgradeUrl: sameOrigin2(r.json.upgrade_url, creds.host) } : {} };
3180
+ const j = r.json ?? {};
3181
+ const t = j.totals && typeof j.totals === "object" ? j.totals : {};
3182
+ const b = j.breakdowns && typeof j.breakdowns === "object" ? j.breakdowns : {};
3183
+ const st = j.agent?.stages && typeof j.agent.stages === "object" ? j.agent.stages : {};
3184
+ const v = j.visits && typeof j.visits === "object" ? j.visits : {};
3185
+ const lock = j.locked?.analytics && typeof j.locked.analytics === "object" ? j.locked.analytics : null;
3186
+ return {
3187
+ ok: true,
3188
+ name: str(j.name, 80) ?? "",
3189
+ range: str(j.range, 8) ?? range,
3190
+ lastEvent: str(j.lastEvent, 40),
3191
+ totals: { visits: count(t.sessions), found: count(t.detections), handled: count(t.acted), possible: count(t.possible), checks: count(t.checks), pageViews: count(t.ix_views) },
3192
+ previous: { found: count(j.previous?.detections), visits: count(j.previous?.sessions) },
3193
+ /** problems found per bucket (hour or day), oldest first */
3194
+ series: (Array.isArray(j.series) ? j.series : []).slice(-400).map((x) => count(x?.detections)),
3195
+ /** kind TAB page */
3196
+ problems: pairs(b.detect_issue, 200),
3197
+ possible: pairs(b.possible_issue, 200),
3198
+ checks: pairs(b.check_issue, 200),
3199
+ kinds: pairs(b.detect_diagnosis, 25),
3200
+ recent: (Array.isArray(j.recent) ? j.recent : []).filter((x) => x && typeof x === "object").slice(0, 20).map((x) => ({ at: str(x.t, 40), kind: str(x.diagnosis, 60), route: str(x.route, 200), handled: x.acted === 1 || x.acted === true })),
3201
+ visitors: lock ? null : { visits: count(v.sessions), pages: count(v.pages), bounces: count(v.bounces), entry: pairs(v.entry, 25) },
3202
+ visitorsPlan: lock ? { plan: str(lock.plan, 40), upgradeUrl: sameOrigin2(lock.upgrade_url, creds.host) } : null,
3203
+ agent: { found: count(st.found), reproduced: count(st.reproduced), fixed: count(st.fixed), closed: count(st.closed), open: count(st.open), last: str(j.agent?.last, 40) },
3204
+ dashboardUrl: sameOrigin2(j.dashboard_url, creds.host),
3205
+ /** Free sees the totals only: the plan that shows the problems, its trial and price, and its page */
3206
+ problemsPlan: lockOf(j.locked?.problems, creds.host),
3207
+ /** the problems fixed live this month against the app's plan: past its limit GenClass observes only */
3208
+ usage: liveUsage(j.usage),
3209
+ /** the app's plan page (plans per project) */
3210
+ planUrl: sameOrigin2(j.plan_url, creds.host),
3211
+ /** the recorded demo's numbers stand in for measured ones (the server's sample app) */
3212
+ demo: j.demo === true,
3213
+ // The rest of what the dashboard page reads, for the other views (views.mjs): every total and breakdown by the
3214
+ // server's own key, the buckets, the latest events as they are stored, the visits' exit pages and the funnels.
3215
+ more: {
3216
+ totals: numbers(t),
3217
+ breakdowns: Object.fromEntries(
3218
+ Object.entries(b).filter(([k, v2]) => /^[a-z_]{1,40}$/.test(k) && Array.isArray(v2)).map(([k, v2]) => [k, pairs(v2, 200)])
3219
+ ),
3220
+ distinct: numbers(j.distinct),
3221
+ series: (Array.isArray(j.series) ? j.series : []).slice(-400).map((x) => ({ bucket: str(x?.bucket, 24) ?? "", pages: count(x?.sessions), found: count(x?.detections), handled: count(x?.acted), possible: count(x?.possible), checks: count(x?.checks), views: count(x?.ix_views), visits: count(x?.ix_sessions) })),
3222
+ events: (Array.isArray(j.recent) ? j.recent : []).filter((x) => x && typeof x === "object").slice(0, 50).map((x) => ({
3223
+ at: str(x.t, 40),
3224
+ route: str(x.route, 200),
3225
+ fn: str(x.fn, 80),
3226
+ kind: str(x.diagnosis, 60),
3227
+ confidence: Number.isFinite(Number(x.confidence)) && x.confidence !== null ? Math.max(0, Math.min(1, Number(x.confidence))) : null,
3228
+ mode: str(x.mode, 20),
3229
+ trigger: str(x.trigger, 40),
3230
+ /** "detect": reported; "acted": the runtime was allowed to act on it */
3231
+ tier: str(x.kind, 20),
3232
+ handled: x.acted === 1 || x.acted === true,
3233
+ executed: x.executed === 1 || x.executed === true,
3234
+ action: str(x.action, 60),
3235
+ ran: str(x.ran, 60)
3236
+ })),
3237
+ exit: lock ? [] : pairs(v.exit, 25),
3238
+ funnels: (Array.isArray(j.funnels) ? j.funnels : []).filter((f) => f && typeof f === "object" && Array.isArray(f.steps)).slice(0, 5).map((f) => ({ name: str(f.name, 60) ?? "Funnel", steps: f.steps.filter((x) => typeof x === "string").slice(0, 6).map((x) => x.slice(0, 120)), counts: (Array.isArray(f.counts) ? f.counts : []).slice(0, 6).map(count) })),
3239
+ /** what the coding agent did with each finding (the MCP server reports it when GENCLASS_REPORT is on) */
3240
+ findings: (Array.isArray(j.agent?.findings) ? j.agent.findings : []).filter((x) => x && typeof x === "object").slice(0, 25).map((x) => ({ id: str(x.id, 80), kind: str(x.kind, 60), route: str(x.route, 200), found: str(x.found, 40), reproduced: x.reproduced === true ? true : x.reproduced === false ? false : null, tested: !!x.tested, proven: !!x.proven, closed: x.closed === true, updated: str(x.updated, 40) })),
3241
+ agentLog: (Array.isArray(j.agent?.log) ? j.agent.log : []).filter((x) => x && typeof x === "object").slice(0, 50).map((x) => ({ at: str(x.at, 40), step: str(x.t, 20), id: str(x.id, 80), kind: str(x.kind, 60), route: str(x.route, 200), reproduced: x.reproduced === true ? true : x.reproduced === false ? false : null, runs: count(x.runs), races: count(x.races), what: str(x.what, 200) })),
3242
+ stages: { found: count(st.found), explained: count(st.explained), reproduced: count(st.reproduced), fixed: count(st.fixed), closed: count(st.closed), open: count(st.open), continued: count(st.continued) },
3243
+ previous: numbers(j.previous),
3244
+ generated: str(j.generated, 40)
3098
3245
  }
3099
- if (inFiles === current.token) {
3100
- if (current.dashboard_url) row("Dashboard", c.cyan(current.dashboard_url));
3101
- out();
3102
- out(` ${c.green("Nothing to do.")}`);
3103
- out();
3104
- return 0;
3105
- }
3106
- out();
3107
- return init({ ...o, token: current.token }, { banner: false, cmd: "connect", creds, app: current });
3108
- }
3109
- let claimable = st.token && !current && st.local?.token === st.token && st.local.dashboardUrl && !o.app && !o.name;
3110
- if (claimable && !onHost(st.local.dashboardUrl, creds.host)) {
3111
- out(` ${c.yellow(sym.warn)} The private dashboard link in ${LOCAL_FILE} belongs to ${new URL(st.local.dashboardUrl).origin}, not ${creds.host},`);
3112
- out(` so it is not sent there and this app is not added to that account from it.`);
3113
- out();
3114
- claimable = false;
3115
- }
3116
- if (claimable) {
3117
- out(` This app already has a dashboard made without an account (key ${st.token}; its private link is in ${LOCAL_FILE}).`);
3118
- const ok = o.dryRun ? null : o.yes ? true : await confirm("Add that dashboard to your account? It keeps its key and its data.");
3119
- if (o.dryRun) {
3120
- out(` ${c.gray("Dry run: it would be added to your account. Only your app list was read; nothing was added or written.")}`);
3121
- out();
3122
- return 0;
3123
- }
3124
- if (ok === null) {
3125
- out(` Not a terminal, so nothing was sent. Re-run with ${c.bold("--yes")} to add it.`);
3126
- out();
3127
- return 1;
3128
- }
3129
- if (ok) {
3130
- const r = await claimProject(creds, st.local.dashboardUrl);
3131
- if (!r.ok) {
3132
- claimFailed(r, pkgName);
3133
- out();
3134
- return 1;
3135
- }
3136
- const app2 = r.project ?? { name: pkgName, token: st.token, dashboard_url: null };
3137
- row("App", `${c.bold(app2.name)} ${c.gray(`(added to your account; project key ${st.token})`)}`);
3138
- if (st.handWritten) {
3139
- out();
3140
- printManual(st.token);
3141
- return 0;
3142
- }
3143
- if (inFiles === st.token) {
3144
- if (app2.dashboard_url) row("Dashboard", c.cyan(app2.dashboard_url));
3145
- out(` ${c.gray("The key in your setup stays the same, so no file changes.")}`);
3146
- out();
3147
- return 0;
3148
- }
3149
- out();
3150
- return init({ ...o, token: st.token }, { banner: false, cmd: "connect", creds, app: { ...app2, token: st.token } });
3151
- }
3152
- out();
3153
- }
3154
- if (st.token && !current && st.local?.token !== st.token && o.yes && !o.app && !o.name && !o.dryRun) {
3155
- err(` ${c.red(sym.cross)} This app's project key ${st.token} is not one of your account's apps (it may be a teammate's).`);
3156
- out(` Say which app it is: ${c.cyan(`${CMD} connect`)} on a terminal and pick, or ${c.cyan(`${CMD} connect --app <id or name>`)}`);
3157
- out(` for one of yours, or ${c.cyan(`${CMD} connect --name <name>`)} for a new one. Nothing was changed.`);
3158
- out();
3159
- return 1;
3160
- }
3161
- const createName = String(o.name || pkgName).slice(0, 80);
3162
- let pick2;
3163
- if (o.app) {
3164
- pick2 = apps2.findIndex((a) => a.id === o.app || a.name === o.app);
3165
- if (pick2 < 0) {
3166
- err(` ${c.red(sym.cross)} No app "${o.app}" in your account.${apps2.length ? ` Your apps: ${apps2.map((a) => `${a.name} (${a.id})`).join(", ")}.` : " It has no apps yet."}`);
3167
- out();
3168
- return 1;
3169
- }
3170
- } else if (o.name) pick2 = apps2.length;
3171
- else {
3172
- const same = apps2.findIndex((a) => a.name === pkgName);
3173
- const def = same >= 0 ? same : apps2.length;
3174
- pick2 = def;
3175
- if (apps2.length && !o.yes && interactive()) {
3176
- const labels = [...apps2.map((a) => `${a.name} ${c.gray(`${a.token} ${a.last_event ? `last event ${when(a.last_event)}` : "no events yet"}`)}`), `Create a new app named ${c.bold(createName)}`];
3177
- const got = await choose(`Which app of your account is this (${pkgName})?`, labels, def);
3178
- if (got !== null) pick2 = got;
3179
- out();
3180
- }
3181
- }
3182
- const app = pick2 < apps2.length ? apps2[pick2] : null;
3183
- if (st.token && st.token !== app?.token) {
3184
- out(` ${c.yellow(sym.warn)} This replaces the project key ${st.token} in your setup.`);
3185
- if (st.local?.dashboardUrl && st.local.token === st.token)
3186
- out(` Its private link stays in ${LOCAL_FILE}; to keep that history, paste it under "Add an existing dashboard" at ${hostUrl("/account")}.`);
3187
- out();
3246
+ };
3247
+ }
3248
+ function numbers(o) {
3249
+ const out2 = {};
3250
+ if (o && typeof o === "object") {
3251
+ for (const [k, v] of Object.entries(o)) if (/^[A-Za-z0-9_]{1,40}$/.test(k) && Number.isFinite(Number(v)) && v !== null) out2[k] = Number(v);
3188
3252
  }
3189
- row("App", app ? `${c.bold(app.name)} ${c.gray(`(in your account; project key ${app.token})`)}` : `${c.bold(createName)} ${c.gray("(a new app in your account, created once you apply the changes)")}`);
3190
- if (st.handWritten) {
3191
- out();
3192
- let token = app?.token;
3193
- if (!token) {
3194
- if (o.dryRun) {
3195
- out(` ${c.gray("Dry run: the app would be created. Only your app list was read; nothing was created.")}`);
3196
- out();
3197
- return 0;
3198
- }
3199
- const ok = o.yes ? true : await confirm(`Create the app "${createName}" in your account?`);
3200
- if (ok === null) {
3201
- out(` Not a terminal, so nothing was sent. Re-run with ${c.bold("--yes")}.`);
3202
- out();
3203
- return 1;
3204
- }
3205
- if (!ok) {
3206
- out(` Nothing changed.`);
3207
- out();
3208
- return 0;
3209
- }
3210
- const r = await createAccountProject(creds, createName);
3211
- if (!r.ok) {
3212
- err(` ${c.red(sym.cross)} Could not create the app (${r.reason}).`);
3213
- out();
3214
- return 1;
3253
+ return out2;
3254
+ }
3255
+ async function fetchAccount(creds, opts = {}) {
3256
+ const r = await request("/api/cli/account", base(creds, opts));
3257
+ if (!r.ok) return refused(r, creds.host);
3258
+ const j = r.json ?? {};
3259
+ const l = j.limits ?? {};
3260
+ const u = j.used ?? {};
3261
+ const t = j.team ?? {};
3262
+ const inc = j.includes ?? {};
3263
+ return {
3264
+ ok: true,
3265
+ plan: { id: str(j.plan?.id, 40) ?? "free", name: str(j.plan?.name, 40) ?? "Free", price: str(j.plan?.price, 60), summary: str(j.plan?.summary, 200) },
3266
+ /** why the account has its plan: "paid", "comp" (a grant), "open" (a server with every plan open) or null */
3267
+ access: ["paid", "comp", "open"].includes(j.access) ? j.access : null,
3268
+ limits: { apps: numOrNull(l.apps), historyDays: numOrNull(l.history_days), seats: numOrNull(l.seats), suggestionsPerDay: numOrNull(l.suggestions_per_day), suggestionsShown: numOrNull(l.suggestions_shown) },
3269
+ used: { apps: count(u.apps), suggestionsToday: count(u.suggestions_today), seats: count(u.seats) },
3270
+ includes: { analytics: inc.analytics === true, forwarding: inc.forwarding === true, export: inc.export === true, privateRepositories: inc.private_repositories === true },
3271
+ subscription: { status: str(j.subscription?.status, 30), periodEnd: str(j.subscription?.current_period_end, 40), cancels: j.subscription?.cancel_at_period_end === true },
3272
+ team: {
3273
+ seats: numOrNull(t.seats),
3274
+ used: count(t.used),
3275
+ members: (Array.isArray(t.members) ? t.members : []).slice(0, 200).map(person),
3276
+ invites: (Array.isArray(t.invites) ? t.invites : []).slice(0, 200).map((x) => ({ created: str(x?.created, 40), expires: str(x?.expires, 40) })),
3277
+ memberships: (Array.isArray(t.memberships) ? t.memberships : []).slice(0, 50).map(person)
3278
+ },
3279
+ billingUrl: sameOrigin2(j.billing_url, creds.host),
3280
+ offer: offerOf(j.offer, creds.host),
3281
+ /** the plan of a paying team the account is in (a newer server says it), else null */
3282
+ teamPlan: j.team_plan && typeof j.team_plan === "object" && str(j.team_plan.id, 40) ? { id: str(j.team_plan.id, 40), name: str(j.team_plan.name, 40) ?? str(j.team_plan.id, 40) } : null
3283
+ };
3284
+ }
3285
+ async function createInvite(creds, opts = {}) {
3286
+ const r = await request("/api/cli/team/invite", { ...base(creds, opts), method: "POST", body: {} });
3287
+ if (!r.ok) return refused(r, creds.host);
3288
+ const url = sameOrigin2(r.json?.url, creds.host);
3289
+ return url ? { ok: true, url, expires: str(r.json?.expires, 40) } : { ok: false, status: r.status, reason: "the server sent no invite link" };
3290
+ }
3291
+ async function fetchConnections(creds, id, opts = {}) {
3292
+ const r = await request(`/api/cli/connections?id=${encodeURIComponent(id)}`, base(creds, opts));
3293
+ if (!r.ok) return refused(r, creds.host);
3294
+ const j = r.json ?? {};
3295
+ return {
3296
+ ok: true,
3297
+ forwarding: j.forwarding === true,
3298
+ plan: str(j.plan, 40),
3299
+ upgradeUrl: sameOrigin2(j.upgrade_url, creds.host),
3300
+ kinds: (Array.isArray(j.kinds) ? j.kinds : []).filter((k) => typeof k === "string" && /^[a-z]{1,20}$/.test(k)),
3301
+ privateLink: j.private_link === true,
3302
+ list: (Array.isArray(j.integrations) ? j.integrations : []).filter((x) => x && typeof x === "object" && typeof x.kind === "string").slice(0, 20).map((x) => ({ kind: x.kind.slice(0, 20), enabled: x.enabled === true, summary: summaryText(x.summary), lastSent: str(x.last_sent, 40), lastError: str(x.last_error, 200) }))
3303
+ };
3304
+ }
3305
+ function summaryText(v) {
3306
+ if (typeof v === "string") return v.slice(0, 160);
3307
+ if (!v || typeof v !== "object") return "";
3308
+ return Object.entries(v).filter(([, x]) => typeof x === "string" || typeof x === "number").slice(0, 4).map(([k, x]) => `${k} ${String(x).slice(0, 80)}`).join(", ");
3309
+ }
3310
+ async function changeConnection(creds, id, kind, how, fields = {}, opts = {}) {
3311
+ const q = `?id=${encodeURIComponent(id)}`;
3312
+ const path = `/api/cli/connections/${encodeURIComponent(kind)}`;
3313
+ const call = { set: [path, "PUT", fields], on: [path, "PATCH", { enabled: true }], off: [path, "PATCH", { enabled: false }], test: [`${path}/test`, "POST", {}], remove: [path, "DELETE", void 0] }[how];
3314
+ if (!call) return { ok: false, status: 0, reason: `unknown change ${how}` };
3315
+ const r = await request(`${call[0]}${q}`, { ...base(creds, opts), method: call[1], ...call[2] !== void 0 ? { body: call[2] } : {}, timeoutMs: how === "test" ? 3e4 : void 0 });
3316
+ if (!r.ok) return refused(r, creds.host);
3317
+ return { ok: true, summary: summaryText(r.json?.summary), secret: str(r.json?.secret, 200) };
3318
+ }
3319
+ async function fetchEvents(creds, id, q = {}, opts = {}) {
3320
+ const p = new URLSearchParams({ id, format: q.format === "csv" ? "csv" : "jsonl" });
3321
+ if (q.from) p.set("from", q.from);
3322
+ if (q.to) p.set("to", q.to);
3323
+ if (q.cursor) p.set("cursor", q.cursor);
3324
+ const fetchFn = opts.fetchFn ?? globalThis.fetch;
3325
+ try {
3326
+ const res = await fetchFn(`${creds.host}/api/cli/events?${p}`, { headers: { authorization: `Bearer ${creds.access_token}`, accept: "*/*" }, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? 6e4) });
3327
+ if (!res.ok) {
3328
+ let json = null;
3329
+ try {
3330
+ json = await res.json();
3331
+ } catch {
3215
3332
  }
3216
- token = r.token;
3217
- row("App", `${c.bold(r.name)} ${c.gray(`created; project key ${token}`)}`);
3218
- if (r.dashboardUrl) row("Dashboard", c.cyan(r.dashboardUrl));
3219
- out();
3333
+ return refused({ status: res.status, json }, creds.host);
3220
3334
  }
3221
- printManual(token);
3222
- return 0;
3335
+ return { ok: true, text: await res.text(), next: res.headers.get("x-genclass-next-cursor") || null };
3336
+ } catch (e) {
3337
+ return { ok: false, status: 0, reason: e?.name === "TimeoutError" ? "no answer within 60 s" : `network error (${e?.cause?.code ?? e?.message ?? e})` };
3223
3338
  }
3224
- out();
3225
- return app ? init({ ...o, token: app.token }, { banner: false, cmd: "connect", creds, app }) : init(o, { banner: false, cmd: "connect", creds, create: createName });
3226
3339
  }
3227
- async function connect(o) {
3228
- banner("connect");
3229
- hostNotice();
3230
- await versionNotice(o);
3231
- const { creds, otherHost } = readCredentialsFor();
3232
- if (!creds) {
3233
- out(` Not signed in${otherHost ? ` at ${apiHost()} (the saved session is for ${otherHost})` : ""}. Sign in first: ${c.cyan(`${CMD} login`)} (it offers to connect this app too).`);
3234
- out();
3235
- return 1;
3236
- }
3237
- row("Account", accountLabel(creds.account));
3238
- const st = inspectProject(o);
3239
- const no = refuse(st);
3240
- if (no !== null) return no;
3241
- return connectApp(o, creds, st, null);
3340
+ async function saveFunnels(creds, id, funnels2, opts = {}) {
3341
+ const r = await request(`/api/cli/funnels?id=${encodeURIComponent(id)}`, { ...base(creds, opts), method: "PUT", body: { funnels: funnels2 } });
3342
+ if (!r.ok) return refused(r, creds.host);
3343
+ return { ok: true, funnels: (Array.isArray(r.json?.funnels) ? r.json.funnels : []).map((f) => ({ name: str(f?.name, 60) ?? "Funnel", steps: (Array.isArray(f?.steps) ? f.steps : []).filter((x) => typeof x === "string") })) };
3242
3344
  }
3243
- async function afterLogin(o, creds, me) {
3244
- if (o.noConnect) return 0;
3245
- const st = inspectProject(o);
3246
- if (st.project.refused || !st.project.framework) {
3247
- out(` Next: run ${c.cyan(`${CMD} connect`)} in your web app's folder to connect it to your account.`);
3248
- out(` ${c.gray(`Your apps' dashboards, free: ${hostUrl("/account")}`)}`);
3249
- out();
3250
- return 0;
3251
- }
3252
- const where = relative4(process.cwd(), st.cwd) || ".";
3253
- const name = st.project.pkg?.name || st.project.name;
3254
- const ok = o.yes ? true : await confirm(`Connect ${name} (${where}, ${st.project.label}) to your account?`);
3255
- if (ok === null) {
3256
- out(` Not a terminal: run ${c.cyan(`${CMD} connect --yes`)} here to connect this app.`);
3257
- out();
3258
- return 0;
3259
- }
3260
- if (!ok) {
3261
- out(` Not connected. Later: ${c.cyan(`${CMD} connect`)}`);
3262
- out();
3263
- return 0;
3345
+ async function makeAgentLink(creds, id, opts = {}) {
3346
+ const r = await request(`/api/cli/link?id=${encodeURIComponent(id)}`, { ...base(creds, opts), method: "POST", body: {} });
3347
+ if (!r.ok) return refused(r, creds.host);
3348
+ const url = sameOrigin2(r.json?.dashboardUrl, creds.host);
3349
+ return url && /\/dashboard\/[A-Za-z0-9]{32}$/.test(url) ? { ok: true, url } : { ok: false, status: r.status, reason: "the server sent no link" };
3350
+ }
3351
+ async function askModel(creds, q, opts = {}) {
3352
+ const r = await request("/api/cli/ask", { ...base(creds, opts), method: "POST", body: { id: q.id, range: q.range ?? "7d", question: q.question, history: (q.history ?? []).slice(-3) }, timeoutMs: opts.timeoutMs ?? 6e4 });
3353
+ if (!r.ok) return refused(r, creds.host);
3354
+ const j = r.json ?? {};
3355
+ return {
3356
+ ok: true,
3357
+ answer: typeof j.answer === "string" && j.answer.trim() ? j.answer.slice(0, 3e3) : null,
3358
+ why: ["no-model", "limit", "failed"].includes(j.why) ? j.why : null,
3359
+ range: str(j.range, 8),
3360
+ remainingToday: numOrNull(j.remaining_today),
3361
+ perDay: numOrNull(j.per_day),
3362
+ upgradeUrl: sameOrigin2(j.upgrade_url, creds.host)
3363
+ };
3364
+ }
3365
+ var str, proOf, why, sameOrigin2, count, pairs, base, refused, numOrNull, person;
3366
+ var init_api = __esm({
3367
+ "src/api.mjs"() {
3368
+ init_define_GENCLASS_BUILD();
3369
+ init_account();
3370
+ str = (v, max = 200) => typeof v === "string" ? v.slice(0, max) : null;
3371
+ proOf = (r, host) => r.status === 402 && r.json?.needs_pro === true ? { needsPro: cliOf({ ...r.json, paid: false }, host) } : {};
3372
+ why = (r, what) => r.status === 402 && r.json?.needs_pro === true && typeof r.json.error === "string" ? r.json.error.slice(0, 300) : failure(r, what);
3373
+ sameOrigin2 = (u, host) => {
3374
+ try {
3375
+ return typeof u === "string" && new URL(u).origin === host ? u : null;
3376
+ } catch {
3377
+ return null;
3378
+ }
3379
+ };
3380
+ count = (v) => Number.isFinite(Number(v)) ? Math.max(0, Math.round(Number(v))) : 0;
3381
+ pairs = (list2, max) => (Array.isArray(list2) ? list2 : []).filter((x) => x && typeof x === "object" && typeof x.key === "string").slice(0, max).map((x) => ({ key: x.key.slice(0, 300), count: count(x.count) }));
3382
+ base = (creds, opts) => ({ token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3383
+ refused = (r, host, what) => ({
3384
+ ok: false,
3385
+ status: r.status,
3386
+ reason: typeof r.json?.error === "string" && r.status !== 401 ? r.json.error.slice(0, 300) : failure(r, what),
3387
+ // an app the caller names comes from the account's own list, so a bare 404 is a server without the route; a
3388
+ // 404 with its own sentence ("slack is not set up for this app") is an answer, and is shown
3389
+ ...r.status === 404 && (typeof r.json?.error !== "string" || r.json.error === "not found") ? { missing: true } : {},
3390
+ ...r.json?.reauth === true ? { reauth: true } : {},
3391
+ ...sameOrigin2(r.json?.upgrade_url, host) ? { upgradeUrl: sameOrigin2(r.json.upgrade_url, host) } : {},
3392
+ // a part of the paid plan: which plan, its trial and price (the Pro box)
3393
+ ...r.json?.locked === true ? { lock: lockOf(r.json, host) } : {},
3394
+ // the genclass command is Pro's: where Pro starts
3395
+ ...proOf(r, host)
3396
+ });
3397
+ numOrNull = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3398
+ person = (x) => ({ label: str(x?.email, 120) ?? (str(x?.github_login, 60) ? `@${str(x.github_login, 60)}` : "a GenClass account"), joined: str(x?.joined, 40), active: x?.active !== false });
3264
3399
  }
3265
- out();
3266
- return connectApp(o, creds, st, me);
3267
- }
3268
- async function login(o) {
3269
- banner("login");
3270
- hostNotice();
3271
- await versionNotice(o);
3272
- const host = apiHost();
3273
- const saved = readCredentialsFor(host);
3274
- if (saved.creds) {
3275
- const me = await fetchMe(saved.creds);
3276
- if (me.ok) {
3277
- row("Account", `${accountLabel(me.account)} ${c.gray(`(already signed in; ${CMD} logout to switch accounts)`)}`);
3278
- out();
3279
- return afterLogin(o, { ...saved.creds, account: me.account }, me);
3280
- }
3281
- if (me.status !== 401) {
3282
- err(` ${c.red(sym.cross)} Could not reach ${host} (${me.reason}).`);
3283
- out();
3284
- return 1;
3400
+ });
3401
+
3402
+ // src/art.mjs
3403
+ function markRows() {
3404
+ const lines = [];
3405
+ for (let y = 0; y < MARK2.length; y += 2) {
3406
+ let line = "";
3407
+ for (let x = 0; x < MARK2[y].length; x++) {
3408
+ const top2 = MARK2[y][x];
3409
+ const bottom = MARK2[y + 1][x];
3410
+ const t = top2 !== ".";
3411
+ const b = bottom !== ".";
3412
+ if (!t && !b) line += " ";
3413
+ else if (!useColor) line += t && b ? "\u2588" : t ? "\u2580" : "\u2584";
3414
+ else if (t && b) line += top2 === bottom ? `${fg(top2)}\u2588${ESC}[39m` : `${fg(top2)}${bg(bottom)}\u2580${ESC}[39m${ESC}[49m`;
3415
+ else line += `${fg(t ? top2 : bottom)}${t ? "\u2580" : "\u2584"}${ESC}[39m`;
3285
3416
  }
3286
- out(` ${c.yellow(sym.warn)} The saved session no longer works (signed out, revoked or expired): signing in again.`);
3287
- out();
3288
- }
3289
- const dev = await startDeviceLogin({ host });
3290
- if (!dev.ok) {
3291
- err(` ${c.red(sym.cross)} Could not start signing in at ${host} (${dev.reason}).`);
3292
- out();
3293
- return 1;
3417
+ lines.push(line);
3294
3418
  }
3295
- out(` Open this link, sign in (Google, email and password, GitHub or a passkey) and approve the code:`);
3296
- out(` ${c.bold(c.cyan(dev.verification_uri_complete))}`);
3297
- out();
3298
- row("Code", `${c.bold(dev.user_code)} ${c.gray("(check that the page shows the same code)")}`);
3299
- out();
3300
- if (openBrowser(dev.verification_uri_complete, o)) out(` ${c.gray("Opening it in your browser.")}`);
3301
- else out(` ${c.gray("Open the link in a browser on any device.")}`);
3302
- const minutes = Math.max(1, Math.round(dev.expires_in / 60));
3303
- out(` Waiting for approval ${c.gray(`(the code expires in ${minutes} minute${minutes === 1 ? "" : "s"}; Ctrl-C to cancel)`)}`);
3304
- const ctl = new AbortController();
3305
- const onSigint = () => ctl.abort();
3306
- process.on("SIGINT", onSigint);
3307
- let r;
3308
- try {
3309
- r = await pollDeviceLogin(dev, { host, signal: ctl.signal, onSlowDown: (s) => out(` ${c.gray(`The server asked for slower polling: every ${s} s now.`)}`) });
3310
- } finally {
3311
- process.removeListener("SIGINT", onSigint);
3419
+ return lines;
3420
+ }
3421
+ function canDraw(columns = process.stdout.columns, env2 = process.env, platform = process.platform) {
3422
+ const unicode3 = platform !== "win32" || !!env2.WT_SESSION || !!env2.TERM_PROGRAM;
3423
+ return !!process.stdout.isTTY && unicode3 && env2.TERM !== "dumb" && Number(columns) >= 44;
3424
+ }
3425
+ var MARK2, COLOURS, truecolor, ESC, fg, bg, brand;
3426
+ var init_art = __esm({
3427
+ "src/art.mjs"() {
3428
+ init_define_GENCLASS_BUILD();
3429
+ init_ui();
3430
+ MARK2 = [
3431
+ ".........G......",
3432
+ ".....GGggGG.....",
3433
+ "...gGGGGggGG....",
3434
+ "..gGGGGGggGG....",
3435
+ ".gGGGG..gg......",
3436
+ "gGGg............",
3437
+ "gGgg............",
3438
+ "Ggg......rrRRR..",
3439
+ "Ggg......rRRRRR.",
3440
+ "Gggg......rrrRR.",
3441
+ "Gggg.......rrRR.",
3442
+ ".gggG.rR..rrrr..",
3443
+ "..gG.RRrrrrrrr..",
3444
+ "....RRRRRRrrr...",
3445
+ ".....RRRRrr.....",
3446
+ ".......R........"
3447
+ ];
3448
+ COLOURS = {
3449
+ G: { rgb: [0, 200, 91], ansi: 92 },
3450
+ g: { rgb: [0, 152, 97], ansi: 32 },
3451
+ R: { rgb: [252, 31, 4], ansi: 91 },
3452
+ r: { rgb: [215, 1, 14], ansi: 31 }
3453
+ };
3454
+ truecolor = () => useColor && /truecolor|24bit/i.test(process.env.COLORTERM ?? "");
3455
+ ESC = String.fromCharCode(27);
3456
+ fg = (k) => truecolor() ? `${ESC}[38;2;${COLOURS[k].rgb.join(";")}m` : `${ESC}[${COLOURS[k].ansi}m`;
3457
+ bg = (k) => truecolor() ? `${ESC}[48;2;${COLOURS[k].rgb.join(";")}m` : `${ESC}[${COLOURS[k].ansi + 10}m`;
3458
+ brand = (text) => truecolor() ? `${fg("G")}${text}${ESC}[39m` : c.green(text);
3312
3459
  }
3313
- if (!r.ok) {
3314
- out();
3315
- if (r.error === "cancelled") {
3316
- err(` Cancelled: not signed in, nothing was saved.`);
3317
- out();
3318
- return 130;
3460
+ });
3461
+
3462
+ // src/tui.mjs
3463
+ import { homedir as homedir2 } from "node:os";
3464
+ function clean(text, max = 400) {
3465
+ const s = String(text ?? "").replace(ANSI, "").replace(CONTROL, " ").replace(/\s+/g, " ").trim();
3466
+ return s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
3467
+ }
3468
+ function units(words2, cols2) {
3469
+ const list2 = [];
3470
+ let cmd = false;
3471
+ let quote2 = false;
3472
+ let valueNext = false;
3473
+ for (const w of words2) {
3474
+ const p = plainWord(w);
3475
+ const last = list2.length ? plainWord(list2[list2.length - 1].at(-1)) : "";
3476
+ let join18 = false;
3477
+ if (list2.length && cmd) {
3478
+ join18 = quote2 || valueNext || last === "npx" || /^(genclass|@genclass\/)/.test(p) && /^(install|uninstall|-g)$/.test(last) || /^-{1,2}[A-Za-z][\w-]*/.test(p) || /^<[^>]*>/.test(p) || /^"/.test(p) || /^https?:\/\//.test(p) || /^\d+[.,;:)]?$/.test(p) || SUBCOMMANDS.has(p.replace(/[.,;:)]$/, ""));
3479
+ if (join18 && visible(list2[list2.length - 1].join(" ")) + 1 + visible(w) > cols2) join18 = false;
3480
+ }
3481
+ if (join18) list2[list2.length - 1].push(w);
3482
+ else {
3483
+ list2.push([w]);
3484
+ cmd = /^(npx|npm)$/.test(p) || /^(genclass|@genclass\/\S+?)[.,;:)]?$/.test(p);
3485
+ quote2 = false;
3486
+ valueNext = false;
3487
+ if (!cmd) continue;
3319
3488
  }
3320
- if (r.error === "access_denied") err(` ${c.red(sym.cross)} The sign-in was denied in the browser. Nothing was saved.`);
3321
- else if (r.error === "expired_token") err(` ${c.red(sym.cross)} The code expired before it was approved. Run ${c.cyan(`${CMD} login`)} again.`);
3322
- else err(` ${c.red(sym.cross)} Could not sign in (${r.reason}). Nothing was saved.`);
3323
- out();
3324
- return 1;
3325
- }
3326
- const creds = { host, access_token: r.access_token, account: r.account ?? { id: "", email: null, github_login: null }, created: (/* @__PURE__ */ new Date()).toISOString() };
3327
- let path;
3328
- try {
3329
- path = saveCredentials(creds);
3330
- } catch (e) {
3331
- err(` ${c.red(sym.cross)} Could not save the session (${e?.message ?? e}), so it was ended again.`);
3332
- await revokeSession(creds);
3333
- out();
3334
- return 1;
3489
+ if (!quote2 && /^"/.test(p) && !/.["][.,;:)]?$/.test(p)) quote2 = true;
3490
+ else if (quote2 && /"[.,;:)]?$/.test(p)) quote2 = false;
3491
+ valueNext = !quote2 && VALUED.test(p);
3492
+ if (!quote2 && closes(p)) cmd = false;
3335
3493
  }
3336
- out();
3337
- row("Signed in", `${c.bold(accountLabel(creds.account))}${creds.account.github_login && creds.account.email ? c.gray(` (GitHub ${creds.account.github_login})`) : ""}`);
3338
- out(` ${c.gray(`Session saved in ${path} (only you can read it). Sign out: ${CMD} logout`)}`);
3339
- out();
3340
- return afterLogin(o, creds, null);
3494
+ return list2.map((u) => u.join(" "));
3341
3495
  }
3342
- async function whoami() {
3343
- banner("whoami");
3344
- hostNotice();
3345
- const { creds, otherHost, path } = readCredentialsFor();
3346
- if (!creds) {
3347
- out(` Not signed in${otherHost ? ` at ${apiHost()} (the saved session is for ${otherHost})` : ""}. Sign in: ${c.cyan(`${CMD} login`)}`);
3348
- out();
3349
- return 1;
3496
+ function wrap2(text, cols2 = width() - 4) {
3497
+ const lines = [];
3498
+ for (const para2 of String(text).split("\n")) {
3499
+ let line = "";
3500
+ for (const word of units(para2.split(/[ \t\r\f\v]+/).filter(Boolean), cols2)) {
3501
+ if (line && visible(line) + 1 + visible(word) > cols2) {
3502
+ lines.push(line);
3503
+ line = word;
3504
+ } else line = line ? `${line} ${word}` : word;
3505
+ }
3506
+ lines.push(line);
3350
3507
  }
3351
- const me = await fetchMe(creds);
3352
- if (!me.ok) {
3353
- if (me.status === 401) sessionGone();
3354
- else err(` ${c.red(sym.cross)} Could not reach ${apiHost()} (${me.reason}).`);
3508
+ return lines;
3509
+ }
3510
+ function para(text, indent = " ", paint = (s) => s) {
3511
+ for (const l of wrap2(text, width() - 2 - indent.length)) out(`${indent}${paint(l)}`);
3512
+ }
3513
+ function header(h = {}) {
3514
+ if (homeApp !== null) {
3355
3515
  out();
3356
- return 1;
3357
- }
3358
- const a = me.account;
3359
- row("Account", `${c.bold(accountLabel(a))}${a.github_login && a.email ? c.gray(` (GitHub ${a.github_login})`) : ""}${a.id ? c.gray(` id ${a.id}`) : ""}`);
3360
- row("Session", c.gray(`${path}${when(creds.created) ? `, signed in ${when(creds.created)}` : ""}`));
3361
- out();
3362
- out(` ${c.bold("Apps")} ${c.gray(`(${me.projects.length})`)}`);
3363
- if (!me.projects.length) out(` None yet. In your app's folder: ${c.cyan(`${CMD} connect`)}`);
3364
- const w = Math.min(28, Math.max(4, ...me.projects.map((p) => p.name.length)));
3365
- for (const p of me.projects) {
3366
- out(` ${c.bold(p.name.padEnd(w))} ${p.token} ${c.gray((p.last_event ? `last event ${when(p.last_event)}` : "no events yet").padEnd(31))} ${p.dashboard_url ? c.cyan(p.dashboard_url) : ""}`.trimEnd());
3516
+ if (h.app && clean(h.app, 40) !== homeApp) out(` ${c.bold(clean(h.app, 40))}`);
3517
+ return;
3367
3518
  }
3368
- if (me.projects.length) out(` ${c.gray(`Each app's dashboard is free: open its link above, or run ${CMD} dashboard in the app's folder.`)}`);
3519
+ const left = `${c.bold(c.magenta("GenClass"))}${h.app ? ` ${c.gray(sym.dot)} ${c.bold(clean(h.app, 40))}` : ""}`;
3520
+ const right = h.framework ? c.gray(clean(h.framework, 40)) : "";
3521
+ const gap = Math.max(2, width() - 4 - visible(left) - visible(right));
3369
3522
  out();
3370
- return 0;
3523
+ out(` ${left}${" ".repeat(gap)}${right}`);
3524
+ const who = [h.account ? clean(h.account, 50) : "not signed in", h.plan ? `${clean(h.plan, 20)} plan` : null].filter(Boolean).join(` ${sym.dot} `);
3525
+ out(` ${c.gray(who)}`);
3526
+ if (h.host) out(` ${c.yellow(sym.warn)} ${c.gray(`talking to ${clean(h.host, 60)} (GENCLASS_HOST is set: for tests only)`)}`);
3527
+ rule();
3371
3528
  }
3372
- function showDashboard(o, link, notes = []) {
3373
- out(` ${c.bold("Your dashboard")} ${c.bold(c.cyan(link))}`);
3374
- for (const n2 of notes) out(` ${n2}`);
3375
- for (const l of FREE_LINES) out(` ${c.gray(l)}`);
3376
- if (o.open && openBrowser(link, o)) out(` ${c.gray("Opening it in your browser.")}`);
3377
- out();
3529
+ function folderName(dir, max = 48, home2 = homedir2()) {
3530
+ const d = String(dir ?? "");
3531
+ const short2 = home2 && (d === home2 || d.startsWith(`${home2}/`)) ? `~${d.slice(home2.length)}` : d;
3532
+ return short2.length > max ? `\u2026${short2.slice(short2.length - max + 1)}` : short2;
3378
3533
  }
3379
- async function dashboard(o) {
3380
- banner("dashboard");
3381
- hostNotice();
3382
- const st = inspectProject(o);
3383
- if (st.local?.dashboardUrl && (!st.token || st.local.token === st.token)) {
3384
- showDashboard(o, st.local.dashboardUrl, [`${c.yellow("Keep this link private; it is the only way to open your dashboard.")} ${c.gray(`(from ${LOCAL_FILE})`)}`]);
3385
- return 0;
3534
+ function firstName(label) {
3535
+ const l = clean(label ?? "", 80);
3536
+ const raw = /^GitHub (\S+)$/.exec(l)?.[1] ?? "";
3537
+ const name = raw.replace(/[^\p{L}\p{N}]/gu, "").slice(0, 24);
3538
+ return name ? name[0].toUpperCase() + name.slice(1) : null;
3539
+ }
3540
+ function card(h = {}) {
3541
+ const inner = width() - 6;
3542
+ const B = unicode2 ? { tl: "\u256D", tr: "\u256E", bl: "\u2570", br: "\u256F", h: "\u2500", v: "\u2502" } : { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" };
3543
+ const title = ` ${c.bold("Gen")}${c.bold(brand("Class"))} `;
3544
+ const version2 = h.version ? ` ${c.gray(`v${clean(h.version, 20)}`)} ` : "";
3545
+ const row3 = (text = "") => out(` ${brand(B.v)}${centre(text, inner)}${brand(B.v)}`);
3546
+ const fit2 = (text) => clean(text, inner - 4);
3547
+ const name = h.account ? firstName(h.account) : null;
3548
+ out();
3549
+ out(` ${brand(B.tl + B.h)}${title}${brand(B.h.repeat(Math.max(0, inner - 2 - visible(title) - visible(version2))))}${version2}${brand(B.h + B.tr)}`);
3550
+ row3();
3551
+ row3(c.bold(h.account ? `Welcome back${name ? `, ${name}` : ""}!` : "Welcome to GenClass"));
3552
+ if (!h.account) {
3553
+ row3();
3554
+ const halves = ["Finds what breaks in your web app,", "and tells you what it needs next."];
3555
+ for (const l of halves.join(" ").length <= inner - 6 ? [halves.join(" ")] : halves) row3(c.gray(l));
3386
3556
  }
3387
- const { creds } = readCredentialsFor();
3388
- if (creds) {
3389
- const me = await fetchMe(creds);
3390
- if (!me.ok) {
3391
- if (me.status === 401) sessionGone();
3392
- else err(` ${c.red(sym.cross)} Could not reach ${apiHost()} (${me.reason}).`);
3393
- out();
3394
- return 1;
3395
- }
3396
- const app = st.token ? me.projects.find((p) => p.token === st.token) : null;
3397
- if (app?.dashboard_url) {
3398
- showDashboard(o, app.dashboard_url, [c.gray(`${app.name}, in your GenClass account (${accountLabel(me.account)}): sign in at ${apiHost()} to open it.`)]);
3399
- return 0;
3400
- }
3401
- if (st.token) out(` This folder's project key (${st.token}) is not one of your account's apps; add it with ${c.cyan(`${CMD} connect`)}.`);
3402
- out(` ${c.bold("Your apps")} ${c.bold(c.cyan(hostUrl("/account")))}`);
3403
- if (!me.projects.length) out(` None yet. In your app's folder: ${c.cyan(`${CMD} connect`)}`);
3404
- const w = Math.min(28, Math.max(4, ...me.projects.map((p) => p.name.length)));
3405
- for (const p of me.projects) out(` ${c.bold(p.name.padEnd(w))} ${p.dashboard_url ? c.cyan(p.dashboard_url) : ""}`.trimEnd());
3406
- for (const l of FREE_LINES) out(` ${c.gray(l)}`);
3407
- if (o.open && openBrowser(hostUrl("/account"), o)) out(` ${c.gray("Opening it in your browser.")}`);
3408
- out();
3409
- return st.token ? 1 : 0;
3557
+ row3();
3558
+ if (unicode2) {
3559
+ for (const m of markRows()) row3(m);
3560
+ row3();
3410
3561
  }
3411
- if (st.token) {
3412
- out(` This app's project key is ${st.token}. Its dashboard is in the GenClass account it belongs to`);
3413
- out(` (${c.cyan(hostUrl("/account"))}), or behind the private link you got with the key.`);
3414
- out(` Sign in to print its link here: ${c.cyan(`${CMD} login`)}`);
3562
+ const app = [h.app ? clean(h.app, 40) : null, h.framework ? clean(h.framework, 40) : null].filter(Boolean).join(` ${sym.dot} `);
3563
+ if (app) row3(c.gray(fit2(app)));
3564
+ row3(c.gray(fit2([h.account ? clean(h.account, 50) : "not signed in", h.plan ? `${clean(h.plan, 20)} plan` : null].filter(Boolean).join(` ${sym.dot} `))));
3565
+ if (h.cwd) row3(c.gray(folderName(h.cwd, inner - 4)));
3566
+ row3();
3567
+ out(` ${brand(B.bl + B.h.repeat(inner) + B.br)}`);
3568
+ if (h.host) {
3415
3569
  out();
3416
- return 1;
3570
+ out(` ${c.yellow(sym.warn)} ${c.gray(`talking to ${clean(h.host, 60)} (GENCLASS_HOST is set: for tests only)`)}`);
3417
3571
  }
3418
- out(` No GenClass project key in ${relative4(process.cwd(), st.cwd) || "this folder"}. Get a free dashboard for this app: ${c.cyan(`${CMD} init`)}`);
3419
- out(` ${c.gray(`(or ${CMD} login, then ${CMD} connect, to keep it in a GenClass account)`)}`);
3420
3572
  out();
3421
- return 1;
3422
3573
  }
3423
- async function logout() {
3424
- banner("logout");
3425
- hostNotice();
3426
- const { creds, otherHost, path } = readCredentialsFor();
3427
- if (!creds) {
3428
- if (otherHost) {
3429
- out(` The saved session is for ${otherHost}, not ${apiHost()}: unset GENCLASS_HOST to sign out there.`);
3430
- out();
3431
- return 1;
3432
- }
3433
- out(` Not signed in: nothing to do.`);
3434
- out();
3435
- return 0;
3436
- }
3437
- const r = await revokeSession(creds);
3438
- deleteCredentials();
3439
- if (!r.ok) {
3440
- err(` ${c.yellow(sym.warn)} Could not end the session at ${apiHost()} (${r.reason}). ${path} is deleted.`);
3441
- err(` End it yourself at ${c.cyan(hostUrl("/account"))} (CLI sessions, Revoke).`);
3442
- out();
3443
- return 1;
3444
- }
3445
- row("Signed out", `${accountLabel(creds.account)} ${c.gray(`(the CLI session is ended at genclass.dev and ${path} is deleted)`)}`);
3574
+ function proBox(what, lock = {}) {
3575
+ const plan2 = clean(lock.plan ?? "Pro", 20);
3446
3576
  out();
3447
- return 0;
3577
+ out(` ${badge(plan2.toUpperCase())}`);
3578
+ for (const l of wrap2(clean(what, 300), width() - 6)) out(` ${c.bold(l)}`);
3579
+ const terms = lock.trialDays ? `${lock.trialDays} days free, then ${clean(lock.price ?? "the monthly price", 40)}. Cancel any time.` : lock.price ? `${clean(lock.price, 40)}.` : "";
3580
+ for (const l of wrap2(`${terms ? `${terms} ` : ""}Start: npx genclass upgrade`, width() - 6)) out(` ${l}`);
3581
+ if (lock.upgradeUrl) out(` ${c.cyan(clean(lock.upgradeUrl, 200))}`);
3448
3582
  }
3449
- async function run2(cmd, argv) {
3450
- const h = hostConfig();
3451
- if (h.error) {
3452
- err(`${SELF2} ${cmd}: ${h.error}`);
3453
- return 2;
3454
- }
3455
- let o;
3456
- try {
3457
- o = parse(argv, SPECS[cmd]);
3458
- if (o.app !== void 0 && o.name !== void 0) throw new UsageError("--app and --name contradict each other (use an app, or create one)");
3459
- } catch (e) {
3460
- if (e instanceof UsageError) {
3461
- err(`${SELF2} ${cmd}: ${e.message}
3462
-
3463
- ${usage2()}`);
3464
- return 2;
3465
- }
3466
- throw e;
3467
- }
3468
- if (o.help) {
3469
- out(usage2());
3470
- return 0;
3583
+ function planCard(offer, app, heading = null) {
3584
+ const inner = width() - 6;
3585
+ const B = unicode2 ? { tl: "\u256D", tr: "\u256E", bl: "\u2570", br: "\u256F", h: "\u2500", v: "\u2502" } : { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" };
3586
+ const title = ` ${c.bold(heading ? clean(heading, 50) : app ? `A plan for ${clean(app, 30)}` : "A plan for this project")} `;
3587
+ const row3 = (text = "") => out(` ${brand(B.v)} ${text}${" ".repeat(Math.max(0, inner - 3 - visible(text)))}${brand(B.v)}`);
3588
+ const room3 = inner - 6;
3589
+ out();
3590
+ out(` ${brand(B.tl + B.h)}${title}${brand(B.h.repeat(Math.max(0, inner - 1 - visible(title))))}${brand(B.tr)}`);
3591
+ row3();
3592
+ const name = badge(clean(offer.plan.name, 20).toUpperCase().split("").join(" "));
3593
+ const price = c.bold(clean(offer.price, 40));
3594
+ if (visible(name) + 2 + visible(price) <= room3) row3(`${name}${" ".repeat(room3 - visible(name) - visible(price))}${price}`);
3595
+ else {
3596
+ row3(name);
3597
+ row3(price);
3471
3598
  }
3472
- if (cmd === "login") return login(o);
3473
- if (cmd === "connect") return connect(o);
3474
- if (cmd === "whoami") return whoami(o);
3475
- if (cmd === "dashboard") return dashboard(o);
3476
- return logout(o);
3477
- }
3478
- var USAGE2, SPECS, when, onHost, sessionGone, SELF2, usage2;
3479
- var init_login = __esm({
3480
- "../runtime/bin/lib/login.mjs"() {
3481
- "use strict";
3482
- init_define_GENCLASS_BUILD();
3483
- init_account();
3484
- init_host();
3485
- init_init();
3486
- init_plan();
3487
- init_token();
3488
- init_ui();
3489
- init_version();
3490
- USAGE2 = `Usage:
3491
- genclass-runtime login [--yes] [--no-browser] [--no-connect] [--app <id|name>] [--name <name>]
3492
- [--no-install] [--cwd <dir>]
3493
- genclass-runtime connect [--app <id|name>] [--name <name>] [--yes] [--dry-run] [--no-install] [--cwd <dir>]
3494
- genclass-runtime whoami
3495
- genclass-runtime logout
3496
- genclass-runtime dashboard [--open] [--cwd <dir>]
3497
-
3498
- login signs this computer in to your GenClass account. It prints a code and a link to
3499
- https://genclass.dev/login/device and opens it in your browser; you sign in there (Google, email
3500
- and password, GitHub or a passkey) and approve the code. The CLI session is saved, readable only by you, in
3501
- ~/.config/genclass/credentials.json ($XDG_CONFIG_HOME/genclass; Windows: %APPDATA%\\genclass).
3502
- Inside an app's folder it then asks whether to connect that app.
3503
- connect connects the app in this folder to your account: pick one of your apps, or create one named after
3504
- package.json. It writes the app's project key (token) the way init does: it shows the diff and asks
3505
- first, and sets GenClass up if init has not. An app init created without an account (its private
3506
- link is in ${LOCAL_FILE}) can be added to your account instead.
3507
- whoami shows the signed-in account and its apps.
3508
- logout ends the CLI session at genclass.dev and deletes the saved file.
3509
- dashboard
3510
- prints the link to this app's dashboard, free for every app: what GenClass found, on which pages
3511
- and what it did (how visitors use each page, with analytics: true, shows on the Team plan). It reads the private link in
3512
- ${LOCAL_FILE} without contacting anything; signed in, it finds the app in your account (or lists
3513
- your apps).
3514
-
3515
- --yes, -y no questions: login connects this folder's app; connect uses your app named like
3516
- package.json (or creates it) and applies the changes
3517
- --no-browser login: print the link only, do not open a browser
3518
- --open dashboard: also open the link in your browser
3519
- --no-connect login: do not offer to connect the app in this folder
3520
- --app <id|name> use this app of your account
3521
- --name <name> create a new app with this name (default: package.json's name)
3522
- --dry-run connect: show what would change; it reads your app list, and creates and writes nothing
3523
- --no-install do not run the package manager (when connect sets GenClass up)
3524
- --cwd <dir> the project directory (default: the current directory)
3525
-
3526
- These commands contact genclass.dev when you run them; creating an app or writing a file is asked first. The
3527
- project key is public (it ships in your page and can only add telemetry to its app); the CLI session is not:
3528
- logout ends it.`;
3529
- SPECS = {
3530
- login: {
3531
- bool: { yes: "yes", y: "yes", "no-browser": "noBrowser", "no-connect": "noConnect", "no-install": "noInstall", help: "help", h: "help" },
3532
- value: { cwd: "cwd", app: "app", name: "name" }
3533
- },
3534
- connect: {
3535
- bool: { yes: "yes", y: "yes", "dry-run": "dryRun", "no-install": "noInstall", help: "help", h: "help" },
3536
- value: { cwd: "cwd", app: "app", name: "name" }
3537
- },
3538
- whoami: { bool: { help: "help", h: "help" }, value: { cwd: "cwd" } },
3539
- logout: { bool: { help: "help", h: "help" }, value: { cwd: "cwd" } },
3540
- dashboard: { bool: { open: "open", help: "help", h: "help" }, value: { cwd: "cwd" } }
3541
- };
3542
- when = (iso) => {
3543
- const d = iso ? new Date(iso) : null;
3544
- if (!d || Number.isNaN(d.getTime())) return null;
3545
- return `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
3546
- };
3547
- onHost = (url, host) => {
3548
- try {
3549
- return new URL(url).origin === host;
3550
- } catch {
3551
- return false;
3552
- }
3553
- };
3554
- sessionGone = () => err(` ${c.red(sym.cross)} The saved CLI session no longer works (signed out, revoked or expired). Sign in again: ${c.cyan(`${CMD} login`)}`);
3555
- SELF2 = HOST_CLI ? CMD : "genclass-runtime";
3556
- usage2 = () => HOST_CLI ? USAGE2.replace(/^ {2}genclass-runtime /gm, ` ${CMD} `) : USAGE2;
3599
+ if (offer.summary) for (const l of wrap2(clean(offer.summary, 200), room3)) row3(c.gray(l));
3600
+ if (offer.trialDays) for (const l of wrap2(`${offer.trialDays} days free, then ${clean(offer.price, 40)}. Cancel any time.`, room3)) row3(c.green(l));
3601
+ row3();
3602
+ for (const f of offer.features) {
3603
+ const [first = "", ...rest] = wrap2(clean(f, 120), room3 - 2);
3604
+ row3(`${c.green(sym.ok)} ${first}`);
3605
+ for (const l of rest) row3(` ${l}`);
3557
3606
  }
3558
- });
3559
-
3560
- // src/api.mjs
3561
- async function fetchOverview(creds, opts = {}) {
3562
- const base2 = { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn };
3563
- let r = await request("/api/cli/overview", base2);
3564
- const full = r.ok;
3565
- if (!r.ok && r.status === 404) r = await request("/api/me", base2);
3566
- if (!r.ok) return { ok: false, status: r.status, reason: failure(r) };
3567
- const j = r.json ?? {};
3568
- const projects = (Array.isArray(j.projects) ? j.projects : []).map((p) => withPlan(cleanProject(p, creds.host), p, creds.host)).filter(Boolean);
3569
- const account = j.account && typeof j.account === "object" ? { id: String(j.account.id ?? ""), email: str(j.account.email), github_login: str(j.account.github_login, 60) } : creds.account;
3570
- if (!full) return { ok: true, account, plan: null, suggestions: null, projects, github: null, billingUrl: null };
3571
- const s = j.suggestions && typeof j.suggestions === "object" ? j.suggestions : null;
3572
- const num = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3573
- return {
3574
- ok: true,
3575
- account,
3576
- plan: j.plan && typeof j.plan === "object" && str(j.plan.id, 40) ? { id: str(j.plan.id, 40), name: str(j.plan.name, 40) ?? str(j.plan.id, 40) } : null,
3577
- suggestions: s ? { perDay: num(s.per_day), shown: num(s.shown), usedToday: num(s.used_today) ?? 0, model: s.model === true } : null,
3578
- projects,
3579
- github: j.github && typeof j.github === "object" ? { app: j.github.app === true, installUrl: sameOrigin2(j.github.install_url, creds.host), connectUrl: sameOrigin2(j.github.connect_url, creds.host) } : null,
3580
- billingUrl: sameOrigin2(j.billing_url, creds.host),
3581
- offer: offerOf(j.offer, creds.host)
3582
- };
3583
- }
3584
- function withPlan(app, p, host) {
3585
- if (!app || !p?.plan || typeof p.plan !== "object" || !str(p.plan.id, 40)) return app;
3586
- return { ...app, plan: { id: str(p.plan.id, 40), name: str(p.plan.name, 40) ?? str(p.plan.id, 40), source: str(p.plan.source, 20) }, needsPlan: p.needs_plan === true, planChosen: p.plan_chosen === true, planUrl: sameOrigin2(p.plan_url, host) };
3587
- }
3588
- function offerOf(o, host) {
3589
- if (!o || typeof o !== "object" || !o.plan || typeof o.plan !== "object") return null;
3590
- const id = str(o.plan.id, 40);
3591
- const price = str(o.price, 60);
3592
- const checkoutUrl = sameOrigin2(o.checkout_url, host);
3593
- if (!id || !price || !checkoutUrl) return null;
3594
- const num = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3595
- const f = o.free && typeof o.free === "object" ? o.free : {};
3596
- return {
3597
- plan: { id, name: str(o.plan.name, 40) ?? id },
3598
- price,
3599
- summary: str(o.summary, 200),
3600
- features: (Array.isArray(o.features) ? o.features : []).filter((x) => typeof x === "string" && x.trim()).slice(0, 12).map((x) => x.slice(0, 120)),
3601
- checkoutUrl,
3602
- free: { name: str(f.name, 40) ?? "Free", apps: num(f.apps), historyDays: num(f.history_days), suggestionsShown: num(f.suggestions_shown), liveFixes: num(f.live_fixes) },
3603
- trialDays: num(o.trial_days)
3604
- };
3607
+ row3();
3608
+ out(` ${brand(B.bl + B.h.repeat(inner) + B.br)}`);
3605
3609
  }
3606
- async function fetchRepoStatus(creds, repo, opts = {}) {
3607
- const r = await request(`/api/cli/github?repo=${encodeURIComponent(repo)}`, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3608
- if (!r.ok) return { ok: false, status: r.status, reason: failure(r), ...r.status === 404 ? { missing: true } : {} };
3609
- const j = r.json ?? {};
3610
- return {
3611
- ok: true,
3612
- known: j.known === true,
3613
- installed: typeof j.installed === "boolean" ? j.installed : null,
3614
- evidence: j.evidence === true,
3615
- prs: Number.isFinite(Number(j.prs)) ? Math.max(0, Number(j.prs)) : 0,
3616
- last: str(j.last, 40),
3617
- private: j.private === true,
3618
- needsPlan: j.needs_plan === true,
3619
- paused: j.paused === true,
3620
- connectUrl: sameOrigin2(j.connect_url, creds.host),
3621
- installUrl: sameOrigin2(j.install_url, creds.host)
3622
- };
3610
+ function barPara(text, paint = c.gray) {
3611
+ for (const l of wrap2(text, width() - 6)) out(` ${BAR()} ${paint(l)}`);
3623
3612
  }
3624
- async function requestPlan(creds, digest, opts = {}) {
3625
- const r = await request("/api/cli/suggest", { method: "POST", token: creds.access_token, host: creds.host, body: digest, fetchFn: opts.fetchFn, timeoutMs: opts.timeoutMs ?? 12e4 });
3626
- if (!r.ok) return { ok: false, status: r.status, reason: failure(r), ...r.status === 404 ? { missing: true } : {} };
3627
- const j = r.json ?? {};
3628
- const items = (Array.isArray(j.items) ? j.items : []).filter((i) => i && typeof i === "object" && /^[a-z0-9-]{1,40}$/.test(String(i.id ?? ""))).slice(0, 80).map((i) => ({ id: String(i.id), why: str(i.why, 600), step: str(i.step, 400), prompt: str(i.prompt, 1200) }));
3629
- return {
3630
- ok: true,
3631
- source: j.source === "model" ? "model" : "checks",
3632
- plan: j.plan && typeof j.plan === "object" && str(j.plan.id, 40) ? { id: str(j.plan.id, 40), name: str(j.plan.name, 40) ?? str(j.plan.id, 40) } : null,
3633
- total: Number.isFinite(Number(j.total)) ? Number(j.total) : items.length,
3634
- items,
3635
- locked: Number.isFinite(Number(j.locked)) ? Math.max(0, Number(j.locked)) : 0,
3636
- lockedIds: (Array.isArray(j.locked_ids) ? j.locked_ids : []).filter((x) => typeof x === "string" && /^[a-z0-9-]{1,40}$/.test(x)).slice(0, 80),
3637
- upgradeUrl: sameOrigin2(j.upgrade_url, creds.host),
3638
- remainingToday: Number.isFinite(Number(j.remaining_today)) && j.remaining_today !== null ? Number(j.remaining_today) : null,
3639
- limited: j.limited === true,
3640
- /** the model's own ideas (not measured) and website designs: Pro gets them, Free their counts */
3641
- ideas: (Array.isArray(j.ideas) ? j.ideas : []).filter((i) => i && typeof i === "object" && str(i.title, 120)).slice(0, 20).map((i) => ({ title: str(i.title, 120), why: str(i.why, 600), step: str(i.step, 400), prompt: str(i.prompt, 1200) })),
3642
- designs: (Array.isArray(j.designs) ? j.designs : []).filter((d) => d && typeof d === "object" && str(d.title, 120) && /^https:\/\/[a-z0-9.-]+\.[a-z]{2,}(\/\S*)?$/i.test(String(d.inspired_by ?? "")) && str(d.prompt, 4e3)).slice(0, 4).map((d) => ({ title: str(d.title, 120), inspiredBy: String(d.inspired_by).slice(0, 200), why: str(d.why, 600), prompt: str(d.prompt, 4e3) })),
3643
- ideasLocked: Number.isFinite(Number(j.ideas_locked)) ? Math.max(0, Number(j.ideas_locked)) : 0,
3644
- designsLocked: Number.isFinite(Number(j.designs_locked)) ? Math.max(0, Number(j.designs_locked)) : 0,
3645
- /** this answer was kept from an earlier run (Free sees its first one again until it pays) */
3646
- cachedAt: str(j.cached_at, 40),
3647
- upgradePlan: j.upgrade_plan && typeof j.upgrade_plan === "object" ? { plan: str(j.upgrade_plan.name, 40), price: str(j.upgrade_plan.price, 60), trialDays: Number.isInteger(j.upgrade_plan.trial_days) && j.upgrade_plan.trial_days > 0 ? j.upgrade_plan.trial_days : null } : null
3613
+ function checklist(steps) {
3614
+ const pad = Math.min(30, Math.max(...steps.map((s) => s.title.length)) + 2);
3615
+ for (const s of steps) {
3616
+ const title = s.state === "next" ? c.bold(s.title.padEnd(pad)) : s.state === "done" ? s.title.padEnd(pad) : c.gray(s.title.padEnd(pad));
3617
+ const room3 = width() - 4 - 3 - pad;
3618
+ const detail = s.detail ? clean(s.detail, Math.max(20, room3)) : "";
3619
+ out(` ${(MARK3[s.state] ?? MARK3.todo)()} ${title}${detail ? c.gray(detail) : ""}`);
3620
+ }
3621
+ }
3622
+ function summary(steps) {
3623
+ const room3 = width() - 4 - 3 - 9;
3624
+ const names = (list2) => {
3625
+ const lines = [];
3626
+ let line2 = "";
3627
+ for (const t of list2.map((s) => s.title)) {
3628
+ if (line2 && visible(line2) + 3 + t.length > room3) {
3629
+ lines.push(`${line2} ${sym.dot}`);
3630
+ line2 = t;
3631
+ } else line2 = line2 ? `${line2} ${sym.dot} ${t}` : t;
3632
+ }
3633
+ if (line2) lines.push(line2);
3634
+ return lines;
3648
3635
  };
3636
+ const line = (mark2, label, text) => {
3637
+ const [first = "", ...rest] = Array.isArray(text) ? text : [text];
3638
+ out(` ${mark2} ${label}${Array.isArray(text) ? c.gray(first) : first}`);
3639
+ for (const l of rest) out(` ${" ".repeat(12)}${c.gray(l)}`);
3640
+ };
3641
+ const pad = (label) => label.padEnd(9);
3642
+ const done = steps.filter((s) => s.state === "done");
3643
+ const next = steps.find((s) => s.state === "next");
3644
+ const later = steps.filter((s) => s.state === "todo");
3645
+ if (done.length) line(MARK3.done(), pad("Done"), names(done));
3646
+ for (const b of steps.filter((s) => s.state === "blocked")) line(MARK3.blocked(), pad(b.title), c.gray(clean(b.detail ?? "", room3)));
3647
+ if (next) line(MARK3.next(), c.bold(pad("Next")), c.bold(clean(next.doing ?? next.title, room3)));
3648
+ for (const w of steps.filter((s) => s.state === "waiting")) line(MARK3.waiting(), pad("Waiting"), c.gray(clean(`${w.title}: ${w.detail ?? ""}`, room3)));
3649
+ if (later.length) line(MARK3.todo(), c.gray(pad("Later")), names(later));
3649
3650
  }
3650
- async function signInIsOld(creds, opts = {}) {
3651
- const ask3 = (path) => request(path, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3652
- const old = (r) => !r.ok && r.status === 403 && r.json?.reauth === true;
3653
- const newest = await ask3("/api/cli/account");
3654
- if (old(newest)) return true;
3655
- if (newest.ok || newest.status !== 404) return false;
3656
- return old(await ask3("/api/cli/app?id=-&range=24h"));
3651
+ function nextBlock(title, text) {
3652
+ out();
3653
+ out(` ${BAR()} ${c.cyan(c.bold("Next"))} ${c.bold(title)}`);
3654
+ if (text) barPara(text);
3657
3655
  }
3658
- function lockOf(l, host) {
3659
- if (!l || typeof l !== "object") return null;
3660
- const days = Number(l.trial_days);
3661
- return { plan: str(l.plan, 40), trialDays: Number.isInteger(days) && days > 0 ? days : null, price: str(l.price, 60), upgradeUrl: sameOrigin2(l.upgrade_url, host) };
3656
+ async function agree(question, def = true) {
3657
+ const a = await confirm(question, def);
3658
+ return inputClosed() ? false : a;
3662
3659
  }
3663
- function liveUsage(u) {
3664
- if (!u || typeof u !== "object" || !Number.isFinite(Number(u.used))) return null;
3665
- const lim = u.limit === null || u.limit === void 0 || !Number.isFinite(Number(u.limit)) ? null : Math.max(0, Math.round(Number(u.limit)));
3666
- return { used: Math.max(0, Math.round(Number(u.used))), limit: lim, observeOnly: u.observe_only === true, resets: str(u.resets, 40) };
3660
+ async function pick(question, labels, def = 0) {
3661
+ const i = await choose(question, labels, def);
3662
+ return inputClosed() ? null : i;
3667
3663
  }
3668
- async function fetchApp(creds, id, range = "7d", opts = {}) {
3669
- const r = await request(`/api/cli/app?id=${encodeURIComponent(id)}&range=${encodeURIComponent(range)}`, { token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3670
- if (!r.ok) return { ok: false, status: r.status, reason: failure(r), ...r.status === 404 ? { missing: true } : {}, ...r.json?.reauth === true ? { reauth: true } : {}, ...r.json?.locked === true ? { locked: true, upgradeUrl: sameOrigin2(r.json.upgrade_url, creds.host) } : {} };
3671
- const j = r.json ?? {};
3672
- const t = j.totals && typeof j.totals === "object" ? j.totals : {};
3673
- const b = j.breakdowns && typeof j.breakdowns === "object" ? j.breakdowns : {};
3674
- const st = j.agent?.stages && typeof j.agent.stages === "object" ? j.agent.stages : {};
3675
- const v = j.visits && typeof j.visits === "object" ? j.visits : {};
3676
- const lock = j.locked?.analytics && typeof j.locked.analytics === "object" ? j.locked.analytics : null;
3677
- return {
3678
- ok: true,
3679
- name: str(j.name, 80) ?? "",
3680
- range: str(j.range, 8) ?? range,
3681
- lastEvent: str(j.lastEvent, 40),
3682
- totals: { visits: count(t.sessions), found: count(t.detections), handled: count(t.acted), possible: count(t.possible), checks: count(t.checks), pageViews: count(t.ix_views) },
3683
- previous: { found: count(j.previous?.detections), visits: count(j.previous?.sessions) },
3684
- /** problems found per bucket (hour or day), oldest first */
3685
- series: (Array.isArray(j.series) ? j.series : []).slice(-400).map((x) => count(x?.detections)),
3686
- /** kind TAB page */
3687
- problems: pairs(b.detect_issue, 200),
3688
- possible: pairs(b.possible_issue, 200),
3689
- checks: pairs(b.check_issue, 200),
3690
- kinds: pairs(b.detect_diagnosis, 25),
3691
- recent: (Array.isArray(j.recent) ? j.recent : []).filter((x) => x && typeof x === "object").slice(0, 20).map((x) => ({ at: str(x.t, 40), kind: str(x.diagnosis, 60), route: str(x.route, 200), handled: x.acted === 1 || x.acted === true })),
3692
- visitors: lock ? null : { visits: count(v.sessions), pages: count(v.pages), bounces: count(v.bounces), entry: pairs(v.entry, 25) },
3693
- visitorsPlan: lock ? { plan: str(lock.plan, 40), upgradeUrl: sameOrigin2(lock.upgrade_url, creds.host) } : null,
3694
- agent: { found: count(st.found), reproduced: count(st.reproduced), fixed: count(st.fixed), closed: count(st.closed), open: count(st.open), last: str(j.agent?.last, 40) },
3695
- dashboardUrl: sameOrigin2(j.dashboard_url, creds.host),
3696
- /** Free sees the totals only: the plan that shows the problems, its trial and price, and its page */
3697
- problemsPlan: lockOf(j.locked?.problems, creds.host),
3698
- /** the problems fixed live this month against the app's plan: past its limit GenClass observes only */
3699
- usage: liveUsage(j.usage),
3700
- /** the app's plan page (plans per project) */
3701
- planUrl: sameOrigin2(j.plan_url, creds.host),
3702
- /** the recorded demo's numbers stand in for measured ones (the server's sample app) */
3703
- demo: j.demo === true,
3704
- // The rest of what the dashboard page reads, for the other views (views.mjs): every total and breakdown by the
3705
- // server's own key, the buckets, the latest events as they are stored, the visits' exit pages and the funnels.
3706
- more: {
3707
- totals: numbers(t),
3708
- breakdowns: Object.fromEntries(
3709
- Object.entries(b).filter(([k, v2]) => /^[a-z_]{1,40}$/.test(k) && Array.isArray(v2)).map(([k, v2]) => [k, pairs(v2, 200)])
3710
- ),
3711
- distinct: numbers(j.distinct),
3712
- series: (Array.isArray(j.series) ? j.series : []).slice(-400).map((x) => ({ bucket: str(x?.bucket, 24) ?? "", pages: count(x?.sessions), found: count(x?.detections), handled: count(x?.acted), possible: count(x?.possible), checks: count(x?.checks), views: count(x?.ix_views), visits: count(x?.ix_sessions) })),
3713
- events: (Array.isArray(j.recent) ? j.recent : []).filter((x) => x && typeof x === "object").slice(0, 50).map((x) => ({
3714
- at: str(x.t, 40),
3715
- route: str(x.route, 200),
3716
- fn: str(x.fn, 80),
3717
- kind: str(x.diagnosis, 60),
3718
- confidence: Number.isFinite(Number(x.confidence)) && x.confidence !== null ? Math.max(0, Math.min(1, Number(x.confidence))) : null,
3719
- mode: str(x.mode, 20),
3720
- trigger: str(x.trigger, 40),
3721
- /** "detect": reported; "acted": the runtime was allowed to act on it */
3722
- tier: str(x.kind, 20),
3723
- handled: x.acted === 1 || x.acted === true,
3724
- executed: x.executed === 1 || x.executed === true,
3725
- action: str(x.action, 60),
3726
- ran: str(x.ran, 60)
3727
- })),
3728
- exit: lock ? [] : pairs(v.exit, 25),
3729
- funnels: (Array.isArray(j.funnels) ? j.funnels : []).filter((f) => f && typeof f === "object" && Array.isArray(f.steps)).slice(0, 5).map((f) => ({ name: str(f.name, 60) ?? "Funnel", steps: f.steps.filter((x) => typeof x === "string").slice(0, 6).map((x) => x.slice(0, 120)), counts: (Array.isArray(f.counts) ? f.counts : []).slice(0, 6).map(count) })),
3730
- /** what the coding agent did with each finding (the MCP server reports it when GENCLASS_REPORT is on) */
3731
- findings: (Array.isArray(j.agent?.findings) ? j.agent.findings : []).filter((x) => x && typeof x === "object").slice(0, 25).map((x) => ({ id: str(x.id, 80), kind: str(x.kind, 60), route: str(x.route, 200), found: str(x.found, 40), reproduced: x.reproduced === true ? true : x.reproduced === false ? false : null, tested: !!x.tested, proven: !!x.proven, closed: x.closed === true, updated: str(x.updated, 40) })),
3732
- agentLog: (Array.isArray(j.agent?.log) ? j.agent.log : []).filter((x) => x && typeof x === "object").slice(0, 50).map((x) => ({ at: str(x.at, 40), step: str(x.t, 20), id: str(x.id, 80), kind: str(x.kind, 60), route: str(x.route, 200), reproduced: x.reproduced === true ? true : x.reproduced === false ? false : null, runs: count(x.runs), races: count(x.races), what: str(x.what, 200) })),
3733
- stages: { found: count(st.found), explained: count(st.explained), reproduced: count(st.reproduced), fixed: count(st.fixed), closed: count(st.closed), open: count(st.open), continued: count(st.continued) },
3734
- previous: numbers(j.previous),
3735
- generated: str(j.generated, 40)
3736
- }
3737
- };
3664
+ async function typed(question) {
3665
+ const a = await ask(question);
3666
+ return a === null || a === "" && inputClosed() ? null : a;
3738
3667
  }
3739
- function numbers(o) {
3740
- const out2 = {};
3741
- if (o && typeof o === "object") {
3742
- for (const [k, v] of Object.entries(o)) if (/^[A-Za-z0-9_]{1,40}$/.test(k) && Number.isFinite(Number(v)) && v !== null) out2[k] = Number(v);
3743
- }
3744
- return out2;
3668
+ async function secret(question) {
3669
+ const a = await ask(question, { hidden: true });
3670
+ return a === null || a === "" && inputClosed() ? null : a;
3745
3671
  }
3746
- async function fetchAccount(creds, opts = {}) {
3747
- const r = await request("/api/cli/account", base(creds, opts));
3748
- if (!r.ok) return refused(r, creds.host);
3749
- const j = r.json ?? {};
3750
- const l = j.limits ?? {};
3751
- const u = j.used ?? {};
3752
- const t = j.team ?? {};
3753
- const inc = j.includes ?? {};
3672
+ function fitLine(label, columns = Number(process.stdout.columns) || 80) {
3673
+ const room3 = Math.max(12, columns - 5);
3674
+ return visible(label) <= room3 ? label : `${String(label).replace(COLOUR, "").slice(0, room3 - 1)}\u2026`;
3675
+ }
3676
+ function spinner(text, opts = {}) {
3677
+ let label = text;
3678
+ let i = 0;
3679
+ let timer = null;
3680
+ if (opts.stoppable && tty2()) {
3681
+ if (visible(`${text} ${STOP_HINT}`) <= Math.max(12, (Number(process.stdout.columns) || 80) - 5)) label = `${text}${c.gray(` ${STOP_HINT}`)}`;
3682
+ else out(` ${c.gray("Enter stops the wait.")}`);
3683
+ }
3684
+ const draw = () => process.stdout.write(`\r\x1B[2K ${c.cyan(FRAMES[i++ % FRAMES.length])} ${fitLine(label)}`);
3685
+ if (tty2()) {
3686
+ draw();
3687
+ timer = setInterval(draw, 90);
3688
+ timer.unref?.();
3689
+ } else out(` ${c.gray(sym.dot)} ${label}`);
3754
3690
  return {
3755
- ok: true,
3756
- plan: { id: str(j.plan?.id, 40) ?? "free", name: str(j.plan?.name, 40) ?? "Free", price: str(j.plan?.price, 60), summary: str(j.plan?.summary, 200) },
3757
- /** why the account has its plan: "paid", "comp" (a grant), "open" (a server with every plan open) or null */
3758
- access: ["paid", "comp", "open"].includes(j.access) ? j.access : null,
3759
- limits: { apps: numOrNull(l.apps), historyDays: numOrNull(l.history_days), seats: numOrNull(l.seats), suggestionsPerDay: numOrNull(l.suggestions_per_day), suggestionsShown: numOrNull(l.suggestions_shown) },
3760
- used: { apps: count(u.apps), suggestionsToday: count(u.suggestions_today), seats: count(u.seats) },
3761
- includes: { analytics: inc.analytics === true, forwarding: inc.forwarding === true, export: inc.export === true, privateRepositories: inc.private_repositories === true },
3762
- subscription: { status: str(j.subscription?.status, 30), periodEnd: str(j.subscription?.current_period_end, 40), cancels: j.subscription?.cancel_at_period_end === true },
3763
- team: {
3764
- seats: numOrNull(t.seats),
3765
- used: count(t.used),
3766
- members: (Array.isArray(t.members) ? t.members : []).slice(0, 200).map(person),
3767
- invites: (Array.isArray(t.invites) ? t.invites : []).slice(0, 200).map((x) => ({ created: str(x?.created, 40), expires: str(x?.expires, 40) })),
3768
- memberships: (Array.isArray(t.memberships) ? t.memberships : []).slice(0, 50).map(person)
3691
+ update(t) {
3692
+ label = t;
3769
3693
  },
3770
- billingUrl: sameOrigin2(j.billing_url, creds.host),
3771
- offer: offerOf(j.offer, creds.host)
3694
+ stop(mark2 = null, final = label) {
3695
+ if (timer) {
3696
+ clearInterval(timer);
3697
+ process.stdout.write("\r\x1B[2K");
3698
+ }
3699
+ if (mark2 === "ok") good(final);
3700
+ else if (mark2 === "warn") warn(final);
3701
+ else if (mark2 === "bad") bad(final);
3702
+ }
3772
3703
  };
3773
3704
  }
3774
- async function createInvite(creds, opts = {}) {
3775
- const r = await request("/api/cli/team/invite", { ...base(creds, opts), method: "POST", body: {} });
3776
- if (!r.ok) return refused(r, creds.host);
3777
- const url = sameOrigin2(r.json?.url, creds.host);
3778
- return url ? { ok: true, url, expires: str(r.json?.expires, 40) } : { ok: false, status: r.status, reason: "the server sent no invite link" };
3705
+ function ago(iso, now = Date.now()) {
3706
+ const t = Date.parse(String(iso ?? ""));
3707
+ if (!Number.isFinite(t)) return "";
3708
+ const s = Math.max(0, Math.round((now - t) / 1e3));
3709
+ if (s < 90) return "just now";
3710
+ const units2 = [
3711
+ [86400 * 365, "year"],
3712
+ [86400 * 30, "month"],
3713
+ [86400, "day"],
3714
+ [3600, "hour"],
3715
+ [60, "minute"]
3716
+ ];
3717
+ for (const [n2, name] of units2) {
3718
+ if (s >= n2) {
3719
+ const v = Math.floor(s / n2);
3720
+ return `${v} ${name}${v === 1 ? "" : "s"} ago`;
3721
+ }
3722
+ }
3723
+ return "just now";
3724
+ }
3725
+ var tty2, unicode2, ESC2, CSI, ANSI, CONTROL, COLOUR, width, visible, SUBCOMMANDS, VALUED, plainWord, closes, rule, homeApp, inHome, homeOpen, centre, badge, BAR, PROMPT, MARK3, note, marked, good, warn, bad, FRAMES, STOP_HINT;
3726
+ var init_tui = __esm({
3727
+ "src/tui.mjs"() {
3728
+ init_define_GENCLASS_BUILD();
3729
+ init_ui();
3730
+ init_art();
3731
+ tty2 = () => !!process.stdout.isTTY;
3732
+ unicode2 = process.platform !== "win32" || !!process.env.WT_SESSION || !!process.env.TERM_PROGRAM;
3733
+ ESC2 = String.fromCharCode(27);
3734
+ CSI = String.fromCharCode(155);
3735
+ ANSI = new RegExp(`${ESC2}\\[[0-9;?]*[ -/]*[@-~]|${ESC2}[@-Z\\\\-_]|${CSI}[0-9;?]*[ -/]*[@-~]`, "g");
3736
+ CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+", "g");
3737
+ COLOUR = new RegExp(`${ESC2}\\[[0-9;]*m`, "g");
3738
+ width = () => Math.max(60, Math.min(96, Number(process.stdout.columns) || 80));
3739
+ visible = (s) => String(s).replace(COLOUR, "").length;
3740
+ SUBCOMMANDS = new Set(
3741
+ "setup status suggest dashboard problems analytics events health report export fix ask scan audit connections agent funnels apps plan upgrade profile team login logout whoami connect init remove help version new add invite link test on off pages sources devices clicks paths stale all install uninstall".split(" ")
3742
+ );
3743
+ VALUED = /^--?(cwd|app|range|out|from|to|format|agent|name|mode|token|url|model-url|sink|variant|ort)$/;
3744
+ plainWord = (w) => w.replace(COLOUR, "");
3745
+ closes = (p) => /[.,;:!?)]$/.test(p) && !/^https?:\/\//.test(p);
3746
+ rule = () => out(` ${c.gray((unicode2 ? "\u2500" : "-").repeat(width() - 4))}`);
3747
+ homeApp = null;
3748
+ inHome = (app) => {
3749
+ homeApp = app === null ? null : clean(app ?? "", 40);
3750
+ };
3751
+ homeOpen = () => homeApp !== null;
3752
+ centre = (text, cols2) => {
3753
+ const pad = Math.max(0, cols2 - visible(text));
3754
+ const left = Math.floor(pad / 2);
3755
+ return `${" ".repeat(left)}${text}${" ".repeat(pad - left)}`;
3756
+ };
3757
+ badge = (text) => useColor ? `${String.fromCharCode(27)}[7m${c.bold(brand(` ${text} `))}${String.fromCharCode(27)}[27m` : c.bold(` ${text} `);
3758
+ BAR = () => brand(unicode2 ? "\u258E" : "|");
3759
+ PROMPT = () => brand(unicode2 ? "\u276F" : ">");
3760
+ MARK3 = {
3761
+ done: () => c.green(sym.ok),
3762
+ next: () => c.cyan(unicode2 ? "\u25CF" : ">"),
3763
+ waiting: () => c.yellow(unicode2 ? "\u25CC" : "~"),
3764
+ todo: () => c.gray(unicode2 ? "\u25CB" : "o"),
3765
+ optional: () => c.gray(unicode2 ? "\u2013" : "-"),
3766
+ blocked: () => c.red(sym.cross)
3767
+ };
3768
+ note = (text) => para(text, " ", c.gray);
3769
+ marked = (mark2, text) => {
3770
+ const [first = "", ...rest] = wrap2(text, width() - 6);
3771
+ out(` ${mark2} ${first}`);
3772
+ for (const l of rest) out(` ${l}`);
3773
+ };
3774
+ good = (text) => marked(c.green(sym.ok), text);
3775
+ warn = (text) => marked(c.yellow(sym.warn), text);
3776
+ bad = (text) => marked(c.red(sym.cross), text);
3777
+ FRAMES = unicode2 ? ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"] : ["-", "\\", "|", "/"];
3778
+ STOP_HINT = "(Enter to stop waiting)";
3779
+ }
3780
+ });
3781
+
3782
+ // ../runtime/bin/lib/login.mjs
3783
+ var login_exports = {};
3784
+ __export(login_exports, {
3785
+ USAGE: () => USAGE2,
3786
+ argsError: () => argsError,
3787
+ offerConnect: () => offerConnect,
3788
+ run: () => run2
3789
+ });
3790
+ import { spawn as spawn4 } from "node:child_process";
3791
+ import { homedir as homedir3 } from "node:os";
3792
+ import { relative as relative4 } from "node:path";
3793
+ function openBrowser(url, o) {
3794
+ if (o.noBrowser || !process.stdout.isTTY) return false;
3795
+ const env2 = process.env;
3796
+ if (env2.SSH_CONNECTION || env2.SSH_TTY) return false;
3797
+ if (process.platform === "linux" && !env2.DISPLAY && !env2.WAYLAND_DISPLAY) return false;
3798
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
3799
+ try {
3800
+ const child = spawn4(cmd, args, { stdio: "ignore", detached: true, shell: false });
3801
+ child.on("error", () => out(` ${c.gray("Could not open a browser: open the link above yourself.")}`));
3802
+ child.unref();
3803
+ return true;
3804
+ } catch {
3805
+ return false;
3806
+ }
3779
3807
  }
3780
- async function fetchConnections(creds, id, opts = {}) {
3781
- const r = await request(`/api/cli/connections?id=${encodeURIComponent(id)}`, base(creds, opts));
3782
- if (!r.ok) return refused(r, creds.host);
3783
- const j = r.json ?? {};
3784
- return {
3785
- ok: true,
3786
- forwarding: j.forwarding === true,
3787
- plan: str(j.plan, 40),
3788
- upgradeUrl: sameOrigin2(j.upgrade_url, creds.host),
3789
- kinds: (Array.isArray(j.kinds) ? j.kinds : []).filter((k) => typeof k === "string" && /^[a-z]{1,20}$/.test(k)),
3790
- privateLink: j.private_link === true,
3791
- list: (Array.isArray(j.integrations) ? j.integrations : []).filter((x) => x && typeof x === "object" && typeof x.kind === "string").slice(0, 20).map((x) => ({ kind: x.kind.slice(0, 20), enabled: x.enabled === true, summary: summaryText(x.summary), lastSent: str(x.last_sent, 40), lastError: str(x.last_error, 200) }))
3792
- };
3808
+ function refuse(st) {
3809
+ if (st.project.refused) {
3810
+ out(` ${c.yellow(sym.warn)} Not a browser app GenClass can be added to (${st.project.refused}).`);
3811
+ out(` Run ${c.cyan(`${CMD} connect`)} inside your web app's folder (or pass --cwd).`);
3812
+ out();
3813
+ return 1;
3814
+ }
3815
+ if (!st.project.framework) {
3816
+ out(` ${c.yellow(sym.warn)} Could not recognise a web app in ${c.bold(st.cwd)}.`);
3817
+ out(` Run ${c.cyan(`${CMD} connect`)} inside your web app's folder (or pass --cwd).`);
3818
+ out();
3819
+ return 1;
3820
+ }
3821
+ return null;
3793
3822
  }
3794
- function summaryText(v) {
3795
- if (typeof v === "string") return v.slice(0, 160);
3796
- if (!v || typeof v !== "object") return "";
3797
- return Object.entries(v).filter(([, x]) => typeof x === "string" || typeof x === "number").slice(0, 4).map(([k, x]) => `${k} ${String(x).slice(0, 80)}`).join(", ");
3823
+ function printManual(token) {
3824
+ out(` GenClass is set up by hand in this project, so connect does not edit your code. Add the key yourself:`);
3825
+ out(` ${c.cyan(`GenClass.init({ token: "${token}" })`)}`);
3826
+ out(` or on the script tag ${c.cyan(`data-token="${token}"`)}, or in <head> ${c.cyan(`<meta name="genclass" content="token=${token}">`)},`);
3827
+ out(` or set ${c.cyan(`window.GENCLASS_CONFIG = { token: "${token}" }`)} before the ${c.cyan(AUTO())} import runs.`);
3828
+ out(` ${c.gray("The key needs @genclass/runtime 0.3.0-beta.0 or later (0.2.x has no token option).")}`);
3829
+ out();
3798
3830
  }
3799
- async function changeConnection(creds, id, kind, how, fields = {}, opts = {}) {
3800
- const q = `?id=${encodeURIComponent(id)}`;
3801
- const path = `/api/cli/connections/${encodeURIComponent(kind)}`;
3802
- const call = { set: [path, "PUT", fields], on: [path, "PATCH", { enabled: true }], off: [path, "PATCH", { enabled: false }], test: [`${path}/test`, "POST", {}], remove: [path, "DELETE", void 0] }[how];
3803
- if (!call) return { ok: false, status: 0, reason: `unknown change ${how}` };
3804
- const r = await request(`${call[0]}${q}`, { ...base(creds, opts), method: call[1], ...call[2] !== void 0 ? { body: call[2] } : {}, timeoutMs: how === "test" ? 3e4 : void 0 });
3805
- if (!r.ok) return refused(r, creds.host);
3806
- return { ok: true, summary: summaryText(r.json?.summary), secret: str(r.json?.secret, 200) };
3831
+ function claimFailed(r, pkgName) {
3832
+ if (r.status === 401) return sessionGone();
3833
+ const fresh = `${CMD} connect --name ${/^[A-Za-z0-9._@/-]+$/.test(pkgName) ? pkgName : JSON.stringify(pkgName)}`;
3834
+ if (r.status === 409) {
3835
+ err(` ${c.red(sym.cross)} That dashboard belongs to another GenClass account, so it was not added to this one.`);
3836
+ err(` Sign in with that account (${c.cyan(`${CMD} logout`)}, then ${c.cyan("login")}), or give this folder a new app in your`);
3837
+ err(` account with ${c.cyan(fresh)} (its key replaces the one in your setup).`);
3838
+ return;
3839
+ }
3840
+ if (r.status === 404 || r.status === 400) {
3841
+ err(` ${c.red(sym.cross)} ${apiHost()} does not know the dashboard link in ${LOCAL_FILE} (it may have been deleted).`);
3842
+ err(` Give this folder a new app in your account with ${c.cyan(fresh)}`);
3843
+ err(` (its key replaces the one in your setup).`);
3844
+ return;
3845
+ }
3846
+ err(` ${c.red(sym.cross)} Could not add it (${r.reason}).`);
3847
+ err(` Try again, or open ${c.cyan(hostUrl("/account"))} and paste the link from ${LOCAL_FILE} under "Add an existing dashboard".`);
3807
3848
  }
3808
- async function fetchEvents(creds, id, q = {}, opts = {}) {
3809
- const p = new URLSearchParams({ id, format: q.format === "csv" ? "csv" : "jsonl" });
3810
- if (q.from) p.set("from", q.from);
3811
- if (q.to) p.set("to", q.to);
3812
- if (q.cursor) p.set("cursor", q.cursor);
3813
- const fetchFn = opts.fetchFn ?? globalThis.fetch;
3814
- try {
3815
- const res = await fetchFn(`${creds.host}/api/cli/events?${p}`, { headers: { authorization: `Bearer ${creds.access_token}`, accept: "*/*" }, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? 6e4) });
3816
- if (!res.ok) {
3817
- let json = null;
3818
- try {
3819
- json = await res.json();
3820
- } catch {
3849
+ async function connectApp(o, creds, st, me) {
3850
+ me ??= await fetchMe(creds);
3851
+ if (!me.ok) {
3852
+ if (me.status === 401) sessionGone();
3853
+ else err(` ${c.red(sym.cross)} Could not read your apps at ${apiHost()} (${me.reason}).`);
3854
+ out();
3855
+ return 1;
3856
+ }
3857
+ const apps2 = me.projects;
3858
+ const pkgName = String(st.project.pkg?.name || st.project.name || "app").slice(0, 80);
3859
+ const inFiles = tokenInFiles(st.marked);
3860
+ const current = st.token ? apps2.find((a) => a.token === st.token) : null;
3861
+ if (current && !o.app && !o.name) {
3862
+ row("App", `${c.bold(current.name)} ${c.gray(`(already in your account; project key ${current.token})`)}`);
3863
+ if (st.handWritten) {
3864
+ out();
3865
+ printManual(current.token);
3866
+ return 0;
3867
+ }
3868
+ if (inFiles === current.token) {
3869
+ if (current.dashboard_url) row("Dashboard", c.cyan(current.dashboard_url));
3870
+ out();
3871
+ out(` ${c.green("Nothing to do.")}`);
3872
+ out();
3873
+ return 0;
3874
+ }
3875
+ out();
3876
+ return init({ ...o, token: current.token }, { banner: false, cmd: "connect", creds, app: current });
3877
+ }
3878
+ let claimable = st.token && !current && st.local?.token === st.token && st.local.dashboardUrl && !o.app && !o.name;
3879
+ if (claimable && !onHost(st.local.dashboardUrl, creds.host)) {
3880
+ out(` ${c.yellow(sym.warn)} The private dashboard link in ${LOCAL_FILE} belongs to ${new URL(st.local.dashboardUrl).origin}, not ${creds.host},`);
3881
+ out(` so it is not sent there and this app is not added to that account from it.`);
3882
+ out();
3883
+ claimable = false;
3884
+ }
3885
+ if (claimable) {
3886
+ out(` This app already has a dashboard made without an account (key ${st.token}; its private link is in ${LOCAL_FILE}).`);
3887
+ const ok = o.dryRun ? null : o.yes ? true : await confirm("Add that dashboard to your account? It keeps its key and its data.");
3888
+ if (o.dryRun) {
3889
+ out(` ${c.gray("Dry run: it would be added to your account. Only your app list was read; nothing was added or written.")}`);
3890
+ out();
3891
+ return 0;
3892
+ }
3893
+ if (ok === null) {
3894
+ out(` Not a terminal, so nothing was sent. Re-run with ${c.bold("--yes")} to add it.`);
3895
+ out();
3896
+ return 1;
3897
+ }
3898
+ if (ok) {
3899
+ const r = await claimProject(creds, st.local.dashboardUrl);
3900
+ if (!r.ok) {
3901
+ claimFailed(r, pkgName);
3902
+ out();
3903
+ return 1;
3821
3904
  }
3822
- return refused({ status: res.status, json }, creds.host);
3905
+ const app2 = r.project ?? { name: pkgName, token: st.token, dashboard_url: null };
3906
+ row("App", `${c.bold(app2.name)} ${c.gray(`(added to your account; project key ${st.token})`)}`);
3907
+ if (st.handWritten) {
3908
+ out();
3909
+ printManual(st.token);
3910
+ return 0;
3911
+ }
3912
+ if (inFiles === st.token) {
3913
+ if (app2.dashboard_url) row("Dashboard", c.cyan(app2.dashboard_url));
3914
+ out(` ${c.gray("The key in your setup stays the same, so no file changes.")}`);
3915
+ out();
3916
+ return 0;
3917
+ }
3918
+ out();
3919
+ return init({ ...o, token: st.token }, { banner: false, cmd: "connect", creds, app: { ...app2, token: st.token } });
3823
3920
  }
3824
- return { ok: true, text: await res.text(), next: res.headers.get("x-genclass-next-cursor") || null };
3825
- } catch (e) {
3826
- return { ok: false, status: 0, reason: e?.name === "TimeoutError" ? "no answer within 60 s" : `network error (${e?.cause?.code ?? e?.message ?? e})` };
3921
+ out();
3827
3922
  }
3828
- }
3829
- async function saveFunnels(creds, id, funnels2, opts = {}) {
3830
- const r = await request(`/api/cli/funnels?id=${encodeURIComponent(id)}`, { ...base(creds, opts), method: "PUT", body: { funnels: funnels2 } });
3831
- if (!r.ok) return refused(r, creds.host);
3832
- return { ok: true, funnels: (Array.isArray(r.json?.funnels) ? r.json.funnels : []).map((f) => ({ name: str(f?.name, 60) ?? "Funnel", steps: (Array.isArray(f?.steps) ? f.steps : []).filter((x) => typeof x === "string") })) };
3833
- }
3834
- async function makeAgentLink(creds, id, opts = {}) {
3835
- const r = await request(`/api/cli/link?id=${encodeURIComponent(id)}`, { ...base(creds, opts), method: "POST", body: {} });
3836
- if (!r.ok) return refused(r, creds.host);
3837
- const url = sameOrigin2(r.json?.dashboardUrl, creds.host);
3838
- return url && /\/dashboard\/[A-Za-z0-9]{32}$/.test(url) ? { ok: true, url } : { ok: false, status: r.status, reason: "the server sent no link" };
3839
- }
3840
- async function askModel(creds, q, opts = {}) {
3841
- const r = await request("/api/cli/ask", { ...base(creds, opts), method: "POST", body: { id: q.id, range: q.range ?? "7d", question: q.question, history: (q.history ?? []).slice(-3) }, timeoutMs: opts.timeoutMs ?? 6e4 });
3842
- if (!r.ok) return refused(r, creds.host);
3843
- const j = r.json ?? {};
3844
- return {
3845
- ok: true,
3846
- answer: typeof j.answer === "string" && j.answer.trim() ? j.answer.slice(0, 3e3) : null,
3847
- why: ["no-model", "limit", "failed"].includes(j.why) ? j.why : null,
3848
- range: str(j.range, 8),
3849
- remainingToday: numOrNull(j.remaining_today),
3850
- perDay: numOrNull(j.per_day),
3851
- upgradeUrl: sameOrigin2(j.upgrade_url, creds.host)
3852
- };
3853
- }
3854
- var str, sameOrigin2, count, pairs, base, refused, numOrNull, person;
3855
- var init_api = __esm({
3856
- "src/api.mjs"() {
3857
- init_define_GENCLASS_BUILD();
3858
- init_account();
3859
- str = (v, max = 200) => typeof v === "string" ? v.slice(0, max) : null;
3860
- sameOrigin2 = (u, host) => {
3861
- try {
3862
- return typeof u === "string" && new URL(u).origin === host ? u : null;
3863
- } catch {
3864
- return null;
3923
+ if (st.token && !current && st.local?.token !== st.token && o.yes && !o.app && !o.name && !o.dryRun) {
3924
+ err(` ${c.red(sym.cross)} This app's project key ${st.token} is not one of your account's apps (it may be a teammate's).`);
3925
+ out(` Say which app it is: ${c.cyan(`${CMD} connect`)} on a terminal and pick, or ${c.cyan(`${CMD} connect --app <id or name>`)}`);
3926
+ out(` for one of yours, or ${c.cyan(`${CMD} connect --name <name>`)} for a new one. Nothing was changed.`);
3927
+ out();
3928
+ return 1;
3929
+ }
3930
+ const createName = String(o.name || pkgName).slice(0, 80);
3931
+ let pick2;
3932
+ if (o.app) {
3933
+ pick2 = apps2.findIndex((a) => a.id === o.app || a.name === o.app);
3934
+ if (pick2 < 0) {
3935
+ err(` ${c.red(sym.cross)} No app "${o.app}" in your account.${apps2.length ? ` Your apps: ${apps2.map((a) => `${a.name} (${a.id})`).join(", ")}.` : " It has no apps yet."}`);
3936
+ out();
3937
+ return 1;
3938
+ }
3939
+ } else if (o.name) pick2 = apps2.length;
3940
+ else {
3941
+ const same = apps2.findIndex((a) => a.name === pkgName);
3942
+ const def = same >= 0 ? same : apps2.length;
3943
+ pick2 = def;
3944
+ if (apps2.length && !o.yes && interactive()) {
3945
+ const labels = [...apps2.map((a) => `${a.name} ${c.gray(`${a.token} ${a.last_event ? `last event ${when(a.last_event)}` : "no events yet"}`)}`), `Create a new app named ${c.bold(createName)}`];
3946
+ const got = await choose(`Which app of your account is this (${pkgName})?`, labels, def);
3947
+ if (got !== null) pick2 = got;
3948
+ out();
3949
+ }
3950
+ }
3951
+ const app = pick2 < apps2.length ? apps2[pick2] : null;
3952
+ if (st.token && st.token !== app?.token) {
3953
+ out(` ${c.yellow(sym.warn)} This replaces the project key ${st.token} in your setup.`);
3954
+ if (st.local?.dashboardUrl && st.local.token === st.token)
3955
+ out(` Its private link stays in ${LOCAL_FILE}; to keep that history, paste it under "Add an existing dashboard" at ${hostUrl("/account")}.`);
3956
+ out();
3957
+ }
3958
+ row("App", app ? `${c.bold(app.name)} ${c.gray(`(in your account; project key ${app.token})`)}` : `${c.bold(createName)} ${c.gray(`(a new app in ${HOST_CLI?.into ? HOST_CLI.into : "your account"}, created once you apply the changes)`)}`);
3959
+ if (st.handWritten) {
3960
+ out();
3961
+ let token = app?.token;
3962
+ if (!token) {
3963
+ if (o.dryRun) {
3964
+ out(` ${c.gray("Dry run: the app would be created. Only your app list was read; nothing was created.")}`);
3965
+ out();
3966
+ return 0;
3967
+ }
3968
+ const ok = o.yes ? true : await confirm(`Create the app "${createName}" in your account?`);
3969
+ if (ok === null) {
3970
+ out(` Not a terminal, so nothing was sent. Re-run with ${c.bold("--yes")}.`);
3971
+ out();
3972
+ return 1;
3973
+ }
3974
+ if (!ok) {
3975
+ out(` Nothing changed.`);
3976
+ out();
3977
+ return 0;
3978
+ }
3979
+ const r = await createAccountProject(creds, createName);
3980
+ if (!r.ok) {
3981
+ err(` ${c.red(sym.cross)} Could not create the app (${r.reason}).`);
3982
+ out();
3983
+ return 1;
3865
3984
  }
3866
- };
3867
- count = (v) => Number.isFinite(Number(v)) ? Math.max(0, Math.round(Number(v))) : 0;
3868
- pairs = (list2, max) => (Array.isArray(list2) ? list2 : []).filter((x) => x && typeof x === "object" && typeof x.key === "string").slice(0, max).map((x) => ({ key: x.key.slice(0, 300), count: count(x.count) }));
3869
- base = (creds, opts) => ({ token: creds.access_token, host: creds.host, fetchFn: opts.fetchFn });
3870
- refused = (r, host, what) => ({
3871
- ok: false,
3872
- status: r.status,
3873
- reason: typeof r.json?.error === "string" && r.status !== 401 ? r.json.error.slice(0, 300) : failure(r, what),
3874
- // an app the caller names comes from the account's own list, so a bare 404 is a server without the route; a
3875
- // 404 with its own sentence ("slack is not set up for this app") is an answer, and is shown
3876
- ...r.status === 404 && (typeof r.json?.error !== "string" || r.json.error === "not found") ? { missing: true } : {},
3877
- ...r.json?.reauth === true ? { reauth: true } : {},
3878
- ...sameOrigin2(r.json?.upgrade_url, host) ? { upgradeUrl: sameOrigin2(r.json.upgrade_url, host) } : {},
3879
- // a part of the paid plan: which plan, its trial and price (the Pro box)
3880
- ...r.json?.locked === true ? { lock: lockOf(r.json, host) } : {}
3881
- });
3882
- numOrNull = (v) => Number.isFinite(Number(v)) && v !== null ? Number(v) : null;
3883
- person = (x) => ({ label: str(x?.email, 120) ?? (str(x?.github_login, 60) ? `@${str(x.github_login, 60)}` : "a GenClass account"), joined: str(x?.joined, 40), active: x?.active !== false });
3884
- }
3885
- });
3886
-
3887
- // src/git.mjs
3888
- import { spawnSync as spawnSync3 } from "node:child_process";
3889
- function runGit(args, cwd) {
3890
- try {
3891
- const r = spawnSync3("git", args, { cwd, encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
3892
- return r.status === 0 && typeof r.stdout === "string" ? r.stdout.trim() : null;
3893
- } catch {
3894
- return null;
3985
+ token = r.token;
3986
+ row("App", `${c.bold(r.name)} ${c.gray(`created; project key ${token}`)}`);
3987
+ if (r.dashboardUrl) row("Dashboard", c.cyan(r.dashboardUrl));
3988
+ out();
3989
+ }
3990
+ printManual(token);
3991
+ return 0;
3895
3992
  }
3993
+ out();
3994
+ return app ? init({ ...o, token: app.token }, { banner: false, cmd: "connect", creds, app }) : init(o, { banner: false, cmd: "connect", creds, create: createName });
3896
3995
  }
3897
- function githubName(remote) {
3898
- const m = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(String(remote ?? "").trim());
3899
- return m && FULL_NAME.test(m[1]) ? m[1] : null;
3900
- }
3901
- function gitInfo(cwd, run5 = runGit) {
3902
- const root = run5(["rev-parse", "--show-toplevel"], cwd);
3903
- if (!root) return { repo: false, root: null, remote: null, github: null, branch: null };
3904
- const remote = run5(["remote", "get-url", "origin"], cwd);
3905
- const branch = run5(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
3906
- return { repo: true, root, remote, github: githubName(remote), branch: branch && branch !== "HEAD" ? branch : null };
3907
- }
3908
- async function renamedRepo(repo, opts = {}) {
3909
- const f = opts.fetchFn ?? globalThis.fetch;
3910
- if (typeof f !== "function" || !/^[A-Za-z0-9_.-]{1,39}\/[A-Za-z0-9_.-]{1,100}$/.test(repo)) return null;
3911
- try {
3912
- const r = await f(`https://github.com/${repo}`, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(4e3), headers: { "user-agent": "genclass-cli" } });
3913
- if (r.status !== 301) return null;
3914
- const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]{1,39}\/[A-Za-z0-9_.-]{1,100})\/?$/.exec(r.headers.get("location") ?? "");
3915
- return m && m[1].toLowerCase() !== repo.toLowerCase() ? m[1] : null;
3916
- } catch {
3917
- return null;
3996
+ async function connect(o) {
3997
+ banner("connect");
3998
+ hostNotice();
3999
+ await versionNotice(o);
4000
+ const { creds, otherHost } = readCredentialsFor();
4001
+ if (!creds) {
4002
+ out(` Not signed in${otherHost ? ` at ${apiHost()} (the saved session is for ${otherHost})` : ""}. Sign in first: ${c.cyan(`${CMD} login`)} (it offers to connect this app too).`);
4003
+ out();
4004
+ return 1;
3918
4005
  }
4006
+ row("Account", accountLabel(creds.account));
4007
+ const st = inspectProject(o);
4008
+ const no = refuse(st);
4009
+ if (no !== null) return no;
4010
+ return connectApp(o, creds, st, null);
3919
4011
  }
3920
- var FULL_NAME;
3921
- var init_git = __esm({
3922
- "src/git.mjs"() {
3923
- init_define_GENCLASS_BUILD();
3924
- FULL_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/;
4012
+ async function afterLogin(o, creds, me) {
4013
+ if (o.noConnect) return 0;
4014
+ const st = inspectProject(o);
4015
+ if (st.project.refused || !st.project.framework) {
4016
+ out(` Next: run ${c.cyan(`${CMD} connect`)} in your web app's folder to connect it to your account.`);
4017
+ out(` ${c.gray("Your apps' dashboards:")} ${c.cyan(hostUrl("/account"))}`);
4018
+ out();
4019
+ return 0;
3925
4020
  }
3926
- });
3927
-
3928
- // src/store.mjs
3929
- import { createHash as createHash2 } from "node:crypto";
3930
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
3931
- import { dirname as dirname7, join as join8, resolve as resolve4 } from "node:path";
3932
- function readNotes(dir) {
3933
- try {
3934
- const j = JSON.parse(readFileSync9(fileFor(dir), "utf8"));
3935
- return j && typeof j === "object" && !Array.isArray(j) ? j : {};
3936
- } catch {
3937
- return {};
4021
+ const where = relative4(process.cwd(), st.cwd) || ".";
4022
+ const name = st.project.pkg?.name || st.project.name;
4023
+ const ok = o.yes ? true : await confirm(`Connect ${name} (${where}, ${st.project.label}) to your account?`);
4024
+ if (ok === null) {
4025
+ out(` Not a terminal: run ${c.cyan(`${CMD} connect --yes`)} here to connect this app.`);
4026
+ out();
4027
+ return 0;
4028
+ }
4029
+ if (!ok) {
4030
+ out(` Not connected. Later: ${c.cyan(`${CMD} connect`)}`);
4031
+ out();
4032
+ return 0;
3938
4033
  }
4034
+ out();
4035
+ return connectApp(o, creds, st, me);
3939
4036
  }
3940
- function saveNotes(dir, patch) {
4037
+ async function offerConnect(argv) {
4038
+ let o;
3941
4039
  try {
3942
- const file = fileFor(dir);
3943
- mkdirSync4(dirname7(file), { recursive: true, mode: 448 });
3944
- writeFileSync5(file, `${JSON.stringify({ ...readNotes(dir), ...patch, dir: resolve4(dir) }, null, 2)}
3945
- `, { mode: 384 });
3946
- return true;
3947
- } catch {
3948
- return false;
4040
+ o = parse(argv.filter((a) => a !== "--no-connect"), SPECS.login);
4041
+ } catch (e) {
4042
+ if (e instanceof UsageError) return 2;
4043
+ throw e;
3949
4044
  }
4045
+ const { creds } = readCredentialsFor();
4046
+ if (!creds) return 1;
4047
+ return afterLogin(o, creds, null);
3950
4048
  }
3951
- var fileFor;
3952
- var init_store = __esm({
3953
- "src/store.mjs"() {
3954
- init_define_GENCLASS_BUILD();
3955
- init_account();
3956
- fileFor = (dir) => join8(dirname7(credentialsPath()), "projects", `${createHash2("sha256").update(resolve4(dir)).digest("hex").slice(0, 24)}.json`);
4049
+ function argsError(cmd, argv) {
4050
+ try {
4051
+ const o = parse(argv, SPECS[cmd]);
4052
+ return o.app !== void 0 && o.name !== void 0 ? "--app and --name contradict each other (use an app, or create one)" : null;
4053
+ } catch (e) {
4054
+ if (e instanceof UsageError) return e.message;
4055
+ throw e;
3957
4056
  }
3958
- });
3959
-
3960
- // src/art.mjs
3961
- function markRows() {
3962
- const lines = [];
3963
- for (let y = 0; y < MARK2.length; y += 2) {
3964
- let line = "";
3965
- for (let x = 0; x < MARK2[y].length; x++) {
3966
- const top2 = MARK2[y][x];
3967
- const bottom = MARK2[y + 1][x];
3968
- const t = top2 !== ".";
3969
- const b = bottom !== ".";
3970
- if (!t && !b) line += " ";
3971
- else if (!useColor) line += t && b ? "\u2588" : t ? "\u2580" : "\u2584";
3972
- else if (t && b) line += top2 === bottom ? `${fg(top2)}\u2588${ESC}[39m` : `${fg(top2)}${bg(bottom)}\u2580${ESC}[39m${ESC}[49m`;
3973
- else line += `${fg(t ? top2 : bottom)}${t ? "\u2580" : "\u2584"}${ESC}[39m`;
4057
+ }
4058
+ async function login(o) {
4059
+ banner("login");
4060
+ hostNotice();
4061
+ await versionNotice(o);
4062
+ const host = apiHost();
4063
+ const saved = readCredentialsFor(host);
4064
+ if (saved.creds) {
4065
+ const me = await fetchMe(saved.creds);
4066
+ if (me.ok) {
4067
+ row("Account", `${accountLabel(me.account)} ${c.gray(`(already signed in; ${CMD} logout to switch accounts)`)}`);
4068
+ out();
4069
+ return afterLogin(o, { ...saved.creds, account: me.account }, me);
3974
4070
  }
3975
- lines.push(line);
4071
+ if (me.status !== 401) {
4072
+ err(` ${c.red(sym.cross)} Could not reach ${host} (${me.reason}).`);
4073
+ out();
4074
+ return 1;
4075
+ }
4076
+ out(` ${c.yellow(sym.warn)} The saved session no longer works (signed out, revoked or expired): signing in again.`);
4077
+ out();
3976
4078
  }
3977
- return lines;
3978
- }
3979
- function canDraw(columns = process.stdout.columns, env2 = process.env, platform = process.platform) {
3980
- const unicode3 = platform !== "win32" || !!env2.WT_SESSION || !!env2.TERM_PROGRAM;
3981
- return !!process.stdout.isTTY && unicode3 && env2.TERM !== "dumb" && Number(columns) >= 44;
3982
- }
3983
- var MARK2, COLOURS, truecolor, ESC, fg, bg, brand;
3984
- var init_art = __esm({
3985
- "src/art.mjs"() {
3986
- init_define_GENCLASS_BUILD();
3987
- init_ui();
3988
- MARK2 = [
3989
- ".........G......",
3990
- ".....GGggGG.....",
3991
- "...gGGGGggGG....",
3992
- "..gGGGGGggGG....",
3993
- ".gGGGG..gg......",
3994
- "gGGg............",
3995
- "gGgg............",
3996
- "Ggg......rrRRR..",
3997
- "Ggg......rRRRRR.",
3998
- "Gggg......rrrRR.",
3999
- "Gggg.......rrRR.",
4000
- ".gggG.rR..rrrr..",
4001
- "..gG.RRrrrrrrr..",
4002
- "....RRRRRRrrr...",
4003
- ".....RRRRrr.....",
4004
- ".......R........"
4005
- ];
4006
- COLOURS = {
4007
- G: { rgb: [0, 200, 91], ansi: 92 },
4008
- g: { rgb: [0, 152, 97], ansi: 32 },
4009
- R: { rgb: [252, 31, 4], ansi: 91 },
4010
- r: { rgb: [215, 1, 14], ansi: 31 }
4011
- };
4012
- truecolor = () => useColor && /truecolor|24bit/i.test(process.env.COLORTERM ?? "");
4013
- ESC = String.fromCharCode(27);
4014
- fg = (k) => truecolor() ? `${ESC}[38;2;${COLOURS[k].rgb.join(";")}m` : `${ESC}[${COLOURS[k].ansi}m`;
4015
- bg = (k) => truecolor() ? `${ESC}[48;2;${COLOURS[k].rgb.join(";")}m` : `${ESC}[${COLOURS[k].ansi + 10}m`;
4016
- brand = (text) => truecolor() ? `${fg("G")}${text}${ESC}[39m` : c.green(text);
4079
+ const dev = await startDeviceLogin({ host });
4080
+ if (!dev.ok) {
4081
+ err(` ${c.red(sym.cross)} Could not start signing in at ${host} (${dev.reason}).`);
4082
+ out();
4083
+ return 1;
4017
4084
  }
4018
- });
4019
-
4020
- // src/tui.mjs
4021
- import { homedir as homedir2 } from "node:os";
4022
- function clean(text, max = 400) {
4023
- const s = String(text ?? "").replace(ANSI, "").replace(CONTROL, " ").replace(/\s+/g, " ").trim();
4024
- return s.length > max ? `${s.slice(0, max - 1)}\u2026` : s;
4025
- }
4026
- function wrap2(text, cols2 = width() - 4) {
4027
- const lines = [];
4028
- for (const para2 of String(text).split("\n")) {
4029
- let line = "";
4030
- for (const word of para2.split(/\s+/).filter(Boolean)) {
4031
- if (line && visible(line) + 1 + visible(word) > cols2) {
4032
- lines.push(line);
4033
- line = word;
4034
- } else line = line ? `${line} ${word}` : word;
4085
+ out(` Open this link, sign in (Google, email and password, GitHub or a passkey) and approve the code:`);
4086
+ out(` ${c.bold(c.cyan(dev.verification_uri_complete))}`);
4087
+ out();
4088
+ row("Code", `${c.bold(dev.user_code)} ${c.gray("(check that the page shows the same code)")}`);
4089
+ out();
4090
+ if (openBrowser(dev.verification_uri_complete, o)) out(` ${c.gray("Opening it in your browser.")}`);
4091
+ else out(` ${c.gray("Open the link in a browser on any device.")}`);
4092
+ const minutes = Math.max(1, Math.round(dev.expires_in / 60));
4093
+ out(` Waiting for approval ${c.gray(`(the code expires in ${minutes} minute${minutes === 1 ? "" : "s"}; Ctrl-C to cancel)`)}`);
4094
+ const ctl = new AbortController();
4095
+ const onSigint = () => ctl.abort();
4096
+ process.on("SIGINT", onSigint);
4097
+ let r;
4098
+ try {
4099
+ r = await pollDeviceLogin(dev, { host, signal: ctl.signal, onSlowDown: (s) => out(` ${c.gray(`The server asked for slower polling: every ${s} s now.`)}`) });
4100
+ } finally {
4101
+ process.removeListener("SIGINT", onSigint);
4102
+ }
4103
+ if (!r.ok) {
4104
+ out();
4105
+ if (r.error === "cancelled") {
4106
+ err(` Cancelled: not signed in, nothing was saved.`);
4107
+ out();
4108
+ return 130;
4035
4109
  }
4036
- lines.push(line);
4110
+ if (r.error === "access_denied") err(` ${c.red(sym.cross)} The sign-in was denied in the browser. Nothing was saved.`);
4111
+ else if (r.error === "expired_token") err(` ${c.red(sym.cross)} The code expired before it was approved. Run ${c.cyan(`${CMD} login`)} again.`);
4112
+ else err(` ${c.red(sym.cross)} Could not sign in (${r.reason}). Nothing was saved.`);
4113
+ out();
4114
+ return 1;
4037
4115
  }
4038
- return lines;
4039
- }
4040
- function para(text, indent = " ", paint = (s) => s) {
4041
- for (const l of wrap2(text, width() - 2 - indent.length)) out(`${indent}${paint(l)}`);
4042
- }
4043
- function header(h = {}) {
4044
- if (homeApp !== null) {
4116
+ const creds = { host, access_token: r.access_token, account: r.account ?? { id: "", email: null, github_login: null }, created: (/* @__PURE__ */ new Date()).toISOString() };
4117
+ let path;
4118
+ try {
4119
+ path = saveCredentials(creds);
4120
+ } catch (e) {
4121
+ err(` ${c.red(sym.cross)} Could not save the session (${e?.message ?? e}), so it was ended again.`);
4122
+ await revokeSession(creds);
4045
4123
  out();
4046
- if (h.app && clean(h.app, 40) !== homeApp) out(` ${c.bold(clean(h.app, 40))}`);
4047
- return;
4124
+ return 1;
4048
4125
  }
4049
- const left = `${c.bold(c.magenta("GenClass"))}${h.app ? ` ${c.gray(sym.dot)} ${c.bold(clean(h.app, 40))}` : ""}`;
4050
- const right = h.framework ? c.gray(clean(h.framework, 40)) : "";
4051
- const gap = Math.max(2, width() - 4 - visible(left) - visible(right));
4052
4126
  out();
4053
- out(` ${left}${" ".repeat(gap)}${right}`);
4054
- const who = [h.account ? clean(h.account, 50) : "not signed in", h.plan ? `${clean(h.plan, 20)} plan` : null].filter(Boolean).join(` ${sym.dot} `);
4055
- out(` ${c.gray(who)}`);
4056
- if (h.host) out(` ${c.yellow(sym.warn)} ${c.gray(`talking to ${clean(h.host, 60)} (GENCLASS_HOST is set: for tests only)`)}`);
4057
- rule();
4058
- }
4059
- function folderName(dir, max = 48, home2 = homedir2()) {
4060
- const d = String(dir ?? "");
4061
- const short2 = home2 && (d === home2 || d.startsWith(`${home2}/`)) ? `~${d.slice(home2.length)}` : d;
4062
- return short2.length > max ? `\u2026${short2.slice(short2.length - max + 1)}` : short2;
4063
- }
4064
- function firstName(label) {
4065
- const l = clean(label ?? "", 80);
4066
- const raw = /^GitHub (\S+)$/.exec(l)?.[1] ?? (l.includes("@") ? l.split("@")[0].split(/[._+-]/)[0] : "");
4067
- const name = raw.replace(/[^\p{L}\p{N}]/gu, "").slice(0, 24);
4068
- return name ? name[0].toUpperCase() + name.slice(1) : null;
4069
- }
4070
- function card(h = {}) {
4071
- const inner = width() - 6;
4072
- const B = unicode2 ? { tl: "\u256D", tr: "\u256E", bl: "\u2570", br: "\u256F", h: "\u2500", v: "\u2502" } : { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" };
4073
- const title = ` ${c.bold("Gen")}${c.bold(brand("Class"))} `;
4074
- const version2 = h.version ? ` ${c.gray(`v${clean(h.version, 20)}`)} ` : "";
4075
- const row3 = (text = "") => out(` ${brand(B.v)}${centre(text, inner)}${brand(B.v)}`);
4076
- const fit2 = (text) => clean(text, inner - 4);
4077
- const name = h.account ? firstName(h.account) : null;
4127
+ row("Signed in", `${c.bold(accountLabel(creds.account))}${creds.account.github_login && creds.account.email ? c.gray(` (GitHub ${creds.account.github_login})`) : ""}`);
4128
+ out(` ${c.gray(`Session saved in ${tilde(path)} (only you can read it).`)}`);
4129
+ out(` ${c.gray(`Sign out: ${CMD} logout`)}`);
4078
4130
  out();
4079
- out(` ${brand(B.tl + B.h)}${title}${brand(B.h.repeat(Math.max(0, inner - 2 - visible(title) - visible(version2))))}${version2}${brand(B.h + B.tr)}`);
4080
- row3();
4081
- row3(c.bold(h.account ? `Welcome back${name ? `, ${name}` : ""}!` : "Welcome to GenClass"));
4082
- if (!h.account) {
4083
- row3();
4084
- const halves = ["Finds what breaks in your web app,", "and tells you what it needs next."];
4085
- for (const l of halves.join(" ").length <= inner - 6 ? [halves.join(" ")] : halves) row3(c.gray(l));
4086
- }
4087
- row3();
4088
- if (unicode2) {
4089
- for (const m of markRows()) row3(m);
4090
- row3();
4131
+ return afterLogin(o, creds, null);
4132
+ }
4133
+ async function whoami() {
4134
+ banner("whoami");
4135
+ hostNotice();
4136
+ const { creds, otherHost, path } = readCredentialsFor();
4137
+ if (!creds) {
4138
+ out(` Not signed in${otherHost ? ` at ${apiHost()} (the saved session is for ${otherHost})` : ""}. Sign in: ${c.cyan(`${CMD} login`)}`);
4139
+ out();
4140
+ return 1;
4091
4141
  }
4092
- const app = [h.app ? clean(h.app, 40) : null, h.framework ? clean(h.framework, 40) : null].filter(Boolean).join(` ${sym.dot} `);
4093
- if (app) row3(c.gray(fit2(app)));
4094
- row3(c.gray(fit2([h.account ? clean(h.account, 50) : "not signed in", h.plan ? `${clean(h.plan, 20)} plan` : null].filter(Boolean).join(` ${sym.dot} `))));
4095
- if (h.cwd) row3(c.gray(folderName(h.cwd, inner - 4)));
4096
- row3();
4097
- out(` ${brand(B.bl + B.h.repeat(inner) + B.br)}`);
4098
- if (h.host) {
4142
+ const me = await fetchMe(creds);
4143
+ if (!me.ok) {
4144
+ if (me.status === 401) sessionGone();
4145
+ else err(` ${c.red(sym.cross)} Could not reach ${apiHost()} (${me.reason}).`);
4099
4146
  out();
4100
- out(` ${c.yellow(sym.warn)} ${c.gray(`talking to ${clean(h.host, 60)} (GENCLASS_HOST is set: for tests only)`)}`);
4147
+ return 1;
4101
4148
  }
4149
+ const a = me.account;
4150
+ row("Account", `${c.bold(accountLabel(a))}${a.github_login && a.email ? c.gray(` (GitHub ${a.github_login})`) : ""}${a.id ? c.gray(` id ${a.id}`) : ""}`);
4151
+ row("Session", c.gray(`${tilde(path)}${when(creds.created) ? `, signed in ${when(creds.created)}` : ""}`));
4102
4152
  out();
4103
- }
4104
- function proBox(what, lock = {}) {
4105
- const plan2 = clean(lock.plan ?? "Pro", 20);
4153
+ out(` ${c.bold("Apps")} ${c.gray(`(${me.projects.length})`)}`);
4154
+ if (!me.projects.length) out(` None yet. In your app's folder: ${c.cyan(SETUP_CMD)}`);
4155
+ const w = Math.min(28, Math.max(4, ...me.projects.map((p) => p.name.length)));
4156
+ for (const p of me.projects) {
4157
+ out(` ${c.bold(p.name.padEnd(w))} ${p.token} ${c.gray((p.last_event ? `last event ${when(p.last_event)}` : "no events yet").padEnd(31))} ${p.dashboard_url ? c.cyan(p.dashboard_url) : ""}`.trimEnd());
4158
+ }
4159
+ if (me.projects.length && HOST_CLI) out(` ${c.gray(`Open a dashboard from its link above. In the terminal, with Pro: ${CMD} dashboard`)}`);
4160
+ else if (me.projects.length) out(` ${c.gray(`Open a dashboard from its link above, or run ${CMD} dashboard in the app's folder. One app's totals are free; the rest comes with Pro.`)}`);
4106
4161
  out();
4107
- out(` ${badge(plan2.toUpperCase())}`);
4108
- for (const l of wrap2(clean(what, 300), width() - 6)) out(` ${c.bold(l)}`);
4109
- const terms = lock.trialDays ? `${lock.trialDays} days free, then ${clean(lock.price ?? "the monthly price", 40)}. Cancel any time.` : lock.price ? `${clean(lock.price, 40)}.` : "";
4110
- for (const l of wrap2(`${terms ? `${terms} ` : ""}Start: npx genclass upgrade`, width() - 6)) out(` ${l}`);
4111
- if (lock.upgradeUrl) out(` ${c.cyan(clean(lock.upgradeUrl, 200))}`);
4162
+ return 0;
4112
4163
  }
4113
- function planCard(offer, app) {
4114
- const inner = width() - 6;
4115
- const B = unicode2 ? { tl: "\u256D", tr: "\u256E", bl: "\u2570", br: "\u256F", h: "\u2500", v: "\u2502" } : { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" };
4116
- const title = ` ${c.bold(app ? `A plan for ${clean(app, 30)}` : "A plan for this project")} `;
4117
- const row3 = (text = "") => out(` ${brand(B.v)} ${text}${" ".repeat(Math.max(0, inner - 3 - visible(text)))}${brand(B.v)}`);
4118
- const room3 = inner - 6;
4164
+ function showDashboard(o, link, notes = []) {
4165
+ out(` ${c.bold("Your dashboard")} ${c.bold(c.cyan(link))}`);
4166
+ for (const n2 of notes) out(` ${n2}`);
4167
+ for (const l of FREE_LINES) out(` ${c.gray(l)}`);
4168
+ if (o.open && openBrowser(link, o)) out(` ${c.gray("Opening it in your browser.")}`);
4119
4169
  out();
4120
- out(` ${brand(B.tl + B.h)}${title}${brand(B.h.repeat(Math.max(0, inner - 1 - visible(title))))}${brand(B.tr)}`);
4121
- row3();
4122
- const name = badge(clean(offer.plan.name, 20).toUpperCase().split("").join(" "));
4123
- const price = c.bold(clean(offer.price, 40));
4124
- if (visible(name) + 2 + visible(price) <= room3) row3(`${name}${" ".repeat(room3 - visible(name) - visible(price))}${price}`);
4125
- else {
4126
- row3(name);
4127
- row3(price);
4128
- }
4129
- if (offer.summary) for (const l of wrap2(clean(offer.summary, 200), room3)) row3(c.gray(l));
4130
- if (offer.trialDays) for (const l of wrap2(`${offer.trialDays} days free, then ${clean(offer.price, 40)}. Cancel any time.`, room3)) row3(c.green(l));
4131
- row3();
4132
- for (const f of offer.features) {
4133
- const [first = "", ...rest] = wrap2(clean(f, 120), room3 - 2);
4134
- row3(`${c.green(sym.ok)} ${first}`);
4135
- for (const l of rest) row3(` ${l}`);
4136
- }
4137
- row3();
4138
- out(` ${brand(B.bl + B.h.repeat(inner) + B.br)}`);
4139
4170
  }
4140
- function barPara(text, paint = c.gray) {
4141
- for (const l of wrap2(text, width() - 6)) out(` ${BAR()} ${paint(l)}`);
4142
- }
4143
- function checklist(steps) {
4144
- const pad = Math.min(30, Math.max(...steps.map((s) => s.title.length)) + 2);
4145
- for (const s of steps) {
4146
- const title = s.state === "next" ? c.bold(s.title.padEnd(pad)) : s.state === "done" ? s.title.padEnd(pad) : c.gray(s.title.padEnd(pad));
4147
- const room3 = width() - 4 - 3 - pad;
4148
- const detail = s.detail ? clean(s.detail, Math.max(20, room3)) : "";
4149
- out(` ${(MARK3[s.state] ?? MARK3.todo)()} ${title}${detail ? c.gray(detail) : ""}`);
4171
+ async function dashboard(o) {
4172
+ banner("dashboard");
4173
+ hostNotice();
4174
+ const st = inspectProject(o);
4175
+ if (st.local?.dashboardUrl && (!st.token || st.local.token === st.token)) {
4176
+ showDashboard(o, st.local.dashboardUrl, [`${c.yellow("Keep this link private; it is the only way to open your dashboard.")} ${c.gray(`(from ${LOCAL_FILE})`)}`]);
4177
+ return 0;
4150
4178
  }
4151
- }
4152
- function summary(steps) {
4153
- const room3 = width() - 4 - 3 - 9;
4154
- const names = (list2) => {
4155
- const lines = [];
4156
- let line2 = "";
4157
- for (const t of list2.map((s) => s.title)) {
4158
- if (line2 && visible(line2) + 3 + t.length > room3) {
4159
- lines.push(`${line2} ${sym.dot}`);
4160
- line2 = t;
4161
- } else line2 = line2 ? `${line2} ${sym.dot} ${t}` : t;
4179
+ const { creds } = readCredentialsFor();
4180
+ if (creds) {
4181
+ const me = await fetchMe(creds);
4182
+ if (!me.ok) {
4183
+ if (me.status === 401) sessionGone();
4184
+ else err(` ${c.red(sym.cross)} Could not reach ${apiHost()} (${me.reason}).`);
4185
+ out();
4186
+ return 1;
4162
4187
  }
4163
- if (line2) lines.push(line2);
4164
- return lines;
4165
- };
4166
- const line = (mark2, label, text) => {
4167
- const [first = "", ...rest] = Array.isArray(text) ? text : [text];
4168
- out(` ${mark2} ${label}${Array.isArray(text) ? c.gray(first) : first}`);
4169
- for (const l of rest) out(` ${" ".repeat(12)}${c.gray(l)}`);
4170
- };
4171
- const pad = (label) => label.padEnd(9);
4172
- const done = steps.filter((s) => s.state === "done");
4173
- const next = steps.find((s) => s.state === "next");
4174
- const later = steps.filter((s) => s.state === "todo");
4175
- if (done.length) line(MARK3.done(), pad("Done"), names(done));
4176
- for (const b of steps.filter((s) => s.state === "blocked")) line(MARK3.blocked(), pad(b.title), c.gray(clean(b.detail ?? "", room3)));
4177
- if (next) line(MARK3.next(), c.bold(pad("Next")), c.bold(clean(next.doing ?? next.title, room3)));
4178
- for (const w of steps.filter((s) => s.state === "waiting")) line(MARK3.waiting(), pad("Waiting"), c.gray(clean(`${w.title}: ${w.detail ?? ""}`, room3)));
4179
- if (later.length) line(MARK3.todo(), c.gray(pad("Later")), names(later));
4180
- }
4181
- function nextBlock(title, text) {
4188
+ const app = st.token ? me.projects.find((p) => p.token === st.token) : null;
4189
+ if (app?.dashboard_url) {
4190
+ showDashboard(o, app.dashboard_url, [c.gray(`${app.name}, in your GenClass account (${accountLabel(me.account)}): sign in at ${apiHost()} to open it.`)]);
4191
+ return 0;
4192
+ }
4193
+ if (st.token) out(` This folder's project key (${st.token}) is not one of your account's apps; add it with ${c.cyan(`${CMD} connect`)}.`);
4194
+ out(` ${c.bold("Your apps")} ${c.bold(c.cyan(hostUrl("/account")))}`);
4195
+ if (!me.projects.length) out(` None yet. In your app's folder: ${c.cyan(SETUP_CMD)}`);
4196
+ const w = Math.min(28, Math.max(4, ...me.projects.map((p) => p.name.length)));
4197
+ for (const p of me.projects) out(` ${c.bold(p.name.padEnd(w))} ${p.dashboard_url ? c.cyan(p.dashboard_url) : ""}`.trimEnd());
4198
+ for (const l of FREE_LINES) out(` ${c.gray(l)}`);
4199
+ if (o.open && openBrowser(hostUrl("/account"), o)) out(` ${c.gray("Opening it in your browser.")}`);
4200
+ out();
4201
+ return st.token ? 1 : 0;
4202
+ }
4203
+ if (st.token) {
4204
+ out(` This app's project key is ${st.token}. Its dashboard is in the GenClass account it belongs to`);
4205
+ out(` (${c.cyan(hostUrl("/account"))}), or behind the private link you got with the key.`);
4206
+ out(` Sign in to print its link here: ${c.cyan(`${CMD} login`)}`);
4207
+ out();
4208
+ return 1;
4209
+ }
4210
+ out(` No GenClass project key in ${relative4(process.cwd(), st.cwd) || "this folder"}. Get a free dashboard for this app: ${c.cyan(`${CMD} init`)}`);
4211
+ out(` ${c.gray(`(or ${CMD} login, then ${CMD} connect, to keep it in a GenClass account)`)}`);
4182
4212
  out();
4183
- out(` ${BAR()} ${c.cyan(c.bold("Next"))} ${c.bold(title)}`);
4184
- if (text) barPara(text);
4185
- }
4186
- async function agree(question, def = true) {
4187
- const a = await confirm(question, def);
4188
- return inputClosed() ? false : a;
4189
- }
4190
- async function pick(question, labels, def = 0) {
4191
- const i = await choose(question, labels, def);
4192
- return inputClosed() ? null : i;
4193
- }
4194
- async function typed(question) {
4195
- const a = await ask(question);
4196
- return a === null || a === "" && inputClosed() ? null : a;
4197
- }
4198
- async function secret(question) {
4199
- const a = await ask(question, { hidden: true });
4200
- return a === null || a === "" && inputClosed() ? null : a;
4213
+ return 1;
4201
4214
  }
4202
- function spinner(text) {
4203
- let label = text;
4204
- let i = 0;
4205
- let timer = null;
4206
- const draw = () => process.stdout.write(`\r\x1B[2K ${c.cyan(FRAMES[i++ % FRAMES.length])} ${label}`);
4207
- if (tty2()) {
4208
- draw();
4209
- timer = setInterval(draw, 90);
4210
- timer.unref?.();
4211
- } else out(` ${c.gray(sym.dot)} ${label}`);
4212
- return {
4213
- update(t) {
4214
- label = t;
4215
- },
4216
- stop(mark2 = null, final = label) {
4217
- if (timer) {
4218
- clearInterval(timer);
4219
- process.stdout.write("\r\x1B[2K");
4220
- }
4221
- if (mark2 === "ok") good(final);
4222
- else if (mark2 === "warn") warn(final);
4223
- else if (mark2 === "bad") bad(final);
4215
+ async function logout() {
4216
+ banner("logout");
4217
+ hostNotice();
4218
+ const { creds, otherHost, path } = readCredentialsFor();
4219
+ if (!creds) {
4220
+ if (otherHost) {
4221
+ out(` The saved session is for ${otherHost}, not ${apiHost()}: unset GENCLASS_HOST to sign out there.`);
4222
+ out();
4223
+ return 1;
4224
4224
  }
4225
- };
4225
+ out(` Not signed in: nothing to do.`);
4226
+ out();
4227
+ return 0;
4228
+ }
4229
+ const r = await revokeSession(creds);
4230
+ deleteCredentials();
4231
+ if (!r.ok) {
4232
+ err(` ${c.yellow(sym.warn)} Could not end the session at ${apiHost()} (${r.reason}). ${tilde(path)} is deleted.`);
4233
+ err(` End it yourself at ${c.cyan(hostUrl("/account"))} (CLI sessions, Revoke).`);
4234
+ out();
4235
+ return 1;
4236
+ }
4237
+ row("Signed out", accountLabel(creds.account));
4238
+ out(` ${c.gray(`The CLI session is ended at genclass.dev, and ${tilde(path)} is deleted.`)}`);
4239
+ out();
4240
+ return 0;
4226
4241
  }
4227
- function ago(iso, now = Date.now()) {
4228
- const t = Date.parse(String(iso ?? ""));
4229
- if (!Number.isFinite(t)) return "";
4230
- const s = Math.max(0, Math.round((now - t) / 1e3));
4231
- if (s < 90) return "just now";
4232
- const units = [
4233
- [86400 * 365, "year"],
4234
- [86400 * 30, "month"],
4235
- [86400, "day"],
4236
- [3600, "hour"],
4237
- [60, "minute"]
4238
- ];
4239
- for (const [n2, name] of units) {
4240
- if (s >= n2) {
4241
- const v = Math.floor(s / n2);
4242
- return `${v} ${name}${v === 1 ? "" : "s"} ago`;
4242
+ async function run2(cmd, argv) {
4243
+ const h = hostConfig();
4244
+ if (h.error) {
4245
+ err(`${SELF2} ${cmd}: ${h.error}`);
4246
+ return 2;
4247
+ }
4248
+ let o;
4249
+ try {
4250
+ o = parse(argv, SPECS[cmd]);
4251
+ if (o.app !== void 0 && o.name !== void 0) throw new UsageError("--app and --name contradict each other (use an app, or create one)");
4252
+ } catch (e) {
4253
+ if (e instanceof UsageError) {
4254
+ err(`${SELF2} ${cmd}: ${e.message}
4255
+
4256
+ ${usage2()}`);
4257
+ return 2;
4243
4258
  }
4259
+ throw e;
4244
4260
  }
4245
- return "just now";
4261
+ if (o.help) {
4262
+ out(usage2());
4263
+ return 0;
4264
+ }
4265
+ if (cmd === "login") return login(o);
4266
+ if (cmd === "connect") return connect(o);
4267
+ if (cmd === "whoami") return whoami(o);
4268
+ if (cmd === "dashboard") return dashboard(o);
4269
+ return logout(o);
4246
4270
  }
4247
- var tty2, unicode2, ESC2, CSI, ANSI, CONTROL, COLOUR, width, visible, rule, homeApp, inHome, centre, badge, BAR, PROMPT, MARK3, note, good, warn, bad, FRAMES;
4248
- var init_tui = __esm({
4249
- "src/tui.mjs"() {
4271
+ var USAGE2, SPECS, when, onHost, tilde, SETUP_CMD, sessionGone, SELF2, usage2;
4272
+ var init_login = __esm({
4273
+ "../runtime/bin/lib/login.mjs"() {
4274
+ "use strict";
4250
4275
  init_define_GENCLASS_BUILD();
4276
+ init_account();
4277
+ init_host();
4278
+ init_init();
4279
+ init_plan();
4280
+ init_token();
4251
4281
  init_ui();
4252
- init_art();
4253
- tty2 = () => !!process.stdout.isTTY;
4254
- unicode2 = process.platform !== "win32" || !!process.env.WT_SESSION || !!process.env.TERM_PROGRAM;
4255
- ESC2 = String.fromCharCode(27);
4256
- CSI = String.fromCharCode(155);
4257
- ANSI = new RegExp(`${ESC2}\\[[0-9;?]*[ -/]*[@-~]|${ESC2}[@-Z\\\\-_]|${CSI}[0-9;?]*[ -/]*[@-~]`, "g");
4258
- CONTROL = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+", "g");
4259
- COLOUR = new RegExp(`${ESC2}\\[[0-9;]*m`, "g");
4260
- width = () => Math.max(60, Math.min(96, Number(process.stdout.columns) || 80));
4261
- visible = (s) => String(s).replace(COLOUR, "").length;
4262
- rule = () => out(` ${c.gray((unicode2 ? "\u2500" : "-").repeat(width() - 4))}`);
4263
- homeApp = null;
4264
- inHome = (app) => {
4265
- homeApp = app === null ? null : clean(app ?? "", 40);
4282
+ init_version();
4283
+ USAGE2 = `Usage:
4284
+ genclass-runtime login [--yes] [--no-browser] [--no-connect] [--app <id|name>] [--name <name>]
4285
+ [--no-install] [--cwd <dir>]
4286
+ genclass-runtime connect [--app <id|name>] [--name <name>] [--yes] [--dry-run] [--no-install] [--cwd <dir>]
4287
+ genclass-runtime whoami
4288
+ genclass-runtime logout
4289
+ genclass-runtime dashboard [--open] [--cwd <dir>]
4290
+
4291
+ login signs this computer in to your GenClass account. It prints a code and a link to
4292
+ https://genclass.dev/login/device and opens it in your browser; you sign in there (Google, email
4293
+ and password, GitHub or a passkey) and approve the code. The CLI session is saved, readable only by you, in
4294
+ ~/.config/genclass/credentials.json ($XDG_CONFIG_HOME/genclass; Windows: %APPDATA%\\genclass).
4295
+ Inside an app's folder it then asks whether to connect that app.
4296
+ connect connects the app in this folder to your account: pick one of your apps, or create one named after
4297
+ package.json. It writes the app's project key (token) the way init does: it shows the diff and asks
4298
+ first, and sets GenClass up if init has not. An app init created without an account (its private
4299
+ link is in ${LOCAL_FILE}) can be added to your account instead.
4300
+ whoami shows the signed-in account and its apps.
4301
+ logout ends the CLI session at genclass.dev and deletes the saved file.
4302
+ dashboard
4303
+ prints the link to this app's dashboard: what GenClass found, on which pages and what it did
4304
+ (Free shows one app's totals; every problem, its pages and how visitors use each page come
4305
+ with the Pro plan). It reads the private link in ${LOCAL_FILE} without contacting anything;
4306
+ signed in, it finds the app in your account (or lists your apps).
4307
+
4308
+ --yes, -y no questions: login connects this folder's app; connect uses your app named like
4309
+ package.json (or creates it) and applies the changes
4310
+ --no-browser login: print the link only, do not open a browser
4311
+ --open dashboard: also open the link in your browser
4312
+ --no-connect login: do not offer to connect the app in this folder
4313
+ --app <id|name> use this app of your account
4314
+ --name <name> create a new app with this name (default: package.json's name)
4315
+ --dry-run connect: show what would change; it reads your app list, and creates and writes nothing
4316
+ --no-install do not run the package manager (when connect sets GenClass up)
4317
+ --cwd <dir> the project directory (default: the current directory)
4318
+
4319
+ These commands contact genclass.dev when you run them; creating an app or writing a file is asked first. The
4320
+ project key is public (it ships in your page and can only add telemetry to its app); the CLI session is not:
4321
+ logout ends it.`;
4322
+ SPECS = {
4323
+ login: {
4324
+ bool: { yes: "yes", y: "yes", "no-browser": "noBrowser", "no-connect": "noConnect", "no-install": "noInstall", help: "help", h: "help" },
4325
+ value: { cwd: "cwd", app: "app", name: "name" }
4326
+ },
4327
+ connect: {
4328
+ bool: { yes: "yes", y: "yes", "dry-run": "dryRun", "no-install": "noInstall", help: "help", h: "help" },
4329
+ value: { cwd: "cwd", app: "app", name: "name" }
4330
+ },
4331
+ whoami: { bool: { help: "help", h: "help" }, value: { cwd: "cwd" } },
4332
+ logout: { bool: { help: "help", h: "help" }, value: { cwd: "cwd" } },
4333
+ dashboard: { bool: { open: "open", help: "help", h: "help" }, value: { cwd: "cwd" } }
4266
4334
  };
4267
- centre = (text, cols2) => {
4268
- const pad = Math.max(0, cols2 - visible(text));
4269
- const left = Math.floor(pad / 2);
4270
- return `${" ".repeat(left)}${text}${" ".repeat(pad - left)}`;
4335
+ when = (iso) => {
4336
+ const d = iso ? new Date(iso) : null;
4337
+ if (!d || Number.isNaN(d.getTime())) return null;
4338
+ return `${d.toISOString().slice(0, 16).replace("T", " ")} UTC`;
4271
4339
  };
4272
- badge = (text) => useColor ? `${String.fromCharCode(27)}[7m${c.bold(brand(` ${text} `))}${String.fromCharCode(27)}[27m` : c.bold(` ${text} `);
4273
- BAR = () => brand(unicode2 ? "\u258E" : "|");
4274
- PROMPT = () => brand(unicode2 ? "\u276F" : ">");
4275
- MARK3 = {
4276
- done: () => c.green(sym.ok),
4277
- next: () => c.cyan(unicode2 ? "\u25CF" : ">"),
4278
- waiting: () => c.yellow(unicode2 ? "\u25CC" : "~"),
4279
- todo: () => c.gray(unicode2 ? "\u25CB" : "o"),
4280
- optional: () => c.gray(unicode2 ? "\u2013" : "-"),
4281
- blocked: () => c.red(sym.cross)
4340
+ onHost = (url, host) => {
4341
+ try {
4342
+ return new URL(url).origin === host;
4343
+ } catch {
4344
+ return false;
4345
+ }
4282
4346
  };
4283
- note = (text) => para(text, " ", c.gray);
4284
- good = (text) => out(` ${c.green(sym.ok)} ${text}`);
4285
- warn = (text) => out(` ${c.yellow(sym.warn)} ${text}`);
4286
- bad = (text) => out(` ${c.red(sym.cross)} ${text}`);
4287
- FRAMES = unicode2 ? ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"] : ["-", "\\", "|", "/"];
4347
+ tilde = (path) => {
4348
+ const home2 = homedir3();
4349
+ return home2 && typeof path === "string" && path.startsWith(`${home2}/`) ? `~${path.slice(home2.length)}` : path;
4350
+ };
4351
+ SETUP_CMD = HOST_CLI ? CMD : `${CMD} connect`;
4352
+ sessionGone = () => err(` ${c.red(sym.cross)} The saved CLI session no longer works (signed out, revoked or expired). Sign in again: ${c.cyan(`${CMD} login`)}`);
4353
+ SELF2 = HOST_CLI ? CMD : "genclass-runtime";
4354
+ usage2 = () => HOST_CLI ? USAGE2.replace(/^ {2}genclass-runtime /gm, ` ${CMD} `) : USAGE2;
4355
+ }
4356
+ });
4357
+
4358
+ // src/git.mjs
4359
+ import { spawnSync as spawnSync3 } from "node:child_process";
4360
+ function runGit(args, cwd) {
4361
+ try {
4362
+ const r = spawnSync3("git", args, { cwd, encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
4363
+ return r.status === 0 && typeof r.stdout === "string" ? r.stdout.trim() : null;
4364
+ } catch {
4365
+ return null;
4366
+ }
4367
+ }
4368
+ function githubName(remote) {
4369
+ const m = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/|git:\/\/github\.com\/)([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i.exec(String(remote ?? "").trim());
4370
+ return m && FULL_NAME.test(m[1]) ? m[1] : null;
4371
+ }
4372
+ function gitInfo(cwd, run5 = runGit) {
4373
+ const root = run5(["rev-parse", "--show-toplevel"], cwd);
4374
+ if (!root) return { repo: false, root: null, remote: null, github: null, branch: null };
4375
+ const remote = run5(["remote", "get-url", "origin"], cwd);
4376
+ const branch = run5(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
4377
+ return { repo: true, root, remote, github: githubName(remote), branch: branch && branch !== "HEAD" ? branch : null };
4378
+ }
4379
+ async function renamedRepo(repo, opts = {}) {
4380
+ const f = opts.fetchFn ?? globalThis.fetch;
4381
+ if (typeof f !== "function" || !/^[A-Za-z0-9_.-]{1,39}\/[A-Za-z0-9_.-]{1,100}$/.test(repo)) return null;
4382
+ try {
4383
+ const r = await f(`https://github.com/${repo}`, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(4e3), headers: { "user-agent": "genclass-cli" } });
4384
+ if (r.status !== 301) return null;
4385
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]{1,39}\/[A-Za-z0-9_.-]{1,100})\/?$/.exec(r.headers.get("location") ?? "");
4386
+ return m && m[1].toLowerCase() !== repo.toLowerCase() ? m[1] : null;
4387
+ } catch {
4388
+ return null;
4389
+ }
4390
+ }
4391
+ var FULL_NAME;
4392
+ var init_git = __esm({
4393
+ "src/git.mjs"() {
4394
+ init_define_GENCLASS_BUILD();
4395
+ FULL_NAME = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}\/(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/;
4396
+ }
4397
+ });
4398
+
4399
+ // src/store.mjs
4400
+ import { createHash as createHash2 } from "node:crypto";
4401
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "node:fs";
4402
+ import { dirname as dirname7, join as join8, resolve as resolve4 } from "node:path";
4403
+ function readNotes(dir) {
4404
+ try {
4405
+ const j = JSON.parse(readFileSync9(fileFor(dir), "utf8"));
4406
+ return j && typeof j === "object" && !Array.isArray(j) ? j : {};
4407
+ } catch {
4408
+ return {};
4409
+ }
4410
+ }
4411
+ function saveNotes(dir, patch) {
4412
+ try {
4413
+ const file = fileFor(dir);
4414
+ mkdirSync4(dirname7(file), { recursive: true, mode: 448 });
4415
+ writeFileSync5(file, `${JSON.stringify({ ...readNotes(dir), ...patch, dir: resolve4(dir) }, null, 2)}
4416
+ `, { mode: 384 });
4417
+ return true;
4418
+ } catch {
4419
+ return false;
4420
+ }
4421
+ }
4422
+ var fileFor;
4423
+ var init_store = __esm({
4424
+ "src/store.mjs"() {
4425
+ init_define_GENCLASS_BUILD();
4426
+ init_account();
4427
+ fileFor = (dir) => join8(dirname7(credentialsPath()), "projects", `${createHash2("sha256").update(resolve4(dir)).digest("hex").slice(0, 24)}.json`);
4288
4428
  }
4289
4429
  });
4290
4430
 
@@ -4295,7 +4435,7 @@ function planViteSettings(cwd, project) {
4295
4435
  if (project?.framework !== "vite") return null;
4296
4436
  const v = versionOf(cwd, "vite", project.deps?.vite);
4297
4437
  if (!v || v.major >= 8) return null;
4298
- const byHand = (why) => ({ major: v.major, note: `Vite ${v.major} needs two settings for GenClass's model worker, or "vite build" fails. Add ${WORKER} and ${DEPS} to your Vite config (${why}).` });
4438
+ const byHand = (why2) => ({ major: v.major, note: `Vite ${v.major} needs two settings for GenClass's model worker, or "vite build" fails. Add ${WORKER} and ${DEPS} to your Vite config (${why2}).` });
4299
4439
  const path = firstFile(cwd, CONFIGS);
4300
4440
  if (!path) return { major: v.major, change: { file: "vite.config.js", path: join9(cwd, "vite.config.js"), kind: "create", before: "", after: VITE_FILE } };
4301
4441
  const file = relative5(cwd, path).split(sep4).join("/");
@@ -4352,6 +4492,21 @@ export default { ${WORKER}, ${DEPS} };
4352
4492
  });
4353
4493
 
4354
4494
  // src/state.mjs
4495
+ var state_exports = {};
4496
+ __export(state_exports, {
4497
+ PRO_TERMS: () => PRO_TERMS,
4498
+ WORKFLOW_PATH: () => WORKFLOW_PATH,
4499
+ accountPaid: () => accountPaid,
4500
+ agentConfigs: () => agentConfigs,
4501
+ appPlanOffer: () => appPlanOffer,
4502
+ appsBelow: () => appsBelow,
4503
+ freeLimits: () => freeLimits,
4504
+ genclassWorkflows: () => genclassWorkflows,
4505
+ hasPlaywright: () => hasPlaywright,
4506
+ planName: () => planName,
4507
+ readState: () => readState,
4508
+ stateJson: () => stateJson
4509
+ });
4355
4510
  import { existsSync as existsSync2, readdirSync as readdirSync3, readFileSync as readFileSync11 } from "node:fs";
4356
4511
  import { join as join10, resolve as resolve5 } from "node:path";
4357
4512
  function genclassWorkflows(root) {
@@ -4379,7 +4534,7 @@ function freeLimits(free) {
4379
4534
  function appsBelow(dir, max = 8) {
4380
4535
  const apps2 = [];
4381
4536
  let more = 0;
4382
- let seen = 0;
4537
+ let seen2 = 0;
4383
4538
  const walk2 = (abs, rel, depth) => {
4384
4539
  let names = [];
4385
4540
  try {
@@ -4388,7 +4543,7 @@ function appsBelow(dir, max = 8) {
4388
4543
  return;
4389
4544
  }
4390
4545
  for (const name of names) {
4391
- if (++seen > 400) return;
4546
+ if (++seen2 > 400) return;
4392
4547
  const at = join10(abs, name);
4393
4548
  const here = rel ? `${rel}/${name}` : name;
4394
4549
  let p = null;
@@ -4451,11 +4606,26 @@ async function readState(o = {}, deps = {}) {
4451
4606
  doing: "Sign in",
4452
4607
  state: me ? "done" : creds && offline && offline !== "expired" ? "done" : "todo",
4453
4608
  detail: me ? `${accountLabel(me.account)}${me.plan ? ` \xB7 ${me.plan.name} plan` : ""}` : creds && offline === "expired" ? "the saved session expired: sign in again" : creds && offline ? `${accountLabel(creds.account)} (not checked: ${offline})` : otherHost ? `the saved session is for ${otherHost}` : "",
4454
- why: "Opens genclass.dev in your browser. New here? Your free account is made there.",
4455
- more: "Your account is where your apps, their dashboards and your plan live. Nothing is typed in the terminal.",
4609
+ // said before anyone signs up: the command is Pro's, with its trial and price (the owner's call, 2026-11-13)
4610
+ why: "Opens genclass.dev. Then Pro: 3 days free, then US$15 a developer a month, with a card on Stripe.",
4611
+ more: `Your account is where your apps, their dashboards and your plan live. New here? It is made on that page. Nothing is typed in the terminal. ${PRO_TERMS} Free stays on the website: one app and its totals.`,
4456
4612
  run: "npx genclass login",
4457
4613
  human: "approve the sign-in in your browser"
4458
4614
  });
4615
+ const cli = me?.cli ?? null;
4616
+ steps.push({
4617
+ id: "plan",
4618
+ title: "Pro",
4619
+ doing: cli && !cli.paid ? cli.trialDays ? `Start your ${cli.trialDays}-day free trial` : `Start ${cli.plan}` : "Pro",
4620
+ state: !me ? creds && offline !== "expired" ? "optional" : "todo" : !cli ? "optional" : cli.paid ? "done" : "todo",
4621
+ detail: !me ? creds ? "" : "3 days free, then US$15 a developer a month" : cli && !cli.paid ? `${cli.price ?? cli.plan}${cli.trialDays ? `, ${cli.trialDays} days free` : ""}` : cli?.paid && cli.via === "team" ? "through your team's plan" : cli?.paid && cli.via === "open" ? "open on this genclass.dev" : me.plan && me.plan.id !== "free" ? me.plan.name : "",
4622
+ why: cli && !cli.paid ? `Every genclass command comes with ${cli.plan}${cli.trialDays ? `, ${cli.trialDays} days free to start` : ""}.` : me ? "Every genclass command comes with Pro." : PRO_TERMS,
4623
+ more: `${cli && !cli.paid && cli.trialDays ? `The trial opens in your browser and the card is asked for there, on Stripe: nothing is charged if you cancel before the ${cli.trialDays} days end. ` : "Pro opens in your browser and is paid there, on Stripe. "}Free stays on the website: one app and its totals. Plans and prices: genclass.dev/pricing.`,
4624
+ run: "npx genclass upgrade",
4625
+ human: cli && !cli.paid ? `start ${cli.plan} in your browser: ${cli.checkoutUrl}` : null,
4626
+ ...cli ? { cli } : {},
4627
+ after: "account"
4628
+ });
4459
4629
  const linked = !!st.token && (!me || !!app);
4460
4630
  let vite = null;
4461
4631
  try {
@@ -4475,25 +4645,19 @@ async function readState(o = {}, deps = {}) {
4475
4645
  run: st.fresh ? "npx genclass init" : vite ? "npx genclass setup" : "npx genclass connect",
4476
4646
  human: null
4477
4647
  });
4478
- const own = app && !app.shared ? app : null;
4479
- const pp = own?.plan ?? null;
4480
- const needs = own?.needsPlan === true;
4481
- const hasPlan = pp ? pp.id !== "free" || !!pp.source : !!me?.plan && me.plan.id !== "free";
4482
- const offer = me?.offer && !hasPlan && !app?.shared && (!pp || own.planUrl) ? pp ? { ...me.offer, checkoutUrl: `${own.planUrl}&from=cli`, project: { id: own.id, name: own.name, token: own.token }, needs } : me.offer : null;
4483
- const choseFree = pp ? own.planChosen === true && !needs : notes.plan === "free";
4484
- const limits = offer ? freeLimits(offer.free) : "";
4648
+ const appOffer = appPlanOffer(app, me?.offer ?? null, accountPaid(me));
4485
4649
  steps.push({
4486
- id: "plan",
4487
- title: "Plan",
4488
- doing: offer?.project ? "Choose this app's plan" : "Choose a plan",
4489
- state: !offer ? "optional" : choseFree ? "done" : "todo",
4490
- detail: !me ? "" : !offer ? pp ? `${pp.name}${pp.source === "comp" ? " (set up by GenClass)" : ""}` : app?.shared ? "the team's owner chooses it" : me.plan ? `${me.plan.name} plan` : "" : needs ? `Free covers ${offer.free.apps ?? 3} apps: this one needs ${offer.plan.name}` : choseFree ? `${offer.free.name} for now (limited) \xB7 ${offer.plan.name} is ${offer.price}` : `${offer.plan.name}, ${offer.price}`,
4491
- why: !offer ? pp ? "This app's plan." : "The plan your account is on." : needs ? `Free covers ${offer.free.apps ?? 3} apps and this is one more. ${offer.plan.name} is ${offer.price}.` : `${offer.plan.name} is ${offer.price}. Or try ${offer.free.name} for now (limited).`,
4492
- more: !offer ? "Plans and prices: genclass.dev/pricing." : offer.project ? `The app's plan page opens in your browser: ${offer.plan.name}, paid there on Stripe, or ${offer.free.name} for now${limits ? ` (${limits})` : ""}. Every app has its own plan: genclass.dev/account/billing.` : `${offer.plan.name} opens in your browser and is paid there, on Stripe. ${offer.free.name} keeps what finds, shows and fixes the problems${limits ? `: ${limits}` : ""}. You can change plan any time at genclass.dev/account/billing.`,
4650
+ id: "app-plan",
4651
+ title: "App plan",
4652
+ doing: appOffer?.current ? `Continue with ${appOffer.current} for this app` : "Choose this app's plan",
4653
+ state: appOffer ? "todo" : "optional",
4654
+ detail: !me || !app?.plan ? app?.shared ? "the team's owner chooses it" : "" : appOffer ? appOffer.needs ? appOffer.paying ? `${appOffer.current ?? "Your plan"} covers no more apps` : `Free covers ${appOffer.free.apps === 1 ? "one app" : `${appOffer.free.apps ?? 1} apps`}: this one needs ${appOffer.plan.name}` : appOffer.current ? `covered by ${appOffer.current}: continue on its plan page` : `${appOffer.plan.name}, ${appOffer.price}` : `${app.plan.name}${app.plan.source === "comp" ? " (set up by GenClass)" : ""}`,
4655
+ why: appOffer?.needs && appOffer.paying ? "Your plan covers no more apps. More apps come with Enterprise, by email." : appOffer?.current ? `Every new app has its plan page once. ${appOffer.current} covers this one: continue with it there.` : "This app's plan, on its page in your browser.",
4656
+ more: "Every app has its plan page: genclass.dev/account/billing. Plans and prices: genclass.dev/pricing.",
4493
4657
  run: "npx genclass setup",
4494
- human: offer && !choseFree ? `choose ${offer.project ? "this app's plan" : "a plan"} in your browser: ${offer.checkoutUrl}` : null,
4495
- ...offer ? { offer } : {},
4496
- // the plan is the app's: the walk asks once the app is in the account
4658
+ human: appOffer ? `open this app's plan page: ${appOffer.checkoutUrl}` : null,
4659
+ ...appOffer ? { offer: appOffer } : {},
4660
+ // the plan page is the app's: the walk asks once the app is in the account
4497
4661
  after: "runtime"
4498
4662
  });
4499
4663
  steps.push({
@@ -4582,14 +4746,16 @@ async function readState(o = {}, deps = {}) {
4582
4746
  run: "npx genclass suggest",
4583
4747
  human: s?.failed ? "work through the list: npx genclass suggest" : null
4584
4748
  });
4585
- const ready = (x) => !x.after || steps.find((y) => y.id === x.after)?.state === "done";
4749
+ const pro = steps.find((y) => y.id === "plan");
4750
+ const proReady = pro.state === "done" || pro.state === "optional";
4751
+ const ready = (x) => (x.id === "account" || x.id === "plan" || proReady) && (!x.after || steps.find((y) => y.id === x.after)?.state === "done");
4586
4752
  const next = steps.find((x) => x.state === "todo" && !(o.skip ?? []).includes(x.id) && ready(x)) ?? null;
4587
4753
  if (next) next.state = "next";
4588
4754
  return {
4589
4755
  cwd,
4590
4756
  host: host.overridden && !host.error ? host.host : null,
4591
4757
  app: { name: app?.name ?? project.name ?? null, framework: project.label || null, isApp, token: st.token ?? null, dashboardUrl: app?.dashboard_url ?? st.local?.dashboardUrl ?? null, site: notes.site ?? null, ...isApp ? {} : { below: appsBelow(cwd) } },
4592
- account: me ? { label: accountLabel(me.account), plan: me.plan, suggestions: me.suggestions, billingUrl: me.billingUrl, github: me.github, offer: me.offer ?? null } : null,
4758
+ account: me ? { label: accountLabel(me.account), plan: me.plan, suggestions: me.suggestions, billingUrl: me.billingUrl, github: me.github, offer: me.offer ?? null, cli: me.cli ?? null, teamPlan: me.account?.teamPlan ?? null } : null,
4593
4759
  signedIn: !!me,
4594
4760
  /** the account's apps as genclass.dev lists them ([] signed out) */
4595
4761
  projects: me?.projects ?? [],
@@ -4603,6 +4769,13 @@ async function readState(o = {}, deps = {}) {
4603
4769
  complete: steps.every((x) => x.state === "done" || x.state === "optional")
4604
4770
  };
4605
4771
  }
4772
+ function appPlanOffer(app, accountOffer, paying) {
4773
+ if (!app || app.shared || !app.plan || !app.planUrl || app.planChosen && !app.needsPlan) return null;
4774
+ const covered = !!app.plan.source && !app.needsPlan;
4775
+ if (!covered && !accountOffer && !paying) return null;
4776
+ const base2 = accountOffer ?? { plan: { name: "Pro" }, price: "", summary: null, features: [], free: { name: "Free", apps: null } };
4777
+ return { ...base2, checkoutUrl: `${app.planUrl}&from=cli`, project: { id: app.id, name: app.name, token: app.token }, needs: app.needsPlan === true, current: covered ? app.plan.name : null, paying: !!paying, chosen: app.planChosen === true };
4778
+ }
4606
4779
  function stateJson(s) {
4607
4780
  return {
4608
4781
  app: s.app,
@@ -4614,7 +4787,7 @@ function stateJson(s) {
4614
4787
  complete: s.complete
4615
4788
  };
4616
4789
  }
4617
- var WORKFLOW_PATH, read4, NOT_APPS, forAgent;
4790
+ var WORKFLOW_PATH, read4, PRO_TERMS, NOT_APPS, accountPaid, planName, forAgent;
4618
4791
  var init_state = __esm({
4619
4792
  "src/state.mjs"() {
4620
4793
  init_define_GENCLASS_BUILD();
@@ -4635,12 +4808,41 @@ var init_state = __esm({
4635
4808
  return null;
4636
4809
  }
4637
4810
  };
4811
+ PRO_TERMS = "The genclass command comes with Pro: 3 days free, then US$15 a developer a month, card on Stripe.";
4638
4812
  NOT_APPS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "coverage", "vendor", "tmp", "target"]);
4813
+ accountPaid = (me) => !!me && (me.cli ? me.cli.paid : !!me.plan && me.plan.id !== "free");
4814
+ planName = (state, token = state?.app?.token) => (state?.projects ?? []).find((p) => p.token === token && p.plan)?.plan?.name ?? state?.account?.plan?.name ?? null;
4639
4815
  forAgent = (run5) => run5 === "npx genclass setup" ? "npx genclass setup --yes" : run5;
4640
4816
  }
4641
4817
  });
4642
4818
 
4643
4819
  // src/actions.mjs
4820
+ var actions_exports = {};
4821
+ __export(actions_exports, {
4822
+ SKILL_MARK: () => SKILL_MARK,
4823
+ SKILL_PATH: () => SKILL_PATH,
4824
+ addRuntime: () => addRuntime,
4825
+ addViteSettings: () => addViteSettings,
4826
+ addWorkflow: () => addWorkflow,
4827
+ checkout: () => checkout,
4828
+ chooseAppPlan: () => chooseAppPlan,
4829
+ choosePlan: () => choosePlan,
4830
+ connectAgent: () => connectAgent,
4831
+ connectGithubApp: () => connectGithubApp,
4832
+ mcpServer: () => mcpServer,
4833
+ openBrowser: () => openBrowser2,
4834
+ planAgentConfig: () => planAgentConfig,
4835
+ planNow: () => planNow,
4836
+ projectPlan: () => projectPlan,
4837
+ runtimeArgs: () => runtimeArgs,
4838
+ sameApp: () => sameApp,
4839
+ signIn: () => signIn,
4840
+ skillText: () => skillText,
4841
+ upgradeOffer: () => upgradeOffer,
4842
+ watchFirstPage: () => watchFirstPage,
4843
+ workflowFor: () => workflowFor,
4844
+ writeSkill: () => writeSkill
4845
+ });
4644
4846
  import { spawn as spawn5 } from "node:child_process";
4645
4847
  import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync6 } from "node:fs";
4646
4848
  import { dirname as dirname8, join as join11, relative as relative6, sep as sep5 } from "node:path";
@@ -4675,7 +4877,7 @@ async function signIn(o = {}) {
4675
4877
  out();
4676
4878
  if (openBrowser2(dev.verification_uri_complete, o)) note("Your browser is opening that page.");
4677
4879
  const stop = stopOnEnter();
4678
- const sp = spinner(`Waiting for you to approve in the browser${canStop()}`);
4880
+ const sp = spinner("Waiting for you to approve in the browser", { stoppable: interactive() });
4679
4881
  const r = await pollDeviceLogin(dev, { signal: stop.signal });
4680
4882
  await stop.done();
4681
4883
  if (!r.ok && r.error === "cancelled") {
@@ -4691,34 +4893,67 @@ async function signIn(o = {}) {
4691
4893
  return "done";
4692
4894
  }
4693
4895
  async function choosePlan(state, o = {}, deps = {}) {
4694
- const offer = state.steps.find((s) => s.id === "plan")?.offer;
4896
+ const cli = state.steps.find((s) => s.id === "plan")?.cli;
4897
+ if (!cli || cli.paid) return "skipped";
4898
+ return await (await Promise.resolve().then(() => (init_paywall(), paywall_exports))).startPro(cli, state.account?.offer ?? null, o, deps) ? "done" : "quit";
4899
+ }
4900
+ async function chooseAppPlan(state, o = {}, deps = {}) {
4901
+ const offer = state.steps.find((s) => s.id === "app-plan")?.offer;
4695
4902
  if (!offer) return "skipped";
4696
- if (offer.project) return projectPlan(offer, o, deps);
4697
- const free = offer.free.name;
4698
- const limits = freeLimits(offer.free);
4699
- const stayFree = (line) => {
4700
- saveNotes(state.cwd, { plan: "free", planAt: (/* @__PURE__ */ new Date()).toISOString() });
4701
- note(line);
4702
- return "done";
4703
- };
4704
- if (o.yes || !interactive()) return stayFree(`${free} for now (limited${limits ? `: ${limits}` : ""}). ${offer.plan.name}, ${offer.price}: ${offer.checkoutUrl}`);
4705
- planCard(offer, state.app?.name ?? null);
4706
- out(` ${c.gray(`f Try ${free.toLowerCase()} for now (limited)`)}`);
4707
- const dot = c.gray("\xB7");
4708
- const a = await typed(` ${PROMPT()} ${c.bold("Enter")} ${c.gray(`to start ${offer.plan.name}`)} ${dot} ${c.bold("f")} ${c.gray("free for now")} ${dot} ${c.bold("q")} ${c.gray("stop")} `);
4709
- if (a === null || /^q/i.test(a)) return "quit";
4710
- if (/^[fs]/i.test(a)) return stayFree(`${free} for now. ${offer.plan.name} any time: ${offer.checkoutUrl}`);
4711
- if (await checkout(offer, o, deps)) return "done";
4712
- note(`This project goes on with ${free} for now.`);
4713
- return "skipped";
4903
+ return projectPlan(offer, o, deps);
4904
+ }
4905
+ function upgradeOffer(state, name = null) {
4906
+ const base2 = state.account?.offer ?? state.steps?.find((x) => x.id === "plan")?.offer ?? null;
4907
+ if (!base2) return null;
4908
+ const mine = (state.projects ?? []).filter((p) => p.plan && !p.shared);
4909
+ if (!mine.length) return base2.project ? base2 : (state.projects ?? []).some((p) => p.plan) ? null : base2;
4910
+ const named = name ? mine.find((p) => p.id === name || p.name.toLowerCase() === String(name).toLowerCase()) : null;
4911
+ const here = mine.find((p) => p.token === state.app?.token) ?? null;
4912
+ const target = named ?? here ?? mine.find((p) => p.needsPlan) ?? mine.find((p) => p.plan.id === "free" && !p.plan.source) ?? null;
4913
+ if (!target || target.plan.id !== "free" || target.plan.source || !target.planUrl) return null;
4914
+ return { ...base2, checkoutUrl: `${target.planUrl}&from=cli`, project: { id: target.id, name: target.name, token: target.token }, needs: target.needsPlan === true, chosen: target.planChosen === true, paying: accountPaid(state.account) };
4915
+ }
4916
+ async function planNow(o = {}, deps = {}, id = null) {
4917
+ let state;
4918
+ try {
4919
+ state = await (deps.readState ?? (await Promise.resolve().then(() => (init_state(), state_exports))).readState)({ cwd: o.cwd }, deps);
4920
+ } catch {
4921
+ return "none";
4922
+ }
4923
+ const app = (state.projects ?? []).find((p) => (id ? p.id === id : p.token === state.app?.token) && !p.shared);
4924
+ const offer = appPlanOffer(app, state.account?.offer ?? null, !!state.account && accountPaid(state.account));
4925
+ if (!offer) return "none";
4926
+ if (offer.needs && offer.paying && !offer.appsPerUnit) {
4927
+ if (!o.json) await projectPlan(offer, o, deps);
4928
+ return "locked";
4929
+ }
4930
+ if (o.json) return offer.current ? "covered" : "open";
4931
+ if (o.yes || !interactive()) {
4932
+ out();
4933
+ note(offer.current ? `${clean(app.name, 40)} is covered by your ${clean(offer.current, 20)} plan. Continue with it once on its plan page: ${offer.checkoutUrl}` : `${clean(app.name, 40)} has no plan yet. Choose it in the browser: ${offer.checkoutUrl}`);
4934
+ return offer.current ? "covered" : "open";
4935
+ }
4936
+ const r = await projectPlan(offer, o, deps);
4937
+ return r === "done" ? "chosen" : offer.current ? "covered" : "open";
4714
4938
  }
4715
4939
  async function checkout(offer, o = {}, deps = {}) {
4716
4940
  return await waitForPlan(offer, o, deps) === "paid";
4717
4941
  }
4718
4942
  async function projectPlan(offer, o = {}, deps = {}) {
4719
4943
  const name = clean(offer.project.name, 30);
4720
- planCard(offer, offer.project.name);
4721
- note(offer.needs ? `Free covers ${offer.free.apps ?? 3} apps and this is one more: it needs ${offer.plan.name}, ${offer.price}.` : `${offer.plan.name} is ${offer.price}. Or try ${offer.free.name.toLowerCase()} for now (limited), on the same page.`);
4944
+ if (offer.needs && offer.paying && !offer.appsPerUnit) {
4945
+ out();
4946
+ warn(`Your plan covers no more apps, and ${name} is one more. More apps come with Enterprise, by email.`);
4947
+ out(` ${c.gray("The address, on its plan page:")}`);
4948
+ out(` ${c.cyan(offer.checkoutUrl)}`);
4949
+ note("Or delete an app you no longer need, in the browser.");
4950
+ return "skipped";
4951
+ }
4952
+ if (offer.features?.length) planCard(offer, offer.project.name);
4953
+ else out();
4954
+ note(
4955
+ offer.current ? `Your ${clean(offer.current, 20)} plan covers ${name}: continue with it on its plan page.` : offer.needs && offer.paying ? `Your plan covers no more apps: add ${offer.appsPerUnit} more for ${name} on its plan page.` : offer.needs ? `Free covers ${offer.free.apps === 1 ? "one app" : `${offer.free.apps ?? 1} apps`} and this is one more: it needs ${offer.plan.name}, ${offer.price}.` : `${offer.plan.name} is ${offer.price}. Or try ${offer.free.name.toLowerCase()} for now (limited), on the same page.`
4956
+ );
4722
4957
  if (o.yes || !interactive()) {
4723
4958
  out(` Open ${c.cyan(offer.checkoutUrl)}`);
4724
4959
  if (openBrowser2(offer.checkoutUrl, o)) note("Your browser is opening its plan page. Run npx genclass again once it is chosen.");
@@ -4726,7 +4961,7 @@ async function projectPlan(offer, o = {}, deps = {}) {
4726
4961
  }
4727
4962
  const got = await waitForPlan(offer, o, deps);
4728
4963
  if (got) return "done";
4729
- note(`The setup goes on once ${name} has its plan: ${offer.needs ? offer.plan.name : `${offer.plan.name}, or ${offer.free.name} for now`}, on ${offer.checkoutUrl}`);
4964
+ note(offer.current ? `${name} goes on with ${clean(offer.current, 20)} once you continue on ${offer.checkoutUrl}` : `${name} has no plan yet: ${offer.needs ? offer.plan.name : `${offer.plan.name}, or ${offer.free.name} for now`}, on ${offer.checkoutUrl}`);
4730
4965
  return "quit";
4731
4966
  }
4732
4967
  async function waitForPlan(offer, o = {}, deps = {}) {
@@ -4736,7 +4971,7 @@ async function waitForPlan(offer, o = {}, deps = {}) {
4736
4971
  if (openBrowser2(offer.checkoutUrl, o)) note(app ? `Your browser is opening the plan page for ${app}.` : "Your browser is opening the checkout.");
4737
4972
  const creds = readCredentials();
4738
4973
  const stop = stopOnEnter();
4739
- const sp = spinner(`${app && !offer.needs ? "Waiting for your choice in the browser" : "Waiting for the payment in the browser"}${canStop()}`);
4974
+ const sp = spinner(offer.current || app && !offer.needs ? "Waiting for your choice in the browser" : "Waiting for the payment in the browser", { stoppable: interactive() });
4740
4975
  const until = Date.now() + (deps.waitMs ?? 10 * 6e4);
4741
4976
  let got = null;
4742
4977
  while (creds && !stop.signal.aborted && Date.now() < until) {
@@ -4746,15 +4981,17 @@ async function waitForPlan(offer, o = {}, deps = {}) {
4746
4981
  if (!me.ok) continue;
4747
4982
  if (offer.project) {
4748
4983
  const p = me.projects.find((x) => x.token === offer.project.token);
4749
- if (p?.plan && (p.plan.id !== "free" || p.plan.source)) got = "paid";
4750
- else if (p?.planChosen && !offer.needs) got = "free";
4751
- } else if (me.plan && me.plan.id !== "free") got = "paid";
4984
+ if (offer.current) got = p?.planChosen ? "kept" : null;
4985
+ else if (p?.plan && (p.plan.id !== "free" || p.plan.source) && !p.needsPlan) got = "paid";
4986
+ else if (p?.planChosen && !offer.chosen && !offer.needs && !p.needsPlan) got = "free";
4987
+ } else if (me.cli ? me.cli.paid : me.plan && me.plan.id !== "free") got = "paid";
4752
4988
  if (got) break;
4753
4989
  }
4754
4990
  await stop.done();
4755
- if (got === "paid") sp.stop("ok", `${offer.plan.name} is active${app ? ` for ${app}` : ""}. Thank you.`);
4991
+ if (got === "kept") sp.stop("ok", `${app} goes on with ${clean(offer.current, 20)}.`);
4992
+ else if (got === "paid") sp.stop("ok", `${offer.plan.name} is active${app ? ` for ${app}` : ""}. Thank you.`);
4756
4993
  else if (got === "free") sp.stop("ok", `${app} is on ${offer.free.name} for now (limited).`);
4757
- else sp.stop("warn", app && !offer.needs ? "No choice yet." : `No payment yet. ${offer.plan.name} starts the moment the payment goes through.`);
4994
+ else sp.stop("warn", app && !offer.needs ? "No choice yet." : `No payment yet. ${offer.plan.name} starts once it is started on Stripe.`);
4758
4995
  return got;
4759
4996
  }
4760
4997
  function runtimeArgs(state, o = {}) {
@@ -4763,14 +5000,39 @@ function runtimeArgs(state, o = {}) {
4763
5000
  return connect2 ? { cmd: "connect", args } : { cmd: "init", args: [...args, ...state.signedIn ? ["--in-account"] : [], "--no-devtools", "--brief"] };
4764
5001
  }
4765
5002
  async function addRuntime(state, o = {}) {
5003
+ if (state.account) (await Promise.resolve().then(() => (init_paywall(), paywall_exports))).noteAccount(state.account);
4766
5004
  if (!state.steps.find((s) => s.id === "runtime")?.vite) {
4767
5005
  const { cmd, args } = runtimeArgs(state, o);
4768
- const code = cmd === "connect" ? await run2("connect", args) : await run("init", args);
5006
+ const again = cmd === "init" ? await sameApp(state, o) : null;
5007
+ const code = again ? await again() : cmd === "connect" ? await run2("connect", args) : await run("init", args);
4769
5008
  if (code !== 0) return "failed";
4770
5009
  if (inspectProject({ cwd: state.cwd }).fresh) return "skipped";
4771
5010
  }
4772
5011
  return await addViteSettings(state, o) === "failed" ? "failed" : "done";
4773
5012
  }
5013
+ async function sameApp(state, o = {}) {
5014
+ if (!state.signedIn) return null;
5015
+ let st;
5016
+ try {
5017
+ st = inspectProject({ cwd: state.cwd });
5018
+ } catch {
5019
+ return null;
5020
+ }
5021
+ const name = String(st.project.pkg?.name || st.project.name || "").slice(0, 80);
5022
+ const app = name ? (state.projects ?? []).find((p) => !p.shared && p.name === name && p.token) : null;
5023
+ if (!app) return null;
5024
+ if (!o.yes) {
5025
+ if (!interactive()) return null;
5026
+ out();
5027
+ if (!await agree(`Use your existing ${clean(app.name, 40)}? ${c.gray("(No makes a new app)")}`)) return null;
5028
+ }
5029
+ const { args } = runtimeArgs(state, o);
5030
+ const creds = readCredentials();
5031
+ return async () => {
5032
+ const { init: init2, parse: parse2 } = await Promise.resolve().then(() => (init_init(), init_exports));
5033
+ return init2({ ...parse2(args), token: app.token, ...o.noInstall ? { noInstall: true } : {} }, { cmd: "init", creds, app });
5034
+ };
5035
+ }
4774
5036
  async function addViteSettings(state, o = {}) {
4775
5037
  let plan2 = null;
4776
5038
  try {
@@ -4822,7 +5084,7 @@ async function watchFirstPage(state, o = {}) {
4822
5084
  }
4823
5085
  } else return "skipped";
4824
5086
  const stop = stopOnEnter();
4825
- const sp = spinner(`Open your live site in a browser now. Watching for its first page${canStop()}`);
5087
+ const sp = spinner("Open your live site in a browser now. Watching for its first page", { stoppable: interactive() });
4826
5088
  const until = Date.now() + (o.seconds ?? 120) * 1e3;
4827
5089
  while (Date.now() < until && !stop.signal.aborted) {
4828
5090
  await nap(5e3, stop.signal);
@@ -4879,7 +5141,7 @@ async function addWorkflow(state, o = {}) {
4879
5141
  }
4880
5142
  async function waitForGithub(creds, repo, text, until, seconds) {
4881
5143
  const stop = stopOnEnter();
4882
- const sp = spinner(`${text}${canStop()}`);
5144
+ const sp = spinner(text, { stoppable: interactive() });
4883
5145
  const end = Date.now() + seconds * 1e3;
4884
5146
  let last = null;
4885
5147
  while (Date.now() < end && !stop.signal.aborted) {
@@ -4993,14 +5255,16 @@ async function connectAgent(state, o = {}) {
4993
5255
  out(` ${c.cyan(`"genclass": ${JSON.stringify(mcpServer())}`)}`);
4994
5256
  return "skipped";
4995
5257
  }
4996
- if (!o.yes && !o.confirmed) {
5258
+ if (!o.yes) {
4997
5259
  out();
4998
5260
  printChange(plan2.change);
5261
+ out(` ${c.gray(`And ${SKILL_PATH}: how the agent uses GenClass's tools (a file you changed is left alone).`)}`);
5262
+ out();
4999
5263
  if (!interactive()) {
5000
5264
  note(`Not a terminal: run ${c.cyan("npx genclass setup --yes")} to write it.`);
5001
5265
  return "skipped";
5002
5266
  }
5003
- if (!await agree("Write this change?")) return "skipped";
5267
+ if (!await agree(`Write ${plan2.file} and the skill?`)) return "skipped";
5004
5268
  }
5005
5269
  try {
5006
5270
  mkdirSync5(dirname8(plan2.path), { recursive: true });
@@ -5015,7 +5279,7 @@ async function connectAgent(state, o = {}) {
5015
5279
  note('Restart your coding agent in this folder, then ask it "is GenClass connected?". The first time, it shows two dev-only lines that connect your running app and adds them when you say yes.');
5016
5280
  return "done";
5017
5281
  }
5018
- var nap, canStop, mcpServer, SKILL_PATH, SKILL_MARK;
5282
+ var nap, mcpServer, SKILL_PATH, SKILL_MARK;
5019
5283
  var init_actions = __esm({
5020
5284
  "src/actions.mjs"() {
5021
5285
  init_define_GENCLASS_BUILD();
@@ -5028,7 +5292,6 @@ var init_actions = __esm({
5028
5292
  init_api();
5029
5293
  init_assets();
5030
5294
  init_state();
5031
- init_store();
5032
5295
  init_tui();
5033
5296
  init_vite();
5034
5297
  nap = (ms, signal) => new Promise((r) => {
@@ -5043,13 +5306,216 @@ var init_actions = __esm({
5043
5306
  { once: true }
5044
5307
  );
5045
5308
  });
5046
- canStop = () => interactive() ? c.gray(" (Enter to stop waiting)") : "";
5047
5309
  mcpServer = () => ({ command: "npx", args: ["-y", `@genclass/mcp@${BUILD.mcpVersion}`] });
5048
5310
  SKILL_PATH = ".claude/skills/genclass/SKILL.md";
5049
5311
  SKILL_MARK = "genclass:init";
5050
5312
  }
5051
5313
  });
5052
5314
 
5315
+ // src/paywall.mjs
5316
+ var paywall_exports = {};
5317
+ __export(paywall_exports, {
5318
+ afterLogin: () => afterLogin2,
5319
+ forgetPro: () => forgetPro,
5320
+ needsProJson: () => needsProJson,
5321
+ noteAccount: () => noteAccount,
5322
+ proLine: () => proLine,
5323
+ proOffer: () => proOffer,
5324
+ proSeen: () => proSeen,
5325
+ requirePro: () => requirePro,
5326
+ startPro: () => startPro
5327
+ });
5328
+ function noteAccount(who) {
5329
+ const host = globalThis.__GENCLASS_CLI__;
5330
+ if (!host || typeof host !== "object" || !who) return;
5331
+ const member = who.plan?.via === "team" || who.cli?.via === "team" || !!who.teamPlan && (!who.plan || who.plan.id === "free");
5332
+ host.into = member ? "your team's account" : null;
5333
+ }
5334
+ function needsProJson(cli, signedIn2 = true) {
5335
+ return {
5336
+ ok: false,
5337
+ error: "the genclass command comes with Pro",
5338
+ needs_pro: true,
5339
+ signed_in: signedIn2,
5340
+ plan: cli?.plan ?? "Pro",
5341
+ price: cli?.price ?? null,
5342
+ trial_days: cli?.trialDays ?? null,
5343
+ checkout_url: cli?.checkoutUrl ?? null,
5344
+ run: signedIn2 ? "npx genclass upgrade" : "npx genclass login"
5345
+ };
5346
+ }
5347
+ function proOffer(cli, offer) {
5348
+ return {
5349
+ plan: { name: cli.plan },
5350
+ price: cli.price ?? offer?.price ?? "",
5351
+ summary: offer?.summary ?? null,
5352
+ // an account whose trial is used has none left: the card does not promise one
5353
+ features: (offer?.features ?? []).filter((f) => cli.trialDays || !/days? free/i.test(f)),
5354
+ trialDays: cli.trialDays,
5355
+ checkoutUrl: cli.checkoutUrl
5356
+ };
5357
+ }
5358
+ function proLine(cli) {
5359
+ const start = cli.trialDays ? `start your ${cli.trialDays}-day free trial` : `start ${clean(cli.plan, 20)}`;
5360
+ return `The genclass command comes with ${clean(cli.plan, 20)}${cli.price ? ` (${clean(cli.price, 40)})` : ""}: ${start} at ${cli.checkoutUrl}`;
5361
+ }
5362
+ async function startPro(cli, offer, o = {}, deps = {}) {
5363
+ const card2 = proOffer(cli, offer);
5364
+ const heading = cli.trialDays ? `Start your ${cli.trialDays}-day free trial` : `genclass comes with ${clean(cli.plan, 20)}`;
5365
+ if (o.yes || o.json || !interactive()) {
5366
+ if (o.json) out(JSON.stringify(needsProJson(cli)));
5367
+ else {
5368
+ if (o.card && card2.features.length) planCard(card2, null, heading);
5369
+ out();
5370
+ warn(proLine(cli));
5371
+ }
5372
+ return false;
5373
+ }
5374
+ if (o.account) {
5375
+ out();
5376
+ note(`For ${clean(o.account, 60)}`);
5377
+ }
5378
+ planCard(card2, null, heading);
5379
+ note(
5380
+ cli.trialDays ? `Every genclass command comes with ${clean(cli.plan, 20)}. ${cli.trialDays} days free, then ${clean(card2.price, 40)}: your card is asked for on Stripe, and nothing is charged if you cancel before the trial ends.` : `Every genclass command comes with ${clean(cli.plan, 20)}, ${clean(card2.price, 40)}, paid on Stripe.`
5381
+ );
5382
+ out();
5383
+ const dot = c.gray("\xB7");
5384
+ const a = await typed(` ${PROMPT()} ${c.bold("Enter")} ${c.gray(cli.trialDays ? "to start the free trial" : `to start ${clean(cli.plan, 20)}`)} ${dot} ${c.bold("q")} ${c.gray("stop")} `);
5385
+ if (a === null || !/^(y|yes)?$/i.test(a.trim())) {
5386
+ out();
5387
+ note(proLine(cli));
5388
+ return false;
5389
+ }
5390
+ const { checkout: checkout2 } = await Promise.resolve().then(() => (init_actions(), actions_exports));
5391
+ if (await checkout2({ ...card2, pro: true }, o, deps)) {
5392
+ seen = true;
5393
+ return true;
5394
+ }
5395
+ return false;
5396
+ }
5397
+ async function requirePro(o = {}, deps = {}) {
5398
+ if (seen) return 0;
5399
+ let creds = readCredentials();
5400
+ if (!creds) {
5401
+ if (o.yes || o.json || !interactive()) {
5402
+ if (o.json) out(JSON.stringify(needsProJson(null, false)));
5403
+ else {
5404
+ out();
5405
+ warn("Sign in first: npx genclass login. The genclass command comes with Pro; its free trial starts right after the sign-in.");
5406
+ }
5407
+ return 1;
5408
+ }
5409
+ out();
5410
+ note("Sign in to genclass.dev first. Pro, with its free trial, comes right after.");
5411
+ const signIn2 = deps.signIn ?? (await Promise.resolve().then(() => (init_actions(), actions_exports))).signIn;
5412
+ if (await signIn2(o) !== "done") return 1;
5413
+ creds = readCredentials();
5414
+ if (!creds) return 1;
5415
+ }
5416
+ const me = await fetchOverview(creds, deps);
5417
+ if (me.ok) noteAccount({ plan: me.plan, cli: me.cli, teamPlan: me.account?.teamPlan });
5418
+ if (!me.ok || !me.cli || me.cli.paid) {
5419
+ if (me.ok && me.cli?.paid) seen = true;
5420
+ return 0;
5421
+ }
5422
+ if (await startPro(me.cli, me.offer ?? null, { ...o, account: accountLabel(me.account) }, deps)) {
5423
+ seen = true;
5424
+ out();
5425
+ return 0;
5426
+ }
5427
+ return 1;
5428
+ }
5429
+ async function afterLogin2(o = {}, deps = {}) {
5430
+ const creds = readCredentials();
5431
+ if (!creds) return false;
5432
+ const me = await fetchOverview(creds, deps);
5433
+ if (me.ok) noteAccount({ plan: me.plan, cli: me.cli, teamPlan: me.account?.teamPlan });
5434
+ if (!me.ok || !me.cli) return true;
5435
+ if (me.cli.paid) {
5436
+ seen = true;
5437
+ if (!o.json) note(`${clean(me.plan && me.plan.id !== "free" ? me.plan.name : "Pro", 20)} is on: every genclass command works.`);
5438
+ return true;
5439
+ }
5440
+ if (await startPro(me.cli, me.offer ?? null, { ...o, account: accountLabel(me.account) }, deps)) {
5441
+ seen = true;
5442
+ return true;
5443
+ }
5444
+ return false;
5445
+ }
5446
+ var seen, forgetPro, proSeen;
5447
+ var init_paywall = __esm({
5448
+ "src/paywall.mjs"() {
5449
+ init_define_GENCLASS_BUILD();
5450
+ init_account();
5451
+ init_init();
5452
+ init_ui();
5453
+ init_api();
5454
+ init_tui();
5455
+ seen = false;
5456
+ forgetPro = () => {
5457
+ seen = false;
5458
+ };
5459
+ proSeen = () => seen;
5460
+ }
5461
+ });
5462
+
5463
+ // src/session.mjs
5464
+ var session_exports = {};
5465
+ __export(session_exports, {
5466
+ asking: () => asking,
5467
+ refused: () => refused2
5468
+ });
5469
+ async function asking(o, creds, call, deps = {}) {
5470
+ let r = await call(creds);
5471
+ if (!r.ok && r.reauth && !o.json && interactive()) {
5472
+ out();
5473
+ note("This sign-in is from before the command could do this, so it was not approved for it. Signing in once more fixes it: the page lists what the terminal can do.");
5474
+ const a = await typed(` ${c.bold("Enter")} ${c.gray("to sign in again \xB7")} ${c.bold("q")} ${c.gray("stop")} `);
5475
+ if (a === null || /^q/i.test(a)) return r;
5476
+ if (await (deps.signIn ?? signIn)(o) !== "done") return r;
5477
+ const again = readCredentialsFor().creds;
5478
+ if (again) r = await call(again);
5479
+ }
5480
+ return r;
5481
+ }
5482
+ function refused2(r, ctx) {
5483
+ if (r.needsPro) {
5484
+ if (ctx.json) out(JSON.stringify(needsProJson(r.needsPro)));
5485
+ else {
5486
+ out();
5487
+ warn(proLine(r.needsPro));
5488
+ out(` ${c.gray("Start it here")} ${c.cyan("npx genclass upgrade")}`);
5489
+ out();
5490
+ }
5491
+ return 1;
5492
+ }
5493
+ if (ctx.json) {
5494
+ out(JSON.stringify({ ok: false, error: r.reauth ? "sign in again" : r.upgradeUrl ? "not in this plan" : r.missing ? "this genclass.dev has no such route" : r.reason, ...r.reauth ? { run: "npx genclass login" } : {}, ...r.upgradeUrl ? { upgrade_url: r.upgradeUrl, run: "npx genclass plan" } : {} }));
5495
+ return 1;
5496
+ }
5497
+ out();
5498
+ if (r.reauth) warn(`This sign-in is from before the command could do this. Run ${c.cyan("npx genclass login")} once, then ${c.cyan(`npx genclass ${ctx.command}`)}.`);
5499
+ else if (r.upgradeUrl) {
5500
+ const lock = r.lock ?? { plan: ctx.plan ?? null, upgradeUrl: r.upgradeUrl };
5501
+ proBox(`${ctx.what} comes with ${clean(lock.plan ?? ctx.plan ?? "Pro", 20)}.`, { ...lock, upgradeUrl: lock.upgradeUrl ?? r.upgradeUrl });
5502
+ } else if (r.missing) note("This genclass.dev cannot do this from the terminal yet.");
5503
+ else bad(`${ctx.what}: ${clean(r.reason ?? "it did not work", 240)}`);
5504
+ if (ctx.browserUrl && !r.upgradeUrl) out(` ${c.gray("In the browser")} ${c.cyan(ctx.browserUrl)}`);
5505
+ out();
5506
+ return 1;
5507
+ }
5508
+ var init_session = __esm({
5509
+ "src/session.mjs"() {
5510
+ init_define_GENCLASS_BUILD();
5511
+ init_account();
5512
+ init_ui();
5513
+ init_actions();
5514
+ init_paywall();
5515
+ init_tui();
5516
+ }
5517
+ });
5518
+
5053
5519
  // src/app.mjs
5054
5520
  var app_exports = {};
5055
5521
  __export(app_exports, {
@@ -5192,11 +5658,11 @@ async function pickApp(o = {}, deps = {}, name = "dashboard") {
5192
5658
  const wanted = byId.length ? byId : o.app ? projects.filter((p) => p.name.toLowerCase() === String(o.app).toLowerCase()) : state.app.token ? projects.filter((p) => p.token === state.app.token) : projects.length === 1 ? projects : [];
5193
5659
  if (wanted.length !== 1 && projects.length && !o.json && !o.yes && interactive()) {
5194
5660
  const list2 = (wanted.length > 1 ? wanted : projects).slice(0, 30);
5195
- header({ app: state.app.name, framework: state.app.framework, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5661
+ header({ app: state.app.name, framework: state.app.framework, account: state.account?.label, plan: planName(state), host: state.host });
5196
5662
  note(wanted.length > 1 ? `More than one app is named "${clean(o.app, 40)}". Which one?` : o.app ? `No app named "${clean(o.app, 40)}". Which one?` : state.app.token ? "This folder's app is not in your account yet. Which app?" : "Which app?");
5197
5663
  list2.forEach((p, i2) => out(` ${c.gray(String(i2 + 1).padStart(2))} ${c.bold(clean(appLabel(p, projects), 34))}${p.last_event ? c.gray(` last page ${ago(p.last_event, deps.now)}`) : ""}`));
5198
5664
  out();
5199
- const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("back")} `);
5665
+ const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("stop")} `);
5200
5666
  const i = a !== null && /^\d+$/.test(a.trim()) ? Number(a.trim()) - 1 : -1;
5201
5667
  if (list2[i]) return { state, creds, target: list2[i] };
5202
5668
  out();
@@ -5205,7 +5671,7 @@ async function pickApp(o = {}, deps = {}, name = "dashboard") {
5205
5671
  if (wanted.length !== 1) {
5206
5672
  if (o.json) out(JSON.stringify({ ok: false, error: projects.length ? "which app" : "no app yet", apps: projects.map((p) => p.name) }));
5207
5673
  else {
5208
- header({ app: state.app.name, framework: state.app.framework, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5674
+ header({ app: state.app.name, framework: state.app.framework, account: state.account?.label, plan: planName(state), host: state.host });
5209
5675
  if (!projects.length) note("No app in your account yet. Run npx genclass in your web app's folder: it adds GenClass and gives the app its dashboard.");
5210
5676
  else {
5211
5677
  note(wanted.length > 1 ? `More than one app is named "${clean(o.app, 40)}". Name it by its id:` : o.app ? `No app named "${clean(o.app, 40)}" in your account. Your apps:` : state.app.token ? "This folder's app is not in your account yet (genclass puts it there). Your apps:" : "Which app? Run this in the app's folder, or name one:");
@@ -5223,22 +5689,40 @@ async function appView(o = {}, deps = {}, view) {
5223
5689
  if ("code" in picked) return picked.code;
5224
5690
  let { state } = picked;
5225
5691
  const { creds, target } = picked;
5692
+ if (!o.json && interactive()) {
5693
+ const p = await planNow({ cwd: o.cwd, yes: o.yes }, deps, target.id);
5694
+ if (p === "locked") {
5695
+ out();
5696
+ return 1;
5697
+ }
5698
+ if (p === "open") {
5699
+ out();
5700
+ note(`${clean(target.name, 40)} needs its plan first. Run this again once it is chosen.`);
5701
+ out();
5702
+ return 1;
5703
+ }
5704
+ if (p === "chosen") state = await readState({ cwd: o.cwd }, deps);
5705
+ }
5226
5706
  if (o.open && target.dashboard_url) openBrowser2(target.dashboard_url, o);
5227
5707
  let app = await fetchApp(creds, target.id, range, deps);
5228
5708
  if (!app.ok && app.reauth && !o.json && interactive()) {
5229
- header({ app: target.name, framework: state.app.framework, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5709
+ header({ app: target.name, framework: state.app.framework, account: state.account?.label, plan: planName(state, target.token), host: state.host });
5230
5710
  note("This sign-in is from before the command could show dashboards, so it was not approved for that. Signing in once more fixes it.");
5231
- const a = await typed(` ${c.bold("Enter")} ${c.gray("to sign in again,")} ${c.bold("q")} ${c.gray("to stop")} `);
5711
+ const a = await typed(` ${c.bold("Enter")} ${c.gray("to sign in again \xB7")} ${c.bold("q")} ${c.gray("stop")} `);
5232
5712
  if (a === null || /^q/i.test(a)) return 1;
5233
5713
  if (await signIn(o) !== "done") return 1;
5234
5714
  const again = readCredentialsFor().creds;
5235
5715
  state = await readState({ cwd: o.cwd }, deps);
5236
5716
  app = await fetchApp(again, target.id, range, deps);
5237
5717
  }
5718
+ if (!app.ok && app.needsPro) {
5719
+ if (!o.json) header({ app: target.name, framework: state.app.framework, account: state.account?.label, plan: planName(state, target.token), host: state.host });
5720
+ return (await Promise.resolve().then(() => (init_session(), session_exports))).refused(app, { what: "The dashboard", command: view.name, json: o.json });
5721
+ }
5238
5722
  if (!app.ok) {
5239
5723
  if (o.json) out(JSON.stringify({ ok: false, error: app.reauth ? "sign in again" : app.reason, run: app.reauth ? "npx genclass login" : null, dashboard_url: target.dashboard_url }));
5240
5724
  else {
5241
- header({ app: target.name, framework: state.app.framework, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5725
+ header({ app: target.name, framework: state.app.framework, account: state.account?.label, plan: planName(state, target.token), host: state.host });
5242
5726
  if (app.reauth) warn(`This sign-in is from before the command could show dashboards. Run ${c.cyan("npx genclass login")} once, then ${c.cyan(`npx genclass ${view.name}`)}.`);
5243
5727
  else if (app.missing) note("This genclass.dev cannot show a dashboard in the terminal yet.");
5244
5728
  else bad(`Could not read the dashboard: ${clean(app.reason, 200)}`);
@@ -5257,12 +5741,12 @@ async function appView(o = {}, deps = {}, view) {
5257
5741
  return 0;
5258
5742
  }
5259
5743
  if (app.problemsPlan && PRO_VIEWS[view.name]) {
5260
- header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5744
+ header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: planName(state, target.token), host: state.host });
5261
5745
  proBox(PRO_VIEWS[view.name], app.problemsPlan);
5262
5746
  out();
5263
5747
  return 0;
5264
5748
  }
5265
- if (!view.plain) header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
5749
+ if (!view.plain) header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: planName(state, target.token), host: state.host });
5266
5750
  const code = await view.show(app, state, target, readCredentialsFor().creds ?? creds);
5267
5751
  return typeof code === "number" ? code : 0;
5268
5752
  }
@@ -5880,7 +6364,7 @@ function hostedReport(url, r, base2) {
5880
6364
  const notes = [];
5881
6365
  if (r.scoreNote) notes.push(r.scoreNote);
5882
6366
  if (unscored) notes.push(`${unscored} more listed but not scored on the full report`);
5883
- for (const [cat, why] of Object.entries(r.notMeasured || {})) notes.push(`${cat} not measured: ${why}`);
6367
+ for (const [cat, why2] of Object.entries(r.notMeasured || {})) notes.push(`${cat} not measured: ${why2}`);
5884
6368
  return {
5885
6369
  format: "genclass-scan/1",
5886
6370
  url,
@@ -5902,8 +6386,8 @@ function hostedReport(url, r, base2) {
5902
6386
  };
5903
6387
  }
5904
6388
  function partialOf(r) {
5905
- const why = r.notMeasured && typeof r.notMeasured === "object" ? r.notMeasured : {};
5906
- const cats = (Array.isArray(r.score?.categories) ? r.score.categories : []).filter((cat) => cat.measured || !/nothing to try/i.test(String(why[cat.id] ?? "")));
6389
+ const why2 = r.notMeasured && typeof r.notMeasured === "object" ? r.notMeasured : {};
6390
+ const cats = (Array.isArray(r.score?.categories) ? r.score.categories : []).filter((cat) => cat.measured || !/nothing to try/i.test(String(why2[cat.id] ?? "")));
5907
6391
  const done = cats.filter((cat) => cat.measured);
5908
6392
  if (!cats.length || done.length === cats.length) return null;
5909
6393
  return { measured: done.length, of: cats.length, labels: done.map((cat) => String(cat.label)), timedOut: r.timedOut === true };
@@ -5943,9 +6427,9 @@ function formatReport(rep) {
5943
6427
  p(` ${score} ${c.gray(sym.dot)} ${found}`);
5944
6428
  if (rep.blocked) p(` ${c.yellow(sym.warn)} ${rep.blocked}`);
5945
6429
  if (part2 && !rep.blocked) {
5946
- const why = part2.timedOut ? "The page was still loading when the page check's time ran out" : "The page check could not finish every part on this page";
6430
+ const why2 = part2.timedOut ? "The page was still loading when the page check's time ran out" : "The page check could not finish every part on this page";
5947
6431
  const what = part2.measured ? `the score covers ${list(part2.labels)} only` : "nothing could be scored";
5948
- p(` ${c.yellow(sym.warn)} ${fold(`${why}, so ${what}.`, " ", 4)}`);
6432
+ p(` ${c.yellow(sym.warn)} ${fold(`${why2}, so ${what}.`, " ", 4)}`);
5949
6433
  p(` ${fold("The visual checks can run on this computer instead, with no time limit:", " ")}`);
5950
6434
  p(` ${c.cyan(`${CMD} scan ${rep.url} --local`)}`);
5951
6435
  }
@@ -6059,8 +6543,8 @@ ${USAGE3}`);
6059
6543
  if (o.json) out(JSON.stringify(rep, null, 2));
6060
6544
  else out(formatReport(rep));
6061
6545
  if (rep.blocked || !rep.views.some((v) => v.ok)) {
6062
- const why = rep.views.map((v) => v.error).filter(Boolean)[0] || (rep.partial?.timedOut ? "the page did not finish loading within the page check's time" : "the page did not load");
6063
- if (!o.json) err(`${NAME} ${cmd}: nothing was measured${rep.blocked ? "" : `: ${why}`}`);
6546
+ const why2 = rep.views.map((v) => v.error).filter(Boolean)[0] || (rep.partial?.timedOut ? "the page did not finish loading within the page check's time" : "the page did not load");
6547
+ if (!o.json) err(`${NAME} ${cmd}: nothing was measured${rep.blocked ? "" : `: ${why2}`}`);
6064
6548
  return 2;
6065
6549
  }
6066
6550
  return rep.findings.length ? 1 : 0;
@@ -6429,7 +6913,7 @@ __export(views_exports, {
6429
6913
  time: () => time
6430
6914
  });
6431
6915
  import { readFileSync as readFileSync15, writeFileSync as writeFileSync8 } from "node:fs";
6432
- import { homedir as homedir3 } from "node:os";
6916
+ import { homedir as homedir4 } from "node:os";
6433
6917
  import { join as join14, resolve as resolve8 } from "node:path";
6434
6918
  function bars(title, rows2, o = {}) {
6435
6919
  if (!rows2?.length) return;
@@ -6473,7 +6957,9 @@ function renderAnalytics(app, o = {}) {
6473
6957
  if (app.visitorsPlan) {
6474
6958
  out();
6475
6959
  out(` ${c.bold(`Visitor analytics come with the ${clean(app.visitorsPlan.plan ?? "Pro", 20)} plan.`)}`);
6476
- note("What your visitors do is already being counted, so it shows from the day you switch: visits, pages, time on a page, where people come from, what they click, funnels.");
6960
+ const counted = (t?.ix_views ?? 0) > 0 || (app.totals?.pageViews ?? 0) > 0;
6961
+ note(counted ? "What your visitors do is already being counted, so it shows from the day you switch: visits, pages, time on a page, where people come from, what they click, funnels." : "Visits, pages, time on a page, where people come from, what they click, funnels. Your app turns it on with one line, no cookies:");
6962
+ if (!counted) out(` ${c.cyan("https://genclass.dev/docs/analytics")}`);
6477
6963
  out(` ${c.cyan("npx genclass plan")}`);
6478
6964
  out();
6479
6965
  return;
@@ -6779,7 +7265,7 @@ function health(o = {}, deps = {}) {
6779
7265
  show: (app) => renderHealth(app, { all: o.all, now: deps.now })
6780
7266
  });
6781
7267
  }
6782
- function agentSetup(dir, home2 = homedir3()) {
7268
+ function agentSetup(dir, home2 = homedir4()) {
6783
7269
  const files = agentConfigs(dir);
6784
7270
  const envs = [];
6785
7271
  let inRepo = false;
@@ -8246,15 +8732,15 @@ function readEnv(facts, ctx) {
8246
8732
  }
8247
8733
  }
8248
8734
  const dirs = ctx.gitRoot === ctx.root ? [ctx.root] : [ctx.root, ctx.gitRoot];
8249
- let seen = false;
8735
+ let seen2 = false;
8250
8736
  let covered = false;
8251
8737
  for (const dir of dirs) {
8252
8738
  const text = readHead(join16(dir, ".gitignore"));
8253
8739
  if (text === null) continue;
8254
- seen = true;
8740
+ seen2 = true;
8255
8741
  if (ignoreCoversEnv(text)) covered = true;
8256
8742
  }
8257
- facts.env.ignored = seen ? covered : facts.git.repo ? false : null;
8743
+ facts.env.ignored = seen2 ? covered : facts.git.repo ? false : null;
8258
8744
  }
8259
8745
  function onlyPublicValues(text) {
8260
8746
  for (const line of text.split(/\r?\n/)) {
@@ -8326,7 +8812,7 @@ function scanContents(facts, ctx) {
8326
8812
  candidates.push({ file, base: base2, env: env2, example, config, secrets, prod, client, markup, rank: env2 || example || prod ? 0 : client || markup ? 1 : 2 });
8327
8813
  }
8328
8814
  candidates.sort((a, b) => a.rank - b.rank);
8329
- const seen = /* @__PURE__ */ new Set();
8815
+ const seen2 = /* @__PURE__ */ new Set();
8330
8816
  let opened = 0;
8331
8817
  for (const c2 of candidates) {
8332
8818
  if (opened >= MAX_SCAN) break;
@@ -8346,8 +8832,8 @@ function scanContents(facts, ctx) {
8346
8832
  if (c2.secrets && !minified) {
8347
8833
  for (const hit of findSecrets(text, c2.env, TEST_PATH.test(c2.file))) {
8348
8834
  const key = `${c2.file}:${hit.line}:${hit.kind}`;
8349
- if (seen.has(key) || facts.secrets.length >= MAX_SECRETS) continue;
8350
- seen.add(key);
8835
+ if (seen2.has(key) || facts.secrets.length >= MAX_SECRETS) continue;
8836
+ seen2.add(key);
8351
8837
  facts.secrets.push({ file: c2.file, line: hit.line, kind: hit.kind });
8352
8838
  if (hit.kind.startsWith("stripe-")) ctx.hints.add("stripe");
8353
8839
  }
@@ -9269,7 +9755,7 @@ function siteAddress(v) {
9269
9755
  return null;
9270
9756
  }
9271
9757
  }
9272
- function layOut(results, plan2) {
9758
+ function layOut(results, plan2, paid = false) {
9273
9759
  const failed = results.filter((r) => r.status === "fail");
9274
9760
  const by = new Map(failed.map((r) => [r.id, r]));
9275
9761
  const order = [];
@@ -9279,7 +9765,7 @@ function layOut(results, plan2) {
9279
9765
  for (const id of plan2.lockedIds ?? []) if (by.has(id) && !order.includes(id)) order.push(id);
9280
9766
  }
9281
9767
  const rest = failed.filter((r) => !order.includes(r.id)).sort((a, b) => b.weight - a.weight);
9282
- const shown = plan2 ? plan2.items.length : Math.min(FREE_SHOWN, rest.length);
9768
+ const shown = plan2 ? plan2.items.length : paid ? rest.length : Math.min(FREE_SHOWN, rest.length);
9283
9769
  for (const r of rest) order.push(r.id);
9284
9770
  return order.map((id, n2) => {
9285
9771
  const r = by.get(id);
@@ -9385,7 +9871,7 @@ ${prompt}
9385
9871
  choices.forEach(([label], i) => out(` ${c.gray(String(i + 1).padStart(2))} ${label}`));
9386
9872
  if (!agents.length) note("No coding agent's command found here (claude, codex, cursor-agent, gemini).");
9387
9873
  out();
9388
- const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("not now")} `);
9874
+ const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("stop")} `);
9389
9875
  const pick2 = a !== null && /^\d+$/.test(a.trim()) ? choices[Number(a.trim()) - 1] : null;
9390
9876
  if (pick2) await pick2[1]();
9391
9877
  }
@@ -9401,11 +9887,12 @@ async function suggest(o = {}, deps = {}) {
9401
9887
  return 2;
9402
9888
  }
9403
9889
  if (!quiet) header({ app: repo.name ?? st.project.name, framework: st.project.label || null, account: readCredentials()?.account?.email ?? null });
9404
- if (!url && !quiet && !o.yes && interactive()) {
9890
+ if (!url && !notes.repoOnly && !quiet && !o.yes && interactive()) {
9405
9891
  para("Where is this app live? With its address GenClass also checks what search engines, AI assistants and visitors get from it.", " ");
9406
9892
  const a = await typed(` ${c.bold("Address")} ${c.gray("(or Enter for the repository only)")} `);
9407
9893
  url = siteAddress(a);
9408
9894
  if (a && !url) warn("That is not a site address, so only the repository is checked this time.");
9895
+ if (a === "") saveNotes(cwd, { repoOnly: true });
9409
9896
  }
9410
9897
  let site = null;
9411
9898
  if (url) {
@@ -9447,7 +9934,7 @@ async function suggest(o = {}, deps = {}) {
9447
9934
  }
9448
9935
  }
9449
9936
  }
9450
- const items = layOut(results, plan2);
9937
+ const items = layOut(results, plan2, !plan2 && !!creds && (o.paid === true || proSeen()));
9451
9938
  const locked = items.filter((i) => !i.open);
9452
9939
  saveNotes(cwd, { ...site?.reachable ? { site: url } : {}, suggest: { at: (/* @__PURE__ */ new Date()).toISOString(), failed: failed.length, urgent: failed.filter((r) => r.weight >= 4).length, passed: passed.length, top: items.slice(0, 3).map((i) => i.id) } });
9453
9940
  if (o.json) {
@@ -9499,7 +9986,7 @@ async function suggest(o = {}, deps = {}) {
9499
9986
  }
9500
9987
  if (unknown2.length) {
9501
9988
  out();
9502
- if (!site?.reachable) note(`${unknown2.length} more checks need your live site${url ? "" : `: ${c.cyan("npx genclass suggest https://your-site.com")}`}.`);
9989
+ if (!site?.reachable) note(`${unknown2.length} more checks need your live site${url ? "." : `: ${c.cyan("npx genclass suggest https://your-site.com")}`}`);
9503
9990
  else note(`${unknown2.length} check${unknown2.length === 1 ? "" : "s"} could not be measured on this site this time.`);
9504
9991
  }
9505
9992
  out();
@@ -9520,6 +10007,7 @@ var init_suggest = __esm({
9520
10007
  init_init();
9521
10008
  init_ui();
9522
10009
  init_api();
10010
+ init_paywall();
9523
10011
  init_fix();
9524
10012
  init_store();
9525
10013
  init_tui();
@@ -9536,46 +10024,6 @@ var init_suggest = __esm({
9536
10024
  }
9537
10025
  });
9538
10026
 
9539
- // src/session.mjs
9540
- async function asking(o, creds, call, deps = {}) {
9541
- let r = await call(creds);
9542
- if (!r.ok && r.reauth && !o.json && interactive()) {
9543
- out();
9544
- note("This sign-in is from before the command could do this, so it was not approved for it. Signing in once more fixes it: the page lists what the terminal can do.");
9545
- const a = await typed(` ${c.bold("Enter")} ${c.gray("to sign in again,")} ${c.bold("q")} ${c.gray("to stop")} `);
9546
- if (a === null || /^q/i.test(a)) return r;
9547
- if (await (deps.signIn ?? signIn)(o) !== "done") return r;
9548
- const again = readCredentialsFor().creds;
9549
- if (again) r = await call(again);
9550
- }
9551
- return r;
9552
- }
9553
- function refused2(r, ctx) {
9554
- if (ctx.json) {
9555
- out(JSON.stringify({ ok: false, error: r.reauth ? "sign in again" : r.upgradeUrl ? "not in this plan" : r.missing ? "this genclass.dev has no such route" : r.reason, ...r.reauth ? { run: "npx genclass login" } : {}, ...r.upgradeUrl ? { upgrade_url: r.upgradeUrl, run: "npx genclass plan" } : {} }));
9556
- return 1;
9557
- }
9558
- out();
9559
- if (r.reauth) warn(`This sign-in is from before the command could do this. Run ${c.cyan("npx genclass login")} once, then ${c.cyan(`npx genclass ${ctx.command}`)}.`);
9560
- else if (r.upgradeUrl) {
9561
- const lock = r.lock ?? { plan: ctx.plan ?? null, upgradeUrl: r.upgradeUrl };
9562
- proBox(`${ctx.what} comes with ${clean(lock.plan ?? ctx.plan ?? "Pro", 20)}.`, { ...lock, upgradeUrl: lock.upgradeUrl ?? r.upgradeUrl });
9563
- } else if (r.missing) note("This genclass.dev cannot do this from the terminal yet.");
9564
- else bad(`${ctx.what}: ${clean(r.reason ?? "it did not work", 240)}`);
9565
- if (ctx.browserUrl && !r.upgradeUrl) out(` ${c.gray("In the browser")} ${c.cyan(ctx.browserUrl)}`);
9566
- out();
9567
- return 1;
9568
- }
9569
- var init_session = __esm({
9570
- "src/session.mjs"() {
9571
- init_define_GENCLASS_BUILD();
9572
- init_account();
9573
- init_ui();
9574
- init_actions();
9575
- init_tui();
9576
- }
9577
- });
9578
-
9579
10027
  // src/manage.mjs
9580
10028
  var manage_exports = {};
9581
10029
  __export(manage_exports, {
@@ -9590,8 +10038,7 @@ __export(manage_exports, {
9590
10038
  plan: () => plan,
9591
10039
  profile: () => profile,
9592
10040
  team: () => team,
9593
- upgrade: () => upgrade,
9594
- upgradeOffer: () => upgradeOffer
10041
+ upgrade: () => upgrade
9595
10042
  });
9596
10043
  import { writeFileSync as writeFileSync9 } from "node:fs";
9597
10044
  import { resolve as resolve10 } from "node:path";
@@ -9635,10 +10082,16 @@ async function apps(o = {}, deps = {}) {
9635
10082
  row2("Project key", r.token);
9636
10083
  const me = await fetchOverview(creds, deps).catch(() => null);
9637
10084
  const made = me?.ok ? me.projects.find((p) => p.token === r.token) : null;
10085
+ const full = !!made?.needsPlan && accountPaid(me);
9638
10086
  if (made?.needsPlan && made.planUrl) {
9639
- warn("Free covers 3 apps: this one needs a paid plan.");
9640
- out(` ${c.gray("Its plan:")} ${c.cyan(made.planUrl)}`);
9641
- } else if (made?.plan?.id === "free" && made.planUrl) out(` ${c.gray("On Free (limited). Its plan:")} ${c.cyan(made.planUrl)}`);
10087
+ warn(full ? "Your plan covers no more apps: more come with Enterprise, by email." : "Free covers one app: this one needs Pro.");
10088
+ out(` ${c.gray(full ? "The address, on its plan page:" : "Its plan:")}`);
10089
+ out(` ${c.cyan(made.planUrl)}`);
10090
+ } else if (made?.plan?.id === "free" && made.planUrl) {
10091
+ out(` ${c.gray("On Free (limited). Its plan:")}`);
10092
+ out(` ${c.cyan(made.planUrl)}`);
10093
+ }
10094
+ if (made?.id && !full) await planNow({ cwd: o.cwd }, deps, made.id);
9642
10095
  note("To put GenClass into that app's code, run npx genclass in its folder and pick this app.");
9643
10096
  }
9644
10097
  out();
@@ -9677,12 +10130,15 @@ async function plan(o = {}, deps = {}) {
9677
10130
  if ("code" in s) return s.code;
9678
10131
  const { state, creds } = s;
9679
10132
  const a = await asking(o, creds, (cr) => fetchAccount(cr, deps), deps);
9680
- const step = state.steps.find((x) => x.id === "plan");
10133
+ const cli = state.account?.cli ?? null;
10134
+ const pro = cli && !cli.paid ? cli : null;
10135
+ const step = state.steps.find((x) => x.id === "app-plan");
9681
10136
  const mine = (state.projects ?? []).filter((p) => p.plan);
9682
- const offer = step?.offer ?? (mine.length ? null : a.ok ? a.offer : null);
10137
+ const offer = pro ? null : step?.offer ?? (mine.length ? null : a.ok ? a.offer : null);
9683
10138
  if (o.json) {
9684
10139
  const apps2 = mine.map((p) => ({ id: p.id, name: p.name, plan: p.plan, needs_plan: p.needsPlan, plan_url: p.planUrl, this_folder: p.token === state.app?.token }));
9685
- out(JSON.stringify(a.ok ? { ok: true, plan: a.plan, access: a.access, limits: a.limits, used: a.used, includes: a.includes, subscription: a.subscription, billing_url: a.billingUrl, offer, apps: apps2 } : { ok: true, plan: state.account?.plan ?? null, billing_url: state.account?.billingUrl ?? null, offer, partial: a.reauth ? "sign in again for the limits: npx genclass login" : "this genclass.dev says no more" }, null, 2));
10140
+ const command = cli ? { paid: cli.paid, ...pro ? { checkout_url: pro.checkoutUrl, trial_days: pro.trialDays, price: pro.price } : {} } : null;
10141
+ out(JSON.stringify(a.ok ? { ok: true, plan: a.plan, access: a.access, limits: a.limits, used: a.used, includes: a.includes, subscription: a.subscription, billing_url: a.billingUrl, offer: offer ?? (pro ? a.offer : null), cli: command, apps: apps2 } : { ok: true, plan: state.account?.plan ?? null, billing_url: state.account?.billingUrl ?? null, offer, cli: command, partial: a.reauth ? "sign in again for the limits: npx genclass login" : "this genclass.dev says no more" }, null, 2));
9686
10142
  return 0;
9687
10143
  }
9688
10144
  top(state);
@@ -9693,12 +10149,16 @@ async function plan(o = {}, deps = {}) {
9693
10149
  if (a.reauth) note("For its limits and what is used: npx genclass login, once (this sign-in is from before the command could show them).");
9694
10150
  } else {
9695
10151
  row2("Plan", `${c.bold(clean(a.plan.name, 20))}${a.plan.price ? c.gray(` ${clean(a.plan.price, 40)}`) : ""}${a.access === "comp" ? c.gray(" granted by GenClass") : ""}`);
9696
- if (a.subscription.periodEnd && a.access === "paid") row2(a.subscription.cancels ? "Ends" : "Renews", day2(a.subscription.periodEnd));
10152
+ if (a.teamPlan && a.teamPlan.id !== a.plan.id) row2("Through", `your team's ${clean(a.teamPlan.name, 20)}`);
10153
+ const trial = a.subscription.status === "trialing" && a.access === "paid" && a.subscription.periodEnd;
10154
+ if (trial) row2("Trial", a.subscription.cancels ? `until ${day2(a.subscription.periodEnd)}. Canceled: nothing is charged.` : `until ${day2(a.subscription.periodEnd)}. Then the first charge, ${a.plan.price ? clean(a.plan.price, 40) : "the plan's price"}, unless you cancel before.`);
10155
+ else if (a.subscription.periodEnd && a.access === "paid") row2(a.subscription.cancels ? "Ends" : "Renews", day2(a.subscription.periodEnd));
9697
10156
  if (a.subscription.status && !["active", "trialing"].includes(a.subscription.status)) row2("Payment", c.yellow(clean(a.subscription.status.replace(/_/g, " "), 30)));
9698
- row2("Apps", a.limits.apps === null ? `${n(a.used.apps)} ${sym.dot} no limit` : `${n(a.used.apps)} of ${n(a.limits.apps)}`);
10157
+ row2("Apps", a.limits.apps === null || a.access === "comp" ? `${n(a.used.apps)} ${sym.dot} no limit` : `${n(a.used.apps)} of ${n(a.limits.apps)}`);
9699
10158
  row2("History", a.limits.historyDays === null ? "" : `${n(a.limits.historyDays)} days`);
9700
10159
  row2("People", a.limits.seats === null ? `${n(a.used.seats)} ${sym.dot} no limit` : `${n(a.used.seats)} of ${n(a.limits.seats)}`);
9701
- if (a.limits.suggestionsPerDay !== null) row2("Model runs", `${n(a.used.suggestionsToday)} of ${n(a.limits.suggestionsPerDay)} used today ${sym.dot} suggest and ask share them`);
10160
+ if (pro) row2("Model runs", "come with Pro (suggest and ask)");
10161
+ else if (a.limits.suggestionsPerDay !== null) row2("Model runs", `${n(a.used.suggestionsToday)} of ${n(a.limits.suggestionsPerDay)} used today ${sym.dot} suggest and ask share them`);
9702
10162
  const has = [a.includes.analytics && "visitor analytics", a.includes.forwarding && "alerts to Slack, Sentry and others", a.includes.export && "the stored events as a file", a.includes.privateRepositories && "private repositories"].filter(Boolean);
9703
10163
  const lacks = [!a.includes.analytics && "visitor analytics", !a.includes.forwarding && "alerts to Slack, Sentry and others", !a.includes.export && "the stored events as a file", !a.includes.privateRepositories && "private repositories"].filter(Boolean);
9704
10164
  if (has.length) row2("Includes", has.join(", "));
@@ -9708,10 +10168,15 @@ async function plan(o = {}, deps = {}) {
9708
10168
  out();
9709
10169
  out(` ${c.bold("Apps and their plans")}`);
9710
10170
  for (const p of mine) {
9711
- const what = p.needsPlan ? c.yellow("needs a plan") : p.plan.id === "free" ? c.gray("Free") : c.bold(clean(p.plan.name, 20));
10171
+ const what = p.needsPlan ? c.yellow("needs a plan") : p.plan.id === "free" ? p.planChosen ? c.gray("Free") : c.yellow("no plan chosen") : c.bold(clean(p.plan.name, 20));
9712
10172
  out(` ${clean(p.name, 24).padEnd(24)} ${what}${p.token === state.app?.token ? c.gray(" this folder") : ""}`);
9713
10173
  }
9714
10174
  }
10175
+ if (pro) {
10176
+ await (await Promise.resolve().then(() => (init_paywall(), paywall_exports))).startPro(pro, state.account?.offer ?? (a.ok ? a.offer : null), { ...o, card: true }, deps);
10177
+ out();
10178
+ return 0;
10179
+ }
9715
10180
  if (!offer) {
9716
10181
  out();
9717
10182
  out(` ${c.gray("Billing, in the browser")} ${c.cyan(billingUrl)}`);
@@ -9730,7 +10195,7 @@ async function plan(o = {}, deps = {}) {
9730
10195
  return 0;
9731
10196
  }
9732
10197
  const dot = c.gray("\xB7");
9733
- const k = await typed(` ${PROMPT()} ${c.bold("Enter")} ${c.gray(`to start ${clean(offer.plan.name, 20)}`)} ${dot} ${c.bold("q")} ${c.gray("not now")} `);
10198
+ const k = await typed(` ${PROMPT()} ${c.bold("Enter")} ${c.gray(`to start ${clean(offer.plan.name, 20)}`)} ${dot} ${c.bold("q")} ${c.gray("stop")} `);
9734
10199
  if (k === null || k !== "") {
9735
10200
  out();
9736
10201
  return 0;
@@ -9739,17 +10204,6 @@ async function plan(o = {}, deps = {}) {
9739
10204
  out();
9740
10205
  return 0;
9741
10206
  }
9742
- function upgradeOffer(state, name = null) {
9743
- const base2 = state.account?.offer ?? state.steps?.find((x) => x.id === "plan")?.offer ?? null;
9744
- if (!base2) return null;
9745
- const mine = (state.projects ?? []).filter((p) => p.plan && !p.shared);
9746
- if (!mine.length) return base2.project ? base2 : (state.projects ?? []).some((p) => p.plan) ? null : base2;
9747
- const named = name ? mine.find((p) => p.id === name || p.name.toLowerCase() === String(name).toLowerCase()) : null;
9748
- const here = mine.find((p) => p.token === state.app?.token) ?? null;
9749
- const target = named ?? here ?? mine.find((p) => p.needsPlan) ?? mine.find((p) => p.plan.id === "free" && !p.plan.source) ?? null;
9750
- if (!target || target.plan.id !== "free" || target.plan.source || !target.planUrl) return null;
9751
- return { ...base2, checkoutUrl: `${target.planUrl}&from=cli`, project: { id: target.id, name: target.name, token: target.token }, needs: target.needsPlan === true };
9752
- }
9753
10207
  async function freeLine(o = {}, deps = {}) {
9754
10208
  let state;
9755
10209
  try {
@@ -9758,10 +10212,17 @@ async function freeLine(o = {}, deps = {}) {
9758
10212
  return false;
9759
10213
  }
9760
10214
  if (!state.signedIn) return false;
9761
- const offer = upgradeOffer(state);
9762
- if (!offer) return false;
9763
- const lim = freeWords(offer.free);
9764
- const [first = "", ...rest] = wrap2(`You are on Free, which has limits${lim ? ` (${lim})` : ""}. ${clean(offer.plan.name, 20)} has none, ${offer.trialDays ? `${offer.trialDays} days free, then ${clean(offer.price, 40)}` : `for ${clean(offer.price, 40)}`}. Upgrade now: npx genclass upgrade`, width() - 6);
10215
+ const cli = state.account?.cli ?? null;
10216
+ const offer = cli?.paid ? null : state.account?.offer ?? upgradeOffer(state);
10217
+ if (!offer && !(cli && !cli.paid)) return false;
10218
+ const lim = offer ? freeWords(offer.free) : "";
10219
+ const name = clean(cli && !cli.paid ? cli.plan : offer.plan.name, 20);
10220
+ const price = clean((cli && !cli.paid ? cli.price : null) ?? offer?.price ?? "", 40);
10221
+ const days = cli && !cli.paid ? cli.trialDays : offer?.trialDays;
10222
+ const [first = "", ...rest] = wrap2(
10223
+ cli && !cli.paid ? `You are on Free${lim ? ` (${lim})` : ""}, on the website. Every genclass command comes with ${name}, ${days ? `${days} days free, then ${price}` : price}. Start it: npx genclass upgrade` : `You are on Free, which has limits${lim ? ` (${lim})` : ""}. ${name} has everything, ${days ? `${days} days free, then ${price}` : `for ${price}`}. Upgrade now: npx genclass upgrade`,
10224
+ width() - 6
10225
+ );
9765
10226
  out();
9766
10227
  out(` ${c.yellow(sym.warn)} ${c.bold(first)}`);
9767
10228
  for (const l of rest) out(` ${l}`);
@@ -9771,18 +10232,47 @@ async function upgrade(o = {}, deps = {}) {
9771
10232
  const s = await signedIn(o, deps, "upgrade");
9772
10233
  if ("code" in s) return s.code;
9773
10234
  const { state } = s;
9774
- const offer = upgradeOffer(state, o.app ?? null);
10235
+ const cli = state.account?.cli ?? null;
10236
+ const paywall = await Promise.resolve().then(() => (init_paywall(), paywall_exports));
10237
+ if (cli && !cli.paid) {
10238
+ if (o.json) {
10239
+ out(JSON.stringify(paywall.needsProJson(cli)));
10240
+ return 1;
10241
+ }
10242
+ top(state);
10243
+ const started = await paywall.startPro(cli, state.account?.offer ?? null, { ...o, card: true }, deps);
10244
+ out();
10245
+ return started ? 0 : 1;
10246
+ }
9775
10247
  const billingUrl = state.account?.billingUrl ?? hostUrl("/account/billing");
10248
+ const here = (state.projects ?? []).find((p) => p.token === state.app?.token && p.plan && !p.shared) ?? null;
10249
+ const paying = accountPaid(state.account);
10250
+ const full = paying && here?.needsPlan ? here : null;
10251
+ const offer = paying ? null : upgradeOffer(state, o.app ?? null);
10252
+ const viaTeam = cli?.via === "team" || state.account?.plan?.via === "team";
9776
10253
  if (o.json) {
9777
- out(JSON.stringify({ ok: true, app: offer?.project?.name ?? null, plan: offer?.plan ?? null, price: offer?.price ?? null, url: offer?.checkoutUrl ?? billingUrl }));
10254
+ if (paying) out(JSON.stringify({ ok: true, paid: true, via: viaTeam ? "team" : cli?.via ?? null, plan: state.account?.plan ?? null, app: here?.name ?? null, needs_plan: !!full, ...full ? { error: "the plan covers no more apps: more come with Enterprise, by email", plan_url: full.planUrl } : {}, billing_url: billingUrl }));
10255
+ else out(JSON.stringify({ ok: true, app: offer?.project?.name ?? null, plan: offer?.plan ?? null, price: offer?.price ?? null, url: offer?.checkoutUrl ?? billingUrl }));
9778
10256
  return 0;
9779
10257
  }
9780
10258
  top(state);
10259
+ if (full) {
10260
+ warn(`Your plan covers no more apps, and ${clean(full.name, 30)} is one more. More apps come with Enterprise, by email.`);
10261
+ if (full.planUrl) {
10262
+ out(` ${c.gray("The address, on its plan page:")}`);
10263
+ out(` ${c.cyan(full.planUrl)}`);
10264
+ }
10265
+ out();
10266
+ return 0;
10267
+ }
9781
10268
  if (!offer) {
9782
- const here = (state.projects ?? []).find((p) => p.token === state.app?.token && p.plan);
9783
- if (here && here.plan.id !== "free") good(`${clean(here.name, 30)} is on ${clean(here.plan.name, 20)}.`);
9784
- else note("Nothing to upgrade here: every app of yours has a plan, or genclass.dev sells none here.");
9785
- out(` ${c.gray("Billing, in the browser")} ${c.cyan(billingUrl)}`);
10269
+ if (paying) {
10270
+ good(viaTeam ? "You are on your team's Pro: there is nothing to upgrade." : `You are on ${clean(state.account?.plan?.id !== "free" ? state.account?.plan?.name ?? "Pro" : "Pro", 20)}: there is nothing to upgrade.`);
10271
+ if (!viaTeam) note("More people on it: add seats in Manage billing, on the billing page.");
10272
+ } else if (here && here.plan.id !== "free") good(`${clean(here.name, 30)} is on ${clean(here.plan.name, 20)}.`);
10273
+ else note("Nothing to upgrade here: genclass.dev sells nothing here.");
10274
+ out(` ${c.gray("Billing, in the browser")}`);
10275
+ out(` ${c.cyan(billingUrl)}`);
9786
10276
  out();
9787
10277
  return 0;
9788
10278
  }
@@ -9800,26 +10290,29 @@ async function profile(o = {}, deps = {}) {
9800
10290
  if ("code" in s) return s.code;
9801
10291
  const { state } = s;
9802
10292
  const mine = (state.projects ?? []).filter((p) => p.plan && !p.shared);
9803
- const offer = upgradeOffer(state, o.app ?? null);
10293
+ const cli = state.account?.cli ?? null;
10294
+ const pro = cli && !cli.paid ? cli : null;
10295
+ const offer = pro ? null : upgradeOffer(state, o.app ?? null);
9804
10296
  const billingUrl = state.account?.billingUrl ?? hostUrl("/account/billing");
9805
10297
  const onFree = state.account?.plan?.id === "free" || mine.length > 0 && mine.every((p) => p.plan.id === "free");
9806
10298
  if (o.json) {
9807
- out(JSON.stringify({ ok: true, account: state.account?.label ?? null, plan: state.account?.plan ?? null, apps: mine.map((p) => ({ id: p.id, name: p.name, plan: p.plan, needs_plan: p.needsPlan })), upgrade_url: offer?.checkoutUrl ?? null, billing_url: billingUrl }));
10299
+ out(JSON.stringify({ ok: true, account: state.account?.label ?? null, plan: state.account?.plan ?? null, apps: mine.map((p) => ({ id: p.id, name: p.name, plan: p.plan, needs_plan: p.needsPlan })), upgrade_url: pro?.checkoutUrl ?? offer?.checkoutUrl ?? null, cli: cli ? { paid: cli.paid } : null, billing_url: billingUrl }));
9808
10300
  return 0;
9809
10301
  }
9810
10302
  top(state);
9811
10303
  out(` ${c.bold("Profile")}`);
9812
10304
  row2("Signed in as", clean(state.account?.label ?? "", 60));
9813
- row2("Plan", onFree ? `Free ${c.gray("(limited)")}` : c.bold(clean(state.account?.plan?.name ?? "", 20)));
10305
+ row2("Plan", onFree ? `Free ${c.gray(pro ? "(website only: the genclass command comes with Pro)" : "(limited)")}` : c.bold(clean(state.account?.plan?.name ?? "", 20)));
9814
10306
  if (mine.length) {
9815
10307
  out();
9816
10308
  out(` ${c.bold("Apps and their plans")}`);
9817
10309
  for (const p of mine) {
9818
- const what = p.needsPlan ? c.yellow("needs a plan") : p.plan.id === "free" ? c.gray("Free") : c.bold(clean(p.plan.name, 20));
10310
+ const what = p.needsPlan ? c.yellow("needs a plan") : p.plan.id === "free" ? p.planChosen ? c.gray("Free") : c.yellow("no plan chosen") : c.bold(clean(p.plan.name, 20));
9819
10311
  out(` ${clean(p.name, 24).padEnd(24)} ${what}${p.token === state.app?.token ? c.gray(" this folder") : ""}`);
9820
10312
  }
9821
10313
  }
9822
10314
  const choices = [];
10315
+ if (pro) choices.push([`${pro.trialDays ? `Start the ${pro.trialDays}-day free trial` : `Start ${clean(pro.plan, 20)}`} ${c.gray(clean(pro.price ?? "", 40))}`, "npx genclass upgrade", () => upgrade(o, deps)]);
9823
10316
  if (offer) choices.push([`Upgrade ${offer.project ? clean(offer.project.name, 20) : "to"} ${offer.project ? `to ${clean(offer.plan.name, 20)}` : clean(offer.plan.name, 20)} ${c.gray(clean(offer.price, 40))}`, "npx genclass upgrade", () => upgrade({ ...o, app: offer.project?.id ?? o.app }, deps)]);
9824
10317
  choices.push(["Billing, in the browser", billingUrl, () => openBrowser2(billingUrl, o) ? note("Your browser is opening billing.") : out(` ${c.cyan(billingUrl)}`)]);
9825
10318
  choices.push(["Sign out", "npx genclass logout", async () => (await Promise.resolve().then(() => (init_login(), login_exports))).run("logout", [])]);
@@ -9834,7 +10327,7 @@ async function profile(o = {}, deps = {}) {
9834
10327
  }
9835
10328
  choices.forEach(([label], i) => out(` ${c.gray(String(i + 1).padStart(2))} ${label}`));
9836
10329
  out();
9837
- const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("back")} `);
10330
+ const a = await typed(` ${PROMPT()} ${c.gray("a number \xB7")} ${c.bold("q")} ${c.gray("stop")} `);
9838
10331
  const pick2 = a !== null && /^\d+$/.test(a.trim()) ? choices[Number(a.trim()) - 1] : null;
9839
10332
  if (pick2) {
9840
10333
  const r = await pick2[2]();
@@ -9850,6 +10343,14 @@ async function team(o = {}, deps = {}) {
9850
10343
  const billing = state.account?.billingUrl ?? hostUrl("/account/billing");
9851
10344
  if ((o.args ?? [])[0] === "invite") {
9852
10345
  const r = await asking(o, creds, (cr) => createInvite(cr, deps), deps);
10346
+ if (!r.ok && r.upgradeUrl && !r.needsPro && accountPaid(state.account)) {
10347
+ if (o.json) out(JSON.stringify({ ok: false, error: "every seat is taken: add seats in Manage billing", billing_url: billing }));
10348
+ else {
10349
+ top(state);
10350
+ seatsFull(billing);
10351
+ }
10352
+ return 1;
10353
+ }
9853
10354
  if (!r.ok) {
9854
10355
  if (!o.json) top(state);
9855
10356
  return refused2(r, { what: "A team", command: "team invite", browserUrl: billing, json: o.json });
@@ -9881,10 +10382,11 @@ async function team(o = {}, deps = {}) {
9881
10382
  for (const i of t.invites) out(` ${c.gray(`an invite link is open${i.expires ? ` until ${day2(i.expires)}` : ""}`)}`);
9882
10383
  for (const m of t.memberships) out(` ${c.gray("You are also in the team of")} ${clean(m.label, 50)}${m.active ? "" : c.gray(" (not active)")}`);
9883
10384
  out();
9884
- if (t.seats !== null && t.seats <= 1) {
10385
+ if (t.seats !== null && t.seats <= t.used && (a.access === "paid" || a.plan.id !== "free")) seatsFull(billing, t.seats);
10386
+ else if (t.seats !== null && t.seats <= 1) {
9885
10387
  out(` ${c.bold(`${clean(a.plan.name, 20)} is for one person.`)}`);
9886
10388
  note("A team comes with Pro: everyone you invite opens the same dashboards.");
9887
- out(` ${c.cyan("npx genclass plan")}`);
10389
+ out(` ${c.cyan("npx genclass upgrade")}`);
9888
10390
  } else {
9889
10391
  out(` ${c.gray("Invite someone:")} ${c.cyan("npx genclass team invite")}`);
9890
10392
  out(` ${c.gray(t.seats === null ? "Remove someone or change your plan, in the browser:" : "Remove someone or add seats, in the browser:")}`);
@@ -9893,6 +10395,11 @@ async function team(o = {}, deps = {}) {
9893
10395
  out();
9894
10396
  return 0;
9895
10397
  }
10398
+ function seatsFull(billing, seats = null) {
10399
+ out(` ${c.bold(seats === 1 ? "Your plan has one seat, yours." : "Every seat of your plan is taken.")}`);
10400
+ note("Add seats in Manage billing, then invite your team: npx genclass team invite");
10401
+ out(` ${c.cyan(billing)}`);
10402
+ }
9896
10403
  async function connections(o = {}, deps = {}) {
9897
10404
  const picked = await pickApp(o, deps, ["connections", ...o.args ?? []].join(" "));
9898
10405
  if ("code" in picked) return picked.code;
@@ -9982,6 +10489,10 @@ async function connections(o = {}, deps = {}) {
9982
10489
  const here = state.app.token === target.token;
9983
10490
  const agentHere = here ? agentSetup(state.cwd, deps.home) : null;
9984
10491
  const gh = here ? state.steps.find((x) => x.id === "github-app") : null;
10492
+ if (!r.ok && r.needsPro) {
10493
+ if (!o.json) top(state, target);
10494
+ return refused2(r, { what: "Alerts", command: "connections", json: o.json });
10495
+ }
9985
10496
  if (o.json) {
9986
10497
  out(JSON.stringify({ ok: true, app: target.name, alerts: r.ok ? { in_plan: r.forwarding, destinations: r.list } : { error: r.reauth ? "sign in again" : r.reason }, private_link: r.ok ? r.privateLink : null, github_app: gh ? { state: gh.state, detail: gh.detail ?? null } : null, coding_agent: agentHere }, null, 2));
9987
10498
  return 0;
@@ -10241,9 +10752,9 @@ var init_manage = __esm({
10241
10752
  out(` ${c.gray(label.padEnd(w))}${first}`);
10242
10753
  for (const l of rest) out(` ${" ".repeat(w)}${l}`);
10243
10754
  };
10244
- top = (state, target = null) => header({ app: target?.name ?? state.app.name, framework: !target || state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
10755
+ top = (state, target = null) => header({ app: target?.name ?? state.app.name, framework: !target || state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: planName(state), host: state.host });
10245
10756
  day2 = (iso) => String(iso ?? "").slice(0, 10);
10246
- freeWords = (free) => [free?.apps ? `${free.apps} apps` : null, free?.liveFixes ? `${free.liveFixes} live fixes a month` : null, free?.historyDays ? `${free.historyDays} days of history` : null].filter(Boolean).join(", ");
10757
+ freeWords = (free) => [free?.apps ? `${free.apps} app${free.apps === 1 ? "" : "s"}` : null, free?.liveFixes ? `${free.liveFixes} live fixes a month` : null, free?.historyDays ? `${free.historyDays} days of history` : null].filter(Boolean).join(", ");
10247
10758
  DESTINATIONS = {
10248
10759
  slack: ["Slack", [["url", "Slack incoming webhook URL", true]]],
10249
10760
  sentry: ["Sentry", [["dsn", "Sentry DSN (Client Keys page)", true]]],
@@ -10310,7 +10821,9 @@ async function ask2(o = {}, deps = {}) {
10310
10821
  if ("code" in picked) return picked.code;
10311
10822
  const { state, creds, target } = picked;
10312
10823
  const range = ["24h", "7d", "30d", "90d", "1y"].includes(o.range) ? o.range : "7d";
10313
- if (!o.json) header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: state.account?.plan?.name, host: state.host });
10824
+ if (!o.json) header({ app: target.name, framework: state.app.token === target.token ? state.app.framework : null, account: state.account?.label, plan: planName(state, target.token), host: state.host });
10825
+ const cli = state.account?.cli ?? null;
10826
+ if (cli && !cli.paid) return refused2({ ok: false, needsPro: cli }, { what: "A question to the model", command: "ask", json: o.json });
10314
10827
  const prefs = (deps.readPrefs ?? readPrefs)();
10315
10828
  if (!prefs.askTold) {
10316
10829
  const told = "Your question goes to GenClass's model on genclass.dev, with this app's dashboard numbers: pages, kinds of problem and counts, and with visitor analytics the sources and the names of what people click. The model is OpenAI's. No code leaves your machine, and neither the question nor the answer is stored.";
@@ -10360,6 +10873,7 @@ var turns, forget;
10360
10873
  var init_ask = __esm({
10361
10874
  "src/ask.mjs"() {
10362
10875
  init_define_GENCLASS_BUILD();
10876
+ init_state();
10363
10877
  init_ui();
10364
10878
  init_api();
10365
10879
  init_app();
@@ -10381,8 +10895,8 @@ __export(setup_exports, {
10381
10895
  });
10382
10896
  import { join as join17, resolve as resolve11 } from "node:path";
10383
10897
  function show(state, details = false, welcome = false) {
10384
- const h = { app: state.app.name, framework: state.app.framework, account: state.account?.label ?? null, plan: state.account?.plan?.name ?? null, host: state.host };
10385
- if (welcome && canDraw()) card({ ...h, cwd: state.cwd, version: BUILD.version });
10898
+ const h = { app: state.app.name, framework: state.app.framework, account: state.account?.label ?? null, plan: planName(state), host: state.host };
10899
+ if (welcome && canDraw() && !homeOpen()) card({ ...h, cwd: state.cwd, version: BUILD.version });
10386
10900
  else header(h);
10387
10901
  if (details) checklist(state.steps);
10388
10902
  else summary(state.steps);
@@ -10437,9 +10951,9 @@ function closing(state) {
10437
10951
  }
10438
10952
  out();
10439
10953
  out(` ${c.gray("Day to day")}`);
10440
- out(` ${c.cyan("npx genclass".padEnd(23))}${c.gray("where things stand")}`);
10441
- out(` ${c.cyan("npx genclass suggest".padEnd(23))}${c.gray("what your app is missing")}`);
10442
- if (state.app.token) out(` ${c.cyan("npx genclass dashboard".padEnd(23))}${c.gray("what it found on your site")}`);
10954
+ out(` ${c.cyan("npx genclass".padEnd(25))}${c.gray("where things stand")}`);
10955
+ out(` ${c.cyan("npx genclass suggest".padEnd(25))}${c.gray("what your app is missing")}`);
10956
+ if (state.app.token) out(` ${c.cyan("npx genclass dashboard".padEnd(25))}${c.gray("what it found on your site")}`);
10443
10957
  out();
10444
10958
  }
10445
10959
  async function status(o = {}) {
@@ -10489,7 +11003,7 @@ async function walk(o, deps, auto) {
10489
11003
  show(state, details, !auto && !welcomed);
10490
11004
  welcomed = true;
10491
11005
  if (!step) break;
10492
- if (step.id === "plan" && !auto) {
11006
+ if ((step.id === "plan" || step.id === "app-plan") && !auto) {
10493
11007
  go = true;
10494
11008
  break;
10495
11009
  }
@@ -10498,7 +11012,7 @@ async function walk(o, deps, auto) {
10498
11012
  if (auto) break;
10499
11013
  const dot = c.gray("\xB7");
10500
11014
  rule();
10501
- const keys = ` ${PROMPT()} ${c.bold("Enter")} ${c.gray("to continue")} ${dot} ${c.bold("d")} ${c.gray(details ? "less" : "every part")} ${dot} ${c.bold("s")} ${c.gray("skip")} ${dot} ${c.bold("q")} ${c.gray(o.home !== false && deps.home ? "later" : "stop")} `;
11015
+ const keys = ` ${PROMPT()} ${c.bold("Enter")} ${c.gray("to continue")} ${dot} ${c.bold("d")} ${c.gray(details ? "less" : "every part")} ${dot} ${c.bold("s")} ${c.gray("skip")} ${dot} ${c.bold("q")} ${c.gray("stop")} `;
10502
11016
  const a = await typed(keys) ?? "q";
10503
11017
  if (/^d/i.test(a)) {
10504
11018
  details = !details;
@@ -10507,7 +11021,7 @@ async function walk(o, deps, auto) {
10507
11021
  if (/^q/i.test(a)) {
10508
11022
  if (o.home !== false && deps.home) {
10509
11023
  out();
10510
- note("The setup waits here: setup continues it.");
11024
+ note("Setup stopped here. Type setup to go on with it.");
10511
11025
  return deps.home({ ...o, cwd: state.cwd, app: state.app.name ?? "" });
10512
11026
  }
10513
11027
  out();
@@ -10537,13 +11051,13 @@ async function walk(o, deps, auto) {
10537
11051
  const so = { ...o, confirmed: true };
10538
11052
  let result = "skipped";
10539
11053
  if (step.id === "account") result = await signIn(so);
10540
- else if (step.id === "plan") {
10541
- result = await choosePlan(state, so);
11054
+ else if (step.id === "plan" || step.id === "app-plan") {
11055
+ result = step.id === "plan" ? await choosePlan(state, so) : await chooseAppPlan(state, so);
10542
11056
  if (result === "quit") {
10543
11057
  out();
10544
- note("Stopped. Run npx genclass again any time: it continues from here.");
11058
+ if (!auto) note("Stopped. Run npx genclass again any time: it continues from here.");
10545
11059
  out();
10546
- return 0;
11060
+ return auto ? 1 : 0;
10547
11061
  }
10548
11062
  } else if (step.id === "runtime") result = await addRuntime(state, so);
10549
11063
  else if (step.id === "dashboard") result = await watchFirstPage(state, so);
@@ -10554,7 +11068,7 @@ async function walk(o, deps, auto) {
10554
11068
  if (auto || !deps.runSuggest) {
10555
11069
  note(`Run ${c.cyan("npx genclass suggest")} to see what your app is missing.`);
10556
11070
  result = "skipped";
10557
- } else result = await deps.runSuggest({ cwd: o.cwd, fromSetup: true }) === 0 ? "done" : "failed";
11071
+ } else result = await deps.runSuggest({ cwd: o.cwd, fromSetup: true, paid: state.steps.find((x) => x.id === "plan")?.state === "done" }) === 0 ? "done" : "failed";
10558
11072
  }
10559
11073
  if (result === "failed") {
10560
11074
  failed = true;
@@ -10723,7 +11237,7 @@ var init_home = __esm({
10723
11237
  ["scan <url>", "check one page", false],
10724
11238
  ["apps", "the apps in your account", false],
10725
11239
  ["plan", "your plan and what it includes", false],
10726
- ["upgrade", "a paid plan for this app", false],
11240
+ ["upgrade", "start Pro, or see what your plan has", false],
10727
11241
  ["team", "the people on your plan", false],
10728
11242
  ["status", "where the setup stands", false],
10729
11243
  ["setup", "walk the setup again", false],
@@ -10739,10 +11253,12 @@ var init_home = __esm({
10739
11253
  var cli_exports = {};
10740
11254
  __export(cli_exports, {
10741
11255
  COMMANDS: () => COMMANDS2,
11256
+ FREE_COMMANDS: () => FREE_COMMANDS,
10742
11257
  USAGE: () => USAGE4,
10743
11258
  nearest: () => nearest,
10744
11259
  parseArgs: () => parseArgs2,
10745
- run: () => run4
11260
+ run: () => run4,
11261
+ telemetryOnly: () => telemetryOnly
10746
11262
  });
10747
11263
  function parseArgs2(argv) {
10748
11264
  const o = {};
@@ -10763,13 +11279,58 @@ function parseArgs2(argv) {
10763
11279
  async function run4(argv, ctx = {}) {
10764
11280
  const cmd = argv[0] && !argv[0].startsWith("-") ? argv[0] : null;
10765
11281
  const args = cmd ? argv.slice(1) : argv;
11282
+ const asksHelp = args.some((a) => ["--help", "-h", "--version", "-v"].includes(a));
11283
+ const paid = async () => {
11284
+ if (asksHelp || FREE_COMMANDS.includes(cmd)) return 0;
11285
+ const h2 = hostConfig();
11286
+ if (h2.error) {
11287
+ err(`genclass: ${h2.error}`);
11288
+ return 2;
11289
+ }
11290
+ return (await Promise.resolve().then(() => (init_paywall(), paywall_exports))).requirePro(parseArgs2(args).o);
11291
+ };
10766
11292
  if (cmd === "login" && !args.some((a) => a === "--help" || a === "-h")) {
10767
11293
  const again = await (await Promise.resolve().then(() => (init_app(), app_exports))).signInAgain(parseArgs2(args).o);
10768
11294
  if (again !== null) return again;
10769
11295
  }
10770
- if (["login", "logout", "whoami", "connect"].includes(cmd)) return (await Promise.resolve().then(() => (init_login(), login_exports))).run(cmd, args);
11296
+ const i = args.indexOf("--cwd");
11297
+ const po = { cwd: i >= 0 ? args[i + 1] : void 0, yes: args.includes("--yes") || args.includes("-y"), json: args.includes("--json"), noBrowser: args.includes("--no-browser") };
11298
+ const thenPlan = async (code) => {
11299
+ if (code !== 0) return code;
11300
+ await (await Promise.resolve().then(() => (init_actions(), actions_exports))).planNow(po).catch(() => "none");
11301
+ return code;
11302
+ };
11303
+ if (["logout", "whoami"].includes(cmd)) return (await Promise.resolve().then(() => (init_login(), login_exports))).run(cmd, args);
11304
+ if (cmd === "login") {
11305
+ const login2 = await Promise.resolve().then(() => (init_login(), login_exports));
11306
+ const noConnect = args.includes("--no-connect");
11307
+ const code = await login2.run(cmd, noConnect || asksHelp ? args : [...args, "--no-connect"]);
11308
+ if (code !== 0 || asksHelp) return code;
11309
+ if (!await (await Promise.resolve().then(() => (init_paywall(), paywall_exports))).afterLogin(po).catch(() => true)) return code;
11310
+ return thenPlan(noConnect ? code : await login2.offerConnect(args).catch(() => 1));
11311
+ }
10771
11312
  if (cmd === "remove") return (await Promise.resolve().then(() => (init_remove(), remove_exports))).remove(args);
10772
- if (cmd === "init") return (await Promise.resolve().then(() => (init_init(), init_exports))).run(cmd, args);
11313
+ if (["connect", "init", "scan", "audit"].includes(cmd)) {
11314
+ if (!asksHelp && !await argsRight(cmd, args)) {
11315
+ if (cmd === "connect") return (await Promise.resolve().then(() => (init_login(), login_exports))).run(cmd, args);
11316
+ if (cmd === "init") return (await Promise.resolve().then(() => (init_init(), init_exports))).run(cmd, args);
11317
+ return (await Promise.resolve().then(() => (init_scan(), scan_exports))).run(cmd, args);
11318
+ }
11319
+ const optOut = cmd === "init" && telemetryOnly(args) && !(await Promise.resolve().then(() => (init_init(), init_exports))).inspectProject({ cwd: po.cwd }).fresh;
11320
+ const gate = optOut ? 0 : await paid();
11321
+ if (gate !== 0) {
11322
+ if (cmd !== "scan" && cmd !== "audit") return gate;
11323
+ if (!po.json && gate === 1) {
11324
+ const { REPORT_PAGE: REPORT_PAGE2 } = await Promise.resolve().then(() => (init_scan(), scan_exports));
11325
+ out(` ${c.gray("Free, without Pro: the page check on the website")}`);
11326
+ out(` ${c.cyan(REPORT_PAGE2)}`);
11327
+ out();
11328
+ }
11329
+ return 2;
11330
+ }
11331
+ }
11332
+ if (cmd === "connect") return thenPlan(await (await Promise.resolve().then(() => (init_login(), login_exports))).run(cmd, args));
11333
+ if (cmd === "init") return thenPlan(await (await Promise.resolve().then(() => (init_init(), init_exports))).run(cmd, args));
10773
11334
  if (cmd === "scan" || cmd === "audit") {
10774
11335
  const withHost = args.includes("--local") || args.includes("--hosted") || args.includes("--help") ? args : [...args, "--hosted"];
10775
11336
  return (await Promise.resolve().then(() => (init_scan(), scan_exports))).run(cmd, withHost);
@@ -10814,6 +11375,8 @@ ${USAGE4}`);
10814
11375
  ${USAGE4}`);
10815
11376
  return 2;
10816
11377
  }
11378
+ const gate = await paid();
11379
+ if (gate !== 0) return gate;
10817
11380
  return upsold(runSuggest({ ...o, url }));
10818
11381
  }
10819
11382
  if (cmd !== null && !COMMANDS2.includes(cmd)) {
@@ -10833,25 +11396,26 @@ ${USAGE4}`);
10833
11396
  ${USAGE4}`);
10834
11397
  return 2;
10835
11398
  }
10836
- if (cmd === "dashboard") {
10837
- const fallback = async () => (await Promise.resolve().then(() => (init_login(), login_exports))).run("dashboard", [...o.cwd ? ["--cwd", o.cwd] : [], ...o.open ? ["--open"] : []]);
10838
- return upsold((await Promise.resolve().then(() => (init_app(), app_exports))).dashboard(o, { fallback }));
11399
+ const { ANALYTICS_SECTIONS: ANALYTICS_SECTIONS2 } = cmd === "analytics" ? await Promise.resolve().then(() => (init_views(), views_exports)) : { ANALYTICS_SECTIONS: [] };
11400
+ if (cmd === "analytics" && words2[0] && !ANALYTICS_SECTIONS2.includes(words2[0])) {
11401
+ err(`genclass analytics: there is no part ${c.bold(words2[0])}. The parts: ${ANALYTICS_SECTIONS2.join(", ")}`);
11402
+ return 2;
10839
11403
  }
10840
- if (["problems", "events", "health", "report"].includes(cmd)) return upsold((await Promise.resolve().then(() => (init_views(), views_exports)))[cmd](o), cmd !== "report");
10841
- if (cmd === "analytics") {
10842
- const { analytics: analytics2, ANALYTICS_SECTIONS: ANALYTICS_SECTIONS2 } = await Promise.resolve().then(() => (init_views(), views_exports));
10843
- if (words2[0] && !ANALYTICS_SECTIONS2.includes(words2[0])) {
10844
- err(`genclass analytics: there is no part ${c.bold(words2[0])}. The parts: ${ANALYTICS_SECTIONS2.join(", ")}`);
10845
- return 2;
10846
- }
10847
- return upsold(analytics2({ ...o, section: words2[0] ?? null }));
11404
+ if (cmd === "agent" && words2[0] && words2[0] !== "link") {
11405
+ err(`genclass agent: there is no ${c.bold(words2[0])}. Try ${c.cyan("npx genclass agent")} or ${c.cyan("npx genclass agent link")}`);
11406
+ return 2;
11407
+ }
11408
+ const fallback = async () => (await Promise.resolve().then(() => (init_login(), login_exports))).run("dashboard", [...o.cwd ? ["--cwd", o.cwd] : [], ...o.open ? ["--open"] : []]);
11409
+ if (cmd === "dashboard" && !o.json && !o.app && await privateLinkHere(o.cwd)) return fallback();
11410
+ if (cmd !== null && !["setup", "status"].includes(cmd)) {
11411
+ const gate = await paid();
11412
+ if (gate !== 0) return gate;
10848
11413
  }
11414
+ if (cmd === "dashboard") return upsold((await Promise.resolve().then(() => (init_app(), app_exports))).dashboard(o, { fallback }));
11415
+ if (["problems", "events", "health", "report"].includes(cmd)) return upsold((await Promise.resolve().then(() => (init_views(), views_exports)))[cmd](o), cmd !== "report");
11416
+ if (cmd === "analytics") return upsold((await Promise.resolve().then(() => (init_views(), views_exports))).analytics({ ...o, section: words2[0] ?? null }));
10849
11417
  if (cmd === "agent") {
10850
11418
  if (words2[0] === "link") return (await Promise.resolve().then(() => (init_manage(), manage_exports))).agentLink(o);
10851
- if (words2[0]) {
10852
- err(`genclass agent: there is no ${c.bold(words2[0])}. Try ${c.cyan("npx genclass agent")} or ${c.cyan("npx genclass agent link")}`);
10853
- return 2;
10854
- }
10855
11419
  return (await Promise.resolve().then(() => (init_views(), views_exports))).agent(o);
10856
11420
  }
10857
11421
  if (cmd === "fix") return upsold((await Promise.resolve().then(() => (init_fix(), fix_exports))).fix({ ...o, what: words2.join(" ") || null }));
@@ -10867,6 +11431,54 @@ ${USAGE4}`);
10867
11431
  }
10868
11432
  return 2;
10869
11433
  }
11434
+ function telemetryOnly(args) {
11435
+ let toggle = false;
11436
+ for (let i = 0; i < args.length; i++) {
11437
+ const a = args[i];
11438
+ if (a === "--cwd") i++;
11439
+ else if (a.startsWith("--cwd=")) continue;
11440
+ else if (a === "--no-telemetry" || a === "--telemetry") toggle = true;
11441
+ else if (!TOGGLE_WITH.has(a)) return false;
11442
+ }
11443
+ return toggle;
11444
+ }
11445
+ async function argsRight(cmd, args) {
11446
+ try {
11447
+ if (cmd === "init") {
11448
+ const { parse: parse2 } = await Promise.resolve().then(() => (init_init(), init_exports));
11449
+ parse2(args);
11450
+ return true;
11451
+ }
11452
+ if (cmd === "connect") return (await Promise.resolve().then(() => (init_login(), login_exports))).argsError("connect", args) === null;
11453
+ const { normaliseUrl: normaliseUrl2 } = await Promise.resolve().then(() => (init_scan(), scan_exports));
11454
+ const urls = [];
11455
+ for (let i = 0; i < args.length; i++) {
11456
+ const a = args[i];
11457
+ if (["--json", "--phone", "--hosted", "--local"].includes(a) || /^--(timeout|cwd)=./.test(a)) continue;
11458
+ if (a === "--timeout" || a === "--cwd") {
11459
+ if (args[++i] === void 0) return false;
11460
+ continue;
11461
+ }
11462
+ if (a.startsWith("-")) return false;
11463
+ urls.push(a);
11464
+ }
11465
+ if (urls.length !== 1) return false;
11466
+ normaliseUrl2(urls[0]);
11467
+ return true;
11468
+ } catch {
11469
+ return false;
11470
+ }
11471
+ }
11472
+ async function privateLinkHere(cwd) {
11473
+ try {
11474
+ const { readCredentialsFor: readCredentialsFor2 } = await Promise.resolve().then(() => (init_account(), account_exports));
11475
+ if (readCredentialsFor2().creds) return false;
11476
+ const st = (await Promise.resolve().then(() => (init_init(), init_exports))).inspectProject({ cwd });
11477
+ return !!st.local?.dashboardUrl && (!st.token || st.local.token === st.token);
11478
+ } catch {
11479
+ return false;
11480
+ }
11481
+ }
10870
11482
  function nearest(word) {
10871
11483
  const w = String(word).toLowerCase();
10872
11484
  let best = null;
@@ -10889,7 +11501,7 @@ function edits(a, b) {
10889
11501
  }
10890
11502
  return row3[b.length];
10891
11503
  }
10892
- var USAGE4, BOOL2, VALUE2, COMMANDS2;
11504
+ var USAGE4, BOOL2, VALUE2, TOGGLE_WITH, FREE_COMMANDS, COMMANDS2;
10893
11505
  var init_cli = __esm({
10894
11506
  "src/cli.mjs"() {
10895
11507
  init_define_GENCLASS_BUILD();
@@ -10898,6 +11510,10 @@ var init_cli = __esm({
10898
11510
  init_assets();
10899
11511
  USAGE4 = `genclass: GenClass in your terminal. Set it up, see what it finds, have it fixed.
10900
11512
 
11513
+ The genclass command comes with Pro: 3 days free, then US$15 a developer a month, with a card
11514
+ on Stripe. Without Pro: login, logout, whoami, status, plan, upgrade, profile, remove, help.
11515
+ Free is on the website: https://genclass.dev
11516
+
10901
11517
  npx genclass where this project stands; on a terminal it walks you through the
10902
11518
  next step, then stays open for commands and questions
10903
11519
  npx genclass setup the guided setup (--yes: no questions, for a coding agent)
@@ -10929,7 +11545,9 @@ var init_cli = __esm({
10929
11545
 
10930
11546
  Account
10931
11547
  npx genclass apps your apps (apps new "Name")
10932
- npx genclass plan your plan, its limits and what is used; start the paid plan (--open)
11548
+ npx genclass plan your plan, its limits and what is used (--open: billing in the browser)
11549
+ npx genclass upgrade start Pro (its free trial first), in the browser
11550
+ npx genclass profile your account and plan, as numbered choices
10933
11551
  npx genclass team who is on the plan (team invite)
10934
11552
  npx genclass login sign in (logout, whoami)
10935
11553
  npx genclass remove take GenClass out of this app again
@@ -10941,6 +11559,8 @@ var init_cli = __esm({
10941
11559
  Every part GenClass sets up is listed by "npx genclass status --all". Docs: https://genclass.dev/docs/cli`;
10942
11560
  BOOL2 = { yes: "yes", y: "yes", json: "json", "no-browser": "noBrowser", "no-model": "noModel", all: "all", help: "help", h: "help", version: "version", v: "version", open: "open", print: "print", copy: "copy" };
10943
11561
  VALUE2 = { cwd: "cwd", url: "url", app: "app", range: "range", from: "from", to: "to", format: "format", out: "out", agent: "agent" };
11562
+ TOGGLE_WITH = /* @__PURE__ */ new Set(["--yes", "-y", "--dry-run", "--no-install", "--no-network"]);
11563
+ FREE_COMMANDS = ["login", "logout", "whoami", "plan", "upgrade", "profile", "status", "remove", "help", "version"];
10944
11564
  COMMANDS2 = [
10945
11565
  "setup",
10946
11566
  "status",