@puckeditor/cli 0.24.0-canary.55558da4 → 0.24.0-canary.b7903763

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/README.md CHANGED
@@ -20,14 +20,18 @@ Other commands:
20
20
  npx @puckeditor/cli add editor # add the Puck editor
21
21
  npx @puckeditor/cli add cloud # connect Puck Cloud
22
22
  npx @puckeditor/cli add ai # add the Puck AI plugin
23
+ npx @puckeditor/cli connect # log in to Puck Cloud again for a new API key
23
24
  npx @puckeditor/cli status # show what's set up
24
25
  npx @puckeditor/cli doctor # diagnose problems
25
26
  npx @puckeditor/cli frameworks # show supported frameworks and versions
26
27
  npx @puckeditor/cli docs # read the docs for this version
28
+ npx @puckeditor/cli telemetry # show or change anonymous usage data collection
27
29
  ```
28
30
 
29
31
  See the [CLI docs](https://puckeditor.com/docs/cli) for the full JSON contract, actions and exit codes.
30
32
 
33
+ The CLI collects anonymous usage data. See [Telemetry](https://puckeditor.com/docs/cli#telemetry) for what's sent and how to turn it off.
34
+
31
35
  ## Development
32
36
 
33
37
  The CLI integrates Puck using the [recipes](../../recipes) as templates. Tests read the recipes directly, and `pnpm build` copies them into `dist/templates`.
@@ -39,7 +43,7 @@ pnpm build
39
43
  node dist/bin.mjs status
40
44
  ```
41
45
 
42
- Set `PUCK_CLOUD_URL` to point the CLI at a local Puck Cloud.
46
+ Set `PUCK_CLOUD_URL` to point the CLI at a local Puck Cloud. Telemetry goes there too. Set `PUCK_TELEMETRY_DEBUG=1` to print events to stderr instead of sending them.
43
47
 
44
48
  ## License
45
49
 
package/dist/bin.mjs CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  // src/bin.ts
4
4
  import os from "os";
5
- import path30 from "path";
6
- import fs7 from "fs";
5
+ import path33 from "path";
6
+ import fs8 from "fs";
7
7
  import { fileURLToPath } from "url";
8
8
 
9
9
  // src/errors.ts
@@ -38,6 +38,7 @@ var exitCodeByError = {
38
38
  "PUCK-CLI-FRAMEWORK-MISMATCH": EXIT_CODES.unsupported,
39
39
  "PUCK-CLI-BACKEND-REQUIRED": EXIT_CODES.usage,
40
40
  "PUCK-CLI-BACKEND-URL-REQUIRED": EXIT_CODES.usage,
41
+ "PUCK-CLI-EXTERNAL-BACKEND": EXIT_CODES.unsupported,
41
42
  "PUCK-CLI-WORKSPACE-TARGET-NOT-FOUND": EXIT_CODES.unsupported,
42
43
  "PUCK-CLI-TYPESCRIPT-REQUIRED": EXIT_CODES.unsupported,
43
44
  "PUCK-CLI-TARGET-DIR-NOT-EMPTY": EXIT_CODES.filesystem,
@@ -67,9 +68,6 @@ var CliError = class extends Error {
67
68
  // src/args.ts
68
69
  import { parseArgs } from "util";
69
70
 
70
- // src/detect/framework.ts
71
- import path3 from "path";
72
-
73
71
  // src/constants.ts
74
72
  var ENV_KEY = "PUCK_API_KEY";
75
73
  var DEFAULT_CLOUD_URL = "https://cloud.puckeditor.com";
@@ -82,6 +80,9 @@ var CLOUD_CLIENT_PACKAGE = "@puckeditor/cloud-client";
82
80
  var PLUGIN_AI_PACKAGE = "@puckeditor/plugin-ai";
83
81
  var CANONICAL_INVOCATION = "npx @puckeditor/cli";
84
82
 
83
+ // src/detect/framework.ts
84
+ import path3 from "path";
85
+
85
86
  // src/ast/parse.ts
86
87
  import { parse } from "@babel/parser";
87
88
  var isTsx = (filename) => /\.(tsx|jsx|js|mjs|cjs)$/.test(filename);
@@ -301,21 +302,21 @@ var MIN_VERSIONS = {
301
302
  express: "4.16"
302
303
  };
303
304
  var SUPPORTED_FRAMEWORKS = "Next.js (App Router), React Router 7 framework mode, TanStack Start, vinext, Astro and Vite React apps, or a Hono or Express server";
304
- var unsupportedVersion = (id, version, range) => {
305
+ var unsupportedVersion = (id2, version, range) => {
305
306
  const found = versionOf(version) ?? versionOf(range);
306
- const [major, minor] = versionOf(MIN_VERSIONS[id]);
307
- if (!found || found[0] > major || found[0] === major && found[1] >= minor)
307
+ const [major2, minor] = versionOf(MIN_VERSIONS[id2]);
308
+ if (!found || found[0] > major2 || found[0] === major2 && found[1] >= minor)
308
309
  return null;
309
- const label2 = FRAMEWORK_LABELS[id];
310
+ const label2 = FRAMEWORK_LABELS[id2];
310
311
  return {
311
312
  status: "unsupported",
312
313
  error: {
313
314
  code: "PUCK-CLI-UNSUPPORTED-FRAMEWORK-VERSION",
314
- message: `${label2} ${version ?? range} is not supported. Upgrade to ${label2} ${MIN_VERSIONS[id]} or later, or integrate Puck manually.`,
315
+ message: `${label2} ${version ?? range} is not supported. Upgrade to ${label2} ${MIN_VERSIONS[id2]} or later, or integrate Puck manually.`,
315
316
  details: {
316
317
  docs: MANUAL_INTEGRATION_DOCS_URL,
317
318
  version: version ?? range,
318
- minVersion: MIN_VERSIONS[id]
319
+ minVersion: MIN_VERSIONS[id2]
319
320
  }
320
321
  }
321
322
  };
@@ -371,7 +372,7 @@ var detectAppRouter = (vfs, root, label2) => {
371
372
  };
372
373
  var detectNext = (vfs, root, range) => {
373
374
  const version = resolveInstalledVersion(vfs, root, "next");
374
- const major = majorOf(version) ?? majorOf(range) ?? 16;
375
+ const major2 = majorOf(version) ?? majorOf(range) ?? 16;
375
376
  const layout = detectAppRouter(vfs, root, "Next.js");
376
377
  if ("status" in layout) return layout;
377
378
  const tooOld = unsupportedVersion("next", version, range);
@@ -381,9 +382,9 @@ var detectNext = (vfs, root, range) => {
381
382
  info: {
382
383
  id: "next",
383
384
  version,
384
- major,
385
+ major: major2,
385
386
  ...layout,
386
- proxyKind: major >= 16 ? "proxy" : "middleware"
387
+ proxyKind: major2 >= 16 ? "proxy" : "middleware"
387
388
  }
388
389
  };
389
390
  };
@@ -411,7 +412,7 @@ var detectVinext = (vfs, root, range) => {
411
412
  };
412
413
  var detectReactRouter = (vfs, root, range) => {
413
414
  const version = resolveInstalledVersion(vfs, root, "@react-router/dev") ?? resolveInstalledVersion(vfs, root, "react-router");
414
- const major = majorOf(version) ?? majorOf(range);
415
+ const major2 = majorOf(version) ?? majorOf(range);
415
416
  const tooOld = unsupportedVersion("react-router", version, range);
416
417
  if (tooOld) return tooOld;
417
418
  const configFile = firstExisting(
@@ -464,7 +465,7 @@ var detectReactRouter = (vfs, root, range) => {
464
465
  info: {
465
466
  id: "react-router",
466
467
  version,
467
- major,
468
+ major: major2,
468
469
  appDir,
469
470
  routesFile,
470
471
  configFile,
@@ -573,14 +574,14 @@ var detectAstro = (vfs, root, range, deps) => {
573
574
  }
574
575
  };
575
576
  };
576
- var detectServer = (id) => (vfs, root, range, deps) => {
577
- const version = resolveInstalledVersion(vfs, root, id);
578
- const tooOld = unsupportedVersion(id, version, range);
577
+ var detectServer = (id2) => (vfs, root, range, deps) => {
578
+ const version = resolveInstalledVersion(vfs, root, id2);
579
+ const tooOld = unsupportedVersion(id2, version, range);
579
580
  if (tooOld) return tooOld;
580
581
  return {
581
582
  status: "detected",
582
583
  info: {
583
- id,
584
+ id: id2,
584
585
  version,
585
586
  major: majorOf(version) ?? majorOf(range),
586
587
  entry: findServerEntry(vfs, root),
@@ -799,19 +800,23 @@ var MUTATING = [
799
800
  var COMMAND_OPTIONS = {
800
801
  init: [...GLOBAL, ...MUTATING, "framework", "name", "ai", "no-ai"],
801
802
  add: [...GLOBAL, ...MUTATING],
803
+ connect: [...GLOBAL, "api-key", "config", "wait"],
802
804
  status: ["json", "help", "version", "cwd", "workspace", "config"],
803
805
  doctor: ["json", "help", "version", "cwd", "workspace", "config", "offline"],
804
806
  docs: ["json", "help", "version"],
805
807
  frameworks: ["json", "help", "version"],
808
+ telemetry: ["json", "help", "version"],
806
809
  help: GLOBAL
807
810
  };
808
811
  var COMMANDS = [
809
812
  "init",
810
813
  "add",
814
+ "connect",
811
815
  "status",
812
816
  "doctor",
813
817
  "docs",
814
818
  "frameworks",
819
+ "telemetry",
815
820
  "help"
816
821
  ];
817
822
  var FRAMEWORKS = FRAMEWORK_IDS;
@@ -836,7 +841,7 @@ var parseCliArgs = (argv) => {
836
841
  if (!COMMANDS.includes(first)) {
837
842
  throw new CliError(
838
843
  "PUCK-CLI-UNKNOWN-COMMAND",
839
- `Unknown command "${first}". Run \`puck --help\` to see available commands.`
844
+ `Unknown command "${first}". Run \`${CANONICAL_INVOCATION} --help\` to see available commands.`
840
845
  );
841
846
  }
842
847
  command = first;
@@ -847,7 +852,7 @@ var parseCliArgs = (argv) => {
847
852
  if (!allowed.includes(key)) {
848
853
  throw new CliError(
849
854
  "PUCK-CLI-INVALID-ARGS",
850
- `--${key} can't be used with \`${command ?? "puck"}\`.`
855
+ `--${key} can't be used with \`${command ?? CANONICAL_INVOCATION}\`.`
851
856
  );
852
857
  }
853
858
  }
@@ -1090,15 +1095,16 @@ var createCloudApi = (baseUrl, fetchImpl) => {
1090
1095
  };
1091
1096
  };
1092
1097
 
1098
+ // src/env/truthy.ts
1099
+ var isTruthyEnv = (value) => value !== void 0 && value !== "" && value !== "0" && value.toLowerCase() !== "false";
1100
+
1093
1101
  // src/context.ts
1094
- var isCI = (env2) => {
1095
- const ci = env2.CI;
1096
- return ci !== void 0 && ci !== "" && ci !== "0" && ci.toLowerCase() !== "false";
1097
- };
1098
- var createRunContext = (deps, flags, argv) => {
1102
+ var isCI = (env2) => isTruthyEnv(env2.CI);
1103
+ var cloudBaseUrl = (env2) => env2.PUCK_CLOUD_URL || DEFAULT_CLOUD_URL;
1104
+ var createRunContext = (deps, flags, argv, telemetry) => {
1099
1105
  const interactive = !flags.yes && !flags.json && deps.stdinIsTTY && Boolean(deps.stdout.isTTY) && !isCI(deps.env);
1100
1106
  const secrets = new SecretRegistry();
1101
- const baseUrl = deps.env.PUCK_CLOUD_URL || DEFAULT_CLOUD_URL;
1107
+ const baseUrl = cloudBaseUrl(deps.env);
1102
1108
  return {
1103
1109
  deps,
1104
1110
  flags,
@@ -1107,6 +1113,7 @@ var createRunContext = (deps, flags, argv) => {
1107
1113
  prompter: interactive ? deps.createPrompter() : nonInteractivePrompter,
1108
1114
  secrets,
1109
1115
  cloud: createCloudApi(baseUrl, deps.fetch),
1116
+ telemetry,
1110
1117
  log: (line) => {
1111
1118
  if (!flags.json) deps.stderr.write(secrets.scrub(line) + "\n");
1112
1119
  }
@@ -1156,6 +1163,10 @@ var COMMANDS2 = [
1156
1163
  name: "add <editor|cloud|ai>",
1157
1164
  description: "Add one capability (ai includes cloud, cloud includes editor)"
1158
1165
  },
1166
+ {
1167
+ name: "connect",
1168
+ description: "Log in to Puck Cloud again and replace PUCK_API_KEY"
1169
+ },
1159
1170
  { name: "status", description: "Show what's installed and configured" },
1160
1171
  {
1161
1172
  name: "doctor",
@@ -1168,6 +1179,10 @@ var COMMANDS2 = [
1168
1179
  {
1169
1180
  name: "docs <command>",
1170
1181
  description: "Read the docs for this version: ls, cat <page>, find <query>, grep <text>"
1182
+ },
1183
+ {
1184
+ name: "telemetry [status|enable|disable]",
1185
+ description: "Show or change anonymous usage data collection"
1171
1186
  }
1172
1187
  ];
1173
1188
  var HELP_TEXT = `Puck CLI: set up Puck and Puck Cloud.
@@ -1504,7 +1519,8 @@ var templates_default = {
1504
1519
  "*.tsbuildinfo",
1505
1520
  "eslint.config.mjs",
1506
1521
  ".env*"
1507
- ]
1522
+ ],
1523
+ allowBuilds: ["esbuild"]
1508
1524
  };
1509
1525
 
1510
1526
  // src/templates/source.ts
@@ -2550,10 +2566,10 @@ var analyzeRoutes = (code, filename) => {
2550
2566
  const topLevel = new Set(exported.elements.filter(Boolean));
2551
2567
  walk(exported, (node) => {
2552
2568
  if (!isRouteCall(node, routeLocal)) return;
2553
- const path31 = stringArg(node, 0);
2569
+ const path34 = stringArg(node, 0);
2554
2570
  const isTop = topLevel.has(node);
2555
- calls.push({ path: path31, file: stringArg(node, 1), topLevel: isTop });
2556
- if (path31 === "*") {
2571
+ calls.push({ path: path34, file: stringArg(node, 1), topLevel: isTop });
2572
+ if (path34 === "*") {
2557
2573
  if (isTop) splat = node;
2558
2574
  else nestedSplat = true;
2559
2575
  }
@@ -3050,7 +3066,7 @@ var locate = (info) => (from) => {
3050
3066
  };
3051
3067
  var tanstackRelocation = (p, info) => {
3052
3068
  const to = locate(info);
3053
- const moduleId = (id) => to(`${id}.ts`).replace(/\.ts$/, "");
3069
+ const moduleId = (id2) => to(`${id2}.ts`).replace(/\.ts$/, "");
3054
3070
  return {
3055
3071
  moduleMap: {
3056
3072
  "src/lib/pages": moduleId("src/lib/pages"),
@@ -3477,9 +3493,9 @@ var planEnvLoading = (p, info) => {
3477
3493
  }
3478
3494
  );
3479
3495
  };
3480
- var serverPlanner = (id) => {
3481
- const recipe = id;
3482
- const aiRecipe = `${id}-ai`;
3496
+ var serverPlanner = (id2) => {
3497
+ const recipe = id2;
3498
+ const aiRecipe = `${id2}-ai`;
3483
3499
  const planEditor = (p, info) => {
3484
3500
  const dir = puckDir(p.vfs, p.ctx.root, info);
3485
3501
  const file = `${dir}/pages.ts`;
@@ -3730,7 +3746,7 @@ var SERVER_DEV_PACKAGES = [
3730
3746
  var locate2 = (info) => (from) => from.startsWith("src/") ? path12.posix.join(info.srcDir || ".", from.slice(4)) : from;
3731
3747
  var viteRelocation = (p, info) => {
3732
3748
  const to = locate2(info);
3733
- const moduleId = (id) => to(`${id}.ts`).replace(/\.ts$/, "");
3749
+ const moduleId = (id2) => to(`${id2}.ts`).replace(/\.ts$/, "");
3734
3750
  return {
3735
3751
  moduleMap: {
3736
3752
  "src/puck/pages": moduleId("src/puck/pages"),
@@ -4843,7 +4859,7 @@ var presentHuman = (out, result, secrets) => {
4843
4859
  };
4844
4860
 
4845
4861
  // src/commands/init.ts
4846
- import path27 from "path";
4862
+ import path28 from "path";
4847
4863
 
4848
4864
  // src/io/vfs.ts
4849
4865
  import fs2 from "fs";
@@ -5092,14 +5108,23 @@ var WORKSPACE_PROTOCOL = /^workspace:/;
5092
5108
  var transformPackageJson = (text, { appName, cliVersion }) => {
5093
5109
  const pkg = JSON.parse(text);
5094
5110
  pkg.name = appName;
5111
+ const pinned = [];
5095
5112
  for (const field of ["dependencies", "devDependencies"]) {
5096
5113
  const deps = pkg[field];
5097
5114
  if (!deps) continue;
5098
5115
  delete deps["eslint-config-custom"];
5099
5116
  for (const [name, range] of Object.entries(deps)) {
5100
- if (WORKSPACE_PROTOCOL.test(range)) deps[name] = `^${cliVersion}`;
5117
+ if (!WORKSPACE_PROTOCOL.test(range)) continue;
5118
+ deps[name] = `^${cliVersion}`;
5119
+ pinned.push(name);
5101
5120
  }
5102
5121
  }
5122
+ if (cliVersion.includes("-") && pinned.length > 0) {
5123
+ pkg.overrides = {
5124
+ ...pkg.overrides,
5125
+ ...Object.fromEntries(pinned.map((name) => [name, `$${name}`]))
5126
+ };
5127
+ }
5103
5128
  if (pkg.scripts?.lint === "eslint") delete pkg.scripts.lint;
5104
5129
  return JSON.stringify(pkg, null, 2) + "\n";
5105
5130
  };
@@ -5313,7 +5338,7 @@ var resolveTarget = async (rc, opts = {}) => {
5313
5338
  };
5314
5339
 
5315
5340
  // src/commands/mutate.ts
5316
- import path26 from "path";
5341
+ import path27 from "path";
5317
5342
 
5318
5343
  // src/plan/planner.ts
5319
5344
  import path22 from "path";
@@ -5370,18 +5395,18 @@ var Planner = class {
5370
5395
  modifyFile(rel, content, opts) {
5371
5396
  const abs = this.abs(rel);
5372
5397
  this.vfs.write(abs, content);
5373
- const id = `${opts.capability}:modify:${rel}`;
5398
+ const id2 = `${opts.capability}:modify:${rel}`;
5374
5399
  const edits = (opts.inserted ?? []).map((e) => ({
5375
5400
  line: lineOf(content, e.at),
5376
5401
  insert: e.text
5377
5402
  }));
5378
- const existing = this.steps.find((s) => s.id === id);
5403
+ const existing = this.steps.find((s) => s.id === id2);
5379
5404
  if (existing && existing.kind === "modify_file") {
5380
5405
  existing.edits.push(...edits);
5381
5406
  return;
5382
5407
  }
5383
5408
  this.steps.push({
5384
- id,
5409
+ id: id2,
5385
5410
  kind: "modify_file",
5386
5411
  capability: opts.capability,
5387
5412
  summary: opts.summary,
@@ -5462,10 +5487,10 @@ var DEPENDS_ON = {
5462
5487
  };
5463
5488
  var resolveCapabilities = (requested) => {
5464
5489
  const ordered = [];
5465
- const visit = (id) => {
5466
- if (ordered.includes(id)) return;
5467
- DEPENDS_ON[id].forEach(visit);
5468
- ordered.push(id);
5490
+ const visit = (id2) => {
5491
+ if (ordered.includes(id2)) return;
5492
+ DEPENDS_ON[id2].forEach(visit);
5493
+ ordered.push(id2);
5469
5494
  };
5470
5495
  requested.forEach(visit);
5471
5496
  return ordered;
@@ -5476,13 +5501,13 @@ var planCapabilities = (p, capabilities) => {
5476
5501
  const status = capabilityStatus(p.state);
5477
5502
  const withAi = capabilities.includes("ai");
5478
5503
  let editorPlanned = false;
5479
- for (const id of capabilities) {
5480
- if (id === "editor") {
5504
+ for (const id2 of capabilities) {
5505
+ if (id2 === "editor") {
5481
5506
  if (status.editor.satisfied) continue;
5482
5507
  editorPlanned = true;
5483
5508
  adapter.planEditor(p, framework, withAi);
5484
5509
  }
5485
- if (id === "cloud") {
5510
+ if (id2 === "cloud") {
5486
5511
  if (p.backend?.mode === "external") {
5487
5512
  p.warn(
5488
5513
  "PUCK-CLI-W-EXTERNAL-BACKEND",
@@ -5504,7 +5529,7 @@ var planCapabilities = (p, capabilities) => {
5504
5529
  "The /api/puck route forwards requests to Puck Cloud using your API key. Add authentication before deploying."
5505
5530
  );
5506
5531
  }
5507
- if (id === "ai") {
5532
+ if (id2 === "ai") {
5508
5533
  if (adapter.kind === "server") continue;
5509
5534
  if (!p.state.ai.installed) {
5510
5535
  p.addDependency(
@@ -5571,6 +5596,66 @@ var planEnvWrite = (p, secret) => {
5571
5596
  planGitignore(p, target);
5572
5597
  };
5573
5598
 
5599
+ // src/plan/pnpm-builds.ts
5600
+ import path24 from "path";
5601
+ import { Document, isMap, isSeq, parseDocument } from "yaml";
5602
+ var LEGACY_LISTS = [
5603
+ "onlyBuiltDependencies",
5604
+ "neverBuiltDependencies",
5605
+ "ignoredBuiltDependencies"
5606
+ ];
5607
+ var allowAll = (names) => Object.fromEntries(names.map((name) => [name, true]));
5608
+ var withAllowedBuilds = (text, names) => {
5609
+ const doc = parseDocument(text ?? "");
5610
+ if (doc.errors.length > 0) return null;
5611
+ if (doc.get("dangerouslyAllowAllBuilds") === true) return null;
5612
+ const allowBuilds = doc.get("allowBuilds");
5613
+ const covered = /* @__PURE__ */ new Set();
5614
+ if (isMap(allowBuilds)) {
5615
+ for (const item of allowBuilds.items) covered.add(String(item.key));
5616
+ }
5617
+ for (const list of LEGACY_LISTS) {
5618
+ const seq = doc.get(list);
5619
+ if (isSeq(seq)) for (const item of seq.toJSON()) covered.add(String(item));
5620
+ }
5621
+ const missing = names.filter((name) => !covered.has(name));
5622
+ if (missing.length === 0) return null;
5623
+ const legacy = doc.get("onlyBuiltDependencies");
5624
+ if (isMap(allowBuilds)) {
5625
+ for (const name of missing) allowBuilds.set(name, true);
5626
+ } else if (isSeq(legacy)) {
5627
+ for (const name of missing) legacy.add(name);
5628
+ } else if (doc.contents === null) {
5629
+ const created = new Document({ allowBuilds: allowAll(missing) });
5630
+ created.commentBefore = " Dependencies allowed to run install scripts (required by pnpm 11+)";
5631
+ return created.toString();
5632
+ } else {
5633
+ doc.set("allowBuilds", allowAll(missing));
5634
+ }
5635
+ return doc.toString();
5636
+ };
5637
+ var planAllowedBuilds = (planner) => {
5638
+ const { ctx, vfs } = planner;
5639
+ if (ctx.packageManager.name !== "pnpm") return;
5640
+ const ws = ctx.workspace;
5641
+ if (ws && ws.source !== "pnpm-workspace.yaml") return;
5642
+ const file = path24.join(ws?.root ?? ctx.root, "pnpm-workspace.yaml");
5643
+ const names = templates_default.allowBuilds;
5644
+ const list = names.join(", ");
5645
+ const next = withAllowedBuilds(vfs.readText(file), names);
5646
+ if (next === null) return;
5647
+ vfs.write(file, next);
5648
+ if (!ws) return;
5649
+ planner.steps.push({
5650
+ id: "bootstrap:allow-builds",
5651
+ kind: "modify_file",
5652
+ capability: "bootstrap",
5653
+ summary: `Allow ${list} build scripts in the workspace's pnpm-workspace.yaml`,
5654
+ path: file,
5655
+ edits: []
5656
+ });
5657
+ };
5658
+
5574
5659
  // src/plan/backend.ts
5575
5660
  var choicesFor = (options, wantsCloud) => [
5576
5661
  { value: "add", label: options.addLabel },
@@ -5640,14 +5725,14 @@ var resolveBackend = async (rc, options, capabilities, planned) => {
5640
5725
 
5641
5726
  // src/auth/session-store.ts
5642
5727
  import fs4 from "fs";
5643
- import path24 from "path";
5728
+ import path25 from "path";
5644
5729
  import { createHash as createHash2 } from "crypto";
5645
5730
  var SessionStore = class {
5646
5731
  #file;
5647
5732
  constructor(cacheDir, projectRoot, baseUrl) {
5648
5733
  const key = createHash2("sha256").update(`${projectRoot}
5649
5734
  ${baseUrl}`).digest("hex").slice(0, 32);
5650
- this.#file = path24.join(cacheDir, "puck", "connect", `${key}.json`);
5735
+ this.#file = path25.join(cacheDir, "puck", "connect", `${key}.json`);
5651
5736
  }
5652
5737
  get path() {
5653
5738
  return this.#file;
@@ -5661,14 +5746,14 @@ ${baseUrl}`).digest("hex").slice(0, 32);
5661
5746
  }
5662
5747
  }
5663
5748
  save(session) {
5664
- fs4.mkdirSync(path24.dirname(this.#file), { recursive: true, mode: 448 });
5749
+ fs4.mkdirSync(path25.dirname(this.#file), { recursive: true, mode: 448 });
5665
5750
  fs4.writeFileSync(this.#file, JSON.stringify(session), { mode: 384 });
5666
5751
  }
5667
5752
  clear() {
5668
5753
  fs4.rmSync(this.#file, { force: true });
5669
5754
  }
5670
5755
  };
5671
- var cacheDirFor = (env2, homedir) => env2.XDG_CACHE_HOME || path24.join(homedir, ".cache");
5756
+ var cacheDirFor = (env2, homedir) => env2.XDG_CACHE_HOME || path25.join(homedir, ".cache");
5672
5757
 
5673
5758
  // src/auth/credentials.ts
5674
5759
  var apiKeysUrl = (rc) => new URL(API_KEYS_PATH, rc.cloud.baseUrl).toString();
@@ -5701,7 +5786,8 @@ var clientPayload = (rc, info) => ({
5701
5786
  cliVersion: rc.deps.cliVersion,
5702
5787
  hostname: rc.deps.hostname.slice(0, 100),
5703
5788
  projectName: info.projectName?.slice(0, 100),
5704
- framework: info.framework
5789
+ framework: info.framework,
5790
+ anonymousId: rc.telemetry?.anonymousId ?? void 0
5705
5791
  });
5706
5792
  var onApproved = (rc, approved) => {
5707
5793
  const secret = secretFrom(rc, approved.apiKey, "Puck Cloud");
@@ -5891,7 +5977,7 @@ var promptForKey = async (rc) => {
5891
5977
  warnings: []
5892
5978
  };
5893
5979
  };
5894
- var resolveCredential = async (rc, state, info) => {
5980
+ var resolveCredential = async (rc, state, info, { fresh = false } = {}) => {
5895
5981
  const warnings = [];
5896
5982
  const fromExplicit = async (value, source) => {
5897
5983
  const secret = secretFrom(
@@ -5917,10 +6003,15 @@ var resolveCredential = async (rc, state, info) => {
5917
6003
  };
5918
6004
  if (rc.flags.apiKey !== void 0)
5919
6005
  return fromExplicit(rc.flags.apiKey, "flag");
5920
- if (rc.deps.env[ENV_KEY])
6006
+ if (fresh && rc.deps.env[ENV_KEY]) {
6007
+ warnings.push({
6008
+ code: "PUCK-CLI-W-KEY-IN-PROCESS-ENV",
6009
+ message: `${ENV_KEY} is set in your environment and overrides the new key in the env file. Unset it to use the new key.`
6010
+ });
6011
+ } else if (rc.deps.env[ENV_KEY])
5921
6012
  return fromExplicit(rc.deps.env[ENV_KEY], "process.env");
5922
6013
  const existing = state.cloud.apiKey;
5923
- if (existing.present && existing.value) {
6014
+ if (!fresh && existing.present && existing.value) {
5924
6015
  const secret = secretFrom(
5925
6016
  rc,
5926
6017
  existing.value,
@@ -5981,7 +6072,7 @@ var resolveCredential = async (rc, state, info) => {
5981
6072
 
5982
6073
  // src/apply/applier.ts
5983
6074
  import fs5 from "fs";
5984
- import path25 from "path";
6075
+ import path26 from "path";
5985
6076
  var tail = (text, lines = 20) => text.trim().split("\n").slice(-lines).join("\n");
5986
6077
  var run = async (rc, spec) => {
5987
6078
  rc.log(`$ ${formatCommand(spec)}`);
@@ -6011,14 +6102,14 @@ ${result.stderr}`))
6011
6102
  }
6012
6103
  };
6013
6104
  var writeFile = (file, content, mode) => {
6014
- fs5.mkdirSync(path25.dirname(file), { recursive: true });
6105
+ fs5.mkdirSync(path26.dirname(file), { recursive: true });
6015
6106
  if (mode === void 0) {
6016
6107
  fs5.writeFileSync(file, content);
6017
6108
  return;
6018
6109
  }
6019
- const temp = path25.join(
6020
- path25.dirname(file),
6021
- `.${path25.basename(file)}.${process.pid}.tmp`
6110
+ const temp = path26.join(
6111
+ path26.dirname(file),
6112
+ `.${path26.basename(file)}.${process.pid}.tmp`
6022
6113
  );
6023
6114
  fs5.writeFileSync(temp, content, { mode });
6024
6115
  fs5.chmodSync(temp, mode);
@@ -6219,6 +6310,7 @@ var runMutation = async (rc, input) => {
6219
6310
  }
6220
6311
  planCapabilities(planner, capabilities);
6221
6312
  planner.finalize();
6313
+ if (bootstrap) planAllowedBuilds(planner);
6222
6314
  if (scaffoldStep) planner.steps.unshift(scaffoldStep);
6223
6315
  const wantsCloud = capabilities.includes("cloud") && planner.backend?.mode !== "external" && !state.cloud.external;
6224
6316
  const needsConsent = planner.steps.length > 0 || wantsCloud && !state.cloud.apiKey.present;
@@ -6257,7 +6349,7 @@ var runMutation = async (rc, input) => {
6257
6349
  if (wantsCloud) {
6258
6350
  credential = await resolveCredential(rc, state, {
6259
6351
  projectRoot: root,
6260
- projectName: bootstrap?.appName ?? ctx.packageJson?.name ?? path26.basename(root),
6352
+ projectName: bootstrap?.appName ?? ctx.packageJson?.name ?? path27.basename(root),
6261
6353
  framework: ctx.framework.id
6262
6354
  });
6263
6355
  for (const w of credential.warnings) planner.warn(w.code, w.message);
@@ -6448,14 +6540,14 @@ var runInit = async (rc) => {
6448
6540
  { globs: target.workspace.globs }
6449
6541
  );
6450
6542
  }
6451
- parentDir = path27.join(target.workspace.root, appsDir);
6543
+ parentDir = path28.join(target.workspace.root, appsDir);
6452
6544
  workspaceRoot = target.workspace.root;
6453
6545
  for (const pkg of target.workspace.packages) {
6454
6546
  if (pkg.name) existingNames.add(pkg.name);
6455
- existingNames.add(path27.basename(pkg.dir));
6547
+ existingNames.add(path28.basename(pkg.dir));
6456
6548
  }
6457
6549
  } else {
6458
- if (vfs.exists(path27.join(target.root, "package.json"))) {
6550
+ if (vfs.exists(path28.join(target.root, "package.json"))) {
6459
6551
  const read = readPackageJson(vfs, target.root);
6460
6552
  const deps = depsOf(read.status === "ok" ? read.pkg : null);
6461
6553
  const detection = detectFramework(vfs, target.root, deps);
@@ -6545,7 +6637,7 @@ var runInit = async (rc) => {
6545
6637
  `A workspace package named "${name}" already exists.`
6546
6638
  );
6547
6639
  }
6548
- const dir = inPlace ? parentDir : path27.join(parentDir, name);
6640
+ const dir = inPlace ? parentDir : path28.join(parentDir, name);
6549
6641
  if (!inPlace && vfs.exists(dir) && !isEmptyDir(vfs, dir)) {
6550
6642
  throw new CliError(
6551
6643
  "PUCK-CLI-TARGET-DIR-NOT-EMPTY",
@@ -6564,7 +6656,7 @@ var runInit = async (rc) => {
6564
6656
  bootstrap: {
6565
6657
  framework,
6566
6658
  dir,
6567
- appName: name ?? sanitizeAppName(path27.basename(dir)),
6659
+ appName: name ?? sanitizeAppName(path28.basename(dir)),
6568
6660
  workspaceRoot
6569
6661
  },
6570
6662
  workspace: target.kind === "workspace-empty" ? target.summary : null
@@ -6578,7 +6670,7 @@ var runAdd = async (rc, positionals) => {
6578
6670
  "PUCK-CLI-INVALID-ARGS",
6579
6671
  `Specify what to add: ${CAPABILITY_IDS.join(
6580
6672
  ", "
6581
- )}. For example \`puck add cloud\`.`
6673
+ )}. For example \`${CANONICAL_INVOCATION} add cloud\`.`
6582
6674
  );
6583
6675
  }
6584
6676
  const unknown = positionals.filter(
@@ -6616,6 +6708,144 @@ var runAdd = async (rc, positionals) => {
6616
6708
  });
6617
6709
  };
6618
6710
 
6711
+ // src/commands/connect.ts
6712
+ import path29 from "path";
6713
+ var runConnect = async (rc) => {
6714
+ const { deps, flags } = rc;
6715
+ const result = emptyResult("connect", flags.dryRun);
6716
+ const target = await resolveTarget(rc);
6717
+ if (target.kind === "action") {
6718
+ result.status = "action_required";
6719
+ result.message = target.action.message;
6720
+ result.actions = [target.action];
6721
+ return result;
6722
+ }
6723
+ if (target.kind === "workspace-empty") {
6724
+ throw new CliError(
6725
+ "PUCK-CLI-UNSUPPORTED-FRAMEWORK",
6726
+ `No supported app was found in this workspace. Run \`${CANONICAL_INVOCATION} init\` to create one.`,
6727
+ { fix: `${CANONICAL_INVOCATION} init --name <name>` }
6728
+ );
6729
+ }
6730
+ const base = baseDir(rc);
6731
+ const root = target.root;
6732
+ const vfs = new Vfs();
6733
+ const ctx = detectProject({
6734
+ vfs,
6735
+ root,
6736
+ cwd: base,
6737
+ packageManagerFlag: flags.packageManager,
6738
+ env: deps.env
6739
+ });
6740
+ assertSupported(rc, ctx);
6741
+ const state = detectState(vfs, ctx, deps.env, { configFlag: flags.config });
6742
+ if (state.cloud.external) {
6743
+ throw new CliError(
6744
+ "PUCK-CLI-EXTERNAL-BACKEND",
6745
+ "This app sends Puck Cloud requests to a server elsewhere, and the key lives there. Run connect against that server instead.",
6746
+ { fix: `${CANONICAL_INVOCATION} connect --cwd <server dir>` }
6747
+ );
6748
+ }
6749
+ const planner = new Planner(vfs, ctx, state, deps.templates, deps.cliVersion);
6750
+ for (const warning of ctx.warnings)
6751
+ planner.warn("PUCK-CLI-W-DETECTION", warning);
6752
+ const cloudReady = state.cloud.clientInstalled && Boolean(state.cloud.routeFile) && state.cloud.routeRegistered !== false;
6753
+ const where = root === base ? "" : ` --cwd ${displayPath(base, root)}`;
6754
+ if (!cloudReady) {
6755
+ planner.warn(
6756
+ "PUCK-CLI-W-CLOUD-NOT-SET-UP",
6757
+ `Puck Cloud isn't set up in this app yet, so nothing uses ${ENV_KEY}. Run \`${CANONICAL_INVOCATION} add cloud\` to set it up.`
6758
+ );
6759
+ }
6760
+ const finish = (status, message) => {
6761
+ result.status = status;
6762
+ result.message = message;
6763
+ result.project = projectSummary(ctx, target.workspace);
6764
+ result.cloud = cloudSummary(state, "none");
6765
+ result.warnings = planner.warnings;
6766
+ return result;
6767
+ };
6768
+ if (!flags.dryRun && !rc.interactive && !flags.yes) {
6769
+ result.actions = [
6770
+ {
6771
+ id: "confirm",
6772
+ type: "confirm_plan",
6773
+ required: true,
6774
+ flag: "--yes",
6775
+ message: `Re-run with --yes to log in to Puck Cloud and replace ${ENV_KEY}.`,
6776
+ rerun: `${rerunCommand(rc)} --yes`
6777
+ }
6778
+ ];
6779
+ return finish(
6780
+ "action_required",
6781
+ `Re-run with --yes to log in to Puck Cloud and replace ${ENV_KEY}.`
6782
+ );
6783
+ }
6784
+ const credential = await resolveCredential(
6785
+ rc,
6786
+ state,
6787
+ {
6788
+ projectRoot: root,
6789
+ projectName: ctx.packageJson?.name ?? path29.basename(root),
6790
+ framework: ctx.framework.id
6791
+ },
6792
+ { fresh: true }
6793
+ );
6794
+ for (const w of credential.warnings) planner.warn(w.code, w.message);
6795
+ if (credential.kind === "action") {
6796
+ result.actions = [credential.action];
6797
+ return finish(
6798
+ "action_required",
6799
+ credential.action.type === "browser_login" ? "Puck Cloud login required. No changes have been made yet." : "A Puck API key is required. No changes have been made yet."
6800
+ );
6801
+ }
6802
+ if (credential.kind === "none") {
6803
+ planner.warn(
6804
+ "PUCK-CLI-W-KEY-NEEDED",
6805
+ "You'll be asked to log in to Puck Cloud when you run this without --dry-run."
6806
+ );
6807
+ return finish("success", "Dry run: no changes were made.");
6808
+ }
6809
+ planEnvWrite(planner, credential.secret);
6810
+ result.plan = { steps: serializeSteps(base, planner.steps) };
6811
+ if (flags.dryRun) return finish("success", "Dry run: no changes were made.");
6812
+ const outcome = await applyPlan(rc, vfs, planner.steps);
6813
+ const after = new Vfs();
6814
+ const verifiedCtx = detectProject({
6815
+ vfs: after,
6816
+ root,
6817
+ cwd: base,
6818
+ packageManagerFlag: flags.packageManager,
6819
+ env: deps.env
6820
+ });
6821
+ const verifiedState = detectState(after, verifiedCtx, deps.env, {
6822
+ configFlag: flags.config
6823
+ });
6824
+ const check = credential.verified;
6825
+ finish(
6826
+ "success",
6827
+ `Connected to Puck Cloud. ${planner.steps.length ? `Saved ${ENV_KEY} to ${displayPath(
6828
+ base,
6829
+ verifiedState.cloud.apiKey.file ?? root
6830
+ )}.` : `${ENV_KEY} was already set to this key.`}`
6831
+ );
6832
+ result.project = projectSummary(verifiedCtx, target.workspace);
6833
+ result.cloud = cloudSummary(
6834
+ verifiedState,
6835
+ check === "valid" ? "remote" : check === "invalid" ? "failed" : "local"
6836
+ );
6837
+ result.changed = planner.steps.length > 0;
6838
+ result.filesCreated = outcome.created.map((f) => displayPath(base, f)).sort();
6839
+ result.filesModified = [...outcome.created, ...outcome.modified].map((f) => displayPath(base, f)).sort();
6840
+ const pm = verifiedCtx.packageManager.name;
6841
+ const cdPrefix = root === base ? "" : `cd ${displayPath(base, root)} && `;
6842
+ result.nextSteps = cloudReady ? [
6843
+ "# Restart the dev server so it picks up the new key",
6844
+ `${cdPrefix}${pm} ${pm === "npm" ? "run " : ""}dev`
6845
+ ] : [`${CANONICAL_INVOCATION} add cloud${where}`];
6846
+ return result;
6847
+ };
6848
+
6619
6849
  // src/commands/status.ts
6620
6850
  var runStatus = async (rc) => {
6621
6851
  const base = baseDir(rc);
@@ -6689,7 +6919,7 @@ var runStatus = async (rc) => {
6689
6919
  };
6690
6920
 
6691
6921
  // src/commands/doctor.ts
6692
- import path28 from "path";
6922
+ import path30 from "path";
6693
6923
  var finding = (check, status, evidence, fix = null) => ({ check, status, evidence, fix });
6694
6924
  var runDoctor = async (rc) => {
6695
6925
  const base = baseDir(rc);
@@ -6774,7 +7004,7 @@ var runDoctor = async (rc) => {
6774
7004
  finding(
6775
7005
  "project.package_json",
6776
7006
  "ok",
6777
- displayPath(base, path28.join(ctx.root, "package.json"))
7007
+ displayPath(base, path30.join(ctx.root, "package.json"))
6778
7008
  )
6779
7009
  );
6780
7010
  result.project = projectSummary(ctx, target.workspace);
@@ -7016,7 +7246,7 @@ var runDoctor = async (rc) => {
7016
7246
  "cloud.connection",
7017
7247
  "fail",
7018
7248
  "Puck Cloud rejected the API key",
7019
- `${CANONICAL_INVOCATION} add cloud${where}`
7249
+ `${CANONICAL_INVOCATION} connect${where}`
7020
7250
  )
7021
7251
  );
7022
7252
  } else {
@@ -7166,15 +7396,15 @@ var NOTES = {
7166
7396
  hono: "Serves the APIs for an editor in another app",
7167
7397
  express: "Serves the APIs for an editor in another app"
7168
7398
  };
7169
- var frameworkSupport = () => FRAMEWORK_IDS.map((id) => {
7170
- const adapter = ADAPTERS[id];
7399
+ var frameworkSupport = () => FRAMEWORK_IDS.map((id2) => {
7400
+ const adapter = ADAPTERS[id2];
7171
7401
  return {
7172
- id,
7173
- name: FRAMEWORK_LABELS[id],
7174
- minVersion: MIN_VERSIONS[id],
7402
+ id: id2,
7403
+ name: FRAMEWORK_LABELS[id2],
7404
+ minVersion: MIN_VERSIONS[id2],
7175
7405
  kind: adapter.kind ?? "app",
7176
7406
  needsServer: Boolean(adapter.backend),
7177
- notes: NOTES[id]
7407
+ notes: NOTES[id2]
7178
7408
  };
7179
7409
  });
7180
7410
  var runFrameworks = async (_rc, positionals) => {
@@ -7190,6 +7420,214 @@ var runFrameworks = async (_rc, positionals) => {
7190
7420
  return result;
7191
7421
  };
7192
7422
 
7423
+ // src/telemetry/consent.ts
7424
+ import { randomUUID } from "crypto";
7425
+
7426
+ // src/telemetry/config.ts
7427
+ import fs6 from "fs";
7428
+ import path31 from "path";
7429
+ var TelemetryConfigStore = class {
7430
+ #file;
7431
+ constructor(configDir) {
7432
+ this.#file = path31.join(configDir, "puck", "telemetry.json");
7433
+ }
7434
+ get path() {
7435
+ return this.#file;
7436
+ }
7437
+ load() {
7438
+ try {
7439
+ const data = JSON.parse(fs6.readFileSync(this.#file, "utf8"));
7440
+ return data && typeof data === "object" ? data : {};
7441
+ } catch {
7442
+ return {};
7443
+ }
7444
+ }
7445
+ /** Throws if the config directory isn't writable */
7446
+ save(config) {
7447
+ fs6.mkdirSync(path31.dirname(this.#file), { recursive: true, mode: 448 });
7448
+ fs6.writeFileSync(this.#file, JSON.stringify(config, null, 2) + "\n", {
7449
+ mode: 384
7450
+ });
7451
+ }
7452
+ };
7453
+ var configDirFor = (env2, homedir) => env2.XDG_CONFIG_HOME || path31.join(homedir, ".config");
7454
+
7455
+ // src/telemetry/consent.ts
7456
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7457
+ var telemetryConsent = (env2, config) => {
7458
+ if (isTruthyEnv(env2.PUCK_TELEMETRY_DISABLED))
7459
+ return { enabled: false, reason: "PUCK_TELEMETRY_DISABLED" };
7460
+ if (isTruthyEnv(env2.DO_NOT_TRACK))
7461
+ return { enabled: false, reason: "DO_NOT_TRACK" };
7462
+ if (config.enabled === false) return { enabled: false, reason: "disabled" };
7463
+ return { enabled: true, reason: config.enabled ? "enabled" : "default" };
7464
+ };
7465
+ var loadTelemetry = (deps) => {
7466
+ const store = new TelemetryConfigStore(configDirFor(deps.env, deps.homedir));
7467
+ const debug = isTruthyEnv(deps.env.PUCK_TELEMETRY_DEBUG);
7468
+ const envOnly = telemetryConsent(deps.env, {});
7469
+ const config = envOnly.reason === "PUCK_TELEMETRY_DISABLED" || envOnly.reason === "DO_NOT_TRACK" ? {} : store.load();
7470
+ const consent = telemetryConsent(deps.env, config);
7471
+ const off = (reason) => ({
7472
+ enabled: false,
7473
+ reason,
7474
+ anonymousId: null,
7475
+ debug,
7476
+ store,
7477
+ config
7478
+ });
7479
+ if (!consent.enabled) return off(consent.reason);
7480
+ if (typeof config.anonymousId !== "string" || !UUID.test(config.anonymousId)) {
7481
+ config.anonymousId = randomUUID();
7482
+ try {
7483
+ store.save(config);
7484
+ } catch {
7485
+ return off("unwritable");
7486
+ }
7487
+ }
7488
+ return { ...consent, anonymousId: config.anonymousId, debug, store, config };
7489
+ };
7490
+
7491
+ // src/commands/telemetry.ts
7492
+ var SUBCOMMANDS2 = ["status", "enable", "disable"];
7493
+ var DISABLE = `\`${CANONICAL_INVOCATION} telemetry disable\``;
7494
+ var MESSAGES = {
7495
+ default: `Telemetry is on. Turn it off with ${DISABLE}.`,
7496
+ enabled: `Telemetry is on. Turn it off with ${DISABLE}.`,
7497
+ disabled: "Telemetry is off.",
7498
+ PUCK_TELEMETRY_DISABLED: "Telemetry is off because PUCK_TELEMETRY_DISABLED is set.",
7499
+ DO_NOT_TRACK: "Telemetry is off because DO_NOT_TRACK is set.",
7500
+ unwritable: "Telemetry is off because its config file can't be written."
7501
+ };
7502
+ var runTelemetry = async (rc, positionals) => {
7503
+ const [sub = "status", ...rest] = positionals;
7504
+ if (rest.length > 0 || !SUBCOMMANDS2.includes(sub)) {
7505
+ throw new CliError(
7506
+ "PUCK-CLI-INVALID-ARGS",
7507
+ `Usage: \`${CANONICAL_INVOCATION} telemetry [status|enable|disable]\`.`
7508
+ );
7509
+ }
7510
+ const { env: env2, homedir } = rc.deps;
7511
+ const store = new TelemetryConfigStore(configDirFor(env2, homedir));
7512
+ const config = store.load();
7513
+ const result = emptyResult("telemetry");
7514
+ if (sub !== "status") {
7515
+ const enabled = sub === "enable";
7516
+ result.changed = config.enabled !== enabled;
7517
+ config.enabled = enabled;
7518
+ if (!enabled) delete config.anonymousId;
7519
+ try {
7520
+ store.save(config);
7521
+ } catch (err) {
7522
+ throw new CliError(
7523
+ "PUCK-CLI-WRITE-FAILED",
7524
+ `Couldn't save ${store.path}: ${err.message}`
7525
+ );
7526
+ }
7527
+ }
7528
+ const consent = telemetryConsent(env2, config);
7529
+ result.telemetry = {
7530
+ ...consent,
7531
+ anonymousId: consent.enabled ? config.anonymousId ?? null : null
7532
+ };
7533
+ result.message = sub === "enable" && !consent.enabled ? `Telemetry is enabled in ${store.path}, but stays off: ${MESSAGES[consent.reason].replace("Telemetry is off because ", "")}` : MESSAGES[consent.reason];
7534
+ return result;
7535
+ };
7536
+
7537
+ // src/telemetry/event.ts
7538
+ var AGENTS = [
7539
+ ["CLAUDECODE", "claude-code"],
7540
+ ["CURSOR_AGENT", "cursor"],
7541
+ ["CODEX_SANDBOX", "codex"],
7542
+ ["CODEX_SANDBOX_NETWORK_DISABLED", "codex"],
7543
+ ["GEMINI_CLI", "gemini-cli"],
7544
+ ["OPENCODE", "opencode"]
7545
+ ];
7546
+ var detectAgent = (env2) => AGENTS.find(([key]) => env2[key] !== void 0 && env2[key] !== "")?.[1] ?? null;
7547
+ var id = (value) => value && /^[A-Za-z0-9._@:-]{1,64}$/.test(value) ? value : null;
7548
+ var ids = (values) => values.map(id).filter((v) => v !== null);
7549
+ var major = (version) => {
7550
+ const match = version?.match(/\d+/);
7551
+ return match ? Number(match[0]) : null;
7552
+ };
7553
+ var buildEvent = (input) => {
7554
+ const { result, flags } = input;
7555
+ const project = result.project;
7556
+ return {
7557
+ event: "cli_command",
7558
+ timestamp: new Date(input.now).toISOString(),
7559
+ command: input.command,
7560
+ capabilities: input.command === "add" ? CAPABILITY_IDS.filter((c) => input.positionals.includes(c)) : [],
7561
+ status: result.status,
7562
+ errorCode: id(result.error?.code),
7563
+ exitCode: input.exitCode,
7564
+ durationMs: Math.max(0, Math.round(input.durationMs)),
7565
+ dryRun: Boolean(flags.dryRun),
7566
+ changed: result.changed,
7567
+ actions: ids(result.actions.map((a) => a.type)),
7568
+ warnings: ids(result.warnings.map((w) => w.code)),
7569
+ cliVersion: id(input.cliVersion) ?? "unknown",
7570
+ os: id(input.platform) ?? "unknown",
7571
+ arch: id(input.arch) ?? "unknown",
7572
+ nodeVersion: id(input.nodeVersion) ?? "unknown",
7573
+ packageManager: project?.packageManager ?? flags.packageManager ?? null,
7574
+ ci: isCI(input.env),
7575
+ interactive: input.interactive,
7576
+ json: Boolean(flags.json),
7577
+ agent: detectAgent(input.env),
7578
+ framework: project?.framework ?? flags.framework ?? null,
7579
+ frameworkMajor: major(project?.frameworkVersion),
7580
+ monorepo: Boolean(project?.workspace),
7581
+ puck: Boolean(result.puck?.installed),
7582
+ cloud: Boolean(result.cloud?.installed),
7583
+ ai: Boolean(result.ai?.installed),
7584
+ backend: flags.backend ?? null
7585
+ };
7586
+ };
7587
+
7588
+ // src/telemetry/client.ts
7589
+ var TIMEOUT_MS2 = 1e3;
7590
+ var sendTelemetry = async (deps, baseUrl, telemetry, events) => {
7591
+ if (!telemetry.enabled || !telemetry.anonymousId) return;
7592
+ const body = JSON.stringify({ anonymousId: telemetry.anonymousId, events });
7593
+ if (telemetry.debug) {
7594
+ deps.stderr.write(`[telemetry] ${body}
7595
+ `);
7596
+ return;
7597
+ }
7598
+ try {
7599
+ await deps.fetch(
7600
+ new URL(
7601
+ "api/cli/telemetry",
7602
+ baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`
7603
+ ),
7604
+ {
7605
+ method: "POST",
7606
+ headers: { "content-type": "application/json" },
7607
+ body,
7608
+ signal: AbortSignal.timeout(TIMEOUT_MS2)
7609
+ }
7610
+ );
7611
+ } catch {
7612
+ }
7613
+ };
7614
+
7615
+ // src/telemetry/notice.ts
7616
+ var TELEMETRY_NOTICE = `Puck CLI collects anonymous usage data, like which commands run and whether they succeed. It never includes code, file paths, project names or API keys.
7617
+ To opt out, run \`${CANONICAL_INVOCATION} telemetry disable\` or set PUCK_TELEMETRY_DISABLED=1.
7618
+ Learn more: ${DOCS_URL}#telemetry
7619
+ `;
7620
+ var showTelemetryNotice = (deps, telemetry) => {
7621
+ if (!telemetry.enabled || telemetry.config.notifiedAt) return;
7622
+ deps.stderr.write(`${TELEMETRY_NOTICE}
7623
+ `);
7624
+ telemetry.config.notifiedAt = new Date(deps.now()).toISOString();
7625
+ try {
7626
+ telemetry.store.save(telemetry.config);
7627
+ } catch {
7628
+ }
7629
+ };
7630
+
7193
7631
  // src/cli.ts
7194
7632
  var exitCodeFor = (result) => {
7195
7633
  if (result.status === "error")
@@ -7214,15 +7652,42 @@ var errorResult = (command, err, dryRun = false) => {
7214
7652
  result.message = cliError.message;
7215
7653
  return result;
7216
7654
  };
7655
+ var recordRun = (deps, telemetry, startedAt, input) => {
7656
+ const now = deps.now();
7657
+ const event = buildEvent({
7658
+ ...input,
7659
+ durationMs: now - startedAt,
7660
+ env: deps.env,
7661
+ cliVersion: deps.cliVersion,
7662
+ platform: deps.platform,
7663
+ arch: deps.arch,
7664
+ nodeVersion: deps.nodeVersion,
7665
+ now
7666
+ });
7667
+ return sendTelemetry(deps, cloudBaseUrl(deps.env), telemetry, [event]);
7668
+ };
7217
7669
  var runCli = async (argv, deps) => {
7670
+ const startedAt = deps.now();
7218
7671
  let parsed;
7219
7672
  try {
7220
7673
  parsed = parseCliArgs(argv);
7221
7674
  } catch (err) {
7222
7675
  const result2 = errorResult("help", err);
7223
- if (wantsJson(argv)) presentJson(deps.stdout, result2, new SecretRegistry());
7676
+ const json = wantsJson(argv);
7677
+ if (json) presentJson(deps.stdout, result2, new SecretRegistry());
7224
7678
  else presentHuman(deps.stderr, result2, new SecretRegistry());
7225
- return exitCodeFor(result2);
7679
+ const exitCode2 = exitCodeFor(result2);
7680
+ if (argv[0] !== "telemetry") {
7681
+ await recordRun(deps, loadTelemetry(deps), startedAt, {
7682
+ command: null,
7683
+ positionals: [],
7684
+ flags: { json },
7685
+ result: result2,
7686
+ exitCode: exitCode2,
7687
+ interactive: false
7688
+ });
7689
+ }
7690
+ return exitCode2;
7226
7691
  }
7227
7692
  const { command, flags, positionals } = parsed;
7228
7693
  if (flags.version) {
@@ -7238,15 +7703,20 @@ var runCli = async (argv, deps) => {
7238
7703
  else deps.stdout.write(HELP_TEXT);
7239
7704
  return EXIT_CODES.success;
7240
7705
  }
7241
- const rc = createRunContext(deps, flags, argv);
7706
+ const telemetry = command === "telemetry" ? null : loadTelemetry(deps);
7707
+ const rc = createRunContext(deps, flags, argv, telemetry);
7708
+ if (telemetry && !flags.json) showTelemetryNotice(deps, telemetry);
7242
7709
  let result;
7243
7710
  try {
7244
7711
  if (command === "init") result = await runInit(rc);
7245
7712
  else if (command === "add") result = await runAdd(rc, positionals);
7713
+ else if (command === "connect") result = await runConnect(rc);
7246
7714
  else if (command === "status") result = await runStatus(rc);
7247
7715
  else if (command === "docs") result = await runDocs(rc, positionals);
7248
7716
  else if (command === "frameworks")
7249
7717
  result = await runFrameworks(rc, positionals);
7718
+ else if (command === "telemetry")
7719
+ result = await runTelemetry(rc, positionals);
7250
7720
  else result = await runDoctor(rc);
7251
7721
  } catch (err) {
7252
7722
  result = errorResult(command, err, flags.dryRun);
@@ -7258,8 +7728,19 @@ var runCli = async (argv, deps) => {
7258
7728
  result,
7259
7729
  rc.secrets
7260
7730
  );
7731
+ const exitCode = exitCodeFor(result);
7732
+ if (telemetry) {
7733
+ await recordRun(deps, telemetry, startedAt, {
7734
+ command,
7735
+ positionals,
7736
+ flags,
7737
+ result,
7738
+ exitCode,
7739
+ interactive: rc.interactive
7740
+ });
7741
+ }
7261
7742
  if (result.status === "success" && rc.afterOutput) await rc.afterOutput();
7262
- return exitCodeFor(result);
7743
+ return exitCode;
7263
7744
  };
7264
7745
 
7265
7746
  // src/io/runner.ts
@@ -7349,8 +7830,8 @@ var runDevServer = (spec, onReady) => new Promise((resolve) => {
7349
7830
  });
7350
7831
 
7351
7832
  // src/docs/source.ts
7352
- import fs6 from "fs";
7353
- import path29 from "path";
7833
+ import fs7 from "fs";
7834
+ import path32 from "path";
7354
7835
  var DirDocsSource = class {
7355
7836
  #dir;
7356
7837
  constructor(dir) {
@@ -7358,21 +7839,21 @@ var DirDocsSource = class {
7358
7839
  }
7359
7840
  list() {
7360
7841
  return JSON.parse(
7361
- fs6.readFileSync(path29.join(this.#dir, "index.json"), "utf8")
7842
+ fs7.readFileSync(path32.join(this.#dir, "index.json"), "utf8")
7362
7843
  );
7363
7844
  }
7364
7845
  read(page) {
7365
- return fs6.readFileSync(path29.join(this.#dir, `${page}.md`), "utf8");
7846
+ return fs7.readFileSync(path32.join(this.#dir, `${page}.md`), "utf8");
7366
7847
  }
7367
7848
  };
7368
7849
 
7369
7850
  // src/bin.ts
7370
- var distDir = path30.dirname(fileURLToPath(import.meta.url));
7371
- var templatesDir = path30.join(distDir, "templates");
7851
+ var distDir = path33.dirname(fileURLToPath(import.meta.url));
7852
+ var templatesDir = path33.join(distDir, "templates");
7372
7853
  var templates = new DirTemplateSource(templatesDir, {
7373
7854
  gitignoreName: "_gitignore",
7374
7855
  manifest: () => JSON.parse(
7375
- fs7.readFileSync(path30.join(templatesDir, "manifest.json"), "utf8")
7856
+ fs8.readFileSync(path33.join(templatesDir, "manifest.json"), "utf8")
7376
7857
  )
7377
7858
  });
7378
7859
  var env = { ...process.env };
@@ -7382,16 +7863,19 @@ runCli(process.argv.slice(2), {
7382
7863
  stdout: process.stdout,
7383
7864
  stderr: process.stderr,
7384
7865
  stdinIsTTY: Boolean(process.stdin.isTTY),
7385
- cliVersion: "0.24.0-canary.55558da4",
7866
+ cliVersion: "0.24.0-canary.b7903763",
7386
7867
  runner: createRunner(env),
7387
7868
  fetch: globalThis.fetch,
7388
7869
  openUrl,
7389
7870
  runDevServer,
7390
7871
  createPrompter: () => createInquirerPrompter(process.stderr),
7391
7872
  templates,
7392
- docs: new DirDocsSource(path30.join(distDir, "docs")),
7873
+ docs: new DirDocsSource(path33.join(distDir, "docs")),
7393
7874
  homedir: os.homedir(),
7394
7875
  hostname: os.hostname(),
7876
+ platform: process.platform,
7877
+ arch: process.arch,
7878
+ nodeVersion: process.versions.node,
7395
7879
  now: () => Date.now(),
7396
7880
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
7397
7881
  }).then(
package/dist/docs/cli.md CHANGED
@@ -159,10 +159,12 @@ npx skills add puckeditor/skills --skill puck
159
159
  | `add editor` | Add the Puck editor |
160
160
  | `add cloud` | Connect Puck Cloud (adds the editor first if needed) |
161
161
  | `add ai` | Add the Puck AI plugin (adds Puck Cloud first if needed) |
162
+ | `connect` | Log in to Puck Cloud again and replace `PUCK_API_KEY` |
162
163
  | `status` | Show what's installed and configured |
163
164
  | `doctor` | Diagnose problems and suggest fixes. Never makes changes |
164
165
  | `frameworks` | Show the supported frameworks and versions |
165
166
  | `docs` | Read these docs: `ls`, `cat <page>`, `find <query>`, `grep <text>` |
167
+ | `telemetry` | Show or change anonymous usage data collection |
166
168
 
167
169
  ## Flags
168
170
 
@@ -195,6 +197,12 @@ To use an existing key, prefer the environment over `--api-key`, which is visibl
195
197
  PUCK_API_KEY=your-key npx @puckeditor/cli add cloud --yes
196
198
  ```
197
199
 
200
+ To log in again, for example to replace a revoked key, run `connect`. It always starts a new login and replaces the existing key, without changing any code:
201
+
202
+ ```sh
203
+ npx @puckeditor/cli connect
204
+ ```
205
+
198
206
  Remember to set `PUCK_API_KEY` in your production environment too. `react-router-serve` and Cloudflare Workers don't load `.env` files; on Workers, use `wrangler secret put PUCK_API_KEY`.
199
207
 
200
208
  The `/api/puck` route and the editor are public by default. Add authentication before deploying.
@@ -202,3 +210,26 @@ The `/api/puck` route and the editor are public by default. Add authentication b
202
210
  ## Puck AI
203
211
 
204
212
  `init` and `add ai` add the Puck AI plugin to the editor, allow design mode in the `/api/puck` route, and wrap your config with `withDynamicConfig` so components designed by Puck AI render on your pages. If your editor has been customised, the CLI leaves it alone and prints the code to add.
213
+
214
+ ## Telemetry
215
+
216
+ The CLI collects anonymous usage data to help us improve it. The first time it runs without `--json`, it prints a notice.
217
+
218
+ Each command sends one event to Puck Cloud with:
219
+
220
+ - The command, what `add` was asked for, the result status, error and warning codes, the actions it returned, the exit code and how long it took
221
+ - Whether it was a dry run, made changes, ran interactively, used `--json` or ran in CI
222
+ - The CLI version, operating system, CPU architecture and Node.js version
223
+ - The name of the coding agent running it, if it's a known one, such as `claude-code`
224
+ - The framework and its major version, the package manager, the `--backend` choice, whether the project is in a monorepo, and whether the Puck editor, Puck Cloud and Puck AI are set up
225
+ - A random ID, stored in `~/.config/puck/telemetry.json`
226
+
227
+ It never sends code, file paths, project or package names, hostnames, error messages, flag values or API keys. When you log in to Puck Cloud with `connect`, the random ID is linked to your account.
228
+
229
+ To turn telemetry off, run:
230
+
231
+ ```sh
232
+ npx @puckeditor/cli telemetry disable
233
+ ```
234
+
235
+ Or set `PUCK_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1` in your environment. `telemetry status` shows whether it's on, and `PUCK_TELEMETRY_DEBUG=1` prints each event instead of sending it.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@puckeditor/cli",
3
- "version": "0.24.0-canary.55558da4",
3
+ "version": "0.24.0-canary.b7903763",
4
4
  "description": "Set up Puck and Puck Cloud from the command line. Built for coding agents, friendly for humans.",
5
5
  "author": "Chris Villa <chris@puckeditor.com>",
6
6
  "repository": {