@10x-media/analytics 1.0.0-beta.7 → 1.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +118 -0
- package/LICENSE +21 -21
- package/README.md +10 -4
- package/dist/adapters/ga4/eventName.d.ts +15 -0
- package/dist/adapters/ga4/eventName.js +19 -0
- package/dist/adapters/ga4/eventName.js.map +1 -0
- package/dist/adapters/ga4/ga4.d.ts +5 -0
- package/dist/adapters/ga4/ga4.js +179 -70
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +15 -0
- package/dist/adapters/ga4/measurementId.js.map +1 -0
- package/dist/adapters/goalRead.js +126 -0
- package/dist/adapters/goalRead.js.map +1 -0
- package/dist/adapters/plausible/plausible.d.ts +15 -0
- package/dist/adapters/plausible/plausible.js +112 -43
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +47 -25
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +8 -0
- package/dist/adapters/umami/umami.js +237 -28
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/slots.js +16 -5
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.d.ts +1 -0
- package/dist/capture/trackerConfig.js +28 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/BarList.d.ts +15 -1
- package/dist/charts/BarList.js +41 -19
- package/dist/charts/BarList.js.map +1 -1
- package/dist/charts/TrendChart.d.ts +16 -3
- package/dist/charts/TrendChart.js +172 -106
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bars.d.ts +2 -0
- package/dist/charts/bars.js +2 -1
- package/dist/charts/bars.js.map +1 -1
- package/dist/charts/bucket.js +10 -1
- package/dist/charts/bucket.js.map +1 -1
- package/dist/charts/spline.js +2 -2
- package/dist/charts/spline.js.map +1 -1
- package/dist/charts/styles.js +18 -1
- package/dist/charts/styles.js.map +1 -1
- package/dist/core/cacheKey.js +24 -2
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/capabilities.js +7 -2
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +1 -1
- package/dist/core/contract.d.ts +46 -9
- package/dist/core/contract.js +29 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/granularity.js +1 -1
- package/dist/core/options.d.ts +62 -7
- package/dist/core/options.js +63 -4
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +33 -23
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/serverEvent.d.ts +44 -0
- package/dist/core/serverEvent.js +12 -0
- package/dist/core/serverEvent.js.map +1 -0
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/client.d.ts +12 -3
- package/dist/exports/client.js +9 -1
- package/dist/exports/rsc.d.ts +7 -2
- package/dist/exports/rsc.js +6 -3
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/tracker.js +2 -1
- package/dist/exports/types.d.ts +13 -4
- package/dist/exports/types.js +3 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/AnalyticsPanelField.js +1 -1
- package/dist/fields/AnalyticsStatField.js +2 -2
- package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
- package/dist/fields/config/FilterDimensionSelectField.js +77 -0
- package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
- package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
- package/dist/fields/config/FilterOperatorSelectField.js +75 -0
- package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
- package/dist/fields/config/MetricSelectField.js +3 -3
- package/dist/fields/config/MetricSelectField.js.map +1 -1
- package/dist/fields/config/SourceSelectField.js +3 -3
- package/dist/fields/config/SourceSelectField.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +5 -1
- package/dist/fields/config/sourcesState.js +19 -3
- package/dist/fields/config/sourcesState.js.map +1 -1
- package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
- package/dist/fields/config/useAnalyticsSources.js +9 -6
- package/dist/fields/config/useAnalyticsSources.js.map +1 -1
- package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
- package/dist/fields/config/useFilterCapabilities.js +52 -0
- package/dist/fields/config/useFilterCapabilities.js.map +1 -0
- package/dist/fields/readForDocument.d.ts +5 -0
- package/dist/fields/readForDocument.js +21 -9
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/GoalSelectField.d.ts +7 -0
- package/dist/goals/GoalSelectField.js +77 -0
- package/dist/goals/GoalSelectField.js.map +1 -0
- package/dist/goals/collection.js +250 -0
- package/dist/goals/collection.js.map +1 -0
- package/dist/goals/currency.js +14 -0
- package/dist/goals/currency.js.map +1 -0
- package/dist/goals/fetchGoals.d.ts +18 -0
- package/dist/goals/fetchGoals.js +29 -0
- package/dist/goals/fetchGoals.js.map +1 -0
- package/dist/goals/goalField.d.ts +31 -0
- package/dist/goals/goalField.js +56 -0
- package/dist/goals/goalField.js.map +1 -0
- package/dist/goals/goalsEndpoint.d.ts +1 -0
- package/dist/goals/goalsEndpoint.js +55 -0
- package/dist/goals/goalsEndpoint.js.map +1 -0
- package/dist/goals/resolver.d.ts +8 -0
- package/dist/goals/resolver.js +147 -0
- package/dist/goals/resolver.js.map +1 -0
- package/dist/goals/trackGoalAction.d.ts +74 -0
- package/dist/goals/trackGoalAction.js +139 -0
- package/dist/goals/trackGoalAction.js.map +1 -0
- package/dist/goals/useAnalyticsGoals.d.ts +20 -0
- package/dist/goals/useAnalyticsGoals.js +67 -0
- package/dist/goals/useAnalyticsGoals.js.map +1 -0
- package/dist/index.d.ts +12 -3
- package/dist/index.js +75 -11
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +36 -0
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/eventScan.js +25 -0
- package/dist/native/eventScan.js.map +1 -0
- package/dist/native/ingest/browser.js +47 -0
- package/dist/native/ingest/browser.js.map +1 -0
- package/dist/native/ingest/device.js +11 -3
- package/dist/native/ingest/device.js.map +1 -1
- package/dist/native/ingest/endpoint.d.ts +1 -0
- package/dist/native/ingest/endpoint.js +2 -17
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/flushBatch.js +26 -26
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/language.js +14 -0
- package/dist/native/ingest/language.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.d.ts +26 -0
- package/dist/native/ingest/normalizeEvent.js +35 -7
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/referrer.js +48 -0
- package/dist/native/ingest/referrer.js.map +1 -0
- package/dist/native/ingest/serverTrack.d.ts +20 -0
- package/dist/native/ingest/serverTrack.js +100 -0
- package/dist/native/ingest/serverTrack.js.map +1 -0
- package/dist/native/ingest/source.d.ts +7 -0
- package/dist/native/ingest/source.js +139 -14
- package/dist/native/ingest/source.js.map +1 -1
- package/dist/native/ingest/utm.js +33 -0
- package/dist/native/ingest/utm.js.map +1 -0
- package/dist/native/ingest/validate.js +27 -0
- package/dist/native/ingest/validate.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +1 -1
- package/dist/native/nativeAdapter.js +53 -36
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +14 -1
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/retention/pruneTask.js +1 -1
- package/dist/native/rollups/bucketKey.js +15 -0
- package/dist/native/rollups/bucketKey.js.map +1 -0
- package/dist/native/rollups/bumpRollups.js +116 -0
- package/dist/native/rollups/bumpRollups.js.map +1 -0
- package/dist/native/rollups/deltas.js +30 -15
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/native/rollups/insertManyIfNew.js +93 -0
- package/dist/native/rollups/insertManyIfNew.js.map +1 -0
- package/dist/next/captureRewrites.d.ts +3 -2
- package/dist/next/captureRewrites.js +3 -2
- package/dist/next/captureRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +52 -15
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/goalHint.d.ts +1 -0
- package/dist/plugin/goalHint.js +24 -0
- package/dist/plugin/goalHint.js.map +1 -0
- package/dist/plugin/paths.js +5 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +120 -0
- package/dist/plugin/queryEndpoint.js.map +1 -0
- package/dist/plugin/readContextForRequest.js +71 -0
- package/dist/plugin/readContextForRequest.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +43 -15
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/responses.js +17 -0
- package/dist/plugin/responses.js.map +1 -0
- package/dist/plugin/runtime.js +31 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/scopeFieldBoot.js +22 -0
- package/dist/plugin/scopeFieldBoot.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +21 -52
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +29 -13
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +4 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/resolver.js.map +1 -1
- package/dist/query/dates.js +64 -0
- package/dist/query/dates.js.map +1 -0
- package/dist/query/errors.d.ts +17 -0
- package/dist/query/errors.js +10 -0
- package/dist/query/errors.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +59 -0
- package/dist/query/fetchQuery.js +110 -0
- package/dist/query/fetchQuery.js.map +1 -0
- package/dist/query/parse.d.ts +22 -0
- package/dist/query/parse.js +168 -0
- package/dist/query/parse.js.map +1 -0
- package/dist/query/response.d.ts +39 -0
- package/dist/query/response.js +11 -0
- package/dist/query/response.js.map +1 -0
- package/dist/surfacing/engine.js +1 -1
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/testing/memoryAdapter.js +0 -1
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/timeframe/tz.js +17 -6
- package/dist/timeframe/tz.js.map +1 -1
- package/dist/tracker/createTracker.js +13 -1
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/sinks/ga4.d.ts +21 -0
- package/dist/tracker/sinks/ga4.js +26 -0
- package/dist/tracker/sinks/ga4.js.map +1 -0
- package/dist/tracker/types.d.ts +5 -0
- package/dist/translations/ar.js +127 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +127 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +127 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +127 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +127 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +127 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +126 -0
- package/dist/translations/keys.js +127 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +127 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +8 -2
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +127 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +127 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +127 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +127 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsNavLink.d.ts +19 -0
- package/dist/view/AnalyticsNavLink.js +40 -0
- package/dist/view/AnalyticsNavLink.js.map +1 -0
- package/dist/view/AnalyticsView.d.ts +23 -0
- package/dist/view/AnalyticsView.js +45 -0
- package/dist/view/AnalyticsView.js.map +1 -0
- package/dist/view/AnalyticsViewClient.d.ts +15 -0
- package/dist/view/AnalyticsViewClient.js +200 -0
- package/dist/view/AnalyticsViewClient.js.map +1 -0
- package/dist/view/authRedirect.js +32 -0
- package/dist/view/authRedirect.js.map +1 -0
- package/dist/view/conversionRate.js +18 -0
- package/dist/view/conversionRate.js.map +1 -0
- package/dist/view/dayRange.js +68 -0
- package/dist/view/dayRange.js.map +1 -0
- package/dist/view/gating.d.ts +1 -0
- package/dist/view/gating.js +142 -0
- package/dist/view/gating.js.map +1 -0
- package/dist/view/labels.js +64 -0
- package/dist/view/labels.js.map +1 -0
- package/dist/view/registerView.js +48 -0
- package/dist/view/registerView.js.map +1 -0
- package/dist/view/sections/Breakdowns.js +197 -0
- package/dist/view/sections/Breakdowns.js.map +1 -0
- package/dist/view/sections/EmptyStates.js +92 -0
- package/dist/view/sections/EmptyStates.js.map +1 -0
- package/dist/view/sections/FilterChips.js +46 -0
- package/dist/view/sections/FilterChips.js.map +1 -0
- package/dist/view/sections/GoalsPanel.js +82 -0
- package/dist/view/sections/GoalsPanel.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +65 -0
- package/dist/view/sections/OverviewCards.js.map +1 -0
- package/dist/view/sections/RealtimeStrip.js +80 -0
- package/dist/view/sections/RealtimeStrip.js.map +1 -0
- package/dist/view/sections/Toolbar.js +186 -0
- package/dist/view/sections/Toolbar.js.map +1 -0
- package/dist/view/sections/Trend.js +125 -0
- package/dist/view/sections/Trend.js.map +1 -0
- package/dist/view/sections/styles.js +74 -0
- package/dist/view/sections/styles.js.map +1 -0
- package/dist/view/state.js +211 -0
- package/dist/view/state.js.map +1 -0
- package/dist/view/useViewQueries.js +153 -0
- package/dist/view/useViewQueries.js.map +1 -0
- package/dist/view/viewProps.d.ts +40 -0
- package/dist/view/viewProps.js +90 -0
- package/dist/view/viewProps.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +78 -11
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
- package/dist/widgets/AnalyticsGoalsWidget.js +196 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsMetricWidget.js +63 -13
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +44 -22
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsTrendWidget.js +79 -16
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/RealtimeCounter.d.ts +4 -0
- package/dist/widgets/RealtimeCounter.js +10 -1
- package/dist/widgets/RealtimeCounter.js.map +1 -1
- package/dist/widgets/WidgetViewLink.js +17 -0
- package/dist/widgets/WidgetViewLink.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +28 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/cardChrome.js +31 -7
- package/dist/widgets/cardChrome.js.map +1 -1
- package/dist/widgets/comparison.js +15 -1
- package/dist/widgets/comparison.js.map +1 -1
- package/dist/widgets/defaults.d.ts +6 -2
- package/dist/widgets/defaults.js +72 -25
- package/dist/widgets/defaults.js.map +1 -1
- package/dist/widgets/filterCaption.js +27 -0
- package/dist/widgets/filterCaption.js.map +1 -0
- package/dist/widgets/filterField.d.ts +19 -0
- package/dist/widgets/filterField.js +75 -0
- package/dist/widgets/filterField.js.map +1 -0
- package/dist/widgets/prepareWidgetRead.d.ts +7 -0
- package/dist/widgets/prepareWidgetRead.js +74 -0
- package/dist/widgets/prepareWidgetRead.js.map +1 -0
- package/dist/widgets/range.js +43 -12
- package/dist/widgets/range.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +24 -2
- package/dist/widgets/readForWidget.js +34 -48
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +32 -1
- package/dist/widgets/readForWidgetBreakdown.js +32 -42
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +67 -0
- package/dist/widgets/readForWidgetGoals.js +140 -0
- package/dist/widgets/readForWidgetGoals.js.map +1 -0
- package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
- package/dist/widgets/readForWidgetRealtime.js +21 -20
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +24 -1
- package/dist/widgets/readForWidgetSeries.js +63 -56
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/readMeta.js +18 -0
- package/dist/widgets/readMeta.js.map +1 -0
- package/dist/widgets/registerWidgets.js +53 -7
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js +12 -1
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.d.ts +22 -0
- package/dist/widgets/viewLink.js +86 -0
- package/dist/widgets/viewLink.js.map +1 -0
- package/package.json +9 -4
- package/dist/native/rollups/applyDistinctDeltas.js +0 -9
- package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
- package/dist/native/rollups/bumpRollup.js +0 -73
- package/dist/native/rollups/bumpRollup.js.map +0 -1
- package/dist/native/rollups/insertIfNew.js +0 -19
- package/dist/native/rollups/insertIfNew.js.map +0 -1
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { zonedCalendarDay } from "../../timeframe/tz.js";
|
|
2
|
+
import { emptyGoalBreakdown, goalHint, hintSlugs, mergeGoalRows, providerMetricKeys, readGoalPair, splitGoalMetrics } from "../goalRead.js";
|
|
1
3
|
import { dayIso } from "../series.js";
|
|
2
4
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
5
|
//#region src/adapters/plausible/plausible.ts
|
|
@@ -49,8 +51,11 @@ const METRIC_MAP = {
|
|
|
49
51
|
avgDuration: "visit_duration",
|
|
50
52
|
events: "events",
|
|
51
53
|
scrollDepth: "scroll_depth",
|
|
54
|
+
conversions: "events",
|
|
52
55
|
revenue: "total_revenue"
|
|
53
56
|
};
|
|
57
|
+
/** Metrics Plausible answers only for a goal-restricted read. */
|
|
58
|
+
const GOAL_METRICS = new Set(["conversions", "revenue"]);
|
|
54
59
|
const DIMENSION_MAP = {
|
|
55
60
|
page: "event:page",
|
|
56
61
|
source: "visit:source",
|
|
@@ -63,26 +68,55 @@ const DIMENSION_MAP = {
|
|
|
63
68
|
city: "visit:city",
|
|
64
69
|
utmSource: "visit:utm_source",
|
|
65
70
|
utmMedium: "visit:utm_medium",
|
|
66
|
-
utmCampaign: "visit:utm_campaign"
|
|
71
|
+
utmCampaign: "visit:utm_campaign",
|
|
72
|
+
goal: "event:goal"
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Stats API v2 filter operators, available on every dimension this adapter offers as a
|
|
76
|
+
* filter (event:goal is the grammar's one exception, taking `is` and `contains` only, and
|
|
77
|
+
* is a breakdown here rather than a filter). `matches` is an re2 full match, so a pattern
|
|
78
|
+
* has to cover the whole value (`/docs/.*`, not `^/docs`).
|
|
79
|
+
*/
|
|
80
|
+
const OPERATOR_MAP = {
|
|
81
|
+
eq: "is",
|
|
82
|
+
contains: "contains",
|
|
83
|
+
matches: "matches"
|
|
67
84
|
};
|
|
68
85
|
const plausibleMetrics = new Set(Object.keys(METRIC_MAP));
|
|
86
|
+
const plausibleMetricsNoRevenue = new Set([...plausibleMetrics].filter((m) => m !== "revenue"));
|
|
69
87
|
const plausibleDimensions = new Set(Object.keys(DIMENSION_MAP));
|
|
88
|
+
const plausibleFilters = new Set([...plausibleDimensions].filter((dimension) => dimension !== "goal"));
|
|
89
|
+
const revenueAmount = (raw) => typeof raw === "object" && raw !== null && typeof raw.value === "number" ? raw.value : void 0;
|
|
70
90
|
const toContractValue = (metric, raw) => metric === "avgDuration" ? Math.round(raw * 1e3) : raw;
|
|
91
|
+
/**
|
|
92
|
+
* Plausible identifies a goal by its display name in the site's own goal list ("Signup",
|
|
93
|
+
* "Visit /thank-you"), so a plugin goal's slug must equal that name for its conversions to
|
|
94
|
+
* read. Conversions are the `events` metric on goal rows, which is the dashboard's Total
|
|
95
|
+
* Conversions; revenue is `total_revenue`, which Plausible serves only for a revenue goal
|
|
96
|
+
* and reports as an object whose `value` is null when the rows mix currencies. Revenue is
|
|
97
|
+
* offered only when `revenueCurrency` says the site has such a goal: asking for it on a site
|
|
98
|
+
* without one errors the request.
|
|
99
|
+
*/
|
|
71
100
|
function plausible(config) {
|
|
72
101
|
const host = config.host ?? "https://plausible.io";
|
|
102
|
+
const maxLookbackDays = config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730;
|
|
103
|
+
const revenueGoals = Boolean(config.revenueCurrency);
|
|
73
104
|
return {
|
|
74
105
|
id: "plausible",
|
|
75
106
|
label: "Plausible",
|
|
76
107
|
capabilities: {
|
|
77
108
|
perPageQuery: true,
|
|
78
109
|
realtime: false,
|
|
79
|
-
comparison: false,
|
|
80
110
|
minGranularity: "day",
|
|
81
|
-
maxLookbackDays
|
|
82
|
-
metrics: plausibleMetrics,
|
|
111
|
+
maxLookbackDays,
|
|
112
|
+
metrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,
|
|
83
113
|
dimensions: plausibleDimensions,
|
|
84
|
-
filters:
|
|
85
|
-
filterOperators: new Set([
|
|
114
|
+
filters: plausibleFilters,
|
|
115
|
+
filterOperators: new Set([
|
|
116
|
+
"eq",
|
|
117
|
+
"contains",
|
|
118
|
+
"matches"
|
|
119
|
+
]),
|
|
86
120
|
batchPageReport: true,
|
|
87
121
|
rateLimit: { requestsPerHour: 600 },
|
|
88
122
|
recommendedTtl: {
|
|
@@ -94,9 +128,24 @@ function plausible(config) {
|
|
|
94
128
|
isConfigured: () => Boolean(config.siteId && config.apiKey),
|
|
95
129
|
async query(q, ctx) {
|
|
96
130
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
97
|
-
const wanted = q.metrics.filter((m) => METRIC_MAP[m]);
|
|
98
|
-
const providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m]))];
|
|
99
131
|
const dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d]);
|
|
132
|
+
const goalBreakdown = dims.includes("goal");
|
|
133
|
+
const hint = goalHint(q);
|
|
134
|
+
const slugs = hintSlugs(hint);
|
|
135
|
+
const empty = goalBreakdown ? emptyGoalBreakdown({
|
|
136
|
+
provider: "plausible",
|
|
137
|
+
q,
|
|
138
|
+
hint
|
|
139
|
+
}) : null;
|
|
140
|
+
if (empty) return empty;
|
|
141
|
+
const { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({
|
|
142
|
+
wanted: q.metrics.filter((m) => METRIC_MAP[m] && (revenueGoals || m !== "revenue")),
|
|
143
|
+
goalOnly: GOAL_METRICS,
|
|
144
|
+
goalBreakdown,
|
|
145
|
+
hint
|
|
146
|
+
});
|
|
147
|
+
const siteKeys = providerMetricKeys(siteMetrics, METRIC_MAP);
|
|
148
|
+
const goalKeys = providerMetricKeys(goalMetrics, METRIC_MAP);
|
|
100
149
|
const filters = [];
|
|
101
150
|
if (q.path) filters.push([
|
|
102
151
|
"is",
|
|
@@ -109,86 +158,106 @@ function plausible(config) {
|
|
|
109
158
|
[q.hostname]
|
|
110
159
|
]);
|
|
111
160
|
for (const filter of q.filters ?? []) {
|
|
112
|
-
const mapped = DIMENSION_MAP[filter.dimension];
|
|
113
|
-
if (!mapped
|
|
161
|
+
const mapped = plausibleFilters.has(filter.dimension) ? DIMENSION_MAP[filter.dimension] : void 0;
|
|
162
|
+
if (!mapped) continue;
|
|
114
163
|
filters.push([
|
|
115
|
-
|
|
164
|
+
OPERATOR_MAP[filter.operator],
|
|
116
165
|
mapped,
|
|
117
166
|
[filter.value]
|
|
118
167
|
]);
|
|
119
168
|
}
|
|
120
|
-
const
|
|
169
|
+
const goalFilters = slugs ? [...filters, [
|
|
170
|
+
"is",
|
|
171
|
+
"event:goal",
|
|
172
|
+
slugs
|
|
173
|
+
]] : filters;
|
|
174
|
+
const siteFilters = goalBreakdown ? goalFilters : filters;
|
|
175
|
+
let goalsFailed = false;
|
|
176
|
+
const meta = () => ({
|
|
177
|
+
provider: "plausible",
|
|
178
|
+
fetchedAt,
|
|
179
|
+
...unresolved || goalsFailed ? { goalsUnresolved: true } : {}
|
|
180
|
+
});
|
|
181
|
+
const readMetrics = (ms, keys, row) => {
|
|
121
182
|
const out = {};
|
|
122
|
-
for (const m of
|
|
123
|
-
const
|
|
124
|
-
|
|
183
|
+
for (const m of ms) {
|
|
184
|
+
const raw = row.metrics[keys.indexOf(METRIC_MAP[m])];
|
|
185
|
+
if (m === "revenue") {
|
|
186
|
+
const amount = revenueAmount(raw);
|
|
187
|
+
if (amount !== void 0) out.revenue = amount;
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
out[m] = toContractValue(m, typeof raw === "number" ? raw : 0);
|
|
125
191
|
}
|
|
126
192
|
return out;
|
|
127
193
|
};
|
|
128
|
-
const postQuery = (extra) => fetchJson(`${host}/api/v2/query`, {
|
|
194
|
+
const postQuery = (metrics, clauses, extra) => fetchJson(`${host}/api/v2/query`, {
|
|
129
195
|
method: "POST",
|
|
130
196
|
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
131
197
|
body: {
|
|
132
198
|
site_id: config.siteId,
|
|
133
|
-
metrics
|
|
134
|
-
date_range: [q.dateRange.start
|
|
135
|
-
...
|
|
199
|
+
metrics,
|
|
200
|
+
date_range: [zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"), zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")],
|
|
201
|
+
...clauses.length ? { filters: clauses } : {},
|
|
136
202
|
...extra
|
|
137
203
|
},
|
|
138
204
|
signal: ctx.signal,
|
|
139
205
|
provider: "plausible"
|
|
140
206
|
});
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
207
|
+
const keyedRows = (response, ms, keys) => response?.results.map((row) => ({
|
|
208
|
+
keys: row.dimensions,
|
|
209
|
+
metrics: readMetrics(ms, keys, row)
|
|
210
|
+
}));
|
|
211
|
+
/**
|
|
212
|
+
* One request shape read twice, plainly and goal-filtered, unioned per row. A row the
|
|
213
|
+
* goal read has no counterpart for carries no conversions: no goal was completed there.
|
|
214
|
+
*/
|
|
215
|
+
const readPair = async (extra) => {
|
|
216
|
+
const pair = await readGoalPair({
|
|
217
|
+
site: siteKeys.length ? () => postQuery(siteKeys, siteFilters, extra) : void 0,
|
|
218
|
+
goals: goalKeys.length ? () => postQuery(goalKeys, goalFilters, extra) : void 0
|
|
219
|
+
});
|
|
220
|
+
if (pair.failed) goalsFailed = true;
|
|
221
|
+
return mergeGoalRows(keyedRows(pair.site, siteMetrics, siteKeys), keyedRows(pair.goals, goalMetrics, goalKeys));
|
|
144
222
|
};
|
|
145
223
|
if (q.granularity === "day" && !dims.length) {
|
|
146
|
-
const [
|
|
224
|
+
const [series, totalRows] = await Promise.all([readPair({ dimensions: ["time:day"] }), readPair({})]);
|
|
147
225
|
const rows = [];
|
|
148
|
-
for (const row of
|
|
149
|
-
const ts = dayIso(row.
|
|
226
|
+
for (const row of series) {
|
|
227
|
+
const ts = dayIso(row.keys[0] ?? "");
|
|
150
228
|
if (ts) rows.push({
|
|
151
229
|
timestamp: ts,
|
|
152
|
-
metrics:
|
|
230
|
+
metrics: row.metrics
|
|
153
231
|
});
|
|
154
232
|
}
|
|
155
233
|
return {
|
|
156
234
|
rows,
|
|
157
|
-
totals,
|
|
158
|
-
meta:
|
|
159
|
-
provider: "plausible",
|
|
160
|
-
fetchedAt
|
|
161
|
-
}
|
|
235
|
+
totals: totalRows[0]?.metrics ?? {},
|
|
236
|
+
meta: meta()
|
|
162
237
|
};
|
|
163
238
|
}
|
|
164
239
|
if (!dims.length) {
|
|
165
|
-
const totals = await
|
|
240
|
+
const totals = (await readPair({}))[0]?.metrics ?? {};
|
|
166
241
|
return {
|
|
167
242
|
rows: [{ metrics: totals }],
|
|
168
243
|
totals,
|
|
169
|
-
meta:
|
|
170
|
-
provider: "plausible",
|
|
171
|
-
fetchedAt
|
|
172
|
-
}
|
|
244
|
+
meta: meta()
|
|
173
245
|
};
|
|
174
246
|
}
|
|
175
247
|
return {
|
|
176
|
-
rows: (await
|
|
248
|
+
rows: (await readPair({ dimensions: dims.map((d) => DIMENSION_MAP[d]) })).map((row) => {
|
|
177
249
|
const dimValues = {};
|
|
178
250
|
for (let i = 0; i < dims.length; i++) {
|
|
179
251
|
const d = dims[i];
|
|
180
|
-
if (d !== void 0) dimValues[d] = row.
|
|
252
|
+
if (d !== void 0) dimValues[d] = row.keys[i] ?? "";
|
|
181
253
|
}
|
|
182
254
|
return {
|
|
183
255
|
dimensions: dimValues,
|
|
184
|
-
metrics:
|
|
256
|
+
metrics: row.metrics
|
|
185
257
|
};
|
|
186
258
|
}),
|
|
187
259
|
totals: void 0,
|
|
188
|
-
meta:
|
|
189
|
-
provider: "plausible",
|
|
190
|
-
fetchedAt
|
|
191
|
-
}
|
|
260
|
+
meta: meta()
|
|
192
261
|
};
|
|
193
262
|
}
|
|
194
263
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,OAAO,UACV,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,OAAO,SAAS;GAAM,OAAO;EAAK,GAC1D,EACC,QAAQ,GAAG,eAAe,2BAA2B,KAAK,UAAU,GAAG,KAAK,WAAW,EAAE,IAC1F,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAgB,UAAU,GAAG,KAAK;EAAc,GAC1D;GAAE,QAAQ;GAAc,UAAU,GAAG,KAAK;EAAY,CACvD,EACD;EACA,UAAU,EAAE,YAAY,EAAE,SAAS,QAAQ,IAAI,EAAE;EACjD,QAAQ,EAAE,MAAM,YAAY;CAC7B;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,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AAM,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\tFilterOperator,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tproviderMetricKeys,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\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\t/**\n\t * The ISO currency of the site's revenue goals. Declaring it turns on the `revenue`\n\t * metric: Plausible serves `total_revenue` only where a revenue goal exists, and errors\n\t * the whole request on a site that has none.\n\t */\n\trevenueCurrency?: 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\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n\tgoal: 'event:goal',\n}\n\n/**\n * Stats API v2 filter operators, available on every dimension this adapter offers as a\n * filter (event:goal is the grammar's one exception, taking `is` and `contains` only, and\n * is a breakdown here rather than a filter). `matches` is an re2 full match, so a pattern\n * has to cover the whole value (`/docs/.*`, not `^/docs`).\n */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n// `goal` is a breakdown, not a filter: the read's own goal slugs own the event:goal clause,\n// and the grammar allows no `matches` on it anyway.\nconst plausibleFilters: ReadonlySet<DimensionKey> = new Set(\n\t[...plausibleDimensions].filter((dimension) => dimension !== 'goal')\n)\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\n/**\n * Plausible identifies a goal by its display name in the site's own goal list (\"Signup\",\n * \"Visit /thank-you\"), so a plugin goal's slug must equal that name for its conversions to\n * read. Conversions are the `events` metric on goal rows, which is the dashboard's Total\n * Conversions; revenue is `total_revenue`, which Plausible serves only for a revenue goal\n * and reports as an object whose `value` is null when the rows mix currencies. Revenue is\n * offered only when `revenueCurrency` says the site has such a goal: asking for it on a site\n * without one errors the request.\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\tconst revenueGoals = Boolean(config.revenueCurrency)\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleFilters,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\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 dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'plausible', q, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m] && (revenueGoals || m !== 'revenue'))\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted,\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteKeys = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalKeys = providerMetricKeys(goalMetrics, METRIC_MAP)\n\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 is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = plausibleFilters.has(filter.dimension)\n\t\t\t\t\t? DIMENSION_MAP[filter.dimension]\n\t\t\t\t\t: undefined\n\t\t\t\tif (!mapped) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], mapped, [filter.value]])\n\t\t\t}\n\t\t\tconst goalFilters: Array<[string, string, string[]]> = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst readMetrics = (\n\t\t\t\tms: MetricKey[],\n\t\t\t\tkeys: string[],\n\t\t\t\trow: PlausibleResult\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 ms) {\n\t\t\t\t\tconst raw = row.metrics[keys.indexOf(METRIC_MAP[m] as string)]\n\t\t\t\t\tif (m === 'revenue') {\n\t\t\t\t\t\tconst amount = revenueAmount(raw)\n\t\t\t\t\t\tif (amount !== undefined) {\n\t\t\t\t\t\t\tout.revenue = amount\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tout[m] = toContractValue(m, typeof raw === 'number' ? raw : 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (\n\t\t\t\tmetrics: string[],\n\t\t\t\tclauses: Array<[string, string, string[]]>,\n\t\t\t\textra: Record<string, unknown>\n\t\t\t): 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,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\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 keyedRows = (\n\t\t\t\tresponse: PlausibleResponse | undefined,\n\t\t\t\tms: MetricKey[],\n\t\t\t\tkeys: string[]\n\t\t\t): GoalKeyedRow[] | undefined =>\n\t\t\t\tresponse?.results.map((row) => ({\n\t\t\t\t\tkeys: row.dimensions,\n\t\t\t\t\tmetrics: readMetrics(ms, keys, row),\n\t\t\t\t}))\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (extra: Record<string, unknown>): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteKeys.length ? () => postQuery(siteKeys, siteFilters, extra) : undefined,\n\t\t\t\t\tgoals: goalKeys.length ? () => postQuery(goalKeys, goalFilters, extra) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteKeys),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalKeys)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series) {\n\t\t\t\t\tconst ts = dayIso(row.keys[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: row.metrics })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals: totalRows[0]?.metrics ?? {}, meta: meta() }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = merged.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.keys[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA4DA,MAAM,iBACL;AAED,SAAS,aAAa,QAAyC;CAC9D,MAAM,OAAO,OAAO,QAAQ;CAC5B,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,OAAO,UACV,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,OAAO,SAAS;GAAM,OAAO;EAAK,GAC1D,EACC,QAAQ,GAAG,eAAe,2BAA2B,KAAK,UAAU,GAAG,KAAK,WAAW,EAAE,IAC1F,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAgB,UAAU,GAAG,KAAK;EAAc,GAC1D;GAAE,QAAQ;GAAc,UAAU,GAAG,KAAK;EAAY,CACvD,EACD;EACA,UAAU,EAAE,YAAY,EAAE,SAAS,QAAQ,IAAI,EAAE;EACjD,QAAQ,EAAE,MAAM,YAAY;CAC7B;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CAGb,aAAa;CACb,SAAS;AACV;;AAGA,MAAM,eAAuC,IAAI,IAAI,CAAC,eAAe,SAAS,CAAC;AAE/E,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;CACb,MAAM;AACP;;;;;;;AAQA,MAAM,eAA+C;CACpD,IAAI;CACJ,UAAU;CAC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,CAAC;IAC9B,KAAK,MAAM,OAAO,QAAQ;KACzB,MAAM,KAAK,OAAO,IAAI,KAAK,MAAM,EAAE;KACnC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,IAAI;KAAQ,CAAC;IAEnD;IACA,OAAO;KAAE;KAAM,QAAQ,UAAU,IAAI,WAAW,CAAC;KAAG,MAAM,KAAK;IAAE;GAClE;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,IAAI,WAAW,CAAC;IACpD,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAaA,OAAO;IAAE,OAVoB,MADR,SAAS,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACrD,KAAK,QAAQ;KAChD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,KAAK,MAAM;KAEhC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,IAAI;KAAQ;IACtD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
|
|
1
2
|
import { dayIso, hourIso } from "../series.js";
|
|
2
3
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
4
|
//#region src/adapters/posthog/posthog.ts
|
|
@@ -61,15 +62,30 @@ const METRIC_SQL_ALL = {
|
|
|
61
62
|
sessions: "count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))",
|
|
62
63
|
events: "count()"
|
|
63
64
|
};
|
|
65
|
+
const METRIC_SQL_GOAL = {
|
|
66
|
+
pageviews: "count()",
|
|
67
|
+
visitors: "count(DISTINCT person_id)",
|
|
68
|
+
visits: "count(DISTINCT properties.$session_id)",
|
|
69
|
+
sessions: "count(DISTINCT properties.$session_id)",
|
|
70
|
+
events: "count()"
|
|
71
|
+
};
|
|
72
|
+
/** A goal is an event name here, so a plugin goal's slug must equal the captured event's name. */
|
|
64
73
|
const DIMENSION_SQL = {
|
|
65
74
|
page: "properties.$pathname",
|
|
66
|
-
event: "event"
|
|
75
|
+
event: "event",
|
|
76
|
+
goal: "event"
|
|
67
77
|
};
|
|
68
|
-
const posthogMetrics = new Set(Object.keys(METRIC_SQL_ALL));
|
|
78
|
+
const posthogMetrics = new Set([...Object.keys(METRIC_SQL_ALL), "conversions"]);
|
|
69
79
|
const posthogDimensions = new Set(Object.keys(DIMENSION_SQL));
|
|
80
|
+
const posthogFilters = new Set([...posthogDimensions].filter((dimension) => dimension !== "goal"));
|
|
70
81
|
const sqlString = (value) => `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
71
82
|
const escapeLikeValue = (value) => value.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
72
|
-
|
|
83
|
+
/**
|
|
84
|
+
* A bare HogQL date literal parses in the project's timezone, so the UTC wall time
|
|
85
|
+
* `toISOString` produces would drift by that offset; the zone is passed explicitly to keep
|
|
86
|
+
* the bound an absolute instant (https://posthog.com/docs/hogql/expressions).
|
|
87
|
+
*/
|
|
88
|
+
const utcDateTime = (d) => `toDateTime(${sqlString(d.toISOString().slice(0, 19).replace("T", " "))}, 'UTC')`;
|
|
73
89
|
function posthog(config) {
|
|
74
90
|
const host = config.host ?? US_CLOUD;
|
|
75
91
|
return {
|
|
@@ -78,12 +94,11 @@ function posthog(config) {
|
|
|
78
94
|
capabilities: {
|
|
79
95
|
perPageQuery: true,
|
|
80
96
|
realtime: false,
|
|
81
|
-
comparison: false,
|
|
82
97
|
minGranularity: "hour",
|
|
83
98
|
maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
|
|
84
99
|
metrics: posthogMetrics,
|
|
85
100
|
dimensions: posthogDimensions,
|
|
86
|
-
filters:
|
|
101
|
+
filters: posthogFilters,
|
|
87
102
|
filterOperators: new Set([
|
|
88
103
|
"eq",
|
|
89
104
|
"contains",
|
|
@@ -105,17 +120,36 @@ function posthog(config) {
|
|
|
105
120
|
async query(q, ctx) {
|
|
106
121
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
107
122
|
const breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d]);
|
|
108
|
-
const
|
|
109
|
-
const
|
|
123
|
+
const hint = goalHint(q);
|
|
124
|
+
const slugs = hintSlugs(hint);
|
|
125
|
+
const empty = breakdownDim === "goal" ? emptyGoalBreakdown({
|
|
126
|
+
provider: "posthog",
|
|
127
|
+
q,
|
|
128
|
+
hint
|
|
129
|
+
}) : null;
|
|
130
|
+
if (empty) return empty;
|
|
131
|
+
const scanAllEvents = q.metrics.includes("events") || q.metrics.includes("conversions") || breakdownDim === "event" || breakdownDim === "goal" || (q.filters ?? []).some((f) => f.dimension === "event" && DIMENSION_SQL[f.dimension]);
|
|
132
|
+
const eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(", ")})` : void 0;
|
|
133
|
+
const metricSql = {
|
|
134
|
+
...breakdownDim === "goal" ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW,
|
|
135
|
+
...eventInHint ? { conversions: `countIf(${eventInHint})` } : {}
|
|
136
|
+
};
|
|
137
|
+
const unresolved = q.metrics.includes("conversions") && hintFailed(hint);
|
|
110
138
|
const wanted = q.metrics.filter((m) => metricSql[m]);
|
|
111
139
|
const exprs = [...new Set(wanted.map((m) => metricSql[m]))];
|
|
112
|
-
const
|
|
140
|
+
const meta = {
|
|
141
|
+
provider: "posthog",
|
|
142
|
+
fetchedAt,
|
|
143
|
+
...unresolved ? { goalsUnresolved: true } : {}
|
|
144
|
+
};
|
|
145
|
+
const where = [`timestamp >= ${utcDateTime(q.dateRange.start)}`, `timestamp <= ${utcDateTime(q.dateRange.end)}`];
|
|
113
146
|
if (!scanAllEvents) where.unshift("event = '$pageview'");
|
|
147
|
+
if (breakdownDim === "goal" && eventInHint) where.push(eventInHint);
|
|
114
148
|
if (q.path) where.push(`properties.$pathname = ${sqlString(q.path)}`);
|
|
115
149
|
if (q.hostname) where.push(`properties.$host = ${sqlString(q.hostname)}`);
|
|
116
150
|
if (config.scopeProperty && q.scope !== void 0) where.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`);
|
|
117
151
|
for (const filter of q.filters ?? []) {
|
|
118
|
-
const expr = DIMENSION_SQL[filter.dimension];
|
|
152
|
+
const expr = posthogFilters.has(filter.dimension) ? DIMENSION_SQL[filter.dimension] : void 0;
|
|
119
153
|
if (!expr) continue;
|
|
120
154
|
if (filter.operator === "eq") where.push(`${expr} = ${sqlString(filter.value)}`);
|
|
121
155
|
else if (filter.operator === "contains") where.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`);
|
|
@@ -158,10 +192,7 @@ function posthog(config) {
|
|
|
158
192
|
return {
|
|
159
193
|
rows,
|
|
160
194
|
totals,
|
|
161
|
-
meta
|
|
162
|
-
provider: "posthog",
|
|
163
|
-
fetchedAt
|
|
164
|
-
}
|
|
195
|
+
meta
|
|
165
196
|
};
|
|
166
197
|
}
|
|
167
198
|
if (q.granularity === "hour" && !breakdownDim) {
|
|
@@ -178,10 +209,7 @@ function posthog(config) {
|
|
|
178
209
|
return {
|
|
179
210
|
rows,
|
|
180
211
|
totals,
|
|
181
|
-
meta
|
|
182
|
-
provider: "posthog",
|
|
183
|
-
fetchedAt
|
|
184
|
-
}
|
|
212
|
+
meta
|
|
185
213
|
};
|
|
186
214
|
}
|
|
187
215
|
if (breakdownDim) return {
|
|
@@ -190,19 +218,13 @@ function posthog(config) {
|
|
|
190
218
|
metrics: readRow(row, 1)
|
|
191
219
|
})),
|
|
192
220
|
totals: void 0,
|
|
193
|
-
meta
|
|
194
|
-
provider: "posthog",
|
|
195
|
-
fetchedAt
|
|
196
|
-
}
|
|
221
|
+
meta
|
|
197
222
|
};
|
|
198
223
|
const totals = await fetchTotals();
|
|
199
224
|
return {
|
|
200
225
|
rows: [{ metrics: totals }],
|
|
201
226
|
totals,
|
|
202
|
-
meta
|
|
203
|
-
provider: "posthog",
|
|
204
|
-
fetchedAt
|
|
205
|
-
}
|
|
227
|
+
meta
|
|
206
228
|
};
|
|
207
229
|
}
|
|
208
230
|
};
|
|
@@ -1 +1 @@
|
|
|
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,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KAAE,QAAQ;KAAQ,UAAU,WAAW,OAAO;IAAoB;GACnE;EACD;EACA,UAAU,EA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AAE;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 { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\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), `conversions`, or an `event`/`goal` breakdown is requested. The WHERE\n// is not filtered to `$pageview`, so the pageview-family metrics scope themselves with\n// 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\n// A goal breakdown restricts the scan to the goal events themselves, so every metric counts\n// the rows it already has. The conditional aggregates above would answer 0 for each one, and\n// a conversion rate against a zeroed visitors count is 0% for every goal.\nconst METRIC_SQL_GOAL: 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\tevents: 'count()',\n}\n\n/** A goal is an event name here, so a plugin goal's slug must equal the captured event's name. */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\n// conversions has no fixed expression: it counts the read's own goal slugs, so the adapter\n// builds its conditional aggregate per query.\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set([\n\t...(Object.keys(METRIC_SQL_ALL) as MetricKey[]),\n\t'conversions',\n])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n// `goal` is a breakdown, not a filter: the read's own goal slugs own the event clause.\nconst posthogFilters: ReadonlySet<DimensionKey> = new Set(\n\t[...posthogDimensions].filter((dimension) => dimension !== 'goal')\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\n/**\n * A bare HogQL date literal parses in the project's timezone, so the UTC wall time\n * `toISOString` produces would drift by that offset; the zone is passed explicitly to keep\n * the bound an absolute instant (https://posthog.com/docs/hogql/expressions).\n */\nconst utcDateTime = (d: Date): string =>\n\t`toDateTime(${sqlString(d.toISOString().slice(0, 19).replace('T', ' '))}, 'UTC')`\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\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogFilters,\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\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst empty =\n\t\t\t\tbreakdownDim === 'goal' ? emptyGoalBreakdown({ provider: 'posthog', q, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\t// A total-events metric, a goal or event-name breakdown, a conversions count, or a\n\t\t\t// filter on the event dimension must scan every event, not just pageviews (a\n\t\t\t// `$pageview` WHERE clause combined with an `event = 'x'` filter would be\n\t\t\t// self-contradictory and zero every metric); those reads switch to conditional\n\t\t\t// aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tq.metrics.includes('conversions') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\tbreakdownDim === 'goal' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(', ')})` : undefined\n\t\t\t// Counting the goals conditionally, rather than restricting the WHERE, keeps the\n\t\t\t// site metrics of a read that asks for both site-wide.\n\t\t\tconst metricSql: Partial<Record<MetricKey, string>> = {\n\t\t\t\t...(breakdownDim === 'goal'\n\t\t\t\t\t? METRIC_SQL_GOAL\n\t\t\t\t\t: scanAllEvents\n\t\t\t\t\t\t? METRIC_SQL_ALL\n\t\t\t\t\t\t: METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\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\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= ${utcDateTime(q.dateRange.start)}`,\n\t\t\t\t`timestamp <= ${utcDateTime(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\t// Only the goal breakdown narrows the scan itself: its rows are the goals and\n\t\t\t// nothing else.\n\t\t\tif (breakdownDim === 'goal' && eventInHint) {\n\t\t\t\twhere.push(eventInHint)\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 = posthogFilters.has(filter.dimension)\n\t\t\t\t\t? DIMENSION_SQL[filter.dimension]\n\t\t\t\t\t: undefined\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 }\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 }\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 }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;AAyCA,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,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KAAE,QAAQ;KAAQ,UAAU,WAAW,OAAO;IAAoB;GACnE;EACD;EACA,UAAU,EAAE,YA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,IAAI,CAAC,OAAO,SAAS,GAAG,YAAY,CAAC,CAAC;IACjF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,WAAW,SAAS;KACrC,MAAM,KAAK,QAAQ,OAAO,IAAI,MAAM,EAAE,CAAC;KACvC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,KAAK,CAAC;KAAE,CAAC;IAEvD;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;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;GAAK;GAGxC,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
|
|
@@ -16,6 +16,14 @@ interface UmamiConfig {
|
|
|
16
16
|
/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
|
|
17
17
|
maxLookbackDays?: number | null;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Targets Umami 3.x (cloud and self-hosted): filter values carry an operator prefix, and
|
|
21
|
+
* `eq.` is always written explicitly. Umami parses any of `eq`, `neq`, `c`, `dnc`, `re`,
|
|
22
|
+
* `nre`, `s`, `ns`, `t`, `f`, `gt`, `lt`, `gte`, `lte`, `bf` and `af` followed by a dot as
|
|
23
|
+
* the operator, so a bare value beginning with one (`s.example.com`) would change meaning;
|
|
24
|
+
* written as `eq.s.example.com` it stays a literal. Umami splits an `eq.` value on commas
|
|
25
|
+
* into a value list, with no escape.
|
|
26
|
+
*/
|
|
19
27
|
declare function umami(config: UmamiConfig): AnalyticsAdapter;
|
|
20
28
|
//#endregion
|
|
21
29
|
export { UmamiConfig, umami };
|