@10x-media/analytics 1.0.0-beta.7 → 1.0.0-beta.8
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 +48 -0
- package/README.md +8 -2
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/capture/slots.js +16 -5
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.d.ts +1 -0
- package/dist/capture/trackerConfig.js +28 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/BarList.d.ts +15 -1
- package/dist/charts/BarList.js +34 -18
- package/dist/charts/BarList.js.map +1 -1
- package/dist/charts/TrendChart.d.ts +16 -3
- package/dist/charts/TrendChart.js +172 -106
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bars.d.ts +2 -0
- package/dist/charts/bars.js +2 -1
- package/dist/charts/bars.js.map +1 -1
- package/dist/charts/bucket.js +10 -1
- package/dist/charts/bucket.js.map +1 -1
- package/dist/charts/spline.js +2 -2
- package/dist/charts/spline.js.map +1 -1
- package/dist/charts/styles.js +18 -1
- package/dist/charts/styles.js.map +1 -1
- package/dist/core/cacheKey.js +13 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/contract.d.ts +14 -7
- package/dist/core/contract.js +29 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/granularity.js +1 -1
- package/dist/core/options.d.ts +54 -5
- package/dist/core/options.js +59 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +33 -23
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/serverEvent.d.ts +42 -0
- package/dist/core/serverEvent.js +12 -0
- package/dist/core/serverEvent.js.map +1 -0
- package/dist/exports/client.d.ts +8 -2
- package/dist/exports/client.js +6 -1
- package/dist/exports/rsc.d.ts +5 -1
- package/dist/exports/rsc.js +6 -3
- package/dist/exports/types.d.ts +12 -4
- package/dist/exports/types.js +2 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/AnalyticsPanelField.js +1 -1
- package/dist/fields/AnalyticsStatField.js +2 -2
- package/dist/fields/config/MetricSelectField.js +2 -2
- package/dist/fields/config/MetricSelectField.js.map +1 -1
- package/dist/fields/config/SourceSelectField.js +2 -2
- package/dist/fields/config/SourceSelectField.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +5 -1
- package/dist/fields/readForDocument.d.ts +5 -0
- package/dist/fields/readForDocument.js +5 -5
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/GoalSelectField.d.ts +7 -0
- package/dist/goals/GoalSelectField.js +77 -0
- package/dist/goals/GoalSelectField.js.map +1 -0
- package/dist/goals/collection.js +250 -0
- package/dist/goals/collection.js.map +1 -0
- package/dist/goals/currency.js +14 -0
- package/dist/goals/currency.js.map +1 -0
- package/dist/goals/fetchGoals.d.ts +18 -0
- package/dist/goals/fetchGoals.js +29 -0
- package/dist/goals/fetchGoals.js.map +1 -0
- package/dist/goals/goalField.d.ts +31 -0
- package/dist/goals/goalField.js +56 -0
- package/dist/goals/goalField.js.map +1 -0
- package/dist/goals/goalsEndpoint.d.ts +1 -0
- package/dist/goals/goalsEndpoint.js +55 -0
- package/dist/goals/goalsEndpoint.js.map +1 -0
- package/dist/goals/resolver.d.ts +8 -0
- package/dist/goals/resolver.js +147 -0
- package/dist/goals/resolver.js.map +1 -0
- package/dist/goals/trackGoalAction.d.ts +74 -0
- package/dist/goals/trackGoalAction.js +139 -0
- package/dist/goals/trackGoalAction.js.map +1 -0
- package/dist/goals/useAnalyticsGoals.d.ts +20 -0
- package/dist/goals/useAnalyticsGoals.js +67 -0
- package/dist/goals/useAnalyticsGoals.js.map +1 -0
- package/dist/index.d.ts +10 -3
- package/dist/index.js +74 -11
- package/dist/index.js.map +1 -1
- package/dist/native/ingest/device.js +11 -3
- package/dist/native/ingest/device.js.map +1 -1
- package/dist/native/ingest/endpoint.d.ts +1 -0
- package/dist/native/ingest/endpoint.js +2 -17
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +20 -0
- package/dist/native/ingest/normalizeEvent.js +3 -2
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.d.ts +20 -0
- package/dist/native/ingest/serverTrack.js +99 -0
- package/dist/native/ingest/serverTrack.js.map +1 -0
- package/dist/native/ingest/validate.js +27 -0
- package/dist/native/ingest/validate.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +1 -1
- package/dist/native/nativeAdapter.js +21 -10
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/retention/pruneTask.js +1 -1
- package/dist/native/rollups/insertIfNew.js +36 -2
- package/dist/native/rollups/insertIfNew.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +27 -9
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/paths.js +5 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +113 -0
- package/dist/plugin/queryEndpoint.js.map +1 -0
- package/dist/plugin/readContextForRequest.js +71 -0
- package/dist/plugin/readContextForRequest.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +6 -3
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/runtime.js +31 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/scopeFieldBoot.js +22 -0
- package/dist/plugin/scopeFieldBoot.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +13 -51
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +15 -9
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/resolver.js.map +1 -1
- package/dist/query/dates.js +64 -0
- package/dist/query/dates.js.map +1 -0
- package/dist/query/errors.d.ts +17 -0
- package/dist/query/errors.js +10 -0
- package/dist/query/errors.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +59 -0
- package/dist/query/fetchQuery.js +110 -0
- package/dist/query/fetchQuery.js.map +1 -0
- package/dist/query/parse.d.ts +22 -0
- package/dist/query/parse.js +168 -0
- package/dist/query/parse.js.map +1 -0
- package/dist/query/response.d.ts +36 -0
- package/dist/timeframe/tz.js +17 -6
- package/dist/timeframe/tz.js.map +1 -1
- package/dist/translations/ar.js +98 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +98 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +98 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +98 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +98 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +98 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +97 -0
- package/dist/translations/keys.js +98 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +98 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +1 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +98 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +98 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +98 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +98 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsNavLink.d.ts +19 -0
- package/dist/view/AnalyticsNavLink.js +40 -0
- package/dist/view/AnalyticsNavLink.js.map +1 -0
- package/dist/view/AnalyticsView.d.ts +23 -0
- package/dist/view/AnalyticsView.js +45 -0
- package/dist/view/AnalyticsView.js.map +1 -0
- package/dist/view/AnalyticsViewClient.d.ts +15 -0
- package/dist/view/AnalyticsViewClient.js +189 -0
- package/dist/view/AnalyticsViewClient.js.map +1 -0
- package/dist/view/authRedirect.js +32 -0
- package/dist/view/authRedirect.js.map +1 -0
- package/dist/view/conversionRate.js +18 -0
- package/dist/view/conversionRate.js.map +1 -0
- package/dist/view/dayRange.js +68 -0
- package/dist/view/dayRange.js.map +1 -0
- package/dist/view/gating.d.ts +1 -0
- package/dist/view/gating.js +105 -0
- package/dist/view/gating.js.map +1 -0
- package/dist/view/labels.js +44 -0
- package/dist/view/labels.js.map +1 -0
- package/dist/view/registerView.js +48 -0
- package/dist/view/registerView.js.map +1 -0
- package/dist/view/sections/Breakdowns.js +157 -0
- package/dist/view/sections/Breakdowns.js.map +1 -0
- package/dist/view/sections/EmptyStates.js +92 -0
- package/dist/view/sections/EmptyStates.js.map +1 -0
- package/dist/view/sections/FilterChips.js +41 -0
- package/dist/view/sections/FilterChips.js.map +1 -0
- package/dist/view/sections/GoalsPanel.js +81 -0
- package/dist/view/sections/GoalsPanel.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +65 -0
- package/dist/view/sections/OverviewCards.js.map +1 -0
- package/dist/view/sections/RealtimeStrip.js +77 -0
- package/dist/view/sections/RealtimeStrip.js.map +1 -0
- package/dist/view/sections/Toolbar.js +179 -0
- package/dist/view/sections/Toolbar.js.map +1 -0
- package/dist/view/sections/Trend.js +119 -0
- package/dist/view/sections/Trend.js.map +1 -0
- package/dist/view/sections/styles.js +74 -0
- package/dist/view/sections/styles.js.map +1 -0
- package/dist/view/state.js +206 -0
- package/dist/view/state.js.map +1 -0
- package/dist/view/useViewQueries.js +150 -0
- package/dist/view/useViewQueries.js.map +1 -0
- package/dist/view/viewProps.d.ts +40 -0
- package/dist/view/viewProps.js +90 -0
- package/dist/view/viewProps.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
- package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsMetricWidget.js +35 -12
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsTrendWidget.js +51 -15
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/WidgetViewLink.js +17 -0
- package/dist/widgets/WidgetViewLink.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +28 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/cardChrome.js +31 -7
- package/dist/widgets/cardChrome.js.map +1 -1
- package/dist/widgets/range.js +43 -12
- package/dist/widgets/range.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +12 -0
- package/dist/widgets/readForWidget.js +6 -5
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
- package/dist/widgets/readForWidgetBreakdown.js +10 -7
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +57 -0
- package/dist/widgets/readForWidgetGoals.js +126 -0
- package/dist/widgets/readForWidgetGoals.js.map +1 -0
- package/dist/widgets/readForWidgetSeries.d.ts +13 -0
- package/dist/widgets/readForWidgetSeries.js +30 -12
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +49 -6
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +12 -1
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.d.ts +22 -0
- package/dist/widgets/viewLink.js +83 -0
- package/dist/widgets/viewLink.js.map +1 -0
- package/package.json +9 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,53 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.8
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- **Additive: goal surfaces.** `goals.collection` (`true`, or `{ enabled, slug, scopeField, access, overrides }`) enables an `analytics-goals` collection scoped exactly like providers: rows filter by the request's resolved scope, `scope` is stamped on write and a forged one is refused, platform admins read every scope, and slugs are unique per scope, checked on every write and backed by a unique index on `slug` for an unscoped install or on `(slug, scope)` once a `scopeResolver` is configured and the plugin owns the scope field. Two cases stay hook-guarded only: install-wide rows on a scoped Postgres install (Postgres treats a NULL scope as distinct), and a host-owned `scopeField`, which the plugin does not index. Enabled collection goals merge over config goals by slug, cached for 30 seconds per scope and invalidated on change (one read serves at most 500 enabled goals per scope), and reach the native ingest, the browser tracker config and the new `GET /api/analytics/goals` endpoint (authenticated, per scope, `{ goals: [{ slug, name, source }], collection }`).
|
|
8
|
+
|
|
9
|
+
`goalField()` is a field factory that stores a goal slug behind a picker of the request's goals, with `goalSlug()` for renderers; the picker follows native field rules (`admin.condition`, `admin.width`, `admin.description`, `admin.placeholder`), and it, `SourceSelectField` and `MetricSelectField` now resolve their path through Payload's field context, so all three behave inside blocks and array rows. `@10x-media/analytics/client` gains `GoalSelectField` and `useAnalyticsGoals` plus the `GoalsResponse` and `WireGoal` wire types, and `GoalFieldOptions` is exported from both the root and `/types`.
|
|
10
|
+
|
|
11
|
+
`trackServerEvent(payload, event, { req, flush })` records a pageview, event or goal from server code through the native ingest (no HTTP round trip, same sanitizers and goal matching). With `req` the event inherits that request's headers, so geo, device and the visitor hash follow the real request; with neither a `req` nor an explicit `userAgent` it is attributed to a stable synthetic server visitor per day per hostname and reports no device at all rather than counting as desktop. `flush: true` awaits a buffered write. An explicit `scope` is ignored on an unscoped install and is never validated against the scopes that exist. A missing required field rejects with `AnalyticsTrackError` naming the field, and nothing is written. Needs the native adapter.
|
|
12
|
+
|
|
13
|
+
`trackGoalAction({ hostname, path, scope })` returns a form-builder action definition (type `analyticsGoal`, exported as `GOAL_ACTION_TYPE`) with no form-builder dependency; register it as `actions: { [GOAL_ACTION_TYPE]: trackGoalAction({ hostname: 'example.com' }) }`. Treat `hostname` as required wherever a jobs runner queues actions, and `scope` as required there on a scoped install: a queued run carries the runner's request rather than the submitter's, so the fallback chain (option, request host, `serverURL` host, then throw) has nothing useful to fall back to. The action is not `essential`, so a failed write never fails the submission.
|
|
14
|
+
|
|
15
|
+
**Breaking (scoped installs on a custom scope field):** where `providers.collection.scopeField` or `goals.collection.scopeField` names a field the plugin does not own, the plugin no longer adds its own hidden `scope` text field to that collection, since shadowing the host's field stored the scope twice. Generated types change accordingly, and a scoped Postgres install on a custom `scopeField` wants a migration dropping the now-unused `scope` column. Boot also fails with a named error when the collection carries no field of that name (`analytics: goals.collection.scopeField "tenant" does not exist on analytics-goals; register the collection with your tenant plugin or use the default scope field`), where the same misconfiguration previously booted and misbehaved silently.
|
|
16
|
+
|
|
17
|
+
**Behavioral:** `resolveGoals` on the adapter register context and on the runtime resolves per scope once the collection is enabled, and a collection goal replaces the config goal of the same slug. The public tracker config, which was a snapshot of the config goals, now carries the request scope's merged goals, still trimmed to `slug`, `match`, `value` and `currency`, so an editor's fixed value and currency reach `trackGoal()` defaults and vendor sinks; a change reaches browsers within the 30 second resolver cache plus that endpoint's own `Cache-Control: private, max-age=60`. `AnalyticsAdapter.ingest` gains an optional `track`.
|
|
18
|
+
|
|
19
|
+
**Consumer steps:** regenerate the admin import map (`payload generate:importmap`) once a `goalField()` is in the config, so `GoalSelectField` resolves. On Postgres, enabling `goals.collection` adds a table: run `payload migrate:create` in the app afterwards, which generates the DDL from the collection config the way every other schema change in this plugin does.
|
|
20
|
+
|
|
21
|
+
Multi-tenant note: the goals collection uses the plugin's own `scope` field and the plugin's scope resolver. Registering it with `@payloadcms/plugin-multi-tenant` (a `tenant` relationship through `scopeField` plus an entry in that plugin's `collections`) is not supported yet: it hangs a tenant user's admin panel in the dev app and the cause is not diagnosed. Providers still support that wiring (`isGlobal: true`). Goals scope correctly either way (access, stamping, per-scope uniqueness, the picker, the tracker config and the endpoint all follow the resolved scope); what a multi-tenant install gives up today is the tenant selector filtering the goals list view. A fix is planned.
|
|
22
|
+
|
|
23
|
+
- **Additive: query endpoint.** `GET /api/analytics/query` reads any configured source through the surfacing engine for signed-in users allowed by `access.read`: metrics, up to two dimensions, a date range, granularity, filters, ordering, a row limit and an optional previous-period comparison, validated against the selected source's capabilities with coded `400` errors (`invalid_param`, `unsupported_metric`, `unsupported_dimension`, `unsupported_filter`, `unsupported_operator`, `unsupported_granularity`, `range_too_long`). Scope follows the same rules as the sources endpoint: it comes from the request, an explicit `scope` is honored only for platform readers (`400 untrusted_scope` otherwise), and a scoped install with no resolvable scope answers `404 unknown_source`. A listed shared source that cannot filter by scope still answers `403` for a tenant reader. Responses carry the normalized query (ISO date range), the source and its capabilities, and `meta.stale` when the engine served an expired cache entry; a provider outage with no cached answer is `503 unavailable` with `Retry-After`, and every answer is `Cache-Control: private, no-store`. Date-only bounds are interpreted in the reporting timezone (the whole `to` day included); datetime bounds must carry an offset. `fetchQuery`, `buildQueryUrl` and `QueryFetchError` from `/client` wrap the endpoint for admin code, and `QueryRequest` carries every parameter including the optional `scope` a platform reader needs; `QueryRequest`, `QueryResponse`, `QueryError` and the parser's own result types are exported from `/types`, where the contract's own key registries are now runtime values too: `DIMENSION_KEYS` and `FILTER_OPERATORS`, named here because picker and validator authors want the list rather than only the union type.
|
|
24
|
+
|
|
25
|
+
**Additive: `access.read`.** A new access option gating every authenticated read endpoint (document, realtime, sources, goals, query); it defaults to allowing any signed-in user, so existing installs see no change until they set it. It is independent of scope gating: granting `read` never widens which scope a user reads.
|
|
26
|
+
|
|
27
|
+
**Behavioral:** a `scopeResolver` that answers the platform wildcard (`'*'`) now requires `access.platformRead` on the sources endpoint too, so a non-platform user gets an empty source list instead of the config adapters.
|
|
28
|
+
|
|
29
|
+
**Behavioral:** GA4 and Plausible reads now format both range bounds as calendar days in the reporting timezone, and every widget and field on those two providers with a non-UTC `reportingTimezone` changes its numbers as a result. East of UTC the start date was one calendar day early, so a 30-day widget was querying 31 days and totals drop after the upgrade; west of UTC the end date named the following UTC day whenever local time was past the UTC rollover, so a trailing partial day is no longer included. Native, PostHog and Umami installs are unaffected.
|
|
30
|
+
|
|
31
|
+
- **Additive: analytics view.** A dedicated admin view at `/admin/analytics` (option `view: { path, defaultRange, defaultMetric, navLabel }`, `view: false` to disable, `access.view` to gate it, defaulting to `access.read`) built on the query endpoint. It shows overview cards with a previous-period comparison, a trend, capability-gated breakdown tabs (pages, sources, technology, geography, events, goals) with click-to-filter chips, a goals panel with conversion rate, and a realtime strip, for any configured source. Range, comparison, source, metric, granularity, tab, filters, row limit and sort live in the URL, so a view is a shareable link and Back undoes a change. Every control appears only when the selected source's capabilities allow it. Scope follows the request (the tenant selector on multi-tenant installs). `AnalyticsView` is exported from `/rsc`, `AnalyticsViewClient` and `AnalyticsNavLink` from `/client`, the option types from `/types`; `AnalyticsViewClientProps` gains `scopeKey`, the resolved scope the server rendered for, which keys the client so a tenant switch refetches. `@payloadcms/next` and `next` are now peer dependencies.
|
|
32
|
+
|
|
33
|
+
**Additive:** `BarList` gains two optional props. `onSelect` makes every row a button reporting its index (rows stay inert `div`s without it), and `fill="soft"` pales the bar and moves its label onto the elevation ramp, for a list whose rows can be zero-valued; the default `fill="solid"` is exactly the current widget look.
|
|
34
|
+
|
|
35
|
+
**Behavioral:** the admin gains an "Analytics" nav link and the `/analytics` route by default; set `view: false` to opt out. The `visits` metric is now labelled "Visits" wherever a metric label is rendered (display fields, the document panel and the view's cards); it carried the "Visitors" label before. No widget metric picker offers `visits`, so widget configuration is unaffected.
|
|
36
|
+
|
|
37
|
+
**Breaking: custom ranges follow the reporting timezone.** A custom widget range and a document read with a custom `from`/`to` now interpret the picked days in the reporting timezone and include the whole final day; captions show the picked days. Previously the picker's stored instant (the admin browser's local midnight) was used as-is, so the final day was mostly dropped and providers could disagree by hemisphere. Numbers move on installs whose admin browsers sit in a different zone from the reporting timezone, and on instant-comparing reads (filtered or hour-granular native reads, and the vendor adapters' calendar-day formatting), which used to drop the final day; day-rollup reads where the two zones coincide were already right. The picked day is recovered from a stored instant exactly for every browser offset in `(-12, +12]`; a browser at +12:45 or beyond recovers the previous day. Day strings (`YYYY-MM-DD`) are accepted on the document endpoint; offset-less datetimes and zero-width instant windows are rejected.
|
|
38
|
+
|
|
39
|
+
**Behavioral: cache keys for a closed window carry its exact bounds.** A window ending on the final instant of its day is no longer day-snapped in the cache key, so an entry cached under the old, narrower window is never served after this upgrade. That covers every custom range and every comparison window, presets included (a previous period ends 1ms before the current window's first day), so each of those re-keys once and reads cold the first time after upgrading. Live preset windows, which end at `now`, keep their day-snapped key and their hit rate. The warm task re-keys its custom-range targets on the stored days and resolves them per scope, so it warms the keys a non-UTC install's widgets actually request.
|
|
40
|
+
|
|
41
|
+
- **Additive: more widgets.** Five new breakdown widgets (referrers, browsers, operating systems, campaigns, events) register from the same table as the existing ones, each gated on its own dimension. A goals widget (`analytics-goals`) lists conversions, revenue and conversion rate per goal for the widget's timeframe, under each goal's own name, with a previous-period delta on conversions when comparison is on; it needs a source that serves both `conversions` and the `goal` dimension, and costs one engine read, plus one for the rate's denominator where the source serves `visitors`, plus one for the deltas with comparison on. Every built-in widget gains an "Open in Analytics" link that opens the analytics view on the widget's source, range, metric or tab; the source is the adapter that actually served the widget, not the id it asked for, and the link serializes against the install's own `view.defaultRange` / `view.defaultMetric`, so anything already on a default is left out. A custom range becomes two day strings in the reporting timezone, clamped to the last 366 days of the window where it is wider than the view can hold; `allTime`, `thisMonth` and `thisYear` are windows the view's range picker does not offer, so those links carry no range and open the view on its default. The link disappears with `view: false`.
|
|
42
|
+
|
|
43
|
+
`TrendChart` accepts `comparison`, `comparisonLabel`, `comparisonRange` and `label` (and `TrendPoint` is exported from `/client`), drawing the previous period as a muted line on a y-scale covering both series, with a legend that carries the previous window's range and a tooltip row per series. The trend widget gains a "Compare to previous period" checkbox (off by default, absent when `widgets.comparison` is false) that reads the previous window's series through `readForWidgetSeries({ compare: true })`, which now returns `comparisonPoints` aligned to `points` by index. `readForWidget` accepts `comparison: false` for callers that only want totals; `readForWidgetBreakdown` accepts `extraMetrics` and returns per-row `metrics` for them; both surface `stale`.
|
|
44
|
+
|
|
45
|
+
**Fix:** the view's trend re-dates the comparison series onto the primary axis by index before labelling it. The query endpoint buckets each window on its own week and month boundaries, so at those granularities the comparison could come back a bucket longer or shorter and the chart padded or truncated it silently.
|
|
46
|
+
|
|
47
|
+
**Behavioral:** the analytics view's trend section draws one chart with the overlay instead of stacking a second chart for the previous period. With the trend widget's comparison ticked, the previous-window read it already made is asked for by day rather than as a total, so an adapter that answers series and totals in separate calls makes one more call for it.
|
|
48
|
+
|
|
49
|
+
**Fix:** a duplicate row on the native engine's seen ledger is treated as "already seen" rather than thrown. A pageview and a goal event arriving together for the same visitor race on the same ledger key, and the loser's duplicate-key error (Mongo 11000, Postgres 23505) used to escape the ingest handler as a 500.
|
|
50
|
+
|
|
3
51
|
## 1.0.0-beta.7
|
|
4
52
|
|
|
5
53
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# @10x-media/analytics
|
|
4
4
|
|
|
5
|
-
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.
|
|
5
|
+
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 an admin analytics view, dashboard widgets and per-document stat fields, with cached reads, an opt-in sync tier, and capability gating so unsupported surfaces never appear.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/@10x-media/analytics)
|
|
8
8
|
|
|
@@ -13,8 +13,11 @@ Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-pl
|
|
|
13
13
|
- **One adapter contract** with a capabilities model; adapters ship as code-split subpaths (`@10x-media/analytics/adapters/*`) plus a `memoryAdapter` for tests.
|
|
14
14
|
- **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.
|
|
15
15
|
- **Capture**: a dependency-free browser tracker (`@10x-media/analytics/tracker`) with SPA pageviews, consent gating, auto-capture, and goals, booted from React (`@10x-media/analytics/react`) or a server component; capture-capable adapters are served through a first-party proxy so a vendor's SDK loads from your own origin.
|
|
16
|
-
- **
|
|
16
|
+
- **Goals**: conversions and revenue, completed from a `data-analytics-goal` attribute, a `goalField()` picker in your own blocks, a `@10x-media/form-builder` action, or `trackServerEvent` from server code (webhooks, jobs), and declared in config or in an opt-in collection editors manage per scope.
|
|
17
|
+
- **Analytics view** at `/admin/analytics`: overview cards, a trend, capability-gated breakdown tabs with click-to-filter, goals and realtime, with range, source, metric, tab and filters in the URL so a report is a shareable link.
|
|
18
|
+
- **Dashboard widgets** for Payload's Modular Dashboard: metric, trend (with an optional previous-period overlay), goals, ten breakdowns, and realtime, each capability-gated, each linking into the analytics view, plus a public API for custom widgets.
|
|
17
19
|
- **Display fields**: `analyticsStat`, `analyticsStatRow`, `analyticsFields`, `analyticsTab`, `analyticsTabsField` place per-document stats on your collections; typed per-collection bindings resolve each document's URL path.
|
|
20
|
+
- **Query endpoint**: an authenticated `GET /api/analytics/query` over any configured source, capability-validated and scope-gated, with coded errors and a `fetchQuery` helper for admin code.
|
|
18
21
|
- **Caching** through `payload.kv` with request coalescing, plus an opt-in scheduled warm job.
|
|
19
22
|
- **Sync tier**: persist provider daily metrics into a queryable Payload collection.
|
|
20
23
|
- **Typed translations** with per-key overrides via `@10x-media/analytics/i18n`.
|
|
@@ -57,6 +60,8 @@ Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
|
|
|
57
60
|
- [Overview](https://docs.10xmedia.de/analytics)
|
|
58
61
|
- [Quick start](https://docs.10xmedia.de/analytics/quick-start)
|
|
59
62
|
- [Adapters](https://docs.10xmedia.de/analytics/adapters)
|
|
63
|
+
- [Data sources and the query endpoint](https://docs.10xmedia.de/analytics/data-sources)
|
|
64
|
+
- [Analytics view](https://docs.10xmedia.de/analytics/analytics-view)
|
|
60
65
|
- [Native engine](https://docs.10xmedia.de/analytics/native)
|
|
61
66
|
- [Capture](https://docs.10xmedia.de/analytics/capture)
|
|
62
67
|
- [Goals](https://docs.10xmedia.de/analytics/goals)
|
|
@@ -67,6 +72,7 @@ Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
|
|
|
67
72
|
- [Caching and warming](https://docs.10xmedia.de/analytics/cache)
|
|
68
73
|
- [Reporting timezone](https://docs.10xmedia.de/analytics/timezone)
|
|
69
74
|
- [Sync tier](https://docs.10xmedia.de/analytics/sync)
|
|
75
|
+
- [Multi-tenancy](https://docs.10xmedia.de/analytics/multi-tenancy)
|
|
70
76
|
- [i18n](https://docs.10xmedia.de/analytics/i18n)
|
|
71
77
|
|
|
72
78
|
## License
|
package/dist/adapters/ga4/ga4.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { zonedCalendarDay } from "../../timeframe/tz.js";
|
|
1
2
|
import { dayIso } from "../series.js";
|
|
2
3
|
//#region src/adapters/ga4/ga4.ts
|
|
3
4
|
const METRIC_MAP = {
|
|
@@ -123,8 +124,8 @@ function ga4(config) {
|
|
|
123
124
|
const baseRequest = {
|
|
124
125
|
property: `properties/${config.propertyId}`,
|
|
125
126
|
dateRanges: [{
|
|
126
|
-
startDate: q.dateRange.start
|
|
127
|
-
endDate: q.dateRange.end
|
|
127
|
+
startDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"),
|
|
128
|
+
endDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")
|
|
128
129
|
}],
|
|
129
130
|
metrics: providerMetrics.map((name) => ({ name })),
|
|
130
131
|
...dimensionFilter ? { dimensionFilter } : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ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C5B,MAAM,SAAS,MAAM,QAAQ,GAAG,IAAI,CAAC;IACrC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GACpF;GAUA,OAAO;IAAE,OARqB,SAAS,QAAQ,CAAC,GAAG,KAAK,QAAQ;KAC/D,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\tendDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAyBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;CACnE,IAAI,WAAW,eACd,OAAO,KAAK,MAAM,MAAM,GAAI;CAE7B,IAAI,WAAW,cACd,OAAO,KAAK,MAAM,MAAM,GAAG;CAE5B,OAAO;AACR;AAEA,SAAgB,IAAI,QAAqC;CAGxD,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;EACT,YAAY;EACZ,SAAS;EACT,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;EAC/B,iBAAiB;EACjB,WAAW;GAAE,eAAe;GAAI,YAAY;GAAU,mBAAmB;EAAK;EAC9E,g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C5E,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,GAAG;KAAE,CAAC;IAEpD;IACA,MAAM,YAAY,SAAS,SAAS;IAEpC,OAAO;KAAE;KAAM,QADA,YAAY,QAAQ,SAAS,IAAI,CAAC;KAC1B,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GAC7D;GAEA,MAAM,CAAC,YAAY,MAAM,OAAO,UAAU;IACzC,GAAG;IACH,GAAI,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC;IACpF,GAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;GACrC,CAAC;GAED,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,MAAM,SAAS,OAAO;IAC5B,MAAM,SAAS,MAAM,QAAQ,GAAG,IAAI,CAAC;IACrC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GACpF;GAUA,OAAO;IAAE,OARqB,SAAS,QAAQ,CAAC,GAAG,KAAK,QAAQ;KAC/D,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { zonedCalendarDay } from "../../timeframe/tz.js";
|
|
1
2
|
import { dayIso } from "../series.js";
|
|
2
3
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
4
|
//#region src/adapters/plausible/plausible.ts
|
|
@@ -131,7 +132,7 @@ function plausible(config) {
|
|
|
131
132
|
body: {
|
|
132
133
|
site_id: config.siteId,
|
|
133
134
|
metrics: providerMetrics,
|
|
134
|
-
date_range: [q.dateRange.start
|
|
135
|
+
date_range: [zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"), zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")],
|
|
135
136
|
...filters.length ? { filters } : {},
|
|
136
137
|
...extra
|
|
137
138
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO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AAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,OAAO,UACV,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,OAAO,SAAS;GAAM,OAAO;EAAK,GAC1D,EACC,QAAQ,GAAG,eAAe,2BAA2B,KAAK,UAAU,GAAG,KAAK,WAAW,EAAE,IAC1F,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAgB,UAAU,GAAG,KAAK;EAAc,GAC1D;GAAE,QAAQ;GAAc,UAAU,GAAG,KAAK;EAAY,CACvD,EACD;EACA,UAAU,EAAE,YAAY,EAAE,SAAS,QAAQ,IAAI,EAAE;EACjD,QAAQ,EAAE,MAAM,YAAY;CAC7B;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,a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EA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,MAAM,YAAY;IACjC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GAC1F;GAaA,OAAO;IAAE,OAVoB,MADV,UAAU,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
|
package/dist/capture/slots.js
CHANGED
|
@@ -13,8 +13,13 @@ const isCaptureSlot = (value) => CAPTURE_SLOTS.includes(value);
|
|
|
13
13
|
*
|
|
14
14
|
* A slot configured `false` is null before any of that runs: an explicit disable outranks
|
|
15
15
|
* every default, and nothing happens on its behalf, not even a scope lookup.
|
|
16
|
+
*
|
|
17
|
+
* `scope` passes in an already-resolved scope so a caller filling both slots (and the
|
|
18
|
+
* request's goals) calls the host's resolver once; omit it and the tenant slot resolves
|
|
19
|
+
* its own.
|
|
16
20
|
*/
|
|
17
|
-
const
|
|
21
|
+
const resolveSlotAdapterFor = async (args) => {
|
|
22
|
+
const { runtime, req, slot, scope } = args;
|
|
18
23
|
const configured = runtime.captureSlots?.[slot];
|
|
19
24
|
if (configured === false) return null;
|
|
20
25
|
try {
|
|
@@ -24,12 +29,12 @@ const resolveSlotAdapter = async (runtime, req, slot) => {
|
|
|
24
29
|
const all = runtime.registry.all();
|
|
25
30
|
return all.length === 1 ? all[0] : null;
|
|
26
31
|
}
|
|
27
|
-
const
|
|
28
|
-
if (
|
|
32
|
+
const resolved = scope === void 0 ? await resolveScopeFor(runtime, req) : scope;
|
|
33
|
+
if (resolved === null) return null;
|
|
29
34
|
const registry = await resolveRegistryFor(runtime, {
|
|
30
35
|
payload: req.payload,
|
|
31
36
|
req,
|
|
32
|
-
scope
|
|
37
|
+
scope: resolved
|
|
33
38
|
});
|
|
34
39
|
return configured ? registry.get(configured) : registry.default();
|
|
35
40
|
} catch (err) {
|
|
@@ -37,7 +42,13 @@ const resolveSlotAdapter = async (runtime, req, slot) => {
|
|
|
37
42
|
return null;
|
|
38
43
|
}
|
|
39
44
|
};
|
|
45
|
+
/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */
|
|
46
|
+
const resolveSlotAdapter = (runtime, req, slot) => resolveSlotAdapterFor({
|
|
47
|
+
runtime,
|
|
48
|
+
req,
|
|
49
|
+
slot
|
|
50
|
+
});
|
|
40
51
|
//#endregion
|
|
41
|
-
export { CAPTURE_SLOTS, isCaptureSlot, resolveSlotAdapter };
|
|
52
|
+
export { CAPTURE_SLOTS, isCaptureSlot, resolveSlotAdapter, resolveSlotAdapterFor };
|
|
42
53
|
|
|
43
54
|
//# sourceMappingURL=slots.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport { type AnalyticsRuntime, resolveRegistryFor, resolveScopeFor } from '../plugin/runtime'\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot =>\n\t(CAPTURE_SLOTS as readonly string[]).includes(value)\n\n/**\n * The adapter filling one capture slot for this request, or null when the slot is\n * unfilled. `global` is install-wide, so it resolves out of the config registry only:\n * the `capture.slots.global` override, else the designated `platformAdapter`, else the\n * single config adapter when there is exactly one. `tenant` resolves out of the\n * request's own per-scope registry (which includes that scope's runtime providers) and\n * is null whenever no scope resolves. Any resolution failure degrades to null, so the\n * proxy 404s instead of throwing.\n *\n * A slot configured `false` is null before any of that runs: an explicit disable outranks\n * every default, and nothing happens on its behalf, not even a scope lookup.\n */\nexport const
|
|
1
|
+
{"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport { type AnalyticsRuntime, resolveRegistryFor, resolveScopeFor } from '../plugin/runtime'\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot =>\n\t(CAPTURE_SLOTS as readonly string[]).includes(value)\n\n/**\n * The adapter filling one capture slot for this request, or null when the slot is\n * unfilled. `global` is install-wide, so it resolves out of the config registry only:\n * the `capture.slots.global` override, else the designated `platformAdapter`, else the\n * single config adapter when there is exactly one. `tenant` resolves out of the\n * request's own per-scope registry (which includes that scope's runtime providers) and\n * is null whenever no scope resolves. Any resolution failure degrades to null, so the\n * proxy 404s instead of throwing.\n *\n * A slot configured `false` is null before any of that runs: an explicit disable outranks\n * every default, and nothing happens on its behalf, not even a scope lookup.\n *\n * `scope` passes in an already-resolved scope so a caller filling both slots (and the\n * request's goals) calls the host's resolver once; omit it and the tenant slot resolves\n * its own.\n */\nexport const resolveSlotAdapterFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tslot: CaptureSlot\n\tscope?: string | null\n}): Promise<AnalyticsAdapter | null> => {\n\tconst { runtime, req, slot, scope } = args\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn null\n\t}\n\ttry {\n\t\tif (slot === 'global') {\n\t\t\tif (configured) {\n\t\t\t\treturn runtime.registry.get(configured)\n\t\t\t}\n\t\t\tif (runtime.platformAdapterId) {\n\t\t\t\treturn runtime.registry.get(runtime.platformAdapterId)\n\t\t\t}\n\t\t\tconst all = runtime.registry.all()\n\t\t\treturn all.length === 1 ? (all[0] as AnalyticsAdapter) : null\n\t\t}\n\t\tconst resolved = scope === undefined ? await resolveScopeFor(runtime, req) : scope\n\t\tif (resolved === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: resolved,\n\t\t})\n\t\treturn configured ? registry.get(configured) : registry.default()\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: capture slot \"${slot}\" resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */\nexport const resolveSlotAdapter = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => resolveSlotAdapterFor({ runtime, req, slot })\n"],"mappings":";;AAOA,MAAa,gBAAwC,CAAC,UAAU,QAAQ;AAExE,MAAa,iBAAiB,UAC5B,cAAoC,SAAS,KAAK;;;;;;;;;;;;;;;;;AAkBpD,MAAa,wBAAwB,OAAO,SAKJ;CACvC,MAAM,EAAE,SAAS,KAAK,MAAM,UAAU;CACtC,MAAM,aAAa,QAAQ,eAAe;CAC1C,IAAI,eAAe,OAClB,OAAO;CAER,IAAI;EACH,IAAI,SAAS,UAAU;GACtB,IAAI,YACH,OAAO,QAAQ,SAAS,IAAI,UAAU;GAEvC,IAAI,QAAQ,mBACX,OAAO,QAAQ,SAAS,IAAI,QAAQ,iBAAiB;GAEtD,MAAM,MAAM,QAAQ,SAAS,IAAI;GACjC,OAAO,IAAI,WAAW,IAAK,IAAI,KAA0B;EAC1D;EACA,MAAM,WAAW,UAAU,KAAA,IAAY,MAAM,gBAAgB,SAAS,GAAG,IAAI;EAC7E,IAAI,aAAa,MAChB,OAAO;EAER,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,OAAO,aAAa,SAAS,IAAI,UAAU,IAAI,SAAS,QAAQ;CACjE,SAAS,KAAK;EACb,IAAI,SAAS,QAAQ,KAAK,4BAA4B,KAAK,uBAAuB,OAAO,GAAG,GAAG;EAC/F,OAAO;CACR;AACD;;AAGA,MAAa,sBACZ,SACA,KACA,SACsC,sBAAsB;CAAE;CAAS;CAAK;AAAK,CAAC"}
|
|
@@ -23,6 +23,7 @@ interface TrackerSlotConfig {
|
|
|
23
23
|
interface TrackerConfig {
|
|
24
24
|
slots: TrackerSlotConfig[];
|
|
25
25
|
autoCapture: ResolvedAutoCapture;
|
|
26
|
+
/** The request scope's goals, config merged with the goals collection. */
|
|
26
27
|
goals: TrackerGoal[];
|
|
27
28
|
/** Where the native sink posts events, derived from the app's own `routes.api`. */
|
|
28
29
|
ingestPath: string;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { INGEST_PATH, PROXY_PATH } from "../plugin/paths.js";
|
|
2
|
-
import {
|
|
2
|
+
import { resolveGoalsFor, resolveScopeFor } from "../plugin/runtime.js";
|
|
3
|
+
import { CAPTURE_SLOTS, resolveSlotAdapterFor } from "./slots.js";
|
|
3
4
|
import { DEFAULT_AUTO_CAPTURE, defaultConsentFor } from "../core/options.js";
|
|
4
5
|
import { normalizeMountPath } from "./mountPath.js";
|
|
5
6
|
//#region src/capture/trackerConfig.ts
|
|
@@ -10,6 +11,24 @@ const trackerGoals = (goals) => (goals ?? []).map(({ slug, match, value, currenc
|
|
|
10
11
|
...value ? { value } : {},
|
|
11
12
|
...currency ? { currency } : {}
|
|
12
13
|
}));
|
|
14
|
+
/** The request's scope, or null when the host's resolver has none or throws. */
|
|
15
|
+
const scopeFor = async (runtime, req) => {
|
|
16
|
+
try {
|
|
17
|
+
return await resolveScopeFor(runtime, req);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
req.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`);
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
/** The scope's merged goals, falling back to the config goals when the merge fails. */
|
|
24
|
+
const goalsFor = async (runtime, req, scope) => {
|
|
25
|
+
try {
|
|
26
|
+
return await resolveGoalsFor(runtime, req, scope);
|
|
27
|
+
} catch (err) {
|
|
28
|
+
req.payload?.logger?.warn(`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`);
|
|
29
|
+
return runtime.goals ?? [];
|
|
30
|
+
}
|
|
31
|
+
};
|
|
13
32
|
/** The config for an install with no runtime yet: no slots, but still a usable ingest path. */
|
|
14
33
|
const emptyTrackerConfig = (req) => ({
|
|
15
34
|
slots: [],
|
|
@@ -33,10 +52,16 @@ const emptyTrackerConfig = (req) => ({
|
|
|
33
52
|
const resolveTrackerConfig = async (args) => {
|
|
34
53
|
const { runtime, req } = args;
|
|
35
54
|
const base = apiRoute(req);
|
|
55
|
+
const scope = await scopeFor(runtime, req);
|
|
36
56
|
const slots = [];
|
|
37
57
|
const filled = /* @__PURE__ */ new Set();
|
|
38
58
|
for (const slot of CAPTURE_SLOTS) {
|
|
39
|
-
const adapter = await
|
|
59
|
+
const adapter = await resolveSlotAdapterFor({
|
|
60
|
+
runtime,
|
|
61
|
+
req,
|
|
62
|
+
slot,
|
|
63
|
+
scope
|
|
64
|
+
});
|
|
40
65
|
const capture = adapter?.capture;
|
|
41
66
|
if (!adapter || !capture || filled.has(adapter.id)) continue;
|
|
42
67
|
const override = runtime.capturePaths?.[slot];
|
|
@@ -60,7 +85,7 @@ const resolveTrackerConfig = async (args) => {
|
|
|
60
85
|
return {
|
|
61
86
|
slots,
|
|
62
87
|
autoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,
|
|
63
|
-
goals: trackerGoals(runtime
|
|
88
|
+
goals: trackerGoals(await goalsFor(runtime, req, scope)),
|
|
64
89
|
ingestPath: `${base}${runtime.ingestPath ?? "/analytics/ingest"}`
|
|
65
90
|
};
|
|
66
91
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { CaptureClientKind, CaptureSnippet, CaptureSupport } from '../core/capture'\nimport { DEFAULT_AUTO_CAPTURE, defaultConsentFor, type ResolvedAutoCapture } from '../core/options'\nimport type { Goal, TrackerGoal } from '../goals/types'\nimport { INGEST_PATH, PROXY_PATH } from '../plugin/paths'\nimport type
|
|
1
|
+
{"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { CaptureClientKind, CaptureSnippet, CaptureSupport } from '../core/capture'\nimport { DEFAULT_AUTO_CAPTURE, defaultConsentFor, type ResolvedAutoCapture } from '../core/options'\nimport type { Goal, TrackerGoal } from '../goals/types'\nimport { INGEST_PATH, PROXY_PATH } from '../plugin/paths'\nimport { type AnalyticsRuntime, resolveGoalsFor, resolveScopeFor } from '../plugin/runtime'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, type CaptureSlot, resolveSlotAdapterFor } from './slots'\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to: the runtime proxy, or a `capture.paths` override. */\n\tpath: string\n\tsnippet: CaptureSnippet\n\tclient: CaptureSupport['client']\n\trequiresConsent: boolean\n}\n\n/**\n * Everything the browser tracker needs, and nothing else. Serialized to any visitor by the\n * public tracker endpoint, so it carries only what an adapter puts in `capture.client` and\n * `capture.snippet`: never a query credential, never a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\t/** The request scope's goals, config merged with the goals collection. */\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, derived from the app's own `routes.api`. */\n\tingestPath: string\n}\n\nconst apiRoute = (req: PayloadRequest): string => req.payload?.config?.routes?.api ?? '/api'\n\nconst trackerGoals = (goals: Goal[] | undefined): TrackerGoal[] =>\n\t(goals ?? []).map(({ slug, match, value, currency }) => ({\n\t\tslug,\n\t\tmatch,\n\t\t...(value ? { value } : {}),\n\t\t...(currency ? { currency } : {}),\n\t}))\n\n/** The request's scope, or null when the host's resolver has none or throws. */\nconst scopeFor = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string | null> => {\n\ttry {\n\t\treturn await resolveScopeFor(runtime, req)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** The scope's merged goals, falling back to the config goals when the merge fails. */\nconst goalsFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<Goal[]> => {\n\ttry {\n\t\treturn await resolveGoalsFor(runtime, req, scope)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`\n\t\t)\n\t\treturn runtime.goals ?? []\n\t}\n}\n\n/** The config for an install with no runtime yet: no slots, but still a usable ingest path. */\nexport const emptyTrackerConfig = (req: PayloadRequest): TrackerConfig => ({\n\tslots: [],\n\tautoCapture: DEFAULT_AUTO_CAPTURE,\n\tgoals: [],\n\tingestPath: `${apiRoute(req)}${INGEST_PATH}`,\n})\n\n/**\n * The per-request tracker config: one entry per capture slot that resolves to an adapter\n * declaring `capture`, in slot order. A slot whose adapter does not resolve (no scope, an\n * unknown id, a throwing scope resolver) is simply absent, as is one whose snippet throws;\n * this runs on a public, unauthenticated path, so every failure degrades a slot away\n * rather than surfacing an error.\n *\n * One adapter fills at most one slot. A scoped install whose tenant registry defaults to\n * the same adapter the global slot names would otherwise hand the tracker two sinks for\n * it and send every event twice; the native adapter in particular resolves its scope from\n * the request, so one sink already covers both. The global slot iterates first and keeps\n * the entry.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n}): Promise<TrackerConfig> => {\n\tconst { runtime, req } = args\n\tconst base = apiRoute(req)\n\t// One scope resolution for the whole config: the slots and the goals must agree on it,\n\t// and the host's resolver can be as expensive as a database read.\n\tconst scope = await scopeFor(runtime, req)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapterFor({ runtime, req, slot, scope })\n\t\tconst capture = adapter?.capture\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override ? normalizeMountPath(override) : `${base}${PROXY_PATH}/${slot}`\n\t\tconst kind = capture.client.kind\n\t\ttry {\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet: capture.snippet({ path }),\n\t\t\t\tclient: capture.client,\n\t\t\t\trequiresConsent:\n\t\t\t\t\t(runtime.consentFor?.(slot, adapter.id, kind) ?? defaultConsentFor(kind)) === 'required',\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(await goalsFor(runtime, req, scope)),\n\t\tingestPath: `${base}${runtime.ingestPath ?? INGEST_PATH}`,\n\t}\n}\n"],"mappings":";;;;;;AAkCA,MAAM,YAAY,QAAgC,IA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WAAW,GAAG;EAC/E,MAAM,OAAO,QAAQ,OAAO;EAC5B,IAAI;GACH,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA,SAAS,QAAQ,QAAQ,EAAE,KAAK,CAAC;IACjC,QAAQ,QAAQ;IAChB,kBACE,QAAQ,aAAa,MAAM,QAAQ,IAAI,IAAI,KAAK,kBAAkB,IAAI,OAAO;GAChF,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC;EACvD,YAAY,GAAG,OAAO,QAAQ,cAAA;CAC/B;AACD"}
|
package/dist/charts/BarList.d.ts
CHANGED
|
@@ -4,6 +4,18 @@ import { BarDatum } from "./bars.js";
|
|
|
4
4
|
interface BarListProps {
|
|
5
5
|
data: BarDatum[];
|
|
6
6
|
emptyLabel: string;
|
|
7
|
+
/**
|
|
8
|
+
* Makes every row a button reporting its index. Left out, rows are inert: a source that
|
|
9
|
+
* cannot filter by the dimension must not offer a click that would do nothing.
|
|
10
|
+
*/
|
|
11
|
+
onSelect?: (index: number) => void;
|
|
12
|
+
/**
|
|
13
|
+
* `solid` (the default) fills the bar with the chart color and puts a white label inside
|
|
14
|
+
* it, which reads as long as every row has a bar to sit on. `soft` pales the fill and
|
|
15
|
+
* moves the label onto the elevation ramp, for a list whose rows can be zero-valued (a
|
|
16
|
+
* goal with no pageviews), where a zero-width bar leaves a white label on bare track.
|
|
17
|
+
*/
|
|
18
|
+
fill?: 'solid' | 'soft';
|
|
7
19
|
}
|
|
8
20
|
/**
|
|
9
21
|
* Ranked horizontal bar list (shadcn "custom label" style): each row is a filled,
|
|
@@ -13,7 +25,9 @@ interface BarListProps {
|
|
|
13
25
|
*/
|
|
14
26
|
declare function BarList({
|
|
15
27
|
data,
|
|
16
|
-
emptyLabel
|
|
28
|
+
emptyLabel,
|
|
29
|
+
onSelect,
|
|
30
|
+
fill
|
|
17
31
|
}: BarListProps): import("react/jsx-runtime").JSX.Element;
|
|
18
32
|
//#endregion
|
|
19
33
|
export { BarList, BarListProps };
|
package/dist/charts/BarList.js
CHANGED
|
@@ -2,15 +2,35 @@
|
|
|
2
2
|
import { toBarRows } from "./bars.js";
|
|
3
3
|
import { ChartStyles } from "./styles.js";
|
|
4
4
|
import { useState } from "react";
|
|
5
|
-
import { jsx, jsxs } from "react/jsx-runtime";
|
|
5
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
6
|
//#region src/charts/BarList.tsx
|
|
7
|
+
const RowContent = ({ row }) => /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
8
|
+
/* @__PURE__ */ jsxs("span", {
|
|
9
|
+
className: "analytics-bars__track",
|
|
10
|
+
children: [/* @__PURE__ */ jsx("span", {
|
|
11
|
+
className: "analytics-bars__fill",
|
|
12
|
+
style: { width: `${row.fraction * 100}%` }
|
|
13
|
+
}), /* @__PURE__ */ jsx("span", {
|
|
14
|
+
className: "analytics-bars__label",
|
|
15
|
+
children: row.label
|
|
16
|
+
})]
|
|
17
|
+
}),
|
|
18
|
+
/* @__PURE__ */ jsx("span", {
|
|
19
|
+
className: "analytics-bars__value",
|
|
20
|
+
children: row.display ?? row.value
|
|
21
|
+
}),
|
|
22
|
+
row.secondary === void 0 ? null : /* @__PURE__ */ jsx("span", {
|
|
23
|
+
className: "analytics-bars__secondary",
|
|
24
|
+
children: row.secondary
|
|
25
|
+
})
|
|
26
|
+
] });
|
|
7
27
|
/**
|
|
8
28
|
* Ranked horizontal bar list (shadcn "custom label" style): each row is a filled,
|
|
9
29
|
* proportional bar with the label inside and the value outside; hovering a row lifts
|
|
10
30
|
* it and shows a tooltip with the full label and value (useful when the label is
|
|
11
31
|
* truncated). Dependency-free; styling comes from the shared chart stylesheet.
|
|
12
32
|
*/
|
|
13
|
-
function BarList({ data, emptyLabel }) {
|
|
33
|
+
function BarList({ data, emptyLabel, onSelect, fill = "solid" }) {
|
|
14
34
|
const rows = toBarRows(data);
|
|
15
35
|
const [hover, setHover] = useState(null);
|
|
16
36
|
if (rows.length === 0) return /* @__PURE__ */ jsx("span", {
|
|
@@ -28,25 +48,21 @@ function BarList({ data, emptyLabel }) {
|
|
|
28
48
|
children: [
|
|
29
49
|
/* @__PURE__ */ jsx(ChartStyles, {}),
|
|
30
50
|
/* @__PURE__ */ jsx("div", {
|
|
31
|
-
className: "analytics-bars"
|
|
32
|
-
children: rows.map((row, i) => /* @__PURE__ */
|
|
33
|
-
className: "analytics-bars__row",
|
|
51
|
+
className: `analytics-bars${fill === "soft" ? " analytics-bars--soft" : ""}`,
|
|
52
|
+
children: rows.map((row, i) => onSelect ? /* @__PURE__ */ jsx("button", {
|
|
53
|
+
className: "analytics-bars__row analytics-bars__row--action",
|
|
54
|
+
onClick: () => onSelect(i),
|
|
34
55
|
onPointerEnter: track(i),
|
|
56
|
+
onPointerLeave: () => setHover(null),
|
|
35
57
|
onPointerMove: track(i),
|
|
58
|
+
type: "button",
|
|
59
|
+
children: /* @__PURE__ */ jsx(RowContent, { row })
|
|
60
|
+
}, row.label) : /* @__PURE__ */ jsx("div", {
|
|
61
|
+
className: "analytics-bars__row",
|
|
62
|
+
onPointerEnter: track(i),
|
|
36
63
|
onPointerLeave: () => setHover(null),
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
children: [/* @__PURE__ */ jsx("span", {
|
|
40
|
-
className: "analytics-bars__fill",
|
|
41
|
-
style: { width: `${row.fraction * 100}%` }
|
|
42
|
-
}), /* @__PURE__ */ jsx("span", {
|
|
43
|
-
className: "analytics-bars__label",
|
|
44
|
-
children: row.label
|
|
45
|
-
})]
|
|
46
|
-
}), /* @__PURE__ */ jsx("span", {
|
|
47
|
-
className: "analytics-bars__value",
|
|
48
|
-
children: row.display ?? row.value
|
|
49
|
-
})]
|
|
64
|
+
onPointerMove: track(i),
|
|
65
|
+
children: /* @__PURE__ */ jsx(RowContent, { row })
|
|
50
66
|
}, row.label))
|
|
51
67
|
}),
|
|
52
68
|
hover && hovered ? /* @__PURE__ */ jsxs("div", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BarList.js","names":[],"sources":["../../src/charts/BarList.tsx"],"sourcesContent":["'use client'\n\nimport { type PointerEvent, useState } from 'react'\nimport { type BarDatum, toBarRows } from './bars'\nimport { ChartStyles } from './styles'\n\nexport interface BarListProps {\n\tdata: BarDatum[]\n\temptyLabel: string\n}\n\ninterface Hover {\n\ti: number\n\tx: number\n\ty: number\n}\n\n/**\n * Ranked horizontal bar list (shadcn \"custom label\" style): each row is a filled,\n * proportional bar with the label inside and the value outside; hovering a row lifts\n * it and shows a tooltip with the full label and value (useful when the label is\n * truncated). Dependency-free; styling comes from the shared chart stylesheet.\n */\nexport function BarList({ data, emptyLabel }: BarListProps) {\n\tconst rows = toBarRows(data)\n\tconst [hover, setHover] = useState<Hover | null>(null)\n\tif (rows.length === 0) {\n\t\treturn <span className=\"analytics-bars__empty\">{emptyLabel}</span>\n\t}\n\tconst track = (i: number) => (e: PointerEvent<
|
|
1
|
+
{"version":3,"file":"BarList.js","names":[],"sources":["../../src/charts/BarList.tsx"],"sourcesContent":["'use client'\n\nimport { type PointerEvent, type ReactNode, useState } from 'react'\nimport { type BarDatum, type BarRow, toBarRows } from './bars'\nimport { ChartStyles } from './styles'\n\nexport interface BarListProps {\n\tdata: BarDatum[]\n\temptyLabel: string\n\t/**\n\t * Makes every row a button reporting its index. Left out, rows are inert: a source that\n\t * cannot filter by the dimension must not offer a click that would do nothing.\n\t */\n\tonSelect?: (index: number) => void\n\t/**\n\t * `solid` (the default) fills the bar with the chart color and puts a white label inside\n\t * it, which reads as long as every row has a bar to sit on. `soft` pales the fill and\n\t * moves the label onto the elevation ramp, for a list whose rows can be zero-valued (a\n\t * goal with no pageviews), where a zero-width bar leaves a white label on bare track.\n\t */\n\tfill?: 'solid' | 'soft'\n}\n\ninterface Hover {\n\ti: number\n\tx: number\n\ty: number\n}\n\nconst RowContent = ({ row }: { row: BarRow }): ReactNode => (\n\t<>\n\t\t<span className=\"analytics-bars__track\">\n\t\t\t<span className=\"analytics-bars__fill\" style={{ width: `${row.fraction * 100}%` }} />\n\t\t\t<span className=\"analytics-bars__label\">{row.label}</span>\n\t\t</span>\n\t\t<span className=\"analytics-bars__value\">{row.display ?? row.value}</span>\n\t\t{row.secondary === undefined ? null : (\n\t\t\t<span className=\"analytics-bars__secondary\">{row.secondary}</span>\n\t\t)}\n\t</>\n)\n\n/**\n * Ranked horizontal bar list (shadcn \"custom label\" style): each row is a filled,\n * proportional bar with the label inside and the value outside; hovering a row lifts\n * it and shows a tooltip with the full label and value (useful when the label is\n * truncated). Dependency-free; styling comes from the shared chart stylesheet.\n */\nexport function BarList({ data, emptyLabel, onSelect, fill = 'solid' }: BarListProps) {\n\tconst rows = toBarRows(data)\n\tconst [hover, setHover] = useState<Hover | null>(null)\n\tif (rows.length === 0) {\n\t\treturn <span className=\"analytics-bars__empty\">{emptyLabel}</span>\n\t}\n\tconst track = (i: number) => (e: PointerEvent<HTMLElement>) =>\n\t\tsetHover({ i, x: e.clientX, y: e.clientY })\n\tconst hovered = hover ? rows[hover.i] : undefined\n\treturn (\n\t\t<div className=\"analytics-chart\">\n\t\t\t<ChartStyles />\n\t\t\t<div className={`analytics-bars${fill === 'soft' ? ' analytics-bars--soft' : ''}`}>\n\t\t\t\t{rows.map((row, i) =>\n\t\t\t\t\tonSelect ? (\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row analytics-bars__row--action\"\n\t\t\t\t\t\t\tkey={row.label}\n\t\t\t\t\t\t\tonClick={() => onSelect(i)}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row\"\n\t\t\t\t\t\t\tkey={row.label}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{hover && hovered ? (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"analytics-chart__tooltip\"\n\t\t\t\t\tstyle={{ position: 'fixed', left: hover.x, top: hover.y }}\n\t\t\t\t>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-label\">{hovered.label}</div>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-value\">{hovered.display ?? hovered.value}</div>\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;AA6BA,MAAM,cAAc,EAAE,UACrB,qBAAA,UAAA,EAAA,UAAA;CACC,qBAAC,QAAD;EAAM,WAAU;YAAhB,CACC,oBAAC,QAAD;GAAM,WAAU;GAAuB,OAAO,EAAE,OAAO,GAAG,IAAI,WAAW,IAAI,GAAG;EAAI,CAAA,GACpF,oBAAC,QAAD;GAAM,WAAU;aAAyB,IAAI;EAAY,CAAA,CACpD;;CACN,oBAAC,QAAD;EAAM,WAAU;YAAyB,IAAI,WAAW,IAAI;CAAY,CAAA;CACvE,IAAI,cAAc,KAAA,IAAY,OAC9B,oBAAC,QAAD;EAAM,WAAU;YAA6B,IAAI;CAAgB,CAAA;AAEjE,EAAA,CAAA;;;;;;;AASH,SAAgB,QAAQ,EAAE,MAAM,YA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