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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +21 -21
  3. package/README.md +10 -4
  4. package/dist/adapters/ga4/eventName.d.ts +15 -0
  5. package/dist/adapters/ga4/eventName.js +19 -0
  6. package/dist/adapters/ga4/eventName.js.map +1 -0
  7. package/dist/adapters/ga4/ga4.d.ts +5 -0
  8. package/dist/adapters/ga4/ga4.js +179 -70
  9. package/dist/adapters/ga4/ga4.js.map +1 -1
  10. package/dist/adapters/ga4/measurementId.js +15 -0
  11. package/dist/adapters/ga4/measurementId.js.map +1 -0
  12. package/dist/adapters/goalRead.js +126 -0
  13. package/dist/adapters/goalRead.js.map +1 -0
  14. package/dist/adapters/plausible/plausible.d.ts +15 -0
  15. package/dist/adapters/plausible/plausible.js +112 -43
  16. package/dist/adapters/plausible/plausible.js.map +1 -1
  17. package/dist/adapters/posthog/posthog.js +47 -25
  18. package/dist/adapters/posthog/posthog.js.map +1 -1
  19. package/dist/adapters/umami/umami.d.ts +8 -0
  20. package/dist/adapters/umami/umami.js +237 -28
  21. package/dist/adapters/umami/umami.js.map +1 -1
  22. package/dist/capture/slots.js +16 -5
  23. package/dist/capture/slots.js.map +1 -1
  24. package/dist/capture/trackerConfig.d.ts +1 -0
  25. package/dist/capture/trackerConfig.js +28 -3
  26. package/dist/capture/trackerConfig.js.map +1 -1
  27. package/dist/charts/BarList.d.ts +15 -1
  28. package/dist/charts/BarList.js +41 -19
  29. package/dist/charts/BarList.js.map +1 -1
  30. package/dist/charts/TrendChart.d.ts +16 -3
  31. package/dist/charts/TrendChart.js +172 -106
  32. package/dist/charts/TrendChart.js.map +1 -1
  33. package/dist/charts/bars.d.ts +2 -0
  34. package/dist/charts/bars.js +2 -1
  35. package/dist/charts/bars.js.map +1 -1
  36. package/dist/charts/bucket.js +10 -1
  37. package/dist/charts/bucket.js.map +1 -1
  38. package/dist/charts/spline.js +2 -2
  39. package/dist/charts/spline.js.map +1 -1
  40. package/dist/charts/styles.js +18 -1
  41. package/dist/charts/styles.js.map +1 -1
  42. package/dist/core/cacheKey.js +24 -2
  43. package/dist/core/cacheKey.js.map +1 -1
  44. package/dist/core/capabilities.js +7 -2
  45. package/dist/core/capabilities.js.map +1 -1
  46. package/dist/core/capture.d.ts +1 -1
  47. package/dist/core/contract.d.ts +46 -9
  48. package/dist/core/contract.js +29 -1
  49. package/dist/core/contract.js.map +1 -1
  50. package/dist/core/granularity.js +1 -1
  51. package/dist/core/options.d.ts +62 -7
  52. package/dist/core/options.js +63 -4
  53. package/dist/core/options.js.map +1 -1
  54. package/dist/core/scopedRead.js +33 -23
  55. package/dist/core/scopedRead.js.map +1 -1
  56. package/dist/core/serverEvent.d.ts +44 -0
  57. package/dist/core/serverEvent.js +12 -0
  58. package/dist/core/serverEvent.js.map +1 -0
  59. package/dist/exports/adapters/ga4.d.ts +2 -1
  60. package/dist/exports/adapters/ga4.js +2 -1
  61. package/dist/exports/client.d.ts +12 -3
  62. package/dist/exports/client.js +9 -1
  63. package/dist/exports/rsc.d.ts +7 -2
  64. package/dist/exports/rsc.js +6 -3
  65. package/dist/exports/tracker.d.ts +3 -2
  66. package/dist/exports/tracker.js +2 -1
  67. package/dist/exports/types.d.ts +13 -4
  68. package/dist/exports/types.js +3 -2
  69. package/dist/fields/AnalyticsPanelClient.js +1 -1
  70. package/dist/fields/AnalyticsPanelField.js +1 -1
  71. package/dist/fields/AnalyticsStatField.js +2 -2
  72. package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
  73. package/dist/fields/config/FilterDimensionSelectField.js +77 -0
  74. package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
  75. package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
  76. package/dist/fields/config/FilterOperatorSelectField.js +75 -0
  77. package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
  78. package/dist/fields/config/MetricSelectField.js +3 -3
  79. package/dist/fields/config/MetricSelectField.js.map +1 -1
  80. package/dist/fields/config/SourceSelectField.js +3 -3
  81. package/dist/fields/config/SourceSelectField.js.map +1 -1
  82. package/dist/fields/config/fetchSources.d.ts +5 -1
  83. package/dist/fields/config/sourcesState.js +19 -3
  84. package/dist/fields/config/sourcesState.js.map +1 -1
  85. package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
  86. package/dist/fields/config/useAnalyticsSources.js +9 -6
  87. package/dist/fields/config/useAnalyticsSources.js.map +1 -1
  88. package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
  89. package/dist/fields/config/useFilterCapabilities.js +52 -0
  90. package/dist/fields/config/useFilterCapabilities.js.map +1 -0
  91. package/dist/fields/readForDocument.d.ts +5 -0
  92. package/dist/fields/readForDocument.js +21 -9
  93. package/dist/fields/readForDocument.js.map +1 -1
  94. package/dist/goals/GoalSelectField.d.ts +7 -0
  95. package/dist/goals/GoalSelectField.js +77 -0
  96. package/dist/goals/GoalSelectField.js.map +1 -0
  97. package/dist/goals/collection.js +250 -0
  98. package/dist/goals/collection.js.map +1 -0
  99. package/dist/goals/currency.js +14 -0
  100. package/dist/goals/currency.js.map +1 -0
  101. package/dist/goals/fetchGoals.d.ts +18 -0
  102. package/dist/goals/fetchGoals.js +29 -0
  103. package/dist/goals/fetchGoals.js.map +1 -0
  104. package/dist/goals/goalField.d.ts +31 -0
  105. package/dist/goals/goalField.js +56 -0
  106. package/dist/goals/goalField.js.map +1 -0
  107. package/dist/goals/goalsEndpoint.d.ts +1 -0
  108. package/dist/goals/goalsEndpoint.js +55 -0
  109. package/dist/goals/goalsEndpoint.js.map +1 -0
  110. package/dist/goals/resolver.d.ts +8 -0
  111. package/dist/goals/resolver.js +147 -0
  112. package/dist/goals/resolver.js.map +1 -0
  113. package/dist/goals/trackGoalAction.d.ts +74 -0
  114. package/dist/goals/trackGoalAction.js +139 -0
  115. package/dist/goals/trackGoalAction.js.map +1 -0
  116. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  117. package/dist/goals/useAnalyticsGoals.js +67 -0
  118. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  119. package/dist/index.d.ts +12 -3
  120. package/dist/index.js +75 -11
  121. package/dist/index.js.map +1 -1
  122. package/dist/native/collections/events.js +36 -0
  123. package/dist/native/collections/events.js.map +1 -1
  124. package/dist/native/eventScan.js +25 -0
  125. package/dist/native/eventScan.js.map +1 -0
  126. package/dist/native/ingest/browser.js +47 -0
  127. package/dist/native/ingest/browser.js.map +1 -0
  128. package/dist/native/ingest/device.js +11 -3
  129. package/dist/native/ingest/device.js.map +1 -1
  130. package/dist/native/ingest/endpoint.d.ts +1 -0
  131. package/dist/native/ingest/endpoint.js +2 -17
  132. package/dist/native/ingest/endpoint.js.map +1 -1
  133. package/dist/native/ingest/flushBatch.js +26 -26
  134. package/dist/native/ingest/flushBatch.js.map +1 -1
  135. package/dist/native/ingest/language.js +14 -0
  136. package/dist/native/ingest/language.js.map +1 -0
  137. package/dist/native/ingest/normalizeEvent.d.ts +26 -0
  138. package/dist/native/ingest/normalizeEvent.js +35 -7
  139. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  140. package/dist/native/ingest/referrer.js +48 -0
  141. package/dist/native/ingest/referrer.js.map +1 -0
  142. package/dist/native/ingest/serverTrack.d.ts +20 -0
  143. package/dist/native/ingest/serverTrack.js +100 -0
  144. package/dist/native/ingest/serverTrack.js.map +1 -0
  145. package/dist/native/ingest/source.d.ts +7 -0
  146. package/dist/native/ingest/source.js +139 -14
  147. package/dist/native/ingest/source.js.map +1 -1
  148. package/dist/native/ingest/utm.js +33 -0
  149. package/dist/native/ingest/utm.js.map +1 -0
  150. package/dist/native/ingest/validate.js +27 -0
  151. package/dist/native/ingest/validate.js.map +1 -0
  152. package/dist/native/nativeAdapter.d.ts +1 -1
  153. package/dist/native/nativeAdapter.js +53 -36
  154. package/dist/native/nativeAdapter.js.map +1 -1
  155. package/dist/native/query/eventAgg.js +14 -1
  156. package/dist/native/query/eventAgg.js.map +1 -1
  157. package/dist/native/retention/pruneTask.js +1 -1
  158. package/dist/native/rollups/bucketKey.js +15 -0
  159. package/dist/native/rollups/bucketKey.js.map +1 -0
  160. package/dist/native/rollups/bumpRollups.js +116 -0
  161. package/dist/native/rollups/bumpRollups.js.map +1 -0
  162. package/dist/native/rollups/deltas.js +30 -15
  163. package/dist/native/rollups/deltas.js.map +1 -1
  164. package/dist/native/rollups/insertManyIfNew.js +93 -0
  165. package/dist/native/rollups/insertManyIfNew.js.map +1 -0
  166. package/dist/next/captureRewrites.d.ts +3 -2
  167. package/dist/next/captureRewrites.js +3 -2
  168. package/dist/next/captureRewrites.js.map +1 -1
  169. package/dist/plugin/documentEndpoint.js +52 -15
  170. package/dist/plugin/documentEndpoint.js.map +1 -1
  171. package/dist/plugin/goalHint.d.ts +1 -0
  172. package/dist/plugin/goalHint.js +24 -0
  173. package/dist/plugin/goalHint.js.map +1 -0
  174. package/dist/plugin/paths.js +5 -1
  175. package/dist/plugin/paths.js.map +1 -1
  176. package/dist/plugin/queryEndpoint.js +120 -0
  177. package/dist/plugin/queryEndpoint.js.map +1 -0
  178. package/dist/plugin/readContextForRequest.js +71 -0
  179. package/dist/plugin/readContextForRequest.js.map +1 -0
  180. package/dist/plugin/realtimeEndpoint.js +43 -15
  181. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  182. package/dist/plugin/responses.js +17 -0
  183. package/dist/plugin/responses.js.map +1 -0
  184. package/dist/plugin/runtime.js +31 -1
  185. package/dist/plugin/runtime.js.map +1 -1
  186. package/dist/plugin/scopeFieldBoot.js +22 -0
  187. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  188. package/dist/plugin/sourcesEndpoint.js +21 -52
  189. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  190. package/dist/plugin/warmTask.js +0 -0
  191. package/dist/plugin/warmTask.js.map +1 -1
  192. package/dist/providers/collection.js +29 -13
  193. package/dist/providers/collection.js.map +1 -1
  194. package/dist/providers/factory.js +4 -2
  195. package/dist/providers/factory.js.map +1 -1
  196. package/dist/providers/resolver.js.map +1 -1
  197. package/dist/query/dates.js +64 -0
  198. package/dist/query/dates.js.map +1 -0
  199. package/dist/query/errors.d.ts +17 -0
  200. package/dist/query/errors.js +10 -0
  201. package/dist/query/errors.js.map +1 -0
  202. package/dist/query/fetchQuery.d.ts +59 -0
  203. package/dist/query/fetchQuery.js +110 -0
  204. package/dist/query/fetchQuery.js.map +1 -0
  205. package/dist/query/parse.d.ts +22 -0
  206. package/dist/query/parse.js +168 -0
  207. package/dist/query/parse.js.map +1 -0
  208. package/dist/query/response.d.ts +39 -0
  209. package/dist/query/response.js +11 -0
  210. package/dist/query/response.js.map +1 -0
  211. package/dist/surfacing/engine.js +1 -1
  212. package/dist/surfacing/engine.js.map +1 -1
  213. package/dist/testing/memoryAdapter.js +0 -1
  214. package/dist/testing/memoryAdapter.js.map +1 -1
  215. package/dist/timeframe/tz.js +17 -6
  216. package/dist/timeframe/tz.js.map +1 -1
  217. package/dist/tracker/createTracker.js +13 -1
  218. package/dist/tracker/createTracker.js.map +1 -1
  219. package/dist/tracker/sinks/ga4.d.ts +21 -0
  220. package/dist/tracker/sinks/ga4.js +26 -0
  221. package/dist/tracker/sinks/ga4.js.map +1 -0
  222. package/dist/tracker/types.d.ts +5 -0
  223. package/dist/translations/ar.js +127 -1
  224. package/dist/translations/ar.js.map +1 -1
  225. package/dist/translations/de.js +127 -1
  226. package/dist/translations/de.js.map +1 -1
  227. package/dist/translations/en.js +127 -1
  228. package/dist/translations/en.js.map +1 -1
  229. package/dist/translations/es.js +127 -1
  230. package/dist/translations/es.js.map +1 -1
  231. package/dist/translations/fr.js +127 -1
  232. package/dist/translations/fr.js.map +1 -1
  233. package/dist/translations/id.js +127 -1
  234. package/dist/translations/id.js.map +1 -1
  235. package/dist/translations/keys.d.ts +126 -0
  236. package/dist/translations/keys.js +127 -1
  237. package/dist/translations/keys.js.map +1 -1
  238. package/dist/translations/ko.js +127 -1
  239. package/dist/translations/ko.js.map +1 -1
  240. package/dist/translations/metricKeys.js +8 -2
  241. package/dist/translations/metricKeys.js.map +1 -1
  242. package/dist/translations/pt.js +127 -1
  243. package/dist/translations/pt.js.map +1 -1
  244. package/dist/translations/ru.js +127 -1
  245. package/dist/translations/ru.js.map +1 -1
  246. package/dist/translations/server.js.map +1 -1
  247. package/dist/translations/uk.js +127 -1
  248. package/dist/translations/uk.js.map +1 -1
  249. package/dist/translations/zh.js +127 -1
  250. package/dist/translations/zh.js.map +1 -1
  251. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  252. package/dist/view/AnalyticsNavLink.js +40 -0
  253. package/dist/view/AnalyticsNavLink.js.map +1 -0
  254. package/dist/view/AnalyticsView.d.ts +23 -0
  255. package/dist/view/AnalyticsView.js +45 -0
  256. package/dist/view/AnalyticsView.js.map +1 -0
  257. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  258. package/dist/view/AnalyticsViewClient.js +200 -0
  259. package/dist/view/AnalyticsViewClient.js.map +1 -0
  260. package/dist/view/authRedirect.js +32 -0
  261. package/dist/view/authRedirect.js.map +1 -0
  262. package/dist/view/conversionRate.js +18 -0
  263. package/dist/view/conversionRate.js.map +1 -0
  264. package/dist/view/dayRange.js +68 -0
  265. package/dist/view/dayRange.js.map +1 -0
  266. package/dist/view/gating.d.ts +1 -0
  267. package/dist/view/gating.js +142 -0
  268. package/dist/view/gating.js.map +1 -0
  269. package/dist/view/labels.js +64 -0
  270. package/dist/view/labels.js.map +1 -0
  271. package/dist/view/registerView.js +48 -0
  272. package/dist/view/registerView.js.map +1 -0
  273. package/dist/view/sections/Breakdowns.js +197 -0
  274. package/dist/view/sections/Breakdowns.js.map +1 -0
  275. package/dist/view/sections/EmptyStates.js +92 -0
  276. package/dist/view/sections/EmptyStates.js.map +1 -0
  277. package/dist/view/sections/FilterChips.js +46 -0
  278. package/dist/view/sections/FilterChips.js.map +1 -0
  279. package/dist/view/sections/GoalsPanel.js +82 -0
  280. package/dist/view/sections/GoalsPanel.js.map +1 -0
  281. package/dist/view/sections/OverviewCards.js +65 -0
  282. package/dist/view/sections/OverviewCards.js.map +1 -0
  283. package/dist/view/sections/RealtimeStrip.js +80 -0
  284. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  285. package/dist/view/sections/Toolbar.js +186 -0
  286. package/dist/view/sections/Toolbar.js.map +1 -0
  287. package/dist/view/sections/Trend.js +125 -0
  288. package/dist/view/sections/Trend.js.map +1 -0
  289. package/dist/view/sections/styles.js +74 -0
  290. package/dist/view/sections/styles.js.map +1 -0
  291. package/dist/view/state.js +211 -0
  292. package/dist/view/state.js.map +1 -0
  293. package/dist/view/useViewQueries.js +153 -0
  294. package/dist/view/useViewQueries.js.map +1 -0
  295. package/dist/view/viewProps.d.ts +40 -0
  296. package/dist/view/viewProps.js +90 -0
  297. package/dist/view/viewProps.js.map +1 -0
  298. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  299. package/dist/widgets/AnalyticsBreakdownWidget.js +78 -11
  300. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  301. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  302. package/dist/widgets/AnalyticsGoalsWidget.js +196 -0
  303. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  304. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  305. package/dist/widgets/AnalyticsMetricWidget.js +63 -13
  306. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  307. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  308. package/dist/widgets/AnalyticsRealtimeWidget.js +44 -22
  309. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  310. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  311. package/dist/widgets/AnalyticsTrendWidget.js +79 -16
  312. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  313. package/dist/widgets/RealtimeCounter.d.ts +4 -0
  314. package/dist/widgets/RealtimeCounter.js +10 -1
  315. package/dist/widgets/RealtimeCounter.js.map +1 -1
  316. package/dist/widgets/WidgetViewLink.js +17 -0
  317. package/dist/widgets/WidgetViewLink.js.map +1 -0
  318. package/dist/widgets/breakdownTypes.js +28 -1
  319. package/dist/widgets/breakdownTypes.js.map +1 -1
  320. package/dist/widgets/cardChrome.js +31 -7
  321. package/dist/widgets/cardChrome.js.map +1 -1
  322. package/dist/widgets/comparison.js +15 -1
  323. package/dist/widgets/comparison.js.map +1 -1
  324. package/dist/widgets/defaults.d.ts +6 -2
  325. package/dist/widgets/defaults.js +72 -25
  326. package/dist/widgets/defaults.js.map +1 -1
  327. package/dist/widgets/filterCaption.js +27 -0
  328. package/dist/widgets/filterCaption.js.map +1 -0
  329. package/dist/widgets/filterField.d.ts +19 -0
  330. package/dist/widgets/filterField.js +75 -0
  331. package/dist/widgets/filterField.js.map +1 -0
  332. package/dist/widgets/prepareWidgetRead.d.ts +7 -0
  333. package/dist/widgets/prepareWidgetRead.js +74 -0
  334. package/dist/widgets/prepareWidgetRead.js.map +1 -0
  335. package/dist/widgets/range.js +43 -12
  336. package/dist/widgets/range.js.map +1 -1
  337. package/dist/widgets/readForWidget.d.ts +24 -2
  338. package/dist/widgets/readForWidget.js +34 -48
  339. package/dist/widgets/readForWidget.js.map +1 -1
  340. package/dist/widgets/readForWidgetBreakdown.d.ts +32 -1
  341. package/dist/widgets/readForWidgetBreakdown.js +32 -42
  342. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  343. package/dist/widgets/readForWidgetGoals.d.ts +67 -0
  344. package/dist/widgets/readForWidgetGoals.js +140 -0
  345. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  346. package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
  347. package/dist/widgets/readForWidgetRealtime.js +21 -20
  348. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  349. package/dist/widgets/readForWidgetSeries.d.ts +24 -1
  350. package/dist/widgets/readForWidgetSeries.js +63 -56
  351. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  352. package/dist/widgets/readMeta.js +18 -0
  353. package/dist/widgets/readMeta.js.map +1 -0
  354. package/dist/widgets/registerWidgets.js +53 -7
  355. package/dist/widgets/registerWidgets.js.map +1 -1
  356. package/dist/widgets/types.d.ts +15 -0
  357. package/dist/widgets/types.js +12 -1
  358. package/dist/widgets/types.js.map +1 -1
  359. package/dist/widgets/viewLink.d.ts +22 -0
  360. package/dist/widgets/viewLink.js +86 -0
  361. package/dist/widgets/viewLink.js.map +1 -0
  362. package/package.json +9 -4
  363. package/dist/native/rollups/applyDistinctDeltas.js +0 -9
  364. package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
  365. package/dist/native/rollups/bumpRollup.js +0 -73
  366. package/dist/native/rollups/bumpRollup.js.map +0 -1
  367. package/dist/native/rollups/insertIfNew.js +0 -19
  368. package/dist/native/rollups/insertIfNew.js.map +0 -1
@@ -0,0 +1,168 @@
1
+ import { DIMENSION_KEYS, FILTER_OPERATORS } from "../core/contract.js";
2
+ import { isValidTimeZone } from "../timeframe/tz.js";
3
+ import { METRIC_KEYS } from "../translations/metricKeys.js";
4
+ import { GRANULARITY_ORDER } from "../core/granularity.js";
5
+ import { parseDayOrInstant } from "./dates.js";
6
+ import { queryError } from "./errors.js";
7
+ //#region src/query/parse.ts
8
+ const KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS));
9
+ const KNOWN_DIMENSIONS = new Set(DIMENSION_KEYS);
10
+ const KNOWN_OPERATORS = new Set(FILTER_OPERATORS);
11
+ const KNOWN_GRANULARITIES = new Set(GRANULARITY_ORDER);
12
+ const DAY_MS = 864e5;
13
+ const fail = (code, message, param) => ({
14
+ ok: false,
15
+ error: queryError(code, message, param)
16
+ });
17
+ /** Echo a rejected value back in a message without letting a caller inflate the response. */
18
+ const echo = (value) => value.length > 40 ? `${value.slice(0, 40)}...` : value;
19
+ /**
20
+ * A trimmed non-empty parameter, or null when absent or blank. Exported so the handler
21
+ * reads `source` and `scope` (which it must resolve before the parser can run) exactly
22
+ * the way the parser reads everything else.
23
+ */
24
+ const readParam = (params, name) => {
25
+ const raw = params.get(name)?.trim();
26
+ return raw ? raw : null;
27
+ };
28
+ const commaList = (raw) => raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
29
+ const dedupe = (values) => [...new Set(values)];
30
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ const parseFilters = (raw, capabilities) => {
32
+ let decoded;
33
+ try {
34
+ decoded = JSON.parse(raw);
35
+ } catch {
36
+ return fail("invalid_param", "filters must be a JSON array", "filters");
37
+ }
38
+ if (!Array.isArray(decoded)) return fail("invalid_param", "filters must be a JSON array", "filters");
39
+ if (decoded.length > 10) return fail("invalid_param", `at most 10 filters are allowed`, "filters");
40
+ const filterable = new Set(capabilities.filters);
41
+ const operators = new Set(capabilities.filterOperators);
42
+ const parsed = [];
43
+ for (const item of decoded) {
44
+ if (!isRecord(item)) return fail("invalid_param", "each filter must be an object", "filters");
45
+ const { dimension, operator, value } = item;
46
+ if (typeof dimension !== "string" || !KNOWN_DIMENSIONS.has(dimension)) return fail("invalid_param", `unknown filter dimension: ${echo(String(dimension))}`, "filters");
47
+ if (typeof operator !== "string" || !KNOWN_OPERATORS.has(operator)) return fail("invalid_param", `unknown filter operator: ${echo(String(operator))}`, "filters");
48
+ if (typeof value !== "string") return fail("invalid_param", "each filter value must be a string", "filters");
49
+ const trimmed = value.trim();
50
+ if (trimmed.length < 1 || trimmed.length > 256) return fail("invalid_param", `each filter value must be 1 to 256 characters`, "filters");
51
+ if (!filterable.has(dimension)) return fail("unsupported_filter", `source cannot filter on ${dimension}`, "filters");
52
+ if (!operators.has(operator)) return fail("unsupported_operator", `source does not support ${operator}`, "filters");
53
+ parsed.push({
54
+ dimension,
55
+ operator,
56
+ value: trimmed
57
+ });
58
+ }
59
+ return parsed;
60
+ };
61
+ /**
62
+ * Validate a query string against a source's serialized capabilities. Rules are evaluated
63
+ * in a fixed order and the first failure wins: timezone, metrics, dimensions, from/to,
64
+ * granularity, filters, limit, order, compare, path, hostname. Within each, a value
65
+ * outside the contract's own union is `invalid_param` and a contract value the source
66
+ * lacks is its `unsupported_*` code. Unknown parameters are ignored; `source` and `scope`
67
+ * pass through unvalidated, since only the handler knows whether they are trusted.
68
+ */
69
+ const parseQueryParams = (params, args) => {
70
+ const rawTimezone = readParam(params, "timezone");
71
+ if (rawTimezone !== null && !isValidTimeZone(rawTimezone)) return fail("invalid_param", `unknown timezone: ${echo(rawTimezone)}`, "timezone");
72
+ const timezone = rawTimezone ?? args.timezone;
73
+ const rawMetrics = readParam(params, "metrics");
74
+ const metricList = rawMetrics ? commaList(rawMetrics) : [];
75
+ if (metricList.length === 0) return fail("invalid_param", "metrics is required", "metrics");
76
+ const unknownMetric = metricList.find((m) => !KNOWN_METRICS.has(m));
77
+ if (unknownMetric !== void 0) return fail("invalid_param", `unknown metric: ${echo(unknownMetric)}`, "metrics");
78
+ const metrics = dedupe(metricList);
79
+ if (metrics.length > 10) return fail("invalid_param", `at most 10 metrics are allowed`, "metrics");
80
+ const servedMetrics = new Set(args.capabilities.metrics);
81
+ const unsupportedMetric = metrics.find((m) => !servedMetrics.has(m));
82
+ if (unsupportedMetric !== void 0) return fail("unsupported_metric", `source does not serve ${unsupportedMetric}`, "metrics");
83
+ const rawDimensions = readParam(params, "dimensions");
84
+ const dimensionList = rawDimensions ? commaList(rawDimensions) : [];
85
+ const unknownDimension = dimensionList.find((d) => !KNOWN_DIMENSIONS.has(d));
86
+ if (unknownDimension !== void 0) return fail("invalid_param", `unknown dimension: ${echo(unknownDimension)}`, "dimensions");
87
+ const dimensions = dedupe(dimensionList);
88
+ if (dimensions.length > 2) return fail("invalid_param", `at most 2 dimensions are allowed`, "dimensions");
89
+ const servedDimensions = new Set(args.capabilities.dimensions);
90
+ const unsupportedDimension = dimensions.find((d) => !servedDimensions.has(d));
91
+ if (unsupportedDimension !== void 0) return fail("unsupported_dimension", `source does not break down by ${unsupportedDimension}`, "dimensions");
92
+ const rawFrom = readParam(params, "from");
93
+ const rawTo = readParam(params, "to");
94
+ if (!rawFrom) return fail("invalid_param", "from is required", "from");
95
+ const start = parseDayOrInstant(rawFrom, {
96
+ timezone,
97
+ edge: "start"
98
+ });
99
+ if (!start) return fail("invalid_param", `from is not a date: ${echo(rawFrom)}`, "from");
100
+ if (!rawTo) return fail("invalid_param", "to is required", "to");
101
+ const end = parseDayOrInstant(rawTo, {
102
+ timezone,
103
+ edge: "end"
104
+ });
105
+ if (!end) return fail("invalid_param", `to is not a date: ${echo(rawTo)}`, "to");
106
+ if (end.getTime() < start.getTime()) return fail("invalid_param", "to must not be before from", "to");
107
+ if (end.getTime() - start.getTime() > 366 * DAY_MS) return fail("range_too_long", `the range must not exceed 366 days`, "to");
108
+ const rawGranularity = readParam(params, "granularity");
109
+ if (rawGranularity !== null && !KNOWN_GRANULARITIES.has(rawGranularity)) return fail("invalid_param", `unknown granularity: ${echo(rawGranularity)}`, "granularity");
110
+ const granularity = rawGranularity;
111
+ if (granularity !== null && GRANULARITY_ORDER.indexOf(granularity) < GRANULARITY_ORDER.indexOf(args.capabilities.minGranularity)) return fail("unsupported_granularity", `source buckets no finer than ${args.capabilities.minGranularity}`, "granularity");
112
+ const rawFilters = readParam(params, "filters");
113
+ const filters = rawFilters === null ? [] : parseFilters(rawFilters, args.capabilities);
114
+ if (!Array.isArray(filters)) return filters;
115
+ const rawLimit = readParam(params, "limit");
116
+ let limit = 50;
117
+ if (rawLimit !== null) {
118
+ if (!/^\d+$/.test(rawLimit)) return fail("invalid_param", `limit must be an integer: ${echo(rawLimit)}`, "limit");
119
+ limit = Number(rawLimit);
120
+ if (limit < 1 || limit > 500) return fail("invalid_param", `limit must be between 1 and 500`, "limit");
121
+ }
122
+ const rawOrder = readParam(params, "order");
123
+ let order;
124
+ if (rawOrder !== null) {
125
+ const parts = rawOrder.split(":");
126
+ const metric = parts[0] ?? "";
127
+ const direction = parts[1] ?? "";
128
+ if (parts.length !== 2 || direction !== "asc" && direction !== "desc") return fail("invalid_param", "order must be <metric>:<asc|desc>", "order");
129
+ const ordered = metrics.find((m) => m === metric);
130
+ if (ordered === void 0) return fail("invalid_param", `order metric is not in metrics: ${echo(metric)}`, "order");
131
+ order = {
132
+ metric: ordered,
133
+ direction
134
+ };
135
+ }
136
+ const rawCompare = readParam(params, "compare");
137
+ if (rawCompare !== null && rawCompare !== "previous") return fail("invalid_param", `compare must be "previous": ${echo(rawCompare)}`, "compare");
138
+ if (rawCompare === "previous" && !args.capabilities.comparison) return fail("invalid_param", "source does not support comparison", "compare");
139
+ const path = readParam(params, "path");
140
+ if (path !== null && path.length > 512) return fail("invalid_param", `path must be at most 512 characters`, "path");
141
+ const hostname = readParam(params, "hostname");
142
+ if (hostname !== null && hostname.length > 253) return fail("invalid_param", `hostname must be at most 253 characters`, "hostname");
143
+ return {
144
+ ok: true,
145
+ value: {
146
+ query: {
147
+ metrics,
148
+ dateRange: {
149
+ start,
150
+ end
151
+ },
152
+ limit,
153
+ timezone,
154
+ ...dimensions.length > 0 ? { dimensions } : {},
155
+ ...granularity !== null ? { granularity } : {},
156
+ ...filters.length > 0 ? { filters } : {},
157
+ ...order ? { order } : {},
158
+ ...path !== null ? { path } : {},
159
+ ...hostname !== null ? { hostname } : {}
160
+ },
161
+ compare: rawCompare === "previous" ? "previous" : null
162
+ }
163
+ };
164
+ };
165
+ //#endregion
166
+ export { parseQueryParams, readParam };
167
+
168
+ //# sourceMappingURL=parse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse.js","names":[],"sources":["../../src/query/parse.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\tFILTER_OPERATORS,\n\ttype FilterOperator,\n\ttype Granularity,\n\ttype MetricKey,\n} from '../core/contract'\nimport { GRANULARITY_ORDER } from '../core/granularity'\nimport { isValidTimeZone } from '../timeframe/tz'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { parseDayOrInstant } from './dates'\nimport { type QueryError, queryError } from './errors'\nimport {\n\tDEFAULT_QUERY_LIMIT,\n\tMAX_QUERY_DIMENSIONS,\n\tMAX_QUERY_FILTER_VALUE_LENGTH,\n\tMAX_QUERY_FILTERS,\n\tMAX_QUERY_HOSTNAME_LENGTH,\n\tMAX_QUERY_LIMIT,\n\tMAX_QUERY_METRICS,\n\tMAX_QUERY_PATH_LENGTH,\n\tMAX_QUERY_RANGE_DAYS,\n\tMIN_QUERY_LIMIT,\n} from './limits'\n\n/**\n * A validated read request. `source` and `scope` are absent by design: the handler must\n * resolve both before the parser can run, and reads them itself through {@link readParam}.\n */\nexport interface ParsedQuery {\n\tquery: AnalyticsQuery\n\tcompare: 'previous' | null\n}\n\nexport type ParseResult = { ok: true; value: ParsedQuery } | { ok: false; error: QueryError }\n\nexport interface ParseQueryArgs {\n\tcapabilities: SerializedCapabilities\n\t/** Reporting timezone the plugin resolved for this request; the `timezone` param overrides it. */\n\ttimezone: string\n}\n\nconst KNOWN_METRICS = new Set<string>(Object.keys(METRIC_KEYS))\nconst KNOWN_DIMENSIONS = new Set<string>(DIMENSION_KEYS)\nconst KNOWN_OPERATORS = new Set<string>(FILTER_OPERATORS)\nconst KNOWN_GRANULARITIES = new Set<string>(GRANULARITY_ORDER)\nconst DAY_MS = 86_400_000\n\nconst fail = (code: QueryError['code'], message: string, param: string): ParseResult => ({\n\tok: false,\n\terror: queryError(code, message, param),\n})\n\n/** Echo a rejected value back in a message without letting a caller inflate the response. */\nconst echo = (value: string): string => (value.length > 40 ? `${value.slice(0, 40)}...` : value)\n\n/**\n * A trimmed non-empty parameter, or null when absent or blank. Exported so the handler\n * reads `source` and `scope` (which it must resolve before the parser can run) exactly\n * the way the parser reads everything else.\n */\nexport const readParam = (params: URLSearchParams, name: string): string | null => {\n\tconst raw = params.get(name)?.trim()\n\treturn raw ? raw : null\n}\n\nconst commaList = (raw: string): string[] =>\n\traw\n\t\t.split(',')\n\t\t.map((part) => part.trim())\n\t\t.filter((part) => part.length > 0)\n\nconst dedupe = <T extends string>(values: T[]): T[] => [...new Set(values)]\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst parseFilters = (\n\traw: string,\n\tcapabilities: SerializedCapabilities\n): AnalyticsFilter[] | ParseResult => {\n\tlet decoded: unknown\n\ttry {\n\t\tdecoded = JSON.parse(raw)\n\t} catch {\n\t\treturn fail('invalid_param', 'filters must be a JSON array', 'filters')\n\t}\n\tif (!Array.isArray(decoded)) {\n\t\treturn fail('invalid_param', 'filters must be a JSON array', 'filters')\n\t}\n\tif (decoded.length > MAX_QUERY_FILTERS) {\n\t\treturn fail('invalid_param', `at most ${MAX_QUERY_FILTERS} filters are allowed`, 'filters')\n\t}\n\tconst filterable = new Set<string>(capabilities.filters)\n\tconst operators = new Set<string>(capabilities.filterOperators)\n\tconst parsed: AnalyticsFilter[] = []\n\tfor (const item of decoded) {\n\t\tif (!isRecord(item)) {\n\t\t\treturn fail('invalid_param', 'each filter must be an object', 'filters')\n\t\t}\n\t\tconst { dimension, operator, value } = item\n\t\tif (typeof dimension !== 'string' || !KNOWN_DIMENSIONS.has(dimension)) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`unknown filter dimension: ${echo(String(dimension))}`,\n\t\t\t\t'filters'\n\t\t\t)\n\t\t}\n\t\tif (typeof operator !== 'string' || !KNOWN_OPERATORS.has(operator)) {\n\t\t\treturn fail('invalid_param', `unknown filter operator: ${echo(String(operator))}`, 'filters')\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\treturn fail('invalid_param', 'each filter value must be a string', 'filters')\n\t\t}\n\t\tconst trimmed = value.trim()\n\t\tif (trimmed.length < 1 || trimmed.length > MAX_QUERY_FILTER_VALUE_LENGTH) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`each filter value must be 1 to ${MAX_QUERY_FILTER_VALUE_LENGTH} characters`,\n\t\t\t\t'filters'\n\t\t\t)\n\t\t}\n\t\tif (!filterable.has(dimension)) {\n\t\t\treturn fail('unsupported_filter', `source cannot filter on ${dimension}`, 'filters')\n\t\t}\n\t\tif (!operators.has(operator)) {\n\t\t\treturn fail('unsupported_operator', `source does not support ${operator}`, 'filters')\n\t\t}\n\t\tparsed.push({\n\t\t\tdimension: dimension as DimensionKey,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue: trimmed,\n\t\t})\n\t}\n\treturn parsed\n}\n\n/**\n * Validate a query string against a source's serialized capabilities. Rules are evaluated\n * in a fixed order and the first failure wins: timezone, metrics, dimensions, from/to,\n * granularity, filters, limit, order, compare, path, hostname. Within each, a value\n * outside the contract's own union is `invalid_param` and a contract value the source\n * lacks is its `unsupported_*` code. Unknown parameters are ignored; `source` and `scope`\n * pass through unvalidated, since only the handler knows whether they are trusted.\n */\nexport const parseQueryParams = (params: URLSearchParams, args: ParseQueryArgs): ParseResult => {\n\tconst rawTimezone = readParam(params, 'timezone')\n\tif (rawTimezone !== null && !isValidTimeZone(rawTimezone)) {\n\t\treturn fail('invalid_param', `unknown timezone: ${echo(rawTimezone)}`, 'timezone')\n\t}\n\tconst timezone = rawTimezone ?? args.timezone\n\n\tconst rawMetrics = readParam(params, 'metrics')\n\tconst metricList = rawMetrics ? commaList(rawMetrics) : []\n\tif (metricList.length === 0) {\n\t\treturn fail('invalid_param', 'metrics is required', 'metrics')\n\t}\n\tconst unknownMetric = metricList.find((m) => !KNOWN_METRICS.has(m))\n\tif (unknownMetric !== undefined) {\n\t\treturn fail('invalid_param', `unknown metric: ${echo(unknownMetric)}`, 'metrics')\n\t}\n\tconst metrics = dedupe(metricList) as MetricKey[]\n\tif (metrics.length > MAX_QUERY_METRICS) {\n\t\treturn fail('invalid_param', `at most ${MAX_QUERY_METRICS} metrics are allowed`, 'metrics')\n\t}\n\tconst servedMetrics = new Set<string>(args.capabilities.metrics)\n\tconst unsupportedMetric = metrics.find((m) => !servedMetrics.has(m))\n\tif (unsupportedMetric !== undefined) {\n\t\treturn fail('unsupported_metric', `source does not serve ${unsupportedMetric}`, 'metrics')\n\t}\n\n\tconst rawDimensions = readParam(params, 'dimensions')\n\tconst dimensionList = rawDimensions ? commaList(rawDimensions) : []\n\tconst unknownDimension = dimensionList.find((d) => !KNOWN_DIMENSIONS.has(d))\n\tif (unknownDimension !== undefined) {\n\t\treturn fail('invalid_param', `unknown dimension: ${echo(unknownDimension)}`, 'dimensions')\n\t}\n\tconst dimensions = dedupe(dimensionList) as DimensionKey[]\n\tif (dimensions.length > MAX_QUERY_DIMENSIONS) {\n\t\treturn fail(\n\t\t\t'invalid_param',\n\t\t\t`at most ${MAX_QUERY_DIMENSIONS} dimensions are allowed`,\n\t\t\t'dimensions'\n\t\t)\n\t}\n\tconst servedDimensions = new Set<string>(args.capabilities.dimensions)\n\tconst unsupportedDimension = dimensions.find((d) => !servedDimensions.has(d))\n\tif (unsupportedDimension !== undefined) {\n\t\treturn fail(\n\t\t\t'unsupported_dimension',\n\t\t\t`source does not break down by ${unsupportedDimension}`,\n\t\t\t'dimensions'\n\t\t)\n\t}\n\n\tconst rawFrom = readParam(params, 'from')\n\tconst rawTo = readParam(params, 'to')\n\tif (!rawFrom) {\n\t\treturn fail('invalid_param', 'from is required', 'from')\n\t}\n\tconst start = parseDayOrInstant(rawFrom, { timezone, edge: 'start' })\n\tif (!start) {\n\t\treturn fail('invalid_param', `from is not a date: ${echo(rawFrom)}`, 'from')\n\t}\n\tif (!rawTo) {\n\t\treturn fail('invalid_param', 'to is required', 'to')\n\t}\n\tconst end = parseDayOrInstant(rawTo, { timezone, edge: 'end' })\n\tif (!end) {\n\t\treturn fail('invalid_param', `to is not a date: ${echo(rawTo)}`, 'to')\n\t}\n\tif (end.getTime() < start.getTime()) {\n\t\treturn fail('invalid_param', 'to must not be before from', 'to')\n\t}\n\tif (end.getTime() - start.getTime() > MAX_QUERY_RANGE_DAYS * DAY_MS) {\n\t\treturn fail('range_too_long', `the range must not exceed ${MAX_QUERY_RANGE_DAYS} days`, 'to')\n\t}\n\n\tconst rawGranularity = readParam(params, 'granularity')\n\tif (rawGranularity !== null && !KNOWN_GRANULARITIES.has(rawGranularity)) {\n\t\treturn fail('invalid_param', `unknown granularity: ${echo(rawGranularity)}`, 'granularity')\n\t}\n\tconst granularity = rawGranularity as Granularity | null\n\tif (\n\t\tgranularity !== null &&\n\t\tGRANULARITY_ORDER.indexOf(granularity) <\n\t\t\tGRANULARITY_ORDER.indexOf(args.capabilities.minGranularity)\n\t) {\n\t\treturn fail(\n\t\t\t'unsupported_granularity',\n\t\t\t`source buckets no finer than ${args.capabilities.minGranularity}`,\n\t\t\t'granularity'\n\t\t)\n\t}\n\n\tconst rawFilters = readParam(params, 'filters')\n\tconst filters = rawFilters === null ? [] : parseFilters(rawFilters, args.capabilities)\n\tif (!Array.isArray(filters)) {\n\t\treturn filters\n\t}\n\n\tconst rawLimit = readParam(params, 'limit')\n\tlet limit = DEFAULT_QUERY_LIMIT\n\tif (rawLimit !== null) {\n\t\tif (!/^\\d+$/.test(rawLimit)) {\n\t\t\treturn fail('invalid_param', `limit must be an integer: ${echo(rawLimit)}`, 'limit')\n\t\t}\n\t\tlimit = Number(rawLimit)\n\t\tif (limit < MIN_QUERY_LIMIT || limit > MAX_QUERY_LIMIT) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`limit must be between ${MIN_QUERY_LIMIT} and ${MAX_QUERY_LIMIT}`,\n\t\t\t\t'limit'\n\t\t\t)\n\t\t}\n\t}\n\n\tconst rawOrder = readParam(params, 'order')\n\tlet order: AnalyticsQuery['order']\n\tif (rawOrder !== null) {\n\t\tconst parts = rawOrder.split(':')\n\t\tconst metric = parts[0] ?? ''\n\t\tconst direction = parts[1] ?? ''\n\t\tif (parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {\n\t\t\treturn fail('invalid_param', 'order must be <metric>:<asc|desc>', 'order')\n\t\t}\n\t\tconst ordered = metrics.find((m) => m === metric)\n\t\tif (ordered === undefined) {\n\t\t\treturn fail('invalid_param', `order metric is not in metrics: ${echo(metric)}`, 'order')\n\t\t}\n\t\torder = { metric: ordered, direction }\n\t}\n\n\tconst rawCompare = readParam(params, 'compare')\n\tif (rawCompare !== null && rawCompare !== 'previous') {\n\t\treturn fail('invalid_param', `compare must be \"previous\": ${echo(rawCompare)}`, 'compare')\n\t}\n\tif (rawCompare === 'previous' && !args.capabilities.comparison) {\n\t\treturn fail('invalid_param', 'source does not support comparison', 'compare')\n\t}\n\n\tconst path = readParam(params, 'path')\n\tif (path !== null && path.length > MAX_QUERY_PATH_LENGTH) {\n\t\treturn fail('invalid_param', `path must be at most ${MAX_QUERY_PATH_LENGTH} characters`, 'path')\n\t}\n\tconst hostname = readParam(params, 'hostname')\n\tif (hostname !== null && hostname.length > MAX_QUERY_HOSTNAME_LENGTH) {\n\t\treturn fail(\n\t\t\t'invalid_param',\n\t\t\t`hostname must be at most ${MAX_QUERY_HOSTNAME_LENGTH} characters`,\n\t\t\t'hostname'\n\t\t)\n\t}\n\n\tconst query: AnalyticsQuery = {\n\t\tmetrics,\n\t\tdateRange: { start, end },\n\t\tlimit,\n\t\ttimezone,\n\t\t...(dimensions.length > 0 ? { dimensions } : {}),\n\t\t...(granularity !== null ? { granularity } : {}),\n\t\t...(filters.length > 0 ? { filters } : {}),\n\t\t...(order ? { order } : {}),\n\t\t...(path !== null ? { path } : {}),\n\t\t...(hostname !== null ? { hostname } : {}),\n\t}\n\treturn {\n\t\tok: true,\n\t\tvalue: { query, compare: rawCompare === 'previous' ? 'previous' : null },\n\t}\n}\n"],"mappings":";;;;;;;AA8CA,MAAM,gBAAgB,IAAI,IAAY,OAAO,KAAK,WAAW,CAAC;AAC9D,MAAM,mBAAmB,IAAI,IAAY,cAAc;AACvD,MAAM,kBAAkB,IAAI,IAAY,gBAAgB;AACxD,MAAM,sBAA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O,KAAK,iBAAiB,mCAAmC,KAAK,MAAM,KAAK,OAAO;EAExF,QAAQ;GAAE,QAAQ;GAAS;EAAU;CACtC;CAEA,MAAM,aAAa,UAAU,QAAQ,SAAS;CAC9C,IAAI,eAAe,QAAQ,eAAe,YACzC,OAAO,KAAK,iBAAiB,+BAA+B,KAAK,UAAU,KAAK,SAAS;CAE1F,IAAI,eAAe,cAAc,CAAC,KAAK,aAAa,YACnD,OAAO,KAAK,iBAAiB,sCAAsC,SAAS;CAG7E,MAAM,OAAO,UAAU,QAAQ,MAAM;CACrC,IAAI,SAAS,QAAQ,KAAK,SAAA,KACzB,OAAO,KAAK,iBAAiB,uCAA4D,MAAM;CAEhG,MAAM,WAAW,UAAU,QAAQ,UAAU;CAC7C,IAAI,aAAa,QAAQ,SAAS,SAAA,KACjC,OAAO,KACN,iBACA,2CACA,UACD;CAeD,OAAO;EACN,IAAI;EACJ,OAAO;GAAE,OAAA;IAbT;IACA,WAAW;KAAE;KAAO;IAAI;IACxB;IACA;IACA,GAAI,WAAW,SAAS,IAAI,EAAE,WAAW,IAAI,CAAC;IAC9C,GAAI,gBAAgB,OAAO,EAAE,YAAY,IAAI,CAAC;IAC9C,GAAI,QAAQ,SAAS,IAAI,EAAE,QAAQ,IAAI,CAAC;IACxC,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;IACzB,GAAI,SAAS,OAAO,EAAE,KAAK,IAAI,CAAC;IAChC,GAAI,aAAa,OAAO,EAAE,SAAS,IAAI,CAAC;GAI3B;GAAG,SAAS,eAAe,aAAa,aAAa;EAAK;CACxE;AACD"}
@@ -0,0 +1,39 @@
1
+ import { AnalyticsQuery, AnalyticsResult } from "../core/contract.js";
2
+ import { SerializedCapabilities } from "../core/capabilities.js";
3
+ import { QueryError } from "./errors.js";
4
+
5
+ //#region src/query/response.d.ts
6
+ /** Identity of the source a read was served by; its capabilities travel beside it. */
7
+ interface QuerySourceRef {
8
+ id: string;
9
+ label: string;
10
+ /** `config` for an adapter every scope shares, `runtime` for one resolved per scope. */
11
+ kind: 'config' | 'runtime';
12
+ }
13
+ /** An `AnalyticsQuery` as it survives JSON: the date range's instants are ISO strings. */
14
+ type SerializedAnalyticsQuery = Omit<AnalyticsQuery, 'dateRange'> & {
15
+ dateRange: {
16
+ start: string;
17
+ end: string;
18
+ };
19
+ };
20
+ /** Successful answer of `GET /analytics/query`. */
21
+ interface QueryResponse {
22
+ result: AnalyticsResult;
23
+ /**
24
+ * The equal-length window before `query.dateRange`, asked for with `compare=previous`.
25
+ * Omitted when the source does not compare or that window is beyond its lookback.
26
+ */
27
+ comparison?: AnalyticsResult;
28
+ source: QuerySourceRef;
29
+ capabilities: SerializedCapabilities;
30
+ /** The query after validation and defaulting, so a client renders what it actually got. */
31
+ query: SerializedAnalyticsQuery;
32
+ }
33
+ /** Every non-2xx answer of `GET /analytics/query`. */
34
+ interface QueryErrorResponse {
35
+ error: QueryError;
36
+ }
37
+ //#endregion
38
+ export { QueryErrorResponse, QueryResponse, QuerySourceRef, SerializedAnalyticsQuery };
39
+ //# sourceMappingURL=response.d.ts.map
@@ -0,0 +1,11 @@
1
+ //#region src/query/response.ts
2
+ /**
3
+ * Whether the echoed query asked about goals and the scope configured none. The hint is
4
+ * set only for a goal read, so an empty list is a scope with nothing to convert on: an
5
+ * empty table rather than a source that could not answer, which is `meta.goalsUnresolved`.
6
+ */
7
+ const askedAboutNoGoals = (query) => Array.isArray(query?.goalSlugs) && query.goalSlugs.length === 0;
8
+ //#endregion
9
+ export { askedAboutNoGoals };
10
+
11
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","names":[],"sources":["../../src/query/response.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../core/capabilities'\nimport type { AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport type { QueryError } from './errors'\n\n/** Identity of the source a read was served by; its capabilities travel beside it. */\nexport interface QuerySourceRef {\n\tid: string\n\tlabel: string\n\t/** `config` for an adapter every scope shares, `runtime` for one resolved per scope. */\n\tkind: 'config' | 'runtime'\n}\n\n/** An `AnalyticsQuery` as it survives JSON: the date range's instants are ISO strings. */\nexport type SerializedAnalyticsQuery = Omit<AnalyticsQuery, 'dateRange'> & {\n\tdateRange: { start: string; end: string }\n}\n\n/** Successful answer of `GET /analytics/query`. */\nexport interface QueryResponse {\n\tresult: AnalyticsResult\n\t/**\n\t * The equal-length window before `query.dateRange`, asked for with `compare=previous`.\n\t * Omitted when the source does not compare or that window is beyond its lookback.\n\t */\n\tcomparison?: AnalyticsResult\n\tsource: QuerySourceRef\n\tcapabilities: SerializedCapabilities\n\t/** The query after validation and defaulting, so a client renders what it actually got. */\n\tquery: SerializedAnalyticsQuery\n}\n\n/**\n * Whether the echoed query asked about goals and the scope configured none. The hint is\n * set only for a goal read, so an empty list is a scope with nothing to convert on: an\n * empty table rather than a source that could not answer, which is `meta.goalsUnresolved`.\n */\nexport const askedAboutNoGoals = (query?: SerializedAnalyticsQuery): boolean =>\n\tArray.isArray(query?.goalSlugs) && query.goalSlugs.length === 0\n\n/** Every non-2xx answer of `GET /analytics/query`. */\nexport interface QueryErrorResponse {\n\terror: QueryError\n}\n"],"mappings":";;;;;;AAoCA,MAAa,qBAAqB,UACjC,MAAM,QAAQ,OAAO,SAAS,KAAK,MAAM,UAAU,WAAW"}
@@ -91,7 +91,7 @@ function createEngine(opts) {
91
91
  clamped: true
92
92
  }
93
93
  } : fresh;
94
- const ttl = opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate;
94
+ const ttl = result.meta.goalsUnresolved === true ? opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime : opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate;
95
95
  await opts.store.set(key, result, ttl);
96
96
  return result;
97
97
  });
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import { buildCacheKey } from '../core/cacheKey'\nimport type { AnalyticsAdapter, AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { CacheStore } from './cacheStore'\nimport { createCoalescer } from './coalesce'\nimport { createQueue, type QueueOptions } from './queue'\nimport { limiterFor, type RateLimiter } from './rateLimiter'\nimport { PROVIDER_READ_TIMEOUT_MESSAGE, shouldRetryProviderError } from './retryPolicy'\n\nconst DAY_MS = 86_400_000\n\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tif (maxLookbackDays == null) {\n\t\treturn { range, clamped: false }\n\t}\n\tconst floor = new Date(startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS)\n\tif (range.start.getTime() >= floor.getTime()) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: floor, end: range.end }, clamped: true }\n}\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\tqueue: QueueOptions\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Budget for a single adapter read; the in-flight request is aborted past this. */\n\ttimeoutMs: number\n\t/** Called once per failed adapter fetch, before falling back to a stale cache entry. */\n\tonError?: (err: unknown, adapterId: string) => void\n}\n\nexport interface Engine {\n\tread(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n}\n\nconst emptyResult = (provider: string, q: AnalyticsQuery): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: q.dateRange.end.toISOString() },\n})\n\nexport function createEngine(opts: EngineOptions): Engine {\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst limiters = new Map<string, RateLimiter>()\n\tconst queue = createQueue({\n\t\t...opts.queue,\n\t\tshouldRetry: shouldRetryProviderError,\n\t\tbaseDelayMs: 500,\n\t})\n\n\treturn {\n\t\tasync read(adapter, query) {\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, query)\n\n\t\t\tconst { range, clamped } = clampRange(\n\t\t\t\tquery.dateRange,\n\t\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\t\tquery.timezone\n\t\t\t)\n\t\t\tconst q = clamped ? { ...query, dateRange: range } : query\n\t\t\tconst key = buildCacheKey(adapter.id, q)\n\t\t\treturn coalesce(key, async () => {\n\t\t\t\tlet fresh: AnalyticsResult\n\t\t\t\tconst controller = new AbortController()\n\t\t\t\tconst timer = setTimeout(\n\t\t\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\t\t\topts.timeoutMs\n\t\t\t\t)\n\t\t\t\ttimer.unref?.()\n\t\t\t\ttry {\n\t\t\t\t\tconst cached = await opts.store.get<AnalyticsResult>(key)\n\t\t\t\t\tif (cached) return cached\n\n\t\t\t\t\t// Races the queued attempt itself, not just its backoff waits, so a signal-blind\n\t\t\t\t\t// adapter (one that never checks ctx.signal) still bounds the read at timeoutMs.\n\t\t\t\t\t// The orphaned attempt keeps its queue slot until the underlying client gives up;\n\t\t\t\t\t// this only bounds how long read() waits for it.\n\t\t\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\t\t\tonce: true,\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\tconst attempt = queue.run(async () => {\n\t\t\t\t\t\tconst release = await limiterFor(limiters, adapter).take(controller.signal)\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await adapter.query(q, { signal: controller.signal })\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trelease()\n\t\t\t\t\t\t}\n\t\t\t\t\t}, controller.signal)\n\t\t\t\t\tattempt.catch(() => {})\n\t\t\t\t\tfresh = await Promise.race([attempt, aborted])\n\t\t\t\t} catch (err) {\n\t\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst stale = await opts.store.getStale<AnalyticsResult>(key)\n\t\t\t\t\t\tif (stale) return { ...stale, meta: { ...stale.meta, stale: true } }\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A broken store fails getStale too; surface the original read error, not this one.\n\t\t\t\t\t}\n\t\t\t\t\tthrow err\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t}\n\t\t\t\tconst result: AnalyticsResult = clamped\n\t\t\t\t\t? { ...fresh, meta: { ...fresh.meta, clamped: true } }\n\t\t\t\t\t: fresh\n\t\t\t\tconst ttl = opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate\n\t\t\t\tawait opts.store.set(key, result, ttl)\n\t\t\t\treturn result\n\t\t\t})\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAM,SAAS;AAEf,MAAM,cACL,OACA,iBACA,KAAA,UAC8D;CAC9D,IAAI,mBAAmB,MACtB,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,MAAM,wBAAQ,IAAI,KAAK,eAAe,MAAM,KAAK,EAAE,EAAE,QAAQ,IAAI,kBAAkB,MAAM;CACzF,IAAI,MAAM,MAAM,QAAQ,KAAK,MAAM,QAAQ,GAC1C,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,OAAO;EAAE,OAAO;GAAE,OAAO;GAAO,KAAK,MAAM;EAAI;EAAG,SAAS;CAAK;AACjE;AAiBA,MAAM,eAAe,UAAkB,OAAwC;CAC9E,MAAM,CAAC;CACP,MAAM;EAAE;EAAU,WAAW,EAAE,UAAU,IAAI,YAAY;CAAE;AAC5D;AAEA,SAAgB,aAAa,MAA6B;CACzD,MAAM,WAAW,gBAAiC;CAClD,MAAM,2BAAW,IAAI,IAAyB;CAC9C,MAAM,QAAQ,YAAY;EACzB,GAAG,KAAK;EACR,aAAa;EACb,aAAa;CACd,CAAC;CAED,OAAO,EACN,MAAM,KAAK,SAAS,O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,aAAa,KAAK;GACnB;GACA,MAAM,SAA0B,UAC7B;IAAE,GAAG;IAAO,MAAM;KAAE,GAAG,MAAM;KAAM,SAAS;IAAK;GAAE,IACnD;GACH,MAAM,MAAM,KAAK,IAAI,aAAa,QAAQ,aAAa,eAAe;GACtE,MAAM,KAAK,MAAM,IAAI,KAAK,QAAQ,GAAG;GACrC,OAAO;EACR,CAAC;CACF,EACD;AACD"}
1
+ {"version":3,"file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import { buildCacheKey } from '../core/cacheKey'\nimport type { AnalyticsAdapter, AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { CacheStore } from './cacheStore'\nimport { createCoalescer } from './coalesce'\nimport { createQueue, type QueueOptions } from './queue'\nimport { limiterFor, type RateLimiter } from './rateLimiter'\nimport { PROVIDER_READ_TIMEOUT_MESSAGE, shouldRetryProviderError } from './retryPolicy'\n\nconst DAY_MS = 86_400_000\n\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tif (maxLookbackDays == null) {\n\t\treturn { range, clamped: false }\n\t}\n\tconst floor = new Date(startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS)\n\tif (range.start.getTime() >= floor.getTime()) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: floor, end: range.end }, clamped: true }\n}\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\tqueue: QueueOptions\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Budget for a single adapter read; the in-flight request is aborted past this. */\n\ttimeoutMs: number\n\t/** Called once per failed adapter fetch, before falling back to a stale cache entry. */\n\tonError?: (err: unknown, adapterId: string) => void\n}\n\nexport interface Engine {\n\tread(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n}\n\nconst emptyResult = (provider: string, q: AnalyticsQuery): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: q.dateRange.end.toISOString() },\n})\n\nexport function createEngine(opts: EngineOptions): Engine {\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst limiters = new Map<string, RateLimiter>()\n\tconst queue = createQueue({\n\t\t...opts.queue,\n\t\tshouldRetry: shouldRetryProviderError,\n\t\tbaseDelayMs: 500,\n\t})\n\n\treturn {\n\t\tasync read(adapter, query) {\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, query)\n\n\t\t\tconst { range, clamped } = clampRange(\n\t\t\t\tquery.dateRange,\n\t\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\t\tquery.timezone\n\t\t\t)\n\t\t\tconst q = clamped ? { ...query, dateRange: range } : query\n\t\t\tconst key = buildCacheKey(adapter.id, q)\n\t\t\treturn coalesce(key, async () => {\n\t\t\t\tlet fresh: AnalyticsResult\n\t\t\t\tconst controller = new AbortController()\n\t\t\t\tconst timer = setTimeout(\n\t\t\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\t\t\topts.timeoutMs\n\t\t\t\t)\n\t\t\t\ttimer.unref?.()\n\t\t\t\ttry {\n\t\t\t\t\tconst cached = await opts.store.get<AnalyticsResult>(key)\n\t\t\t\t\tif (cached) return cached\n\n\t\t\t\t\t// Races the queued attempt itself, not just its backoff waits, so a signal-blind\n\t\t\t\t\t// adapter (one that never checks ctx.signal) still bounds the read at timeoutMs.\n\t\t\t\t\t// The orphaned attempt keeps its queue slot until the underlying client gives up;\n\t\t\t\t\t// this only bounds how long read() waits for it.\n\t\t\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\t\t\tonce: true,\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\tconst attempt = queue.run(async () => {\n\t\t\t\t\t\tconst release = await limiterFor(limiters, adapter).take(controller.signal)\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await adapter.query(q, { signal: controller.signal })\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trelease()\n\t\t\t\t\t\t}\n\t\t\t\t\t}, controller.signal)\n\t\t\t\t\tattempt.catch(() => {})\n\t\t\t\t\tfresh = await Promise.race([attempt, aborted])\n\t\t\t\t} catch (err) {\n\t\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst stale = await opts.store.getStale<AnalyticsResult>(key)\n\t\t\t\t\t\tif (stale) return { ...stale, meta: { ...stale.meta, stale: true } }\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A broken store fails getStale too; surface the original read error, not this one.\n\t\t\t\t\t}\n\t\t\t\t\tthrow err\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t}\n\t\t\t\tconst result: AnalyticsResult = clamped\n\t\t\t\t\t? { ...fresh, meta: { ...fresh.meta, clamped: true } }\n\t\t\t\t\t: fresh\n\t\t\t\t// `goalsUnresolved` is always a failure to resolve, whatever hint the read carried:\n\t\t\t\t// a scope with no goals answers empty rows unflagged. At the aggregate TTL one\n\t\t\t\t// transient error would pin \"no conversions\" for an hour. A direct engine caller\n\t\t\t\t// that never hints is flagged on every read and so stays at the short TTL.\n\t\t\t\tconst degraded = result.meta.goalsUnresolved === true\n\t\t\t\tconst ttl = degraded\n\t\t\t\t\t? (opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime)\n\t\t\t\t\t: (opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate)\n\t\t\t\tawait opts.store.set(key, result, ttl)\n\t\t\t\treturn result\n\t\t\t})\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAM,SAAS;AAEf,M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;KACxD,WAAW,OAAO,iBAAiB,eAAe,OAAO,WAAW,OAAO,MAAM,GAAG,EACnF,MAAM,KACP,CAAC;IACF,CAAC;IACD,MAAM,UAAU,MAAM,IAAI,YAAY;KACrC,MAAM,UAAU,MAAM,WAAW,UAAU,OAAO,EAAE,KAAK,WAAW,MAAM;KAC1E,IAAI;MACH,OAAO,MAAM,QAAQ,MAAM,GAAG,EAAE,QAAQ,WAAW,OAAO,CAAC;KAC5D,UAAU;MACT,QAAQ;KACT;IACD,GAAG,WAAW,MAAM;IACpB,QAAQ,YAAY,CAAC,CAAC;IACtB,QAAQ,MAAM,QAAQ,KAAK,CAAC,SAAS,OAAO,CAAC;GAC9C,SAAS,KAAK;IACb,KAAK,UAAU,KAAK,QAAQ,EAAE;IAC9B,IAAI;KACH,MAAM,QAAQ,MAAM,KAAK,MAAM,SAA0B,GAAG;KAC5D,IAAI,OAAO,OAAO;MAAE,GAAG;MAAO,MAAM;OAAE,GAAG,MAAM;OAAM,OAAO;MAAK;KAAE;IACpE,QAAQ,CAER;IACA,MAAM;GACP,UAAU;IACT,aAAa,KAAK;GACnB;GACA,MAAM,SAA0B,UAC7B;IAAE,GAAG;IAAO,MAAM;KAAE,GAAG,MAAM;KAAM,SAAS;IAAK;GAAE,IACnD;GAMH,MAAM,MADW,OAAO,KAAK,oBAAoB,OAE7C,KAAK,IAAI,YAAY,QAAQ,aAAa,eAAe,WACzD,KAAK,IAAI,aAAa,QAAQ,aAAa,eAAe;GAC9D,MAAM,KAAK,MAAM,IAAI,KAAK,QAAQ,GAAG;GACrC,OAAO;EACR,CAAC;CACF,EACD;AACD"}
@@ -4,7 +4,6 @@ const capabilities = {
4
4
  perPageQuery: true,
5
5
  realtime: true,
6
6
  realtimeWindowMinutes: 5,
7
- comparison: true,
8
7
  minGranularity: "minute",
9
8
  maxLookbackDays: null,
10
9
  metrics: new Set([
@@ -1 +1 @@
1
- {"version":3,"file":"memoryAdapter.js","names":[],"sources":["../../src/testing/memoryAdapter.ts"],"sourcesContent":["import { ProviderHttpError } from '../adapters/http/fetchJson'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\n\ninterface MemoryEvent {\n\tpath: string\n\ttimestamp: Date\n\tvisitor?: string\n}\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set(['page', 'referrer', 'country', 'device'])\n\nconst capabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 5,\n\tcomparison: true,\n\tminGranularity: 'minute',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page']),\n\tfilterOperators: new Set(['eq']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n}\n\nexport interface MemoryAnalyticsAdapter extends AnalyticsAdapter {\n\trecord(event: MemoryEvent): void\n\treset(): void\n\t/** Test seam for engine resilience: the next query() call rejects with err, then resets. */\n\tfailNext(err?: Error): void\n}\n\nexport function memoryAdapter(): MemoryAnalyticsAdapter {\n\tconst events: MemoryEvent[] = []\n\tlet pendingFailure: Error | undefined\n\n\t// Only page has a backing MemoryEvent field; other declared dimensions drop as unsupported.\n\tconst matchesFilters = (e: MemoryEvent, q: AnalyticsQuery): boolean =>\n\t\t(q.filters ?? []).every((filter) => {\n\t\t\tif (filter.dimension !== 'page' || filter.operator !== 'eq') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn e.path === filter.value\n\t\t})\n\n\tconst inRange = (e: MemoryEvent, q: AnalyticsQuery): boolean => {\n\t\tif (q.path && e.path !== q.path) return false\n\t\tif (!matchesFilters(e, q)) return false\n\t\treturn e.timestamp >= q.dateRange.start && e.timestamp <= q.dateRange.end\n\t}\n\n\treturn {\n\t\tid: 'memory',\n\t\tlabel: 'In-memory (testing)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\trecord: (event) => {\n\t\t\tevents.push(event)\n\t\t},\n\t\treset: () => {\n\t\t\tevents.length = 0\n\t\t},\n\t\tfailNext: (err) => {\n\t\t\tpendingFailure = err ?? new ProviderHttpError(500, 'memory', 'memory: injected failure')\n\t\t},\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (pendingFailure) {\n\t\t\t\tconst err = pendingFailure\n\t\t\t\tpendingFailure = undefined\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst matched = events.filter((e) => inRange(e, q))\n\t\t\tconst countVisitors = (list: MemoryEvent[]): number =>\n\t\t\t\tnew Set(list.map((e) => e.visitor ?? e.path + e.timestamp.toDateString())).size\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst byDay = new Map<string, MemoryEvent[]>()\n\t\t\t\tfor (const e of matched) {\n\t\t\t\t\tconst day = new Date(\n\t\t\t\t\t\tDate.UTC(\n\t\t\t\t\t\t\te.timestamp.getUTCFullYear(),\n\t\t\t\t\t\t\te.timestamp.getUTCMonth(),\n\t\t\t\t\t\t\te.timestamp.getUTCDate()\n\t\t\t\t\t\t)\n\t\t\t\t\t).toISOString()\n\t\t\t\t\tconst list = byDay.get(day) ?? []\n\t\t\t\t\tlist.push(e)\n\t\t\t\t\tbyDay.set(day, list)\n\t\t\t\t}\n\t\t\t\tconst rows = [...byDay.entries()]\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([day, list]) => ({\n\t\t\t\t\t\ttimestamp: day,\n\t\t\t\t\t\tmetrics: { pageviews: list.length, visitors: countVisitors(list) },\n\t\t\t\t\t}))\n\t\t\t\treturn {\n\t\t\t\t\trows,\n\t\t\t\t\ttotals: { pageviews: matched.length, visitors: countVisitors(matched) },\n\t\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst pageviews = matched.length\n\t\t\tconst visitors = countVisitors(matched)\n\t\t\treturn {\n\t\t\t\trows: [{ metrics: { pageviews, visitors } }],\n\t\t\t\ttotals: { pageviews, visitors },\n\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;AA2BA,MAAM,eAAsC;CAC3C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB,SAAA,IAjB2C,IAAI;EAC/C;EACA;EACA;EACA;EACA;EACA;CACD,CAUO;CACN,YAAA,IAViD,IAAI;EAAC;EAAQ;EAAY;EAAW;CAAQ,CAUpF;CACT,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC;CACzB,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;CAC/B,iBAAiB;CACjB,WAAW;CACX,gBAAgB;EAAE,UAAU;EAAK,WAAW;CAAK;AAClD;AASA,SAAgB,gBAAwC;CACvD,MAAM,SAAwB,CAAC;CAC/B,IAAI;CAGJ,MAAM,kBAAkB,GAAgB,OACtC,EAAE,WAAW,CAAC,GAAG,OAAO,WAAW;EACnC,IAAI,OAAO,cAAc,UAAU,OAAO,aAAa,MACtD,OAAO;EAER,OAAO,EAAE,SAAS,OAAO;CAC1B,CAAC;CAEF,MAAM,WAAW,GAAgB,MAA+B;EAC/D,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO;EACxC,IAAI,CAAC,eAAe,GAAG,CAAC,GAAG,OAAO;EAClC,OAAO,EAAE,aAAa,EAAE,UAAU,SAAS,EAAE,aAAa,EAAE,UAAU;CACvE;CAEA,OAAO;EACN,IAAI;EACJ,OAAO;EACP;EACA,oBAAoB;EACpB,SAAS,UAAU;GAClB,OAAO,KAAK,KAAK;EACl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AC;IAC3C,QAAQ;KAAE;KAAW;IAAS;IAC9B,MAAM;KAAE,UAAU;KAAU,WAAW,EAAE,UAAU,IAAI,YAAY;IAAE;GACtE;EACD;CACD;AACD"}
1
+ {"version":3,"file":"memoryAdapter.js","names":[],"sources":["../../src/testing/memoryAdapter.ts"],"sourcesContent":["import { ProviderHttpError } from '../adapters/http/fetchJson'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\n\ninterface MemoryEvent {\n\tpath: string\n\ttimestamp: Date\n\tvisitor?: string\n}\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set(['page', 'referrer', 'country', 'device'])\n\nconst capabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 5,\n\tminGranularity: 'minute',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page']),\n\tfilterOperators: new Set(['eq']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n}\n\nexport interface MemoryAnalyticsAdapter extends AnalyticsAdapter {\n\trecord(event: MemoryEvent): void\n\treset(): void\n\t/** Test seam for engine resilience: the next query() call rejects with err, then resets. */\n\tfailNext(err?: Error): void\n}\n\nexport function memoryAdapter(): MemoryAnalyticsAdapter {\n\tconst events: MemoryEvent[] = []\n\tlet pendingFailure: Error | undefined\n\n\t// Only page has a backing MemoryEvent field; other declared dimensions drop as unsupported.\n\tconst matchesFilters = (e: MemoryEvent, q: AnalyticsQuery): boolean =>\n\t\t(q.filters ?? []).every((filter) => {\n\t\t\tif (filter.dimension !== 'page' || filter.operator !== 'eq') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn e.path === filter.value\n\t\t})\n\n\tconst inRange = (e: MemoryEvent, q: AnalyticsQuery): boolean => {\n\t\tif (q.path && e.path !== q.path) return false\n\t\tif (!matchesFilters(e, q)) return false\n\t\treturn e.timestamp >= q.dateRange.start && e.timestamp <= q.dateRange.end\n\t}\n\n\treturn {\n\t\tid: 'memory',\n\t\tlabel: 'In-memory (testing)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\trecord: (event) => {\n\t\t\tevents.push(event)\n\t\t},\n\t\treset: () => {\n\t\t\tevents.length = 0\n\t\t},\n\t\tfailNext: (err) => {\n\t\t\tpendingFailure = err ?? new ProviderHttpError(500, 'memory', 'memory: injected failure')\n\t\t},\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (pendingFailure) {\n\t\t\t\tconst err = pendingFailure\n\t\t\t\tpendingFailure = undefined\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst matched = events.filter((e) => inRange(e, q))\n\t\t\tconst countVisitors = (list: MemoryEvent[]): number =>\n\t\t\t\tnew Set(list.map((e) => e.visitor ?? e.path + e.timestamp.toDateString())).size\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst byDay = new Map<string, MemoryEvent[]>()\n\t\t\t\tfor (const e of matched) {\n\t\t\t\t\tconst day = new Date(\n\t\t\t\t\t\tDate.UTC(\n\t\t\t\t\t\t\te.timestamp.getUTCFullYear(),\n\t\t\t\t\t\t\te.timestamp.getUTCMonth(),\n\t\t\t\t\t\t\te.timestamp.getUTCDate()\n\t\t\t\t\t\t)\n\t\t\t\t\t).toISOString()\n\t\t\t\t\tconst list = byDay.get(day) ?? []\n\t\t\t\t\tlist.push(e)\n\t\t\t\t\tbyDay.set(day, list)\n\t\t\t\t}\n\t\t\t\tconst rows = [...byDay.entries()]\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([day, list]) => ({\n\t\t\t\t\t\ttimestamp: day,\n\t\t\t\t\t\tmetrics: { pageviews: list.length, visitors: countVisitors(list) },\n\t\t\t\t\t}))\n\t\t\t\treturn {\n\t\t\t\t\trows,\n\t\t\t\t\ttotals: { pageviews: matched.length, visitors: countVisitors(matched) },\n\t\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst pageviews = matched.length\n\t\t\tconst visitors = countVisitors(matched)\n\t\t\treturn {\n\t\t\t\trows: [{ metrics: { pageviews, visitors } }],\n\t\t\t\ttotals: { pageviews, visitors },\n\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;AA2BA,MAAM,eAAsC;CAC3C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,gBAAgB;CAChB,iBAAiB;CACjB,SAAA,IAhB2C,IAAI;EAC/C;EACA;EACA;EACA;EACA;EACA;CACD,CASO;CACN,YAAA,IATiD,IAAI;EAAC;EAAQ;EAAY;EAAW;CAAQ,CASpF;CACT,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC;CACzB,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;CAC/B,iBAAiB;CACjB,WAAW;CACX,gBAAgB;EAAE,UAAU;EAAK,WAAW;CAAK;AAClD;AASA,SAAgB,gBAAwC;CACvD,MAAM,SAAwB,CAAC;CAC/B,IAAI;CAGJ,MAAM,kBAAkB,GAAgB,OACtC,EAAE,WAAW,CAAC,GAAG,OAAO,WAAW;EACnC,IAAI,OAAO,cAAc,UAAU,OAAO,aAAa,MACtD,OAAO;EAER,OAAO,EAAE,SAAS,OAAO;CAC1B,CAAC;CAEF,MAAM,WAAW,GAAgB,MAA+B;EAC/D,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO;EACxC,IAAI,CAAC,eAAe,GAAG,CAAC,GAAG,OAAO;EAClC,OAAO,E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UAAU,IAAI,YAAY;KAAE;IACtE;GACD;GACA,MAAM,YAAY,QAAQ;GAC1B,MAAM,WAAW,cAAc,OAAO;GACtC,OAAO;IACN,MAAM,CAAC,EAAE,SAAS;KAAE;KAAW;IAAS,EAAE,CAAC;IAC3C,QAAQ;KAAE;KAAW;IAAS;IAC9B,MAAM;KAAE,UAAU;KAAU,WAAW,EAAE,UAAU,IAAI,YAAY;IAAE;GACtE;EACD;CACD;AACD"}
@@ -45,22 +45,22 @@ const sameLocalDay = (date, ymd, tz) => {
45
45
  * offsets, so the candidate that still falls on `ymd` (the transition instant, local
46
46
  * 01:00) is taken instead of the refined one that fell back onto the previous day.
47
47
  */
48
- const zonedMidnight = (ymd, tz) => {
48
+ const startOfCalendarDayInTz = (ymd, tz = "UTC") => {
49
49
  const asUtc = Date.UTC(ymd.year, ymd.month - 1, ymd.day);
50
50
  const guess = new Date(asUtc - offsetMs(new Date(asUtc), tz));
51
51
  const refined = new Date(asUtc - offsetMs(guess, tz));
52
52
  if (sameLocalDay(refined, ymd, tz)) return refined;
53
53
  if (sameLocalDay(guess, ymd, tz)) return guess;
54
- return zonedMidnight(zonedParts(refined.getTime() > guess.getTime() ? refined : guess, tz), tz);
54
+ return startOfCalendarDayInTz(zonedParts(refined.getTime() > guess.getTime() ? refined : guess, tz), tz);
55
55
  };
56
56
  /** Start of `date`'s local day in `tz`. */
57
57
  const startOfDayInTz = (date, tz = "UTC") => {
58
- return zonedMidnight(zonedParts(date, tz), tz);
58
+ return startOfCalendarDayInTz(zonedParts(date, tz), tz);
59
59
  };
60
60
  /** Start of `date`'s local month in `tz`. */
61
61
  const startOfMonthInTz = (date, tz = "UTC") => {
62
62
  const p = zonedParts(date, tz);
63
- return zonedMidnight({
63
+ return startOfCalendarDayInTz({
64
64
  year: p.year,
65
65
  month: p.month,
66
66
  day: 1
@@ -68,7 +68,7 @@ const startOfMonthInTz = (date, tz = "UTC") => {
68
68
  };
69
69
  /** Start of `date`'s local year in `tz`. */
70
70
  const startOfYearInTz = (date, tz = "UTC") => {
71
- return zonedMidnight({
71
+ return startOfCalendarDayInTz({
72
72
  year: zonedParts(date, tz).year,
73
73
  month: 1,
74
74
  day: 1
@@ -95,6 +95,17 @@ const startOfWeekInTz = (date, tz = "UTC") => {
95
95
  };
96
96
  /** ISO string of `date`'s local day start in `tz`; the canonical day-bucket key. */
97
97
  const zonedDayIso = (date, tz = "UTC") => startOfDayInTz(date, tz).toISOString();
98
+ /**
99
+ * `date`'s local calendar date in `tz` as `YYYY-MM-DD`, the form day-granular provider APIs
100
+ * take. Not `zonedDayIso(...).slice(0, 10)`: that returns the UTC spelling of the local day
101
+ * start, which names the previous calendar day for every zone east of UTC.
102
+ */
103
+ const zonedCalendarDay = (date, tz = "UTC") => {
104
+ const p = zonedParts(date, tz);
105
+ const month = String(p.month).padStart(2, "0");
106
+ const day = String(p.day).padStart(2, "0");
107
+ return `${String(p.year).padStart(4, "0")}-${month}-${day}`;
108
+ };
98
109
  /** True when `tz` is a resolvable IANA identifier. */
99
110
  const isValidTimeZone = (tz) => {
100
111
  try {
@@ -105,6 +116,6 @@ const isValidTimeZone = (tz) => {
105
116
  }
106
117
  };
107
118
  //#endregion
108
- export { addDaysInTz, isValidTimeZone, startOfDayInTz, startOfMonthInTz, startOfWeekInTz, startOfYearInTz, zonedDayIso };
119
+ export { addDaysInTz, isValidTimeZone, startOfCalendarDayInTz, startOfDayInTz, startOfMonthInTz, startOfWeekInTz, startOfYearInTz, zonedCalendarDay, zonedDayIso };
109
120
 
110
121
  //# sourceMappingURL=tz.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tz.js","names":[],"sources":["../../src/timeframe/tz.ts"],"sourcesContent":["/**\n * IANA-timezone day math, built on `Intl.DateTimeFormat` so there is no dependency.\n * All reporting boundaries (timeframe windows, series axes, native rollup buckets,\n * cache-key day snaps) resolve through these helpers. `startOfDayInTz(d, 'UTC')` is\n * exactly the previous `Date.UTC(...)` day floor, so the default path is unchanged.\n */\n\nexport const DEFAULT_TIMEZONE = 'UTC'\n\ninterface ZonedParts {\n\tyear: number\n\tmonth: number\n\tday: number\n\thour: number\n\tminute: number\n\tsecond: number\n}\n\n// Constructing Intl.DateTimeFormat dominates the cost of these helpers (~14x), and they\n// run per event at ingest and in series loops, so formatters are cached per zone.\nconst formatterCache = new Map<string, Intl.DateTimeFormat>()\n\nconst partsFormatter = (tz: string): Intl.DateTimeFormat => {\n\tlet formatter = formatterCache.get(tz)\n\tif (!formatter) {\n\t\tformatter = new Intl.DateTimeFormat('en-US', {\n\t\t\ttimeZone: tz,\n\t\t\thourCycle: 'h23',\n\t\t\tyear: 'numeric',\n\t\t\tmonth: '2-digit',\n\t\t\tday: '2-digit',\n\t\t\thour: '2-digit',\n\t\t\tminute: '2-digit',\n\t\t\tsecond: '2-digit',\n\t\t})\n\t\tformatterCache.set(tz, formatter)\n\t}\n\treturn formatter\n}\n\n/** Wall-clock parts `date` maps to in `tz`. */\nconst zonedParts = (date: Date, tz: string): ZonedParts => {\n\tconst map: Record<string, string> = {}\n\tfor (const part of partsFormatter(tz).formatToParts(date)) {\n\t\tif (part.type !== 'literal') {\n\t\t\tmap[part.type] = part.value\n\t\t}\n\t}\n\treturn {\n\t\tyear: Number(map.year),\n\t\tmonth: Number(map.month),\n\t\tday: Number(map.day),\n\t\thour: Number(map.hour),\n\t\tminute: Number(map.minute),\n\t\tsecond: Number(map.second),\n\t}\n}\n\n/** Milliseconds `tz` is ahead of UTC at `date` (positive east of UTC). */\nconst offsetMs = (date: Date, tz: string): number => {\n\tconst p = zonedParts(date, tz)\n\tconst asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second)\n\t// formatToParts drops sub-second precision, so compare against the truncated instant.\n\treturn asUtc - Math.floor(date.getTime() / 1000) * 1000\n}\n\nconst sameLocalDay = (\n\tdate: Date,\n\tymd: { year: number; month: number; day: number },\n\ttz: string\n): boolean => {\n\tconst p = zonedParts(date, tz)\n\treturn p.year === ymd.year && p.month === ymd.month && p.day === ymd.day\n}\n\n/**\n * The first instant of a wall-clock calendar date in `tz`. Usually local midnight; when a\n * spring-forward transition lands exactly at midnight (Chile, Cuba) the 00:00 wall clock\n * does not exist and the refinement below oscillates between the pre- and post-transition\n * offsets, so the candidate that still falls on `ymd` (the transition instant, local\n * 01:00) is taken instead of the refined one that fell back onto the previous day.\n */\nconst zonedMidnight = (ymd: { year: number; month: number; day: number }, tz: string): Date => {\n\tconst asUtc = Date.UTC(ymd.year, ymd.month - 1, ymd.day)\n\tconst guess = new Date(asUtc - offsetMs(new Date(asUtc), tz))\n\tconst refined = new Date(asUtc - offsetMs(guess, tz))\n\tif (sameLocalDay(refined, ymd, tz)) {\n\t\treturn refined\n\t}\n\tif (sameLocalDay(guess, ymd, tz)) {\n\t\treturn guess\n\t}\n\t// Neither candidate lands on ymd (the calendar date was skipped entirely, e.g. a\n\t// dateline change): fall forward to the later candidate's day start.\n\tconst later = refined.getTime() > guess.getTime() ? refined : guess\n\treturn zonedMidnight(zonedParts(later, tz), tz)\n}\n\n/** Start of `date`'s local day in `tz`. */\nexport const startOfDayInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn zonedMidnight(p, tz)\n}\n\n/** Start of `date`'s local month in `tz`. */\nexport const startOfMonthInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn zonedMidnight({ year: p.year, month: p.month, day: 1 }, tz)\n}\n\n/** Start of `date`'s local year in `tz`. */\nexport const startOfYearInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn zonedMidnight({ year: p.year, month: 1, day: 1 }, tz)\n}\n\n/**\n * Add `days` calendar days to `date`'s local day in `tz`, returning the resulting day\n * start. The +12h buffer before re-flooring absorbs 23/25-hour DST days so stepping\n * never lands short of, or past, the intended calendar day.\n */\nexport const addDaysInTz = (date: Date, days: number, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst start = startOfDayInTz(date, tz)\n\treturn startOfDayInTz(new Date(start.getTime() + days * 86_400_000 + 43_200_000), tz)\n}\n\n/**\n * Start of the ISO week (Monday) containing `date`'s local day in `tz`. The weekday of a\n * calendar Y-M-D is timezone-independent, so it is derived from the zoned date and the\n * step back to Monday runs through `addDaysInTz` to stay DST-safe.\n */\nexport const startOfWeekInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\tconst dow = new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay()\n\tconst mondayIndex = (dow + 6) % 7\n\treturn addDaysInTz(startOfDayInTz(date, tz), -mondayIndex, tz)\n}\n\n/** ISO string of `date`'s local day start in `tz`; the canonical day-bucket key. */\nexport const zonedDayIso = (date: Date, tz: string = DEFAULT_TIMEZONE): string =>\n\tstartOfDayInTz(date, tz).toISOString()\n\n/** True when `tz` is a resolvable IANA identifier. */\nexport const isValidTimeZone = (tz: string): boolean => {\n\ttry {\n\t\tnew Intl.DateTimeFormat('en-US', { timeZone: tz })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n"],"mappings":"AAoBA,MAAM,iCAAiB,IAAI,IAAiC;AAE5D,MAAM,kBAAkB,OAAoC;CAC3D,IAAI,YAAY,eAAe,IAAI,EAAE;CACrC,IAAI,CAAC,WAAW;EACf,YAAY,IAAI,KAAK,eAAe,SAAS;GAC5C,UAAU;GACV,WAAW;GACX,MAAM;GACN,OAAO;GACP,KAAK;GACL,MAAM;GACN,QAAQ;GACR,QAAQ;EACT,CAAC;EACD,eAAe,IAAI,IAAI,SAAS;CACjC;CACA,OAAO;AACR;;AAGA,MAAM,cAAc,MAAY,OAA2B;CAC1D,MAAM,MAA8B,CAAC;CACrC,KAAK,MAAM,QAAQ,eAAe,EAAE,EAAE,cAAc,IAAI,GACvD,IAAI,KAAK,SAAS,WACjB,IAAI,KAAK,QAAQ,KAAK;CAGxB,OAAO;EACN,MAAM,OAAO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AM,OAAO,EAAE;EAAO,KAAK;CAAE,GAAG,EAAE;AAClE;;AAGA,MAAa,mBAAmB,MAAY,KAAA,UAAwC;CAEnF,OAAO,cAAc;EAAE,MADb,WAAW,MAAM,EACE,EAAE;EAAM,OAAO;EAAG,KAAK;CAAE,GAAG,EAAE;AAC5D;;;;;;AAOA,MAAa,eAAe,MAAY,MAAc,KAAA,UAAwC;CAC7F,MAAM,QAAQ,eAAe,MAAM,EAAE;CACrC,OAAO,eAAe,IAAI,KAAK,MAAM,QAAQ,IAAI,OAAO,QAAa,KAAU,GAAG,EAAE;AACrF;;;;;;AAOA,MAAa,mBAAmB,MAAY,KAAA,UAAwC;CACnF,MAAM,IAAI,WAAW,MAAM,EAAE;CAE7B,MAAM,eADM,IAAI,KAAK,KAAK,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAG,EAAE,GAAG,CAAC,EAAE,UACpC,IAAI,KAAK;CAChC,OAAO,YAAY,eAAe,MAAM,EAAE,GAAG,CAAC,aAAa,EAAE;AAC9D;;AAGA,MAAa,eAAe,MAAY,KAAA,UACvC,eAAe,MAAM,EAAE,EAAE,YAAY;;AAGtC,MAAa,mBAAmB,OAAwB;CACvD,IAAI;EACH,IAAI,KAAK,eAAe,SAAS,EAAE,UAAU,GAAG,CAAC;EACjD,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD"}
1
+ {"version":3,"file":"tz.js","names":[],"sources":["../../src/timeframe/tz.ts"],"sourcesContent":["/**\n * IANA-timezone day math, built on `Intl.DateTimeFormat` so there is no dependency.\n * All reporting boundaries (timeframe windows, series axes, native rollup buckets,\n * cache-key day snaps) resolve through these helpers. `startOfDayInTz(d, 'UTC')` is\n * exactly the previous `Date.UTC(...)` day floor, so the default path is unchanged.\n */\n\nexport const DEFAULT_TIMEZONE = 'UTC'\n\ninterface ZonedParts {\n\tyear: number\n\tmonth: number\n\tday: number\n\thour: number\n\tminute: number\n\tsecond: number\n}\n\n// Constructing Intl.DateTimeFormat dominates the cost of these helpers (~14x), and they\n// run per event at ingest and in series loops, so formatters are cached per zone.\nconst formatterCache = new Map<string, Intl.DateTimeFormat>()\n\nconst partsFormatter = (tz: string): Intl.DateTimeFormat => {\n\tlet formatter = formatterCache.get(tz)\n\tif (!formatter) {\n\t\tformatter = new Intl.DateTimeFormat('en-US', {\n\t\t\ttimeZone: tz,\n\t\t\thourCycle: 'h23',\n\t\t\tyear: 'numeric',\n\t\t\tmonth: '2-digit',\n\t\t\tday: '2-digit',\n\t\t\thour: '2-digit',\n\t\t\tminute: '2-digit',\n\t\t\tsecond: '2-digit',\n\t\t})\n\t\tformatterCache.set(tz, formatter)\n\t}\n\treturn formatter\n}\n\n/** Wall-clock parts `date` maps to in `tz`. */\nconst zonedParts = (date: Date, tz: string): ZonedParts => {\n\tconst map: Record<string, string> = {}\n\tfor (const part of partsFormatter(tz).formatToParts(date)) {\n\t\tif (part.type !== 'literal') {\n\t\t\tmap[part.type] = part.value\n\t\t}\n\t}\n\treturn {\n\t\tyear: Number(map.year),\n\t\tmonth: Number(map.month),\n\t\tday: Number(map.day),\n\t\thour: Number(map.hour),\n\t\tminute: Number(map.minute),\n\t\tsecond: Number(map.second),\n\t}\n}\n\n/** Milliseconds `tz` is ahead of UTC at `date` (positive east of UTC). */\nconst offsetMs = (date: Date, tz: string): number => {\n\tconst p = zonedParts(date, tz)\n\tconst asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second)\n\t// formatToParts drops sub-second precision, so compare against the truncated instant.\n\treturn asUtc - Math.floor(date.getTime() / 1000) * 1000\n}\n\nconst sameLocalDay = (\n\tdate: Date,\n\tymd: { year: number; month: number; day: number },\n\ttz: string\n): boolean => {\n\tconst p = zonedParts(date, tz)\n\treturn p.year === ymd.year && p.month === ymd.month && p.day === ymd.day\n}\n\n/**\n * The first instant of a wall-clock calendar date in `tz`. Usually local midnight; when a\n * spring-forward transition lands exactly at midnight (Chile, Cuba) the 00:00 wall clock\n * does not exist and the refinement below oscillates between the pre- and post-transition\n * offsets, so the candidate that still falls on `ymd` (the transition instant, local\n * 01:00) is taken instead of the refined one that fell back onto the previous day.\n */\nexport const startOfCalendarDayInTz = (\n\tymd: { year: number; month: number; day: number },\n\ttz: string = DEFAULT_TIMEZONE\n): Date => {\n\tconst asUtc = Date.UTC(ymd.year, ymd.month - 1, ymd.day)\n\tconst guess = new Date(asUtc - offsetMs(new Date(asUtc), tz))\n\tconst refined = new Date(asUtc - offsetMs(guess, tz))\n\tif (sameLocalDay(refined, ymd, tz)) {\n\t\treturn refined\n\t}\n\tif (sameLocalDay(guess, ymd, tz)) {\n\t\treturn guess\n\t}\n\t// Neither candidate lands on ymd (the calendar date was skipped entirely, e.g. a\n\t// dateline change): fall forward to the later candidate's day start.\n\tconst later = refined.getTime() > guess.getTime() ? refined : guess\n\treturn startOfCalendarDayInTz(zonedParts(later, tz), tz)\n}\n\n/** Start of `date`'s local day in `tz`. */\nexport const startOfDayInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn startOfCalendarDayInTz(p, tz)\n}\n\n/** Start of `date`'s local month in `tz`. */\nexport const startOfMonthInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn startOfCalendarDayInTz({ year: p.year, month: p.month, day: 1 }, tz)\n}\n\n/** Start of `date`'s local year in `tz`. */\nexport const startOfYearInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\treturn startOfCalendarDayInTz({ year: p.year, month: 1, day: 1 }, tz)\n}\n\n/**\n * Add `days` calendar days to `date`'s local day in `tz`, returning the resulting day\n * start. The +12h buffer before re-flooring absorbs 23/25-hour DST days so stepping\n * never lands short of, or past, the intended calendar day.\n */\nexport const addDaysInTz = (date: Date, days: number, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst start = startOfDayInTz(date, tz)\n\treturn startOfDayInTz(new Date(start.getTime() + days * 86_400_000 + 43_200_000), tz)\n}\n\n/**\n * Start of the ISO week (Monday) containing `date`'s local day in `tz`. The weekday of a\n * calendar Y-M-D is timezone-independent, so it is derived from the zoned date and the\n * step back to Monday runs through `addDaysInTz` to stay DST-safe.\n */\nexport const startOfWeekInTz = (date: Date, tz: string = DEFAULT_TIMEZONE): Date => {\n\tconst p = zonedParts(date, tz)\n\tconst dow = new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay()\n\tconst mondayIndex = (dow + 6) % 7\n\treturn addDaysInTz(startOfDayInTz(date, tz), -mondayIndex, tz)\n}\n\n/** ISO string of `date`'s local day start in `tz`; the canonical day-bucket key. */\nexport const zonedDayIso = (date: Date, tz: string = DEFAULT_TIMEZONE): string =>\n\tstartOfDayInTz(date, tz).toISOString()\n\n/**\n * `date`'s local calendar date in `tz` as `YYYY-MM-DD`, the form day-granular provider APIs\n * take. Not `zonedDayIso(...).slice(0, 10)`: that returns the UTC spelling of the local day\n * start, which names the previous calendar day for every zone east of UTC.\n */\nexport const zonedCalendarDay = (date: Date, tz: string = DEFAULT_TIMEZONE): string => {\n\tconst p = zonedParts(date, tz)\n\tconst month = String(p.month).padStart(2, '0')\n\tconst day = String(p.day).padStart(2, '0')\n\treturn `${String(p.year).padStart(4, '0')}-${month}-${day}`\n}\n\n/** True when `tz` is a resolvable IANA identifier. */\nexport const isValidTimeZone = (tz: string): boolean => {\n\ttry {\n\t\tnew Intl.DateTimeFormat('en-US', { timeZone: tz })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n"],"mappings":"AAoBA,MAAM,iCAAiB,IAAI,IAAiC;AAE5D,MAAM,kBAAkB,OAAoC;CAC3D,IAAI,YAAY,eAAe,IAAI,EAAE;CACrC,IAAI,CAAC,WAAW;EACf,YAAY,IAAI,KAAK,eAAe,SAAS;GAC5C,UAAU;GACV,WAAW;GACX,MAAM;GACN,OAAO;GACP,KAAK;GACL,MAAM;GACN,QAAQ;GACR,QAAQ;EACT,CAAC;EACD,eAAe,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G;AACvD;;AAGA,MAAa,mBAAmB,OAAwB;CACvD,IAAI;EACH,IAAI,KAAK,eAAe,SAAS,EAAE,UAAU,GAAG,CAAC;EACjD,OAAO;CACR,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -2,6 +2,7 @@ import { createAutoCapture } from "./autoCapture.js";
2
2
  import { createConsentQueue, readConsent, writeConsent } from "./consent.js";
3
3
  import { createScriptLoader } from "./loadScript.js";
4
4
  import { createPageTracking } from "./pageTracking.js";
5
+ import { createGa4Sink } from "./sinks/ga4.js";
5
6
  import { createNativeSink } from "./sinks/native.js";
6
7
  import { createPlausibleSink } from "./sinks/plausible.js";
7
8
  import { createPosthogSink } from "./sinks/posthog.js";
@@ -34,6 +35,7 @@ const buildSink = (args) => {
34
35
  case "posthog": return createPosthogSink(vendor);
35
36
  case "plausible": return createPlausibleSink(vendor);
36
37
  case "umami": return createUmamiSink(vendor);
38
+ case "ga4": return createGa4Sink(vendor);
37
39
  }
38
40
  };
39
41
  /**
@@ -90,10 +92,20 @@ const createTracker = (config, options = {}) => {
90
92
  hostname: win.location.hostname,
91
93
  ...win.document.referrer ? { referrer: win.document.referrer } : {}
92
94
  });
95
+ /**
96
+ * Pageviews only: it exists so ingest can extract the campaign keys, and an event fired
97
+ * later in the page's life would attribute the same visit twice.
98
+ */
99
+ const query = () => {
100
+ if (config.autoCapture.query === false) return {};
101
+ const search = win.location.search.replace(/^\?/, "").slice(0, 512);
102
+ return search ? { query: search } : {};
103
+ };
93
104
  const page = () => {
94
105
  dispatch({
95
106
  type: "pageview",
96
- ...context()
107
+ ...context(),
108
+ ...query()
97
109
  });
98
110
  auto?.resetPage();
99
111
  };
@@ -1 +1 @@
1
- {"version":3,"file":"createTracker.js","names":[],"sources":["../../src/tracker/createTracker.ts"],"sourcesContent":["import type { TrackerConfig, TrackerSlotConfig } from '../capture/trackerConfig'\nimport { type AutoCapture, createAutoCapture } from './autoCapture'\nimport { createConsentQueue, readConsent, writeConsent } from './consent'\nimport { createScriptLoader } from './loadScript'\nimport { createPageTracking } from './pageTracking'\nimport { createNativeSink } from './sinks/native'\nimport { createPlausibleSink } from './sinks/plausible'\nimport { createPosthogSink } from './sinks/posthog'\nimport { createUmamiSink } from './sinks/umami'\nimport type {\n\tConsentState,\n\tLoadScript,\n\tSink,\n\tTracker,\n\tTrackerEvent,\n\tTrackerOptions,\n\tTrackerWindow,\n} from './types'\n\n/** Stand-in for a host with no DOM (server rendering, a worker). Every call is a no-op. */\nexport const createNoopTracker = (): Tracker => ({\n\tpage: () => undefined,\n\ttrack: () => undefined,\n\ttrackGoal: () => undefined,\n\tconsent: () => undefined,\n\tflush: () => undefined,\n\tdestroy: () => undefined,\n})\n\nconst buildSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\tscrollDepth: () => number | undefined\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, scrollDepth } = args\n\tconst vendor = { slot: slot.slot, win, scripts: slot.snippet.scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath, scrollDepth })\n\t\tcase 'posthog':\n\t\t\treturn createPosthogSink(vendor)\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t}\n}\n\n/**\n * The browser tracker: one sink per capture slot, a consent gate in front of the slots the\n * server marked as gated, SPA page tracking, and the auto-capture listeners.\n *\n * Every event fans out to every slot; there is no dual-write of one slot's events into\n * another. The config is a server-rendered snapshot, so an unknown goal slug is still sent:\n * the server may know goals the snapshot predates.\n */\nexport const createTracker = (config: TrackerConfig, options: TrackerOptions = {}): Tracker => {\n\tconst win = options.window ?? (globalThis as { window?: TrackerWindow }).window\n\tif (!win) {\n\t\treturn createNoopTracker()\n\t}\n\tconst persist = options.persistConsent !== false\n\tconst loadScript = options.loadScript ?? createScriptLoader(win, options.nonce)\n\tconst queue = createConsentQueue<{ sink: Sink; event: TrackerEvent }>()\n\tlet auto: AutoCapture | null = null\n\tlet state: ConsentState | null = persist ? readConsent(win) : null\n\n\tconst entries = config.slots.map((slot) => ({\n\t\trequiresConsent: slot.requiresConsent,\n\t\tsink: buildSink({\n\t\t\tslot,\n\t\t\twin,\n\t\t\tloadScript,\n\t\t\tingestPath: config.ingestPath,\n\t\t\tscrollDepth: () => auto?.scrollDepth(),\n\t\t}),\n\t}))\n\n\tconst load = (sink: Sink) => {\n\t\tvoid sink.ready().catch(() => undefined)\n\t}\n\n\t/**\n\t * Slots are isolated from each other and from the caller: a vendor global that throws,\n\t * or an event that cannot be serialized, must not skip the remaining slots or escape\n\t * into the host's click handler.\n\t */\n\tconst guard = (run: () => void) => {\n\t\ttry {\n\t\t\trun()\n\t\t} catch {\n\t\t\t// Dropped, like every other delivery failure.\n\t\t}\n\t}\n\n\tconst deliver = (sink: Sink, event: TrackerEvent) => {\n\t\tguard(() => sink.send(event))\n\t}\n\n\tconst dispatch = (event: TrackerEvent) => {\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.requiresConsent || state === 'granted') {\n\t\t\t\tdeliver(entry.sink, event)\n\t\t\t} else if (state !== 'denied') {\n\t\t\t\tqueue.push({ sink: entry.sink, event })\n\t\t\t}\n\t\t}\n\t}\n\n\tconst context = (): Pick<TrackerEvent, 'path' | 'hostname' | 'referrer'> => ({\n\t\tpath: win.location.pathname,\n\t\thostname: win.location.hostname,\n\t\t...(win.document.referrer ? { referrer: win.document.referrer } : {}),\n\t})\n\n\tconst page = () => {\n\t\tdispatch({ type: 'pageview', ...context() })\n\t\tauto?.resetPage()\n\t}\n\n\tconst track = (name: string, props?: Record<string, unknown>) => {\n\t\tdispatch({ type: 'event', name, ...context(), ...(props ? { props } : {}) })\n\t}\n\n\tconst trackGoal = (slug: string, opts?: { value?: number; currency?: string }) => {\n\t\tconst goal = config.goals.find((candidate) => candidate.slug === slug)\n\t\tconst value = opts?.value ?? goal?.value?.fixed\n\t\tconst currency = opts?.currency ?? goal?.currency\n\t\tdispatch({\n\t\t\ttype: 'goal',\n\t\t\tname: slug,\n\t\t\t...context(),\n\t\t\t...(value === undefined ? {} : { value }),\n\t\t\t...(currency === undefined ? {} : { currency }),\n\t\t})\n\t}\n\n\tconst flush = () => {\n\t\tfor (const entry of entries) {\n\t\t\tguard(() => entry.sink.flush?.())\n\t\t}\n\t}\n\n\tauto = createAutoCapture({\n\t\twin,\n\t\toptions: config.autoCapture,\n\t\thandlers: { track, trackGoal },\n\t})\n\tconst pageTracking = createPageTracking(win, page)\n\twin.addEventListener('pagehide', flush)\n\n\tfor (const entry of entries) {\n\t\tif (!entry.requiresConsent || state === 'granted') {\n\t\t\tload(entry.sink)\n\t\t}\n\t}\n\tpage()\n\n\treturn {\n\t\tpage,\n\t\ttrack,\n\t\ttrackGoal,\n\t\tflush,\n\t\tconsent(next) {\n\t\t\tstate = next\n\t\t\tif (persist) {\n\t\t\t\twriteConsent(win, next)\n\t\t\t}\n\t\t\tif (next === 'denied') {\n\t\t\t\tqueue.clear()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.requiresConsent) {\n\t\t\t\t\tload(entry.sink)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const queued of queue.drain()) {\n\t\t\t\tdeliver(queued.sink, queued.event)\n\t\t\t}\n\t\t},\n\t\tdestroy() {\n\t\t\tflush()\n\t\t\tpageTracking.destroy()\n\t\t\tauto?.destroy()\n\t\t\tauto = null\n\t\t\twin.removeEventListener('pagehide', flush)\n\t\t\tqueue.clear()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAa,2BAAoC;CAChD,YAAY,KAAA;CACZ,aAAa,KAAA;CACb,iBAAiB,KAAA;CACjB,eAAe,KAAA;CACf,aAAa,KAAA;CACb,eAAe,KAAA;AAChB;AAEA,MAAM,aAAa,SAMP;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,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IACZ;GACD;GACA,KAAK,MAAM,SAAS,SACnB,IAAI,MAAM,iBACT,KAAK,MAAM,IAAI;GAGjB,KAAK,MAAM,UAAU,MAAM,MAAM,GAChC,QAAQ,OAAO,MAAM,OAAO,KAAK;EAEnC;EACA,UAAU;GACT,MAAM;GACN,aAAa,QAAQ;GACrB,MAAM,QAAQ;GACd,OAAO;GACP,IAAI,oBAAoB,YAAY,KAAK;GACzC,MAAM,MAAM;EACb;CACD;AACD"}
1
+ {"version":3,"file":"createTracker.js","names":[],"sources":["../../src/tracker/createTracker.ts"],"sourcesContent":["import type { TrackerConfig, TrackerSlotConfig } from '../capture/trackerConfig'\nimport { MAX_QUERY_LENGTH } from '../query/limits'\nimport { type AutoCapture, createAutoCapture } from './autoCapture'\nimport { createConsentQueue, readConsent, writeConsent } from './consent'\nimport { createScriptLoader } from './loadScript'\nimport { createPageTracking } from './pageTracking'\nimport { createGa4Sink } from './sinks/ga4'\nimport { createNativeSink } from './sinks/native'\nimport { createPlausibleSink } from './sinks/plausible'\nimport { createPosthogSink } from './sinks/posthog'\nimport { createUmamiSink } from './sinks/umami'\nimport type {\n\tConsentState,\n\tLoadScript,\n\tSink,\n\tTracker,\n\tTrackerEvent,\n\tTrackerOptions,\n\tTrackerWindow,\n} from './types'\n\n/** Stand-in for a host with no DOM (server rendering, a worker). Every call is a no-op. */\nexport const createNoopTracker = (): Tracker => ({\n\tpage: () => undefined,\n\ttrack: () => undefined,\n\ttrackGoal: () => undefined,\n\tconsent: () => undefined,\n\tflush: () => undefined,\n\tdestroy: () => undefined,\n})\n\nconst buildSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\tscrollDepth: () => number | undefined\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, scrollDepth } = args\n\tconst vendor = { slot: slot.slot, win, scripts: slot.snippet.scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath, scrollDepth })\n\t\tcase 'posthog':\n\t\t\treturn createPosthogSink(vendor)\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t\tcase 'ga4':\n\t\t\treturn createGa4Sink(vendor)\n\t}\n}\n\n/**\n * The browser tracker: one sink per capture slot, a consent gate in front of the slots the\n * server marked as gated, SPA page tracking, and the auto-capture listeners.\n *\n * Every event fans out to every slot; there is no dual-write of one slot's events into\n * another. The config is a server-rendered snapshot, so an unknown goal slug is still sent:\n * the server may know goals the snapshot predates.\n */\nexport const createTracker = (config: TrackerConfig, options: TrackerOptions = {}): Tracker => {\n\tconst win = options.window ?? (globalThis as { window?: TrackerWindow }).window\n\tif (!win) {\n\t\treturn createNoopTracker()\n\t}\n\tconst persist = options.persistConsent !== false\n\tconst loadScript = options.loadScript ?? createScriptLoader(win, options.nonce)\n\tconst queue = createConsentQueue<{ sink: Sink; event: TrackerEvent }>()\n\tlet auto: AutoCapture | null = null\n\tlet state: ConsentState | null = persist ? readConsent(win) : null\n\n\tconst entries = config.slots.map((slot) => ({\n\t\trequiresConsent: slot.requiresConsent,\n\t\tsink: buildSink({\n\t\t\tslot,\n\t\t\twin,\n\t\t\tloadScript,\n\t\t\tingestPath: config.ingestPath,\n\t\t\tscrollDepth: () => auto?.scrollDepth(),\n\t\t}),\n\t}))\n\n\tconst load = (sink: Sink) => {\n\t\tvoid sink.ready().catch(() => undefined)\n\t}\n\n\t/**\n\t * Slots are isolated from each other and from the caller: a vendor global that throws,\n\t * or an event that cannot be serialized, must not skip the remaining slots or escape\n\t * into the host's click handler.\n\t */\n\tconst guard = (run: () => void) => {\n\t\ttry {\n\t\t\trun()\n\t\t} catch {\n\t\t\t// Dropped, like every other delivery failure.\n\t\t}\n\t}\n\n\tconst deliver = (sink: Sink, event: TrackerEvent) => {\n\t\tguard(() => sink.send(event))\n\t}\n\n\tconst dispatch = (event: TrackerEvent) => {\n\t\tfor (const entry of entries) {\n\t\t\tif (!entry.requiresConsent || state === 'granted') {\n\t\t\t\tdeliver(entry.sink, event)\n\t\t\t} else if (state !== 'denied') {\n\t\t\t\tqueue.push({ sink: entry.sink, event })\n\t\t\t}\n\t\t}\n\t}\n\n\tconst context = (): Pick<TrackerEvent, 'path' | 'hostname' | 'referrer'> => ({\n\t\tpath: win.location.pathname,\n\t\thostname: win.location.hostname,\n\t\t...(win.document.referrer ? { referrer: win.document.referrer } : {}),\n\t})\n\n\t/**\n\t * Pageviews only: it exists so ingest can extract the campaign keys, and an event fired\n\t * later in the page's life would attribute the same visit twice.\n\t */\n\tconst query = (): Pick<TrackerEvent, 'query'> => {\n\t\t// Absent means on: a tracker config snapshot rendered before the toggle existed must\n\t\t// keep the documented default rather than silently losing campaign attribution.\n\t\tif (config.autoCapture.query === false) {\n\t\t\treturn {}\n\t\t}\n\t\tconst search = win.location.search.replace(/^\\?/, '').slice(0, MAX_QUERY_LENGTH)\n\t\treturn search ? { query: search } : {}\n\t}\n\n\tconst page = () => {\n\t\tdispatch({ type: 'pageview', ...context(), ...query() })\n\t\tauto?.resetPage()\n\t}\n\n\tconst track = (name: string, props?: Record<string, unknown>) => {\n\t\tdispatch({ type: 'event', name, ...context(), ...(props ? { props } : {}) })\n\t}\n\n\tconst trackGoal = (slug: string, opts?: { value?: number; currency?: string }) => {\n\t\tconst goal = config.goals.find((candidate) => candidate.slug === slug)\n\t\tconst value = opts?.value ?? goal?.value?.fixed\n\t\tconst currency = opts?.currency ?? goal?.currency\n\t\tdispatch({\n\t\t\ttype: 'goal',\n\t\t\tname: slug,\n\t\t\t...context(),\n\t\t\t...(value === undefined ? {} : { value }),\n\t\t\t...(currency === undefined ? {} : { currency }),\n\t\t})\n\t}\n\n\tconst flush = () => {\n\t\tfor (const entry of entries) {\n\t\t\tguard(() => entry.sink.flush?.())\n\t\t}\n\t}\n\n\tauto = createAutoCapture({\n\t\twin,\n\t\toptions: config.autoCapture,\n\t\thandlers: { track, trackGoal },\n\t})\n\tconst pageTracking = createPageTracking(win, page)\n\twin.addEventListener('pagehide', flush)\n\n\tfor (const entry of entries) {\n\t\tif (!entry.requiresConsent || state === 'granted') {\n\t\t\tload(entry.sink)\n\t\t}\n\t}\n\tpage()\n\n\treturn {\n\t\tpage,\n\t\ttrack,\n\t\ttrackGoal,\n\t\tflush,\n\t\tconsent(next) {\n\t\t\tstate = next\n\t\t\tif (persist) {\n\t\t\t\twriteConsent(win, next)\n\t\t\t}\n\t\t\tif (next === 'denied') {\n\t\t\t\tqueue.clear()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tif (entry.requiresConsent) {\n\t\t\t\t\tload(entry.sink)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const queued of queue.drain()) {\n\t\t\t\tdeliver(queued.sink, queued.event)\n\t\t\t}\n\t\t},\n\t\tdestroy() {\n\t\t\tflush()\n\t\t\tpageTracking.destroy()\n\t\t\tauto?.destroy()\n\t\t\tauto = null\n\t\t\twin.removeEventListener('pagehide', flush)\n\t\t\tqueue.clear()\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAsBA,MAAa,2BAAoC;CAChD,YAAY,KAAA;CACZ,aAAa,KAAA;CACb,iBAAiB,KAAA;CACjB,eAAe,KAAA;CACf,aAAa,KAAA;CACb,eAAe,KAAA;AAChB;AAEA,MAAM,aAAa,SAMP;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,YAAY,gBAAgB;CAC3D,MAAM,SAAS;EAAE,MAAM,KAAK;EAAM;EAAK,SAAS,KAAK,QAAQ;EAAS;CAAW;CACjF,QAAQ,KAAK,MAAb;EACC,KAAK,UACJ,OAAO,iBAAiB;GAAE,MAAM,KAAK;GAAM;GAAK,KAAK;GAAY;EAAY,CAAC;EAC/E,KAAK,WACJ,OAAO,kBAAkB,MAAM;EAChC,KAAK,aACJ,OAAO,oBAAoB,MAAM;EAClC,KAAK,SACJ,OAAO,gB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AM,iBACT,KAAK,MAAM,IAAI;GAGjB,KAAK,MAAM,UAAU,MAAM,MAAM,GAChC,QAAQ,OAAO,MAAM,OAAO,KAAK;EAEnC;EACA,UAAU;GACT,MAAM;GACN,aAAa,QAAQ;GACrB,MAAM,QAAQ;GACd,OAAO;GACP,IAAI,oBAAoB,YAAY,KAAK;GACzC,MAAM,MAAM;EACb;CACD;AACD"}
@@ -0,0 +1,21 @@
1
+ import { Sink } from "../types.js";
2
+ import { VendorSinkArgs } from "./vendor.js";
3
+
4
+ //#region src/tracker/sinks/ga4.d.ts
5
+ /**
6
+ * Forwards events and goals to `gtag('event', name, params)`, under the name GA4 accepts for
7
+ * them rather than the kebab-case slug: the other vendors take hyphens, GA4 does not. Revenue
8
+ * rides along as the `value` and `currency` params, which is what GA4's own ecommerce reports
9
+ * read. The inline half of the snippet defines `gtag` and its `dataLayer` queue the moment it
10
+ * runs, so calls made before gtag.js lands are replayed by it.
11
+ *
12
+ * Pageviews are dropped by `createVendorSink`, as for every other vendor: `gtag('config', id)`
13
+ * sends the first page view itself, and page views on history changes come from the web data
14
+ * stream's enhanced measurement (https://support.google.com/analytics/answer/9216061), on by
15
+ * default and switchable per stream. An install that turned that option off should turn it
16
+ * back on: this sink forwards no pageview, because on a default stream it would double-count.
17
+ */
18
+ declare const createGa4Sink: (args: VendorSinkArgs) => Sink;
19
+ //#endregion
20
+ export { createGa4Sink };
21
+ //# sourceMappingURL=ga4.d.ts.map
@@ -0,0 +1,26 @@
1
+ import { ga4EventName } from "../../adapters/ga4/eventName.js";
2
+ import { createVendorSink, flatProps, vendorEventName } from "./vendor.js";
3
+ //#region src/tracker/sinks/ga4.ts
4
+ /**
5
+ * Forwards events and goals to `gtag('event', name, params)`, under the name GA4 accepts for
6
+ * them rather than the kebab-case slug: the other vendors take hyphens, GA4 does not. Revenue
7
+ * rides along as the `value` and `currency` params, which is what GA4's own ecommerce reports
8
+ * read. The inline half of the snippet defines `gtag` and its `dataLayer` queue the moment it
9
+ * runs, so calls made before gtag.js lands are replayed by it.
10
+ *
11
+ * Pageviews are dropped by `createVendorSink`, as for every other vendor: `gtag('config', id)`
12
+ * sends the first page view itself, and page views on history changes come from the web data
13
+ * stream's enhanced measurement (https://support.google.com/analytics/answer/9216061), on by
14
+ * default and switchable per stream. An install that turned that option off should turn it
15
+ * back on: this sink forwards no pageview, because on a default stream it would double-count.
16
+ */
17
+ const createGa4Sink = (args) => createVendorSink(args, {
18
+ has: () => typeof args.win.gtag === "function",
19
+ dispatch: (event) => {
20
+ args.win.gtag?.("event", ga4EventName(vendorEventName(event)), flatProps(event));
21
+ }
22
+ });
23
+ //#endregion
24
+ export { createGa4Sink };
25
+
26
+ //# sourceMappingURL=ga4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/tracker/sinks/ga4.ts"],"sourcesContent":["import { ga4EventName } from '../../adapters/ga4/eventName'\nimport type { Sink, TrackerWindow } from '../types'\nimport { createVendorSink, flatProps, type VendorSinkArgs, vendorEventName } from './vendor'\n\ntype GtagWindow = TrackerWindow & {\n\tgtag?: (command: 'event', name: string, params?: Record<string, unknown>) => void\n}\n\n/**\n * Forwards events and goals to `gtag('event', name, params)`, under the name GA4 accepts for\n * them rather than the kebab-case slug: the other vendors take hyphens, GA4 does not. Revenue\n * rides along as the `value` and `currency` params, which is what GA4's own ecommerce reports\n * read. The inline half of the snippet defines `gtag` and its `dataLayer` queue the moment it\n * runs, so calls made before gtag.js lands are replayed by it.\n *\n * Pageviews are dropped by `createVendorSink`, as for every other vendor: `gtag('config', id)`\n * sends the first page view itself, and page views on history changes come from the web data\n * stream's enhanced measurement (https://support.google.com/analytics/answer/9216061), on by\n * default and switchable per stream. An install that turned that option off should turn it\n * back on: this sink forwards no pageview, because on a default stream it would double-count.\n */\nexport const createGa4Sink = (args: VendorSinkArgs): Sink =>\n\tcreateVendorSink(args, {\n\t\thas: () => typeof (args.win as GtagWindow).gtag === 'function',\n\t\tdispatch: (event) => {\n\t\t\t;(args.win as GtagWindow).gtag?.(\n\t\t\t\t'event',\n\t\t\t\tga4EventName(vendorEventName(event)),\n\t\t\t\tflatProps(event)\n\t\t\t)\n\t\t},\n\t})\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAa,iBAAiB,SAC7B,iBAAiB,MAAM;CACtB,WAAW,OAAQ,KAAK,IAAmB,SAAS;CACpD,WAAW,UAAU;EACnB,KAAM,IAAmB,OACzB,SACA,aAAa,gBAAgB,KAAK,CAAC,GACnC,UAAU,KAAK,CAChB;CACD;AACD,CAAC"}
@@ -19,6 +19,11 @@ interface TrackerEvent {
19
19
  path: string;
20
20
  hostname: string;
21
21
  referrer?: string;
22
+ /**
23
+ * The page's query string without its leading `?`, on pageviews only. Ingest reads the
24
+ * utm keys out of it and drops the rest; the raw string is never stored.
25
+ */
26
+ query?: string;
22
27
  props?: Record<string, unknown>;
23
28
  value?: number;
24
29
  currency?: string;