@10x-media/analytics 0.1.0-beta.0 → 0.1.0-beta.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/CHANGELOG.md +127 -0
- package/README.md +38 -357
- package/dist/adapters/ga4/ga4.d.ts +20 -0
- package/dist/adapters/ga4/ga4.js +187 -0
- package/dist/adapters/ga4/ga4.js.map +1 -0
- package/dist/{fetchJson-DZb2_Puj.js → adapters/http/fetchJson.js} +2 -2
- package/dist/adapters/http/fetchJson.js.map +1 -0
- package/dist/adapters/plausible/plausible.d.ts +15 -0
- package/dist/adapters/plausible/plausible.js +148 -0
- package/dist/adapters/plausible/plausible.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +23 -0
- package/dist/adapters/posthog/posthog.js +132 -0
- package/dist/adapters/posthog/posthog.js.map +1 -0
- package/dist/{series-zytbzPoc.js → adapters/series.js} +2 -2
- package/dist/adapters/series.js.map +1 -0
- package/dist/adapters/umami/umami.d.ts +18 -0
- package/dist/adapters/umami/umami.js +139 -0
- package/dist/{exports/adapters → adapters/umami}/umami.js.map +1 -1
- package/dist/binding/resolvePath.js +61 -0
- package/dist/binding/resolvePath.js.map +1 -0
- package/dist/binding/types.d.ts +55 -0
- package/dist/charts/BarList.d.ts +20 -0
- package/dist/charts/BarList.js +73 -0
- package/dist/charts/BarList.js.map +1 -0
- package/dist/charts/TrendChart.d.ts +25 -0
- package/dist/charts/TrendChart.js +195 -0
- package/dist/charts/TrendChart.js.map +1 -0
- package/dist/charts/bars.d.ts +9 -0
- package/dist/charts/bars.js +19 -0
- package/dist/charts/bars.js.map +1 -0
- package/dist/charts/bucket.js +86 -0
- package/dist/charts/bucket.js.map +1 -0
- package/dist/charts/spline.js +84 -0
- package/dist/charts/spline.js.map +1 -0
- package/dist/charts/styles.js +42 -0
- package/dist/charts/styles.js.map +1 -0
- package/dist/core/cacheKey.js +28 -0
- package/dist/core/cacheKey.js.map +1 -0
- package/dist/core/capabilities.d.ts +12 -0
- package/dist/core/capabilities.js +12 -0
- package/dist/core/capabilities.js.map +1 -0
- package/dist/{contract-CWZPKWuR.d.ts → core/contract.d.ts} +42 -5
- package/dist/core/contract.js +10 -0
- package/dist/core/contract.js.map +1 -0
- package/dist/core/granularity.js +17 -0
- package/dist/core/granularity.js.map +1 -0
- package/dist/core/options.d.ts +140 -0
- package/dist/core/options.js +114 -0
- package/dist/core/options.js.map +1 -0
- package/dist/core/registry.js +24 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/scopedRead.js +57 -0
- package/dist/core/scopedRead.js.map +1 -0
- package/dist/exports/adapters/ga4.d.ts +2 -20
- package/dist/exports/adapters/ga4.js +1 -176
- package/dist/exports/adapters/native.d.ts +2 -22
- package/dist/exports/adapters/native.js +1 -848
- package/dist/exports/adapters/plausible.d.ts +2 -15
- package/dist/exports/adapters/plausible.js +1 -142
- package/dist/exports/adapters/posthog.d.ts +2 -17
- package/dist/exports/adapters/posthog.js +1 -118
- package/dist/exports/adapters/umami.d.ts +2 -18
- package/dist/exports/adapters/umami.js +1 -138
- package/dist/exports/client.d.ts +5 -77
- package/dist/exports/client.js +4 -386
- package/dist/exports/geo.d.ts +4 -19
- package/dist/exports/geo.js +3 -1
- package/dist/exports/i18n.d.ts +3 -63
- package/dist/exports/i18n.js +2 -2
- package/dist/exports/next.d.ts +2 -0
- package/dist/exports/next.js +2 -0
- package/dist/exports/rsc.d.ts +16 -120
- package/dist/exports/rsc.js +14 -598
- package/dist/exports/types.d.ts +6 -4
- package/dist/exports/types.js +2 -1
- package/dist/fields/AnalyticsPanelClient.js +193 -0
- package/dist/fields/AnalyticsPanelClient.js.map +1 -0
- package/dist/fields/AnalyticsPanelField.d.ts +28 -0
- package/dist/fields/AnalyticsPanelField.js +54 -0
- package/dist/fields/AnalyticsPanelField.js.map +1 -0
- package/dist/fields/AnalyticsStatField.d.ts +31 -0
- package/dist/fields/AnalyticsStatField.js +104 -0
- package/dist/fields/AnalyticsStatField.js.map +1 -0
- package/dist/fields/dateRange/field.js +55 -0
- package/dist/fields/dateRange/field.js.map +1 -0
- package/dist/fields/dateRange/styles.js +23 -0
- package/dist/fields/dateRange/styles.js.map +1 -0
- package/dist/fields/dateRange/types.d.ts +11 -0
- package/dist/fields/dateRange/ui.d.ts +9 -0
- package/dist/fields/dateRange/ui.js +373 -0
- package/dist/fields/dateRange/ui.js.map +1 -0
- package/dist/fields/emptyState.js +46 -0
- package/dist/fields/emptyState.js.map +1 -0
- package/dist/fields/factories.d.ts +60 -0
- package/dist/fields/factories.js +94 -0
- package/dist/fields/factories.js.map +1 -0
- package/dist/fields/format.d.ts +7 -0
- package/dist/fields/format.js +22 -0
- package/dist/fields/format.js.map +1 -0
- package/dist/fields/readForDocument.d.ts +57 -0
- package/dist/fields/readForDocument.js +147 -0
- package/dist/fields/readForDocument.js.map +1 -0
- package/dist/index.d.ts +18 -3
- package/dist/index.js +83 -1028
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +101 -0
- package/dist/native/collections/events.js.map +1 -0
- package/dist/native/collections/rollups.js +115 -0
- package/dist/native/collections/rollups.js.map +1 -0
- package/dist/native/collections/seen.js +47 -0
- package/dist/native/collections/seen.js.map +1 -0
- package/dist/native/geo/composeGeoResolvers.d.ts +7 -0
- package/dist/native/geo/composeGeoResolvers.js +14 -0
- package/dist/native/geo/composeGeoResolvers.js.map +1 -0
- package/dist/{geoResolver-CasIa4T9.d.ts → native/geo/geoResolver.d.ts} +2 -2
- package/dist/native/geo/geoResolver.js +11 -0
- package/dist/native/geo/geoResolver.js.map +1 -0
- package/dist/native/geo/maxmindResolver.d.ts +16 -0
- package/dist/native/geo/maxmindResolver.js +55 -0
- package/dist/native/geo/maxmindResolver.js.map +1 -0
- package/dist/native/ingest/device.js +15 -0
- package/dist/native/ingest/device.js.map +1 -0
- package/dist/native/ingest/endpoint.js +30 -0
- package/dist/native/ingest/endpoint.js.map +1 -0
- package/dist/native/ingest/flushBatch.js +69 -0
- package/dist/native/ingest/flushBatch.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.js +39 -0
- package/dist/native/ingest/normalizeEvent.js.map +1 -0
- package/dist/native/ingest/salt.js +14 -0
- package/dist/native/ingest/salt.js.map +1 -0
- package/dist/native/ingest/source.js +22 -0
- package/dist/native/ingest/source.js.map +1 -0
- package/dist/native/ingest/visitorHash.js +12 -0
- package/dist/native/ingest/visitorHash.js.map +1 -0
- package/dist/native/ingest/writeBuffer.js +55 -0
- package/dist/native/ingest/writeBuffer.js.map +1 -0
- package/dist/native/ingest/writeEvent.js +14 -0
- package/dist/native/ingest/writeEvent.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +22 -0
- package/dist/native/nativeAdapter.js +216 -0
- package/dist/native/nativeAdapter.js.map +1 -0
- package/dist/native/realtime/buildRealtime.js +53 -0
- package/dist/native/realtime/buildRealtime.js.map +1 -0
- package/dist/native/retention/pruneTask.js +29 -0
- package/dist/native/retention/pruneTask.js.map +1 -0
- package/dist/native/rollupAcc.js +53 -0
- package/dist/native/rollupAcc.js.map +1 -0
- package/dist/native/rollups/applyDistinctDeltas.js +9 -0
- package/dist/native/rollups/applyDistinctDeltas.js.map +1 -0
- package/dist/native/rollups/bumpRollup.js +52 -0
- package/dist/native/rollups/bumpRollup.js.map +1 -0
- package/dist/native/rollups/deltas.js +31 -0
- package/dist/native/rollups/deltas.js.map +1 -0
- package/dist/native/rollups/insertIfNew.js +19 -0
- package/dist/native/rollups/insertIfNew.js.map +1 -0
- package/dist/next/posthogProxyRewrites.d.ts +36 -0
- package/dist/next/posthogProxyRewrites.js +50 -0
- package/dist/next/posthogProxyRewrites.js.map +1 -0
- package/dist/plugin/documentEndpoint.js +80 -0
- package/dist/plugin/documentEndpoint.js.map +1 -0
- package/dist/plugin/paths.js +11 -0
- package/dist/plugin/paths.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +36 -0
- package/dist/plugin/realtimeEndpoint.js.map +1 -0
- package/dist/plugin/registerTranslations.js +19 -0
- package/dist/plugin/registerTranslations.js.map +1 -0
- package/dist/plugin/runtime.js +21 -0
- package/dist/plugin/runtime.js.map +1 -0
- package/dist/plugin/warmTask.js +165 -0
- package/dist/plugin/warmTask.js.map +1 -0
- package/dist/providers/collection.js +159 -0
- package/dist/providers/collection.js.map +1 -0
- package/dist/providers/factory.js +62 -0
- package/dist/providers/factory.js.map +1 -0
- package/dist/providers/resolver.js +67 -0
- package/dist/providers/resolver.js.map +1 -0
- package/dist/providers/secrets.js +27 -0
- package/dist/providers/secrets.js.map +1 -0
- package/dist/surfacing/cacheStore.js +26 -0
- package/dist/surfacing/cacheStore.js.map +1 -0
- package/dist/surfacing/coalesce.js +15 -0
- package/dist/surfacing/coalesce.js.map +1 -0
- package/dist/surfacing/engine.js +63 -0
- package/dist/surfacing/engine.js.map +1 -0
- package/dist/surfacing/queue.js +44 -0
- package/dist/surfacing/queue.js.map +1 -0
- package/dist/sync/collection.js +70 -0
- package/dist/sync/collection.js.map +1 -0
- package/dist/sync/syncTask.js +123 -0
- package/dist/sync/syncTask.js.map +1 -0
- package/dist/testing/memoryAdapter.d.ts +1 -1
- package/dist/timeframe/presets.d.ts +6 -0
- package/dist/timeframe/presets.js +59 -0
- package/dist/timeframe/presets.js.map +1 -0
- package/dist/timeframe/tz.js +110 -0
- package/dist/timeframe/tz.js.map +1 -0
- package/dist/translations/de.js +78 -0
- package/dist/translations/de.js.map +1 -0
- package/dist/{translations-keiKtSjF.js → translations/en.js} +30 -25
- package/dist/translations/en.js.map +1 -0
- package/dist/translations/index.d.ts +15 -0
- package/dist/translations/index.js +30 -0
- package/dist/translations/index.js.map +1 -0
- package/dist/translations/keys.d.ts +81 -0
- package/dist/{keys-DEqL4LOT.js → translations/keys.js} +29 -5
- package/dist/translations/keys.js.map +1 -0
- package/dist/translations/metricKeys.js +28 -0
- package/dist/translations/metricKeys.js.map +1 -0
- package/dist/translations/server.js +13 -0
- package/dist/translations/server.js.map +1 -0
- package/dist/translations/useTranslation.js +12 -0
- package/dist/translations/useTranslation.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +7 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js +85 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +7 -0
- package/dist/widgets/AnalyticsMetricWidget.js +89 -0
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -0
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +7 -0
- package/dist/widgets/AnalyticsRealtimeWidget.js +64 -0
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -0
- package/dist/widgets/AnalyticsTrendWidget.d.ts +7 -0
- package/dist/widgets/AnalyticsTrendWidget.js +99 -0
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -0
- package/dist/widgets/ComparisonDelta.js +83 -0
- package/dist/widgets/ComparisonDelta.js.map +1 -0
- package/dist/widgets/RealtimeCounter.d.ts +19 -0
- package/dist/widgets/RealtimeCounter.js +76 -0
- package/dist/widgets/RealtimeCounter.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +29 -0
- package/dist/widgets/breakdownTypes.js.map +1 -0
- package/dist/widgets/cardChrome.d.ts +8 -0
- package/dist/widgets/cardChrome.js +22 -0
- package/dist/widgets/cardChrome.js.map +1 -0
- package/dist/widgets/comparison.js +43 -0
- package/dist/widgets/comparison.js.map +1 -0
- package/dist/widgets/customWidget.d.ts +20 -0
- package/dist/widgets/customWidget.js +30 -0
- package/dist/widgets/customWidget.js.map +1 -0
- package/dist/widgets/defaults.d.ts +12 -0
- package/dist/widgets/defaults.js +72 -0
- package/dist/widgets/defaults.js.map +1 -0
- package/dist/widgets/range.js +28 -0
- package/dist/widgets/range.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +31 -0
- package/dist/widgets/readForWidget.js +72 -0
- package/dist/widgets/readForWidget.js.map +1 -0
- package/dist/widgets/readForWidgetBreakdown.d.ts +38 -0
- package/dist/widgets/readForWidgetBreakdown.js +80 -0
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -0
- package/dist/{readForWidgetRealtime-D1BD37ST.d.ts → widgets/readForWidgetRealtime.d.ts} +5 -3
- package/dist/widgets/readForWidgetRealtime.js +63 -0
- package/dist/widgets/readForWidgetRealtime.js.map +1 -0
- package/dist/widgets/readForWidgetSeries.d.ts +44 -0
- package/dist/widgets/readForWidgetSeries.js +117 -0
- package/dist/widgets/readForWidgetSeries.js.map +1 -0
- package/dist/widgets/realtimePoll.js +26 -0
- package/dist/widgets/realtimePoll.js.map +1 -0
- package/dist/widgets/registerWidgets.js +228 -0
- package/dist/widgets/registerWidgets.js.map +1 -0
- package/dist/widgets/types.js +13 -0
- package/dist/widgets/types.js.map +1 -0
- package/package.json +19 -5
- package/dist/RealtimeCounter-BJrjMPSa.js +0 -473
- package/dist/RealtimeCounter-BJrjMPSa.js.map +0 -1
- package/dist/dist-B6HruP5v.js +0 -4731
- package/dist/dist-B6HruP5v.js.map +0 -1
- package/dist/exports/adapters/ga4.js.map +0 -1
- package/dist/exports/adapters/native.js.map +0 -1
- package/dist/exports/adapters/plausible.js.map +0 -1
- package/dist/exports/adapters/posthog.js.map +0 -1
- package/dist/exports/client.js.map +0 -1
- package/dist/exports/rsc.js.map +0 -1
- package/dist/fetchJson-DZb2_Puj.js.map +0 -1
- package/dist/index-CZdCT0WJ.d.ts +0 -98
- package/dist/keys-DEqL4LOT.js.map +0 -1
- package/dist/lib-CE5x1zLQ.js +0 -1058
- package/dist/lib-CE5x1zLQ.js.map +0 -1
- package/dist/maxmindResolver-CXYXXdul.js +0 -99
- package/dist/maxmindResolver-CXYXXdul.js.map +0 -1
- package/dist/presets-CBfq_uJX.d.ts +0 -38
- package/dist/series-zytbzPoc.js.map +0 -1
- package/dist/server-Cuvhgz-S.js +0 -492
- package/dist/server-Cuvhgz-S.js.map +0 -1
- package/dist/translations-keiKtSjF.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,132 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 0.1.0-beta.2
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Add period-over-period comparison to the metric and trend widgets.
|
|
8
|
+
|
|
9
|
+
When the active adapter declares `capabilities.comparison`, the widget read helpers also fetch (in parallel with the current window) the same count of whole reporting-timezone days immediately preceding the current window and return the previous value alongside the current one. The metric and trend widgets render a colored delta (up/down arrow with the percentage change) and a "vs. previous period" caption; metrics where lower is better (bounce rate) invert the coloring, and `allTime` never compares. The comparison is capability-gated, so adapters that cannot answer a second window omit it entirely and existing installs are unchanged; `widgets: { comparison: false }` skips the previous-window read.
|
|
10
|
+
|
|
11
|
+
The previous window aligns to whole days in the reporting timezone so day-stamped rollup stores never lose their first day to a mid-day window start, and every comparison string routes through the typed `keys.ts` translations so it is fully localizable.
|
|
12
|
+
|
|
13
|
+
- Ship built-in German (`de`) translations alongside English. All admin strings (metrics, widgets, timeframes, provider fields, comparison captions) are covered; a project `translations` override still wins per key.
|
|
14
|
+
|
|
15
|
+
- Interactive per-document analytics panel and an authenticated document read endpoint.
|
|
16
|
+
|
|
17
|
+
`analyticsTab` now renders an interactive panel by default: metric cards with period-over-period deltas (capability-gated, mirroring the widgets), a daily trend chart for the first metric, and a timeframe picker that refetches in place. Reads go through the new `GET /api/analytics/document` endpoint, which whitelists timeframes/metrics and enforces read access on the target document before answering, so analytics never leak for content the requester cannot see. Pass `interactive: false` for the previous static stats row. `readForField` (now exported from `/rsc` with `compare`, `series`, and `range` options) backs both paths.
|
|
18
|
+
|
|
19
|
+
Widget config select fields carry `isClearable: false` (required metric/timeframe and the always-present data source/window have no meaningful cleared state), select option labels ship as static locale maps so `filterOptions` results survive form-state serialization, and analytics display fields no longer surface as empty list-view columns.
|
|
20
|
+
|
|
21
|
+
The sync tier's `analytics-daily` collection is now hidden from the admin nav by default (it stays fully API-queryable); pass `sync: { hidden: false }` to surface it.
|
|
22
|
+
|
|
23
|
+
The plugin now installs its runtime before the app's own `onInit` runs, so consumer init code (seeding, warming, sync passes) can already read through the plugin; custom widget authors also get the exported `widgetCardStyle` / `widgetLabelStyle` chrome.
|
|
24
|
+
|
|
25
|
+
- Fixes and improvements across widgets, caching, bindings, and the PostHog adapter.
|
|
26
|
+
|
|
27
|
+
Widget metric selects now list only metrics a configured adapter can actually serve, mirroring the capability gating that already hides whole widgets. On a PostHog-only install the metric picker no longer offers `bounceRate` or other unsupported metrics, and breakdown widgets narrow the picker by both metric and their dimension.
|
|
28
|
+
|
|
29
|
+
`cache.ttl` now overrides the adapter's `recommendedTtl`. Previously an adapter's recommendation always won, so setting `cache.ttl.aggregate` had no effect. An explicit value now wins; leave a value unset to keep each adapter's own recommendation.
|
|
30
|
+
|
|
31
|
+
Binding `hostname` is now applied as a query filter by adapters that support it: PostHog (`properties.$host`), GA4 (`hostName`), and Plausible (`event:hostname`). It previously only partitioned the cache key without filtering. Umami and the native engine still ignore it (native rollups are not yet keyed by hostname).
|
|
32
|
+
|
|
33
|
+
The PostHog adapter gains the `events` metric (total captured events, matching PostHog's own Events definition) and the `event` dimension (per-event-name breakdown). Requesting either switches the read off the `$pageview`-only filter; the pageview-family metrics stay pageview-scoped through conditional aggregation.
|
|
34
|
+
|
|
35
|
+
The dashboard trend chart no longer flashes at a wrong width on first paint: it measures its container before paint and defers rendering the line until measured, removing the initial-load resize jump.
|
|
36
|
+
|
|
37
|
+
- **Breaking:** remove the unsupported `entries` and `exits` metric keys. No adapter ever implemented them and no widget surfaced real data for them, so they only widened the `MetricKey` union without a backing read path. Their translation keys (`metricEntries`, `metricExits`) are dropped as well; code referencing either key or the removed translation keys no longer compiles.
|
|
38
|
+
|
|
39
|
+
- Add `reportingTimezone` so daily analytics boundaries can align to an IANA timezone instead of always UTC.
|
|
40
|
+
|
|
41
|
+
Day boundaries (timeframe windows, the daily series axis, native rollup buckets, and the surfacing cache key) now resolve through a reporting timezone that defaults to `'UTC'`. An install that does not set the option is unchanged.
|
|
42
|
+
|
|
43
|
+
`reportingTimezone` accepts a fixed string (single-site, or forcing one zone) or a resolver `({ req, scope }) => string | null`. The resolver receives the already-resolved scope, so per-tenant (look up by scope), per-user-account (`req.user`), and selector (cookie/preference) strategies are all expressible with one option. Invalid or unresolvable zones fall back to UTC with a warning.
|
|
44
|
+
|
|
45
|
+
Native rollups bucket into the resolved timezone's day at ingest. This keeps reads cheap and correct for a tenant's own zone, at the cost that changing the timezone does not re-bucket existing history, and a per-user selector cannot re-slice already-written native days (documented). External providers that accept a timezone are told the resolved zone: Umami via its `timezone` param, PostHog via `toStartOfDay(timestamp, '<zone>')`. GA4 and Plausible continue to bucket in their own account timezone.
|
|
46
|
+
|
|
47
|
+
Options considered: (1) a fixed string only, rejected because it cannot vary per tenant or user; (2) a resolver only, rejected because it forces single-site consumers to write a function for a constant; (3) the shipped `string | resolver` union, chosen because it mirrors the existing `scopeResolver` pattern and serves every named use case with one familiar, testable option. For bucketing, write-time (per the "go for B, no historical re-bucketing" decision) was chosen over read-time re-bucketing, which would have required storing finer-grained rollups.
|
|
48
|
+
|
|
49
|
+
- Bucket the per-document trend chart in the reporting timezone, and show a "New" state for documents without analytics yet.
|
|
50
|
+
|
|
51
|
+
The comparison windows, cache keys, and daily series already resolved on reporting-timezone day boundaries, but the trend chart still bucketed and labelled on UTC days. Any reporting timezone east of UTC (whose day starts fall on the previous UTC calendar day) therefore shifted every axis label, and the weekly and monthly groupings, back by a day. The chart now buckets and labels in the reporting timezone the read resolved in; the read helpers return that zone and the panel carries it in its endpoint payload for client-side re-bucketing. The default stays UTC, so existing installs are unchanged.
|
|
52
|
+
|
|
53
|
+
A per-document analytics surface with nothing to show now reads as "New" rather than the flat "No analytics yet" line or a row of zeros captioned "No change vs. previous period". That covers both an unsaved or unbound document (no path resolves) and a saved page that has not gathered a single tracked metric yet. Genuine configuration states (not bound, no provider, unavailable) keep their message, since those are setup problems rather than new pages. The "New" label is localized (`keys.stateNew`, English and German) and the `analytics-empty-state` classes are stable hooks for overriding the look.
|
|
54
|
+
|
|
55
|
+
### Patch Changes
|
|
56
|
+
|
|
57
|
+
- Correct `payload` and `@payloadcms/ui` peer ranges to `^3.83.0`. The plugin uses `definePlugin`, which shipped in Payload 3.83.0, so 3.82.x installs satisfied the old range but failed at import.
|
|
58
|
+
|
|
59
|
+
## 0.1.0-beta.1
|
|
60
|
+
|
|
61
|
+
### Minor Changes
|
|
62
|
+
|
|
63
|
+
- Field, type, and resolver API fixes from user feedback.
|
|
64
|
+
|
|
65
|
+
**Breaking:** `analyticsTab()` now returns a Payload `Tab` (as its name promises) instead of a whole tabs field, so it can be pushed into your own tabs field's `tabs` array. If you used it standalone in a `fields` array, switch to the new `analyticsTabsField()`:
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
fields: [analyticsTab()]; // before
|
|
69
|
+
fields: [analyticsTabsField()]; // after (same rendered result)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Display fields no longer blank entirely when one requested metric is unsupported by the active adapter: unsupported metrics are dropped (logged once per field render with the dropped names and adapter id), the supported remainder renders, and the "not available" state shows only when nothing survives.
|
|
73
|
+
|
|
74
|
+
Bindings are typed over `CollectionSlug`: the `collections` option keys are checked against your generated slugs and inline resolvers receive that collection's generated document type (degrading to `Record<string, unknown>` without generated types); `sync.collectionSlug` is checked the same way. `HostnameResolver` gains the same `(doc, ctx)` signature as `PathResolver` and may return `string | null | Promise<string | null>`; sync one-argument resolvers keep working.
|
|
75
|
+
|
|
76
|
+
Widget config Titles can opt into localization via `widgets: { localizeText: true }`. Field factories accept label overrides wherever they hardcoded translation keys: `analyticsStat` takes `label`, the row/fields/tab factories take per-metric `labels`, and `analyticsTab` / `analyticsTabsField` take tab `label` and `description`, each as a string, locale map, or Payload label function. The date range picker placeholder is now translatable.
|
|
77
|
+
|
|
78
|
+
- Runtime provider configuration and multi-tenant scoping. New options: `scopeResolver` maps each request to an analytics boundary (tenant id, site key; null = whole install), `providers.collection` (false | true | object) scaffolds an admin collection where providers are configured at runtime per scope (masked secrets, overridable slug/fields/access, `scopeField` for tenant-plugin fields), `providers.resolve` replaces the collection lookup with a custom store, `platformAdapter` designates one config adapter shared by every scope, and `access.platformRead` gates cross-scope reads (default: any authenticated user). Scoped installs add an indexed scope column to native events and rollups (existing native installs need a migration), the posthog adapter gains `scopeProperty` for per-scope reads against one shared project, and `posthogProxyRewrites` (new `./next` subpath) returns Next.js rewrites for a first-party PostHog proxy.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { getTenantFromCookie } from "@payloadcms/plugin-multi-tenant/utilities";
|
|
82
|
+
|
|
83
|
+
analytics({
|
|
84
|
+
adapters: [
|
|
85
|
+
native(),
|
|
86
|
+
posthog({ projectId, apiKey, scopeProperty: "tenant" }),
|
|
87
|
+
],
|
|
88
|
+
platformAdapter: "posthog",
|
|
89
|
+
scopeResolver: ({ req }) => {
|
|
90
|
+
const tenant = getTenantFromCookie(
|
|
91
|
+
req.headers,
|
|
92
|
+
req.payload.db.defaultIDType
|
|
93
|
+
);
|
|
94
|
+
return tenant === null ? null : String(tenant);
|
|
95
|
+
},
|
|
96
|
+
providers: { collection: { scopeField: "tenant" } },
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Static `adapters` config and default behavior without the new options are unchanged.
|
|
101
|
+
|
|
102
|
+
- Add a typed `translations` option to every plugin factory and make translation keys a stable public API. Each plugin's `./i18n` subpath now exports the `keys` object, the `TranslationKey` union, and the `TranslationsOption` shape. Overrides are flat and per-locale: values win over the built-in locales key-by-key, locales a plugin does not ship are added whole, and app-level `i18n.translations` still wins over everything.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { analytics } from "@10x-media/analytics";
|
|
106
|
+
import { keys } from "@10x-media/analytics/i18n";
|
|
107
|
+
|
|
108
|
+
analytics({
|
|
109
|
+
adapters: [nativeAdapter()],
|
|
110
|
+
translations: {
|
|
111
|
+
de: { [keys.pluginName]: "Analytik" },
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
A typo'd key inside `translations` is a compile error.
|
|
117
|
+
|
|
118
|
+
### Patch Changes
|
|
119
|
+
|
|
120
|
+
- Declare `maxmind` and `@payloadcms/db-postgres` as optional peer dependencies. Both are loaded lazily (maxmind by the MaxMind geo resolver, `@payloadcms/db-postgres` by the atomic rollup path on Postgres), but they were previously bundled into the published package, which inlined the entire Postgres driver stack and the MaxMind reader into dist. Consumers on Postgres already have `@payloadcms/db-postgres` installed; Mongo-only consumers never load it. Install `maxmind` only if you use the MaxMind geo resolver.
|
|
121
|
+
|
|
122
|
+
- Preserve `'use client'` directives in shared build chunks so the `/client` and `/rsc` entries expose correct React Server Component boundaries. Client widgets (`RealtimeCounter`, `TrendChart`, `BarList`) that get hoisted into a shared chunk now keep their directive, preventing "use client" boundary errors in Next.js consumers.
|
|
123
|
+
|
|
124
|
+
- Restructure README: features, quick start, and links into the documentation site at https://docs.10xmedia.de. Long-form documentation moved out of the package README.
|
|
125
|
+
|
|
126
|
+
- Update README documentation links: the docs site now serves from the domain root, so `docs.10xmedia.de/docs/<plugin>` links became `docs.10xmedia.de/<plugin>`.
|
|
127
|
+
|
|
128
|
+
- Ship per-file dist output instead of bundled chunks. Bundling merged client components into shared chunks and dropped their 'use client' directives, so Next.js lost the RSC boundary and the admin panel crashed with "useRef only works in Client Components" when rendering components imported through such a chunk (for analytics: every chart-based dashboard widget). Dist now mirrors src one file at a time, directives stay exactly where they were authored, and file names are stable across releases. A repo-level `check:dist` verification (directive parity, no inlined dependencies, exports resolution, publint) now runs in CI so this class of regression cannot ship again.
|
|
129
|
+
|
|
3
130
|
## 0.1.0-beta.0
|
|
4
131
|
|
|
5
132
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,211 +1,32 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
-
Adapter-based analytics for Payload v3
|
|
3
|
+
Adapter-based analytics for Payload v3. One adapter contract covers a self-hosted native engine and the major providers (GA4, Plausible, Umami, PostHog), surfaced through dashboard widgets and per-document stat fields, with cached reads, an opt-in sync tier, and capability gating so unsupported surfaces never appear.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/@10x-media/analytics)
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-plugins) collection. In beta: published under the `beta` dist-tag until a stable 1.0.
|
|
8
8
|
|
|
9
|
-
|
|
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`.
|
|
9
|
+
## Features
|
|
71
10
|
|
|
72
|
-
|
|
11
|
+
- **One adapter contract** with a capabilities model; adapters ship as code-split subpaths (`@10x-media/analytics/adapters/*`) plus a `memoryAdapter` for tests.
|
|
12
|
+
- **Native engine**: self-hosted, cookieless analytics in your own database, with atomic rollups, exact daily uniques, geo resolution (platform headers or MaxMind), retention pruning, and opt-in write batching.
|
|
13
|
+
- **Dashboard widgets** for Payload's Modular Dashboard: metric, trend, four breakdowns, and realtime, all capability-gated, plus a public API for custom widgets.
|
|
14
|
+
- **Display fields**: `analyticsStat`, `analyticsStatRow`, `analyticsFields`, `analyticsTab`, `analyticsTabsField` place per-document stats on your collections; typed per-collection bindings resolve each document's URL path.
|
|
15
|
+
- **Caching** through `payload.kv` with request coalescing, plus an opt-in scheduled warm job.
|
|
16
|
+
- **Sync tier**: persist provider daily metrics into a queryable Payload collection.
|
|
17
|
+
- **Typed translations** with per-key overrides via `@10x-media/analytics/i18n`.
|
|
73
18
|
|
|
74
|
-
|
|
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
|
-
```
|
|
19
|
+
Optional peer dependencies, installed only if used: `@google-analytics/data` (GA4), `maxmind` (MaxMind geo).
|
|
169
20
|
|
|
170
|
-
|
|
21
|
+
## Quick start
|
|
171
22
|
|
|
172
|
-
|
|
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
|
-
]
|
|
23
|
+
```bash
|
|
24
|
+
pnpm add @10x-media/analytics
|
|
186
25
|
```
|
|
187
26
|
|
|
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
27
|
```ts
|
|
28
|
+
// payload.config.ts
|
|
29
|
+
import { buildConfig } from 'payload'
|
|
209
30
|
import { analytics, analyticsDefaultWidgets } from '@10x-media/analytics'
|
|
210
31
|
import { native } from '@10x-media/analytics/adapters/native'
|
|
211
32
|
|
|
@@ -213,175 +34,35 @@ export default buildConfig({
|
|
|
213
34
|
admin: {
|
|
214
35
|
dashboard: { defaultLayout: [...analyticsDefaultWidgets()] },
|
|
215
36
|
},
|
|
216
|
-
plugins: [
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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!,
|
|
37
|
+
plugins: [
|
|
38
|
+
analytics({
|
|
39
|
+
adapters: [native()],
|
|
40
|
+
collections: {
|
|
41
|
+
pages: { path: (doc) => (doc.slug ? `/${doc.slug}` : null) },
|
|
365
42
|
},
|
|
366
43
|
}),
|
|
367
44
|
],
|
|
368
45
|
})
|
|
369
46
|
```
|
|
370
47
|
|
|
371
|
-
|
|
48
|
+
Run `payload generate:importmap`, send pageviews to `POST /api/analytics/ingest`, and the dashboard fills in.
|
|
372
49
|
|
|
373
|
-
|
|
50
|
+
## Documentation
|
|
374
51
|
|
|
375
|
-
|
|
376
|
-
import { posthog } from '@10x-media/analytics/adapters/posthog'
|
|
52
|
+
Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
|
|
377
53
|
|
|
378
|
-
analytics
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
54
|
+
- [Overview](https://docs.10xmedia.de/analytics)
|
|
55
|
+
- [Quick start](https://docs.10xmedia.de/analytics/quick-start)
|
|
56
|
+
- [Adapters](https://docs.10xmedia.de/analytics/adapters)
|
|
57
|
+
- [Native engine](https://docs.10xmedia.de/analytics/native)
|
|
58
|
+
- [Geo resolution](https://docs.10xmedia.de/analytics/geo)
|
|
59
|
+
- [Display fields](https://docs.10xmedia.de/analytics/display-fields)
|
|
60
|
+
- [Dashboard widgets](https://docs.10xmedia.de/analytics/widgets)
|
|
61
|
+
- [Caching and warming](https://docs.10xmedia.de/analytics/cache)
|
|
62
|
+
- [Reporting timezone](https://docs.10xmedia.de/analytics/timezone)
|
|
63
|
+
- [Sync tier](https://docs.10xmedia.de/analytics/sync)
|
|
64
|
+
- [i18n](https://docs.10xmedia.de/analytics/i18n)
|
|
384
65
|
|
|
385
|
-
|
|
66
|
+
## License
|
|
386
67
|
|
|
387
|
-
|
|
68
|
+
[MIT](./LICENSE). Copyright 10x Media GmbH.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { AnalyticsAdapter } from "../../core/contract.js";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/ga4/ga4.d.ts
|
|
4
|
+
interface Ga4Config {
|
|
5
|
+
/** GA4 property id (numeric), e.g. '123456789'. */
|
|
6
|
+
propertyId: string;
|
|
7
|
+
/** Service-account credentials. */
|
|
8
|
+
credentials: {
|
|
9
|
+
client_email: string;
|
|
10
|
+
private_key: string;
|
|
11
|
+
};
|
|
12
|
+
/** GCP project id; inferred from the credentials when omitted. */
|
|
13
|
+
projectId?: string;
|
|
14
|
+
/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */
|
|
15
|
+
maxLookbackDays?: number | null;
|
|
16
|
+
}
|
|
17
|
+
declare function ga4(config: Ga4Config): AnalyticsAdapter;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { Ga4Config, ga4 };
|
|
20
|
+
//# sourceMappingURL=ga4.d.ts.map
|