@10x-media/analytics 0.1.0-beta.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/CHANGELOG.md +41 -0
- package/LICENSE +21 -0
- package/README.md +387 -0
- package/dist/RealtimeCounter-BJrjMPSa.js +473 -0
- package/dist/RealtimeCounter-BJrjMPSa.js.map +1 -0
- package/dist/contract-CWZPKWuR.d.ts +83 -0
- package/dist/dist-B6HruP5v.js +4731 -0
- package/dist/dist-B6HruP5v.js.map +1 -0
- package/dist/exports/adapters/ga4.d.ts +20 -0
- package/dist/exports/adapters/ga4.js +177 -0
- package/dist/exports/adapters/ga4.js.map +1 -0
- package/dist/exports/adapters/native.d.ts +22 -0
- package/dist/exports/adapters/native.js +849 -0
- package/dist/exports/adapters/native.js.map +1 -0
- package/dist/exports/adapters/plausible.d.ts +15 -0
- package/dist/exports/adapters/plausible.js +143 -0
- package/dist/exports/adapters/plausible.js.map +1 -0
- package/dist/exports/adapters/posthog.d.ts +17 -0
- package/dist/exports/adapters/posthog.js +119 -0
- package/dist/exports/adapters/posthog.js.map +1 -0
- package/dist/exports/adapters/umami.d.ts +18 -0
- package/dist/exports/adapters/umami.js +139 -0
- package/dist/exports/adapters/umami.js.map +1 -0
- package/dist/exports/client.d.ts +77 -0
- package/dist/exports/client.js +388 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/exports/geo.d.ts +19 -0
- package/dist/exports/geo.js +2 -0
- package/dist/exports/i18n.d.ts +63 -0
- package/dist/exports/i18n.js +3 -0
- package/dist/exports/rsc.d.ts +120 -0
- package/dist/exports/rsc.js +598 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/exports/types.d.ts +4 -0
- package/dist/exports/types.js +1 -0
- package/dist/fetchJson-DZb2_Puj.js +36 -0
- package/dist/fetchJson-DZb2_Puj.js.map +1 -0
- package/dist/geoResolver-CasIa4T9.d.ts +12 -0
- package/dist/index-CZdCT0WJ.d.ts +98 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1081 -0
- package/dist/index.js.map +1 -0
- package/dist/keys-DEqL4LOT.js +57 -0
- package/dist/keys-DEqL4LOT.js.map +1 -0
- package/dist/lib-CE5x1zLQ.js +1058 -0
- package/dist/lib-CE5x1zLQ.js.map +1 -0
- package/dist/maxmindResolver-CXYXXdul.js +99 -0
- package/dist/maxmindResolver-CXYXXdul.js.map +1 -0
- package/dist/presets-CBfq_uJX.d.ts +38 -0
- package/dist/readForWidgetRealtime-D1BD37ST.d.ts +32 -0
- package/dist/series-zytbzPoc.js +17 -0
- package/dist/series-zytbzPoc.js.map +1 -0
- package/dist/server-Cuvhgz-S.js +492 -0
- package/dist/server-Cuvhgz-S.js.map +1 -0
- package/dist/testing/memoryAdapter.d.ts +16 -0
- package/dist/testing/memoryAdapter.js +98 -0
- package/dist/testing/memoryAdapter.js.map +1 -0
- package/dist/translations-keiKtSjF.js +77 -0
- package/dist/translations-keiKtSjF.js.map +1 -0
- package/package.json +156 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# @10x-media/analytics
|
|
2
|
+
|
|
3
|
+
## 0.1.0-beta.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Add four breakdown dashboard widgets (Top pages, Top sources, Devices, Countries) that rank one metric by a dimension as a dependency-free bar list, exported as the shared `BarList` primitive from `@10x-media/analytics/client`. The native engine now captures `source` (derived from the referrer) and `device` (classified from the user-agent) alongside page and country, so all four breakdowns are native-backed. Each breakdown widget is capability-gated on its dimension, so providers that do not report a dimension simply do not register that widget.
|
|
8
|
+
|
|
9
|
+
- Redesign the dashboard widget charts. The trend widget is now a gradient area chart with a monotone-cubic curve, gridlines, dots, timeframe-aware x-axis labels (weekdays for a 7-day range, dates for a month, months for a year), and a hover tooltip. The breakdown widgets render shadcn-style filled bars with the label inside the bar, the value outside, and a hover tooltip. Series colors use overridable `--analytics-chart-1` / `--analytics-chart-2` tokens (no more disabled-gray). Every widget gains an editable title with its sensible default shown as the field's placeholder. All hand-rolled SVG and CSS with Payload design tokens; no new dependencies.
|
|
10
|
+
|
|
11
|
+
- Add per-document binding and portable, read-only display fields. Bind any URL-bearing collection with a `path` resolver (or `pathField` fallback), then place `analyticsStat`, `analyticsStatRow`, `analyticsFields`, or the `analyticsTab` preset explicitly on your collections. Fields surface per-document metrics through the surfacing engine, are capability-gated against the active adapter, and inject nothing by default (sidebar placement is opt-in). Display components ship under the new `@10x-media/analytics/rsc` subpath.
|
|
12
|
+
|
|
13
|
+
- Adapter contract and surfacing engine foundation: the unified `AnalyticsAdapter` interface with capability flags, a `payload.kv`-cached read engine (request coalescing, bounded queue, exponential backoff, `expiresAt` TTL), the adapter registry and plugin factory, and an in-memory testing adapter.
|
|
14
|
+
|
|
15
|
+
- Add GA4 and PostHog provider adapters under the `@10x-media/analytics/adapters/ga4` and `@10x-media/analytics/adapters/posthog` subpaths, completing the Phase-1 adapter set. GA4 wraps the official `@google-analytics/data` SDK (an optional peer dependency loaded lazily, so only GA4 sites install it) and normalizes ratios and durations to the contract's percentage and millisecond units. PostHog derives web metrics with HogQL through the Query API, with US/EU Cloud and self-hosted hosts. Both implement the shared `AnalyticsAdapter` contract with per-URL queries and capability gating, and plug into the surfacing engine with no engine changes.
|
|
16
|
+
|
|
17
|
+
- Native engine: optional MaxMind GeoLite2 geo resolver with graceful degradation (empty geo when the lib or database is missing), composable geo resolvers, a `./geo` export subpath, and a configurable retention prune task for raw events.
|
|
18
|
+
|
|
19
|
+
- Native analytics engine core loop: a beacon ingestion endpoint, the events + rollups collections, cross-db atomic rollups (Mongo and Postgres), and the native() adapter (pageviews, events, avgDuration).
|
|
20
|
+
|
|
21
|
+
- Add Plausible and Umami provider adapters under the `@10x-media/analytics/adapters/plausible` and `@10x-media/analytics/adapters/umami` subpaths. Each implements the shared `AnalyticsAdapter` contract (per-URL queries, capability gating, normalized metrics) and plugs into the surfacing engine with no engine changes. Plausible uses Stats API v2 with self-hosted support; Umami supports both Cloud and self-hosted. GA4 and PostHog adapters follow in a later release.
|
|
22
|
+
|
|
23
|
+
- Provider adapters now honor `granularity: 'day'` and return a per-day series, so a trend widget backed by GA4, Plausible, PostHog, or Umami renders a real chart instead of a flat line. Range totals stay correct (distinct metrics are never summed across days). Umami's series covers pageviews and sessions; its other metrics keep a correct headline with an empty series.
|
|
24
|
+
|
|
25
|
+
- Add a realtime "active now" dashboard widget: native serves a live count of active visitors (or pageviews) in the last N minutes plus a per-minute sparkline, polled from an authenticated endpoint every 15 seconds. The widget registers only when a realtime-capable adapter is configured; providers can implement realtime later through the same capability gate.
|
|
26
|
+
|
|
27
|
+
- Add a public extension API for dashboard widgets: register your own widget with `widgets: { register: [...] }` (capability-gated, slug-validated), and build its server component from the now-public reads (`readForWidget`, `readForWidgetSeries`, `readForWidgetBreakdown`, `readForWidgetRealtime`) plus `formatMetricValue` from `@10x-media/analytics/rsc` and the chart primitives from `@10x-media/analytics/client`.
|
|
28
|
+
|
|
29
|
+
- Add a computed page-path resolver for on-document analytics fields: bind a collection with an async, request-aware `path(doc, ctx)` resolver and the field reads analytics for that path without persisting anything. Dashboard widgets gain a "Custom range" timeframe with a native date-range picker. Reads now coalesce within a UTC day, and over-long ranges are clamped to each provider's maximum lookback with a visible note.
|
|
30
|
+
|
|
31
|
+
- Add an opt-in scheduled cache-warm job. Set `cache: { warm: true }` (or `cache: { warm: { cron } }`) to register a Payload task (`analytics-warm-cache`) that pre-runs the dashboard's widget reads on a cron, deriving its targets from `admin.dashboard.defaultLayout`, so a provider-backed dashboard loads from warm `payload.kv` cache. Realtime and custom widgets are skipped; one provider failure does not abort the rest. Off by default.
|
|
32
|
+
|
|
33
|
+
- Add an opt-in sync tier. Set `sync: true` (or `sync: { cron, lookbackDays, collectionSlug, adapters }`) to register a queryable `analytics-daily` collection and a Payload task (`analytics-sync`) that, on a cron, ETLs each configured provider's last N days of daily metrics into one upserted row per `(source, date)`. The collection is queryable via Payload's APIs; native is excluded; one provider failure does not abort the rest. Off by default.
|
|
34
|
+
|
|
35
|
+
- Add a trend dashboard widget that draws a metric over time as a dependency-free SVG sparkline, backed by a new native day-granularity time-series read. The per-widget timeframe picker now offers a fuller set of relative ranges (today, last 7 days, last 30 days, last 90 days, this month, this year, last year, all time). The shared `TrendChart` primitive is exported from `@10x-media/analytics/client`. Provider adapters (Plausible, Umami, GA4, PostHog) do not yet emit time-series rows, so a trend widget pointed at a provider renders an empty line for now; the native engine is fully wired.
|
|
36
|
+
|
|
37
|
+
- Native engine now tracks unique visitors and sessions with exact cross-database distinct counting (Mongo and Postgres), plus a site-wide country breakdown dimension and a `page` breakdown for top-pages views. The seen-ledger is pruned by the retention task.
|
|
38
|
+
|
|
39
|
+
- Add dashboard widgets (Payload's experimental Modular Dashboard, PR #15700). The plugin registers capability-filtered widgets into `admin.dashboard.widgets`, starting with a configurable metric widget (pick a metric, a relative timeframe, and a data source when more than one adapter is configured) that reads through the surfacing engine. Widgets are on by default (`widgets: false` disables them, `widgets: { disabled: [...] }` drops specific slugs). Apps place widgets by spreading the exported `analyticsDefaultWidgets()` into their own `admin.dashboard.defaultLayout`; the plugin never sets `defaultLayout` itself.
|
|
40
|
+
|
|
41
|
+
- Native engine gains an opt-in in-process write buffer (`native({ buffer: true })`) that coalesces per-request event, rollup, and dedup writes into batched, per-bucket upserts to cut database round-trips under load. Off by default (writes stay synchronous and durable); `native().flush()` drains the buffer for graceful shutdown.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 10x Media GmbH
|
|
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/README.md
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# @10x-media/analytics
|
|
2
|
+
|
|
3
|
+
Adapter-based analytics for Payload v3: a unified adapter contract and a cached surfacing engine. Provider adapters (GA4, Plausible, Umami, PostHog), the native analytics engine, dashboard widgets, and portable fields land in subsequent releases.
|
|
4
|
+
|
|
5
|
+
> Status: foundation (beta). This release ships the adapter contract and the surfacing engine. It is not useful on its own yet without an adapter.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @10x-media/analytics
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { buildConfig } from 'payload'
|
|
17
|
+
import { analytics } from '@10x-media/analytics'
|
|
18
|
+
|
|
19
|
+
export default buildConfig({
|
|
20
|
+
plugins: [
|
|
21
|
+
analytics({
|
|
22
|
+
adapters: [/* one or more AnalyticsAdapter instances */],
|
|
23
|
+
}),
|
|
24
|
+
],
|
|
25
|
+
})
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Pass `false` to disable without removing the call:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
analytics(false)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## The adapter contract
|
|
35
|
+
|
|
36
|
+
Every provider and the native engine implement one `AnalyticsAdapter` interface. Author your own adapter against the published types:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import type { AnalyticsAdapter } from '@10x-media/analytics/types'
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
An adapter declares its `capabilities` (which metrics and dimensions it supports, realtime, rate limits, recommended cache TTLs). The surfacing engine reads through `payload.kv` with request coalescing, a bounded queue, and exponential backoff, so unconfigured adapters and provider outages degrade gracefully.
|
|
43
|
+
|
|
44
|
+
## Testing
|
|
45
|
+
|
|
46
|
+
`@10x-media/analytics/testing` exports `memoryAdapter()`, a deterministic in-memory adapter for tests and local development.
|
|
47
|
+
|
|
48
|
+
## Native engine (beta)
|
|
49
|
+
|
|
50
|
+
`@10x-media/analytics/adapters/native` exports `native()`, a self-hosted analytics engine that stores data inside Payload itself.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { native } from '@10x-media/analytics/adapters/native'
|
|
54
|
+
|
|
55
|
+
analytics({ adapters: [native()] })
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Registering the adapter adds three hidden collections (`analytics-events`, `analytics-rollups`, and `analytics-seen`) and a `POST /api/analytics/ingest` beacon endpoint. Events are written atomically via `$inc` (Mongo) or `ON CONFLICT DO UPDATE` (Postgres), so concurrent ingestion is safe.
|
|
59
|
+
|
|
60
|
+
**Write batching (opt-in):** by default each ingest is written synchronously before the endpoint responds. Pass `buffer: true` (or `buffer: { maxSize, maxAgeMs }`) to batch writes in memory and flush on size (default 50) or age (default 2000 ms), coalescing per-bucket upserts to cut database round-trips under load.
|
|
61
|
+
|
|
62
|
+
> Buffering trades durability for throughput: the endpoint responds before the batch is persisted, so a hard crash can lose up to `maxAgeMs` of unflushed events (the same best-effort model as Plausible and Umami). Call `native().flush()` on graceful shutdown to drain the buffer.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { native } from '@10x-media/analytics/adapters/native'
|
|
66
|
+
|
|
67
|
+
analytics({ adapters: [native({ buffer: true })] })
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Supported metrics: `pageviews`, `events`, `avgDuration`, `visitors`, `sessions`.
|
|
71
|
+
|
|
72
|
+
The native engine pre-aggregates unique visitors and sessions alongside pageviews. Distinct counts are computed exactly via a dedicated `analytics-seen` ledger and stored at every granularity they are queried (per page, site-wide, and site-wide per country), so they are read directly and never summed across the page or country breakdowns. Within a single UTC day a unique count is exact; across a multi-day range the daily counts are summed, so longer-range uniques are approximate (the same tradeoff Plausible, Fathom, and Umami make). A site-wide country breakdown dimension is available out of the box; geoless events are simply omitted from it.
|
|
73
|
+
|
|
74
|
+
**Production note (Mongo):** exact distinct counting relies on a unique index on the `analytics-seen` collection, which under concurrent ingestion must be live, so the Mongoose adapter should be configured with `ensureIndexes: true`:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { mongooseAdapter } from '@payloadcms/db-mongodb'
|
|
78
|
+
|
|
79
|
+
mongooseAdapter({ url: process.env.DATABASE_URI, ensureIndexes: true })
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
On Postgres the unique index is created by migrations, so no extra configuration is needed once migrations have run.
|
|
83
|
+
|
|
84
|
+
### Geo resolution
|
|
85
|
+
|
|
86
|
+
The native engine resolves the visitor country, region, and city from each ingest request. Resolution is layered: platform-injected headers (`x-vercel-ip-country`, `cf-ipcountry`, and friends) are checked first. MaxMind GeoLite2 is tried only when headers do not already supply a country.
|
|
87
|
+
|
|
88
|
+
**MaxMind (optional)** Pass `geoDbPath` to enable IP-level lookup:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
native({ geoDbPath: '/data/GeoLite2-City.mmdb' })
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
This requires the optional `maxmind` peer dependency and a downloaded `.mmdb` file. If the library is not installed, the file is missing or unreadable, or a lookup fails, geo resolution degrades to empty fields. A single warning is logged and ingestion continues unaffected.
|
|
95
|
+
|
|
96
|
+
**Custom geo pipeline** The `@10x-media/analytics/geo` subpath exports the building blocks for your own resolver:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import {
|
|
100
|
+
platformHeaderResolver,
|
|
101
|
+
maxmindResolver,
|
|
102
|
+
composeGeoResolvers,
|
|
103
|
+
noopResolver,
|
|
104
|
+
type GeoResolver,
|
|
105
|
+
type Geo,
|
|
106
|
+
} from '@10x-media/analytics/geo'
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Compose resolvers left-to-right; the first non-empty value wins:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
native({
|
|
113
|
+
geoResolver: composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: '...' })),
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Retention pruning
|
|
118
|
+
|
|
119
|
+
Pass `retentionDays` to register a nightly Payload task that deletes raw `analytics-events` older than N days:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
native({ retentionDays: 90 })
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The task runs at 03:00 UTC. If `retentionDays` is not set, no task is registered and raw events are kept indefinitely.
|
|
126
|
+
|
|
127
|
+
## Document binding
|
|
128
|
+
|
|
129
|
+
Bind any URL-bearing collection to its analytics with a per-collection path resolver. Binding a collection registers the resolver only; it renders no fields and injects nothing.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
analytics({
|
|
133
|
+
adapters: [native()],
|
|
134
|
+
collections: {
|
|
135
|
+
pages: {
|
|
136
|
+
path: (doc) => (doc.slug ? `/${doc.slug}` : null), // primary resolver
|
|
137
|
+
// pathField: 'permalink', // optional explicit-field fallback
|
|
138
|
+
// hostname: 'example.com', // optional, for multi-domain
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
})
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The resolver returns the document's URL pathname (or `null` for an unsaved document). `pathField` is a fallback used only when the resolver is absent or returns `null`; a binding must define at least one of the two.
|
|
145
|
+
|
|
146
|
+
### Computed page paths
|
|
147
|
+
|
|
148
|
+
The `path` resolver is a plain function with the signature `(doc, ctx) => string | null | Promise<string | null>`. It receives `ctx.req` (a `PayloadRequest`), so it can look up related documents:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
analytics({
|
|
152
|
+
adapters: [native()],
|
|
153
|
+
collections: {
|
|
154
|
+
posts: {
|
|
155
|
+
path: async (doc, ctx) => {
|
|
156
|
+
if (!doc.slug) return null
|
|
157
|
+
// look up a related category to build the path
|
|
158
|
+
const cat = await ctx.req.payload.findByID({
|
|
159
|
+
collection: 'categories',
|
|
160
|
+
id: doc.category as string,
|
|
161
|
+
req: ctx.req,
|
|
162
|
+
})
|
|
163
|
+
return `/${cat.slug}/${doc.slug}`
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
})
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Nothing is persisted - the path is computed at read time and memoized once per request. Keep resolvers cheap: they may be called for many documents in a single list request. If you must look up related docs, pass `req` so Payload dedupes calls through its request data loader. When the path is already stored on the document, `pathField` is the zero-cost alternative.
|
|
171
|
+
|
|
172
|
+
## Portable display fields
|
|
173
|
+
|
|
174
|
+
Read-only fields you place explicitly on your own collections. Nothing is auto-injected, and nothing lands in the sidebar unless you ask for it. Each field surfaces metrics for the document's bound path through the surfacing engine, and auto-disables when the active adapter cannot supply the requested metric.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
import { analyticsStat, analyticsStatRow, analyticsFields, analyticsTab } from '@10x-media/analytics'
|
|
178
|
+
|
|
179
|
+
fields: [
|
|
180
|
+
analyticsStat({ metric: 'pageviews' }), // a single stat
|
|
181
|
+
analyticsStat({ metric: 'visitors', position: 'sidebar' }), // opt in to the sidebar
|
|
182
|
+
analyticsStatRow({ metrics: ['pageviews', 'visitors', 'avgDuration'] }), // a row of stats
|
|
183
|
+
...analyticsFields({ metrics: ['pageviews', 'sessions'] }), // several individual fields
|
|
184
|
+
analyticsTab(), // a ready-made "Analytics" tab
|
|
185
|
+
]
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Every factory accepts an optional `timeframe` (a relative preset: `today`, `last7days`, `last30days`, `last90days`, `thisMonth`, `thisYear`; default `last30days`) and `adapter` (an adapter id, when more than one is configured). The native engine backs `pageviews`, `visitors`, `sessions`, `events`, and `avgDuration`; fields requesting anything else render a muted "not available" state until a provider that supports it is configured.
|
|
189
|
+
|
|
190
|
+
The display components are server components; add `@10x-media/analytics/rsc` to your Payload import map (run `payload generate:importmap`) so the admin can resolve them.
|
|
191
|
+
|
|
192
|
+
## Dashboard widgets
|
|
193
|
+
|
|
194
|
+
The plugin registers capability-filtered widgets into `admin.dashboard.widgets`. A widget that requires a metric no configured adapter supports is not registered, so dead surfaces never appear.
|
|
195
|
+
|
|
196
|
+
Widgets are enabled by default. Disable them entirely with `widgets: false`, or drop specific slugs with `widgets: { disabled: ['analytics-metric'] }`.
|
|
197
|
+
|
|
198
|
+
The widgets that ship today: a **metric** widget (a single headline number), a **trend** widget (a gradient area chart of one metric over time, with timeframe-aware axis labels [weekdays for a 7-day range, months for a year] and a hover tooltip), four **breakdown** widgets that rank one metric by a dimension as a filled bar list (**Top pages**, **Top sources**, **Devices**, **Countries**), and a **realtime** widget that shows a live "active now" count (active visitors or pageviews in the last few minutes) with a per-minute sparkline. The realtime widget polls an authenticated `GET /api/analytics/realtime` endpoint every 15 seconds, so the number updates without reloading the dashboard. It is native-backed and registers only when a realtime-capable adapter is configured; external providers can implement realtime later through the same capability gate. Each widget is configurable per instance: an editable title (a sensible default shows as the field's placeholder), a metric, a relative timeframe (today, last 7 days, last 30 days, last 90 days, this month, this year, last year, or all time), and (when more than one adapter is configured) a data source. A widget whose dimension no configured adapter supports is not registered, so a provider that does not report devices simply has no Devices widget.
|
|
199
|
+
|
|
200
|
+
The Timeframe selector also includes a **Custom range** option that reveals a native date-range picker, letting you query any arbitrary from/to window. For external providers that enforce a maximum lookback (for example GA4 or Plausible tiers), a range that exceeds the limit is automatically narrowed to the provider maximum and the widget shows a short note below the caption so the narrowing is visible.
|
|
201
|
+
|
|
202
|
+
The charts are dependency-free SVG and CSS themed with Payload's design tokens. The series color comes from `--analytics-chart-1`, which a consuming app can override in its admin stylesheet.
|
|
203
|
+
|
|
204
|
+
Trend widgets render a real daily series for every provider. GA4, Plausible, and PostHog cover all of their supported metrics; Umami's series covers pageviews and sessions (its API has no per-day source for visitors, bounce rate, or average duration, so a trend on those metrics shows a correct headline with an empty series). The headline total is always range-correct: distinct metrics like visitors are never summed across days.
|
|
205
|
+
|
|
206
|
+
A plugin must never set `admin.dashboard.defaultLayout` (Payload applies it with `??=`; a setter would clobber the app's own layout). Instead, the app places widgets by spreading the exported helper into its own config:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
import { analytics, analyticsDefaultWidgets } from '@10x-media/analytics'
|
|
210
|
+
import { native } from '@10x-media/analytics/adapters/native'
|
|
211
|
+
|
|
212
|
+
export default buildConfig({
|
|
213
|
+
admin: {
|
|
214
|
+
dashboard: { defaultLayout: [...analyticsDefaultWidgets()] },
|
|
215
|
+
},
|
|
216
|
+
plugins: [analytics({ adapters: [native()] })],
|
|
217
|
+
})
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`analyticsDefaultWidgets()` returns a wide pageviews trend plus two small metric widgets (pageviews and visitors), all over the last 30 days. If you set `widgets: false`, do not spread it into your layout; its instances would then reference unregistered widgets.
|
|
221
|
+
|
|
222
|
+
> The Modular Dashboard is an experimental Payload feature (PR #15700). After installing, run `payload generate:importmap` so the widget's server component resolves in the admin.
|
|
223
|
+
|
|
224
|
+
### Custom widgets
|
|
225
|
+
|
|
226
|
+
An app can register its own widgets alongside the built-in ones. Each entry is capability-gated by `requires` and slug-validated; the `analytics-` prefix is reserved for built-ins.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
analytics({
|
|
230
|
+
adapters: [native()],
|
|
231
|
+
widgets: {
|
|
232
|
+
register: [
|
|
233
|
+
{
|
|
234
|
+
slug: 'myapp-top-sources',
|
|
235
|
+
component: '/components/TopSourcesWidget#default',
|
|
236
|
+
label: 'Top sources',
|
|
237
|
+
requires: { dimensions: ['source'] },
|
|
238
|
+
},
|
|
239
|
+
],
|
|
240
|
+
},
|
|
241
|
+
})
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Build the widget as a server component. Import reads from `@10x-media/analytics/rsc` and chart primitives from `@10x-media/analytics/client`:
|
|
245
|
+
|
|
246
|
+
```tsx
|
|
247
|
+
import { BarList } from '@10x-media/analytics/client'
|
|
248
|
+
import { formatMetricValue, readForWidgetBreakdown } from '@10x-media/analytics/rsc'
|
|
249
|
+
import type { WidgetServerProps } from 'payload'
|
|
250
|
+
|
|
251
|
+
export default async function TopSourcesWidget(props: WidgetServerProps) {
|
|
252
|
+
const locale = props.req.i18n.language ?? 'en-US'
|
|
253
|
+
const result = await readForWidgetBreakdown({
|
|
254
|
+
req: props.req,
|
|
255
|
+
metric: 'pageviews',
|
|
256
|
+
dimension: 'source',
|
|
257
|
+
timeframe: 'last30days',
|
|
258
|
+
limit: 5,
|
|
259
|
+
now: new Date(),
|
|
260
|
+
})
|
|
261
|
+
if (result.status !== 'ok') return <span>No data</span>
|
|
262
|
+
return (
|
|
263
|
+
<BarList
|
|
264
|
+
data={result.rows.map((r) => ({
|
|
265
|
+
label: r.label,
|
|
266
|
+
value: r.value,
|
|
267
|
+
display: formatMetricValue('pageviews', r.value, locale),
|
|
268
|
+
}))}
|
|
269
|
+
emptyLabel="No data"
|
|
270
|
+
/>
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
After registering, run `payload generate:importmap` so the admin can resolve the component. The widget only appears when a configured adapter satisfies its `requires` gate.
|
|
276
|
+
|
|
277
|
+
## Sync tier
|
|
278
|
+
|
|
279
|
+
The cache and warm tiers keep `payload.kv` hot, but that store is ephemeral. The **sync tier** persists each configured **provider** adapter's daily metrics into a durable, queryable Payload collection, so you can query your third-party analytics with Payload's own APIs (`find`/`where`/REST/GraphQL, relationships, custom reports) without calling the provider live:
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
analytics({
|
|
283
|
+
adapters: [plausible({ /* ... */ })],
|
|
284
|
+
sync: true, // default: every 6h, last 3 days, into the `analytics-daily` collection
|
|
285
|
+
})
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Customize the schedule, window, collection, or which providers sync:
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
analytics({
|
|
292
|
+
adapters: [/* ... */],
|
|
293
|
+
sync: { cron: '0 4 * * *', lookbackDays: 7, collectionSlug: 'site-metrics', adapters: ['plausible'] },
|
|
294
|
+
})
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
When enabled, the plugin registers a queryable collection (default `analytics-daily`) and a Payload task (`analytics-sync`). On its cron the task reads each provider's last `lookbackDays` of **daily** metrics through the surfacing engine and upserts one row per `(source, date)` (idempotent via a unique `source + date` index; re-running refreshes recent days as provider data finalizes). Reads go through the surfacing cache, so persisted rows reflect cached values up to the aggregate TTL; keep `cache.ttl.aggregate` below your sync interval for the freshest data. Rows are read-only in the admin (the job writes them); metrics a provider does not report are left null. The native engine is excluded, since its data already lives in `analytics-rollups`. One provider failure is logged and does not abort the rest. Run it on demand with `payload.jobs.queue({ task: 'analytics-sync' })`.
|
|
298
|
+
|
|
299
|
+
Sync is **off by default** and, like warming, needs Payload's jobs runner enabled (cron `autoRun` or an external scheduler) for the schedule to fire. Daily breakdowns and serving widgets from the synced collection are planned follow-ups.
|
|
300
|
+
|
|
301
|
+
## Scheduled cache warming
|
|
302
|
+
|
|
303
|
+
Surfacing reads are cached in `payload.kv`, keyed per adapter + query and snapped to the UTC day. For a provider-backed dashboard (GA4, Plausible, Umami, PostHog), the first load after a cache entry expires pays a cold provider round-trip. Opt into a background job that pre-runs the dashboard's reads on a cron so that first load is a warm cache hit:
|
|
304
|
+
|
|
305
|
+
```ts
|
|
306
|
+
analytics({
|
|
307
|
+
adapters: [plausible({ /* ... */ })],
|
|
308
|
+
cache: { warm: true }, // default cron: every 30 minutes
|
|
309
|
+
})
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Pass a cron to change the cadence:
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
analytics({
|
|
316
|
+
adapters: [/* ... */],
|
|
317
|
+
cache: { warm: { cron: '0 * * * *' } }, // hourly
|
|
318
|
+
})
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
The job registers a Payload task (`analytics-warm-cache`) whose work is derived from your `admin.dashboard.defaultLayout`: each metric, trend, and breakdown widget becomes one warm read for the same metric, timeframe, and (in multi-provider setups) data source it renders. The realtime widget is skipped (its short-lived count is kept warm by the live poller), as is any custom widget whose read shape the plugin does not know. One provider failure is logged and does not abort the rest.
|
|
322
|
+
|
|
323
|
+
Warming is **off by default** because it spends provider API quota on a schedule. It pays off most when the dashboard is provider-backed; the native engine is fast enough that warming it is harmless but low value. The task runs through Payload's jobs runner, so your app must have that runner enabled (cron `autoRun`, or an external scheduler invoking the queue) for the schedule to fire.
|
|
324
|
+
|
|
325
|
+
## Provider adapters
|
|
326
|
+
|
|
327
|
+
Third-party providers implement the same `AnalyticsAdapter` contract and ship as code-split subpaths, so a site installs only what it uses.
|
|
328
|
+
|
|
329
|
+
### Plausible
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { plausible } from '@10x-media/analytics/adapters/plausible'
|
|
333
|
+
|
|
334
|
+
analytics({ adapters: [plausible({ siteId: 'example.com', apiKey: process.env.PLAUSIBLE_API_KEY! })] })
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Uses the Stats API v2 (`POST /api/v2/query`). Pass `host` for a self-hosted Community Edition instance. Supported metrics: pageviews, visitors, visits, sessions, bounceRate, avgDuration, events, scrollDepth, revenue. Durations are normalized to milliseconds.
|
|
338
|
+
|
|
339
|
+
### Umami
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
import { umami } from '@10x-media/analytics/adapters/umami'
|
|
343
|
+
|
|
344
|
+
// Umami Cloud
|
|
345
|
+
analytics({ adapters: [umami({ websiteId: 'xxxx', apiKey: process.env.UMAMI_API_KEY! })] })
|
|
346
|
+
|
|
347
|
+
// Self-hosted (token from POST /api/auth/login)
|
|
348
|
+
analytics({ adapters: [umami({ websiteId: 'xxxx', token: process.env.UMAMI_TOKEN!, host: 'https://analytics.example.com/api' })] })
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
Supported metrics: pageviews, visitors, visits, sessions, bounceRate (derived), avgDuration (derived). A `page` dimension breakdown maps to Umami's `/metrics?type=url`.
|
|
352
|
+
|
|
353
|
+
### GA4
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
import { ga4 } from '@10x-media/analytics/adapters/ga4'
|
|
357
|
+
|
|
358
|
+
analytics({
|
|
359
|
+
adapters: [
|
|
360
|
+
ga4({
|
|
361
|
+
propertyId: '123456789',
|
|
362
|
+
credentials: {
|
|
363
|
+
client_email: process.env.GA4_CLIENT_EMAIL!,
|
|
364
|
+
private_key: process.env.GA4_PRIVATE_KEY!,
|
|
365
|
+
},
|
|
366
|
+
}),
|
|
367
|
+
],
|
|
368
|
+
})
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
Uses the GA4 Data API (`runReport`) via the official `@google-analytics/data` SDK, declared as an **optional peer dependency** and loaded lazily, so only GA4 sites install it (`pnpm add @google-analytics/data`). Supported metrics: pageviews, visitors, visits, sessions, bounceRate, avgDuration, events, conversions, revenue. Durations are normalized to milliseconds and bounce rate to a percentage. GA4 bills a token quota, so the adapter recommends a long cache TTL.
|
|
372
|
+
|
|
373
|
+
### PostHog
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { posthog } from '@10x-media/analytics/adapters/posthog'
|
|
377
|
+
|
|
378
|
+
analytics({
|
|
379
|
+
adapters: [
|
|
380
|
+
posthog({ projectId: '123', apiKey: process.env.POSTHOG_API_KEY! }),
|
|
381
|
+
],
|
|
382
|
+
})
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
Derives web metrics with HogQL through the Query API. Pass `host` for EU Cloud (`https://eu.posthog.com`) or a self-hosted instance; US Cloud is the default. The API key is a personal API key with the "Query Read" scope. Supported metrics: pageviews, visitors, visits, sessions. A `page` dimension returns a top-pages breakdown.
|
|
386
|
+
|
|
387
|
+
All provider adapters auto-disable any surface whose required metric they do not provide, and degrade to an empty state when unconfigured (no network calls).
|