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

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 (213) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +5 -1
  3. package/dist/adapters/http/fetchJson.js +1 -1
  4. package/dist/adapters/plausible/plausible.d.ts +10 -0
  5. package/dist/adapters/plausible/plausible.js +40 -0
  6. package/dist/adapters/plausible/plausible.js.map +1 -1
  7. package/dist/adapters/posthog/posthog.d.ts +10 -1
  8. package/dist/adapters/posthog/posthog.js +47 -0
  9. package/dist/adapters/posthog/posthog.js.map +1 -1
  10. package/dist/adapters/umami/umami.d.ts +5 -1
  11. package/dist/adapters/umami/umami.js +26 -0
  12. package/dist/adapters/umami/umami.js.map +1 -1
  13. package/dist/capture/getTrackerConfig.d.ts +20 -0
  14. package/dist/capture/getTrackerConfig.js +31 -0
  15. package/dist/capture/getTrackerConfig.js.map +1 -0
  16. package/dist/capture/mountPath.js +14 -0
  17. package/dist/capture/mountPath.js.map +1 -0
  18. package/dist/capture/proxyEndpoint.js +123 -0
  19. package/dist/capture/proxyEndpoint.js.map +1 -0
  20. package/dist/capture/proxyRoutes.js +108 -0
  21. package/dist/capture/proxyRoutes.js.map +1 -0
  22. package/dist/capture/requestBody.js +68 -0
  23. package/dist/capture/requestBody.js.map +1 -0
  24. package/dist/capture/slots.d.ts +8 -0
  25. package/dist/capture/slots.js +43 -0
  26. package/dist/capture/slots.js.map +1 -0
  27. package/dist/capture/trackerConfig.d.ts +32 -0
  28. package/dist/capture/trackerConfig.js +70 -0
  29. package/dist/capture/trackerConfig.js.map +1 -0
  30. package/dist/capture/trackerEndpoint.js +35 -0
  31. package/dist/capture/trackerEndpoint.js.map +1 -0
  32. package/dist/core/capture.d.ts +49 -0
  33. package/dist/core/contract.d.ts +26 -2
  34. package/dist/core/contract.js.map +1 -1
  35. package/dist/core/options.d.ts +97 -2
  36. package/dist/core/options.js +63 -2
  37. package/dist/core/options.js.map +1 -1
  38. package/dist/core/registry.d.ts +1 -0
  39. package/dist/core/scopeList.js +32 -0
  40. package/dist/core/scopeList.js.map +1 -0
  41. package/dist/core/scopedRead.js +13 -6
  42. package/dist/core/scopedRead.js.map +1 -1
  43. package/dist/exports/next.d.ts +2 -1
  44. package/dist/exports/next.js +2 -1
  45. package/dist/exports/react.d.ts +4 -0
  46. package/dist/exports/react.js +5 -0
  47. package/dist/exports/rsc.d.ts +4 -1
  48. package/dist/exports/rsc.js +3 -1
  49. package/dist/exports/tracker.d.ts +18 -0
  50. package/dist/exports/tracker.js +12 -0
  51. package/dist/exports/types.d.ts +5 -2
  52. package/dist/fields/AnalyticsPanelClient.js +1 -1
  53. package/dist/fields/config/narrow.js +2 -0
  54. package/dist/fields/config/narrow.js.map +1 -1
  55. package/dist/fields/readForDocument.js +1 -1
  56. package/dist/goals/match.js +64 -0
  57. package/dist/goals/match.js.map +1 -0
  58. package/dist/goals/types.d.ts +33 -0
  59. package/dist/goals/types.js +7 -0
  60. package/dist/goals/types.js.map +1 -0
  61. package/dist/index.d.ts +4 -3
  62. package/dist/index.js +33 -9
  63. package/dist/index.js.map +1 -1
  64. package/dist/native/collections/events.js +21 -1
  65. package/dist/native/collections/events.js.map +1 -1
  66. package/dist/native/collections/rollups.js +24 -0
  67. package/dist/native/collections/rollups.js.map +1 -1
  68. package/dist/native/geo/maxmindResolver.js +2 -4
  69. package/dist/native/geo/maxmindResolver.js.map +1 -1
  70. package/dist/native/ingest/clientIp.js +15 -0
  71. package/dist/native/ingest/clientIp.js.map +1 -0
  72. package/dist/native/ingest/endpoint.js +40 -4
  73. package/dist/native/ingest/endpoint.js.map +1 -1
  74. package/dist/native/ingest/flushBatch.js +4 -13
  75. package/dist/native/ingest/flushBatch.js.map +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +76 -9
  77. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  78. package/dist/native/nativeAdapter.js +20 -4
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/native/query/eventAgg.js +39 -13
  81. package/dist/native/query/eventAgg.js.map +1 -1
  82. package/dist/native/rollupAcc.js +12 -1
  83. package/dist/native/rollupAcc.js.map +1 -1
  84. package/dist/native/rollups/bumpRollup.js +5 -1
  85. package/dist/native/rollups/bumpRollup.js.map +1 -1
  86. package/dist/native/rollups/deltas.js +28 -6
  87. package/dist/native/rollups/deltas.js.map +1 -1
  88. package/dist/next/captureRewrites.d.ts +41 -0
  89. package/dist/next/captureRewrites.js +56 -0
  90. package/dist/next/captureRewrites.js.map +1 -0
  91. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  92. package/dist/next/posthogProxyRewrites.js +16 -21
  93. package/dist/next/posthogProxyRewrites.js.map +1 -1
  94. package/dist/plugin/documentEndpoint.js +1 -1
  95. package/dist/plugin/paths.js +11 -1
  96. package/dist/plugin/paths.js.map +1 -1
  97. package/dist/plugin/runtime.d.ts +1 -0
  98. package/dist/plugin/runtime.js.map +1 -1
  99. package/dist/plugin/sourcesEndpoint.js +16 -4
  100. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  101. package/dist/plugin/warmTask.js +0 -0
  102. package/dist/plugin/warmTask.js.map +1 -1
  103. package/dist/providers/collection.js +56 -16
  104. package/dist/providers/collection.js.map +1 -1
  105. package/dist/providers/factory.js +8 -2
  106. package/dist/providers/factory.js.map +1 -1
  107. package/dist/react/AnalyticsProvider.d.ts +43 -0
  108. package/dist/react/AnalyticsProvider.js +66 -0
  109. package/dist/react/AnalyticsProvider.js.map +1 -0
  110. package/dist/react/TrackerBoot.d.ts +22 -0
  111. package/dist/react/TrackerBoot.js +30 -0
  112. package/dist/react/TrackerBoot.js.map +1 -0
  113. package/dist/react/useAnalytics.d.ts +17 -0
  114. package/dist/react/useAnalytics.js +36 -0
  115. package/dist/react/useAnalytics.js.map +1 -0
  116. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  117. package/dist/rsc/AnalyticsScripts.js +41 -0
  118. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  119. package/dist/surfacing/cacheStore.d.ts +1 -0
  120. package/dist/surfacing/cacheStore.js +18 -2
  121. package/dist/surfacing/cacheStore.js.map +1 -1
  122. package/dist/surfacing/engine.d.ts +1 -0
  123. package/dist/surfacing/engine.js +44 -4
  124. package/dist/surfacing/engine.js.map +1 -1
  125. package/dist/surfacing/queue.js +22 -6
  126. package/dist/surfacing/queue.js.map +1 -1
  127. package/dist/surfacing/rateLimiter.js +130 -0
  128. package/dist/surfacing/rateLimiter.js.map +1 -0
  129. package/dist/surfacing/retryPolicy.js +15 -0
  130. package/dist/surfacing/retryPolicy.js.map +1 -0
  131. package/dist/sync/syncTask.js +60 -33
  132. package/dist/sync/syncTask.js.map +1 -1
  133. package/dist/testing/memoryAdapter.d.ts +2 -0
  134. package/dist/testing/memoryAdapter.js +10 -0
  135. package/dist/testing/memoryAdapter.js.map +1 -1
  136. package/dist/tracker/autoCapture.d.ts +48 -0
  137. package/dist/tracker/autoCapture.js +129 -0
  138. package/dist/tracker/autoCapture.js.map +1 -0
  139. package/dist/tracker/consent.d.ts +24 -0
  140. package/dist/tracker/consent.js +48 -0
  141. package/dist/tracker/consent.js.map +1 -0
  142. package/dist/tracker/createTracker.d.ts +18 -0
  143. package/dist/tracker/createTracker.js +163 -0
  144. package/dist/tracker/createTracker.js.map +1 -0
  145. package/dist/tracker/initTracker.d.ts +22 -0
  146. package/dist/tracker/initTracker.js +33 -0
  147. package/dist/tracker/initTracker.js.map +1 -0
  148. package/dist/tracker/loadScript.d.ts +14 -0
  149. package/dist/tracker/loadScript.js +41 -0
  150. package/dist/tracker/loadScript.js.map +1 -0
  151. package/dist/tracker/pageTracking.d.ts +17 -0
  152. package/dist/tracker/pageTracking.js +38 -0
  153. package/dist/tracker/pageTracking.js.map +1 -0
  154. package/dist/tracker/registry.d.ts +27 -0
  155. package/dist/tracker/registry.js +73 -0
  156. package/dist/tracker/registry.js.map +1 -0
  157. package/dist/tracker/sinks/native.d.ts +22 -0
  158. package/dist/tracker/sinks/native.js +56 -0
  159. package/dist/tracker/sinks/native.js.map +1 -0
  160. package/dist/tracker/sinks/plausible.d.ts +14 -0
  161. package/dist/tracker/sinks/plausible.js +25 -0
  162. package/dist/tracker/sinks/plausible.js.map +1 -0
  163. package/dist/tracker/sinks/posthog.d.ts +14 -0
  164. package/dist/tracker/sinks/posthog.js +18 -0
  165. package/dist/tracker/sinks/posthog.js.map +1 -0
  166. package/dist/tracker/sinks/umami.d.ts +13 -0
  167. package/dist/tracker/sinks/umami.js +17 -0
  168. package/dist/tracker/sinks/umami.js.map +1 -0
  169. package/dist/tracker/sinks/vendor.d.ts +14 -0
  170. package/dist/tracker/sinks/vendor.js +66 -0
  171. package/dist/tracker/sinks/vendor.js.map +1 -0
  172. package/dist/tracker/transport.js +28 -0
  173. package/dist/tracker/transport.js.map +1 -0
  174. package/dist/tracker/types.d.ts +66 -0
  175. package/dist/translations/ar.js +6 -0
  176. package/dist/translations/ar.js.map +1 -1
  177. package/dist/translations/de.js +6 -0
  178. package/dist/translations/de.js.map +1 -1
  179. package/dist/translations/en.js +6 -0
  180. package/dist/translations/en.js.map +1 -1
  181. package/dist/translations/es.js +6 -0
  182. package/dist/translations/es.js.map +1 -1
  183. package/dist/translations/fr.js +6 -0
  184. package/dist/translations/fr.js.map +1 -1
  185. package/dist/translations/id.js +6 -0
  186. package/dist/translations/id.js.map +1 -1
  187. package/dist/translations/keys.d.ts +6 -0
  188. package/dist/translations/keys.js +6 -0
  189. package/dist/translations/keys.js.map +1 -1
  190. package/dist/translations/ko.js +6 -0
  191. package/dist/translations/ko.js.map +1 -1
  192. package/dist/translations/pt.js +6 -0
  193. package/dist/translations/pt.js.map +1 -1
  194. package/dist/translations/ru.js +6 -0
  195. package/dist/translations/ru.js.map +1 -1
  196. package/dist/translations/uk.js +6 -0
  197. package/dist/translations/uk.js.map +1 -1
  198. package/dist/translations/zh.js +6 -0
  199. package/dist/translations/zh.js.map +1 -1
  200. package/dist/widgets/breakdownTypes.js +5 -0
  201. package/dist/widgets/breakdownTypes.js.map +1 -1
  202. package/dist/widgets/readForWidget.js +24 -14
  203. package/dist/widgets/readForWidget.js.map +1 -1
  204. package/dist/widgets/readForWidgetBreakdown.js +23 -14
  205. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  206. package/dist/widgets/readForWidgetRealtime.js +1 -1
  207. package/dist/widgets/readForWidgetSeries.js +26 -16
  208. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  209. package/dist/widgets/registerWidgets.js +10 -4
  210. package/dist/widgets/registerWidgets.js.map +1 -1
  211. package/dist/widgets/types.js +4 -1
  212. package/dist/widgets/types.js.map +1 -1
  213. package/package.json +21 -6
@@ -0,0 +1,18 @@
1
+ import { TrackerGoal } from "../goals/types.js";
2
+ import { CaptureSnippet, SnippetScript } from "../core/capture.js";
3
+ import { ResolvedAutoCapture } from "../core/options.js";
4
+ import { TrackerConfig, TrackerSlotConfig } from "../capture/trackerConfig.js";
5
+ import { ConsentState, LoadScript, Sink, Tracker, TrackerEvent, TrackerOptions, TrackerWindow } from "../tracker/types.js";
6
+ import { AutoCapture, AutoCaptureHandlers, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, SCROLL_EVENT, createAutoCapture } from "../tracker/autoCapture.js";
7
+ import { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, createConsentQueue, readConsent, writeConsent } from "../tracker/consent.js";
8
+ import { createNoopTracker, createTracker } from "../tracker/createTracker.js";
9
+ import { DEFAULT_TRACKER_ENDPOINT, InitTrackerArgs, initTracker } from "../tracker/initTracker.js";
10
+ import { createScriptLoader } from "../tracker/loadScript.js";
11
+ import { PageTracking, createPageTracking } from "../tracker/pageTracking.js";
12
+ import { TrackerLease, acquireTracker } from "../tracker/registry.js";
13
+ import { PAGEVIEW_BUFFER_MS, createNativeSink } from "../tracker/sinks/native.js";
14
+ import { VendorSinkArgs } from "../tracker/sinks/vendor.js";
15
+ import { createPlausibleSink } from "../tracker/sinks/plausible.js";
16
+ import { createPosthogSink } from "../tracker/sinks/posthog.js";
17
+ import { createUmamiSink } from "../tracker/sinks/umami.js";
18
+ export { type AutoCapture, type AutoCaptureHandlers, CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, type CaptureSnippet, type ConsentState, DEFAULT_TRACKER_ENDPOINT, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, type InitTrackerArgs, type LoadScript, OUTBOUND_EVENT, PAGEVIEW_BUFFER_MS, type PageTracking, type ResolvedAutoCapture, SCROLL_EVENT, type Sink, type SnippetScript, type Tracker, type TrackerConfig, type TrackerEvent, type TrackerGoal, type TrackerLease, type TrackerOptions, type TrackerSlotConfig, type TrackerWindow, type VendorSinkArgs, acquireTracker, createAutoCapture, createConsentQueue, createNativeSink, createNoopTracker, createPageTracking, createPlausibleSink, createPosthogSink, createScriptLoader, createTracker, createUmamiSink, initTracker, readConsent, writeConsent };
@@ -0,0 +1,12 @@
1
+ import { DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, SCROLL_EVENT, createAutoCapture } from "../tracker/autoCapture.js";
2
+ import { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, createConsentQueue, readConsent, writeConsent } from "../tracker/consent.js";
3
+ import { createScriptLoader } from "../tracker/loadScript.js";
4
+ import { createPageTracking } from "../tracker/pageTracking.js";
5
+ import { PAGEVIEW_BUFFER_MS, createNativeSink } from "../tracker/sinks/native.js";
6
+ import { createPlausibleSink } from "../tracker/sinks/plausible.js";
7
+ import { createPosthogSink } from "../tracker/sinks/posthog.js";
8
+ import { createUmamiSink } from "../tracker/sinks/umami.js";
9
+ import { createNoopTracker, createTracker } from "../tracker/createTracker.js";
10
+ import { acquireTracker } from "../tracker/registry.js";
11
+ import { DEFAULT_TRACKER_ENDPOINT, initTracker } from "../tracker/initTracker.js";
12
+ export { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, DEFAULT_TRACKER_ENDPOINT, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, PAGEVIEW_BUFFER_MS, SCROLL_EVENT, acquireTracker, createAutoCapture, createConsentQueue, createNativeSink, createNoopTracker, createPageTracking, createPlausibleSink, createPosthogSink, createScriptLoader, createTracker, createUmamiSink, initTracker, readConsent, writeConsent };
@@ -1,7 +1,10 @@
1
+ import { Goal, GoalMatch, TrackerGoal } from "../goals/types.js";
2
+ import { CaptureClientKind, CaptureSnippet, CaptureSupport, ProxyDescriptor, ProxyRoute, SnippetScript } from "../core/capture.js";
1
3
  import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, FilterOperator, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
2
4
  import { SerializedCapabilities } from "../core/capabilities.js";
3
5
  import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "../binding/types.js";
6
+ import { AnalyticsPluginOptions, ResolvedAutoCapture } from "../core/options.js";
7
+ import { TrackerConfig, TrackerSlotConfig } from "../capture/trackerConfig.js";
4
8
  import { TimeframePreset } from "../timeframe/presets.js";
5
9
  import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions } from "../fields/factories.js";
6
- import { AnalyticsPluginOptions } from "../core/options.js";
7
- export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, FilterOperator, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };
10
+ export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, CaptureClientKind, CaptureSnippet, CaptureSupport, DateRange, DimensionKey, FilterOperator, type Goal, type GoalMatch, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, ProxyDescriptor, ProxyRoute, RateLimitDescriptor, type ResolvedAutoCapture, type SerializedCapabilities, SnippetScript, type TimeframePreset, type TrackerConfig, type TrackerGoal, type TrackerSlotConfig };
@@ -1,8 +1,8 @@
1
1
  "use client";
2
+ import { DOCUMENT_PATH } from "../plugin/paths.js";
2
3
  import { keys } from "../translations/keys.js";
3
4
  import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
4
5
  import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
5
- import { DOCUMENT_PATH } from "../plugin/paths.js";
6
6
  import { TrendChart } from "../charts/TrendChart.js";
7
7
  import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
8
8
  import { AnalyticsEmptyState, isNewDocumentAnalytics } from "./emptyState.js";
@@ -5,6 +5,8 @@ const satisfiesSerialized = (caps, req) => {
5
5
  if (req.perPageQuery && !caps.perPageQuery) return false;
6
6
  if (req.metrics?.some((m) => !caps.metrics.includes(m))) return false;
7
7
  if (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false;
8
+ if (req.filters?.some((d) => !caps.filters.includes(d))) return false;
9
+ if (req.filterOperators?.some((op) => !caps.filterOperators.includes(op))) return false;
8
10
  return true;
9
11
  };
10
12
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
1
+ {"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\tif (req.filters?.some((d) => !caps.filters.includes(d))) return false\n\tif (req.filterOperators?.some((op) => !caps.filterOperators.includes(op))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,iBAAiB,MAAM,OAAO,CAAC,KAAK,gBAAgB,SAAS,EAAE,CAAC,GAAG,OAAO;CAClF,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
@@ -1,7 +1,7 @@
1
+ import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
1
2
  import { resolveHostname, resolvePathCached } from "../binding/resolvePath.js";
2
3
  import { satisfiesCapabilities } from "../core/capabilities.js";
3
4
  import { supportsGranularity } from "../core/granularity.js";
4
- import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
5
5
  import { resolveReadContext } from "../core/scopedRead.js";
6
6
  import { resolveTimeframe } from "../timeframe/presets.js";
7
7
  import { previousWindow } from "../widgets/comparison.js";
@@ -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,33 @@
1
+ //#region src/goals/types.d.ts
2
+ /**
3
+ * How an incoming event is recognized as a completion of this goal. `goal` matches an
4
+ * explicit `trackGoal(slug)` call, which is what the attribute and action hookups emit.
5
+ */
6
+ type GoalMatch = {
7
+ kind: 'event';
8
+ name: string;
9
+ } | {
10
+ kind: 'path';
11
+ pattern: string;
12
+ } | {
13
+ kind: 'goal';
14
+ };
15
+ interface Goal {
16
+ /** Stable identifier, kebab-case; unique across the install's goals. */
17
+ slug: string;
18
+ /** Admin-facing label. Never leaves the server: the tracker config carries slugs only. */
19
+ name: string;
20
+ match: GoalMatch;
21
+ /** Revenue for one completion: a fixed amount, or read from an event property. */
22
+ value?: {
23
+ fixed?: number;
24
+ prop?: string;
25
+ };
26
+ /** ISO 4217 code the goal's value is denominated in. */
27
+ currency?: string;
28
+ }
29
+ /** The goal fields the browser tracker needs; `name` is admin-facing only. */
30
+ type TrackerGoal = Pick<Goal, 'slug' | 'match' | 'value' | 'currency'>;
31
+ //#endregion
32
+ export { Goal, GoalMatch, TrackerGoal };
33
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,7 @@
1
+ //#region src/goals/types.ts
2
+ /** Kebab-case, so a slug is safe in a URL, a data attribute, and a rollup bucket key. */
3
+ const GOAL_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
4
+ //#endregion
5
+ export { GOAL_SLUG_PATTERN };
6
+
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/goals/types.ts"],"sourcesContent":["/**\n * How an incoming event is recognized as a completion of this goal. `goal` matches an\n * explicit `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\nexport interface Goal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\t/** Admin-facing label. Never leaves the server: the tracker config carries slugs only. */\n\tname: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/** The goal fields the browser tracker needs; `name` is admin-facing only. */\nexport type TrackerGoal = Pick<Goal, 'slug' | 'match' | 'value' | 'currency'>\n\n/** Kebab-case, so a slug is safe in a URL, a data attribute, and a rollup bucket key. */\nexport const GOAL_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n"],"mappings":";;AAyBA,MAAa,oBAAoB"}
package/dist/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
+ import { Goal, GoalMatch, TrackerGoal } from "./goals/types.js";
1
2
  import { PLATFORM_SCOPE } from "./core/contract.js";
2
3
  import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "./binding/types.js";
4
+ import { CustomWidgetDef } from "./widgets/customWidget.js";
5
+ import { AnalyticsAccessOptions, AnalyticsCaptureOptions, AnalyticsGoalsOptions, AnalyticsPluginOptions, AutoCaptureOptions, CaptureConsentOption, ConsentMode, ConsentResolver, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ScopeResolver, ScopesResolver, TimezoneResolver } from "./core/options.js";
3
6
  import { TimeframePreset } from "./timeframe/presets.js";
4
7
  import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField } from "./fields/factories.js";
5
- import { CustomWidgetDef } from "./widgets/customWidget.js";
6
- import { AnalyticsAccessOptions, AnalyticsPluginOptions, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ScopeResolver, TimezoneResolver } from "./core/options.js";
7
8
  import { analyticsDefaultWidgets } from "./widgets/defaults.js";
8
9
 
9
10
  //#region src/index.d.ts
@@ -14,5 +15,5 @@ declare module 'payload' {
14
15
  }
15
16
  declare const analytics: (options: AnalyticsPluginOptions) => import("payload").Plugin;
16
17
  //#endregion
17
- export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsFieldsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, type CustomWidgetDef, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ScopeResolver, type TimeframePreset, type TimezoneResolver, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField };
18
+ export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsCaptureOptions, type AnalyticsFieldsOptions, type AnalyticsGoalsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type AutoCaptureOptions, type BindingContext, type CaptureConsentOption, type ConsentMode, type ConsentResolver, type CustomWidgetDef, type Goal, type GoalMatch, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ScopeResolver, type ScopesResolver, type TimeframePreset, type TimezoneResolver, type TrackerGoal, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField };
18
19
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
+ import { DOCUMENT_PATH, REALTIME_PATH, SOURCES_PATH } from "./plugin/paths.js";
2
+ import { isValidTimeZone } from "./timeframe/tz.js";
3
+ import { setRuntime } from "./plugin/runtime.js";
4
+ import { proxyEndpoints } from "./capture/proxyEndpoint.js";
1
5
  import { buildProvidersCollection } from "./providers/collection.js";
2
6
  import { resolveOptions } from "./core/options.js";
7
+ import { trackerEndpoint } from "./capture/trackerEndpoint.js";
3
8
  import { createRegistry, staticRegistryResolver } from "./core/registry.js";
4
- import { isValidTimeZone } from "./timeframe/tz.js";
5
- import { setRuntime } from "./plugin/runtime.js";
6
9
  import { PLATFORM_SCOPE } from "./core/contract.js";
7
- import { DOCUMENT_PATH, REALTIME_PATH, SOURCES_PATH } from "./plugin/paths.js";
8
10
  import { makeDocumentHandler } from "./plugin/documentEndpoint.js";
9
11
  import { isModuleNotFoundError } from "./plugin/peerImportError.js";
10
12
  import { kvCacheStore } from "./surfacing/cacheStore.js";
@@ -26,6 +28,7 @@ const analytics = definePlugin({
26
28
  plugin: async ({ config, plugins: _plugins, ...options }) => {
27
29
  if (options.disabled === true) return config;
28
30
  const resolved = resolveOptions(options);
31
+ const providersEnabled = resolved.providers.collection.enabled || Boolean(resolved.providers.resolve);
29
32
  const defaultLayout = config.admin?.dashboard?.defaultLayout;
30
33
  registerTranslations(config, options.translations);
31
34
  const registry = createRegistry(resolved.adapters, resolved.defaultAdapter);
@@ -89,12 +92,14 @@ const analytics = definePlugin({
89
92
  return "UTC";
90
93
  }
91
94
  };
95
+ const resolveGoals = async (_req, _scope) => resolved.goals;
92
96
  for (const adapter of resolved.adapters) adapter.register?.(config, {
93
97
  scoped: resolved.scoped,
94
98
  resolveScope,
95
- resolveTimezone
99
+ resolveTimezone,
100
+ resolveGoals
96
101
  });
97
- if (resolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === "function")) config.endpoints = [...config.endpoints ?? [], {
102
+ if (resolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === "function") || providersEnabled) config.endpoints = [...config.endpoints ?? [], {
98
103
  method: "get",
99
104
  path: REALTIME_PATH,
100
105
  handler: makeRealtimeHandler()
@@ -109,11 +114,17 @@ const analytics = definePlugin({
109
114
  path: SOURCES_PATH,
110
115
  handler: makeSourcesHandler()
111
116
  }];
117
+ if (resolved.adapters.some((a) => a.capture) || providersEnabled) config.endpoints = [
118
+ ...config.endpoints,
119
+ ...proxyEndpoints(),
120
+ trackerEndpoint()
121
+ ];
112
122
  if (resolved.widgets.enabled) {
113
- const multiProvider = registry.isMultiProvider() || resolved.providers.collection.enabled || Boolean(resolved.providers.resolve);
123
+ const multiProvider = registry.isMultiProvider() || providersEnabled;
114
124
  registerWidgets(config, {
115
125
  adapters: resolved.adapters,
116
126
  multiProvider,
127
+ providersEnabled,
117
128
  disabled: resolved.widgets.disabled,
118
129
  register: resolved.widgets.register,
119
130
  localizeText: resolved.widgets.localizeText,
@@ -122,7 +133,7 @@ const analytics = definePlugin({
122
133
  }
123
134
  if (resolved.cache.warm.enabled) config.jobs = {
124
135
  ...config.jobs,
125
- tasks: [...config.jobs?.tasks ?? [], warmTask(resolved.cache.warm.cron, defaultLayout)]
136
+ tasks: [...config.jobs?.tasks ?? [], warmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes)]
126
137
  };
127
138
  if (resolved.sync.enabled) {
128
139
  config.collections = [...config.collections ?? [], syncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {
@@ -137,7 +148,8 @@ const analytics = definePlugin({
137
148
  cron: resolved.sync.cron,
138
149
  lookbackDays: resolved.sync.lookbackDays,
139
150
  collectionSlug: resolved.sync.collectionSlug,
140
- adapterIds: resolved.sync.adapters
151
+ adapterIds: resolved.sync.adapters,
152
+ scopes: resolved.scopes
141
153
  })]
142
154
  };
143
155
  }
@@ -150,7 +162,11 @@ const analytics = definePlugin({
150
162
  const engine = createEngine({
151
163
  store: kvCacheStore(payload.kv),
152
164
  queue: { concurrency: 4 },
153
- ttl: resolved.cache.ttl
165
+ ttl: resolved.cache.ttl,
166
+ timeoutMs: resolved.cache.timeoutMs,
167
+ onError: (err, adapterId) => {
168
+ payload.logger?.warn(`analytics: read failed for adapter "${adapterId}": ${String(err)}`);
169
+ }
154
170
  });
155
171
  setRuntime(payload, {
156
172
  registry,
@@ -158,6 +174,14 @@ const analytics = definePlugin({
158
174
  resolveScope,
159
175
  resolveTimezone,
160
176
  platformAdapterId: resolved.platformAdapter,
177
+ captureSlots: resolved.capture.slots,
178
+ capturePaths: resolved.capture.paths,
179
+ captureProxy: resolved.capture.proxy,
180
+ consentFor: resolved.capture.consent,
181
+ autoCapture: resolved.capture.autoCapture,
182
+ goals: resolved.goals,
183
+ ingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,
184
+ scoped: resolved.scoped,
161
185
  configAdapterIds: new Set(resolved.adapters.map((a) => a.id)),
162
186
  platformRead: resolved.access.platformRead,
163
187
  bindings: resolved.bindings,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, { scoped: resolved.scoped, resolveScope, resolveTimezone })\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function')\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t]\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider =\n\t\t\t\tregistry.isMultiProvider() ||\n\t\t\t\tresolved.providers.collection.enabled ||\n\t\t\t\tBoolean(resolved.providers.resolve)\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t})\n\t\t}\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), warmTask(resolved.cache.warm.cron, defaultLayout)],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: 'scope',\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,IAAI,QAAQ,aAAa,MACxB,OAAO;EAER,MAAM,WAAW,eAAe,OAAO;EACvC,MAAM,gBAAgB,OAAO,OAAO,WAAW;EAC/C,qBAAqB,QAAQ,QAAQ,YAAY;EACjD,MAAM,WAAW,eAAe,SAAS,UAAU,SAAS,cAAc;EAC1E,MAAM,eAAe;GAAE,UAAU,SAAS;GAAU,WAAW,SAAS;EAAe;EACvF,IAAI,kBAAkB,uBAAuB,QAAQ;EACrD,IAAI,4BAA4B,CAAC;EACjC,MAAM,mBAAmB,SAAS,UAAU;EAC5C,IAAI,kBACH,kBAAkB,OAAO,SACxB,kBACC,cACA,MAAM,iBAAiB;GAAE,SAAS,KAAK;GAAS,KAAK,KAAK;GAAK,OAAO,KAAK;EAAM,CAAC,CACnF;OACK,IAAI,SAAS,UAAU,WAAW,SAAS;GACjD,MAAM,SAAS,6BAA6B;IAC3C,MAAM;IACN,QAAQ,0BACP,SAAS,UAAU,WAAW,MAC9B,SAAS,UAAU,WAAW,UAC/B;GACD,CAAC;GACD,kBAAkB,OAAO;GACzB,sBAAsB,OAAO;EAC9B;EACA,MAAM,eAAe,OAAO,QAAwB,SAAS,cAAc,EAAE,IAAI,CAAC;EAClF,IAAI,SAAS,UAAU,WAAW,SAAS;GAC1C,MAAM,EAAE,gBAAgB,8BAA8B,MAAM,OAC3D,+BACC,OAAO,QAAiB;IACzB,IAAI,sBAAsB,GAAG,GAC5B,MAAM,IAAI,MACT,2GACD;IAED,M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AAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,OAAO;IAC/C,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,SAAS,aAAa;IAC3B,OAAO,aAAa,QAAQ,EAAE;IAC9B,OAAO,EAAE,aAAa,EAAE;IACxB,KAAK,SAAS,MAAM;GACrB,CAAC;GACD,WAAW,SAAS;IACnB;IACA;IACA;IACA;IACA,mBAAmB,SAAS;IAC5B,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport type { Goal } from './goals/types'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\t// A tenant's own runtime adapter (providers.collection or providers.resolve) has\n\t\t// capabilities unknown at config time, so it opens the widget/endpoint gates that\n\t\t// otherwise key off the config-adapter capability union.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\t// Config goals are install-wide, so scope is accepted and ignored here; a collection\n\t\t// source resolves per scope behind the same signature.\n\t\tconst resolveGoals = async (_req: PayloadRequest, _scope?: string | null): Promise<Goal[]> =>\n\t\t\tresolved.goals\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, {\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveGoals,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function') ||\n\t\t\tprovidersEnabled\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t]\n\t\t// A runtime provider's capture support is unknown at config time, so providers\n\t\t// alone are enough to mount the proxy; every slot is still resolved per request.\n\t\tif (resolved.adapters.some((a) => a.capture) || providersEnabled) {\n\t\t\tconfig.endpoints = [...config.endpoints, ...proxyEndpoints(), trackerEndpoint()]\n\t\t}\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider = registry.isMultiProvider() || providersEnabled\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tprovidersEnabled,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t})\n\t\t}\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\twarmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: 'scope',\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t\tscopes: resolved.scopes,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\tpayload.logger?.warn(`analytics: read failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\t\t\t},\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tcaptureSlots: resolved.capture.slots,\n\t\t\t\tcapturePaths: resolved.capture.paths,\n\t\t\t\tcaptureProxy: resolved.capture.proxy,\n\t\t\t\tconsentFor: resolved.capture.consent,\n\t\t\t\tautoCapture: resolved.capture.autoCapture,\n\t\t\t\tgoals: resolved.goals,\n\t\t\t\tingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsCaptureOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAutoCaptureOptions,\n\tCaptureConsentOption,\n\tConsentMode,\n\tConsentResolver,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tScopesResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { Goal, GoalMatch, TrackerGoal } from './goals/types'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,IAAI,QAAQ,aAAa,MACxB,OAAO;EAER,MAAM,WAAW,eAAe,OAAO;EAIvC,MAAM,mBACL,SAAS,UAAU,WAAW,WAAW,QAAQ,SAAS,UAAU,OAAO;EAC5E,MAAM,gBAAgB,OAAO,OAAO,WAAW;EAC/C,qBAAqB,QAAQ,QAAQ,YAAY;EACjD,MAAM,WAA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AAQ,KAAK,uCAAuC,UAAU,KAAK,OAAO,GAAG,GAAG;IACzF;GACD,CAAC;GACD,WAAW,SAAS;IACnB;IACA;IACA;IACA;IACA,mBAAmB,SAAS;IAC5B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,YAAY,SAAS,QAAQ;IAC7B,aAAa,SAAS,QAAQ;IAC9B,OAAO,SAAS;IAChB,YAAY,SAAS,SAAS,MAAM,MAAM,EAAE,MAAM,GAAG,QAAQ;IAC7D,QAAQ,SAAS;IACjB,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
@@ -25,7 +25,11 @@ const eventsCollection = (scoped = false) => ({
25
25
  name: "type",
26
26
  type: "select",
27
27
  required: true,
28
- options: ["pageview", "event"],
28
+ options: [
29
+ "pageview",
30
+ "event",
31
+ "goal"
32
+ ],
29
33
  index: true
30
34
  },
31
35
  {
@@ -87,6 +91,22 @@ const eventsCollection = (scoped = false) => ({
87
91
  name: "props",
88
92
  type: "json"
89
93
  },
94
+ {
95
+ name: "value",
96
+ type: "number"
97
+ },
98
+ {
99
+ name: "currency",
100
+ type: "text"
101
+ },
102
+ {
103
+ name: "scrollDepth",
104
+ type: "number"
105
+ },
106
+ {
107
+ name: "goals",
108
+ type: "json"
109
+ },
90
110
  ...scoped ? [{
91
111
  name: "scope",
92
112
  type: "text",
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":[],"sources":["../../../src/native/collections/events.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const EVENTS_SLUG = 'analytics-events'\n\n/**\n * The scope column exists only for scoped installs (a configured scopeResolver);\n * enabling scope on an existing native install therefore needs a migration adding\n * the column to events and rollups.\n */\nexport const eventsCollection = (scoped = false): CollectionConfig => ({\n\tslug: EVENTS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => false, delete: () => false },\n\tfields: [\n\t\t{ name: 'timestamp', type: 'date', required: true, index: true },\n\t\t{ name: 'type', type: 'select', required: true, options: ['pageview', 'event'], index: true },\n\t\t{ name: 'name', type: 'text' },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'hostname', type: 'text', required: true },\n\t\t{ name: 'referrer', type: 'text' },\n\t\t{ name: 'device', type: 'text' },\n\t\t{ name: 'source', type: 'text' },\n\t\t{ name: 'country', type: 'text' },\n\t\t{ name: 'region', type: 'text' },\n\t\t{ name: 'city', type: 'text' },\n\t\t{ name: 'visitorHash', type: 'text', required: true, index: true },\n\t\t{ name: 'sessionId', type: 'text', required: true, index: true },\n\t\t{ name: 'durationMs', type: 'number' },\n\t\t{ name: 'props', type: 'json' },\n\t\t...(scoped ? [{ name: 'scope', type: 'text', index: true } satisfies Field] : []),\n\t],\n\tindexes: [{ fields: ['path', 'timestamp'] }, { fields: ['type', 'timestamp'] }],\n})\n"],"mappings":";AAEA,MAAa,cAAc;;;;;;AAO3B,MAAa,oBAAoB,SAAS,WAA6B;CACtE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAO,cAAc;CAAM;CAC1F,QAAQ;EACP;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC/D;GAAE,MAAM;GAAQ,MAAM;GAAU,UAAU;GAAM,SAAS,CAAC,YAAY,OAAO;GAAG,OAAO;EAAK;EAC5F;GAAE,MAAM;GAAQ,MAAM;EAAO;EAC7B;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;EAAK;EACjD;GAAE,MAAM;GAAY,MAAM;EAAO;EACjC;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAW,MAAM;EAAO;EAChC;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAQ,MAAM;EAAO;EAC7B;GAAE,MAAM;GAAe,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EACjE;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC/D;GAAE,MAAM;GAAc,MAAM;EAAS;EACrC;GAAE,MAAM;GAAS,MAAM;EAAO;EAC9B,GAAI,SAAS,CAAC;GAAE,MAAM;GAAS,MAAM;GAAQ,OAAO;EAAK,CAAiB,IAAI,CAAC;CAChF;CACA,SAAS,CAAC,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,GAAG,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,CAAC;AAC/E"}
1
+ {"version":3,"file":"events.js","names":[],"sources":["../../../src/native/collections/events.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const EVENTS_SLUG = 'analytics-events'\n\n/**\n * The scope column exists only for scoped installs (a configured scopeResolver);\n * enabling scope on an existing native install therefore needs a migration adding\n * the column to events and rollups.\n */\nexport const eventsCollection = (scoped = false): CollectionConfig => ({\n\tslug: EVENTS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => false, delete: () => false },\n\tfields: [\n\t\t{ name: 'timestamp', type: 'date', required: true, index: true },\n\t\t{\n\t\t\tname: 'type',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\toptions: ['pageview', 'event', 'goal'],\n\t\t\tindex: true,\n\t\t},\n\t\t{ name: 'name', type: 'text' },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'hostname', type: 'text', required: true },\n\t\t{ name: 'referrer', type: 'text' },\n\t\t{ name: 'device', type: 'text' },\n\t\t{ name: 'source', type: 'text' },\n\t\t{ name: 'country', type: 'text' },\n\t\t{ name: 'region', type: 'text' },\n\t\t{ name: 'city', type: 'text' },\n\t\t{ name: 'visitorHash', type: 'text', required: true, index: true },\n\t\t{ name: 'sessionId', type: 'text', required: true, index: true },\n\t\t{ name: 'durationMs', type: 'number' },\n\t\t{ name: 'props', type: 'json' },\n\t\t{ name: 'value', type: 'number' },\n\t\t{ name: 'currency', type: 'text' },\n\t\t{ name: 'scrollDepth', type: 'number' },\n\t\t// The completions matched at ingest, so a raw-event read (filtered or hourly) reports\n\t\t// the same conversions the rollups hold instead of re-matching against goals that may\n\t\t// since have changed.\n\t\t{ name: 'goals', type: 'json' },\n\t\t...(scoped ? [{ name: 'scope', type: 'text', index: true } satisfies Field] : []),\n\t],\n\tindexes: [{ fields: ['path', 'timestamp'] }, { fields: ['type', 'timestamp'] }],\n})\n"],"mappings":";AAEA,MAAa,cAAc;;;;;;AAO3B,MAAa,oBAAoB,SAAS,WAA6B;CACtE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAO,cAAc;CAAM;CAC1F,QAAQ;EACP;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC/D;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,SAAS;IAAC;IAAY;IAAS;GAAM;GACrC,OAAO;EACR;EACA;GAAE,MAAM;GAAQ,MAAM;EAAO;EAC7B;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;EAAK;EACjD;GAAE,MAAM;GAAY,MAAM;EAAO;EACjC;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAW,MAAM;EAAO;EAChC;GAAE,MAAM;GAAU,MAAM;EAAO;EAC/B;GAAE,MAAM;GAAQ,MAAM;EAAO;EAC7B;GAAE,MAAM;GAAe,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EACjE;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC/D;GAAE,MAAM;GAAc,MAAM;EAAS;EACrC;GAAE,MAAM;GAAS,MAAM;EAAO;EAC9B;GAAE,MAAM;GAAS,MAAM;EAAS;EAChC;GAAE,MAAM;GAAY,MAAM;EAAO;EACjC;GAAE,MAAM;GAAe,MAAM;EAAS;EAItC;GAAE,MAAM;GAAS,MAAM;EAAO;EAC9B,GAAI,SAAS,CAAC;GAAE,MAAM;GAAS,MAAM;GAAQ,OAAO;EAAK,CAAiB,IAAI,CAAC;CAChF;CACA,SAAS,CAAC,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,GAAG,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,CAAC;AAC/E"}
@@ -96,6 +96,30 @@ const rollupsCollection = (scoped = false) => ({
96
96
  type: "number",
97
97
  required: true,
98
98
  defaultValue: 0
99
+ },
100
+ {
101
+ name: "conversions",
102
+ type: "number",
103
+ required: true,
104
+ defaultValue: 0
105
+ },
106
+ {
107
+ name: "revenue",
108
+ type: "number",
109
+ required: true,
110
+ defaultValue: 0
111
+ },
112
+ {
113
+ name: "scrollDepthSum",
114
+ type: "number",
115
+ required: true,
116
+ defaultValue: 0
117
+ },
118
+ {
119
+ name: "scrollSamples",
120
+ type: "number",
121
+ required: true,
122
+ defaultValue: 0
99
123
  }
100
124
  ],
101
125
  indexes: [scoped ? {
@@ -1 +1 @@
1
- {"version":3,"file":"rollups.js","names":[],"sources":["../../../src/native/collections/rollups.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const ROLLUPS_SLUG = 'analytics-rollups'\n\n/**\n * `hostname` ('' = the hostname-less family) is part of the unique bucket on every\n * native install: unfiltered reads hit the '' family and hostname-scoped reads hit the\n * exact-hostname family, both kept per-bucket exact by dual emission in computeRollupDeltas.\n * Scoped installs add a further required scope key ('' = the null scope) to every rollup\n * row and to the unique bucket index, so each scope accumulates its own buckets.\n * Existing native installs need a migration for the new hostname column (and, if\n * enabling scope, the scope column too).\n */\nexport const rollupsCollection = (scoped = false): CollectionConfig => ({\n\tslug: ROLLUPS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => true, delete: () => true },\n\tfields: [\n\t\t{ name: 'granularity', type: 'text', required: true },\n\t\t{ name: 'period', type: 'date', required: true, index: true },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'dimension', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'dimvalue', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'hostname', type: 'text', required: true, defaultValue: '' },\n\t\t...(scoped\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'scope',\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tdefaultValue: '',\n\t\t\t\t\t\tindex: true,\n\t\t\t\t\t} satisfies Field,\n\t\t\t\t]\n\t\t\t: []),\n\t\t{ name: 'pageviews', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'events', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'durationMs', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'visitors', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'sessions', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'samples', type: 'number', required: true, defaultValue: 0 },\n\t],\n\tindexes: [\n\t\tscoped\n\t\t\t? {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname', 'scope'],\n\t\t\t\t\tunique: true,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname'],\n\t\t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ACT,CACH;AACD"}
1
+ {"version":3,"file":"rollups.js","names":[],"sources":["../../../src/native/collections/rollups.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const ROLLUPS_SLUG = 'analytics-rollups'\n\n/**\n * `hostname` ('' = the hostname-less family) is part of the unique bucket on every\n * native install: unfiltered reads hit the '' family and hostname-scoped reads hit the\n * exact-hostname family, both kept per-bucket exact by dual emission in computeRollupDeltas.\n * Scoped installs add a further required scope key ('' = the null scope) to every rollup\n * row and to the unique bucket index, so each scope accumulates its own buckets.\n * Existing native installs need a migration for the new hostname column (and, if\n * enabling scope, the scope column too).\n */\nexport const rollupsCollection = (scoped = false): CollectionConfig => ({\n\tslug: ROLLUPS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => true, delete: () => true },\n\tfields: [\n\t\t{ name: 'granularity', type: 'text', required: true },\n\t\t{ name: 'period', type: 'date', required: true, index: true },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'dimension', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'dimvalue', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'hostname', type: 'text', required: true, defaultValue: '' },\n\t\t...(scoped\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'scope',\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tdefaultValue: '',\n\t\t\t\t\t\tindex: true,\n\t\t\t\t\t} satisfies Field,\n\t\t\t\t]\n\t\t\t: []),\n\t\t{ name: 'pageviews', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'events', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'durationMs', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'visitors', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'sessions', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'samples', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'conversions', type: 'number', required: true, defaultValue: 0 },\n\t\t// Revenue is stored in the event's own currency and never converted, so a bucket\n\t\t// spanning several currencies sums figures that are not comparable.\n\t\t{ name: 'revenue', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'scrollDepthSum', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'scrollSamples', type: 'number', required: true, defaultValue: 0 },\n\t],\n\tindexes: [\n\t\tscoped\n\t\t\t? {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname', 'scope'],\n\t\t\t\t\tunique: true,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname'],\n\t\t\t\t\tunique: true,\n\t\t\t\t},\n\t],\n})\n"],"mappings":";AAEA,MAAa,eAAe;;;;;;;;;;AAW5B,MAAa,qBAAqB,SAAS,WAA6B;CACvE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAM,cAAc;CAAK;CACxF,QAAQ;EACP;GAAE,MAAM;GAAe,MAAM;GAAQ,UAAU;EAAK;EACpD;GAAE,MAAM;GAAU,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC5D;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACpE;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACnE;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACnE,GAAI,SACD,CACA;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,cAAc;GACd,OAAO;EACR,CACD,IACC,CAAC;EACJ;GAAE,MAAM;GAAa,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACrE;GAAE,MAAM;GAAU,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EAClE;GAAE,MAAM;GAAc,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACtE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAW,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACnE;GAAE,MAAM;GAAe,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EAGvE;GAAE,MAAM;GAAW,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACnE;GAAE,MAAM;GAAkB,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EAC1E;GAAE,MAAM;GAAiB,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;CAC1E;CACA,SAAS,CACR,SACG;EACA,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;GAAY;GAAY;EAAO;EACtF,QAAQ;CACT,IACC;EACA,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;GAAY;EAAU;EAC7E,QAAQ;CACT,CACH;AACD"}
@@ -1,7 +1,5 @@
1
+ import { clientIpFromHeaders } from "../ingest/clientIp.js";
1
2
  //#region src/native/geo/maxmindResolver.ts
2
- const clientIp = (headers) => {
3
- return headers.get("x-forwarded-for")?.split(",")[0]?.trim() || headers.get("x-real-ip") || null;
4
- };
5
3
  /**
6
4
  * Optional MaxMind GeoLite2 resolver. The mmdb and the maxmind lib are loaded
7
5
  * lazily on first use. Any failure (lib not installed, file missing/unreadable,
@@ -26,7 +24,7 @@ function maxmindResolver(options) {
26
24
  return readerPromise;
27
25
  };
28
26
  return async (headers) => {
29
- const ip = clientIp(headers);
27
+ const ip = clientIpFromHeaders(headers);
30
28
  if (!ip) return {};
31
29
  let reader;
32
30
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"maxmindResolver.js","names":[],"sources":["../../../src/native/geo/maxmindResolver.ts"],"sourcesContent":["import type { CityResponse, Reader } from 'maxmind'\nimport type { Geo, GeoResolver } from './geoResolver'\n\nexport interface MaxmindOptions {\n\tdbPath: string\n}\n\nconst clientIp = (headers: Headers): string | null => {\n\tconst fwd = headers.get('x-forwarded-for')?.split(',')[0]?.trim()\n\treturn fwd || headers.get('x-real-ip') || null\n}\n\n/**\n * Optional MaxMind GeoLite2 resolver. The mmdb and the maxmind lib are loaded\n * lazily on first use. Any failure (lib not installed, file missing/unreadable,\n * lookup error) degrades to empty geo after a single warning, so a missing or\n * unconfigured database never breaks ingestion.\n */\nexport function maxmindResolver(options: MaxmindOptions): GeoResolver {\n\tlet readerPromise: Promise<Reader<CityResponse>> | undefined\n\tlet warned = false\n\n\tconst warn = (detail: unknown): null => {\n\t\tif (!warned) {\n\t\t\twarned = true\n\t\t\tconsole.warn(\n\t\t\t\t`[analytics] MaxMind geo unavailable for \"${options.dbPath}\"; geo will be empty.`,\n\t\t\t\tdetail instanceof Error ? detail.message : detail\n\t\t\t)\n\t\t}\n\t\treturn null\n\t}\n\n\tconst getReader = (): Promise<Reader<CityResponse>> => {\n\t\tif (!readerPromise) {\n\t\t\treaderPromise = (async () => {\n\t\t\t\tconst { open } = await import('maxmind')\n\t\t\t\treturn open<CityResponse>(options.dbPath)\n\t\t\t})()\n\t\t}\n\t\treturn readerPromise\n\t}\n\n\treturn async (headers: Headers): Promise<Geo> => {\n\t\tconst ip = clientIp(headers)\n\t\tif (!ip) {\n\t\t\treturn {}\n\t\t}\n\t\tlet reader: Reader<CityResponse> | null\n\t\ttry {\n\t\t\treader = await getReader()\n\t\t} catch (err) {\n\t\t\twarn(err)\n\t\t\treturn {}\n\t\t}\n\t\ttry {\n\t\t\tconst r = reader.get(ip)\n\t\t\tif (!r) {\n\t\t\t\treturn {}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcountry: r.country?.iso_code ?? undefined,\n\t\t\t\tregion: r.subdivisions?.[0]?.iso_code ?? undefined,\n\t\t\t\tcity: r.city?.names.en ?? undefined,\n\t\t\t}\n\t\t} catch (err) {\n\t\t\twarn(err)\n\t\t\treturn {}\n\t\t}\n\t}\n}\n"],"mappings":";AAOA,MAAM,YAAY,YAAoC;CAErD,OADY,QAAQ,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,IAAI,KAAK,KAClD,QAAQ,IAAI,WAAW,KAAK;AAC3C;;;;;;;AAQA,SAAgB,gBAAgB,SAAsC;CACrE,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,QAAQ,WAA0B;EACvC,IAAI,CAAC,QAAQ;GACZ,SAAS;GACT,QAAQ,KACP,4CAA4C,QAAQ,OAAO,wBAC3D,kBAAkB,QAAQ,OAAO,UAAU,MAC5C;EACD;EACA,OAAO;CACR;CAEA,MAAM,kBAAiD;EACtD,IAAI,CAAC,eACJ,iBAAiB,YAAY;GAC5B,MAAM,EAAE,SAAS,MAAM,OAAO;GAC9B,OAAO,KAAmB,QAAQ,MAAM;EACzC,GAAG;EAEJ,OAAO;CACR;CAEA,OAAO,OAAO,YAAmC;EAChD,MAAM,KAAK,SAAS,OAAO;EAC3B,IAAI,CAAC,IACJ,OAAO,CAAC;EAET,IAAI;EACJ,IAAI;GACH,SAAS,MAAM,UAAU;EAC1B,SAAS,KAAK;GACb,KAAK,GAAG;GACR,OAAO,CAAC;EACT;EACA,IAAI;GACH,MAAM,IAAI,OAAO,IAAI,EAAE;GACvB,IAAI,CAAC,GACJ,OAAO,CAAC;GAET,OAAO;IACN,SAAS,EAAE,SAAS,YAAY,KAAA;IAChC,QAAQ,EAAE,eAAe,IAAI,YAAY,KAAA;IACzC,MAAM,EAAE,MAAM,MAAM,MAAM,KAAA;GAC3B;EACD,SAAS,KAAK;GACb,KAAK,GAAG;GACR,OAAO,CAAC;EACT;CACD;AACD"}
1
+ {"version":3,"file":"maxmindResolver.js","names":[],"sources":["../../../src/native/geo/maxmindResolver.ts"],"sourcesContent":["import type { CityResponse, Reader } from 'maxmind'\nimport { clientIpFromHeaders } from '../ingest/clientIp'\nimport type { Geo, GeoResolver } from './geoResolver'\n\nexport interface MaxmindOptions {\n\tdbPath: string\n}\n\n/**\n * Optional MaxMind GeoLite2 resolver. The mmdb and the maxmind lib are loaded\n * lazily on first use. Any failure (lib not installed, file missing/unreadable,\n * lookup error) degrades to empty geo after a single warning, so a missing or\n * unconfigured database never breaks ingestion.\n */\nexport function maxmindResolver(options: MaxmindOptions): GeoResolver {\n\tlet readerPromise: Promise<Reader<CityResponse>> | undefined\n\tlet warned = false\n\n\tconst warn = (detail: unknown): null => {\n\t\tif (!warned) {\n\t\t\twarned = true\n\t\t\tconsole.warn(\n\t\t\t\t`[analytics] MaxMind geo unavailable for \"${options.dbPath}\"; geo will be empty.`,\n\t\t\t\tdetail instanceof Error ? detail.message : detail\n\t\t\t)\n\t\t}\n\t\treturn null\n\t}\n\n\tconst getReader = (): Promise<Reader<CityResponse>> => {\n\t\tif (!readerPromise) {\n\t\t\treaderPromise = (async () => {\n\t\t\t\tconst { open } = await import('maxmind')\n\t\t\t\treturn open<CityResponse>(options.dbPath)\n\t\t\t})()\n\t\t}\n\t\treturn readerPromise\n\t}\n\n\treturn async (headers: Headers): Promise<Geo> => {\n\t\tconst ip = clientIpFromHeaders(headers)\n\t\tif (!ip) {\n\t\t\treturn {}\n\t\t}\n\t\tlet reader: Reader<CityResponse> | null\n\t\ttry {\n\t\t\treader = await getReader()\n\t\t} catch (err) {\n\t\t\twarn(err)\n\t\t\treturn {}\n\t\t}\n\t\ttry {\n\t\t\tconst r = reader.get(ip)\n\t\t\tif (!r) {\n\t\t\t\treturn {}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcountry: r.country?.iso_code ?? undefined,\n\t\t\t\tregion: r.subdivisions?.[0]?.iso_code ?? undefined,\n\t\t\t\tcity: r.city?.names.en ?? undefined,\n\t\t\t}\n\t\t} catch (err) {\n\t\t\twarn(err)\n\t\t\treturn {}\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;AAcA,SAAgB,gBAAgB,SAAsC;CACrE,IAAI;CACJ,IAAI,SAAS;CAEb,MAAM,QAAQ,WAA0B;EACvC,IAAI,CAAC,QAAQ;GACZ,SAAS;GACT,QAAQ,KACP,4CAA4C,QAAQ,OAAO,wBAC3D,kBAAkB,QAAQ,OAAO,UAAU,MAC5C;EACD;EACA,OAAO;CACR;CAEA,MAAM,kBAAiD;EACtD,IAAI,CAAC,eACJ,iBAAiB,YAAY;GAC5B,MAAM,EAAE,SAAS,MAAM,OAAO;GAC9B,OAAO,KAAmB,QAAQ,MAAM;EACzC,GAAG;EAEJ,OAAO;CACR;CAEA,OAAO,OAAO,YAAmC;EAChD,MAAM,KAAK,oBAAoB,OAAO;EACtC,IAAI,CAAC,IACJ,OAAO,CAAC;EAET,IAAI;EACJ,IAAI;GACH,SAAS,MAAM,UAAU;EAC1B,SAAS,KAAK;GACb,KAAK,GAAG;GACR,OAAO,CAAC;EACT;EACA,IAAI;GACH,MAAM,IAAI,OAAO,IAAI,EAAE;GACvB,IAAI,CAAC,GACJ,OAAO,CAAC;GAET,OAAO;IACN,SAAS,EAAE,SAAS,YAAY,KAAA;IAChC,QAAQ,EAAE,eAAe,IAAI,YAAY,KAAA;IACzC,MAAM,EAAE,MAAM,MAAM,MAAM,KAAA;GAC3B;EACD,SAAS,KAAK;GACb,KAAK,GAAG;GACR,OAAO,CAAC;EACT;CACD;AACD"}
@@ -0,0 +1,15 @@
1
+ //#region src/native/ingest/clientIp.ts
2
+ /**
3
+ * The originating client IP a proxy chain reported: the first hop of
4
+ * `x-forwarded-for`, else `x-real-ip`. Null when the request carries neither, so
5
+ * callers can omit the value instead of forwarding a fabricated one.
6
+ */
7
+ const clientIpFromHeaders = (headers) => {
8
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim();
9
+ if (forwarded) return forwarded;
10
+ return headers.get("x-real-ip")?.trim() || null;
11
+ };
12
+ //#endregion
13
+ export { clientIpFromHeaders };
14
+
15
+ //# sourceMappingURL=clientIp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clientIp.js","names":[],"sources":["../../../src/native/ingest/clientIp.ts"],"sourcesContent":["/**\n * The originating client IP a proxy chain reported: the first hop of\n * `x-forwarded-for`, else `x-real-ip`. Null when the request carries neither, so\n * callers can omit the value instead of forwarding a fabricated one.\n */\nexport const clientIpFromHeaders = (headers: Headers): string | null => {\n\tconst forwarded = headers.get('x-forwarded-for')?.split(',')[0]?.trim()\n\tif (forwarded) {\n\t\treturn forwarded\n\t}\n\treturn headers.get('x-real-ip')?.trim() || null\n}\n"],"mappings":";;;;;;AAKA,MAAa,uBAAuB,YAAoC;CACvE,MAAM,YAAY,QAAQ,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,IAAI,KAAK;CACtE,IAAI,WACH,OAAO;CAER,OAAO,QAAQ,IAAI,WAAW,GAAG,KAAK,KAAK;AAC5C"}