@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.14

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 (194) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/adapters/ga4/ga4.d.ts +6 -0
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +2 -1
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +6 -0
  9. package/dist/adapters/posthog/posthog.js +21 -8
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/umami/umami.d.ts +6 -0
  12. package/dist/adapters/umami/umami.js +2 -1
  13. package/dist/adapters/umami/umami.js.map +1 -1
  14. package/dist/capture/exclusionEndpoint.js +1 -1
  15. package/dist/capture/exclusionEndpoint.js.map +1 -1
  16. package/dist/capture/slots.js +3 -3
  17. package/dist/capture/slots.js.map +1 -1
  18. package/dist/capture/trackerConfig.js +11 -3
  19. package/dist/capture/trackerConfig.js.map +1 -1
  20. package/dist/charts/series.js +1 -1
  21. package/dist/core/adminOptions.js +6 -1
  22. package/dist/core/adminOptions.js.map +1 -1
  23. package/dist/core/capture.d.ts +3 -1
  24. package/dist/core/contract.d.ts +13 -1
  25. package/dist/core/contract.js.map +1 -1
  26. package/dist/core/options.d.ts +37 -5
  27. package/dist/core/options.js +6 -2
  28. package/dist/core/options.js.map +1 -1
  29. package/dist/core/registry.js.map +1 -1
  30. package/dist/core/scopeOptions.js +2 -0
  31. package/dist/core/scopeOptions.js.map +1 -1
  32. package/dist/core/scopedRead.js +170 -21
  33. package/dist/core/scopedRead.js.map +1 -1
  34. package/dist/core/sourceLabel.d.ts +10 -0
  35. package/dist/core/sourceLabel.js +63 -0
  36. package/dist/core/sourceLabel.js.map +1 -0
  37. package/dist/core/sourceOptions.js +18 -6
  38. package/dist/core/sourceOptions.js.map +1 -1
  39. package/dist/core/sourcePolicy.d.ts +55 -0
  40. package/dist/core/sourcePolicy.js +51 -0
  41. package/dist/core/sourcePolicy.js.map +1 -0
  42. package/dist/exports/adapters/contract.d.ts +2 -1
  43. package/dist/exports/adapters/ga4.d.ts +3 -2
  44. package/dist/exports/adapters/native.d.ts +3 -2
  45. package/dist/exports/adapters/plausible.d.ts +3 -2
  46. package/dist/exports/adapters/posthog.d.ts +3 -2
  47. package/dist/exports/adapters/umami.d.ts +3 -2
  48. package/dist/exports/client.d.ts +7 -5
  49. package/dist/exports/client.js +2 -1
  50. package/dist/exports/next.d.ts +3 -2
  51. package/dist/exports/rsc.d.ts +7 -6
  52. package/dist/exports/testing.d.ts +3 -2
  53. package/dist/exports/types.d.ts +12 -8
  54. package/dist/fields/AnalyticsPanelClient.js.map +1 -1
  55. package/dist/fields/AnalyticsPanelField.d.ts +1 -1
  56. package/dist/fields/AnalyticsPanelField.js +3 -1
  57. package/dist/fields/AnalyticsPanelField.js.map +1 -1
  58. package/dist/fields/AnalyticsStatField.d.ts +1 -1
  59. package/dist/fields/AnalyticsStatField.js +1 -1
  60. package/dist/fields/PanelContent.js +6 -1
  61. package/dist/fields/PanelContent.js.map +1 -1
  62. package/dist/fields/config/fetchSources.d.ts +3 -0
  63. package/dist/fields/config/fetchSources.js +5 -3
  64. package/dist/fields/config/fetchSources.js.map +1 -1
  65. package/dist/fields/readForDocument.d.ts +5 -4
  66. package/dist/fields/readForDocument.js +6 -2
  67. package/dist/fields/readForDocument.js.map +1 -1
  68. package/dist/goals/collection.js +4 -31
  69. package/dist/goals/collection.js.map +1 -1
  70. package/dist/goals/resolver.js +2 -2
  71. package/dist/goals/trackGoalAction.js +1 -1
  72. package/dist/index.d.ts +14 -11
  73. package/dist/index.js +6 -5
  74. package/dist/index.js.map +1 -1
  75. package/dist/native/geo/maxmindResolver.js +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +1 -1
  77. package/dist/native/nativeAdapter.d.ts +6 -0
  78. package/dist/native/nativeAdapter.js +3 -2
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/plugin/createRuntime.js +6 -3
  81. package/dist/plugin/createRuntime.js.map +1 -1
  82. package/dist/plugin/documentEndpoint.js +1 -0
  83. package/dist/plugin/documentEndpoint.js.map +1 -1
  84. package/dist/plugin/pluginCollections.js +11 -5
  85. package/dist/plugin/pluginCollections.js.map +1 -1
  86. package/dist/plugin/queryEndpoint.js +1 -1
  87. package/dist/plugin/queryEndpoint.js.map +1 -1
  88. package/dist/plugin/readContextForRequest.d.ts +11 -0
  89. package/dist/plugin/readContextForRequest.js +25 -15
  90. package/dist/plugin/readContextForRequest.js.map +1 -1
  91. package/dist/plugin/runtime.js +13 -5
  92. package/dist/plugin/runtime.js.map +1 -1
  93. package/dist/plugin/sourcesEndpoint.js +8 -9
  94. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  95. package/dist/providers/ProvidersListNotice.d.ts +11 -0
  96. package/dist/providers/ProvidersListNotice.js +36 -0
  97. package/dist/providers/ProvidersListNotice.js.map +1 -0
  98. package/dist/providers/collection.d.ts +9 -1
  99. package/dist/providers/collection.js +111 -42
  100. package/dist/providers/collection.js.map +1 -1
  101. package/dist/providers/factory.d.ts +1 -1
  102. package/dist/providers/factory.js +8 -11
  103. package/dist/providers/factory.js.map +1 -1
  104. package/dist/providers/probe.js +5 -1
  105. package/dist/providers/probe.js.map +1 -1
  106. package/dist/providers/registry.js +49 -39
  107. package/dist/providers/registry.js.map +1 -1
  108. package/dist/providers/resolver.js +6 -3
  109. package/dist/providers/resolver.js.map +1 -1
  110. package/dist/providers/scopeUnique.js +41 -0
  111. package/dist/providers/scopeUnique.js.map +1 -0
  112. package/dist/query/fetchQuery.d.ts +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/tracker/config.d.ts +5 -0
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/sinks/createSink.js +4 -1
  117. package/dist/tracker/sinks/createSink.js.map +1 -1
  118. package/dist/tracker/sinks/ga4.js +2 -2
  119. package/dist/tracker/sinks/posthog.js +30 -2
  120. package/dist/tracker/sinks/posthog.js.map +1 -1
  121. package/dist/tracker/sinks/vendor.js +2 -2
  122. package/dist/tracker/sinks/vendor.js.map +1 -1
  123. package/dist/translations/ar.js +6 -0
  124. package/dist/translations/ar.js.map +1 -1
  125. package/dist/translations/de.js +6 -0
  126. package/dist/translations/de.js.map +1 -1
  127. package/dist/translations/en.js +6 -0
  128. package/dist/translations/en.js.map +1 -1
  129. package/dist/translations/es.js +6 -0
  130. package/dist/translations/es.js.map +1 -1
  131. package/dist/translations/fr.js +6 -0
  132. package/dist/translations/fr.js.map +1 -1
  133. package/dist/translations/id.js +6 -0
  134. package/dist/translations/id.js.map +1 -1
  135. package/dist/translations/keys.d.ts +6 -0
  136. package/dist/translations/keys.js +7 -1
  137. package/dist/translations/keys.js.map +1 -1
  138. package/dist/translations/ko.js +6 -0
  139. package/dist/translations/ko.js.map +1 -1
  140. package/dist/translations/pt.js +6 -0
  141. package/dist/translations/pt.js.map +1 -1
  142. package/dist/translations/ru.js +6 -0
  143. package/dist/translations/ru.js.map +1 -1
  144. package/dist/translations/uk.js +6 -0
  145. package/dist/translations/uk.js.map +1 -1
  146. package/dist/translations/zh.js +6 -0
  147. package/dist/translations/zh.js.map +1 -1
  148. package/dist/ui/analytics.css +5 -0
  149. package/dist/ui/components/SourcesNoticeBanner.js +20 -0
  150. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
  151. package/dist/view/ViewRoot.js +2 -0
  152. package/dist/view/ViewRoot.js.map +1 -1
  153. package/dist/view/registerView.js +5 -4
  154. package/dist/view/registerView.js.map +1 -1
  155. package/dist/view/viewContext.d.ts +1 -1
  156. package/dist/view/viewProps.d.ts +1 -1
  157. package/dist/view/viewProps.js +3 -2
  158. package/dist/view/viewProps.js.map +1 -1
  159. package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
  160. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  161. package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
  162. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  163. package/dist/widgets/AnalyticsMetricWidget.js +1 -0
  164. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  165. package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
  166. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  167. package/dist/widgets/AnalyticsTrendWidget.js +1 -0
  168. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  169. package/dist/widgets/defaultLayout.d.ts +26 -0
  170. package/dist/widgets/defaultLayout.js +51 -0
  171. package/dist/widgets/defaultLayout.js.map +1 -0
  172. package/dist/widgets/notices.js +1 -0
  173. package/dist/widgets/notices.js.map +1 -1
  174. package/dist/widgets/prepareWidgetRead.d.ts +14 -1
  175. package/dist/widgets/prepareWidgetRead.js +6 -2
  176. package/dist/widgets/prepareWidgetRead.js.map +1 -1
  177. package/dist/widgets/readForWidget.d.ts +4 -4
  178. package/dist/widgets/readForWidget.js +3 -1
  179. package/dist/widgets/readForWidget.js.map +1 -1
  180. package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
  181. package/dist/widgets/readForWidgetBreakdown.js +3 -1
  182. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  183. package/dist/widgets/readForWidgetGoals.d.ts +4 -4
  184. package/dist/widgets/readForWidgetGoals.js +3 -1
  185. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  186. package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
  187. package/dist/widgets/readForWidgetRealtime.js +3 -1
  188. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  189. package/dist/widgets/readForWidgetSeries.d.ts +4 -4
  190. package/dist/widgets/readForWidgetSeries.js +3 -1
  191. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  192. package/dist/widgets/registerWidgets.js +3 -1
  193. package/dist/widgets/registerWidgets.js.map +1 -1
  194. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"readForDocument.js","names":[],"sources":["../../src/fields/readForDocument.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf, SYSTEM } from '../access/principal'\nimport { bindsItems, type ReportMode } from '../binding/report'\nimport { resolveHostname, resolvePathCached } from '../binding/resolvePath'\nimport type { BindingContext, BindingDoc, ResolvedBinding } from '../binding/types'\nimport {\n\tfillSeries,\n\ttype SeriesGranularity,\n\ttype SeriesPoint,\n\tseriesGranularityFor,\n} from '../charts/series'\nimport { metricReaches, satisfiesCapabilities, supportsFilter } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { readAsAsked, servedName } from '../core/metricAliases'\nimport { type ReadContext, resolveReadContext } from '../core/scopedRead'\nimport { ITEM_CLICK_EVENT } from '../goals/constants'\nimport { itemRefOf } from '../items/ref'\nimport { resolveDocumentScope } from '../plugin/documentScopes'\nimport { goalSlugsFor } from '../plugin/goalHint'\nimport { type AnalyticsRuntime, getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { exceedsRangeCap } from '../query/limits'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport { PEEK_BUDGET_MS, type ReadOptions } from '../surfacing/engine'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { comparisonWindow } from '../widgets/prepareWidgetRead'\nimport { mergeNotices, type ReadNotices, readMeta } from '../widgets/readMeta'\nimport { scopeFromDocument } from './documentScope'\nimport { ITEM_READ_METRICS } from './itemReport'\n\n/**\n * `no-access` is about the reader, never a page without traffic; `unavailable` a source that\n * cannot read the document at all; `busy` a failure for now, which a retry can fix.\n */\nexport type FieldReadStatus =\n\t| 'ok'\n\t| 'no-path'\n\t| 'not-bound'\n\t| 'not-configured'\n\t| 'no-access'\n\t| 'no-scope'\n\t| 'unavailable'\n\t| 'busy'\n\t| 'invalid'\n\t| 'range-too-long'\n\t| 'misconfigured'\n\t| 'host-refused'\n\n/** One ranked value of a dimension, for this document's page only. */\nexport interface FieldBreakdownRow {\n\tvalue: string\n\tmetric: number\n}\n\n/**\n * A dimension ranked for this page. The read is a `page eq <path>` filter rather than the\n * per-page report, because that is the only shape a source can group another dimension by.\n */\nexport interface FieldBreakdown extends Partial<ReadNotices> {\n\tdimension: DimensionKey\n\t/** The metric the rows are ranked by; `visitors` wherever the source serves it. */\n\tmetric: MetricKey\n\trows: FieldBreakdownRow[]\n\t/** The source that answered, for the value labels that read differently per provider. */\n\tprovider?: string\n}\n\nexport interface FieldReadResult {\n\tstatus: FieldReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\t/** The headline numbers answered but a comparison, series or list did not: try again for it. */\n\tincomplete?: true\n\t/** `item` when the read was about the document as a content item, absent for its page. */\n\treport?: 'item'\n\tadapterId: string\n\tdateRange: DateRange\n\t/** The reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\t/** An average with nothing to average over reads `null`; render it as no data, not zero. */\n\tmetrics: MetricValues\n\t/** Requested metrics the adapter supports, in request order; the set actually read. */\n\tsupportedMetrics: MetricKey[]\n\t/** Requested metrics the adapter cannot serve, dropped from the read. */\n\tdroppedMetrics: MetricKey[]\n\t/** Previous-window totals, present only when comparison was requested and supported. */\n\tpreviousMetrics?: MetricValues\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/** Series for the first supported metric, present only when requested. */\n\tpoints?: SeriesPoint[]\n\t/**\n\t * The bucket `points` carry. A window of a day or two is charted by hour, so `day` there\n\t * says the source serves no hourly rows and the panel has a single value, not a line.\n\t */\n\tseriesGranularity?: SeriesGranularity\n\t/** The source counts live visitors, so the panel may poll for this page's own count. */\n\trealtime?: boolean\n\t/** One entry per requested dimension the source can rank for a single page. */\n\tbreakdowns?: FieldBreakdown[]\n\t/** What the totals' and the series' reads say about their numbers. */\n\tnotices?: ReadNotices\n\t/**\n\t * Reader may not read into the document's scope (or is no member of the request's), so the\n\t * read never ran. Rendered as `no-access`; the endpoint answers `untrusted_scope`.\n\t */\n\tuntrustedScope?: boolean\n}\n\n/**\n * Without `scope` the read takes the document's scope (binding `scopeField`) else the request's,\n * gated as endpoints gate it; a given `scope` is already cleared, or a job's under `SYSTEM`.\n */\nexport type ReadForFieldArgs = ReadPrincipal & {\n\treq: PayloadRequest\n\tcollectionSlug: string\n\tdata: BindingDoc\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\t/** Overrides the preset window (custom range). */\n\trange?: DateRange\n\tadapterId?: string\n\tnow: Date\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\t/** Also read the previous comparable window when the adapter supports comparison. */\n\tcompare?: boolean\n\t/** Also read a series for the first supported metric, bucketed to suit the window. */\n\tseries?: boolean\n\t/**\n\t * Metrics the caller added speculatively rather than asked for, so a source that serves none\n\t * of them is not worth a warning on every render.\n\t */\n\toptionalMetrics?: MetricKey[]\n\t/** Rank these dimensions for the document's own page; each one the source cannot is skipped. */\n\tdimensions?: DimensionKey[]\n\t/** Rows per breakdown. Default 5. */\n\tlimit?: number\n\t/**\n\t * `item` reads the document as content shown on other pages: its views, clicks and outcomes,\n\t * wherever it appeared. Absent, or `page`, reads the document's own page.\n\t */\n\treport?: ReportMode\n}\n\n/** Rows per breakdown block: a card-sized list, not a table. */\nconst DEFAULT_BREAKDOWN_LIMIT = 5\n\n/** The ranked lists a panel read, and whether any it could rank failed to answer. */\ninterface RankedLists {\n\tblocks: FieldBreakdown[]\n\tfailed: boolean\n}\n\nconst NO_LISTS: RankedLists = { blocks: [], failed: false }\n\n/** The numbers of a read that never ran, fresh per result so no two results share an array. */\nconst noMetrics = (): Pick<FieldReadResult, 'metrics' | 'supportedMetrics' | 'droppedMetrics'> => ({\n\tmetrics: {},\n\tsupportedMetrics: [],\n\tdroppedMetrics: [],\n})\n\n/** A read that settles either way: its answer, or `undefined` and `failed` for one that threw. */\nconst settled = <T>(work: Promise<T>): Promise<{ value?: T; failed: boolean }> =>\n\twork.then(\n\t\t(value) => ({ value, failed: false }),\n\t\t() => ({ failed: true })\n\t)\n\n/** How a field read asks for one of the answers behind it. */\nexport type FieldReader = (\n\tadapter: AnalyticsAdapter,\n\tquery: AnalyticsQuery,\n\toptions: ReadOptions\n) => Promise<AnalyticsResult>\n\n/**\n * `read` asking the source in its own names and answering under the read's: `visits` from a source\n * that serves the count as `sessions`.\n */\nconst asAsked =\n\t(read: FieldReader): FieldReader =>\n\t(adapter, query, options) =>\n\t\treadAsAsked((served) => read(adapter, served, options), query, adapter.capabilities.metrics)\n\n/** The reader a field read uses on one runtime. */\nexport type FieldReads = (runtime: AnalyticsRuntime) => FieldReader\n\n/** Engine's own read with `options` laid over each read's own: a cached answer or the source's. */\nexport const engineReads =\n\t(options: ReadOptions = {}): FieldReads =>\n\t(runtime) =>\n\t(adapter, query, base) =>\n\t\truntime.engine.read(adapter, query, { ...base, ...options })\n\n/** A peek found nothing kept for one of the reads, so the field read has no answer to seed with. */\nclass PeekMissError extends Error {\n\tconstructor() {\n\t\tsuper('analytics: nothing kept for this read yet')\n\t\tthis.name = 'PeekMissError'\n\t}\n}\n\n/** What {@link peekForField} found. */\nexport interface FieldPeek {\n\tresult: FieldReadResult\n\t/** False when a read behind it found nothing kept: the result is incomplete or failed for it. */\n\tcomplete: boolean\n\t/** True when an answer behind it was kept past its freshness and is served stale. */\n\tstale: boolean\n}\n\n/**\n * Field read answered only from what the engine keeps (memory and cache store, within `budgetMs`),\n * never a source; a status decided before any read is as final as {@link readForField}'s.\n */\nexport const peekForField = async (\n\targs: ReadForFieldArgs,\n\tbudgetMs: number = PEEK_BUDGET_MS\n): Promise<FieldPeek> => {\n\tlet complete = true\n\tlet stale = false\n\tconst { incomplete: _unkept, ...result } = await readFieldWith(\n\t\targs,\n\t\t(runtime) => async (adapter, query) => {\n\t\t\tconst kept = await runtime.engine.peek?.(adapter, query, { budgetMs })\n\t\t\tif (!kept) {\n\t\t\t\tcomplete = false\n\t\t\t\tthrow new PeekMissError()\n\t\t\t}\n\t\t\tif (kept.meta.stale === true) {\n\t\t\t\tstale = true\n\t\t\t}\n\t\t\treturn kept\n\t\t}\n\t)\n\t// What a peek left unread is `complete: false`, read again by the panel, not a failure.\n\treturn { result, complete, stale }\n}\n\n/**\n * Reads a document's analytics for one display field, never throwing: a status picks the empty\n * state. An unsupported metric is dropped with a warning; `unavailable` only when none survives.\n */\nexport const readForField = (args: ReadForFieldArgs): Promise<FieldReadResult> =>\n\treadFieldWith(args, engineReads())\n\n/**\n * A document scope with nothing this reader may read, a denied `access.read` or a tenant they do\n * not belong to is the reader's own reach, not an unavailable source.\n */\nconst refusedStatus = (\n\treason: Extract<ReadContext, { ok: false }>['reason'],\n\tdocumentScoped: boolean\n): FieldReadStatus => {\n\tif (\n\t\treason === 'no-access' ||\n\t\treason === 'not-member' ||\n\t\t(documentScoped && reason === 'no-sources')\n\t) {\n\t\treturn 'no-access'\n\t}\n\treturn reason === 'no-scope' ? 'no-scope' : 'unavailable'\n}\n\n/**\n * {@link readForField} with the reads behind it answered another way: the engine's own read with\n * other options, or {@link peekForField}'s look at what the engine has kept.\n */\nexport const readFieldWith = async (\n\targs: ReadForFieldArgs,\n\tvia: FieldReads\n): Promise<FieldReadResult> => {\n\tconst { req, collectionSlug, data, timeframe, range, adapterId, now } = args\n\tconst unreadRange = range ?? resolveTimeframe(timeframe, now)\n\tconst unread = (\n\t\tstatus: FieldReadStatus,\n\t\textra: Pick<FieldReadResult, 'untrustedScope'> = {}\n\t): FieldReadResult => ({\n\t\tstatus,\n\t\t...extra,\n\t\tadapterId: adapterId ?? '',\n\t\tdateRange: unreadRange,\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t...noMetrics(),\n\t})\n\tif (range && exceedsRangeCap(range)) {\n\t\treturn unread('range-too-long')\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn unread('not-bound')\n\t}\n\tconst read = asAsked(via(runtime))\n\tconst binding = runtime.bindings[collectionSlug]\n\tif (!binding) {\n\t\treturn unread('not-bound')\n\t}\n\tconst documentScope = scopeFromDocument(data, binding.scopeField)\n\tlet principal: ReadPrincipal = readPrincipalOf(args)\n\t// A pinned scope was already decided (a job's own, or one the caller cleared); anything\n\t// resolved from the document is a scope this reader is naming, gate and all.\n\tif (args.principal !== SYSTEM && args.scope === undefined) {\n\t\tconst resolved = await resolveDocumentScope({ runtime, req, collection: collectionSlug, data })\n\t\tif (!resolved.ok) {\n\t\t\treturn unread('no-access', { untrustedScope: true })\n\t\t}\n\t\tprincipal = resolved.scope === null ? {} : { scope: resolved.gated }\n\t}\n\tconst ctx = await resolveReadContext({\n\t\truntime,\n\t\treq,\n\t\tadapterId,\n\t\t...principal,\n\t\t// An item read goes through a source that can answer one, wherever the scope has one.\n\t\t...(args.report === 'item'\n\t\t\t? { prefer: (candidate: AnalyticsAdapter) => candidate.capabilities.perItemQuery === true }\n\t\t\t: {}),\n\t})\n\tif (!ctx.ok) {\n\t\treturn unread(\n\t\t\trefusedStatus(ctx.reason, documentScope !== null),\n\t\t\tctx.reason === 'not-member' ? { untrustedScope: true } : {}\n\t\t)\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst resolved: ResolvedRead = {\n\t\targs,\n\t\truntime,\n\t\tread,\n\t\tbinding,\n\t\tadapter: ctx.adapter,\n\t\tscope: ctx.scope,\n\t\tqueryScope: ctx.queryScope,\n\t\ttz,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now, tz),\n\t\tbindingCtx: { req, locale: req.locale ?? undefined },\n\t}\n\treturn args.report === 'item' ? readItem(resolved) : readPage(resolved)\n}\n\n/** A field read past every gate: its source chosen, its scope and window resolved. */\ninterface ResolvedRead {\n\targs: ReadForFieldArgs\n\truntime: AnalyticsRuntime\n\tread: FieldReader\n\tbinding: ResolvedBinding\n\tadapter: AnalyticsAdapter\n\tscope: string | null\n\tqueryScope: string | undefined\n\ttz: string\n\tdateRange: DateRange\n\tbindingCtx: BindingContext\n}\n\n/**\n * Splits the asked metrics by what the source serves; the dropped ones the caller did not add\n * speculatively are worth a warning.\n */\nconst splitMetrics = (args: ReadForFieldArgs, serves: (metric: MetricKey) => boolean) => {\n\tconst supportedMetrics = args.metrics.filter(serves)\n\tconst droppedMetrics = args.metrics.filter((metric) => !serves(metric))\n\tconst optional = new Set(args.optionalMetrics ?? [])\n\tconst unasked = droppedMetrics.filter((metric) => !optional.has(metric))\n\treturn { supportedMetrics, droppedMetrics, unasked }\n}\n\n/** What every query of one read narrows by besides its page or item: host, zone, scope, goals. */\nconst sharedQuery = async (input: ResolvedRead, metrics: MetricKey[]) => {\n\tconst hostname = await resolveHostname(input.binding, input.args.data, input.bindingCtx)\n\tconst goalSlugs = await goalSlugsFor({\n\t\truntime: input.runtime,\n\t\treq: input.args.req,\n\t\tscope: input.scope,\n\t\tmetrics,\n\t})\n\treturn {\n\t\thostname,\n\t\ttimezone: input.tz,\n\t\tscope: input.queryScope,\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n}\n\n/** What a ranked list narrows to besides its own filter. */\ninterface ListScope {\n\ttimezone: string\n\thostname?: string | undefined\n\tscope?: string | undefined\n}\n\n/** How each list of a read is read: the same source, window and narrowing for all of them. */\ninterface ListReads {\n\tread: FieldReader\n\tadapter: AnalyticsAdapter\n\twithin: ListScope\n\tdateRange: DateRange\n\tdimensions: DimensionKey[]\n\tlimit: number\n\toptions: ReadOptions\n}\n\n/** One dimension ranked by `metric` within `narrowing`; null when the read throws. */\nconst readRankedList = async (\n\tinput: Omit<ListReads, 'dimensions'> & {\n\t\tdimension: DimensionKey\n\t\tmetric: MetricKey\n\t\tnarrowing: Pick<AnalyticsQuery, 'filters' | 'item'>\n\t}\n): Promise<FieldBreakdown | null> => {\n\tconst { dimension, metric, within, limit } = input\n\ttry {\n\t\tconst result = await input.read(\n\t\t\tinput.adapter,\n\t\t\t{\n\t\t\t\tmetrics: [metric],\n\t\t\t\tdimensions: [dimension],\n\t\t\t\tdateRange: input.dateRange,\n\t\t\t\tlimit,\n\t\t\t\torder: { metric, direction: 'desc' },\n\t\t\t\t...input.narrowing,\n\t\t\t\ttimezone: within.timezone,\n\t\t\t\t...(within.hostname === undefined ? {} : { hostname: within.hostname }),\n\t\t\t\t...(within.scope === undefined ? {} : { scope: within.scope }),\n\t\t\t},\n\t\t\tinput.options\n\t\t)\n\t\tconst rows = result.rows\n\t\t\t.map((row) => ({\n\t\t\t\tvalue: row.dimensions?.[dimension] ?? '',\n\t\t\t\tmetric: row.metrics[metric] ?? 0,\n\t\t\t}))\n\t\t\t.slice(0, limit)\n\t\treturn { dimension, metric, rows, ...readMeta(result) }\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Settles every list read: one that answered null is dropped alone and marks the set failed. */\nconst rankedLists = async (reads: Array<Promise<FieldBreakdown | null>>): Promise<RankedLists> => {\n\tconst answered = await Promise.all(reads)\n\tconst blocks = answered.filter((block): block is FieldBreakdown => block !== null)\n\treturn { blocks, failed: blocks.length < answered.length }\n}\n\n/** Ranked by people rather than hits wherever the source counts them. */\nconst breakdownMetric = (adapter: AnalyticsAdapter): MetricKey =>\n\tadapter.capabilities.metrics.has('visitors') ? 'visitors' : 'pageviews'\n\n/**\n * Ranks each dimension for one page via a `page eq` filter; a source that cannot filter or group\n * so gives no block rather than a site-wide list, and a block that throws is dropped alone.\n */\nconst readBreakdowns = async (lists: ListReads & { path: string }): Promise<RankedLists> => {\n\tconst caps = lists.adapter.capabilities\n\tif (\n\t\tlists.dimensions.length === 0 ||\n\t\t!supportsFilter(caps, { dimension: 'page', operator: 'eq' })\n\t) {\n\t\treturn NO_LISTS\n\t}\n\tconst metric = breakdownMetric(lists.adapter)\n\tconst wanted = lists.dimensions.filter(\n\t\t(dimension) =>\n\t\t\tcaps.dimensions.has(dimension) &&\n\t\t\tmetricReaches(caps, metric, { dimensions: [dimension], filters: ['page'] })\n\t)\n\treturn rankedLists(\n\t\twanted.map((dimension) =>\n\t\t\treadRankedList({\n\t\t\t\t...lists,\n\t\t\t\tdimension,\n\t\t\t\tmetric,\n\t\t\t\t// `path` is deliberately not set: it selects the per-page report, which no source\n\t\t\t\t// groups a second dimension by. The filter is the same narrowing said another way.\n\t\t\t\tnarrowing: { filters: [{ dimension: 'page', operator: 'eq', value: lists.path }] },\n\t\t\t})\n\t\t)\n\t)\n}\n\n/**\n * An `item eq` filter matches the item's views too, so clickers are its visitors with an\n * `item_click` event; a source unable to filter that ranks clicks instead. Null if neither.\n */\nconst clickList = (\n\tcaps: AnalyticsAdapter['capabilities'],\n\titem: string\n): { metric: MetricKey; filters: AnalyticsFilter[] } | null => {\n\tconst byItem: AnalyticsFilter = { dimension: 'item', operator: 'eq', value: item }\n\tif (!supportsFilter(caps, byItem)) {\n\t\treturn null\n\t}\n\tif (\n\t\tcaps.metrics.has('visitors') &&\n\t\tsupportsFilter(caps, { dimension: 'event', operator: 'eq' })\n\t) {\n\t\treturn {\n\t\t\tmetric: 'visitors',\n\t\t\tfilters: [byItem, { dimension: 'event', operator: 'eq', value: ITEM_CLICK_EVENT }],\n\t\t}\n\t}\n\treturn caps.metrics.has('interactions') ? { metric: 'interactions', filters: [byItem] } : null\n}\n\n/**\n * Ranks pages the item was seen on and where its clickers are (see {@link clickList}); a list the\n * source cannot rank is left out, and one that fails is dropped alone.\n */\nconst readItemBreakdowns = async (lists: ListReads & { item: string }): Promise<RankedLists> => {\n\tconst caps = lists.adapter.capabilities\n\tconst reads: Array<Promise<FieldBreakdown | null>> = []\n\tfor (const dimension of lists.dimensions) {\n\t\tconst pages = dimension === 'page'\n\t\tconst clicks = pages ? null : clickList(caps, lists.item)\n\t\tif (!caps.dimensions.has(dimension) || (!pages && clicks === null)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst metric: MetricKey = clicks?.metric ?? 'impressions'\n\t\tif (!metricReaches(caps, metric, { dimensions: [dimension], filters: clicks?.filters ?? [] })) {\n\t\t\tcontinue\n\t\t}\n\t\treads.push(\n\t\t\treadRankedList({\n\t\t\t\t...lists,\n\t\t\t\tdimension,\n\t\t\t\tmetric,\n\t\t\t\tnarrowing: clicks === null ? { item: lists.item } : { filters: clicks.filters },\n\t\t\t})\n\t\t)\n\t}\n\treturn rankedLists(reads)\n}\n\n/** One read's queries, decided: what to read and through what, before any of it is asked. */\ninterface Answering {\n\tresolved: ResolvedRead\n\t/** Every query's narrowing to the document: its page or item, host, zone, scope and goals. */\n\tbase: Omit<AnalyticsQuery, 'metrics' | 'dateRange'>\n\tsupportedMetrics: MetricKey[]\n\tdroppedMetrics: MetricKey[]\n\t/** The trend's metric and bucket; absent when no series is read. */\n\tseries: { metric: MetricKey; granularity: SeriesGranularity } | undefined\n\trank: () => Promise<RankedLists>\n\treport?: 'item'\n\trealtime?: boolean\n}\n\n/**\n * Reads the headline, then its comparison, series and lists beside it. Only the headline can fail\n * the read; any other that fails leaves the answer `incomplete`.\n */\nconst readAnswers = async (answering: Answering): Promise<FieldReadResult> => {\n\tconst { resolved, base, supportedMetrics, droppedMetrics, series } = answering\n\tconst { read, adapter, dateRange, tz } = resolved\n\tconst comparisonRange = resolved.args.compare\n\t\t? comparisonWindow(resolved, resolved.args.now)\n\t\t: undefined\n\tconst options: ReadOptions = { timeframe: resolved.args.timeframe }\n\tconst reportTag = answering.report === undefined ? {} : { report: answering.report }\n\t// The headline takes the source's first slot and alone can fail the read; the lists wait for it.\n\tconst main = read(adapter, { ...base, metrics: supportedMetrics, dateRange }, options)\n\tconst comparing = comparisonRange\n\t\t? settled(\n\t\t\t\tread(adapter, { ...base, metrics: supportedMetrics, dateRange: comparisonRange }, options)\n\t\t\t)\n\t\t: undefined\n\tconst charting = series\n\t\t? settled(\n\t\t\t\tread(\n\t\t\t\t\tadapter,\n\t\t\t\t\t{ ...base, metrics: [series.metric], dateRange, granularity: series.granularity },\n\t\t\t\t\toptions\n\t\t\t\t)\n\t\t\t)\n\t\t: undefined\n\tconst ranking = main.then(\n\t\t() => answering.rank(),\n\t\t() => NO_LISTS\n\t)\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await main\n\t} catch (err) {\n\t\t// Nothing cached survived the failed read: a status, never a throw through the edit view.\n\t\treturn {\n\t\t\t...readFailureOf(err),\n\t\t\t...reportTag,\n\t\t\tadapterId: adapter.id,\n\t\t\tdateRange,\n\t\t\ttimezone: tz,\n\t\t\tmetrics: {},\n\t\t\tsupportedMetrics,\n\t\t\tdroppedMetrics,\n\t\t}\n\t}\n\tconst [compared, charted, lists] = await Promise.all([comparing, charting, ranking])\n\tconst previous = compared?.value\n\tconst seriesResult = charted?.value\n\tconst ranked = lists.blocks\n\tconst incomplete = compared?.failed === true || charted?.failed === true || lists.failed\n\treturn {\n\t\tstatus: 'ok',\n\t\t...(incomplete ? { incomplete: true as const } : {}),\n\t\t...reportTag,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...(answering.realtime === undefined ? {} : { realtime: answering.realtime }),\n\t\t...(ranked.length > 0 ? { breakdowns: ranked } : {}),\n\t\tnotices: mergeNotices(readMeta(result), seriesResult ? readMeta(seriesResult) : undefined),\n\t\tmetrics: result.totals ?? {},\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tpreviousMetrics: previous ? (previous.totals ?? {}) : undefined,\n\t\tcomparisonRange: previous ? comparisonRange : undefined,\n\t\tpoints:\n\t\t\tseriesResult && series\n\t\t\t\t? fillSeries({\n\t\t\t\t\t\trows: seriesResult.rows,\n\t\t\t\t\t\tdateRange,\n\t\t\t\t\t\tmetric: series.metric,\n\t\t\t\t\t\ttz,\n\t\t\t\t\t\tgranularity: series.granularity,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\tseriesGranularity: seriesResult ? series?.granularity : undefined,\n\t}\n}\n\n/** Document read as its own page, at the path its binding resolves. */\nconst readPage = async (resolved: ResolvedRead): Promise<FieldReadResult> => {\n\tconst { args, binding, adapter, tz, dateRange } = resolved\n\tconst unread = (status: FieldReadStatus): FieldReadResult => ({\n\t\tstatus,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...noMetrics(),\n\t})\n\tlet path: string | null\n\ttry {\n\t\tpath = await resolvePathCached(binding, args.data, resolved.bindingCtx)\n\t} catch {\n\t\tpath = null\n\t}\n\tif (!path) {\n\t\treturn unread('no-path')\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn unread('not-configured')\n\t}\n\tconst caps = adapter.capabilities\n\tconst servesForPage = (metric: MetricKey): boolean => {\n\t\tconst name = servedName(metric, caps.metrics)\n\t\treturn caps.metrics.has(name) && metricReaches(caps, name, { path: true })\n\t}\n\tconst { supportedMetrics, droppedMetrics, unasked } = splitMetrics(args, servesForPage)\n\tif (unasked.length > 0) {\n\t\targs.req.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" does not support metric(s) ${unasked.join(', ')}; dropped from the \"${args.collectionSlug}\" display field`\n\t\t)\n\t}\n\tconst leadMetric = supportedMetrics[0]\n\tif (\n\t\tleadMetric === undefined ||\n\t\t!satisfiesCapabilities(caps, {\n\t\t\tmetrics: supportedMetrics.map((metric) => servedName(metric, caps.metrics)),\n\t\t\tpath: true,\n\t\t})\n\t) {\n\t\treturn { ...unread('unavailable'), droppedMetrics: args.metrics }\n\t}\n\tconst shared = await sharedQuery(resolved, supportedMetrics)\n\treturn readAnswers({\n\t\tresolved,\n\t\tbase: { path, ...shared },\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tseries:\n\t\t\targs.series && supportsGranularity(caps, 'day')\n\t\t\t\t? { metric: leadMetric, granularity: seriesGranularityFor(dateRange, caps) }\n\t\t\t\t: undefined,\n\t\trank: () =>\n\t\t\treadBreakdowns({\n\t\t\t\tread: resolved.read,\n\t\t\t\tadapter,\n\t\t\t\tpath,\n\t\t\t\twithin: shared,\n\t\t\t\tdateRange,\n\t\t\t\tdimensions: args.dimensions ?? [],\n\t\t\t\tlimit: args.limit ?? DEFAULT_BREAKDOWN_LIMIT,\n\t\t\t\toptions: { timeframe: args.timeframe },\n\t\t\t}),\n\t\trealtime: caps.realtime && typeof adapter.realtime === 'function',\n\t})\n}\n\n/**\n * Document read as a content item under its ref `<collection>:<id>`. Metrics an item's buckets\n * never count are dropped like unserved ones; nothing about an item is counted live.\n */\nconst readItem = async (resolved: ResolvedRead): Promise<FieldReadResult> => {\n\tconst { args, binding, adapter, tz, dateRange } = resolved\n\tconst unread = (status: FieldReadStatus): FieldReadResult => ({\n\t\tstatus,\n\t\treport: 'item',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...noMetrics(),\n\t})\n\tif (!bindsItems(binding)) {\n\t\treturn unread('not-bound')\n\t}\n\tconst ref = itemRefOf(args.collectionSlug, args.data.id)\n\tif (ref === undefined) {\n\t\treturn unread('no-path')\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn unread('not-configured')\n\t}\n\tconst caps = adapter.capabilities\n\tconst { supportedMetrics, droppedMetrics, unasked } = splitMetrics(\n\t\targs,\n\t\t(metric) => caps.metrics.has(metric) && ITEM_READ_METRICS.has(metric)\n\t)\n\tif (unasked.length > 0 && caps.perItemQuery === true) {\n\t\targs.req.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" cannot read metric(s) ${unasked.join(', ')} for an item; dropped from the \"${args.collectionSlug}\" display field`\n\t\t)\n\t}\n\tconst first = supportedMetrics[0]\n\tif (caps.perItemQuery !== true || first === undefined) {\n\t\treturn { ...unread('unavailable'), droppedMetrics: args.metrics }\n\t}\n\tconst shared = await sharedQuery(resolved, supportedMetrics)\n\t// Never by hour: an item's views are only kept per day, so a short window reads its days.\n\tconst bucket = seriesGranularityFor(dateRange, caps)\n\treturn readAnswers({\n\t\tresolved,\n\t\tbase: { item: ref, ...shared },\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tseries:\n\t\t\targs.series && supportsGranularity(caps, 'day')\n\t\t\t\t? { metric: first, granularity: bucket === 'hour' ? 'day' : bucket }\n\t\t\t\t: undefined,\n\t\trank: () =>\n\t\t\treadItemBreakdowns({\n\t\t\t\tread: resolved.read,\n\t\t\t\tadapter,\n\t\t\t\titem: ref,\n\t\t\t\twithin: shared,\n\t\t\t\tdateRange,\n\t\t\t\tdimensions: args.dimensions ?? [],\n\t\t\t\tlimit: args.limit ?? DEFAULT_BREAKDOWN_LIMIT,\n\t\t\t\toptions: { timeframe: args.timeframe },\n\t\t\t}),\n\t\treport: 'item',\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+JA,MAAM,0BAA0B;AAQhC,MAAM,WAAwB;CAAE,QAAQ,CAAC;CAAG,QAAQ;AAAM;;AAG1D,MAAM,mBAA6F;CAClG,SAAS,CAAC;CACV,kBAAkB,CAAC;CACnB,gBAAgB,CAAC;AAClB;;AAGA,MAAM,WAAc,SACnB,KAAK,MACH,WAAW;CAAE;CAAO,QAAQ;AAAM,WAC5B,EAAE,QAAQ,KAAK,EACvB;;;;;AAaD,MAAM,WACJ,UACA,SAAS,OAAO,YAChB,aAAa,WAAW,KAAK,SAAS,QAAQ,OAAO,GAAG,OAAO,QAAQ,aAAa,OAAO;;AAM7F,MAAa,eACX,UAAuB,CAAC,OACxB,aACA,SAAS,OAAO,SAChB,QAAQ,OAAO,KAAK,SAAS,OAAO;CAAE,GAAG;CAAM,GAAG;AAAQ,CAAC;;AAG7D,IAAM,gBAAN,cAA4B,MAAM;CACjC,cAAc;EACb,MAAM,2CAA2C;EACjD,KAAK,OAAO;C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ument.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type ReadPrincipal, readPrincipalOf, SYSTEM } from '../access/principal'\nimport { bindsItems, type ReportMode } from '../binding/report'\nimport { resolveHostname, resolvePathCached } from '../binding/resolvePath'\nimport type { BindingContext, BindingDoc, ResolvedBinding } from '../binding/types'\nimport {\n\tfillSeries,\n\ttype SeriesGranularity,\n\ttype SeriesPoint,\n\tseriesGranularityFor,\n} from '../charts/series'\nimport { metricReaches, satisfiesCapabilities, supportsFilter } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { readAsAsked, servedName } from '../core/metricAliases'\nimport { type ReadContext, resolveReadContext } from '../core/scopedRead'\nimport { ITEM_CLICK_EVENT } from '../goals/constants'\nimport { itemRefOf } from '../items/ref'\nimport { resolveDocumentScope } from '../plugin/documentScopes'\nimport { goalSlugsFor } from '../plugin/goalHint'\nimport { type AnalyticsRuntime, getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { exceedsRangeCap } from '../query/limits'\nimport { readFailureOf } from '../surfacing/classifyError'\nimport { PEEK_BUDGET_MS, type ReadOptions } from '../surfacing/engine'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport {\n\tcomparisonWindow,\n\ttype StoredSourceRead,\n\ttype SubstitutedSource,\n\tsubstitutionOf,\n} from '../widgets/prepareWidgetRead'\nimport { mergeNotices, type ReadNotices, readMeta } from '../widgets/readMeta'\nimport { scopeFromDocument } from './documentScope'\nimport { ITEM_READ_METRICS } from './itemReport'\n\n/**\n * `no-access` is about the reader, never a page without traffic; `unavailable` a source that\n * cannot read the document at all; `busy` a failure for now, which a retry can fix.\n */\nexport type FieldReadStatus =\n\t| 'ok'\n\t| 'no-path'\n\t| 'not-bound'\n\t| 'not-configured'\n\t| 'no-access'\n\t| 'no-scope'\n\t| 'unavailable'\n\t| 'busy'\n\t| 'invalid'\n\t| 'range-too-long'\n\t| 'misconfigured'\n\t| 'host-refused'\n\n/** One ranked value of a dimension, for this document's page only. */\nexport interface FieldBreakdownRow {\n\tvalue: string\n\tmetric: number\n}\n\n/**\n * A dimension ranked for this page. The read is a `page eq <path>` filter rather than the\n * per-page report, because that is the only shape a source can group another dimension by.\n */\nexport interface FieldBreakdown extends Partial<ReadNotices> {\n\tdimension: DimensionKey\n\t/** The metric the rows are ranked by; `visitors` wherever the source serves it. */\n\tmetric: MetricKey\n\trows: FieldBreakdownRow[]\n\t/** The source that answered, for the value labels that read differently per provider. */\n\tprovider?: string\n}\n\nexport interface FieldReadResult extends SubstitutedSource {\n\tstatus: FieldReadStatus\n\t/** How long until a `busy` read can succeed, when the source or the plugin knows. */\n\tretryAfterMs?: number\n\t/** The headline numbers answered but a comparison, series or list did not: try again for it. */\n\tincomplete?: true\n\t/** `item` when the read was about the document as a content item, absent for its page. */\n\treport?: 'item'\n\tadapterId: string\n\tdateRange: DateRange\n\t/** The reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\t/** An average with nothing to average over reads `null`; render it as no data, not zero. */\n\tmetrics: MetricValues\n\t/** Requested metrics the adapter supports, in request order; the set actually read. */\n\tsupportedMetrics: MetricKey[]\n\t/** Requested metrics the adapter cannot serve, dropped from the read. */\n\tdroppedMetrics: MetricKey[]\n\t/** Previous-window totals, present only when comparison was requested and supported. */\n\tpreviousMetrics?: MetricValues\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/** Series for the first supported metric, present only when requested. */\n\tpoints?: SeriesPoint[]\n\t/**\n\t * The bucket `points` carry. A window of a day or two is charted by hour, so `day` there\n\t * says the source serves no hourly rows and the panel has a single value, not a line.\n\t */\n\tseriesGranularity?: SeriesGranularity\n\t/** The source counts live visitors, so the panel may poll for this page's own count. */\n\trealtime?: boolean\n\t/** One entry per requested dimension the source can rank for a single page. */\n\tbreakdowns?: FieldBreakdown[]\n\t/** What the totals' and the series' reads say about their numbers. */\n\tnotices?: ReadNotices\n\t/**\n\t * Reader may not read into the document's scope (or is no member of the request's), so the\n\t * read never ran. Rendered as `no-access`; the endpoint answers `untrusted_scope`.\n\t */\n\tuntrustedScope?: boolean\n}\n\n/**\n * Without `scope` the read takes the document's scope (binding `scopeField`) else the request's,\n * gated as endpoints gate it; a given `scope` is already cleared, or a job's under `SYSTEM`.\n */\nexport type ReadForFieldArgs = ReadPrincipal &\n\tStoredSourceRead & {\n\t\treq: PayloadRequest\n\t\tcollectionSlug: string\n\t\tdata: BindingDoc\n\t\tmetrics: MetricKey[]\n\t\ttimeframe: TimeframePreset\n\t\t/** Overrides the preset window (custom range). */\n\t\trange?: DateRange\n\t\tadapterId?: string\n\t\tnow: Date\n\t\t/**\n\t\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t\t */\n\t\ttimezone?: string\n\t\t/** Also read the previous comparable window when the adapter supports comparison. */\n\t\tcompare?: boolean\n\t\t/** Also read a series for the first supported metric, bucketed to suit the window. */\n\t\tseries?: boolean\n\t\t/**\n\t\t * Metrics the caller added speculatively rather than asked for, so a source that serves none\n\t\t * of them is not worth a warning on every render.\n\t\t */\n\t\toptionalMetrics?: MetricKey[]\n\t\t/** Rank these dimensions for the document's own page; each one the source cannot is skipped. */\n\t\tdimensions?: DimensionKey[]\n\t\t/** Rows per breakdown. Default 5. */\n\t\tlimit?: number\n\t\t/**\n\t\t * `item` reads the document as content shown on other pages: its views, clicks and outcomes,\n\t\t * wherever it appeared. Absent, or `page`, reads the document's own page.\n\t\t */\n\t\treport?: ReportMode\n\t}\n\n/** Rows per breakdown block: a card-sized list, not a table. */\nconst DEFAULT_BREAKDOWN_LIMIT = 5\n\n/** The ranked lists a panel read, and whether any it could rank failed to answer. */\ninterface RankedLists {\n\tblocks: FieldBreakdown[]\n\tfailed: boolean\n}\n\nconst NO_LISTS: RankedLists = { blocks: [], failed: false }\n\n/** The numbers of a read that never ran, fresh per result so no two results share an array. */\nconst noMetrics = (): Pick<FieldReadResult, 'metrics' | 'supportedMetrics' | 'droppedMetrics'> => ({\n\tmetrics: {},\n\tsupportedMetrics: [],\n\tdroppedMetrics: [],\n})\n\n/** A read that settles either way: its answer, or `undefined` and `failed` for one that threw. */\nconst settled = <T>(work: Promise<T>): Promise<{ value?: T; failed: boolean }> =>\n\twork.then(\n\t\t(value) => ({ value, failed: false }),\n\t\t() => ({ failed: true })\n\t)\n\n/** How a field read asks for one of the answers behind it. */\nexport type FieldReader = (\n\tadapter: AnalyticsAdapter,\n\tquery: AnalyticsQuery,\n\toptions: ReadOptions\n) => Promise<AnalyticsResult>\n\n/**\n * `read` asking the source in its own names and answering under the read's: `visits` from a source\n * that serves the count as `sessions`.\n */\nconst asAsked =\n\t(read: FieldReader): FieldReader =>\n\t(adapter, query, options) =>\n\t\treadAsAsked((served) => read(adapter, served, options), query, adapter.capabilities.metrics)\n\n/** The reader a field read uses on one runtime. */\nexport type FieldReads = (runtime: AnalyticsRuntime) => FieldReader\n\n/** Engine's own read with `options` laid over each read's own: a cached answer or the source's. */\nexport const engineReads =\n\t(options: ReadOptions = {}): FieldReads =>\n\t(runtime) =>\n\t(adapter, query, base) =>\n\t\truntime.engine.read(adapter, query, { ...base, ...options })\n\n/** A peek found nothing kept for one of the reads, so the field read has no answer to seed with. */\nclass PeekMissError extends Error {\n\tconstructor() {\n\t\tsuper('analytics: nothing kept for this read yet')\n\t\tthis.name = 'PeekMissError'\n\t}\n}\n\n/** What {@link peekForField} found. */\nexport interface FieldPeek {\n\tresult: FieldReadResult\n\t/** False when a read behind it found nothing kept: the result is incomplete or failed for it. */\n\tcomplete: boolean\n\t/** True when an answer behind it was kept past its freshness and is served stale. */\n\tstale: boolean\n}\n\n/**\n * Field read answered only from what the engine keeps (memory and cache store, within `budgetMs`),\n * never a source; a status decided before any read is as final as {@link readForField}'s.\n */\nexport const peekForField = async (\n\targs: ReadForFieldArgs,\n\tbudgetMs: number = PEEK_BUDGET_MS\n): Promise<FieldPeek> => {\n\tlet complete = true\n\tlet stale = false\n\tconst { incomplete: _unkept, ...result } = await readFieldWith(\n\t\targs,\n\t\t(runtime) => async (adapter, query) => {\n\t\t\tconst kept = await runtime.engine.peek?.(adapter, query, { budgetMs })\n\t\t\tif (!kept) {\n\t\t\t\tcomplete = false\n\t\t\t\tthrow new PeekMissError()\n\t\t\t}\n\t\t\tif (kept.meta.stale === true) {\n\t\t\t\tstale = true\n\t\t\t}\n\t\t\treturn kept\n\t\t}\n\t)\n\t// What a peek left unread is `complete: false`, read again by the panel, not a failure.\n\treturn { result, complete, stale }\n}\n\n/**\n * Reads a document's analytics for one display field, never throwing: a status picks the empty\n * state. An unsupported metric is dropped with a warning; `unavailable` only when none survives.\n */\nexport const readForField = (args: ReadForFieldArgs): Promise<FieldReadResult> =>\n\treadFieldWith(args, engineReads())\n\n/**\n * A document scope with nothing this reader may read, a denied `access.read` or a tenant they do\n * not belong to is the reader's own reach, not an unavailable source.\n */\nconst refusedStatus = (\n\treason: Extract<ReadContext, { ok: false }>['reason'],\n\tdocumentScoped: boolean\n): FieldReadStatus => {\n\tif (\n\t\treason === 'no-access' ||\n\t\treason === 'not-member' ||\n\t\t(documentScoped && reason === 'no-sources')\n\t) {\n\t\treturn 'no-access'\n\t}\n\treturn reason === 'no-scope' ? 'no-scope' : 'unavailable'\n}\n\n/**\n * {@link readForField} with the reads behind it answered another way: the engine's own read with\n * other options, or {@link peekForField}'s look at what the engine has kept.\n */\nexport const readFieldWith = async (\n\targs: ReadForFieldArgs,\n\tvia: FieldReads\n): Promise<FieldReadResult> => {\n\tconst { req, collectionSlug, data, timeframe, range, adapterId, now } = args\n\tconst unreadRange = range ?? resolveTimeframe(timeframe, now)\n\tconst unread = (\n\t\tstatus: FieldReadStatus,\n\t\textra: Pick<FieldReadResult, 'untrustedScope'> = {}\n\t): FieldReadResult => ({\n\t\tstatus,\n\t\t...extra,\n\t\tadapterId: adapterId ?? '',\n\t\tdateRange: unreadRange,\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t...noMetrics(),\n\t})\n\tif (range && exceedsRangeCap(range)) {\n\t\treturn unread('range-too-long')\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn unread('not-bound')\n\t}\n\tconst read = asAsked(via(runtime))\n\tconst binding = runtime.bindings[collectionSlug]\n\tif (!binding) {\n\t\treturn unread('not-bound')\n\t}\n\tconst documentScope = scopeFromDocument(data, binding.scopeField)\n\tlet principal: ReadPrincipal = readPrincipalOf(args)\n\t// A pinned scope was already decided (a job's own, or one the caller cleared); anything\n\t// resolved from the document is a scope this reader is naming, gate and all.\n\tif (args.principal !== SYSTEM && args.scope === undefined) {\n\t\tconst resolved = await resolveDocumentScope({ runtime, req, collection: collectionSlug, data })\n\t\tif (!resolved.ok) {\n\t\t\treturn unread('no-access', { untrustedScope: true })\n\t\t}\n\t\tprincipal = resolved.scope === null ? {} : { scope: resolved.gated }\n\t}\n\tconst ctx = await resolveReadContext({\n\t\truntime,\n\t\treq,\n\t\tadapterId,\n\t\t...principal,\n\t\t...(args.fallbackWhenUnreadable ? { fallbackWhenUnreadable: true } : {}),\n\t\t// An item read goes through a source that can answer one, wherever the scope has one.\n\t\t...(args.report === 'item'\n\t\t\t? { prefer: (candidate: AnalyticsAdapter) => candidate.capabilities.perItemQuery === true }\n\t\t\t: {}),\n\t})\n\tif (!ctx.ok) {\n\t\treturn unread(\n\t\t\trefusedStatus(ctx.reason, documentScope !== null),\n\t\t\tctx.reason === 'not-member' ? { untrustedScope: true } : {}\n\t\t)\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst resolved: ResolvedRead = {\n\t\targs,\n\t\truntime,\n\t\tread,\n\t\tbinding,\n\t\tadapter: ctx.adapter,\n\t\tscope: ctx.scope,\n\t\tqueryScope: ctx.queryScope,\n\t\ttz,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now, tz),\n\t\tbindingCtx: { req, locale: req.locale ?? undefined },\n\t}\n\tconst result = args.report === 'item' ? await readItem(resolved) : await readPage(resolved)\n\treturn { ...result, ...substitutionOf(ctx) }\n}\n\n/** A field read past every gate: its source chosen, its scope and window resolved. */\ninterface ResolvedRead {\n\targs: ReadForFieldArgs\n\truntime: AnalyticsRuntime\n\tread: FieldReader\n\tbinding: ResolvedBinding\n\tadapter: AnalyticsAdapter\n\tscope: string | null\n\tqueryScope: string | undefined\n\ttz: string\n\tdateRange: DateRange\n\tbindingCtx: BindingContext\n}\n\n/**\n * Splits the asked metrics by what the source serves; the dropped ones the caller did not add\n * speculatively are worth a warning.\n */\nconst splitMetrics = (args: ReadForFieldArgs, serves: (metric: MetricKey) => boolean) => {\n\tconst supportedMetrics = args.metrics.filter(serves)\n\tconst droppedMetrics = args.metrics.filter((metric) => !serves(metric))\n\tconst optional = new Set(args.optionalMetrics ?? [])\n\tconst unasked = droppedMetrics.filter((metric) => !optional.has(metric))\n\treturn { supportedMetrics, droppedMetrics, unasked }\n}\n\n/** What every query of one read narrows by besides its page or item: host, zone, scope, goals. */\nconst sharedQuery = async (input: ResolvedRead, metrics: MetricKey[]) => {\n\tconst hostname = await resolveHostname(input.binding, input.args.data, input.bindingCtx)\n\tconst goalSlugs = await goalSlugsFor({\n\t\truntime: input.runtime,\n\t\treq: input.args.req,\n\t\tscope: input.scope,\n\t\tmetrics,\n\t})\n\treturn {\n\t\thostname,\n\t\ttimezone: input.tz,\n\t\tscope: input.queryScope,\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n}\n\n/** What a ranked list narrows to besides its own filter. */\ninterface ListScope {\n\ttimezone: string\n\thostname?: string | undefined\n\tscope?: string | undefined\n}\n\n/** How each list of a read is read: the same source, window and narrowing for all of them. */\ninterface ListReads {\n\tread: FieldReader\n\tadapter: AnalyticsAdapter\n\twithin: ListScope\n\tdateRange: DateRange\n\tdimensions: DimensionKey[]\n\tlimit: number\n\toptions: ReadOptions\n}\n\n/** One dimension ranked by `metric` within `narrowing`; null when the read throws. */\nconst readRankedList = async (\n\tinput: Omit<ListReads, 'dimensions'> & {\n\t\tdimension: DimensionKey\n\t\tmetric: MetricKey\n\t\tnarrowing: Pick<AnalyticsQuery, 'filters' | 'item'>\n\t}\n): Promise<FieldBreakdown | null> => {\n\tconst { dimension, metric, within, limit } = input\n\ttry {\n\t\tconst result = await input.read(\n\t\t\tinput.adapter,\n\t\t\t{\n\t\t\t\tmetrics: [metric],\n\t\t\t\tdimensions: [dimension],\n\t\t\t\tdateRange: input.dateRange,\n\t\t\t\tlimit,\n\t\t\t\torder: { metric, direction: 'desc' },\n\t\t\t\t...input.narrowing,\n\t\t\t\ttimezone: within.timezone,\n\t\t\t\t...(within.hostname === undefined ? {} : { hostname: within.hostname }),\n\t\t\t\t...(within.scope === undefined ? {} : { scope: within.scope }),\n\t\t\t},\n\t\t\tinput.options\n\t\t)\n\t\tconst rows = result.rows\n\t\t\t.map((row) => ({\n\t\t\t\tvalue: row.dimensions?.[dimension] ?? '',\n\t\t\t\tmetric: row.metrics[metric] ?? 0,\n\t\t\t}))\n\t\t\t.slice(0, limit)\n\t\treturn { dimension, metric, rows, ...readMeta(result) }\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/** Settles every list read: one that answered null is dropped alone and marks the set failed. */\nconst rankedLists = async (reads: Array<Promise<FieldBreakdown | null>>): Promise<RankedLists> => {\n\tconst answered = await Promise.all(reads)\n\tconst blocks = answered.filter((block): block is FieldBreakdown => block !== null)\n\treturn { blocks, failed: blocks.length < answered.length }\n}\n\n/** Ranked by people rather than hits wherever the source counts them. */\nconst breakdownMetric = (adapter: AnalyticsAdapter): MetricKey =>\n\tadapter.capabilities.metrics.has('visitors') ? 'visitors' : 'pageviews'\n\n/**\n * Ranks each dimension for one page via a `page eq` filter; a source that cannot filter or group\n * so gives no block rather than a site-wide list, and a block that throws is dropped alone.\n */\nconst readBreakdowns = async (lists: ListReads & { path: string }): Promise<RankedLists> => {\n\tconst caps = lists.adapter.capabilities\n\tif (\n\t\tlists.dimensions.length === 0 ||\n\t\t!supportsFilter(caps, { dimension: 'page', operator: 'eq' })\n\t) {\n\t\treturn NO_LISTS\n\t}\n\tconst metric = breakdownMetric(lists.adapter)\n\tconst wanted = lists.dimensions.filter(\n\t\t(dimension) =>\n\t\t\tcaps.dimensions.has(dimension) &&\n\t\t\tmetricReaches(caps, metric, { dimensions: [dimension], filters: ['page'] })\n\t)\n\treturn rankedLists(\n\t\twanted.map((dimension) =>\n\t\t\treadRankedList({\n\t\t\t\t...lists,\n\t\t\t\tdimension,\n\t\t\t\tmetric,\n\t\t\t\t// `path` is deliberately not set: it selects the per-page report, which no source\n\t\t\t\t// groups a second dimension by. The filter is the same narrowing said another way.\n\t\t\t\tnarrowing: { filters: [{ dimension: 'page', operator: 'eq', value: lists.path }] },\n\t\t\t})\n\t\t)\n\t)\n}\n\n/**\n * An `item eq` filter matches the item's views too, so clickers are its visitors with an\n * `item_click` event; a source unable to filter that ranks clicks instead. Null if neither.\n */\nconst clickList = (\n\tcaps: AnalyticsAdapter['capabilities'],\n\titem: string\n): { metric: MetricKey; filters: AnalyticsFilter[] } | null => {\n\tconst byItem: AnalyticsFilter = { dimension: 'item', operator: 'eq', value: item }\n\tif (!supportsFilter(caps, byItem)) {\n\t\treturn null\n\t}\n\tif (\n\t\tcaps.metrics.has('visitors') &&\n\t\tsupportsFilter(caps, { dimension: 'event', operator: 'eq' })\n\t) {\n\t\treturn {\n\t\t\tmetric: 'visitors',\n\t\t\tfilters: [byItem, { dimension: 'event', operator: 'eq', value: ITEM_CLICK_EVENT }],\n\t\t}\n\t}\n\treturn caps.metrics.has('interactions') ? { metric: 'interactions', filters: [byItem] } : null\n}\n\n/**\n * Ranks pages the item was seen on and where its clickers are (see {@link clickList}); a list the\n * source cannot rank is left out, and one that fails is dropped alone.\n */\nconst readItemBreakdowns = async (lists: ListReads & { item: string }): Promise<RankedLists> => {\n\tconst caps = lists.adapter.capabilities\n\tconst reads: Array<Promise<FieldBreakdown | null>> = []\n\tfor (const dimension of lists.dimensions) {\n\t\tconst pages = dimension === 'page'\n\t\tconst clicks = pages ? null : clickList(caps, lists.item)\n\t\tif (!caps.dimensions.has(dimension) || (!pages && clicks === null)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst metric: MetricKey = clicks?.metric ?? 'impressions'\n\t\tif (!metricReaches(caps, metric, { dimensions: [dimension], filters: clicks?.filters ?? [] })) {\n\t\t\tcontinue\n\t\t}\n\t\treads.push(\n\t\t\treadRankedList({\n\t\t\t\t...lists,\n\t\t\t\tdimension,\n\t\t\t\tmetric,\n\t\t\t\tnarrowing: clicks === null ? { item: lists.item } : { filters: clicks.filters },\n\t\t\t})\n\t\t)\n\t}\n\treturn rankedLists(reads)\n}\n\n/** One read's queries, decided: what to read and through what, before any of it is asked. */\ninterface Answering {\n\tresolved: ResolvedRead\n\t/** Every query's narrowing to the document: its page or item, host, zone, scope and goals. */\n\tbase: Omit<AnalyticsQuery, 'metrics' | 'dateRange'>\n\tsupportedMetrics: MetricKey[]\n\tdroppedMetrics: MetricKey[]\n\t/** The trend's metric and bucket; absent when no series is read. */\n\tseries: { metric: MetricKey; granularity: SeriesGranularity } | undefined\n\trank: () => Promise<RankedLists>\n\treport?: 'item'\n\trealtime?: boolean\n}\n\n/**\n * Reads the headline, then its comparison, series and lists beside it. Only the headline can fail\n * the read; any other that fails leaves the answer `incomplete`.\n */\nconst readAnswers = async (answering: Answering): Promise<FieldReadResult> => {\n\tconst { resolved, base, supportedMetrics, droppedMetrics, series } = answering\n\tconst { read, adapter, dateRange, tz } = resolved\n\tconst comparisonRange = resolved.args.compare\n\t\t? comparisonWindow(resolved, resolved.args.now)\n\t\t: undefined\n\tconst options: ReadOptions = { timeframe: resolved.args.timeframe }\n\tconst reportTag = answering.report === undefined ? {} : { report: answering.report }\n\t// The headline takes the source's first slot and alone can fail the read; the lists wait for it.\n\tconst main = read(adapter, { ...base, metrics: supportedMetrics, dateRange }, options)\n\tconst comparing = comparisonRange\n\t\t? settled(\n\t\t\t\tread(adapter, { ...base, metrics: supportedMetrics, dateRange: comparisonRange }, options)\n\t\t\t)\n\t\t: undefined\n\tconst charting = series\n\t\t? settled(\n\t\t\t\tread(\n\t\t\t\t\tadapter,\n\t\t\t\t\t{ ...base, metrics: [series.metric], dateRange, granularity: series.granularity },\n\t\t\t\t\toptions\n\t\t\t\t)\n\t\t\t)\n\t\t: undefined\n\tconst ranking = main.then(\n\t\t() => answering.rank(),\n\t\t() => NO_LISTS\n\t)\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await main\n\t} catch (err) {\n\t\t// Nothing cached survived the failed read: a status, never a throw through the edit view.\n\t\treturn {\n\t\t\t...readFailureOf(err),\n\t\t\t...reportTag,\n\t\t\tadapterId: adapter.id,\n\t\t\tdateRange,\n\t\t\ttimezone: tz,\n\t\t\tmetrics: {},\n\t\t\tsupportedMetrics,\n\t\t\tdroppedMetrics,\n\t\t}\n\t}\n\tconst [compared, charted, lists] = await Promise.all([comparing, charting, ranking])\n\tconst previous = compared?.value\n\tconst seriesResult = charted?.value\n\tconst ranked = lists.blocks\n\tconst incomplete = compared?.failed === true || charted?.failed === true || lists.failed\n\treturn {\n\t\tstatus: 'ok',\n\t\t...(incomplete ? { incomplete: true as const } : {}),\n\t\t...reportTag,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...(answering.realtime === undefined ? {} : { realtime: answering.realtime }),\n\t\t...(ranked.length > 0 ? { breakdowns: ranked } : {}),\n\t\tnotices: mergeNotices(readMeta(result), seriesResult ? readMeta(seriesResult) : undefined),\n\t\tmetrics: result.totals ?? {},\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tpreviousMetrics: previous ? (previous.totals ?? {}) : undefined,\n\t\tcomparisonRange: previous ? comparisonRange : undefined,\n\t\tpoints:\n\t\t\tseriesResult && series\n\t\t\t\t? fillSeries({\n\t\t\t\t\t\trows: seriesResult.rows,\n\t\t\t\t\t\tdateRange,\n\t\t\t\t\t\tmetric: series.metric,\n\t\t\t\t\t\ttz,\n\t\t\t\t\t\tgranularity: series.granularity,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\tseriesGranularity: seriesResult ? series?.granularity : undefined,\n\t}\n}\n\n/** Document read as its own page, at the path its binding resolves. */\nconst readPage = async (resolved: ResolvedRead): Promise<FieldReadResult> => {\n\tconst { args, binding, adapter, tz, dateRange } = resolved\n\tconst unread = (status: FieldReadStatus): FieldReadResult => ({\n\t\tstatus,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...noMetrics(),\n\t})\n\tlet path: string | null\n\ttry {\n\t\tpath = await resolvePathCached(binding, args.data, resolved.bindingCtx)\n\t} catch {\n\t\tpath = null\n\t}\n\tif (!path) {\n\t\treturn unread('no-path')\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn unread('not-configured')\n\t}\n\tconst caps = adapter.capabilities\n\tconst servesForPage = (metric: MetricKey): boolean => {\n\t\tconst name = servedName(metric, caps.metrics)\n\t\treturn caps.metrics.has(name) && metricReaches(caps, name, { path: true })\n\t}\n\tconst { supportedMetrics, droppedMetrics, unasked } = splitMetrics(args, servesForPage)\n\tif (unasked.length > 0) {\n\t\targs.req.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" does not support metric(s) ${unasked.join(', ')}; dropped from the \"${args.collectionSlug}\" display field`\n\t\t)\n\t}\n\tconst leadMetric = supportedMetrics[0]\n\tif (\n\t\tleadMetric === undefined ||\n\t\t!satisfiesCapabilities(caps, {\n\t\t\tmetrics: supportedMetrics.map((metric) => servedName(metric, caps.metrics)),\n\t\t\tpath: true,\n\t\t})\n\t) {\n\t\treturn { ...unread('unavailable'), droppedMetrics: args.metrics }\n\t}\n\tconst shared = await sharedQuery(resolved, supportedMetrics)\n\treturn readAnswers({\n\t\tresolved,\n\t\tbase: { path, ...shared },\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tseries:\n\t\t\targs.series && supportsGranularity(caps, 'day')\n\t\t\t\t? { metric: leadMetric, granularity: seriesGranularityFor(dateRange, caps) }\n\t\t\t\t: undefined,\n\t\trank: () =>\n\t\t\treadBreakdowns({\n\t\t\t\tread: resolved.read,\n\t\t\t\tadapter,\n\t\t\t\tpath,\n\t\t\t\twithin: shared,\n\t\t\t\tdateRange,\n\t\t\t\tdimensions: args.dimensions ?? [],\n\t\t\t\tlimit: args.limit ?? DEFAULT_BREAKDOWN_LIMIT,\n\t\t\t\toptions: { timeframe: args.timeframe },\n\t\t\t}),\n\t\trealtime: caps.realtime && typeof adapter.realtime === 'function',\n\t})\n}\n\n/**\n * Document read as a content item under its ref `<collection>:<id>`. Metrics an item's buckets\n * never count are dropped like unserved ones; nothing about an item is counted live.\n */\nconst readItem = async (resolved: ResolvedRead): Promise<FieldReadResult> => {\n\tconst { args, binding, adapter, tz, dateRange } = resolved\n\tconst unread = (status: FieldReadStatus): FieldReadResult => ({\n\t\tstatus,\n\t\treport: 'item',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\t...noMetrics(),\n\t})\n\tif (!bindsItems(binding)) {\n\t\treturn unread('not-bound')\n\t}\n\tconst ref = itemRefOf(args.collectionSlug, args.data.id)\n\tif (ref === undefined) {\n\t\treturn unread('no-path')\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn unread('not-configured')\n\t}\n\tconst caps = adapter.capabilities\n\tconst { supportedMetrics, droppedMetrics, unasked } = splitMetrics(\n\t\targs,\n\t\t(metric) => caps.metrics.has(metric) && ITEM_READ_METRICS.has(metric)\n\t)\n\tif (unasked.length > 0 && caps.perItemQuery === true) {\n\t\targs.req.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" cannot read metric(s) ${unasked.join(', ')} for an item; dropped from the \"${args.collectionSlug}\" display field`\n\t\t)\n\t}\n\tconst first = supportedMetrics[0]\n\tif (caps.perItemQuery !== true || first === undefined) {\n\t\treturn { ...unread('unavailable'), droppedMetrics: args.metrics }\n\t}\n\tconst shared = await sharedQuery(resolved, supportedMetrics)\n\t// Never by hour: an item's views are only kept per day, so a short window reads its days.\n\tconst bucket = seriesGranularityFor(dateRange, caps)\n\treturn readAnswers({\n\t\tresolved,\n\t\tbase: { item: ref, ...shared },\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tseries:\n\t\t\targs.series && supportsGranularity(caps, 'day')\n\t\t\t\t? { metric: first, granularity: bucket === 'hour' ? 'day' : bucket }\n\t\t\t\t: undefined,\n\t\trank: () =>\n\t\t\treadItemBreakdowns({\n\t\t\t\tread: resolved.read,\n\t\t\t\tadapter,\n\t\t\t\titem: ref,\n\t\t\t\twithin: shared,\n\t\t\t\tdateRange,\n\t\t\t\tdimensions: args.dimensions ?? [],\n\t\t\t\tlimit: args.limit ?? DEFAULT_BREAKDOWN_LIMIT,\n\t\t\t\toptions: { timeframe: args.timeframe },\n\t\t\t}),\n\t\treport: 'item',\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqKA,MAAM,0BAA0B;AAQhC,MAAM,WAAwB;CAAE,QAAQ,CAAC;CAAG,QAAQ;AAAM;;AAG1D,MAAM,mBAA6F;CAClG,SAAS,CAAC;CACV,kBAAkB,CAAC;CACnB,gBAAgB,CAAC;AAClB;;AAGA,MAAM,WAAc,SACnB,KAAK,MACH,WAAW;CAAE;CAAO,QAAQ;AAAM,WAC5B,EAAE,QAAQ,KAAK,EACvB;;;;;AAaD,MAAM,WACJ,UACA,SAAS,OAAO,YAChB,aAAa,WAAW,KAAK,SAAS,QAAQ,OAAO,GAAG,OAAO,QAAQ,aAAa,OAAO;;AAM7F,MAAa,eACX,UAAuB,CAAC,OACxB,aACA,SAAS,OAAO,SAChB,QAAQ,OAAO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AAA;EACJ,YACC,mBAAmB;GAClB,MAAM,SAAS;GACf;GACA,MAAM;GACN,QAAQ;GACR;GACA,YAAY,KAAK,cAAc,CAAC;GAChC,OAAO,KAAK,SAAS;GACrB,SAAS,EAAE,WAAW,KAAK,UAAU;EACtC,CAAC;EACF,QAAQ;CACT,CAAC;AACF"}
@@ -1,17 +1,17 @@
1
1
  import { valueAt } from "../core/values.js";
2
2
  import { keys } from "../translations/keys.js";
3
- import { memberScopeOf, providerCreateAccess, providerRowAccess } from "../providers/access.js";
3
+ import { providerCreateAccess, providerRowAccess } from "../providers/access.js";
4
4
  import { asTranslate, labelForKey } from "../translations/server.js";
5
5
  import { builtInStaticLabel } from "../translations/staticLabel.js";
6
6
  import { amountCurrencyField } from "./currency.js";
7
7
  import { hasNamedField, overrideField, pairInRow } from "../plugin/collectionFields.js";
8
8
  import { docScope } from "../plugin/scopeChange.js";
9
+ import { takenInScope } from "../providers/scopeUnique.js";
9
10
  import { stampScope } from "../providers/stampScope.js";
10
11
  import { amountField } from "./amountField.js";
11
12
  import { hiddenAdmin } from "./moneyFields.js";
12
13
  import { patternProblem } from "./pathMatch.js";
13
14
  import { GOAL_SLUG_PATTERN } from "./types.js";
14
- import { goalScopeWhere } from "./resolver.js";
15
15
  import { ValidationError } from "payload";
16
16
  //#region src/goals/collection.ts
17
17
  const GOALS_SLUG = "analytics-goals";
@@ -21,20 +21,6 @@ const validatePattern = (value, { req }) => typeof value === "string" && pattern
21
21
  segments: 32,
22
22
  globstars: 4
23
23
  }) : true;
24
- const asScope = (value) => value === null || value === void 0 || value === "" ? null : String(value);
25
- /**
26
- * The scope the stamp will land the write in. Only a platform admin's declared scope is trusted:
27
- * anyone else's would turn "slug taken" into an oracle for what another tenant owns.
28
- */
29
- const writeScope = async (args, write) => {
30
- const { data, originalDoc, req } = write;
31
- try {
32
- if (await args.crossScope({ req })) return asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField]);
33
- return await memberScopeOf(args, req);
34
- } catch {
35
- return null;
36
- }
37
- };
38
24
  const slugError = (collection, req, key) => new ValidationError({
39
25
  collection,
40
26
  errors: [{
@@ -52,24 +38,11 @@ const checkSlug = (args) => {
52
38
  const slug = data?.slug;
53
39
  if (typeof slug !== "string" || slug === "") return data;
54
40
  if (!GOAL_SLUG_PATTERN.test(slug)) throw slugError(args.slug, req, keys.goalErrorSlug);
55
- const where = [{ slug: { equals: slug } }];
56
- if (args.scoped) where.push(goalScopeWhere(args.scopeField, await writeScope(args, {
41
+ if (await takenInScope(args, {
57
42
  data,
58
43
  originalDoc,
59
44
  req
60
- })));
61
- const id = originalDoc?.id;
62
- if (id !== void 0 && id !== null) where.push({ id: { not_equals: id } });
63
- const { docs } = await req.payload.find({
64
- collection: args.slug,
65
- where: { and: where },
66
- limit: 1,
67
- pagination: false,
68
- depth: 0,
69
- overrideAccess: true,
70
- req
71
- });
72
- if (docs.length > 0) throw slugError(args.slug, req, keys.goalErrorSlugTaken);
45
+ }, { slug: { equals: slug } })) throw slugError(args.slug, req, keys.goalErrorSlugTaken);
73
46
  return data;
74
47
  };
75
48
  };
@@ -1 +1 @@
1
- {"version":3,"file":"collection.js","names":[],"sources":["../../src/goals/collection.ts"],"sourcesContent":["import type {\n\tCollectionBeforeValidateHook,\n\tCollectionConfig,\n\tCollectionSlug,\n\tCompoundIndex,\n\tField,\n\tPayloadRequest,\n\tTextFieldSingleValidation,\n\tWhere,\n} from 'payload'\nimport { ValidationError } from 'payload'\nimport { valueAt } from '../core/values'\nimport {\n\ttype CollectionFieldOverride,\n\thasNamedField,\n\toverrideField,\n\tpairInRow,\n} from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport type { ProviderAccessArgs } from '../providers/access'\nimport { memberScopeOf, providerCreateAccess, providerRowAccess } from '../providers/access'\nimport { stampScope } from '../providers/stampScope'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { amountField } from './amountField'\nimport { type AmountOf, amountCurrencyField } from './currency'\nimport { hiddenAdmin } from './moneyFields'\nimport { MAX_PATTERN_GLOBSTARS, MAX_PATTERN_SEGMENTS, patternProblem } from './pathMatch'\nimport { goalScopeWhere } from './resolver'\nimport { GOAL_SLUG_PATTERN } from './types'\n\nexport const GOALS_SLUG = 'analytics-goals'\n\n/**\n * Replaces one default field, receiving the plugin's own to spread. Any field type may come back, a\n * `row` included, as long as the slug override still holds a field named `slug`.\n */\nexport type GoalFieldOverride = CollectionFieldOverride\n\nexport interface GoalCollectionFieldOverrides {\n\tname?: GoalFieldOverride\n\tslug?: GoalFieldOverride\n\tenabled?: GoalFieldOverride\n\tbrowser?: GoalFieldOverride\n\tmatch?: GoalFieldOverride\n\tvalue?: GoalFieldOverride\n\tcurrency?: GoalFieldOverride\n}\n\nexport interface BuildGoalsCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: GoalCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Whether the install measures money, default on. False hides the amount and currency rather than\n\t * removing them, so existing amounts survive and show again when it is turned back on.\n\t */\n\trevenue?: boolean\n\t/**\n\t * The install's reporting currency when it is one fixed code. The Amount control fills it\n\t * in once an amount is set on a goal that has no currency yet.\n\t */\n\tdefaultCurrency?: string\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n}\n\nconst validateSlug: TextFieldSingleValidation = (value, { req }) =>\n\ttypeof value === 'string' && GOAL_SLUG_PATTERN.test(value)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.goalErrorSlug)\n\n/** The matcher's caps, refused here so an editor hears about them rather than a goal never matching. */\nconst validatePattern: TextFieldSingleValidation = (value, { req }) =>\n\ttypeof value === 'string' && patternProblem(value) !== null\n\t\t? asTranslate(req.t)(keys.goalErrorPatternLimits, {\n\t\t\t\tsegments: MAX_PATTERN_SEGMENTS,\n\t\t\t\tglobstars: MAX_PATTERN_GLOBSTARS,\n\t\t\t})\n\t\t: true\n\nconst asScope = (value: unknown): string | null =>\n\tvalue === null || value === undefined || value === '' ? null : String(value)\n\n/**\n * The scope the stamp will land the write in. Only a platform admin's declared scope is trusted:\n * anyone else's would turn \"slug taken\" into an oracle for what another tenant owns.\n */\nconst writeScope = async (\n\targs: BuildGoalsCollectionArgs,\n\twrite: {\n\t\tdata?: Record<string, unknown>\n\t\toriginalDoc?: Record<string, unknown>\n\t\treq: PayloadRequest\n\t}\n): Promise<string | null> => {\n\tconst { data, originalDoc, req } = write\n\ttry {\n\t\tif (await args.crossScope({ req })) {\n\t\t\t// No declared scope means an install-wide goal, not one in whatever scope the\n\t\t\t// admin's own request happens to resolve to.\n\t\t\treturn asScope(data?.[args.scopeField]) ?? asScope(originalDoc?.[args.scopeField])\n\t\t}\n\t\treturn await memberScopeOf(args, req)\n\t} catch {\n\t\treturn null\n\t}\n}\n\nconst slugError = (collection: string, req: PayloadRequest, key: TranslationKey) =>\n\tnew ValidationError({\n\t\tcollection,\n\t\terrors: [\n\t\t\t{\n\t\t\t\tlabel: labelForKey(keys.goalFieldSlug),\n\t\t\t\tmessage: asTranslate(req.t)(key),\n\t\t\t\tpath: 'slug',\n\t\t\t},\n\t\t],\n\t})\n\n/**\n * Slug shape and per-scope uniqueness at collection level, so a replaced slug field without its own\n * `validate` keeps them; the index cannot cover install-wide Postgres rows or host scope fields.\n */\nconst checkSlug = (args: BuildGoalsCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tconst slug = data?.slug\n\t\tif (typeof slug !== 'string' || slug === '') {\n\t\t\treturn data\n\t\t}\n\t\tif (!GOAL_SLUG_PATTERN.test(slug)) {\n\t\t\tthrow slugError(args.slug, req, keys.goalErrorSlug)\n\t\t}\n\t\tconst where: Where[] = [{ slug: { equals: slug } }]\n\t\tif (args.scoped) {\n\t\t\twhere.push(\n\t\t\t\tgoalScopeWhere(args.scopeField, await writeScope(args, { data, originalDoc, req }))\n\t\t\t)\n\t\t}\n\t\tconst id = originalDoc?.id\n\t\tif (id !== undefined && id !== null) {\n\t\t\twhere.push({ id: { not_equals: id } })\n\t\t}\n\t\t// pagination:false is load-bearing: a paginated read fires its count and its find in\n\t\t// parallel on one Mongo session, which the write's open transaction refuses.\n\t\tconst { docs } = await req.payload.find({\n\t\t\t// This hook runs on the collection itself, so its slug is registered.\n\t\t\tcollection: args.slug as CollectionSlug,\n\t\t\twhere: { and: where },\n\t\t\tlimit: 1,\n\t\t\tpagination: false,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\tif (docs.length > 0) {\n\t\t\tthrow slugError(args.slug, req, keys.goalErrorSlugTaken)\n\t\t}\n\t\treturn data\n\t}\n}\n\n/**\n * Database backstop for the hook, only where the plugin owns the scope field. Postgres treats a NULL\n * scope as distinct, so install-wide rows stay hook-guarded.\n */\nconst uniqueSlugIndex = (args: BuildGoalsCollectionArgs): CompoundIndex | undefined => {\n\tif (!args.scoped) {\n\t\treturn { fields: ['slug'], unique: true }\n\t}\n\treturn args.scopeField === 'scope' ? { fields: ['slug', 'scope'], unique: true } : undefined\n}\n\n/**\n * The plugin's scope field, only while `scopeField` names it: a host-owned field is the host's to\n * register, and a hidden twin would store the scope twice.\n */\nconst scopeField = (args: BuildGoalsCollectionArgs): Field[] =>\n\targs.scopeField === 'scope'\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.goalFieldName),\n\tadmin: { width: '50%', description: labelForKey(keys.goalFieldNameHelp) },\n})\n\nconst slugField = (indexed: boolean): Field => ({\n\tname: 'slug',\n\ttype: 'text',\n\trequired: true,\n\t// Mongoose refuses a field index and a compound index that share a key spec, and the\n\t// compound one already covers a lookup by slug.\n\tindex: indexed,\n\tlabel: labelForKey(keys.goalFieldSlug),\n\tvalidate: validateSlug,\n\tadmin: { width: '50%', description: labelForKey(keys.goalFieldSlugHelp) },\n})\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.goalFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.goalFieldEnabledHelp) },\n})\n\n/** Off for a goal only server code completes: a browser's completion of it is then ignored. */\nconst browserField = (): Field => ({\n\tname: 'browser',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.goalFieldBrowser),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.goalFieldBrowserHelp) },\n})\n\nconst matchField = (staticLabel: StaticLabelFor): Field => ({\n\tname: 'match',\n\ttype: 'group',\n\tlabel: labelForKey(keys.goalFieldMatch),\n\tfields: [\n\t\t{\n\t\t\tname: 'kind',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\tdefaultValue: 'goal',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchKind),\n\t\t\t// `admin.description` on a select is read where a label function never runs, so the\n\t\t\t// three kinds are explained through the locale map instead.\n\t\t\tadmin: { description: staticLabel(keys.goalFieldMatchKindHelp) },\n\t\t\toptions: [\n\t\t\t\t{ label: labelForKey(keys.goalKindGoal), value: 'goal' },\n\t\t\t\t{ label: labelForKey(keys.goalKindEvent), value: 'event' },\n\t\t\t\t{ label: labelForKey(keys.goalKindPath), value: 'path' },\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tname: 'name',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchEventName),\n\t\t\tadmin: {\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.kind === 'event',\n\t\t\t\tdescription: labelForKey(keys.goalFieldMatchEventNameHelp),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'pattern',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchPathPattern),\n\t\t\tvalidate: validatePattern,\n\t\t\tadmin: {\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.kind === 'path',\n\t\t\t\tdescription: labelForKey(keys.goalFieldMatchPathPatternHelp),\n\t\t\t},\n\t\t},\n\t],\n})\n\n/**\n * The amount and where else it may come from, with no heading of their own so they read as\n * part of the goal. The currency is the sibling `currency` field, edited in the Amount control.\n */\nconst valueField = (defaultCurrency: string | undefined): Field => ({\n\tname: 'value',\n\ttype: 'group',\n\tlabel: false,\n\tadmin: { hideGutter: true },\n\tfields: [\n\t\tamountField(\n\t\t\t{\n\t\t\t\tname: 'fixed',\n\t\t\t\ttype: 'number',\n\t\t\t\tmin: 0,\n\t\t\t\tlabel: labelForKey(keys.goalFieldAmount),\n\t\t\t\tadmin: { description: labelForKey(keys.goalFieldAmountHelp) },\n\t\t\t},\n\t\t\t{ currencyPath: '../currency', defaultCurrency }\n\t\t),\n\t\t{\n\t\t\tname: 'prop',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldAmountProp),\n\t\t\tadmin: {\n\t\t\t\tdescription: labelForKey(keys.goalFieldAmountPropHelp),\n\t\t\t\t// Only an action's own details can carry an amount to read.\n\t\t\t\tcondition: (data) => data?.match?.kind === 'event',\n\t\t\t},\n\t\t},\n\t],\n})\n\n/** The amount a goal's currency belongs to: its fixed amount. */\nconst fixedAmount: AmountOf = ({ data }) => valueAt(data, 'value.fixed')\n\n/**\n * Hidden rather than removed while the install measures no money, a replacement included: the\n * field stays in the schema, so a goal that already carries an amount keeps it.\n */\nconst moneyOnly = (field: Field, revenue: boolean | undefined): Field =>\n\trevenue === false ? Object.assign({}, field, { admin: hiddenAdmin(field) }) : field\n\n/**\n * Name and slug share the first row while both are plain named fields; a layout or sidebar\n * replacement cannot live in a row, so it goes top level at its declared position.\n */\nconst layout = (args: BuildGoalsCollectionArgs, indexed: boolean): Field[] => [\n\t...pairInRow(\n\t\toverrideField(nameField(), args.fields?.name),\n\t\toverrideField(slugField(indexed), args.fields?.slug)\n\t),\n\toverrideField(enabledField(), args.fields?.enabled),\n\toverrideField(browserField(), args.fields?.browser),\n\toverrideField(matchField(args.staticLabel ?? builtInStaticLabel), args.fields?.match),\n\tmoneyOnly(overrideField(valueField(args.defaultCurrency), args.fields?.value), args.revenue),\n\tmoneyOnly(overrideField(amountCurrencyField(fixedAmount), args.fields?.currency), args.revenue),\n\t...scopeField(args),\n]\n\n/**\n * The editor-managed goals collection, one document per goal and scope, merged over config goals.\n * Admin-only by default; `access`, `fields` and finally `overrides` reshape it.\n */\nexport const buildGoalsCollection = (args: BuildGoalsCollectionArgs): CollectionConfig => {\n\tconst unique = uniqueSlugIndex(args)\n\tconst fields = layout(args, unique === undefined)\n\tif (!hasNamedField(fields, 'slug')) {\n\t\tthrow new Error(\n\t\t\t`analytics: goals.collection.fields.slug must return a field named \"slug\" (a row or group containing one is fine); the goals collection \"${args.slug}\" keys every report on that value`\n\t\t)\n\t}\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\t...(unique ? { indexes: [unique] } : {}),\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.goalsCollectionSingular),\n\t\t\tplural: labelForKey(keys.goalsCollectionPlural),\n\t\t},\n\t\t// A duplicate would carry the slug over, which the uniqueness hook refuses anyway.\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'slug', 'match.kind', 'enabled'],\n\t\t\tgroup: (args.staticLabel ?? builtInStaticLabel)(keys.adminGroup),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\tbeforeValidate: [checkSlug(args)],\n\t\t\tbeforeChange: [stampScope(args)],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields,\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAa,aAAa;AA2C1B,MAAM,gBAA2C,OAAO,EAAE,UACzD,OAAO,UAAU,YAAY,kBAAkB,KAAK,KAAK,IACtD,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,aAAa;;AAGzC,MAAM,mBAA8C,OAAO,EAAE,UAC5D,OAAO,UAAU,YAAY,eAAe,KAAK,MAAM,OACpD,YAAY,IAAI,CAAC,EAAE,KAAK,wBAAwB;CAChD,UAAA;CACA,WAAA;AACD,CAAC,IACA;AAEJ,MAAM,WAAW,UAChB,UAAU,QAAQ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,OAAO,EAAE,KAAK,WAAW,aAAa,UAAU;IAC/C,MAAM,KAAK,SACV;KACC,OAAO,SAAS,KAAK,KAAK,UAAU;KACpC,GAAI,cAAc,WACf,EAAE,eAAe,SAAS,aAAa,KAAK,UAAU,EAAE,IACxD,CAAC;IACL,GACA,GACD;IACA,OAAO;GACR,CACD;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,UAAU;IACvB,MAAM,KAAK,SAAS,EAAE,OAAO,SAAS,KAAK,KAAK,UAAU,EAAE,GAAG,GAAG;IAClE,OAAO;GACR,CACD;EACD;EACA;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
1
+ {"version":3,"file":"collection.js","names":[],"sources":["../../src/goals/collection.ts"],"sourcesContent":["import type {\n\tCollectionBeforeValidateHook,\n\tCollectionConfig,\n\tCompoundIndex,\n\tField,\n\tPayloadRequest,\n\tTextFieldSingleValidation,\n} from 'payload'\nimport { ValidationError } from 'payload'\nimport { valueAt } from '../core/values'\nimport {\n\ttype CollectionFieldOverride,\n\thasNamedField,\n\toverrideField,\n\tpairInRow,\n} from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport type { ProviderAccessArgs } from '../providers/access'\nimport { providerCreateAccess, providerRowAccess } from '../providers/access'\nimport { takenInScope } from '../providers/scopeUnique'\nimport { stampScope } from '../providers/stampScope'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { amountField } from './amountField'\nimport { type AmountOf, amountCurrencyField } from './currency'\nimport { hiddenAdmin } from './moneyFields'\nimport { MAX_PATTERN_GLOBSTARS, MAX_PATTERN_SEGMENTS, patternProblem } from './pathMatch'\nimport { GOAL_SLUG_PATTERN } from './types'\n\nexport const GOALS_SLUG = 'analytics-goals'\n\n/**\n * Replaces one default field, receiving the plugin's own to spread. Any field type may come back, a\n * `row` included, as long as the slug override still holds a field named `slug`.\n */\nexport type GoalFieldOverride = CollectionFieldOverride\n\nexport interface GoalCollectionFieldOverrides {\n\tname?: GoalFieldOverride\n\tslug?: GoalFieldOverride\n\tenabled?: GoalFieldOverride\n\tbrowser?: GoalFieldOverride\n\tmatch?: GoalFieldOverride\n\tvalue?: GoalFieldOverride\n\tcurrency?: GoalFieldOverride\n}\n\nexport interface BuildGoalsCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: GoalCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Whether the install measures money, default on. False hides the amount and currency rather than\n\t * removing them, so existing amounts survive and show again when it is turned back on.\n\t */\n\trevenue?: boolean\n\t/**\n\t * The install's reporting currency when it is one fixed code. The Amount control fills it\n\t * in once an amount is set on a goal that has no currency yet.\n\t */\n\tdefaultCurrency?: string\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n}\n\nconst validateSlug: TextFieldSingleValidation = (value, { req }) =>\n\ttypeof value === 'string' && GOAL_SLUG_PATTERN.test(value)\n\t\t? true\n\t\t: asTranslate(req.t)(keys.goalErrorSlug)\n\n/** The matcher's caps, refused here so an editor hears about them rather than a goal never matching. */\nconst validatePattern: TextFieldSingleValidation = (value, { req }) =>\n\ttypeof value === 'string' && patternProblem(value) !== null\n\t\t? asTranslate(req.t)(keys.goalErrorPatternLimits, {\n\t\t\t\tsegments: MAX_PATTERN_SEGMENTS,\n\t\t\t\tglobstars: MAX_PATTERN_GLOBSTARS,\n\t\t\t})\n\t\t: true\n\nconst slugError = (collection: string, req: PayloadRequest, key: TranslationKey) =>\n\tnew ValidationError({\n\t\tcollection,\n\t\terrors: [\n\t\t\t{\n\t\t\t\tlabel: labelForKey(keys.goalFieldSlug),\n\t\t\t\tmessage: asTranslate(req.t)(key),\n\t\t\t\tpath: 'slug',\n\t\t\t},\n\t\t],\n\t})\n\n/**\n * Slug shape and per-scope uniqueness at collection level, so a replaced slug field without its own\n * `validate` keeps them; the index cannot cover install-wide Postgres rows or host scope fields.\n */\nconst checkSlug = (args: BuildGoalsCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tconst slug = data?.slug\n\t\tif (typeof slug !== 'string' || slug === '') {\n\t\t\treturn data\n\t\t}\n\t\tif (!GOAL_SLUG_PATTERN.test(slug)) {\n\t\t\tthrow slugError(args.slug, req, keys.goalErrorSlug)\n\t\t}\n\t\tif (await takenInScope(args, { data, originalDoc, req }, { slug: { equals: slug } })) {\n\t\t\tthrow slugError(args.slug, req, keys.goalErrorSlugTaken)\n\t\t}\n\t\treturn data\n\t}\n}\n\n/**\n * Database backstop for the hook, only where the plugin owns the scope field. Postgres treats a NULL\n * scope as distinct, so install-wide rows stay hook-guarded.\n */\nconst uniqueSlugIndex = (args: BuildGoalsCollectionArgs): CompoundIndex | undefined => {\n\tif (!args.scoped) {\n\t\treturn { fields: ['slug'], unique: true }\n\t}\n\treturn args.scopeField === 'scope' ? { fields: ['slug', 'scope'], unique: true } : undefined\n}\n\n/**\n * The plugin's scope field, only while `scopeField` names it: a host-owned field is the host's to\n * register, and a hidden twin would store the scope twice.\n */\nconst scopeField = (args: BuildGoalsCollectionArgs): Field[] =>\n\targs.scopeField === 'scope'\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.goalFieldName),\n\tadmin: { width: '50%', description: labelForKey(keys.goalFieldNameHelp) },\n})\n\nconst slugField = (indexed: boolean): Field => ({\n\tname: 'slug',\n\ttype: 'text',\n\trequired: true,\n\t// Mongoose refuses a field index and a compound index that share a key spec, and the\n\t// compound one already covers a lookup by slug.\n\tindex: indexed,\n\tlabel: labelForKey(keys.goalFieldSlug),\n\tvalidate: validateSlug,\n\tadmin: { width: '50%', description: labelForKey(keys.goalFieldSlugHelp) },\n})\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.goalFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.goalFieldEnabledHelp) },\n})\n\n/** Off for a goal only server code completes: a browser's completion of it is then ignored. */\nconst browserField = (): Field => ({\n\tname: 'browser',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.goalFieldBrowser),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.goalFieldBrowserHelp) },\n})\n\nconst matchField = (staticLabel: StaticLabelFor): Field => ({\n\tname: 'match',\n\ttype: 'group',\n\tlabel: labelForKey(keys.goalFieldMatch),\n\tfields: [\n\t\t{\n\t\t\tname: 'kind',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\tdefaultValue: 'goal',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchKind),\n\t\t\t// `admin.description` on a select is read where a label function never runs, so the\n\t\t\t// three kinds are explained through the locale map instead.\n\t\t\tadmin: { description: staticLabel(keys.goalFieldMatchKindHelp) },\n\t\t\toptions: [\n\t\t\t\t{ label: labelForKey(keys.goalKindGoal), value: 'goal' },\n\t\t\t\t{ label: labelForKey(keys.goalKindEvent), value: 'event' },\n\t\t\t\t{ label: labelForKey(keys.goalKindPath), value: 'path' },\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tname: 'name',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchEventName),\n\t\t\tadmin: {\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.kind === 'event',\n\t\t\t\tdescription: labelForKey(keys.goalFieldMatchEventNameHelp),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'pattern',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldMatchPathPattern),\n\t\t\tvalidate: validatePattern,\n\t\t\tadmin: {\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.kind === 'path',\n\t\t\t\tdescription: labelForKey(keys.goalFieldMatchPathPatternHelp),\n\t\t\t},\n\t\t},\n\t],\n})\n\n/**\n * The amount and where else it may come from, with no heading of their own so they read as\n * part of the goal. The currency is the sibling `currency` field, edited in the Amount control.\n */\nconst valueField = (defaultCurrency: string | undefined): Field => ({\n\tname: 'value',\n\ttype: 'group',\n\tlabel: false,\n\tadmin: { hideGutter: true },\n\tfields: [\n\t\tamountField(\n\t\t\t{\n\t\t\t\tname: 'fixed',\n\t\t\t\ttype: 'number',\n\t\t\t\tmin: 0,\n\t\t\t\tlabel: labelForKey(keys.goalFieldAmount),\n\t\t\t\tadmin: { description: labelForKey(keys.goalFieldAmountHelp) },\n\t\t\t},\n\t\t\t{ currencyPath: '../currency', defaultCurrency }\n\t\t),\n\t\t{\n\t\t\tname: 'prop',\n\t\t\ttype: 'text',\n\t\t\tlabel: labelForKey(keys.goalFieldAmountProp),\n\t\t\tadmin: {\n\t\t\t\tdescription: labelForKey(keys.goalFieldAmountPropHelp),\n\t\t\t\t// Only an action's own details can carry an amount to read.\n\t\t\t\tcondition: (data) => data?.match?.kind === 'event',\n\t\t\t},\n\t\t},\n\t],\n})\n\n/** The amount a goal's currency belongs to: its fixed amount. */\nconst fixedAmount: AmountOf = ({ data }) => valueAt(data, 'value.fixed')\n\n/**\n * Hidden rather than removed while the install measures no money, a replacement included: the\n * field stays in the schema, so a goal that already carries an amount keeps it.\n */\nconst moneyOnly = (field: Field, revenue: boolean | undefined): Field =>\n\trevenue === false ? Object.assign({}, field, { admin: hiddenAdmin(field) }) : field\n\n/**\n * Name and slug share the first row while both are plain named fields; a layout or sidebar\n * replacement cannot live in a row, so it goes top level at its declared position.\n */\nconst layout = (args: BuildGoalsCollectionArgs, indexed: boolean): Field[] => [\n\t...pairInRow(\n\t\toverrideField(nameField(), args.fields?.name),\n\t\toverrideField(slugField(indexed), args.fields?.slug)\n\t),\n\toverrideField(enabledField(), args.fields?.enabled),\n\toverrideField(browserField(), args.fields?.browser),\n\toverrideField(matchField(args.staticLabel ?? builtInStaticLabel), args.fields?.match),\n\tmoneyOnly(overrideField(valueField(args.defaultCurrency), args.fields?.value), args.revenue),\n\tmoneyOnly(overrideField(amountCurrencyField(fixedAmount), args.fields?.currency), args.revenue),\n\t...scopeField(args),\n]\n\n/**\n * The editor-managed goals collection, one document per goal and scope, merged over config goals.\n * Admin-only by default; `access`, `fields` and finally `overrides` reshape it.\n */\nexport const buildGoalsCollection = (args: BuildGoalsCollectionArgs): CollectionConfig => {\n\tconst unique = uniqueSlugIndex(args)\n\tconst fields = layout(args, unique === undefined)\n\tif (!hasNamedField(fields, 'slug')) {\n\t\tthrow new Error(\n\t\t\t`analytics: goals.collection.fields.slug must return a field named \"slug\" (a row or group containing one is fine); the goals collection \"${args.slug}\" keys every report on that value`\n\t\t)\n\t}\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\t...(unique ? { indexes: [unique] } : {}),\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.goalsCollectionSingular),\n\t\t\tplural: labelForKey(keys.goalsCollectionPlural),\n\t\t},\n\t\t// A duplicate would carry the slug over, which the uniqueness hook refuses anyway.\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'slug', 'match.kind', 'enabled'],\n\t\t\tgroup: (args.staticLabel ?? builtInStaticLabel)(keys.adminGroup),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\tbeforeValidate: [checkSlug(args)],\n\t\t\tbeforeChange: [stampScope(args)],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields,\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,MAAa,aAAa;AA2C1B,MAAM,gBAA2C,OAAO,EAAE,UACzD,OAAO,UAAU,YAAY,kBAAkB,KAAK,KAAK,IACtD,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,aAAa;;AAGzC,MAAM,mBAA8C,OAAO,EAAE,UAC5D,OAAO,UAAU,YAAY,eAAe,KAAK,MAAM,OACpD,YAAY,IAAI,CAAC,EAAE,KAAK,wBAAwB;CAChD,UAAA;CACA,WAAA;AACD,CAAC,IACA;AAEJ,MAAM,aAAa,YAAoB,KAAqB,QAC3D,IAAI,gBAAgB;CACnB;CACA,QAAQ,CACP;EACC,OAAO,YAAY,KAAK,aAAa;EACrC,SAAS,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qBAAqB;EAC/C;EAEA,kBAAkB;EAClB,OAAO;GACN,YAAY;GACZ,gBAAgB;IAAC;IAAQ;IAAQ;IAAc;GAAS;GACxD,QAAQ,KAAK,eAAe,oBAAoB,KAAK,UAAU;EAChE;EACA,QAAQ;GACP,MAAM,kBAAkB,IAAI;GAC5B,QAAQ,qBAAqB,IAAI;GACjC,QAAQ,kBAAkB,IAAI;GAC9B,QAAQ,kBAAkB,IAAI;GAC9B,GAAG,KAAK;EACT;EACA,OAAO;GACN,gBAAgB,CAAC,UAAU,IAAI,CAAC;GAChC,cAAc,CAAC,WAAW,IAAI,CAAC;GAC/B,aAAa,CACZ,OAAO,EAAE,KAAK,WAAW,aAAa,UAAU;IAC/C,MAAM,KAAK,SACV;KACC,OAAO,SAAS,KAAK,KAAK,UAAU;KACpC,GAAI,cAAc,WACf,EAAE,eAAe,SAAS,aAAa,KAAK,UAAU,EAAE,IACxD,CAAC;IACL,GACA,GACD;IACA,OAAO;GACR,CACD;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,UAAU;IACvB,MAAM,KAAK,SAAS,EAAE,OAAO,SAAS,KAAK,KAAK,UAAU,EAAE,GAAG,GAAG;IAClE,OAAO;GACR,CACD;EACD;EACA;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
@@ -4,11 +4,11 @@ import { currentTime } from "../core/clock.js";
4
4
  import { recall, remember } from "../surfacing/bounded.js";
5
5
  import { createEpochFallback } from "../surfacing/epoch.js";
6
6
  import { asTranslate } from "../translations/server.js";
7
+ import { GOAL_SLUG_PATTERN } from "./types.js";
7
8
  import { isCollectionSlug } from "../core/collectionSlug.js";
8
9
  import { PROBE_MEMO_MS, createCollectionProbe } from "../providers/probe.js";
9
10
  import "./constants.js";
10
11
  import { builtinPurchaseGoal } from "./builtin.js";
11
- import { GOAL_SLUG_PATTERN } from "./types.js";
12
12
  //#region src/goals/resolver.ts
13
13
  /** The most enabled goals one scope's read takes: a ceiling, not a page size. */
14
14
  const MAX_GOALS = 500;
@@ -250,6 +250,6 @@ const createGoalsResolver = (args) => {
250
250
  };
251
251
  };
252
252
  //#endregion
253
- export { configGoalsResolver, createGoalsResolver, goalScopeWhere };
253
+ export { configGoalsResolver, createGoalsResolver };
254
254
 
255
255
  //# sourceMappingURL=resolver.js.map
@@ -6,8 +6,8 @@ import { labelForKey } from "../translations/server.js";
6
6
  import { CURRENCY_PATTERN, amountCurrencyField } from "./currency.js";
7
7
  import { amountField } from "./amountField.js";
8
8
  import { applyRevenueVisibility, moneyField } from "./moneyFields.js";
9
- import { GOAL_ACTION_TYPE } from "./constants.js";
10
9
  import { finiteNumber } from "./match.js";
10
+ import { GOAL_ACTION_TYPE } from "./constants.js";
11
11
  import { AnalyticsTrackError } from "../core/serverEvent.js";
12
12
  import { ingestAdapter, trackServerEvent } from "../native/ingest/serverTrack.js";
13
13
  import { goalField, goalSlug } from "./goalField.js";
package/dist/index.d.ts CHANGED
@@ -15,14 +15,14 @@ import { AnalyticsAttributes } from "./exports/attributes.js";
15
15
  import { ItemSignatureMode, itemAttributesFor, signItemRef } from "./native/ingest/itemSignature.js";
16
16
  import { RawEventInput } from "./native/ingest/normalizeEvent.js";
17
17
  import { AnalyticsTrackError, IngestHostnameResolver, ServerEventInput, ServerTrack, ServerTrackIdentity, ServerTrackOptions } from "./core/serverEvent.js";
18
- import { AdapterContext, AdapterRegisterContext, AdapterSchemaContext, AnalyticsAdapter, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DIMENSION_KEYS, DateRange, DimensionKey, FILTER_OPERATORS, FilterOperator, FilterOperatorMap, Granularity, MetricKey, MetricReach, MetricSemantics, MetricValue, MetricValues, PLATFORM_SCOPE, RateLimitDescriptor, SourceErrorKind, VisitorCounting } from "./core/contract.js";
18
+ import { AdapterContext, AdapterLabelArgs, AdapterRegisterContext, AdapterSchemaContext, AnalyticsAdapter, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DIMENSION_KEYS, DateRange, DimensionKey, FILTER_OPERATORS, FilterOperator, FilterOperatorMap, Granularity, MetricKey, MetricReach, MetricSemantics, MetricValue, MetricValues, PLATFORM_SCOPE, RateLimitDescriptor, SourceErrorKind, VisitorCounting } from "./core/contract.js";
19
+ import { AnalyticsSourceOptions, DefaultSourceFunction, DefaultSourceRule, OwnSource, SourcePolicy, SourcePolicyFunction, SourceRef } from "./core/sourcePolicy.js";
20
+ import { AdapterLabelOption } from "./core/sourceLabel.js";
19
21
  import { STATE_SLUG } from "./native/collections/slugs.js";
20
22
  import { RebuildDaysInput, RebuildDaysReport } from "./native/engine/rebuild.js";
21
23
  import { CapabilityRequirement, FilterPair, SerializedCapabilities } from "./core/capabilities.js";
22
- import { GoalSource } from "./goals/resolver.js";
23
- import { GoalsResponse, WireGoal } from "./goals/fetchGoals.js";
24
+ import { GatedScope, ReadPrincipal, SYSTEM } from "./access/principal.js";
24
25
  import { ANALYTICS_ERROR_CODES, AnalyticsError, AnalyticsErrorCode, analyticsError, readErrorCode } from "./plugin/errors.js";
25
- import { TIMEFRAME_PRESETS, TimeframePreset } from "./timeframe/presets.js";
26
26
  import { QueryError, QueryErrorCode } from "./query/errors.js";
27
27
  import { ItemLabels, QueryErrorResponse, QueryResponse, QuerySourceRef, SerializedAnalyticsQuery } from "./query/response.js";
28
28
  import { AnalyticsBinding, BindingContext, BindingDoc, HostnameResolver, PathResolver } from "./binding/types.js";
@@ -30,22 +30,25 @@ import { CollectionFieldOverride } from "./plugin/collectionFields.js";
30
30
  import { PluralCategory, PluralName, PluralVariant, SingularKey, TranslationKey, keys, pluralKeys } from "./translations/keys.js";
31
31
  import { TranslationsOption } from "./translations/index.js";
32
32
  import { GOALS_SLUG, GoalCollectionFieldOverrides, GoalFieldOverride } from "./goals/collection.js";
33
- import { CacheEntry, CacheSetOptions, CacheStore, ReadRecipe, RecipeWindow } from "./surfacing/cacheStore.js";
34
- import { AfterReadAnswer, AfterReadArgs, AfterReadHook, ReadOrigin } from "./surfacing/afterRead.js";
35
- import { BuildSecretField, ConnectionAccess, ConnectionFieldAccess, PROVIDERS_SLUG, ProviderCollectionFieldOverrides, ProviderFieldOverride, ProviderFieldsOptions, analyticsProviderFields } from "./providers/collection.js";
36
33
  import { HostPattern, ProviderHostPolicy, resolveHostPolicy } from "./providers/hosts.js";
34
+ import { PROVIDER_IDS, ProviderDoc, ProviderFactoryContext, ProviderId, adapterFromProviderDoc } from "./providers/factory.js";
35
+ import { BuildSecretField, ConnectionAccess, ConnectionFieldAccess, PROVIDERS_SLUG, ProviderCollectionFieldOverrides, ProviderFieldOverride, ProviderFieldsOptions, analyticsProviderFields } from "./providers/collection.js";
36
+ import { AfterReadAnswer, AfterReadArgs, AfterReadHook, ReadOrigin } from "./surfacing/afterRead.js";
37
+ import { TIMEFRAME_PRESETS, TimeframePreset } from "./timeframe/presets.js";
38
+ import { CacheEntry, CacheSetOptions, CacheStore, ReadRecipe, RecipeWindow } from "./surfacing/cacheStore.js";
37
39
  import { CustomWidgetDef } from "./widgets/customWidget.js";
38
40
  import { BUILT_IN_WIDGET_SLUGS, BuiltInWidgetSlug } from "./core/widgetSlugs.js";
39
41
  import { AnalyticsAccessOptions, AnalyticsCacheCollectionOptions, AnalyticsCacheOptions, AnalyticsCaptureOptions, AnalyticsComponent, AnalyticsConcurrencyOptions, AnalyticsCountryFlags, AnalyticsCrossScopeOptions, AnalyticsExclusionOptions, AnalyticsGoalsCollectionOptions, AnalyticsGoalsOptions, AnalyticsHooksOptions, AnalyticsPluginOptions, AnalyticsReadAccess, AnalyticsRevenueOptions, AnalyticsRoutesOptions, AnalyticsScopeOptions, AnalyticsSyncCollectionOptions, AnalyticsSyncOptions, AnalyticsViewAccess, AnalyticsViewOptions, AnalyticsWarmOptions, AnalyticsWidgetOverride, AnalyticsWidgetOverrides, AnalyticsWidgetsOptions, AutoCaptureOptions, CaptureGate, CaptureGateArgs, CaptureSlotOption, CrossScopeAccess, CurrencyResolver, ExclusionSitesResolver, ItemCaptureOptions, ProviderHostsOptions, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ProvidersResolveArgs, ScopeCallSite, ScopeLabelResolver, ScopeListResolver, ScopeMemberAccess, ScopeResolver, TimezoneResolver } from "./core/options.js";
42
+ import { GoalSource } from "./goals/resolver.js";
43
+ import { GoalsResponse, WireGoal } from "./goals/fetchGoals.js";
40
44
  import { ReadNotices } from "./widgets/readMeta.js";
41
- import { GatedScope, ReadPrincipal, SYSTEM } from "./access/principal.js";
45
+ import { StoredSourceRead, SubstitutedSource, WidgetReadStatus } from "./widgets/prepareWidgetRead.js";
42
46
  import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "./widgets/readForWidgetRealtime.js";
43
47
  import { ReportMode, ReportOption } from "./binding/report.js";
44
48
  import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatBaseOptions, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField } from "./fields/factories.js";
45
49
  import { SeriesGranularity, SeriesPoint } from "./charts/series.js";
46
50
  import { FieldBreakdown, FieldBreakdownRow, FieldReadResult, FieldReadStatus, ReadForFieldArgs, readForField } from "./fields/readForDocument.js";
47
51
  import { WidgetFilter } from "./widgets/types.js";
48
- import { WidgetReadStatus } from "./widgets/prepareWidgetRead.js";
49
52
  import { ReadForWidgetArgs, WidgetReadResult, readForWidget } from "./widgets/readForWidget.js";
50
53
  import { BreakdownRow, ReadForWidgetBreakdownArgs, WidgetBreakdownResult, readForWidgetBreakdown } from "./widgets/readForWidgetBreakdown.js";
51
54
  import { GoalRow, ReadForWidgetGoalsArgs, WidgetGoalsResult, readForWidgetGoals } from "./widgets/readForWidgetGoals.js";
@@ -61,11 +64,11 @@ import { signOrderId } from "./native/ingest/orderSignature.js";
61
64
  import { trackServerEvent } from "./native/ingest/serverTrack.js";
62
65
  import { rebuildDays } from "./native/rebuildDays.js";
63
66
  import { GuardedFetch, GuardedFetchOptions, createGuardedFetch } from "./net/guardedFetch.js";
64
- import { PROVIDER_IDS, ProviderDoc, ProviderFactoryContext, ProviderId, adapterFromProviderDoc } from "./providers/factory.js";
65
67
  import { RefreshProvidersOptions, refreshProviders } from "./providers/refresh.js";
66
68
  import { CONNECTION_PATHS, SECRET_PATHS } from "./providers/secrets.js";
67
69
  import { CACHE_SLUG } from "./surfacing/cacheCollection.js";
68
70
  import { SYNC_SLUG } from "./sync/collection.js";
71
+ import { AnalyticsDefaultLayoutOptions, analyticsDefaultLayout } from "./widgets/defaultLayout.js";
69
72
  import { analyticsDefaultWidgets } from "./widgets/defaults.js";
70
73
  import { widgetFilters } from "./widgets/filterField.js";
71
74
 
@@ -77,5 +80,5 @@ declare module 'payload' {
77
80
  }
78
81
  declare const analytics: (options: AnalyticsPluginOptions) => import("payload").Plugin;
79
82
  //#endregion
80
- export { ANALYTICS_ERROR_CODES, type AdapterContext, type AdapterJobs, type AdapterRegisterContext, type AdapterSchemaContext, type AfterReadAnswer, type AfterReadArgs, type AfterReadHook, type AnalyticsAccessOptions, type AnalyticsAdapter, type AnalyticsAttributes, type AnalyticsBinding, type AnalyticsCacheCollectionOptions, type AnalyticsCacheOptions, type AnalyticsCapabilities, type AnalyticsCaptureOptions, type AnalyticsCollectionOptions, type AnalyticsComponent, type AnalyticsConcurrencyOptions, type AnalyticsCountryFlags, type AnalyticsCrossScopeOptions, type AnalyticsError, type AnalyticsErrorCode, type AnalyticsExclusionOptions, type AnalyticsFieldsOptions, type AnalyticsFilter, type AnalyticsGoalsCollectionOptions, type AnalyticsGoalsOptions, type AnalyticsHooksOptions, type AnalyticsJobsOptions, type AnalyticsLinkFieldsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsQuery, type AnalyticsReadAccess, type AnalyticsResult, type AnalyticsRevenueOptions, type AnalyticsRoutesOptions, type AnalyticsRow, type AnalyticsScopeOptions, type AnalyticsSdks, type AnalyticsStatBaseOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsSyncCollectionOptions, type AnalyticsSyncOptions, type AnalyticsTabOptions, type AnalyticsTaskName, type AnalyticsTaskOptions, AnalyticsTrackError, type AnalyticsViewAccess, type AnalyticsViewOptions, type AnalyticsWarmOptions, type AnalyticsWidgetOverride, type AnalyticsWidgetOverrides, type AnalyticsWidgetsOptions, type AutoCaptureOptions, BUILT_IN_WIDGET_SLUGS, type BindingContext, type BindingDoc, type BreakdownRow, type BrowserAmounts, type BuildSecretField, type BuiltInWidgetSlug, CACHE_SLUG, CONNECTION_PATHS, CURRENCY_ATTRIBUTE, type CacheEntry, type CacheSetOptions, type CacheStore, type CapabilityRequirement, type CaptureClientKind, type CaptureGate, type CaptureGateArgs, type CaptureSlot, type CaptureSlotOption, type CaptureSnippet, type CaptureSupport, type CollectionFieldOverride, type CollectionOverrides, type ConnectionAccess, type ConnectionFieldAccess, type CrossScopeAccess, type CurrencyConverter, type CurrencyResolver, type CustomWidgetDef, DEFAULT_ROUTE_BASE, type DIMENSION_KEYS, type DateRange, type DimensionKey, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, type ExclusionSitesResolver, type FILTER_OPERATORS, type FetchInit, type FetchLike, type FieldBreakdown, type FieldBreakdownRow, type FieldReadResult, type FieldReadStatus, type FilterOperator, type FilterOperatorMap, type FilterPair, GOALS_SLUG, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, type Ga4Client, type Ga4ClientOptions, type Ga4ReportResponse, type Ga4ReportRow, type Ga4Sdk, type GatedScope, type Goal, type GoalActionDefinition, type GoalActionRunArgs, type GoalCollectionFieldOverrides, type GoalFieldOptions, type GoalFieldOverride, type GoalMatch, type GoalRow, type GoalSource, type GoalsResponse, type Granularity, type GuardedFetch, type GuardedFetchOptions, type HitType, type HostPattern, type HostnameResolver, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, type IngestHostnameResolver, type ItemCaptureOptions, type ItemLabels, type ItemSignatureMode, MAX_ITEMS_PER_BEACON, type MaxmindReader, type MaxmindSdk, type MetricKey, type MetricReach, type MetricSemantics, type MetricValue, type MetricValues, type OrderSignatureMode, PLATFORM_SCOPE, PROVIDERS_SLUG, PROVIDER_IDS, PURCHASE_GOAL_SLUG, type PathResolver, type AnalyticsPluginOptions as PluginOptions, type PluralCategory, type PluralName, type PluralVariant, type ProviderCollectionFieldOverrides, type ProviderDoc, type ProviderFactoryContext, type ProviderFieldOverride, type ProviderFieldsOptions, type ProviderHostPolicy, type ProviderHostsOptions, ProviderHttpError, type ProviderId, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ProvidersResolveArgs, type ProxyDescriptor, type ProxyRoute, type ProxyRouteKind, type QueryError, type QueryErrorCode, type QueryErrorResponse, type QueryResponse, type QuerySourceRef, type RateLimitDescriptor, type RawEventInput, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetGoalsArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type ReadNotices, type ReadOrigin, type ReadPrincipal, type ReadRecipe, type RealtimePoint, type RebuildDaysInput, type RebuildDaysReport, type RecipeWindow, type RefreshProvidersOptions, type ReportMode, type ReportOption, type RevenueItem, type RouteBase, type RoutePaths, type RoutesConfigSource, SECRET_PATHS, STATE_SLUG, SYNC_SLUG, SYSTEM, type ScheduledTask, type ScopeCallSite, type ScopeLabelResolver, type ScopeListResolver, type ScopeMemberAccess, type ScopeResolver, type SerializedAnalyticsQuery, type SerializedCapabilities, type SeriesGranularity, type SeriesPoint, type ServerEventInput, type PurchaseInput as ServerPurchaseInput, type RefundInput as ServerRefundInput, type ServerTrack, type ServerTrackIdentity, type ServerTrackOptions, type SingularKey, type SnippetScript, type SourceErrorKind, type TASK_NAMES, TIMEFRAME_PRESETS, type TenantMembershipOptions, type TimeframePreset, type TimezoneResolver, type TrackGoalActionOptions, type TrackerGoal, type TrackerSlotConfig, type TranslationKey, type TranslationsOption, type TrustedPlatform, VALUE_ATTRIBUTE, type VisitorCounting, type WidgetBreakdownResult, type WidgetFilter, type WidgetGoalsResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, type WireGoal, adapterFromProviderDoc, analytics, analyticsDefaultWidgets, analyticsError, analyticsFields, analyticsLinkFields, analyticsProviderFields, analyticsRoutes, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, createGuardedFetch, goalField, goalSlug, isAdminUser, itemAttributesFor, keys, parseRetryAfter, pluralKeys, purchase, readErrorCode, readForField, readForWidget, readForWidgetBreakdown, readForWidgetGoals, readForWidgetRealtime, readForWidgetSeries, rebuildDays, refreshProviders, refund, resolveHostPolicy, routePaths, signItemRef, signOrderId, tenantMembership, trackGoalAction, trackServerEvent, widgetFilters };
83
+ export { ANALYTICS_ERROR_CODES, type AdapterContext, type AdapterJobs, type AdapterLabelArgs, type AdapterLabelOption, type AdapterRegisterContext, type AdapterSchemaContext, type AfterReadAnswer, type AfterReadArgs, type AfterReadHook, type AnalyticsAccessOptions, type AnalyticsAdapter, type AnalyticsAttributes, type AnalyticsBinding, type AnalyticsCacheCollectionOptions, type AnalyticsCacheOptions, type AnalyticsCapabilities, type AnalyticsCaptureOptions, type AnalyticsCollectionOptions, type AnalyticsComponent, type AnalyticsConcurrencyOptions, type AnalyticsCountryFlags, type AnalyticsCrossScopeOptions, type AnalyticsDefaultLayoutOptions, type AnalyticsError, type AnalyticsErrorCode, type AnalyticsExclusionOptions, type AnalyticsFieldsOptions, type AnalyticsFilter, type AnalyticsGoalsCollectionOptions, type AnalyticsGoalsOptions, type AnalyticsHooksOptions, type AnalyticsJobsOptions, type AnalyticsLinkFieldsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsQuery, type AnalyticsReadAccess, type AnalyticsResult, type AnalyticsRevenueOptions, type AnalyticsRoutesOptions, type AnalyticsRow, type AnalyticsScopeOptions, type AnalyticsSdks, type AnalyticsSourceOptions, type AnalyticsStatBaseOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsSyncCollectionOptions, type AnalyticsSyncOptions, type AnalyticsTabOptions, type AnalyticsTaskName, type AnalyticsTaskOptions, AnalyticsTrackError, type AnalyticsViewAccess, type AnalyticsViewOptions, type AnalyticsWarmOptions, type AnalyticsWidgetOverride, type AnalyticsWidgetOverrides, type AnalyticsWidgetsOptions, type AutoCaptureOptions, BUILT_IN_WIDGET_SLUGS, type BindingContext, type BindingDoc, type BreakdownRow, type BrowserAmounts, type BuildSecretField, type BuiltInWidgetSlug, CACHE_SLUG, CONNECTION_PATHS, CURRENCY_ATTRIBUTE, type CacheEntry, type CacheSetOptions, type CacheStore, type CapabilityRequirement, type CaptureClientKind, type CaptureGate, type CaptureGateArgs, type CaptureSlot, type CaptureSlotOption, type CaptureSnippet, type CaptureSupport, type CollectionFieldOverride, type CollectionOverrides, type ConnectionAccess, type ConnectionFieldAccess, type CrossScopeAccess, type CurrencyConverter, type CurrencyResolver, type CustomWidgetDef, DEFAULT_ROUTE_BASE, type DIMENSION_KEYS, type DateRange, type DefaultSourceFunction, type DefaultSourceRule, type DimensionKey, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, type ExclusionSitesResolver, type FILTER_OPERATORS, type FetchInit, type FetchLike, type FieldBreakdown, type FieldBreakdownRow, type FieldReadResult, type FieldReadStatus, type FilterOperator, type FilterOperatorMap, type FilterPair, GOALS_SLUG, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, type Ga4Client, type Ga4ClientOptions, type Ga4ReportResponse, type Ga4ReportRow, type Ga4Sdk, type GatedScope, type Goal, type GoalActionDefinition, type GoalActionRunArgs, type GoalCollectionFieldOverrides, type GoalFieldOptions, type GoalFieldOverride, type GoalMatch, type GoalRow, type GoalSource, type GoalsResponse, type Granularity, type GuardedFetch, type GuardedFetchOptions, type HitType, type HostPattern, type HostnameResolver, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, type IngestHostnameResolver, type ItemCaptureOptions, type ItemLabels, type ItemSignatureMode, MAX_ITEMS_PER_BEACON, type MaxmindReader, type MaxmindSdk, type MetricKey, type MetricReach, type MetricSemantics, type MetricValue, type MetricValues, type OrderSignatureMode, type OwnSource, PLATFORM_SCOPE, PROVIDERS_SLUG, PROVIDER_IDS, PURCHASE_GOAL_SLUG, type PathResolver, type AnalyticsPluginOptions as PluginOptions, type PluralCategory, type PluralName, type PluralVariant, type ProviderCollectionFieldOverrides, type ProviderDoc, type ProviderFactoryContext, type ProviderFieldOverride, type ProviderFieldsOptions, type ProviderHostPolicy, type ProviderHostsOptions, ProviderHttpError, type ProviderId, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ProvidersResolveArgs, type ProxyDescriptor, type ProxyRoute, type ProxyRouteKind, type QueryError, type QueryErrorCode, type QueryErrorResponse, type QueryResponse, type QuerySourceRef, type RateLimitDescriptor, type RawEventInput, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetGoalsArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type ReadNotices, type ReadOrigin, type ReadPrincipal, type ReadRecipe, type RealtimePoint, type RebuildDaysInput, type RebuildDaysReport, type RecipeWindow, type RefreshProvidersOptions, type ReportMode, type ReportOption, type RevenueItem, type RouteBase, type RoutePaths, type RoutesConfigSource, SECRET_PATHS, STATE_SLUG, SYNC_SLUG, SYSTEM, type ScheduledTask, type ScopeCallSite, type ScopeLabelResolver, type ScopeListResolver, type ScopeMemberAccess, type ScopeResolver, type SerializedAnalyticsQuery, type SerializedCapabilities, type SeriesGranularity, type SeriesPoint, type ServerEventInput, type PurchaseInput as ServerPurchaseInput, type RefundInput as ServerRefundInput, type ServerTrack, type ServerTrackIdentity, type ServerTrackOptions, type SingularKey, type SnippetScript, type SourceErrorKind, type SourcePolicy, type SourcePolicyFunction, type SourceRef, type StoredSourceRead, type SubstitutedSource, type TASK_NAMES, TIMEFRAME_PRESETS, type TenantMembershipOptions, type TimeframePreset, type TimezoneResolver, type TrackGoalActionOptions, type TrackerGoal, type TrackerSlotConfig, type TranslationKey, type TranslationsOption, type TrustedPlatform, VALUE_ATTRIBUTE, type VisitorCounting, type WidgetBreakdownResult, type WidgetFilter, type WidgetGoalsResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, type WireGoal, adapterFromProviderDoc, analytics, analyticsDefaultLayout, analyticsDefaultWidgets, analyticsError, analyticsFields, analyticsLinkFields, analyticsProviderFields, analyticsRoutes, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, createGuardedFetch, goalField, goalSlug, isAdminUser, itemAttributesFor, keys, parseRetryAfter, pluralKeys, purchase, readErrorCode, readForField, readForWidget, readForWidgetBreakdown, readForWidgetGoals, readForWidgetRealtime, readForWidgetSeries, rebuildDays, refreshProviders, refund, resolveHostPolicy, routePaths, signItemRef, signOrderId, tenantMembership, trackGoalAction, trackServerEvent, widgetFilters };
81
84
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -21,15 +21,17 @@ import { createStaticLabels } from "./translations/staticLabel.js";
21
21
  import { SYNC_SLUG } from "./sync/collection.js";
22
22
  import { CURRENCY_PATTERN } from "./goals/currency.js";
23
23
  import { changedScopes } from "./plugin/scopeChange.js";
24
+ import { ProviderHttpError, parseRetryAfter } from "./adapters/http/fetchJson.js";
24
25
  import { resolveHostPolicy } from "./providers/hosts.js";
26
+ import { PROVIDER_IDS, adapterFromProviderDoc } from "./providers/factory.js";
25
27
  import { CONNECTION_PATHS, SECRET_PATHS } from "./providers/secrets.js";
26
28
  import { PROVIDERS_SLUG, analyticsProviderFields } from "./providers/collection.js";
27
29
  import { applyConfigRevenueVisibility } from "./goals/moneyFields.js";
28
- import { CURRENCY_ATTRIBUTE, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, MAX_ITEMS_PER_BEACON, PURCHASE_GOAL_SLUG, VALUE_ATTRIBUTE } from "./goals/constants.js";
29
- import { configGoalsResolver } from "./goals/resolver.js";
30
30
  import { GOALS_SLUG } from "./goals/collection.js";
31
31
  import { resolveOptions } from "./core/options.js";
32
32
  import { makeGoalsHandler } from "./goals/goalsEndpoint.js";
33
+ import { CURRENCY_ATTRIBUTE, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, MAX_ITEMS_PER_BEACON, PURCHASE_GOAL_SLUG, VALUE_ATTRIBUTE } from "./goals/constants.js";
34
+ import { configGoalsResolver } from "./goals/resolver.js";
33
35
  import { FLAG_DEPENDENCY, addComponentDependency } from "./plugin/adminDependencies.js";
34
36
  import { expectedCollections } from "./plugin/collectionChecks.js";
35
37
  import { AnalyticsTrackError } from "./core/serverEvent.js";
@@ -45,8 +47,6 @@ import { addTask, schemaOnly } from "./plugin/schemaOnly.js";
45
47
  import { signOrderId } from "./native/ingest/orderSignature.js";
46
48
  import { createGuardedFetch } from "./net/guardedFetch.js";
47
49
  import { refreshProviders } from "./providers/refresh.js";
48
- import { ProviderHttpError, parseRetryAfter } from "./adapters/http/fetchJson.js";
49
- import { PROVIDER_IDS, adapterFromProviderDoc } from "./providers/factory.js";
50
50
  import { assertRoutesReachable } from "./plugin/routeChecks.js";
51
51
  import { createRuntimeFactory } from "./plugin/createRuntime.js";
52
52
  import { readForField } from "./fields/readForDocument.js";
@@ -69,6 +69,7 @@ import { purchase, refund } from "./goals/serverRevenue.js";
69
69
  import { trackGoalAction } from "./goals/trackGoalAction.js";
70
70
  import { rebuildDays } from "./native/rebuildDays.js";
71
71
  import { analyticsDefaultWidgets } from "./widgets/defaults.js";
72
+ import { analyticsDefaultLayout } from "./widgets/defaultLayout.js";
72
73
  import { readForWidget } from "./widgets/readForWidget.js";
73
74
  import { readForWidgetBreakdown } from "./widgets/readForWidgetBreakdown.js";
74
75
  import { readForWidgetGoals } from "./widgets/readForWidgetGoals.js";
@@ -331,6 +332,6 @@ const analytics = definePlugin({
331
332
  /** Said at boot when a step after the plugin dropped its runtime from `config.custom`. */
332
333
  const RUNTIME_FACTORY_LOST = `analytics: config.custom["${ANALYTICS_CONFIG_KEY}"] no longer holds the analytics runtime: a plugin or config step that runs after analytics replaced config.custom instead of spreading it. Spread the existing value there ({ ...config.custom, ... }), or list analytics after that plugin.`;
333
334
  //#endregion
334
- export { ANALYTICS_ERROR_CODES, AnalyticsTrackError, BUILT_IN_WIDGET_SLUGS, CACHE_SLUG, CONNECTION_PATHS, CURRENCY_ATTRIBUTE, DEFAULT_ROUTE_BASE, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, GOALS_SLUG, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, MAX_ITEMS_PER_BEACON, PLATFORM_SCOPE, PROVIDERS_SLUG, PROVIDER_IDS, PURCHASE_GOAL_SLUG, ProviderHttpError, SECRET_PATHS, STATE_SLUG, SYNC_SLUG, SYSTEM, TIMEFRAME_PRESETS, VALUE_ATTRIBUTE, adapterFromProviderDoc, analytics, analyticsDefaultWidgets, analyticsError, analyticsFields, analyticsLinkFields, analyticsProviderFields, analyticsRoutes, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, createGuardedFetch, goalField, goalSlug, isAdminUser, itemAttributesFor, keys, parseRetryAfter, pluralKeys, purchase, readErrorCode, readForField, readForWidget, readForWidgetBreakdown, readForWidgetGoals, readForWidgetRealtime, readForWidgetSeries, rebuildDays, refreshProviders, refund, resolveHostPolicy, routePaths, signItemRef, signOrderId, tenantMembership, trackGoalAction, trackServerEvent, widgetFilters };
335
+ export { ANALYTICS_ERROR_CODES, AnalyticsTrackError, BUILT_IN_WIDGET_SLUGS, CACHE_SLUG, CONNECTION_PATHS, CURRENCY_ATTRIBUTE, DEFAULT_ROUTE_BASE, EVENT_ATTRIBUTE, EVENT_PROP_PREFIX, GOALS_SLUG, GOAL_ACTION_TYPE, GOAL_ATTRIBUTE, ITEM_ATTRIBUTE, ITEM_CLICK_EVENT, ITEM_NAME_ATTRIBUTE, MAX_ITEMS_PER_BEACON, PLATFORM_SCOPE, PROVIDERS_SLUG, PROVIDER_IDS, PURCHASE_GOAL_SLUG, ProviderHttpError, SECRET_PATHS, STATE_SLUG, SYNC_SLUG, SYSTEM, TIMEFRAME_PRESETS, VALUE_ATTRIBUTE, adapterFromProviderDoc, analytics, analyticsDefaultLayout, analyticsDefaultWidgets, analyticsError, analyticsFields, analyticsLinkFields, analyticsProviderFields, analyticsRoutes, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, createGuardedFetch, goalField, goalSlug, isAdminUser, itemAttributesFor, keys, parseRetryAfter, pluralKeys, purchase, readErrorCode, readForField, readForWidget, readForWidgetBreakdown, readForWidgetGoals, readForWidgetRealtime, readForWidgetSeries, rebuildDays, refreshProviders, refund, resolveHostPolicy, routePaths, signItemRef, signOrderId, tenantMembership, trackGoalAction, trackServerEvent, widgetFilters };
335
336
 
336
337
  //# sourceMappingURL=index.js.map