@prunellejs/analytics 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -4,21 +4,24 @@
4
4
 
5
5
  ## Imports
6
6
 
7
- - `@prunellejs/analytics`: `analytics`, `plausible`, `umami`, `matomo`, `custom`, `computeVisitorId`, `DEFAULT_EVENT_ENDPOINT`, `DEFAULT_VITALS_ENDPOINT`; types `AnalyticsOptions`, `AnalyticsProvider`, `AnalyticsPageview`, `AnalyticsEvent`, `AnalyticsEventProps`, `WebVitalMetric`, `WebVitalName`, `WebVitalRating`, `WebVitalsOptions`, `PlausibleOptions`, `UmamiOptions`, `MatomoOptions`, `CustomAnalyticsOptions`.
7
+ - `@prunellejs/analytics`: `analytics`, `plausible`, `umami`, `matomo`, `custom`, `coarseUserAgent`, `computeVisitorId`, `DEFAULT_EVENT_ENDPOINT`, `DEFAULT_OPT_OUT_ENDPOINT`, `DEFAULT_VITALS_ENDPOINT`, `OPT_OUT_COOKIE`; types `AnalyticsOptions`, `AnalyticsProvider`, `AnalyticsPageview`, `AnalyticsEvent`, `AnalyticsEventProps`, `WebVitalMetric`, `WebVitalName`, `WebVitalRating`, `WebVitalsOptions`, `PlausibleOptions`, `UmamiOptions`, `MatomoOptions`, `CustomAnalyticsOptions`.
8
8
  - `@prunellejs/analytics/client`: `trackEvent`; types `AnalyticsEventProps`, `TrackEventOptions` (browser-safe, zero server imports).
9
9
 
10
10
  ## Setup (`analytics(options)`)
11
11
 
12
12
  Register in `prunelle.config.ts` `plugins`:
13
13
 
14
- - `provider`: `plausible({ domain, host? })`, `umami({ websiteId, host })`, `matomo({ url, siteId, tokenAuth? })`, or `custom({ sendPageview, sendEvent?, sendVital?, requiresConsent? })`. Self-hosted providers default to `requiresConsent: false`; third-party `plausible.io` defaults to `requiresConsent: true`.
15
- - Counts both dynamic and prerendered HTML GET 2xx page views via `api.use(mw, { scope: 'all' })` with **0 B client JS** (never sets `clientEntry`). Automatically skips non-GET, non-2xx/non-HTML, `/_pru/` assets, `/auth` and `/auth/*` paths, bots, and prefetch requests. Strips query strings and fragments from `url` and `referrer` by default (pass `includeQueryParams: ['utm_source', ...]` to allowlist specific query params).
14
+ - `provider`: `plausible({ domain, host? })`, `umami({ websiteId, host })`, `matomo({ url, siteId, tokenAuth? })`, or `custom({ sendPageview, sendEvent?, sendVital?, requiresConsent? })`. `plausible()` defaults to `requiresConsent: true` for `plausible.io` and `false` for a self-hosted host; `umami()` and `matomo()` default to `true` unless their host is the app's own (the `site` host, a subdomain of it, or loopback), and `custom()` to `true`. `requiresConsent: false` is the explicit waiver, for a tool that meets the CNIL conditions (publisher alone, anonymous, no cross-site tracking). Providers receive a User-Agent cut to major versions and 160 characters.
15
+ - Counts both dynamic and prerendered HTML GET 2xx page views via `api.use(mw, { scope: 'all' })` with **0 B client JS** (never sets `clientEntry`). Automatically skips non-GET, non-2xx/non-HTML, `/_pru/` assets, `/auth` and `/auth/*` paths, bots, and prefetch requests (`Purpose: prefetch`, as `@prunellejs/spa` sends, and the browsers' own headers). Strips query strings and fragments from `url` and `referrer` by default (pass `includeQueryParams: ['utm_source', ...]` to allowlist specific query params).
16
16
  - `secret`: optional hash salt (defaults to `process.env.ANALYTICS_SECRET` or a random ephemeral per-process 32-byte secret). Visitor ID is `SHA-256(YYYY-MM-DD, secret, ip, userAgent, hostname)` — daily-rotating, no cookies, no persistent storage.
17
17
  - `sendIp`: default `false`. Raw client IP is NEVER forwarded to providers unless `sendIp: true`.
18
- - `requiresConsent` / `consentCategory`: consent gating automatically turns on (`'analytics'`) when `sendIp: true` or `provider.requiresConsent === true`. Applies to page views, custom events, and Web Vitals (`onVital` and `provider.sendVital`). Override with `consentCategory: 'analytics'` or `consentCategory: false`.
18
+ - `requiresConsent` / `consentCategory`: consent gating automatically turns on (`'analytics'`) when `sendIp: true` or the provider requires it (see `provider`). Applies to page views, custom events, and Web Vitals (`onVital` and `provider.sendVital`). Override with `consentCategory: 'analytics'` or `consentCategory: false`. The category must be declared in `consent.categories` (`requires()`: a production start refuses, dev and `prunelle check` warn); `prunelle check` warns about `sendIp: true` with consent off.
19
+ - `viewEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/view'`, or `false` to count no prefetched page). A prefetch that would be counted is answered with `x-pru-view: <viewEndpoint>` instead of being counted, and `@prunellejs/spa` posts the page path and query there with `navigator.sendBeacon` when it renders the page from its prefetch cache. The beacon counts one view through the middleware's filters (bot, `exclude`, consent, query stripping), takes the `Referer` of the page left, answers `400` to a body that is not a same-origin path of at most 2000 characters, and `204` otherwise.
19
20
  - `eventEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/event'`, or `false` to disable). Event URLs are confined to same-origin (`site` or request origin).
20
- - `webVitals`: default `false` (0 B JS). Set `true` or `{ endpoint?, onVital? }` to emit a `<1.5 KB` `<script defer src="/_pru/analytics-vitals-*.js">` collecting LCP, session-window CLS, p98 INP, FCP, and TTFB to `POST /_pru/analytics/vitals` (CSRF-protected).
21
- - `ignoreBots`: default `true`. `exclude`: path prefixes, RegExps, or `(ctx) => boolean`. `rateLimit`: rate limit on event/vitals endpoints (default `60/min` per IP; `false` disables). `maxPending`: max concurrent outbound provider requests before dropping (default `64`). `onError`: optional provider error callback.
21
+ - `webVitals`: default `false` (0 B JS). Set `true` or `{ endpoint?, sampleRate?, onVital? }` to emit a `<1.5 KB` `<script defer src="/_pru/analytics-vitals-*.js">` collecting LCP, session-window CLS, p98 INP, FCP, and TTFB, sent in one beacon when the page hides to `POST /_pru/analytics/vitals` (CSRF-protected; `onVital` runs per metric; `sampleRate: 0.1` measures one view in ten). Under consent the tag is `<script defer src="/_pru/analytics/vitals.js">`, answered only to a visitor who granted the category (an empty script otherwise, `private, no-cache` with an ETag).
22
+ - `ignoreBots`: default `true`, on page views, events and vitals (the last two answer 204). Event and vitals bodies over 16 KiB get 413. An event is refused with 400 past: name 100 characters, `url` or `path` 2000, 30 props, 64 character keys, 100 character string values. Props are dropped unless their key is in `eventProps: string[]` (default none).
23
+ - `optOutEndpoint`: default `'/_pru/analytics/opt-out'`, `false` removes it. `POST` sets the essential cookie `pru_no_count` (one year) and the visitor is no longer counted on page views, events or vitals; `DELETE` clears it. A form post (`Accept: text/html`) is sent back to its referer with `303`, otherwise `204`. In dev each dropped event or vital logs `@prunellejs/analytics: dropped event: <reason>`. Provider `timeoutMs` must be a positive finite number (`plausible()`, `umami()` and `matomo()` throw otherwise); a provider error carries at most 300 characters of the response body.
24
+ - `exclude`: path prefixes, RegExps, or `(ctx) => boolean`. `rateLimit`: rate limit on event/vitals endpoints (default `60/min` per IP; `false` disables). `maxPending`: max concurrent outbound provider requests before dropping (default `64`). `onError`: optional provider error callback.
22
25
 
23
26
  ## Snippet
24
27
 
@@ -32,6 +35,7 @@ export default defineConfig({
32
35
  plugins: [
33
36
  analytics({
34
37
  provider: plausible({ domain: 'example.com', host: 'https://stats.example.com' }),
38
+ eventProps: ['plan'],
35
39
  }),
36
40
  ],
37
41
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/analytics",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "CNIL-compliant server-side first-party audience measurement, custom events, and optional Web Vitals plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,6 +22,6 @@
22
22
  "directory": "packages/plugin-analytics"
23
23
  },
24
24
  "peerDependencies": {
25
- "prunelle": "^0.6.0"
25
+ "prunelle": "^0.7.1"
26
26
  }
27
27
  }
package/src/client.ts CHANGED
@@ -31,13 +31,17 @@ export async function trackEvent(
31
31
  const url = options?.url ?? (typeof location !== 'undefined' ? location.href : '/')
32
32
  const body = JSON.stringify(props !== undefined ? { name: trimmed, url, props } : { name: trimmed, url })
33
33
 
34
+ // A beacon the browser refuses (its queue is full, or the body over its quota) goes by fetch keepalive below.
34
35
  if (options?.beacon === true && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
36
+ let queued: boolean
35
37
  try {
36
- return navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))
38
+ queued = navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))
37
39
  }
38
40
  catch {
39
- return false
41
+ queued = false
40
42
  }
43
+ if (queued)
44
+ return true
41
45
  }
42
46
 
43
47
  if (typeof fetch !== 'function')
package/src/consent.ts ADDED
@@ -0,0 +1,31 @@
1
+ // Whether counting waits for consent, and for which category: the app's options and where the provider's collector lives decide.
2
+
3
+ import type { AnalyticsOptions } from './types'
4
+
5
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1'])
6
+
7
+ // A collector the publisher runs for itself: loopback, the site's own host, or a subdomain of it (`www.` ignored).
8
+ function isOwnHost(host: string | undefined, site: string | undefined): boolean {
9
+ if (host === undefined)
10
+ return false
11
+ if (LOOPBACK_HOSTS.has(host))
12
+ return true
13
+ if (site === undefined || !URL.canParse(site))
14
+ return false
15
+ const base = new URL(site).hostname.toLowerCase().replace(/^www\./, '')
16
+ return host === base || host === `www.${base}` || host.endsWith(`.${base}`)
17
+ }
18
+
19
+ export function resolveConsentCategory(options: AnalyticsOptions, site: string | undefined): string | undefined {
20
+ if (options.consentCategory === false)
21
+ return undefined
22
+ if (typeof options.consentCategory === 'string') {
23
+ if (options.requiresConsent === false)
24
+ return undefined
25
+ const trimmed = options.consentCategory.trim()
26
+ return trimmed !== '' ? trimmed : 'analytics'
27
+ }
28
+ const { provider } = options
29
+ const needsConsent = options.requiresConsent ?? (options.sendIp === true || (provider.requiresConsent ?? !isOwnHost(provider.host, site)))
30
+ return needsConsent ? 'analytics' : undefined
31
+ }
package/src/index.ts CHANGED
@@ -11,8 +11,10 @@ import type {
11
11
  WebVitalsOptions,
12
12
  } from './types'
13
13
  import { definePlugin } from 'prunelle/config'
14
- import { escAttr } from 'prunelle/server'
14
+ import { resolveConsentCategory } from './consent'
15
+ import { escAttr, safeRedirect } from 'prunelle/server'
15
16
  import {
17
+ coarseUserAgent,
16
18
  computeVisitorId,
17
19
  extractPrimaryLanguage,
18
20
  formatUtcDate,
@@ -25,10 +27,10 @@ import {
25
27
  resolveCanonicalLocation,
26
28
  sanitizeReferrer,
27
29
  } from './visitor'
28
- import { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, parseWebVitalPayload } from './vitals'
30
+ import { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, parseWebVitalPayloads } from './vitals'
29
31
 
30
32
  export { custom, matomo, plausible, umami } from './providers'
31
- export { computeVisitorId, formatUtcDate, isBotUserAgent, isPrefetchRequest } from './visitor'
33
+ export { coarseUserAgent, computeVisitorId, formatUtcDate, isBotUserAgent, isPrefetchRequest } from './visitor'
32
34
  export { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, rateWebVital } from './vitals'
33
35
  export type {
34
36
  AnalyticsEvent,
@@ -49,13 +51,21 @@ export type {
49
51
  export type { VisitorIdInput } from './visitor'
50
52
 
51
53
  export const DEFAULT_EVENT_ENDPOINT = '/_pru/analytics/event'
54
+ export const DEFAULT_VIEW_ENDPOINT = '/_pru/analytics/view'
52
55
  export const DEFAULT_MAX_PENDING = 64
53
56
  export const DEFAULT_RATE_LIMIT: RateLimit<RequestContext> = { max: 60, windowMs: 60_000 }
54
57
 
58
+ const VIEW_HEADER = 'x-pru-view'
55
59
  const MAX_EVENT_NAME_LEN = 100
56
- const MAX_PROP_KEYS = 32
60
+ const MAX_PROP_KEYS = 30
61
+ const MAX_URL_LEN = 2000
62
+ const MAX_BODY_BYTES = 16 * 1024
57
63
  const MAX_PROP_KEY_LEN = 64
58
- const MAX_PROP_STR_LEN = 256
64
+ const MAX_PROP_STR_LEN = 100
65
+ export const DEFAULT_OPT_OUT_ENDPOINT = '/_pru/analytics/opt-out'
66
+ /** The essential cookie that marks a visitor who opted out of being counted. */
67
+ export const OPT_OUT_COOKIE = 'pru_no_count'
68
+ const OPT_OUT_MAX_AGE_S = 365 * 24 * 60 * 60
59
69
 
60
70
  function normalizeEndpoint(raw: string): string {
61
71
  const trimmed = raw.trim()
@@ -63,45 +73,47 @@ function normalizeEndpoint(raw: string): string {
63
73
  return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1) : withSlash
64
74
  }
65
75
 
66
- function resolveConsentCategory(options: AnalyticsOptions): string | undefined {
67
- if (options.consentCategory === false)
68
- return undefined
69
- if (typeof options.consentCategory === 'string') {
70
- if (options.requiresConsent === false)
71
- return undefined
72
- const trimmed = options.consentCategory.trim()
73
- return trimmed !== '' ? trimmed : 'analytics'
74
- }
75
- const needsConsent = options.requiresConsent ?? (options.sendIp === true || options.provider.requiresConsent === true)
76
- return needsConsent ? 'analytics' : undefined
76
+ interface WebVitalsConfig {
77
+ endpoint: string
78
+ sampleRate: number
79
+ onVital?: WebVitalsOptions['onVital']
77
80
  }
78
81
 
79
- function normalizeWebVitals(webVitals: AnalyticsOptions['webVitals']): { endpoint: string, onVital?: WebVitalsOptions['onVital'] } | undefined {
82
+ function normalizeWebVitals(webVitals: AnalyticsOptions['webVitals']): WebVitalsConfig | undefined {
80
83
  if (webVitals === undefined || webVitals === false)
81
84
  return undefined
82
85
  if (webVitals === true)
83
- return { endpoint: DEFAULT_VITALS_ENDPOINT }
86
+ return { endpoint: DEFAULT_VITALS_ENDPOINT, sampleRate: 1 }
87
+ const sampleRate = webVitals.sampleRate ?? 1
88
+ if (!(sampleRate > 0 && sampleRate <= 1))
89
+ throw new Error(`prunelle: @prunellejs/analytics webVitals.sampleRate must be above 0 and at most 1, got ${String(sampleRate)}`)
84
90
  return {
85
91
  endpoint: normalizeEndpoint(webVitals.endpoint ?? DEFAULT_VITALS_ENDPOINT),
92
+ sampleRate,
86
93
  ...(webVitals.onVital !== undefined ? { onVital: webVitals.onVital } : {}),
87
94
  }
88
95
  }
89
96
 
90
- function sanitizeEventProps(raw: unknown): AnalyticsEventProps | undefined | null {
97
+ // Keys outside `allowed` are dropped, never refused, so a client that sends more than the app lists still counts its event.
98
+ function sanitizeEventProps(raw: unknown, allowed: ReadonlySet<string>): AnalyticsEventProps | undefined | null {
91
99
  if (raw === undefined || raw === null)
92
100
  return undefined
93
101
  if (typeof raw !== 'object' || Array.isArray(raw))
94
102
  return null
95
103
  const out: AnalyticsEventProps = {}
96
104
  let count = 0
105
+ let seen = 0
97
106
  for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
98
- if (count >= MAX_PROP_KEYS)
99
- break
100
107
  const key = k.trim()
101
- if (key === '' || key.length > MAX_PROP_KEY_LEN)
108
+ if (key === '' || key.length > MAX_PROP_KEY_LEN || ++seen > MAX_PROP_KEYS)
102
109
  return null
103
- if (typeof v === 'string')
104
- out[key] = v.slice(0, MAX_PROP_STR_LEN)
110
+ if (!allowed.has(key))
111
+ continue
112
+ if (typeof v === 'string') {
113
+ if (v.length > MAX_PROP_STR_LEN)
114
+ return null
115
+ out[key] = v
116
+ }
105
117
  else if (typeof v === 'number' && Number.isFinite(v))
106
118
  out[key] = v
107
119
  else if (typeof v === 'boolean')
@@ -163,42 +175,79 @@ function resolveEventLocation(
163
175
  return resolveCanonicalLocation(targetUrl, site, overrideHostname, includeQueryParams)
164
176
  }
165
177
 
166
- async function readJsonBody(request: Request): Promise<{ ok: true, value: unknown } | { ok: false }> {
167
- let text: string
178
+ type BodyFailure = { ok: false, status: 400 | 413, reason: string }
179
+ type JsonBody = { ok: true, value: unknown } | BodyFailure
180
+
181
+ const TOO_LARGE: BodyFailure = { ok: false, status: 413, reason: `body over ${MAX_BODY_BYTES} bytes` }
182
+
183
+ // Reads at most MAX_BODY_BYTES: a larger declared length is refused before reading, and a stream that outgrows it is cancelled.
184
+ async function readBodyText(request: Request): Promise<string | BodyFailure> {
185
+ if (Number(request.headers.get('content-length')) > MAX_BODY_BYTES)
186
+ return TOO_LARGE
187
+ if (request.body === null)
188
+ return ''
189
+ const reader = request.body.getReader()
190
+ const chunks: Uint8Array[] = []
191
+ let size = 0
168
192
  try {
169
- text = await request.text()
193
+ for (;;) {
194
+ const { done, value } = await reader.read()
195
+ if (done)
196
+ break
197
+ size += value.byteLength
198
+ if (size > MAX_BODY_BYTES) {
199
+ await reader.cancel().catch(() => undefined)
200
+ return TOO_LARGE
201
+ }
202
+ chunks.push(value)
203
+ }
170
204
  }
171
205
  catch {
172
- return { ok: false }
206
+ return { ok: false, status: 400, reason: 'unreadable body' }
173
207
  }
208
+ return new TextDecoder().decode(Buffer.concat(chunks))
209
+ }
210
+
211
+ async function readJsonBody(request: Request): Promise<JsonBody> {
212
+ const text = await readBodyText(request)
213
+ if (typeof text !== 'string')
214
+ return text
174
215
  if (text.trim() === '')
175
- return { ok: false }
216
+ return { ok: false, status: 400, reason: 'empty body' }
176
217
  try {
177
218
  return { ok: true, value: JSON.parse(text) as unknown }
178
219
  }
179
220
  catch {
180
- return { ok: false }
221
+ return { ok: false, status: 400, reason: 'body is not JSON' }
181
222
  }
182
223
  }
183
224
 
225
+ function logDrop(dev: boolean, kind: 'event' | 'vital', reason: string): void {
226
+ if (dev)
227
+ console.warn(`@prunellejs/analytics: dropped ${kind}: ${reason}`)
228
+ }
229
+
184
230
  function parseEventPayload(
185
231
  raw: unknown,
186
232
  ctx: RequestContext,
187
233
  site: string | undefined,
188
234
  overrideHostname: string | undefined,
189
235
  includeQueryParams: readonly string[] | undefined,
190
- ): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | undefined {
236
+ allowedProps: ReadonlySet<string>,
237
+ ): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | string {
191
238
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
192
- return undefined
239
+ return 'payload is not an object'
193
240
  const obj = raw as Record<string, unknown>
194
241
  if (typeof obj.name !== 'string')
195
- return undefined
242
+ return 'name is not a string'
196
243
  const name = obj.name.trim()
197
244
  if (name === '' || name.length > MAX_EVENT_NAME_LEN)
198
- return undefined
199
- const props = sanitizeEventProps(obj.props)
245
+ return `name is empty or over ${MAX_EVENT_NAME_LEN} characters`
246
+ if ([obj.url, obj.path].some(v => typeof v === 'string' && v.length > MAX_URL_LEN))
247
+ return `url or path over ${MAX_URL_LEN} characters`
248
+ const props = sanitizeEventProps(obj.props, allowedProps)
200
249
  if (props === null)
201
- return undefined
250
+ return `props invalid or past the caps (${MAX_PROP_KEYS} keys, ${MAX_PROP_KEY_LEN} character keys, ${MAX_PROP_STR_LEN} character strings)`
202
251
  const loc = resolveEventLocation(obj.url, obj.path, ctx, site, overrideHostname, includeQueryParams)
203
252
  return {
204
253
  name,
@@ -240,73 +289,159 @@ interface RuntimeConfig {
240
289
  includeQueryParams: readonly string[] | undefined
241
290
  overrideHostname: string | undefined
242
291
  consentCategory: string | undefined
292
+ allowedProps: ReadonlySet<string>
293
+ optOutEndpoint: string | false
243
294
  eventEndpoint: string | false
244
- webVitals: { endpoint: string, onVital?: WebVitalsOptions['onVital'] } | undefined
295
+ viewEndpoint: string | false
296
+ webVitals: WebVitalsConfig | undefined
245
297
  now: () => Date
246
298
  onError: AnalyticsOptions['onError']
247
299
  visitorIdFor: (ctx: RequestContext, hostname: string, timestamp: Date) => string
248
300
  }
249
301
 
250
- function createPageviewMiddleware(
251
- cfg: RuntimeConfig,
252
- assetPrefix: string,
253
- site: string | undefined,
254
- dispatch: DispatchFn,
255
- ): Middleware {
256
- const isInternalPath = (pathname: string): boolean =>
302
+ // The paths no page view counts: the assets, the auth pages and the plugin's own endpoints.
303
+ function internalPathTest(cfg: RuntimeConfig, assetPrefix: string): (pathname: string) => boolean {
304
+ return pathname =>
257
305
  pathname === assetPrefix
258
306
  || pathname.startsWith(`${assetPrefix}/`)
259
307
  || isDefaultSensitivePath(pathname)
260
308
  || (cfg.eventEndpoint !== false && pathname === cfg.eventEndpoint)
309
+ || (cfg.optOutEndpoint !== false && pathname === cfg.optOutEndpoint)
261
310
  || (cfg.webVitals !== undefined && pathname === cfg.webVitals.endpoint)
311
+ }
262
312
 
313
+ function createPageviewMiddleware(
314
+ cfg: RuntimeConfig,
315
+ isInternalPath: (pathname: string) => boolean,
316
+ site: string | undefined,
317
+ dispatch: DispatchFn,
318
+ ): Middleware {
263
319
  return async (ctx, next) => {
264
320
  const res = await next()
265
- if (ctx.request.method !== 'GET' || isInternalPath(ctx.url.pathname) || !isHtmlSuccessResponse(res))
321
+ if (ctx.request.method !== 'GET' || isInternalPath(ctx.url.pathname) || !isHtmlSuccessResponse(res) || !isCountable(cfg, ctx))
266
322
  return res
267
- if (isPrefetchRequest(ctx.request))
268
- return res
269
- const userAgent = ctx.request.headers.get('user-agent') ?? undefined
270
- if (cfg.ignoreBots && isBotUserAgent(userAgent))
323
+ if (!isPrefetchRequest(ctx.request)) {
324
+ countPageview(cfg, site, dispatch, ctx, res.status)
271
325
  return res
272
- if (isPathExcluded(ctx, cfg.exclude))
273
- return res
274
- if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
275
- return res
276
-
277
- const timestamp = cfg.now()
278
- const loc = resolveCanonicalLocation(ctx.url, site, cfg.overrideHostname, cfg.includeQueryParams)
279
- const referrer = sanitizeReferrer(ctx.request.headers.get('referer'))
280
- const language = extractPrimaryLanguage(ctx.request)
281
- const pageview: AnalyticsPageview = {
282
- ...loc,
283
- visitorId: cfg.visitorIdFor(ctx, loc.hostname, timestamp),
284
- ...(referrer !== undefined ? { referrer } : {}),
285
- ...(userAgent !== undefined && userAgent !== '' ? { userAgent } : {}),
286
- ...(language !== undefined ? { language } : {}),
287
- ...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
288
- status: res.status,
289
- timestamp,
290
326
  }
291
- dispatch(() => cfg.provider.sendPageview(pageview), 'pageview')
327
+ return cfg.viewEndpoint === false ? res : withView(res, cfg.viewEndpoint)
328
+ }
329
+ }
330
+
331
+ // A page the visitor opens from the spa prefetch cache makes no request: the header tells spa where to post it.
332
+ function withView(res: Response, endpoint: string): Response {
333
+ try {
334
+ res.headers.set(VIEW_HEADER, endpoint)
292
335
  return res
293
336
  }
337
+ catch {
338
+ const headers = new Headers(res.headers)
339
+ headers.set(VIEW_HEADER, endpoint)
340
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
341
+ }
342
+ }
343
+
344
+ function isOptedOut(ctx: RequestContext): boolean {
345
+ return ctx.cookies.get(OPT_OUT_COOKIE) !== undefined
346
+ }
347
+
348
+ // POST stops counting this visitor, DELETE resumes it; a form post (no JS) is sent back to the page it came from.
349
+ function createOptOutHandler(site: string | undefined): (ctx: RequestContext) => Response {
350
+ return (ctx) => {
351
+ if (ctx.request.method === 'DELETE')
352
+ ctx.cookies.delete(OPT_OUT_COOKIE, { path: '/' })
353
+ else
354
+ ctx.cookies.set(OPT_OUT_COOKIE, '1', { path: '/', maxAge: OPT_OUT_MAX_AGE_S, httpOnly: true, sameSite: 'lax', category: 'essential' })
355
+ if (!(ctx.request.headers.get('accept') ?? '').includes('text/html'))
356
+ return new Response(null, { status: 204 })
357
+ const back = parseSameOriginCandidate(ctx.request.headers.get('referer'), resolveBaseOrigin(site, ctx.url.origin), ctx.url.origin)
358
+ return new Response(null, { status: 303, headers: { location: back !== undefined ? safeRedirect(`${back.pathname}${back.search}`) : '/' } })
359
+ }
360
+ }
361
+
362
+ function isCountable(cfg: RuntimeConfig, ctx: RequestContext): boolean {
363
+ if (cfg.ignoreBots && isBotUserAgent(ctx.request.headers.get('user-agent') ?? undefined))
364
+ return false
365
+ if (isPathExcluded(ctx, cfg.exclude) || isOptedOut(ctx))
366
+ return false
367
+ return cfg.consentCategory === undefined || ctx.consent.has(cfg.consentCategory)
368
+ }
369
+
370
+ // `ctx.url` is the page counted: the request's own URL for the middleware, the path in the body for the view beacon.
371
+ function countPageview(cfg: RuntimeConfig, site: string | undefined, dispatch: DispatchFn, ctx: RequestContext, status: number): void {
372
+ const userAgent = ctx.request.headers.get('user-agent') ?? undefined
373
+ const timestamp = cfg.now()
374
+ const loc = resolveCanonicalLocation(ctx.url, site, cfg.overrideHostname, cfg.includeQueryParams)
375
+ const referrer = sanitizeReferrer(ctx.request.headers.get('referer'))
376
+ const language = extractPrimaryLanguage(ctx.request)
377
+ const pageview: AnalyticsPageview = {
378
+ ...loc,
379
+ visitorId: cfg.visitorIdFor(ctx, loc.hostname, timestamp),
380
+ ...(referrer !== undefined ? { referrer } : {}),
381
+ ...(userAgent !== undefined && userAgent !== '' ? { userAgent: coarseUserAgent(userAgent) } : {}),
382
+ ...(language !== undefined ? { language } : {}),
383
+ ...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
384
+ status,
385
+ timestamp,
386
+ }
387
+ dispatch(() => cfg.provider.sendPageview(pageview), 'pageview')
388
+ }
389
+
390
+ // The body is the page path and query, as `navigator.sendBeacon` sends it: anything that does not resolve to a path of this origin is refused.
391
+ function parseViewPath(raw: string, origin: string): URL | undefined {
392
+ if (raw.length > MAX_URL_LEN || !raw.startsWith('/') || raw.startsWith('//') || raw.startsWith('/\\') || !URL.canParse(raw, origin))
393
+ return undefined
394
+ const url = new URL(raw, origin)
395
+ return url.origin === origin ? url : undefined
396
+ }
397
+
398
+ function createViewHandler(
399
+ cfg: RuntimeConfig,
400
+ isInternalPath: (pathname: string) => boolean,
401
+ site: string | undefined,
402
+ dispatch: DispatchFn,
403
+ ): (ctx: RequestContext) => Promise<Response> {
404
+ return async (ctx) => {
405
+ const body = await readBodyText(ctx.request)
406
+ if (typeof body !== 'string')
407
+ return ctx.deny(body.status, body.status === 413 ? 'Request body too large' : 'Invalid view body')
408
+ const page = parseViewPath(body.trim(), ctx.url.origin)
409
+ if (page === undefined)
410
+ return ctx.deny(400, 'Invalid analytics view: the body is the page path')
411
+ const view = Object.create(ctx, { url: { value: page } }) as RequestContext
412
+ if (!isInternalPath(page.pathname) && isCountable(cfg, view))
413
+ countPageview(cfg, site, dispatch, view, 200)
414
+ return new Response(null, { status: 204 })
415
+ }
294
416
  }
295
417
 
296
418
  function createEventHandler(
297
419
  cfg: RuntimeConfig,
298
420
  site: string | undefined,
421
+ dev: boolean,
299
422
  dispatch: DispatchFn,
300
423
  ): (ctx: RequestContext) => Promise<Response> {
301
424
  return async (ctx) => {
425
+ if (cfg.ignoreBots && isBotUserAgent(ctx.request.headers.get('user-agent') ?? undefined)) {
426
+ logDrop(dev, 'event', 'bot user agent')
427
+ return new Response(null, { status: 204 })
428
+ }
302
429
  const parsedBody = await readJsonBody(ctx.request)
303
- if (!parsedBody.ok)
304
- return ctx.deny(400, 'Invalid JSON body')
305
- const parsed = parseEventPayload(parsedBody.value, ctx, site, cfg.overrideHostname, cfg.includeQueryParams)
306
- if (parsed === undefined)
430
+ if (!parsedBody.ok) {
431
+ logDrop(dev, 'event', parsedBody.reason)
432
+ return ctx.deny(parsedBody.status, parsedBody.status === 413 ? 'Request body too large' : 'Invalid JSON body')
433
+ }
434
+ if (isOptedOut(ctx))
435
+ return new Response(null, { status: 204 })
436
+ const parsed = parseEventPayload(parsedBody.value, ctx, site, cfg.overrideHostname, cfg.includeQueryParams, cfg.allowedProps)
437
+ if (typeof parsed === 'string') {
438
+ logDrop(dev, 'event', parsed)
307
439
  return ctx.deny(400, 'Invalid analytics event payload')
308
- if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
440
+ }
441
+ if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory)) {
442
+ logDrop(dev, 'event', `no consent to "${cfg.consentCategory}"`)
309
443
  return new Response(null, { status: 204 })
444
+ }
310
445
 
311
446
  const timestamp = cfg.now()
312
447
  const userAgent = ctx.request.headers.get('user-agent') ?? undefined
@@ -316,7 +451,7 @@ function createEventHandler(
316
451
  ...parsed,
317
452
  visitorId: cfg.visitorIdFor(ctx, parsed.hostname, timestamp),
318
453
  ...(referrer !== undefined ? { referrer } : {}),
319
- ...(userAgent !== undefined && userAgent !== '' ? { userAgent } : {}),
454
+ ...(userAgent !== undefined && userAgent !== '' ? { userAgent: coarseUserAgent(userAgent) } : {}),
320
455
  ...(language !== undefined ? { language } : {}),
321
456
  ...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
322
457
  timestamp,
@@ -333,38 +468,65 @@ function createEventHandler(
333
468
 
334
469
  function createVitalsHandler(
335
470
  cfg: RuntimeConfig,
336
- vitals: { endpoint: string, onVital?: WebVitalsOptions['onVital'] },
471
+ vitals: WebVitalsConfig,
337
472
  dev: boolean,
338
473
  dispatch: DispatchFn,
339
474
  ): (ctx: RequestContext) => Promise<Response> {
340
475
  return async (ctx) => {
476
+ if (cfg.ignoreBots && isBotUserAgent(ctx.request.headers.get('user-agent') ?? undefined)) {
477
+ logDrop(dev, 'vital', 'bot user agent')
478
+ return new Response(null, { status: 204 })
479
+ }
341
480
  const parsedBody = await readJsonBody(ctx.request)
342
- if (!parsedBody.ok)
343
- return ctx.deny(400, 'Invalid JSON body')
344
- const vital = parseWebVitalPayload(parsedBody.value, ctx.request)
345
- if (vital === undefined)
481
+ if (!parsedBody.ok) {
482
+ logDrop(dev, 'vital', parsedBody.reason)
483
+ return ctx.deny(parsedBody.status, parsedBody.status === 413 ? 'Request body too large' : 'Invalid JSON body')
484
+ }
485
+ if (isOptedOut(ctx))
486
+ return new Response(null, { status: 204 })
487
+ const received = parseWebVitalPayloads(parsedBody.value, ctx.request)
488
+ if (received === undefined) {
489
+ logDrop(dev, 'vital', 'invalid Web Vital payload')
346
490
  return ctx.deny(400, 'Invalid Web Vital payload')
347
- if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
491
+ }
492
+ if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory)) {
493
+ logDrop(dev, 'vital', `no consent to "${cfg.consentCategory}"`)
348
494
  return new Response(null, { status: 204 })
495
+ }
349
496
 
350
- if (vitals.onVital !== undefined) {
351
- try {
352
- await vitals.onVital(vital, ctx)
497
+ const sendVital = cfg.provider.sendVital
498
+ for (const vital of received) {
499
+ if (vitals.onVital !== undefined) {
500
+ try {
501
+ await vitals.onVital(vital, ctx)
502
+ }
503
+ catch (err) {
504
+ reportError(cfg.onError, err, 'vital', dev)
505
+ }
353
506
  }
354
- catch (err) {
355
- reportError(cfg.onError, err, 'vital', dev)
507
+ if (sendVital !== undefined) {
508
+ const pending = dispatch(() => sendVital(vital, ctx), 'vital')
509
+ if (pending !== undefined)
510
+ await pending
356
511
  }
357
512
  }
358
- const sendVital = cfg.provider.sendVital
359
- if (sendVital !== undefined) {
360
- const pending = dispatch(() => sendVital(vital, ctx), 'vital')
361
- if (pending !== undefined)
362
- await pending
363
- }
364
513
  return new Response(null, { status: 202 })
365
514
  }
366
515
  }
367
516
 
517
+ // Under consent, the page loads the collector from here: a visitor who granted the category gets it and anyone else an empty script, so the HTML stays the same for every visitor and a prerendered or cached page stays safe.
518
+ function createVitalsScriptHandler(script: string, category: string): (ctx: RequestContext) => Response {
519
+ const version = hashScript(script)
520
+ return (ctx) => {
521
+ const granted = ctx.consent.has(category)
522
+ const etag = `"${granted ? version : 'off'}"`
523
+ const headers = { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'private, no-cache', 'etag': etag }
524
+ if (ctx.request.headers.get('if-none-match') === etag)
525
+ return new Response(null, { status: 304, headers })
526
+ return new Response(granted ? script : '', { headers })
527
+ }
528
+ }
529
+
368
530
  /**
369
531
  * CNIL-compliant first-party analytics plugin for Prunelle.
370
532
  *
@@ -385,6 +547,9 @@ export function analytics(options: AnalyticsOptions): PrunellePlugin {
385
547
  const eventEndpoint = options.eventEndpoint === false
386
548
  ? false
387
549
  : normalizeEndpoint(options.eventEndpoint ?? DEFAULT_EVENT_ENDPOINT)
550
+ const viewEndpoint = options.viewEndpoint === false
551
+ ? false
552
+ : normalizeEndpoint(options.viewEndpoint ?? DEFAULT_VIEW_ENDPOINT)
388
553
  const rateLimit = options.rateLimit === false ? undefined : options.rateLimit ?? DEFAULT_RATE_LIMIT
389
554
 
390
555
  const cfg: RuntimeConfig = {
@@ -394,8 +559,11 @@ export function analytics(options: AnalyticsOptions): PrunellePlugin {
394
559
  exclude: options.exclude,
395
560
  includeQueryParams: options.includeQueryParams,
396
561
  overrideHostname: options.hostname,
397
- consentCategory: resolveConsentCategory(options),
562
+ consentCategory: resolveConsentCategory(options, undefined),
563
+ allowedProps: new Set(options.eventProps),
564
+ optOutEndpoint: options.optOutEndpoint === false ? false : normalizeEndpoint(options.optOutEndpoint ?? DEFAULT_OPT_OUT_ENDPOINT),
398
565
  eventEndpoint,
566
+ viewEndpoint,
399
567
  webVitals,
400
568
  now: options.now ?? (() => new Date()),
401
569
  onError: options.onError,
@@ -412,10 +580,28 @@ export function analytics(options: AnalyticsOptions): PrunellePlugin {
412
580
  return definePlugin({
413
581
  name: '@prunellejs/analytics',
414
582
 
583
+ requires(ctx) {
584
+ cfg.consentCategory = resolveConsentCategory(options, ctx.site)
585
+ const category = cfg.consentCategory
586
+ if (category === undefined || ctx.consentCategories.includes(category))
587
+ return []
588
+ return [`counting waits for consent to "${category}", which consent.categories in prunelle.config.ts does not declare, so no visitor can grant it and nothing is counted: declare it, such as consent: { categories: { ${category}: 'Audience measurement' } }`]
589
+ },
590
+
591
+ check(ctx) {
592
+ if (cfg.sendIp && cfg.consentCategory === undefined)
593
+ ctx.warn("@prunellejs/analytics: sendIp: true forwards each visitor's IP address to the provider without their consent: drop sendIp, or remove requiresConsent: false and consentCategory: false so counting waits for consent.")
594
+ },
595
+
415
596
  build(ctx) {
597
+ cfg.consentCategory = resolveConsentCategory(options, ctx.site)
416
598
  if (webVitals === undefined)
417
599
  return
418
- const script = buildWebVitalsScript(webVitals.endpoint)
600
+ if (cfg.consentCategory !== undefined) {
601
+ ctx.addHead(`<script defer src="${escAttr(`${webVitals.endpoint}.js`)}"></script>`)
602
+ return
603
+ }
604
+ const script = buildWebVitalsScript(webVitals.endpoint, webVitals.sampleRate)
419
605
  const assetUrl = ctx.emitAsset(`analytics-vitals-${hashScript(script)}.js`, script)
420
606
  ctx.addHead(`<script defer src="${escAttr(assetUrl)}"></script>`)
421
607
  },
@@ -425,7 +611,9 @@ export function analytics(options: AnalyticsOptions): PrunellePlugin {
425
611
  if (api.config?.prerender === true)
426
612
  return
427
613
 
614
+ cfg.consentCategory = resolveConsentCategory(options, api.site)
428
615
  const assetPrefix = api.assetPrefix.replace(/\/+$/, '')
616
+ const isInternalPath = internalPathTest(cfg, assetPrefix)
429
617
  const pending = new Set<Promise<void>>()
430
618
  const dispatch: DispatchFn = (fn, kind) => {
431
619
  if (pending.size >= maxPending)
@@ -450,13 +638,22 @@ export function analytics(options: AnalyticsOptions): PrunellePlugin {
450
638
  }
451
639
 
452
640
  // `scope: 'all'` counts both dynamic and prerendered pages without shipping any client JS.
453
- api.use(createPageviewMiddleware(cfg, assetPrefix, api.site, dispatch), { scope: 'all' })
641
+ api.use(createPageviewMiddleware(cfg, isInternalPath, api.site, dispatch), { scope: 'all' })
454
642
 
455
643
  const routeOpts = { csrf: true, ...(rateLimit !== undefined ? { rateLimit } : {}) }
456
644
  if (eventEndpoint !== false)
457
- api.route('POST', eventEndpoint, createEventHandler(cfg, api.site, dispatch), routeOpts)
645
+ api.route('POST', eventEndpoint, createEventHandler(cfg, api.site, api.dev, dispatch), routeOpts)
646
+ if (cfg.optOutEndpoint !== false) {
647
+ const optOutHandler = createOptOutHandler(api.site)
648
+ api.route('POST', cfg.optOutEndpoint, optOutHandler, { csrf: true })
649
+ api.route('DELETE', cfg.optOutEndpoint, optOutHandler, { csrf: true })
650
+ }
651
+ if (viewEndpoint !== false)
652
+ api.route('POST', viewEndpoint, createViewHandler(cfg, isInternalPath, api.site, dispatch), routeOpts)
458
653
  if (webVitals !== undefined)
459
654
  api.route('POST', webVitals.endpoint, createVitalsHandler(cfg, webVitals, api.dev, dispatch), routeOpts)
655
+ if (webVitals !== undefined && cfg.consentCategory !== undefined)
656
+ api.route('GET', `${webVitals.endpoint}.js`, createVitalsScriptHandler(buildWebVitalsScript(webVitals.endpoint, webVitals.sampleRate), cfg.consentCategory))
460
657
 
461
658
  api.onShutdown(async () => {
462
659
  if (pending.size > 0)
package/src/providers.ts CHANGED
@@ -26,6 +26,36 @@ function assertNonEmpty(value: string, label: string): string {
26
26
  return trimmed
27
27
  }
28
28
 
29
+ const MAX_ERROR_BODY_CHARS = 300
30
+
31
+ function resolveTimeoutMs(value: number | undefined): number {
32
+ const timeoutMs = value ?? DEFAULT_TIMEOUT_MS
33
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
34
+ throw new Error(`prunelle: @prunellejs/analytics timeoutMs must be a positive finite number, got ${String(timeoutMs)}`)
35
+ return timeoutMs
36
+ }
37
+
38
+ // Reads only the start of a response body, so a provider answering with a huge page costs neither memory nor a long error.
39
+ async function readBodyStart(res: Response): Promise<string> {
40
+ if (res.body === null)
41
+ return ''
42
+ const reader = res.body.getReader()
43
+ const decoder = new TextDecoder()
44
+ let text = ''
45
+ try {
46
+ while (text.length < MAX_ERROR_BODY_CHARS) {
47
+ const { done, value } = await reader.read()
48
+ if (done)
49
+ break
50
+ text += decoder.decode(value, { stream: true })
51
+ }
52
+ }
53
+ finally {
54
+ await reader.cancel().catch(() => undefined)
55
+ }
56
+ return text.slice(0, MAX_ERROR_BODY_CHARS)
57
+ }
58
+
29
59
  async function postUpstream(
30
60
  fetchImpl: FetchLike,
31
61
  url: string,
@@ -38,14 +68,18 @@ async function postUpstream(
38
68
  method: 'POST',
39
69
  headers,
40
70
  body,
41
- ...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
71
+ signal: AbortSignal.timeout(timeoutMs),
42
72
  })
43
73
  if (!res.ok) {
44
- const text = await res.text()
74
+ const text = await readBodyStart(res)
45
75
  throw new Error(`prunelle: @prunellejs/analytics (${providerName}): HTTP ${res.status}: ${text}`)
46
76
  }
47
77
  }
48
78
 
79
+ function hostnameOf(url: string): string | undefined {
80
+ return URL.canParse(url) ? new URL(url).hostname.toLowerCase() : undefined
81
+ }
82
+
49
83
  function isThirdPartyPlausibleHost(host: string): boolean {
50
84
  if (!URL.canParse(host))
51
85
  return false
@@ -62,7 +96,7 @@ export function plausible(options: PlausibleOptions): AnalyticsProvider {
62
96
  const domain = assertNonEmpty(options.domain, 'plausible() domain')
63
97
  const host = stripTrailingSlash(options.host ?? 'https://plausible.io')
64
98
  const endpoint = `${host}/api/event`
65
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
99
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs)
66
100
  const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
67
101
  const defaultRequiresConsent = isThirdPartyPlausibleHost(host)
68
102
 
@@ -105,7 +139,7 @@ export function umami(options: UmamiOptions): AnalyticsProvider {
105
139
  const websiteId = assertNonEmpty(options.websiteId, 'umami() websiteId')
106
140
  const host = stripTrailingSlash(assertNonEmpty(options.host, 'umami() host'))
107
141
  const endpoint = `${host}/api/send`
108
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
142
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs)
109
143
  const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
110
144
 
111
145
  const send = async (
@@ -136,7 +170,8 @@ export function umami(options: UmamiOptions): AnalyticsProvider {
136
170
 
137
171
  return {
138
172
  name: 'umami',
139
- requiresConsent: options.requiresConsent ?? false,
173
+ host: hostnameOf(host),
174
+ requiresConsent: options.requiresConsent,
140
175
  sendPageview: pv => send(pv),
141
176
  sendEvent: ev => send(ev, ev.name, ev.props),
142
177
  }
@@ -181,7 +216,7 @@ function buildMatomoParams(
181
216
  export function matomo(options: MatomoOptions): AnalyticsProvider {
182
217
  const endpoint = matomoEndpoint(options.url)
183
218
  const siteId = assertNonEmpty(String(options.siteId), 'matomo() siteId')
184
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
219
+ const timeoutMs = resolveTimeoutMs(options.timeoutMs)
185
220
  const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
186
221
 
187
222
  const post = async (item: AnalyticsPageview | AnalyticsEvent, params: URLSearchParams): Promise<void> => {
@@ -196,7 +231,8 @@ export function matomo(options: MatomoOptions): AnalyticsProvider {
196
231
 
197
232
  return {
198
233
  name: 'matomo',
199
- requiresConsent: options.requiresConsent ?? false,
234
+ host: hostnameOf(endpoint),
235
+ requiresConsent: options.requiresConsent,
200
236
  sendPageview(pv) {
201
237
  const params = buildMatomoParams(siteId, pv, options.tokenAuth)
202
238
  params.set('action_name', pv.path)
@@ -219,7 +255,7 @@ export function matomo(options: MatomoOptions): AnalyticsProvider {
219
255
  export function custom(options: CustomAnalyticsOptions): AnalyticsProvider {
220
256
  return {
221
257
  name: options.name ?? 'custom',
222
- requiresConsent: options.requiresConsent ?? false,
258
+ requiresConsent: options.requiresConsent,
223
259
  sendPageview: options.sendPageview,
224
260
  ...(options.sendEvent !== undefined ? { sendEvent: options.sendEvent } : {}),
225
261
  ...(options.sendVital !== undefined ? { sendVital: options.sendVital } : {}),
package/src/types.ts CHANGED
@@ -66,7 +66,9 @@ export interface AnalyticsEvent {
66
66
 
67
67
  export interface AnalyticsProvider {
68
68
  readonly name: string
69
- /** Set `true` when the provider requires prior user consent (e.g. non-exempt third-party SaaS). */
69
+ /** Hostname that receives the measurements, when the provider has one: `analytics()` waives consent for it only when it is the app's own. */
70
+ readonly host?: string | undefined
71
+ /** `true` requires prior consent, `false` waives it; left out, `analytics()` requires it unless `host` is the app's own (the site's host, a subdomain of it, or loopback). */
70
72
  readonly requiresConsent?: boolean | undefined
71
73
  sendPageview(pageview: AnalyticsPageview): void | Promise<void>
72
74
  sendEvent?(event: AnalyticsEvent): void | Promise<void>
@@ -95,7 +97,7 @@ export interface UmamiOptions {
95
97
  host: string
96
98
  /** HTTP request timeout in milliseconds (default: `5000`). */
97
99
  timeoutMs?: number | undefined
98
- /** Whether consent is required before sending to this Umami instance (default: `false`). */
100
+ /** Whether consent is required before sending to this Umami instance (default: `true`, unless `host` is the app's own: the site's host, a subdomain of it, or loopback). */
99
101
  requiresConsent?: boolean | undefined
100
102
  /** Custom `fetch` implementation (useful for tests or proxying). */
101
103
  fetch?: FetchLike | undefined
@@ -110,7 +112,7 @@ export interface MatomoOptions {
110
112
  tokenAuth?: string | undefined
111
113
  /** HTTP request timeout in milliseconds (default: `5000`). */
112
114
  timeoutMs?: number | undefined
113
- /** Whether consent is required before sending to this Matomo instance (default: `false`). */
115
+ /** Whether consent is required before sending to this Matomo instance (default: `true`, unless `url` is the app's own: the site's host, a subdomain of it, or loopback). */
114
116
  requiresConsent?: boolean | undefined
115
117
  /** Custom `fetch` implementation (useful for tests or proxying). */
116
118
  fetch?: FetchLike | undefined
@@ -119,7 +121,7 @@ export interface MatomoOptions {
119
121
  export interface CustomAnalyticsOptions {
120
122
  /** Provider label for diagnostics (default: `'custom'`). */
121
123
  name?: string | undefined
122
- /** Whether consent is required before sending to this provider (default: `false`). */
124
+ /** Whether consent is required before sending to this provider (default: `true`: a callback can send anywhere, so `false` is the app's word that it measures for the publisher alone). */
123
125
  requiresConsent?: boolean | undefined
124
126
  sendPageview: (pageview: AnalyticsPageview) => void | Promise<void>
125
127
  sendEvent?: ((event: AnalyticsEvent) => void | Promise<void>) | undefined
@@ -129,7 +131,9 @@ export interface CustomAnalyticsOptions {
129
131
  export interface WebVitalsOptions {
130
132
  /** First-party POST endpoint for Web Vitals beacons (default: `'/_pru/analytics/vitals'`). */
131
133
  endpoint?: string | undefined
132
- /** Callback invoked on every validated Web Vital beacon. */
134
+ /** Share of page views measured, above 0 and at most 1 (default: `1`); `0.1` sends a beacon for one view in ten. */
135
+ sampleRate?: number | undefined
136
+ /** Callback invoked on every validated Web Vital of a beacon. */
133
137
  onVital?: ((vital: WebVitalMetric, ctx: RequestContext) => void | Promise<void>) | undefined
134
138
  }
135
139
 
@@ -146,12 +150,18 @@ export interface AnalyticsOptions {
146
150
  consentCategory?: string | false | undefined
147
151
  /** First-party POST endpoint for custom events (default: `'/_pru/analytics/event'`; set `false` to disable). */
148
152
  eventEndpoint?: string | false | undefined
153
+ /** First-party POST endpoint that counts a page a spa visitor opens from its prefetch cache (default: `'/_pru/analytics/view'`; set `false` to count no prefetched page). A prefetch is never counted: its response names this path in `x-pru-view`, and `@prunellejs/spa` posts the page to it when the visitor opens the page. */
154
+ viewEndpoint?: string | false | undefined
149
155
  /** Enable first-party Web Vitals collection (default: `false`, emitting 0 B of JS). */
150
156
  webVitals?: boolean | WebVitalsOptions | undefined
151
157
  /** Skip common crawler/bot User-Agents for page views (default: `true`). */
152
158
  ignoreBots?: boolean | undefined
153
159
  /** Paths, regexes, or predicate excluded from server-side page view counting (in addition to `/_pru/*`, `/auth/*`, and analytics endpoints). */
154
160
  exclude?: readonly (string | RegExp)[] | ((ctx: RequestContext) => boolean) | undefined
161
+ /** Names of the event props a custom event may carry (default: none, so props are dropped): a free-text prop is how personal data reaches a provider. Values are strings up to 100 characters, finite numbers or booleans. */
162
+ eventProps?: readonly string[] | undefined
163
+ /** First-party endpoint a visitor posts to so their views stop being counted, and deletes to resume (default: `'/_pru/analytics/opt-out'`; set `false` to remove it). It sets an essential cookie. */
164
+ optOutEndpoint?: string | false | undefined
155
165
  /** Allowlist of query parameter names to keep in reported `url` values (default: none — all query strings are stripped to prevent leaking tokens or PII). */
156
166
  includeQueryParams?: readonly string[] | undefined
157
167
  /** Override hostname used for visitor hashing and provider payloads. */
package/src/visitor.ts CHANGED
@@ -40,6 +40,14 @@ export function computeVisitorId(input: VisitorIdInput): string {
40
40
  }
41
41
 
42
42
  /** Returns `true` when `userAgent` matches a known crawler, bot, monitor, or CLI HTTP client. */
43
+ const VERSION_TAIL_RE = /(\d+)(?:\.\d+)+/g
44
+ const MAX_USER_AGENT_CHARS = 160
45
+
46
+ /** A User-Agent cut to what a count needs: versions kept to their major number, at most 160 characters. */
47
+ export function coarseUserAgent(userAgent: string): string {
48
+ return userAgent.replace(VERSION_TAIL_RE, '$1').slice(0, MAX_USER_AGENT_CHARS)
49
+ }
50
+
43
51
  export function isBotUserAgent(userAgent: string | null | undefined): boolean {
44
52
  if (userAgent === null || userAgent === undefined || userAgent === '')
45
53
  return false
package/src/vitals.ts CHANGED
@@ -25,19 +25,20 @@ export function rateWebVital(name: WebVitalName, value: number): WebVitalRating
25
25
  return 'poor'
26
26
  }
27
27
 
28
+ /** At most one entry per metric in a beacon. */
29
+ const MAX_VITALS_PER_BEACON = VALID_VITAL_NAMES.size
30
+
28
31
  /**
29
- * Generates a standalone, zero-dependency browser script (<1.5 KB) that observes
30
- * LCP, CLS, INP, FCP, and TTFB via `PerformanceObserver` and reports them to `endpoint`
31
- * using `navigator.sendBeacon` with a `fetch(..., { keepalive: true })` fallback.
32
+ * A standalone, zero-dependency browser script (<1.5 KB) that observes LCP, CLS, INP, FCP and TTFB via `PerformanceObserver`
33
+ * and sends them to `endpoint` in one beacon when the page hides, by `navigator.sendBeacon` or else `fetch(..., { keepalive: true })`.
34
+ * A `sampleRate` under 1 measures only that share of page views.
32
35
  */
33
- export function buildWebVitalsScript(endpoint: string = DEFAULT_VITALS_ENDPOINT): string {
36
+ export function buildWebVitalsScript(endpoint: string = DEFAULT_VITALS_ENDPOINT, sampleRate = 1): string {
34
37
  const ep = JSON.stringify(endpoint)
35
- return `(()=>{if(typeof PerformanceObserver>"t")return;`
36
- + `let e=${ep},j="application/json",s={},t={LCP:[2500,4e3],CLS:[.1,.25],INP:[200,500],FCP:[1800,3e3],TTFB:[800,1800]},l=-1,c=0,w=0,a=0,b=0,m={},`
38
+ return `(()=>{if(typeof PerformanceObserver>"t"${sampleRate < 1 ? `||Math.random()>=${sampleRate}` : ''})return;`
39
+ + `let e=${ep},j="application/json",s={},q=[],t={LCP:[2500,4e3],CLS:[.1,.25],INP:[200,500],FCP:[1800,3e3],TTFB:[800,1800]},l=-1,c=0,w=0,a=0,b=0,m={},`
37
40
  + `p=(k,v)=>{if(s[k]||!(v>=0))return;s[k]=1;`
38
- + `let r=t[k],d=JSON.stringify({name:k,value:+v.toFixed(3),rating:v<=r[0]?"good":v<=r[1]?"needs-improvement":"poor",path:location.pathname});`
39
- + `try{if(navigator.sendBeacon?.(e,new Blob([d],{type:j})))return}catch(_){}`
40
- + `fetch(e,{method:"POST",headers:{"content-type":j},body:d,keepalive:!0,credentials:"same-origin"}).catch(()=>{})},`
41
+ + `let r=t[k];q.push({name:k,value:+v.toFixed(3),rating:v<=r[0]?"good":v<=r[1]?"needs-improvement":"poor",path:location.pathname})},`
41
42
  + `o=(y,f,x)=>{try{new PerformanceObserver(g=>f(g.getEntries())).observe({type:y,buffered:!0,...x})}catch(_){}},`
42
43
  + `h=addEventListener;`
43
44
  + `try{let n=performance.getEntriesByType("navigation")[0]?.responseStart;n>=0&&p("TTFB",n)}catch(_){}`
@@ -45,7 +46,9 @@ export function buildWebVitalsScript(endpoint: string = DEFAULT_VITALS_ENDPOINT)
45
46
  + `o("largest-contentful-paint",g=>{let i=g.at(-1);i&&(l=i.startTime)});`
46
47
  + `o("layout-shift",g=>{for(let i of g){if(i.hadRecentInput)continue;let u=i.startTime;w=w&&u-b<1e3&&u-a<=5e3?w+i.value:(a=u,i.value);b=u;if(w>c)c=w}});`
47
48
  + `o("event",g=>{for(let i of g){let k=i.interactionId;if(k>0&&!(m[k]>=i.duration))m[k]=i.duration}},{durationThreshold:40});`
48
- + `let f=()=>{p("LCP",l);p("CLS",c);let v=Object.values(m).sort((x,y)=>y-x);p("INP",v.length?v[v.length/50|0]:-1)};`
49
+ + `let f=()=>{p("LCP",l);p("CLS",c);let v=Object.values(m).sort((x,y)=>y-x);p("INP",v.length?v[v.length/50|0]:-1);if(!q.length)return;`
50
+ + `let d=JSON.stringify(q);q=[];try{if(navigator.sendBeacon?.(e,new Blob([d],{type:j})))return}catch(_){}`
51
+ + `fetch(e,{method:"POST",headers:{"content-type":j},body:d,keepalive:!0,credentials:"same-origin"}).catch(()=>{})};`
49
52
  + `h("visibilitychange",()=>document.visibilityState=="hidden"&&f());h("pagehide",f)})();\n`
50
53
  }
51
54
 
@@ -56,6 +59,18 @@ function fallbackPathFromReferer(request: Request): string {
56
59
  return '/'
57
60
  }
58
61
 
62
+ /** The valid metrics of a beacon: one metric object, or an array of at most one per metric; `undefined` when none is valid or the array is longer. */
63
+ export function parseWebVitalPayloads(raw: unknown, request: Request): WebVitalMetric[] | undefined {
64
+ if (!Array.isArray(raw)) {
65
+ const one = parseWebVitalPayload(raw, request)
66
+ return one === undefined ? undefined : [one]
67
+ }
68
+ if (raw.length > MAX_VITALS_PER_BEACON)
69
+ return undefined
70
+ const vitals = raw.map(entry => parseWebVitalPayload(entry, request)).filter(v => v !== undefined)
71
+ return vitals.length === 0 ? undefined : vitals
72
+ }
73
+
59
74
  /** Parses and validates a Web Vital JSON beacon payload. */
60
75
  export function parseWebVitalPayload(raw: unknown, request: Request): WebVitalMetric | undefined {
61
76
  if (raw === null || typeof raw !== 'object' || Array.isArray(raw))