@prunellejs/analytics 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +45 -0
- package/package.json +25 -4
- package/src/client.ts +63 -0
- package/src/consent.ts +31 -0
- package/src/index.ts +663 -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/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
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @prunellejs/analytics Reference
|
|
2
|
+
|
|
3
|
+
> CNIL-compliant server-side audience measurement (0 B client JS), daily-rotating SHA-256 visitor hashes with no cookies, first-party CSRF-protected custom events, and optional `<1.5 KB` Web Vitals.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
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`.
|
|
8
|
+
- `@prunellejs/analytics/client`: `trackEvent`; types `AnalyticsEventProps`, `TrackEventOptions` (browser-safe, zero server imports).
|
|
9
|
+
|
|
10
|
+
## Setup (`analytics(options)`)
|
|
11
|
+
|
|
12
|
+
Register in `prunelle.config.ts` `plugins`:
|
|
13
|
+
|
|
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
|
+
- `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
|
+
- `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 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.
|
|
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).
|
|
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.
|
|
25
|
+
|
|
26
|
+
## Snippet
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// prunelle.config.ts
|
|
30
|
+
import { analytics, plausible } from '@prunellejs/analytics'
|
|
31
|
+
import { defineConfig } from 'prunelle/config'
|
|
32
|
+
|
|
33
|
+
export default defineConfig({
|
|
34
|
+
site: 'https://example.com',
|
|
35
|
+
plugins: [
|
|
36
|
+
analytics({
|
|
37
|
+
provider: plausible({ domain: 'example.com', host: 'https://stats.example.com' }),
|
|
38
|
+
}),
|
|
39
|
+
],
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// In an island (browser):
|
|
43
|
+
import { trackEvent } from '@prunellejs/analytics/client'
|
|
44
|
+
await trackEvent('newsletter_signup', { plan: 'free' })
|
|
45
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/analytics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "CNIL-compliant server-side first-party audience measurement, custom events, and optional Web Vitals plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts",
|
|
14
|
+
"./client": "./src/client.ts"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"bun": ">=1.4.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
22
|
+
"directory": "packages/plugin-analytics"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"prunelle": "^0.7.0"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Browser-safe first-party custom event helper for @prunellejs/analytics/client.
|
|
2
|
+
// Zero server/Node/Bun imports.
|
|
3
|
+
|
|
4
|
+
export type AnalyticsEventProps = Record<string, string | number | boolean>
|
|
5
|
+
|
|
6
|
+
export interface TrackEventOptions {
|
|
7
|
+
/** First-party POST endpoint path (default: `'/_pru/analytics/event'`). */
|
|
8
|
+
endpoint?: string | undefined
|
|
9
|
+
/** Page URL or pathname to associate with the event (defaults to `location.href`). */
|
|
10
|
+
url?: string | undefined
|
|
11
|
+
/** Use `navigator.sendBeacon` when available (default: `false`, uses `fetch` with `keepalive: true`). */
|
|
12
|
+
beacon?: boolean | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_EVENT_ENDPOINT = '/_pru/analytics/event'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Sends a custom analytics event to Prunelle's first-party CSRF-protected endpoint.
|
|
19
|
+
* Returns `true` when accepted (HTTP 2xx or queued via `sendBeacon`), `false` otherwise.
|
|
20
|
+
*/
|
|
21
|
+
export async function trackEvent(
|
|
22
|
+
name: string,
|
|
23
|
+
props?: AnalyticsEventProps,
|
|
24
|
+
options?: TrackEventOptions,
|
|
25
|
+
): Promise<boolean> {
|
|
26
|
+
const trimmed = name.trim()
|
|
27
|
+
if (trimmed === '' || typeof window === 'undefined')
|
|
28
|
+
return false
|
|
29
|
+
|
|
30
|
+
const endpoint = options?.endpoint ?? DEFAULT_EVENT_ENDPOINT
|
|
31
|
+
const url = options?.url ?? (typeof location !== 'undefined' ? location.href : '/')
|
|
32
|
+
const body = JSON.stringify(props !== undefined ? { name: trimmed, url, props } : { name: trimmed, url })
|
|
33
|
+
|
|
34
|
+
// A beacon the browser refuses (its queue is full, or the body over its quota) goes by fetch keepalive below.
|
|
35
|
+
if (options?.beacon === true && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
36
|
+
let queued: boolean
|
|
37
|
+
try {
|
|
38
|
+
queued = navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
queued = false
|
|
42
|
+
}
|
|
43
|
+
if (queued)
|
|
44
|
+
return true
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (typeof fetch !== 'function')
|
|
48
|
+
return false
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const res = await fetch(endpoint, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { 'content-type': 'application/json' },
|
|
54
|
+
body,
|
|
55
|
+
keepalive: true,
|
|
56
|
+
credentials: 'same-origin',
|
|
57
|
+
})
|
|
58
|
+
return res.ok
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return false
|
|
62
|
+
}
|
|
63
|
+
}
|
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
|
+
}
|