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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/adapters/ga4/ga4.d.ts +7 -0
  3. package/dist/adapters/ga4/ga4.js +17 -3
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +6 -3
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +7 -0
  9. package/dist/adapters/posthog/posthog.js +92 -19
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/posthog/projectCheck.js +56 -0
  12. package/dist/adapters/posthog/projectCheck.js.map +1 -0
  13. package/dist/adapters/umami/umami.d.ts +6 -0
  14. package/dist/adapters/umami/umami.js +3 -1
  15. package/dist/adapters/umami/umami.js.map +1 -1
  16. package/dist/capture/trackerConfig.js +29 -6
  17. package/dist/capture/trackerConfig.js.map +1 -1
  18. package/dist/capture/withoutConsent.js +91 -0
  19. package/dist/capture/withoutConsent.js.map +1 -0
  20. package/dist/core/capture.d.ts +41 -11
  21. package/dist/core/captureOptions.js +97 -8
  22. package/dist/core/captureOptions.js.map +1 -1
  23. package/dist/core/contract.d.ts +25 -0
  24. package/dist/core/contract.js.map +1 -1
  25. package/dist/core/options.d.ts +26 -4
  26. package/dist/core/options.js.map +1 -1
  27. package/dist/core/sourceOptions.js +2 -1
  28. package/dist/core/sourceOptions.js.map +1 -1
  29. package/dist/exports/adapters/contract.d.ts +3 -3
  30. package/dist/exports/adapters/ga4.d.ts +4 -4
  31. package/dist/exports/adapters/native.d.ts +5 -5
  32. package/dist/exports/adapters/plausible.d.ts +4 -4
  33. package/dist/exports/adapters/posthog.d.ts +4 -4
  34. package/dist/exports/adapters/umami.d.ts +4 -4
  35. package/dist/exports/next.d.ts +4 -4
  36. package/dist/exports/react.d.ts +3 -2
  37. package/dist/exports/site.d.ts +2 -2
  38. package/dist/exports/testing.d.ts +4 -4
  39. package/dist/exports/tracker.d.ts +3 -2
  40. package/dist/exports/types.d.ts +5 -5
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +2 -0
  43. package/dist/index.js.map +1 -1
  44. package/dist/native/collections/hits.js +1 -0
  45. package/dist/native/collections/hits.js.map +1 -1
  46. package/dist/native/engine/engine.js +5 -1
  47. package/dist/native/engine/engine.js.map +1 -1
  48. package/dist/native/engine/planner.js +2 -1
  49. package/dist/native/engine/planner.js.map +1 -1
  50. package/dist/native/engine/toHit.js +4 -2
  51. package/dist/native/engine/toHit.js.map +1 -1
  52. package/dist/native/ingest/endpoint.js +5 -2
  53. package/dist/native/ingest/endpoint.js.map +1 -1
  54. package/dist/native/ingest/normalizeEvent.d.ts +6 -1
  55. package/dist/native/ingest/normalizeEvent.js +17 -7
  56. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  57. package/dist/native/ingest/serverTrack.js +2 -1
  58. package/dist/native/ingest/serverTrack.js.map +1 -1
  59. package/dist/native/ingest/validate.js +3 -0
  60. package/dist/native/ingest/validate.js.map +1 -1
  61. package/dist/native/nativeAdapter.d.ts +10 -1
  62. package/dist/native/nativeAdapter.js +11 -1
  63. package/dist/native/nativeAdapter.js.map +1 -1
  64. package/dist/native/store/aggregate.js +1 -1
  65. package/dist/native/store/aggregate.js.map +1 -1
  66. package/dist/native/store/hitRow.js +3 -0
  67. package/dist/native/store/hitRow.js.map +1 -1
  68. package/dist/native/store/hits.js +3 -1
  69. package/dist/native/store/hits.js.map +1 -1
  70. package/dist/native/store/mongo/aggregatePipelines.js +10 -2
  71. package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
  72. package/dist/native/store/mongo/pipelines.js +15 -5
  73. package/dist/native/store/mongo/pipelines.js.map +1 -1
  74. package/dist/native/store/parts.js +9 -3
  75. package/dist/native/store/parts.js.map +1 -1
  76. package/dist/native/store/rawRead.js +6 -3
  77. package/dist/native/store/rawRead.js.map +1 -1
  78. package/dist/native/store/sql/aggregateSql.js +6 -2
  79. package/dist/native/store/sql/aggregateSql.js.map +1 -1
  80. package/dist/native/store/sql/columns.js +1 -0
  81. package/dist/native/store/sql/columns.js.map +1 -1
  82. package/dist/native/store/sql/compile.js +19 -7
  83. package/dist/native/store/sql/compile.js.map +1 -1
  84. package/dist/native/store/types.d.ts +7 -1
  85. package/dist/native/store/types.js +10 -0
  86. package/dist/native/store/types.js.map +1 -0
  87. package/dist/plugin/createRuntime.js +10 -1
  88. package/dist/plugin/createRuntime.js.map +1 -1
  89. package/dist/plugin/runtime.js.map +1 -1
  90. package/dist/providers/collection.d.ts +4 -2
  91. package/dist/providers/collection.js +29 -4
  92. package/dist/providers/collection.js.map +1 -1
  93. package/dist/providers/factory.d.ts +9 -1
  94. package/dist/providers/factory.js +14 -5
  95. package/dist/providers/factory.js.map +1 -1
  96. package/dist/providers/registry.js +2 -1
  97. package/dist/providers/registry.js.map +1 -1
  98. package/dist/react/AnalyticsProvider.d.ts +6 -0
  99. package/dist/react/AnalyticsProvider.js.map +1 -1
  100. package/dist/react/useAnalytics.js +9 -5
  101. package/dist/react/useAnalytics.js.map +1 -1
  102. package/dist/site/AnalyticsScripts.d.ts +4 -3
  103. package/dist/site/AnalyticsScripts.js +18 -4
  104. package/dist/site/AnalyticsScripts.js.map +1 -1
  105. package/dist/surfacing/todaySplit.js +7 -1
  106. package/dist/surfacing/todaySplit.js.map +1 -1
  107. package/dist/tracker/config.d.ts +26 -1
  108. package/dist/tracker/config.js.map +1 -1
  109. package/dist/tracker/createTracker.d.ts +2 -1
  110. package/dist/tracker/createTracker.js +91 -59
  111. package/dist/tracker/createTracker.js.map +1 -1
  112. package/dist/tracker/gate.d.ts +8 -0
  113. package/dist/tracker/gate.js +61 -11
  114. package/dist/tracker/gate.js.map +1 -1
  115. package/dist/tracker/loadScript.js +2 -1
  116. package/dist/tracker/loadScript.js.map +1 -1
  117. package/dist/tracker/registry.js +14 -3
  118. package/dist/tracker/registry.js.map +1 -1
  119. package/dist/tracker/sinks/createSink.js +27 -8
  120. package/dist/tracker/sinks/createSink.js.map +1 -1
  121. package/dist/tracker/sinks/ga4.js +38 -6
  122. package/dist/tracker/sinks/ga4.js.map +1 -1
  123. package/dist/tracker/sinks/native.js +17 -3
  124. package/dist/tracker/sinks/native.js.map +1 -1
  125. package/dist/tracker/sinks/plausible.js +8 -2
  126. package/dist/tracker/sinks/plausible.js.map +1 -1
  127. package/dist/tracker/sinks/posthog.js +108 -16
  128. package/dist/tracker/sinks/posthog.js.map +1 -1
  129. package/dist/tracker/sinks/umami.js +2 -2
  130. package/dist/tracker/sinks/umami.js.map +1 -1
  131. package/dist/tracker/sinks/vendor.js +25 -11
  132. package/dist/tracker/sinks/vendor.js.map +1 -1
  133. package/dist/tracker/types.d.ts +10 -3
  134. package/dist/translations/ar.js +7 -0
  135. package/dist/translations/ar.js.map +1 -1
  136. package/dist/translations/de.js +7 -0
  137. package/dist/translations/de.js.map +1 -1
  138. package/dist/translations/en.js +7 -0
  139. package/dist/translations/en.js.map +1 -1
  140. package/dist/translations/es.js +7 -0
  141. package/dist/translations/es.js.map +1 -1
  142. package/dist/translations/fr.js +7 -0
  143. package/dist/translations/fr.js.map +1 -1
  144. package/dist/translations/id.js +7 -0
  145. package/dist/translations/id.js.map +1 -1
  146. package/dist/translations/keys.d.ts +7 -0
  147. package/dist/translations/keys.js +8 -1
  148. package/dist/translations/keys.js.map +1 -1
  149. package/dist/translations/ko.js +7 -0
  150. package/dist/translations/ko.js.map +1 -1
  151. package/dist/translations/pt.js +7 -0
  152. package/dist/translations/pt.js.map +1 -1
  153. package/dist/translations/ru.js +7 -0
  154. package/dist/translations/ru.js.map +1 -1
  155. package/dist/translations/uk.js +7 -0
  156. package/dist/translations/uk.js.map +1 -1
  157. package/dist/translations/zh.js +7 -0
  158. package/dist/translations/zh.js.map +1 -1
  159. package/dist/view/consentShare.js +15 -0
  160. package/dist/view/consentShare.js.map +1 -0
  161. package/dist/view/sections/OverviewCards.js +38 -28
  162. package/dist/view/sections/OverviewCards.js.map +1 -1
  163. package/dist/widgets/notices.js +6 -1
  164. package/dist/widgets/notices.js.map +1 -1
  165. package/dist/widgets/readMeta.d.ts +4 -0
  166. package/dist/widgets/readMeta.js +5 -0
  167. package/dist/widgets/readMeta.js.map +1 -1
  168. package/package.json +4 -4
@@ -1,6 +1,8 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { currentTime } from "../../core/clock.js";
2
3
  import { adapterLabel } from "../../core/sourceLabel.js";
3
4
  import { jsLiteral } from "../../capture/jsLiteral.js";
5
+ import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
4
6
  import { vendorReading } from "../../core/metricValues.js";
5
7
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
6
8
  import { declaredFilters, everyOperatorOn, firstMapped, mappedKeys, providerMetricKeys } from "../mapping.js";
@@ -8,6 +10,7 @@ import { readTime } from "../readTime.js";
8
10
  import { dayIso, hourIso } from "../series.js";
9
11
  import { upstreamJson } from "../upstream.js";
10
12
  import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
13
+ import { createProjectCheck } from "./projectCheck.js";
11
14
  //#region src/adapters/posthog/posthog.ts
12
15
  const US_CLOUD = "https://us.posthog.com";
13
16
  const resolveRegion = (config) => {
@@ -84,6 +87,17 @@ const CAPTURE_PAGEVIEW = "history_change";
84
87
  */
85
88
  const NAMED_CLIENT_PAGEVIEWS = ["capture_pageview:false", "capture_pageleave:true"];
86
89
  /**
90
+ * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to
91
+ * rather than stopping. Started cookieless, it counts from the first pageview while opted out by
92
+ * default, storing nothing, until the sink opts it in.
93
+ */
94
+ const cookielessOptions = (mode) => [`cookieless_mode:${jsLiteral("on_reject")}`, ...mode === "cookieless" ? ["opt_out_capturing_by_default:true"] : []];
95
+ /**
96
+ * The scope stamped on each event as it is sent: switching between cookieless and full resets
97
+ * PostHog's identity and every super-property `register` set with it.
98
+ */
99
+ const scopeHook = (property, scope) => `before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`;
100
+ /**
87
101
  * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's
88
102
  * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.
89
103
  */
@@ -92,7 +106,7 @@ const initOptions = (path, ui, named) => [
92
106
  ...ui === void 0 ? [] : [`ui_host:${jsLiteral(ui)}`],
93
107
  ...named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`],
94
108
  "opt_out_persistence_by_default:true"
95
- ].join(",");
109
+ ];
96
110
  function buildCapture(config, token) {
97
111
  const hosts = captureHosts(config);
98
112
  return {
@@ -113,12 +127,18 @@ function buildCapture(config, token) {
113
127
  ],
114
128
  ...config.fetch ? { fetch: config.fetch } : {}
115
129
  },
116
- snippet: ({ path, scope, instance }) => {
130
+ snippet: ({ path, scope, instance, mode = "full", withoutConsent = false }) => {
117
131
  const named = instance !== void 0;
118
132
  const client = named ? `posthog[${jsLiteral(instance)}]` : "posthog";
119
- const stamp = config.scopeProperty && scope ? `;${client}.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})` : "";
133
+ const property = config.scopeProperty && scope ? config.scopeProperty : void 0;
134
+ const stamp = property && scope && !withoutConsent ? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})` : "";
135
+ const options = [
136
+ ...initOptions(path, hosts.ui, named),
137
+ ...withoutConsent ? cookielessOptions(mode) : [],
138
+ ...withoutConsent && property && scope ? [scopeHook(property, scope)] : []
139
+ ].join(",");
120
140
  const name = named ? `,${jsLiteral(instance)}` : "";
121
- return { scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui, named)}}${name})${stamp}` }] };
141
+ return { scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${options}}${name})${stamp}` }] };
122
142
  },
123
143
  client: {
124
144
  kind: "posthog",
@@ -147,6 +167,11 @@ const METRIC_SQL_GOAL = {
147
167
  events: "count()"
148
168
  };
149
169
  /**
170
+ * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;
171
+ * compared as text, it matches whether the project types the property as a boolean or not.
172
+ */
173
+ const COOKIELESS_EVENT = "toString(properties.$cookieless_mode) = 'true'";
174
+ /**
150
175
  * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own
151
176
  * `$channel_type`, computed per session and honouring a project's custom channel rules.
152
177
  */
@@ -191,10 +216,12 @@ const SERIES_BUCKETS = {
191
216
  const utcDateTime = (d) => `toDateTime(${sqlString(d.toISOString().slice(0, 19).replace("T", " "))}, 'UTC')`;
192
217
  function posthog(config) {
193
218
  const host = withoutTrailingSlash(config.host ?? US_CLOUD);
219
+ const maxLookbackDays = config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730;
220
+ const withoutConsent = adapterWithoutConsent(config.withoutConsent, "posthog({ withoutConsent })", WITHOUT_CONSENT_LEVELS);
194
221
  const capabilities = {
195
222
  realtime: false,
196
223
  minGranularity: "hour",
197
- maxLookbackDays: config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730,
224
+ maxLookbackDays,
198
225
  metrics: posthogMetrics,
199
226
  dimensions: posthogDimensions,
200
227
  filters: posthogFilters,
@@ -213,23 +240,57 @@ function posthog(config) {
213
240
  upstreamAware: true,
214
241
  ...config.scopeProperty ? { scopedQueries: true } : {}
215
242
  };
243
+ let fillsCountingSlot = true;
244
+ const projectDropsCookieless = createProjectCheck({
245
+ host,
246
+ projectId: config.projectId,
247
+ apiKey: config.apiKey,
248
+ ...config.fetch ? { fetch: config.fetch } : {}
249
+ });
250
+ /**
251
+ * Whether a held slot this source fills may count cookielessly, which the project must accept:
252
+ * the boot's answer for a config source, the factory's `withoutConsent` for a document's.
253
+ */
254
+ const countsCookieless = () => Boolean(config.projectToken) && withoutConsent !== "off" && fillsCountingSlot;
216
255
  return {
217
256
  id: "posthog",
218
257
  ...adapterLabel(config.label, "PostHog", "posthog({ label })"),
219
258
  capabilities,
220
- ...config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {},
259
+ ...config.projectToken ? { capture: {
260
+ ...buildCapture(config, config.projectToken),
261
+ ...cookielessCapture({ kind: "switched" }, withoutConsent)
262
+ } } : {},
221
263
  isConfigured: () => Boolean(config.projectId && config.apiKey),
264
+ register(_config, context) {
265
+ fillsCountingSlot = context?.adapterCountsWithoutConsent !== false;
266
+ },
222
267
  async query(q, ctx) {
223
268
  const fetchedAt = readTime(ctx);
269
+ const dropped = countsCookieless() ? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime()) : Promise.resolve(void 0);
224
270
  const breakdown = firstMapped(q.dimensions, DIMENSION_SQL);
225
271
  const goalBreakdown = breakdown?.dimension === "goal";
226
272
  const hint = goalHint(q);
273
+ let cookieless = 0;
274
+ /** The result with what the read learnt about events counted without consent. */
275
+ const withConsentMeta = async (result) => {
276
+ const drops = await dropped;
277
+ const counted = cookieless > 0;
278
+ return {
279
+ ...result,
280
+ meta: {
281
+ ...result.meta,
282
+ ...counted && q.metrics.includes("visitors") ? { visitorsAre: "sumOfDaily" } : {},
283
+ ...counted && !breakdown && q.metrics.includes("pageviews") ? { withoutConsent: { pageviews: cookieless } } : {},
284
+ ...drops ? { withoutConsentDropped: true } : {}
285
+ }
286
+ };
287
+ };
227
288
  const empty = goalBreakdown ? emptyGoalBreakdown({
228
289
  provider: "posthog",
229
290
  fetchedAt,
230
291
  hint
231
292
  }) : null;
232
- if (empty) return empty;
293
+ if (empty) return withConsentMeta(empty);
233
294
  const scanAllEvents = q.metrics.includes("events") || q.metrics.includes("conversions") || breakdown?.dimension === "event" || goalBreakdown || (q.filters ?? []).some((f) => f.dimension === "event");
234
295
  const slugs = hintSlugs(hint);
235
296
  const eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(", ")})` : void 0;
@@ -255,6 +316,13 @@ function posthog(config) {
255
316
  for (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) where.push(FILTER_SQL[filter.operator](field, filter.value));
256
317
  const columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(", ");
257
318
  const from = `FROM events WHERE ${where.join(" AND ")}`;
319
+ const cookielessRows = scanAllEvents && !goalBreakdown ? `event = '$pageview' AND ${COOKIELESS_EVENT}` : COOKIELESS_EVENT;
320
+ const countsCookielessColumn = q.metrics.includes("visitors") || !breakdown && q.metrics.includes("pageviews");
321
+ const cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : "";
322
+ /** Adds a result row's count of events counted without consent, after its metric columns. */
323
+ const tallyCookieless = (row, offset) => {
324
+ if (countsCookielessColumn) cookieless += vendorReading("pageviews", row[offset + exprs.length]) ?? 0;
325
+ };
258
326
  const runSql = (sql) => upstreamJson(ctx, `${host}/api/projects/${config.projectId}/query/`, {
259
327
  method: "POST",
260
328
  headers: { authorization: `Bearer ${config.apiKey}` },
@@ -275,8 +343,10 @@ function posthog(config) {
275
343
  return out;
276
344
  };
277
345
  const fetchTotals = async () => {
278
- const row = (await runSql(`SELECT ${columns} ${from}`)).results[0];
279
- return row ? readRow(row, 0) : {};
346
+ const row = (await runSql(`SELECT ${columns}${cookielessColumn} ${from}`)).results[0];
347
+ if (!row) return {};
348
+ tallyCookieless(row, 0);
349
+ return readRow(row, 0);
280
350
  };
281
351
  const unit = !breakdown && (q.granularity === "day" || q.granularity === "hour") ? q.granularity : void 0;
282
352
  if (unit) {
@@ -291,26 +361,29 @@ function posthog(config) {
291
361
  metrics: readRow(row, 1)
292
362
  });
293
363
  }
294
- return {
364
+ return withConsentMeta({
295
365
  rows,
296
366
  totals,
297
367
  meta
298
- };
368
+ });
299
369
  }
300
- if (breakdown) return {
301
- rows: (await runSql(`SELECT ${breakdown.field} AS dim, ${columns} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`)).results.map((row) => ({
302
- dimensions: { [breakdown.dimension]: String(row[0] ?? "") },
303
- metrics: readRow(row, 1)
304
- })),
370
+ if (breakdown) return withConsentMeta({
371
+ rows: (await runSql(`SELECT ${breakdown.field} AS dim, ${columns}${cookielessColumn} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`)).results.map((row) => {
372
+ tallyCookieless(row, 1);
373
+ return {
374
+ dimensions: { [breakdown.dimension]: String(row[0] ?? "") },
375
+ metrics: readRow(row, 1)
376
+ };
377
+ }),
305
378
  totals: void 0,
306
379
  meta
307
- };
380
+ });
308
381
  const totals = await fetchTotals();
309
- return {
382
+ return withConsentMeta({
310
383
  rows: [{ metrics: totals }],
311
384
  totals,
312
385
  meta
313
- };
386
+ });
314
387
  }
315
388
  };
316
389
  }
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport, ProxyRoute } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface PosthogConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.\n\t */\n\tlabel?: AdapterLabelOption\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/**\n\t * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A\n\t * self-hosted `host` takes capture itself and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\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 stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so\n * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded\n * posthog-js (no longer an array) is never replaced, so the client is initialised on it.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? `https://${region}.posthog.com`,\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview to the primary client.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first\n * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to\n * its own pageviews, is asked for outright.\n */\nconst NAMED_CLIENT_PAGEVIEWS = ['capture_pageview:false', 'capture_pageleave:true']\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined, named: boolean): string =>\n\t[\n\t\t`api_host:${jsLiteral(path)}`,\n\t\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t\t'opt_out_persistence_by_default:true',\n\t].join(',')\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope, instance }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\t// A super-property rather than a per-call one, so it rides the events a host\n\t\t\t// captures itself, which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tconfig.scopeProperty && scope\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst name = named ? `,${jsLiteral(instance)}` : ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui, named)}}${name})${stamp}`,\n\t\t\t\t\t},\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, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by 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, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview 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\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\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/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\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 reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** The HogQL function that buckets a timestamp. */\n\tfn: string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { fn: 'toStartOfDay', isoOf: dayIso },\n\thour: { fn: 'toStartOfHour', isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\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 = withoutTrailingSlash(config.host ?? US_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\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\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\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 = readTime(ctx)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional 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\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\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...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\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...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\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\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 (goalBreakdown && 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\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${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\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns} ${from}`)\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\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { fn, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? DEFAULT_TIMEZONE)})`\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\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 series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, 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 (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdown.dimension]: 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":";;;;;;;;;;;AAyEA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;AASA,MAAM,eACL;;AAGD,MAAM,eAAe,YAA6B;CACjD,MAAM,WAAW,WAAW,OAAO;CACnC,OAAO,aAAa,iBAAiB,SAAS,SAAS,cAAc;AACtE;;;;;AAaA,MAAM,gBAAgB,WAAwC;CAC7D,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,IAAI;CACrF,MAAM,KAAK,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,MAAM;CACvF,IAAI,SAAS,KAAA,KAAa,CAAC,YAAY,IAAI,GAC1C,OAAO;EAAE,QAAQ;EAAM,QAAQ;EAAM,OAAO;EAAO,GAAI,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,GAAG;CAAG;CAExF,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,QAAQ,WAAW,OAAO;EAC1B,QAA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G,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;KAC1D,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"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, ProxyRoute, SnippetMode } from '../../core/capture'\nimport { currentTime } from '../../core/clock'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { createProjectCheck } from './projectCheck'\n\nexport interface PosthogConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.\n\t */\n\tlabel?: AdapterLabelOption\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/**\n\t * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A\n\t * self-hosted `host` takes capture itself and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's\n\t * \"Cookieless tracking\" (Web analytics settings); `'off'` keeps PostHog opted out until then.\n\t */\n\twithoutConsent?: WithoutConsentLevel\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 stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so\n * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded\n * posthog-js (no longer an array) is never replaced, so the client is initialised on it.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? `https://${region}.posthog.com`,\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview to the primary client.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first\n * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to\n * its own pageviews, is asked for outright.\n */\nconst NAMED_CLIENT_PAGEVIEWS = ['capture_pageview:false', 'capture_pageleave:true']\n\n/**\n * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to\n * rather than stopping. Started cookieless, it counts from the first pageview while opted out by\n * default, storing nothing, until the sink opts it in.\n */\nconst cookielessOptions = (mode: SnippetMode): string[] => [\n\t`cookieless_mode:${jsLiteral('on_reject')}`,\n\t...(mode === 'cookieless' ? ['opt_out_capturing_by_default:true'] : []),\n]\n\n/**\n * The scope stamped on each event as it is sent: switching between cookieless and full resets\n * PostHog's identity and every super-property `register` set with it.\n */\nconst scopeHook = (property: string, scope: string): string =>\n\t`before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined, named: boolean): string[] => [\n\t`api_host:${jsLiteral(path)}`,\n\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t'opt_out_persistence_by_default:true',\n]\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope, instance, mode = 'full', withoutConsent = false }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\tconst property = config.scopeProperty && scope ? config.scopeProperty : undefined\n\t\t\t// Stamped on every event rather than per call, so it rides the events a host captures itself,\n\t\t\t// which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tproperty && scope && !withoutConsent\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst options = [\n\t\t\t\t...initOptions(path, hosts.ui, named),\n\t\t\t\t...(withoutConsent ? cookielessOptions(mode) : []),\n\t\t\t\t...(withoutConsent && property && scope ? [scopeHook(property, scope)] : []),\n\t\t\t].join(',')\n\t\t\tconst name = named ? `,${jsLiteral(instance)}` : ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${options}}${name})${stamp}`,\n\t\t\t\t\t},\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, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by 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, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview 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\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\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/**\n * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;\n * compared as text, it matches whether the project types the property as a boolean or not.\n */\nconst COOKIELESS_EVENT = \"toString(properties.$cookieless_mode) = 'true'\"\n\n/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\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 reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** The HogQL function that buckets a timestamp. */\n\tfn: string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { fn: 'toStartOfDay', isoOf: dayIso },\n\thour: { fn: 'toStartOfHour', isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\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 = withoutTrailingSlash(config.host ?? US_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'posthog({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\n\n\tconst capabilities: AnalyticsCapabilities = {\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\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\tlet fillsCountingSlot = true\n\tconst projectDropsCookieless = createProjectCheck({\n\t\thost,\n\t\tprojectId: config.projectId,\n\t\tapiKey: config.apiKey,\n\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t})\n\t/**\n\t * Whether a held slot this source fills may count cookielessly, which the project must accept:\n\t * the boot's answer for a config source, the factory's `withoutConsent` for a document's.\n\t */\n\tconst countsCookieless = (): boolean =>\n\t\tBoolean(config.projectToken) && withoutConsent !== 'off' && fillsCountingSlot\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(config, config.projectToken),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tregister(_config, context) {\n\t\t\tfillsCountingSlot = context?.adapterCountsWithoutConsent !== false\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dropped = countsCookieless()\n\t\t\t\t? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime())\n\t\t\t\t: Promise.resolve(undefined)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tlet cookieless = 0\n\t\t\t/** The result with what the read learnt about events counted without consent. */\n\t\t\tconst withConsentMeta = async (result: AnalyticsResult): Promise<AnalyticsResult> => {\n\t\t\t\tconst drops = await dropped\n\t\t\t\tconst counted = cookieless > 0\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\t...result.meta,\n\t\t\t\t\t\t...(counted && q.metrics.includes('visitors') ? { visitorsAre: 'sumOfDaily' } : {}),\n\t\t\t\t\t\t...(counted && !breakdown && q.metrics.includes('pageviews')\n\t\t\t\t\t\t\t? { withoutConsent: { pageviews: cookieless } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(drops ? { withoutConsentDropped: true } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn withConsentMeta(empty)\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional 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\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\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...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\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...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\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\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 (goalBreakdown && 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\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\t\t\t// A column on the totals or breakdown query the read runs anyway, never a request of its\n\t\t\t// own. Visitors are counted on pageviews, except in a goal breakdown, which counts its rows.\n\t\t\tconst cookielessRows =\n\t\t\t\tscanAllEvents && !goalBreakdown\n\t\t\t\t\t? `event = '$pageview' AND ${COOKIELESS_EVENT}`\n\t\t\t\t\t: COOKIELESS_EVENT\n\t\t\tconst countsCookielessColumn =\n\t\t\t\tq.metrics.includes('visitors') || (!breakdown && q.metrics.includes('pageviews'))\n\t\t\tconst cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : ''\n\t\t\t/** Adds a result row's count of events counted without consent, after its metric columns. */\n\t\t\tconst tallyCookieless = (row: unknown[], offset: number): void => {\n\t\t\t\tif (countsCookielessColumn) {\n\t\t\t\t\tcookieless += vendorReading('pageviews', row[offset + exprs.length]) ?? 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${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\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns}${cookielessColumn} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn {}\n\t\t\t\t}\n\t\t\t\ttallyCookieless(row, 0)\n\t\t\t\treturn readRow(row, 0)\n\t\t\t}\n\n\t\t\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { fn, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? DEFAULT_TIMEZONE)})`\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\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 series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn withConsentMeta({ rows, totals, meta })\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns}${cookielessColumn} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\t\ttallyCookieless(row, 1)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn withConsentMeta({ rows, totals: undefined, meta })\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn withConsentMeta({ rows: [{ metrics: totals }], totals, meta })\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAuFA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;AASA,MAAM,eACL;;AAGD,MAAM,eAAe,YAA6B;CACjD,MAAM,WAAW,WAAW,OAAO;CACnC,OAAO,aAAa,iBAAiB,SAAS,SAAS,cAAc;AACtE;;;;;AAaA,MAAM,gBAAgB,WAAwC;CAC7D,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,IAAI;CACrF,MAAM,KAAK,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,MAAM;CACvF,IAAI,SAAS,KAAA,KA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AEA,MAAM,OACL,CAAC,cAAc,EAAE,gBAAgB,SAAS,EAAE,gBAAgB,UACzD,EAAE,cACF,KAAA;GACJ,IAAI,MAAM;IACT,MAAM,EAAE,IAAI,UAAU,eAAe;IAGrC,MAAM,SAAS,GAAG,GAAG,cAAc,UAAU,EAAE,YAAA,KAA4B,EAAE;IAC7E,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,OACC,UAAU,OAAO,MAAM,KAAK,IAAI,QAAQ,GAAG,KAAK,YAAY,KAAK,YAAY,MAC9E,GACA,YAAY,CACb,CAAC;IACD,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,OAAO,SAAS;KACjC,MAAM,YAAY,MAAM,OAAO,IAAI,MAAM,EAAE,CAAC;KAC5C,IAAI,WACH,KAAK,KAAK;MAAE;MAAW,SAAS,QAAQ,KAAK,CAAC;KAAE,CAAC;IAEnD;IACA,OAAO,gBAAgB;KAAE;KAAM;KAAQ;IAAK,CAAC;GAC9C;GAEA,IAAI,WAWH,OAAO,gBAAgB;IAAE,OAPI,MAHV,OAClB,UAAU,UAAU,MAAM,WAAW,UAAU,iBAAiB,GAAG,KAAK,uCAAuC,EAAE,SAAS,KAC3H,GACkC,QAAQ,KAAK,QAAQ;KACtD,gBAAgB,KAAK,CAAC;KACtB,OAAO;MACN,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;MAC1D,SAAS,QAAQ,KAAK,CAAC;KACxB;IACD,CAC4B;IAAG,QAAQ,KAAA;IAAW;GAAK,CAAC;GAGzD,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO,gBAAgB;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK,CAAC;EACrE;CACD;AACD"}
@@ -0,0 +1,56 @@
1
+ import { isRecord } from "../../core/values.js";
2
+ import { fetchJson } from "../http/fetchJson.js";
3
+ //#region src/adapters/posthog/projectCheck.ts
4
+ /** How long one answer about the project's setting is trusted. */
5
+ const PROJECT_CHECK_TTL_MS = 3600 * 1e3;
6
+ /** How long a failed check waits before the next read asks again. */
7
+ const PROJECT_CHECK_RETRY_MS = 300 * 1e3;
8
+ /** A slow settings endpoint holds up the read that asked, so it gets little time. */
9
+ const PROJECT_CHECK_TIMEOUT_MS = 5e3;
10
+ /**
11
+ * PostHog's `cookieless_server_hash_mode` (0 or null off, 1 and 2 on) as whether events are
12
+ * dropped; anything else, such as an instance too old to have the field, is unknown.
13
+ */
14
+ const dropsCookieless = (project) => {
15
+ if (!isRecord(project)) return;
16
+ const mode = project.cookieless_server_hash_mode;
17
+ if (mode === null || mode === 0) return true;
18
+ return typeof mode === "number" ? false : void 0;
19
+ };
20
+ /**
21
+ * Answers by host and project, shared by every adapter reading the project: `providers.resolve`
22
+ * builds a new adapter per read, which would otherwise ask again each time.
23
+ */
24
+ const checks = /* @__PURE__ */ new Map();
25
+ /**
26
+ * Reads the project's settings (`GET /api/projects/:id/`) with the personal API key, memoized per
27
+ * host and project: one request an hour at most, and a failure is remembered for a few minutes
28
+ * rather than thrown.
29
+ */
30
+ const createProjectCheck = (options) => {
31
+ const key = `${options.host}\n${options.projectId}`;
32
+ return (now) => {
33
+ const memo = checks.get(key);
34
+ if (memo && now - memo.at < memo.ttl) return memo.answer;
35
+ const entry = {
36
+ at: now,
37
+ ttl: PROJECT_CHECK_TTL_MS,
38
+ answer: Promise.resolve(void 0)
39
+ };
40
+ entry.answer = fetchJson(`${options.host}/api/projects/${encodeURIComponent(options.projectId)}/`, {
41
+ method: "GET",
42
+ headers: { authorization: `Bearer ${options.apiKey}` },
43
+ provider: "posthog",
44
+ signal: AbortSignal.timeout(PROJECT_CHECK_TIMEOUT_MS),
45
+ ...options.fetch ? { fetch: options.fetch } : {}
46
+ }).then(dropsCookieless, () => {
47
+ entry.ttl = PROJECT_CHECK_RETRY_MS;
48
+ });
49
+ checks.set(key, entry);
50
+ return entry.answer;
51
+ };
52
+ };
53
+ //#endregion
54
+ export { createProjectCheck };
55
+
56
+ //# sourceMappingURL=projectCheck.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projectCheck.js","names":[],"sources":["../../../src/adapters/posthog/projectCheck.ts"],"sourcesContent":["import type { FetchLike } from '../../core/fetch'\nimport { isRecord } from '../../core/values'\nimport { fetchJson } from '../http/fetchJson'\n\n/** How long one answer about the project's setting is trusted. */\nexport const PROJECT_CHECK_TTL_MS = 60 * 60 * 1000\n\n/** How long a failed check waits before the next read asks again. */\nexport const PROJECT_CHECK_RETRY_MS = 5 * 60 * 1000\n\n/** A slow settings endpoint holds up the read that asked, so it gets little time. */\nconst PROJECT_CHECK_TIMEOUT_MS = 5_000\n\nexport interface ProjectCheckOptions {\n\thost: string\n\tprojectId: string\n\tapiKey: string\n\tfetch?: FetchLike\n}\n\n/**\n * Whether the project drops events counted without consent: true when its cookieless tracking\n * setting is off, undefined when that could not be read (a key without `project:read`, an outage).\n */\nexport type ProjectCheck = (now: number) => Promise<boolean | undefined>\n\n/**\n * PostHog's `cookieless_server_hash_mode` (0 or null off, 1 and 2 on) as whether events are\n * dropped; anything else, such as an instance too old to have the field, is unknown.\n */\nconst dropsCookieless = (project: unknown): boolean | undefined => {\n\tif (!isRecord(project)) {\n\t\treturn undefined\n\t}\n\tconst mode = project.cookieless_server_hash_mode\n\tif (mode === null || mode === 0) {\n\t\treturn true\n\t}\n\treturn typeof mode === 'number' ? false : undefined\n}\n\ninterface ProjectCheckEntry {\n\tat: number\n\tttl: number\n\tanswer: Promise<boolean | undefined>\n}\n\n/**\n * Answers by host and project, shared by every adapter reading the project: `providers.resolve`\n * builds a new adapter per read, which would otherwise ask again each time.\n */\nconst checks = new Map<string, ProjectCheckEntry>()\n\n/** Forgets every remembered answer, for tests that reuse one project. */\nexport const forgetProjectChecks = (): void => {\n\tchecks.clear()\n}\n\n/**\n * Reads the project's settings (`GET /api/projects/:id/`) with the personal API key, memoized per\n * host and project: one request an hour at most, and a failure is remembered for a few minutes\n * rather than thrown.\n */\nexport const createProjectCheck = (options: ProjectCheckOptions): ProjectCheck => {\n\tconst key = `${options.host}\\n${options.projectId}`\n\treturn (now) => {\n\t\tconst memo = checks.get(key)\n\t\tif (memo && now - memo.at < memo.ttl) {\n\t\t\treturn memo.answer\n\t\t}\n\t\tconst entry: ProjectCheckEntry = {\n\t\t\tat: now,\n\t\t\tttl: PROJECT_CHECK_TTL_MS,\n\t\t\tanswer: Promise.resolve<boolean | undefined>(undefined),\n\t\t}\n\t\t// Not the read's own signal: one aborted read would otherwise hush the check for everyone.\n\t\tentry.answer = fetchJson<unknown>(\n\t\t\t`${options.host}/api/projects/${encodeURIComponent(options.projectId)}/`,\n\t\t\t{\n\t\t\t\tmethod: 'GET',\n\t\t\t\theaders: { authorization: `Bearer ${options.apiKey}` },\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tsignal: AbortSignal.timeout(PROJECT_CHECK_TIMEOUT_MS),\n\t\t\t\t...(options.fetch ? { fetch: options.fetch } : {}),\n\t\t\t}\n\t\t).then(dropsCookieless, () => {\n\t\t\tentry.ttl = PROJECT_CHECK_RETRY_MS\n\t\t\treturn undefined\n\t\t})\n\t\tchecks.set(key, entry)\n\t\treturn entry.answer\n\t}\n}\n"],"mappings":";;;;AAKA,MAAa,uBAAuB,OAAU;;AAG9C,MAAa,yBAAyB,MAAS;;AAG/C,MAAM,2BAA2B;;;;;AAmBjC,MAAM,mBAAmB,YAA0C;CAClE,IAAI,CAAC,SAAS,OAAO,GACpB;CAED,MAAM,OAAO,QAAQ;CACrB,IAAI,SAAS,QAAQ,SAAS,GAC7B,OAAO;CAER,OAAO,OAAO,SAAS,WAAW,QAAQ,KAAA;AAC3C;;;;;AAYA,MAAM,yBAAS,IAAI,IAA+B;;;;;;AAYlD,MAAa,sBAAsB,YAA+C;CACjF,MAAM,MAAM,GAAG,QAAQ,KAAK,IAAI,QAAQ;CACxC,QAAQ,QAAQ;EACf,MAAM,OAAO,OAAO,IAAI,GAAG;EAC3B,IAAI,QAAQ,MAAM,KAAK,KAAK,KAAK,KAChC,OAAO,KAAK;EAEb,MAAM,QAA2B;GAChC,IAAI;GACJ,KAAK;GACL,QAAQ,QAAQ,QAA6B,KAAA,CAAS;EACvD;EAEA,MAAM,SAAS,UACd,GAAG,QAAQ,KAAK,gBAAgB,mBAAmB,QAAQ,SAAS,EAAE,IACtE;GACC,QAAQ;GACR,SAAS,EAAE,eAAe,UAAU,QAAQ,SAAS;GACrD,UAAU;GACV,QAAQ,YAAY,QAAQ,wBAAwB;GACpD,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;EACjD,CACD,EAAE,KAAK,uBAAuB;GAC7B,MAAM,MAAM;EAEb,CAAC;EACD,OAAO,IAAI,KAAK,KAAK;EACrB,OAAO,MAAM;CACd;AACD"}
@@ -1,3 +1,4 @@
1
+ import { WithoutConsentLevel } from "../../tracker/config.js";
1
2
  import { FetchLike } from "../../core/fetch.js";
2
3
  import { AnalyticsAdapter } from "../../core/contract.js";
3
4
  import { AdapterLabelOption } from "../../core/sourceLabel.js";
@@ -23,6 +24,11 @@ interface UmamiConfig {
23
24
  maxLookbackDays?: number | null;
24
25
  /** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */
25
26
  fetch?: FetchLike;
27
+ /**
28
+ * What this source's held slot does without consent, over `capture.withoutConsent`. Umami stores
29
+ * nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.
30
+ */
31
+ withoutConsent?: WithoutConsentLevel;
26
32
  }
27
33
  /**
28
34
  * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,
@@ -1,5 +1,6 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
2
  import { adapterLabel } from "../../core/sourceLabel.js";
3
+ import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
3
4
  import { filterableDimensions } from "../../core/capabilities.js";
4
5
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
5
6
  import { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from "../mapping.js";
@@ -50,7 +51,8 @@ function buildCapture(config, endpoints) {
50
51
  "data-host-url": path
51
52
  }
52
53
  }] }),
53
- client: { kind: "umami" }
54
+ client: { kind: "umami" },
55
+ ...cookielessCapture({ kind: "inherent" }, adapterWithoutConsent(config.withoutConsent, "umami({ withoutConsent })", WITHOUT_CONSENT_LEVELS))
54
56
  };
55
57
  }
56
58
  const umamiMetrics = new Set([
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.\n\t */\n\tlabel?: AdapterLabelOption\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\t...adapterLabel(config.label, 'Umami', 'umami({ label })'),\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\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\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAwDA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBAAuC,IAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;;;;;AAMvF,MAAa,kBAAkB,SAA6C;CAE3E,MAAM,UAAU,qBADA,qBAAqB,MAAM,KAAK,KAAK,EACV,EAAE,QAAQ,UAAU,EAAE,CAAC;CAClE,IAAI,YAAY,MAAM,gBAAgB,IAAI,WAAW,OAAO,CAAC,GAC5D,OAAO;CAER,OAAO;EAAE,KAAK,GAAG,QAAQ;EAAO,QAAQ,GAAG,QAAQ;EAAa,MAAM,GAAG,QAAQ;CAAW;AAC7F;AAEA,SAAS,aAAa,QAAqB,WAA2C;CACrF,OAAO;EACN,OAAO;GACN,QAAQ,CACP;IAAE,QAAQ;IAAc,UAAU,UAAU;IAAQ,MAAM;GAAS,GACnE;IAAE,QAAQ;IAAa,UAAU,UAAU;IAAM,MAAM;GAAO,CAC/D;GACA,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC/C;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,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,GAAI,WAAW,EAAE,aAAa,SAAS,QAAQ,KAAK,QAAQ,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,CAAC;KACjF,WAAW,MAAM;KACjB,UAAU,MAAM;KAChB,QAAQ,MAAM;KACd,UAAU,MAAM;KAGhB,YAAY,MAAM,SAAS,IAAI,KAAK,MAAO,MAAM,UAAU,MAAM,SAAU,GAAG,IAAI;KAClF,eACC,MAAM,SAAS,IAAI,KAAK,MAAO,MAAM,YAAY,MAAM,SAAU,GAAI,IAAI;IAC3E,CAAC;GACF;GAIA,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,QACC,aACA,OAAO;KAAE,MAAM;KAAO,UAAU,EAAE,YAAA;IAA6B,CAAC,CACjE,GACA,YAAY,CACb,CAAC;IACD,MAAM,gBAAgB,IAAI,IAAI,OAAO,SAAS,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,SAAS,OAAO,WAAW;KACrC,MAAM,YAAY,OAAO,MAAM,CAAC;KAChC,IAAI,CAAC,WACJ;KAED,MAAM,WAAW,cAAc,IAAI,MAAM,CAAC,KAAK;KAC/C,KAAK,KAAK;MACT;MACA,SAAS,UAAU,EAAE,SAAS;OAAE,WAAW,MAAM;OAAG,QAAQ;OAAU;MAAS,CAAC;KACjF,CAAC;IACF;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
1
+ {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.\n\t */\n\tlabel?: AdapterLabelOption\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Umami stores\n\t * nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t\t...cookielessCapture(\n\t\t\t{ kind: 'inherent' },\n\t\t\tadapterWithoutConsent(\n\t\t\t\tconfig.withoutConsent,\n\t\t\t\t'umami({ withoutConsent })',\n\t\t\t\tWITHOUT_CONSENT_LEVELS\n\t\t\t)\n\t\t),\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\t...adapterLabel(config.label, 'Umami', 'umami({ label })'),\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\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\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAmEA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBAAuC,IAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;;;;;AAMvF,MAAa,kBAAkB,SAA6C;CAE3E,MAAM,UAAU,qBADA,qBAAqB,MAAM,KAAK,KAAK,EACV,EAAE,QAAQ,UAAU,EAAE,CAAC;CAClE,IAAI,YAAY,MAAM,gBAAgB,IAAI,WAAW,OAAO,CAAC,GAC5D,OAAO;CAER,OAAO;EAAE,KAAK,GAAG,QAAQ;EAAO,QAAQ,GAAG,QAAQ;EAAa,MAAM,GAAG,QAAQ;CAAW;AAC7F;AAEA,SAAS,aAAa,QAAqB,WAA2C;CACrF,OAAO;EACN,OAAO;GACN,QAAQ,CACP;IAAE,QAAQ;IAAc,UAAU,UAAU;IAAQ,MAAM;GAAS,GACnE;IAAE,QAAQ;IAAa,UAAU,UAAU;IAAM,MAAM;GAAO,CAC/D;GACA,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC/C;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,mBAAmB,OAAO;IAAW,iBAAiB;GAAK;EACrE,CACD,EACD;EACA,QAAQ,EAAE,M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