@10x-media/analytics 1.0.0-beta.6 → 1.0.0-beta.8

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 (391) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +13 -3
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/http/fetchJson.js +1 -1
  6. package/dist/adapters/plausible/plausible.d.ts +10 -0
  7. package/dist/adapters/plausible/plausible.js +42 -1
  8. package/dist/adapters/plausible/plausible.js.map +1 -1
  9. package/dist/adapters/posthog/posthog.d.ts +10 -1
  10. package/dist/adapters/posthog/posthog.js +47 -0
  11. package/dist/adapters/posthog/posthog.js.map +1 -1
  12. package/dist/adapters/umami/umami.d.ts +5 -1
  13. package/dist/adapters/umami/umami.js +26 -0
  14. package/dist/adapters/umami/umami.js.map +1 -1
  15. package/dist/capture/getTrackerConfig.d.ts +20 -0
  16. package/dist/capture/getTrackerConfig.js +31 -0
  17. package/dist/capture/getTrackerConfig.js.map +1 -0
  18. package/dist/capture/mountPath.js +14 -0
  19. package/dist/capture/mountPath.js.map +1 -0
  20. package/dist/capture/proxyEndpoint.js +123 -0
  21. package/dist/capture/proxyEndpoint.js.map +1 -0
  22. package/dist/capture/proxyRoutes.js +108 -0
  23. package/dist/capture/proxyRoutes.js.map +1 -0
  24. package/dist/capture/requestBody.js +68 -0
  25. package/dist/capture/requestBody.js.map +1 -0
  26. package/dist/capture/slots.d.ts +8 -0
  27. package/dist/capture/slots.js +54 -0
  28. package/dist/capture/slots.js.map +1 -0
  29. package/dist/capture/trackerConfig.d.ts +33 -0
  30. package/dist/capture/trackerConfig.js +95 -0
  31. package/dist/capture/trackerConfig.js.map +1 -0
  32. package/dist/capture/trackerEndpoint.js +35 -0
  33. package/dist/capture/trackerEndpoint.js.map +1 -0
  34. package/dist/charts/BarList.d.ts +15 -1
  35. package/dist/charts/BarList.js +34 -18
  36. package/dist/charts/BarList.js.map +1 -1
  37. package/dist/charts/TrendChart.d.ts +16 -3
  38. package/dist/charts/TrendChart.js +172 -106
  39. package/dist/charts/TrendChart.js.map +1 -1
  40. package/dist/charts/bars.d.ts +2 -0
  41. package/dist/charts/bars.js +2 -1
  42. package/dist/charts/bars.js.map +1 -1
  43. package/dist/charts/bucket.js +10 -1
  44. package/dist/charts/bucket.js.map +1 -1
  45. package/dist/charts/spline.js +2 -2
  46. package/dist/charts/spline.js.map +1 -1
  47. package/dist/charts/styles.js +18 -1
  48. package/dist/charts/styles.js.map +1 -1
  49. package/dist/core/cacheKey.js +13 -1
  50. package/dist/core/cacheKey.js.map +1 -1
  51. package/dist/core/capture.d.ts +49 -0
  52. package/dist/core/contract.d.ts +35 -4
  53. package/dist/core/contract.js +29 -1
  54. package/dist/core/contract.js.map +1 -1
  55. package/dist/core/granularity.js +1 -1
  56. package/dist/core/options.d.ts +148 -4
  57. package/dist/core/options.js +121 -3
  58. package/dist/core/options.js.map +1 -1
  59. package/dist/core/registry.d.ts +1 -0
  60. package/dist/core/scopeList.js +32 -0
  61. package/dist/core/scopeList.js.map +1 -0
  62. package/dist/core/scopedRead.js +45 -28
  63. package/dist/core/scopedRead.js.map +1 -1
  64. package/dist/core/serverEvent.d.ts +42 -0
  65. package/dist/core/serverEvent.js +12 -0
  66. package/dist/core/serverEvent.js.map +1 -0
  67. package/dist/exports/client.d.ts +8 -2
  68. package/dist/exports/client.js +6 -1
  69. package/dist/exports/next.d.ts +2 -1
  70. package/dist/exports/next.js +2 -1
  71. package/dist/exports/react.d.ts +4 -0
  72. package/dist/exports/react.js +5 -0
  73. package/dist/exports/rsc.d.ts +8 -1
  74. package/dist/exports/rsc.js +7 -2
  75. package/dist/exports/tracker.d.ts +18 -0
  76. package/dist/exports/tracker.js +12 -0
  77. package/dist/exports/types.d.ts +14 -3
  78. package/dist/exports/types.js +2 -2
  79. package/dist/fields/AnalyticsPanelClient.js +2 -2
  80. package/dist/fields/AnalyticsPanelField.js +1 -1
  81. package/dist/fields/AnalyticsStatField.js +2 -2
  82. package/dist/fields/config/MetricSelectField.js +2 -2
  83. package/dist/fields/config/MetricSelectField.js.map +1 -1
  84. package/dist/fields/config/SourceSelectField.js +2 -2
  85. package/dist/fields/config/SourceSelectField.js.map +1 -1
  86. package/dist/fields/config/fetchSources.d.ts +5 -1
  87. package/dist/fields/config/narrow.js +2 -0
  88. package/dist/fields/config/narrow.js.map +1 -1
  89. package/dist/fields/readForDocument.d.ts +5 -0
  90. package/dist/fields/readForDocument.js +6 -6
  91. package/dist/fields/readForDocument.js.map +1 -1
  92. package/dist/goals/GoalSelectField.d.ts +7 -0
  93. package/dist/goals/GoalSelectField.js +77 -0
  94. package/dist/goals/GoalSelectField.js.map +1 -0
  95. package/dist/goals/collection.js +250 -0
  96. package/dist/goals/collection.js.map +1 -0
  97. package/dist/goals/currency.js +14 -0
  98. package/dist/goals/currency.js.map +1 -0
  99. package/dist/goals/fetchGoals.d.ts +18 -0
  100. package/dist/goals/fetchGoals.js +29 -0
  101. package/dist/goals/fetchGoals.js.map +1 -0
  102. package/dist/goals/goalField.d.ts +31 -0
  103. package/dist/goals/goalField.js +56 -0
  104. package/dist/goals/goalField.js.map +1 -0
  105. package/dist/goals/goalsEndpoint.d.ts +1 -0
  106. package/dist/goals/goalsEndpoint.js +55 -0
  107. package/dist/goals/goalsEndpoint.js.map +1 -0
  108. package/dist/goals/match.js +64 -0
  109. package/dist/goals/match.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/types.d.ts +33 -0
  117. package/dist/goals/types.js +7 -0
  118. package/dist/goals/types.js.map +1 -0
  119. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  120. package/dist/goals/useAnalyticsGoals.js +67 -0
  121. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  122. package/dist/index.d.ts +11 -3
  123. package/dist/index.js +104 -17
  124. package/dist/index.js.map +1 -1
  125. package/dist/native/collections/events.js +21 -1
  126. package/dist/native/collections/events.js.map +1 -1
  127. package/dist/native/collections/rollups.js +24 -0
  128. package/dist/native/collections/rollups.js.map +1 -1
  129. package/dist/native/geo/maxmindResolver.js +2 -4
  130. package/dist/native/geo/maxmindResolver.js.map +1 -1
  131. package/dist/native/ingest/clientIp.js +15 -0
  132. package/dist/native/ingest/clientIp.js.map +1 -0
  133. package/dist/native/ingest/device.js +11 -3
  134. package/dist/native/ingest/device.js.map +1 -1
  135. package/dist/native/ingest/endpoint.d.ts +1 -0
  136. package/dist/native/ingest/endpoint.js +25 -4
  137. package/dist/native/ingest/endpoint.js.map +1 -1
  138. package/dist/native/ingest/flushBatch.js +4 -13
  139. package/dist/native/ingest/flushBatch.js.map +1 -1
  140. package/dist/native/ingest/normalizeEvent.d.ts +20 -0
  141. package/dist/native/ingest/normalizeEvent.js +78 -10
  142. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  143. package/dist/native/ingest/serverTrack.d.ts +20 -0
  144. package/dist/native/ingest/serverTrack.js +99 -0
  145. package/dist/native/ingest/serverTrack.js.map +1 -0
  146. package/dist/native/ingest/validate.js +27 -0
  147. package/dist/native/ingest/validate.js.map +1 -0
  148. package/dist/native/nativeAdapter.d.ts +1 -1
  149. package/dist/native/nativeAdapter.js +38 -11
  150. package/dist/native/nativeAdapter.js.map +1 -1
  151. package/dist/native/query/eventAgg.js +39 -13
  152. package/dist/native/query/eventAgg.js.map +1 -1
  153. package/dist/native/retention/pruneTask.js +1 -1
  154. package/dist/native/rollupAcc.js +12 -1
  155. package/dist/native/rollupAcc.js.map +1 -1
  156. package/dist/native/rollups/bumpRollup.js +5 -1
  157. package/dist/native/rollups/bumpRollup.js.map +1 -1
  158. package/dist/native/rollups/deltas.js +28 -6
  159. package/dist/native/rollups/deltas.js.map +1 -1
  160. package/dist/native/rollups/insertIfNew.js +36 -2
  161. package/dist/native/rollups/insertIfNew.js.map +1 -1
  162. package/dist/next/captureRewrites.d.ts +41 -0
  163. package/dist/next/captureRewrites.js +56 -0
  164. package/dist/next/captureRewrites.js.map +1 -0
  165. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  166. package/dist/next/posthogProxyRewrites.js +16 -21
  167. package/dist/next/posthogProxyRewrites.js.map +1 -1
  168. package/dist/plugin/documentEndpoint.js +28 -10
  169. package/dist/plugin/documentEndpoint.js.map +1 -1
  170. package/dist/plugin/paths.js +15 -1
  171. package/dist/plugin/paths.js.map +1 -1
  172. package/dist/plugin/queryEndpoint.js +113 -0
  173. package/dist/plugin/queryEndpoint.js.map +1 -0
  174. package/dist/plugin/readContextForRequest.js +71 -0
  175. package/dist/plugin/readContextForRequest.js.map +1 -0
  176. package/dist/plugin/realtimeEndpoint.js +6 -3
  177. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  178. package/dist/plugin/runtime.d.ts +1 -0
  179. package/dist/plugin/runtime.js +31 -1
  180. package/dist/plugin/runtime.js.map +1 -1
  181. package/dist/plugin/scopeFieldBoot.js +22 -0
  182. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  183. package/dist/plugin/sourcesEndpoint.js +13 -39
  184. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  185. package/dist/plugin/warmTask.js +0 -0
  186. package/dist/plugin/warmTask.js.map +1 -1
  187. package/dist/providers/collection.js +71 -25
  188. package/dist/providers/collection.js.map +1 -1
  189. package/dist/providers/factory.js +8 -2
  190. package/dist/providers/factory.js.map +1 -1
  191. package/dist/providers/resolver.js.map +1 -1
  192. package/dist/query/dates.js +64 -0
  193. package/dist/query/dates.js.map +1 -0
  194. package/dist/query/errors.d.ts +17 -0
  195. package/dist/query/errors.js +10 -0
  196. package/dist/query/errors.js.map +1 -0
  197. package/dist/query/fetchQuery.d.ts +59 -0
  198. package/dist/query/fetchQuery.js +110 -0
  199. package/dist/query/fetchQuery.js.map +1 -0
  200. package/dist/query/parse.d.ts +22 -0
  201. package/dist/query/parse.js +168 -0
  202. package/dist/query/parse.js.map +1 -0
  203. package/dist/query/response.d.ts +36 -0
  204. package/dist/react/AnalyticsProvider.d.ts +43 -0
  205. package/dist/react/AnalyticsProvider.js +66 -0
  206. package/dist/react/AnalyticsProvider.js.map +1 -0
  207. package/dist/react/TrackerBoot.d.ts +22 -0
  208. package/dist/react/TrackerBoot.js +30 -0
  209. package/dist/react/TrackerBoot.js.map +1 -0
  210. package/dist/react/useAnalytics.d.ts +17 -0
  211. package/dist/react/useAnalytics.js +36 -0
  212. package/dist/react/useAnalytics.js.map +1 -0
  213. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  214. package/dist/rsc/AnalyticsScripts.js +41 -0
  215. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  216. package/dist/surfacing/cacheStore.d.ts +1 -0
  217. package/dist/surfacing/cacheStore.js +18 -2
  218. package/dist/surfacing/cacheStore.js.map +1 -1
  219. package/dist/surfacing/engine.d.ts +1 -0
  220. package/dist/surfacing/engine.js +44 -4
  221. package/dist/surfacing/engine.js.map +1 -1
  222. package/dist/surfacing/queue.js +22 -6
  223. package/dist/surfacing/queue.js.map +1 -1
  224. package/dist/surfacing/rateLimiter.js +130 -0
  225. package/dist/surfacing/rateLimiter.js.map +1 -0
  226. package/dist/surfacing/retryPolicy.js +15 -0
  227. package/dist/surfacing/retryPolicy.js.map +1 -0
  228. package/dist/sync/syncTask.js +60 -33
  229. package/dist/sync/syncTask.js.map +1 -1
  230. package/dist/testing/memoryAdapter.d.ts +2 -0
  231. package/dist/testing/memoryAdapter.js +10 -0
  232. package/dist/testing/memoryAdapter.js.map +1 -1
  233. package/dist/timeframe/tz.js +17 -6
  234. package/dist/timeframe/tz.js.map +1 -1
  235. package/dist/tracker/autoCapture.d.ts +48 -0
  236. package/dist/tracker/autoCapture.js +129 -0
  237. package/dist/tracker/autoCapture.js.map +1 -0
  238. package/dist/tracker/consent.d.ts +24 -0
  239. package/dist/tracker/consent.js +48 -0
  240. package/dist/tracker/consent.js.map +1 -0
  241. package/dist/tracker/createTracker.d.ts +18 -0
  242. package/dist/tracker/createTracker.js +163 -0
  243. package/dist/tracker/createTracker.js.map +1 -0
  244. package/dist/tracker/initTracker.d.ts +22 -0
  245. package/dist/tracker/initTracker.js +33 -0
  246. package/dist/tracker/initTracker.js.map +1 -0
  247. package/dist/tracker/loadScript.d.ts +14 -0
  248. package/dist/tracker/loadScript.js +41 -0
  249. package/dist/tracker/loadScript.js.map +1 -0
  250. package/dist/tracker/pageTracking.d.ts +17 -0
  251. package/dist/tracker/pageTracking.js +38 -0
  252. package/dist/tracker/pageTracking.js.map +1 -0
  253. package/dist/tracker/registry.d.ts +27 -0
  254. package/dist/tracker/registry.js +73 -0
  255. package/dist/tracker/registry.js.map +1 -0
  256. package/dist/tracker/sinks/native.d.ts +22 -0
  257. package/dist/tracker/sinks/native.js +56 -0
  258. package/dist/tracker/sinks/native.js.map +1 -0
  259. package/dist/tracker/sinks/plausible.d.ts +14 -0
  260. package/dist/tracker/sinks/plausible.js +25 -0
  261. package/dist/tracker/sinks/plausible.js.map +1 -0
  262. package/dist/tracker/sinks/posthog.d.ts +14 -0
  263. package/dist/tracker/sinks/posthog.js +18 -0
  264. package/dist/tracker/sinks/posthog.js.map +1 -0
  265. package/dist/tracker/sinks/umami.d.ts +13 -0
  266. package/dist/tracker/sinks/umami.js +17 -0
  267. package/dist/tracker/sinks/umami.js.map +1 -0
  268. package/dist/tracker/sinks/vendor.d.ts +14 -0
  269. package/dist/tracker/sinks/vendor.js +66 -0
  270. package/dist/tracker/sinks/vendor.js.map +1 -0
  271. package/dist/tracker/transport.js +28 -0
  272. package/dist/tracker/transport.js.map +1 -0
  273. package/dist/tracker/types.d.ts +66 -0
  274. package/dist/translations/ar.js +104 -1
  275. package/dist/translations/ar.js.map +1 -1
  276. package/dist/translations/de.js +104 -1
  277. package/dist/translations/de.js.map +1 -1
  278. package/dist/translations/en.js +104 -1
  279. package/dist/translations/en.js.map +1 -1
  280. package/dist/translations/es.js +104 -1
  281. package/dist/translations/es.js.map +1 -1
  282. package/dist/translations/fr.js +104 -1
  283. package/dist/translations/fr.js.map +1 -1
  284. package/dist/translations/id.js +104 -1
  285. package/dist/translations/id.js.map +1 -1
  286. package/dist/translations/keys.d.ts +103 -0
  287. package/dist/translations/keys.js +104 -1
  288. package/dist/translations/keys.js.map +1 -1
  289. package/dist/translations/ko.js +104 -1
  290. package/dist/translations/ko.js.map +1 -1
  291. package/dist/translations/metricKeys.js +1 -1
  292. package/dist/translations/metricKeys.js.map +1 -1
  293. package/dist/translations/pt.js +104 -1
  294. package/dist/translations/pt.js.map +1 -1
  295. package/dist/translations/ru.js +104 -1
  296. package/dist/translations/ru.js.map +1 -1
  297. package/dist/translations/uk.js +104 -1
  298. package/dist/translations/uk.js.map +1 -1
  299. package/dist/translations/zh.js +104 -1
  300. package/dist/translations/zh.js.map +1 -1
  301. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  302. package/dist/view/AnalyticsNavLink.js +40 -0
  303. package/dist/view/AnalyticsNavLink.js.map +1 -0
  304. package/dist/view/AnalyticsView.d.ts +23 -0
  305. package/dist/view/AnalyticsView.js +45 -0
  306. package/dist/view/AnalyticsView.js.map +1 -0
  307. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  308. package/dist/view/AnalyticsViewClient.js +189 -0
  309. package/dist/view/AnalyticsViewClient.js.map +1 -0
  310. package/dist/view/authRedirect.js +32 -0
  311. package/dist/view/authRedirect.js.map +1 -0
  312. package/dist/view/conversionRate.js +18 -0
  313. package/dist/view/conversionRate.js.map +1 -0
  314. package/dist/view/dayRange.js +68 -0
  315. package/dist/view/dayRange.js.map +1 -0
  316. package/dist/view/gating.d.ts +1 -0
  317. package/dist/view/gating.js +105 -0
  318. package/dist/view/gating.js.map +1 -0
  319. package/dist/view/labels.js +44 -0
  320. package/dist/view/labels.js.map +1 -0
  321. package/dist/view/registerView.js +48 -0
  322. package/dist/view/registerView.js.map +1 -0
  323. package/dist/view/sections/Breakdowns.js +157 -0
  324. package/dist/view/sections/Breakdowns.js.map +1 -0
  325. package/dist/view/sections/EmptyStates.js +92 -0
  326. package/dist/view/sections/EmptyStates.js.map +1 -0
  327. package/dist/view/sections/FilterChips.js +41 -0
  328. package/dist/view/sections/FilterChips.js.map +1 -0
  329. package/dist/view/sections/GoalsPanel.js +81 -0
  330. package/dist/view/sections/GoalsPanel.js.map +1 -0
  331. package/dist/view/sections/OverviewCards.js +65 -0
  332. package/dist/view/sections/OverviewCards.js.map +1 -0
  333. package/dist/view/sections/RealtimeStrip.js +77 -0
  334. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  335. package/dist/view/sections/Toolbar.js +179 -0
  336. package/dist/view/sections/Toolbar.js.map +1 -0
  337. package/dist/view/sections/Trend.js +119 -0
  338. package/dist/view/sections/Trend.js.map +1 -0
  339. package/dist/view/sections/styles.js +74 -0
  340. package/dist/view/sections/styles.js.map +1 -0
  341. package/dist/view/state.js +206 -0
  342. package/dist/view/state.js.map +1 -0
  343. package/dist/view/useViewQueries.js +150 -0
  344. package/dist/view/useViewQueries.js.map +1 -0
  345. package/dist/view/viewProps.d.ts +40 -0
  346. package/dist/view/viewProps.js +90 -0
  347. package/dist/view/viewProps.js.map +1 -0
  348. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  349. package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
  350. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  351. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  352. package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
  353. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  354. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  355. package/dist/widgets/AnalyticsMetricWidget.js +35 -12
  356. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  357. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  358. package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
  359. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  360. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  361. package/dist/widgets/AnalyticsTrendWidget.js +51 -15
  362. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  363. package/dist/widgets/WidgetViewLink.js +17 -0
  364. package/dist/widgets/WidgetViewLink.js.map +1 -0
  365. package/dist/widgets/breakdownTypes.js +32 -0
  366. package/dist/widgets/breakdownTypes.js.map +1 -1
  367. package/dist/widgets/cardChrome.js +31 -7
  368. package/dist/widgets/cardChrome.js.map +1 -1
  369. package/dist/widgets/range.js +43 -12
  370. package/dist/widgets/range.js.map +1 -1
  371. package/dist/widgets/readForWidget.d.ts +12 -0
  372. package/dist/widgets/readForWidget.js +30 -19
  373. package/dist/widgets/readForWidget.js.map +1 -1
  374. package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
  375. package/dist/widgets/readForWidgetBreakdown.js +32 -20
  376. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  377. package/dist/widgets/readForWidgetGoals.d.ts +57 -0
  378. package/dist/widgets/readForWidgetGoals.js +126 -0
  379. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  380. package/dist/widgets/readForWidgetRealtime.js +1 -1
  381. package/dist/widgets/readForWidgetSeries.d.ts +13 -0
  382. package/dist/widgets/readForWidgetSeries.js +56 -28
  383. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  384. package/dist/widgets/registerWidgets.js +58 -9
  385. package/dist/widgets/registerWidgets.js.map +1 -1
  386. package/dist/widgets/types.js +16 -2
  387. package/dist/widgets/types.js.map +1 -1
  388. package/dist/widgets/viewLink.d.ts +22 -0
  389. package/dist/widgets/viewLink.js +83 -0
  390. package/dist/widgets/viewLink.js.map +1 -0
  391. package/package.json +25 -5
@@ -1,6 +1,9 @@
1
- import { AnalyticsAdapter } from "./contract.js";
2
- import { TranslationsOption } from "../translations/index.js";
1
+ import { Goal } from "../goals/types.js";
2
+ import { AnalyticsAdapter, MetricKey } from "./contract.js";
3
3
  import { AnalyticsBinding } from "../binding/types.js";
4
+ import { CaptureSlot } from "../capture/slots.js";
5
+ import { TimeframePreset } from "../timeframe/presets.js";
6
+ import { TranslationsOption } from "../translations/index.js";
4
7
  import { CustomWidgetDef } from "../widgets/customWidget.js";
5
8
  import { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from "payload";
6
9
  import { KeysConfig } from "@10x-media/fields/encrypted";
@@ -24,6 +27,13 @@ type TimezoneResolver = (args: {
24
27
  req: PayloadRequest;
25
28
  scope: string | null;
26
29
  }) => string | null | Promise<string | null>;
30
+ /**
31
+ * Enumerates the tenant scopes the cron tiers (cache warming, sync) fan out over.
32
+ * Absent, each tier runs once for the install-wide scope.
33
+ */
34
+ type ScopesResolver = (args: {
35
+ payload: Payload;
36
+ }) => string[] | Promise<string[]>;
27
37
  /**
28
38
  * Escape hatch replacing the provider-collection lookup: return the runtime
29
39
  * adapters for a scope yourself (any store, any shape). Results are layered onto
@@ -63,7 +73,22 @@ type ProvidersOptions = {
63
73
  type PlatformReadAccess = (args: {
64
74
  req: PayloadRequest;
65
75
  }) => boolean | Promise<boolean>;
76
+ /** Access checker for authenticated analytics reads. */
77
+ type AnalyticsReadAccess = (args: {
78
+ req: PayloadRequest;
79
+ }) => boolean | Promise<boolean>;
80
+ /** Access checker for the analytics admin view. */
81
+ type AnalyticsViewAccess = (args: {
82
+ req: PayloadRequest;
83
+ }) => boolean | Promise<boolean>;
66
84
  type AnalyticsAccessOptions = {
85
+ /**
86
+ * Gates every authenticated read endpoint: query, document panel, realtime, sources
87
+ * and goals. Defaults to any authenticated user; narrow it to a role check to keep
88
+ * analytics away from admins who should not see them. Scope gating is separate and
89
+ * always applies: granting `read` never widens which scope a user reads.
90
+ */
91
+ read?: AnalyticsReadAccess;
67
92
  /**
68
93
  * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through
69
94
  * a shared config adapter that cannot filter by scope. Scoped installs
@@ -72,6 +97,107 @@ type AnalyticsAccessOptions = {
72
97
  * providers. Unscoped installs default to any authenticated admin-panel user.
73
98
  */
74
99
  platformRead?: PlatformReadAccess;
100
+ /**
101
+ * Gates the analytics admin view. Defaults to `read`, so one gate covers the view and
102
+ * the endpoints behind it. A reader this denies still sees the nav link (it is a client
103
+ * component with no access context) and lands on the view's no-access message.
104
+ */
105
+ view?: AnalyticsViewAccess;
106
+ };
107
+ type ConsentMode = 'none' | 'required';
108
+ /** Per-slot consent decision, evaluated against the slot's resolved adapter. */
109
+ type ConsentResolver = (args: {
110
+ slot: CaptureSlot;
111
+ adapterId: string;
112
+ }) => ConsentMode;
113
+ /** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */
114
+ type CaptureSlotOption = string | false;
115
+ /**
116
+ * A bare mode applies to every slot; a resolver decides per request-resolved adapter; the
117
+ * object form maps ids and slots, with an adapter entry winning over a slot entry. Every
118
+ * form overrides the default, which is `none` for the cookieless native tracker and
119
+ * `required` for a vendor's.
120
+ */
121
+ type CaptureConsentOption = ConsentMode | ConsentResolver | {
122
+ slots?: Partial<Record<CaptureSlot, ConsentMode>>;
123
+ /**
124
+ * Keyed by adapter id. A bare id must name a config adapter; a runtime provider
125
+ * instance id (`<provider>:<instance>`) is taken on trust, since the providers it
126
+ * comes from are only resolved per request.
127
+ */
128
+ adapters?: Record<string, ConsentMode>;
129
+ };
130
+ type AutoCaptureOptions = {
131
+ scrollDepth?: boolean;
132
+ outboundLinks?: boolean;
133
+ fileDownloads?: boolean;
134
+ goalAttribute?: boolean;
135
+ };
136
+ type ResolvedAutoCapture = Required<AutoCaptureOptions>;
137
+ type AnalyticsGoalsCollectionOptions = {
138
+ /** Set false to keep the object form's other settings while leaving the collection off. */enabled?: boolean;
139
+ slug?: string;
140
+ /**
141
+ * Field matched against the resolved scope when looking up a scope's goals. Point it at
142
+ * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.
143
+ */
144
+ scopeField?: string;
145
+ overrides?: (collection: CollectionConfig) => CollectionConfig;
146
+ access?: Partial<CollectionConfig['access']>;
147
+ };
148
+ /** Goals as config, plus the opt-in collection editors manage their own goals through. */
149
+ type AnalyticsGoalsOptions = {
150
+ defaults?: Goal[]; /** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */
151
+ collection?: boolean | AnalyticsGoalsCollectionOptions;
152
+ };
153
+ type AnalyticsCaptureOptions = {
154
+ /**
155
+ * Which adapter fills each capture slot, overriding the defaults: `global` is the
156
+ * designated `platformAdapter`, or the single config adapter when only one is
157
+ * configured; `tenant` is the resolved scope's default adapter. A `global` id must
158
+ * name a config adapter; a `tenant` id may also name a runtime provider instance,
159
+ * so it is resolved per request rather than validated at config time.
160
+ *
161
+ * `false` disables a slot outright: it fills with nothing, its proxy mount 404s, and
162
+ * the tracker config omits it. Use it to keep a default from filling a slot at all.
163
+ */
164
+ slots?: {
165
+ global?: CaptureSlotOption;
166
+ tenant?: CaptureSlotOption;
167
+ };
168
+ /**
169
+ * Mount each slot's snippet points at. Defaults to the runtime proxy endpoint
170
+ * (`<routes.api>/analytics/p/<slot>`); set it when the slot is served through Next
171
+ * rewrites instead, passing the same path `captureRewrites` was mounted at.
172
+ */
173
+ paths?: {
174
+ global?: string;
175
+ tenant?: string;
176
+ }; /** Whether a slot's tracker waits for consent. Native defaults to no gate, vendors to one. */
177
+ consent?: CaptureConsentOption; /** Browser auto-capture listeners, all on by default except `scrollDepth`. */
178
+ autoCapture?: AutoCaptureOptions; /** Limits for the public runtime capture proxy, separate from the read-path `cache`. */
179
+ proxy?: {
180
+ /**
181
+ * Deadline for the upstream response headers, in ms. Default 10000. The body
182
+ * download is not on the clock, so a large tracker bundle streams to completion.
183
+ */
184
+ timeoutMs?: number;
185
+ /**
186
+ * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog
187
+ * batch carrying session-replay data. Anything larger is refused with 413.
188
+ */
189
+ maxBodyBytes?: number;
190
+ };
191
+ };
192
+ type AnalyticsViewOptions = {
193
+ /** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */path?: `/${string}`; /** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */
194
+ defaultRange?: TimeframePreset; /** Metric the cards and the trend open on. Default `pageviews`. */
195
+ defaultMetric?: MetricKey;
196
+ /**
197
+ * Nav link label. A string is used as-is; a map is keyed by admin language code and
198
+ * falls back to `en`. Unset, the plugin's own translated label applies.
199
+ */
200
+ navLabel?: string | Record<string, string>;
75
201
  };
76
202
  type AnalyticsPluginOptions = {
77
203
  disabled?: boolean;
@@ -85,6 +211,12 @@ type AnalyticsPluginOptions = {
85
211
  adapters?: AnalyticsAdapter[];
86
212
  defaultAdapter?: string;
87
213
  scopeResolver?: ScopeResolver;
214
+ /**
215
+ * Enumerates the tenant scopes the cache-warming and sync cron tiers fan out
216
+ * over, in addition to the install-wide (null) scope every tier already runs.
217
+ * Unset, those tiers run once for the whole install, same as before.
218
+ */
219
+ scopes?: ScopesResolver;
88
220
  /**
89
221
  * IANA reporting timezone that day boundaries (timeframe windows, series axes,
90
222
  * native rollup buckets) align to. Defaults to UTC. A string forces one timezone
@@ -103,6 +235,17 @@ type AnalyticsPluginOptions = {
103
235
  */
104
236
  platformAdapter?: string;
105
237
  access?: AnalyticsAccessOptions;
238
+ /**
239
+ * The analytics admin view and its nav link, on by default. `false` registers neither;
240
+ * the read endpoints stay mounted either way, so a custom surface keeps working.
241
+ */
242
+ view?: false | AnalyticsViewOptions;
243
+ capture?: AnalyticsCaptureOptions;
244
+ /**
245
+ * Conversion goals the tracker and the native ingest match events against. Slugs must
246
+ * be unique and kebab-case; only the slug and its match reach the browser.
247
+ */
248
+ goals?: Goal[] | AnalyticsGoalsOptions;
106
249
  /**
107
250
  * Per-collection bindings, keyed by collection slug. With generated types
108
251
  * augmented, each slug's resolvers receive that collection's typed document.
@@ -115,7 +258,8 @@ type AnalyticsPluginOptions = {
115
258
  };
116
259
  warm?: boolean | {
117
260
  cron?: string;
118
- };
261
+ }; /** Per-read provider timeout in ms, spanning retries and limiter waits. Default 15000. */
262
+ timeoutMs?: number;
119
263
  };
120
264
  widgets?: boolean | {
121
265
  disabled?: string[];
@@ -148,5 +292,5 @@ type AnalyticsPluginOptions = {
148
292
  };
149
293
  };
150
294
  //#endregion
151
- export { AnalyticsAccessOptions, AnalyticsPluginOptions, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ScopeResolver, TimezoneResolver };
295
+ export { AnalyticsAccessOptions, AnalyticsCaptureOptions, AnalyticsGoalsCollectionOptions, AnalyticsGoalsOptions, AnalyticsPluginOptions, AnalyticsReadAccess, AnalyticsViewAccess, AnalyticsViewOptions, AutoCaptureOptions, CaptureConsentOption, ConsentMode, ConsentResolver, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ResolvedAutoCapture, ScopeResolver, ScopesResolver, TimezoneResolver };
152
296
  //# sourceMappingURL=options.d.ts.map
@@ -1,10 +1,99 @@
1
+ import "../capture/proxyEndpoint.js";
2
+ import { GOAL_SLUG_PATTERN } from "../goals/types.js";
3
+ import { GOALS_SLUG } from "../goals/collection.js";
1
4
  import { PROVIDERS_SLUG } from "../providers/collection.js";
5
+ import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
6
+ import { METRIC_KEYS } from "../translations/metricKeys.js";
2
7
  //#region src/core/options.ts
3
8
  const DEFAULT_WARM_CRON = "*/30 * * * *";
4
9
  const DEFAULT_SYNC_CRON = "0 */6 * * *";
5
10
  const DEFAULT_SYNC_COLLECTION = "analytics-daily";
6
11
  const DEFAULT_SYNC_LOOKBACK = 3;
7
12
  const DEFAULT_SCOPE_FIELD = "scope";
13
+ const DEFAULT_TIMEOUT_MS = 15e3;
14
+ /** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */
15
+ const DEFAULT_AUTO_CAPTURE = {
16
+ scrollDepth: false,
17
+ outboundLinks: true,
18
+ fileDownloads: true,
19
+ goalAttribute: true
20
+ };
21
+ const resolveAutoCapture = (option) => ({
22
+ scrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,
23
+ outboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,
24
+ fileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,
25
+ goalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute
26
+ });
27
+ /** Cookieless native capture needs no consent gate; a vendor's tracker does. */
28
+ const defaultConsentFor = (kind) => kind === "native" ? "none" : "required";
29
+ const resolveConsent = (option, adapters) => {
30
+ if (option === "none" || option === "required") return () => option;
31
+ if (typeof option === "function") return (slot, adapterId) => option({
32
+ slot,
33
+ adapterId
34
+ });
35
+ for (const id of Object.keys(option?.adapters ?? {})) if (!id.includes(":") && !adapters.some((a) => a.id === id)) throw new Error(`analytics: unknown consent adapter "${id}"`);
36
+ return (slot, adapterId, kind) => option?.adapters?.[adapterId] ?? option?.slots?.[slot] ?? defaultConsentFor(kind);
37
+ };
38
+ const resolveGoals = (option) => {
39
+ const goals = Array.isArray(option) ? option : option?.defaults ?? [];
40
+ const seen = /* @__PURE__ */ new Set();
41
+ for (const goal of goals) {
42
+ if (!GOAL_SLUG_PATTERN.test(goal.slug)) throw new Error(`analytics: goal slug "${goal.slug}" must be kebab-case`);
43
+ if (seen.has(goal.slug)) throw new Error(`analytics: duplicate goal slug "${goal.slug}"`);
44
+ const fixed = goal.value?.fixed;
45
+ if (fixed !== void 0 && (!Number.isFinite(fixed) || fixed < 0)) throw new Error(`analytics: goal "${goal.slug}" value.fixed must be a finite number >= 0, got ${String(fixed)}`);
46
+ seen.add(goal.slug);
47
+ }
48
+ return goals;
49
+ };
50
+ const resolveGoalsCollection = (option) => {
51
+ const off = {
52
+ enabled: false,
53
+ slug: GOALS_SLUG,
54
+ scopeField: DEFAULT_SCOPE_FIELD
55
+ };
56
+ const collection = Array.isArray(option) ? void 0 : option?.collection;
57
+ if (!collection) return off;
58
+ const resolved = collection === true ? {
59
+ ...off,
60
+ enabled: true
61
+ } : {
62
+ enabled: collection.enabled ?? true,
63
+ slug: collection.slug ?? "analytics-goals",
64
+ scopeField: collection.scopeField ?? DEFAULT_SCOPE_FIELD,
65
+ overrides: collection.overrides,
66
+ access: collection.access
67
+ };
68
+ if (!resolved.enabled) return off;
69
+ if (typeof resolved.slug !== "string" || resolved.slug.trim() === "") throw new Error("analytics: goals.collection.slug must be a non-empty collection slug");
70
+ if (resolved.scopeField.trim() === "") throw new Error("analytics: goals.collection.scopeField must be a non-empty field name");
71
+ if (resolved.scopeField.includes(".")) throw new Error("analytics: goals.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key");
72
+ return {
73
+ ...resolved,
74
+ slug: resolved.slug.trim()
75
+ };
76
+ };
77
+ const DEFAULT_VIEW = {
78
+ path: "/analytics",
79
+ defaultRange: "last30days",
80
+ defaultMetric: "pageviews"
81
+ };
82
+ const resolveView = (option) => {
83
+ if (option === false) return false;
84
+ const path = option?.path ?? DEFAULT_VIEW.path;
85
+ if (typeof path !== "string" || !path.startsWith("/")) throw new Error(`analytics: view.path must start with "/", got "${String(path)}"`);
86
+ const defaultRange = option?.defaultRange ?? DEFAULT_VIEW.defaultRange;
87
+ if (!TIMEFRAME_PRESETS.includes(defaultRange)) throw new Error(`analytics: unknown view.defaultRange "${String(defaultRange)}"`);
88
+ const defaultMetric = option?.defaultMetric ?? DEFAULT_VIEW.defaultMetric;
89
+ if (!(defaultMetric in METRIC_KEYS)) throw new Error(`analytics: unknown view.defaultMetric "${String(defaultMetric)}"`);
90
+ return {
91
+ path,
92
+ defaultRange,
93
+ defaultMetric,
94
+ ...option?.navLabel !== void 0 ? { navLabel: option.navLabel } : {}
95
+ };
96
+ };
8
97
  const resolveBindings = (collections) => {
9
98
  const out = {};
10
99
  for (const [slug, binding] of Object.entries(collections ?? {})) {
@@ -17,6 +106,9 @@ const resolveBindings = (collections) => {
17
106
  function resolveOptions(options) {
18
107
  if (!options.adapters || options.adapters.length === 0) throw new Error("analytics: at least one adapter is required");
19
108
  if (options.platformAdapter !== void 0 && !options.adapters.some((a) => a.id === options.platformAdapter)) throw new Error(`analytics: unknown platform adapter "${options.platformAdapter}"`);
109
+ for (const [slot, value] of Object.entries(options.capture?.slots ?? {})) if (value !== false && typeof value !== "string" && value !== void 0) throw new Error(`analytics: capture slot "${slot}" must be an adapter id or false, got ${typeof value}`);
110
+ const globalSlot = options.capture?.slots?.global;
111
+ if (typeof globalSlot === "string" && !options.adapters.some((a) => a.id === globalSlot)) throw new Error(`analytics: unknown global capture slot adapter "${globalSlot}"`);
20
112
  const widgets = options.widgets === false ? {
21
113
  enabled: false,
22
114
  disabled: [],
@@ -93,14 +185,39 @@ function resolveOptions(options) {
93
185
  hidden: true
94
186
  };
95
187
  const scoped = options.scopeResolver !== void 0;
188
+ const read = options.access?.read ?? (({ req }) => Boolean(req.user));
96
189
  return {
97
190
  adapters: options.adapters,
98
191
  defaultAdapter: options.defaultAdapter,
99
192
  scopeResolver: options.scopeResolver ?? (() => null),
100
193
  scoped,
194
+ scopes: options.scopes,
101
195
  reportingTimezone: options.reportingTimezone,
102
196
  platformAdapter: options.platformAdapter,
103
- access: { platformRead: options.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)) },
197
+ access: {
198
+ platformRead: options.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),
199
+ read,
200
+ view: options.access?.view ?? read
201
+ },
202
+ view: resolveView(options.view),
203
+ capture: {
204
+ slots: {
205
+ global: options.capture?.slots?.global,
206
+ tenant: options.capture?.slots?.tenant
207
+ },
208
+ paths: {
209
+ global: options.capture?.paths?.global,
210
+ tenant: options.capture?.paths?.tenant
211
+ },
212
+ consent: resolveConsent(options.capture?.consent, options.adapters),
213
+ autoCapture: resolveAutoCapture(options.capture?.autoCapture),
214
+ proxy: {
215
+ timeoutMs: options.capture?.proxy?.timeoutMs ?? 1e4,
216
+ maxBodyBytes: options.capture?.proxy?.maxBodyBytes ?? 1048576
217
+ }
218
+ },
219
+ goals: resolveGoals(options.goals),
220
+ goalsCollection: resolveGoalsCollection(options.goals),
104
221
  providers,
105
222
  bindings: resolveBindings(options.collections),
106
223
  cache: {
@@ -108,13 +225,14 @@ function resolveOptions(options) {
108
225
  aggregate: options.cache?.ttl?.aggregate,
109
226
  realtime: options.cache?.ttl?.realtime
110
227
  },
111
- warm
228
+ warm,
229
+ timeoutMs: options.cache?.timeoutMs ?? DEFAULT_TIMEOUT_MS
112
230
  },
113
231
  widgets,
114
232
  sync
115
233
  };
116
234
  }
117
235
  //#endregion
118
- export { resolveOptions };
236
+ export { DEFAULT_AUTO_CAPTURE, DEFAULT_VIEW, defaultConsentFor, resolveOptions };
119
237
 
120
238
  //# sourceMappingURL=options.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t},\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;AAQ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C,OAAO;GAGN,KAAK;IACJ,WAAW,QAAQ,OAAO,KAAK;IAC/B,UAAU,QAAQ,OAAO,KAAK;GAC/B;GACA;EACD;EACA;EACA;CACD;AACD"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS } from '../capture/proxyEndpoint'\nimport type { CaptureSlot } from '../capture/slots'\nimport { GOALS_SLUG } from '../goals/collection'\nimport { GOAL_SLUG_PATTERN, type Goal } from '../goals/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport type { TranslationsOption } from '../translations'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { CaptureClientKind } from './capture'\nimport type { AnalyticsAdapter, MetricKey } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Enumerates the tenant scopes the cron tiers (cache warming, sync) fan out over.\n * Absent, each tier runs once for the install-wide scope.\n */\nexport type ScopesResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for authenticated analytics reads. */\nexport type AnalyticsReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for the analytics admin view. */\nexport type AnalyticsViewAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates every authenticated read endpoint: query, document panel, realtime, sources\n\t * and goals. Defaults to any authenticated user; narrow it to a role check to keep\n\t * analytics away from admins who should not see them. Scope gating is separate and\n\t * always applies: granting `read` never widens which scope a user reads.\n\t */\n\tread?: AnalyticsReadAccess\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n\t/**\n\t * Gates the analytics admin view. Defaults to `read`, so one gate covers the view and\n\t * the endpoints behind it. A reader this denies still sees the nav link (it is a client\n\t * component with no access context) and lands on the view's no-access message.\n\t */\n\tview?: AnalyticsViewAccess\n}\n\nexport type ConsentMode = 'none' | 'required'\n\n/** Per-slot consent decision, evaluated against the slot's resolved adapter. */\nexport type ConsentResolver = (args: { slot: CaptureSlot; adapterId: string }) => ConsentMode\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/**\n * A bare mode applies to every slot; a resolver decides per request-resolved adapter; the\n * object form maps ids and slots, with an adapter entry winning over a slot entry. Every\n * form overrides the default, which is `none` for the cookieless native tracker and\n * `required` for a vendor's.\n */\nexport type CaptureConsentOption =\n\t| ConsentMode\n\t| ConsentResolver\n\t| {\n\t\t\tslots?: Partial<Record<CaptureSlot, ConsentMode>>\n\t\t\t/**\n\t\t\t * Keyed by adapter id. A bare id must name a config adapter; a runtime provider\n\t\t\t * instance id (`<provider>:<instance>`) is taken on trust, since the providers it\n\t\t\t * comes from are only resolved per request.\n\t\t\t */\n\t\t\tadapters?: Record<string, ConsentMode>\n\t }\n\n/** The normalized policy the runtime evaluates; `kind` carries the adapter's tracker family. */\nexport type ConsentPolicy = (\n\tslot: CaptureSlot,\n\tadapterId: string,\n\tkind: CaptureClientKind\n) => ConsentMode\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n}\n\nexport type ResolvedAutoCapture = Required<AutoCaptureOptions>\n\nexport type AnalyticsGoalsCollectionOptions = {\n\t/** Set false to keep the object form's other settings while leaving the collection off. */\n\tenabled?: boolean\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's goals. Point it at\n\t * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n}\n\n/** Goals as config, plus the opt-in collection editors manage their own goals through. */\nexport type AnalyticsGoalsOptions = {\n\tdefaults?: Goal[]\n\t/** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */\n\tcollection?: boolean | AnalyticsGoalsCollectionOptions\n}\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which adapter fills each capture slot, overriding the defaults: `global` is the\n\t * designated `platformAdapter`, or the single config adapter when only one is\n\t * configured; `tenant` is the resolved scope's default adapter. A `global` id must\n\t * name a config adapter; a `tenant` id may also name a runtime provider instance,\n\t * so it is resolved per request rather than validated at config time.\n\t *\n\t * `false` disables a slot outright: it fills with nothing, its proxy mount 404s, and\n\t * the tracker config omits it. Use it to keep a default from filling a slot at all.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Defaults to the runtime proxy endpoint\n\t * (`<routes.api>/analytics/p/<slot>`); set it when the slot is served through Next\n\t * rewrites instead, passing the same path `captureRewrites` was mounted at.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Whether a slot's tracker waits for consent. Native defaults to no gate, vendors to one. */\n\tconsent?: CaptureConsentOption\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsViewOptions = {\n\t/** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */\n\tpath?: `/${string}`\n\t/** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */\n\tdefaultRange?: TimeframePreset\n\t/** Metric the cards and the trend open on. Default `pageviews`. */\n\tdefaultMetric?: MetricKey\n\t/**\n\t * Nav link label. A string is used as-is; a map is keyed by admin language code and\n\t * falls back to `en`. Unset, the plugin's own translated label applies.\n\t */\n\tnavLabel?: string | Record<string, string>\n}\n\nexport interface ResolvedView {\n\tpath: `/${string}`\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tnavLabel?: string | Record<string, string>\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * Enumerates the tenant scopes the cache-warming and sync cron tiers fan out\n\t * over, in addition to the install-wide (null) scope every tier already runs.\n\t * Unset, those tiers run once for the whole install, same as before.\n\t */\n\tscopes?: ScopesResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * The analytics admin view and its nav link, on by default. `false` registers neither;\n\t * the read endpoints stay mounted either way, so a custom surface keeps working.\n\t */\n\tview?: false | AnalyticsViewOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and the native ingest match events against. Slugs must\n\t * be unique and kebab-case; only the slug and its match reach the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: {\n\t\tttl?: { aggregate?: number; realtime?: number }\n\t\twarm?: boolean | { cron?: string }\n\t\t/** Per-read provider timeout in ms, spanning retries and limiter waits. Default 15000. */\n\t\ttimeoutMs?: number\n\t}\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tconsent: ConsentPolicy\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw scopes option; undefined runs the cron tiers install-wide only. */\n\tscopes?: ScopesResolver\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: {\n\t\tplatformRead: PlatformReadAccess\n\t\tread: AnalyticsReadAccess\n\t\tview: AnalyticsViewAccess\n\t}\n\t/** The admin view, filled with its defaults, or false when the app turned it off. */\n\tview: false | ResolvedView\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; the goals collection layers its own on top of these. */\n\tgoals: Goal[]\n\tgoalsCollection: {\n\t\tenabled: boolean\n\t\tslug: string\n\t\tscopeField: string\n\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\taccess?: Partial<CollectionConfig['access']>\n\t}\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t\ttimeoutMs: number\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n}\n\nconst resolveAutoCapture = (option: AutoCaptureOptions | undefined): ResolvedAutoCapture => ({\n\tscrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,\n\toutboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,\n\tfileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,\n\tgoalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute,\n})\n\n/** Cookieless native capture needs no consent gate; a vendor's tracker does. */\nexport const defaultConsentFor = (kind: CaptureClientKind): ConsentMode =>\n\tkind === 'native' ? 'none' : 'required'\n\nconst resolveConsent = (\n\toption: CaptureConsentOption | undefined,\n\tadapters: AnalyticsAdapter[]\n): ConsentPolicy => {\n\tif (option === 'none' || option === 'required') {\n\t\treturn () => option\n\t}\n\tif (typeof option === 'function') {\n\t\treturn (slot, adapterId) => option({ slot, adapterId })\n\t}\n\tfor (const id of Object.keys(option?.adapters ?? {})) {\n\t\t// A runtime provider instance id is `<provider>:<instance>` and only exists once a\n\t\t// scope resolves, so it cannot be checked here; a bare id must name a config adapter.\n\t\tif (!id.includes(':') && !adapters.some((a) => a.id === id)) {\n\t\t\tthrow new Error(`analytics: unknown consent adapter \"${id}\"`)\n\t\t}\n\t}\n\treturn (slot, adapterId, kind) =>\n\t\toption?.adapters?.[adapterId] ?? option?.slots?.[slot] ?? defaultConsentFor(kind)\n}\n\nconst resolveGoals = (option: AnalyticsPluginOptions['goals']): Goal[] => {\n\tconst goals = Array.isArray(option) ? option : (option?.defaults ?? [])\n\tconst seen = new Set<string>()\n\tfor (const goal of goals) {\n\t\tif (!GOAL_SLUG_PATTERN.test(goal.slug)) {\n\t\t\tthrow new Error(`analytics: goal slug \"${goal.slug}\" must be kebab-case`)\n\t\t}\n\t\tif (seen.has(goal.slug)) {\n\t\t\tthrow new Error(`analytics: duplicate goal slug \"${goal.slug}\"`)\n\t\t}\n\t\tconst fixed = goal.value?.fixed\n\t\t// Revenue is money: a negative or non-finite fixed value would be silently ignored at\n\t\t// ingest, so it fails the boot instead.\n\t\tif (fixed !== undefined && (!Number.isFinite(fixed) || fixed < 0)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: goal \"${goal.slug}\" value.fixed must be a finite number >= 0, got ${String(fixed)}`\n\t\t\t)\n\t\t}\n\t\tseen.add(goal.slug)\n\t}\n\treturn goals\n}\n\nconst resolveGoalsCollection = (\n\toption: AnalyticsPluginOptions['goals']\n): ResolvedOptions['goalsCollection'] => {\n\tconst off = { enabled: false, slug: GOALS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\tconst collection = Array.isArray(option) ? undefined : option?.collection\n\tif (!collection) {\n\t\treturn off\n\t}\n\tconst resolved =\n\t\tcollection === true\n\t\t\t? { ...off, enabled: true }\n\t\t\t: {\n\t\t\t\t\tenabled: collection.enabled ?? true,\n\t\t\t\t\tslug: collection.slug ?? GOALS_SLUG,\n\t\t\t\t\tscopeField: collection.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\toverrides: collection.overrides,\n\t\t\t\t\taccess: collection.access,\n\t\t\t\t}\n\tif (!resolved.enabled) {\n\t\treturn off\n\t}\n\tif (typeof resolved.slug !== 'string' || resolved.slug.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.slug must be a non-empty collection slug')\n\t}\n\tif (resolved.scopeField.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.scopeField must be a non-empty field name')\n\t}\n\tif (resolved.scopeField.includes('.')) {\n\t\tthrow new Error(\n\t\t\t'analytics: goals.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t)\n\t}\n\treturn { ...resolved, slug: resolved.slug.trim() }\n}\n\nexport const DEFAULT_VIEW: ResolvedView = {\n\tpath: '/analytics',\n\tdefaultRange: 'last30days',\n\tdefaultMetric: 'pageviews',\n}\n\nconst resolveView = (option: AnalyticsPluginOptions['view']): false | ResolvedView => {\n\tif (option === false) {\n\t\treturn false\n\t}\n\tconst path = option?.path ?? DEFAULT_VIEW.path\n\tif (typeof path !== 'string' || !path.startsWith('/')) {\n\t\tthrow new Error(`analytics: view.path must start with \"/\", got \"${String(path)}\"`)\n\t}\n\tconst defaultRange = option?.defaultRange ?? DEFAULT_VIEW.defaultRange\n\tif (!TIMEFRAME_PRESETS.includes(defaultRange)) {\n\t\tthrow new Error(`analytics: unknown view.defaultRange \"${String(defaultRange)}\"`)\n\t}\n\tconst defaultMetric = option?.defaultMetric ?? DEFAULT_VIEW.defaultMetric\n\tif (!(defaultMetric in METRIC_KEYS)) {\n\t\tthrow new Error(`analytics: unknown view.defaultMetric \"${String(defaultMetric)}\"`)\n\t}\n\treturn {\n\t\tpath,\n\t\tdefaultRange,\n\t\tdefaultMetric,\n\t\t...(option?.navLabel !== undefined ? { navLabel: option.navLabel } : {}),\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tfor (const [slot, value] of Object.entries(options.capture?.slots ?? {})) {\n\t\tif (value !== false && typeof value !== 'string' && value !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: capture slot \"${slot}\" must be an adapter id or false, got ${typeof value}`\n\t\t\t)\n\t\t}\n\t}\n\tconst globalSlot = options.capture?.slots?.global\n\t// A tenant id may name a runtime provider instance, which only exists once a scope\n\t// resolves; a global one can only come from the config registry, so it is checked here.\n\tif (typeof globalSlot === 'string' && !options.adapters.some((a) => a.id === globalSlot)) {\n\t\tthrow new Error(`analytics: unknown global capture slot adapter \"${globalSlot}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\t// The view gate defaults to this exact function, so one `access.read` covers both.\n\tconst read: AnalyticsReadAccess = options.access?.read ?? (({ req }) => Boolean(req.user))\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\tscopes: options.scopes,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t\tread,\n\t\t\tview: options.access?.view ?? read,\n\t\t},\n\t\tview: resolveView(options.view),\n\t\tcapture: {\n\t\t\tslots: {\n\t\t\t\tglobal: options.capture?.slots?.global,\n\t\t\t\ttenant: options.capture?.slots?.tenant,\n\t\t\t},\n\t\t\tpaths: {\n\t\t\t\tglobal: options.capture?.paths?.global,\n\t\t\t\ttenant: options.capture?.paths?.tenant,\n\t\t\t},\n\t\t\tconsent: resolveConsent(options.capture?.consent, options.adapters),\n\t\t\tautoCapture: resolveAutoCapture(options.capture?.autoCapture),\n\t\t\tproxy: {\n\t\t\t\ttimeoutMs: options.capture?.proxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\t\t\t\tmaxBodyBytes: options.capture?.proxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n\t\t\t},\n\t\t},\n\t\tgoals: resolveGoals(options.goals),\n\t\tgoalsCollection: resolveGoalsCollection(options.goals),\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t\ttimeoutMs: options.cache?.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;;;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;;AAkY3B,MAAa,uBAA4C;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 /**
3
+ * Resolves the scopes a cron tier (warm, sync) fans out over: the install-wide
4
+ * null scope first, then each tenant scope from `scopes()`, deduplicated (an
5
+ * empty string folds into null). A throwing or rejecting resolver degrades to
6
+ * the null-only pass so one tenant-enumeration bug does not block the whole run.
7
+ */
8
+ const resolveScopeList = async (scopes, payload) => {
9
+ if (!scopes) return [null];
10
+ let raw;
11
+ try {
12
+ const result = await scopes({ payload });
13
+ if (!Array.isArray(result)) throw new Error("scopes() must resolve to an array of scope ids");
14
+ raw = result;
15
+ } catch (err) {
16
+ payload.logger.warn(`analytics: scopes() failed, falling back to the install-wide scope: ${String(err)}`);
17
+ return [null];
18
+ }
19
+ const out = [null];
20
+ const seen = new Set([null]);
21
+ for (const value of raw) {
22
+ const scope = value === "" ? null : value;
23
+ if (seen.has(scope)) continue;
24
+ seen.add(scope);
25
+ out.push(scope);
26
+ }
27
+ return out;
28
+ };
29
+ //#endregion
30
+ export { resolveScopeList };
31
+
32
+ //# sourceMappingURL=scopeList.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scopeList.js","names":[],"sources":["../../src/core/scopeList.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { ScopesResolver } from './options'\n\n/**\n * Resolves the scopes a cron tier (warm, sync) fans out over: the install-wide\n * null scope first, then each tenant scope from `scopes()`, deduplicated (an\n * empty string folds into null). A throwing or rejecting resolver degrades to\n * the null-only pass so one tenant-enumeration bug does not block the whole run.\n */\nexport const resolveScopeList = async (\n\tscopes: ScopesResolver | undefined,\n\tpayload: Payload\n): Promise<Array<string | null>> => {\n\tif (!scopes) {\n\t\treturn [null]\n\t}\n\tlet raw: string[]\n\ttry {\n\t\tconst result = await scopes({ payload })\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error('scopes() must resolve to an array of scope ids')\n\t\t}\n\t\traw = result\n\t} catch (err) {\n\t\tpayload.logger.warn(\n\t\t\t`analytics: scopes() failed, falling back to the install-wide scope: ${String(err)}`\n\t\t)\n\t\treturn [null]\n\t}\n\tconst out: Array<string | null> = [null]\n\tconst seen = new Set<string | null>([null])\n\tfor (const value of raw) {\n\t\tconst scope = value === '' ? null : value\n\t\tif (seen.has(scope)) {\n\t\t\tcontinue\n\t\t}\n\t\tseen.add(scope)\n\t\tout.push(scope)\n\t}\n\treturn out\n}\n"],"mappings":";;;;;;;AASA,MAAa,mBAAmB,OAC/B,QACA,YACmC;CACnC,IAAI,CAAC,QACJ,OAAO,CAAC,IAAI;CAEb,IAAI;CACJ,IAAI;EACH,MAAM,SAAS,MAAM,OAAO,EAAE,QAAQ,CAAC;EACvC,IAAI,CAAC,MAAM,QAAQ,MAAM,GACxB,MAAM,IAAI,MAAM,gDAAgD;EAEjE,MAAM;CACP,SAAS,KAAK;EACb,QAAQ,OAAO,KACd,uEAAuE,OAAO,GAAG,GAClF;EACA,OAAO,CAAC,IAAI;CACb;CACA,MAAM,MAA4B,CAAC,IAAI;CACvC,MAAM,OAAO,IAAI,IAAmB,CAAC,IAAI,CAAC;CAC1C,KAAK,MAAM,SAAS,KAAK;EACxB,MAAM,QAAQ,UAAU,KAAK,OAAO;EACpC,IAAI,KAAK,IAAI,KAAK,GACjB;EAED,KAAK,IAAI,KAAK;EACd,IAAI,KAAK,KAAK;CACf;CACA,OAAO;AACR"}
@@ -1,21 +1,48 @@
1
- import { platformReadFor, resolveRegistryFor, resolveScopeFor } from "../plugin/runtime.js";
2
1
  import "./contract.js";
2
+ import { platformReadGate, resolveRegistryFor, resolveScopeFor } from "../plugin/runtime.js";
3
3
  //#region src/core/scopedRead.ts
4
4
  /**
5
+ * The scope to stamp on one adapter query, or a refusal. Cross-scope reads fail closed
6
+ * behind `platformRead`: the `'*'` marker, and any scoped read through a shared config
7
+ * adapter that cannot narrow the query to one scope (whether or not it is the designated
8
+ * platform adapter), which would otherwise answer with every scope's data. A tenant's own
9
+ * runtime adapters are never gated. Every read path decides this here, so the widgets and
10
+ * the query endpoint cannot drift apart on what counts as cross-scope.
11
+ */
12
+ const resolveQueryScope = async (args) => {
13
+ const { runtime, req, scope, adapter } = args;
14
+ const allowed = args.platformRead ?? platformReadGate(runtime, req);
15
+ if (scope === "*") return await allowed() ? { ok: true } : { ok: false };
16
+ if (scope === null) return { ok: true };
17
+ if (runtime.configAdapterIds.has(adapter.id) && !adapter.capabilities.scopedQueries) return await allowed() ? { ok: true } : { ok: false };
18
+ return {
19
+ ok: true,
20
+ queryScope: scope
21
+ };
22
+ };
23
+ /**
5
24
  * Resolve one read's scope and adapter: explicit scope wins over the request's
6
25
  * resolved scope, the registry is resolved per scope, then the adapter is picked
7
26
  * by id (or the registry default). Cross-scope reads fail closed behind
8
- * `platformRead`: an explicit `'*'` scope always, and any scoped read through a
9
- * shared config adapter that cannot narrow the query to one scope, whether or
10
- * not it is the designated platform adapter. A tenant's own runtime adapters
11
- * are never gated. Any resolution failure (unknown adapter id, a throwing
12
- * scopeResolver or provider lookup) degrades to `{ ok: false }` so read paths
13
- * render their unavailable state instead of throwing.
27
+ * `platformRead`: an explicit `'*'` scope always, any scoped read through a
28
+ * shared config adapter that cannot narrow the query to one scope (whether or
29
+ * not it is the designated platform adapter), and, on a scoped install, a
30
+ * request that resolves no scope at all. That last case is ambiguous rather
31
+ * than intentionally install-wide (a tenant's scopeResolver returning null
32
+ * usually means "no tenant selected", not "read everything"), so it fails
33
+ * closed the same way. An explicit `scope: null` override bypasses that gate:
34
+ * it is the trusted server-side caller's path (cron passes, tests), never a
35
+ * request's own resolution. A tenant's own runtime adapters are never gated.
36
+ * Any resolution failure (unknown adapter id, a throwing scopeResolver or
37
+ * provider lookup) degrades to `{ ok: false }` so read paths render their
38
+ * unavailable state instead of throwing.
14
39
  */
15
40
  const resolveReadContext = async (args) => {
16
41
  const { runtime, req, adapterId } = args;
42
+ const allowed = platformReadGate(runtime, req);
17
43
  try {
18
44
  const scope = args.scope !== void 0 ? args.scope : await resolveScopeFor(runtime, req);
45
+ if (runtime.scoped && args.scope === void 0 && scope === null && !await allowed()) return { ok: false };
19
46
  const registryScope = scope === "*" ? null : scope;
20
47
  const registry = await resolveRegistryFor(runtime, {
21
48
  payload: req.payload,
@@ -23,29 +50,19 @@ const resolveReadContext = async (args) => {
23
50
  scope: registryScope
24
51
  });
25
52
  const adapter = adapterId ? registry.get(adapterId) : registry.default();
26
- if (scope === "*") {
27
- if (!await platformReadFor(runtime, req)) return { ok: false };
28
- return {
29
- ok: true,
30
- adapter,
31
- scope: null,
32
- queryScope: void 0
33
- };
34
- }
35
- if (scope !== null && runtime.configAdapterIds.has(adapter.id) && !adapter.capabilities.scopedQueries) {
36
- if (!await platformReadFor(runtime, req)) return { ok: false };
37
- return {
38
- ok: true,
39
- adapter,
40
- scope,
41
- queryScope: void 0
42
- };
43
- }
53
+ const decision = await resolveQueryScope({
54
+ runtime,
55
+ req,
56
+ scope,
57
+ adapter,
58
+ platformRead: allowed
59
+ });
60
+ if (!decision.ok) return { ok: false };
44
61
  return {
45
62
  ok: true,
46
63
  adapter,
47
- scope,
48
- queryScope: scope ?? void 0
64
+ scope: registryScope,
65
+ queryScope: decision.queryScope
49
66
  };
50
67
  } catch (err) {
51
68
  req.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`);
@@ -53,6 +70,6 @@ const resolveReadContext = async (args) => {
53
70
  }
54
71
  };
55
72
  //#endregion
56
- export { resolveReadContext };
73
+ export { resolveQueryScope, resolveReadContext };
57
74
 
58
75
  //# sourceMappingURL=scopedRead.js.map