@10x-media/analytics 0.1.0-beta.4 → 1.0.0-beta.10

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 (521) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/LICENSE +21 -21
  3. package/README.md +15 -4
  4. package/dist/adapters/ga4/disableKey.d.ts +9 -0
  5. package/dist/adapters/ga4/disableKey.js +21 -0
  6. package/dist/adapters/ga4/disableKey.js.map +1 -0
  7. package/dist/adapters/ga4/eventName.d.ts +15 -0
  8. package/dist/adapters/ga4/eventName.js +19 -0
  9. package/dist/adapters/ga4/eventName.js.map +1 -0
  10. package/dist/adapters/ga4/ga4.d.ts +5 -0
  11. package/dist/adapters/ga4/ga4.js +186 -58
  12. package/dist/adapters/ga4/ga4.js.map +1 -1
  13. package/dist/adapters/ga4/measurementId.js +15 -0
  14. package/dist/adapters/ga4/measurementId.js.map +1 -0
  15. package/dist/adapters/goalRead.js +126 -0
  16. package/dist/adapters/goalRead.js.map +1 -0
  17. package/dist/adapters/http/fetchJson.js +1 -1
  18. package/dist/adapters/plausible/plausible.d.ts +25 -0
  19. package/dist/adapters/plausible/plausible.js +159 -38
  20. package/dist/adapters/plausible/plausible.js.map +1 -1
  21. package/dist/adapters/posthog/posthog.d.ts +10 -1
  22. package/dist/adapters/posthog/posthog.js +130 -21
  23. package/dist/adapters/posthog/posthog.js.map +1 -1
  24. package/dist/adapters/series.js +11 -1
  25. package/dist/adapters/series.js.map +1 -1
  26. package/dist/adapters/umami/umami.d.ts +13 -1
  27. package/dist/adapters/umami/umami.js +278 -26
  28. package/dist/adapters/umami/umami.js.map +1 -1
  29. package/dist/binding/resolvePath.js +18 -2
  30. package/dist/binding/resolvePath.js.map +1 -1
  31. package/dist/capture/getTrackerConfig.d.ts +20 -0
  32. package/dist/capture/getTrackerConfig.js +31 -0
  33. package/dist/capture/getTrackerConfig.js.map +1 -0
  34. package/dist/capture/mountPath.js +14 -0
  35. package/dist/capture/mountPath.js.map +1 -0
  36. package/dist/capture/proxyEndpoint.js +127 -0
  37. package/dist/capture/proxyEndpoint.js.map +1 -0
  38. package/dist/capture/proxyRoutes.js +108 -0
  39. package/dist/capture/proxyRoutes.js.map +1 -0
  40. package/dist/capture/requestBody.js +68 -0
  41. package/dist/capture/requestBody.js.map +1 -0
  42. package/dist/capture/slots.d.ts +8 -0
  43. package/dist/capture/slots.js +54 -0
  44. package/dist/capture/slots.js.map +1 -0
  45. package/dist/capture/trackerConfig.d.ts +33 -0
  46. package/dist/capture/trackerConfig.js +95 -0
  47. package/dist/capture/trackerConfig.js.map +1 -0
  48. package/dist/capture/trackerEndpoint.js +35 -0
  49. package/dist/capture/trackerEndpoint.js.map +1 -0
  50. package/dist/charts/BarList.d.ts +16 -1
  51. package/dist/charts/BarList.js +41 -19
  52. package/dist/charts/BarList.js.map +1 -1
  53. package/dist/charts/TrendChart.d.ts +16 -3
  54. package/dist/charts/TrendChart.js +172 -106
  55. package/dist/charts/TrendChart.js.map +1 -1
  56. package/dist/charts/bars.d.ts +4 -0
  57. package/dist/charts/bars.js +3 -1
  58. package/dist/charts/bars.js.map +1 -1
  59. package/dist/charts/bucket.js +10 -1
  60. package/dist/charts/bucket.js.map +1 -1
  61. package/dist/charts/spline.js +2 -2
  62. package/dist/charts/spline.js.map +1 -1
  63. package/dist/charts/styles.js +18 -1
  64. package/dist/charts/styles.js.map +1 -1
  65. package/dist/core/cacheKey.js +26 -3
  66. package/dist/core/cacheKey.js.map +1 -1
  67. package/dist/core/capabilities.d.ts +17 -2
  68. package/dist/core/capabilities.js +20 -1
  69. package/dist/core/capabilities.js.map +1 -1
  70. package/dist/core/capture.d.ts +49 -0
  71. package/dist/core/contract.d.ts +74 -5
  72. package/dist/core/contract.js +30 -1
  73. package/dist/core/contract.js.map +1 -1
  74. package/dist/core/granularity.js +1 -1
  75. package/dist/core/options.d.ts +168 -8
  76. package/dist/core/options.js +132 -4
  77. package/dist/core/options.js.map +1 -1
  78. package/dist/core/registry.d.ts +1 -0
  79. package/dist/core/scopeList.js +32 -0
  80. package/dist/core/scopeList.js.map +1 -0
  81. package/dist/core/scopedRead.js +101 -29
  82. package/dist/core/scopedRead.js.map +1 -1
  83. package/dist/core/serverEvent.d.ts +60 -0
  84. package/dist/core/serverEvent.js +12 -0
  85. package/dist/core/serverEvent.js.map +1 -0
  86. package/dist/exports/adapters/ga4.d.ts +2 -1
  87. package/dist/exports/adapters/ga4.js +2 -1
  88. package/dist/exports/adapters/native.d.ts +3 -1
  89. package/dist/exports/adapters/native.js +2 -1
  90. package/dist/exports/client.d.ts +16 -2
  91. package/dist/exports/client.js +13 -1
  92. package/dist/exports/geo.d.ts +2 -2
  93. package/dist/exports/next.d.ts +2 -1
  94. package/dist/exports/next.js +2 -1
  95. package/dist/exports/react.d.ts +4 -0
  96. package/dist/exports/react.js +5 -0
  97. package/dist/exports/rsc.d.ts +12 -4
  98. package/dist/exports/rsc.js +7 -2
  99. package/dist/exports/tracker.d.ts +21 -0
  100. package/dist/exports/tracker.js +15 -0
  101. package/dist/exports/types.d.ts +17 -3
  102. package/dist/exports/types.js +4 -2
  103. package/dist/fields/AnalyticsPanelClient.js +2 -2
  104. package/dist/fields/AnalyticsPanelField.js +1 -1
  105. package/dist/fields/AnalyticsStatField.js +2 -2
  106. package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
  107. package/dist/fields/config/FilterDimensionSelectField.js +77 -0
  108. package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
  109. package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
  110. package/dist/fields/config/FilterOperatorSelectField.js +75 -0
  111. package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
  112. package/dist/fields/config/MetricSelectField.d.ts +23 -0
  113. package/dist/fields/config/MetricSelectField.js +51 -0
  114. package/dist/fields/config/MetricSelectField.js.map +1 -0
  115. package/dist/fields/config/SourceSelectField.d.ts +14 -0
  116. package/dist/fields/config/SourceSelectField.js +46 -0
  117. package/dist/fields/config/SourceSelectField.js.map +1 -0
  118. package/dist/fields/config/fetchSources.d.ts +16 -0
  119. package/dist/fields/config/fetchSources.js +33 -0
  120. package/dist/fields/config/fetchSources.js.map +1 -0
  121. package/dist/fields/config/narrow.js +32 -0
  122. package/dist/fields/config/narrow.js.map +1 -0
  123. package/dist/fields/config/sourcesState.js +27 -0
  124. package/dist/fields/config/sourcesState.js.map +1 -0
  125. package/dist/fields/config/toSelectOption.js +27 -0
  126. package/dist/fields/config/toSelectOption.js.map +1 -0
  127. package/dist/fields/config/useAnalyticsSources.d.ts +24 -0
  128. package/dist/fields/config/useAnalyticsSources.js +62 -0
  129. package/dist/fields/config/useAnalyticsSources.js.map +1 -0
  130. package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
  131. package/dist/fields/config/useFilterCapabilities.js +52 -0
  132. package/dist/fields/config/useFilterCapabilities.js.map +1 -0
  133. package/dist/fields/readForDocument.d.ts +5 -0
  134. package/dist/fields/readForDocument.js +22 -10
  135. package/dist/fields/readForDocument.js.map +1 -1
  136. package/dist/goals/GoalSelectField.d.ts +7 -0
  137. package/dist/goals/GoalSelectField.js +77 -0
  138. package/dist/goals/GoalSelectField.js.map +1 -0
  139. package/dist/goals/collection.js +254 -0
  140. package/dist/goals/collection.js.map +1 -0
  141. package/dist/goals/currency.js +14 -0
  142. package/dist/goals/currency.js.map +1 -0
  143. package/dist/goals/fetchGoals.d.ts +18 -0
  144. package/dist/goals/fetchGoals.js +33 -0
  145. package/dist/goals/fetchGoals.js.map +1 -0
  146. package/dist/goals/goalField.d.ts +31 -0
  147. package/dist/goals/goalField.js +56 -0
  148. package/dist/goals/goalField.js.map +1 -0
  149. package/dist/goals/goalsEndpoint.d.ts +1 -0
  150. package/dist/goals/goalsEndpoint.js +58 -0
  151. package/dist/goals/goalsEndpoint.js.map +1 -0
  152. package/dist/goals/match.js +64 -0
  153. package/dist/goals/match.js.map +1 -0
  154. package/dist/goals/resolver.d.ts +8 -0
  155. package/dist/goals/resolver.js +147 -0
  156. package/dist/goals/resolver.js.map +1 -0
  157. package/dist/goals/trackGoalAction.d.ts +76 -0
  158. package/dist/goals/trackGoalAction.js +158 -0
  159. package/dist/goals/trackGoalAction.js.map +1 -0
  160. package/dist/goals/types.d.ts +33 -0
  161. package/dist/goals/types.js +7 -0
  162. package/dist/goals/types.js.map +1 -0
  163. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  164. package/dist/goals/useAnalyticsGoals.js +67 -0
  165. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  166. package/dist/index.d.ts +14 -3
  167. package/dist/index.js +185 -19
  168. package/dist/index.js.map +1 -1
  169. package/dist/native/collections/events.js +65 -1
  170. package/dist/native/collections/events.js.map +1 -1
  171. package/dist/native/collections/rollups.js +39 -3
  172. package/dist/native/collections/rollups.js.map +1 -1
  173. package/dist/native/eventScan.js +25 -0
  174. package/dist/native/eventScan.js.map +1 -0
  175. package/dist/native/geo/composeGeoResolvers.js +2 -2
  176. package/dist/native/geo/composeGeoResolvers.js.map +1 -1
  177. package/dist/native/geo/geoResolver.d.ts +9 -2
  178. package/dist/native/geo/geoResolver.js.map +1 -1
  179. package/dist/native/geo/maxmindResolver.js +3 -5
  180. package/dist/native/geo/maxmindResolver.js.map +1 -1
  181. package/dist/native/ingest/bots.d.ts +11 -0
  182. package/dist/native/ingest/bots.js +71 -0
  183. package/dist/native/ingest/bots.js.map +1 -0
  184. package/dist/native/ingest/browser.js +47 -0
  185. package/dist/native/ingest/browser.js.map +1 -0
  186. package/dist/native/ingest/clientIp.js +20 -0
  187. package/dist/native/ingest/clientIp.js.map +1 -0
  188. package/dist/native/ingest/device.js +11 -3
  189. package/dist/native/ingest/device.js.map +1 -1
  190. package/dist/native/ingest/endpoint.d.ts +1 -0
  191. package/dist/native/ingest/endpoint.js +107 -21
  192. package/dist/native/ingest/endpoint.js.map +1 -1
  193. package/dist/native/ingest/flushBatch.js +29 -38
  194. package/dist/native/ingest/flushBatch.js.map +1 -1
  195. package/dist/native/ingest/language.js +14 -0
  196. package/dist/native/ingest/language.js.map +1 -0
  197. package/dist/native/ingest/normalizeEvent.d.ts +30 -0
  198. package/dist/native/ingest/normalizeEvent.js +115 -16
  199. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  200. package/dist/native/ingest/referrer.js +48 -0
  201. package/dist/native/ingest/referrer.js.map +1 -0
  202. package/dist/native/ingest/requestHost.js +57 -0
  203. package/dist/native/ingest/requestHost.js.map +1 -0
  204. package/dist/native/ingest/resolveHostname.d.ts +29 -0
  205. package/dist/native/ingest/resolveHostname.js +52 -0
  206. package/dist/native/ingest/resolveHostname.js.map +1 -0
  207. package/dist/native/ingest/salt.js +27 -2
  208. package/dist/native/ingest/salt.js.map +1 -1
  209. package/dist/native/ingest/serverTrack.d.ts +20 -0
  210. package/dist/native/ingest/serverTrack.js +109 -0
  211. package/dist/native/ingest/serverTrack.js.map +1 -0
  212. package/dist/native/ingest/source.d.ts +11 -0
  213. package/dist/native/ingest/source.js +264 -16
  214. package/dist/native/ingest/source.js.map +1 -1
  215. package/dist/native/ingest/utm.js +33 -0
  216. package/dist/native/ingest/utm.js.map +1 -0
  217. package/dist/native/ingest/validate.js +26 -0
  218. package/dist/native/ingest/validate.js.map +1 -0
  219. package/dist/native/nativeAdapter.d.ts +37 -1
  220. package/dist/native/nativeAdapter.js +175 -22
  221. package/dist/native/nativeAdapter.js.map +1 -1
  222. package/dist/native/query/eventAgg.js +175 -0
  223. package/dist/native/query/eventAgg.js.map +1 -0
  224. package/dist/native/retention/pruneTask.js +53 -13
  225. package/dist/native/retention/pruneTask.js.map +1 -1
  226. package/dist/native/rollupAcc.js +12 -1
  227. package/dist/native/rollupAcc.js.map +1 -1
  228. package/dist/native/rollups/bucketKey.js +15 -0
  229. package/dist/native/rollups/bucketKey.js.map +1 -0
  230. package/dist/native/rollups/bumpRollups.js +116 -0
  231. package/dist/native/rollups/bumpRollups.js.map +1 -0
  232. package/dist/native/rollups/deltas.js +86 -11
  233. package/dist/native/rollups/deltas.js.map +1 -1
  234. package/dist/native/rollups/insertManyIfNew.js +93 -0
  235. package/dist/native/rollups/insertManyIfNew.js.map +1 -0
  236. package/dist/next/captureRewrites.d.ts +42 -0
  237. package/dist/next/captureRewrites.js +57 -0
  238. package/dist/next/captureRewrites.js.map +1 -0
  239. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  240. package/dist/next/posthogProxyRewrites.js +16 -21
  241. package/dist/next/posthogProxyRewrites.js.map +1 -1
  242. package/dist/plugin/documentEndpoint.js +71 -24
  243. package/dist/plugin/documentEndpoint.js.map +1 -1
  244. package/dist/plugin/errors.d.ts +31 -0
  245. package/dist/plugin/errors.js +79 -0
  246. package/dist/plugin/errors.js.map +1 -0
  247. package/dist/plugin/goalHint.d.ts +1 -0
  248. package/dist/plugin/goalHint.js +24 -0
  249. package/dist/plugin/goalHint.js.map +1 -0
  250. package/dist/plugin/paths.js +19 -1
  251. package/dist/plugin/paths.js.map +1 -1
  252. package/dist/plugin/queryEndpoint.js +124 -0
  253. package/dist/plugin/queryEndpoint.js.map +1 -0
  254. package/dist/plugin/readContextForRequest.js +73 -0
  255. package/dist/plugin/readContextForRequest.js.map +1 -0
  256. package/dist/plugin/realtimeEndpoint.js +39 -18
  257. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  258. package/dist/plugin/refreshEndpoint.js +113 -0
  259. package/dist/plugin/refreshEndpoint.js.map +1 -0
  260. package/dist/plugin/runtime.d.ts +1 -0
  261. package/dist/plugin/runtime.js +33 -1
  262. package/dist/plugin/runtime.js.map +1 -1
  263. package/dist/plugin/scopeChange.js +22 -0
  264. package/dist/plugin/scopeChange.js.map +1 -0
  265. package/dist/plugin/scopeFieldBoot.js +22 -0
  266. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  267. package/dist/plugin/sourcesEndpoint.js +28 -0
  268. package/dist/plugin/sourcesEndpoint.js.map +1 -0
  269. package/dist/plugin/warmTask.js +0 -0
  270. package/dist/plugin/warmTask.js.map +1 -1
  271. package/dist/providers/access.js +2 -1
  272. package/dist/providers/access.js.map +1 -1
  273. package/dist/providers/collection.js +90 -29
  274. package/dist/providers/collection.js.map +1 -1
  275. package/dist/providers/factory.js +11 -3
  276. package/dist/providers/factory.js.map +1 -1
  277. package/dist/providers/resolver.js.map +1 -1
  278. package/dist/query/dates.js +64 -0
  279. package/dist/query/dates.js.map +1 -0
  280. package/dist/query/errors.d.ts +14 -0
  281. package/dist/query/fetchQuery.d.ts +79 -0
  282. package/dist/query/fetchQuery.js +117 -0
  283. package/dist/query/fetchQuery.js.map +1 -0
  284. package/dist/query/parse.d.ts +22 -0
  285. package/dist/query/parse.js +168 -0
  286. package/dist/query/parse.js.map +1 -0
  287. package/dist/query/response.d.ts +39 -0
  288. package/dist/query/response.js +11 -0
  289. package/dist/query/response.js.map +1 -0
  290. package/dist/react/AnalyticsProvider.d.ts +50 -0
  291. package/dist/react/AnalyticsProvider.js +67 -0
  292. package/dist/react/AnalyticsProvider.js.map +1 -0
  293. package/dist/react/TrackerBoot.d.ts +22 -0
  294. package/dist/react/TrackerBoot.js +30 -0
  295. package/dist/react/TrackerBoot.js.map +1 -0
  296. package/dist/react/useAnalytics.d.ts +20 -0
  297. package/dist/react/useAnalytics.js +52 -0
  298. package/dist/react/useAnalytics.js.map +1 -0
  299. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  300. package/dist/rsc/AnalyticsScripts.js +41 -0
  301. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  302. package/dist/surfacing/cacheStore.d.ts +1 -0
  303. package/dist/surfacing/cacheStore.js +18 -2
  304. package/dist/surfacing/cacheStore.js.map +1 -1
  305. package/dist/surfacing/engine.d.ts +1 -0
  306. package/dist/surfacing/engine.js +47 -6
  307. package/dist/surfacing/engine.js.map +1 -1
  308. package/dist/surfacing/epoch.d.ts +1 -0
  309. package/dist/surfacing/epoch.js +72 -0
  310. package/dist/surfacing/epoch.js.map +1 -0
  311. package/dist/surfacing/queue.js +22 -6
  312. package/dist/surfacing/queue.js.map +1 -1
  313. package/dist/surfacing/rateLimiter.js +130 -0
  314. package/dist/surfacing/rateLimiter.js.map +1 -0
  315. package/dist/surfacing/retryPolicy.js +15 -0
  316. package/dist/surfacing/retryPolicy.js.map +1 -0
  317. package/dist/sync/collection.js +23 -7
  318. package/dist/sync/collection.js.map +1 -1
  319. package/dist/sync/syncTask.js +68 -33
  320. package/dist/sync/syncTask.js.map +1 -1
  321. package/dist/testing/memoryAdapter.d.ts +2 -0
  322. package/dist/testing/memoryAdapter.js +17 -1
  323. package/dist/testing/memoryAdapter.js.map +1 -1
  324. package/dist/timeframe/tz.js +17 -6
  325. package/dist/timeframe/tz.js.map +1 -1
  326. package/dist/tracker/autoCapture.d.ts +48 -0
  327. package/dist/tracker/autoCapture.js +129 -0
  328. package/dist/tracker/autoCapture.js.map +1 -0
  329. package/dist/tracker/consent.d.ts +24 -0
  330. package/dist/tracker/consent.js +48 -0
  331. package/dist/tracker/consent.js.map +1 -0
  332. package/dist/tracker/createTracker.d.ts +18 -0
  333. package/dist/tracker/createTracker.js +215 -0
  334. package/dist/tracker/createTracker.js.map +1 -0
  335. package/dist/tracker/exclusion.d.ts +28 -0
  336. package/dist/tracker/exclusion.js +50 -0
  337. package/dist/tracker/exclusion.js.map +1 -0
  338. package/dist/tracker/initTracker.d.ts +22 -0
  339. package/dist/tracker/initTracker.js +33 -0
  340. package/dist/tracker/initTracker.js.map +1 -0
  341. package/dist/tracker/loadScript.d.ts +14 -0
  342. package/dist/tracker/loadScript.js +41 -0
  343. package/dist/tracker/loadScript.js.map +1 -0
  344. package/dist/tracker/pageTracking.d.ts +17 -0
  345. package/dist/tracker/pageTracking.js +38 -0
  346. package/dist/tracker/pageTracking.js.map +1 -0
  347. package/dist/tracker/registry.d.ts +27 -0
  348. package/dist/tracker/registry.js +73 -0
  349. package/dist/tracker/registry.js.map +1 -0
  350. package/dist/tracker/sinks/ga4.d.ts +29 -0
  351. package/dist/tracker/sinks/ga4.js +30 -0
  352. package/dist/tracker/sinks/ga4.js.map +1 -0
  353. package/dist/tracker/sinks/native.d.ts +22 -0
  354. package/dist/tracker/sinks/native.js +56 -0
  355. package/dist/tracker/sinks/native.js.map +1 -0
  356. package/dist/tracker/sinks/plausible.d.ts +20 -0
  357. package/dist/tracker/sinks/plausible.js +32 -0
  358. package/dist/tracker/sinks/plausible.js.map +1 -0
  359. package/dist/tracker/sinks/posthog.d.ts +18 -0
  360. package/dist/tracker/sinks/posthog.js +30 -0
  361. package/dist/tracker/sinks/posthog.js.map +1 -0
  362. package/dist/tracker/sinks/umami.d.ts +18 -0
  363. package/dist/tracker/sinks/umami.js +23 -0
  364. package/dist/tracker/sinks/umami.js.map +1 -0
  365. package/dist/tracker/sinks/vendor.d.ts +14 -0
  366. package/dist/tracker/sinks/vendor.js +81 -0
  367. package/dist/tracker/sinks/vendor.js.map +1 -0
  368. package/dist/tracker/transport.js +28 -0
  369. package/dist/tracker/transport.js.map +1 -0
  370. package/dist/tracker/types.d.ts +91 -0
  371. package/dist/translations/ar.js +221 -0
  372. package/dist/translations/ar.js.map +1 -0
  373. package/dist/translations/de.js +145 -1
  374. package/dist/translations/de.js.map +1 -1
  375. package/dist/translations/en.js +145 -1
  376. package/dist/translations/en.js.map +1 -1
  377. package/dist/translations/es.js +221 -0
  378. package/dist/translations/es.js.map +1 -0
  379. package/dist/translations/fr.js +221 -0
  380. package/dist/translations/fr.js.map +1 -0
  381. package/dist/translations/id.js +221 -0
  382. package/dist/translations/id.js.map +1 -0
  383. package/dist/translations/index.d.ts +10 -1
  384. package/dist/translations/index.js +19 -1
  385. package/dist/translations/index.js.map +1 -1
  386. package/dist/translations/keys.d.ts +144 -0
  387. package/dist/translations/keys.js +145 -1
  388. package/dist/translations/keys.js.map +1 -1
  389. package/dist/translations/ko.js +221 -0
  390. package/dist/translations/ko.js.map +1 -0
  391. package/dist/translations/metricKeys.js +8 -2
  392. package/dist/translations/metricKeys.js.map +1 -1
  393. package/dist/translations/pt.js +221 -0
  394. package/dist/translations/pt.js.map +1 -0
  395. package/dist/translations/ru.js +221 -0
  396. package/dist/translations/ru.js.map +1 -0
  397. package/dist/translations/server.js.map +1 -1
  398. package/dist/translations/uk.js +221 -0
  399. package/dist/translations/uk.js.map +1 -0
  400. package/dist/translations/zh.js +221 -0
  401. package/dist/translations/zh.js.map +1 -0
  402. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  403. package/dist/view/AnalyticsNavLink.js +40 -0
  404. package/dist/view/AnalyticsNavLink.js.map +1 -0
  405. package/dist/view/AnalyticsView.d.ts +23 -0
  406. package/dist/view/AnalyticsView.js +45 -0
  407. package/dist/view/AnalyticsView.js.map +1 -0
  408. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  409. package/dist/view/AnalyticsViewClient.js +244 -0
  410. package/dist/view/AnalyticsViewClient.js.map +1 -0
  411. package/dist/view/authRedirect.js +32 -0
  412. package/dist/view/authRedirect.js.map +1 -0
  413. package/dist/view/conversionRate.js +18 -0
  414. package/dist/view/conversionRate.js.map +1 -0
  415. package/dist/view/dayRange.js +68 -0
  416. package/dist/view/dayRange.js.map +1 -0
  417. package/dist/view/gating.d.ts +1 -0
  418. package/dist/view/gating.js +142 -0
  419. package/dist/view/gating.js.map +1 -0
  420. package/dist/view/labels.js +76 -0
  421. package/dist/view/labels.js.map +1 -0
  422. package/dist/view/registerView.js +48 -0
  423. package/dist/view/registerView.js.map +1 -0
  424. package/dist/view/sections/Breakdowns.js +198 -0
  425. package/dist/view/sections/Breakdowns.js.map +1 -0
  426. package/dist/view/sections/EmptyStates.js +92 -0
  427. package/dist/view/sections/EmptyStates.js.map +1 -0
  428. package/dist/view/sections/FilterChips.js +46 -0
  429. package/dist/view/sections/FilterChips.js.map +1 -0
  430. package/dist/view/sections/GoalsPanel.js +82 -0
  431. package/dist/view/sections/GoalsPanel.js.map +1 -0
  432. package/dist/view/sections/OverviewCards.js +65 -0
  433. package/dist/view/sections/OverviewCards.js.map +1 -0
  434. package/dist/view/sections/RealtimeStrip.js +80 -0
  435. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  436. package/dist/view/sections/Toolbar.js +207 -0
  437. package/dist/view/sections/Toolbar.js.map +1 -0
  438. package/dist/view/sections/Trend.js +125 -0
  439. package/dist/view/sections/Trend.js.map +1 -0
  440. package/dist/view/sections/styles.js +76 -0
  441. package/dist/view/sections/styles.js.map +1 -0
  442. package/dist/view/state.js +211 -0
  443. package/dist/view/state.js.map +1 -0
  444. package/dist/view/useViewQueries.js +153 -0
  445. package/dist/view/useViewQueries.js.map +1 -0
  446. package/dist/view/viewProps.d.ts +40 -0
  447. package/dist/view/viewProps.js +90 -0
  448. package/dist/view/viewProps.js.map +1 -0
  449. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  450. package/dist/widgets/AnalyticsBreakdownWidget.js +78 -11
  451. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  452. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  453. package/dist/widgets/AnalyticsGoalsWidget.js +196 -0
  454. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  455. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  456. package/dist/widgets/AnalyticsMetricWidget.js +63 -13
  457. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  458. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  459. package/dist/widgets/AnalyticsRealtimeWidget.js +45 -23
  460. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  461. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  462. package/dist/widgets/AnalyticsTrendWidget.js +79 -16
  463. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  464. package/dist/widgets/RealtimeCounter.d.ts +4 -0
  465. package/dist/widgets/RealtimeCounter.js +18 -4
  466. package/dist/widgets/RealtimeCounter.js.map +1 -1
  467. package/dist/widgets/WidgetViewLink.js +17 -0
  468. package/dist/widgets/WidgetViewLink.js.map +1 -0
  469. package/dist/widgets/breakdownTypes.js +38 -0
  470. package/dist/widgets/breakdownTypes.js.map +1 -1
  471. package/dist/widgets/cardChrome.js +31 -7
  472. package/dist/widgets/cardChrome.js.map +1 -1
  473. package/dist/widgets/comparison.js +15 -1
  474. package/dist/widgets/comparison.js.map +1 -1
  475. package/dist/widgets/defaults.d.ts +6 -2
  476. package/dist/widgets/defaults.js +78 -23
  477. package/dist/widgets/defaults.js.map +1 -1
  478. package/dist/widgets/filterCaption.js +27 -0
  479. package/dist/widgets/filterCaption.js.map +1 -0
  480. package/dist/widgets/filterField.d.ts +19 -0
  481. package/dist/widgets/filterField.js +75 -0
  482. package/dist/widgets/filterField.js.map +1 -0
  483. package/dist/widgets/prepareWidgetRead.d.ts +7 -0
  484. package/dist/widgets/prepareWidgetRead.js +74 -0
  485. package/dist/widgets/prepareWidgetRead.js.map +1 -0
  486. package/dist/widgets/range.js +43 -12
  487. package/dist/widgets/range.js.map +1 -1
  488. package/dist/widgets/readForWidget.d.ts +26 -3
  489. package/dist/widgets/readForWidget.js +48 -44
  490. package/dist/widgets/readForWidget.js.map +1 -1
  491. package/dist/widgets/readForWidgetBreakdown.d.ts +34 -2
  492. package/dist/widgets/readForWidgetBreakdown.js +53 -49
  493. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  494. package/dist/widgets/readForWidgetGoals.d.ts +67 -0
  495. package/dist/widgets/readForWidgetGoals.js +140 -0
  496. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  497. package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
  498. package/dist/widgets/readForWidgetRealtime.js +23 -21
  499. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  500. package/dist/widgets/readForWidgetSeries.d.ts +26 -2
  501. package/dist/widgets/readForWidgetSeries.js +78 -53
  502. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  503. package/dist/widgets/readMeta.js +18 -0
  504. package/dist/widgets/readMeta.js.map +1 -0
  505. package/dist/widgets/realtimePoll.js +16 -1
  506. package/dist/widgets/realtimePoll.js.map +1 -1
  507. package/dist/widgets/registerWidgets.js +76 -14
  508. package/dist/widgets/registerWidgets.js.map +1 -1
  509. package/dist/widgets/types.d.ts +15 -0
  510. package/dist/widgets/types.js +16 -2
  511. package/dist/widgets/types.js.map +1 -1
  512. package/dist/widgets/viewLink.d.ts +22 -0
  513. package/dist/widgets/viewLink.js +86 -0
  514. package/dist/widgets/viewLink.js.map +1 -0
  515. package/package.json +27 -7
  516. package/dist/native/rollups/applyDistinctDeltas.js +0 -9
  517. package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
  518. package/dist/native/rollups/bumpRollup.js +0 -68
  519. package/dist/native/rollups/bumpRollup.js.map +0 -1
  520. package/dist/native/rollups/insertIfNew.js +0 -19
  521. package/dist/native/rollups/insertIfNew.js.map +0 -1
@@ -0,0 +1,33 @@
1
+ import { GOALS_PATH } from "../plugin/paths.js";
2
+ import { readResponseError } from "../plugin/errors.js";
3
+ //#region src/goals/fetchGoals.ts
4
+ const cache = /* @__PURE__ */ new Map();
5
+ /**
6
+ * Fetch the caller-scope goal list once per user per admin session and share it between
7
+ * every picker on the page (a document can carry several goal fields). A failed fetch
8
+ * clears its cache entry so a later mount retries instead of pinning the error, and the
9
+ * user id in the key keeps a soft-navigation logout/login from serving the previous
10
+ * user's goals.
11
+ */
12
+ const fetchGoals = (serverURL, apiRoute, userKey) => {
13
+ const url = `${serverURL}${apiRoute}${GOALS_PATH}`;
14
+ const key = `${userKey}:${url}`;
15
+ const hit = cache.get(key);
16
+ if (hit) return hit;
17
+ const pending = fetch(url, { credentials: "include" }).then(async (res) => {
18
+ if (!res.ok) {
19
+ const code = (await readResponseError(res))?.code;
20
+ throw new Error(`analytics: goals ${res.status}${code ? ` ${code}` : ""}`);
21
+ }
22
+ return await res.json();
23
+ }).catch((err) => {
24
+ cache.delete(key);
25
+ throw err;
26
+ });
27
+ cache.set(key, pending);
28
+ return pending;
29
+ };
30
+ //#endregion
31
+ export { fetchGoals };
32
+
33
+ //# sourceMappingURL=fetchGoals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchGoals.js","names":[],"sources":["../../src/goals/fetchGoals.ts"],"sourcesContent":["import { readResponseError } from '../plugin/errors'\nimport { GOALS_PATH } from '../plugin/paths'\nimport type { GoalSource } from './resolver'\n\nexport interface WireGoal {\n\tslug: string\n\tname: string\n\tsource: GoalSource\n}\n\nexport interface GoalsResponse {\n\tgoals: WireGoal[]\n\t/** The goals collection, when the install enabled it, so a picker can link to it. */\n\tcollection: { slug: string } | null\n}\n\nconst cache = new Map<string, Promise<GoalsResponse>>()\n\n/**\n * Fetch the caller-scope goal list once per user per admin session and share it between\n * every picker on the page (a document can carry several goal fields). A failed fetch\n * clears its cache entry so a later mount retries instead of pinning the error, and the\n * user id in the key keeps a soft-navigation logout/login from serving the previous\n * user's goals.\n */\nexport const fetchGoals = (\n\tserverURL: string,\n\tapiRoute: string,\n\tuserKey: string\n): Promise<GoalsResponse> => {\n\tconst url = `${serverURL}${apiRoute}${GOALS_PATH}`\n\tconst key = `${userKey}:${url}`\n\tconst hit = cache.get(key)\n\tif (hit) return hit\n\tconst pending = fetch(url, { credentials: 'include' })\n\t\t.then(async (res) => {\n\t\t\tif (!res.ok) {\n\t\t\t\t// One failed state covers every refusal the picker can get, so the code rides in\n\t\t\t\t// the message rather than becoming a second state nothing would render.\n\t\t\t\tconst code = (await readResponseError(res))?.code\n\t\t\t\tthrow new Error(`analytics: goals ${res.status}${code ? ` ${code}` : ''}`)\n\t\t\t}\n\t\t\treturn (await res.json()) as GoalsResponse\n\t\t})\n\t\t.catch((err) => {\n\t\t\tcache.delete(key)\n\t\t\tthrow err\n\t\t})\n\tcache.set(key, pending)\n\treturn pending\n}\n"],"mappings":";;;AAgBA,MAAM,wBAAQ,IAAI,IAAoC;;;;;;;;AAStD,MAAa,cACZ,WACA,UACA,YAC4B;CAC5B,MAAM,MAAM,GAAG,YAAY,WAAW;CACtC,MAAM,MAAM,GAAG,QAAQ,GAAG;CAC1B,MAAM,MAAM,MAAM,IAAI,GAAG;CACzB,IAAI,KAAK,OAAO;CAChB,MAAM,UAAU,MAAM,KAAK,EAAE,aAAa,UAAU,CAAC,EACnD,KAAK,OAAO,QAAQ;EACpB,IAAI,CAAC,IAAI,IAAI;GAGZ,MAAM,QAAQ,MAAM,kBAAkB,GAAG,IAAI;GAC7C,MAAM,IAAI,MAAM,oBAAoB,IAAI,SAAS,OAAO,IAAI,SAAS,IAAI;EAC1E;EACA,OAAQ,MAAM,IAAI,KAAK;CACxB,CAAC,EACA,OAAO,QAAQ;EACf,MAAM,OAAO,GAAG;EAChB,MAAM;CACP,CAAC;CACF,MAAM,IAAI,KAAK,OAAO;CACtB,OAAO;AACR"}
@@ -0,0 +1,31 @@
1
+ import { LabelFunction, StaticLabel, TextField } from "payload";
2
+
3
+ //#region src/goals/goalField.d.ts
4
+ interface GoalFieldOptions {
5
+ /** Field name, and therefore the property the slug is stored under. Default `'goal'`. */
6
+ name?: string;
7
+ /** Default: the translated "Goal". */
8
+ label?: LabelFunction | StaticLabel;
9
+ required?: boolean;
10
+ /** Merged over the factory's own admin config; the Field component is not replaceable here. */
11
+ admin?: TextField['admin'];
12
+ /** Last word on the built field. Spread the field, never deep-merge it. */
13
+ overrides?: (args: {
14
+ field: TextField;
15
+ }) => TextField;
16
+ }
17
+ /**
18
+ * A goal picker for any collection or global: a text field storing the goal slug, rendered
19
+ * by the client picker that lists the config goals merged with the goals collection for the
20
+ * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.
21
+ */
22
+ declare const goalField: (options?: GoalFieldOptions) => TextField;
23
+ /**
24
+ * The slug out of a stored goal value, for renderers that read a {@link goalField} back.
25
+ * Accepts the stored string and the `{ slug }` shape a populated document carries; anything
26
+ * else is not a goal reference and resolves to null rather than a guess.
27
+ */
28
+ declare const goalSlug: (value: unknown) => string | null;
29
+ //#endregion
30
+ export { GoalFieldOptions, goalField, goalSlug };
31
+ //# sourceMappingURL=goalField.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { keys } from "../translations/keys.js";
2
+ import { asTranslate, labelForKey } from "../translations/server.js";
3
+ import { GOAL_SLUG_PATTERN } from "./types.js";
4
+ //#region src/goals/goalField.ts
5
+ /** importMap path of the picker; the factory never imports the component itself. */
6
+ const GOAL_FIELD_COMPONENT = "@10x-media/analytics/client#GoalSelectField";
7
+ const makeValidate = (required) => (value, { req }) => {
8
+ const slug = typeof value === "string" ? value.trim() : "";
9
+ if (slug === "") return required ? req.t("validation:required") : true;
10
+ return GOAL_SLUG_PATTERN.test(slug) ? true : asTranslate(req.t)(keys.fieldGoalInvalid);
11
+ };
12
+ /**
13
+ * A goal picker for any collection or global: a text field storing the goal slug, rendered
14
+ * by the client picker that lists the config goals merged with the goals collection for the
15
+ * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.
16
+ */
17
+ const goalField = (options = {}) => {
18
+ const field = {
19
+ name: options.name ?? "goal",
20
+ type: "text",
21
+ label: options.label ?? labelForKey(keys.fieldGoalLabel),
22
+ ...options.required ? { required: true } : {},
23
+ validate: makeValidate(Boolean(options.required)),
24
+ admin: {
25
+ ...options.admin,
26
+ components: {
27
+ ...options.admin?.components,
28
+ Field: { path: GOAL_FIELD_COMPONENT }
29
+ }
30
+ }
31
+ };
32
+ return options.overrides ? options.overrides({ field }) : field;
33
+ };
34
+ /**
35
+ * The slug out of a stored goal value, for renderers that read a {@link goalField} back.
36
+ * Accepts the stored string and the `{ slug }` shape a populated document carries; anything
37
+ * else is not a goal reference and resolves to null rather than a guess.
38
+ */
39
+ const goalSlug = (value) => {
40
+ if (typeof value === "string") {
41
+ const slug = value.trim();
42
+ return slug === "" ? null : slug;
43
+ }
44
+ if (value && typeof value === "object" && !Array.isArray(value)) {
45
+ const { slug } = value;
46
+ if (typeof slug === "string") {
47
+ const trimmed = slug.trim();
48
+ return trimmed === "" ? null : trimmed;
49
+ }
50
+ }
51
+ return null;
52
+ };
53
+ //#endregion
54
+ export { goalField, goalSlug };
55
+
56
+ //# sourceMappingURL=goalField.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalField.js","names":[],"sources":["../../src/goals/goalField.ts"],"sourcesContent":["import type { LabelFunction, StaticLabel, TextField, TextFieldSingleValidation } from 'payload'\nimport { keys } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { GOAL_SLUG_PATTERN } from './types'\n\n/** importMap path of the picker; the factory never imports the component itself. */\nexport const GOAL_FIELD_COMPONENT = '@10x-media/analytics/client#GoalSelectField'\n\nexport interface GoalFieldOptions {\n\t/** Field name, and therefore the property the slug is stored under. Default `'goal'`. */\n\tname?: string\n\t/** Default: the translated \"Goal\". */\n\tlabel?: LabelFunction | StaticLabel\n\trequired?: boolean\n\t/** Merged over the factory's own admin config; the Field component is not replaceable here. */\n\tadmin?: TextField['admin']\n\t/** Last word on the built field. Spread the field, never deep-merge it. */\n\toverrides?: (args: { field: TextField }) => TextField\n}\n\nconst makeValidate =\n\t(required: boolean): TextFieldSingleValidation =>\n\t(value, { req }) => {\n\t\tconst slug = typeof value === 'string' ? value.trim() : ''\n\t\tif (slug === '') {\n\t\t\treturn required ? req.t('validation:required') : true\n\t\t}\n\t\treturn GOAL_SLUG_PATTERN.test(slug) ? true : asTranslate(req.t)(keys.fieldGoalInvalid)\n\t}\n\n/**\n * A goal picker for any collection or global: a text field storing the goal slug, rendered\n * by the client picker that lists the config goals merged with the goals collection for the\n * requesting scope. Pair it with {@link goalSlug} wherever the stored value is read back.\n */\nexport const goalField = (options: GoalFieldOptions = {}): TextField => {\n\tconst field: TextField = {\n\t\tname: options.name ?? 'goal',\n\t\ttype: 'text',\n\t\tlabel: options.label ?? labelForKey(keys.fieldGoalLabel),\n\t\t...(options.required ? { required: true } : {}),\n\t\tvalidate: makeValidate(Boolean(options.required)),\n\t\tadmin: {\n\t\t\t...options.admin,\n\t\t\tcomponents: {\n\t\t\t\t...options.admin?.components,\n\t\t\t\tField: { path: GOAL_FIELD_COMPONENT },\n\t\t\t},\n\t\t},\n\t}\n\treturn options.overrides ? options.overrides({ field }) : field\n}\n\n/**\n * The slug out of a stored goal value, for renderers that read a {@link goalField} back.\n * Accepts the stored string and the `{ slug }` shape a populated document carries; anything\n * else is not a goal reference and resolves to null rather than a guess.\n */\nexport const goalSlug = (value: unknown): string | null => {\n\tif (typeof value === 'string') {\n\t\tconst slug = value.trim()\n\t\treturn slug === '' ? null : slug\n\t}\n\tif (value && typeof value === 'object' && !Array.isArray(value)) {\n\t\tconst { slug } = value as { slug?: unknown }\n\t\tif (typeof slug === 'string') {\n\t\t\tconst trimmed = slug.trim()\n\t\t\treturn trimmed === '' ? null : trimmed\n\t\t}\n\t}\n\treturn null\n}\n"],"mappings":";;;;;AAMA,MAAa,uBAAuB;AAcpC,MAAM,gBACJ,cACA,OAAO,EAAE,UAAU;CACnB,MAAM,OAAO,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CACxD,IAAI,SAAS,IACZ,OAAO,WAAW,IAAI,EAAE,qBAAqB,IAAI;CAElD,OAAO,kBAAkB,KAAK,IAAI,IAAI,OAAO,YAAY,IAAI,CAAC,EAAE,KAAK,gBAAgB;AACtF;;;;;;AAOD,MAAa,aAAa,UAA4B,CAAC,MAAiB;CACvE,MAAM,QAAmB;EACxB,MAAM,QAAQ,QAAQ;EACtB,MAAM;EACN,OAAO,QAAQ,SAAS,YAAY,KAAK,cAAc;EACvD,GAAI,QAAQ,WAAW,EAAE,UAAU,KAAK,IAAI,CAAC;EAC7C,UAAU,aAAa,QAAQ,QAAQ,QAAQ,CAAC;EAChD,OAAO;GACN,GAAG,QAAQ;GACX,YAAY;IACX,GAAG,QAAQ,OAAO;IAClB,OAAO,EAAE,MAAM,qBAAqB;GACrC;EACD;CACD;CACA,OAAO,QAAQ,YAAY,QAAQ,UAAU,EAAE,MAAM,CAAC,IAAI;AAC3D;;;;;;AAOA,MAAa,YAAY,UAAkC;CAC1D,IAAI,OAAO,UAAU,UAAU;EAC9B,MAAM,OAAO,MAAM,KAAK;EACxB,OAAO,SAAS,KAAK,OAAO;CAC7B;CACA,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,GAAG;EAChE,MAAM,EAAE,SAAS;EACjB,IAAI,OAAO,SAAS,UAAU;GAC7B,MAAM,UAAU,KAAK,KAAK;GAC1B,OAAO,YAAY,KAAK,OAAO;EAChC;CACD;CACA,OAAO;AACR"}
@@ -0,0 +1 @@
1
+ import { GoalsResponse, WireGoal } from "./fetchGoals.js";
@@ -0,0 +1,58 @@
1
+ import "../plugin/paths.js";
2
+ import { getRuntime, platformReadFor, readAccessFor, resolveGoalsDetailedFor, resolveScopeFor } from "../plugin/runtime.js";
3
+ import { NO_STORE, analyticsError, errorResponse } from "../plugin/errors.js";
4
+ //#region src/goals/goalsEndpoint.ts
5
+ /**
6
+ * Authenticated GET listing the goals visible to the requesting scope, gated by
7
+ * `access.read` like every other read endpoint: the config goals
8
+ * merged with the goals collection, each tagged with where it came from. Scope gating
9
+ * mirrors the sources endpoint exactly, because the reasoning is the same: there is no
10
+ * scope parameter, so a tenant can never enumerate another tenant's goals; on a scoped
11
+ * install a request that resolves no scope is ambiguous rather than install-wide and
12
+ * answers empty unless `platformRead` grants it; and a failed resolution on a scoped
13
+ * install is indistinguishable from a forged one, so it answers empty too, while an
14
+ * unscoped install falls back to the static config goals.
15
+ *
16
+ * Every answer is `no-store`: which goals a caller sees depends on its own scope.
17
+ */
18
+ const makeGoalsHandler = () => async (req) => {
19
+ if (!req.user) return errorResponse(401, analyticsError("unauthorized", "analytics: authentication required"));
20
+ const runtime = getRuntime(req.payload);
21
+ if (!runtime) return Response.json({
22
+ goals: [],
23
+ collection: null
24
+ }, { headers: NO_STORE });
25
+ if (!await readAccessFor(runtime, req)) return errorResponse(403, analyticsError("forbidden", "analytics: read access denied"));
26
+ const collection = runtime.goalsCollectionSlug ? { slug: runtime.goalsCollectionSlug } : null;
27
+ const configGoals = () => (runtime.goals ?? []).map((goal) => ({
28
+ slug: goal.slug,
29
+ name: goal.name,
30
+ source: "config"
31
+ }));
32
+ try {
33
+ const scope = await resolveScopeFor(runtime, req);
34
+ if (runtime.scoped && scope === null && !await platformReadFor(runtime, req)) return Response.json({
35
+ goals: [],
36
+ collection
37
+ }, { headers: NO_STORE });
38
+ const goals = (await resolveGoalsDetailedFor(runtime, req, scope)).map(({ goal, source }) => ({
39
+ slug: goal.slug,
40
+ name: goal.name,
41
+ source
42
+ }));
43
+ return Response.json({
44
+ goals,
45
+ collection
46
+ }, { headers: NO_STORE });
47
+ } catch (err) {
48
+ req.payload.logger?.warn(`analytics: goals listing failed: ${String(err)}`);
49
+ return Response.json({
50
+ goals: runtime.scoped ? [] : configGoals(),
51
+ collection
52
+ }, { headers: NO_STORE });
53
+ }
54
+ };
55
+ //#endregion
56
+ export { makeGoalsHandler };
57
+
58
+ //# sourceMappingURL=goalsEndpoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalsEndpoint.js","names":[],"sources":["../../src/goals/goalsEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { analyticsError, errorResponse, NO_STORE } from '../plugin/errors'\nimport { GOALS_PATH } from '../plugin/paths'\nimport {\n\tgetRuntime,\n\tplatformReadFor,\n\treadAccessFor,\n\tresolveGoalsDetailedFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport type { GoalsResponse, WireGoal } from './fetchGoals'\n\nexport type { GoalsResponse, WireGoal }\nexport { GOALS_PATH }\n\n/**\n * Authenticated GET listing the goals visible to the requesting scope, gated by\n * `access.read` like every other read endpoint: the config goals\n * merged with the goals collection, each tagged with where it came from. Scope gating\n * mirrors the sources endpoint exactly, because the reasoning is the same: there is no\n * scope parameter, so a tenant can never enumerate another tenant's goals; on a scoped\n * install a request that resolves no scope is ambiguous rather than install-wide and\n * answers empty unless `platformRead` grants it; and a failed resolution on a scoped\n * install is indistinguishable from a forged one, so it answers empty too, while an\n * unscoped install falls back to the static config goals.\n *\n * Every answer is `no-store`: which goals a caller sees depends on its own scope.\n */\nexport const makeGoalsHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, analyticsError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn Response.json({ goals: [], collection: null } satisfies GoalsResponse, {\n\t\t\theaders: NO_STORE,\n\t\t})\n\t}\n\tif (!(await readAccessFor(runtime, req))) {\n\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t}\n\tconst collection = runtime.goalsCollectionSlug ? { slug: runtime.goalsCollectionSlug } : null\n\tconst configGoals = (): WireGoal[] =>\n\t\t(runtime.goals ?? []).map((goal) => ({\n\t\t\tslug: goal.slug,\n\t\t\tname: goal.name,\n\t\t\tsource: 'config' as const,\n\t\t}))\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\tif (runtime.scoped && scope === null && !(await platformReadFor(runtime, req))) {\n\t\t\treturn Response.json({ goals: [], collection } satisfies GoalsResponse, { headers: NO_STORE })\n\t\t}\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\tconst goals = resolved.map(({ goal, source }) => ({\n\t\t\tslug: goal.slug,\n\t\t\tname: goal.name,\n\t\t\tsource,\n\t\t}))\n\t\treturn Response.json({ goals, collection } satisfies GoalsResponse, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: goals listing failed: ${String(err)}`)\n\t\treturn Response.json(\n\t\t\t{\n\t\t\t\tgoals: runtime.scoped ? [] : configGoals(),\n\t\t\t\tcollection,\n\t\t\t} satisfies GoalsResponse,\n\t\t\t{ headers: NO_STORE }\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,cAAc,KAAK,eAAe,gBAAgB,oCAAoC,CAAC;CAE/F,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,SAAS,KAAK;EAAE,OAAO,CAAC;EAAG,YAAY;CAAK,GAA2B,EAC7E,SAAS,SACV,CAAC;CAEF,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACrC,OAAO,cAAc,KAAK,eAAe,aAAa,+BAA+B,CAAC;CAEvF,MAAM,aAAa,QAAQ,sBAAsB,EAAE,MAAM,QAAQ,oBAAoB,IAAI;CACzF,MAAM,qBACJ,QAAQ,SAAS,CAAC,GAAG,KAAK,UAAU;EACpC,MAAM,KAAK;EACX,MAAM,KAAK;EACX,QAAQ;CACT,EAAE;CACH,IAAI;EACH,MAAM,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,IAAI,QAAQ,UAAU,UAAU,QAAQ,CAAE,MAAM,gBAAgB,SAAS,GAAG,GAC3E,OAAO,SAAS,KAAK;GAAE,OAAO,CAAC;GAAG;EAAW,GAA2B,EAAE,SAAS,SAAS,CAAC;EAG9F,MAAM,SAAQ,MADS,wBAAwB,SAAS,KAAK,KAAK,GAC3C,KAAK,EAAE,MAAM,cAAc;GACjD,MAAM,KAAK;GACX,MAAM,KAAK;GACX;EACD,EAAE;EACF,OAAO,SAAS,KAAK;GAAE;GAAO;EAAW,GAA2B,EAAE,SAAS,SAAS,CAAC;CAC1F,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,oCAAoC,OAAO,GAAG,GAAG;EAC1E,OAAO,SAAS,KACf;GACC,OAAO,QAAQ,SAAS,CAAC,IAAI,YAAY;GACzC;EACD,GACA,EAAE,SAAS,SAAS,CACrB;CACD;AACD"}
@@ -0,0 +1,64 @@
1
+ //#region src/goals/match.ts
2
+ const trimTrailingSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
3
+ /** Query and hash are not part of the path a pattern is matched against. */
4
+ const pathOnly = (path) => {
5
+ const cut = path.search(/[?#]/);
6
+ return trimTrailingSlash(cut === -1 ? path : path.slice(0, cut));
7
+ };
8
+ /** Every regex metacharacter except `*`, the one glob token this translates itself. */
9
+ const ESCAPE = /[.+?^${}()|[\]\\]/g;
10
+ /**
11
+ * Anchored, case-sensitive glob: `*` is exactly one non-empty path segment and `**` is one
12
+ * or more segments at any depth, so `/docs/**` covers everything below `/docs` but not
13
+ * `/docs` itself. A trailing slash is insignificant on both sides, and a pattern pasted
14
+ * from a URL gets the same query/hash cut as the path it is matched against.
15
+ */
16
+ const patternToRegExp = (pattern) => {
17
+ const body = pathOnly(pattern).replace(ESCAPE, "\\$&").split("**").map((part) => part.replace(/\*/g, "[^/]+")).join(".+");
18
+ return new RegExp(`^${body}$`);
19
+ };
20
+ const cache = /* @__PURE__ */ new Map();
21
+ const matchesPath = (pattern, path) => {
22
+ let re = cache.get(pattern);
23
+ if (!re) {
24
+ re = patternToRegExp(pattern);
25
+ cache.set(pattern, re);
26
+ }
27
+ return re.test(pathOnly(path));
28
+ };
29
+ /** Revenue is money: a source only counts when it is a finite, non-negative number. */
30
+ const amount = (value) => {
31
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
32
+ return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
33
+ };
34
+ const completionValue = (event, goal) => {
35
+ const fromEvent = amount(event.value);
36
+ if (fromEvent !== void 0) return fromEvent;
37
+ const fixed = amount(goal.value?.fixed);
38
+ if (fixed !== void 0) return fixed;
39
+ const prop = goal.value?.prop;
40
+ return (prop ? amount(event.props?.[prop]) : void 0) ?? 0;
41
+ };
42
+ const completes = (event, goal) => {
43
+ switch (goal.match.kind) {
44
+ case "goal": return event.type === "goal" && event.name === goal.slug;
45
+ case "event": return event.type === "event" && event.name === goal.match.name;
46
+ case "path": return event.type === "pageview" && matchesPath(goal.match.pattern, event.path);
47
+ }
48
+ };
49
+ /**
50
+ * Every goal the event completes, in config order. Pure: the same event and goals always
51
+ * produce the same completions, which is what lets a read re-derive them from a stored event.
52
+ */
53
+ const matchGoals = (event, goals) => {
54
+ const out = [];
55
+ for (const goal of goals) if (completes(event, goal)) out.push({
56
+ slug: goal.slug,
57
+ value: completionValue(event, goal)
58
+ });
59
+ return out;
60
+ };
61
+ //#endregion
62
+ export { matchGoals };
63
+
64
+ //# sourceMappingURL=match.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"match.js","names":[],"sources":["../../src/goals/match.ts"],"sourcesContent":["import type { Goal } from './types'\n\n/** The event fields goal matching reads. Satisfied by both the wire payload and StoredEvent. */\nexport interface MatchableEvent {\n\ttype: string\n\tname?: string\n\tpath: string\n\tprops?: Record<string, unknown>\n\tvalue?: number\n}\n\n/** One goal completion: the goal's slug and the revenue this completion is worth. */\nexport interface GoalCompletion {\n\tslug: string\n\tvalue: number\n}\n\nconst trimTrailingSlash = (path: string): string =>\n\tpath.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path\n\n/** Query and hash are not part of the path a pattern is matched against. */\nconst pathOnly = (path: string): string => {\n\tconst cut = path.search(/[?#]/)\n\treturn trimTrailingSlash(cut === -1 ? path : path.slice(0, cut))\n}\n\n/** Every regex metacharacter except `*`, the one glob token this translates itself. */\nconst ESCAPE = /[.+?^${}()|[\\]\\\\]/g\n\n/**\n * Anchored, case-sensitive glob: `*` is exactly one non-empty path segment and `**` is one\n * or more segments at any depth, so `/docs/**` covers everything below `/docs` but not\n * `/docs` itself. A trailing slash is insignificant on both sides, and a pattern pasted\n * from a URL gets the same query/hash cut as the path it is matched against.\n */\nconst patternToRegExp = (pattern: string): RegExp => {\n\tconst body = pathOnly(pattern)\n\t\t.replace(ESCAPE, '\\\\$&')\n\t\t.split('**')\n\t\t.map((part) => part.replace(/\\*/g, '[^/]+'))\n\t\t.join('.+')\n\treturn new RegExp(`^${body}$`)\n}\n\nconst cache = new Map<string, RegExp>()\n\nconst matchesPath = (pattern: string, path: string): boolean => {\n\tlet re = cache.get(pattern)\n\tif (!re) {\n\t\tre = patternToRegExp(pattern)\n\t\tcache.set(pattern, re)\n\t}\n\treturn re.test(pathOnly(path))\n}\n\n/** Revenue is money: a source only counts when it is a finite, non-negative number. */\nconst amount = (value: unknown): number | undefined => {\n\tconst n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value\n\treturn typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : undefined\n}\n\nconst completionValue = (event: MatchableEvent, goal: Goal): number => {\n\tconst fromEvent = amount(event.value)\n\tif (fromEvent !== undefined) {\n\t\treturn fromEvent\n\t}\n\tconst fixed = amount(goal.value?.fixed)\n\tif (fixed !== undefined) {\n\t\treturn fixed\n\t}\n\tconst prop = goal.value?.prop\n\treturn (prop ? amount(event.props?.[prop]) : undefined) ?? 0\n}\n\nconst completes = (event: MatchableEvent, goal: Goal): boolean => {\n\tswitch (goal.match.kind) {\n\t\tcase 'goal':\n\t\t\treturn event.type === 'goal' && event.name === goal.slug\n\t\tcase 'event':\n\t\t\treturn event.type === 'event' && event.name === goal.match.name\n\t\tcase 'path':\n\t\t\treturn event.type === 'pageview' && matchesPath(goal.match.pattern, event.path)\n\t}\n}\n\n/**\n * Every goal the event completes, in config order. Pure: the same event and goals always\n * produce the same completions, which is what lets a read re-derive them from a stored event.\n */\nexport const matchGoals = (event: MatchableEvent, goals: Goal[]): GoalCompletion[] => {\n\tconst out: GoalCompletion[] = []\n\tfor (const goal of goals) {\n\t\tif (completes(event, goal)) {\n\t\t\tout.push({ slug: goal.slug, value: completionValue(event, goal) })\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";AAiBA,MAAM,qBAAqB,SAC1B,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;;AAG7D,MAAM,YAAY,SAAyB;CAC1C,MAAM,MAAM,KAAK,OAAO,MAAM;CAC9B,OAAO,kBAAkB,QAAQ,KAAK,OAAO,KAAK,MAAM,GAAG,GAAG,CAAC;AAChE;;AAGA,MAAM,SAAS;;;;;;;AAQf,MAAM,mBAAmB,YAA4B;CACpD,MAAM,OAAO,SAAS,OAAO,EAC3B,QAAQ,QAAQ,MAAM,EACtB,MAAM,IAAI,EACV,KAAK,SAAS,KAAK,QAAQ,OAAO,OAAO,CAAC,EAC1C,KAAK,IAAI;CACX,OAAO,IAAI,OAAO,IAAI,KAAK,EAAE;AAC9B;AAEA,MAAM,wBAAQ,IAAI,IAAoB;AAEtC,MAAM,eAAe,SAAiB,SAA0B;CAC/D,IAAI,KAAK,MAAM,IAAI,OAAO;CAC1B,IAAI,CAAC,IAAI;EACR,KAAK,gBAAgB,OAAO;EAC5B,MAAM,IAAI,SAAS,EAAE;CACtB;CACA,OAAO,GAAG,KAAK,SAAS,IAAI,CAAC;AAC9B;;AAGA,MAAM,UAAU,UAAuC;CACtD,MAAM,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI;CAC7E,OAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,KAAK,IAAI,IAAI,KAAA;AACpE;AAEA,MAAM,mBAAmB,OAAuB,SAAuB;CACtE,MAAM,YAAY,OAAO,MAAM,KAAK;CACpC,IAAI,cAAc,KAAA,GACjB,OAAO;CAER,MAAM,QAAQ,OAAO,KAAK,OAAO,KAAK;CACtC,IAAI,UAAU,KAAA,GACb,OAAO;CAER,MAAM,OAAO,KAAK,OAAO;CACzB,QAAQ,OAAO,OAAO,MAAM,QAAQ,KAAK,IAAI,KAAA,MAAc;AAC5D;AAEA,MAAM,aAAa,OAAuB,SAAwB;CACjE,QAAQ,KAAK,MAAM,MAAnB;EACC,KAAK,QACJ,OAAO,MAAM,SAAS,UAAU,MAAM,SAAS,KAAK;EACrD,KAAK,SACJ,OAAO,MAAM,SAAS,WAAW,MAAM,SAAS,KAAK,MAAM;EAC5D,KAAK,QACJ,OAAO,MAAM,SAAS,cAAc,YAAY,KAAK,MAAM,SAAS,MAAM,IAAI;CAChF;AACD;;;;;AAMA,MAAa,cAAc,OAAuB,UAAoC;CACrF,MAAM,MAAwB,CAAC;CAC/B,KAAK,MAAM,QAAQ,OAClB,IAAI,UAAU,OAAO,IAAI,GACxB,IAAI,KAAK;EAAE,MAAM,KAAK;EAAM,OAAO,gBAAgB,OAAO,IAAI;CAAE,CAAC;CAGnE,OAAO;AACR"}
@@ -0,0 +1,8 @@
1
+ import { PayloadRequest } from "payload";
2
+
3
+ //#region src/goals/resolver.d.ts
4
+ /** Where a resolved goal came from; Task 2's endpoint shows it next to the goal. */
5
+ type GoalSource = 'config' | 'collection';
6
+ //#endregion
7
+ export { GoalSource };
8
+ //# sourceMappingURL=resolver.d.ts.map
@@ -0,0 +1,147 @@
1
+ import { GOAL_SLUG_PATTERN } from "./types.js";
2
+ /**
3
+ * A scoped install stores install-wide goals with no scope at all, so a null scope has to
4
+ * match both an absent field and an empty string (same shape the providers lookup uses).
5
+ * The empty string is not castable on a relationship-typed `scopeField`, so install-wide
6
+ * lookups on a host-owned relationship field fail the read and resolve config goals only.
7
+ */
8
+ const goalScopeWhere = (scopeField, scope) => scope === null ? { or: [{ [scopeField]: { equals: null } }, { [scopeField]: { equals: "" } }] } : { [scopeField]: { equals: scope } };
9
+ const text = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
10
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
11
+ const docToMatch = (value) => {
12
+ const raw = object(value);
13
+ switch (raw?.kind) {
14
+ case "goal": return { kind: "goal" };
15
+ case "event": {
16
+ const name = text(raw.name);
17
+ return name ? {
18
+ kind: "event",
19
+ name
20
+ } : null;
21
+ }
22
+ case "path": {
23
+ const pattern = text(raw.pattern);
24
+ return pattern ? {
25
+ kind: "path",
26
+ pattern
27
+ } : null;
28
+ }
29
+ default: return null;
30
+ }
31
+ };
32
+ /**
33
+ * One goal document as the matcher sees it, or null when the document cannot produce a
34
+ * usable goal. Editors can save a half-filled draft, so a document missing the part its
35
+ * match kind needs is skipped rather than allowed to match everything or nothing.
36
+ */
37
+ const docToGoal = (doc) => {
38
+ if (doc.enabled === false) return null;
39
+ const slug = text(doc.slug);
40
+ if (!slug || !GOAL_SLUG_PATTERN.test(slug)) return null;
41
+ const match = docToMatch(doc.match);
42
+ if (!match) return null;
43
+ const raw = object(doc.value);
44
+ const fixed = raw?.fixed;
45
+ if (fixed !== null && fixed !== void 0) {
46
+ if (typeof fixed !== "number" || !Number.isFinite(fixed) || fixed < 0) return null;
47
+ }
48
+ const prop = text(raw?.prop);
49
+ const value = typeof fixed === "number" || prop ? {
50
+ ...typeof fixed === "number" ? { fixed } : {},
51
+ ...prop ? { prop } : {}
52
+ } : void 0;
53
+ const currency = text(doc.currency);
54
+ return {
55
+ slug,
56
+ name: text(doc.name) ?? slug,
57
+ match,
58
+ ...value ? { value } : {},
59
+ ...currency ? { currency } : {}
60
+ };
61
+ };
62
+ const mergeDetailed = (config, collection) => {
63
+ const bySlug = /* @__PURE__ */ new Map();
64
+ for (const goal of collection) if (!bySlug.has(goal.slug)) bySlug.set(goal.slug, goal);
65
+ const out = [];
66
+ const taken = /* @__PURE__ */ new Set();
67
+ for (const goal of config) {
68
+ const override = bySlug.get(goal.slug);
69
+ out.push(override ? {
70
+ goal: override,
71
+ source: "collection"
72
+ } : {
73
+ goal,
74
+ source: "config"
75
+ });
76
+ taken.add(goal.slug);
77
+ }
78
+ for (const [slug, goal] of bySlug) if (!taken.has(slug)) out.push({
79
+ goal,
80
+ source: "collection"
81
+ });
82
+ return out;
83
+ };
84
+ /** The resolver an install without the goals collection gets: config goals, no reads. */
85
+ const configGoalsResolver = (config) => {
86
+ const detailed = mergeDetailed(config, []);
87
+ return {
88
+ resolve: async () => config,
89
+ resolveDetailed: async () => detailed,
90
+ invalidate: () => {}
91
+ };
92
+ };
93
+ /**
94
+ * Merges the goals collection over the config goals, cached per scope for a short TTL so
95
+ * ingest (which resolves goals on every event) does not query the collection per request.
96
+ * Invalidation clears all scopes at once: a document's scope can itself change, so evicting
97
+ * one scope could leave a stale entry under the other.
98
+ */
99
+ const createGoalsResolver = (args) => {
100
+ const ttlMs = args.ttlMs ?? 3e4;
101
+ const now = args.now ?? Date.now;
102
+ const configGoals = mergeDetailed(args.config, []);
103
+ const cache = /* @__PURE__ */ new Map();
104
+ const load = async (req, scope) => {
105
+ try {
106
+ const { docs } = await req.payload.find({
107
+ collection: args.slug,
108
+ where: args.scoped ? { and: [{ enabled: { equals: true } }, goalScopeWhere(args.scopeField, scope)] } : { enabled: { equals: true } },
109
+ limit: 500,
110
+ pagination: false,
111
+ depth: 0,
112
+ overrideAccess: true,
113
+ req
114
+ });
115
+ const goals = [];
116
+ for (const doc of docs) {
117
+ const goal = docToGoal(doc);
118
+ if (goal) goals.push(goal);
119
+ }
120
+ return mergeDetailed(args.config, goals);
121
+ } catch (err) {
122
+ req.payload.logger?.warn?.(`analytics: goals collection read failed for scope "${scope ?? ""}", falling back to config goals: ${String(err)}`);
123
+ return configGoals;
124
+ }
125
+ };
126
+ const resolveDetailed = async (req, scope) => {
127
+ const key = scope ?? "";
128
+ const at = now();
129
+ const hit = cache.get(key);
130
+ if (hit && hit.expiresAt > at) return hit.goals;
131
+ const goals = await load(req, args.scoped ? scope ?? null : null);
132
+ cache.set(key, {
133
+ goals,
134
+ expiresAt: at + ttlMs
135
+ });
136
+ return goals;
137
+ };
138
+ return {
139
+ resolve: async (req, scope) => (await resolveDetailed(req, scope)).map((entry) => entry.goal),
140
+ resolveDetailed,
141
+ invalidate: () => cache.clear()
142
+ };
143
+ };
144
+ //#endregion
145
+ export { configGoalsResolver, createGoalsResolver, goalScopeWhere };
146
+
147
+ //# sourceMappingURL=resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolver.js","names":[],"sources":["../../src/goals/resolver.ts"],"sourcesContent":["import type { PayloadRequest, Where } from 'payload'\nimport { GOAL_SLUG_PATTERN, type Goal, type GoalMatch } from './types'\n\nexport const GOALS_CACHE_TTL_MS = 30_000\n\n/** Where a resolved goal came from; Task 2's endpoint shows it next to the goal. */\nexport type GoalSource = 'config' | 'collection'\n\nexport interface ResolvedGoal {\n\tgoal: Goal\n\tsource: GoalSource\n}\n\nexport interface GoalsResolver {\n\tresolve: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n\tresolveDetailed: (req: PayloadRequest, scope?: string | null) => Promise<ResolvedGoal[]>\n\t/** Drops every cached scope; wired to the goals collection's change hooks. */\n\tinvalidate: () => void\n}\n\n/**\n * A scoped install stores install-wide goals with no scope at all, so a null scope has to\n * match both an absent field and an empty string (same shape the providers lookup uses).\n * The empty string is not castable on a relationship-typed `scopeField`, so install-wide\n * lookups on a host-owned relationship field fail the read and resolve config goals only.\n */\nexport const goalScopeWhere = (scopeField: string, scope: string | null): Where =>\n\tscope === null\n\t\t? { or: [{ [scopeField]: { equals: null } }, { [scopeField]: { equals: '' } }] }\n\t\t: { [scopeField]: { equals: scope } }\n\nconst text = (value: unknown): string | undefined =>\n\ttypeof value === 'string' && value.trim() !== '' ? value : undefined\n\nconst object = (value: unknown): Record<string, unknown> | undefined =>\n\tvalue && typeof value === 'object' && !Array.isArray(value)\n\t\t? (value as Record<string, unknown>)\n\t\t: undefined\n\nconst docToMatch = (value: unknown): GoalMatch | null => {\n\tconst raw = object(value)\n\tswitch (raw?.kind) {\n\t\tcase 'goal':\n\t\t\treturn { kind: 'goal' }\n\t\tcase 'event': {\n\t\t\tconst name = text(raw.name)\n\t\t\treturn name ? { kind: 'event', name } : null\n\t\t}\n\t\tcase 'path': {\n\t\t\tconst pattern = text(raw.pattern)\n\t\t\treturn pattern ? { kind: 'path', pattern } : null\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * One goal document as the matcher sees it, or null when the document cannot produce a\n * usable goal. Editors can save a half-filled draft, so a document missing the part its\n * match kind needs is skipped rather than allowed to match everything or nothing.\n */\nexport const docToGoal = (doc: Record<string, unknown>): Goal | null => {\n\tif (doc.enabled === false) {\n\t\treturn null\n\t}\n\tconst slug = text(doc.slug)\n\tif (!slug || !GOAL_SLUG_PATTERN.test(slug)) {\n\t\treturn null\n\t}\n\tconst match = docToMatch(doc.match)\n\tif (!match) {\n\t\treturn null\n\t}\n\tconst raw = object(doc.value)\n\tconst fixed = raw?.fixed\n\tif (fixed !== null && fixed !== undefined) {\n\t\tif (typeof fixed !== 'number' || !Number.isFinite(fixed) || fixed < 0) {\n\t\t\treturn null\n\t\t}\n\t}\n\tconst prop = text(raw?.prop)\n\tconst value =\n\t\ttypeof fixed === 'number' || prop\n\t\t\t? { ...(typeof fixed === 'number' ? { fixed } : {}), ...(prop ? { prop } : {}) }\n\t\t\t: undefined\n\tconst currency = text(doc.currency)\n\treturn {\n\t\tslug,\n\t\tname: text(doc.name) ?? slug,\n\t\tmatch,\n\t\t...(value ? { value } : {}),\n\t\t...(currency ? { currency } : {}),\n\t}\n}\n\nconst mergeDetailed = (config: Goal[], collection: Goal[]): ResolvedGoal[] => {\n\tconst bySlug = new Map<string, Goal>()\n\tfor (const goal of collection) {\n\t\tif (!bySlug.has(goal.slug)) {\n\t\t\tbySlug.set(goal.slug, goal)\n\t\t}\n\t}\n\tconst out: ResolvedGoal[] = []\n\tconst taken = new Set<string>()\n\tfor (const goal of config) {\n\t\tconst override = bySlug.get(goal.slug)\n\t\tout.push(override ? { goal: override, source: 'collection' } : { goal, source: 'config' })\n\t\ttaken.add(goal.slug)\n\t}\n\tfor (const [slug, goal] of bySlug) {\n\t\tif (!taken.has(slug)) {\n\t\t\tout.push({ goal, source: 'collection' })\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Config order first, with a collection goal replacing the config goal of the same slug in\n * place, then the collection's own extras. Editors adjust what config declared without\n * reordering the reports built on it.\n */\nexport const mergeGoals = (config: Goal[], collection: Goal[]): Goal[] =>\n\tmergeDetailed(config, collection).map((entry) => entry.goal)\n\n/** The resolver an install without the goals collection gets: config goals, no reads. */\nexport const configGoalsResolver = (config: Goal[]): GoalsResolver => {\n\tconst detailed = mergeDetailed(config, [])\n\treturn {\n\t\tresolve: async () => config,\n\t\tresolveDetailed: async () => detailed,\n\t\tinvalidate: () => {},\n\t}\n}\n\nexport interface CreateGoalsResolverArgs {\n\tslug: string\n\tscopeField: string\n\t/** True when the install configured a scopeResolver; unscoped installs ignore scope. */\n\tscoped: boolean\n\tconfig: Goal[]\n\tttlMs?: number\n\tnow?: () => number\n}\n\n/**\n * Merges the goals collection over the config goals, cached per scope for a short TTL so\n * ingest (which resolves goals on every event) does not query the collection per request.\n * Invalidation clears all scopes at once: a document's scope can itself change, so evicting\n * one scope could leave a stale entry under the other.\n */\nexport const createGoalsResolver = (args: CreateGoalsResolverArgs): GoalsResolver => {\n\tconst ttlMs = args.ttlMs ?? GOALS_CACHE_TTL_MS\n\tconst now = args.now ?? Date.now\n\tconst configGoals = mergeDetailed(args.config, [])\n\tconst cache = new Map<string, { goals: ResolvedGoal[]; expiresAt: number }>()\n\n\tconst load = async (req: PayloadRequest, scope: string | null): Promise<ResolvedGoal[]> => {\n\t\ttry {\n\t\t\tconst { docs } = await req.payload.find({\n\t\t\t\tcollection: args.slug as never,\n\t\t\t\twhere: args.scoped\n\t\t\t\t\t? { and: [{ enabled: { equals: true } }, goalScopeWhere(args.scopeField, scope)] }\n\t\t\t\t\t: { enabled: { equals: true } },\n\t\t\t\tlimit: 500,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t\tconst goals: Goal[] = []\n\t\t\tfor (const doc of docs as unknown as Array<Record<string, unknown>>) {\n\t\t\t\tconst goal = docToGoal(doc)\n\t\t\t\tif (goal) {\n\t\t\t\t\tgoals.push(goal)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mergeDetailed(args.config, goals)\n\t\t} catch (err) {\n\t\t\t// Goal matching must not take ingest down with the collection: config goals still\n\t\t\t// match, and the failed result is cached so a broken read is not retried per event.\n\t\t\treq.payload.logger?.warn?.(\n\t\t\t\t`analytics: goals collection read failed for scope \"${scope ?? ''}\", falling back to config goals: ${String(err)}`\n\t\t\t)\n\t\t\treturn configGoals\n\t\t}\n\t}\n\n\tconst resolveDetailed = async (\n\t\treq: PayloadRequest,\n\t\tscope?: string | null\n\t): Promise<ResolvedGoal[]> => {\n\t\tconst key = scope ?? ''\n\t\tconst at = now()\n\t\tconst hit = cache.get(key)\n\t\tif (hit && hit.expiresAt > at) {\n\t\t\treturn hit.goals\n\t\t}\n\t\tconst goals = await load(req, args.scoped ? (scope ?? null) : null)\n\t\tcache.set(key, { goals, expiresAt: at + ttlMs })\n\t\treturn goals\n\t}\n\n\treturn {\n\t\tresolve: async (req, scope) => (await resolveDetailed(req, scope)).map((entry) => entry.goal),\n\t\tresolveDetailed,\n\t\tinvalidate: () => cache.clear(),\n\t}\n}\n"],"mappings":";;;;;;;AA0BA,MAAa,kBAAkB,YAAoB,UAClD,UAAU,OACP,EAAE,IAAI,CAAC,GAAG,aAAa,EAAE,QAAQ,KAAK,EAAE,GAAG,GAAG,aAAa,EAAE,QAAQ,GAAG,EAAE,CAAC,EAAE,IAC7E,GAAG,aAAa,EAAE,QAAQ,MAAM,EAAE;AAEtC,MAAM,QAAQ,UACb,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAAK,QAAQ,KAAA;AAE5D,MAAM,UAAU,UACf,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACtD,QACD,KAAA;AAEJ,MAAM,cAAc,UAAqC;CACxD,MAAM,MAAM,OAAO,KAAK;CACxB,QAAQ,KAAK,MAAb;EACC,KAAK,QACJ,OAAO,EAAE,MAAM,OAAO;EACvB,KAAK,SAAS;GACb,MAAM,OAAO,KAAK,IAAI,IAAI;GAC1B,OAAO,OAAO;IAAE,MAAM;IAAS;GAAK,IAAI;EACzC;EACA,KAAK,QAAQ;GACZ,MAAM,UAAU,KAAK,IAAI,OAAO;GAChC,OAAO,UAAU;IAAE,MAAM;IAAQ;GAAQ,IAAI;EAC9C;EACA,SACC,OAAO;CACT;AACD;;;;;;AAOA,MAAa,aAAa,QAA8C;CACvE,IAAI,IAAI,YAAY,OACnB,OAAO;CAER,MAAM,OAAO,KAAK,IAAI,IAAI;CAC1B,IAAI,CAAC,QAAQ,CAAC,kBAAkB,KAAK,IAAI,GACxC,OAAO;CAER,MAAM,QAAQ,WAAW,IAAI,KAAK;CAClC,IAAI,CAAC,OACJ,OAAO;CAER,MAAM,MAAM,OAAO,IAAI,KAAK;CAC5B,MAAM,QAAQ,KAAK;CACnB,IAAI,UAAU,QAAQ,UAAU,KAAA;MAC3B,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GACnE,OAAO;CAAA;CAGT,MAAM,OAAO,KAAK,KAAK,IAAI;CAC3B,MAAM,QACL,OAAO,UAAU,YAAY,OAC1B;EAAE,GAAI,OAAO,UAAU,WAAW,EAAE,MAAM,IAAI,CAAC;EAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;CAAG,IAC7E,KAAA;CACJ,MAAM,WAAW,KAAK,IAAI,QAAQ;CAClC,OAAO;EACN;EACA,MAAM,KAAK,IAAI,IAAI,KAAK;EACxB;EACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EACzB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;CAChC;AACD;AAEA,MAAM,iBAAiB,QAAgB,eAAuC;CAC7E,MAAM,yBAAS,IAAI,IAAkB;CACrC,KAAK,MAAM,QAAQ,YAClB,IAAI,CAAC,OAAO,IAAI,KAAK,IAAI,GACxB,OAAO,IAAI,KAAK,MAAM,IAAI;CAG5B,MAAM,MAAsB,CAAC;CAC7B,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,QAAQ,QAAQ;EAC1B,MAAM,WAAW,OAAO,IAAI,KAAK,IAAI;EACrC,IAAI,KAAK,WAAW;GAAE,MAAM;GAAU,QAAQ;EAAa,IAAI;GAAE;GAAM,QAAQ;EAAS,CAAC;EACzF,MAAM,IAAI,KAAK,IAAI;CACpB;CACA,KAAK,MAAM,CAAC,MAAM,SAAS,QAC1B,IAAI,CAAC,MAAM,IAAI,IAAI,GAClB,IAAI,KAAK;EAAE;EAAM,QAAQ;CAAa,CAAC;CAGzC,OAAO;AACR;;AAWA,MAAa,uBAAuB,WAAkC;CACrE,MAAM,WAAW,cAAc,QAAQ,CAAC,CAAC;CACzC,OAAO;EACN,SAAS,YAAY;EACrB,iBAAiB,YAAY;EAC7B,kBAAkB,CAAC;CACpB;AACD;;;;;;;AAkBA,MAAa,uBAAuB,SAAiD;CACpF,MAAM,QAAQ,KAAK,SAAA;CACnB,MAAM,MAAM,KAAK,OAAO,KAAK;CAC7B,MAAM,cAAc,cAAc,KAAK,QAAQ,CAAC,CAAC;CACjD,MAAM,wBAAQ,IAAI,IAA0D;CAE5E,MAAM,OAAO,OAAO,KAAqB,UAAkD;EAC1F,IAAI;GACH,MAAM,EAAE,SAAS,MAAM,IAAI,QAAQ,KAAK;IACvC,YAAY,KAAK;IACjB,OAAO,KAAK,SACT,EAAE,KAAK,CAAC,EAAE,SAAS,EAAE,QAAQ,KAAK,EAAE,GAAG,eAAe,KAAK,YAAY,KAAK,CAAC,EAAE,IAC/E,EAAE,SAAS,EAAE,QAAQ,KAAK,EAAE;IAC/B,OAAO;IACP,YAAY;IACZ,OAAO;IACP,gBAAgB;IAChB;GACD,CAAC;GACD,MAAM,QAAgB,CAAC;GACvB,KAAK,MAAM,OAAO,MAAmD;IACpE,MAAM,OAAO,UAAU,GAAG;IAC1B,IAAI,MACH,MAAM,KAAK,IAAI;GAEjB;GACA,OAAO,cAAc,KAAK,QAAQ,KAAK;EACxC,SAAS,KAAK;GAGb,IAAI,QAAQ,QAAQ,OACnB,sDAAsD,SAAS,GAAG,mCAAmC,OAAO,GAAG,GAChH;GACA,OAAO;EACR;CACD;CAEA,MAAM,kBAAkB,OACvB,KACA,UAC6B;EAC7B,MAAM,MAAM,SAAS;EACrB,MAAM,KAAK,IAAI;EACf,MAAM,MAAM,MAAM,IAAI,GAAG;EACzB,IAAI,OAAO,IAAI,YAAY,IAC1B,OAAO,IAAI;EAEZ,MAAM,QAAQ,MAAM,KAAK,KAAK,KAAK,SAAU,SAAS,OAAQ,IAAI;EAClE,MAAM,IAAI,KAAK;GAAE;GAAO,WAAW,KAAK;EAAM,CAAC;EAC/C,OAAO;CACR;CAEA,OAAO;EACN,SAAS,OAAO,KAAK,WAAW,MAAM,gBAAgB,KAAK,KAAK,GAAG,KAAK,UAAU,MAAM,IAAI;EAC5F;EACA,kBAAkB,MAAM,MAAM;CAC/B;AACD"}
@@ -0,0 +1,76 @@
1
+ import { Field, Payload, PayloadRequest } from "payload";
2
+
3
+ //#region src/goals/trackGoalAction.d.ts
4
+ /** The action type form-builder stores as the block slug on a form's `actions` array. */
5
+ declare const GOAL_ACTION_TYPE = "analyticsGoal";
6
+ /**
7
+ * The run context form-builder hands a post-submit action, narrowed to what goal tracking
8
+ * reads. A structural subset rather than an import: analytics never depends on form-builder
9
+ * at runtime, so an install without it still resolves this module.
10
+ */
11
+ interface GoalActionRunArgs {
12
+ form: {
13
+ id: number | string;
14
+ title?: string;
15
+ };
16
+ submissionId: number | string;
17
+ /** One entry per answered field, keyed by the field's machine name. */
18
+ values: Array<{
19
+ field: string;
20
+ value: unknown;
21
+ }>;
22
+ config: Record<string, unknown>;
23
+ payload: Payload;
24
+ /**
25
+ * The request the action runs under. On a queued dispatch this is the job runner's own
26
+ * request, not the visitor's, so it carries neither the submitting host nor the tenant.
27
+ */
28
+ req?: PayloadRequest;
29
+ }
30
+ /**
31
+ * Structural counterpart of form-builder's `ActionDefinition<Record<string, unknown>>`; a
32
+ * value of this type is assignable to it, which `trackGoalAction.test.ts` pins.
33
+ */
34
+ interface GoalActionDefinition {
35
+ type: typeof GOAL_ACTION_TYPE;
36
+ label: string | Record<string, string>;
37
+ config: Field[];
38
+ run: (args: GoalActionRunArgs) => Promise<void>;
39
+ }
40
+ interface TrackGoalActionOptions {
41
+ /**
42
+ * Site the completion belongs to. Falls back to the submitting request's host as the
43
+ * native adapter's `hostname` policy judges it, then to the host of `serverURL`. With none
44
+ * of the three the completion is not recorded at all, and one warning names the install.
45
+ * Set it whenever a jobs runner queues actions: the runner's request carries the CMS host
46
+ * at best, and often no host at all.
47
+ */
48
+ hostname?: string | ((args: GoalActionRunArgs) => string);
49
+ /** Page the completion is attributed to. Defaults to `/forms/<form id>`. */
50
+ path?: string | ((args: GoalActionRunArgs) => string);
51
+ /**
52
+ * Analytics boundary to stamp; `null` is install-wide. Leave unset and the scope resolves
53
+ * from the action's request, which on a queued dispatch is the runner's rather than the
54
+ * submitter's and so usually lands install-wide. Set it on any scoped install whose
55
+ * actions are queued, since the submitter's tenant cannot be recovered there.
56
+ */
57
+ scope?: string | null | ((args: GoalActionRunArgs) => string | null | Promise<string | null>);
58
+ }
59
+ /**
60
+ * A form-builder post-submit action that completes an analytics goal, authored per form in
61
+ * the admin: pick the goal, optionally a revenue value (fixed, or read from a submission
62
+ * field) and its currency. Register it through form-builder's `actions` option under
63
+ * {@link GOAL_ACTION_TYPE}.
64
+ *
65
+ * Needs the native adapter, since it records through {@link trackServerEvent}. `essential`
66
+ * is deliberately unset: a goal is a measurement, so a failed write is logged and the
67
+ * submission still succeeds.
68
+ *
69
+ * On any install with a jobs runner, form-builder queues non-essential actions, and the
70
+ * queued run carries the runner's request rather than the visitor's. Set `hostname` (and
71
+ * `scope`, on a scoped install) there, since neither can be recovered from that request.
72
+ */
73
+ declare const trackGoalAction: (options?: TrackGoalActionOptions) => GoalActionDefinition;
74
+ //#endregion
75
+ export { GOAL_ACTION_TYPE, GoalActionDefinition, GoalActionRunArgs, TrackGoalActionOptions, trackGoalAction };
76
+ //# sourceMappingURL=trackGoalAction.d.ts.map