diff --git a/AGENTS.md b/AGENTS.md
index c6bbc071..6a53443d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -113,7 +113,9 @@ Azure, `git push`, `npm publish`.
`package-lock.json` in sync. TypeScript strict, ESM only, `src/` uses no Node APIs (`types: []`).
8. **Telemetry** stays disclosed (console notice, `TELEMETRY.md`, both READMEs, CHANGELOG), sends no page text
unless the app opts in, keeps every opt-out (`telemetry: false`, `?genclass=no-telemetry`, localStorage, GPC) and
- never feeds a decision. Widening what is sent needs the owner's OK.
+ never feeds a decision. Widening what is sent needs the owner's OK. Owner, 2026-11-20: the `genclass` command's
+ setup turns interaction analytics on (`init --analytics`, said before it writes; `setup --no-analytics` and
+ `genclass analytics off` are the opt-outs and need no Pro); the runtime's own default stays off.
9. **Publish only through the release workflows**: `.github/workflows/release.yml` on a `v*` tag whose version
equals `packages/runtime/package.json`; `.github/workflows/release-mcp.yml` on a `mcp-v*` tag for
`@genclass/mcp` (its first version is published once by the owner from the workflow's tarball, because npm sets up
diff --git a/PRIVACY.md b/PRIVACY.md
index 0a0eadcf..9fff0918 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -47,7 +47,9 @@ object; version 0.2.1 sent from those hosts by default, by mistake, fixed in 0.2
function wrapped with `protect()`, on the decisions about what that function caused. A name that looks like data
(an e-mail address, a URL, 4 or more digits in a row, a long hex id) is sent as `[redacted]`.
- **How visitors use the site, only if the website's developer turned on interaction analytics** (`analytics: true`
- with a token; from runtime 0.3.0-beta.1, off by default): for each page view, the page's path (as above), how long
+ with a token; from runtime 0.3.0-beta.1, off by default in the runtime; the `genclass` command's setup, from
+ genclass 0.3.14, turns them on for an app it sets up unless the developer passes `--no-analytics`, and says so
+ before it writes anything): for each page view, the page's path (as above), how long
the page was visible and in use (at most 30 seconds after the last mouse, key, scroll or touch input), how far down
the page the visitor scrolled (25, 50, 75 or 100 %), and how many times each element was clicked, clicked 3 or more
times within a second, or clicked without anything changing on the page. An element is named from the page's code
diff --git a/docs/runtime/ANALYTICS.md b/docs/runtime/ANALYTICS.md
index 0f49931d..8cacb6f9 100644
--- a/docs/runtime/ANALYTICS.md
+++ b/docs/runtime/ANALYTICS.md
@@ -22,6 +22,15 @@ whatever its plan, and leaves them out of the stats it serves to a plan without
(`telemetry-worker/src/dashboard.ts` stripAnalytics), so an upgrade shows what was counted before it. Nothing in the
runtime changes with the plan, and a collector you host yourself shows them to everyone.
+**The `genclass` command's setup turns them on (owner, 2026-11-20).** "Turn on analytics in genclass setup by
+default so they can see visitors": from genclass 0.3.14 the setup's runtime step hands the runtime CLI's `init` the
+new `--analytics` flag, which writes `analytics: true` next to the app's token (`data-analytics="on"` on a script
+tag, `analytics=on` in the Astro meta line). The step's sentence and init's lines say what is counted, the consent
+advice of section 5 and the switch before anything is written; `genclass setup --no-analytics` leaves them out and
+`genclass analytics on` / `off` changes it later (`off` without Pro, like every opt-out). The runtime's own default
+stays off (`init` without the flag, the script tag, `GenClass.init()`), and an app set up before that release is not
+changed. Section 5 still holds: an app with visitors in the EU, the EEA or the UK starts analytics after consent.
+
**Where the genclass.dev paths are now.** Since 2026-10-18 the website and its admin (`site/`) live in the private
repository `genclass-dev/genclass-site`, which includes this repository as its `lib/` submodule. The paths `site/...`
in sections 6, 7 and 10 (`site/src/admin.js`, `site/src/worker.js`, `site/src/pages/privacy.html`) are in that
@@ -228,7 +237,8 @@ GenClass.init({ token: "gc_…", analytics: true });
```
- **Default: off.** It records nothing unless the app sets `analytics: true` (also `data-analytics="on"` on the
- script tag, ``, `window.GENCLASS_CONFIG.analytics`).
+ script tag, ``, `window.GENCLASS_CONFIG.analytics`). `init
+ --analytics` writes it; the `genclass` command's setup passes that flag unless `--no-analytics` (2026-11-20).
- **Needs telemetry and a token.** Analytics only feed a dashboard, so they are sent only on batches that carry the
app's token, or to a custom `telemetry.endpoint`. Without either, `analytics: true` warns once and stays off.
- **After consent.** `rt.analytics.start()` turns it on later, `rt.analytics.stop()` turns it off and drops the
diff --git a/docs/runtime/API.md b/docs/runtime/API.md
index 7f24284f..aa268c70 100644
--- a/docs/runtime/API.md
+++ b/docs/runtime/API.md
@@ -94,7 +94,9 @@ Every telemetry opt-out and Global Privacy Control turn them off; without a toke
`analytics: true` warns once and records nothing. They run in a lazy chunk (`dist/analytics/index.js`), outside the
event log: nothing reaches a situation, a decision or the model. `rt.analytics.start()` / `stop()` turn them on and
off later (consent; `stop()` drops the counts not sent yet and removes the visit entry). Also `data-analytics="on"`, `analytics=on` in the meta
-tag, `window.GENCLASS_CONFIG.analytics`. Schema: [TELEMETRY.md](../../packages/runtime/TELEMETRY.md#interaction-analytics).
+tag, `window.GENCLASS_CONFIG.analytics`; `init --analytics` writes the option and `init --no-analytics` takes it out
+(from the release after 0.3.0-beta.7), and the `genclass` command's setup turns it on unless it is run with
+`--no-analytics` (genclass 0.3.14). Schema: [TELEMETRY.md](../../packages/runtime/TELEMETRY.md#interaction-analytics).
With the script tag, a chunk that does not load warns once per load (`[GenClass] analytics: (@genclass/runtime
) did not load; nothing is recorded. ...`, `reason: "error"`), and a chunk of another release than the tag
warns once with both versions. `0.2.x` (npm's `latest` until 0.3.0)
diff --git a/docs/runtime/INSTALL.md b/docs/runtime/INSTALL.md
index 4dcd8482..7e48d81f 100644
--- a/docs/runtime/INSTALL.md
+++ b/docs/runtime/INSTALL.md
@@ -54,6 +54,8 @@ Content-Security-Policy (`next.config` headers, a proxy or middleware, a `` | init | use a self-hosted model directory (made with `fetch-model`), with ONNX Runtime from `ort/` |
| `--sink ` | init | also send findings to your own side: `console-json`, `console-json:noevidence` or `webhook:`; repeat the flag or comma-separate ([SINKS.md](SINKS.md)) |
| `--yes`, `-y` | both | apply without asking |
diff --git a/package-lock.json b/package-lock.json
index c6e939e2..3096bc9c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16819,7 +16819,7 @@
},
"packages/cli": {
"name": "genclass",
- "version": "0.3.13",
+ "version": "0.3.14",
"license": "Apache-2.0",
"bin": {
"genclass": "bin/genclass.mjs"
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index d71213f7..66dca6a3 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,24 @@
# Changelog
+## 0.3.14
+
+- **Setup turns visitor analytics on.** The runtime step now writes `analytics: true` next to the app's token, so an
+ app set up with `genclass` counts its visitors from the first deploy and `genclass analytics` and the dashboard's
+ Visitors have something to show: page views, time on a page, scroll depth, clicks per element (named from markup,
+ never its text), where visits come from and the device class. No cookies; one `localStorage` entry holds the visit;
+ nothing is counted on localhost, and a visitor's Global Privacy Control turns it off. The step's sentence says so,
+ the change is shown before it is written, and the lines under it say what is counted, how to turn it off, and that
+ where the law asks for a visitor's consent to analytics (the EU, EEA and UK) the app starts them with
+ `runtime.analytics.start()` once the visitor agrees. `genclass setup --no-analytics` adds GenClass without them.
+ An app set up before this release is not changed.
+- **`genclass analytics on`** and **`genclass analytics off`**: the switch for this folder's app, any time. It changes
+ that one option in what the setup added, shows the change first, and sends nothing. `off` (and
+ `genclass init --no-analytics`) works without Pro and signed out, like every opt-out.
+- `genclass analytics` and the dashboard's Visitors line say why no visit is counted: analytics are off in this app
+ (with the command that turns them on), or on and waiting for the deployed site's first visitors.
+- `genclass status` names `npx genclass init --analytics` for an app without GenClass: the command that does what the
+ step says.
+
## 0.3.13
- **`genclass site `**: the site check, which used to be on genclass.dev, now runs from the command only.
diff --git a/packages/cli/README.md b/packages/cli/README.md
index c879a30b..656caba7 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -88,7 +88,7 @@ it off). After that you type `genclass`, and every screen says `genclass` instea
|---|---|---|
| Account | Opens genclass.dev in your browser; you approve a short code there. | A session file in your user config folder. Nothing is typed in the terminal. |
| Pro | Right after the sign-in: Pro's 3-day free trial opens in your browser, and the command waits for it. Every step after it needs Pro. | Nothing in your project. The payment is on Stripe's page; the command never sees a card. |
-| Runtime | Adds GenClass to the app: one import (or script tag) and the package. It watches the page in your users' browsers for lost edits, double submits and old data shown over new, and only reports, to the console and your dashboard. Nothing is drawn on your pages. | Your entry file and `package.json`; you see the change first. `genclass remove` undoes it. |
+| Runtime | Adds GenClass to the app: one import (or script tag) and the package. It watches the page in your users' browsers for lost edits, double submits and old data shown over new, and only reports, to the console and your dashboard. Nothing is drawn on your pages. Visitor analytics are on too (`analytics: true` next to the app's token): page views, time on a page, scroll depth, clicks per element (never its text), where visits come from and the device class, with no cookies and nothing from localhost. `npx genclass setup --no-analytics` leaves them off, `npx genclass analytics off` turns them off later. Where the law asks for a visitor's consent to analytics (the EU, EEA and UK), set up without them and call `runtime.analytics.start()` once the visitor agrees. | Your entry file and `package.json`; you see the change first. `genclass remove` undoes it. |
| App plan | Once the app is in your account, its plan page opens in your browser once: Continue with Pro. Pro covers up to 3 apps; more apps come with Enterprise, by email. | Nothing in your project. |
| Dashboard | Waits for your live site to be opened once. GenClass sends nothing from localhost. | Nothing. |
| Test workflow | Runs your Playwright tests once more per pull request with slow and reordered responses. | One new file, `.github/workflows/genclass.yml`, which you commit. |
@@ -172,7 +172,7 @@ Each part of the browser dashboard has its own view, short first, `--all` for ev
| | |
|---|---|
| `npx genclass problems` | what was found, by kind and by page, the measured visual checks, what GenClass stopped on the visitor's screen, how it compares with the period before |
-| `npx genclass analytics` | visitors: visits, page views, time on a page, where people come from, devices and countries, what gets clicked again and again. One part in full: `analytics pages`, `sources`, `devices`, `clicks`, `paths`, `funnels` |
+| `npx genclass analytics` | visitors: visits, page views, time on a page, where people come from, devices and countries, what gets clicked again and again. One part in full: `analytics pages`, `sources`, `devices`, `clicks`, `paths`, `funnels`. `analytics on` and `analytics off` turn the counting on or off in this folder's app (the setup turns it on) |
| `npx genclass events` | the latest events one per line: when, kind, how sure the model was, the page, and what GenClass did |
| `npx genclass health` | how GenClass itself runs on your pages: model loads, where it ran, decision time, what was not checked, runtime versions |
| `npx genclass report` | the period as Markdown, to paste or pipe (`--out report.md` writes a file) |
@@ -280,11 +280,12 @@ first step and the agent prompt, with the model's own ideas and website designs.
| | |
|---|---|
| `npx genclass` | where the project stands; on a terminal, the next step, then the home |
-| `npx genclass setup` | the guided setup (`--yes`: no questions) |
+| `npx genclass setup` | the guided setup (`--yes`: no questions; `--no-analytics`: without visitor analytics) |
| `npx genclass status` | what is done and what is next (`--all`: every part; `--json`) |
| `npx genclass dashboard` | your app in the terminal (`--open` the browser dashboard) |
| `npx genclass problems` | every problem found, by kind and page, and what GenClass did |
| `npx genclass analytics [part]` | visitors; parts: `pages`, `sources`, `devices`, `clicks`, `paths`, `funnels` |
+| `npx genclass analytics on` \| `off` | count this app's visitors, or stop (changes one option in your code; `off` needs no Pro) |
| `npx genclass events` | the latest events, one per line |
| `npx genclass health` | how GenClass itself runs on your pages |
| `npx genclass report` | the period as Markdown (`--out `) |
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 1419f3e8..9f00d7a6 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "genclass",
- "version": "0.3.13",
+ "version": "0.3.14",
"description": "GenClass CLI: one command that sets GenClass up, shows your app in the terminal (problems, analytics, events), hands problems to your coding agent, answers questions about your app and tells you what it is missing.",
"type": "module",
"license": "Apache-2.0",
diff --git a/packages/cli/src/actions.mjs b/packages/cli/src/actions.mjs
index 1bece740..16e9006f 100644
--- a/packages/cli/src/actions.mjs
+++ b/packages/cli/src/actions.mjs
@@ -287,7 +287,10 @@ async function waitForPlan(offer, o = {}, deps = {}) {
* The arguments the runtime step hands to the runtime CLI's `init` (a fresh project) or `connect` (added, not in
* the account yet). `init` gets --no-devtools: GenClass set up by this command draws nothing on a page, not on the
* deployed site (it never did) and not on localhost either (the developer overlay is left out). What it finds goes
- * to the browser console, the dashboard and `genclass dashboard`.
+ * to the browser console, the dashboard and `genclass dashboard`. It also gets --analytics (the owner's call,
+ * 2026-11-20): an app set up by this command counts its visitors from the first deploy, so `genclass analytics` and
+ * the dashboard's Visitors have something to show; the step's sentence and init's own lines say so before anything
+ * is written, and `setup --no-analytics` (o.noAnalytics) leaves it out.
*/
export function runtimeArgs(state, o = {}) {
const connect = state.steps.find((s) => s.id === "runtime")?.run === "npx genclass connect";
@@ -296,7 +299,7 @@ export function runtimeArgs(state, o = {}) {
// account this is, and the account is the one signed in. init gets --in-account (signed in one step earlier, so
// the app goes into that account without asking again), --no-devtools and --brief (the walk has its own header,
// so init says the same things in a few lines)
- return connect ? { cmd: "connect", args } : { cmd: "init", args: [...args, ...(state.signedIn ? ["--in-account"] : []), "--no-devtools", "--brief"] };
+ return connect ? { cmd: "connect", args } : { cmd: "init", args: [...args, ...(state.signedIn ? ["--in-account"] : []), "--no-devtools", ...(o.noAnalytics ? [] : ["--analytics"]), "--brief"] };
}
/**
@@ -357,6 +360,40 @@ export async function sameApp(state, o = {}) {
};
}
+/**
+ * `genclass analytics on` and `off`: turns visitor analytics on or off in what the setup added to this folder's app,
+ * with the runtime CLI's own init (it shows the one-line change and asks; --yes: no question). Nothing is sent. An
+ * app without GenClass is pointed at the setup, one set up by hand at its own GenClass.init(). Returns the exit code.
+ */
+export async function switchAnalytics(on, o = {}) {
+ let st = null;
+ try {
+ st = inspectProject({ cwd: o.cwd });
+ } catch {
+ st = null;
+ }
+ if (!st || st.fresh) {
+ out();
+ note(`GenClass is not in this app yet. ${c.cyan("npx genclass setup")} adds it${on ? ", with visitor analytics on" : ""}.`);
+ out();
+ return 1;
+ }
+ if (st.analytics === on) {
+ out();
+ good(`Visitor analytics are already ${on ? "on" : "off"} in this app.`);
+ if (on) note("Visits are counted on the deployed site, never from localhost.");
+ out();
+ return 0;
+ }
+ if (st.handWritten) {
+ out();
+ note(`GenClass is set up by hand here, so this command leaves the code alone: ${on ? "add analytics: true to" : "take analytics: true out of"} your GenClass.init({ ... }) options.`);
+ out();
+ return 1;
+ }
+ return runInit("init", ["--cwd", st.cwd, ...(o.yes ? ["--yes"] : []), on ? "--analytics" : "--no-analytics"]);
+}
+
/** Shows the two Vite settings and writes them on a yes (--yes, or one question on a terminal). */
export async function addViteSettings(state, o = {}) {
let plan = null;
diff --git a/packages/cli/src/app.mjs b/packages/cli/src/app.mjs
index a0a6870c..18f4f2af 100644
--- a/packages/cli/src/app.mjs
+++ b/packages/cli/src/app.mjs
@@ -153,7 +153,7 @@ export function render(app, state, o = {}) {
if (app.visitors) {
const v = app.visitors;
const bounce = v.visits ? ` · ${Math.round((v.bounces / v.visits) * 100)}% left after one page` : "";
- part("Visitors", v.visits ? `${plural(v.visits, "visit")} · ${plural(v.pages, "page view")}${bounce}` : c.gray("none counted in this period (analytics is opt-in: genclass.dev/docs)"));
+ part("Visitors", v.visits ? `${plural(v.visits, "visit")} · ${plural(v.pages, "page view")}${bounce}` : c.gray(!state.app ? "none counted in this period" : state.app.analytics ? "none counted in this period (the deployed site only)" : "off in this app: npx genclass analytics on"));
if (v.visits && v.entry.length) for (const l of wrap(`came in on ${v.entry.slice(0, all ? 10 : 3).map((e) => `${clean(e.key, 30)} (${n(e.count)})`).join(", ")}`, width() - 4 - 15)) out(` ${" ".repeat(15)}${c.gray(l)}`);
} else if (app.visitorsPlan) part("Visitors", c.gray(`visitor analytics come with the ${clean(app.visitorsPlan.plan ?? "Pro", 20)} plan${app.visitorsPlan.upgradeUrl ? `: ${app.visitorsPlan.upgradeUrl}` : ""}`));
if (u && u.limit !== null) part("Live fixes", u.observeOnly ? c.yellow(`${n(u.used)} of ${n(u.limit)} this month · observing only`) : `${n(u.used)} of ${n(u.limit)} this month`);
diff --git a/packages/cli/src/cli.mjs b/packages/cli/src/cli.mjs
index a4516ba7..9ee964eb 100644
--- a/packages/cli/src/cli.mjs
+++ b/packages/cli/src/cli.mjs
@@ -12,8 +12,9 @@
// - The command is Pro's (the owner's call, 2026-11-13): every command but FREE_COMMANDS passes paywall.mjs
// requirePro first (signed out: the sign-in, then Pro with its free trial), the home's commands (ctx.nested)
// included. The walk (`genclass`, `setup`) has Pro as its own step right after the sign-in (state.mjs).
-// - Every opt-out keeps working without Pro (AGENTS.md rule 8): `init --no-telemetry` and `init --telemetry` on an
-// app that has GenClass change only that option, and pass without the gate.
+// - Every opt-out keeps working without Pro (AGENTS.md rule 8): `init --no-telemetry`, `init --telemetry` and
+// `init --no-analytics` on an app that has GenClass change only that option, and pass without the gate; so does
+// `analytics off`, the same switch by its short name.
// - A command's own usage errors come before the gate: nothing is asked of genclass.dev for words that are wrong.
// - Nothing here reads the network but that gate, and nothing reads a file but the two checks before it (whether
// the app has GenClass, for the opt-out; its private dashboard link, signed out): it parses and dispatches.
@@ -27,13 +28,13 @@ import { width, wrap } from "./tui.mjs";
const HELP = [
[null, [
["npx genclass", "the command's prompt, for commands and questions (the first time in a folder, the setup first)"],
- ["npx genclass setup", "the guided setup, any time, to add or change a part (--yes: no questions, for a coding agent)"],
+ ["npx genclass setup", "the guided setup, any time, to add or change a part (--yes: no questions, for a coding agent; --no-analytics: add GenClass without visitor analytics, which are on otherwise)"],
["npx genclass status", "what is done, what is next (--all: every part; --json)"],
]],
["See", [
["npx genclass dashboard", "your app, whole: problems found, checks, visitors, agent, GitHub App"],
["npx genclass problems", "every problem found, by kind and page, and what GenClass did about it"],
- ["npx genclass analytics", "visitors: visits, pages, time, where they come from, what they click (one part in full: analytics pages | sources | devices | clicks | paths | funnels)"],
+ ["npx genclass analytics", "visitors: visits, pages, time, where they come from, what they click (one part in full: analytics pages | sources | devices | clicks | paths | funnels; analytics on | off: count this app's visitors, or stop)"],
["npx genclass events", "the latest events, one per line (--all: each one's mode and trigger)"],
["npx genclass health", "how GenClass itself runs on your pages (--all: every breakdown)"],
["npx genclass report", "the period as Markdown (--out report.md)"],
@@ -102,7 +103,7 @@ export function usage(cols = width()) {
/** The help at the default width (80 columns), for tests and anything that wants it as one string. */
export const USAGE = usage(80);
-const BOOL = { 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" };
+const BOOL = { yes: "yes", y: "yes", json: "json", "no-browser": "noBrowser", "no-model": "noModel", "no-analytics": "noAnalytics", all: "all", help: "help", h: "help", version: "version", v: "version", open: "open", print: "print", copy: "copy" };
const VALUE = { cwd: "cwd", url: "url", app: "app", range: "range", from: "from", to: "to", format: "format", out: "out", agent: "agent", user: "user", "login-page": "loginPage" };
/** The flags this file knows, and what is left ({ o, rest }); an unknown flag stays in `rest` for the command it is for. */
@@ -268,10 +269,14 @@ export async function run(argv, ctx = {}) {
}
// the words of the commands that take them, before anything is asked of genclass.dev
const { ANALYTICS_SECTIONS } = cmd === "analytics" ? await import("./views.mjs") : { ANALYTICS_SECTIONS: [] };
- if (cmd === "analytics" && words[0] && !ANALYTICS_SECTIONS.includes(words[0])) {
- err(`genclass analytics: there is no part ${c.bold(words[0])}. The parts: ${ANALYTICS_SECTIONS.join(", ")}`);
+ // `analytics on` and `analytics off`: the switch for this folder's app (actions.mjs switchAnalytics)
+ const toggle = cmd === "analytics" && (words[0] === "on" || words[0] === "off") ? words[0] : null;
+ if (cmd === "analytics" && words[0] && !toggle && !ANALYTICS_SECTIONS.includes(words[0])) {
+ err(`genclass analytics: there is no part ${c.bold(words[0])}. The parts: ${ANALYTICS_SECTIONS.join(", ")}; and ${c.cyan("analytics on")} or ${c.cyan("analytics off")}`);
return 2;
}
+ // off is an opt-out: like init --no-telemetry it works for everyone, with no sign-in and no Pro (AGENTS.md rule 8)
+ if (toggle === "off") return (await import("./actions.mjs")).switchAnalytics(false, o);
if (cmd === "agent" && words[0] && words[0] !== "link") {
err(`genclass agent: there is no ${c.bold(words[0])}. Try ${c.cyan("npx genclass agent")} or ${c.cyan("npx genclass agent link")}`);
return 2;
@@ -290,6 +295,7 @@ export async function run(argv, ctx = {}) {
}
if (cmd === "dashboard") return upsold((await import("./app.mjs")).dashboard(o, { fallback }));
if (["problems", "events", "health", "report"].includes(cmd)) return upsold((await import("./views.mjs"))[cmd](o), cmd !== "report");
+ if (toggle === "on") return (await import("./actions.mjs")).switchAnalytics(true, o);
if (cmd === "analytics") return upsold((await import("./views.mjs")).analytics({ ...o, section: words[0] ?? null }));
if (cmd === "agent") {
if (words[0] === "link") return (await import("./manage.mjs")).agentLink(o);
@@ -386,14 +392,17 @@ async function ownLogin(po) {
/** init's options that leave what it does at the telemetry switch: where, whether to ask, and what not to run. */
const TOGGLE_WITH = new Set(["--yes", "-y", "--dry-run", "--no-install", "--no-network"]);
-/** Whether `init`'s arguments only turn the anonymous diagnostics off (--no-telemetry) or back on (--telemetry). */
+/**
+ * Whether `init`'s arguments only turn the anonymous diagnostics off (--no-telemetry) or back on (--telemetry), or
+ * visitor analytics off (--no-analytics): the opt-outs, which pass without Pro.
+ */
export function telemetryOnly(args) {
let toggle = false;
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === "--cwd") i++;
else if (a.startsWith("--cwd=")) continue;
- else if (a === "--no-telemetry" || a === "--telemetry") toggle = true;
+ else if (a === "--no-telemetry" || a === "--telemetry" || a === "--no-analytics") toggle = true;
else if (!TOGGLE_WITH.has(a)) return false;
}
return toggle;
diff --git a/packages/cli/src/setup.mjs b/packages/cli/src/setup.mjs
index ac8ed6ef..935eedf1 100644
--- a/packages/cli/src/setup.mjs
+++ b/packages/cli/src/setup.mjs
@@ -140,7 +140,8 @@ export async function status(o = {}) {
/**
* `genclass setup` (and `genclass` on a terminal): walks the steps. `runSuggest` runs the suggestions step (passed in
* by cli.mjs, so this module does not load the checks until they are needed). Exit code 0, or 1 when a step failed.
- * @param {{ cwd?: string, yes?: boolean, noBrowser?: boolean, json?: boolean, all?: boolean }} o
+ * @param {{ cwd?: string, yes?: boolean, noBrowser?: boolean, json?: boolean, all?: boolean, noAnalytics?: boolean }} o
+ * noAnalytics: the runtime step adds GenClass without visitor analytics (they are on by default)
* @param {{ runSuggest?: (o: object) => Promise }} [deps]
*/
export async function setup(o = {}, deps = {}) {
@@ -169,7 +170,7 @@ async function walk(o, deps, auto) {
let welcomed = false;
let signInTries = 0;
for (let turn = 0; turn < 14; turn++) {
- const state = await readState({ cwd: o.cwd, skip });
+ const state = await readState({ cwd: o.cwd, skip, noAnalytics: o.noAnalytics });
const step = state.next;
let go = auto;
// the view, and (on a terminal) the keys: Enter starts the step, d unfolds or folds every part, s skips, q stops
diff --git a/packages/cli/src/state.mjs b/packages/cli/src/state.mjs
index 0f31806f..32e6aad1 100644
--- a/packages/cli/src/state.mjs
+++ b/packages/cli/src/state.mjs
@@ -263,12 +263,15 @@ export async function readState(o = {}, deps = {}) {
? `added · Vite ${vite.major} needs two build settings`
: `${st.handWritten ? "added by hand" : "added"}${app ? ` · app "${app.name}"` : ""}`,
why: st.fresh
- ? "One import and the package. You see the change first. Nothing is drawn on your pages."
+ ? o.noAnalytics
+ ? "One import and the package. You see the change first. Nothing is drawn on your pages."
+ : "One import and the package. It counts visitors too. You see it first. Nothing is drawn on pages."
: vite
? `Without them "vite build" fails on Vite ${vite.major}. You see the change first.`
: "Gives the app its place in your account, so what it finds shows on your dashboard.",
- more: "The runtime watches the page in your users' browsers for lost edits, double submits and old data shown over new. It only reports, to the browser console and your dashboard: it never holds, delays or changes anything your app does, and it puts nothing on the page.",
- run: st.fresh ? "npx genclass init" : vite ? "npx genclass setup" : "npx genclass connect",
+ more: `The runtime watches the page in your users' browsers for lost edits, double submits and old data shown over new. It only reports, to the browser console and your dashboard: it never holds, delays or changes anything your app does, and it puts nothing on the page.${st.fresh && !o.noAnalytics ? " Visitor analytics are on too: page views, time on a page, clicks per element (never its text) and where visits come from, with no cookies. Without them: npx genclass setup --no-analytics. Where the law asks for a visitor's consent to analytics (the EU, EEA and UK), set up without them and start them once the visitor agrees." : ""}`,
+ // the command that does what the sentence above says: init turns visitor analytics on only when asked to
+ run: st.fresh ? (o.noAnalytics ? "npx genclass init" : "npx genclass init --analytics") : vite ? "npx genclass setup" : "npx genclass connect",
human: null,
});
@@ -406,7 +409,7 @@ export async function readState(o = {}, deps = {}) {
return {
cwd,
host: host.overridden && !host.error ? host.host : null,
- 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) }) },
+ app: { name: app?.name ?? project.name ?? null, framework: project.label || null, isApp, token: st.token ?? null, analytics: !!st.analytics, dashboardUrl: app?.dashboard_url ?? st.local?.dashboardUrl ?? null, site: notes.site ?? null, ...(isApp ? {} : { below: appsBelow(cwd) }) },
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,
signedIn: !!me,
/** the account's apps as genclass.dev lists them ([] signed out) */
@@ -449,7 +452,7 @@ export const planName = (state, token = state?.app?.token) => (state?.projects ?
/** The command for a step as a coding agent runs it: without a terminal the walk does a step only with --yes. */
// init and connect too: without --yes they write nothing, so an agent told "npx genclass init" would read the same
// state and be told it again, for ever (the 0.3.9 user stories); setup --yes does the step the way the walk does it
-const forAgent = (run) => (["npx genclass setup", "npx genclass init", "npx genclass connect"].includes(run) ? "npx genclass setup --yes" : run);
+const forAgent = (run) => (["npx genclass setup", "npx genclass init", "npx genclass init --analytics", "npx genclass connect"].includes(run) ? "npx genclass setup --yes" : run);
export function stateJson(s) {
// a step that waits on nothing (an app the plan already covers: its page's Continue is offered, not required) is
diff --git a/packages/cli/src/views.mjs b/packages/cli/src/views.mjs
index 43a3ea7b..17c08b63 100644
--- a/packages/cli/src/views.mjs
+++ b/packages/cli/src/views.mjs
@@ -87,7 +87,10 @@ export function bars(title, rows, o = {}) {
export const ANALYTICS_SECTIONS = ["pages", "sources", "devices", "clicks", "paths", "funnels"];
-/** The lines of `genclass analytics`. `section`: one of ANALYTICS_SECTIONS, or null for every section, short. */
+/**
+ * The lines of `genclass analytics`. `section`: one of ANALYTICS_SECTIONS, or null for every section, short. `here`:
+ * { analytics } when the app shown is this folder's (whether visitor analytics are on in its code), else null.
+ */
export function renderAnalytics(app, o = {}) {
const m = app.more;
const b = m.breakdowns;
@@ -117,8 +120,8 @@ export function renderAnalytics(app, o = {}) {
out(` ${c.bold(`Visitor analytics come with the ${clean(app.visitorsPlan.plan ?? "Pro", 20)} plan.`)}`);
// "already counted" only when the app sends visitor events (page views in the totals); else it is the app's switch
const counted = (t?.ix_views ?? 0) > 0 || (app.totals?.pageViews ?? 0) > 0;
- 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:");
- if (!counted) out(` ${c.cyan("https://genclass.dev/docs/analytics")}`);
+ 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. ${o.here?.analytics ? "This app counts them already, with no cookies." : "Your app turns it on with one line, no cookies:"}`);
+ if (!counted && !o.here?.analytics) out(` ${c.cyan("npx genclass analytics on")}`);
out(` ${c.cyan("npx genclass plan")}`);
out();
return;
@@ -127,7 +130,7 @@ export function renderAnalytics(app, o = {}) {
const views = t.ix_views ?? v.pages;
if (!v.visits && !views && only !== "funnels") {
out();
- note("No visits counted in this period. Visitor analytics is something your app turns on (one line, no cookies): https://genclass.dev/docs/analytics. GenClass counts nothing from localhost.");
+ note(`No visits counted in this period. ${noVisits(o.here)} GenClass counts nothing from localhost.`);
out();
return;
}
@@ -241,12 +244,20 @@ export function renderAnalytics(app, o = {}) {
const ix = (o) => Object.fromEntries(Object.entries(o).filter(([k]) => k.startsWith("ix_")));
-/** `genclass analytics [pages|sources|devices|clicks|paths|funnels]`. */
+/** Why no visit is counted: analytics off in this folder's app (and the command that turns them on), on and waiting for visitors, or another app. */
+const noVisits = (here) =>
+ !here
+ ? "Visitor analytics are something the app turns on, in its folder: npx genclass analytics on."
+ : here.analytics
+ ? "Visitor analytics are on in this app: visits show once the deployed site has visitors."
+ : "Visitor analytics are off in this app. Turn them on: npx genclass analytics on.";
+
+/** `genclass analytics [pages|sources|devices|clicks|paths|funnels]`, and `analytics on | off` (actions.mjs switchAnalytics). */
export function analytics(o = {}, deps = {}) {
return appView(o, deps, {
name: "analytics",
json: (app, _s, target) => ({ ok: true, app: target.name, range: app.range, demo: app.demo, locked: app.visitorsPlan, visitors: app.visitors, exit: app.more.exit, totals: ix(app.more.totals), breakdowns: ix(app.more.breakdowns), series: app.more.series.map((x) => ({ bucket: x.bucket, visits: x.visits, views: x.views })), funnels: app.more.funnels }),
- show: (app) => renderAnalytics(app, { all: o.all, section: o.section, now: deps.now }),
+ show: (app, state, target) => renderAnalytics(app, { all: o.all, section: o.section, now: deps.now, here: state.app.token && state.app.token === target.token ? { analytics: !!state.app.analytics } : null }),
});
}
diff --git a/packages/cli/test/actions.test.ts b/packages/cli/test/actions.test.ts
index eb9ff4b4..86046bf2 100644
--- a/packages/cli/test/actions.test.ts
+++ b/packages/cli/test/actions.test.ts
@@ -116,8 +116,10 @@ describe("genclass: nothing is drawn on a page (src/actions.mjs runtimeArgs)", (
const dir = tempDir();
viteApp(dir);
const fresh = { cwd: dir, signedIn: true, steps: [{ id: "runtime", run: "npx genclass init" }] } as never;
- expect(runtimeArgs(fresh, { yes: true })).toEqual({ cmd: "init", args: ["--cwd", dir, "--yes", "--in-account", "--no-devtools", "--brief"] });
- expect(runtimeArgs({ cwd: dir, signedIn: false, steps: [{ id: "runtime", run: "npx genclass init" }] } as never, {})).toEqual({ cmd: "init", args: ["--cwd", dir, "--no-devtools", "--brief"] });
+ expect(runtimeArgs(fresh, { yes: true })).toEqual({ cmd: "init", args: ["--cwd", dir, "--yes", "--in-account", "--no-devtools", "--analytics", "--brief"] });
+ expect(runtimeArgs({ cwd: dir, signedIn: false, steps: [{ id: "runtime", run: "npx genclass init" }] } as never, {})).toEqual({ cmd: "init", args: ["--cwd", dir, "--no-devtools", "--analytics", "--brief"] });
+ // setup --no-analytics: the app is added without visitor analytics
+ expect(runtimeArgs(fresh, { yes: true, noAnalytics: true })).toEqual({ cmd: "init", args: ["--cwd", dir, "--yes", "--in-account", "--no-devtools", "--brief"] });
// an app that already has the runtime is only put in the account: nothing in its code is touched
// connect takes only its own options: it asks which app of the signed-in account this is
expect(runtimeArgs({ cwd: dir, signedIn: true, steps: [{ id: "runtime", run: "npx genclass connect" }] } as never, {})).toEqual({ cmd: "connect", args: ["--cwd", dir] });
@@ -308,6 +310,55 @@ describe("genclass: the command line (src/cli.mjs, src/main.mjs)", () => {
});
});
+describe("genclass: the setup turns visitor analytics on, says so first, and one command turns them off (src/actions.mjs runtimeArgs, switchAnalytics)", () => {
+ const TOKEN = "gc_Mine0123456789abcdefgh";
+ it("init with the step's arguments writes analytics: true next to the token and says what is counted, the consent advice and the switch", async () => {
+ const dir = tempDir();
+ viteApp(dir);
+ const { args } = runtimeArgs({ cwd: dir, signedIn: false, steps: [{ id: "runtime", run: "npx genclass init --analytics" }] } as never, { yes: true });
+ const { run: runInit, inspectProject } = await import("../../runtime/bin/lib/init.mjs");
+ const said = await printed(async () => expect(await runInit("init", [...args, "--no-install", "--no-network", "--token", TOKEN])).toBe(0));
+ const flat = said.replace(/\s+/g, " ");
+ expect(flat).toContain("Visitor analytics are on: page views, time on a page, scroll depth, clicks per element (never its text)");
+ expect(flat).toContain("No cookies; one localStorage entry holds the visit. Never from localhost.");
+ expect(flat).toMatch(/consent to analytics \(the EU, EEA and UK\), turn them off and call runtime\.analytics\.start\(\)/);
+ // the switch, as this command names it (run by the runtime CLI itself it is init's own flag)
+ expect(said).toMatch(/Off: \S.* (?:analytics off|init --no-analytics)/);
+ expect(readFileSync(join(dir, "src/genclass.config.js"), "utf8")).toContain(`globalThis.GENCLASS_CONFIG = { token: "${TOKEN}", analytics: true };`);
+ expect(inspectProject({ cwd: dir }).analytics).toBe(true);
+ // without the flag (setup --no-analytics) nothing of it is said or written
+ const plain = tempDir();
+ viteApp(plain);
+ const quiet = await printed(async () => expect(await runInit("init", [...runtimeArgs({ cwd: plain, signedIn: false, steps: [{ id: "runtime", run: "npx genclass init" }] } as never, { yes: true, noAnalytics: true }).args, "--no-install", "--no-network", "--token", TOKEN])).toBe(0));
+ expect(quiet).not.toMatch(/analytics/i);
+ expect(readFileSync(join(plain, "src/genclass.config.js"), "utf8")).not.toContain("analytics");
+ expect(inspectProject({ cwd: plain }).analytics).toBe(false);
+ });
+
+ it("analytics off and on change that one option in what the setup added; an app without GenClass is pointed at the setup", async () => {
+ const { switchAnalytics } = await import("../src/actions.mjs");
+ const { run: runInit } = await import("../../runtime/bin/lib/init.mjs");
+ const dir = tempDir();
+ viteApp(dir);
+ await printed(async () => expect(await runInit("init", ["--cwd", dir, "--yes", "--no-install", "--no-network", "--token", TOKEN, "--analytics"])).toBe(0));
+ const config = () => readFileSync(join(dir, "src/genclass.config.js"), "utf8");
+ const entry = readFileSync(join(dir, "src/main.jsx"), "utf8");
+ const already = await printed(async () => expect(await switchAnalytics(true, { cwd: dir, yes: true })).toBe(0));
+ expect(already).toContain("Visitor analytics are already on in this app.");
+ await printed(async () => expect(await switchAnalytics(false, { cwd: dir, yes: true })).toBe(0));
+ expect(config()).toContain(`GENCLASS_CONFIG = { token: "${TOKEN}" };`);
+ await printed(async () => expect(await switchAnalytics(true, { cwd: dir, yes: true })).toBe(0));
+ expect(config()).toContain(`GENCLASS_CONFIG = { token: "${TOKEN}", analytics: true };`);
+ // only the options file changed
+ expect(readFileSync(join(dir, "src/main.jsx"), "utf8")).toBe(entry);
+ const fresh = tempDir();
+ viteApp(fresh);
+ const none = await printed(async () => expect(await switchAnalytics(true, { cwd: fresh, yes: true })).toBe(1));
+ expect(none.replace(/\s+/g, " ")).toContain("GenClass is not in this app yet. npx genclass setup adds it, with visitor analytics on.");
+ expect(existsSync(join(fresh, "src/genclass.config.js"))).toBe(false);
+ });
+});
+
describe("genclass: the runtime step hands the runtime CLI only options it takes (src/actions.mjs runtimeArgs)", () => {
// genclass 0.2.x to 0.3.2 passed --in-account to connect, which refused it, printed its usage, and the walk went
// on: a project already set up but not in the account could never be put there (seen on a real project,
diff --git a/packages/cli/test/gate.test.ts b/packages/cli/test/gate.test.ts
index d6e61560..116f4a08 100644
--- a/packages/cli/test/gate.test.ts
+++ b/packages/cli/test/gate.test.ts
@@ -54,6 +54,9 @@ describe("genclass without Pro: every opt-out and the app's own link keep workin
expect(telemetryOnly(["--telemetry", "--cwd", "web", "--yes", "--dry-run", "--no-install", "--no-network"])).toBe(true);
expect(telemetryOnly(["--no-telemetry", "--mode", "guard"])).toBe(false);
expect(telemetryOnly(["--yes"])).toBe(false);
+ // visitor analytics: turning them off is an opt-out, turning them on is the command's
+ expect(telemetryOnly(["--no-analytics", "--yes"])).toBe(true);
+ expect(telemetryOnly(["--analytics"])).toBe(false);
// on an app without GenClass, init --no-telemetry would add it: that is the command's, behind the gate
const fresh = tempDir();
viteApp(fresh);
@@ -62,6 +65,30 @@ describe("genclass without Pro: every opt-out and the app's own link keep workin
expect(existsSync(join(fresh, "src/genclass.config.js"))).toBe(false);
});
+ it("visitor analytics are turned off signed out, with no gate: analytics off, and init --no-analytics; turning them on is behind it", async () => {
+ const dir = tempDir();
+ viteApp(dir);
+ await printed(async () => expect(await runInit("init", ["--cwd", dir, "--yes", "--no-install", "--no-network", "--token", TOKEN, "--analytics"])).toBe(0));
+ const config = () => readFileSync(join(dir, "src/genclass.config.js"), "utf8");
+ expect(config()).toContain("analytics: true");
+ forgetPro();
+ const off = await printed(async () => expect(await run(["analytics", "off", "--yes", "--cwd", dir])).toBe(0));
+ expect(off).not.toContain("Sign in first");
+ expect(config()).not.toContain("analytics");
+ const on = await printed(async () => expect(await run(["analytics", "on", "--yes", "--cwd", dir])).toBe(1));
+ expect(flat(on)).toContain("Sign in first: npx genclass login");
+ expect(config()).not.toContain("analytics");
+ // the same switch by init's own flag
+ await printed(async () => expect(await runInit("init", ["--cwd", dir, "--yes", "--no-install", "--no-network", "--analytics"])).toBe(0));
+ expect(config()).toContain("analytics: true");
+ const flag = await printed(async () => expect(await run(["init", "--no-analytics", "--yes", "--no-install", "--cwd", dir])).toBe(0));
+ expect(flag).not.toContain("Sign in first");
+ expect(config()).not.toContain("analytics");
+ // a word that is neither a part nor the switch is a usage error
+ const r = await quietErr(() => printed(async () => expect(await run(["analytics", "maybe", "--cwd", dir])).toBe(2)));
+ expect(r.err).toMatch(/there is no part .*maybe.*analytics on.* or .*analytics off/s);
+ });
+
it("a command's own usage error comes before the gate: nothing is asked of genclass.dev for words that are wrong", async () => {
const dir = tempDir();
viteApp(dir);
diff --git a/packages/cli/test/state.test.ts b/packages/cli/test/state.test.ts
index ca417a56..3600bcf9 100644
--- a/packages/cli/test/state.test.ts
+++ b/packages/cli/test/state.test.ts
@@ -46,9 +46,18 @@ describe("genclass: the state of a project (src/state.mjs header)", () => {
const s = await readState({ cwd: dir }, { runGit: noGit, fetchFn: server.fetchFn });
expect(server.calls).toEqual([]);
expect(states(s)).toEqual({ account: "next", plan: "todo", runtime: "todo", "app-plan": "optional", dashboard: "todo", workflow: "optional", "github-app": "optional", agent: "todo", suggestions: "todo" });
- expect(s.steps.find((x) => x.id === "runtime")!).toMatchObject({ run: "npx genclass init", detail: "Vite + React" });
+ // the step says that visitors are counted too, and names the command that does that (init alone leaves them off)
+ const rt = s.steps.find((x) => x.id === "runtime")!;
+ expect(rt).toMatchObject({ run: "npx genclass init --analytics", detail: "Vite + React" });
+ expect(rt.why).toContain("It counts visitors too.");
+ expect(rt.more).toContain("npx genclass setup --no-analytics");
+ expect(rt.more).toMatch(/consent to analytics \(the EU, EEA and UK\)/);
+ // setup --no-analytics: the sentence and the command say nothing of visitors
+ const plain = (await readState({ cwd: dir, noAnalytics: true }, { runGit: noGit, fetchFn: server.fetchFn })).steps.find((x) => x.id === "runtime")!;
+ expect(plain.run).toBe("npx genclass init");
+ expect(`${plain.why} ${plain.more}`).not.toMatch(/visitor|analytics/i);
expect(s.steps.find((x) => x.id === "workflow")!.detail).toBe("not a git repository yet");
- expect(s.app).toMatchObject({ name: "shop", framework: "Vite + React", isApp: true, token: null });
+ expect(s.app).toMatchObject({ name: "shop", framework: "Vite + React", isApp: true, token: null, analytics: false });
});
it("signed in: the account and its plan are read once, and adding the runtime is next", async () => {
diff --git a/packages/cli/test/views.test.ts b/packages/cli/test/views.test.ts
index a34e6b03..73f392c7 100644
--- a/packages/cli/test/views.test.ts
+++ b/packages/cli/test/views.test.ts
@@ -74,6 +74,12 @@ describe("genclass analytics (src/views.mjs renderAnalytics)", () => {
const none = await at(58, async () => renderAnalytics(await appOf({ totals: {}, breakdowns: {}, visits: { sessions: 0, pages: 0, bounces: 0, entry: [], exit: [] } }), { now: NOW }));
expect(none).toContain("No visits counted in this period.");
expect(plainLines(none).join(" ").replace(/\s+/g, " ")).toContain("GenClass counts nothing from localhost.");
+ // for this folder's app it says whether its code counts visitors, and the command that turns that on
+ const empty = { totals: {}, breakdowns: {}, visits: { sessions: 0, pages: 0, bounces: 0, entry: [], exit: [] } };
+ const flat = (t: string) => plainLines(t).join(" ").replace(/\s+/g, " ");
+ expect(flat(await at(58, async () => renderAnalytics(await appOf(empty), { now: NOW, here: { analytics: false } })))).toContain("Visitor analytics are off in this app. Turn them on: npx genclass analytics on.");
+ expect(flat(await at(58, async () => renderAnalytics(await appOf(empty), { now: NOW, here: { analytics: true } })))).toContain("Visitor analytics are on in this app: visits show once the deployed site has visitors.");
+ expect(flat(none)).toContain("in its folder: npx genclass analytics on.");
});
it("bars() and time(): a share of the whole, a label cut to the window, minutes and seconds", async () => {
diff --git a/packages/runtime/CHANGELOG.md b/packages/runtime/CHANGELOG.md
index 316a409b..a2cf7000 100644
--- a/packages/runtime/CHANGELOG.md
+++ b/packages/runtime/CHANGELOG.md
@@ -1,5 +1,18 @@
# Changelog
+## Unreleased
+
+- **`init --analytics`** turns on interaction analytics for the app's dashboard, and **`init --no-analytics`** takes
+ the option out again. The runtime's default is unchanged: off. `--analytics` writes `analytics: true` in the option
+ file (`genclass.config.ts/js`), `data-analytics="on"` on a plain HTML script tag, `analytics=on` in the Astro meta
+ line, all inside init's markers, so `remove` takes them out; on a setup init already made it changes that one
+ option in place. init says what is counted and kept (page views, time on a page, scroll depth, clicks per element,
+ where visits come from, the device class; no cookies, one `localStorage` entry), the consent advice for the EU, EEA
+ and UK, and how to turn it off, before anything is written. Analytics need the app's token and telemetry on: with
+ `--no-telemetry` or `--no-token` the flag is a usage error, a setup without a token is told so and gets no option,
+ and when a token cannot be made the option is left out with it. The `genclass` command's setup passes `--analytics`
+ from genclass 0.3.14 (owner, 2026-11-20), with `--no-analytics` to leave it out (`bin/lib/init.mjs`, `edit.mjs`).
+
## 0.3.0-beta.7 (2026-11-16)
- **`init` no longer adds the devtools overlay** (owner, 2026-11-16: nothing GenClass sets up is drawn on a page;
diff --git a/packages/runtime/README.md b/packages/runtime/README.md
index 8ff4510c..66c89dad 100644
--- a/packages/runtime/README.md
+++ b/packages/runtime/README.md
@@ -478,7 +478,9 @@ npx @genclass/runtime@beta remove # undo exactly what init added
```
Other flags: `--yes`, `--no-telemetry` (`--telemetry` undoes it on a later run and writes no telemetry option, so
-the default applies: on, but off on local hosts), `--no-token`, `--token gc_...`, `--sink`, `--model-url`, `--no-install`,
+the default applies: on, but off on local hosts), `--analytics` (from the release after `0.3.0-beta.7`: turns on
+[interaction analytics](TELEMETRY.md#interaction-analytics) for the app's dashboard, which are off by default and need
+the app's token; `--no-analytics` takes the option out again), `--no-token`, `--token gc_...`, `--sink`, `--model-url`, `--no-install`,
`--devtools`, and from `0.3.0-beta.2` `--no-network` and `--sync` (plain HTML). `init` of 0.3.0-beta.6 and earlier
added the overlay by default (`--no-devtools` left it out; it is still accepted and changes nothing); running `init`
again on such a setup names the file, and deleting the one statement that imports `@genclass/runtime/devtools`
diff --git a/packages/runtime/TELEMETRY.md b/packages/runtime/TELEMETRY.md
index 56c770d7..639f0192 100644
--- a/packages/runtime/TELEMETRY.md
+++ b/packages/runtime/TELEMETRY.md
@@ -384,7 +384,11 @@ GenClass.init({ token: "gc_…", analytics: true });
```
(also `data-analytics="on"` on the script tag, ``,
-`window.GENCLASS_CONFIG.analytics`). They need telemetry on and the app's token, or a custom `telemetry.endpoint`;
+`window.GENCLASS_CONFIG.analytics`). `npx @genclass/runtime@beta init --analytics` (from the release after
+`0.3.0-beta.7`) writes the option for you, and `init --no-analytics` takes it out again. **The `genclass` command's
+setup turns them on** (`npx genclass`, from genclass 0.3.14): it writes `analytics: true` next to the app's token
+unless it is run with `--no-analytics`, says so before writing, and `npx genclass analytics off` turns them off later.
+The runtime's own default is unchanged. They need telemetry on and the app's token, or a custom `telemetry.endpoint`;
without either, `analytics: true` warns once in the console and records nothing. Every telemetry opt-out below, Global
Privacy Control and the local-host default turn them off too. When they start, the console says so once:
diff --git a/packages/runtime/bin/lib/edit.mjs b/packages/runtime/bin/lib/edit.mjs
index 94e21997..f08017c6 100644
--- a/packages/runtime/bin/lib/edit.mjs
+++ b/packages/runtime/bin/lib/edit.mjs
@@ -433,7 +433,7 @@ export function bodyTagEnd(text) {
// ------------------------------------------------------------------------------------------- options
//
-// init --no-telemetry / --telemetry / --model-url write options without hand-editing. An ES module's imports run
+// init --no-telemetry / --telemetry / --analytics / --model-url write options without hand-editing. An ES module's imports run
// before its own code, so options cannot be set in the entry file above the /auto import: init writes them to a
// file of their own, genclass.config.(ts|js), which sets window.GENCLASS_CONFIG (read by /auto), and imports it
// right before the /auto import. A plain HTML page gets data attributes on the script tag instead, an Astro layout
@@ -441,14 +441,18 @@ export function bodyTagEnd(text) {
export const CONFIG_COMMENT = "// Read by @genclass/runtime/auto, imported right after this file: any GenClass.init() option works here (see the README).";
-const isEmptyConfig = (cfg) => !cfg || (cfg.telemetry === undefined && !cfg.model && !cfg.token && !(cfg.sinks && cfg.sinks.length));
+const isEmptyConfig = (cfg) => !cfg || (cfg.telemetry === undefined && cfg.analytics === undefined && !cfg.model && !cfg.token && !(cfg.sinks && cfg.sinks.length));
export { isEmptyConfig };
/**
* What init writes for cfg on a new setup: `telemetry: true` (--telemetry) is the default, so it is left out. Written
* explicitly it would be an opt-in that also sends from local hosts (TELEMETRY.md), which --telemetry does not mean.
+ * `analytics: false` (--no-analytics) is the runtime's default too, so it is left out the same way.
*/
-export const writtenConfig = (cfg) => (cfg && cfg.telemetry === true ? { ...cfg, telemetry: undefined } : cfg);
+export const writtenConfig = (cfg) => {
+ if (!cfg || (cfg.telemetry !== true && cfg.analytics !== false)) return cfg;
+ return { ...cfg, ...(cfg.telemetry === true ? { telemetry: undefined } : {}), ...(cfg.analytics === false ? { analytics: undefined } : {}) };
+};
const modelLiteral = (m) => `model: { baseUrl: ${JSON.stringify(m.baseUrl)}, ortWasmPaths: ${JSON.stringify(m.ortWasmPaths)}${m.device ? `, device: ${JSON.stringify(m.device)}` : ""} }`;
@@ -462,15 +466,18 @@ export const sinkNoEvidence = (s) => /^[^:=]+[:=]\s*no[-_\s]?evidence\s*$/i.test
/** `sinks: ["console-json", "webhook:/genclass"]`. */
const sinksLiteral = (cfg) => `sinks: [${cfg.sinks.map((s) => JSON.stringify(s)).join(", ")}]`;
const SINKS_RE = /\bsinks\s*:\s*\[[^\]]*\]/;
+const ANALYTICS_RE = /\banalytics\s*:\s*(?:true|false)/;
/**
- * The object init writes: `{ token: "gc_...", telemetry: false, model: { baseUrl: "/genclass-model/", ortWasmPaths: "..." }, sinks: ["webhook:/genclass"] }`.
- * Only the telemetry opt-out is ever written: `telemetry: true` would also send from local hosts.
+ * The object init writes: `{ token: "gc_...", telemetry: false, analytics: true, model: { baseUrl: "/genclass-model/", ortWasmPaths: "..." }, sinks: ["webhook:/genclass"] }`.
+ * Only the telemetry opt-out is ever written: `telemetry: true` would also send from local hosts. Only the analytics
+ * opt-in is ever written (--analytics): off is the runtime's default.
*/
export function configLiteral(cfg) {
const parts = [];
if (cfg.token) parts.push(`token: ${JSON.stringify(cfg.token)}`);
if (cfg.telemetry === false) parts.push("telemetry: false");
+ if (cfg.analytics === true) parts.push("analytics: true");
if (cfg.model) parts.push(modelLiteral(cfg.model));
if (cfg.sinks?.length) parts.push(sinksLiteral(cfg));
return parts.length ? `{ ${parts.join(", ")} }` : "{}";
@@ -480,9 +487,10 @@ export function configLiteral(cfg) {
export const configStatement = (cfg, ts) => `${ts ? "(globalThis as { GENCLASS_CONFIG?: object })" : "globalThis"}.GENCLASS_CONFIG = ${configLiteral(cfg)};`;
/**
- * Sets token / telemetry / model / sinks in an existing GENCLASS_CONFIG statement (other keys a user added stay).
- * `telemetry: false` writes the opt-out; `telemetry: true` (--telemetry) takes the telemetry key out, back to the
- * default (an explicit `true` would also send from local hosts).
+ * Sets token / telemetry / analytics / model / sinks in an existing GENCLASS_CONFIG statement (other keys a user
+ * added stay). `telemetry: false` writes the opt-out; `telemetry: true` (--telemetry) takes the telemetry key out,
+ * back to the default (an explicit `true` would also send from local hosts). `analytics: true` (--analytics) writes
+ * the opt-in; `analytics: false` (--no-analytics) takes the key out, back to the default (off).
*/
export function updateConfigText(text, cfg) {
return text.replace(/(GENCLASS_CONFIG\s*=\s*\{)([^;]*)(\}\s*;?)/, (_m, open, body, close) => {
@@ -497,6 +505,12 @@ export function updateConfigText(text, cfg) {
} else if (cfg.telemetry === true) {
b = b.replace(/\btelemetry\s*:\s*(?:true|false)\s*,?/, "").replace(/,\s*,/, ",");
}
+ if (cfg.analytics === true) {
+ const v = "analytics: true";
+ b = ANALYTICS_RE.test(b) ? b.replace(ANALYTICS_RE, v) : `${b.trim().replace(/,\s*$/, "")}${b.trim() ? ", " : ""}${v}`;
+ } else if (cfg.analytics === false) {
+ b = b.replace(/\banalytics\s*:\s*(?:true|false)\s*,?/, "").replace(/,\s*,/, ",");
+ }
if (cfg.model) b = /\bmodel\s*:\s*\{[^}]*\}/.test(b) ? b.replace(/\bmodel\s*:\s*\{[^}]*\}/, modelLiteral(cfg.model)) : `${b.trim().replace(/,\s*$/, "")}, ${modelLiteral(cfg.model)}`;
if (cfg.sinks?.length) b = SINKS_RE.test(b) ? b.replace(SINKS_RE, sinksLiteral(cfg)) : `${b.trim().replace(/,\s*$/, "")}, ${sinksLiteral(cfg)}`;
b = b.trim().replace(/^,\s*/, "").replace(/,\s*$/, "");
@@ -504,20 +518,21 @@ export function updateConfigText(text, cfg) {
});
}
-/** `telemetry=off, model=/genclass-model/, ort=/genclass-model/ort/, sink=console-json+webhook:/g` (meta content; `+` joins sink names since commas separate keys), "" when nothing to say. */
+/** `telemetry=off, analytics=on, model=/genclass-model/, ort=/genclass-model/ort/, sink=console-json+webhook:/g` (meta content; `+` joins sink names since commas separate keys), "" when nothing to say. */
export function metaContent(cfg) {
const parts = [];
if (cfg.token) parts.push(`token=${cfg.token}`);
if (cfg.telemetry === false) parts.push("telemetry=off");
+ if (cfg.analytics === true) parts.push("analytics=on");
if (cfg.model) parts.push(`model=${cfg.model.baseUrl}`, `ort=${cfg.model.ortWasmPaths}`, ...(cfg.model.device ? [`device=${cfg.model.device}`] : []));
if (cfg.sinks?.length) parts.push(`sink=${cfg.sinks.join("+")}`);
return parts.join(", ");
}
-const TAG_ATTRS = { token: "data-token", telemetry: "data-telemetry", model: "data-model", ort: "data-ort", device: "data-device", sink: "data-sink" };
+const TAG_ATTRS = { token: "data-token", telemetry: "data-telemetry", analytics: "data-analytics", model: "data-model", ort: "data-ort", device: "data-device", sink: "data-sink" };
const attrRe = (name) => new RegExp(String.raw`\s+${name}\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)`, "i");
-/** A script tag with data-token / data-telemetry / data-model / data-ort / data-sink set for cfg (telemetry true removes the opt-out). */
+/** A script tag with data-token / data-telemetry / data-analytics / data-model / data-ort / data-sink set for cfg (telemetry true removes the opt-out, analytics false the opt-in). */
export function tagWithConfig(tag, cfg) {
const set = (t, name, value) => {
const re = attrRe(name);
@@ -530,6 +545,7 @@ export function tagWithConfig(tag, cfg) {
let t = tag;
if (cfg.token) t = set(t, TAG_ATTRS.token, cfg.token);
if (cfg.telemetry !== undefined) t = set(t, TAG_ATTRS.telemetry, cfg.telemetry ? null : "off");
+ if (cfg.analytics !== undefined) t = set(t, TAG_ATTRS.analytics, cfg.analytics ? "on" : null);
if (cfg.model) {
t = set(t, TAG_ATTRS.model, cfg.model.baseUrl);
t = set(t, TAG_ATTRS.ort, cfg.model.ortWasmPaths);
@@ -567,6 +583,8 @@ export function switchMetaConfig(text, cfg) {
if (cfg.token) pairs.token = cfg.token;
if (cfg.telemetry === false) pairs.telemetry = "off";
if (cfg.telemetry === true) delete pairs.telemetry;
+ if (cfg.analytics === true) pairs.analytics = "on";
+ if (cfg.analytics === false) delete pairs.analytics;
if (cfg.model) Object.assign(pairs, { model: cfg.model.baseUrl, ort: cfg.model.ortWasmPaths, ...(cfg.model.device ? { device: cfg.model.device } : {}) });
if (cfg.sinks?.length) pairs.sink = cfg.sinks.join("+");
const content = Object.entries(pairs).map(([k, v]) => `${k}=${v}`).join(", ");
diff --git a/packages/runtime/bin/lib/init.mjs b/packages/runtime/bin/lib/init.mjs
index 130c36bb..175be657 100644
--- a/packages/runtime/bin/lib/init.mjs
+++ b/packages/runtime/bin/lib/init.mjs
@@ -14,7 +14,7 @@ import { spawnSync } from "node:child_process";
import { mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, relative, resolve, sep } from "node:path";
import { detectCsp, detectProject, detectState, htmlFiles, littleToWatch, isDir, isFile, readText, walkSkipped, walkSources } from "./detect.mjs";
-import { MARK, hasMarker, isEmptyConfig, planRemoval, removeMarked, sinkBase, sinkNoEvidence, switchMetaConfig, switchMode, switchTagConfig, updateConfigText } from "./edit.mjs";
+import { MARK, hasMarker, isEmptyConfig, planRemoval, removeMarked, sinkBase, sinkNoEvidence, switchMetaConfig, switchMode, switchTagConfig, updateConfigText, writtenConfig } from "./edit.mjs";
import { AUTO, configFileChange, configFileFor, planInit, scriptTag } from "./plan.mjs";
import { createAccountProject, readCredentials } from "./account.mjs";
import { apiHost, hostConfig, hostUrl } from "./host.mjs";
@@ -44,7 +44,8 @@ export const FREE_LINES = HOST_CLI
export const USAGE = `Usage:
genclass-runtime init [--mode observe|guard|heal] [--token | --no-token]
- [--no-telemetry | --telemetry] [--model-url ]
+ [--no-telemetry | --telemetry] [--analytics | --no-analytics]
+ [--model-url ]
[--sink console-json|webhook:]
[--yes] [--dry-run] [--no-install] [--devtools] [--no-network] [--cwd ]
genclass-runtime remove [--yes] [--dry-run] [--keep-package] [--cwd ]
@@ -72,6 +73,15 @@ remove takes out exactly what init added (the lines and blocks marked "${MARK}
--no-token (a dashboard only gets data while telemetry is on)
--telemetry undo --no-telemetry: back to the default (on, but never from local hosts); init
takes the opt-out out and writes no telemetry option of its own
+ --analytics turn on visitor analytics for this app's dashboard (off by default): page views, time
+ on a page, scroll depth, clicks per element (named from markup, never its text), where
+ visits come from and the device class. No cookies; one localStorage entry holds the
+ visit. They need the app's token and telemetry on, never run on localhost, and every
+ telemetry opt-out and Global Privacy Control turn them off. Written as analytics: true
+ in the option file, data-analytics="on" on a script tag, analytics=on in the Astro
+ meta line. Where the law asks for consent to analytics (the EU, EEA and UK), leave
+ them off and call runtime.analytics.start() once the visitor agrees (TELEMETRY.md)
+ --no-analytics undo --analytics: init takes the option out again (back to the default, off)
--model-url use a self-hosted model directory (made with \`fetch-model\`), e.g. /genclass-model/,
with ONNX Runtime from ort/ (for a Content-Security-Policy without cdn.jsdelivr.net)
--sink also send every detection and intervention to your own side, with no new dependency:
@@ -113,6 +123,8 @@ const BOOL = {
sync: "sync",
"no-telemetry": "noTelemetry",
telemetry: "telemetry",
+ analytics: "analytics",
+ "no-analytics": "noAnalytics",
"no-token": "noToken",
"in-account": "inAccount",
brief: "brief",
@@ -158,6 +170,9 @@ export function parse(argv, spec = { bool: BOOL, value: VALUE }) {
}
if (o.mode && !MODES.includes(o.mode)) throw new UsageError(`--mode must be observe, guard or heal`);
if (o.noTelemetry && o.telemetry) throw new UsageError(`--telemetry and --no-telemetry contradict each other`);
+ if (o.analytics && o.noAnalytics) throw new UsageError(`--analytics and --no-analytics contradict each other`);
+ if (o.analytics && o.noTelemetry) throw new UsageError(`--analytics needs telemetry on (visitor analytics are sent with it): drop --no-telemetry`);
+ if (o.analytics && o.noToken) throw new UsageError(`--analytics needs the app's token (visitor analytics only feed its dashboard): drop --no-token`);
if (o.token !== undefined && o.noToken) throw new UsageError(`--token and --no-token contradict each other`);
if (o.token !== undefined && o.noTelemetry) throw new UsageError(`--no-telemetry means no token (a dashboard only gets data while telemetry is on): drop --token`);
if (o.token !== undefined && !TOKEN_RE.test(o.token)) throw new UsageError(`--token must be "gc_" followed by 22 letters or digits (get one: ${START_URL})`);
@@ -375,12 +390,14 @@ function printRecommendations(recs) {
// ----------------------------------------------------------------------------------------- options
-/** The options init writes: { token?, telemetry?, model?, sinks? } (empty: none). */
+/** The options init writes: { token?, telemetry?, analytics?, model?, sinks? } (empty: none). */
export function configOf(o, token) {
const c = {};
if (token) c.token = token;
if (o.noTelemetry) c.telemetry = false;
else if (o.telemetry) c.telemetry = true;
+ if (o.analytics) c.analytics = true;
+ else if (o.noAnalytics) c.analytics = false;
if (o.modelUrl) {
const u = o.modelUrl.endsWith("/") ? o.modelUrl : `${o.modelUrl}/`;
c.model = { baseUrl: u, ortWasmPaths: `${u}ort/` };
@@ -430,6 +447,37 @@ function briefTelemetry(cfg) {
out(` ${c.gray(TELEMETRY_URL)}`);
}
+/** What visitor analytics count and keep, in one sentence (TELEMETRY.md "Interaction analytics" is the full list). */
+const ANALYTICS_WHAT = "page views, time on a page, scroll depth, clicks per element (never its text), where visits come from and the device class go to this app's dashboard. No cookies; one localStorage entry holds the visit. Never from localhost.";
+/** The consent advice of TELEMETRY.md, said wherever init turns analytics on. */
+const ANALYTICS_CONSENT = "Where the law asks for a visitor's consent to analytics (the EU, EEA and UK), turn them off and call runtime.analytics.start() once the visitor agrees.";
+export const ANALYTICS_URL = `${TELEMETRY_URL}#interaction-analytics`;
+/** The command that turns them off again: the `genclass` command has a short name for init's own flag. */
+const ANALYTICS_OFF = HOST_CLI ? `${CMD} analytics off` : `${CMD} init --no-analytics`;
+
+/** Visitor analytics disclosure (--analytics): that they are on, what is counted and kept, consent, how to turn them off. */
+function analyticsNotice(cfg, where) {
+ if (cfg.analytics === undefined) return;
+ if (cfg.analytics === false) {
+ row("Analytics", `off ${c.gray("(--no-analytics)")}`);
+ return;
+ }
+ row("Analytics", `${c.bold("on")} ${c.gray(`(--analytics${where ? `, written to ${where}` : ""})`)}`);
+ more(`Visitor analytics: ${ANALYTICS_WHAT}`);
+ more(ANALYTICS_CONSENT);
+ // on a line of its own, so a narrow terminal never breaks the command in two
+ more(`Off: ${c.cyan(ANALYTICS_OFF)}`);
+ more(`What is sent: ${ANALYTICS_URL}`);
+}
+
+/** The same disclosure for --brief (the `genclass` command's walk). Nothing is left out that analyticsNotice says. */
+function briefAnalytics(cfg) {
+ if (cfg.analytics !== true) return;
+ briefLines(`Visitor analytics are on: ${ANALYTICS_WHAT}`);
+ briefLines(ANALYTICS_CONSENT);
+ out(` ${c.gray(`Off: ${ANALYTICS_OFF}`)}`);
+}
+
/**
* A command shown as what will run: on its label's line when it fits the window, else under it, folded between its
* words (a narrow terminal would otherwise break a word of it in two, "--n" and "o-audit").
@@ -516,7 +564,7 @@ function planConfigSwitch(project, cwd, marked, cfg, readText) {
let after = before;
if (/\.html?$/.test(f)) after = switchTagConfig(before, cfg);
else if (/\.astro$/.test(f)) after = switchMetaConfig(before, cfg);
- else if (!isEmptyConfig({ ...cfg, telemetry: cfg.telemetry === true && !cfg.model ? undefined : cfg.telemetry })) {
+ else if (!isEmptyConfig(writtenConfig(cfg))) {
// the JS line init wrote: put the options import right before it
const lines = before.split("\n");
// (a marked line, or a line inside a block init created)
@@ -604,21 +652,34 @@ const describeConfig = (cfg) =>
[
cfg.token ? (cfg.token === PENDING_TOKEN ? "the new app's token" : `token ${cfg.token}`) : null,
cfg.telemetry === false ? "telemetry off" : cfg.telemetry ? "telemetry on" : null,
+ cfg.analytics === true ? "visitor analytics on" : cfg.analytics === false ? "visitor analytics off" : null,
cfg.model ? `model ${cfg.model.baseUrl}` : null,
cfg.sinks?.length ? `sinks ${cfg.sinks.join(", ")}` : null,
]
.filter(Boolean)
.join(", ");
-/** Telemetry as the marked files set it (an existing setup): false when init wrote the opt-out. */
+/**
+ * Telemetry and visitor analytics as the marked files set them (an existing setup): `telemetry: false` when init
+ * wrote the opt-out, `analytics: true` when it wrote the opt-in.
+ */
function currentConfig(files) {
+ const cur = {};
for (const f of files) {
const t = readText(f) ?? "";
- if (/GENCLASS_CONFIG\s*=\s*\{[^;]*\btelemetry\s*:\s*false/.test(t) || /data-telemetry=["']?off/.test(t) || /]*name=["']genclass["'][^>]*telemetry=off/.test(t)) return { telemetry: false };
+ if (/GENCLASS_CONFIG\s*=\s*\{[^;]*\btelemetry\s*:\s*false/.test(t) || /data-telemetry=["']?off/.test(t) || /]*name=["']genclass["'][^>]*telemetry=off/.test(t)) cur.telemetry = false;
+ if (analyticsIn(t)) cur.analytics = true;
}
- return {};
+ return cur;
}
+/** Whether a file's text turns visitor analytics on: the options init writes, or `analytics: true` in a hand-written GenClass.init(). */
+const analyticsIn = (t) =>
+ /GENCLASS_CONFIG\s*=\s*\{[^;]*\banalytics\s*:\s*true\b/.test(t) ||
+ /GenClass\.init\(\s*\{[^)]*\banalytics\s*:\s*true\b/.test(t) ||
+ /data-analytics=["']?on\b/.test(t) ||
+ /]*name=["']genclass["'][^>]*\banalytics=on\b/.test(t);
+
/**
* --model-url pointing into the app's public folder that `fetch-model --ort wasm` filled: no WebGPU ONNX Runtime
* there, so the model must run on WASM (device "wasm"), else WebGPU devices would fail to load it.
@@ -660,9 +721,12 @@ function planToken(o, project, cwd, marked, fresh) {
return { pending: true, name: project.pkg?.name || project.name };
}
-/** cfg without its token (what init writes when no token could be created). */
+/**
+ * cfg without its token (what init writes when no token could be created), and without the analytics opt-in: visitor
+ * analytics only feed the app's dashboard, so without a token the runtime would warn on every page and record nothing.
+ */
const withoutToken = (cfg) => {
- const { token: _t, ...rest } = cfg;
+ const { token: _t, analytics: _a, ...rest } = cfg;
return rest;
};
@@ -860,7 +924,9 @@ export function inspectProject(o) {
const local = readLocal(cwd);
// the key: in init's markers, else in a hand-written setup's files (GenClass.init({ token }), a meta tag, the
// integrations' options), else in .genclass.local
- 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 };
+ // visitor analytics: on when init's options, or a hand-written setup's own, turn them on
+ const analytics = (marked.length ? marked : manual).some((f) => analyticsIn(readText(f) ?? ""));
+ 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, analytics };
}
/**
@@ -933,6 +999,14 @@ export async function init(o, ctx = {}) {
}
if (tk.write) cfg = { token: tk.token, ...cfg };
else if (tk.pending) cfg = { token: PENDING_TOKEN, ...cfg };
+ // --analytics on a setup that has no token and gets none here (telemetry off, set up by hand, made without one):
+ // the option is not written, since the runtime would record nothing and warn on every page
+ const noAnalytics = cfg.analytics === true && !tk.token && !tk.pending && !tk.wouldCreate;
+ if (noAnalytics) {
+ const { analytics: _a, ...rest } = cfg;
+ cfg = rest;
+ row("Analytics", `not turned on: visitor analytics need this app's token and telemetry on (${tk.why ?? "no token"}). ${HOST_CLI ? `${CMD} setup` : `${CMD} connect`} gives the app one.`, c.yellow(sym.warn));
+ }
// an older @genclass/runtime in the project (0.2.x from `npx @genclass/runtime init` without @beta) is upgraded:
// without that, this init would write options and imports the installed runtime does not have
const older = project.framework !== "html" ? olderRuntime(project, cwd) : null;
@@ -967,6 +1041,7 @@ export async function init(o, ctx = {}) {
const optionsChanged = switches.some((ch) => !o.mode || ch.kind === "create" || switchMode(ch.before, o.mode) !== ch.after);
out();
telemetryNotice(isEmptyConfig(cfg) ? currentConfig(marked) : { ...currentConfig(marked), ...cfg }, null);
+ analyticsNotice({ ...currentConfig(marked), ...cfg }, null);
tokenRow(tk);
const overlay = o.devtools && !HOST_CLI ? null : overlayHint(project, overlayFiles(marked).map((f) => posix(relative(cwd, f))));
if (overlay) row("Overlay", overlay, c.yellow(sym.warn));
@@ -1015,14 +1090,18 @@ export async function init(o, ctx = {}) {
row("Entry", posix(relative(cwd, plan.entry)));
row("Mode", `${o.mode ?? "observe"}${o.mode ? "" : c.gray(" (default: reports only, never changes anything; --mode guard lets it act)")}`);
}
- const cfgAtOf = (changes, config) => changes.find((ch) => /genclass\.config\.[cm]?[jt]s$/.test(ch.file))?.rel ?? (config.telemetry === false || config.sinks?.length ? changes[0]?.rel : null);
+ const cfgAtOf = (changes, config) => changes.find((ch) => /genclass\.config\.[cm]?[jt]s$/.test(ch.file))?.rel ?? (config.telemetry === false || config.analytics === true || config.sinks?.length ? changes[0]?.rel : null);
let cfgAt = cfgAtOf(plan.changes, cfg);
if (brief) {
out();
out(` ${c.bold(project.name)} ${c.gray(`${sym.dot} ${project.label}${project.pm ? ` ${sym.dot} ${project.pm}` : ""} ${sym.dot} ${posix(relative(cwd, plan.entry))}`)}`);
briefLines(`Adds ${PKG} ${VERSION} in ${o.mode ?? "observe"} mode${o.mode ? "" : ": it reports and never changes anything"}.`, (l) => l);
briefTelemetry(cfg);
- } else telemetryNotice(cfg, cfgAt);
+ briefAnalytics(cfg);
+ } else {
+ telemetryNotice(cfg, cfgAt);
+ analyticsNotice(cfg, cfgAt);
+ }
if (!ctx.creds) tk = await offerAccount(o, tk);
if (brief && tk.pending && tk.account) briefLines(`The app goes into ${accountWhere(tk.account.account)} as "${String(tk.name ?? "").slice(0, 80) || "unnamed"}".`);
else tokenRow(tk);
@@ -1079,6 +1158,9 @@ export async function init(o, ctx = {}) {
return 1;
}
if (changes !== plan.changes) cfgAt = cfgAtOf(changes, tk.token ? cfg : withoutToken(cfg));
+ // no token could be made: the analytics opt-in was left out with it (withoutToken)
+ const analyticsOn = cfg.analytics === true && !!tk.token;
+ if (cfg.analytics === true && !tk.token) out(` ${c.yellow(sym.warn)} Visitor analytics were left off: they need the app's token. Once the app has one: ${c.cyan(`${CMD} init --analytics`)}`);
// a project created just now: keep its private link before writing anything else (it is shown only once)
const saved = tk.created ? persistCreated(tk, cwd) : null;
for (const ch of changes) {
@@ -1097,6 +1179,7 @@ export async function init(o, ctx = {}) {
if (brief && (tk.created?.account || tk.app)) {
out(` ${c.green(sym.ok)} ${c.bold("GenClass is in your app.")} ${c.gray(`(${changes.map((ch) => ch.rel).join(", ")})`)}`);
briefLines("What it finds shows in the browser console as [GenClass] lines, and on your dashboard once the site is deployed.");
+ if (analyticsOn && HOST_CLI) briefLines(`Visitors are counted from then on too: ${CMD} analytics`);
printMoneyAdvice(money, cfgAt);
// the address part and the command each stay whole on a line of their own
out(` ${c.gray("Off for one page: ?genclass=off")}`);
@@ -1114,6 +1197,7 @@ export async function init(o, ctx = {}) {
if (devtools && changes.some((ch) => /devtools/.test(ch.after))) out(` ${sym.dot} An overlay at the bottom right of dev pages shows what GenClass sees (${c.bold("Alt+Shift+G")}).`);
out(` ${sym.dot} Findings also appear in the browser console as ${c.cyan("[GenClass] ...")} lines.`);
if (cfg.sinks?.length) out(` ${sym.dot} They also reach ${c.cyan(cfg.sinks.join(", "))}: ${cfg.sinks.map((s) => SINK_WHAT[sinkBase(s)] ?? s).join("; ")}.`);
+ if (analyticsOn) out(` ${sym.dot} Visitors are counted on your dashboard once the site is deployed (never from localhost).`);
out();
printMoneyAdvice(money, cfgAt);
printLittleToWatch(quiet);
diff --git a/packages/runtime/bin/lib/plan.mjs b/packages/runtime/bin/lib/plan.mjs
index 00d6d875..4562e8c6 100644
--- a/packages/runtime/bin/lib/plan.mjs
+++ b/packages/runtime/bin/lib/plan.mjs
@@ -22,6 +22,7 @@ import {
isEmptyConfig,
lineIndexAt,
linesOf,
+ metaContent,
switchMetaConfig,
tagWithConfig,
writtenConfig,
@@ -367,7 +368,7 @@ export function configFileFor(p, entry) {
/** The options file: one marked block setting window.GENCLASS_CONFIG. */
export const configFileChange = (file, cfg) => createFile(file, [CONFIG_COMMENT, configStatement(cfg, /\.[cm]?tsx?$/.test(file))]);
-/** { entry?, changes, notes?, manual? } for the detected project. opts.config: { telemetry?, model? } to write. */
+/** { entry?, changes, notes?, manual? } for the detected project. opts.config: { token?, telemetry?, analytics?, model?, sinks? } to write. */
export function planInit(project, opts, ctx) {
const planner = PLANNERS[project.framework];
if (!planner) return { changes: [], manual: "the project type was not recognised" };
@@ -378,7 +379,8 @@ export function planInit(project, opts, ctx) {
if (project.framework === "astro") {
for (const ch of r.changes) {
const next = switchMetaConfig(ch.after, cfg);
- if (next === ch.after) (r.notes ??= []).push(`${posix(relative(project.dir, ch.file))}: GenClass is inline in , so its options were not written there: add yourself.`);
+ // the line to add names the options asked for (the token is not known yet: it is made after the approval)
+ if (next === ch.after) (r.notes ??= []).push(`${posix(relative(project.dir, ch.file))}: GenClass is inline in , so its options were not written there: add yourself.`);
ch.after = next;
}
// a meta tag only takes a same-origin webhook URL (src/cdn/config.ts readMetaConfig); say so instead of writing a dead sink
diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts
index 0acbae98..ea065aad 100644
--- a/packages/runtime/src/types.ts
+++ b/packages/runtime/src/types.ts
@@ -963,6 +963,7 @@ export interface InitOptions {
* (`genclass.analytics.`) holds the visit id and the visited-before flag. Where analytics need consent
* (the EU, EEA and UK), leave it off and call `runtime.analytics.start()` once the visitor agrees. Also
* `data-analytics="on"`, ``, `window.GENCLASS_CONFIG.analytics`.
+ * `init --analytics` writes it; the `genclass` command's setup does unless it is run with `--no-analytics`.
* Since 0.3.0-beta.1 (`npm install @genclass/runtime@beta`; 0.2.x, npm's `latest` until 0.3.0, ignores it). When the
* analytics code does not load, `runtime.analytics.reason` is "error" (the script tag also warns on the console).
*/
diff --git a/packages/runtime/test/install/cli.test.ts b/packages/runtime/test/install/cli.test.ts
index 50fae7e3..d29bd7f7 100644
--- a/packages/runtime/test/install/cli.test.ts
+++ b/packages/runtime/test/install/cli.test.ts
@@ -970,6 +970,126 @@ describe("init options: --no-telemetry / --telemetry / --model-url (Troy trial,
});
});
+describe("init options: --analytics / --no-analytics (visitor analytics; TELEMETRY.md \"Interaction analytics\", AGENTS.md rule 8)", () => {
+ const MINE = "gc_Mine0123456789abcdefgh";
+ const astro = () =>
+ project({
+ "package.json": pkg({ astro: "^5" }),
+ "src/layouts/Layout.astro": `---\n---\n\n\t\n\t\tx\n\t\n\t\n\n`,
+ });
+
+ it("Vite: --analytics writes analytics: true next to the token; remove restores the files", () => {
+ const after = roundTrip(viteVue(), "--token", MINE, "--analytics");
+ expect(after["src/genclass.config.js"]).toContain(`globalThis.GENCLASS_CONFIG = { token: "${MINE}", analytics: true };`);
+ expect(after["src/main.js"].split("\n").slice(0, 2)).toEqual([`import "./genclass.config"; // genclass:init`, `import "@genclass/runtime/auto"; // genclass:init`]);
+ });
+
+ it("the written statement is what /auto reads, and the script tag's and the meta line's forms are the page config's", () => {
+ const dir = viteVue();
+ cli(dir, "init", "--yes", "--no-install", "--token", MINE, "--analytics");
+ const stmt = readFileSync(join(dir, "src/genclass.config.js"), "utf8").split("\n").find((l) => l.startsWith("globalThis."))!;
+ const win: Record = {};
+ new Function("globalThis", stmt)(win);
+ expect(mergeConfig({ mode: "observe" }, win.GENCLASS_CONFIG as object)).toEqual({ mode: "observe", token: MINE, analytics: true });
+ const html = roundTrip(project({ "index.html": PAGE }), "--token", MINE, "--analytics", "--no-sri");
+ expect(html["index.html"]).toContain(` defer data-token="${MINE}" data-analytics="on"> `);
+ expect(fromDataset({ token: MINE, analytics: "on" })).toMatchObject({ token: MINE, analytics: true });
+ const page = roundTrip(astro(), "--token", MINE, "--analytics");
+ expect(page["src/layouts/Layout.astro"]).toContain(` `);
+ expect(fromPairs(parsePairs(`token=${MINE}, analytics=on`))).toMatchObject({ token: MINE, analytics: true });
+ });
+
+ it("without the flag nothing about analytics is written or said: off stays the default", () => {
+ const after = roundTrip(viteVue(), "--token", MINE);
+ expect(after["src/genclass.config.js"]).toContain(`GENCLASS_CONFIG = { token: "${MINE}" };`);
+ expect(cli(viteVue(), "init", "--dry-run", "--token", MINE).out).not.toMatch(/Analytics|analytics: true/);
+ // --no-analytics on a new setup is the default: no key, no file of its own
+ const off = roundTrip(viteVue(), "--no-token", "--no-analytics");
+ expect(Object.keys(off).some((f) => /genclass\.config/.test(f))).toBe(false);
+ });
+
+ it("on an existing setup: --analytics adds the key, --no-analytics takes it out, the same flag again changes nothing, remove takes everything out", () => {
+ for (const make of [viteVue, () => project({ "index.html": PAGE }), astro]) {
+ const dir = make();
+ const before = snapshot(dir);
+ expect(cli(dir, "init", "--yes", "--no-install", "--no-sri", "--token", MINE).code).toBe(0);
+ const plain = snapshot(dir);
+ const on = cli(dir, "init", "--yes", "--no-install", "--analytics");
+ expect(on.code, on.out).toBe(0);
+ expect(on.out).toContain("visitor analytics on");
+ expect(Object.values(snapshot(dir)).join("\n")).toMatch(/analytics: true|data-analytics="on"|analytics=on/);
+ expect(cli(dir, "init", "--yes", "--no-install", "--analytics").out).toContain("Nothing to do");
+ const off = cli(dir, "init", "--yes", "--no-install", "--no-analytics");
+ expect(off.code, off.out).toBe(0);
+ expect(off.out).toContain("visitor analytics off");
+ // exactly the setup without the option again
+ expect(snapshot(dir)).toEqual(plain);
+ expect(cli(dir, "init", "--yes", "--no-install", "--no-analytics").out).toContain("Nothing to do");
+ cli(dir, "init", "--yes", "--no-install", "--analytics");
+ expect(cli(dir, "remove", "--yes").code).toBe(0);
+ expect(snapshot(dir)).toEqual(before);
+ }
+ });
+
+ it("a user's own key in the options file survives both switches", () => {
+ const dir = viteVue();
+ cli(dir, "init", "--yes", "--no-install", "--token", MINE);
+ const f = join(dir, "src/genclass.config.js");
+ writeFileSync(f, readFileSync(f, "utf8").replace(`{ token: "${MINE}" }`, `{ token: "${MINE}", debug: true }`));
+ cli(dir, "init", "--yes", "--no-install", "--analytics");
+ expect(readFileSync(f, "utf8")).toContain(`GENCLASS_CONFIG = { token: "${MINE}", debug: true, analytics: true };`);
+ cli(dir, "init", "--yes", "--no-install", "--no-analytics");
+ expect(readFileSync(f, "utf8")).toContain(`GENCLASS_CONFIG = { token: "${MINE}", debug: true };`);
+ });
+
+ it("no token, no analytics: a setup without one is told so and gets no option; a token that cannot be made leaves it out", () => {
+ // an existing setup made without a token
+ const dir = viteVue();
+ cli(dir, "init", "--yes", "--no-install", "--no-token");
+ const plain = snapshot(dir);
+ const r = cli(dir, "init", "--yes", "--no-install", "--analytics");
+ expect(r.out.replace(/\s+/g, " ")).toMatch(/Analytics not turned on: visitor analytics need this app's token and telemetry on/);
+ expect(snapshot(dir)).toEqual(plain);
+ // a new setup while genclass.dev does not answer (the mock fetch fails): GenClass is added, without the option
+ const fresh = viteVue();
+ const made = cli(fresh, "init", "--yes", "--no-install", "--analytics");
+ expect(made.code, made.out).toBe(0);
+ expect(made.out.replace(/\s+/g, " ")).toContain("Visitor analytics were left off: they need the app's token.");
+ expect(Object.values(snapshot(fresh)).join("\n")).not.toMatch(/analytics\s*:\s*true/);
+ expect(readFileSync(join(fresh, "src/main.js"), "utf8")).toContain(`import "@genclass/runtime/auto"; // genclass:init`);
+ });
+
+ it("flag errors: --analytics with --no-analytics, --no-telemetry or --no-token", () => {
+ for (const [args, why] of [
+ [["--analytics", "--no-analytics"], "contradict"],
+ [["--analytics", "--no-telemetry"], "needs telemetry on"],
+ [["--analytics", "--no-token"], "needs the app's token"],
+ ] as const) {
+ const r = cli(viteVue(), "init", ...args);
+ expect(r.code, args.join(" ")).toBe(2);
+ expect(r.out, args.join(" ")).toContain(why);
+ }
+ });
+
+ it("discloses what is counted and kept, the consent advice, the switch and the link, before anything is written", () => {
+ const dir = viteVue();
+ const before = snapshot(dir);
+ const out = cli(dir, "init", "--dry-run", "--token", MINE, "--analytics").out.replace(/\s+/g, " ");
+ expect(snapshot(dir)).toEqual(before);
+ expect(out).toMatch(/Analytics on \(--analytics, written to src\/genclass\.config\.js\)/);
+ expect(out).toContain("page views, time on a page, scroll depth, clicks per element (never its text), where visits come from and the device class");
+ expect(out).toContain("No cookies; one localStorage entry holds the visit. Never from localhost.");
+ expect(out).toContain("Where the law asks for a visitor's consent to analytics (the EU, EEA and UK), turn them off and call runtime.analytics.start() once the visitor agrees.");
+ expect(out).toContain(`${CMD} init --no-analytics`);
+ expect(out).toContain("packages/runtime/TELEMETRY.md#interaction-analytics");
+ const usage = cli(project({}), "init", "--help").out;
+ expect(usage).toContain("--analytics");
+ expect(usage).toContain("--no-analytics");
+ // the heading the link points at is in TELEMETRY.md
+ expect(readFileSync(resolve(HERE, "..", "..", "TELEMETRY.md"), "utf8")).toMatch(/^### Interaction analytics$/m);
+ });
+});
+
describe("init finds a Content-Security-Policy and prints the self-host steps", () => {
const CSP_CONFIG = `const csp = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self'";\nexport default { async headers() { return [{ source: "/(.*)", headers: [{ key: "Content-Security-Policy", value: csp }] }]; } };\n`;
const next = (files: Record) =>