@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.
- package/dist/admin-shell/chrome/admin-menu-drawer.d.ts +2 -1
- package/dist/admin-shell/chrome/admin-menu-drawer.js +14 -2
- package/dist/integrations/analytics-agent.d.ts +20 -0
- package/dist/integrations/analytics-agent.js +57 -0
- package/dist/integrations/analytics-events.d.ts +51 -0
- package/dist/integrations/analytics-events.js +129 -0
- package/dist/integrations/serve-analytics-agent.d.ts +8 -0
- package/dist/integrations/serve-analytics-agent.js +11 -0
- package/dist/routes/analytics-range.d.ts +12 -0
- package/dist/routes/analytics-range.js +35 -0
- package/dist/routes/create-admin-analytics-route.d.ts +8 -0
- package/dist/routes/create-admin-analytics-route.js +108 -0
- package/dist/routes/create-admin-layout-route.js +10 -4
- package/dist/routes/index.d.ts +1 -0
- package/dist/routes/index.js +1 -0
- package/dist/server-fns/analytics/index.d.ts +9 -0
- package/dist/server-fns/analytics/index.js +2 -0
- package/dist/server-fns/analytics/maintenance.d.ts +22 -0
- package/dist/server-fns/analytics/maintenance.js +42 -0
- package/dist/server-fns/analytics/queries.d.ts +25 -0
- package/dist/server-fns/analytics/queries.js +54 -0
- package/dist/vite/analytics-dev.d.ts +22 -0
- package/dist/vite/analytics-dev.js +28 -0
- package/dist/vite/index.d.ts +1 -0
- package/dist/vite/index.js +1 -0
- package/package.json +14 -8
- package/src/admin-shell/chrome/admin-menu-drawer.tsx +14 -0
- package/src/integrations/analytics-agent.tsx +91 -0
- package/src/integrations/analytics-events.test.node.ts +245 -0
- package/src/integrations/analytics-events.ts +224 -0
- package/src/integrations/serve-analytics-agent.test.node.ts +20 -0
- package/src/integrations/serve-analytics-agent.ts +19 -0
- package/src/routes/analytics-range.ts +55 -0
- package/src/routes/create-admin-analytics-route.test.node.ts +46 -0
- package/src/routes/create-admin-analytics-route.tsx +109 -0
- package/src/routes/create-admin-layout-route.tsx +15 -8
- package/src/routes/index.ts +1 -0
- package/src/server-fns/analytics/index.ts +23 -0
- package/src/server-fns/analytics/maintenance.ts +54 -0
- package/src/server-fns/analytics/queries.ts +86 -0
- package/src/vite/analytics-dev.test.node.ts +126 -0
- package/src/vite/analytics-dev.ts +56 -0
- package/src/vite/index.ts +1 -0
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* Copyright (c) Infonomic Company Limited
|
|
7
7
|
*/
|
|
8
8
|
import type React from 'react';
|
|
9
|
-
export declare function AdminMenuDrawer({ scheduledPublicationEnabled, }: {
|
|
9
|
+
export declare function AdminMenuDrawer({ analyticsEnabled, scheduledPublicationEnabled, }: {
|
|
10
|
+
analyticsEnabled?: boolean;
|
|
10
11
|
scheduledPublicationEnabled?: boolean;
|
|
11
12
|
}): React.JSX.Element | null;
|
|
@@ -4,9 +4,10 @@ import { ADMIN_ACTIVITY_ABILITIES } from "@byline/admin/admin-activity";
|
|
|
4
4
|
import { ADMIN_PERMISSIONS_ABILITIES } from "@byline/admin/admin-permissions";
|
|
5
5
|
import { ADMIN_ROLES_ABILITIES } from "@byline/admin/admin-roles";
|
|
6
6
|
import { ADMIN_USERS_ABILITIES } from "@byline/admin/admin-users";
|
|
7
|
+
import { ANALYTICS_ABILITIES } from "@byline/admin/analytics";
|
|
7
8
|
import { collectionAbilityKey, getAdminConfig } from "@byline/core";
|
|
8
9
|
import { useTranslation } from "@byline/i18n/react";
|
|
9
|
-
import { ActivityIcon, CalendarIcon, HomeIcon, RolesIcon, SettingsSlidersIcon, Tooltip, UserIcon, UsersIcon } from "@byline/ui/react";
|
|
10
|
+
import { ActivityIcon, AnalyticsIcon, CalendarIcon, HomeIcon, RolesIcon, SettingsSlidersIcon, Tooltip, UserIcon, UsersIcon } from "@byline/ui/react";
|
|
10
11
|
import clsx from "clsx";
|
|
11
12
|
import { useSwipeable } from "react-swipeable";
|
|
12
13
|
import { useAbilities } from "../../integrations/abilities.js";
|
|
@@ -46,7 +47,7 @@ function MenuItem({ to, label, icon, pathname, compact }) {
|
|
|
46
47
|
})
|
|
47
48
|
});
|
|
48
49
|
}
|
|
49
|
-
function AdminMenuDrawer({ scheduledPublicationEnabled = false }) {
|
|
50
|
+
function AdminMenuDrawer({ analyticsEnabled = false, scheduledPublicationEnabled = false }) {
|
|
50
51
|
const pathname = useRouterState({
|
|
51
52
|
select: (s)=>s.location.pathname
|
|
52
53
|
});
|
|
@@ -57,6 +58,7 @@ function AdminMenuDrawer({ scheduledPublicationEnabled = false }) {
|
|
|
57
58
|
const canReadRoles = has(ADMIN_ROLES_ABILITIES.read);
|
|
58
59
|
const canReadPermissions = has(ADMIN_PERMISSIONS_ABILITIES.read);
|
|
59
60
|
const canReadActivity = has(ADMIN_ACTIVITY_ABILITIES.read);
|
|
61
|
+
const canReadAnalytics = analyticsEnabled && has(ANALYTICS_ABILITIES.read);
|
|
60
62
|
const canSeeScheduledPublications = scheduledPublicationEnabled && getAdminConfig().collections.some((collection)=>has(collectionAbilityKey(collection.path, 'changeStatus')) && has(collectionAbilityKey(collection.path, 'publish')));
|
|
61
63
|
const showAdminSection = canReadUsers || canReadRoles || canReadPermissions || canReadActivity;
|
|
62
64
|
const handlers = useSwipeable({
|
|
@@ -106,6 +108,16 @@ function AdminMenuDrawer({ scheduledPublicationEnabled = false }) {
|
|
|
106
108
|
pathname: pathname,
|
|
107
109
|
compact: compact
|
|
108
110
|
}),
|
|
111
|
+
canReadAnalytics && /*#__PURE__*/ jsx(MenuItem, {
|
|
112
|
+
to: getAdminRoutePath('analytics'),
|
|
113
|
+
label: t('chrome.menu.analytics'),
|
|
114
|
+
icon: /*#__PURE__*/ jsx(AnalyticsIcon, {
|
|
115
|
+
width: "20px",
|
|
116
|
+
height: "20px"
|
|
117
|
+
}),
|
|
118
|
+
pathname: pathname,
|
|
119
|
+
compact: compact
|
|
120
|
+
}),
|
|
109
121
|
showAdminSection && /*#__PURE__*/ jsxs(Fragment, {
|
|
110
122
|
children: [
|
|
111
123
|
/*#__PURE__*/ jsx("li", {
|
|
@@ -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
|
+
import type React from 'react';
|
|
9
|
+
export interface AnalyticsAgentProps {
|
|
10
|
+
/** Application-owned same-origin route that receives browser events. */
|
|
11
|
+
endpoint: string;
|
|
12
|
+
src?: string;
|
|
13
|
+
cdnHosts?: readonly string[];
|
|
14
|
+
downloadExtensions?: readonly string[];
|
|
15
|
+
ignoredPathPrefixes?: readonly string[];
|
|
16
|
+
countSearchChanges?: boolean;
|
|
17
|
+
countHashChanges?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Render the standalone script and bridge only committed router locations into it. */
|
|
20
|
+
export declare function AnalyticsAgent({ endpoint, src, cdnHosts, downloadExtensions, ignoredPathPrefixes, countSearchChanges, countHashChanges, }: AnalyticsAgentProps): React.JSX.Element;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useRef } from "react";
|
|
4
|
+
import { useRouterState } from "@tanstack/react-router";
|
|
5
|
+
import { ANALYTICS_NAVIGATION_EVENT, ANALYTICS_STOP_EVENT } from "@byline/analytics-agent";
|
|
6
|
+
let pendingStopTimer;
|
|
7
|
+
function AnalyticsAgent({ endpoint, src = '/b.js', cdnHosts, downloadExtensions, ignoredPathPrefixes, countSearchChanges = false, countHashChanges = false }) {
|
|
8
|
+
return /*#__PURE__*/ jsxs(Fragment, {
|
|
9
|
+
children: [
|
|
10
|
+
/*#__PURE__*/ jsx("script", {
|
|
11
|
+
defer: true,
|
|
12
|
+
src: src,
|
|
13
|
+
"data-endpoint": endpoint,
|
|
14
|
+
"data-cdn-hosts": boundedAttribute(cdnHosts),
|
|
15
|
+
"data-download-extensions": boundedAttribute(downloadExtensions),
|
|
16
|
+
"data-ignore-prefixes": boundedAttribute(ignoredPathPrefixes),
|
|
17
|
+
"data-count-search": countSearchChanges ? 'true' : void 0,
|
|
18
|
+
"data-count-hash": countHashChanges ? 'true' : void 0
|
|
19
|
+
}),
|
|
20
|
+
/*#__PURE__*/ jsx(AnalyticsNavigationBridge, {})
|
|
21
|
+
]
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
function AnalyticsNavigationBridge() {
|
|
25
|
+
const href = useRouterState({
|
|
26
|
+
select: (state)=>state.location.href
|
|
27
|
+
});
|
|
28
|
+
const previousHref = useRef(void 0);
|
|
29
|
+
useEffect(()=>{
|
|
30
|
+
const previous = previousHref.current;
|
|
31
|
+
previousHref.current = href;
|
|
32
|
+
if (null == previous || previous === href) return;
|
|
33
|
+
document.dispatchEvent(new CustomEvent(ANALYTICS_NAVIGATION_EVENT, {
|
|
34
|
+
detail: href
|
|
35
|
+
}));
|
|
36
|
+
}, [
|
|
37
|
+
href
|
|
38
|
+
]);
|
|
39
|
+
useEffect(()=>{
|
|
40
|
+
if (void 0 !== pendingStopTimer) {
|
|
41
|
+
window.clearTimeout(pendingStopTimer);
|
|
42
|
+
pendingStopTimer = void 0;
|
|
43
|
+
}
|
|
44
|
+
return ()=>{
|
|
45
|
+
pendingStopTimer = window.setTimeout(()=>{
|
|
46
|
+
pendingStopTimer = void 0;
|
|
47
|
+
document.dispatchEvent(new Event(ANALYTICS_STOP_EVENT));
|
|
48
|
+
}, 0);
|
|
49
|
+
};
|
|
50
|
+
}, []);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
function boundedAttribute(values) {
|
|
54
|
+
if (null == values || 0 === values.length) return;
|
|
55
|
+
return values.slice(0, 64).join(',').slice(0, 2048);
|
|
56
|
+
}
|
|
57
|
+
export { AnalyticsAgent };
|
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
import { type Analytics } from '@byline/analytics';
|
|
9
|
+
import { type BylineLogger } from '@byline/core';
|
|
10
|
+
export interface AnalyticsEventHandlerOptions {
|
|
11
|
+
/** Host-owned resolver for deployment-specific, request-scoped network facts. */
|
|
12
|
+
resolveRequestContext: AnalyticsRequestContextResolver;
|
|
13
|
+
/** Test/embedding seam; production resolves the registered installation runtime. */
|
|
14
|
+
analytics?: () => Pick<Analytics, 'ingest'>;
|
|
15
|
+
/** Test/embedding seam; production resolves the initialized application logger. */
|
|
16
|
+
logger?: () => Pick<BylineLogger, 'error'>;
|
|
17
|
+
}
|
|
18
|
+
export interface AnalyticsRequestContext {
|
|
19
|
+
clientIp?: string | null;
|
|
20
|
+
country?: string | null;
|
|
21
|
+
}
|
|
22
|
+
export type AnalyticsRequestContextResolver = (request: Request) => AnalyticsRequestContext | Promise<AnalyticsRequestContext>;
|
|
23
|
+
export interface LocalAnalyticsRequestContextOptions {
|
|
24
|
+
/** Resolve the direct peer address from the host runtime, without forwarded headers. */
|
|
25
|
+
resolveClientIp: (request: Request) => string | null | undefined | Promise<string | null | undefined>;
|
|
26
|
+
/** Explicit development-only identity for runtimes that expose no peer address. */
|
|
27
|
+
developmentFallbackClientIp?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface TrustedAnalyticsHeadersOptions {
|
|
30
|
+
/** Header overwritten by the trusted reverse proxy with the normalized client address. */
|
|
31
|
+
clientIpHeader: string;
|
|
32
|
+
/** Optional header overwritten by the trusted edge with an ISO country code. */
|
|
33
|
+
countryHeader?: string;
|
|
34
|
+
/** Explicit context or resolver used only when a trusted header is absent. */
|
|
35
|
+
fallback?: AnalyticsRequestContext | AnalyticsRequestContextResolver;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Resolve an identity for a server reached directly through a loopback URL.
|
|
39
|
+
* Both the URL and the direct peer address must be loopback. This is safe for
|
|
40
|
+
* a directly reached local server. A same-host reverse proxy also appears as
|
|
41
|
+
* a loopback peer, however, so do not expose this fallback through a public
|
|
42
|
+
* proxy where a client can select the Host header.
|
|
43
|
+
*/
|
|
44
|
+
export declare function localAnalyticsRequestContext(options: LocalAnalyticsRequestContextOptions): AnalyticsRequestContextResolver;
|
|
45
|
+
/**
|
|
46
|
+
* Resolve network facts from headers owned and overwritten by a trusted proxy.
|
|
47
|
+
* This helper does not establish that trust: the deployment must prevent a
|
|
48
|
+
* client from selecting the configured header values or bypassing the proxy.
|
|
49
|
+
*/
|
|
50
|
+
export declare function trustedAnalyticsHeaders(options: TrustedAnalyticsHeadersOptions): AnalyticsRequestContextResolver;
|
|
51
|
+
export declare function createAnalyticsEventHandler(options: AnalyticsEventHandlerOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { ANALYTICS_MAX_BODY_BYTES, getAnalytics } from "@byline/analytics";
|
|
2
|
+
import { getLogger } from "@byline/core";
|
|
3
|
+
function localAnalyticsRequestContext(options) {
|
|
4
|
+
const developmentFallbackClientIp = null == options.developmentFallbackClientIp ? void 0 : validateFact(options.developmentFallbackClientIp, 'developmentFallbackClientIp', 255);
|
|
5
|
+
return async (request)=>{
|
|
6
|
+
const clientIp = await options.resolveClientIp(request);
|
|
7
|
+
if (isLoopbackHostname(new URL(request.url).hostname) && isLoopbackAddress(clientIp)) return {
|
|
8
|
+
clientIp: validateFact(clientIp, 'resolved clientIp', 255)
|
|
9
|
+
};
|
|
10
|
+
return null == developmentFallbackClientIp ? {} : {
|
|
11
|
+
clientIp: developmentFallbackClientIp
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function trustedAnalyticsHeaders(options) {
|
|
16
|
+
const clientIpHeader = validateHeaderName(options.clientIpHeader, 'clientIpHeader');
|
|
17
|
+
const countryHeader = null == options.countryHeader ? void 0 : validateHeaderName(options.countryHeader, 'countryHeader');
|
|
18
|
+
const fallback = 'function' == typeof options.fallback ? options.fallback : validateFallback(options.fallback);
|
|
19
|
+
return async (request)=>{
|
|
20
|
+
const fallbackContext = 'function' == typeof fallback ? validateFallback(await fallback(request)) : fallback;
|
|
21
|
+
return {
|
|
22
|
+
clientIp: request.headers.get(clientIpHeader)?.trim() || fallbackContext?.clientIp,
|
|
23
|
+
country: (null == countryHeader ? null : request.headers.get(countryHeader)?.trim()) || fallbackContext?.country
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function createAnalyticsEventHandler(options) {
|
|
28
|
+
const resolveAnalytics = options.analytics ?? getAnalytics;
|
|
29
|
+
return async (request)=>{
|
|
30
|
+
const body = await readBoundedBody(request, ANALYTICS_MAX_BODY_BYTES);
|
|
31
|
+
try {
|
|
32
|
+
const requestContext = await options.resolveRequestContext(request);
|
|
33
|
+
const result = await resolveAnalytics().ingest({
|
|
34
|
+
method: request.method,
|
|
35
|
+
body: body ?? new Uint8Array(ANALYTICS_MAX_BODY_BYTES + 1),
|
|
36
|
+
origin: request.headers.get('origin'),
|
|
37
|
+
referer: request.headers.get('referer'),
|
|
38
|
+
userAgent: request.headers.get('user-agent'),
|
|
39
|
+
secPurpose: request.headers.get('sec-purpose'),
|
|
40
|
+
xPurpose: request.headers.get('x-purpose'),
|
|
41
|
+
clientIp: requestContext.clientIp,
|
|
42
|
+
country: requestContext.country
|
|
43
|
+
});
|
|
44
|
+
return analyticsResponse(result.status);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
const logger = options.logger?.() ?? getLogger();
|
|
47
|
+
logger.error({
|
|
48
|
+
errorCode: safeErrorCode(error)
|
|
49
|
+
}, '[analytics] event persistence failed');
|
|
50
|
+
return analyticsResponse(503);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function safeErrorCode(error) {
|
|
55
|
+
if (null == error || 'object' != typeof error || !('code' in error)) return 'UNKNOWN';
|
|
56
|
+
const code = error.code;
|
|
57
|
+
return 'string' == typeof code && /^[a-z0-9_-]{1,64}$/iu.test(code) ? code : 'UNKNOWN';
|
|
58
|
+
}
|
|
59
|
+
function analyticsResponse(status) {
|
|
60
|
+
return new Response(null, {
|
|
61
|
+
status,
|
|
62
|
+
headers: {
|
|
63
|
+
'cache-control': 'no-store'
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function readBoundedBody(request, limit) {
|
|
68
|
+
const declaredLength = Number(request.headers.get('content-length'));
|
|
69
|
+
if (Number.isFinite(declaredLength) && declaredLength > limit) return null;
|
|
70
|
+
if (null == request.body) return new Uint8Array();
|
|
71
|
+
const reader = request.body.getReader();
|
|
72
|
+
const chunks = [];
|
|
73
|
+
let length = 0;
|
|
74
|
+
try {
|
|
75
|
+
while(true){
|
|
76
|
+
const { done, value } = await reader.read();
|
|
77
|
+
if (done) break;
|
|
78
|
+
length += value.byteLength;
|
|
79
|
+
if (length > limit) {
|
|
80
|
+
await reader.cancel();
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
chunks.push(value);
|
|
84
|
+
}
|
|
85
|
+
} finally{
|
|
86
|
+
reader.releaseLock();
|
|
87
|
+
}
|
|
88
|
+
const body = new Uint8Array(length);
|
|
89
|
+
let offset = 0;
|
|
90
|
+
for (const chunk of chunks){
|
|
91
|
+
body.set(chunk, offset);
|
|
92
|
+
offset += chunk.byteLength;
|
|
93
|
+
}
|
|
94
|
+
return body;
|
|
95
|
+
}
|
|
96
|
+
function validateHeaderName(value, label) {
|
|
97
|
+
const normalized = value.trim().toLowerCase();
|
|
98
|
+
if (!/^[!#$%&'*+.^_`|~0-9a-z-]+$/u.test(normalized)) throw new Error(`analytics ${label} must be a valid HTTP header name`);
|
|
99
|
+
return normalized;
|
|
100
|
+
}
|
|
101
|
+
function validateFallback(value) {
|
|
102
|
+
if (null == value) return;
|
|
103
|
+
return {
|
|
104
|
+
...null == value.clientIp ? {} : {
|
|
105
|
+
clientIp: validateFact(value.clientIp, 'fallback.clientIp', 255)
|
|
106
|
+
},
|
|
107
|
+
...null == value.country ? {} : {
|
|
108
|
+
country: validateFact(value.country, 'fallback.country', 16)
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function validateFact(value, label, maxLength) {
|
|
113
|
+
const normalized = value.trim();
|
|
114
|
+
if (0 === normalized.length || normalized.length > maxLength) throw new Error(`analytics ${label} must contain 1 to ${maxLength} characters`);
|
|
115
|
+
return normalized;
|
|
116
|
+
}
|
|
117
|
+
function isLoopbackHostname(value) {
|
|
118
|
+
const normalized = stripIpv6Brackets(value.toLowerCase());
|
|
119
|
+
return 'localhost' === normalized || normalized.endsWith('.localhost') || isLoopbackAddress(normalized);
|
|
120
|
+
}
|
|
121
|
+
function isLoopbackAddress(value) {
|
|
122
|
+
if (null == value) return false;
|
|
123
|
+
const normalized = stripIpv6Brackets(value.trim().toLowerCase());
|
|
124
|
+
return '::1' === normalized || /^127(?:\.\d{1,3}){3}$/u.test(normalized) || /^::ffff:127(?:\.\d{1,3}){3}$/u.test(normalized);
|
|
125
|
+
}
|
|
126
|
+
function stripIpv6Brackets(value) {
|
|
127
|
+
return value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value;
|
|
128
|
+
}
|
|
129
|
+
export { createAnalyticsEventHandler, localAnalyticsRequestContext, trustedAnalyticsHeaders };
|
|
@@ -0,0 +1,8 @@
|
|
|
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
|
+
export declare function serveAnalyticsAgent(): Response;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ANALYTICS_AGENT_SOURCE } from "@byline/analytics-agent/source";
|
|
2
|
+
function serveAnalyticsAgent() {
|
|
3
|
+
return new Response(ANALYTICS_AGENT_SOURCE, {
|
|
4
|
+
headers: {
|
|
5
|
+
'cache-control': 'public, max-age=3600, must-revalidate',
|
|
6
|
+
'content-type': "text/javascript; charset=utf-8",
|
|
7
|
+
'x-content-type-options': 'nosniff'
|
|
8
|
+
}
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
export { serveAnalyticsAgent };
|
|
@@ -0,0 +1,12 @@
|
|
|
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
|
+
import type { AnalyticsDashboardPeriod } from '@byline/admin/analytics';
|
|
9
|
+
export declare function buildAnalyticsDashboardRange(period: AnalyticsDashboardPeriod, now?: Date, earliestReportDay?: string | null): {
|
|
10
|
+
from: string;
|
|
11
|
+
to: string;
|
|
12
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const UTC_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
|
|
2
|
+
function buildAnalyticsDashboardRange(period, now = new Date(), earliestReportDay = null) {
|
|
3
|
+
const to = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
4
|
+
if ('ytd' === period) return {
|
|
5
|
+
from: formatUtcDay(new Date(Date.UTC(to.getUTCFullYear(), 0, 1))),
|
|
6
|
+
to: formatUtcDay(to)
|
|
7
|
+
};
|
|
8
|
+
if ('all' === period) {
|
|
9
|
+
const toDay = formatUtcDay(to);
|
|
10
|
+
const earliest = null == earliestReportDay ? toDay : assertUtcDay(earliestReportDay);
|
|
11
|
+
return {
|
|
12
|
+
from: earliest <= toDay ? earliest : toDay,
|
|
13
|
+
to: toDay
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
const from = new Date(to);
|
|
17
|
+
from.setUTCDate(from.getUTCDate() - (period - 1));
|
|
18
|
+
return {
|
|
19
|
+
from: formatUtcDay(from),
|
|
20
|
+
to: formatUtcDay(to)
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function formatUtcDay(value) {
|
|
24
|
+
const year = value.getUTCFullYear().toString().padStart(4, '0');
|
|
25
|
+
const month = (value.getUTCMonth() + 1).toString().padStart(2, '0');
|
|
26
|
+
const day = value.getUTCDate().toString().padStart(2, '0');
|
|
27
|
+
return `${year}-${month}-${day}`;
|
|
28
|
+
}
|
|
29
|
+
function assertUtcDay(value) {
|
|
30
|
+
if (!UTC_DAY_PATTERN.test(value)) throw new Error('analytics report day must use YYYY-MM-DD');
|
|
31
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
32
|
+
if (!Number.isFinite(date.valueOf()) || formatUtcDay(date) !== value) throw new Error('analytics report day must be a real UTC calendar day');
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
export { buildAnalyticsDashboardRange };
|
|
@@ -0,0 +1,8 @@
|
|
|
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
|
+
export declare function createAdminAnalyticsRoute(path: string): any;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { createFileRoute, notFound } from "@tanstack/react-router";
|
|
3
|
+
import { AnalyticsDashboard } from "@byline/admin/analytics/components/dashboard";
|
|
4
|
+
import { isAnalyticsDashboardPeriod } from "@byline/analytics/config";
|
|
5
|
+
import { useTranslation } from "@byline/i18n/react";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { BreadcrumbsClient } from "../admin-shell/chrome/breadcrumbs/breadcrumbs-client.js";
|
|
8
|
+
import { useNavigate } from "../admin-shell/chrome/loose-router.js";
|
|
9
|
+
import { getAnalyticsCountries, getAnalyticsReferrers, getAnalyticsReportCoverage, getAnalyticsRuntime, getAnalyticsSummary, getAnalyticsTop } from "../server-fns/analytics/index.js";
|
|
10
|
+
import { getAdminRoutePath } from "./admin-path.js";
|
|
11
|
+
import { buildAnalyticsDashboardRange } from "./analytics-range.js";
|
|
12
|
+
const periodSchema = z.preprocess((value)=>{
|
|
13
|
+
if (null == value) return;
|
|
14
|
+
if ('ytd' === value || 'all' === value) return value;
|
|
15
|
+
return Number(value);
|
|
16
|
+
}, z.custom((value)=>isAnalyticsDashboardPeriod(value)).optional());
|
|
17
|
+
const searchSchema = z.object({
|
|
18
|
+
period: periodSchema.catch(void 0)
|
|
19
|
+
});
|
|
20
|
+
function createAdminAnalyticsRoute(path) {
|
|
21
|
+
const Route = createFileRoute(path)({
|
|
22
|
+
validateSearch: searchSchema,
|
|
23
|
+
loaderDeps: ({ search })=>({
|
|
24
|
+
period: search.period ?? 30
|
|
25
|
+
}),
|
|
26
|
+
loader: async ({ deps })=>{
|
|
27
|
+
const runtime = await getAnalyticsRuntime();
|
|
28
|
+
if (!runtime.enabled) throw notFound();
|
|
29
|
+
const coverage = await getAnalyticsReportCoverage();
|
|
30
|
+
const range = buildAnalyticsDashboardRange(deps.period, new Date(), coverage.summaryFrom);
|
|
31
|
+
const [summary, pages, downloads, referrers, countries] = await Promise.all([
|
|
32
|
+
getAnalyticsSummary({
|
|
33
|
+
data: range
|
|
34
|
+
}),
|
|
35
|
+
getAnalyticsTop({
|
|
36
|
+
data: {
|
|
37
|
+
...range,
|
|
38
|
+
kind: 'page',
|
|
39
|
+
limit: 20
|
|
40
|
+
}
|
|
41
|
+
}),
|
|
42
|
+
getAnalyticsTop({
|
|
43
|
+
data: {
|
|
44
|
+
...range,
|
|
45
|
+
kind: 'download',
|
|
46
|
+
limit: 20
|
|
47
|
+
}
|
|
48
|
+
}),
|
|
49
|
+
getAnalyticsReferrers({
|
|
50
|
+
data: {
|
|
51
|
+
...range,
|
|
52
|
+
limit: 20
|
|
53
|
+
}
|
|
54
|
+
}),
|
|
55
|
+
getAnalyticsCountries({
|
|
56
|
+
data: range
|
|
57
|
+
})
|
|
58
|
+
]);
|
|
59
|
+
return {
|
|
60
|
+
data: {
|
|
61
|
+
summary,
|
|
62
|
+
pages,
|
|
63
|
+
downloads,
|
|
64
|
+
referrers,
|
|
65
|
+
countries,
|
|
66
|
+
range,
|
|
67
|
+
coverage
|
|
68
|
+
},
|
|
69
|
+
period: deps.period
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
component: function() {
|
|
73
|
+
const { data, period } = Route.useLoaderData();
|
|
74
|
+
const navigate = useNavigate();
|
|
75
|
+
const { t } = useTranslation('byline-admin');
|
|
76
|
+
return /*#__PURE__*/ jsxs(Fragment, {
|
|
77
|
+
children: [
|
|
78
|
+
/*#__PURE__*/ jsx(BreadcrumbsClient, {
|
|
79
|
+
breadcrumbs: [
|
|
80
|
+
{
|
|
81
|
+
label: t('chrome.menu.dashboard'),
|
|
82
|
+
href: getAdminRoutePath()
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
label: t('analytics.title'),
|
|
86
|
+
href: getAdminRoutePath('analytics')
|
|
87
|
+
}
|
|
88
|
+
]
|
|
89
|
+
}),
|
|
90
|
+
/*#__PURE__*/ jsx(AnalyticsDashboard, {
|
|
91
|
+
data: data,
|
|
92
|
+
period: period,
|
|
93
|
+
onPeriodChange: (nextPeriod)=>{
|
|
94
|
+
navigate({
|
|
95
|
+
to: getAdminRoutePath('analytics'),
|
|
96
|
+
search: {
|
|
97
|
+
period: nextPeriod
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
]
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
return Route;
|
|
107
|
+
}
|
|
108
|
+
export { createAdminAnalyticsRoute };
|
|
@@ -18,6 +18,7 @@ import { buildLocaleDefinitions } from "../i18n/locale-definitions.js";
|
|
|
18
18
|
import { bylineAdminServices } from "../integrations/byline-admin-services.js";
|
|
19
19
|
import { BylineAiAdminProvider } from "../integrations/byline-ai.js";
|
|
20
20
|
import { bylineFieldServices } from "../integrations/byline-field-services.js";
|
|
21
|
+
import { getAnalyticsRuntime } from "../server-fns/analytics/index.js";
|
|
21
22
|
import { getCurrentAdminUser } from "../server-fns/auth/index.js";
|
|
22
23
|
import { getScheduledPublicationRuntime } from "../server-fns/collections/index.js";
|
|
23
24
|
import { getActiveLocaleFn, setAdminLocaleFn } from "../server-fns/i18n/index.js";
|
|
@@ -28,12 +29,16 @@ function createAdminLayoutRoute(path) {
|
|
|
28
29
|
const signInPath = getSignInRoutePath();
|
|
29
30
|
try {
|
|
30
31
|
const user = await getCurrentAdminUser();
|
|
31
|
-
const activeLocale = await
|
|
32
|
-
|
|
32
|
+
const [activeLocale, scheduledPublicationRuntime, analyticsRuntime] = await Promise.all([
|
|
33
|
+
getActiveLocaleFn(),
|
|
34
|
+
getScheduledPublicationRuntime(),
|
|
35
|
+
getAnalyticsRuntime()
|
|
36
|
+
]);
|
|
33
37
|
return {
|
|
34
38
|
user,
|
|
35
39
|
activeLocale,
|
|
36
|
-
scheduledPublicationRuntime
|
|
40
|
+
scheduledPublicationRuntime,
|
|
41
|
+
analyticsRuntime
|
|
37
42
|
};
|
|
38
43
|
} catch {
|
|
39
44
|
throw redirect({
|
|
@@ -45,7 +50,7 @@ function createAdminLayoutRoute(path) {
|
|
|
45
50
|
}
|
|
46
51
|
},
|
|
47
52
|
component: function() {
|
|
48
|
-
const { user, activeLocale, scheduledPublicationRuntime } = Route.useRouteContext();
|
|
53
|
+
const { user, activeLocale, scheduledPublicationRuntime, analyticsRuntime } = Route.useRouteContext();
|
|
49
54
|
const { i18n } = getAdminConfig();
|
|
50
55
|
const localeDefinitions = buildLocaleDefinitions(i18n.admin.locales, i18n.admin.localeDefinitions);
|
|
51
56
|
useEffect(()=>{
|
|
@@ -80,6 +85,7 @@ function createAdminLayoutRoute(path) {
|
|
|
80
85
|
className: clsx('byline-admin-layout-main', admin_layout_module.main),
|
|
81
86
|
children: [
|
|
82
87
|
/*#__PURE__*/ jsx(AdminMenuDrawer, {
|
|
88
|
+
analyticsEnabled: analyticsRuntime.enabled,
|
|
83
89
|
scheduledPublicationEnabled: scheduledPublicationRuntime.enabled
|
|
84
90
|
}),
|
|
85
91
|
/*#__PURE__*/ jsx(Content, {
|
package/dist/routes/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { getSignInRoutePath } from './sign-in-path.js';
|
|
|
23
23
|
*/
|
|
24
24
|
export { createAdminAccountRoute } from './create-admin-account-route.js';
|
|
25
25
|
export { createAdminActivityRoute } from './create-admin-activity-route.js';
|
|
26
|
+
export { createAdminAnalyticsRoute } from './create-admin-analytics-route.js';
|
|
26
27
|
export { createAdminDashboardRoute } from './create-admin-dashboard-route.js';
|
|
27
28
|
export { createAdminLayoutRoute } from './create-admin-layout-route.js';
|
|
28
29
|
export { createAdminPermissionsRoute } from './create-admin-permissions-route.js';
|
package/dist/routes/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export { getAdminRouteId, getAdminRoutePath, isAdminRoutePathActive, isRoutePath
|
|
|
2
2
|
export { getSignInRoutePath } from "./sign-in-path.js";
|
|
3
3
|
export { createAdminAccountRoute } from "./create-admin-account-route.js";
|
|
4
4
|
export { createAdminActivityRoute } from "./create-admin-activity-route.js";
|
|
5
|
+
export { createAdminAnalyticsRoute } from "./create-admin-analytics-route.js";
|
|
5
6
|
export { createAdminDashboardRoute } from "./create-admin-dashboard-route.js";
|
|
6
7
|
export { createAdminLayoutRoute } from "./create-admin-layout-route.js";
|
|
7
8
|
export { createAdminPermissionsRoute } from "./create-admin-permissions-route.js";
|
|
@@ -0,0 +1,9 @@
|
|
|
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
|
+
export { type DeleteAnalyticsEventsInput, deleteAnalyticsEvents, rebuildAnalyticsDay, } from './maintenance.js';
|
|
9
|
+
export { type AnalyticsRuntimeState, type AnalyticsTopInput, getAnalyticsCountries, getAnalyticsReferrers, getAnalyticsReportCoverage, getAnalyticsRuntime, getAnalyticsSummary, getAnalyticsTop, } from './queries.js';
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
export interface DeleteAnalyticsEventsInput {
|
|
9
|
+
from: string;
|
|
10
|
+
to: string;
|
|
11
|
+
visitorHash?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare const deleteAnalyticsEvents: import("@tanstack/react-start").RequiredFetcher<undefined, (input: DeleteAnalyticsEventsInput) => DeleteAnalyticsEventsInput, Promise<{
|
|
14
|
+
deleted: number;
|
|
15
|
+
}>>;
|
|
16
|
+
export declare const rebuildAnalyticsDay: import("@tanstack/react-start").RequiredFetcher<undefined, (input: {
|
|
17
|
+
day: string;
|
|
18
|
+
}) => {
|
|
19
|
+
day: string;
|
|
20
|
+
}, Promise<{
|
|
21
|
+
rebuilt: string;
|
|
22
|
+
}>>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createServerFn } from "@tanstack/react-start";
|
|
2
|
+
import { assertAdminActor } from "@byline/admin";
|
|
3
|
+
import { ANALYTICS_ABILITIES } from "@byline/admin/analytics";
|
|
4
|
+
import { getAdminRequestContext } from "@byline/client/server";
|
|
5
|
+
const deleteAnalyticsEvents = createServerFn({
|
|
6
|
+
method: 'POST'
|
|
7
|
+
}).validator((input)=>input).handler(async ({ data })=>{
|
|
8
|
+
await assertAnalyticsMaintenance();
|
|
9
|
+
const { getAnalytics } = await import("@byline/analytics");
|
|
10
|
+
const from = parseInstant(data.from, 'from');
|
|
11
|
+
const to = parseInstant(data.to, 'to');
|
|
12
|
+
const deleted = await getAnalytics().deleteEvents({
|
|
13
|
+
from,
|
|
14
|
+
to,
|
|
15
|
+
...null == data.visitorHash ? {} : {
|
|
16
|
+
visitorHash: data.visitorHash
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
deleted
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
const rebuildAnalyticsDay = createServerFn({
|
|
24
|
+
method: 'POST'
|
|
25
|
+
}).validator((input)=>input).handler(async ({ data })=>{
|
|
26
|
+
await assertAnalyticsMaintenance();
|
|
27
|
+
const { getAnalytics } = await import("@byline/analytics");
|
|
28
|
+
await getAnalytics().rebuildDay(data.day);
|
|
29
|
+
return {
|
|
30
|
+
rebuilt: data.day
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
async function assertAnalyticsMaintenance() {
|
|
34
|
+
const context = await getAdminRequestContext();
|
|
35
|
+
assertAdminActor(context, ANALYTICS_ABILITIES.maintain);
|
|
36
|
+
}
|
|
37
|
+
function parseInstant(value, label) {
|
|
38
|
+
const date = new Date(value);
|
|
39
|
+
if (Number.isNaN(date.valueOf())) throw new Error(`analytics ${label} must be an ISO instant`);
|
|
40
|
+
return date;
|
|
41
|
+
}
|
|
42
|
+
export { deleteAnalyticsEvents, rebuildAnalyticsDay };
|