@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.13

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.
Files changed (194) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/adapters/ga4/ga4.d.ts +6 -0
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +2 -1
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +6 -0
  9. package/dist/adapters/posthog/posthog.js +21 -8
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/umami/umami.d.ts +6 -0
  12. package/dist/adapters/umami/umami.js +2 -1
  13. package/dist/adapters/umami/umami.js.map +1 -1
  14. package/dist/capture/exclusionEndpoint.js +1 -1
  15. package/dist/capture/exclusionEndpoint.js.map +1 -1
  16. package/dist/capture/slots.js +3 -3
  17. package/dist/capture/slots.js.map +1 -1
  18. package/dist/capture/trackerConfig.js +11 -3
  19. package/dist/capture/trackerConfig.js.map +1 -1
  20. package/dist/charts/series.js +1 -1
  21. package/dist/core/adminOptions.js +6 -1
  22. package/dist/core/adminOptions.js.map +1 -1
  23. package/dist/core/capture.d.ts +3 -1
  24. package/dist/core/contract.d.ts +13 -1
  25. package/dist/core/contract.js.map +1 -1
  26. package/dist/core/options.d.ts +37 -5
  27. package/dist/core/options.js +6 -2
  28. package/dist/core/options.js.map +1 -1
  29. package/dist/core/registry.js.map +1 -1
  30. package/dist/core/scopeOptions.js +2 -0
  31. package/dist/core/scopeOptions.js.map +1 -1
  32. package/dist/core/scopedRead.js +170 -21
  33. package/dist/core/scopedRead.js.map +1 -1
  34. package/dist/core/sourceLabel.d.ts +10 -0
  35. package/dist/core/sourceLabel.js +63 -0
  36. package/dist/core/sourceLabel.js.map +1 -0
  37. package/dist/core/sourceOptions.js +18 -6
  38. package/dist/core/sourceOptions.js.map +1 -1
  39. package/dist/core/sourcePolicy.d.ts +55 -0
  40. package/dist/core/sourcePolicy.js +51 -0
  41. package/dist/core/sourcePolicy.js.map +1 -0
  42. package/dist/exports/adapters/contract.d.ts +2 -1
  43. package/dist/exports/adapters/ga4.d.ts +3 -2
  44. package/dist/exports/adapters/native.d.ts +3 -2
  45. package/dist/exports/adapters/plausible.d.ts +3 -2
  46. package/dist/exports/adapters/posthog.d.ts +3 -2
  47. package/dist/exports/adapters/umami.d.ts +3 -2
  48. package/dist/exports/client.d.ts +7 -5
  49. package/dist/exports/client.js +2 -1
  50. package/dist/exports/next.d.ts +3 -2
  51. package/dist/exports/rsc.d.ts +7 -6
  52. package/dist/exports/testing.d.ts +3 -2
  53. package/dist/exports/types.d.ts +12 -8
  54. package/dist/fields/AnalyticsPanelClient.js.map +1 -1
  55. package/dist/fields/AnalyticsPanelField.d.ts +1 -1
  56. package/dist/fields/AnalyticsPanelField.js +3 -1
  57. package/dist/fields/AnalyticsPanelField.js.map +1 -1
  58. package/dist/fields/AnalyticsStatField.d.ts +1 -1
  59. package/dist/fields/AnalyticsStatField.js +1 -1
  60. package/dist/fields/PanelContent.js +6 -1
  61. package/dist/fields/PanelContent.js.map +1 -1
  62. package/dist/fields/config/fetchSources.d.ts +3 -0
  63. package/dist/fields/config/fetchSources.js +5 -3
  64. package/dist/fields/config/fetchSources.js.map +1 -1
  65. package/dist/fields/readForDocument.d.ts +5 -4
  66. package/dist/fields/readForDocument.js +6 -2
  67. package/dist/fields/readForDocument.js.map +1 -1
  68. package/dist/goals/collection.js +4 -31
  69. package/dist/goals/collection.js.map +1 -1
  70. package/dist/goals/resolver.js +2 -2
  71. package/dist/goals/trackGoalAction.js +1 -1
  72. package/dist/index.d.ts +14 -11
  73. package/dist/index.js +6 -5
  74. package/dist/index.js.map +1 -1
  75. package/dist/native/geo/maxmindResolver.js +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +1 -1
  77. package/dist/native/nativeAdapter.d.ts +6 -0
  78. package/dist/native/nativeAdapter.js +3 -2
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/plugin/createRuntime.js +6 -3
  81. package/dist/plugin/createRuntime.js.map +1 -1
  82. package/dist/plugin/documentEndpoint.js +1 -0
  83. package/dist/plugin/documentEndpoint.js.map +1 -1
  84. package/dist/plugin/pluginCollections.js +11 -5
  85. package/dist/plugin/pluginCollections.js.map +1 -1
  86. package/dist/plugin/queryEndpoint.js +1 -1
  87. package/dist/plugin/queryEndpoint.js.map +1 -1
  88. package/dist/plugin/readContextForRequest.d.ts +11 -0
  89. package/dist/plugin/readContextForRequest.js +25 -15
  90. package/dist/plugin/readContextForRequest.js.map +1 -1
  91. package/dist/plugin/runtime.js +13 -5
  92. package/dist/plugin/runtime.js.map +1 -1
  93. package/dist/plugin/sourcesEndpoint.js +8 -9
  94. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  95. package/dist/providers/ProvidersListNotice.d.ts +11 -0
  96. package/dist/providers/ProvidersListNotice.js +36 -0
  97. package/dist/providers/ProvidersListNotice.js.map +1 -0
  98. package/dist/providers/collection.d.ts +9 -1
  99. package/dist/providers/collection.js +107 -42
  100. package/dist/providers/collection.js.map +1 -1
  101. package/dist/providers/factory.d.ts +1 -1
  102. package/dist/providers/factory.js +8 -11
  103. package/dist/providers/factory.js.map +1 -1
  104. package/dist/providers/probe.js +5 -1
  105. package/dist/providers/probe.js.map +1 -1
  106. package/dist/providers/registry.js +49 -39
  107. package/dist/providers/registry.js.map +1 -1
  108. package/dist/providers/resolver.js +6 -3
  109. package/dist/providers/resolver.js.map +1 -1
  110. package/dist/providers/scopeUnique.js +41 -0
  111. package/dist/providers/scopeUnique.js.map +1 -0
  112. package/dist/query/fetchQuery.d.ts +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/tracker/config.d.ts +5 -0
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/sinks/createSink.js +4 -1
  117. package/dist/tracker/sinks/createSink.js.map +1 -1
  118. package/dist/tracker/sinks/ga4.js +2 -2
  119. package/dist/tracker/sinks/posthog.js +30 -2
  120. package/dist/tracker/sinks/posthog.js.map +1 -1
  121. package/dist/tracker/sinks/vendor.js +2 -2
  122. package/dist/tracker/sinks/vendor.js.map +1 -1
  123. package/dist/translations/ar.js +6 -0
  124. package/dist/translations/ar.js.map +1 -1
  125. package/dist/translations/de.js +6 -0
  126. package/dist/translations/de.js.map +1 -1
  127. package/dist/translations/en.js +6 -0
  128. package/dist/translations/en.js.map +1 -1
  129. package/dist/translations/es.js +6 -0
  130. package/dist/translations/es.js.map +1 -1
  131. package/dist/translations/fr.js +6 -0
  132. package/dist/translations/fr.js.map +1 -1
  133. package/dist/translations/id.js +6 -0
  134. package/dist/translations/id.js.map +1 -1
  135. package/dist/translations/keys.d.ts +6 -0
  136. package/dist/translations/keys.js +7 -1
  137. package/dist/translations/keys.js.map +1 -1
  138. package/dist/translations/ko.js +6 -0
  139. package/dist/translations/ko.js.map +1 -1
  140. package/dist/translations/pt.js +6 -0
  141. package/dist/translations/pt.js.map +1 -1
  142. package/dist/translations/ru.js +6 -0
  143. package/dist/translations/ru.js.map +1 -1
  144. package/dist/translations/uk.js +6 -0
  145. package/dist/translations/uk.js.map +1 -1
  146. package/dist/translations/zh.js +6 -0
  147. package/dist/translations/zh.js.map +1 -1
  148. package/dist/ui/analytics.css +5 -0
  149. package/dist/ui/components/SourcesNoticeBanner.js +20 -0
  150. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
  151. package/dist/view/ViewRoot.js +2 -0
  152. package/dist/view/ViewRoot.js.map +1 -1
  153. package/dist/view/registerView.js +5 -4
  154. package/dist/view/registerView.js.map +1 -1
  155. package/dist/view/viewContext.d.ts +1 -1
  156. package/dist/view/viewProps.d.ts +1 -1
  157. package/dist/view/viewProps.js +3 -2
  158. package/dist/view/viewProps.js.map +1 -1
  159. package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
  160. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  161. package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
  162. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  163. package/dist/widgets/AnalyticsMetricWidget.js +1 -0
  164. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  165. package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
  166. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  167. package/dist/widgets/AnalyticsTrendWidget.js +1 -0
  168. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  169. package/dist/widgets/defaultLayout.d.ts +26 -0
  170. package/dist/widgets/defaultLayout.js +51 -0
  171. package/dist/widgets/defaultLayout.js.map +1 -0
  172. package/dist/widgets/notices.js +1 -0
  173. package/dist/widgets/notices.js.map +1 -1
  174. package/dist/widgets/prepareWidgetRead.d.ts +14 -1
  175. package/dist/widgets/prepareWidgetRead.js +6 -2
  176. package/dist/widgets/prepareWidgetRead.js.map +1 -1
  177. package/dist/widgets/readForWidget.d.ts +4 -4
  178. package/dist/widgets/readForWidget.js +3 -1
  179. package/dist/widgets/readForWidget.js.map +1 -1
  180. package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
  181. package/dist/widgets/readForWidgetBreakdown.js +3 -1
  182. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  183. package/dist/widgets/readForWidgetGoals.d.ts +4 -4
  184. package/dist/widgets/readForWidgetGoals.js +3 -1
  185. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  186. package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
  187. package/dist/widgets/readForWidgetRealtime.js +3 -1
  188. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  189. package/dist/widgets/readForWidgetSeries.d.ts +4 -4
  190. package/dist/widgets/readForWidgetSeries.js +3 -1
  191. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  192. package/dist/widgets/registerWidgets.js +3 -1
  193. package/dist/widgets/registerWidgets.js.map +1 -1
  194. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,72 @@
1
1
  # @10x-media/analytics
2
2
 
3
+ ## 1.0.0-beta.13
4
+
5
+ ### Minor Changes
6
+
7
+ - **Options for hosts that build their own admin around the plugin: a view without its nav link, a source name per reader, and a dashboard layout per reader.** None changes an install that does not set it ([A source's name](https://docs.10xmedia.de/analytics/providers#a-sources-name), [A layout per reader](https://docs.10xmedia.de/analytics/widgets#a-layout-per-reader), [Options](https://docs.10xmedia.de/analytics/analytics-view#options)).
8
+
9
+ **Additive:** `view.navLink` (default `true`). `false` registers the view at its path without its link in the admin nav, in place of filtering `admin.components.afterNavLinks`.
10
+
11
+ **Additive:** `label` on `native()`, `plausible()`, `umami()`, `ga4()` and `posthog()`: a string, a map by admin language (read in the reader's language, then `i18n.fallbackLanguage`, then `en`, as `view.navLabel` is), or `({ req, scope }) => string | Promise<string>` naming the source per reader, so staff can read "Platform (PostHog)" where a tenant reads its own site's name. Where no reader is known the name is the string, else the map's `en` or first entry, else the vendor's name; a function that throws or answers blank falls back to it with a warning. A provider document's source keeps the document's name.
12
+
13
+ **Additive:** `AnalyticsAdapter.labelFor`, the optional per-reader name a custom adapter can declare, and the types `AdapterLabelOption` and `AdapterLabelArgs`.
14
+
15
+ **Additive:** `analyticsDefaultLayout(options?)` (`@beta`) from the package root, for `admin.dashboard.defaultLayout`: the default widgets less those the reader's default source cannot serve (realtime, goals, a breakdown's dimension, a metric). It keeps widgets that are not the plugin's and widgets naming their own `dataSource`, returns the full list when the reader may read no source, and narrows `options.widgets` when given. `analyticsDefaultWidgets()` is unchanged.
16
+
17
+ - **A tenant's own PostHog captures beside the platform's PostHog.** When both capture slots resolve to PostHog, the tenant slot runs as a second posthog-js client named `tenant`, so one page captures into both projects, each with its own gate, opt-out and exclusion ([Two PostHog projects on one page](https://docs.10xmedia.de/analytics/capture#two-posthog-projects-on-one-page), [From 1.0.0-beta.12](https://docs.10xmedia.de/analytics/upgrading/beta-13#a-tenants-own-posthog)).
18
+
19
+ **Upgrade actions**
20
+
21
+ 1. To keep 1.0.0-beta.12's behavior, set `capture.slots.tenant: false`, which empties the tenant slot for every tenant.
22
+ 2. A site that loads the vendor scripts itself (`snippets={false}`) starts the tenant's project as the named client, with pageviews off: `posthog.init(token, { api_host, capture_pageview: false }, 'tenant')`. Started any other way, the tenant slot finds no client and sends nothing.
23
+ 3. A Content Security Policy that allows the PostHog snippet by hash needs the new hashes.
24
+
25
+ **Behavioral:** 1.0.0-beta.12 left the tenant slot out with a warning; it now captures, so a tenant's own PostHog project receives events it never did. The named client starts with `capture_pageview: false` and `capture_pageleave: true` and gets the tracker's own pageviews as `$pageview`; the platform's client keeps `capture_pageview: 'history_change'`. Each project counts each pageview once, and `array.js` loads once.
26
+
27
+ **Behavioral:** each PostHog slot opens, closes and is excluded on its own client: `setGate({ tenant: false })` opts out `posthog.tenant` and leaves the platform's client capturing. PostHog stores each client's state under its own project token.
28
+
29
+ **Behavioral:** PostHog's snippet no longer replaces a posthog-js already loaded on the page; it starts the slot's client on it. The snippet's text changed, so its CSP hash did.
30
+
31
+ **Behavioral:** a second slot of Plausible, Umami or GA4 is still left out of the tracker config with a warning, as before.
32
+
33
+ **Additive:** `instance` on `TrackerSlotConfig` and on `CaptureSupport.snippet`'s arguments, naming the client a slot captures with.
34
+
35
+ - **A provider document is a source only once it can read, and the Provider select offers only the types the install serves.** A document now has to be enabled, of a served type and hold the credentials its adapter reads with; `native` is offered only beside `native()`; `providers.collection.types` narrows the list; and a scoped install's documents get a **Default for this site** checkbox ([When a document is a source](https://docs.10xmedia.de/analytics/providers#when-a-document-is-a-source), [Which provider types a document may have](https://docs.10xmedia.de/analytics/providers#which-provider-types-a-document-may-have), [From 1.0.0-beta.12](https://docs.10xmedia.de/analytics/upgrading/beta-13)).
36
+
37
+ **Upgrade actions**
38
+
39
+ 1. On a scoped install running the providers collection, on Postgres or SQLite in migrate mode, generate a migration (`pnpm payload migrate:create`), review it and run it: it adds the `is_default` column to the providers table. Push mode and MongoDB need nothing ([The `is_default` column](https://docs.10xmedia.de/analytics/upgrading/beta-13#the-is_default-column)).
40
+ 2. On Postgres or SQLite, where the install runs the providers collection without `native()` in `adapters`, or sets `providers.collection.types` with another type first, the generated migration also drops the **Provider** column's `native` default. No stored value changes ([The `provider` column](https://docs.10xmedia.de/analytics/upgrading/beta-13#the-provider-column)).
41
+ 3. Enter the read credentials of any provider document that lacks them, or switch it off.
42
+
43
+ **Behavioral:** a provider document missing the credentials its adapter reads with is no longer listed as a source, fills no capture slot whatever capture fields it holds, and is no tenant's own source under a `fallback` policy. 1.0.0-beta.12 listed it and showed an empty state. A document whose credential fails to decrypt is still listed, as a failing source. `providers.resolve` installs decide for themselves.
44
+
45
+ **Behavioral:** the **Provider** select offers `native` only while `adapters` holds `native()`, and defaults to the first type it offers rather than `native`. Saving a document with a type the install does not serve is refused with a message on that field; a stored document keeps its type until it is saved.
46
+
47
+ **Additive:** `providers.collection.types` lists the types documents may have, in the order the select offers them; an unknown id, or a list leaving no served type, fails the boot. `analyticsProviderFields({ types })` takes the same list.
48
+
49
+ **Additive:** on a scoped install, the **Default for this site** checkbox (`isDefault`) in the provider document's sidebar, at most one per scope, a second refused on save. `providers.collection.defaultAccess` (a field access function or `{ create, update }`) decides who may set it, following `connectionAccess` when unset; `providers.collection.fields.isDefault` replaces the field. The flagged document's source also fills the tenant capture slot when it captures.
50
+
51
+ - **Tenants can read the platform's shared source, and each tenant picks the source its readers open on.** On a scoped install, `sources` decides per shared config adapter whether a tenant's own members read their tenant through it, and `defaultSource` with the provider document's **Default for this site** checkbox decides a tenant's default source ([Letting tenants read a shared source](https://docs.10xmedia.de/analytics/multi-tenancy#letting-tenants-read-a-shared-source), [A tenant's default source](https://docs.10xmedia.de/analytics/multi-tenancy#a-tenants-default-source), [From 1.0.0-beta.12](https://docs.10xmedia.de/analytics/upgrading/beta-13)).
52
+
53
+ **Upgrade actions**
54
+
55
+ 1. Check `access.crossScope` functions that query a database or a service: a gate may now be asked once per scope and adapter in a request, so keep it cheap or memoize it per request.
56
+ 2. Keep a `named` gate able to answer from `{ req }` alone: the providers and goals collections still ask it without `scope`.
57
+
58
+ **Behavioral:** the `access.crossScope` gates are asked with `{ req, scope, adapterId }`: `named` with the scope a reader names, `aggregate` with `'*'` or `null`, `unscopedSource` with the tenant and the config adapter's id. A gate written for `{ req }` keeps working, but where 1.0.0-beta.12 asked it once per request it may now run once per scope and adapter.
59
+
60
+ **Behavioral:** a widget or a document panel whose stored data source its reader can no longer read reads the scope's default source and says so in a note, rather than failing. The query endpoint does not substitute: a `source` it cannot read still answers `404 unknown_source`.
61
+
62
+ **Additive:** `sources: { [adapterId]: { tenants } }`, with `tenants` one of `'staff'` (the default, what 1.0.0-beta.12 did), `'tenant'` (the tenant's members always read it, narrowed to their tenant), `'fallback'` (they read it until they read a source of their own) or `({ req, scope, adapterId, ownSources }) => boolean`. Anything but `'staff'` needs an adapter with `capabilities.scopedQueries`, or the boot fails naming `sources.<id>.tenants`. A policy never widens which scope a user reads: a tenant user still gets `400 untrusted_scope` for `scope=*` or another tenant. Jobs read as `SYSTEM` and ask no policy, and capture is unaffected.
63
+
64
+ **Additive:** under `'fallback'` the view and the providers list tell a tenant's users the numbers are the platform's until they add a source, and `GET /api/_x/sources` answers `notice: 'platformFallback'`. A provider save switches the next request to the tenant's own source.
65
+
66
+ **Additive:** `defaultSource: 'tenantFirst' | 'platformFirst' | ({ req, scope, sources }) => string | undefined`. A tenant's default is its document flagged **Default for this site**, then this rule, then what 1.0.0-beta.12 picked; the sources endpoint's `defaultId`, the view, widgets without a data source, the document panel, the read helpers and the warm task follow it. `sources` and `defaultSource` fail the boot without `scope.resolve`, and `'platformFirst'` without `platformAdapter`.
67
+
68
+ **Additive:** the types `AnalyticsSourceOptions`, `SourcePolicy`, `SourcePolicyFunction`, `OwnSource`, `SourceRef`, `DefaultSourceRule` and `DefaultSourceFunction`; `CrossScopeAccess` takes the optional `scope` and `adapterId`.
69
+
3
70
  ## 1.0.0-beta.12
4
71
 
5
72
  ### Minor Changes
@@ -1,8 +1,14 @@
1
1
  import { Ga4Sdk } from "../../core/sdks.js";
2
2
  import { AnalyticsAdapter } from "../../core/contract.js";
3
+ import { AdapterLabelOption } from "../../core/sourceLabel.js";
3
4
 
4
5
  //#region src/adapters/ga4/ga4.d.ts
5
6
  interface Ga4Config {
7
+ /**
8
+ * The source's name in pickers and listings: a string, a map by admin language (read like
9
+ * `view.navLabel`), or a function naming it per reader and scope. Default `'Google Analytics 4'`.
10
+ */
11
+ label?: AdapterLabelOption;
6
12
  /** GA4 property id (numeric), e.g. '123456789'. */
7
13
  propertyId: string;
8
14
  /** Service-account credentials. */
@@ -1,9 +1,10 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { adapterLabel } from "../../core/sourceLabel.js";
2
3
  import { jsLiteral } from "../../capture/jsLiteral.js";
3
4
  import { MEASUREMENT_ID_PATTERN } from "./measurementId.js";
4
5
  import { CURRENCY_PATTERN, currencyOption } from "../../goals/currency.js";
5
- import { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from "../../plugin/peers.js";
6
6
  import { vendorReading } from "../../core/metricValues.js";
7
+ import { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from "../../plugin/peers.js";
7
8
  import { emptyGoalBreakdown, goalHint, hintSlugs, mergeGoalRows, mergeGoalTotals, readGoalPair, splitGoalMetrics } from "../goalRead.js";
8
9
  import { calendarDays, declaredFilters, everyOperatorOn, mappedKeys, providerMetricKeys, readableMetrics } from "../mapping.js";
9
10
  import { readTime } from "../readTime.js";
@@ -239,7 +240,7 @@ function ga4(config) {
239
240
  const measurementId = config.measurementId;
240
241
  return {
241
242
  id: "ga4",
242
- label: "Google Analytics 4",
243
+ ...adapterLabel(config.label, "Google Analytics 4", "ga4({ label })"),
243
244
  capabilities,
244
245
  ...measurementId && MEASUREMENT_ID_PATTERN.test(measurementId) ? { capture: buildCapture(measurementId) } : {},
245
246
  isConfigured: () => Boolean(config.propertyId && config.credentials?.client_email && config.credentials?.private_key),
@@ -1 +1 @@
1
- {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport { vendorReading } from '../../core/metricValues'\nimport type { Ga4Client, Ga4ReportResponse, Ga4ReportRow, Ga4Sdk } from '../../core/sdks'\nimport { CURRENCY_PATTERN, currencyOption } from '../../goals/currency'\nimport { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from '../../plugin/peers'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tmergeGoalTotals,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstream } from '../upstream'\nimport { ga4ExcludeGuard } from './disableKey'\nimport { ga4EventName } from './eventName'\nimport { MEASUREMENT_ID_PATTERN } from './measurementId'\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\t/**\n\t * Public measurement id (`G-XXXXXXX`). Setting it turns on capture: the tag is loaded\n\t * from googletagmanager.com and booted with gtag.\n\t */\n\tmeasurementId?: string\n\t/**\n\t * `{ BetaAnalyticsDataClient }` from `@google-analytics/data`. Unset, the plugin's `sdks.ga4`\n\t * serves, and without either it is loaded at runtime, which a standalone build does not ship.\n\t */\n\tsdk?: Ga4Sdk\n\t/**\n\t * The property's ISO 4217 currency, used only when an answer names none; GA4's own wins. Anything\n\t * but such a code throws when the adapter is built.\n\t */\n\tcurrency?: string\n}\n\n/** How long one report may take when the adapter is called outside the engine, which sets its own. */\nconst DEFAULT_REPORT_TIMEOUT_MS = 60_000\n\n/**\n * Cancels a Data API call when its read gives up, where `cancel` survives: `@google-analytics/data`\n * 6.1 drops it, leaving the call's own gRPC `timeout` to bound it.\n */\nconst cancelWhenAborted = (call: Promise<unknown>, signal: AbortSignal | undefined): void => {\n\tconst cancel: unknown = Reflect.get(call, 'cancel')\n\tif (!signal || typeof cancel !== 'function') {\n\t\treturn\n\t}\n\tconst onAbort = (): void => {\n\t\tReflect.apply(cancel, call, [])\n\t}\n\tif (signal.aborted) {\n\t\tonAbort()\n\t\treturn\n\t}\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\tvoid call.then(\n\t\t() => signal.removeEventListener('abort', onAbort),\n\t\t() => signal.removeEventListener('abort', onAbort)\n\t)\n}\n\n/**\n * Google's install snippet, inline first as consent mode expects, led by the exclusion guard. The\n * tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404.\n */\nfunction buildCapture(measurementId: string): CaptureSupport {\n\tconst id = jsLiteral(measurementId)\n\treturn {\n\t\tproxy: { routes: [] },\n\t\tsnippet: () => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag(\"js\",new Date());gtag(\"config\",${id})`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsrc: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,\n\t\t\t\t\tasync: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'ga4', measurementId },\n\t}\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\tvisitDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst ENGAGED_SECONDS = 'userEngagementDuration'\nconst VIEWS = 'screenPageViews'\n\n/**\n * The GA4 metrics each contract metric is read from. Time on page is engaged seconds over views;\n * both are sums, so the ratio holds per row and for the totals alike.\n */\nconst METRIC_SOURCES: Partial<Record<MetricKey, string | readonly string[]>> = {\n\t...METRIC_MAP,\n\tavgDuration: [ENGAGED_SECONDS, VIEWS],\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tchannel: 'sessionDefaultChannelGroup',\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\tgoal: 'eventName',\n}\n\n/**\n * Metrics GA4 answers only for a goal-restricted read. `keyEvents` counts only events the property\n * marks as key events, so a goal here that GA4 does not mark reports 0.\n */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions'])\n\n/**\n * The hint's slugs by the GA4 event name each normalizes to, for the request and mapping rows back.\n * Two slugs normalizing alike are one GA4 event: the first slug owns its rows.\n */\nconst goalSlugsByEventName = (slugs: string[]): Map<string, string> => {\n\tconst byName = new Map<string, string>()\n\tfor (const slug of slugs) {\n\t\tconst name = ga4EventName(slug)\n\t\tif (!byName.has(name)) {\n\t\t\tbyName.set(name, slug)\n\t\t}\n\t}\n\treturn byName\n}\n\ntype StringMatchType = 'EXACT' | 'CONTAINS' | 'FULL_REGEXP'\n\n/**\n * FULL_REGEXP is a full match, so a pattern has to cover the whole value (`/docs/.*`, not\n * `^/docs`). PARTIAL_REGEXP exists but is not the contract's `matches`.\n */\nconst MATCH_TYPE_MAP: Record<FilterOperator, StringMatchType> = {\n\teq: 'EXACT',\n\tcontains: 'CONTAINS',\n\tmatches: 'FULL_REGEXP',\n}\n\n// The Data API defaults caseSensitive to false, so it is explicit: `contains` stays\n// insensitive like native and Umami's ilike, while `eq` and `matches` compare literally.\nconst CASE_SENSITIVE: Record<StringMatchType, boolean> = {\n\tEXACT: true,\n\tCONTAINS: false,\n\tFULL_REGEXP: true,\n}\n\n/**\n * A filter expression as the Data API reads one (`FilterExpression` in its REST reference), written\n * here so the adapter needs no type of the SDK.\n */\ninterface FilterExpression {\n\tfilter?: {\n\t\tfieldName: string\n\t\tstringFilter?: { matchType: StringMatchType; value: string; caseSensitive: boolean }\n\t\tinListFilter?: { values: string[]; caseSensitive: boolean }\n\t}\n\tandGroup?: { expressions: FilterExpression[] }\n}\n\n/** The parts of a `RunReportRequest` a read adds to the property, the window and the metrics. */\ninterface ReportShape {\n\tdimensions?: Array<{ name: string }>\n\tmetricAggregations?: Array<'TOTAL'>\n\torderBys?: Array<{ dimension: { dimensionName: string } }>\n\tlimit?: number\n}\n\nconst stringFilter = (\n\tfieldName: string,\n\tmatchType: StringMatchType,\n\tvalue: string\n): FilterExpression => ({\n\tfilter: {\n\t\tfieldName,\n\t\tstringFilter: { matchType, value, caseSensitive: CASE_SENSITIVE[matchType] },\n\t},\n})\n\n/** `exprs` as one dimension filter: none, the only one, or all of them and-ed. */\nconst allOf = (exprs: FilterExpression[]): FilterExpression | undefined =>\n\texprs.length > 1 ? { andGroup: { expressions: exprs } } : exprs[0]\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n\t'visitDuration',\n\t'events',\n\t'conversions',\n\t'revenue',\n])\nconst ga4Dimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\n/**\n * Views are page_view and screen_view events only, so a time on page per event name divides the\n * engagement of one event by the views of another: it is read under every other breakdown.\n */\nconst ga4Reach: Partial<Record<MetricKey, MetricReach>> = {\n\tavgDuration: {\n\t\tdimensions: [...ga4Dimensions].filter(\n\t\t\t(dimension) => dimension !== 'event' && dimension !== 'goal'\n\t\t),\n\t},\n}\nconst ga4Filters = everyOperatorOn(ga4Dimensions)\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 === 'visitDuration') {\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\ninterface Ga4Reading {\n\tmetrics: MetricValues\n\t/** The views each time on page was taken over, which folds days into weeks exactly. */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** One report row's contract metrics, each read back by GA4 name from the report's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: Ga4ReportRow): Ga4Reading => {\n\tconst raw = (name: string): unknown => row.metricValues?.[names.indexOf(name)]?.value\n\tconst out: MetricValues = {}\n\tlet samples: Ga4Reading['samples']\n\tfor (const metric of metrics) {\n\t\tif (metric === 'avgDuration') {\n\t\t\tconst views = vendorReading('pageviews', raw(VIEWS)) ?? 0\n\t\t\tconst engaged = vendorReading('avgDuration', raw(ENGAGED_SECONDS))\n\t\t\tout.avgDuration = views > 0 && engaged !== null ? Math.round((engaged / views) * 1000) : null\n\t\t\tsamples = { avgDuration: views }\n\t\t\tcontinue\n\t\t}\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst value = name === undefined ? null : vendorReading(metric, raw(name))\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn samples ? { metrics: out, samples } : { metrics: out }\n}\n\n/** A report's rows keyed by their dimension values; undefined when the report was never run. */\nconst keyedRows = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.rows?.map((row) => ({\n\t\tkeys: (row.dimensionValues ?? []).map((value) => value.value ?? ''),\n\t\t...readRow(metrics, names, row),\n\t})) ?? (response ? [] : undefined)\n\nconst totalsOf = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): MetricValues | undefined => {\n\tconst row = response?.totals?.[0]\n\treturn row ? readRow(metrics, names, row).metrics : undefined\n}\n\n/** GA4's `date` dimension value (`YYYYMMDD`) as a UTC-day ISO string. */\nconst ga4DayIso = (ymd: string): string | null =>\n\tdayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tmetricReach: ga4Reach,\n\t\tfilters: ga4Filters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { maxConcurrent: 10, readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t\tupstreamAware: true,\n\t}\n\tconst configCurrency = currencyOption('ga4({ currency })', config.currency)\n\n\t/** One client per Payload instance, so closing one instance's leaves the others' open. */\n\tconst clients = new WeakMap<object, Promise<Ga4Client>>()\n\t/** The instances this adapter was closed for, which get no client again until attached anew. */\n\tconst closed = new WeakSet<object>()\n\t/** Whom a read with no instance in its context shares a client with. */\n\tconst unattached = {}\n\t/** The plugin's `sdks.ga4`, handed over when the plugin registers this adapter. */\n\tlet pluginSdk: Ga4Sdk | undefined\n\tlet warned = false\n\tconst sdk = (): Ga4Sdk | undefined => config.sdk ?? pluginSdk\n\n\tconst getClient = (payload: Payload | undefined): Promise<Ga4Client> => {\n\t\tconst owner = payload ?? unattached\n\t\tconst held = clients.get(owner)\n\t\tif (held) {\n\t\t\treturn held\n\t\t}\n\t\t// A read that reaches a closed adapter late (a retired runtime's refresh) would otherwise\n\t\t// open a client nothing ever closes.\n\t\tif (closed.has(owner)) {\n\t\t\treturn Promise.reject(new Error('analytics: this GA4 source was closed'))\n\t\t}\n\t\tconst created = (async () => {\n\t\t\tconst mod = sdk() ?? (await loadGa4())\n\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\tcredentials: config.credentials,\n\t\t\t\t...(config.projectId ? { projectId: config.projectId } : {}),\n\t\t\t})\n\t\t})()\n\t\tclients.set(owner, created)\n\t\treturn created\n\t}\n\n\tconst measurementId = config.measurementId\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\t// An id that is not a bare token is dropped rather than escaped: it lands in an inline\n\t\t// script and in the tag URL, and no legitimate measurement id needs anything else.\n\t\t...(measurementId && MEASUREMENT_ID_PATTERN.test(measurementId)\n\t\t\t? { capture: buildCapture(measurementId) }\n\t\t\t: {}),\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\tregister(_config, context) {\n\t\t\tpluginSdk = context?.sdks?.ga4\n\t\t},\n\t\t// At boot, before the first read fails in front of an editor.\n\t\tattach(payload: Payload) {\n\t\t\tclosed.delete(payload)\n\t\t\tif (!warned && sdk() === undefined && isProductionBuild()) {\n\t\t\t\twarned = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tclosed.add(payload)\n\t\t\tconst held = clients.get(payload)\n\t\t\tclients.delete(payload)\n\t\t\tconst client = await held?.catch(() => undefined)\n\t\t\tawait client?.close?.()\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'ga4', fetchedAt, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_SOURCES)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_SOURCES)\n\t\t\tconst providerDims = [...new Set(dims.flatMap((d) => DIMENSION_MAP[d] ?? []))]\n\t\t\t// Set when GA4 rejects a goal report the site report survived, so the rows keep their\n\t\t\t// site metrics and lose only their conversions.\n\t\t\tlet goalsFailed = false\n\t\t\t// What the answers said about themselves: a sampled report anywhere makes the read an estimate.\n\t\t\tlet sampled = false\n\t\t\tlet reportedCurrency: string | undefined\n\t\t\tconst meta = (): AnalyticsResult['meta'] => {\n\t\t\t\tconst currency = reportedCurrency ?? configCurrency\n\t\t\t\treturn {\n\t\t\t\t\tprovider: 'ga4',\n\t\t\t\t\tfetchedAt,\n\t\t\t\t\t...(currency ? { currency } : {}),\n\t\t\t\t\t...(sampled ? { sampled: true } : {}),\n\t\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst filterExprs: FilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push(stringFilter('pagePath', 'EXACT', q.path))\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push(stringFilter('hostName', 'EXACT', q.hostname))\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilterExprs.push(stringFilter(field, MATCH_TYPE_MAP[filter.operator], filter.value))\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalSlugs = slugs ? goalSlugsByEventName(slugs) : null\n\t\t\tconst goalExprs: FilterExpression[] = goalSlugs\n\t\t\t\t? [\n\t\t\t\t\t\t...filterExprs,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfilter: {\n\t\t\t\t\t\t\t\tfieldName: 'eventName',\n\t\t\t\t\t\t\t\tinListFilter: { values: [...goalSlugs.keys()], caseSensitive: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: filterExprs\n\t\t\t// A goal breakdown restricts its own rows, so its one report carries the hint too.\n\t\t\tconst siteExprs = goalBreakdown ? goalExprs : filterExprs\n\n\t\t\tconst [startDate, endDate] = calendarDays(q)\n\t\t\tconst client = await getClient(ctx.payload)\n\n\t\t\t// Each report is one upstream request with its own token, so a paired read spends two. It\n\t\t\t// runs with no retry of the SDK's own (the lane retries) and a deadline of what the read has left.\n\t\t\tconst runReport = (\n\t\t\t\tnames: string[],\n\t\t\t\texprs: FilterExpression[],\n\t\t\t\tshape: ReportShape\n\t\t\t): Promise<Ga4ReportResponse> =>\n\t\t\t\tupstream(ctx, async (signal) => {\n\t\t\t\t\tconst dimensionFilter = allOf(exprs)\n\t\t\t\t\tconst request = {\n\t\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\t\tdateRanges: [{ startDate, endDate }],\n\t\t\t\t\t\tmetrics: names.map((name) => ({ name })),\n\t\t\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t}\n\t\t\t\t\tconst timeout = Math.max(1, Math.floor(ctx.remainingMs?.() ?? DEFAULT_REPORT_TIMEOUT_MS))\n\t\t\t\t\tconst call = client.runReport(request, { timeout, retry: null })\n\t\t\t\t\tcancelWhenAborted(call, signal)\n\t\t\t\t\tconst [response] = await call\n\t\t\t\t\tif ((response.metadata?.samplingMetadatas?.length ?? 0) > 0) {\n\t\t\t\t\t\tsampled = true\n\t\t\t\t\t}\n\t\t\t\t\tconst code = response.metadata?.currencyCode?.toUpperCase()\n\t\t\t\t\tif (code && CURRENCY_PATTERN.test(code)) {\n\t\t\t\t\t\treportedCurrency = code\n\t\t\t\t\t}\n\t\t\t\t\treturn response\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One report shape run plainly and goal-filtered, unioned per row. `limit` is the site report's\n\t\t\t * alone, since a goal ranked outside its top N would otherwise drop out of the union.\n\t\t\t */\n\t\t\tconst runPair = async (\n\t\t\t\tshape: ReportShape,\n\t\t\t\tlimit?: number\n\t\t\t): Promise<{ rows: GoalKeyedRow[]; totals: MetricValues | undefined }> => {\n\t\t\t\tconst siteShape = limit ? { ...shape, limit } : shape\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => runReport(siteNames, siteExprs, siteShape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => runReport(goalNames, goalExprs, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\trows: mergeGoalRows(\n\t\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t\ttotals: mergeGoalTotals(\n\t\t\t\t\t\ttotalsOf(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\ttotalsOf(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst report = await runPair({\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: ['TOTAL'],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(report.rows, ga4DayIso),\n\t\t\t\t\ttotals: report.totals ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst report = await runPair(\n\t\t\t\tproviderDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {},\n\t\t\t\tq.limit\n\t\t\t)\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = report.rows[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = report.rows.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst name = DIMENSION_MAP[d]\n\t\t\t\t\tconst value =\n\t\t\t\t\t\t(name === undefined ? undefined : row.keys[providerDims.indexOf(name)]) ?? ''\n\t\t\t\t\t// A `goal` row reports the slug it was asked for; an `event` row reports GA4's own\n\t\t\t\t\t// event name, even though both read the same dimension.\n\t\t\t\t\tdimensions[d] = d === 'goal' ? (goalSlugs?.get(value) ?? value) : value\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetrics: row.metrics,\n\t\t\t\t\t...(row.samples ? { samples: row.samples } : {}),\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyEA,MAAM,4BAA4B;;;;;AAMlC,MAAM,qBAAqB,MAAwB,WAA0C;CAC5F,MAAM,SAAkB,QAAQ,IAAI,MAAM,QAAQ;CAClD,IAAI,CAAC,UAAU,OAAO,WAAW,YAChC;CAED,MAAM,gBAAsB;EAC3B,QAAQ,MAAM,QAAQ,MAAM,CAAC,CAAC;CAC/B;CACA,IAAI,OAAO,SAAS;EACnB,QAAQ;EACR;CACD;CACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACxD,KAAU,WACH,OAAO,oBAAoB,SAAS,OAAO,SAC3C,OAAO,oBAAoB,SAAS,OAAO,CAClD;AACD;;;;;AAMA,SAAS,aAAa,eAAuC;CAC5D,MAAM,KAAK,UAAU,aAAa;CAClC,OAAO;EACN,OAAO,EAAE,QAAQ,CAAC,EAAE;EACpB,gBAAgB,EACf,SAAS,CACR,EACC,QAAQ,GAAG,gBAAgB,aAAa,EAAE,sHAAsH,GAAG,GACpK,GACA;GACC,KAAK,+CAA+C,mBAAmB,aAAa;GACpF,OAAO;EACR,CACD,EACD;EACA,QAAQ;GAAE,MAAM;GAAO;EAAc;CACtC;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,eAAe;CACf,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,kBAAkB;AACxB,MAAM,QAAQ;;;;;AAMd,MAAM,iBAAyE;CAC9E,GAAG;CACH,aAAa,CAAC,iBAAiB,KAAK;AACrC;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,SAAS;CACT,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AM,SACJ,SAAS,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,aAAa,QAAQ,IAAI,OAAO;MAG5E,WAAW,KAAK,MAAM,SAAU,WAAW,IAAI,KAAK,KAAK,QAAS;KACnE;KACA,OAAO;MACN;MACA,SAAS,IAAI;MACb,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;KAC/C;IACD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport { vendorReading } from '../../core/metricValues'\nimport type { Ga4Client, Ga4ReportResponse, Ga4ReportRow, Ga4Sdk } from '../../core/sdks'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { CURRENCY_PATTERN, currencyOption } from '../../goals/currency'\nimport { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from '../../plugin/peers'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tmergeGoalTotals,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstream } from '../upstream'\nimport { ga4ExcludeGuard } from './disableKey'\nimport { ga4EventName } from './eventName'\nimport { MEASUREMENT_ID_PATTERN } from './measurementId'\n\nexport interface Ga4Config {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Google Analytics 4'`.\n\t */\n\tlabel?: AdapterLabelOption\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\t/**\n\t * Public measurement id (`G-XXXXXXX`). Setting it turns on capture: the tag is loaded\n\t * from googletagmanager.com and booted with gtag.\n\t */\n\tmeasurementId?: string\n\t/**\n\t * `{ BetaAnalyticsDataClient }` from `@google-analytics/data`. Unset, the plugin's `sdks.ga4`\n\t * serves, and without either it is loaded at runtime, which a standalone build does not ship.\n\t */\n\tsdk?: Ga4Sdk\n\t/**\n\t * The property's ISO 4217 currency, used only when an answer names none; GA4's own wins. Anything\n\t * but such a code throws when the adapter is built.\n\t */\n\tcurrency?: string\n}\n\n/** How long one report may take when the adapter is called outside the engine, which sets its own. */\nconst DEFAULT_REPORT_TIMEOUT_MS = 60_000\n\n/**\n * Cancels a Data API call when its read gives up, where `cancel` survives: `@google-analytics/data`\n * 6.1 drops it, leaving the call's own gRPC `timeout` to bound it.\n */\nconst cancelWhenAborted = (call: Promise<unknown>, signal: AbortSignal | undefined): void => {\n\tconst cancel: unknown = Reflect.get(call, 'cancel')\n\tif (!signal || typeof cancel !== 'function') {\n\t\treturn\n\t}\n\tconst onAbort = (): void => {\n\t\tReflect.apply(cancel, call, [])\n\t}\n\tif (signal.aborted) {\n\t\tonAbort()\n\t\treturn\n\t}\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\tvoid call.then(\n\t\t() => signal.removeEventListener('abort', onAbort),\n\t\t() => signal.removeEventListener('abort', onAbort)\n\t)\n}\n\n/**\n * Google's install snippet, inline first as consent mode expects, led by the exclusion guard. The\n * tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404.\n */\nfunction buildCapture(measurementId: string): CaptureSupport {\n\tconst id = jsLiteral(measurementId)\n\treturn {\n\t\tproxy: { routes: [] },\n\t\tsnippet: () => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag(\"js\",new Date());gtag(\"config\",${id})`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsrc: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,\n\t\t\t\t\tasync: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'ga4', measurementId },\n\t}\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\tvisitDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst ENGAGED_SECONDS = 'userEngagementDuration'\nconst VIEWS = 'screenPageViews'\n\n/**\n * The GA4 metrics each contract metric is read from. Time on page is engaged seconds over views;\n * both are sums, so the ratio holds per row and for the totals alike.\n */\nconst METRIC_SOURCES: Partial<Record<MetricKey, string | readonly string[]>> = {\n\t...METRIC_MAP,\n\tavgDuration: [ENGAGED_SECONDS, VIEWS],\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tchannel: 'sessionDefaultChannelGroup',\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\tgoal: 'eventName',\n}\n\n/**\n * Metrics GA4 answers only for a goal-restricted read. `keyEvents` counts only events the property\n * marks as key events, so a goal here that GA4 does not mark reports 0.\n */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions'])\n\n/**\n * The hint's slugs by the GA4 event name each normalizes to, for the request and mapping rows back.\n * Two slugs normalizing alike are one GA4 event: the first slug owns its rows.\n */\nconst goalSlugsByEventName = (slugs: string[]): Map<string, string> => {\n\tconst byName = new Map<string, string>()\n\tfor (const slug of slugs) {\n\t\tconst name = ga4EventName(slug)\n\t\tif (!byName.has(name)) {\n\t\t\tbyName.set(name, slug)\n\t\t}\n\t}\n\treturn byName\n}\n\ntype StringMatchType = 'EXACT' | 'CONTAINS' | 'FULL_REGEXP'\n\n/**\n * FULL_REGEXP is a full match, so a pattern has to cover the whole value (`/docs/.*`, not\n * `^/docs`). PARTIAL_REGEXP exists but is not the contract's `matches`.\n */\nconst MATCH_TYPE_MAP: Record<FilterOperator, StringMatchType> = {\n\teq: 'EXACT',\n\tcontains: 'CONTAINS',\n\tmatches: 'FULL_REGEXP',\n}\n\n// The Data API defaults caseSensitive to false, so it is explicit: `contains` stays\n// insensitive like native and Umami's ilike, while `eq` and `matches` compare literally.\nconst CASE_SENSITIVE: Record<StringMatchType, boolean> = {\n\tEXACT: true,\n\tCONTAINS: false,\n\tFULL_REGEXP: true,\n}\n\n/**\n * A filter expression as the Data API reads one (`FilterExpression` in its REST reference), written\n * here so the adapter needs no type of the SDK.\n */\ninterface FilterExpression {\n\tfilter?: {\n\t\tfieldName: string\n\t\tstringFilter?: { matchType: StringMatchType; value: string; caseSensitive: boolean }\n\t\tinListFilter?: { values: string[]; caseSensitive: boolean }\n\t}\n\tandGroup?: { expressions: FilterExpression[] }\n}\n\n/** The parts of a `RunReportRequest` a read adds to the property, the window and the metrics. */\ninterface ReportShape {\n\tdimensions?: Array<{ name: string }>\n\tmetricAggregations?: Array<'TOTAL'>\n\torderBys?: Array<{ dimension: { dimensionName: string } }>\n\tlimit?: number\n}\n\nconst stringFilter = (\n\tfieldName: string,\n\tmatchType: StringMatchType,\n\tvalue: string\n): FilterExpression => ({\n\tfilter: {\n\t\tfieldName,\n\t\tstringFilter: { matchType, value, caseSensitive: CASE_SENSITIVE[matchType] },\n\t},\n})\n\n/** `exprs` as one dimension filter: none, the only one, or all of them and-ed. */\nconst allOf = (exprs: FilterExpression[]): FilterExpression | undefined =>\n\texprs.length > 1 ? { andGroup: { expressions: exprs } } : exprs[0]\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n\t'visitDuration',\n\t'events',\n\t'conversions',\n\t'revenue',\n])\nconst ga4Dimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\n/**\n * Views are page_view and screen_view events only, so a time on page per event name divides the\n * engagement of one event by the views of another: it is read under every other breakdown.\n */\nconst ga4Reach: Partial<Record<MetricKey, MetricReach>> = {\n\tavgDuration: {\n\t\tdimensions: [...ga4Dimensions].filter(\n\t\t\t(dimension) => dimension !== 'event' && dimension !== 'goal'\n\t\t),\n\t},\n}\nconst ga4Filters = everyOperatorOn(ga4Dimensions)\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 === 'visitDuration') {\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\ninterface Ga4Reading {\n\tmetrics: MetricValues\n\t/** The views each time on page was taken over, which folds days into weeks exactly. */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** One report row's contract metrics, each read back by GA4 name from the report's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: Ga4ReportRow): Ga4Reading => {\n\tconst raw = (name: string): unknown => row.metricValues?.[names.indexOf(name)]?.value\n\tconst out: MetricValues = {}\n\tlet samples: Ga4Reading['samples']\n\tfor (const metric of metrics) {\n\t\tif (metric === 'avgDuration') {\n\t\t\tconst views = vendorReading('pageviews', raw(VIEWS)) ?? 0\n\t\t\tconst engaged = vendorReading('avgDuration', raw(ENGAGED_SECONDS))\n\t\t\tout.avgDuration = views > 0 && engaged !== null ? Math.round((engaged / views) * 1000) : null\n\t\t\tsamples = { avgDuration: views }\n\t\t\tcontinue\n\t\t}\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst value = name === undefined ? null : vendorReading(metric, raw(name))\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn samples ? { metrics: out, samples } : { metrics: out }\n}\n\n/** A report's rows keyed by their dimension values; undefined when the report was never run. */\nconst keyedRows = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.rows?.map((row) => ({\n\t\tkeys: (row.dimensionValues ?? []).map((value) => value.value ?? ''),\n\t\t...readRow(metrics, names, row),\n\t})) ?? (response ? [] : undefined)\n\nconst totalsOf = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): MetricValues | undefined => {\n\tconst row = response?.totals?.[0]\n\treturn row ? readRow(metrics, names, row).metrics : undefined\n}\n\n/** GA4's `date` dimension value (`YYYYMMDD`) as a UTC-day ISO string. */\nconst ga4DayIso = (ymd: string): string | null =>\n\tdayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tmetricReach: ga4Reach,\n\t\tfilters: ga4Filters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { maxConcurrent: 10, readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t\tupstreamAware: true,\n\t}\n\tconst configCurrency = currencyOption('ga4({ currency })', config.currency)\n\n\t/** One client per Payload instance, so closing one instance's leaves the others' open. */\n\tconst clients = new WeakMap<object, Promise<Ga4Client>>()\n\t/** The instances this adapter was closed for, which get no client again until attached anew. */\n\tconst closed = new WeakSet<object>()\n\t/** Whom a read with no instance in its context shares a client with. */\n\tconst unattached = {}\n\t/** The plugin's `sdks.ga4`, handed over when the plugin registers this adapter. */\n\tlet pluginSdk: Ga4Sdk | undefined\n\tlet warned = false\n\tconst sdk = (): Ga4Sdk | undefined => config.sdk ?? pluginSdk\n\n\tconst getClient = (payload: Payload | undefined): Promise<Ga4Client> => {\n\t\tconst owner = payload ?? unattached\n\t\tconst held = clients.get(owner)\n\t\tif (held) {\n\t\t\treturn held\n\t\t}\n\t\t// A read that reaches a closed adapter late (a retired runtime's refresh) would otherwise\n\t\t// open a client nothing ever closes.\n\t\tif (closed.has(owner)) {\n\t\t\treturn Promise.reject(new Error('analytics: this GA4 source was closed'))\n\t\t}\n\t\tconst created = (async () => {\n\t\t\tconst mod = sdk() ?? (await loadGa4())\n\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\tcredentials: config.credentials,\n\t\t\t\t...(config.projectId ? { projectId: config.projectId } : {}),\n\t\t\t})\n\t\t})()\n\t\tclients.set(owner, created)\n\t\treturn created\n\t}\n\n\tconst measurementId = config.measurementId\n\treturn {\n\t\tid: 'ga4',\n\t\t...adapterLabel(config.label, 'Google Analytics 4', 'ga4({ label })'),\n\t\tcapabilities,\n\t\t// An id that is not a bare token is dropped rather than escaped: it lands in an inline\n\t\t// script and in the tag URL, and no legitimate measurement id needs anything else.\n\t\t...(measurementId && MEASUREMENT_ID_PATTERN.test(measurementId)\n\t\t\t? { capture: buildCapture(measurementId) }\n\t\t\t: {}),\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\tregister(_config, context) {\n\t\t\tpluginSdk = context?.sdks?.ga4\n\t\t},\n\t\t// At boot, before the first read fails in front of an editor.\n\t\tattach(payload: Payload) {\n\t\t\tclosed.delete(payload)\n\t\t\tif (!warned && sdk() === undefined && isProductionBuild()) {\n\t\t\t\twarned = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tclosed.add(payload)\n\t\t\tconst held = clients.get(payload)\n\t\t\tclients.delete(payload)\n\t\t\tconst client = await held?.catch(() => undefined)\n\t\t\tawait client?.close?.()\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'ga4', fetchedAt, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_SOURCES)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_SOURCES)\n\t\t\tconst providerDims = [...new Set(dims.flatMap((d) => DIMENSION_MAP[d] ?? []))]\n\t\t\t// Set when GA4 rejects a goal report the site report survived, so the rows keep their\n\t\t\t// site metrics and lose only their conversions.\n\t\t\tlet goalsFailed = false\n\t\t\t// What the answers said about themselves: a sampled report anywhere makes the read an estimate.\n\t\t\tlet sampled = false\n\t\t\tlet reportedCurrency: string | undefined\n\t\t\tconst meta = (): AnalyticsResult['meta'] => {\n\t\t\t\tconst currency = reportedCurrency ?? configCurrency\n\t\t\t\treturn {\n\t\t\t\t\tprovider: 'ga4',\n\t\t\t\t\tfetchedAt,\n\t\t\t\t\t...(currency ? { currency } : {}),\n\t\t\t\t\t...(sampled ? { sampled: true } : {}),\n\t\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst filterExprs: FilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push(stringFilter('pagePath', 'EXACT', q.path))\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push(stringFilter('hostName', 'EXACT', q.hostname))\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilterExprs.push(stringFilter(field, MATCH_TYPE_MAP[filter.operator], filter.value))\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalSlugs = slugs ? goalSlugsByEventName(slugs) : null\n\t\t\tconst goalExprs: FilterExpression[] = goalSlugs\n\t\t\t\t? [\n\t\t\t\t\t\t...filterExprs,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfilter: {\n\t\t\t\t\t\t\t\tfieldName: 'eventName',\n\t\t\t\t\t\t\t\tinListFilter: { values: [...goalSlugs.keys()], caseSensitive: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: filterExprs\n\t\t\t// A goal breakdown restricts its own rows, so its one report carries the hint too.\n\t\t\tconst siteExprs = goalBreakdown ? goalExprs : filterExprs\n\n\t\t\tconst [startDate, endDate] = calendarDays(q)\n\t\t\tconst client = await getClient(ctx.payload)\n\n\t\t\t// Each report is one upstream request with its own token, so a paired read spends two. It\n\t\t\t// runs with no retry of the SDK's own (the lane retries) and a deadline of what the read has left.\n\t\t\tconst runReport = (\n\t\t\t\tnames: string[],\n\t\t\t\texprs: FilterExpression[],\n\t\t\t\tshape: ReportShape\n\t\t\t): Promise<Ga4ReportResponse> =>\n\t\t\t\tupstream(ctx, async (signal) => {\n\t\t\t\t\tconst dimensionFilter = allOf(exprs)\n\t\t\t\t\tconst request = {\n\t\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\t\tdateRanges: [{ startDate, endDate }],\n\t\t\t\t\t\tmetrics: names.map((name) => ({ name })),\n\t\t\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t}\n\t\t\t\t\tconst timeout = Math.max(1, Math.floor(ctx.remainingMs?.() ?? DEFAULT_REPORT_TIMEOUT_MS))\n\t\t\t\t\tconst call = client.runReport(request, { timeout, retry: null })\n\t\t\t\t\tcancelWhenAborted(call, signal)\n\t\t\t\t\tconst [response] = await call\n\t\t\t\t\tif ((response.metadata?.samplingMetadatas?.length ?? 0) > 0) {\n\t\t\t\t\t\tsampled = true\n\t\t\t\t\t}\n\t\t\t\t\tconst code = response.metadata?.currencyCode?.toUpperCase()\n\t\t\t\t\tif (code && CURRENCY_PATTERN.test(code)) {\n\t\t\t\t\t\treportedCurrency = code\n\t\t\t\t\t}\n\t\t\t\t\treturn response\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One report shape run plainly and goal-filtered, unioned per row. `limit` is the site report's\n\t\t\t * alone, since a goal ranked outside its top N would otherwise drop out of the union.\n\t\t\t */\n\t\t\tconst runPair = async (\n\t\t\t\tshape: ReportShape,\n\t\t\t\tlimit?: number\n\t\t\t): Promise<{ rows: GoalKeyedRow[]; totals: MetricValues | undefined }> => {\n\t\t\t\tconst siteShape = limit ? { ...shape, limit } : shape\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => runReport(siteNames, siteExprs, siteShape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => runReport(goalNames, goalExprs, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\trows: mergeGoalRows(\n\t\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t\ttotals: mergeGoalTotals(\n\t\t\t\t\t\ttotalsOf(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\ttotalsOf(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst report = await runPair({\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: ['TOTAL'],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(report.rows, ga4DayIso),\n\t\t\t\t\ttotals: report.totals ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst report = await runPair(\n\t\t\t\tproviderDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {},\n\t\t\t\tq.limit\n\t\t\t)\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = report.rows[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = report.rows.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst name = DIMENSION_MAP[d]\n\t\t\t\t\tconst value =\n\t\t\t\t\t\t(name === undefined ? undefined : row.keys[providerDims.indexOf(name)]) ?? ''\n\t\t\t\t\t// A `goal` row reports the slug it was asked for; an `event` row reports GA4's own\n\t\t\t\t\t// event name, even though both read the same dimension.\n\t\t\t\t\tdimensions[d] = d === 'goal' ? (goalSlugs?.get(value) ?? value) : value\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetrics: row.metrics,\n\t\t\t\t\t...(row.samples ? { samples: row.samples } : {}),\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+EA,MAAM,4BAA4B;;;;;AAMlC,MAAM,qBAAqB,MAAwB,WAA0C;CAC5F,MAAM,SAAkB,QAAQ,IAAI,MAAM,QAAQ;CAClD,IAAI,CAAC,UAAU,OAAO,WAAW,YAChC;CAED,MAAM,gBAAsB;EAC3B,QAAQ,MAAM,QAAQ,MAAM,CAAC,CAAC;CAC/B;CACA,IAAI,OAAO,SAAS;EACnB,QAAQ;EACR;CACD;CACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACxD,KAAU,WACH,OAAO,oBAAoB,SAAS,OAAO,SAC3C,OAAO,oBAAoB,SAAS,OAAO,CAClD;AACD;;;;;AAMA,SAAS,aAAa,eAAuC;CAC5D,MAAM,KAAK,UAAU,aAAa;CAClC,OAAO;EACN,OAAO,EAAE,QAAQ,CAAC,EAAE;EACpB,gBAAgB,EACf,SAAS,CACR,EACC,QAAQ,GAAG,gBAAgB,aAAa,EAAE,sHAAsH,GAAG,GACpK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AAM,KAAK;IACZ;GACD;GAEA,MAAM,SAAS,MAAM,QACpB,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC,GAChF,EAAE,KACH;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,OAAO,KAAK,IAAI,WAAW,CAAC;IAC3C,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAkBA,OAAO;IAAE,MAhBoB,OAAO,KAAK,KAAK,QAAQ;KACrD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,OAAO,cAAc;MAC3B,MAAM,SACJ,SAAS,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,aAAa,QAAQ,IAAI,OAAO;MAG5E,WAAW,KAAK,MAAM,SAAU,WAAW,IAAI,KAAK,KAAK,QAAS;KACnE;KACA,OAAO;MACN;MACA,SAAS,IAAI;MACb,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;KAC/C;IACD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
@@ -1,8 +1,14 @@
1
1
  import { FetchLike } from "../../core/fetch.js";
2
2
  import { AnalyticsAdapter } from "../../core/contract.js";
3
+ import { AdapterLabelOption } from "../../core/sourceLabel.js";
3
4
 
4
5
  //#region src/adapters/plausible/plausible.d.ts
5
6
  interface PlausibleConfig {
7
+ /**
8
+ * The source's name in pickers and listings: a string, a map by admin language (read like
9
+ * `view.navLabel`), or a function naming it per reader and scope. Default `'Plausible'`.
10
+ */
11
+ label?: AdapterLabelOption;
6
12
  siteId: string;
7
13
  apiKey: string;
8
14
  /**
@@ -1,4 +1,5 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { adapterLabel } from "../../core/sourceLabel.js";
2
3
  import { jsLiteral } from "../../capture/jsLiteral.js";
3
4
  import { isScriptId } from "./scriptId.js";
4
5
  import { currencyOption } from "../../goals/currency.js";
@@ -168,7 +169,7 @@ function plausible(config) {
168
169
  };
169
170
  return {
170
171
  id: "plausible",
171
- label: "Plausible",
172
+ ...adapterLabel(config.label, "Plausible", "plausible({ label })"),
172
173
  capabilities,
173
174
  ...config.domain || scriptId ? { capture: buildCapture(config, scriptId) } : {},
174
175
  isConfigured: () => Boolean(config.siteId && config.apiKey),
@@ -1 +1 @@
1
- {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { currencyOption } from '../../goals/currency'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { isScriptId } from './scriptId'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/**\n\t * Address of a self-hosted Community Edition, with the base path when it runs under one.\n\t * Defaults to Plausible Cloud.\n\t */\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: letters, digits, `_`\n\t * and `-`. Any other value is dropped, and capture then needs `domain`.\n\t */\n\tscriptId?: string\n\t/**\n\t * The ISO 4217 currency of the site's revenue goals. Declaring it turns on `revenue`: Plausible\n\t * errors the whole request for `total_revenue` on a site without a revenue goal.\n\t */\n\trevenueCurrency?: string\n\t/** The fetch reads and the capture proxy reach Plausible with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\nconst PLAUSIBLE_CLOUD = 'https://plausible.io'\n\n/**\n * Plausible's official per-site stub, safe beside the async loader in either order. `init` is\n * guarded with `||` because the loader may win the race, and overwriting it would lose the 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, scriptId: string | undefined): CaptureSupport {\n\tconst base = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\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 (scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${encodeURIComponent(scriptId)}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${jsLiteral(`${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*`, kind: 'script' },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event`, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\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\tvisitDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\tchannel: 'visit:channel',\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\tgoal: 'event:goal',\n}\n\n/** `matches` is an re2 full match, so a pattern must cover the whole value (`/docs/.*`, not `^/docs`). */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'events',\n\t'scrollDepth',\n\t'conversions',\n\t'revenue',\n])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\nconst withoutGoal: readonly DimensionKey[] = [...plausibleDimensions].filter(\n\t(dimension) => dimension !== 'goal'\n)\n/**\n * The Stats API refuses bounce rate and duration under event dimensions but event:page, and scroll\n * depth without event:page. Its `time_on_page` is per visit, not per pageview, so none is offered.\n */\nconst plausibleReach: Partial<Record<MetricKey, MetricReach>> = {\n\tbounceRate: { dimensions: withoutGoal },\n\tvisitDuration: { dimensions: withoutGoal },\n\tscrollDepth: { dimensions: withoutGoal, requires: 'page' },\n}\nconst plausibleFilters = everyOperatorOn(plausibleDimensions)\n\n/** One Stats API v2 filter: `[operator, dimension, values]`. */\ntype PlausibleClause = [operator: string, dimension: string, values: string[]]\n\n/** The parts of a v2 query a read adds to the site, the window, the metrics and the filters. */\ninterface QueryShape {\n\tdimensions?: string[]\n}\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract's visitDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'visitDuration' ? Math.round(raw * 1000) : raw\n\n/** One result row's contract metrics, each read back by Plausible name from the request's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: PlausibleResult): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst raw = name === undefined ? undefined : row.metrics[names.indexOf(name)]\n\t\tif (metric === 'revenue') {\n\t\t\tconst amount = revenueAmount(raw)\n\t\t\tif (amount !== undefined) {\n\t\t\t\tout.revenue = amount\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Plausible answers an average it has no samples for with null, which stays no\n\t\t// data here rather than becoming a 0 the reports would read as a real value.\n\t\tconst value = vendorReading(metric, raw)\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn out\n}\n\n/** A response's rows keyed by their dimension values; undefined when the request was never sent. */\nconst keyedRows = (\n\tresponse: PlausibleResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.results.map((row) => ({ keys: row.dimensions, metrics: readRow(metrics, names, row) }))\n\n/**\n * The Plausible adapter. A goal's slug must equal its display name in the site's goal list for its\n * conversions to read; `revenue` needs `revenueCurrency`.\n */\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst revenueCurrency = currencyOption('plausible({ revenueCurrency })', config.revenueCurrency)\n\tconst revenueGoals = revenueCurrency !== undefined\n\t// Dropped rather than escaped, like GA4's measurement id: it lands in the page's script address.\n\tconst scriptId = isScriptId(config.scriptId) ? config.scriptId : undefined\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tmetricReach: plausibleReach,\n\t\tfilters: plausibleFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || scriptId ? { capture: buildCapture(config, scriptId) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'plausible', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_MAP)\n\n\t\t\tconst filters: PlausibleClause[] = []\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\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], field, [filter.value]])\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalFilters: PlausibleClause[] = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(revenueCurrency ? { currency: revenueCurrency } : {}),\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst dateRange = calendarDays(q)\n\t\t\tconst postQuery = (\n\t\t\t\tnames: string[],\n\t\t\t\tclauses: PlausibleClause[],\n\t\t\t\tshape: QueryShape\n\t\t\t): Promise<PlausibleResponse> =>\n\t\t\t\tupstreamJson<PlausibleResponse>(ctx, `${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: names,\n\t\t\t\t\t\tdate_range: dateRange,\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t},\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (shape: QueryShape): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => postQuery(siteNames, siteFilters, shape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => postQuery(goalNames, goalFilters, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(series, dayIso),\n\t\t\t\t\ttotals: totalRows[0]?.metrics ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.flatMap((d) => DIMENSION_MAP[d] ?? []) })\n\t\t\tconst rows: AnalyticsRow[] = merged.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const [i, d] of dims.entries()) {\n\t\t\t\t\tdimensions[d] = row.keys[i] ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAuEA,MAAM,kBAAkB;;;;;AAMxB,MAAM,iBACL;AAED,SAAS,aAAa,QAAyB,UAA8C;CAC5F,MAAM,OAAO,qBAAqB,OAAO,QAAQ,eAAe;CAChE,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,UACH,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,mBAAmB,QAAQ,EAAE;GA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jB,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,IAAI,WAAW,CAAC;IACpD,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAUA,OAAO;IAAE,OAPoB,MADR,SAAS,EAAE,YAAY,KAAK,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,EAAE,CAAC,GACrD,KAAK,QAAQ;KAChD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,CAAC,GAAG,MAAM,KAAK,QAAQ,GACjC,WAAW,KAAK,IAAI,KAAK,MAAM;KAEhC,OAAO;MAAE;MAAY,SAAS,IAAI;KAAQ;IAC3C,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
1
+ {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { currencyOption } from '../../goals/currency'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { isScriptId } from './scriptId'\n\nexport interface PlausibleConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Plausible'`.\n\t */\n\tlabel?: AdapterLabelOption\n\tsiteId: string\n\tapiKey: string\n\t/**\n\t * Address of a self-hosted Community Edition, with the base path when it runs under one.\n\t * Defaults to Plausible Cloud.\n\t */\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: letters, digits, `_`\n\t * and `-`. Any other value is dropped, and capture then needs `domain`.\n\t */\n\tscriptId?: string\n\t/**\n\t * The ISO 4217 currency of the site's revenue goals. Declaring it turns on `revenue`: Plausible\n\t * errors the whole request for `total_revenue` on a site without a revenue goal.\n\t */\n\trevenueCurrency?: string\n\t/** The fetch reads and the capture proxy reach Plausible with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\nconst PLAUSIBLE_CLOUD = 'https://plausible.io'\n\n/**\n * Plausible's official per-site stub, safe beside the async loader in either order. `init` is\n * guarded with `||` because the loader may win the race, and overwriting it would lose the 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, scriptId: string | undefined): CaptureSupport {\n\tconst base = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\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 (scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${encodeURIComponent(scriptId)}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${jsLiteral(`${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*`, kind: 'script' },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event`, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\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\tvisitDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\tchannel: 'visit:channel',\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\tgoal: 'event:goal',\n}\n\n/** `matches` is an re2 full match, so a pattern must cover the whole value (`/docs/.*`, not `^/docs`). */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'events',\n\t'scrollDepth',\n\t'conversions',\n\t'revenue',\n])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\nconst withoutGoal: readonly DimensionKey[] = [...plausibleDimensions].filter(\n\t(dimension) => dimension !== 'goal'\n)\n/**\n * The Stats API refuses bounce rate and duration under event dimensions but event:page, and scroll\n * depth without event:page. Its `time_on_page` is per visit, not per pageview, so none is offered.\n */\nconst plausibleReach: Partial<Record<MetricKey, MetricReach>> = {\n\tbounceRate: { dimensions: withoutGoal },\n\tvisitDuration: { dimensions: withoutGoal },\n\tscrollDepth: { dimensions: withoutGoal, requires: 'page' },\n}\nconst plausibleFilters = everyOperatorOn(plausibleDimensions)\n\n/** One Stats API v2 filter: `[operator, dimension, values]`. */\ntype PlausibleClause = [operator: string, dimension: string, values: string[]]\n\n/** The parts of a v2 query a read adds to the site, the window, the metrics and the filters. */\ninterface QueryShape {\n\tdimensions?: string[]\n}\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract's visitDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'visitDuration' ? Math.round(raw * 1000) : raw\n\n/** One result row's contract metrics, each read back by Plausible name from the request's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: PlausibleResult): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst raw = name === undefined ? undefined : row.metrics[names.indexOf(name)]\n\t\tif (metric === 'revenue') {\n\t\t\tconst amount = revenueAmount(raw)\n\t\t\tif (amount !== undefined) {\n\t\t\t\tout.revenue = amount\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Plausible answers an average it has no samples for with null, which stays no\n\t\t// data here rather than becoming a 0 the reports would read as a real value.\n\t\tconst value = vendorReading(metric, raw)\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn out\n}\n\n/** A response's rows keyed by their dimension values; undefined when the request was never sent. */\nconst keyedRows = (\n\tresponse: PlausibleResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.results.map((row) => ({ keys: row.dimensions, metrics: readRow(metrics, names, row) }))\n\n/**\n * The Plausible adapter. A goal's slug must equal its display name in the site's goal list for its\n * conversions to read; `revenue` needs `revenueCurrency`.\n */\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst revenueCurrency = currencyOption('plausible({ revenueCurrency })', config.revenueCurrency)\n\tconst revenueGoals = revenueCurrency !== undefined\n\t// Dropped rather than escaped, like GA4's measurement id: it lands in the page's script address.\n\tconst scriptId = isScriptId(config.scriptId) ? config.scriptId : undefined\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tmetricReach: plausibleReach,\n\t\tfilters: plausibleFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\treturn {\n\t\tid: 'plausible',\n\t\t...adapterLabel(config.label, 'Plausible', 'plausible({ label })'),\n\t\tcapabilities,\n\t\t...(config.domain || scriptId ? { capture: buildCapture(config, scriptId) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'plausible', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_MAP)\n\n\t\t\tconst filters: PlausibleClause[] = []\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\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], field, [filter.value]])\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalFilters: PlausibleClause[] = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(revenueCurrency ? { currency: revenueCurrency } : {}),\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst dateRange = calendarDays(q)\n\t\t\tconst postQuery = (\n\t\t\t\tnames: string[],\n\t\t\t\tclauses: PlausibleClause[],\n\t\t\t\tshape: QueryShape\n\t\t\t): Promise<PlausibleResponse> =>\n\t\t\t\tupstreamJson<PlausibleResponse>(ctx, `${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: names,\n\t\t\t\t\t\tdate_range: dateRange,\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t},\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (shape: QueryShape): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => postQuery(siteNames, siteFilters, shape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => postQuery(goalNames, goalFilters, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(series, dayIso),\n\t\t\t\t\ttotals: totalRows[0]?.metrics ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.flatMap((d) => DIMENSION_MAP[d] ?? []) })\n\t\t\tconst rows: AnalyticsRow[] = merged.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const [i, d] of dims.entries()) {\n\t\t\t\t\tdimensions[d] = row.keys[i] ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;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,UAAU,KAAK,MAAM,aAAa,SAAS,GAC3C,UAAU,KAAK,OAAO,aAAa,SAAS,CAC7C;GACD;GAEA,IAAI,EAAE,gBAAgB,SAAS,CAAC,KAAK,QAAQ;IAC5C,MAAM,CAAC,QAAQ,aAAa,MAAM,QAAQ,IAAI,CAC7C,SAAS,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC,GACrC,SAAS,CAAC,CAAC,CACZ,CAAC;IACD,OAAO;KACN,MAAM,UAAU,QAAQ,MAAM;KAC9B,QAAQ,UAAU,IAAI,WAAW,CAAC;KAClC,MAAM,KAAK;IACZ;GACD;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,IAAI,WAAW,CAAC;IACpD,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAUA,OAAO;IAAE,OAPoB,MADR,SAAS,EAAE,YAAY,KAAK,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,EAAE,CAAC,GACrD,KAAK,QAAQ;KAChD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,CAAC,GAAG,MAAM,KAAK,QAAQ,GACjC,WAAW,KAAK,IAAI,KAAK,MAAM;KAEhC,OAAO;MAAE;MAAY,SAAS,IAAI;KAAQ;IAC3C,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
@@ -1,8 +1,14 @@
1
1
  import { FetchLike } from "../../core/fetch.js";
2
2
  import { AnalyticsAdapter } from "../../core/contract.js";
3
+ import { AdapterLabelOption } from "../../core/sourceLabel.js";
3
4
 
4
5
  //#region src/adapters/posthog/posthog.d.ts
5
6
  interface PosthogConfig {
7
+ /**
8
+ * The source's name in pickers and listings: a string, a map by admin language (read like
9
+ * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.
10
+ */
11
+ label?: AdapterLabelOption;
6
12
  /** PostHog project id (numeric). */
7
13
  projectId: string;
8
14
  /** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
@@ -1,4 +1,5 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { adapterLabel } from "../../core/sourceLabel.js";
2
3
  import { jsLiteral } from "../../capture/jsLiteral.js";
3
4
  import { vendorReading } from "../../core/metricValues.js";
4
5
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
@@ -16,8 +17,11 @@ const resolveRegion = (config) => {
16
17
  /**
17
18
  * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from
18
19
  * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.
20
+ * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so
21
+ * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded
22
+ * posthog-js (no longer an array) is never replaced, so the client is initialised on it.
19
23
  */
20
- const POSTHOG_STUB = "!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);";
24
+ const POSTHOG_STUB = "!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);";
21
25
  /** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */
22
26
  const isCloudHost = (address) => {
23
27
  const hostname = hostnameOf(address);
@@ -70,17 +74,23 @@ const dataRoutes = (hosts) => hosts.cloud ? [{
70
74
  }));
71
75
  /**
72
76
  * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since
73
- * the vendor sink forwards no pageview.
77
+ * the vendor sink forwards no pageview to the primary client.
74
78
  */
75
79
  const CAPTURE_PAGEVIEW = "history_change";
76
80
  /**
81
+ * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first
82
+ * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to
83
+ * its own pageviews, is asked for outright.
84
+ */
85
+ const NAMED_CLIENT_PAGEVIEWS = ["capture_pageview:false", "capture_pageleave:true"];
86
+ /**
77
87
  * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's
78
88
  * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.
79
89
  */
80
- const initOptions = (path, ui) => [
90
+ const initOptions = (path, ui, named) => [
81
91
  `api_host:${jsLiteral(path)}`,
82
92
  ...ui === void 0 ? [] : [`ui_host:${jsLiteral(ui)}`],
83
- `capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`,
93
+ ...named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`],
84
94
  "opt_out_persistence_by_default:true"
85
95
  ].join(",");
86
96
  function buildCapture(config, token) {
@@ -103,9 +113,12 @@ function buildCapture(config, token) {
103
113
  ],
104
114
  ...config.fetch ? { fetch: config.fetch } : {}
105
115
  },
106
- snippet: ({ path, scope }) => {
107
- const stamp = config.scopeProperty && scope ? `;posthog.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})` : "";
108
- return { scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui)}})${stamp}` }] };
116
+ snippet: ({ path, scope, instance }) => {
117
+ const named = instance !== void 0;
118
+ const client = named ? `posthog[${jsLiteral(instance)}]` : "posthog";
119
+ const stamp = config.scopeProperty && scope ? `;${client}.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})` : "";
120
+ const name = named ? `,${jsLiteral(instance)}` : "";
121
+ return { scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui, named)}}${name})${stamp}` }] };
109
122
  },
110
123
  client: {
111
124
  kind: "posthog",
@@ -202,7 +215,7 @@ function posthog(config) {
202
215
  };
203
216
  return {
204
217
  id: "posthog",
205
- label: "PostHog",
218
+ ...adapterLabel(config.label, "PostHog", "posthog({ label })"),
206
219
  capabilities,
207
220
  ...config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {},
208
221
  isConfigured: () => Boolean(config.projectId && config.apiKey),