@byline/host-tanstack-start 4.15.0 → 4.16.0

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 (43) hide show
  1. package/dist/admin-shell/chrome/admin-menu-drawer.d.ts +2 -1
  2. package/dist/admin-shell/chrome/admin-menu-drawer.js +14 -2
  3. package/dist/integrations/analytics-agent.d.ts +20 -0
  4. package/dist/integrations/analytics-agent.js +57 -0
  5. package/dist/integrations/analytics-events.d.ts +51 -0
  6. package/dist/integrations/analytics-events.js +129 -0
  7. package/dist/integrations/serve-analytics-agent.d.ts +8 -0
  8. package/dist/integrations/serve-analytics-agent.js +11 -0
  9. package/dist/routes/analytics-range.d.ts +12 -0
  10. package/dist/routes/analytics-range.js +35 -0
  11. package/dist/routes/create-admin-analytics-route.d.ts +8 -0
  12. package/dist/routes/create-admin-analytics-route.js +108 -0
  13. package/dist/routes/create-admin-layout-route.js +10 -4
  14. package/dist/routes/index.d.ts +1 -0
  15. package/dist/routes/index.js +1 -0
  16. package/dist/server-fns/analytics/index.d.ts +9 -0
  17. package/dist/server-fns/analytics/index.js +2 -0
  18. package/dist/server-fns/analytics/maintenance.d.ts +22 -0
  19. package/dist/server-fns/analytics/maintenance.js +42 -0
  20. package/dist/server-fns/analytics/queries.d.ts +25 -0
  21. package/dist/server-fns/analytics/queries.js +54 -0
  22. package/dist/vite/analytics-dev.d.ts +22 -0
  23. package/dist/vite/analytics-dev.js +28 -0
  24. package/dist/vite/index.d.ts +1 -0
  25. package/dist/vite/index.js +1 -0
  26. package/package.json +14 -8
  27. package/src/admin-shell/chrome/admin-menu-drawer.tsx +14 -0
  28. package/src/integrations/analytics-agent.tsx +91 -0
  29. package/src/integrations/analytics-events.test.node.ts +245 -0
  30. package/src/integrations/analytics-events.ts +224 -0
  31. package/src/integrations/serve-analytics-agent.test.node.ts +20 -0
  32. package/src/integrations/serve-analytics-agent.ts +19 -0
  33. package/src/routes/analytics-range.ts +55 -0
  34. package/src/routes/create-admin-analytics-route.test.node.ts +46 -0
  35. package/src/routes/create-admin-analytics-route.tsx +109 -0
  36. package/src/routes/create-admin-layout-route.tsx +15 -8
  37. package/src/routes/index.ts +1 -0
  38. package/src/server-fns/analytics/index.ts +23 -0
  39. package/src/server-fns/analytics/maintenance.ts +54 -0
  40. package/src/server-fns/analytics/queries.ts +86 -0
  41. package/src/vite/analytics-dev.test.node.ts +126 -0
  42. package/src/vite/analytics-dev.ts +56 -0
  43. package/src/vite/index.ts +1 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { ANALYTICS_MAX_BODY_BYTES, type Analytics, getAnalytics } from '@byline/analytics'
10
+ import { type BylineLogger, getLogger } from '@byline/core'
11
+
12
+ export interface AnalyticsEventHandlerOptions {
13
+ /** Host-owned resolver for deployment-specific, request-scoped network facts. */
14
+ resolveRequestContext: AnalyticsRequestContextResolver
15
+ /** Test/embedding seam; production resolves the registered installation runtime. */
16
+ analytics?: () => Pick<Analytics, 'ingest'>
17
+ /** Test/embedding seam; production resolves the initialized application logger. */
18
+ logger?: () => Pick<BylineLogger, 'error'>
19
+ }
20
+
21
+ export interface AnalyticsRequestContext {
22
+ clientIp?: string | null
23
+ country?: string | null
24
+ }
25
+
26
+ export type AnalyticsRequestContextResolver = (
27
+ request: Request
28
+ ) => AnalyticsRequestContext | Promise<AnalyticsRequestContext>
29
+
30
+ export interface LocalAnalyticsRequestContextOptions {
31
+ /** Resolve the direct peer address from the host runtime, without forwarded headers. */
32
+ resolveClientIp: (
33
+ request: Request
34
+ ) => string | null | undefined | Promise<string | null | undefined>
35
+ /** Explicit development-only identity for runtimes that expose no peer address. */
36
+ developmentFallbackClientIp?: string
37
+ }
38
+
39
+ export interface TrustedAnalyticsHeadersOptions {
40
+ /** Header overwritten by the trusted reverse proxy with the normalized client address. */
41
+ clientIpHeader: string
42
+ /** Optional header overwritten by the trusted edge with an ISO country code. */
43
+ countryHeader?: string
44
+ /** Explicit context or resolver used only when a trusted header is absent. */
45
+ fallback?: AnalyticsRequestContext | AnalyticsRequestContextResolver
46
+ }
47
+
48
+ /**
49
+ * Resolve an identity for a server reached directly through a loopback URL.
50
+ * Both the URL and the direct peer address must be loopback. This is safe for
51
+ * a directly reached local server. A same-host reverse proxy also appears as
52
+ * a loopback peer, however, so do not expose this fallback through a public
53
+ * proxy where a client can select the Host header.
54
+ */
55
+ export function localAnalyticsRequestContext(
56
+ options: LocalAnalyticsRequestContextOptions
57
+ ): AnalyticsRequestContextResolver {
58
+ const developmentFallbackClientIp =
59
+ options.developmentFallbackClientIp == null
60
+ ? undefined
61
+ : validateFact(options.developmentFallbackClientIp, 'developmentFallbackClientIp', 255)
62
+
63
+ return async (request) => {
64
+ const clientIp = await options.resolveClientIp(request)
65
+ if (isLoopbackHostname(new URL(request.url).hostname) && isLoopbackAddress(clientIp)) {
66
+ return { clientIp: validateFact(clientIp, 'resolved clientIp', 255) }
67
+ }
68
+ return developmentFallbackClientIp == null ? {} : { clientIp: developmentFallbackClientIp }
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Resolve network facts from headers owned and overwritten by a trusted proxy.
74
+ * This helper does not establish that trust: the deployment must prevent a
75
+ * client from selecting the configured header values or bypassing the proxy.
76
+ */
77
+ export function trustedAnalyticsHeaders(
78
+ options: TrustedAnalyticsHeadersOptions
79
+ ): AnalyticsRequestContextResolver {
80
+ const clientIpHeader = validateHeaderName(options.clientIpHeader, 'clientIpHeader')
81
+ const countryHeader =
82
+ options.countryHeader == null
83
+ ? undefined
84
+ : validateHeaderName(options.countryHeader, 'countryHeader')
85
+ const fallback =
86
+ typeof options.fallback === 'function' ? options.fallback : validateFallback(options.fallback)
87
+
88
+ return async (request) => {
89
+ const fallbackContext =
90
+ typeof fallback === 'function' ? validateFallback(await fallback(request)) : fallback
91
+ return {
92
+ clientIp: request.headers.get(clientIpHeader)?.trim() || fallbackContext?.clientIp,
93
+ country:
94
+ (countryHeader == null ? null : request.headers.get(countryHeader)?.trim()) ||
95
+ fallbackContext?.country,
96
+ }
97
+ }
98
+ }
99
+
100
+ export function createAnalyticsEventHandler(
101
+ options: AnalyticsEventHandlerOptions
102
+ ): (request: Request) => Promise<Response> {
103
+ const resolveAnalytics = options.analytics ?? getAnalytics
104
+
105
+ return async (request) => {
106
+ const body = await readBoundedBody(request, ANALYTICS_MAX_BODY_BYTES)
107
+ try {
108
+ const requestContext = await options.resolveRequestContext(request)
109
+ const result = await resolveAnalytics().ingest({
110
+ method: request.method,
111
+ body: body ?? new Uint8Array(ANALYTICS_MAX_BODY_BYTES + 1),
112
+ origin: request.headers.get('origin'),
113
+ referer: request.headers.get('referer'),
114
+ userAgent: request.headers.get('user-agent'),
115
+ secPurpose: request.headers.get('sec-purpose'),
116
+ xPurpose: request.headers.get('x-purpose'),
117
+ clientIp: requestContext.clientIp,
118
+ country: requestContext.country,
119
+ })
120
+
121
+ return analyticsResponse(result.status)
122
+ } catch (error) {
123
+ const logger = options.logger?.() ?? getLogger()
124
+ logger.error({ errorCode: safeErrorCode(error) }, '[analytics] event persistence failed')
125
+ return analyticsResponse(503)
126
+ }
127
+ }
128
+ }
129
+
130
+ function safeErrorCode(error: unknown): string {
131
+ if (error == null || typeof error !== 'object' || !('code' in error)) return 'UNKNOWN'
132
+ const code = error.code
133
+ return typeof code === 'string' && /^[a-z0-9_-]{1,64}$/iu.test(code) ? code : 'UNKNOWN'
134
+ }
135
+
136
+ function analyticsResponse(status: number): Response {
137
+ return new Response(null, {
138
+ status,
139
+ headers: { 'cache-control': 'no-store' },
140
+ })
141
+ }
142
+
143
+ async function readBoundedBody(request: Request, limit: number): Promise<Uint8Array | null> {
144
+ const declaredLength = Number(request.headers.get('content-length'))
145
+ if (Number.isFinite(declaredLength) && declaredLength > limit) return null
146
+ if (request.body == null) return new Uint8Array()
147
+
148
+ const reader = request.body.getReader()
149
+ const chunks: Uint8Array[] = []
150
+ let length = 0
151
+ try {
152
+ while (true) {
153
+ const { done, value } = await reader.read()
154
+ if (done) break
155
+ length += value.byteLength
156
+ if (length > limit) {
157
+ await reader.cancel()
158
+ return null
159
+ }
160
+ chunks.push(value)
161
+ }
162
+ } finally {
163
+ reader.releaseLock()
164
+ }
165
+
166
+ const body = new Uint8Array(length)
167
+ let offset = 0
168
+ for (const chunk of chunks) {
169
+ body.set(chunk, offset)
170
+ offset += chunk.byteLength
171
+ }
172
+ return body
173
+ }
174
+
175
+ function validateHeaderName(value: string, label: string): string {
176
+ const normalized = value.trim().toLowerCase()
177
+ if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/u.test(normalized)) {
178
+ throw new Error(`analytics ${label} must be a valid HTTP header name`)
179
+ }
180
+ return normalized
181
+ }
182
+
183
+ function validateFallback(
184
+ value: AnalyticsRequestContext | undefined
185
+ ): AnalyticsRequestContext | undefined {
186
+ if (value == null) return undefined
187
+ return {
188
+ ...(value.clientIp == null
189
+ ? {}
190
+ : { clientIp: validateFact(value.clientIp, 'fallback.clientIp', 255) }),
191
+ ...(value.country == null
192
+ ? {}
193
+ : { country: validateFact(value.country, 'fallback.country', 16) }),
194
+ }
195
+ }
196
+
197
+ function validateFact(value: string, label: string, maxLength: number): string {
198
+ const normalized = value.trim()
199
+ if (normalized.length === 0 || normalized.length > maxLength) {
200
+ throw new Error(`analytics ${label} must contain 1 to ${maxLength} characters`)
201
+ }
202
+ return normalized
203
+ }
204
+
205
+ function isLoopbackHostname(value: string): boolean {
206
+ const normalized = stripIpv6Brackets(value.toLowerCase())
207
+ return (
208
+ normalized === 'localhost' || normalized.endsWith('.localhost') || isLoopbackAddress(normalized)
209
+ )
210
+ }
211
+
212
+ function isLoopbackAddress(value: string | null | undefined): value is string {
213
+ if (value == null) return false
214
+ const normalized = stripIpv6Brackets(value.trim().toLowerCase())
215
+ return (
216
+ normalized === '::1' ||
217
+ /^127(?:\.\d{1,3}){3}$/u.test(normalized) ||
218
+ /^::ffff:127(?:\.\d{1,3}){3}$/u.test(normalized)
219
+ )
220
+ }
221
+
222
+ function stripIpv6Brackets(value: string): string {
223
+ return value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value
224
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { describe, expect, it } from 'vitest'
10
+
11
+ import { serveAnalyticsAgent } from './serve-analytics-agent.js'
12
+
13
+ describe('serveAnalyticsAgent', () => {
14
+ it('serves the bundled standalone collector with bounded first-party caching', async () => {
15
+ const response = serveAnalyticsAgent()
16
+ expect(response.headers.get('content-type')).toBe('text/javascript; charset=utf-8')
17
+ expect(response.headers.get('cache-control')).toBe('public, max-age=3600, must-revalidate')
18
+ expect(await response.text()).toContain('text/plain')
19
+ })
20
+ })
@@ -0,0 +1,19 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { ANALYTICS_AGENT_SOURCE } from '@byline/analytics-agent/source'
10
+
11
+ export function serveAnalyticsAgent(): Response {
12
+ return new Response(ANALYTICS_AGENT_SOURCE, {
13
+ headers: {
14
+ 'cache-control': 'public, max-age=3600, must-revalidate',
15
+ 'content-type': 'text/javascript; charset=utf-8',
16
+ 'x-content-type-options': 'nosniff',
17
+ },
18
+ })
19
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import type { AnalyticsDashboardPeriod } from '@byline/admin/analytics'
10
+
11
+ const UTC_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/u
12
+
13
+ export function buildAnalyticsDashboardRange(
14
+ period: AnalyticsDashboardPeriod,
15
+ now = new Date(),
16
+ earliestReportDay: string | null = null
17
+ ): { from: string; to: string } {
18
+ const to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()))
19
+
20
+ if (period === 'ytd') {
21
+ return {
22
+ from: formatUtcDay(new Date(Date.UTC(to.getUTCFullYear(), 0, 1))),
23
+ to: formatUtcDay(to),
24
+ }
25
+ }
26
+
27
+ if (period === 'all') {
28
+ const toDay = formatUtcDay(to)
29
+ const earliest = earliestReportDay == null ? toDay : assertUtcDay(earliestReportDay)
30
+ return {
31
+ from: earliest <= toDay ? earliest : toDay,
32
+ to: toDay,
33
+ }
34
+ }
35
+
36
+ const from = new Date(to)
37
+ from.setUTCDate(from.getUTCDate() - (period - 1))
38
+ return { from: formatUtcDay(from), to: formatUtcDay(to) }
39
+ }
40
+
41
+ function formatUtcDay(value: Date): string {
42
+ const year = value.getUTCFullYear().toString().padStart(4, '0')
43
+ const month = (value.getUTCMonth() + 1).toString().padStart(2, '0')
44
+ const day = value.getUTCDate().toString().padStart(2, '0')
45
+ return `${year}-${month}-${day}`
46
+ }
47
+
48
+ function assertUtcDay(value: string): string {
49
+ if (!UTC_DAY_PATTERN.test(value)) throw new Error('analytics report day must use YYYY-MM-DD')
50
+ const date = new Date(`${value}T00:00:00.000Z`)
51
+ if (!Number.isFinite(date.valueOf()) || formatUtcDay(date) !== value) {
52
+ throw new Error('analytics report day must be a real UTC calendar day')
53
+ }
54
+ return value
55
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { describe, expect, it } from 'vitest'
10
+
11
+ import { buildAnalyticsDashboardRange } from './analytics-range.js'
12
+
13
+ describe('buildAnalyticsDashboardRange', () => {
14
+ it('builds inclusive UTC periods across month and year boundaries', () => {
15
+ expect(buildAnalyticsDashboardRange(7, new Date('2027-01-03T23:59:59.999Z'))).toEqual({
16
+ from: '2026-12-28',
17
+ to: '2027-01-03',
18
+ })
19
+ })
20
+
21
+ it('builds year-to-date from January 1 in UTC', () => {
22
+ expect(buildAnalyticsDashboardRange('ytd', new Date('2027-06-03T23:59:59.999Z'))).toEqual({
23
+ from: '2027-01-01',
24
+ to: '2027-06-03',
25
+ })
26
+ })
27
+
28
+ it('builds all-time from the earliest reportable day', () => {
29
+ expect(
30
+ buildAnalyticsDashboardRange('all', new Date('2027-06-03T23:59:59.999Z'), '2024-02-29')
31
+ ).toEqual({ from: '2024-02-29', to: '2027-06-03' })
32
+ })
33
+
34
+ it('uses today for an empty all-time report', () => {
35
+ expect(buildAnalyticsDashboardRange('all', new Date('2027-06-03T23:59:59.999Z'))).toEqual({
36
+ from: '2027-06-03',
37
+ to: '2027-06-03',
38
+ })
39
+ })
40
+
41
+ it('rejects an invalid earliest report day before constructing a range', () => {
42
+ expect(() =>
43
+ buildAnalyticsDashboardRange('all', new Date('2027-06-03T23:59:59.999Z'), '2027-02-30')
44
+ ).toThrow(/real UTC calendar day/u)
45
+ })
46
+ })
@@ -0,0 +1,109 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { createFileRoute, notFound } from '@tanstack/react-router'
10
+
11
+ import type { AnalyticsDashboardData, AnalyticsDashboardPeriod } from '@byline/admin/analytics'
12
+ import { AnalyticsDashboard } from '@byline/admin/analytics/components/dashboard'
13
+ import { isAnalyticsDashboardPeriod } from '@byline/analytics/config'
14
+ import { useTranslation } from '@byline/i18n/react'
15
+ import { z } from 'zod'
16
+
17
+ import { BreadcrumbsClient } from '../admin-shell/chrome/breadcrumbs/breadcrumbs-client.js'
18
+ import { useNavigate } from '../admin-shell/chrome/loose-router.js'
19
+ import {
20
+ getAnalyticsCountries,
21
+ getAnalyticsReferrers,
22
+ getAnalyticsReportCoverage,
23
+ getAnalyticsRuntime,
24
+ getAnalyticsSummary,
25
+ getAnalyticsTop,
26
+ } from '../server-fns/analytics/index.js'
27
+ import { getAdminRoutePath } from './admin-path.js'
28
+ import { buildAnalyticsDashboardRange } from './analytics-range.js'
29
+
30
+ const periodSchema = z.preprocess((value) => {
31
+ if (value == null) return undefined
32
+ if (value === 'ytd' || value === 'all') return value
33
+ return Number(value)
34
+ }, z.custom<AnalyticsDashboardPeriod>((value) => isAnalyticsDashboardPeriod(value)).optional())
35
+
36
+ const searchSchema = z.object({
37
+ period: periodSchema.catch(undefined),
38
+ })
39
+
40
+ interface AnalyticsSearch {
41
+ period?: AnalyticsDashboardPeriod
42
+ }
43
+
44
+ export function createAdminAnalyticsRoute(path: string) {
45
+ const Route: any = createFileRoute(path as never)({
46
+ validateSearch: searchSchema,
47
+ loaderDeps: ({ search }: { search: AnalyticsSearch }) => ({
48
+ period: search.period ?? 30,
49
+ }),
50
+ loader: async ({ deps }: { deps: { period: AnalyticsDashboardPeriod } }) => {
51
+ const runtime = await getAnalyticsRuntime()
52
+ if (!runtime.enabled) throw notFound()
53
+
54
+ const coverage = await getAnalyticsReportCoverage()
55
+ const range = buildAnalyticsDashboardRange(deps.period, new Date(), coverage.summaryFrom)
56
+ const [summary, pages, downloads, referrers, countries] = await Promise.all([
57
+ getAnalyticsSummary({ data: range }),
58
+ getAnalyticsTop({ data: { ...range, kind: 'page', limit: 20 } }),
59
+ getAnalyticsTop({ data: { ...range, kind: 'download', limit: 20 } }),
60
+ getAnalyticsReferrers({ data: { ...range, limit: 20 } }),
61
+ getAnalyticsCountries({ data: range }),
62
+ ])
63
+
64
+ return {
65
+ data: {
66
+ summary,
67
+ pages,
68
+ downloads,
69
+ referrers,
70
+ countries,
71
+ range,
72
+ coverage,
73
+ } satisfies AnalyticsDashboardData,
74
+ period: deps.period,
75
+ }
76
+ },
77
+ component: function AdminAnalyticsComponent() {
78
+ const { data, period } = Route.useLoaderData() as {
79
+ data: AnalyticsDashboardData
80
+ period: AnalyticsDashboardPeriod
81
+ }
82
+ const navigate = useNavigate()
83
+ const { t } = useTranslation('byline-admin')
84
+
85
+ return (
86
+ <>
87
+ <BreadcrumbsClient
88
+ breadcrumbs={[
89
+ { label: t('chrome.menu.dashboard'), href: getAdminRoutePath() },
90
+ { label: t('analytics.title'), href: getAdminRoutePath('analytics') },
91
+ ]}
92
+ />
93
+ <AnalyticsDashboard
94
+ data={data}
95
+ period={period}
96
+ onPeriodChange={(nextPeriod) => {
97
+ navigate({
98
+ to: getAdminRoutePath('analytics'),
99
+ search: { period: nextPeriod },
100
+ })
101
+ }}
102
+ />
103
+ </>
104
+ )
105
+ },
106
+ })
107
+
108
+ return Route
109
+ }
@@ -41,6 +41,7 @@ import { buildLocaleDefinitions } from '../i18n/locale-definitions.js'
41
41
  import { bylineAdminServices } from '../integrations/byline-admin-services.js'
42
42
  import { BylineAiAdminProvider } from '../integrations/byline-ai.js'
43
43
  import { bylineFieldServices } from '../integrations/byline-field-services.js'
44
+ import { getAnalyticsRuntime } from '../server-fns/analytics/index.js'
44
45
  import { getCurrentAdminUser } from '../server-fns/auth/index.js'
45
46
  import { getScheduledPublicationRuntime } from '../server-fns/collections/index.js'
46
47
  import { getActiveLocaleFn, setAdminLocaleFn } from '../server-fns/i18n/index.js'
@@ -58,9 +59,12 @@ export function createAdminLayoutRoute(path: string) {
58
59
  // than calling `resolveRequestLocale` directly) keeps
59
60
  // `@tanstack/react-start/server` out of the client bundle — the
60
61
  // same pattern `getCurrentAdminUser` uses for `getAdminRequestContext`.
61
- const activeLocale = await getActiveLocaleFn()
62
- const scheduledPublicationRuntime = await getScheduledPublicationRuntime()
63
- return { user, activeLocale, scheduledPublicationRuntime }
62
+ const [activeLocale, scheduledPublicationRuntime, analyticsRuntime] = await Promise.all([
63
+ getActiveLocaleFn(),
64
+ getScheduledPublicationRuntime(),
65
+ getAnalyticsRuntime(),
66
+ ])
67
+ return { user, activeLocale, scheduledPublicationRuntime, analyticsRuntime }
64
68
  } catch {
65
69
  // `getCurrentAdminUser` (via `getAdminRequestContext`) throws
66
70
  // `ERR_UNAUTHENTICATED` or a related auth error when no valid
@@ -73,11 +77,13 @@ export function createAdminLayoutRoute(path: string) {
73
77
  }
74
78
  },
75
79
  component: function AdminLayoutComponent() {
76
- const { user, activeLocale, scheduledPublicationRuntime } = Route.useRouteContext() as {
77
- user: Awaited<ReturnType<typeof getCurrentAdminUser>>
78
- activeLocale: LocaleCode
79
- scheduledPublicationRuntime: Awaited<ReturnType<typeof getScheduledPublicationRuntime>>
80
- }
80
+ const { user, activeLocale, scheduledPublicationRuntime, analyticsRuntime } =
81
+ Route.useRouteContext() as {
82
+ user: Awaited<ReturnType<typeof getCurrentAdminUser>>
83
+ activeLocale: LocaleCode
84
+ scheduledPublicationRuntime: Awaited<ReturnType<typeof getScheduledPublicationRuntime>>
85
+ analyticsRuntime: Awaited<ReturnType<typeof getAnalyticsRuntime>>
86
+ }
81
87
  const { i18n } = getAdminConfig()
82
88
  const localeDefinitions = buildLocaleDefinitions(
83
89
  i18n.admin.locales,
@@ -113,6 +119,7 @@ export function createAdminLayoutRoute(path: string) {
113
119
  <AdminAppBar user={user} />
114
120
  <main className={cx('byline-admin-layout-main', layoutStyles.main)}>
115
121
  <AdminMenuDrawer
122
+ analyticsEnabled={analyticsRuntime.enabled}
116
123
  scheduledPublicationEnabled={scheduledPublicationRuntime.enabled}
117
124
  />
118
125
  <Content>
@@ -33,6 +33,7 @@ export { getSignInRoutePath } from './sign-in-path.js'
33
33
 
34
34
  export { createAdminAccountRoute } from './create-admin-account-route.js'
35
35
  export { createAdminActivityRoute } from './create-admin-activity-route.js'
36
+ export { createAdminAnalyticsRoute } from './create-admin-analytics-route.js'
36
37
  export { createAdminDashboardRoute } from './create-admin-dashboard-route.js'
37
38
  export { createAdminLayoutRoute } from './create-admin-layout-route.js'
38
39
  export { createAdminPermissionsRoute } from './create-admin-permissions-route.js'
@@ -0,0 +1,23 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ export {
10
+ type DeleteAnalyticsEventsInput,
11
+ deleteAnalyticsEvents,
12
+ rebuildAnalyticsDay,
13
+ } from './maintenance.js'
14
+ export {
15
+ type AnalyticsRuntimeState,
16
+ type AnalyticsTopInput,
17
+ getAnalyticsCountries,
18
+ getAnalyticsReferrers,
19
+ getAnalyticsReportCoverage,
20
+ getAnalyticsRuntime,
21
+ getAnalyticsSummary,
22
+ getAnalyticsTop,
23
+ } from './queries.js'
@@ -0,0 +1,54 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+
9
+ import { createServerFn } from '@tanstack/react-start'
10
+
11
+ import { assertAdminActor } from '@byline/admin'
12
+ import { ANALYTICS_ABILITIES } from '@byline/admin/analytics'
13
+ import { getAdminRequestContext } from '@byline/client/server'
14
+
15
+ export interface DeleteAnalyticsEventsInput {
16
+ from: string
17
+ to: string
18
+ visitorHash?: string
19
+ }
20
+
21
+ export const deleteAnalyticsEvents = createServerFn({ method: 'POST' })
22
+ .validator((input: DeleteAnalyticsEventsInput) => input)
23
+ .handler(async ({ data }): Promise<{ deleted: number }> => {
24
+ await assertAnalyticsMaintenance()
25
+ const { getAnalytics } = await import('@byline/analytics')
26
+ const from = parseInstant(data.from, 'from')
27
+ const to = parseInstant(data.to, 'to')
28
+ const deleted = await getAnalytics().deleteEvents({
29
+ from,
30
+ to,
31
+ ...(data.visitorHash == null ? {} : { visitorHash: data.visitorHash }),
32
+ })
33
+ return { deleted }
34
+ })
35
+
36
+ export const rebuildAnalyticsDay = createServerFn({ method: 'POST' })
37
+ .validator((input: { day: string }) => input)
38
+ .handler(async ({ data }): Promise<{ rebuilt: string }> => {
39
+ await assertAnalyticsMaintenance()
40
+ const { getAnalytics } = await import('@byline/analytics')
41
+ await getAnalytics().rebuildDay(data.day)
42
+ return { rebuilt: data.day }
43
+ })
44
+
45
+ async function assertAnalyticsMaintenance(): Promise<void> {
46
+ const context = await getAdminRequestContext()
47
+ assertAdminActor(context, ANALYTICS_ABILITIES.maintain)
48
+ }
49
+
50
+ function parseInstant(value: string, label: string): Date {
51
+ const date = new Date(value)
52
+ if (Number.isNaN(date.valueOf())) throw new Error(`analytics ${label} must be an ISO instant`)
53
+ return date
54
+ }