@10x-media/analytics 0.1.0-beta.5 → 1.0.0-beta.7

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 (231) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -21
  3. package/README.md +5 -1
  4. package/dist/adapters/ga4/ga4.js +13 -0
  5. package/dist/adapters/ga4/ga4.js.map +1 -1
  6. package/dist/adapters/http/fetchJson.js +1 -1
  7. package/dist/adapters/plausible/plausible.d.ts +10 -0
  8. package/dist/adapters/plausible/plausible.js +51 -0
  9. package/dist/adapters/plausible/plausible.js.map +1 -1
  10. package/dist/adapters/posthog/posthog.d.ts +10 -1
  11. package/dist/adapters/posthog/posthog.js +84 -3
  12. package/dist/adapters/posthog/posthog.js.map +1 -1
  13. package/dist/adapters/series.js +11 -1
  14. package/dist/adapters/series.js.map +1 -1
  15. package/dist/adapters/umami/umami.d.ts +5 -1
  16. package/dist/adapters/umami/umami.js +28 -0
  17. package/dist/adapters/umami/umami.js.map +1 -1
  18. package/dist/capture/getTrackerConfig.d.ts +20 -0
  19. package/dist/capture/getTrackerConfig.js +31 -0
  20. package/dist/capture/getTrackerConfig.js.map +1 -0
  21. package/dist/capture/mountPath.js +14 -0
  22. package/dist/capture/mountPath.js.map +1 -0
  23. package/dist/capture/proxyEndpoint.js +123 -0
  24. package/dist/capture/proxyEndpoint.js.map +1 -0
  25. package/dist/capture/proxyRoutes.js +108 -0
  26. package/dist/capture/proxyRoutes.js.map +1 -0
  27. package/dist/capture/requestBody.js +68 -0
  28. package/dist/capture/requestBody.js.map +1 -0
  29. package/dist/capture/slots.d.ts +8 -0
  30. package/dist/capture/slots.js +43 -0
  31. package/dist/capture/slots.js.map +1 -0
  32. package/dist/capture/trackerConfig.d.ts +32 -0
  33. package/dist/capture/trackerConfig.js +70 -0
  34. package/dist/capture/trackerConfig.js.map +1 -0
  35. package/dist/capture/trackerEndpoint.js +35 -0
  36. package/dist/capture/trackerEndpoint.js.map +1 -0
  37. package/dist/core/capabilities.d.ts +5 -1
  38. package/dist/core/capabilities.js +4 -0
  39. package/dist/core/capabilities.js.map +1 -1
  40. package/dist/core/capture.d.ts +49 -0
  41. package/dist/core/contract.d.ts +33 -4
  42. package/dist/core/contract.js.map +1 -1
  43. package/dist/core/options.d.ts +97 -2
  44. package/dist/core/options.js +63 -2
  45. package/dist/core/options.js.map +1 -1
  46. package/dist/core/registry.d.ts +1 -0
  47. package/dist/core/scopeList.js +32 -0
  48. package/dist/core/scopeList.js.map +1 -0
  49. package/dist/core/scopedRead.js +13 -6
  50. package/dist/core/scopedRead.js.map +1 -1
  51. package/dist/exports/next.d.ts +2 -1
  52. package/dist/exports/next.js +2 -1
  53. package/dist/exports/react.d.ts +4 -0
  54. package/dist/exports/react.js +5 -0
  55. package/dist/exports/rsc.d.ts +5 -2
  56. package/dist/exports/rsc.js +3 -1
  57. package/dist/exports/tracker.d.ts +18 -0
  58. package/dist/exports/tracker.js +12 -0
  59. package/dist/exports/types.d.ts +6 -3
  60. package/dist/fields/AnalyticsPanelClient.js +1 -1
  61. package/dist/fields/config/narrow.js +2 -0
  62. package/dist/fields/config/narrow.js.map +1 -1
  63. package/dist/fields/readForDocument.js +1 -1
  64. package/dist/goals/match.js +64 -0
  65. package/dist/goals/match.js.map +1 -0
  66. package/dist/goals/types.d.ts +33 -0
  67. package/dist/goals/types.js +7 -0
  68. package/dist/goals/types.js.map +1 -0
  69. package/dist/index.d.ts +4 -3
  70. package/dist/index.js +39 -10
  71. package/dist/index.js.map +1 -1
  72. package/dist/native/collections/events.js +21 -1
  73. package/dist/native/collections/events.js.map +1 -1
  74. package/dist/native/collections/rollups.js +39 -3
  75. package/dist/native/collections/rollups.js.map +1 -1
  76. package/dist/native/geo/maxmindResolver.js +2 -4
  77. package/dist/native/geo/maxmindResolver.js.map +1 -1
  78. package/dist/native/ingest/clientIp.js +15 -0
  79. package/dist/native/ingest/clientIp.js.map +1 -0
  80. package/dist/native/ingest/endpoint.js +40 -4
  81. package/dist/native/ingest/endpoint.js.map +1 -1
  82. package/dist/native/ingest/flushBatch.js +4 -13
  83. package/dist/native/ingest/flushBatch.js.map +1 -1
  84. package/dist/native/ingest/normalizeEvent.js +76 -9
  85. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  86. package/dist/native/nativeAdapter.js +100 -5
  87. package/dist/native/nativeAdapter.js.map +1 -1
  88. package/dist/native/query/eventAgg.js +161 -0
  89. package/dist/native/query/eventAgg.js.map +1 -0
  90. package/dist/native/rollupAcc.js +12 -1
  91. package/dist/native/rollupAcc.js.map +1 -1
  92. package/dist/native/rollups/applyDistinctDeltas.js +1 -1
  93. package/dist/native/rollups/applyDistinctDeltas.js.map +1 -1
  94. package/dist/native/rollups/bumpRollup.js +7 -2
  95. package/dist/native/rollups/bumpRollup.js.map +1 -1
  96. package/dist/native/rollups/deltas.js +70 -11
  97. package/dist/native/rollups/deltas.js.map +1 -1
  98. package/dist/next/captureRewrites.d.ts +41 -0
  99. package/dist/next/captureRewrites.js +56 -0
  100. package/dist/next/captureRewrites.js.map +1 -0
  101. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  102. package/dist/next/posthogProxyRewrites.js +16 -21
  103. package/dist/next/posthogProxyRewrites.js.map +1 -1
  104. package/dist/plugin/documentEndpoint.js +1 -1
  105. package/dist/plugin/paths.js +11 -1
  106. package/dist/plugin/paths.js.map +1 -1
  107. package/dist/plugin/runtime.d.ts +1 -0
  108. package/dist/plugin/runtime.js.map +1 -1
  109. package/dist/plugin/sourcesEndpoint.js +16 -4
  110. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  111. package/dist/plugin/warmTask.js +0 -0
  112. package/dist/plugin/warmTask.js.map +1 -1
  113. package/dist/providers/collection.js +56 -16
  114. package/dist/providers/collection.js.map +1 -1
  115. package/dist/providers/factory.js +8 -2
  116. package/dist/providers/factory.js.map +1 -1
  117. package/dist/react/AnalyticsProvider.d.ts +43 -0
  118. package/dist/react/AnalyticsProvider.js +66 -0
  119. package/dist/react/AnalyticsProvider.js.map +1 -0
  120. package/dist/react/TrackerBoot.d.ts +22 -0
  121. package/dist/react/TrackerBoot.js +30 -0
  122. package/dist/react/TrackerBoot.js.map +1 -0
  123. package/dist/react/useAnalytics.d.ts +17 -0
  124. package/dist/react/useAnalytics.js +36 -0
  125. package/dist/react/useAnalytics.js.map +1 -0
  126. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  127. package/dist/rsc/AnalyticsScripts.js +41 -0
  128. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  129. package/dist/surfacing/cacheStore.d.ts +1 -0
  130. package/dist/surfacing/cacheStore.js +18 -2
  131. package/dist/surfacing/cacheStore.js.map +1 -1
  132. package/dist/surfacing/engine.d.ts +1 -0
  133. package/dist/surfacing/engine.js +44 -4
  134. package/dist/surfacing/engine.js.map +1 -1
  135. package/dist/surfacing/queue.js +22 -6
  136. package/dist/surfacing/queue.js.map +1 -1
  137. package/dist/surfacing/rateLimiter.js +130 -0
  138. package/dist/surfacing/rateLimiter.js.map +1 -0
  139. package/dist/surfacing/retryPolicy.js +15 -0
  140. package/dist/surfacing/retryPolicy.js.map +1 -0
  141. package/dist/sync/collection.js +23 -7
  142. package/dist/sync/collection.js.map +1 -1
  143. package/dist/sync/syncTask.js +68 -33
  144. package/dist/sync/syncTask.js.map +1 -1
  145. package/dist/testing/memoryAdapter.d.ts +2 -0
  146. package/dist/testing/memoryAdapter.js +17 -0
  147. package/dist/testing/memoryAdapter.js.map +1 -1
  148. package/dist/tracker/autoCapture.d.ts +48 -0
  149. package/dist/tracker/autoCapture.js +129 -0
  150. package/dist/tracker/autoCapture.js.map +1 -0
  151. package/dist/tracker/consent.d.ts +24 -0
  152. package/dist/tracker/consent.js +48 -0
  153. package/dist/tracker/consent.js.map +1 -0
  154. package/dist/tracker/createTracker.d.ts +18 -0
  155. package/dist/tracker/createTracker.js +163 -0
  156. package/dist/tracker/createTracker.js.map +1 -0
  157. package/dist/tracker/initTracker.d.ts +22 -0
  158. package/dist/tracker/initTracker.js +33 -0
  159. package/dist/tracker/initTracker.js.map +1 -0
  160. package/dist/tracker/loadScript.d.ts +14 -0
  161. package/dist/tracker/loadScript.js +41 -0
  162. package/dist/tracker/loadScript.js.map +1 -0
  163. package/dist/tracker/pageTracking.d.ts +17 -0
  164. package/dist/tracker/pageTracking.js +38 -0
  165. package/dist/tracker/pageTracking.js.map +1 -0
  166. package/dist/tracker/registry.d.ts +27 -0
  167. package/dist/tracker/registry.js +73 -0
  168. package/dist/tracker/registry.js.map +1 -0
  169. package/dist/tracker/sinks/native.d.ts +22 -0
  170. package/dist/tracker/sinks/native.js +56 -0
  171. package/dist/tracker/sinks/native.js.map +1 -0
  172. package/dist/tracker/sinks/plausible.d.ts +14 -0
  173. package/dist/tracker/sinks/plausible.js +25 -0
  174. package/dist/tracker/sinks/plausible.js.map +1 -0
  175. package/dist/tracker/sinks/posthog.d.ts +14 -0
  176. package/dist/tracker/sinks/posthog.js +18 -0
  177. package/dist/tracker/sinks/posthog.js.map +1 -0
  178. package/dist/tracker/sinks/umami.d.ts +13 -0
  179. package/dist/tracker/sinks/umami.js +17 -0
  180. package/dist/tracker/sinks/umami.js.map +1 -0
  181. package/dist/tracker/sinks/vendor.d.ts +14 -0
  182. package/dist/tracker/sinks/vendor.js +66 -0
  183. package/dist/tracker/sinks/vendor.js.map +1 -0
  184. package/dist/tracker/transport.js +28 -0
  185. package/dist/tracker/transport.js.map +1 -0
  186. package/dist/tracker/types.d.ts +66 -0
  187. package/dist/translations/ar.js +83 -0
  188. package/dist/translations/ar.js.map +1 -0
  189. package/dist/translations/de.js +6 -0
  190. package/dist/translations/de.js.map +1 -1
  191. package/dist/translations/en.js +6 -0
  192. package/dist/translations/en.js.map +1 -1
  193. package/dist/translations/es.js +83 -0
  194. package/dist/translations/es.js.map +1 -0
  195. package/dist/translations/fr.js +83 -0
  196. package/dist/translations/fr.js.map +1 -0
  197. package/dist/translations/id.js +83 -0
  198. package/dist/translations/id.js.map +1 -0
  199. package/dist/translations/index.d.ts +10 -1
  200. package/dist/translations/index.js +19 -1
  201. package/dist/translations/index.js.map +1 -1
  202. package/dist/translations/keys.d.ts +6 -0
  203. package/dist/translations/keys.js +6 -0
  204. package/dist/translations/keys.js.map +1 -1
  205. package/dist/translations/ko.js +83 -0
  206. package/dist/translations/ko.js.map +1 -0
  207. package/dist/translations/pt.js +83 -0
  208. package/dist/translations/pt.js.map +1 -0
  209. package/dist/translations/ru.js +83 -0
  210. package/dist/translations/ru.js.map +1 -0
  211. package/dist/translations/uk.js +83 -0
  212. package/dist/translations/uk.js.map +1 -0
  213. package/dist/translations/zh.js +83 -0
  214. package/dist/translations/zh.js.map +1 -0
  215. package/dist/widgets/breakdownTypes.js +5 -0
  216. package/dist/widgets/breakdownTypes.js.map +1 -1
  217. package/dist/widgets/readForWidget.d.ts +2 -1
  218. package/dist/widgets/readForWidget.js +32 -14
  219. package/dist/widgets/readForWidget.js.map +1 -1
  220. package/dist/widgets/readForWidgetBreakdown.d.ts +2 -1
  221. package/dist/widgets/readForWidgetBreakdown.js +29 -15
  222. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  223. package/dist/widgets/readForWidgetRealtime.js +1 -1
  224. package/dist/widgets/readForWidgetSeries.d.ts +2 -1
  225. package/dist/widgets/readForWidgetSeries.js +34 -16
  226. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  227. package/dist/widgets/registerWidgets.js +10 -4
  228. package/dist/widgets/registerWidgets.js.map +1 -1
  229. package/dist/widgets/types.js +4 -1
  230. package/dist/widgets/types.js.map +1 -1
  231. package/package.json +20 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # @10x-media/analytics
2
2
 
3
+ ## 1.0.0-beta.7
4
+
5
+ ### Minor Changes
6
+
7
+ - **Breaking: first-class event capture.** Capture-capable adapters (native, PostHog, Plausible, Umami) now declare a `capture` descriptor: proxy routes, a snippet, and a public client config. An adapter declares one only when the public config capture needs is present, so a read-only PostHog (no `projectToken`) or a Plausible with neither `domain` nor `scriptId` gets no proxy route, no snippet, and fills no slot; reads are unaffected. The descriptor drives three new surfaces:
8
+
9
+ - A first-party runtime proxy at `/api/analytics/p/<slot>/*` (public; declared routes only; GET, POST and OPTIONS served, and PUT, PATCH and DELETE answered 405; cookies and authorization never forwarded and `set-cookie` never returned; body cap and timeout via `capture.proxy.{maxBodyBytes,timeoutMs}`; 404 for unknown slots or paths, 413 over the cap, 400 on a body that dies in transit, 502 on upstream failure). No rate limiting yet.
10
+ - `captureRewrites([{ path, adapter }])` from `@10x-media/analytics/next` for installs that prefer Next rewrites. `posthogProxyRewrites` now wraps it and is deprecated; its emitted param name changed from `:path*` to `:p*` (equivalent for Next). Root mounts and nested or duplicate mount paths throw.
11
+ - A public `GET /api/analytics/tracker` endpoint plus `getTrackerConfig(payload, { headers })` and the `AnalyticsScripts` server component (`@10x-media/analytics/rsc`) that resolve per-request capture config for up to two slots, `global` and `tenant`, one adapter each, deduped when both resolve to the same adapter. Vendor snippets are rendered only for slots that do not require consent; consent-gated vendors load after `consent('granted')`.
12
+
13
+ **Breaking: native engine.** Ingest accepts `type: 'goal'`, plus `value`, `currency` and `scrollDepth` on any event; a missing or non-string `name` on events and goals answers 400 (a nameless `type: 'event'` previously ingested); `name` is capped at 128 characters and `props`, previously stored verbatim, is sanitized to at most 20 flat scalar keys. Config `goals` (`{ slug, name, match: { kind: 'goal' | 'event' | 'path' }, value?, currency? }`) are matched at ingest into `goal` rollup buckets and stamped onto the stored event. `DimensionKey` gains `goal`, `RollupDelta.inc` widens to the full counter set, and `AdapterRegisterContext` gains a required `resolveGoals(req, scope)` that any code building that context by hand must supply. Existing native installs need a migration adding four numeric rollup counters, the `value`, `currency`, `scrollDepth` and `goals` event fields, and the `goal` event type (snippet in the native docs; on Postgres the enum change is irreversible).
14
+
15
+ **Behavioral:** native serves `conversions`, `revenue` (summed in the event's currency, no conversion) and `scrollDepth` (average over the pageviews that reported one), and a `goal` dimension that is groupable but not filterable. A `goal` event counts under `events` and never appears in the `event` dimension breakdown. Goal buckets also accrue visitor and session rows. The native ingest endpoint now caps the request body at 64 KiB (`413` above it), answers `400` on unparseable or non-object JSON (previously a logged `500`), drops a non-finite, negative or over-a-day `durationMs`, and truncates `path` to 512 and `hostname` to 253 characters. `autoCapture` is on by default except `scrollDepth`. Consent defaults per tracker family: vendors require it, native does not.
16
+
17
+ **Additive:** new subpaths `@10x-media/analytics/tracker` (dependency-free browser tracker: `page`, `track`, `trackGoal`, a consent gate whose decision persists under the `analytics:consent` storage key and whose pending events wait in a bounded in-memory queue, SPA route tracking, scroll depth, outbound links, file downloads, `data-analytics-goal` on click and submit) and `@10x-media/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `TrackerBoot`). `useAnalytics()` also works without a provider once `TrackerBoot` has booted. Vendor snippets are self-sequencing (PostHog's official queued stub, Plausible's per-site stub) and carry the CSP nonce, which the PostHog stub propagates onto the bundle it injects. New options: `capture.{slots, paths, consent, autoCapture, proxy}` and `goals` (array, or `{ defaults }`); `capture.slots.<slot>: false` disables a slot; `capture.consent` overrides per slot, per adapter id, or through a resolver. `AnalyticsAdapter` gains optional `capture` and `ingest` members; PostHog gains `region` and `projectToken`; Plausible gains `domain` and `scriptId`; Umami's `host` also serves as the app origin for capture. The widget pickers offer `conversions`, `revenue` and `scrollDepth`, and a new `analytics-breakdown-goals` block lists goal completions.
18
+
19
+ - Engine hardening. Provider reads now run under a real timeout (`cache.timeoutMs`, default 15s) delivered to adapters as `AdapterContext.signal`, retry with backoff only on 429/5xx (one retry for network failures, none for other 4xx or aborts), and respect each adapter's declared rate limits through per-adapter token buckets (`requestsPerMinute`/`requestsPerHour`/`maxConcurrent`). When a refresh fails and an expired cache entry is still within a 24 hour stale window, the read serves it flagged `meta.stale: true` instead of degrading, and failures are logged with the adapter id. Also: native `realtime()` now honors `hostname` and `path` the way aggregate reads do, multiple filters on one dimension compose as AND instead of last-wins, and the client-side capability check mirrors the server's filter requirements.
20
+
21
+ - Multi-tenancy completes. A new `scopes` option enumerates tenant scopes so the cache-warm and sync cron tiers fan out per tenant (each scope resolves its own runtime providers and sync rows carry that scope); without it both tiers keep running install-wide only. Installs with runtime providers (`providers.collection` or `providers.resolve`) no longer treat the config-adapter capability union as a ceiling: every built-in widget registers, the metric pickers offer every metric, and the realtime endpoint is always available, with the per-request sources endpoint and pickers narrowing to what each tenant's sources actually serve. The dev app gains a `TENANCY=on` mode wired through `@payloadcms/plugin-multi-tenant` with two seeded tenants, and the e2e suite runs in both tenancy shapes. The sync task no longer derives a scope from the job request (it fans out over `scopes` and otherwise runs install-wide), and reads on a scoped install that resolve no scope now fail closed unless `access.platformRead` grants.
22
+
23
+ ### Patch Changes
24
+
25
+ - Updated dependencies:
26
+ - @10x-media/fields@0.1.0-beta.7
27
+
28
+ ## 1.0.0-beta.6
29
+
30
+ ### Minor Changes
31
+
32
+ - More built-in locales for the `analytics:` strings.
33
+
34
+ - Added: `es`, `fr`, `id`, `pt`, `ru`, `zh`, `uk`, `ar`, `ko`. Every key is covered in each.
35
+
36
+ - **Breaking:** the query contract grows real filters and finer granularity, and two schemas change. `AnalyticsCapabilities` now requires `filters` and `filterOperators` declarations (custom adapters must add them). `AnalyticsQuery.filters` is honored by native (from raw events, retention-bounded, `eq`/`contains`), PostHog (`eq`/`contains`/`matches` via HogQL), Plausible and GA4 (`eq`), and the widget read helpers accept a `filters` option gated by capability. Native gains the `event` name dimension and `hour` granularity (UTC hour buckets from raw events). Native rollups are now keyed by hostname: deltas write both a hostname-less and a per-hostname bucket family, so `binding.hostname` finally filters native reads with exact unique counts; existing installs must run a migration adding the `hostname` column (backfill `''`) and, on Postgres, rebuilding the rollup unique index to include it: until that index is rebuilt, every native rollup write fails outright on migrate-mode Postgres, not just colliding ones (rebuild DDL is in the native docs). Distinct counting resets once within the deploy-day bucket because ledger keys changed shape. The sync collection gains a required `scope` column (backfill `''`, unique key now source+date+scope) and its read access is scope-filtered in scoped installs, closing a would-be cross-tenant read of synced daily metrics. Migrate-mode Postgres installs must rebuild that unique index too, exactly like the rollups index above; both rebuilds are documented in the native docs' upgrade note.
37
+
38
+ ### Patch Changes
39
+
40
+ - Updated dependencies:
41
+ - @10x-media/fields@0.1.0-beta.6
42
+
3
43
  ## 0.1.0-beta.5
4
44
 
5
45
  ### Minor Changes
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 10x Media GmbH
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 10x Media GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -12,6 +12,7 @@ Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-pl
12
12
 
13
13
  - **One adapter contract** with a capabilities model; adapters ship as code-split subpaths (`@10x-media/analytics/adapters/*`) plus a `memoryAdapter` for tests.
14
14
  - **Native engine**: self-hosted, cookieless analytics in your own database, with atomic rollups, exact daily uniques, geo resolution (platform headers or MaxMind), retention pruning, and opt-in write batching.
15
+ - **Capture**: a dependency-free browser tracker (`@10x-media/analytics/tracker`) with SPA pageviews, consent gating, auto-capture, and goals, booted from React (`@10x-media/analytics/react`) or a server component; capture-capable adapters are served through a first-party proxy so a vendor's SDK loads from your own origin.
15
16
  - **Dashboard widgets** for Payload's Modular Dashboard: metric, trend, four breakdowns, and realtime, all capability-gated, plus a public API for custom widgets.
16
17
  - **Display fields**: `analyticsStat`, `analyticsStatRow`, `analyticsFields`, `analyticsTab`, `analyticsTabsField` place per-document stats on your collections; typed per-collection bindings resolve each document's URL path.
17
18
  - **Caching** through `payload.kv` with request coalescing, plus an opt-in scheduled warm job.
@@ -47,7 +48,7 @@ export default buildConfig({
47
48
  })
48
49
  ```
49
50
 
50
- Run `payload generate:importmap`, send pageviews to `POST /api/analytics/ingest`, and the dashboard fills in.
51
+ Run `payload generate:importmap`, render `<AnalyticsScripts config={await getTrackerConfig(payload, { headers: await headers() })} />` from `@10x-media/analytics/rsc` in your root layout, and the dashboard fills in.
51
52
 
52
53
  ## Documentation
53
54
 
@@ -57,6 +58,9 @@ Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
57
58
  - [Quick start](https://docs.10xmedia.de/analytics/quick-start)
58
59
  - [Adapters](https://docs.10xmedia.de/analytics/adapters)
59
60
  - [Native engine](https://docs.10xmedia.de/analytics/native)
61
+ - [Capture](https://docs.10xmedia.de/analytics/capture)
62
+ - [Goals](https://docs.10xmedia.de/analytics/goals)
63
+ - [First-party proxy](https://docs.10xmedia.de/analytics/proxy)
60
64
  - [Geo resolution](https://docs.10xmedia.de/analytics/geo)
61
65
  - [Display fields](https://docs.10xmedia.de/analytics/display-fields)
62
66
  - [Dashboard widgets](https://docs.10xmedia.de/analytics/widgets)
@@ -45,6 +45,8 @@ function ga4(config) {
45
45
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 425,
46
46
  metrics: ga4Metrics,
47
47
  dimensions: ga4Dimensions,
48
+ filters: ga4Dimensions,
49
+ filterOperators: new Set(["eq"]),
48
50
  batchPageReport: true,
49
51
  rateLimit: {
50
52
  maxConcurrent: 10,
@@ -106,6 +108,17 @@ function ga4(config) {
106
108
  value: q.hostname
107
109
  }
108
110
  } });
111
+ for (const filter of q.filters ?? []) {
112
+ const fieldName = DIMENSION_MAP[filter.dimension];
113
+ if (!fieldName || filter.operator !== "eq") continue;
114
+ filterExprs.push({ filter: {
115
+ fieldName,
116
+ stringFilter: {
117
+ matchType: "EXACT",
118
+ value: filter.value
119
+ }
120
+ } });
121
+ }
109
122
  const dimensionFilter = filterExprs.length === 0 ? void 0 : filterExprs.length === 1 ? filterExprs[0] : { andGroup: { expressions: filterExprs } };
110
123
  const baseRequest = {
111
124
  property: `properties/${config.propertyId}`,
@@ -1 +1 @@
1
- {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;CACnE,IAAI,WAAW,eACd,OAAO,KAAK,MAAM,MAAM,GAAI;CAE7B,IAAI,WAAW,cACd,OAAO,KAAK,MAAM,MAAM,GAAG;CAE5B,OAAO;AACR;AAEA,SAAgB,IAAI,QAAqC;CAGxD,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;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AAM,QADA,YAAY,QAAQ,SAAS,IAAI,CAAC;KAC1B,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GAC7D;GAEA,MAAM,CAAC,YAAY,MAAM,OAAO,UAAU;IACzC,GAAG;IACH,GAAI,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC;IACpF,GAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;GACrC,CAAC;GAED,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,MAAM,SAAS,OAAO;IAC5B,MAAM,SAAS,MAAM,QAAQ,GAAG,IAAI,CAAC;IACrC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GACpF;GAUA,OAAO;IAAE,OARqB,SAAS,QAAQ,CAAC,GAAG,KAAK,QAAQ;KAC/D,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;CACnE,IAAI,WAAW,eACd,OAAO,KAAK,MAAM,MAAM,GAAI;CAE7B,IAAI,WAAW,cACd,OAAO,KAAK,MAAM,MAAM,GAAG;CAE5B,OAAO;AACR;AAEA,SAAgB,IAAI,QAAqC;CAGxD,MAAM,eAAsC;E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,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
@@ -31,6 +31,6 @@ const fetchJson = async (url, opts) => {
31
31
  return await res.json();
32
32
  };
33
33
  //#endregion
34
- export { fetchJson };
34
+ export { ProviderHttpError, fetchJson };
35
35
 
36
36
  //# sourceMappingURL=fetchJson.js.map
@@ -8,6 +8,16 @@ interface PlausibleConfig {
8
8
  host?: string;
9
9
  /** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
10
10
  maxLookbackDays?: number | null;
11
+ /**
12
+ * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.
13
+ * The adapter declares `capture` only when one of the two is set.
14
+ */
15
+ domain?: string;
16
+ /**
17
+ * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter
18
+ * declares `capture` only when one of it and `domain` is set.
19
+ */
20
+ scriptId?: string;
11
21
  }
12
22
  declare function plausible(config: PlausibleConfig): AnalyticsAdapter;
13
23
  //#endregion
@@ -1,6 +1,45 @@
1
1
  import { dayIso } from "../series.js";
2
2
  import { fetchJson } from "../http/fetchJson.js";
3
3
  //#region src/adapters/plausible/plausible.ts
4
+ /**
5
+ * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`
6
+ * queues calls the tracker replays on load, and `plausible.init` parks the options on
7
+ * `plausible.o` for it to read. It makes the inline safe next to the async loader in either
8
+ * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`
9
+ * (the official one assigns unconditionally) because here the tracker is a separate async
10
+ * tag and may win the race, and overwriting the real `init` with the stub would lose the
11
+ * endpoint.
12
+ */
13
+ const PLAUSIBLE_STUB = "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||{}};";
14
+ function buildCapture(config) {
15
+ const base = config.host ?? "https://plausible.io";
16
+ const scripts = (path) => {
17
+ if (config.domain) return [{
18
+ src: `${path}/js/script.js`,
19
+ defer: true,
20
+ attrs: {
21
+ "data-domain": config.domain,
22
+ "data-api": `${path}/api/event`
23
+ }
24
+ }];
25
+ if (config.scriptId) return [{
26
+ src: `${path}/js/pa-${config.scriptId}.js`,
27
+ async: true
28
+ }, { inline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})` }];
29
+ return [];
30
+ };
31
+ return {
32
+ proxy: { routes: [{
33
+ source: "/js/:script*",
34
+ upstream: `${base}/js/:script*`
35
+ }, {
36
+ source: "/api/event",
37
+ upstream: `${base}/api/event`
38
+ }] },
39
+ snippet: ({ path }) => ({ scripts: scripts(path) }),
40
+ client: { kind: "plausible" }
41
+ };
42
+ }
4
43
  const METRIC_MAP = {
5
44
  pageviews: "pageviews",
6
45
  visitors: "visitors",
@@ -42,6 +81,8 @@ function plausible(config) {
42
81
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
43
82
  metrics: plausibleMetrics,
44
83
  dimensions: plausibleDimensions,
84
+ filters: plausibleDimensions,
85
+ filterOperators: new Set(["eq"]),
45
86
  batchPageReport: true,
46
87
  rateLimit: { requestsPerHour: 600 },
47
88
  recommendedTtl: {
@@ -49,6 +90,7 @@ function plausible(config) {
49
90
  aggregate: 3600
50
91
  }
51
92
  },
93
+ ...config.domain || config.scriptId ? { capture: buildCapture(config) } : {},
52
94
  isConfigured: () => Boolean(config.siteId && config.apiKey),
53
95
  async query(q, ctx) {
54
96
  const fetchedAt = q.dateRange.end.toISOString();
@@ -66,6 +108,15 @@ function plausible(config) {
66
108
  "event:hostname",
67
109
  [q.hostname]
68
110
  ]);
111
+ for (const filter of q.filters ?? []) {
112
+ const mapped = DIMENSION_MAP[filter.dimension];
113
+ if (!mapped || filter.operator !== "eq") continue;
114
+ filters.push([
115
+ "is",
116
+ mapped,
117
+ [filter.value]
118
+ ]);
119
+ }
69
120
  const readRow = (row) => {
70
121
  const out = {};
71
122
  for (const m of wanted) {
@@ -1 +1 @@
1
- {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAsBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,aAAa,CAC1B;AAOA,MAAM,mBAAmB,QAAmB,QAC3C,WAAW,gBAAgB,KAAK,MAAM,MAAM,GAAI,IAAI;AAErD,SAAgB,UAAU,QAA2C;CACpE,MAAM,OAAO,OAAO,QAAQ;CAgB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAfA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gBAAgB;GAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;GAQvF,SAAS;GACT,YAAY;GACZ,iBAAiB;GACjB,WAAW,EAAE,iBAAiB,IAAI;GAClC,gBAAgB;IAAE,UAAU;IAAK,WAAW;GAAK;EAMtC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Q,KAAK,QAAQ,EAAE,IAAI,CAAC;GACtD;GAEA,IAAI,EAAE,gBAAgB,SAAS,CAAC,KAAK,QAAQ;IAC5C,MAAM,CAAC,YAAY,UAAU,MAAM,QAAQ,IAAI,CAC9C,UAAU,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC,GACtC,YAAY,CACb,CAAC;IACD,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,WAAW,SAAS;KACrC,MAAM,KAAK,OAAO,IAAI,WAAW,MAAM,EAAE;KACzC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,GAAG;KAAE,CAAC;IAEpD;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GACnE;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,MAAM,YAAY;IACjC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GAC1F;GAaA,OAAO;IAAE,OAVoB,MADV,UAAU,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
1
+ {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,OAAO,UACV,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,OAAO,SAAS;GAAM,OAAO;EAAK,GAC1D,EACC,QAAQ,GAAG,eAAe,2BAA2B,KAAK,UAAU,GAAG,KAAK,WAAW,EAAE,IAC1F,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;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../../core/contract.js";
4
4
  interface PosthogConfig {
5
5
  /** PostHog project id (numeric). */
6
6
  projectId: string;
7
- /** Personal API key with the "Query Read" scope (phx_...). */
7
+ /** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
8
8
  apiKey: string;
9
9
  /** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */
10
10
  host?: string;
@@ -16,6 +16,15 @@ interface PosthogConfig {
16
16
  * read filters on it. Both the property name and value are escaped literals.
17
17
  */
18
18
  scopeProperty?: string;
19
+ /** Cloud region for the proxied capture routes. Derived from `host` when omitted. */
20
+ region?: 'us' | 'eu';
21
+ /**
22
+ * The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the
23
+ * private Query API key, which must never reach the client. The adapter declares
24
+ * `capture` only when this is set: without it the install reads dashboards and captures
25
+ * nothing, so it gets no public proxy and no snippet.
26
+ */
27
+ projectToken?: string;
19
28
  }
20
29
  declare function posthog(config: PosthogConfig): AnalyticsAdapter;
21
30
  //#endregion
@@ -1,7 +1,53 @@
1
- import { dayIso } from "../series.js";
1
+ import { dayIso, hourIso } from "../series.js";
2
2
  import { fetchJson } from "../http/fetchJson.js";
3
3
  //#region src/adapters/posthog/posthog.ts
4
4
  const US_CLOUD = "https://us.posthog.com";
5
+ const resolveRegion = (config) => {
6
+ if (config.region) return config.region;
7
+ return config.host?.includes("eu.posthog.com") ? "eu" : "us";
8
+ };
9
+ /**
10
+ * PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the
11
+ * methods this plugin and a host are likely to call before the SDK lands. It has to be one
12
+ * self-sequencing script: `init` is what injects `array.js`, deriving the URL from
13
+ * `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it
14
+ * resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call
15
+ * made before the SDK arrives is queued on the stub and replayed by it.
16
+ *
17
+ * One addition to the official code: the injected tag inherits the nonce of the inline that
18
+ * injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the
19
+ * bundle. `document.currentScript` is the inline itself during its own synchronous run, on
20
+ * the server-rendered path and the loader's path alike. The IDL property is read first
21
+ * because browsers blank the content attribute once the document is parsed.
22
+ */
23
+ 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
+ function buildCapture(config, token) {
25
+ const region = resolveRegion(config);
26
+ return {
27
+ proxy: {
28
+ trailingSlashes: true,
29
+ routes: [
30
+ {
31
+ source: "/static/:p*",
32
+ upstream: `https://${region}-assets.i.posthog.com/static/:p*`
33
+ },
34
+ {
35
+ source: "/array/:p*",
36
+ upstream: `https://${region}-assets.i.posthog.com/array/:p*`
37
+ },
38
+ {
39
+ source: "/:p*",
40
+ upstream: `https://${region}.i.posthog.com/:p*`
41
+ }
42
+ ]
43
+ },
44
+ snippet: ({ path }) => ({ scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})` }] }),
45
+ client: {
46
+ kind: "posthog",
47
+ token
48
+ }
49
+ };
50
+ }
5
51
  const METRIC_SQL_PAGEVIEW = {
6
52
  pageviews: "count()",
7
53
  visitors: "count(DISTINCT person_id)",
@@ -22,6 +68,7 @@ const DIMENSION_SQL = {
22
68
  const posthogMetrics = new Set(Object.keys(METRIC_SQL_ALL));
23
69
  const posthogDimensions = new Set(Object.keys(DIMENSION_SQL));
24
70
  const sqlString = (value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
71
+ const escapeLikeValue = (value) => value.replace(/[\\%_]/g, (c) => `\\${c}`);
25
72
  const sqlDateTimeLiteral = (d) => sqlString(d.toISOString().slice(0, 19).replace("T", " "));
26
73
  function posthog(config) {
27
74
  const host = config.host ?? US_CLOUD;
@@ -32,10 +79,16 @@ function posthog(config) {
32
79
  perPageQuery: true,
33
80
  realtime: false,
34
81
  comparison: false,
35
- minGranularity: "day",
82
+ minGranularity: "hour",
36
83
  maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
37
84
  metrics: posthogMetrics,
38
85
  dimensions: posthogDimensions,
86
+ filters: posthogDimensions,
87
+ filterOperators: new Set([
88
+ "eq",
89
+ "contains",
90
+ "matches"
91
+ ]),
39
92
  batchPageReport: true,
40
93
  rateLimit: {
41
94
  requestsPerMinute: 240,
@@ -47,11 +100,12 @@ function posthog(config) {
47
100
  },
48
101
  ...config.scopeProperty ? { scopedQueries: true } : {}
49
102
  },
103
+ ...config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {},
50
104
  isConfigured: () => Boolean(config.projectId && config.apiKey),
51
105
  async query(q, ctx) {
52
106
  const fetchedAt = q.dateRange.end.toISOString();
53
107
  const breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d]);
54
- const scanAllEvents = q.metrics.includes("events") || breakdownDim === "event";
108
+ const scanAllEvents = q.metrics.includes("events") || breakdownDim === "event" || (q.filters ?? []).some((f) => f.dimension === "event" && DIMENSION_SQL[f.dimension]);
55
109
  const metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW;
56
110
  const wanted = q.metrics.filter((m) => metricSql[m]);
57
111
  const exprs = [...new Set(wanted.map((m) => metricSql[m]))];
@@ -60,6 +114,13 @@ function posthog(config) {
60
114
  if (q.path) where.push(`properties.$pathname = ${sqlString(q.path)}`);
61
115
  if (q.hostname) where.push(`properties.$host = ${sqlString(q.hostname)}`);
62
116
  if (config.scopeProperty && q.scope !== void 0) where.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`);
117
+ for (const filter of q.filters ?? []) {
118
+ const expr = DIMENSION_SQL[filter.dimension];
119
+ if (!expr) continue;
120
+ if (filter.operator === "eq") where.push(`${expr} = ${sqlString(filter.value)}`);
121
+ else if (filter.operator === "contains") where.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`);
122
+ else if (filter.operator === "matches") where.push(`match(${expr}, ${sqlString(filter.value)})`);
123
+ }
63
124
  const selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`);
64
125
  const runSql = (sql) => fetchJson(`${host}/api/projects/${config.projectId}/query/`, {
65
126
  method: "POST",
@@ -103,6 +164,26 @@ function posthog(config) {
103
164
  }
104
165
  };
105
166
  }
167
+ if (q.granularity === "hour" && !breakdownDim) {
168
+ const seriesSql = `SELECT ${`toStartOfHour(timestamp, ${sqlString(q.timezone ?? "UTC")})`} AS hour, ${selectMetrics.join(", ")} FROM events WHERE ${where.join(" AND ")} GROUP BY hour ORDER BY hour`;
169
+ const [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()]);
170
+ const rows = [];
171
+ for (const row of seriesData.results) {
172
+ const ts = hourIso(String(row[0] ?? ""));
173
+ if (ts) rows.push({
174
+ timestamp: ts,
175
+ metrics: readRow(row, 1)
176
+ });
177
+ }
178
+ return {
179
+ rows,
180
+ totals,
181
+ meta: {
182
+ provider: "posthog",
183
+ fetchedAt
184
+ }
185
+ };
186
+ }
106
187
  if (breakdownDim) return {
107
188
  rows: (await runSql(`SELECT ${DIMENSION_SQL[breakdownDim]} AS dim, ${selectMetrics.join(", ")} FROM events WHERE ${where.join(" AND ")} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`)).results.map((row) => ({
108
189
  dimensions: { [breakdownDim]: String(row[0] ?? "") },
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\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 * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric or an event-name breakdown must scan every event, not\n\t\t\t// just pageviews; those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents = q.metrics.includes('events') || breakdownDim === 'event'\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,WAAW;AAKjB,MAAM,sBAA0D;CAC/D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;AACX;AAKA,MAAM,iBAAqD;CAC1D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,QAAQ;AACT;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,OAAO;AACR;AAEA,MAAM,iBAAyC,IAAI,IAAI,OAAO,KAAK,cAAc,CAAgB;AACjG,MAAM,oBAA+C,IAAI,IACxD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,aAAa,UAClB,IAAI,MAAM,QAAQ,OAAO,MAAM,EAAE,QAAQ,MAAM,KAAK,EAAE;AAEvD,MAAM,sBAAsB,MAC3B,UAAU,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,EAAE,QAAQ,KAAK,GAAG,CAAC;AA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AE,UAAU;MAAW;KAAU;IAAE;GACjE;GAEA,IAAI,cAQH,OAAO;IAAE,OAJoB,MADV,OAAO,UAFX,cAAc,cACA,WAAW,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE,uCAAuC,EAAE,SAAS,KAC/H,GACK,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,eAAe,OAAO,IAAI,MAAM,EAAE,EAAE;KACnD,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;GAG5E,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\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 * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n\t/** Cloud region for the proxied capture routes. Derived from `host` when omitted. */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the\n\t * private Query API key, which must never reach the client. The adapter declares\n\t * `capture` only when this is set: without it the install reads dashboards and captures\n\t * nothing, so it gets no public proxy and no snippet.\n\t */\n\tprojectToken?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the\n * methods this plugin and a host are likely to call before the SDK lands. It has to be one\n * self-sequencing script: `init` is what injects `array.js`, deriving the URL from\n * `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it\n * resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call\n * made before the SDK arrives is queued on the stub and replayed by it.\n *\n * One addition to the official code: the injected tag inherits the nonce of the inline that\n * injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the\n * bundle. `document.currentScript` is the inline itself during its own synchronous run, on\n * the server-rendered path and the loader's path alike. The IDL property is read first\n * because browsers blank the content attribute once the document is parsed.\n */\nconst POSTHOG_STUB =\n\t'!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||[]);'\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{\n\t\t\t\t\tsource: '/static/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/static/:p*`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsource: '/array/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/array/:p*`,\n\t\t\t\t},\n\t\t\t\t{ source: '/:p*', upstream: `https://${region}.i.posthog.com/:p*` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})`,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\t...(config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAwCA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;;;;;;;;AAgBA,MAAM,eACL;AAED,SAAS,aAAa,QAAuB,OAA+B;CAC3E,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,OAAO;GACN,iBAAiB;GACjB,QAAQ;IACP;KACC,Q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