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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (256) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +8 -2
  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.js +2 -1
  6. package/dist/adapters/plausible/plausible.js.map +1 -1
  7. package/dist/capture/slots.js +16 -5
  8. package/dist/capture/slots.js.map +1 -1
  9. package/dist/capture/trackerConfig.d.ts +1 -0
  10. package/dist/capture/trackerConfig.js +28 -3
  11. package/dist/capture/trackerConfig.js.map +1 -1
  12. package/dist/charts/BarList.d.ts +15 -1
  13. package/dist/charts/BarList.js +34 -18
  14. package/dist/charts/BarList.js.map +1 -1
  15. package/dist/charts/TrendChart.d.ts +16 -3
  16. package/dist/charts/TrendChart.js +172 -106
  17. package/dist/charts/TrendChart.js.map +1 -1
  18. package/dist/charts/bars.d.ts +2 -0
  19. package/dist/charts/bars.js +2 -1
  20. package/dist/charts/bars.js.map +1 -1
  21. package/dist/charts/bucket.js +10 -1
  22. package/dist/charts/bucket.js.map +1 -1
  23. package/dist/charts/spline.js +2 -2
  24. package/dist/charts/spline.js.map +1 -1
  25. package/dist/charts/styles.js +18 -1
  26. package/dist/charts/styles.js.map +1 -1
  27. package/dist/core/cacheKey.js +13 -1
  28. package/dist/core/cacheKey.js.map +1 -1
  29. package/dist/core/contract.d.ts +14 -7
  30. package/dist/core/contract.js +29 -1
  31. package/dist/core/contract.js.map +1 -1
  32. package/dist/core/granularity.js +1 -1
  33. package/dist/core/options.d.ts +54 -5
  34. package/dist/core/options.js +59 -2
  35. package/dist/core/options.js.map +1 -1
  36. package/dist/core/scopedRead.js +33 -23
  37. package/dist/core/scopedRead.js.map +1 -1
  38. package/dist/core/serverEvent.d.ts +42 -0
  39. package/dist/core/serverEvent.js +12 -0
  40. package/dist/core/serverEvent.js.map +1 -0
  41. package/dist/exports/client.d.ts +8 -2
  42. package/dist/exports/client.js +6 -1
  43. package/dist/exports/rsc.d.ts +5 -1
  44. package/dist/exports/rsc.js +6 -3
  45. package/dist/exports/types.d.ts +12 -4
  46. package/dist/exports/types.js +2 -2
  47. package/dist/fields/AnalyticsPanelClient.js +1 -1
  48. package/dist/fields/AnalyticsPanelField.js +1 -1
  49. package/dist/fields/AnalyticsStatField.js +2 -2
  50. package/dist/fields/config/MetricSelectField.js +2 -2
  51. package/dist/fields/config/MetricSelectField.js.map +1 -1
  52. package/dist/fields/config/SourceSelectField.js +2 -2
  53. package/dist/fields/config/SourceSelectField.js.map +1 -1
  54. package/dist/fields/config/fetchSources.d.ts +5 -1
  55. package/dist/fields/readForDocument.d.ts +5 -0
  56. package/dist/fields/readForDocument.js +5 -5
  57. package/dist/fields/readForDocument.js.map +1 -1
  58. package/dist/goals/GoalSelectField.d.ts +7 -0
  59. package/dist/goals/GoalSelectField.js +77 -0
  60. package/dist/goals/GoalSelectField.js.map +1 -0
  61. package/dist/goals/collection.js +250 -0
  62. package/dist/goals/collection.js.map +1 -0
  63. package/dist/goals/currency.js +14 -0
  64. package/dist/goals/currency.js.map +1 -0
  65. package/dist/goals/fetchGoals.d.ts +18 -0
  66. package/dist/goals/fetchGoals.js +29 -0
  67. package/dist/goals/fetchGoals.js.map +1 -0
  68. package/dist/goals/goalField.d.ts +31 -0
  69. package/dist/goals/goalField.js +56 -0
  70. package/dist/goals/goalField.js.map +1 -0
  71. package/dist/goals/goalsEndpoint.d.ts +1 -0
  72. package/dist/goals/goalsEndpoint.js +55 -0
  73. package/dist/goals/goalsEndpoint.js.map +1 -0
  74. package/dist/goals/resolver.d.ts +8 -0
  75. package/dist/goals/resolver.js +147 -0
  76. package/dist/goals/resolver.js.map +1 -0
  77. package/dist/goals/trackGoalAction.d.ts +74 -0
  78. package/dist/goals/trackGoalAction.js +139 -0
  79. package/dist/goals/trackGoalAction.js.map +1 -0
  80. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  81. package/dist/goals/useAnalyticsGoals.js +67 -0
  82. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  83. package/dist/index.d.ts +10 -3
  84. package/dist/index.js +74 -11
  85. package/dist/index.js.map +1 -1
  86. package/dist/native/ingest/device.js +11 -3
  87. package/dist/native/ingest/device.js.map +1 -1
  88. package/dist/native/ingest/endpoint.d.ts +1 -0
  89. package/dist/native/ingest/endpoint.js +2 -17
  90. package/dist/native/ingest/endpoint.js.map +1 -1
  91. package/dist/native/ingest/normalizeEvent.d.ts +20 -0
  92. package/dist/native/ingest/normalizeEvent.js +3 -2
  93. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  94. package/dist/native/ingest/serverTrack.d.ts +20 -0
  95. package/dist/native/ingest/serverTrack.js +99 -0
  96. package/dist/native/ingest/serverTrack.js.map +1 -0
  97. package/dist/native/ingest/validate.js +27 -0
  98. package/dist/native/ingest/validate.js.map +1 -0
  99. package/dist/native/nativeAdapter.d.ts +1 -1
  100. package/dist/native/nativeAdapter.js +21 -10
  101. package/dist/native/nativeAdapter.js.map +1 -1
  102. package/dist/native/retention/pruneTask.js +1 -1
  103. package/dist/native/rollups/insertIfNew.js +36 -2
  104. package/dist/native/rollups/insertIfNew.js.map +1 -1
  105. package/dist/plugin/documentEndpoint.js +27 -9
  106. package/dist/plugin/documentEndpoint.js.map +1 -1
  107. package/dist/plugin/paths.js +5 -1
  108. package/dist/plugin/paths.js.map +1 -1
  109. package/dist/plugin/queryEndpoint.js +113 -0
  110. package/dist/plugin/queryEndpoint.js.map +1 -0
  111. package/dist/plugin/readContextForRequest.js +71 -0
  112. package/dist/plugin/readContextForRequest.js.map +1 -0
  113. package/dist/plugin/realtimeEndpoint.js +6 -3
  114. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  115. package/dist/plugin/runtime.js +31 -1
  116. package/dist/plugin/runtime.js.map +1 -1
  117. package/dist/plugin/scopeFieldBoot.js +22 -0
  118. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  119. package/dist/plugin/sourcesEndpoint.js +13 -51
  120. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  121. package/dist/plugin/warmTask.js +0 -0
  122. package/dist/plugin/warmTask.js.map +1 -1
  123. package/dist/providers/collection.js +15 -9
  124. package/dist/providers/collection.js.map +1 -1
  125. package/dist/providers/resolver.js.map +1 -1
  126. package/dist/query/dates.js +64 -0
  127. package/dist/query/dates.js.map +1 -0
  128. package/dist/query/errors.d.ts +17 -0
  129. package/dist/query/errors.js +10 -0
  130. package/dist/query/errors.js.map +1 -0
  131. package/dist/query/fetchQuery.d.ts +59 -0
  132. package/dist/query/fetchQuery.js +110 -0
  133. package/dist/query/fetchQuery.js.map +1 -0
  134. package/dist/query/parse.d.ts +22 -0
  135. package/dist/query/parse.js +168 -0
  136. package/dist/query/parse.js.map +1 -0
  137. package/dist/query/response.d.ts +36 -0
  138. package/dist/timeframe/tz.js +17 -6
  139. package/dist/timeframe/tz.js.map +1 -1
  140. package/dist/translations/ar.js +98 -1
  141. package/dist/translations/ar.js.map +1 -1
  142. package/dist/translations/de.js +98 -1
  143. package/dist/translations/de.js.map +1 -1
  144. package/dist/translations/en.js +98 -1
  145. package/dist/translations/en.js.map +1 -1
  146. package/dist/translations/es.js +98 -1
  147. package/dist/translations/es.js.map +1 -1
  148. package/dist/translations/fr.js +98 -1
  149. package/dist/translations/fr.js.map +1 -1
  150. package/dist/translations/id.js +98 -1
  151. package/dist/translations/id.js.map +1 -1
  152. package/dist/translations/keys.d.ts +97 -0
  153. package/dist/translations/keys.js +98 -1
  154. package/dist/translations/keys.js.map +1 -1
  155. package/dist/translations/ko.js +98 -1
  156. package/dist/translations/ko.js.map +1 -1
  157. package/dist/translations/metricKeys.js +1 -1
  158. package/dist/translations/metricKeys.js.map +1 -1
  159. package/dist/translations/pt.js +98 -1
  160. package/dist/translations/pt.js.map +1 -1
  161. package/dist/translations/ru.js +98 -1
  162. package/dist/translations/ru.js.map +1 -1
  163. package/dist/translations/uk.js +98 -1
  164. package/dist/translations/uk.js.map +1 -1
  165. package/dist/translations/zh.js +98 -1
  166. package/dist/translations/zh.js.map +1 -1
  167. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  168. package/dist/view/AnalyticsNavLink.js +40 -0
  169. package/dist/view/AnalyticsNavLink.js.map +1 -0
  170. package/dist/view/AnalyticsView.d.ts +23 -0
  171. package/dist/view/AnalyticsView.js +45 -0
  172. package/dist/view/AnalyticsView.js.map +1 -0
  173. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  174. package/dist/view/AnalyticsViewClient.js +189 -0
  175. package/dist/view/AnalyticsViewClient.js.map +1 -0
  176. package/dist/view/authRedirect.js +32 -0
  177. package/dist/view/authRedirect.js.map +1 -0
  178. package/dist/view/conversionRate.js +18 -0
  179. package/dist/view/conversionRate.js.map +1 -0
  180. package/dist/view/dayRange.js +68 -0
  181. package/dist/view/dayRange.js.map +1 -0
  182. package/dist/view/gating.d.ts +1 -0
  183. package/dist/view/gating.js +105 -0
  184. package/dist/view/gating.js.map +1 -0
  185. package/dist/view/labels.js +44 -0
  186. package/dist/view/labels.js.map +1 -0
  187. package/dist/view/registerView.js +48 -0
  188. package/dist/view/registerView.js.map +1 -0
  189. package/dist/view/sections/Breakdowns.js +157 -0
  190. package/dist/view/sections/Breakdowns.js.map +1 -0
  191. package/dist/view/sections/EmptyStates.js +92 -0
  192. package/dist/view/sections/EmptyStates.js.map +1 -0
  193. package/dist/view/sections/FilterChips.js +41 -0
  194. package/dist/view/sections/FilterChips.js.map +1 -0
  195. package/dist/view/sections/GoalsPanel.js +81 -0
  196. package/dist/view/sections/GoalsPanel.js.map +1 -0
  197. package/dist/view/sections/OverviewCards.js +65 -0
  198. package/dist/view/sections/OverviewCards.js.map +1 -0
  199. package/dist/view/sections/RealtimeStrip.js +77 -0
  200. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  201. package/dist/view/sections/Toolbar.js +179 -0
  202. package/dist/view/sections/Toolbar.js.map +1 -0
  203. package/dist/view/sections/Trend.js +119 -0
  204. package/dist/view/sections/Trend.js.map +1 -0
  205. package/dist/view/sections/styles.js +74 -0
  206. package/dist/view/sections/styles.js.map +1 -0
  207. package/dist/view/state.js +206 -0
  208. package/dist/view/state.js.map +1 -0
  209. package/dist/view/useViewQueries.js +150 -0
  210. package/dist/view/useViewQueries.js.map +1 -0
  211. package/dist/view/viewProps.d.ts +40 -0
  212. package/dist/view/viewProps.js +90 -0
  213. package/dist/view/viewProps.js.map +1 -0
  214. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  215. package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
  216. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  217. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  218. package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
  219. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  220. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  221. package/dist/widgets/AnalyticsMetricWidget.js +35 -12
  222. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  223. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  224. package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
  225. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  226. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  227. package/dist/widgets/AnalyticsTrendWidget.js +51 -15
  228. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  229. package/dist/widgets/WidgetViewLink.js +17 -0
  230. package/dist/widgets/WidgetViewLink.js.map +1 -0
  231. package/dist/widgets/breakdownTypes.js +28 -1
  232. package/dist/widgets/breakdownTypes.js.map +1 -1
  233. package/dist/widgets/cardChrome.js +31 -7
  234. package/dist/widgets/cardChrome.js.map +1 -1
  235. package/dist/widgets/range.js +43 -12
  236. package/dist/widgets/range.js.map +1 -1
  237. package/dist/widgets/readForWidget.d.ts +12 -0
  238. package/dist/widgets/readForWidget.js +6 -5
  239. package/dist/widgets/readForWidget.js.map +1 -1
  240. package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
  241. package/dist/widgets/readForWidgetBreakdown.js +10 -7
  242. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  243. package/dist/widgets/readForWidgetGoals.d.ts +57 -0
  244. package/dist/widgets/readForWidgetGoals.js +126 -0
  245. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  246. package/dist/widgets/readForWidgetSeries.d.ts +13 -0
  247. package/dist/widgets/readForWidgetSeries.js +30 -12
  248. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  249. package/dist/widgets/registerWidgets.js +49 -6
  250. package/dist/widgets/registerWidgets.js.map +1 -1
  251. package/dist/widgets/types.js +12 -1
  252. package/dist/widgets/types.js.map +1 -1
  253. package/dist/widgets/viewLink.d.ts +22 -0
  254. package/dist/widgets/viewLink.js +83 -0
  255. package/dist/widgets/viewLink.js.map +1 -0
  256. package/package.json +9 -4
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsTrendWidget.js","names":[],"sources":["../../src/widgets/AnalyticsTrendWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport { bucketByRange, bucketSeries } from '../charts/bucket'\nimport { TrendChart } from '../charts/TrendChart'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetSeries } from './readForWidgetSeries'\nimport type { MetricWidgetData } from './types'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nexport default async function AnalyticsTrendWidget(props: WidgetServerProps) {\n\tconst data = (props.widgetData ?? {}) as MetricWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\tconst customRange = resolveCustomRange(rawTimeframe, data.range)\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst title = data.title?.trim() || t(METRIC_KEYS[metric])\n\n\tconst result = await readForWidgetSeries({\n\t\treq: props.req,\n\t\tmetric,\n\t\ttimeframe,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t})\n\n\tif (result.status !== 'ok') {\n\t\treturn (\n\t\t\t<div className=\"analytics-trend-widget\" style={cardStyle}>\n\t\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst caption = customRange\n\t\t? formatRangeCaption(customRange, locale)\n\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst buckets = customRange\n\t\t? bucketByRange(result.points, customRange, result.timezone)\n\t\t: bucketSeries(result.points, timeframe, result.timezone)\n\tconst trendPoints = buckets.map((b) => ({\n\t\t...b,\n\t\tdisplay: formatMetricValue(metric, b.value, locale),\n\t}))\n\treturn (\n\t\t<div className=\"analytics-trend-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t<span\n\t\t\t\tstyle={{\n\t\t\t\t\tfontSize: '1.75rem',\n\t\t\t\t\tfontWeight: 700,\n\t\t\t\t\tlineHeight: 1.1,\n\t\t\t\t\tcolor: 'var(--theme-elevation-800)',\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t{formatMetricValue(metric, result.total, locale)}\n\t\t\t</span>\n\t\t\t<TrendChart buckets={trendPoints} ariaLabel={`${title} ${caption}`} minHeight={180} />\n\t\t\t<span style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }}>{caption}</span>\n\t\t\t{result.comparisonRange ? (\n\t\t\t\t<ComparisonDelta\n\t\t\t\t\tcurrent={result.total}\n\t\t\t\t\tprevious={result.previousTotal}\n\t\t\t\t\tmetric={metric}\n\t\t\t\t\tlocale={locale}\n\t\t\t\t\tt={t}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{result.clamped ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateClamped)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,MAAM,YAAqE;CAC1E,kBAAkB,KAAK;CACvB,aAAa,KAAK;AACnB;AAEA,eAA8B,qBAAqB,OAA0B;CAC5E,MAAM,OAAQ,MAAM,cAAc,CAAC;CACnC,MAAM,SAAoB,KAAK,UAAU;CACzC,MAAM,eAAe,KAAK,aAAa;CACvC,MAAM,cAAc,mBAAmB,cAAc,KAAK,KAAK;CAC/D,MAAM,YAA6B,iBAAiB,WAAW,eAAe;CAC9E,MAAM,IAAI,YAAY,MAAM,IAAI,KAAK,CAAC;CACtC,MAAM,SAAS,MAAM,IAAI,KAAK,YAAY;CAC1C,MAAM,QAAQ,KAAK,OAAO,KAAK,KAAK,EAAE,YAAY,OAAO;CAEzD,MAAM,SAAS,MAAM,oBAAoB;EACxC,KAAK,MAAM;EACX;EACA;EACA,WAAW,KAAK;EAChB,qBAAK,IAAI,KAAK;EACd,OAAO;CACR,CAAC;CAED,IAAI,OAAO,WAAW,MACrB,OACC,qBAAC,OAAD;EAAK,WAAU;EAAyB,OAAO;YAA/C,CACC,oBAAC,QAAD;GAAM,OAAO;aAAa;EAAY,CAAA,GACtC,oBAAC,QAAD;GAAM,OAAO,EAAE,OAAO,6BAA6B;aAAI,EAAE,UAAU,OAAO,OAAO;EAAQ,CAAA,CACrF;;CAIP,MAAM,UAAU,cACb,mBAAmB,aAAa,MAAM,IACtC,EAAE,eAAe,UAAU;CAI9B,MAAM,eAHU,cACb,cAAc,OAAO,QAAQ,aAAa,OAAO,QAAQ,IACzD,aAAa,OAAO,QAAQ,WAAW,OAAO,QAAQ,GAC7B,KAAK,OAAO;EACvC,GAAG;EACH,SAAS,kBAAkB,QAAQ,EAAE,OAAO,MAAM;CACnD,EAAE;CACF,OACC,qBAAC,OAAD;EAAK,WAAU;EAAyB,OAAO;YAA/C;GACC,oBAAC,QAAD;IAAM,OAAO;cAAa;GAAY,CAAA;GACtC,oBAAC,QAAD;IACC,OAAO;KACN,UAAU;KACV,YAAY;KACZ,YAAY;KACZ,OAAO;IACR;cAEC,kBAAkB,QAAQ,OAAO,OAAO,MAAM;GAC1C,CAAA;GACN,oBAAC,YAAD;IAAY,SAAS;IAAa,WAAW,GAAG,MAAM,GAAG;IAAW,WAAW;GAAM,CAAA;GACrF,oBAAC,QAAD;IAAM,OAAO;KAAE,UAAU;KAAW,OAAO;IAA6B;cAAI;GAAc,CAAA;GACzF,OAAO,kBACP,oBAAC,iBAAD;IACC,SAAS,OAAO;IAChB,UAAU,OAAO;IACT;IACA;IACL;GACH,CAAA,IACE;GACH,OAAO,UACP,oBAAC,QAAD;IAAM,OAAO;KAAE,UAAU;KAAa,OAAO;IAA6B;cACxE,EAAE,KAAK,YAAY;GACf,CAAA,IACH;EACA;;AAEP"}
1
+ {"version":3,"file":"AnalyticsTrendWidget.js","names":[],"sources":["../../src/widgets/AnalyticsTrendWidget.tsx"],"sourcesContent":["import type { WidgetServerProps } from 'payload'\nimport { bucketByRange, bucketSeries, onPrimaryAxis } from '../charts/bucket'\nimport { TrendChart } from '../charts/TrendChart'\nimport type { MetricKey } from '../core/contract'\nimport { formatMetricValue } from '../fields/format'\nimport { requestTimezone } from '../plugin/runtime'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { asTranslate } from '../translations/server'\nimport { ComparisonDelta } from './ComparisonDelta'\nimport { cardStyle, labelStyle } from './cardChrome'\nimport { formatRangeCaption, resolveCustomRange } from './range'\nimport type { WidgetReadStatus } from './readForWidget'\nimport { readForWidgetSeries } from './readForWidgetSeries'\nimport type { MetricWidgetData } from './types'\nimport { type WidgetViewProps, widgetViewHref } from './viewLink'\nimport { WidgetViewLink } from './WidgetViewLink'\n\nconst STATE_KEY: Record<Exclude<WidgetReadStatus, 'ok'>, TranslationKey> = {\n\t'not-configured': keys.stateNotConfigured,\n\tunavailable: keys.stateUnavailable,\n}\n\nexport default async function AnalyticsTrendWidget(props: WidgetServerProps & WidgetViewProps) {\n\tconst data = (props.widgetData ?? {}) as MetricWidgetData\n\tconst metric: MetricKey = data.metric ?? 'pageviews'\n\tconst rawTimeframe = data.timeframe ?? 'last30days'\n\t// Only a custom range needs the reporting timezone before the read; a preset window\n\t// resolves inside the read path, which resolves the timezone there as it always has.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(props.req) : undefined\n\tconst customRange = timezone ? resolveCustomRange(rawTimeframe, data.range, timezone) : undefined\n\tconst timeframe: TimeframePreset = rawTimeframe === 'custom' ? 'last30days' : rawTimeframe\n\tconst t = asTranslate(props.req.i18n.t)\n\tconst locale = props.req.i18n.language ?? 'en-US'\n\tconst title = data.title?.trim() || t(METRIC_KEYS[metric])\n\n\tconst compare = data.compare === true\n\tconst result = await readForWidgetSeries({\n\t\treq: props.req,\n\t\tmetric,\n\t\ttimeframe,\n\t\tadapterId: data.dataSource,\n\t\tnow: new Date(),\n\t\trange: customRange,\n\t\tcompare,\n\t\t...(timezone ? { timezone } : {}),\n\t})\n\t// The adapter that answered, which on a scoped or runtime-provider install is not the\n\t// id the widget asked for.\n\tconst href = widgetViewHref(props.view, props.req, {\n\t\ttimeframe: rawTimeframe,\n\t\ttimezone: timezone ?? DEFAULT_TIMEZONE,\n\t\t...(customRange ? { range: customRange } : {}),\n\t\t...(result.adapterId ? { source: result.adapterId } : {}),\n\t\tmetric,\n\t\tcompare,\n\t})\n\n\tif (result.status !== 'ok') {\n\t\treturn (\n\t\t\t<div className=\"analytics-trend-widget\" style={cardStyle}>\n\t\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t\t<span style={{ color: 'var(--theme-elevation-400)' }}>{t(STATE_KEY[result.status])}</span>\n\t\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t\t</div>\n\t\t)\n\t}\n\n\tconst caption =\n\t\tcustomRange && timezone\n\t\t\t? formatRangeCaption(customRange, locale, timezone)\n\t\t\t: t(TIMEFRAME_KEYS[timeframe])\n\tconst buckets = customRange\n\t\t? bucketByRange(result.points, customRange, result.timezone)\n\t\t: bucketSeries(result.points, timeframe, result.timezone)\n\tconst toPoints = (source: typeof buckets) =>\n\t\tsource.map((b) => ({ ...b, display: formatMetricValue(metric, b.value, locale) }))\n\tconst trendPoints = toPoints(buckets)\n\t// The comparison is re-dated onto the primary axis before bucketing: at week and month\n\t// units its own dates would fall on different boundaries.\n\tconst previousSeries =\n\t\tcompare && result.comparisonPoints\n\t\t\t? onPrimaryAxis(result.comparisonPoints, result.points)\n\t\t\t: undefined\n\tconst comparisonPoints = previousSeries\n\t\t? toPoints(\n\t\t\t\tcustomRange\n\t\t\t\t\t? bucketByRange(previousSeries, customRange, result.timezone)\n\t\t\t\t\t: bucketSeries(previousSeries, timeframe, result.timezone)\n\t\t\t)\n\t\t: undefined\n\treturn (\n\t\t<div className=\"analytics-trend-widget\" style={cardStyle}>\n\t\t\t<span style={labelStyle}>{title}</span>\n\t\t\t<span\n\t\t\t\tstyle={{\n\t\t\t\t\tfontSize: '1.75rem',\n\t\t\t\t\tfontWeight: 700,\n\t\t\t\t\tlineHeight: 1.1,\n\t\t\t\t\tcolor: 'var(--theme-elevation-800)',\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t{formatMetricValue(metric, result.total, locale)}\n\t\t\t</span>\n\t\t\t<TrendChart\n\t\t\t\tbuckets={trendPoints}\n\t\t\t\t{...(comparisonPoints && result.comparisonRange\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcomparison: comparisonPoints,\n\t\t\t\t\t\t\tcomparisonLabel: t(keys.viewTrendPrevious),\n\t\t\t\t\t\t\tcomparisonRange: formatRangeCaption(result.comparisonRange, locale, result.timezone),\n\t\t\t\t\t\t\tlabel: title,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {})}\n\t\t\t\tariaLabel={`${title} ${caption}`}\n\t\t\t\tminHeight={180}\n\t\t\t/>\n\t\t\t<span style={{ fontSize: '0.75rem', color: 'var(--theme-elevation-400)' }}>{caption}</span>\n\t\t\t{result.comparisonRange ? (\n\t\t\t\t<ComparisonDelta\n\t\t\t\t\tcurrent={result.total}\n\t\t\t\t\tprevious={result.previousTotal}\n\t\t\t\t\tmetric={metric}\n\t\t\t\t\tlocale={locale}\n\t\t\t\t\tt={t}\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t{result.clamped ? (\n\t\t\t\t<span style={{ fontSize: '0.6875rem', color: 'var(--theme-elevation-400)' }}>\n\t\t\t\t\t{t(keys.stateClamped)}\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t<WidgetViewLink href={href} label={t(keys.widgetOpenInView)} />\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAM,YAAqE;CAC1E,kBAAkB,KAAK;CACvB,aAAa,KAAK;AACnB;AAEA,eAA8B,qBAAqB,OAA4C;CAC9F,MAAM,OAAQ,MAAM,cAAc,CAAC;CACnC,MAAM,SAAoB,KAAK,UAAU;CACzC,MAAM,eAAe,KAAK,aAAa;CAGvC,MAAM,WA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linkStyle } from "./cardChrome.js";
2
+ import { jsx } from "react/jsx-runtime";
3
+ //#region src/widgets/WidgetViewLink.tsx
4
+ /**
5
+ * A built-in widget's footer link into the analytics view. Renders nothing without an
6
+ * href, which is how a widget carries "the app turned the view off" through to the markup.
7
+ */
8
+ const WidgetViewLink = ({ href, label }) => href === void 0 ? null : /* @__PURE__ */ jsx("a", {
9
+ className: "analytics-widget__link",
10
+ href,
11
+ style: linkStyle,
12
+ children: label
13
+ });
14
+ //#endregion
15
+ export { WidgetViewLink };
16
+
17
+ //# sourceMappingURL=WidgetViewLink.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WidgetViewLink.js","names":[],"sources":["../../src/widgets/WidgetViewLink.tsx"],"sourcesContent":["import { linkStyle } from './cardChrome'\n\n/**\n * A built-in widget's footer link into the analytics view. Renders nothing without an\n * href, which is how a widget carries \"the app turned the view off\" through to the markup.\n */\nexport const WidgetViewLink = ({ href, label }: { href?: string; label: string }) =>\n\thref === undefined ? null : (\n\t\t<a className=\"analytics-widget__link\" href={href} style={linkStyle}>\n\t\t\t{label}\n\t\t</a>\n\t)\n"],"mappings":";;;;;;;AAMA,MAAa,kBAAkB,EAAE,MAAM,YACtC,SAAS,KAAA,IAAY,OACpB,oBAAC,KAAD;CAAG,WAAU;CAA+B;CAAM,OAAO;WACvD;AACC,CAAA"}
@@ -24,7 +24,34 @@ const BREAKDOWN_SPECS = [
24
24
  {
25
25
  slug: "analytics-breakdown-goals",
26
26
  dimension: "goal",
27
- label: keys.widgetBreakdownGoals
27
+ label: keys.widgetBreakdownGoals,
28
+ preferredDefault: "conversions"
29
+ },
30
+ {
31
+ slug: "analytics-breakdown-referrers",
32
+ dimension: "referrer",
33
+ label: keys.widgetBreakdownReferrers
34
+ },
35
+ {
36
+ slug: "analytics-breakdown-browsers",
37
+ dimension: "browser",
38
+ label: keys.widgetBreakdownBrowsers
39
+ },
40
+ {
41
+ slug: "analytics-breakdown-os",
42
+ dimension: "os",
43
+ label: keys.widgetBreakdownOs
44
+ },
45
+ {
46
+ slug: "analytics-breakdown-campaigns",
47
+ dimension: "utmCampaign",
48
+ label: keys.widgetBreakdownCampaigns
49
+ },
50
+ {
51
+ slug: "analytics-breakdown-events",
52
+ dimension: "event",
53
+ label: keys.widgetBreakdownEvents,
54
+ preferredDefault: "events"
28
55
  }
29
56
  ];
30
57
  const breakdownSpecBySlug = (slug) => BREAKDOWN_SPECS.find((s) => s.slug === slug);
@@ -1 +1 @@
1
- {"version":3,"file":"breakdownTypes.js","names":[],"sources":["../../src/widgets/breakdownTypes.ts"],"sourcesContent":["import type { DimensionKey, MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport type { WidgetRange } from './types'\n\nexport interface BreakdownWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tlimit?: number\n\tdataSource?: string\n}\n\nexport interface BreakdownSpec {\n\tslug: string\n\tdimension: DimensionKey\n\tlabel: TranslationKey\n}\n\nexport const BREAKDOWN_SPECS: BreakdownSpec[] = [\n\t{ slug: 'analytics-breakdown-pages', dimension: 'page', label: keys.widgetBreakdownPages },\n\t{ slug: 'analytics-breakdown-sources', dimension: 'source', label: keys.widgetBreakdownSources },\n\t{ slug: 'analytics-breakdown-devices', dimension: 'device', label: keys.widgetBreakdownDevices },\n\t{\n\t\tslug: 'analytics-breakdown-countries',\n\t\tdimension: 'country',\n\t\tlabel: keys.widgetBreakdownCountries,\n\t},\n\t{ slug: 'analytics-breakdown-goals', dimension: 'goal', label: keys.widgetBreakdownGoals },\n]\n\nexport const breakdownSpecBySlug = (slug: string): BreakdownSpec | undefined =>\n\tBREAKDOWN_SPECS.find((s) => s.slug === slug)\n"],"mappings":";;AAoBA,MAAa,kBAAmC;CAC/C;EAAE,MAAM;EAA6B,WAAW;EAAQ,OAAO,KAAK;CAAqB;CACzF;EAAE,MAAM;EAA+B,WAAW;EAAU,OAAO,KAAK;CAAuB;CAC/F;EAAE,MAAM;EAA+B,WAAW;EAAU,OAAO,KAAK;CAAuB;CAC/F;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAA6B,WAAW;EAAQ,OAAO,KAAK;CAAqB;AAC1F;AAEA,MAAa,uBAAuB,SACnC,gBAAgB,MAAM,MAAM,EAAE,SAAS,IAAI"}
1
+ {"version":3,"file":"breakdownTypes.js","names":[],"sources":["../../src/widgets/breakdownTypes.ts"],"sourcesContent":["import type { DimensionKey, MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport type { WidgetRange } from './types'\n\nexport interface BreakdownWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tlimit?: number\n\tdataSource?: string\n}\n\nexport interface BreakdownSpec {\n\tslug: string\n\tdimension: DimensionKey\n\tlabel: TranslationKey\n\tpreferredDefault?: MetricKey\n}\n\nexport const BREAKDOWN_SPECS: BreakdownSpec[] = [\n\t{ slug: 'analytics-breakdown-pages', dimension: 'page', label: keys.widgetBreakdownPages },\n\t{ slug: 'analytics-breakdown-sources', dimension: 'source', label: keys.widgetBreakdownSources },\n\t{ slug: 'analytics-breakdown-devices', dimension: 'device', label: keys.widgetBreakdownDevices },\n\t{\n\t\tslug: 'analytics-breakdown-countries',\n\t\tdimension: 'country',\n\t\tlabel: keys.widgetBreakdownCountries,\n\t},\n\t{\n\t\tslug: 'analytics-breakdown-goals',\n\t\tdimension: 'goal',\n\t\tlabel: keys.widgetBreakdownGoals,\n\t\t// A goals breakdown is a conversion table: pageviews per goal is a stranger default.\n\t\tpreferredDefault: 'conversions',\n\t},\n\t{\n\t\tslug: 'analytics-breakdown-referrers',\n\t\tdimension: 'referrer',\n\t\tlabel: keys.widgetBreakdownReferrers,\n\t},\n\t{\n\t\tslug: 'analytics-breakdown-browsers',\n\t\tdimension: 'browser',\n\t\tlabel: keys.widgetBreakdownBrowsers,\n\t},\n\t{ slug: 'analytics-breakdown-os', dimension: 'os', label: keys.widgetBreakdownOs },\n\t{\n\t\tslug: 'analytics-breakdown-campaigns',\n\t\tdimension: 'utmCampaign',\n\t\tlabel: keys.widgetBreakdownCampaigns,\n\t},\n\t{\n\t\tslug: 'analytics-breakdown-events',\n\t\tdimension: 'event',\n\t\tlabel: keys.widgetBreakdownEvents,\n\t\tpreferredDefault: 'events',\n\t},\n]\n\nexport const breakdownSpecBySlug = (slug: string): BreakdownSpec | undefined =>\n\tBREAKDOWN_SPECS.find((s) => s.slug === slug)\n"],"mappings":";;AAqBA,MAAa,kBAAmC;CAC/C;EAAE,MAAM;EAA6B,WAAW;EAAQ,OAAO,KAAK;CAAqB;CACzF;EAAE,MAAM;EAA+B,WAAW;EAAU,OAAO,KAAK;CAAuB;CAC/F;EAAE,MAAM;EAA+B,WAAW;EAAU,OAAO,KAAK;CAAuB;CAC/F;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;CACb;CACA;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;EAEZ,kBAAkB;CACnB;CACA;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;CACb;CACA;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;CACb;CACA;EAAE,MAAM;EAA0B,WAAW;EAAM,OAAO,KAAK;CAAkB;CACjF;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;CACb;CACA;EACC,MAAM;EACN,WAAW;EACX,OAAO,KAAK;EACZ,kBAAkB;CACnB;AACD;AAEA,MAAa,uBAAuB,SACnC,gBAAgB,MAAM,MAAM,EAAE,SAAS,IAAI"}
@@ -1,22 +1,46 @@
1
1
  //#region src/widgets/cardChrome.ts
2
- const cardStyle = {
3
- display: "flex",
4
- flexDirection: "column",
2
+ /**
3
+ * The card chrome, as token values rather than only as style objects: the widgets apply them
4
+ * inline (they are server-rendered and the package ships no stylesheet), while the analytics
5
+ * view interpolates the same values into its own injected CSS, where hover and pressed states
6
+ * need real selectors. One definition, so the two surfaces cannot drift apart.
7
+ */
8
+ const CARD_CHROME = {
5
9
  gap: "0.375rem",
6
10
  padding: "var(--base, 1rem)",
7
11
  background: "var(--theme-elevation-50)",
8
12
  border: "1px solid var(--theme-elevation-150)",
9
- borderRadius: "var(--style-radius-m, 6px)",
10
- boxSizing: "border-box"
13
+ radius: "var(--style-radius-m, 6px)"
11
14
  };
12
- const labelStyle = {
15
+ const CARD_LABEL = {
13
16
  fontSize: "0.6875rem",
14
17
  fontWeight: 600,
15
18
  letterSpacing: "0.04em",
16
19
  textTransform: "uppercase",
17
20
  color: "var(--theme-elevation-500)"
18
21
  };
22
+ const cardStyle = {
23
+ display: "flex",
24
+ flexDirection: "column",
25
+ gap: CARD_CHROME.gap,
26
+ padding: CARD_CHROME.padding,
27
+ background: CARD_CHROME.background,
28
+ border: CARD_CHROME.border,
29
+ borderRadius: CARD_CHROME.radius,
30
+ boxSizing: "border-box"
31
+ };
32
+ const labelStyle = { ...CARD_LABEL };
33
+ /** The card's footer link. `marginTop: auto` floors it, so cards of a row line their links up. */
34
+ const linkStyle = {
35
+ marginTop: "auto",
36
+ alignSelf: "flex-start",
37
+ fontSize: "0.75rem",
38
+ fontWeight: 500,
39
+ color: "var(--theme-elevation-500)",
40
+ textDecoration: "underline",
41
+ textUnderlineOffset: "2px"
42
+ };
19
43
  //#endregion
20
- export { cardStyle, labelStyle };
44
+ export { CARD_CHROME, CARD_LABEL, cardStyle, labelStyle, linkStyle };
21
45
 
22
46
  //# sourceMappingURL=cardChrome.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cardChrome.js","names":[],"sources":["../../src/widgets/cardChrome.ts"],"sourcesContent":["import type { CSSProperties } from 'react'\n\nexport const cardStyle: CSSProperties = {\n\tdisplay: 'flex',\n\tflexDirection: 'column',\n\tgap: '0.375rem',\n\tpadding: 'var(--base, 1rem)',\n\tbackground: 'var(--theme-elevation-50)',\n\tborder: '1px solid var(--theme-elevation-150)',\n\tborderRadius: 'var(--style-radius-m, 6px)',\n\tboxSizing: 'border-box',\n}\n\nexport const labelStyle: CSSProperties = {\n\tfontSize: '0.6875rem',\n\tfontWeight: 600,\n\tletterSpacing: '0.04em',\n\ttextTransform: 'uppercase',\n\tcolor: 'var(--theme-elevation-500)',\n}\n"],"mappings":";AAEA,MAAa,YAA2B;CACvC,SAAS;CACT,eAAe;CACf,KAAK;CACL,SAAS;CACT,YAAY;CACZ,QAAQ;CACR,cAAc;CACd,WAAW;AACZ;AAEA,MAAa,aAA4B;CACxC,UAAU;CACV,YAAY;CACZ,eAAe;CACf,eAAe;CACf,OAAO;AACR"}
1
+ {"version":3,"file":"cardChrome.js","names":[],"sources":["../../src/widgets/cardChrome.ts"],"sourcesContent":["import type { CSSProperties } from 'react'\n\n/**\n * The card chrome, as token values rather than only as style objects: the widgets apply them\n * inline (they are server-rendered and the package ships no stylesheet), while the analytics\n * view interpolates the same values into its own injected CSS, where hover and pressed states\n * need real selectors. One definition, so the two surfaces cannot drift apart.\n */\nexport const CARD_CHROME = {\n\tgap: '0.375rem',\n\tpadding: 'var(--base, 1rem)',\n\tbackground: 'var(--theme-elevation-50)',\n\tborder: '1px solid var(--theme-elevation-150)',\n\tradius: 'var(--style-radius-m, 6px)',\n} as const\n\nexport const CARD_LABEL = {\n\tfontSize: '0.6875rem',\n\tfontWeight: 600,\n\tletterSpacing: '0.04em',\n\ttextTransform: 'uppercase',\n\tcolor: 'var(--theme-elevation-500)',\n} as const\n\nexport const cardStyle: CSSProperties = {\n\tdisplay: 'flex',\n\tflexDirection: 'column',\n\tgap: CARD_CHROME.gap,\n\tpadding: CARD_CHROME.padding,\n\tbackground: CARD_CHROME.background,\n\tborder: CARD_CHROME.border,\n\tborderRadius: CARD_CHROME.radius,\n\tboxSizing: 'border-box',\n}\n\nexport const labelStyle: CSSProperties = { ...CARD_LABEL }\n\n/** The card's footer link. `marginTop: auto` floors it, so cards of a row line their links up. */\nexport const linkStyle: CSSProperties = {\n\tmarginTop: 'auto',\n\talignSelf: 'flex-start',\n\tfontSize: '0.75rem',\n\tfontWeight: 500,\n\tcolor: 'var(--theme-elevation-500)',\n\ttextDecoration: 'underline',\n\ttextUnderlineOffset: '2px',\n}\n"],"mappings":";;;;;;;AAQA,MAAa,cAAc;CAC1B,KAAK;CACL,SAAS;CACT,YAAY;CACZ,QAAQ;CACR,QAAQ;AACT;AAEA,MAAa,aAAa;CACzB,UAAU;CACV,YAAY;CACZ,eAAe;CACf,eAAe;CACf,OAAO;AACR;AAEA,MAAa,YAA2B;CACvC,SAAS;CACT,eAAe;CACf,KAAK,YAAY;CACjB,SAAS,YAAY;CACrB,YAAY,YAAY;CACxB,QAAQ,YAAY;CACpB,cAAc,YAAY;CAC1B,WAAW;AACZ;AAEA,MAAa,aAA4B,EAAE,GAAG,WAAW;;AAGzD,MAAa,YAA2B;CACvC,WAAW;CACX,WAAW;CACX,UAAU;CACV,YAAY;CACZ,OAAO;CACP,gBAAgB;CAChB,qBAAqB;AACtB"}
@@ -1,27 +1,58 @@
1
+ import { zonedCalendarDay } from "../timeframe/tz.js";
2
+ import { DATE_ONLY, parseDayOrInstant } from "../query/dates.js";
1
3
  //#region src/widgets/range.ts
4
+ const NOON_MS = 12 * 36e5;
2
5
  /**
3
- * Resolve a widget's explicit custom range to a concrete DateRange, or undefined when
4
- * the widget is on a relative preset, the custom range is incomplete, or either bound
5
- * is an unparseable date (a corrupt or hand-set widgetData would otherwise reach the
6
- * cache key and throw on `toISOString`).
6
+ * The calendar day a stored bound names. The `dayOnly` picker stores the picked day at the
7
+ * admin browser's local midnight, so the instant lands on that day or the one before it in
8
+ * UTC depending on the browser's offset; a 12-hour shift recovers the picked day for every
9
+ * offset in (-12, +12]. Zones at +12:45 and beyond (Chatham in DST, Kiritimati) recover the
10
+ * day before, and the uninhabited UTC-12 the day after.
7
11
  */
8
- const resolveCustomRange = (timeframe, range) => {
12
+ const pickedDay = (raw) => {
13
+ if (DATE_ONLY.test(raw)) return raw;
14
+ const instant = new Date(raw);
15
+ if (Number.isNaN(instant.getTime())) return null;
16
+ return zonedCalendarDay(new Date(instant.getTime() + NOON_MS), "UTC");
17
+ };
18
+ /**
19
+ * Resolve a widget's explicit custom range to a concrete DateRange, or undefined when the
20
+ * widget is on a relative preset, the custom range is incomplete, or either bound names no
21
+ * real day (a corrupt or hand-set widgetData would otherwise reach the cache key and throw
22
+ * on `toISOString`). The two picked days are read inclusively in `timezone`, the reporting
23
+ * timezone the read resolves in: `from` at the first instant of its day, `to` at the last.
24
+ */
25
+ const resolveCustomRange = (timeframe, range, timezone) => {
9
26
  if (timeframe !== "custom" || !range?.from || !range?.to) return;
10
- const start = new Date(range.from);
11
- const end = new Date(range.to);
12
- if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return;
27
+ const fromDay = pickedDay(range.from);
28
+ const toDay = pickedDay(range.to);
29
+ if (!fromDay || !toDay) return;
30
+ const start = parseDayOrInstant(fromDay, {
31
+ timezone,
32
+ edge: "start"
33
+ });
34
+ const end = parseDayOrInstant(toDay, {
35
+ timezone,
36
+ edge: "end"
37
+ });
38
+ if (!start || !end) return;
13
39
  return {
14
40
  start,
15
41
  end
16
42
  };
17
43
  };
18
- const formatDay = (d, locale) => d.toLocaleDateString(locale, {
44
+ const formatDay = (d, locale, timeZone) => d.toLocaleDateString(locale, {
19
45
  month: "short",
20
46
  day: "numeric",
21
- year: "numeric"
47
+ year: "numeric",
48
+ timeZone
22
49
  });
23
- /** Server-side caption for a custom range, e.g. "Jun 1, 2026 - Jun 23, 2026". */
24
- const formatRangeCaption = (range, locale) => `${formatDay(range.start, locale)} - ${formatDay(range.end, locale)}`;
50
+ /**
51
+ * Server-side caption for a custom range, e.g. "Jun 1, 2026 - Jun 23, 2026". Both bounds
52
+ * render in the reporting timezone, so the caption names the days that were read rather
53
+ * than the days the server's own zone would spell them as.
54
+ */
55
+ const formatRangeCaption = (range, locale, timezone) => `${formatDay(range.start, locale, timezone)} - ${formatDay(range.end, locale, timezone)}`;
25
56
  //#endregion
26
57
  export { formatRangeCaption, resolveCustomRange };
27
58
 
@@ -1 +1 @@
1
- {"version":3,"file":"range.js","names":[],"sources":["../../src/widgets/range.ts"],"sourcesContent":["import type { DateRange } from '../core/contract'\nimport type { WidgetRange } from './types'\n\n/**\n * Resolve a widget's explicit custom range to a concrete DateRange, or undefined when\n * the widget is on a relative preset, the custom range is incomplete, or either bound\n * is an unparseable date (a corrupt or hand-set widgetData would otherwise reach the\n * cache key and throw on `toISOString`).\n */\nexport const resolveCustomRange = (\n\ttimeframe: string | undefined,\n\trange: WidgetRange | undefined\n): DateRange | undefined => {\n\tif (timeframe !== 'custom' || !range?.from || !range?.to) {\n\t\treturn undefined\n\t}\n\tconst start = new Date(range.from)\n\tconst end = new Date(range.to)\n\tif (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {\n\t\treturn undefined\n\t}\n\treturn { start, end }\n}\n\nconst formatDay = (d: Date, locale: string): string =>\n\td.toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric' })\n\n/** Server-side caption for a custom range, e.g. \"Jun 1, 2026 - Jun 23, 2026\". */\nexport const formatRangeCaption = (range: DateRange, locale: string): string =>\n\t`${formatDay(range.start, locale)} - ${formatDay(range.end, locale)}`\n"],"mappings":";;;;;;;AASA,MAAa,sBACZ,WACA,UAC2B;CAC3B,IAAI,cAAc,YAAY,CAAC,OAAO,QAAQ,CAAC,OAAO,IACrD;CAED,MAAM,QAAQ,IAAI,KAAK,MAAM,IAAI;CACjC,MAAM,MAAM,IAAI,KAAK,MAAM,EAAE;CAC7B,IAAI,OAAO,MAAM,MAAM,QAAQ,CAAC,KAAK,OAAO,MAAM,IAAI,QAAQ,CAAC,GAC9D;CAED,OAAO;EAAE;EAAO;CAAI;AACrB;AAEA,MAAM,aAAa,GAAS,WAC3B,EAAE,mBAAmB,QAAQ;CAAE,OAAO;CAAS,KAAK;CAAW,MAAM;AAAU,CAAC;;AAGjF,MAAa,sBAAsB,OAAkB,WACpD,GAAG,UAAU,MAAM,OAAO,MAAM,EAAE,KAAK,UAAU,MAAM,KAAK,MAAM"}
1
+ {"version":3,"file":"range.js","names":[],"sources":["../../src/widgets/range.ts"],"sourcesContent":["import type { DateRange } from '../core/contract'\nimport { DATE_ONLY, parseDayOrInstant } from '../query/dates'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport type { WidgetRange } from './types'\n\nconst NOON_MS = 12 * 3_600_000\n\n/**\n * The calendar day a stored bound names. The `dayOnly` picker stores the picked day at the\n * admin browser's local midnight, so the instant lands on that day or the one before it in\n * UTC depending on the browser's offset; a 12-hour shift recovers the picked day for every\n * offset in (-12, +12]. Zones at +12:45 and beyond (Chatham in DST, Kiritimati) recover the\n * day before, and the uninhabited UTC-12 the day after.\n */\nconst pickedDay = (raw: string): string | null => {\n\tif (DATE_ONLY.test(raw)) {\n\t\treturn raw\n\t}\n\tconst instant = new Date(raw)\n\tif (Number.isNaN(instant.getTime())) {\n\t\treturn null\n\t}\n\treturn zonedCalendarDay(new Date(instant.getTime() + NOON_MS), 'UTC')\n}\n\n/**\n * Resolve a widget's explicit custom range to a concrete DateRange, or undefined when the\n * widget is on a relative preset, the custom range is incomplete, or either bound names no\n * real day (a corrupt or hand-set widgetData would otherwise reach the cache key and throw\n * on `toISOString`). The two picked days are read inclusively in `timezone`, the reporting\n * timezone the read resolves in: `from` at the first instant of its day, `to` at the last.\n */\nexport const resolveCustomRange = (\n\ttimeframe: string | undefined,\n\trange: WidgetRange | undefined,\n\ttimezone: string\n): DateRange | undefined => {\n\tif (timeframe !== 'custom' || !range?.from || !range?.to) {\n\t\treturn undefined\n\t}\n\tconst fromDay = pickedDay(range.from)\n\tconst toDay = pickedDay(range.to)\n\tif (!fromDay || !toDay) {\n\t\treturn undefined\n\t}\n\tconst start = parseDayOrInstant(fromDay, { timezone, edge: 'start' })\n\tconst end = parseDayOrInstant(toDay, { timezone, edge: 'end' })\n\tif (!start || !end) {\n\t\treturn undefined\n\t}\n\treturn { start, end }\n}\n\nconst formatDay = (d: Date, locale: string, timeZone: string): string =>\n\td.toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric', timeZone })\n\n/**\n * Server-side caption for a custom range, e.g. \"Jun 1, 2026 - Jun 23, 2026\". Both bounds\n * render in the reporting timezone, so the caption names the days that were read rather\n * than the days the server's own zone would spell them as.\n */\nexport const formatRangeCaption = (range: DateRange, locale: string, timezone: string): string =>\n\t`${formatDay(range.start, locale, timezone)} - ${formatDay(range.end, locale, timezone)}`\n"],"mappings":";;;AAKA,MAAM,UAAU,KAAK;;;;;;;;AASrB,MAAM,aAAa,QAA+B;CACjD,IAAI,UAAU,KAAK,GAAG,GACrB,OAAO;CAER,MAAM,UAAU,IAAI,KAAK,GAAG;CAC5B,IAAI,OAAO,MAAM,QAAQ,QAAQ,CAAC,GACjC,OAAO;CAER,OAAO,iBAAiB,IAAI,KAAK,QAAQ,QAAQ,IAAI,OAAO,GAAG,KAAK;AACrE;;;;;;;;AASA,MAAa,sBACZ,WACA,OACA,aAC2B;CAC3B,IAAI,cAAc,YAAY,CAAC,OAAO,QAAQ,CAAC,OAAO,IACrD;CAED,MAAM,UAAU,UAAU,MAAM,IAAI;CACpC,MAAM,QAAQ,UAAU,MAAM,EAAE;CAChC,IAAI,CAAC,WAAW,CAAC,OAChB;CAED,MAAM,QAAQ,kBAAkB,SAAS;EAAE;EAAU,MAAM;CAAQ,CAAC;CACpE,MAAM,MAAM,kBAAkB,OAAO;EAAE;EAAU,MAAM;CAAM,CAAC;CAC9D,IAAI,CAAC,SAAS,CAAC,KACd;CAED,OAAO;EAAE;EAAO;CAAI;AACrB;AAEA,MAAM,aAAa,GAAS,QAAgB,aAC3C,EAAE,mBAAmB,QAAQ;CAAE,OAAO;CAAS,KAAK;CAAW,MAAM;CAAW;AAAS,CAAC;;;;;;AAO3F,MAAa,sBAAsB,OAAkB,QAAgB,aACpE,GAAG,UAAU,MAAM,OAAO,QAAQ,QAAQ,EAAE,KAAK,UAAU,MAAM,KAAK,QAAQ,QAAQ"}
@@ -10,6 +10,8 @@ interface WidgetReadResult {
10
10
  dateRange: DateRange;
11
11
  metrics: Partial<Record<MetricKey, number>>;
12
12
  clamped?: boolean;
13
+ /** True when the engine served a stale cache entry after a failed provider read. */
14
+ stale?: boolean;
13
15
  /** Previous-window totals, present only when the adapter supports comparison. */
14
16
  previousMetrics?: Partial<Record<MetricKey, number>>;
15
17
  /** The previous comparable window, present only when comparison ran. */
@@ -24,7 +26,17 @@ interface ReadForWidgetArgs {
24
26
  range?: DateRange;
25
27
  /** Explicit scope override; omitted resolves via the plugin's scopeResolver. */
26
28
  scope?: string | null;
29
+ /**
30
+ * Reporting timezone the caller already resolved, reused rather than resolved again so
31
+ * a caller-supplied `range` is read in the very timezone it was interpreted in.
32
+ */
33
+ timezone?: string;
27
34
  filters?: AnalyticsFilter[];
35
+ /**
36
+ * Read the previous window too, where the install and the source both allow it. Defaults
37
+ * to on; a caller that never renders a delta passes false to save the second read.
38
+ */
39
+ comparison?: boolean;
28
40
  }
29
41
  declare const readForWidget: (args: ReadForWidgetArgs) => Promise<WidgetReadResult>;
30
42
  //#endregion
@@ -1,7 +1,7 @@
1
1
  import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
2
+ import { resolveTimeframe } from "../timeframe/presets.js";
2
3
  import { satisfiesCapabilities } from "../core/capabilities.js";
3
4
  import { resolveReadContext } from "../core/scopedRead.js";
4
- import { resolveTimeframe } from "../timeframe/presets.js";
5
5
  import { previousWindow } from "./comparison.js";
6
6
  //#region src/widgets/readForWidget.ts
7
7
  const readForWidget = async (args) => {
@@ -11,7 +11,7 @@ const readForWidget = async (args) => {
11
11
  if (!runtime) return {
12
12
  status: "unavailable",
13
13
  adapterId: adapterId ?? "",
14
- dateRange: range ?? resolveTimeframe(timeframe, now),
14
+ dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
15
15
  metrics: emptyMetrics
16
16
  };
17
17
  const ctx = await resolveReadContext({
@@ -23,10 +23,10 @@ const readForWidget = async (args) => {
23
23
  if (!ctx.ok) return {
24
24
  status: "unavailable",
25
25
  adapterId: adapterId ?? "",
26
- dateRange: range ?? resolveTimeframe(timeframe, now),
26
+ dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
27
27
  metrics: emptyMetrics
28
28
  };
29
- const tz = await resolveTimezoneFor(runtime, req, ctx.scope);
29
+ const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
30
30
  const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
31
31
  const base = {
32
32
  dateRange,
@@ -49,7 +49,7 @@ const readForWidget = async (args) => {
49
49
  adapterId: adapter.id,
50
50
  ...base
51
51
  };
52
- const comparisonRange = runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
52
+ const comparisonRange = args.comparison !== false && runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
53
53
  let result;
54
54
  let previous;
55
55
  try {
@@ -80,6 +80,7 @@ const readForWidget = async (args) => {
80
80
  dateRange,
81
81
  metrics: result.totals ?? {},
82
82
  clamped: result.meta.clamped ?? false,
83
+ stale: result.meta.stale ?? false,
83
84
  previousMetrics,
84
85
  comparisonRange
85
86
  };
@@ -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/** 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\tfilters?: AnalyticsFilter[]\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),\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),\n\t\t\tmetrics: emptyMetrics,\n\t\t}\n\t}\n\tconst tz = 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\truntime.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\tpreviousMetrics,\n\t\tcomparisonRange,\n\t}\n}\n"],"mappings":";;;;;;AAwCA,MAAa,gBAAgB,OAAO,SAAuD;CAC1F,MAAM,EAAE,KAAK,SAAS,WAAW,WAAW,KAAK,OAAO,YAAY;CACpE,MAAM,eAAe,CAAC;CAEtB,MAAM,UAAU,WAAW,IAAI,OAAO;C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,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;EACA;CACD;AACD"}
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,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AC;EAC3B,SAAS,OAAO,KAAK,WAAW;EAChC,OAAO,OAAO,KAAK,SAAS;EAC5B;EACA;CACD;AACD"}
@@ -7,6 +7,8 @@ import { PayloadRequest } from "payload";
7
7
  interface BreakdownRow {
8
8
  label: string;
9
9
  value: number;
10
+ /** Every metric the read asked for, present only when `extraMetrics` asked for more. */
11
+ metrics?: Partial<Record<MetricKey, number>>;
10
12
  }
11
13
  interface WidgetBreakdownResult {
12
14
  status: WidgetReadStatus;
@@ -14,6 +16,8 @@ interface WidgetBreakdownResult {
14
16
  dateRange: DateRange;
15
17
  rows: BreakdownRow[];
16
18
  clamped?: boolean;
19
+ /** True when the engine served a stale cache entry after a failed provider read. */
20
+ stale?: boolean;
17
21
  }
18
22
  interface ReadForWidgetBreakdownArgs {
19
23
  req: PayloadRequest;
@@ -26,7 +30,18 @@ interface ReadForWidgetBreakdownArgs {
26
30
  range?: DateRange;
27
31
  /** Explicit scope override; omitted resolves via the plugin's scopeResolver. */
28
32
  scope?: string | null;
33
+ /**
34
+ * Reporting timezone the caller already resolved, reused rather than resolved again so
35
+ * a caller-supplied `range` is read in the very timezone it was interpreted in.
36
+ */
37
+ timezone?: string;
29
38
  filters?: AnalyticsFilter[];
39
+ /**
40
+ * Further metrics to read alongside the ranked one, narrowed to what the source serves
41
+ * so an unsupported one never turns the whole read unavailable. They reach each row's
42
+ * `metrics`; ranking and status still follow `metric` alone.
43
+ */
44
+ extraMetrics?: MetricKey[];
30
45
  }
31
46
  /**
32
47
  * Site-wide ranked breakdown of one metric by one dimension, read through the engine.
@@ -1,7 +1,7 @@
1
1
  import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
2
+ import { resolveTimeframe } from "../timeframe/presets.js";
2
3
  import { satisfiesCapabilities } from "../core/capabilities.js";
3
4
  import { resolveReadContext } from "../core/scopedRead.js";
4
- import { resolveTimeframe } from "../timeframe/presets.js";
5
5
  //#region src/widgets/readForWidgetBreakdown.ts
6
6
  /**
7
7
  * Site-wide ranked breakdown of one metric by one dimension, read through the engine.
@@ -15,7 +15,7 @@ const readForWidgetBreakdown = async (args) => {
15
15
  if (!runtime) return {
16
16
  status: "unavailable",
17
17
  adapterId: adapterId ?? "",
18
- dateRange: range ?? resolveTimeframe(timeframe, now),
18
+ dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
19
19
  rows: emptyRows
20
20
  };
21
21
  const ctx = await resolveReadContext({
@@ -27,10 +27,10 @@ const readForWidgetBreakdown = async (args) => {
27
27
  if (!ctx.ok) return {
28
28
  status: "unavailable",
29
29
  adapterId: adapterId ?? "",
30
- dateRange: range ?? resolveTimeframe(timeframe, now),
30
+ dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
31
31
  rows: emptyRows
32
32
  };
33
- const tz = await resolveTimezoneFor(runtime, req, ctx.scope);
33
+ const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
34
34
  const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
35
35
  const base = {
36
36
  dateRange,
@@ -54,10 +54,11 @@ const readForWidgetBreakdown = async (args) => {
54
54
  adapterId: adapter.id,
55
55
  ...base
56
56
  };
57
+ const metrics = [metric, ...(args.extraMetrics ?? []).filter((m) => m !== metric && adapter.capabilities.metrics.has(m))];
57
58
  let result;
58
59
  try {
59
60
  result = await runtime.engine.read(adapter, {
60
- metrics: [metric],
61
+ metrics,
61
62
  dimensions: [dimension],
62
63
  dateRange,
63
64
  limit,
@@ -78,14 +79,16 @@ const readForWidgetBreakdown = async (args) => {
78
79
  }
79
80
  const rows = result.rows.map((row) => ({
80
81
  label: row.dimensions?.[dimension] ?? "(none)",
81
- value: row.metrics[metric] ?? 0
82
+ value: row.metrics[metric] ?? 0,
83
+ ...metrics.length > 1 ? { metrics: row.metrics } : {}
82
84
  }));
83
85
  return {
84
86
  status: "ok",
85
87
  adapterId: adapter.id,
86
88
  dateRange,
87
89
  rows,
88
- clamped: result.meta.clamped ?? false
90
+ clamped: result.meta.clamped ?? false,
91
+ stale: result.meta.stale ?? false
89
92
  };
90
93
  };
91
94
  //#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}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\tclamped?: 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\tfilters?: AnalyticsFilter[]\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),\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),\n\t\t\trows: emptyRows,\n\t\t}\n\t}\n\tconst tz = 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\tlet result: AnalyticsResult\n\ttry {\n\t\tresult = await runtime.engine.read(adapter, {\n\t\t\tmetrics: [metric],\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}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId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CAAC,MAAM;GAChB,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;CAC/B,EAAE;CACF,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA;EACA,SAAS,OAAO,KAAK,WAAW;CACjC;AACD"}
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,SA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;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"}
@@ -0,0 +1,57 @@
1
+ import { DateRange } from "../core/contract.js";
2
+ import { TimeframePreset } from "../timeframe/presets.js";
3
+ import { WidgetReadStatus } from "./readForWidget.js";
4
+ import { PayloadRequest } from "payload";
5
+
6
+ //#region src/widgets/readForWidgetGoals.d.ts
7
+ interface GoalRow {
8
+ slug: string;
9
+ /** The goal's admin-facing name, or its slug when no configured goal claims it. */
10
+ name: string;
11
+ conversions: number;
12
+ revenue?: number;
13
+ /** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */
14
+ rate?: number;
15
+ previousConversions?: number;
16
+ }
17
+ interface WidgetGoalsResult {
18
+ status: WidgetReadStatus;
19
+ adapterId: string;
20
+ dateRange: DateRange;
21
+ timezone: string;
22
+ rows: GoalRow[];
23
+ /** Range total the rate divides by; absent when the source does not serve visitors. */
24
+ siteVisitors?: number;
25
+ clamped?: boolean;
26
+ stale?: boolean;
27
+ }
28
+ interface ReadForWidgetGoalsArgs {
29
+ req: PayloadRequest;
30
+ timeframe: TimeframePreset;
31
+ limit: number;
32
+ /** Read the previous window too, when the source can compare. */
33
+ compare: boolean;
34
+ adapterId?: string;
35
+ now: Date;
36
+ range?: DateRange;
37
+ /** Explicit scope override; omitted resolves via the plugin's scopeResolver. */
38
+ scope?: string | null;
39
+ /**
40
+ * Reporting timezone the caller already resolved, reused rather than resolved again so
41
+ * a caller-supplied `range` is read in the very timezone it was interpreted in.
42
+ */
43
+ timezone?: string;
44
+ }
45
+ /**
46
+ * The goals table behind the goals widget: conversions per goal over the window, each with
47
+ * its revenue, its share of the site's visitors, and (when comparing) the same goal's
48
+ * conversions in the previous window. Rows come from one `goal` breakdown read and the site
49
+ * total from one totals read, both through the existing widget helpers so capability
50
+ * gating, scoping and caching stay in one place. Revenue and visitors ride along only where
51
+ * the source serves them; the status is the breakdown's, since a table without its rows has
52
+ * nothing to show.
53
+ */
54
+ declare const readForWidgetGoals: (args: ReadForWidgetGoalsArgs) => Promise<WidgetGoalsResult>;
55
+ //#endregion
56
+ export { GoalRow, ReadForWidgetGoalsArgs, WidgetGoalsResult, readForWidgetGoals };
57
+ //# sourceMappingURL=readForWidgetGoals.d.ts.map