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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/dist/adapters/ga4/eventName.d.ts +15 -0
  5. package/dist/adapters/ga4/eventName.js +19 -0
  6. package/dist/adapters/ga4/eventName.js.map +1 -0
  7. package/dist/adapters/ga4/ga4.d.ts +5 -0
  8. package/dist/adapters/ga4/ga4.js +178 -70
  9. package/dist/adapters/ga4/ga4.js.map +1 -1
  10. package/dist/adapters/ga4/measurementId.js +15 -0
  11. package/dist/adapters/ga4/measurementId.js.map +1 -0
  12. package/dist/adapters/goalRead.js +126 -0
  13. package/dist/adapters/goalRead.js.map +1 -0
  14. package/dist/adapters/plausible/plausible.d.ts +15 -0
  15. package/dist/adapters/plausible/plausible.js +110 -42
  16. package/dist/adapters/plausible/plausible.js.map +1 -1
  17. package/dist/adapters/posthog/posthog.js +47 -25
  18. package/dist/adapters/posthog/posthog.js.map +1 -1
  19. package/dist/adapters/umami/umami.d.ts +8 -0
  20. package/dist/adapters/umami/umami.js +237 -28
  21. package/dist/adapters/umami/umami.js.map +1 -1
  22. package/dist/charts/BarList.js +8 -2
  23. package/dist/charts/BarList.js.map +1 -1
  24. package/dist/core/cacheKey.js +11 -1
  25. package/dist/core/cacheKey.js.map +1 -1
  26. package/dist/core/capabilities.js +7 -2
  27. package/dist/core/capabilities.js.map +1 -1
  28. package/dist/core/capture.d.ts +1 -1
  29. package/dist/core/contract.d.ts +32 -2
  30. package/dist/core/contract.js.map +1 -1
  31. package/dist/core/options.d.ts +8 -2
  32. package/dist/core/options.js +4 -2
  33. package/dist/core/options.js.map +1 -1
  34. package/dist/core/serverEvent.d.ts +4 -2
  35. package/dist/core/serverEvent.js.map +1 -1
  36. package/dist/exports/adapters/ga4.d.ts +2 -1
  37. package/dist/exports/adapters/ga4.js +2 -1
  38. package/dist/exports/client.d.ts +5 -2
  39. package/dist/exports/client.js +4 -1
  40. package/dist/exports/rsc.d.ts +2 -1
  41. package/dist/exports/tracker.d.ts +3 -2
  42. package/dist/exports/tracker.js +2 -1
  43. package/dist/exports/types.d.ts +2 -1
  44. package/dist/exports/types.js +2 -1
  45. package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
  46. package/dist/fields/config/FilterDimensionSelectField.js +77 -0
  47. package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
  48. package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
  49. package/dist/fields/config/FilterOperatorSelectField.js +75 -0
  50. package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
  51. package/dist/fields/config/MetricSelectField.js +1 -1
  52. package/dist/fields/config/SourceSelectField.js +1 -1
  53. package/dist/fields/config/sourcesState.js +19 -3
  54. package/dist/fields/config/sourcesState.js.map +1 -1
  55. package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
  56. package/dist/fields/config/useAnalyticsSources.js +9 -6
  57. package/dist/fields/config/useAnalyticsSources.js.map +1 -1
  58. package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
  59. package/dist/fields/config/useFilterCapabilities.js +52 -0
  60. package/dist/fields/config/useFilterCapabilities.js.map +1 -0
  61. package/dist/fields/readForDocument.js +16 -4
  62. package/dist/fields/readForDocument.js.map +1 -1
  63. package/dist/index.d.ts +3 -1
  64. package/dist/index.js +2 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/native/collections/events.js +36 -0
  67. package/dist/native/collections/events.js.map +1 -1
  68. package/dist/native/eventScan.js +25 -0
  69. package/dist/native/eventScan.js.map +1 -0
  70. package/dist/native/ingest/browser.js +47 -0
  71. package/dist/native/ingest/browser.js.map +1 -0
  72. package/dist/native/ingest/flushBatch.js +26 -26
  73. package/dist/native/ingest/flushBatch.js.map +1 -1
  74. package/dist/native/ingest/language.js +14 -0
  75. package/dist/native/ingest/language.js.map +1 -0
  76. package/dist/native/ingest/normalizeEvent.d.ts +6 -0
  77. package/dist/native/ingest/normalizeEvent.js +32 -5
  78. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  79. package/dist/native/ingest/referrer.js +48 -0
  80. package/dist/native/ingest/referrer.js.map +1 -0
  81. package/dist/native/ingest/serverTrack.js +1 -0
  82. package/dist/native/ingest/serverTrack.js.map +1 -1
  83. package/dist/native/ingest/source.d.ts +7 -0
  84. package/dist/native/ingest/source.js +139 -14
  85. package/dist/native/ingest/source.js.map +1 -1
  86. package/dist/native/ingest/utm.js +33 -0
  87. package/dist/native/ingest/utm.js.map +1 -0
  88. package/dist/native/nativeAdapter.js +32 -26
  89. package/dist/native/nativeAdapter.js.map +1 -1
  90. package/dist/native/query/eventAgg.js +14 -1
  91. package/dist/native/query/eventAgg.js.map +1 -1
  92. package/dist/native/rollups/bucketKey.js +15 -0
  93. package/dist/native/rollups/bucketKey.js.map +1 -0
  94. package/dist/native/rollups/bumpRollups.js +116 -0
  95. package/dist/native/rollups/bumpRollups.js.map +1 -0
  96. package/dist/native/rollups/deltas.js +30 -15
  97. package/dist/native/rollups/deltas.js.map +1 -1
  98. package/dist/native/rollups/insertManyIfNew.js +93 -0
  99. package/dist/native/rollups/insertManyIfNew.js.map +1 -0
  100. package/dist/next/captureRewrites.d.ts +3 -2
  101. package/dist/next/captureRewrites.js +3 -2
  102. package/dist/next/captureRewrites.js.map +1 -1
  103. package/dist/plugin/documentEndpoint.js +26 -7
  104. package/dist/plugin/documentEndpoint.js.map +1 -1
  105. package/dist/plugin/goalHint.d.ts +1 -0
  106. package/dist/plugin/goalHint.js +24 -0
  107. package/dist/plugin/goalHint.js.map +1 -0
  108. package/dist/plugin/queryEndpoint.js +19 -12
  109. package/dist/plugin/queryEndpoint.js.map +1 -1
  110. package/dist/plugin/realtimeEndpoint.js +40 -15
  111. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  112. package/dist/plugin/responses.js +17 -0
  113. package/dist/plugin/responses.js.map +1 -0
  114. package/dist/plugin/sourcesEndpoint.js +10 -3
  115. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  116. package/dist/providers/collection.js +14 -4
  117. package/dist/providers/collection.js.map +1 -1
  118. package/dist/providers/factory.js +4 -2
  119. package/dist/providers/factory.js.map +1 -1
  120. package/dist/query/response.d.ts +4 -1
  121. package/dist/query/response.js +11 -0
  122. package/dist/query/response.js.map +1 -0
  123. package/dist/surfacing/engine.js +1 -1
  124. package/dist/surfacing/engine.js.map +1 -1
  125. package/dist/testing/memoryAdapter.js +0 -1
  126. package/dist/testing/memoryAdapter.js.map +1 -1
  127. package/dist/tracker/createTracker.js +13 -1
  128. package/dist/tracker/createTracker.js.map +1 -1
  129. package/dist/tracker/sinks/ga4.d.ts +21 -0
  130. package/dist/tracker/sinks/ga4.js +26 -0
  131. package/dist/tracker/sinks/ga4.js.map +1 -0
  132. package/dist/tracker/types.d.ts +5 -0
  133. package/dist/translations/ar.js +30 -1
  134. package/dist/translations/ar.js.map +1 -1
  135. package/dist/translations/de.js +30 -1
  136. package/dist/translations/de.js.map +1 -1
  137. package/dist/translations/en.js +30 -1
  138. package/dist/translations/en.js.map +1 -1
  139. package/dist/translations/es.js +30 -1
  140. package/dist/translations/es.js.map +1 -1
  141. package/dist/translations/fr.js +30 -1
  142. package/dist/translations/fr.js.map +1 -1
  143. package/dist/translations/id.js +30 -1
  144. package/dist/translations/id.js.map +1 -1
  145. package/dist/translations/keys.d.ts +29 -0
  146. package/dist/translations/keys.js +30 -1
  147. package/dist/translations/keys.js.map +1 -1
  148. package/dist/translations/ko.js +30 -1
  149. package/dist/translations/ko.js.map +1 -1
  150. package/dist/translations/metricKeys.js +7 -1
  151. package/dist/translations/metricKeys.js.map +1 -1
  152. package/dist/translations/pt.js +30 -1
  153. package/dist/translations/pt.js.map +1 -1
  154. package/dist/translations/ru.js +30 -1
  155. package/dist/translations/ru.js.map +1 -1
  156. package/dist/translations/server.js.map +1 -1
  157. package/dist/translations/uk.js +30 -1
  158. package/dist/translations/uk.js.map +1 -1
  159. package/dist/translations/zh.js +30 -1
  160. package/dist/translations/zh.js.map +1 -1
  161. package/dist/view/AnalyticsViewClient.js +13 -2
  162. package/dist/view/AnalyticsViewClient.js.map +1 -1
  163. package/dist/view/gating.js +40 -3
  164. package/dist/view/gating.js.map +1 -1
  165. package/dist/view/labels.js +21 -1
  166. package/dist/view/labels.js.map +1 -1
  167. package/dist/view/sections/Breakdowns.js +78 -38
  168. package/dist/view/sections/Breakdowns.js.map +1 -1
  169. package/dist/view/sections/FilterChips.js +8 -3
  170. package/dist/view/sections/FilterChips.js.map +1 -1
  171. package/dist/view/sections/GoalsPanel.js +2 -1
  172. package/dist/view/sections/GoalsPanel.js.map +1 -1
  173. package/dist/view/sections/RealtimeStrip.js +4 -1
  174. package/dist/view/sections/RealtimeStrip.js.map +1 -1
  175. package/dist/view/sections/Toolbar.js +10 -3
  176. package/dist/view/sections/Toolbar.js.map +1 -1
  177. package/dist/view/sections/Trend.js +8 -2
  178. package/dist/view/sections/Trend.js.map +1 -1
  179. package/dist/view/state.js +7 -2
  180. package/dist/view/state.js.map +1 -1
  181. package/dist/view/useViewQueries.js +6 -3
  182. package/dist/view/useViewQueries.js.map +1 -1
  183. package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
  184. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  185. package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
  186. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  187. package/dist/widgets/AnalyticsMetricWidget.js +30 -3
  188. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  189. package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
  190. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  191. package/dist/widgets/AnalyticsTrendWidget.js +30 -3
  192. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  193. package/dist/widgets/RealtimeCounter.d.ts +4 -0
  194. package/dist/widgets/RealtimeCounter.js +10 -1
  195. package/dist/widgets/RealtimeCounter.js.map +1 -1
  196. package/dist/widgets/breakdownTypes.js.map +1 -1
  197. package/dist/widgets/comparison.js +15 -1
  198. package/dist/widgets/comparison.js.map +1 -1
  199. package/dist/widgets/defaults.d.ts +6 -2
  200. package/dist/widgets/defaults.js +72 -25
  201. package/dist/widgets/defaults.js.map +1 -1
  202. package/dist/widgets/filterCaption.js +27 -0
  203. package/dist/widgets/filterCaption.js.map +1 -0
  204. package/dist/widgets/filterField.d.ts +19 -0
  205. package/dist/widgets/filterField.js +75 -0
  206. package/dist/widgets/filterField.js.map +1 -0
  207. package/dist/widgets/prepareWidgetRead.d.ts +7 -0
  208. package/dist/widgets/prepareWidgetRead.js +74 -0
  209. package/dist/widgets/prepareWidgetRead.js.map +1 -0
  210. package/dist/widgets/readForWidget.d.ts +12 -2
  211. package/dist/widgets/readForWidget.js +34 -49
  212. package/dist/widgets/readForWidget.js.map +1 -1
  213. package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
  214. package/dist/widgets/readForWidgetBreakdown.js +29 -42
  215. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  216. package/dist/widgets/readForWidgetGoals.d.ts +11 -1
  217. package/dist/widgets/readForWidgetGoals.js +44 -30
  218. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  219. package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
  220. package/dist/widgets/readForWidgetRealtime.js +21 -20
  221. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  222. package/dist/widgets/readForWidgetSeries.d.ts +11 -1
  223. package/dist/widgets/readForWidgetSeries.js +38 -49
  224. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  225. package/dist/widgets/readMeta.js +18 -0
  226. package/dist/widgets/readMeta.js.map +1 -0
  227. package/dist/widgets/registerWidgets.js +5 -2
  228. package/dist/widgets/registerWidgets.js.map +1 -1
  229. package/dist/widgets/types.d.ts +15 -0
  230. package/dist/widgets/types.js.map +1 -1
  231. package/dist/widgets/viewLink.js +5 -2
  232. package/dist/widgets/viewLink.js.map +1 -1
  233. package/package.json +5 -5
  234. package/dist/native/rollups/applyDistinctDeltas.js +0 -9
  235. package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
  236. package/dist/native/rollups/bumpRollup.js +0 -73
  237. package/dist/native/rollups/bumpRollup.js.map +0 -1
  238. package/dist/native/rollups/insertIfNew.js +0 -53
  239. package/dist/native/rollups/insertIfNew.js.map +0 -1
@@ -0,0 +1,74 @@
1
+ import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
2
+ import { resolveTimeframe } from "../timeframe/presets.js";
3
+ import { satisfiesCapabilities } from "../core/capabilities.js";
4
+ import { supportsGranularity } from "../core/granularity.js";
5
+ import { resolveReadContext } from "../core/scopedRead.js";
6
+ import { goalSlugsFor } from "../plugin/goalHint.js";
7
+ //#region src/widgets/prepareWidgetRead.ts
8
+ /**
9
+ * Whether the serving source can apply every filter the read carries. Answered before the
10
+ * query so a source that cannot filter says so rather than returning site-wide numbers a
11
+ * reader would take for filtered ones.
12
+ */
13
+ const supportsFilters = (caps, filters) => !filters || filters.length === 0 || satisfiesCapabilities(caps, {
14
+ filters: filters.map((f) => f.dimension),
15
+ filterOperators: filters.map((f) => f.operator)
16
+ });
17
+ /**
18
+ * The prologue every widget read shares: the runtime, the read's scope and adapter, the
19
+ * reporting timezone, the window, and the gates a source has to pass before it is worth
20
+ * querying. A refusal carries the status the widget renders and the window it would have
21
+ * read, so a helper's own failure shape is one spread rather than five early returns.
22
+ */
23
+ const prepareWidgetRead = async (args) => {
24
+ const { req, now } = args;
25
+ const windowIn = (zone) => args.timeframe === void 0 ? args.range : args.range ?? resolveTimeframe(args.timeframe, now, zone);
26
+ const runtime = getRuntime(req.payload);
27
+ const ctx = runtime ? await resolveReadContext({
28
+ runtime,
29
+ req,
30
+ adapterId: args.adapterId,
31
+ scope: args.scope
32
+ }) : { ok: false };
33
+ if (!runtime || !ctx.ok) return {
34
+ ok: false,
35
+ status: "unavailable",
36
+ adapterId: args.adapterId ?? "",
37
+ dateRange: windowIn(args.timezone),
38
+ tz: args.timezone ?? "UTC"
39
+ };
40
+ const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
41
+ const dateRange = windowIn(tz);
42
+ const adapter = ctx.adapter;
43
+ const refuse = (status) => ({
44
+ ok: false,
45
+ status,
46
+ adapterId: adapter.id,
47
+ dateRange,
48
+ tz
49
+ });
50
+ if (!adapter.isConfigured()) return refuse("not-configured");
51
+ if (args.requires && !satisfiesCapabilities(adapter.capabilities, args.requires)) return refuse("unavailable");
52
+ if (args.granularity && !supportsGranularity(adapter.capabilities, args.granularity)) return refuse("unavailable");
53
+ if (!supportsFilters(adapter.capabilities, args.filters)) return refuse("filter-unsupported");
54
+ const goalSlugs = args.goalSlugs ?? (args.goalRead ? await goalSlugsFor({
55
+ runtime,
56
+ req,
57
+ scope: ctx.scope,
58
+ ...args.goalRead(adapter)
59
+ }) : void 0);
60
+ return {
61
+ ok: true,
62
+ runtime,
63
+ adapter,
64
+ tz,
65
+ dateRange,
66
+ scope: ctx.scope,
67
+ ...ctx.queryScope === void 0 ? {} : { queryScope: ctx.queryScope },
68
+ ...goalSlugs === void 0 ? {} : { goalSlugs }
69
+ };
70
+ };
71
+ //#endregion
72
+ export { prepareWidgetRead };
73
+
74
+ //# sourceMappingURL=prepareWidgetRead.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepareWidgetRead.js","names":[],"sources":["../../src/widgets/prepareWidgetRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type CapabilityRequirement, satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsFilter,\n\tDateRange,\n\tGranularity,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { type GoalRead, goalSlugsFor } from '../plugin/goalHint'\nimport { type AnalyticsRuntime, getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\nexport type WidgetReadStatus = 'ok' | 'not-configured' | 'unavailable' | 'filter-unsupported'\n\n/**\n * Whether the serving source can apply every filter the read carries. Answered before the\n * query so a source that cannot filter says so rather than returning site-wide numbers a\n * reader would take for filtered ones.\n */\nexport const supportsFilters = (\n\tcaps: AnalyticsCapabilities,\n\tfilters?: AnalyticsFilter[]\n): boolean =>\n\t!filters ||\n\tfilters.length === 0 ||\n\tsatisfiesCapabilities(caps, {\n\t\tfilters: filters.map((f) => f.dimension),\n\t\tfilterOperators: filters.map((f) => f.operator),\n\t})\n\ninterface PrepareWidgetReadBase {\n\treq: PayloadRequest\n\tnow: Date\n\tadapterId?: string\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\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\tfilters?: AnalyticsFilter[]\n\t/** What the source must serve for the read to be worth making. */\n\trequires?: CapabilityRequirement\n\t/** The finest bucket the read needs, gated against the source's `minGranularity`. */\n\tgranularity?: Granularity\n\t/**\n\t * The read the goal hint is resolved for, answered once the adapter is known so a caller\n\t * that narrows its metrics against the source hints on the list it will actually ask for.\n\t * Omitted asks about no goals.\n\t */\n\tgoalRead?: (adapter: AnalyticsAdapter) => GoalRead\n\t/** A hint the caller already resolved, which wins over `goalRead`. */\n\tgoalSlugs?: string[] | 'unresolved'\n}\n\n/** Either a preset to resolve the window from or the window itself. */\nexport type PrepareWidgetReadArgs = PrepareWidgetReadBase &\n\t({ timeframe: TimeframePreset; range?: DateRange } | { timeframe?: undefined; range: DateRange })\n\nexport type PreparedWidgetRead =\n\t| {\n\t\t\tok: true\n\t\t\truntime: AnalyticsRuntime\n\t\t\tadapter: AnalyticsAdapter\n\t\t\t/** Reporting timezone the window was resolved in. */\n\t\t\ttz: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The read's own scope, which sub-reads pin so all of them answer about one thing. */\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t\t\t/** The scope's goal slugs, `'unresolved'`, or absent for a read about no goals. */\n\t\t\tgoalSlugs?: string[] | 'unresolved'\n\t }\n\t| {\n\t\t\tok: false\n\t\t\tstatus: WidgetReadStatus\n\t\t\tadapterId: string\n\t\t\tdateRange: DateRange\n\t\t\t/** The timezone the window was read in: the resolved one, or the caller's own, or UTC. */\n\t\t\ttz: string\n\t }\n\n/**\n * The prologue every widget read shares: the runtime, the read's scope and adapter, the\n * reporting timezone, the window, and the gates a source has to pass before it is worth\n * querying. A refusal carries the status the widget renders and the window it would have\n * read, so a helper's own failure shape is one spread rather than five early returns.\n */\nexport const prepareWidgetRead = async (\n\targs: PrepareWidgetReadArgs\n): Promise<PreparedWidgetRead> => {\n\tconst { req, now } = args\n\tconst windowIn = (zone?: string): DateRange =>\n\t\targs.timeframe === undefined\n\t\t\t? args.range\n\t\t\t: (args.range ?? resolveTimeframe(args.timeframe, now, zone))\n\n\tconst runtime = getRuntime(req.payload)\n\tconst ctx = runtime\n\t\t? await resolveReadContext({ runtime, req, adapterId: args.adapterId, scope: args.scope })\n\t\t: { ok: false as const }\n\tif (!runtime || !ctx.ok) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: args.adapterId ?? '',\n\t\t\tdateRange: windowIn(args.timezone),\n\t\t\ttz: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t}\n\t}\n\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = windowIn(tz)\n\tconst adapter = ctx.adapter\n\tconst refuse = (status: WidgetReadStatus): PreparedWidgetRead => ({\n\t\tok: false,\n\t\tstatus,\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttz,\n\t})\n\tif (!adapter.isConfigured()) {\n\t\treturn refuse('not-configured')\n\t}\n\tif (args.requires && !satisfiesCapabilities(adapter.capabilities, args.requires)) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (args.granularity && !supportsGranularity(adapter.capabilities, args.granularity)) {\n\t\treturn refuse('unavailable')\n\t}\n\tif (!supportsFilters(adapter.capabilities, args.filters)) {\n\t\treturn refuse('filter-unsupported')\n\t}\n\n\tconst goalSlugs =\n\t\targs.goalSlugs ??\n\t\t(args.goalRead\n\t\t\t? await goalSlugsFor({ runtime, req, scope: ctx.scope, ...args.goalRead(adapter) })\n\t\t\t: undefined)\n\treturn {\n\t\tok: true,\n\t\truntime,\n\t\tadapter,\n\t\ttz,\n\t\tdateRange,\n\t\tscope: ctx.scope,\n\t\t...(ctx.queryScope === undefined ? {} : { queryScope: ctx.queryScope }),\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAa,mBACZ,MACA,YAEA,CAAC,WACD,QAAQ,WAAW,KACnB,sBAAsB,MAAM;CAC3B,SAAS,QAAQ,KAAK,MAAM,EAAE,SAAS;CACvC,iBAAiB,QAAQ,KAAK,MAAM,EAAE,QAAQ;AAC/C,CAAC;;;;;;;AA8DF,MAAa,oBAAoB,OAChC,SACiC;CACjC,MAAM,EAAE,KAAK,QAAQ;CACrB,MAAM,YAAY,SACjB,KAAK,cAAc,KAAA,IAChB,KAAK,QACJ,KAAK,SAAS,iBAAiB,KAAK,WAAW,KAAK,IAAI;CAE7D,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,MAAM,MAAM,UACT,MAAM,mBAAmB;EAAE;EAAS;EAAK,WAAW,KAAK;EAAW,OAAO,KAAK;CAAM,CAAC,IACvF,EAAE,IAAI,MAAe;CACxB,IAAI,CAAC,WAAW,CAAC,IAAI,IACpB,OAAO;EACN,IAAI;EACJ,QAAQ;EACR,WAAW,KAAK,aAAa;EAC7B,WAAW,SAAS,KAAK,QAAQ;EACjC,IAAI,KAAK,YAAA;CACV;CAGD,MAAM,KAAK,KAAK,YAAa,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC7E,MAAM,YAAY,SAAS,EAAE;CAC7B,MAAM,UAAU,IAAI;CACpB,MAAM,UAAU,YAAkD;EACjE,IAAI;EACJ;EACA,WAAW,QAAQ;EACnB;EACA;CACD;CACA,IAAI,CAAC,QAAQ,aAAa,GACzB,OAAO,OAAO,gBAAgB;CAE/B,IAAI,KAAK,YAAY,CAAC,sBAAsB,QAAQ,cAAc,KAAK,QAAQ,GAC9E,OAAO,OAAO,aAAa;CAE5B,IAAI,KAAK,eAAe,CAAC,oBAAoB,QAAQ,cAAc,KAAK,WAAW,GAClF,OAAO,OAAO,aAAa;CAE5B,IAAI,CAAC,gBAAgB,QAAQ,cAAc,KAAK,OAAO,GACtD,OAAO,OAAO,oBAAoB;CAGnC,MAAM,YACL,KAAK,cACJ,KAAK,WACH,MAAM,aAAa;EAAE;EAAS;EAAK,OAAO,IAAI;EAAO,GAAG,KAAK,SAAS,OAAO;CAAE,CAAC,IAChF,KAAA;CACJ,OAAO;EACN,IAAI;EACJ;EACA;EACA;EACA;EACA,OAAO,IAAI;EACX,GAAI,IAAI,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,IAAI,WAAW;EACrE,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;CAChD;AACD"}
@@ -1,17 +1,27 @@
1
1
  import { AnalyticsFilter, DateRange, MetricKey } from "../core/contract.js";
2
2
  import { TimeframePreset } from "../timeframe/presets.js";
3
+ import { WidgetReadStatus } from "./prepareWidgetRead.js";
3
4
  import { PayloadRequest } from "payload";
4
5
 
5
6
  //#region src/widgets/readForWidget.d.ts
6
- type WidgetReadStatus = 'ok' | 'not-configured' | 'unavailable';
7
7
  interface WidgetReadResult {
8
8
  status: WidgetReadStatus;
9
9
  adapterId: string;
10
10
  dateRange: DateRange;
11
11
  metrics: Partial<Record<MetricKey, number>>;
12
+ /** The source that answered, absent on a read that never reached one. */
13
+ provider?: string;
12
14
  clamped?: boolean;
13
15
  /** True when the engine served a stale cache entry after a failed provider read. */
14
16
  stale?: boolean;
17
+ /** True when the source answered without one of the filters the read carried. */
18
+ filtersUnapplied?: boolean;
19
+ /** True when the read hit the source's event scan cap, so the numbers are a floor. */
20
+ sampled?: boolean;
21
+ /** True when the source could not read the scope's goals, so a conversions total means nothing. */
22
+ goalsUnresolved?: boolean;
23
+ /** The read asked about goals and the scope has none configured. */
24
+ noGoals?: boolean;
15
25
  /** Previous-window totals, present only when the adapter supports comparison. */
16
26
  previousMetrics?: Partial<Record<MetricKey, number>>;
17
27
  /** The previous comparable window, present only when comparison ran. */
@@ -40,5 +50,5 @@ interface ReadForWidgetArgs {
40
50
  }
41
51
  declare const readForWidget: (args: ReadForWidgetArgs) => Promise<WidgetReadResult>;
42
52
  //#endregion
43
- export { ReadForWidgetArgs, WidgetReadResult, WidgetReadStatus, readForWidget };
53
+ export { ReadForWidgetArgs, WidgetReadResult, readForWidget };
44
54
  //# sourceMappingURL=readForWidget.d.ts.map
@@ -1,70 +1,55 @@
1
- import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
2
- import { resolveTimeframe } from "../timeframe/presets.js";
3
- import { satisfiesCapabilities } from "../core/capabilities.js";
4
- import { resolveReadContext } from "../core/scopedRead.js";
5
- import { previousWindow } from "./comparison.js";
1
+ import { comparisonOf } from "../core/capabilities.js";
2
+ import { previousWindow, withinLookback } from "./comparison.js";
3
+ import { prepareWidgetRead } from "./prepareWidgetRead.js";
4
+ import { readMeta } from "./readMeta.js";
6
5
  //#region src/widgets/readForWidget.ts
7
6
  const readForWidget = async (args) => {
8
7
  const { req, metrics, timeframe, adapterId, now, range, filters } = args;
9
8
  const emptyMetrics = {};
10
- const runtime = getRuntime(req.payload);
11
- if (!runtime) return {
12
- status: "unavailable",
13
- adapterId: adapterId ?? "",
14
- dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
15
- metrics: emptyMetrics
16
- };
17
- const ctx = await resolveReadContext({
18
- runtime,
9
+ const prepared = await prepareWidgetRead({
19
10
  req,
11
+ now,
12
+ timeframe,
20
13
  adapterId,
21
- scope: args.scope
14
+ scope: args.scope,
15
+ timezone: args.timezone,
16
+ range,
17
+ filters,
18
+ requires: { metrics },
19
+ goalRead: () => ({ metrics })
22
20
  });
23
- if (!ctx.ok) return {
24
- status: "unavailable",
25
- adapterId: adapterId ?? "",
26
- dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
21
+ if (!prepared.ok) return {
22
+ status: prepared.status,
23
+ adapterId: prepared.adapterId,
24
+ dateRange: prepared.dateRange,
27
25
  metrics: emptyMetrics
28
26
  };
29
- const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
30
- const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
27
+ const { runtime, adapter, tz, dateRange } = prepared;
31
28
  const base = {
32
29
  dateRange,
33
30
  metrics: emptyMetrics
34
31
  };
35
- const adapter = ctx.adapter;
36
- if (!adapter.isConfigured()) return {
37
- status: "not-configured",
38
- adapterId: adapter.id,
39
- ...base
40
- };
41
- if (!satisfiesCapabilities(adapter.capabilities, {
32
+ const previousRange = args.comparison !== false && runtime.comparison && comparisonOf(adapter.capabilities) ? previousWindow(dateRange, tz) : null;
33
+ const comparisonRange = previousRange && withinLookback(previousRange, adapter.capabilities.maxLookbackDays, {
34
+ tz,
35
+ now
36
+ }) ? previousRange : void 0;
37
+ const readBase = {
42
38
  metrics,
43
- ...filters && filters.length > 0 ? {
44
- filters: filters.map((f) => f.dimension),
45
- filterOperators: filters.map((f) => f.operator)
46
- } : {}
47
- })) return {
48
- status: "unavailable",
49
- adapterId: adapter.id,
50
- ...base
39
+ filters,
40
+ timezone: tz,
41
+ scope: prepared.queryScope,
42
+ ...prepared.goalSlugs === void 0 ? {} : { goalSlugs: prepared.goalSlugs }
51
43
  };
52
- const comparisonRange = args.comparison !== false && runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
53
44
  let result;
54
45
  let previous;
55
46
  try {
56
47
  [result, previous] = await Promise.all([runtime.engine.read(adapter, {
57
- metrics,
58
- dateRange,
59
- filters,
60
- timezone: tz,
61
- scope: ctx.queryScope
48
+ ...readBase,
49
+ dateRange
62
50
  }), comparisonRange ? runtime.engine.read(adapter, {
63
- metrics,
64
- dateRange: comparisonRange,
65
- filters,
66
- timezone: tz,
67
- scope: ctx.queryScope
51
+ ...readBase,
52
+ dateRange: comparisonRange
68
53
  }) : void 0]);
69
54
  } catch {
70
55
  return {
@@ -79,8 +64,8 @@ const readForWidget = async (args) => {
79
64
  adapterId: adapter.id,
80
65
  dateRange,
81
66
  metrics: result.totals ?? {},
82
- clamped: result.meta.clamped ?? false,
83
- stale: result.meta.stale ?? false,
67
+ ...readMeta(result),
68
+ noGoals: Array.isArray(prepared.goalSlugs) && prepared.goalSlugs.length === 0,
84
69
  previousMetrics,
85
70
  comparisonRange
86
71
  };
@@ -1 +1 @@
1
- {"version":3,"file":"readForWidget.js","names":[],"sources":["../../src/widgets/readForWidget.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tMetricKey,\n} from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { previousWindow } from './comparison'\n\nexport type WidgetReadStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface WidgetReadResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\tmetrics: Partial<Record<MetricKey, number>>\n\tclamped?: boolean\n\t/** True when the engine served a stale cache entry after a failed provider read. */\n\tstale?: boolean\n\t/** Previous-window totals, present only when the adapter supports comparison. */\n\tpreviousMetrics?: Partial<Record<MetricKey, number>>\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n}\n\nexport interface ReadForWidgetArgs {\n\treq: PayloadRequest\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\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\tfilters?: AnalyticsFilter[]\n\t/**\n\t * Read the previous window too, where the install and the source both allow it. Defaults\n\t * to on; a caller that never renders a delta passes false to save the second read.\n\t */\n\tcomparison?: boolean\n}\n\nexport const readForWidget = async (args: ReadForWidgetArgs): Promise<WidgetReadResult> => {\n\tconst { req, metrics, timeframe, adapterId, now, range, filters } = args\n\tconst emptyMetrics = {} as Partial<Record<MetricKey, number>>\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\t\tmetrics: emptyMetrics,\n\t\t}\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\t\tmetrics: emptyMetrics,\n\t\t}\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, metrics: emptyMetrics }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\tmetrics,\n\t\t\t...(filters && filters.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\tfilters: filters.map((f) => f.dimension),\n\t\t\t\t\t\tfilterOperators: filters.map((f) => f.operator),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t})\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst comparisonRange =\n\t\targs.comparison !== false && runtime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, {\n\t\t\t\tmetrics,\n\t\t\t\tdateRange,\n\t\t\t\tfilters,\n\t\t\t\ttimezone: tz,\n\t\t\t\tscope: ctx.queryScope,\n\t\t\t}),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t\tmetrics,\n\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\ttimezone: tz,\n\t\t\t\t\t\tscope: ctx.queryScope,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousMetrics = previous ? (previous.totals ?? {}) : undefined\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\tmetrics: result.totals ?? {},\n\t\tclamped: result.meta.clamped ?? false,\n\t\tstale: result.meta.stale ?? false,\n\t\tpreviousMetrics,\n\t\tcomparisonRange,\n\t}\n}\n"],"mappings":";;;;;;AAoDA,MAAa,gBAAgB,OAAO,SAAuD;CAC1F,MAAM,EAAE,KAAK,SAAS,WAAW,WAAW,KAAK,OAAO,YAAY;CACpE,MAAM,eAAe,CAAC;CAEtB,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,KAAK,KAAK,QAAQ;EAClE,SAAS;CACV;CAED,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,KAAK,KAAK,QAAQ;EAClE,SAAS;CACV;CAED,MAAM,KAAK,KAAK,YAAa,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC7E,MAAM,YAAY,SAAS,iBAAiB,WAAW,KAAK,EAAE;CAC9D,MAAM,OAAO;EAAE;EAAW,SAAS;CAAa;CAChD,MAAM,UAA4B,IAAI;CACtC,IAAI,CAAC,QAAQ,aAAa,GACzB,OAAO;EAAE,QAAQ;EAAkB,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEnE,IACC,CAAC,sBAAsB,QAAQ,cAAc;EAC5C;EACA,GAAI,WAAW,QAAQ,SAAS,IAC7B;GACA,SAAS,QAAQ,KAAK,MAAM,EAAE,SAAS;GACvC,iBAAiB,QAAQ,KAAK,MAAM,EAAE,QAAQ;EAC/C,IACC,CAAC;CACL,CAAC,GAED,OAAO;EAAE,QAAQ;EAAe,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEhE,MAAM,kBACL,KAAK,eAAe,SAAS,QAAQ,cAAc,QAAQ,aAAa,aACpE,eAAe,WAAW,EAAE,KAAK,KAAA,IAClC,KAAA;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,CAAC,QAAQ,YAAY,MAAM,QAAQ,IAAI,CACvC,QAAQ,OAAO,KAAK,SAAS;GAC5B;GACA;GACA;GACA,UAAU;GACV,OAAO,IAAI;EACZ,CAAC,GACD,kBACG,QAAQ,OAAO,KAAK,SAAS;GAC7B;GACA,WAAW;GACX;GACA,UAAU;GACV,OAAO,IAAI;EACZ,CAAC,IACA,KAAA,CACJ,CAAC;CACF,QAAQ;EAGP,OAAO;GAAE,QAAQ;GAAe,WAAW,QAAQ;GAAI,GAAG;EAAK;CAChE;CACA,MAAM,kBAAkB,WAAY,SAAS,UAAU,CAAC,IAAK,KAAA;CAC7D,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,SAAS,OAAO,UAAU,CAAC;EAC3B,SAAS,OAAO,KAAK,WAAW;EAChC,OAAO,OAAO,KAAK,SAAS;EAC5B;EACA;CACD;AACD"}
1
+ {"version":3,"file":"readForWidget.js","names":[],"sources":["../../src/widgets/readForWidget.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { comparisonOf } from '../core/capabilities'\nimport type { AnalyticsFilter, AnalyticsResult, DateRange, MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { previousWindow, withinLookback } from './comparison'\nimport { prepareWidgetRead, type WidgetReadStatus } from './prepareWidgetRead'\nimport { readMeta } from './readMeta'\n\nexport type { WidgetReadStatus } from './prepareWidgetRead'\n\nexport interface WidgetReadResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\tmetrics: Partial<Record<MetricKey, number>>\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\tclamped?: boolean\n\t/** True when the engine served a stale cache entry after a failed provider read. */\n\tstale?: boolean\n\t/** True when the source answered without one of the filters the read carried. */\n\tfiltersUnapplied?: boolean\n\t/** True when the read hit the source's event scan cap, so the numbers are a floor. */\n\tsampled?: boolean\n\t/** True when the source could not read the scope's goals, so a conversions total means nothing. */\n\tgoalsUnresolved?: boolean\n\t/** The read asked about goals and the scope has none configured. */\n\tnoGoals?: boolean\n\t/** Previous-window totals, present only when the adapter supports comparison. */\n\tpreviousMetrics?: Partial<Record<MetricKey, number>>\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n}\n\nexport interface ReadForWidgetArgs {\n\treq: PayloadRequest\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\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\tfilters?: AnalyticsFilter[]\n\t/**\n\t * Read the previous window too, where the install and the source both allow it. Defaults\n\t * to on; a caller that never renders a delta passes false to save the second read.\n\t */\n\tcomparison?: boolean\n}\n\nexport const readForWidget = async (args: ReadForWidgetArgs): Promise<WidgetReadResult> => {\n\tconst { req, metrics, timeframe, adapterId, now, range, filters } = args\n\tconst emptyMetrics = {} as Partial<Record<MetricKey, number>>\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tscope: args.scope,\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics },\n\t\tgoalRead: () => ({ metrics }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\tmetrics: emptyMetrics,\n\t\t}\n\t}\n\tconst { runtime, adapter, tz, dateRange } = prepared\n\tconst base = { dateRange, metrics: emptyMetrics }\n\n\tconst previousRange =\n\t\targs.comparison !== false && runtime.comparison && comparisonOf(adapter.capabilities)\n\t\t\t? previousWindow(dateRange, tz)\n\t\t\t: null\n\tconst comparisonRange =\n\t\tpreviousRange &&\n\t\twithinLookback(previousRange, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t\t? previousRange\n\t\t\t: undefined\n\tconst readBase = {\n\t\tmetrics,\n\t\tfilters,\n\t\ttimezone: tz,\n\t\tscope: prepared.queryScope,\n\t\t...(prepared.goalSlugs === undefined ? {} : { goalSlugs: prepared.goalSlugs }),\n\t}\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, { ...readBase, dateRange }),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, { ...readBase, dateRange: comparisonRange })\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousMetrics = previous ? (previous.totals ?? {}) : undefined\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\tmetrics: result.totals ?? {},\n\t\t...readMeta(result),\n\t\tnoGoals: Array.isArray(prepared.goalSlugs) && prepared.goalSlugs.length === 0,\n\t\tpreviousMetrics,\n\t\tcomparisonRange,\n\t}\n}\n"],"mappings":";;;;;AAwDA,MAAa,gBAAgB,OAAO,SAAuD;CAC1F,MAAM,EAAE,KAAK,SAAS,WAAW,WAAW,KAAK,OAAO,YAAY;CACpE,MAAM,eAAe,CAAC;CAEtB,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,OAAO,KAAK;EACZ,UAAU,KAAK;EACf;EACA;EACA,UAAU,EAAE,QAAQ;EACpB,iBAAiB,EAAE,QAAQ;CAC5B,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO;EACN,QAAQ,SAAS;EACjB,WAAW,SAAS;EACpB,WAAW,SAAS;EACpB,SAAS;CACV;CAED,MAAM,EAAE,SAAS,SAAS,IAAI,cAAc;CAC5C,MAAM,OAAO;EAAE;EAAW,SAAS;CAAa;CAEhD,MAAM,gBACL,KAAK,eAAe,SAAS,QAAQ,cAAc,aAAa,QAAQ,YAAY,IACjF,eAAe,WAAW,EAAE,IAC5B;CACJ,MAAM,kBACL,iBACA,eAAe,eAAe,QAAQ,aAAa,iBAAiB;EAAE;EAAI;CAAI,CAAC,IAC5E,gBACA,KAAA;CACJ,MAAM,WAAW;EAChB;EACA;EACA,UAAU;EACV,OAAO,SAAS;EAChB,GAAI,SAAS,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,SAAS,UAAU;CAC7E;CACA,IAAI;CACJ,IAAI;CACJ,IAAI;EACF,CAAC,QAAQ,YAAY,MAAM,QAAQ,IAAI,CACvC,QAAQ,OAAO,KAAK,SAAS;GAAE,GAAG;GAAU;EAAU,CAAC,GACvD,kBACG,QAAQ,OAAO,KAAK,SAAS;GAAE,GAAG;GAAU,WAAW;EAAgB,CAAC,IACxE,KAAA,CACJ,CAAC;CACF,QAAQ;EAGP,OAAO;GAAE,QAAQ;GAAe,WAAW,QAAQ;GAAI,GAAG;EAAK;CAChE;CACA,MAAM,kBAAkB,WAAY,SAAS,UAAU,CAAC,IAAK,KAAA;CAC7D,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,SAAS,OAAO,UAAU,CAAC;EAC3B,GAAG,SAAS,MAAM;EAClB,SAAS,MAAM,QAAQ,SAAS,SAAS,KAAK,SAAS,UAAU,WAAW;EAC5E;EACA;CACD;AACD"}
@@ -1,6 +1,6 @@
1
1
  import { AnalyticsFilter, DateRange, DimensionKey, MetricKey } from "../core/contract.js";
2
2
  import { TimeframePreset } from "../timeframe/presets.js";
3
- import { WidgetReadStatus } from "./readForWidget.js";
3
+ import { WidgetReadStatus } from "./prepareWidgetRead.js";
4
4
  import { PayloadRequest } from "payload";
5
5
 
6
6
  //#region src/widgets/readForWidgetBreakdown.d.ts
@@ -15,9 +15,19 @@ interface WidgetBreakdownResult {
15
15
  adapterId: string;
16
16
  dateRange: DateRange;
17
17
  rows: BreakdownRow[];
18
+ /** The source that answered, absent on a read that never reached one. */
19
+ provider?: string;
18
20
  clamped?: boolean;
19
21
  /** True when the engine served a stale cache entry after a failed provider read. */
20
22
  stale?: boolean;
23
+ /** True when the source answered without one of the filters the read carried. */
24
+ filtersUnapplied?: boolean;
25
+ /** True when the read hit the source's event scan cap, so the numbers are a floor. */
26
+ sampled?: boolean;
27
+ /** True when the source could not read the scope's goals; the rows say nothing about them. */
28
+ goalsUnresolved?: boolean;
29
+ /** True when the read asked about goals and the scope configures none: an empty table. */
30
+ noGoals?: boolean;
21
31
  }
22
32
  interface ReadForWidgetBreakdownArgs {
23
33
  req: PayloadRequest;
@@ -42,6 +52,12 @@ interface ReadForWidgetBreakdownArgs {
42
52
  * `metrics`; ranking and status still follow `metric` alone.
43
53
  */
44
54
  extraMetrics?: MetricKey[];
55
+ /**
56
+ * The scope's goal slugs, for a `goal` or `conversions` read, or `'unresolved'` when the
57
+ * caller's own resolver failed. Resolved here when omitted, so a caller that already
58
+ * resolved them (the goals table) does not resolve them twice.
59
+ */
60
+ goalSlugs?: string[] | 'unresolved';
45
61
  }
46
62
  /**
47
63
  * Site-wide ranked breakdown of one metric by one dimension, read through the engine.
@@ -1,7 +1,5 @@
1
- import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
2
- import { resolveTimeframe } from "../timeframe/presets.js";
3
- import { satisfiesCapabilities } from "../core/capabilities.js";
4
- import { resolveReadContext } from "../core/scopedRead.js";
1
+ import { prepareWidgetRead } from "./prepareWidgetRead.js";
2
+ import { readMeta } from "./readMeta.js";
5
3
  //#region src/widgets/readForWidgetBreakdown.ts
6
4
  /**
7
5
  * Site-wide ranked breakdown of one metric by one dimension, read through the engine.
@@ -11,50 +9,38 @@ import { resolveReadContext } from "../core/scopedRead.js";
11
9
  const readForWidgetBreakdown = async (args) => {
12
10
  const { req, metric, dimension, timeframe, limit, adapterId, now, range, filters } = args;
13
11
  const emptyRows = [];
14
- const runtime = getRuntime(req.payload);
15
- if (!runtime) return {
16
- status: "unavailable",
17
- adapterId: adapterId ?? "",
18
- dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
19
- rows: emptyRows
20
- };
21
- const ctx = await resolveReadContext({
22
- runtime,
12
+ const metricsFor = (adapter) => [metric, ...(args.extraMetrics ?? []).filter((m) => m !== metric && adapter.capabilities.metrics.has(m))];
13
+ const prepared = await prepareWidgetRead({
23
14
  req,
15
+ now,
16
+ timeframe,
24
17
  adapterId,
25
- scope: args.scope
18
+ scope: args.scope,
19
+ timezone: args.timezone,
20
+ range,
21
+ filters,
22
+ requires: {
23
+ metrics: [metric],
24
+ dimensions: [dimension]
25
+ },
26
+ goalRead: (adapter) => ({
27
+ metrics: metricsFor(adapter),
28
+ dimensions: [dimension]
29
+ }),
30
+ goalSlugs: args.goalSlugs
26
31
  });
27
- if (!ctx.ok) return {
28
- status: "unavailable",
29
- adapterId: adapterId ?? "",
30
- dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
32
+ if (!prepared.ok) return {
33
+ status: prepared.status,
34
+ adapterId: prepared.adapterId,
35
+ dateRange: prepared.dateRange,
31
36
  rows: emptyRows
32
37
  };
33
- const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
34
- const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
38
+ const { runtime, adapter, tz, dateRange, goalSlugs } = prepared;
35
39
  const base = {
36
40
  dateRange,
37
41
  rows: emptyRows
38
42
  };
39
- const adapter = ctx.adapter;
40
- if (!adapter.isConfigured()) return {
41
- status: "not-configured",
42
- adapterId: adapter.id,
43
- ...base
44
- };
45
- if (!satisfiesCapabilities(adapter.capabilities, {
46
- metrics: [metric],
47
- dimensions: [dimension],
48
- ...filters && filters.length > 0 ? {
49
- filters: filters.map((f) => f.dimension),
50
- filterOperators: filters.map((f) => f.operator)
51
- } : {}
52
- })) return {
53
- status: "unavailable",
54
- adapterId: adapter.id,
55
- ...base
56
- };
57
- const metrics = [metric, ...(args.extraMetrics ?? []).filter((m) => m !== metric && adapter.capabilities.metrics.has(m))];
43
+ const metrics = metricsFor(adapter);
58
44
  let result;
59
45
  try {
60
46
  result = await runtime.engine.read(adapter, {
@@ -68,7 +54,8 @@ const readForWidgetBreakdown = async (args) => {
68
54
  },
69
55
  filters,
70
56
  timezone: tz,
71
- scope: ctx.queryScope
57
+ scope: prepared.queryScope,
58
+ ...goalSlugs === void 0 ? {} : { goalSlugs }
72
59
  });
73
60
  } catch {
74
61
  return {
@@ -87,8 +74,8 @@ const readForWidgetBreakdown = async (args) => {
87
74
  adapterId: adapter.id,
88
75
  dateRange,
89
76
  rows,
90
- clamped: result.meta.clamped ?? false,
91
- stale: result.meta.stale ?? false
77
+ ...readMeta(result),
78
+ noGoals: Array.isArray(goalSlugs) && goalSlugs.length === 0
92
79
  };
93
80
  };
94
81
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface BreakdownRow {\n\tlabel: string\n\tvalue: number\n\t/** Every metric the read asked for, present only when `extraMetrics` asked for more. */\n\tmetrics?: Partial<Record<MetricKey, number>>\n}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\tclamped?: boolean\n\t/** True when the engine served a stale cache entry after a failed provider read. */\n\tstale?: boolean\n}\n\nexport interface ReadForWidgetBreakdownArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\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\tfilters?: AnalyticsFilter[]\n\t/**\n\t * Further metrics to read alongside the ranked one, narrowed to what the source serves\n\t * so an unsupported one never turns the whole read unavailable. They reach each row's\n\t * `metrics`; ranking and status still follow `metric` alone.\n\t */\n\textraMetrics?: MetricKey[]\n}\n\n/**\n * Site-wide ranked breakdown of one metric by one dimension, read through the engine.\n * Mirrors `readForWidget` but gates on the dimension too and maps each result row to a\n * `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range, filters } = args\n\tconst emptyRows = [] as BreakdownRow[]\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, rows: emptyRows }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\tmetrics: [metric],\n\t\t\tdimensions: [dimension],\n\t\t\t...(filters && filters.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\tfilters: filters.map((f) => f.dimension),\n\t\t\t\t\t\tfilterOperators: filters.map((f) => f.operator),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t})\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst metrics = [\n\t\tmetric,\n\t\t...(args.extraMetrics ?? []).filter((m) => m !== metric && adapter.capabilities.metrics.has(m)),\n\t]\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await runtime.engine.read(adapter, {\n\t\t\tmetrics,\n\t\t\tdimensions: [dimension],\n\t\t\tdateRange,\n\t\t\tlimit,\n\t\t\torder: { metric, direction: 'desc' },\n\t\t\tfilters,\n\t\t\ttimezone: tz,\n\t\t\tscope: ctx.queryScope,\n\t\t})\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst rows = result.rows.map((row) => ({\n\t\tlabel: row.dimensions?.[dimension] ?? '(none)',\n\t\tvalue: row.metrics[metric] ?? 0,\n\t\t...(metrics.length > 1 ? { metrics: row.metrics } : {}),\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\trows,\n\t\tclamped: result.meta.clamped ?? false,\n\t\tstale: result.meta.stale ?? false,\n\t}\n}\n"],"mappings":";;;;;;;;;;AA8DA,MAAa,yBAAyB,OACrC,SACoC;CACpC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,OAAO,WAAW,KAAK,OAAO,YAAY;CACrF,MAAM,YAAY,CAAC;CAEnB,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,KAAK,KAAK,QAAQ;EAClE,MAAM;CACP;CAED,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB,WAAW,SAAS,iBAAiB,WAAW,KAAK,KAAK,QAAQ;EAClE,MAAM;CACP;CAED,MAAM,KAAK,KAAK,YAAa,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC7E,MAAM,YAAY,SAAS,iBAAiB,WAAW,KAAK,EAAE;CAC9D,MAAM,OAAO;EAAE;EAAW,MAAM;CAAU;CAC1C,MAAM,UAA4B,IAAI;CACtC,IAAI,CAAC,QAAQ,aAAa,GACzB,OAAO;EAAE,QAAQ;EAAkB,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEnE,IACC,CAAC,sBAAsB,QAAQ,cAAc;EAC5C,SAAS,CAAC,MAAM;EAChB,YAAY,CAAC,SAAS;EACtB,GAAI,WAAW,QAAQ,SAAS,IAC7B;GACA,SAAS,QAAQ,KAAK,MAAM,EAAE,SAAS;GACvC,iBAAiB,QAAQ,KAAK,MAAM,EAAE,QAAQ;EAC/C,IACC,CAAC;CACL,CAAC,GAED,OAAO;EAAE,QAAQ;EAAe,WAAW,QAAQ;EAAI,GAAG;CAAK;CAEhE,MAAM,UAAU,CACf,QACA,IAAI,KAAK,gBAAgB,CAAC,GAAG,QAAQ,MAAM,MAAM,UAAU,QAAQ,aAAa,QAAQ,IAAI,CAAC,CAAC,CAC/F;CACA,IAAI;CACJ,IAAI;EACH,SAAS,MAAM,QAAQ,OAAO,KAAK,SAAS;GAC3C;GACA,YAAY,CAAC,SAAS;GACtB;GACA;GACA,OAAO;IAAE;IAAQ,WAAW;GAAO;GACnC;GACA,UAAU;GACV,OAAO,IAAI;EACZ,CAAC;CACF,QAAQ;EAGP,OAAO;GAAE,QAAQ;GAAe,WAAW,QAAQ;GAAI,GAAG;EAAK;CAChE;CACA,MAAM,OAAO,OAAO,KAAK,KAAK,SAAS;EACtC,OAAO,IAAI,aAAa,cAAc;EACtC,OAAO,IAAI,QAAQ,WAAW;EAC9B,GAAI,QAAQ,SAAS,IAAI,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CACtD,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA;EACA,SAAS,OAAO,KAAK,WAAW;EAChC,OAAO,OAAO,KAAK,SAAS;CAC7B;AACD"}
1
+ {"version":3,"file":"readForWidgetBreakdown.js","names":[],"sources":["../../src/widgets/readForWidgetBreakdown.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tDateRange,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { prepareWidgetRead, type WidgetReadStatus } from './prepareWidgetRead'\nimport { readMeta } from './readMeta'\n\nexport interface BreakdownRow {\n\tlabel: string\n\tvalue: number\n\t/** Every metric the read asked for, present only when `extraMetrics` asked for more. */\n\tmetrics?: Partial<Record<MetricKey, number>>\n}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\tclamped?: boolean\n\t/** True when the engine served a stale cache entry after a failed provider read. */\n\tstale?: boolean\n\t/** True when the source answered without one of the filters the read carried. */\n\tfiltersUnapplied?: boolean\n\t/** True when the read hit the source's event scan cap, so the numbers are a floor. */\n\tsampled?: boolean\n\t/** True when the source could not read the scope's goals; the rows say nothing about them. */\n\tgoalsUnresolved?: boolean\n\t/** True when the read asked about goals and the scope configures none: an empty table. */\n\tnoGoals?: boolean\n}\n\nexport interface ReadForWidgetBreakdownArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\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\tfilters?: AnalyticsFilter[]\n\t/**\n\t * Further metrics to read alongside the ranked one, narrowed to what the source serves\n\t * so an unsupported one never turns the whole read unavailable. They reach each row's\n\t * `metrics`; ranking and status still follow `metric` alone.\n\t */\n\textraMetrics?: MetricKey[]\n\t/**\n\t * The scope's goal slugs, for a `goal` or `conversions` read, or `'unresolved'` when the\n\t * caller's own resolver failed. Resolved here when omitted, so a caller that already\n\t * resolved them (the goals table) does not resolve them twice.\n\t */\n\tgoalSlugs?: string[] | 'unresolved'\n}\n\n/**\n * Site-wide ranked breakdown of one metric by one dimension, read through the engine.\n * Mirrors `readForWidget` but gates on the dimension too and maps each result row to a\n * `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range, filters } = args\n\tconst emptyRows = [] as BreakdownRow[]\n\n\tconst metricsFor = (adapter: AnalyticsAdapter): MetricKey[] => [\n\t\tmetric,\n\t\t...(args.extraMetrics ?? []).filter((m) => m !== metric && adapter.capabilities.metrics.has(m)),\n\t]\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tscope: args.scope,\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics: [metric], dimensions: [dimension] },\n\t\tgoalRead: (adapter) => ({ metrics: metricsFor(adapter), dimensions: [dimension] }),\n\t\tgoalSlugs: args.goalSlugs,\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst { runtime, adapter, tz, dateRange, goalSlugs } = prepared\n\tconst base = { dateRange, rows: emptyRows }\n\tconst metrics = metricsFor(adapter)\n\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await runtime.engine.read(adapter, {\n\t\t\tmetrics,\n\t\t\tdimensions: [dimension],\n\t\t\tdateRange,\n\t\t\tlimit,\n\t\t\torder: { metric, direction: 'desc' },\n\t\t\tfilters,\n\t\t\ttimezone: tz,\n\t\t\tscope: prepared.queryScope,\n\t\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t\t})\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst rows = result.rows.map((row) => ({\n\t\tlabel: row.dimensions?.[dimension] ?? '(none)',\n\t\tvalue: row.metrics[metric] ?? 0,\n\t\t...(metrics.length > 1 ? { metrics: row.metrics } : {}),\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\trows,\n\t\t...readMeta(result),\n\t\t// The hint is set only for a read about goals, so an empty one is a scope that\n\t\t// configured none rather than a read that never asked.\n\t\tnoGoals: Array.isArray(goalSlugs) && goalSlugs.length === 0,\n\t}\n}\n"],"mappings":";;;;;;;;AA4EA,MAAa,yBAAyB,OACrC,SACoC;CACpC,MAAM,EAAE,KAAK,QAAQ,WAAW,WAAW,OAAO,WAAW,KAAK,OAAO,YAAY;CACrF,MAAM,YAAY,CAAC;CAEnB,MAAM,cAAc,YAA2C,CAC9D,QACA,IAAI,KAAK,gBAAgB,CAAC,GAAG,QAAQ,MAAM,MAAM,UAAU,QAAQ,aAAa,QAAQ,IAAI,CAAC,CAAC,CAC/F;CACA,MAAM,WAAW,MAAM,kBAAkB;EACxC;EACA;EACA;EACA;EACA,OAAO,KAAK;EACZ,UAAU,KAAK;EACf;EACA;EACA,UAAU;GAAE,SAAS,CAAC,MAAM;GAAG,YAAY,CAAC,SAAS;EAAE;EACvD,WAAW,aAAa;GAAE,SAAS,WAAW,OAAO;GAAG,YAAY,CAAC,SAAS;EAAE;EAChF,WAAW,KAAK;CACjB,CAAC;CACD,IAAI,CAAC,SAAS,IACb,OAAO;EACN,QAAQ,SAAS;EACjB,WAAW,SAAS;EACpB,WAAW,SAAS;EACpB,MAAM;CACP;CAED,MAAM,EAAE,SAAS,SAAS,IAAI,WAAW,cAAc;CACvD,MAAM,OAAO;EAAE;EAAW,MAAM;CAAU;CAC1C,MAAM,UAAU,WAAW,OAAO;CAClC,IAAI;CACJ,IAAI;EACH,SAAS,MAAM,QAAQ,OAAO,KAAK,SAAS;GAC3C;GACA,YAAY,CAAC,SAAS;GACtB;GACA;GACA,OAAO;IAAE;IAAQ,WAAW;GAAO;GACnC;GACA,UAAU;GACV,OAAO,SAAS;GAChB,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAChD,CAAC;CACF,QAAQ;EAGP,OAAO;GAAE,QAAQ;GAAe,WAAW,QAAQ;GAAI,GAAG;EAAK;CAChE;CACA,MAAM,OAAO,OAAO,KAAK,KAAK,SAAS;EACtC,OAAO,IAAI,aAAa,cAAc;EACtC,OAAO,IAAI,QAAQ,WAAW;EAC9B,GAAI,QAAQ,SAAS,IAAI,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;CACtD,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA;EACA,GAAG,SAAS,MAAM;EAGlB,SAAS,MAAM,QAAQ,SAAS,KAAK,UAAU,WAAW;CAC3D;AACD"}
@@ -1,6 +1,6 @@
1
1
  import { DateRange } from "../core/contract.js";
2
2
  import { TimeframePreset } from "../timeframe/presets.js";
3
- import { WidgetReadStatus } from "./readForWidget.js";
3
+ import { WidgetReadStatus } from "./prepareWidgetRead.js";
4
4
  import { PayloadRequest } from "payload";
5
5
 
6
6
  //#region src/widgets/readForWidgetGoals.d.ts
@@ -22,8 +22,18 @@ interface WidgetGoalsResult {
22
22
  rows: GoalRow[];
23
23
  /** Range total the rate divides by; absent when the source does not serve visitors. */
24
24
  siteVisitors?: number;
25
+ /** The source that answered, absent on a read that never reached one. */
26
+ provider?: string;
25
27
  clamped?: boolean;
26
28
  stale?: boolean;
29
+ /** True when the source answered without one of the filters a read carried. */
30
+ filtersUnapplied?: boolean;
31
+ /** True when a read hit the source's event scan cap, so the numbers are a floor. */
32
+ sampled?: boolean;
33
+ /** True when the source could not read the scope's goals, so the empty table means nothing. */
34
+ goalsUnresolved?: boolean;
35
+ /** True when the scope configures no goals at all, which is an empty table, not a failure. */
36
+ noGoals?: boolean;
27
37
  }
28
38
  interface ReadForWidgetGoalsArgs {
29
39
  req: PayloadRequest;
@@ -1,7 +1,7 @@
1
- import { getRuntime, resolveGoalsDetailedFor, resolveTimezoneFor } from "../plugin/runtime.js";
2
- import { resolveTimeframe } from "../timeframe/presets.js";
3
- import { resolveReadContext } from "../core/scopedRead.js";
4
- import { previousWindow } from "./comparison.js";
1
+ import { resolveGoalsDetailedFor } from "../plugin/runtime.js";
2
+ import { comparisonOf } from "../core/capabilities.js";
3
+ import { previousWindow, withinLookback } from "./comparison.js";
4
+ import { prepareWidgetRead } from "./prepareWidgetRead.js";
5
5
  import { readForWidget } from "./readForWidget.js";
6
6
  import { readForWidgetBreakdown } from "./readForWidgetBreakdown.js";
7
7
  import { conversionRate } from "../view/conversionRate.js";
@@ -16,7 +16,8 @@ const PREVIOUS_LIMIT_FACTOR = 4;
16
16
  const previousLimit = (limit) => Math.min(limit * PREVIOUS_LIMIT_FACTOR, 500);
17
17
  /**
18
18
  * Goal names for the read's own scope. A resolver that throws must not cost the widget its
19
- * table, so the rows fall back to their slugs.
19
+ * table, so the rows fall back to their slugs; the failure travels on as the hint, which is
20
+ * what tells the read apart from a scope that configured no goals at all.
20
21
  */
21
22
  const goalNames = async (runtime, req, scope) => {
22
23
  try {
@@ -24,7 +25,7 @@ const goalNames = async (runtime, req, scope) => {
24
25
  return new Map(resolved.map(({ goal }) => [goal.slug, goal.name]));
25
26
  } catch (err) {
26
27
  req.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`);
27
- return /* @__PURE__ */ new Map();
28
+ return "unresolved";
28
29
  }
29
30
  };
30
31
  /**
@@ -38,42 +39,51 @@ const goalNames = async (runtime, req, scope) => {
38
39
  */
39
40
  const readForWidgetGoals = async (args) => {
40
41
  const { req, timeframe, limit, compare, adapterId, now } = args;
41
- const fallback = (status, id) => ({
42
+ const fallback = (status, id, window) => ({
42
43
  status,
43
44
  adapterId: id,
44
- dateRange: args.range ?? resolveTimeframe(timeframe, now, args.timezone),
45
- timezone: args.timezone ?? "UTC",
46
- rows: []
45
+ rows: [],
46
+ ...window
47
47
  });
48
- const runtime = getRuntime(req.payload);
49
- if (!runtime) return fallback("unavailable", adapterId ?? "");
50
- const ctx = await resolveReadContext({
51
- runtime,
48
+ const prepared = await prepareWidgetRead({
52
49
  req,
50
+ now,
51
+ timeframe,
53
52
  adapterId,
54
- scope: args.scope
53
+ scope: args.scope,
54
+ timezone: args.timezone,
55
+ range: args.range
56
+ });
57
+ if (!prepared.ok) return fallback(prepared.status, prepared.adapterId, {
58
+ dateRange: prepared.dateRange,
59
+ timezone: prepared.tz
55
60
  });
56
- if (!ctx.ok) return fallback("unavailable", adapterId ?? "");
57
- const adapter = ctx.adapter;
58
- const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
59
- const dateRange = args.range ?? resolveTimeframe(timeframe, now, tz);
61
+ const { runtime, adapter, tz, dateRange } = prepared;
60
62
  const shared = {
61
63
  req,
62
64
  timeframe,
63
65
  adapterId: adapter.id,
64
- scope: ctx.scope,
66
+ scope: prepared.scope,
65
67
  timezone: tz,
66
68
  now
67
69
  };
68
- const comparisonRange = compare && runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
69
- const [breakdown, totals, previous, names] = await Promise.all([
70
+ const previousRange = compare && runtime.comparison && comparisonOf(adapter.capabilities) ? previousWindow(dateRange, tz) : null;
71
+ const comparisonRange = previousRange && withinLookback(previousRange, adapter.capabilities.maxLookbackDays, {
72
+ tz,
73
+ now
74
+ }) ? previousRange : void 0;
75
+ const resolved = await goalNames(runtime, req, prepared.scope);
76
+ const names = resolved === "unresolved" ? /* @__PURE__ */ new Map() : resolved;
77
+ const goalSlugs = resolved === "unresolved" ? "unresolved" : [...names.keys()];
78
+ const [breakdown, totals, previous] = await Promise.all([
70
79
  readForWidgetBreakdown({
71
80
  ...shared,
72
81
  range: dateRange,
73
82
  metric: "conversions",
74
83
  dimension: "goal",
75
84
  limit,
76
- extraMetrics: ["revenue", "visitors"]
85
+ extraMetrics: ["revenue", "visitors"],
86
+ goalSlugs
77
87
  }),
78
88
  adapter.capabilities.metrics.has("visitors") ? readForWidget({
79
89
  ...shared,
@@ -86,15 +96,14 @@ const readForWidgetGoals = async (args) => {
86
96
  range: comparisonRange,
87
97
  metric: "conversions",
88
98
  dimension: "goal",
89
- limit: previousLimit(limit)
90
- }) : void 0,
91
- goalNames(runtime, req, ctx.scope)
99
+ limit: previousLimit(limit),
100
+ goalSlugs
101
+ }) : void 0
92
102
  ]);
93
- if (breakdown.status !== "ok") return {
94
- ...fallback(breakdown.status, breakdown.adapterId),
103
+ if (breakdown.status !== "ok") return fallback(breakdown.status, breakdown.adapterId, {
95
104
  dateRange,
96
105
  timezone: tz
97
- };
106
+ });
98
107
  const previousBySlug = new Map((previous?.status === "ok" ? previous.rows : []).map((row) => [row.label, row.value]));
99
108
  const siteVisitors = totals?.status === "ok" ? totals.metrics.visitors : void 0;
100
109
  const rows = breakdown.rows.map((row) => {
@@ -116,8 +125,13 @@ const readForWidgetGoals = async (args) => {
116
125
  timezone: tz,
117
126
  rows,
118
127
  ...siteVisitors !== void 0 ? { siteVisitors } : {},
128
+ ...breakdown.provider === void 0 ? {} : { provider: breakdown.provider },
119
129
  clamped: Boolean(breakdown.clamped || totals?.clamped || previous?.clamped),
120
- stale: Boolean(breakdown.stale || totals?.stale || previous?.stale)
130
+ stale: Boolean(breakdown.stale || totals?.stale || previous?.stale),
131
+ filtersUnapplied: Boolean(breakdown.filtersUnapplied || totals?.filtersUnapplied || previous?.filtersUnapplied),
132
+ sampled: Boolean(breakdown.sampled || totals?.sampled || previous?.sampled),
133
+ goalsUnresolved: breakdown.goalsUnresolved === true,
134
+ noGoals: breakdown.noGoals === true
121
135
  };
122
136
  };
123
137
  //#endregion