@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/LICENSE +21 -0
- package/llms.txt +46 -0
- package/package.json +25 -4
- package/src/client.ts +63 -0
- package/src/consent.ts +31 -0
- package/src/index.ts +664 -0
- package/src/providers.ts +263 -0
- package/src/types.ts +177 -0
- package/src/visitor.ts +168 -0
- package/src/vitals.ts +99 -0
- package/README.md +0 -3
package/src/providers.ts
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Built-in analytics providers: Plausible, Umami, Matomo, and custom transport.
|
|
2
|
+
// Client IPs are NEVER sent unless `pageview.ip` / `event.ip` is explicitly populated via `sendIp: true`.
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
AnalyticsEvent,
|
|
6
|
+
AnalyticsPageview,
|
|
7
|
+
AnalyticsProvider,
|
|
8
|
+
CustomAnalyticsOptions,
|
|
9
|
+
FetchLike,
|
|
10
|
+
MatomoOptions,
|
|
11
|
+
PlausibleOptions,
|
|
12
|
+
UmamiOptions,
|
|
13
|
+
} from './types'
|
|
14
|
+
|
|
15
|
+
const DEFAULT_TIMEOUT_MS = 5_000
|
|
16
|
+
const DEFAULT_USER_AGENT = 'Prunelle-Analytics/1.0'
|
|
17
|
+
|
|
18
|
+
function stripTrailingSlash(url: string): string {
|
|
19
|
+
return url.replace(/\/+$/, '')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function assertNonEmpty(value: string, label: string): string {
|
|
23
|
+
const trimmed = value.trim()
|
|
24
|
+
if (trimmed === '')
|
|
25
|
+
throw new Error(`prunelle: @prunellejs/analytics ${label} must be a non-empty string`)
|
|
26
|
+
return trimmed
|
|
27
|
+
}
|
|
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
|
+
|
|
59
|
+
async function postUpstream(
|
|
60
|
+
fetchImpl: FetchLike,
|
|
61
|
+
url: string,
|
|
62
|
+
headers: Record<string, string>,
|
|
63
|
+
body: string,
|
|
64
|
+
timeoutMs: number,
|
|
65
|
+
providerName: string,
|
|
66
|
+
): Promise<void> {
|
|
67
|
+
const res = await fetchImpl(url, {
|
|
68
|
+
method: 'POST',
|
|
69
|
+
headers,
|
|
70
|
+
body,
|
|
71
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
72
|
+
})
|
|
73
|
+
if (!res.ok) {
|
|
74
|
+
const text = await readBodyStart(res)
|
|
75
|
+
throw new Error(`prunelle: @prunellejs/analytics (${providerName}): HTTP ${res.status}: ${text}`)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function hostnameOf(url: string): string | undefined {
|
|
80
|
+
return URL.canParse(url) ? new URL(url).hostname.toLowerCase() : undefined
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isThirdPartyPlausibleHost(host: string): boolean {
|
|
84
|
+
if (!URL.canParse(host))
|
|
85
|
+
return false
|
|
86
|
+
const hostname = new URL(host).hostname.toLowerCase()
|
|
87
|
+
return hostname === 'plausible.io' || hostname.endsWith('.plausible.io')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Plausible Events API provider (`POST <host>/api/event`).
|
|
92
|
+
* Self-hosted Plausible without `sendIp: true` defaults to `requiresConsent: false`.
|
|
93
|
+
* Third-party `https://plausible.io` defaults to `requiresConsent: true` unless explicitly opted out.
|
|
94
|
+
*/
|
|
95
|
+
export function plausible(options: PlausibleOptions): AnalyticsProvider {
|
|
96
|
+
const domain = assertNonEmpty(options.domain, 'plausible() domain')
|
|
97
|
+
const host = stripTrailingSlash(options.host ?? 'https://plausible.io')
|
|
98
|
+
const endpoint = `${host}/api/event`
|
|
99
|
+
const timeoutMs = resolveTimeoutMs(options.timeoutMs)
|
|
100
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
101
|
+
const defaultRequiresConsent = isThirdPartyPlausibleHost(host)
|
|
102
|
+
|
|
103
|
+
const send = async (
|
|
104
|
+
name: string,
|
|
105
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
106
|
+
props?: AnalyticsEvent['props'],
|
|
107
|
+
): Promise<void> => {
|
|
108
|
+
const headers: Record<string, string> = {
|
|
109
|
+
'content-type': 'application/json',
|
|
110
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
111
|
+
'x-visitor-id': item.visitorId,
|
|
112
|
+
}
|
|
113
|
+
if (item.ip !== undefined)
|
|
114
|
+
headers['x-forwarded-for'] = item.ip
|
|
115
|
+
const payload: Record<string, unknown> = {
|
|
116
|
+
name,
|
|
117
|
+
url: item.url,
|
|
118
|
+
domain,
|
|
119
|
+
referrer: item.referrer ?? null,
|
|
120
|
+
}
|
|
121
|
+
if (props !== undefined)
|
|
122
|
+
payload.props = props
|
|
123
|
+
await postUpstream(fetchImpl, endpoint, headers, JSON.stringify(payload), timeoutMs, 'plausible')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
name: 'plausible',
|
|
128
|
+
requiresConsent: options.requiresConsent ?? defaultRequiresConsent,
|
|
129
|
+
sendPageview: pv => send('pageview', pv),
|
|
130
|
+
sendEvent: ev => send(ev.name, ev, ev.props),
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Umami Collect API provider (`POST <host>/api/send`).
|
|
136
|
+
* Self-hosted Umami without `sendIp: true` uses daily-rotating hashes and zero cookies.
|
|
137
|
+
*/
|
|
138
|
+
export function umami(options: UmamiOptions): AnalyticsProvider {
|
|
139
|
+
const websiteId = assertNonEmpty(options.websiteId, 'umami() websiteId')
|
|
140
|
+
const host = stripTrailingSlash(assertNonEmpty(options.host, 'umami() host'))
|
|
141
|
+
const endpoint = `${host}/api/send`
|
|
142
|
+
const timeoutMs = resolveTimeoutMs(options.timeoutMs)
|
|
143
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
144
|
+
|
|
145
|
+
const send = async (
|
|
146
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
147
|
+
eventName?: string,
|
|
148
|
+
props?: AnalyticsEvent['props'],
|
|
149
|
+
): Promise<void> => {
|
|
150
|
+
const headers: Record<string, string> = {
|
|
151
|
+
'content-type': 'application/json',
|
|
152
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
153
|
+
}
|
|
154
|
+
if (item.ip !== undefined)
|
|
155
|
+
headers['x-forwarded-for'] = item.ip
|
|
156
|
+
const payload: Record<string, unknown> = {
|
|
157
|
+
website: websiteId,
|
|
158
|
+
hostname: item.hostname,
|
|
159
|
+
url: item.path,
|
|
160
|
+
referrer: item.referrer ?? '',
|
|
161
|
+
language: item.language ?? '',
|
|
162
|
+
id: item.visitorId,
|
|
163
|
+
}
|
|
164
|
+
if (eventName !== undefined)
|
|
165
|
+
payload.name = eventName
|
|
166
|
+
if (props !== undefined)
|
|
167
|
+
payload.data = props
|
|
168
|
+
await postUpstream(fetchImpl, endpoint, headers, JSON.stringify({ type: 'event', payload }), timeoutMs, 'umami')
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return {
|
|
172
|
+
name: 'umami',
|
|
173
|
+
host: hostnameOf(host),
|
|
174
|
+
requiresConsent: options.requiresConsent,
|
|
175
|
+
sendPageview: pv => send(pv),
|
|
176
|
+
sendEvent: ev => send(ev, ev.name, ev.props),
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function matomoEndpoint(rawUrl: string): string {
|
|
181
|
+
const trimmed = stripTrailingSlash(assertNonEmpty(rawUrl, 'matomo() url'))
|
|
182
|
+
return trimmed.endsWith('.php') ? trimmed : `${trimmed}/matomo.php`
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function buildMatomoParams(
|
|
186
|
+
siteId: string,
|
|
187
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
188
|
+
tokenAuth: string | undefined,
|
|
189
|
+
): URLSearchParams {
|
|
190
|
+
const params = new URLSearchParams({
|
|
191
|
+
idsite: siteId,
|
|
192
|
+
rec: '1',
|
|
193
|
+
apiv: '1',
|
|
194
|
+
send_image: '0',
|
|
195
|
+
url: item.url,
|
|
196
|
+
_id: item.visitorId.slice(0, 16),
|
|
197
|
+
})
|
|
198
|
+
if (item.referrer !== undefined)
|
|
199
|
+
params.set('urlref', item.referrer)
|
|
200
|
+
if (item.userAgent !== undefined)
|
|
201
|
+
params.set('ua', item.userAgent)
|
|
202
|
+
if (item.language !== undefined)
|
|
203
|
+
params.set('lang', item.language)
|
|
204
|
+
if (item.ip !== undefined) {
|
|
205
|
+
params.set('cip', item.ip)
|
|
206
|
+
if (tokenAuth !== undefined && tokenAuth !== '')
|
|
207
|
+
params.set('token_auth', tokenAuth)
|
|
208
|
+
}
|
|
209
|
+
return params
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Matomo Tracking HTTP API provider (`POST <url>/matomo.php`).
|
|
214
|
+
* Uses a 16-hex-char daily-rotating `_id` with zero cookies and never forwards `cip` unless `sendIp: true`.
|
|
215
|
+
*/
|
|
216
|
+
export function matomo(options: MatomoOptions): AnalyticsProvider {
|
|
217
|
+
const endpoint = matomoEndpoint(options.url)
|
|
218
|
+
const siteId = assertNonEmpty(String(options.siteId), 'matomo() siteId')
|
|
219
|
+
const timeoutMs = resolveTimeoutMs(options.timeoutMs)
|
|
220
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
221
|
+
|
|
222
|
+
const post = async (item: AnalyticsPageview | AnalyticsEvent, params: URLSearchParams): Promise<void> => {
|
|
223
|
+
const headers: Record<string, string> = {
|
|
224
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
225
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
226
|
+
}
|
|
227
|
+
if (item.ip !== undefined)
|
|
228
|
+
headers['x-forwarded-for'] = item.ip
|
|
229
|
+
await postUpstream(fetchImpl, endpoint, headers, params.toString(), timeoutMs, 'matomo')
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
name: 'matomo',
|
|
234
|
+
host: hostnameOf(endpoint),
|
|
235
|
+
requiresConsent: options.requiresConsent,
|
|
236
|
+
sendPageview(pv) {
|
|
237
|
+
const params = buildMatomoParams(siteId, pv, options.tokenAuth)
|
|
238
|
+
params.set('action_name', pv.path)
|
|
239
|
+
return post(pv, params)
|
|
240
|
+
},
|
|
241
|
+
sendEvent(ev) {
|
|
242
|
+
const params = buildMatomoParams(siteId, ev, options.tokenAuth)
|
|
243
|
+
params.set('e_c', typeof ev.props?.category === 'string' ? ev.props.category : 'custom')
|
|
244
|
+
params.set('e_a', ev.name)
|
|
245
|
+
if (ev.props?.label !== undefined)
|
|
246
|
+
params.set('e_n', String(ev.props.label))
|
|
247
|
+
if (typeof ev.props?.value === 'number' && Number.isFinite(ev.props.value))
|
|
248
|
+
params.set('e_v', String(ev.props.value))
|
|
249
|
+
return post(ev, params)
|
|
250
|
+
},
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Custom analytics provider backed by user-supplied callbacks. */
|
|
255
|
+
export function custom(options: CustomAnalyticsOptions): AnalyticsProvider {
|
|
256
|
+
return {
|
|
257
|
+
name: options.name ?? 'custom',
|
|
258
|
+
requiresConsent: options.requiresConsent,
|
|
259
|
+
sendPageview: options.sendPageview,
|
|
260
|
+
...(options.sendEvent !== undefined ? { sendEvent: options.sendEvent } : {}),
|
|
261
|
+
...(options.sendVital !== undefined ? { sendVital: options.sendVital } : {}),
|
|
262
|
+
}
|
|
263
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Public types for @prunellejs/analytics.
|
|
2
|
+
|
|
3
|
+
import type { RateLimit, RequestContext } from 'prunelle/server'
|
|
4
|
+
|
|
5
|
+
export type AnalyticsEventProps = Record<string, string | number | boolean>
|
|
6
|
+
|
|
7
|
+
export type WebVitalName = 'LCP' | 'CLS' | 'INP' | 'FCP' | 'TTFB'
|
|
8
|
+
|
|
9
|
+
export type WebVitalRating = 'good' | 'needs-improvement' | 'poor'
|
|
10
|
+
|
|
11
|
+
export interface WebVitalMetric {
|
|
12
|
+
name: WebVitalName
|
|
13
|
+
value: number
|
|
14
|
+
rating: WebVitalRating
|
|
15
|
+
path: string
|
|
16
|
+
id?: string | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface AnalyticsPageview {
|
|
20
|
+
/** Canonical full URL of the viewed page. */
|
|
21
|
+
url: string
|
|
22
|
+
/** Request pathname (e.g. `'/blog/hello'`). */
|
|
23
|
+
path: string
|
|
24
|
+
/** Resolved hostname (e.g. `'example.com'`). */
|
|
25
|
+
hostname: string
|
|
26
|
+
/** Daily-rotating SHA-256 visitor hash (never stored in cookies or browser storage). */
|
|
27
|
+
visitorId: string
|
|
28
|
+
/** Referer header, when present. */
|
|
29
|
+
referrer?: string | undefined
|
|
30
|
+
/** User-Agent header, when present. */
|
|
31
|
+
userAgent?: string | undefined
|
|
32
|
+
/** Accept-Language primary value, when present. */
|
|
33
|
+
language?: string | undefined
|
|
34
|
+
/** Client IP address — ONLY populated when `sendIp: true` is explicitly opted in. */
|
|
35
|
+
ip?: string | undefined
|
|
36
|
+
/** HTTP response status code (always 2xx for counted page views). */
|
|
37
|
+
status: number
|
|
38
|
+
/** Timestamp when the page view was recorded. */
|
|
39
|
+
timestamp: Date
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface AnalyticsEvent {
|
|
43
|
+
/** Event name (e.g. `'signup'`, `'download'`). */
|
|
44
|
+
name: string
|
|
45
|
+
/** Full page URL where the event occurred. */
|
|
46
|
+
url: string
|
|
47
|
+
/** Page pathname where the event occurred. */
|
|
48
|
+
path: string
|
|
49
|
+
/** Resolved hostname. */
|
|
50
|
+
hostname: string
|
|
51
|
+
/** Daily-rotating SHA-256 visitor hash. */
|
|
52
|
+
visitorId: string
|
|
53
|
+
/** Optional flat primitive event properties. */
|
|
54
|
+
props?: AnalyticsEventProps | undefined
|
|
55
|
+
/** Referer header, when present. */
|
|
56
|
+
referrer?: string | undefined
|
|
57
|
+
/** User-Agent header, when present. */
|
|
58
|
+
userAgent?: string | undefined
|
|
59
|
+
/** Accept-Language primary value, when present. */
|
|
60
|
+
language?: string | undefined
|
|
61
|
+
/** Client IP address — ONLY populated when `sendIp: true` is explicitly opted in. */
|
|
62
|
+
ip?: string | undefined
|
|
63
|
+
/** Timestamp when the event was recorded. */
|
|
64
|
+
timestamp: Date
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface AnalyticsProvider {
|
|
68
|
+
readonly name: string
|
|
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). */
|
|
72
|
+
readonly requiresConsent?: boolean | undefined
|
|
73
|
+
sendPageview(pageview: AnalyticsPageview): void | Promise<void>
|
|
74
|
+
sendEvent?(event: AnalyticsEvent): void | Promise<void>
|
|
75
|
+
sendVital?(vital: WebVitalMetric, ctx: RequestContext): void | Promise<void>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>
|
|
79
|
+
|
|
80
|
+
export interface PlausibleOptions {
|
|
81
|
+
/** Site domain configured in Plausible (e.g. `'example.com'`). */
|
|
82
|
+
domain: string
|
|
83
|
+
/** Plausible server origin (default: `'https://plausible.io'`). */
|
|
84
|
+
host?: string | undefined
|
|
85
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
86
|
+
timeoutMs?: number | undefined
|
|
87
|
+
/** Whether consent is required before sending to this Plausible instance (default: `true` for third-party `plausible.io`, `false` for self-hosted `host`). */
|
|
88
|
+
requiresConsent?: boolean | undefined
|
|
89
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
90
|
+
fetch?: FetchLike | undefined
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface UmamiOptions {
|
|
94
|
+
/** Umami website UUID. */
|
|
95
|
+
websiteId: string
|
|
96
|
+
/** Umami server origin (e.g. `'https://analytics.example.com'`). */
|
|
97
|
+
host: string
|
|
98
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
99
|
+
timeoutMs?: number | undefined
|
|
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). */
|
|
101
|
+
requiresConsent?: boolean | undefined
|
|
102
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
103
|
+
fetch?: FetchLike | undefined
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface MatomoOptions {
|
|
107
|
+
/** Matomo base URL or tracking script URL (e.g. `'https://matomo.example.com'`). */
|
|
108
|
+
url: string
|
|
109
|
+
/** Matomo site ID (`idsite`). */
|
|
110
|
+
siteId: number | string
|
|
111
|
+
/** Optional Matomo `token_auth` (required by Matomo when forwarding `cip` via `sendIp: true`). */
|
|
112
|
+
tokenAuth?: string | undefined
|
|
113
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
114
|
+
timeoutMs?: number | undefined
|
|
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). */
|
|
116
|
+
requiresConsent?: boolean | undefined
|
|
117
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
118
|
+
fetch?: FetchLike | undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export interface CustomAnalyticsOptions {
|
|
122
|
+
/** Provider label for diagnostics (default: `'custom'`). */
|
|
123
|
+
name?: string | undefined
|
|
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). */
|
|
125
|
+
requiresConsent?: boolean | undefined
|
|
126
|
+
sendPageview: (pageview: AnalyticsPageview) => void | Promise<void>
|
|
127
|
+
sendEvent?: ((event: AnalyticsEvent) => void | Promise<void>) | undefined
|
|
128
|
+
sendVital?: ((vital: WebVitalMetric, ctx: RequestContext) => void | Promise<void>) | undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export interface WebVitalsOptions {
|
|
132
|
+
/** First-party POST endpoint for Web Vitals beacons (default: `'/_pru/analytics/vitals'`). */
|
|
133
|
+
endpoint?: string | undefined
|
|
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. */
|
|
137
|
+
onVital?: ((vital: WebVitalMetric, ctx: RequestContext) => void | Promise<void>) | undefined
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface AnalyticsOptions {
|
|
141
|
+
/** Analytics backend (`plausible(...)`, `umami(...)`, `matomo(...)`, or `custom(...)`). */
|
|
142
|
+
provider: AnalyticsProvider
|
|
143
|
+
/** Ephemeral salt for the daily-rotating SHA-256 visitor hash (defaults to `process.env.ANALYTICS_SECRET` or a random per-process 32-byte key). */
|
|
144
|
+
secret?: string | undefined
|
|
145
|
+
/** Forward raw client IP to the provider (default: `false`). Opting in automatically enables consent gating unless `consentCategory: false`. */
|
|
146
|
+
sendIp?: boolean | undefined
|
|
147
|
+
/** Explicitly require or waive `ctx.consent` checks (defaults to `true` when `sendIp: true` or `provider.requiresConsent === true`). */
|
|
148
|
+
requiresConsent?: boolean | undefined
|
|
149
|
+
/** Consent category checked via `ctx.consent.has(...)` (default: `'analytics'` when consent is required; pass `false` to disable consent gating). */
|
|
150
|
+
consentCategory?: string | false | undefined
|
|
151
|
+
/** First-party POST endpoint for custom events (default: `'/_pru/analytics/event'`; set `false` to disable). */
|
|
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
|
|
155
|
+
/** Enable first-party Web Vitals collection (default: `false`, emitting 0 B of JS). */
|
|
156
|
+
webVitals?: boolean | WebVitalsOptions | undefined
|
|
157
|
+
/** Skip common crawler/bot User-Agents for page views (default: `true`). */
|
|
158
|
+
ignoreBots?: boolean | undefined
|
|
159
|
+
/** Paths, regexes, or predicate excluded from server-side page view counting (in addition to `/_pru/*`, `/auth/*`, and analytics endpoints). */
|
|
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
|
|
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). */
|
|
166
|
+
includeQueryParams?: readonly string[] | undefined
|
|
167
|
+
/** Override hostname used for visitor hashing and provider payloads. */
|
|
168
|
+
hostname?: string | undefined
|
|
169
|
+
/** Rate limit applied to the first-party event and Web Vitals POST endpoints (default: 60 requests/minute per IP; set `false` to disable). */
|
|
170
|
+
rateLimit?: RateLimit<RequestContext> | false | undefined
|
|
171
|
+
/** Maximum concurrent in-flight outbound provider requests before new analytics pings are dropped (default: `64`). */
|
|
172
|
+
maxPending?: number | undefined
|
|
173
|
+
/** Optional clock provider (defaults to `() => new Date()`). */
|
|
174
|
+
now?: (() => Date) | undefined
|
|
175
|
+
/** Error handler invoked when a provider transport call fails (never fails user responses). */
|
|
176
|
+
onError?: ((error: unknown, kind: 'pageview' | 'event' | 'vital') => void) | undefined
|
|
177
|
+
}
|
package/src/visitor.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Daily-rotating SHA-256 visitor hashing and server-side page view filtering.
|
|
2
|
+
|
|
3
|
+
import type { RequestContext } from 'prunelle/server'
|
|
4
|
+
|
|
5
|
+
export interface VisitorIdInput {
|
|
6
|
+
/** UTC calendar date in `YYYY-MM-DD` format. */
|
|
7
|
+
date: string
|
|
8
|
+
/** Server-side ephemeral or configured hash salt. */
|
|
9
|
+
secret: string
|
|
10
|
+
/** Client IP address (empty string if unavailable). */
|
|
11
|
+
ip: string
|
|
12
|
+
/** Raw User-Agent header (empty string if unavailable). */
|
|
13
|
+
userAgent: string
|
|
14
|
+
/** Site or request hostname. */
|
|
15
|
+
hostname: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const BOT_UA_RE = /\b(?:bot|crawl(?:er|ing)?|spider|slurp|bingpreview|facebookexternalhit|linkedinbot|twitterbot|whatsapp|telegrambot|discordbot|applebot|duckduckbot|yandex|baiduspider|semrush|ahrefs|mj12bot|dotbot|petalbot|bytespider|gptbot|claudebot|anthropic-ai|googleother|lighthouse|pagespeed|headlesschrome|phantomjs|uptime|pingdom|datadog|statuscake|check_http)\b|^(?:curl|wget|python-requests|go-http-client|axios|node-fetch|undici|libwww-perl|httpie)\//i
|
|
19
|
+
|
|
20
|
+
/** Formats `date` as a UTC `YYYY-MM-DD` string for daily visitor-hash rotation. */
|
|
21
|
+
export function formatUtcDate(date: Date = new Date()): string {
|
|
22
|
+
return date.toISOString().slice(0, 10)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Generates a random 32-byte hex secret scoped to the current process. */
|
|
26
|
+
export function generateProcessSecret(): string {
|
|
27
|
+
const bytes = new Uint8Array(32)
|
|
28
|
+
crypto.getRandomValues(bytes)
|
|
29
|
+
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Computes a daily-rotating SHA-256 visitor hash keyed by UTC date, secret, client IP,
|
|
34
|
+
* User-Agent, and hostname. Uses no cookies and no persistent browser storage.
|
|
35
|
+
*/
|
|
36
|
+
export function computeVisitorId(input: VisitorIdInput): string {
|
|
37
|
+
const hasher = new Bun.CryptoHasher('sha256')
|
|
38
|
+
hasher.update(`${input.date}\0${input.secret}\0${input.ip}\0${input.userAgent}\0${input.hostname}`)
|
|
39
|
+
return hasher.digest('hex')
|
|
40
|
+
}
|
|
41
|
+
|
|
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
|
+
|
|
51
|
+
export function isBotUserAgent(userAgent: string | null | undefined): boolean {
|
|
52
|
+
if (userAgent === null || userAgent === undefined || userAgent === '')
|
|
53
|
+
return false
|
|
54
|
+
return BOT_UA_RE.test(userAgent)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Returns `true` when request headers indicate a speculative prefetch or prerender rather than a navigation. */
|
|
58
|
+
export function isPrefetchRequest(request: Request): boolean {
|
|
59
|
+
const secPurpose = request.headers.get('sec-purpose')?.toLowerCase() ?? ''
|
|
60
|
+
if (secPurpose.includes('prefetch') || secPurpose.includes('prerender'))
|
|
61
|
+
return true
|
|
62
|
+
const purpose = request.headers.get('purpose')?.toLowerCase() ?? ''
|
|
63
|
+
if (purpose === 'prefetch' || purpose === 'preview')
|
|
64
|
+
return true
|
|
65
|
+
const xMoz = request.headers.get('x-moz')?.toLowerCase() ?? ''
|
|
66
|
+
if (xMoz === 'prefetch')
|
|
67
|
+
return true
|
|
68
|
+
const xPurpose = request.headers.get('x-purpose')?.toLowerCase() ?? ''
|
|
69
|
+
return xPurpose === 'prefetch' || xPurpose === 'preview'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Extracts the primary language tag from an `Accept-Language` header, if present. */
|
|
73
|
+
export function extractPrimaryLanguage(request: Request): string | undefined {
|
|
74
|
+
const raw = request.headers.get('accept-language')?.trim()
|
|
75
|
+
if (raw === undefined || raw === '')
|
|
76
|
+
return undefined
|
|
77
|
+
const first = raw.split(',')[0]?.split(';')[0]?.trim()
|
|
78
|
+
return first !== undefined && first !== '' ? first : undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Strips query strings and fragments from a Referer header to prevent leaking tokens or search PII. */
|
|
82
|
+
export function sanitizeReferrer(raw: string | null | undefined): string | undefined {
|
|
83
|
+
if (raw === null || raw === undefined)
|
|
84
|
+
return undefined
|
|
85
|
+
const trimmed = raw.trim()
|
|
86
|
+
if (trimmed === '' || !URL.canParse(trimmed))
|
|
87
|
+
return undefined
|
|
88
|
+
const parsed = new URL(trimmed)
|
|
89
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
90
|
+
return undefined
|
|
91
|
+
parsed.search = ''
|
|
92
|
+
parsed.hash = ''
|
|
93
|
+
return parsed.href
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function buildAllowedSearch(url: URL, includeQueryParams: readonly string[] | undefined): string {
|
|
97
|
+
if (includeQueryParams === undefined || includeQueryParams.length === 0 || url.search === '')
|
|
98
|
+
return ''
|
|
99
|
+
const allowed = new Set(includeQueryParams)
|
|
100
|
+
const kept = new URLSearchParams()
|
|
101
|
+
for (const [k, v] of url.searchParams) {
|
|
102
|
+
if (allowed.has(k))
|
|
103
|
+
kept.append(k, v)
|
|
104
|
+
}
|
|
105
|
+
const qs = kept.toString()
|
|
106
|
+
return qs !== '' ? `?${qs}` : ''
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Resolves the canonical URL and hostname for a request, preferring `site` from `prunelle.config.ts` when set.
|
|
111
|
+
* Strips query strings and fragments by default unless parameter names are explicitly listed in `includeQueryParams`.
|
|
112
|
+
*/
|
|
113
|
+
export function resolveCanonicalLocation(
|
|
114
|
+
url: URL,
|
|
115
|
+
site: string | undefined,
|
|
116
|
+
overrideHostname: string | undefined,
|
|
117
|
+
includeQueryParams?: readonly string[] | undefined,
|
|
118
|
+
): { url: string, path: string, hostname: string } {
|
|
119
|
+
const path = url.pathname
|
|
120
|
+
let origin = url.origin
|
|
121
|
+
let hostname = url.hostname
|
|
122
|
+
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
123
|
+
const parsedSite = new URL(site)
|
|
124
|
+
if (parsedSite.protocol === 'http:' || parsedSite.protocol === 'https:') {
|
|
125
|
+
origin = parsedSite.origin
|
|
126
|
+
hostname = parsedSite.hostname
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const canonical = new URL(origin)
|
|
130
|
+
canonical.pathname = path
|
|
131
|
+
canonical.search = buildAllowedSearch(url, includeQueryParams)
|
|
132
|
+
if (overrideHostname !== undefined && overrideHostname !== '')
|
|
133
|
+
hostname = overrideHostname
|
|
134
|
+
return { url: canonical.href, path, hostname }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Returns `true` for sensitive auth paths (`/auth` and `/auth/*`) excluded from automatic pageview counting by default. */
|
|
138
|
+
export function isDefaultSensitivePath(pathname: string): boolean {
|
|
139
|
+
return pathname === '/auth' || pathname.startsWith('/auth/')
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function isPathExcluded(
|
|
143
|
+
ctx: RequestContext,
|
|
144
|
+
exclude: readonly (string | RegExp)[] | ((ctx: RequestContext) => boolean) | undefined,
|
|
145
|
+
): boolean {
|
|
146
|
+
if (exclude === undefined)
|
|
147
|
+
return false
|
|
148
|
+
if (typeof exclude === 'function')
|
|
149
|
+
return exclude(ctx)
|
|
150
|
+
const pathname = ctx.url.pathname
|
|
151
|
+
for (const rule of exclude) {
|
|
152
|
+
if (typeof rule === 'string') {
|
|
153
|
+
if (pathname === rule || pathname.startsWith(rule.endsWith('/') ? rule : `${rule}/`))
|
|
154
|
+
return true
|
|
155
|
+
}
|
|
156
|
+
else if (rule.test(pathname)) {
|
|
157
|
+
return true
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return false
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function isHtmlSuccessResponse(res: Response): boolean {
|
|
164
|
+
if (res.status < 200 || res.status >= 300)
|
|
165
|
+
return false
|
|
166
|
+
const ct = res.headers.get('content-type')?.toLowerCase() ?? ''
|
|
167
|
+
return ct.includes('text/html')
|
|
168
|
+
}
|