@10x-media/analytics 1.0.0-beta.8 → 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 +70 -0
- package/LICENSE +21 -21
- package/README.md +3 -3
- 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 +178 -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 +110 -42
- 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/charts/BarList.js +8 -2
- package/dist/charts/BarList.js.map +1 -1
- package/dist/core/cacheKey.js +11 -1
- 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 +32 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +8 -2
- package/dist/core/options.js +4 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/serverEvent.d.ts +4 -2
- package/dist/core/serverEvent.js.map +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/client.d.ts +5 -2
- package/dist/exports/client.js +4 -1
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/tracker.js +2 -1
- package/dist/exports/types.d.ts +2 -1
- package/dist/exports/types.js +2 -1
- 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 +1 -1
- package/dist/fields/config/SourceSelectField.js +1 -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.js +16 -4
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- 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/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 +6 -0
- package/dist/native/ingest/normalizeEvent.js +32 -5
- 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.js +1 -0
- package/dist/native/ingest/serverTrack.js.map +1 -1
- 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/nativeAdapter.js +32 -26
- 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/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 +26 -7
- 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/queryEndpoint.js +19 -12
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/realtimeEndpoint.js +40 -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/sourcesEndpoint.js +10 -3
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/collection.js +14 -4
- 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/query/response.d.ts +4 -1
- 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/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 +30 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +30 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +30 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +30 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +30 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +30 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +29 -0
- package/dist/translations/keys.js +30 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +30 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +7 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +30 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +30 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +30 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +30 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsViewClient.js +13 -2
- package/dist/view/AnalyticsViewClient.js.map +1 -1
- package/dist/view/gating.js +40 -3
- package/dist/view/gating.js.map +1 -1
- package/dist/view/labels.js +21 -1
- package/dist/view/labels.js.map +1 -1
- package/dist/view/sections/Breakdowns.js +78 -38
- package/dist/view/sections/Breakdowns.js.map +1 -1
- package/dist/view/sections/FilterChips.js +8 -3
- package/dist/view/sections/FilterChips.js.map +1 -1
- package/dist/view/sections/GoalsPanel.js +2 -1
- package/dist/view/sections/GoalsPanel.js.map +1 -1
- package/dist/view/sections/RealtimeStrip.js +4 -1
- package/dist/view/sections/RealtimeStrip.js.map +1 -1
- package/dist/view/sections/Toolbar.js +10 -3
- package/dist/view/sections/Toolbar.js.map +1 -1
- package/dist/view/sections/Trend.js +8 -2
- package/dist/view/sections/Trend.js.map +1 -1
- package/dist/view/state.js +7 -2
- package/dist/view/state.js.map +1 -1
- package/dist/view/useViewQueries.js +6 -3
- package/dist/view/useViewQueries.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +30 -3
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +30 -3
- 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/breakdownTypes.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/readForWidget.d.ts +12 -2
- package/dist/widgets/readForWidget.js +34 -49
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
- package/dist/widgets/readForWidgetBreakdown.js +29 -42
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +11 -1
- package/dist/widgets/readForWidgetGoals.js +44 -30
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- 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 +11 -1
- package/dist/widgets/readForWidgetSeries.js +38 -49
- 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 +5 -2
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.js +5 -2
- package/dist/widgets/viewLink.js.map +1 -1
- package/package.json +5 -5
- 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 -53
- package/dist/native/rollups/insertIfNew.js.map +0 -1
|
@@ -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,WAA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AO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { 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,OAA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AAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE;IACnH,MAAM,CAAC,YAAY,UAAU,MAAM,QAAQ,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 };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
|
|
1
2
|
import { dayIso } from "../series.js";
|
|
2
3
|
import { fetchJson } from "../http/fetchJson.js";
|
|
3
4
|
//#region src/adapters/umami/umami.ts
|
|
@@ -33,21 +34,115 @@ const umamiMetrics = new Set([
|
|
|
33
34
|
"visits",
|
|
34
35
|
"sessions",
|
|
35
36
|
"bounceRate",
|
|
36
|
-
"avgDuration"
|
|
37
|
+
"avgDuration",
|
|
38
|
+
"conversions"
|
|
37
39
|
]);
|
|
38
|
-
const
|
|
40
|
+
const DIMENSION_MAP = {
|
|
41
|
+
page: {
|
|
42
|
+
param: "path",
|
|
43
|
+
metric: "visitors"
|
|
44
|
+
},
|
|
45
|
+
referrer: {
|
|
46
|
+
param: "referrer",
|
|
47
|
+
metric: "visitors"
|
|
48
|
+
},
|
|
49
|
+
browser: {
|
|
50
|
+
param: "browser",
|
|
51
|
+
metric: "visitors"
|
|
52
|
+
},
|
|
53
|
+
os: {
|
|
54
|
+
param: "os",
|
|
55
|
+
metric: "visitors"
|
|
56
|
+
},
|
|
57
|
+
device: {
|
|
58
|
+
param: "device",
|
|
59
|
+
metric: "visitors"
|
|
60
|
+
},
|
|
61
|
+
country: {
|
|
62
|
+
param: "country",
|
|
63
|
+
metric: "visitors"
|
|
64
|
+
},
|
|
65
|
+
region: {
|
|
66
|
+
param: "region",
|
|
67
|
+
metric: "visitors"
|
|
68
|
+
},
|
|
69
|
+
city: {
|
|
70
|
+
param: "city",
|
|
71
|
+
metric: "visitors"
|
|
72
|
+
},
|
|
73
|
+
language: {
|
|
74
|
+
param: "language",
|
|
75
|
+
metric: "visitors"
|
|
76
|
+
},
|
|
77
|
+
event: {
|
|
78
|
+
param: "event",
|
|
79
|
+
metric: "events"
|
|
80
|
+
},
|
|
81
|
+
utmSource: {
|
|
82
|
+
param: "utmSource",
|
|
83
|
+
metric: "visitors"
|
|
84
|
+
},
|
|
85
|
+
utmMedium: {
|
|
86
|
+
param: "utmMedium",
|
|
87
|
+
metric: "visitors"
|
|
88
|
+
},
|
|
89
|
+
utmCampaign: {
|
|
90
|
+
param: "utmCampaign",
|
|
91
|
+
metric: "visitors"
|
|
92
|
+
},
|
|
93
|
+
utmContent: {
|
|
94
|
+
param: "utmContent",
|
|
95
|
+
metric: "visitors"
|
|
96
|
+
},
|
|
97
|
+
utmTerm: {
|
|
98
|
+
param: "utmTerm",
|
|
99
|
+
metric: "visitors"
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* Goals are custom events here, counted by `/metrics?type=event`, whose y is the number of
|
|
104
|
+
* occurrences: a plugin goal's slug must equal the captured event's name. It is the one
|
|
105
|
+
* shape that answers `conversions`, so a breakdown by any other dimension and the daily
|
|
106
|
+
* series report none.
|
|
107
|
+
*/
|
|
108
|
+
const GOAL_DIMENSION = {
|
|
109
|
+
param: "event",
|
|
110
|
+
metric: "conversions"
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits
|
|
114
|
+
* anywhere in the value. `c.` is `ilike`, also case-insensitive.
|
|
115
|
+
*/
|
|
116
|
+
const OPERATOR_PREFIX = {
|
|
117
|
+
eq: "eq.",
|
|
118
|
+
contains: "c.",
|
|
119
|
+
matches: "re."
|
|
120
|
+
};
|
|
121
|
+
const umamiFilters = new Set(Object.keys(DIMENSION_MAP));
|
|
122
|
+
const umamiDimensions = new Set([...[...umamiFilters].filter((dimension) => dimension !== "event"), "goal"]);
|
|
123
|
+
/**
|
|
124
|
+
* Targets Umami 3.x (cloud and self-hosted): filter values carry an operator prefix, and
|
|
125
|
+
* `eq.` is always written explicitly. Umami parses any of `eq`, `neq`, `c`, `dnc`, `re`,
|
|
126
|
+
* `nre`, `s`, `ns`, `t`, `f`, `gt`, `lt`, `gte`, `lte`, `bf` and `af` followed by a dot as
|
|
127
|
+
* the operator, so a bare value beginning with one (`s.example.com`) would change meaning;
|
|
128
|
+
* written as `eq.s.example.com` it stays a literal. Umami splits an `eq.` value on commas
|
|
129
|
+
* into a value list, with no escape.
|
|
130
|
+
*/
|
|
39
131
|
function umami(config) {
|
|
40
132
|
const base = config.host ?? CLOUD_BASE;
|
|
41
133
|
const capabilities = {
|
|
42
134
|
perPageQuery: true,
|
|
43
135
|
realtime: false,
|
|
44
|
-
comparison: false,
|
|
45
136
|
minGranularity: "day",
|
|
46
137
|
maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
|
|
47
138
|
metrics: umamiMetrics,
|
|
48
139
|
dimensions: umamiDimensions,
|
|
49
|
-
filters:
|
|
50
|
-
filterOperators: new Set([
|
|
140
|
+
filters: umamiFilters,
|
|
141
|
+
filterOperators: new Set([
|
|
142
|
+
"eq",
|
|
143
|
+
"contains",
|
|
144
|
+
"matches"
|
|
145
|
+
]),
|
|
51
146
|
batchPageReport: true,
|
|
52
147
|
rateLimit: null,
|
|
53
148
|
recommendedTtl: {
|
|
@@ -56,13 +151,62 @@ function umami(config) {
|
|
|
56
151
|
}
|
|
57
152
|
};
|
|
58
153
|
const authHeaders = () => config.apiKey ? { "x-umami-api-key": config.apiKey } : config.token ? { authorization: `Bearer ${config.token}` } : {};
|
|
154
|
+
/**
|
|
155
|
+
* Umami takes one value per query param, so filters that land on the same param cannot
|
|
156
|
+
* all be sent. Two `eq` values on one param are an AND that matches nothing, which the
|
|
157
|
+
* read answers as empty without calling the API; anything else keeps the first filter,
|
|
158
|
+
* except that `q.path` always wins the `path` param so a per-page read stays scoped to
|
|
159
|
+
* its page. An `eq` value carrying a comma is dropped too: Umami reads such a value as a
|
|
160
|
+
* list and offers no escape, so sending it would answer a wider question than the one
|
|
161
|
+
* asked. Whatever was dropped travels back in `meta.unappliedFilters`.
|
|
162
|
+
*/
|
|
59
163
|
const params = (q) => {
|
|
60
164
|
const p = new URLSearchParams({
|
|
61
165
|
startAt: String(q.dateRange.start.getTime()),
|
|
62
166
|
endAt: String(q.dateRange.end.getTime())
|
|
63
167
|
});
|
|
64
|
-
|
|
65
|
-
|
|
168
|
+
const unapplied = [];
|
|
169
|
+
const eqValues = /* @__PURE__ */ new Map();
|
|
170
|
+
for (const filter of q.filters ?? []) {
|
|
171
|
+
const mapped = DIMENSION_MAP[filter.dimension];
|
|
172
|
+
if (!mapped || filter.operator !== "eq") continue;
|
|
173
|
+
const held = eqValues.get(mapped.param);
|
|
174
|
+
if (held !== void 0 && held !== filter.value) return {
|
|
175
|
+
search: p,
|
|
176
|
+
unapplied,
|
|
177
|
+
empty: true
|
|
178
|
+
};
|
|
179
|
+
eqValues.set(mapped.param, filter.value);
|
|
180
|
+
}
|
|
181
|
+
const held = /* @__PURE__ */ new Map();
|
|
182
|
+
for (const filter of q.filters ?? []) {
|
|
183
|
+
const mapped = DIMENSION_MAP[filter.dimension];
|
|
184
|
+
if (!mapped) continue;
|
|
185
|
+
if (filter.operator === "eq" && filter.value.includes(",")) {
|
|
186
|
+
unapplied.push(filter);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const value = `${OPERATOR_PREFIX[filter.operator]}${filter.value}`;
|
|
190
|
+
const first = held.get(mapped.param);
|
|
191
|
+
if (first === void 0) {
|
|
192
|
+
held.set(mapped.param, {
|
|
193
|
+
value,
|
|
194
|
+
filter
|
|
195
|
+
});
|
|
196
|
+
p.set(mapped.param, value);
|
|
197
|
+
} else if (first.value !== value) unapplied.push(filter);
|
|
198
|
+
}
|
|
199
|
+
if (q.path) {
|
|
200
|
+
const value = `eq.${q.path}`;
|
|
201
|
+
const first = held.get("path");
|
|
202
|
+
if (first !== void 0 && first.value !== value) unapplied.push(first.filter);
|
|
203
|
+
p.set("path", value);
|
|
204
|
+
}
|
|
205
|
+
return {
|
|
206
|
+
search: p,
|
|
207
|
+
unapplied,
|
|
208
|
+
empty: false
|
|
209
|
+
};
|
|
66
210
|
};
|
|
67
211
|
return {
|
|
68
212
|
id: "umami",
|
|
@@ -73,34 +217,105 @@ function umami(config) {
|
|
|
73
217
|
async query(q, ctx) {
|
|
74
218
|
const fetchedAt = q.dateRange.end.toISOString();
|
|
75
219
|
const headers = authHeaders();
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
220
|
+
const goalBreakdown = (q.dimensions ?? []).includes("goal");
|
|
221
|
+
const hint = goalHint(q);
|
|
222
|
+
const slugs = hintSlugs(hint);
|
|
223
|
+
const plan = params(q);
|
|
224
|
+
let breakdown;
|
|
225
|
+
for (const dimension of q.dimensions ?? []) {
|
|
226
|
+
const mapped = DIMENSION_MAP[dimension];
|
|
227
|
+
if (mapped) {
|
|
228
|
+
breakdown = {
|
|
229
|
+
dimension,
|
|
230
|
+
...mapped
|
|
231
|
+
};
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const askable = (slugs ?? []).filter((slug) => !slug.includes(","));
|
|
236
|
+
const eventValue = `eq.${askable.join(",")}`;
|
|
237
|
+
const eventFilter = (q.filters ?? []).find((f) => f.dimension === "event");
|
|
238
|
+
const readsGoals = goalBreakdown || !breakdown && q.metrics.includes("conversions") && slugs !== null;
|
|
239
|
+
const unapplied = [
|
|
240
|
+
...plan.unapplied,
|
|
241
|
+
...(slugs ?? []).filter((slug) => slug.includes(",")).map((slug) => ({
|
|
242
|
+
dimension: "goal",
|
|
243
|
+
operator: "eq",
|
|
244
|
+
value: slug
|
|
245
|
+
})),
|
|
246
|
+
...readsGoals && eventFilter && `${OPERATOR_PREFIX[eventFilter.operator]}${eventFilter.value}` !== eventValue ? [eventFilter] : []
|
|
247
|
+
];
|
|
248
|
+
const unresolved = q.metrics.includes("conversions") && hintFailed(hint);
|
|
249
|
+
const unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {};
|
|
250
|
+
const empty = goalBreakdown ? emptyGoalBreakdown({
|
|
251
|
+
provider: "umami",
|
|
252
|
+
q,
|
|
253
|
+
hint,
|
|
254
|
+
meta: unappliedMeta
|
|
255
|
+
}) : null;
|
|
256
|
+
if (empty) return empty;
|
|
257
|
+
const meta = {
|
|
258
|
+
provider: "umami",
|
|
259
|
+
fetchedAt,
|
|
260
|
+
...unappliedMeta,
|
|
261
|
+
...unresolved ? { goalsUnresolved: true } : {}
|
|
262
|
+
};
|
|
263
|
+
if (plan.empty) return {
|
|
264
|
+
rows: [],
|
|
265
|
+
totals: void 0,
|
|
266
|
+
meta
|
|
267
|
+
};
|
|
268
|
+
const search = () => new URLSearchParams(plan.search);
|
|
269
|
+
/**
|
|
270
|
+
* The goal rows for the hint, narrowed to it again on the way back so nothing the API
|
|
271
|
+
* did not restrict can arrive as a goal.
|
|
272
|
+
*/
|
|
273
|
+
const fetchGoalRows = async () => {
|
|
274
|
+
if (askable.length === 0) return [];
|
|
275
|
+
const p = search();
|
|
276
|
+
p.set("type", GOAL_DIMENSION.param);
|
|
277
|
+
p.set(GOAL_DIMENSION.param, eventValue);
|
|
79
278
|
const data = await fetchJson(`${base}/websites/${config.websiteId}/metrics?${p.toString()}`, {
|
|
80
279
|
headers,
|
|
81
280
|
signal: ctx.signal,
|
|
82
281
|
provider: "umami"
|
|
83
282
|
});
|
|
84
|
-
const
|
|
283
|
+
const wanted = new Set(askable);
|
|
284
|
+
return data.filter((row) => wanted.has(row.x));
|
|
285
|
+
};
|
|
286
|
+
if (goalBreakdown) return {
|
|
287
|
+
rows: (await fetchGoalRows()).map((row) => ({
|
|
288
|
+
dimensions: { goal: row.x },
|
|
289
|
+
metrics: { [GOAL_DIMENSION.metric]: row.y }
|
|
290
|
+
})),
|
|
291
|
+
totals: void 0,
|
|
292
|
+
meta
|
|
293
|
+
};
|
|
294
|
+
if (breakdown) {
|
|
295
|
+
const { dimension, param, metric } = breakdown;
|
|
296
|
+
const p = search();
|
|
297
|
+
p.set("type", param);
|
|
85
298
|
return {
|
|
86
|
-
rows:
|
|
87
|
-
|
|
299
|
+
rows: (await fetchJson(`${base}/websites/${config.websiteId}/metrics?${p.toString()}`, {
|
|
300
|
+
headers,
|
|
301
|
+
signal: ctx.signal,
|
|
302
|
+
provider: "umami"
|
|
303
|
+
})).map((row) => ({
|
|
304
|
+
dimensions: { [dimension]: row.x },
|
|
88
305
|
metrics: { [metric]: row.y }
|
|
89
306
|
})),
|
|
90
307
|
totals: void 0,
|
|
91
|
-
meta
|
|
92
|
-
provider: "umami",
|
|
93
|
-
fetchedAt
|
|
94
|
-
}
|
|
308
|
+
meta
|
|
95
309
|
};
|
|
96
310
|
}
|
|
97
311
|
const fetchTotals = async () => {
|
|
98
|
-
const stats = await fetchJson(`${base}/websites/${config.websiteId}/stats?${
|
|
312
|
+
const [stats, goalRows] = await Promise.all([fetchJson(`${base}/websites/${config.websiteId}/stats?${search().toString()}`, {
|
|
99
313
|
headers,
|
|
100
314
|
signal: ctx.signal,
|
|
101
315
|
provider: "umami"
|
|
102
|
-
});
|
|
316
|
+
}), q.metrics.includes("conversions") && slugs ? fetchGoalRows() : void 0]);
|
|
103
317
|
const all = {
|
|
318
|
+
...goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {},
|
|
104
319
|
pageviews: stats.pageviews,
|
|
105
320
|
visitors: stats.visitors,
|
|
106
321
|
visits: stats.visits,
|
|
@@ -113,7 +328,7 @@ function umami(config) {
|
|
|
113
328
|
return totals;
|
|
114
329
|
};
|
|
115
330
|
if (q.granularity === "day") {
|
|
116
|
-
const p =
|
|
331
|
+
const p = search();
|
|
117
332
|
p.set("unit", "day");
|
|
118
333
|
p.set("timezone", q.timezone ?? "UTC");
|
|
119
334
|
const fetchSeries = () => fetchJson(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {
|
|
@@ -143,20 +358,14 @@ function umami(config) {
|
|
|
143
358
|
return {
|
|
144
359
|
rows,
|
|
145
360
|
totals,
|
|
146
|
-
meta
|
|
147
|
-
provider: "umami",
|
|
148
|
-
fetchedAt
|
|
149
|
-
}
|
|
361
|
+
meta
|
|
150
362
|
};
|
|
151
363
|
}
|
|
152
364
|
const totals = await fetchTotals();
|
|
153
365
|
return {
|
|
154
366
|
rows: [{ metrics: totals }],
|
|
155
367
|
totals,
|
|
156
|
-
meta
|
|
157
|
-
provider: "umami",
|
|
158
|
-
fetchedAt
|
|
159
|
-
}
|
|
368
|
+
meta
|
|
160
369
|
};
|
|
161
370
|
}
|
|
162
371
|
};
|