@prunellejs/analytics 0.0.0-stage → 0.7.2

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/src/index.ts ADDED
@@ -0,0 +1,664 @@
1
+ // @prunellejs/analytics — CNIL-compliant server-side audience measurement, first-party custom events, and optional Web Vitals.
2
+ // Built strictly on the public PrunellePlugin API. NEVER sets `clientEntry` (0 B of JS for page views).
3
+
4
+ import type { PrunellePlugin } from 'prunelle/config'
5
+ import type { Middleware, RateLimit, RequestContext } from 'prunelle/server'
6
+ import type {
7
+ AnalyticsEvent,
8
+ AnalyticsEventProps,
9
+ AnalyticsOptions,
10
+ AnalyticsPageview,
11
+ WebVitalsOptions,
12
+ } from './types'
13
+ import { definePlugin } from 'prunelle/config'
14
+ import { resolveConsentCategory } from './consent'
15
+ import { escAttr, safeRedirect } from 'prunelle/server'
16
+ import {
17
+ coarseUserAgent,
18
+ computeVisitorId,
19
+ extractPrimaryLanguage,
20
+ formatUtcDate,
21
+ generateProcessSecret,
22
+ isBotUserAgent,
23
+ isDefaultSensitivePath,
24
+ isHtmlSuccessResponse,
25
+ isPathExcluded,
26
+ isPrefetchRequest,
27
+ resolveCanonicalLocation,
28
+ sanitizeReferrer,
29
+ } from './visitor'
30
+ import { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, parseWebVitalPayloads } from './vitals'
31
+
32
+ export { custom, matomo, plausible, umami } from './providers'
33
+ export { coarseUserAgent, computeVisitorId, formatUtcDate, isBotUserAgent, isPrefetchRequest } from './visitor'
34
+ export { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, rateWebVital } from './vitals'
35
+ export type {
36
+ AnalyticsEvent,
37
+ AnalyticsEventProps,
38
+ AnalyticsOptions,
39
+ AnalyticsPageview,
40
+ AnalyticsProvider,
41
+ CustomAnalyticsOptions,
42
+ FetchLike,
43
+ MatomoOptions,
44
+ PlausibleOptions,
45
+ UmamiOptions,
46
+ WebVitalMetric,
47
+ WebVitalName,
48
+ WebVitalRating,
49
+ WebVitalsOptions,
50
+ } from './types'
51
+ export type { VisitorIdInput } from './visitor'
52
+
53
+ export const DEFAULT_EVENT_ENDPOINT = '/_pru/analytics/event'
54
+ export const DEFAULT_VIEW_ENDPOINT = '/_pru/analytics/view'
55
+ export const DEFAULT_MAX_PENDING = 64
56
+ export const DEFAULT_RATE_LIMIT: RateLimit<RequestContext> = { max: 60, windowMs: 60_000 }
57
+
58
+ const VIEW_HEADER = 'x-pru-view'
59
+ const MAX_EVENT_NAME_LEN = 100
60
+ const MAX_PROP_KEYS = 30
61
+ const MAX_URL_LEN = 2000
62
+ const MAX_BODY_BYTES = 16 * 1024
63
+ const MAX_PROP_KEY_LEN = 64
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
69
+
70
+ function normalizeEndpoint(raw: string): string {
71
+ const trimmed = raw.trim()
72
+ const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
73
+ return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1) : withSlash
74
+ }
75
+
76
+ interface WebVitalsConfig {
77
+ endpoint: string
78
+ sampleRate: number
79
+ onVital?: WebVitalsOptions['onVital']
80
+ }
81
+
82
+ function normalizeWebVitals(webVitals: AnalyticsOptions['webVitals']): WebVitalsConfig | undefined {
83
+ if (webVitals === undefined || webVitals === false)
84
+ return undefined
85
+ if (webVitals === true)
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)}`)
90
+ return {
91
+ endpoint: normalizeEndpoint(webVitals.endpoint ?? DEFAULT_VITALS_ENDPOINT),
92
+ sampleRate,
93
+ ...(webVitals.onVital !== undefined ? { onVital: webVitals.onVital } : {}),
94
+ }
95
+ }
96
+
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 {
99
+ if (raw === undefined || raw === null)
100
+ return undefined
101
+ if (typeof raw !== 'object' || Array.isArray(raw))
102
+ return null
103
+ const out: AnalyticsEventProps = {}
104
+ let count = 0
105
+ let seen = 0
106
+ for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
107
+ const key = k.trim()
108
+ if (key === '' || key.length > MAX_PROP_KEY_LEN || ++seen > MAX_PROP_KEYS)
109
+ return null
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
+ }
117
+ else if (typeof v === 'number' && Number.isFinite(v))
118
+ out[key] = v
119
+ else if (typeof v === 'boolean')
120
+ out[key] = v
121
+ else
122
+ return null
123
+ count++
124
+ }
125
+ return count > 0 ? out : undefined
126
+ }
127
+
128
+ function parseSameOriginCandidate(
129
+ raw: unknown,
130
+ baseOrigin: string,
131
+ requestOrigin: string,
132
+ ): URL | undefined {
133
+ if (typeof raw !== 'string')
134
+ return undefined
135
+ const trimmed = raw.trim()
136
+ if (trimmed === '')
137
+ return undefined
138
+ let parsed: URL
139
+ try {
140
+ parsed = new URL(trimmed, baseOrigin)
141
+ }
142
+ catch {
143
+ return undefined
144
+ }
145
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
146
+ return undefined
147
+ if (parsed.origin !== baseOrigin && parsed.origin !== requestOrigin)
148
+ return undefined
149
+ return parsed
150
+ }
151
+
152
+ function resolveBaseOrigin(site: string | undefined, requestOrigin: string): string {
153
+ if (site !== undefined && site !== '' && URL.canParse(site)) {
154
+ const parsed = new URL(site)
155
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
156
+ return parsed.origin
157
+ }
158
+ return requestOrigin
159
+ }
160
+
161
+ function resolveEventLocation(
162
+ rawUrl: unknown,
163
+ rawPath: unknown,
164
+ ctx: RequestContext,
165
+ site: string | undefined,
166
+ overrideHostname: string | undefined,
167
+ includeQueryParams: readonly string[] | undefined,
168
+ ): { url: string, path: string, hostname: string } {
169
+ const requestOrigin = ctx.url.origin
170
+ const baseOrigin = resolveBaseOrigin(site, requestOrigin)
171
+ const targetUrl = parseSameOriginCandidate(rawUrl, baseOrigin, requestOrigin)
172
+ ?? parseSameOriginCandidate(rawPath, baseOrigin, requestOrigin)
173
+ ?? parseSameOriginCandidate(ctx.request.headers.get('referer'), baseOrigin, requestOrigin)
174
+ ?? new URL('/', baseOrigin)
175
+ return resolveCanonicalLocation(targetUrl, site, overrideHostname, includeQueryParams)
176
+ }
177
+
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
192
+ try {
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
+ }
204
+ }
205
+ catch {
206
+ return { ok: false, status: 400, reason: 'unreadable body' }
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
215
+ if (text.trim() === '')
216
+ return { ok: false, status: 400, reason: 'empty body' }
217
+ try {
218
+ return { ok: true, value: JSON.parse(text) as unknown }
219
+ }
220
+ catch {
221
+ return { ok: false, status: 400, reason: 'body is not JSON' }
222
+ }
223
+ }
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
+
230
+ function parseEventPayload(
231
+ raw: unknown,
232
+ ctx: RequestContext,
233
+ site: string | undefined,
234
+ overrideHostname: string | undefined,
235
+ includeQueryParams: readonly string[] | undefined,
236
+ allowedProps: ReadonlySet<string>,
237
+ ): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | string {
238
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
239
+ return 'payload is not an object'
240
+ const obj = raw as Record<string, unknown>
241
+ if (typeof obj.name !== 'string')
242
+ return 'name is not a string'
243
+ const name = obj.name.trim()
244
+ if (name === '' || name.length > MAX_EVENT_NAME_LEN)
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)
249
+ if (props === null)
250
+ return `props invalid or past the caps (${MAX_PROP_KEYS} keys, ${MAX_PROP_KEY_LEN} character keys, ${MAX_PROP_STR_LEN} character strings)`
251
+ const loc = resolveEventLocation(obj.url, obj.path, ctx, site, overrideHostname, includeQueryParams)
252
+ return {
253
+ name,
254
+ ...loc,
255
+ ...(props !== undefined ? { props } : {}),
256
+ }
257
+ }
258
+
259
+ function reportError(
260
+ onError: AnalyticsOptions['onError'],
261
+ error: unknown,
262
+ kind: 'pageview' | 'event' | 'vital',
263
+ dev: boolean,
264
+ ): void {
265
+ if (onError !== undefined) {
266
+ onError(error, kind)
267
+ return
268
+ }
269
+ if (dev)
270
+ console.warn(`@prunellejs/analytics: failed to send ${kind}:`, error)
271
+ }
272
+
273
+ function hashScript(script: string): string {
274
+ const hasher = new Bun.CryptoHasher('sha256')
275
+ hasher.update(script)
276
+ return hasher.digest('hex').slice(0, 8)
277
+ }
278
+
279
+ type DispatchFn = (
280
+ fn: () => void | Promise<void>,
281
+ kind: 'pageview' | 'event' | 'vital',
282
+ ) => Promise<void> | undefined
283
+
284
+ interface RuntimeConfig {
285
+ provider: AnalyticsOptions['provider']
286
+ sendIp: boolean
287
+ ignoreBots: boolean
288
+ exclude: AnalyticsOptions['exclude']
289
+ includeQueryParams: readonly string[] | undefined
290
+ overrideHostname: string | undefined
291
+ consentCategory: string | undefined
292
+ allowedProps: ReadonlySet<string>
293
+ optOutEndpoint: string | false
294
+ eventEndpoint: string | false
295
+ viewEndpoint: string | false
296
+ webVitals: WebVitalsConfig | undefined
297
+ now: () => Date
298
+ onError: AnalyticsOptions['onError']
299
+ visitorIdFor: (ctx: RequestContext, hostname: string, timestamp: Date) => string
300
+ }
301
+
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 =>
305
+ pathname === assetPrefix
306
+ || pathname.startsWith(`${assetPrefix}/`)
307
+ || isDefaultSensitivePath(pathname)
308
+ || (cfg.eventEndpoint !== false && pathname === cfg.eventEndpoint)
309
+ || (cfg.optOutEndpoint !== false && pathname === cfg.optOutEndpoint)
310
+ || (cfg.webVitals !== undefined && pathname === cfg.webVitals.endpoint)
311
+ }
312
+
313
+ function createPageviewMiddleware(
314
+ cfg: RuntimeConfig,
315
+ isInternalPath: (pathname: string) => boolean,
316
+ site: string | undefined,
317
+ dispatch: DispatchFn,
318
+ ): Middleware {
319
+ return async (ctx, next) => {
320
+ const res = await next()
321
+ if (ctx.request.method !== 'GET' || isInternalPath(ctx.url.pathname) || !isHtmlSuccessResponse(res) || !isCountable(cfg, ctx))
322
+ return res
323
+ if (!isPrefetchRequest(ctx.request)) {
324
+ countPageview(cfg, site, dispatch, ctx, res.status)
325
+ return res
326
+ }
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)
335
+ return res
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
+ }
416
+ }
417
+
418
+ function createEventHandler(
419
+ cfg: RuntimeConfig,
420
+ site: string | undefined,
421
+ dev: boolean,
422
+ dispatch: DispatchFn,
423
+ ): (ctx: RequestContext) => Promise<Response> {
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
+ }
429
+ const parsedBody = await readJsonBody(ctx.request)
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)
439
+ return ctx.deny(400, 'Invalid analytics event payload')
440
+ }
441
+ if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory)) {
442
+ logDrop(dev, 'event', `no consent to "${cfg.consentCategory}"`)
443
+ return new Response(null, { status: 204 })
444
+ }
445
+
446
+ const timestamp = cfg.now()
447
+ const userAgent = ctx.request.headers.get('user-agent') ?? undefined
448
+ const referrer = sanitizeReferrer(ctx.request.headers.get('referer'))
449
+ const language = extractPrimaryLanguage(ctx.request)
450
+ const event: AnalyticsEvent = {
451
+ ...parsed,
452
+ visitorId: cfg.visitorIdFor(ctx, parsed.hostname, timestamp),
453
+ ...(referrer !== undefined ? { referrer } : {}),
454
+ ...(userAgent !== undefined && userAgent !== '' ? { userAgent: coarseUserAgent(userAgent) } : {}),
455
+ ...(language !== undefined ? { language } : {}),
456
+ ...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
457
+ timestamp,
458
+ }
459
+ const sendEvent = cfg.provider.sendEvent
460
+ if (sendEvent !== undefined) {
461
+ const pending = dispatch(() => sendEvent(event), 'event')
462
+ if (pending !== undefined)
463
+ await pending
464
+ }
465
+ return new Response(null, { status: 202 })
466
+ }
467
+ }
468
+
469
+ function createVitalsHandler(
470
+ cfg: RuntimeConfig,
471
+ vitals: WebVitalsConfig,
472
+ dev: boolean,
473
+ dispatch: DispatchFn,
474
+ ): (ctx: RequestContext) => Promise<Response> {
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
+ }
480
+ const parsedBody = await readJsonBody(ctx.request)
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')
490
+ return ctx.deny(400, 'Invalid Web Vital payload')
491
+ }
492
+ if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory)) {
493
+ logDrop(dev, 'vital', `no consent to "${cfg.consentCategory}"`)
494
+ return new Response(null, { status: 204 })
495
+ }
496
+
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
+ }
506
+ }
507
+ if (sendVital !== undefined) {
508
+ const pending = dispatch(() => sendVital(vital, ctx), 'vital')
509
+ if (pending !== undefined)
510
+ await pending
511
+ }
512
+ }
513
+ return new Response(null, { status: 202 })
514
+ }
515
+ }
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
+
530
+ /**
531
+ * CNIL-compliant first-party analytics plugin for Prunelle.
532
+ *
533
+ * - Counts both dynamic and prerendered HTML page views server-side with **0 B of client JS**.
534
+ * - Uses a daily-rotating SHA-256 visitor hash with no cookies and no persistent storage.
535
+ * - Never forwards client IP addresses unless `sendIp: true` is explicitly configured.
536
+ * - Exposes a first-party CSRF-protected custom event endpoint respecting `ctx.consent`.
537
+ * - Optionally emits a `<1.5 KB` standalone Web Vitals collector when `webVitals` is enabled.
538
+ */
539
+ export function analytics(options: AnalyticsOptions): PrunellePlugin {
540
+ const maxPending = options.maxPending ?? DEFAULT_MAX_PENDING
541
+ if (!Number.isInteger(maxPending) || maxPending < 1)
542
+ throw new Error(`prunelle: @prunellejs/analytics maxPending must be an integer >= 1, got ${String(maxPending)}`)
543
+
544
+ const fallbackSecret = generateProcessSecret()
545
+ const getSecret = (): string => options.secret ?? process.env.ANALYTICS_SECRET ?? fallbackSecret
546
+ const webVitals = normalizeWebVitals(options.webVitals)
547
+ const eventEndpoint = options.eventEndpoint === false
548
+ ? false
549
+ : normalizeEndpoint(options.eventEndpoint ?? DEFAULT_EVENT_ENDPOINT)
550
+ const viewEndpoint = options.viewEndpoint === false
551
+ ? false
552
+ : normalizeEndpoint(options.viewEndpoint ?? DEFAULT_VIEW_ENDPOINT)
553
+ const rateLimit = options.rateLimit === false ? undefined : options.rateLimit ?? DEFAULT_RATE_LIMIT
554
+
555
+ const cfg: RuntimeConfig = {
556
+ provider: options.provider,
557
+ sendIp: options.sendIp ?? false,
558
+ ignoreBots: options.ignoreBots ?? true,
559
+ exclude: options.exclude,
560
+ includeQueryParams: options.includeQueryParams,
561
+ overrideHostname: options.hostname,
562
+ consentCategory: resolveConsentCategory(options, undefined),
563
+ allowedProps: new Set(options.eventProps),
564
+ optOutEndpoint: options.optOutEndpoint === false ? false : normalizeEndpoint(options.optOutEndpoint ?? DEFAULT_OPT_OUT_ENDPOINT),
565
+ eventEndpoint,
566
+ viewEndpoint,
567
+ webVitals,
568
+ now: options.now ?? (() => new Date()),
569
+ onError: options.onError,
570
+ visitorIdFor: (ctx, hostname, timestamp) =>
571
+ computeVisitorId({
572
+ date: formatUtcDate(timestamp),
573
+ secret: getSecret(),
574
+ ip: ctx.ip ?? '',
575
+ userAgent: ctx.request.headers.get('user-agent') ?? '',
576
+ hostname,
577
+ }),
578
+ }
579
+
580
+ return definePlugin({
581
+ name: '@prunellejs/analytics',
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
+
596
+ build(ctx) {
597
+ cfg.consentCategory = resolveConsentCategory(options, ctx.site)
598
+ if (webVitals === undefined)
599
+ return
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)
605
+ const assetUrl = ctx.emitAsset(`analytics-vitals-${hashScript(script)}.js`, script)
606
+ ctx.addHead(`<script defer src="${escAttr(assetUrl)}"></script>`)
607
+ },
608
+
609
+ server(api) {
610
+ // Never count build-time prerender requests or mount live endpoints on the prerender server.
611
+ if (api.config?.prerender === true)
612
+ return
613
+
614
+ cfg.consentCategory = resolveConsentCategory(options, api.site)
615
+ const assetPrefix = api.assetPrefix.replace(/\/+$/, '')
616
+ const isInternalPath = internalPathTest(cfg, assetPrefix)
617
+ const pending = new Set<Promise<void>>()
618
+ const dispatch: DispatchFn = (fn, kind) => {
619
+ if (pending.size >= maxPending)
620
+ return undefined
621
+ let result: void | Promise<void>
622
+ try {
623
+ result = fn()
624
+ }
625
+ catch (err) {
626
+ reportError(cfg.onError, err, kind, api.dev)
627
+ return undefined
628
+ }
629
+ if (result === undefined)
630
+ return undefined
631
+ const wrapped: Promise<void> = Promise.resolve(result).catch((err) => {
632
+ reportError(cfg.onError, err, kind, api.dev)
633
+ }).finally(() => {
634
+ pending.delete(wrapped)
635
+ })
636
+ pending.add(wrapped)
637
+ return wrapped
638
+ }
639
+
640
+ // `scope: 'all'` counts both dynamic and prerendered pages without shipping any client JS.
641
+ api.use(createPageviewMiddleware(cfg, isInternalPath, api.site, dispatch), { scope: 'all' })
642
+
643
+ const routeOpts = { csrf: true, ...(rateLimit !== undefined ? { rateLimit } : {}) }
644
+ if (eventEndpoint !== false)
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)
653
+ if (webVitals !== undefined)
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))
657
+
658
+ api.onShutdown(async () => {
659
+ if (pending.size > 0)
660
+ await Promise.allSettled([...pending])
661
+ })
662
+ },
663
+ })
664
+ }