@unbase-app/cli 0.2.0 → 0.3.0

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/AGENTS.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # Unbase in a site: the steps for an agent or a developer
2
2
 
3
3
  `npx @unbase-app/cli init` adds what a fixed change can add: the packages, their lines in the
4
- framework's config, and the files they need. What is left needs judgement about this site's code,
5
- and is yours. You add code. You never move or rewrite the site's content: Unbase edits a text where
6
- it is written, in a page, a component or a content file, so moving text into JSON gains nothing and
7
- risks the site.
4
+ framework's config, the files they need, and the analytics collector (`https://unbase.app`) in the
5
+ Content-Security-Policy of `vercel.json` and `public/_headers`. What is left needs judgement about
6
+ this site's code, and is yours. You add code. You never move or rewrite the site's content: Unbase
7
+ edits a text where it is written, in a page, a component or a content file, so moving text into
8
+ JSON gains nothing and risks the site.
8
9
 
9
10
  ## Your framework's steps
10
11
 
package/README.md CHANGED
@@ -13,9 +13,11 @@ bare `npx @unbase-app/cli` outside a site that has this CLI installed would fetc
13
13
 
14
14
  Unbase works on a connected site without any of this: the canvas, comments on the canvas,
15
15
  publishing, and visual editing (on Astro, nothing installed). What has to live in the site's own
16
- code is what this adds: comments on the live site (`?comment`), and page management (draft pages
17
- kept off Live, page and site settings). The packages change how the site is edited and built, never
18
- how it renders, and nothing here calls Unbase.
16
+ code is what this adds: comments on the live site (`?comment`), page management (draft pages
17
+ kept off Live, page and site settings), and analytics (Unbase's beacon, a pageview from every page
18
+ of a production build, no cookies). The packages change how the site is edited and built, never
19
+ how it renders, but for the beacon's script, which renders nothing. The CLI itself never calls
20
+ Unbase.
19
21
 
20
22
  Astro, Vite + React with React Router as a library (what Lovable makes: *Vite + React*, below),
21
23
  and Next.js; each framework's own steps are in `agents/<framework>.md`. Node 18.17 or newer for the
@@ -42,7 +44,7 @@ the framework's own file, [`agents/astro.md`](./agents/astro.md) or
42
44
  | Flag | |
43
45
  |---|---|
44
46
  | `--comments` / `--no-comments` | Comments on the live site, with `?comment` (`@jens4m/comment-modus`, inside `@unbase-app/astro`). Default: in, or as the site has it when Unbase is in it already |
45
- | `--project <id or slug>` | Link comment mode to an Unbase project now (see *Linking*) |
47
+ | `--project <id or slug>` | Link comment mode and analytics to an Unbase project now (see *Linking*) |
46
48
  | `--pointer[=AGENTS.md\|CLAUDE.md]` / `--no-pointer` | One line in the site's `AGENTS.md` (or `CLAUDE.md`) pointing its agent at this package's `AGENTS.md`. Default: no |
47
49
  | `--no-install` | Write `package.json` only; install yourself |
48
50
  | `--tarballs <dir>` | Install the packages from `npm pack` tarballs in `<dir>`, for testing a release before it is on npm |
@@ -54,7 +56,7 @@ versions:
54
56
 
55
57
  | Package | Version | |
56
58
  |---|---|---|
57
- | `@unbase-app/astro` | 0.1.0 | Unbase in an Astro site, one integration: comment mode (`@jens4m/comment-modus` 1.9.0: comments on the live site; it writes the content schemas Unbase reads) and the draft-pages kit (`@unbase-app/pages` 0.3.0: draft pages kept out of production builds) |
59
+ | `@unbase-app/astro` | 0.2.0 | Unbase in an Astro site, one integration: comment mode (`@jens4m/comment-modus` 1.9.0: comments on the live site; it writes the content schemas Unbase reads), the draft-pages kit (`@unbase-app/pages` 0.3.0: draft pages kept out of production builds) and the analytics beacon (`@unbase-app/analytics` 0.1.0) |
58
60
  | `@unbase-app/cli` | this one | devDependency: `AGENTS.md` and `doctor`, pinned |
59
61
 
60
62
  In `astro.config`, found and changed through its syntax tree, never by text substitution:
@@ -81,7 +83,7 @@ second run changes nothing. It touches no content.
81
83
 
82
84
  ### Vite + React
83
85
 
84
- One package, `@unbase-app/vite` (a devDependency, beside `vite`), at 0.1.0: the draft-pages kit and
86
+ One package, `@unbase-app/vite` (a devDependency, beside `vite`), at 0.2.0: the draft-pages kit, the analytics beacon and
85
87
  comment mode's loader in one Vite plugin. In `vite.config`, through its syntax tree (Lovable's
86
88
  `defineConfig(({ mode }) => ({ … }))` and `plugins: [ … ].filter(Boolean)` included):
87
89
 
@@ -99,7 +101,7 @@ Unbase reads and writes as it is; it has no page settings, so nothing is written
99
101
 
100
102
  ### Next.js
101
103
 
102
- On a Next.js site `init` adds `@unbase-app/next` and wraps the config `next.config` hands Next.js in
104
+ On a Next.js site `init` adds `@unbase-app/next` (0.2.0) and wraps the config `next.config` hands Next.js in
103
105
  `withUnbase(…)` (through its syntax tree; a CommonJS config gets the `require`), writes
104
106
  `comment-modus.json`, and on a Next.js from 15.3 to 16.2 imports the comments' loader in
105
107
  `instrumentation-client.ts` (from 16.3 `withUnbase` injects it). `doctor` builds with `next build`
@@ -108,11 +110,32 @@ into the site's own `.next` and reads it; page settings need nothing installed (
108
110
  `uninstall` takes it all out and compares the prerendered pages, with Next.js's scripts and hashed
109
111
  asset names left out. The steps: [`agents/next.md`](./agents/next.md).
110
112
 
113
+ ### Analytics
114
+
115
+ The beacon comes with the framework's package, on by default (`@unbase-app/analytics`): every page
116
+ of a production build sends a pageview to Unbase once the site is linked, never in a dev server.
117
+ `analytics: false` in the package's call (`unbase({ … })`, `withUnbase(nextConfig, { … })`) leaves
118
+ it out; init never writes that, and keeps it when a site has it.
119
+
120
+ What init adds for it is the collector's origin, `https://unbase.app`, in `connect-src` wherever
121
+ the site sets a Content-Security-Policy it can edit safely: `vercel.json`'s `headers` and
122
+ `public/_headers` (Netlify, Cloudflare Pages), each value changed in place and the rest of the file
123
+ as it was; with no `connect-src`, one made of `default-src`'s sources and the origin. A CSP set
124
+ anywhere else (next.config's `headers()`, a middleware, a `<meta http-equiv>`, `netlify.toml`,
125
+ Astro's `csp` option) is named in `next` and `csp.elsewhere`, never edited. `uninstall` takes the
126
+ origin out of the two files again, to the letter. The reading and the editing are Unbase's own
127
+ (`lib/readers.mjs`, `csp`), the same code `read_install` uses for its Analytics row.
128
+
129
+ On Astro and Vite the package reads `comment-modus.json` itself, so `--no-comments` still writes
130
+ it for analytics, and `--project` links analytics alone. On Next.js the beacon comes with the
131
+ comments' client module: one link for both, and `--no-comments` leaves both out.
132
+
111
133
  ### Linking
112
134
 
113
- comment mode needs the site's Unbase project, which a site added before Unbase knows it does not
114
- have yet. So init writes `comment-modus.json` with `"project": null`, and the config only turns
115
- comment mode on once that file names the project: until then the site builds and renders as before.
135
+ comment mode and analytics need the site's Unbase project, which a site added before Unbase knows it
136
+ does not have yet. So init writes `comment-modus.json` with `"project": null`, and the config only
137
+ turns comment mode (and analytics) on once that file names the project: until then the site builds
138
+ and renders as before.
116
139
  Unbase fills the value in when the site is connected (one JSON value, never a change to the
117
140
  config), or `init --project <id>` does. `comment-modus.json` is the same file comment-modus's own
118
141
  CLI reads.
@@ -159,8 +182,10 @@ and per check what is missing, the file, and the step in `agents/astro.md` that
159
182
  Features: **Visual editing** (Astro, the site builds), **Comments on the site** (the package, its
160
183
  line, the link, the markers, the loader), **Page management** (the kit, the drafts in
161
184
  `unbase.pages.json`, the kit running in a production build, the content schemas, the route files
162
- and the site settings and that the layout reads them). `--no-build` skips the build and what needs
163
- it.
185
+ and the site settings and that the layout reads them), **Analytics** (the package at a version that
186
+ brings it, not `analytics: false`, the link, before Next.js 16.3 the client module's import, and the
187
+ CSP of `vercel.json` and `public/_headers` allowing `https://unbase.app`; a CSP set elsewhere is
188
+ named as `info`). `--no-build` skips the build and what needs it.
164
189
 
165
190
  The markers are comment mode's `data-c`: a pin on the live site takes its title and source file
166
191
  from them, so with comments they belong in the production build. A site without comment mode, or
@@ -173,8 +198,9 @@ an older comment-modus that ignores `"preview"`.
173
198
  Refuses while `unbase.pages.json` holds a draft, and lists them: without the kit a draft is built
174
199
  and goes live, so each is published or deleted in Unbase first. Then it builds the site, removes
175
200
  the packages, their lines in `astro.config`, `comment-modus.json`, `unbase.pages.json`,
176
- `src/content/.schemas/` and the pointer line, builds again, and compares every page's HTML. Taken
177
- out first: comment mode's markers and loader, and what differs between any two builds (asset
201
+ `src/content/.schemas/`, the collector in the CSP of `vercel.json` and `public/_headers`, and the
202
+ pointer line, builds again, and compares every page's HTML. Taken out first: comment mode's markers
203
+ and loader, the analytics beacon, and what differs between any two builds (asset
178
204
  hashes, Astro's ids, white space, attribute order). When pages still differ it builds the after
179
205
  state once more, and what differs between those two builds (an id a component makes at random on
180
206
  every render) is noise, not a change. "No differences in the built pages" is the pass. `--yes` without
@@ -189,7 +215,9 @@ The route files, the settings file and the layout's reads stay: they are the sit
189
215
  - **`--json`** on every command. `init`: `packages` (name, the pinned `version`, dev, and `action`:
190
216
  `added`, `updated` with `from` and `to`, or `kept`, with a `note` when the one there is newer)
191
217
  and `files` (file, `created`, `changed` or `removed`, and the changes; the lockfile too when
192
- the package manager ran). `doctor`: `features`, each
218
+ the package manager ran); `analytics` (on, unless the config says `analytics: false`) and `csp`
219
+ (`files` it allowed the collector in, `invalid` ones it could not read, and `elsewhere`: each
220
+ `{ file, why }` that may set a CSP it does not edit). `doctor`: `features`, each
193
221
  with `state` (`on`, `off`, `waiting`, `not-installed`) and `checks` (`id`, `state`, `message`,
194
222
  and for a `missing` or `waiting` check `missing`, `file`, `step`). `uninstall`: `files`
195
223
  (every file it touched, the lockfile included), `packages`, `comparison` (`pages`,
package/agents/astro.md CHANGED
@@ -141,7 +141,22 @@ Nothing to add: `unbase()` brings the kit, which keeps every page Unbase marks a
141
141
  cannot. It runs after every other integration by itself; don't add `unbasePages()` beside it. A page
142
142
  that cannot be a draft (a dynamic route, a page another file imports) is fine; doctor lists them.
143
143
 
144
- ## 6. Check
144
+ ## 6. Analytics
145
+
146
+ Nothing to add for the beacon itself: the package brings it, on by default, and every page of a
147
+ production build sends a pageview to Unbase once the site is linked to its project (no cookies,
148
+ nothing stored on the visitor's device; never in the dev server). `analytics: false` in `unbase({ … })`
149
+ leaves it out; keep that only if the site's owner asked for it.
150
+
151
+ What can stop it is the site's own **Content-Security-Policy**: the beacon posts to
152
+ `https://unbase.app`, so a CSP needs that origin in `connect-src` (or in `default-src` when there
153
+ is no `connect-src`). `init` adds it where the site sets the CSP in `vercel.json` (its `headers`) or
154
+ `public/_headers`, and doctor checks both. A CSP set anywhere else (next.config's `headers()`, a
155
+ middleware, a `<meta http-equiv>`, `netlify.toml`, Astro's own `csp` option) is yours: doctor names the file; add
156
+ `https://unbase.app` to its `connect-src`, and change nothing else in it.
157
+ The beacon is bundled with the site's own page scripts, so `script-src` needs nothing new.
158
+
159
+ ## 7. Check
145
160
 
146
161
  `npx @unbase-app/cli doctor` builds the site once and says, per feature, what Unbase will say:
147
162
 
@@ -151,12 +166,14 @@ that cannot be a draft (a dynamic route, a page another file imports) is fine; d
151
166
  `componentMarker: "preview"` in `unbase()`).
152
167
  - **Page management**: the kit, the drafts, the route files and the site settings, and that the
153
168
  layout reads them.
169
+ - **Analytics**: the package new enough, not `analytics: false`, the link to a project, and the
170
+ CSP allowing `https://unbase.app`.
154
171
 
155
172
  `missing` is yours to fix. `waiting` is outside this repository (Unbase linking the project, a
156
173
  package release) and does not fail the run. Then commit on a new branch.
157
174
 
158
175
  ## Leaving
159
176
 
160
- `npx @unbase-app/cli uninstall` takes out what init added, after the drafts are published or deleted, and
161
- compares every built page before and after. The route files, the settings file and the layout's
177
+ `npx @unbase-app/cli uninstall` takes out what init added (the collector in the CSP too), after the drafts
178
+ are published or deleted, and compares every built page before and after. The route files, the settings file and the layout's
162
179
  reads stay: they are the site's own code and keep working.
package/agents/next.md CHANGED
@@ -95,7 +95,25 @@ a draft is fine; doctor lists them with the reason:
95
95
 
96
96
  Drafts need Next.js 15.4 or later (the check after the compile).
97
97
 
98
- ## 5. Check
98
+ ## 5. Analytics
99
+
100
+ Nothing to add for the beacon itself: the package brings it, on by default, and every page of a
101
+ production build sends a pageview to Unbase once the site is linked to its project (no cookies,
102
+ nothing stored on the visitor's device; never in the dev server). `analytics: false` in `withUnbase(nextConfig, { analytics: false })`
103
+ leaves it out; keep that only if the site's owner asked for it.
104
+
105
+ What can stop it is the site's own **Content-Security-Policy**: the beacon posts to
106
+ `https://unbase.app`, so a CSP needs that origin in `connect-src` (or in `default-src` when there
107
+ is no `connect-src`). `init` adds it where the site sets the CSP in `vercel.json` (its `headers`) or
108
+ `public/_headers`, and doctor checks both. A CSP set anywhere else (next.config's `headers()`, a
109
+ middleware, a `<meta http-equiv>`, `netlify.toml`) is yours: doctor names the file; add
110
+ `https://unbase.app` to its `connect-src`, and change nothing else in it.
111
+ The beacon comes with the comments' client module (step 2), so it needs the same link to a project
112
+ and, before Next.js 16.3, the same import in `instrumentation-client`: on Next.js, a site without
113
+ comments on the live site has no analytics either. It is bundled into the site's own chunks, so
114
+ `script-src` needs nothing new.
115
+
116
+ ## 6. Check
99
117
 
100
118
  `npx @unbase-app/cli doctor` builds the site once and says, per feature, what Unbase will say:
101
119
 
@@ -104,6 +122,8 @@ Drafts need Next.js 15.4 or later (the check after the compile).
104
122
  loader on the page and in the build.
105
123
  - **Page management**: the package, the drafts, `withUnbase` running in a production build, which
106
124
  pages can be drafts, and which pages' settings Unbase can set.
125
+ - **Analytics**: the package new enough, not `analytics: false`, the link to a project, the client
126
+ module on the page, and the CSP allowing `https://unbase.app`.
107
127
 
108
128
  `missing` is yours to fix. `waiting` is outside this repository (Unbase linking the project, a
109
129
  package release) and does not fail the run. Then commit on a new branch.
@@ -87,7 +87,23 @@ puts a few lines in `index.html` that load comment mode only with `?comment`, an
87
87
  values where the site is built, `PUBLIC_SUPABASE_URL` and `PUBLIC_SUPABASE_ANON_KEY`; Unbase sets
88
88
  them on Vercel when the site is connected there. Do not put them in the repository.
89
89
 
90
- ## 5. Check
90
+ ## 5. Analytics
91
+
92
+ Nothing to add for the beacon itself: the package brings it, on by default, and every page of a
93
+ production build sends a pageview to Unbase once the site is linked to its project (no cookies,
94
+ nothing stored on the visitor's device; never in the dev server). `analytics: false` in `unbase({ … })`
95
+ leaves it out; keep that only if the site's owner asked for it.
96
+
97
+ What can stop it is the site's own **Content-Security-Policy**: the beacon posts to
98
+ `https://unbase.app`, so a CSP needs that origin in `connect-src` (or in `default-src` when there
99
+ is no `connect-src`). `init` adds it where the site sets the CSP in `vercel.json` (its `headers`) or
100
+ `public/_headers`, and doctor checks both. A CSP set anywhere else (next.config's `headers()`, a
101
+ middleware, a `<meta http-equiv>`, `netlify.toml`) is yours: doctor names the file; add
102
+ `https://unbase.app` to its `connect-src`, and change nothing else in it.
103
+ The beacon is an inline script in the built `index.html`, as comment mode's loader is: a CSP without
104
+ `'unsafe-inline'` in `script-src` needs the script's hash there.
105
+
106
+ ## 6. Check
91
107
 
92
108
  `npx @unbase-app/cli doctor` builds the site once (production, with `vite build` into a folder of its own)
93
109
  and says, per feature, what Unbase will say:
@@ -97,6 +113,8 @@ and says, per feature, what Unbase will say:
97
113
  files in the build.
98
114
  - **Page management**: the kit, the drafts, the pages Unbase finds in the router, and the site
99
115
  settings in `index.html`.
116
+ - **Analytics**: the package new enough, not `analytics: false`, the link to a project, and the
117
+ CSP allowing `https://unbase.app`.
100
118
 
101
119
  `missing` is yours to fix. `waiting` is outside this repository (Unbase linking the project, a
102
120
  package release) and does not fail the run. Then commit on a new branch.
@@ -0,0 +1,142 @@
1
+ // ============================================================================
2
+ // Analytics in the CLI (docs/plan-analytics.md, AN2). Unbase's beacon comes
3
+ // inside each framework's package from the version ANALYTICS_FROM names, on
4
+ // by default, for the project comment-modus.json names; `analytics: false` in
5
+ // the package's call leaves it out. What the CLI adds around it is the site's
6
+ // Content-Security-Policy, with Unbase's own CSP reader (lib/readers.mjs
7
+ // `csp`, the code read_install and an install run use):
8
+ //
9
+ // init the collector's origin added to `connect-src` where the site
10
+ // sets a CSP the CLI can edit safely (vercel.json,
11
+ // public/_headers), and every other place that may set one
12
+ // named, never edited (next.config's headers(), a middleware,
13
+ // a <meta http-equiv>, netlify.toml, Astro's `csp`)
14
+ // uninstall the origin taken out of those two files again
15
+ // doctor a fourth feature, Analytics: the package new enough, not
16
+ // `analytics: false`, the project linked, the CSP allowing the
17
+ // collector
18
+ //
19
+ // The framework modules call these with what they read of their own config.
20
+ // ============================================================================
21
+
22
+ import { check, featureState } from "./feature.mjs";
23
+ import { csp } from "./readers.mjs";
24
+ import { ANALYTICS_FROM, compareVersions, versionIn } from "./versions.mjs";
25
+
26
+ /** The collector's origin, as a CSP allows it. */
27
+ export const COLLECTOR_ORIGIN = csp.COLLECTOR_ORIGIN;
28
+
29
+ /** Where a site's files may set a CSP besides the two the CLI edits: paths worth reading. */
30
+ const MAY_SET = /\.(m?[jt]sx?|c[jt]s|astro|html?|vue|svelte|toml|ya?ml)$/;
31
+
32
+ /** Every other place the site may set a CSP: [{ file, why }], for init and doctor to name. */
33
+ export function cspElsewhereIn(site) {
34
+ const out = [];
35
+ for (const file of site.appPaths) {
36
+ if (!MAY_SET.test(file) || file.includes("node_modules/")) continue;
37
+ const why = csp.cspElsewhere(file, site.text(file));
38
+ if (why) out.push({ file, why });
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /** A policy as a change line names it: the header, and the path it is set for. */
44
+ const named = (p) => `Content-Security-Policy${p.source ? ` for ${p.source}` : ""}`;
45
+
46
+ /**
47
+ * The CSP files as init (`add`) or uninstall leaves them: each one that changes, as
48
+ * { file, action: "changed", changes, text }, and what could not be read (`invalid`). Writes nothing.
49
+ */
50
+ export function planCsp(site, { add }) {
51
+ const files = [];
52
+ const invalid = [];
53
+ for (const file of csp.CSP_FILES) {
54
+ const text = site.text(file);
55
+ if (text === null) continue;
56
+ const read = csp.policiesIn(file, text);
57
+ if (read.invalid) {
58
+ invalid.push(file);
59
+ continue;
60
+ }
61
+ const next = add ? csp.withCollectorIn(file, text) : csp.withoutCollectorIn(file, text);
62
+ if (next === text) continue;
63
+ const after = csp.policiesIn(file, next).policies;
64
+ const changed = read.policies.filter((p, i) => after[i]?.value !== p.value);
65
+ files.push({ file, action: "changed", changes: changed.map((p) => `${named(p)}: connect-src ${add ? "+" : "−"} ${COLLECTOR_ORIGIN}`), text: next });
66
+ }
67
+ return { files, invalid };
68
+ }
69
+
70
+ /** The lines init adds to `next` for the CSPs it found but does not edit. */
71
+ export const elsewhereSteps = (elsewhere) => elsewhere.map((e) => `Allow ${COLLECTOR_ORIGIN} in connect-src in ${e.file} (${e.why}), which sets a Content-Security-Policy the CLI does not edit.`);
72
+
73
+ /**
74
+ * doctor's Analytics feature. `umbrella`: the framework's package { name }; `version`: the one the
75
+ * site has, or null; `configured`: its call is in the config; `option`: its `analytics` option
76
+ * there (true when absent, false, or null when not literal); `project`: the linked project, or null; `before`: a site from before K5 (the
77
+ * pair, no framework package); `step`: the agents file's Analytics step; `install`: its Install
78
+ * step; `config`: the config's file name; `loader`: Next.js before 16.3, whether the client module
79
+ * that brings the beacon is imported (null where not asked).
80
+ */
81
+ export function analyticsFeature(site, { umbrella, version, configured, option, project, before, step, install, config, loader = null }) {
82
+ const checks = [];
83
+ const from = ANALYTICS_FROM[umbrella.name];
84
+ const done = (chose = false) => ({ id: "analytics", name: "Analytics", state: featureState(checks, chose), checks });
85
+
86
+ if (before) {
87
+ checks.push(check("package", "info", `Analytics comes with ${umbrella.name} ${from}: \`npx @unbase-app/cli init\` moves the site across to it.`));
88
+ return done(true);
89
+ }
90
+ if (!version && !configured) {
91
+ checks.push(check("package", "missing", `${umbrella.name} is not a dependency, and analytics comes with it.`, { missing: `${umbrella.name} ${from} or later`, file: "package.json", step: install }));
92
+ return done();
93
+ }
94
+ const have = versionIn(version);
95
+ if (have && compareVersions(have, from) < 0)
96
+ checks.push(check("version", "missing", `${umbrella.name} ${have} has no analytics; ${from} brings it: \`npx @unbase-app/cli init\` updates it.`, { missing: `${umbrella.name} ${from} or later`, file: "package.json", step: install }));
97
+ else if (!configured) checks.push(check("config", "missing", `${config} does not use ${umbrella.name}, which brings analytics.`, { missing: `${umbrella.name}'s line in ${config}`, file: config, step: install }));
98
+ else checks.push(check("package", "ok", `${umbrella.name} ${have ?? version} brings the analytics beacon: a pageview to Unbase from every page of a production build, no cookies.`));
99
+ if (option === false) {
100
+ checks.push(check("option", "info", `${config} says \`analytics: false\`: no beacon. Take the option out to count visits in Unbase.`));
101
+ return done(true);
102
+ }
103
+ if (option === null) checks.push(check("option", "info", `${config} passes options doctor cannot read; \`analytics: false\` among them would leave the beacon out.`));
104
+ if (loader === false) checks.push(check("loader", "missing", `Next.js before 16.3 runs the beacon only when instrumentation-client imports the client module.`, { missing: "the client module's import", file: "instrumentation-client.ts", step }));
105
+
106
+ if (project) checks.push(check("link", "ok", `Counting for the Unbase project "${project}".`));
107
+ else
108
+ checks.push(
109
+ check("link", "waiting", "Not linked to an Unbase project yet, so analytics stays off. Unbase fills in `project` in comment-modus.json when the site is connected; or run `unbase init --project <id or slug>`.", {
110
+ missing: "project in comment-modus.json",
111
+ file: "comment-modus.json",
112
+ }),
113
+ );
114
+
115
+ // The CSP: the two files the CLI edits are read; elsewhere is named.
116
+ let any = false;
117
+ for (const file of csp.CSP_FILES) {
118
+ const text = site.text(file);
119
+ if (text === null) continue;
120
+ const read = csp.policiesIn(file, text);
121
+ if (read.invalid) {
122
+ checks.push(check("csp", "info", `${file} cannot be read as its format, so doctor cannot see whether its Content-Security-Policy allows ${COLLECTOR_ORIGIN}.`, { file }));
123
+ continue;
124
+ }
125
+ for (const p of read.policies) {
126
+ any = true;
127
+ checks.push(
128
+ csp.policyAllows(p.value)
129
+ ? check("csp", "ok", `${file}: the ${named(p)} allows ${COLLECTOR_ORIGIN}.`, { file })
130
+ : check("csp", "missing", `${file}: the ${named(p)} does not allow ${COLLECTOR_ORIGIN} in connect-src, so the browser blocks every pageview. \`npx @unbase-app/cli init\` adds it.`, {
131
+ missing: `${COLLECTOR_ORIGIN} in connect-src`,
132
+ file,
133
+ step,
134
+ }),
135
+ );
136
+ }
137
+ }
138
+ for (const e of cspElsewhereIn(site))
139
+ checks.push(check("csp-elsewhere", "info", `${e.file} may set a Content-Security-Policy (${e.why}), which doctor does not read: allow ${COLLECTOR_ORIGIN} in its connect-src.`, { file: e.file, step }));
140
+ if (!any) checks.push(check("csp", "ok", `No Content-Security-Policy in ${csp.CSP_FILES.join(" or ")}.`));
141
+ return done();
142
+ }
package/lib/compare.mjs CHANGED
@@ -1,24 +1,28 @@
1
1
  // ============================================================================
2
2
  // Two builds' pages, compared: what a visitor gets, before and after
3
3
  // uninstall. What only the packages put in a page is taken out first (comment
4
- // mode's markers and its loader scripts), and what differs between any two
5
- // builds (asset hashes, Astro's scope and island ids, white space, comments).
6
- // Anything else that differs is a difference.
4
+ // mode's markers and its loader scripts, and the analytics beacon), and what
5
+ // differs between any two builds (asset hashes, Astro's scope and island ids,
6
+ // white space, comments). Anything else that differs is a difference.
7
7
  // ============================================================================
8
8
 
9
9
  /** comment-modus's loader and the head script that keeps its toolbar across pages carry its name. */
10
- const OURS = /comment-modus/;
10
+ const COMMENTS = /comment-modus/;
11
+ /** The analytics beacon (@unbase-app/analytics) carries the flag it sets on the window. */
12
+ const BEACON = /__unbaseAnalytics/;
13
+ /** Every script of ours. */
14
+ const OURS = /comment-modus|__unbaseAnalytics/;
11
15
 
12
16
  /**
13
- * The page without comment mode's scripts: inline ones that carry its name always; a script file
14
- * that carries it only with `files` (Astro may bundle the loader with the site's own page scripts
15
- * into one file, which then stays after uninstall).
17
+ * The page without our scripts (`ours`: by default all of them): inline ones that carry the mark
18
+ * always; a script file that carries it only with `files` (Astro may bundle the loader and the
19
+ * beacon with the site's own page scripts into one file, which then stays after uninstall).
16
20
  */
17
- function withoutOurScripts(html, file, files = true) {
21
+ function withoutOurScripts(html, file, files = true, ours = OURS) {
18
22
  return html.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g, (whole, attrs, body) => {
19
- if (OURS.test(body)) return "";
23
+ if (ours.test(body)) return "";
20
24
  const src = /\bsrc=["']?([^"'\s>]+)/.exec(attrs)?.[1];
21
- if (files && src && src.startsWith("/") && OURS.test(file(src.replace(/^\/+/, "").replace(/[?#].*$/, "")) ?? "")) return "";
25
+ if (files && src && src.startsWith("/") && ours.test(file(src.replace(/^\/+/, "").replace(/[?#].*$/, "")) ?? "")) return "";
22
26
  return whole;
23
27
  });
24
28
  }
@@ -93,4 +97,7 @@ export function comparePages(before, after, again = null, pre = (html) => html)
93
97
  }
94
98
 
95
99
  /** Whether a page carries comment mode's loader (inline, or in a script file it loads). */
96
- export const hasOurScript = (html, file = () => null) => withoutOurScripts(html, file) !== html;
100
+ export const hasOurScript = (html, file = () => null) => withoutOurScripts(html, file, true, COMMENTS) !== html;
101
+
102
+ /** Whether a page carries the analytics beacon (inline, or in a script file it loads). */
103
+ export const hasBeacon = (html, file = () => null) => withoutOurScripts(html, file, true, BEACON) !== html;
@@ -159,16 +159,17 @@ function projectOf(call) {
159
159
  return v?.type === "StringLiteral" ? v.value : null;
160
160
  }
161
161
 
162
- /** unbase()'s `comments`: true (absent, or true), false, or null when the config does not say it literally. */
163
- function commentsIn(call) {
162
+ /** unbase()'s boolean option `name` (`comments`, `analytics`): true (absent, or true), false, or null when the config does not say it literally. */
163
+ function booleanIn(call, name = "comments") {
164
164
  const opts = unwrap(call?.arguments[0]);
165
165
  if (!opts) return true;
166
166
  if (opts.type !== "ObjectExpression") return null;
167
- const prop = propNamed(opts, "comments");
167
+ const prop = propNamed(opts, name);
168
168
  if (!prop) return spreads(opts) ? null : true;
169
169
  const v = unwrap(prop.value);
170
170
  return v.type === "BooleanLiteral" ? v.value : null;
171
171
  }
172
+ const commentsIn = (call) => booleanIn(call, "comments");
172
173
 
173
174
  /**
174
175
  * What a config holds of Unbase's packages, read from its tree: for doctor, and for init and
@@ -213,6 +214,10 @@ export function inspectConfig(code, file) {
213
214
  },
214
215
  /** unbase()'s `comments`: true, false (comments: false), null when not literal; null without unbase(). */
215
216
  unbaseComments,
217
+ /** unbase()'s `analytics`: true, false (analytics: false), null when not literal; null without unbase(). */
218
+ unbaseAnalytics: unbase ? booleanIn(callOf(unbase.el), "analytics") : null,
219
+ /** A literal `project` in unbase(), with or without comment mode; null otherwise. */
220
+ unbaseProject: unbase ? projectOf(callOf(unbase.el)) : null,
216
221
  /** comment mode's componentMarker: "always", "preview", false; null when unreadable or without comment mode. */
217
222
  markers: comments ? markersOf(callOf(comments.el)) : null,
218
223
  /** comment mode's own literal project, set in the config itself; null when it comes from comment-modus.json or a variable. */
@@ -4,14 +4,15 @@
4
4
  // astro.config (config-edit, through the syntax tree) and comment-modus.json;
5
5
  // on a site from before K5 it moves the pair (comment-modus and the kit)
6
6
  // across to it (`replaced`). uninstall takes either out with
7
- // unbase.pages.json and the content schemas; doctor reads three features
7
+ // unbase.pages.json and the content schemas; doctor reads four features
8
8
  // with Unbase's own readers (lib/readers.mjs: detect, read_settings,
9
- // list_pages and the kit's core) on the working tree and one production
10
- // build. The steps init leaves: agents/astro.md.
9
+ // list_pages, the kit's core and the CSP reader) on the working tree and one
10
+ // production build. The steps init leaves: agents/astro.md.
11
11
  // ============================================================================
12
12
 
13
13
  import { existsSync, readdirSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
+ import { analyticsFeature } from "../analytics.mjs";
15
16
  import { tailOf } from "../build.mjs";
16
17
  import { hasOurScript } from "../compare.mjs";
17
18
  import { addToConfig, inspectConfig, removeFromConfig } from "../config-edit.mjs";
@@ -32,6 +33,7 @@ const STEPS = {
32
33
  siteSettings: `${AGENTS} step 3: Site settings`,
33
34
  schemas: `${AGENTS} step 4: Schemas`,
34
35
  drafts: `${AGENTS} step 5: Draft pages`,
36
+ analytics: `${AGENTS} step 6: Analytics`,
35
37
  };
36
38
  const SITE_FIELDS = ["naam", "beschrijving", "taal", "favicon", "faviconDonker", "ogImage", "googleAnalytics"];
37
39
  const SOURCE = /^src\/.*\.(astro|ts|tsx|js|jsx|mjs|mts|mdx)$/;
@@ -60,8 +62,8 @@ export function readLink(site) {
60
62
 
61
63
  // ── init ───────────────────────────────────────────────────────────────────
62
64
 
63
- /** init's plan for astro.config and comment-modus.json. */
64
- function planInit(site, { comments, project }) {
65
+ /** init's plan for astro.config and comment-modus.json (for comment mode, or for analytics alone with --no-comments). */
66
+ function planInit(site, { comments, project, analytics = true }) {
65
67
  if (!site.configFile) throw new CouldNotRun("no_config", "No astro.config.(mjs|ts|js|mts) in the site's folder.");
66
68
  const configCode = site.text(site.configFile);
67
69
  const before = inspectConfig(configCode, site.configFile);
@@ -96,6 +98,9 @@ function planInit(site, { comments, project }) {
96
98
  if (project && data.project !== project) link = { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
97
99
  else if (!("project" in data) && usesLink) link = { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
98
100
  }
101
+ } else if (analytics) {
102
+ // Without comment mode the link is analytics': unbase() reads comment-modus.json itself.
103
+ link = linkFor(site, project);
99
104
  }
100
105
  return [
101
106
  ...(config.changes.length ? [{ file: site.configFile, action: "changed", changes: config.changes, text: config.code }] : []),
@@ -103,6 +108,33 @@ function planInit(site, { comments, project }) {
103
108
  ];
104
109
  }
105
110
 
111
+ /** comment-modus.json for analytics alone: made with the project (or null), the project changed, else nothing. */
112
+ function linkFor(site, project) {
113
+ const text = site.text(LINK_FILE);
114
+ if (text === null) return { action: "created", data: { project }, indent: " ", changes: [project ? `project: "${project}"` : "project: null (Unbase fills it in when the site is connected)"] };
115
+ let data;
116
+ try {
117
+ data = JSON.parse(text);
118
+ } catch {
119
+ throw new CouldNotRun("link_file", `${LINK_FILE} is not valid JSON.`, { file: LINK_FILE });
120
+ }
121
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new CouldNotRun("link_file", `${LINK_FILE} is not a JSON object.`, { file: LINK_FILE });
122
+ const indent = /^[ \t]+(?=")/m.exec(text)?.[0] ?? " ";
123
+ if (project && data.project !== project) return { action: "changed", data: { ...data, project }, indent, changes: [`project: ${JSON.stringify(data.project ?? null)} → "${project}"`] };
124
+ if (!("project" in data)) return { action: "changed", data: { project: null, ...data }, indent, changes: ["project: null"] };
125
+ return null;
126
+ }
127
+
128
+ /** unbase()'s `analytics` in the config as it is: false only when it says so literally. */
129
+ function analyticsOption(site) {
130
+ if (!site.configFile) return true;
131
+ try {
132
+ return inspectConfig(site.text(site.configFile), site.configFile).unbaseAnalytics !== false;
133
+ } catch {
134
+ return true;
135
+ }
136
+ }
137
+
106
138
  // ── uninstall ──────────────────────────────────────────────────────────────
107
139
 
108
140
  // ── The move (K5) ──────────────────────────────────────────────────────────
@@ -457,6 +489,21 @@ async function doctorFeatures(site, { build }) {
457
489
  }
458
490
  features.push({ id: "page-management", name: "Page management", state: featureState(checks), checks });
459
491
  }
492
+
493
+ // ── Analytics ─────────────────────────────────────────────────────────────
494
+ features.push(
495
+ analyticsFeature(site, {
496
+ umbrella: ASTRO,
497
+ version: one ? (installedVersion(site, ASTRO.name) ?? deps[ASTRO.name]) : null,
498
+ configured: !!config?.has.unbase,
499
+ option: config ? config.unbaseAnalytics : null,
500
+ project: readLink(site) ?? config?.unbaseProject ?? null,
501
+ before: !one && [COMMENT_MODUS.name, BEFORE.pages].some((n) => deps[n] !== undefined),
502
+ step: STEPS.analytics,
503
+ install: STEPS.install,
504
+ config: site.configFile ?? "astro.config.mjs",
505
+ }),
506
+ );
460
507
  return features;
461
508
  }
462
509
 
@@ -474,6 +521,9 @@ export default {
474
521
  configFiles: core.kitFiles("astro").filter((f) => f !== "package.json"),
475
522
  agents: AGENTS,
476
523
  comments: true,
524
+ /** comment-modus.json links analytics without comment mode too: unbase() reads it itself. */
525
+ analyticsLink: true,
526
+ analyticsOption,
477
527
  build: { bin: "astro", args: (outDir) => ["build", "--outDir", outDir], env: { ASTRO_TELEMETRY_DISABLED: "1" }, output: ADAPTER_OUTPUT },
478
528
  packages: () => [ASTRO, SELF],
479
529
  init: planInit,
@@ -15,6 +15,13 @@
15
15
  // relative to the package ("agents/astro.md"); AGENTS.md
16
16
  // points to it, init names it, doctor's steps cite it
17
17
  // comments whether init offers comments on the live site (--comments)
18
+ // analyticsLink
19
+ // whether comment-modus.json links analytics without comment
20
+ // mode (the package reads the file itself): init writes it
21
+ // with --no-comments too, and takes --project then
22
+ // analyticsOption(site)
23
+ // the config's `analytics` option as it is: false only when it
24
+ // says so literally; init leaves the CSP alone then
18
25
  // build the production build doctor and uninstall make (build.mjs):
19
26
  // { bin, args(outDir), env, output }, `output` the folders a
20
27
  // build may write its pages to instead of outDir