Add a dedicated Analytics section #47

Merged
eleith merged 10 commits from feat/admin-analytics into main 2026-11-23 01:26:41 +00:00
45 changed files with 2392 additions and 2437 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
---
'@goto/web': minor
'@goto/cli': minor
'@goto/worker': minor
---
Add a dedicated Analytics page with one searchable scope picker for all traffic, domains, Root and named redirects, or tags. Tag reports use current YAML membership across domains. Hide its navigation link when analytics is disabled and send direct visits to Health. Display the 90-day timeframe in days without changing the reporting window. Use a chart icon beside Health and compact icon controls in the mobile navbar. Keep Overview, Domain, Root, named Link, and Tag pages focused on configuration and all-time visit summaries, with their charts, breakdowns, and timeframes in Analytics.
When Analytics is enabled, add report links to Domain, Root, Link, and Tag details. The Root page opens its domain-wide report. Show the tag name in the Tag details card instead of the page heading.
+381 -242
View File
@@ -13,20 +13,16 @@ test('shared credentials protect admin pages and sign-out removes access', async
appServer
}) => {
await page.setViewportSize({ width: 1280, height: 720 });
const navigationWarnings: string[] = [];
page.on('console', (message) => {
const text = message.text();
if (text.includes('push_state_deprecated')) navigationWarnings.push(text);
});
const root = await request.get('/', { maxRedirects: 0 });
expect(root.status()).toBe(404);
expect(root.headers().location).toBeUndefined();
const adminRedirect = await request.get('/admin', {
const adminRedirect = await request.get('/admin/analytics', {
headers: { accept: 'text/html' },
maxRedirects: 0
});
expect(adminRedirect.status()).toBe(303);
expect(adminRedirect.headers().location).toBe('/signin?callbackUrl=%2Fadmin%2Fanalytics');
expect(adminRedirect.headers()['cache-control']).toBe('private, no-store');
const signInPage = await page.goto(`${appServer.origin}/admin`);
@@ -44,109 +40,30 @@ test('shared credentials protect admin pages and sign-out removes access', async
await page.getByLabel('Password', { exact: true }).fill('e2e-only-password');
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible();
const visitsValue = page
.getByRole('region', { name: 'Visits', exact: true })
.locator('.admin-stat-value');
await expect(page.getByRole('region', { name: 'Domains', exact: true })).toContainText('2');
await expect(visitsValue).toHaveText('3');
const acceptedLanguages = page.getByRole('region', { name: 'Accepted languages', exact: true });
await expect(acceptedLanguages.getByRole('columnheader')).toHaveText([
'Language',
'Visits',
'Share'
]);
await expect(
acceptedLanguages.getByRole('rowheader', { name: 'Other', exact: true })
).toBeVisible();
const browsers = page.getByRole('region', { name: 'Browsers', exact: true });
const operatingSystems = page.getByRole('region', { name: 'Operating systems', exact: true });
await expect(browsers).toBeVisible();
await expect(operatingSystems).toBeVisible();
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
const summary = page.getByRole('region', { name: 'Summary', exact: true });
await expect(summary.locator('.admin-stat-label')).toHaveText([
'Domains',
'Links',
'Visits',
'Retention'
'Total Visits'
]);
const totalVisits = summary.getByRole('region', { name: 'Total Visits', exact: true });
await expect(totalVisits.getByText('5', { exact: true })).toBeVisible();
await expect(summary.getByRole('link')).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount(
0
);
const heading = page.locator('.admin-heading');
await expect(heading.locator('.admin-title > h1 + time')).toBeVisible();
const timeframe = heading.getByRole('group', { name: 'Timeframe', exact: true });
await expect(timeframe.getByRole('button')).toHaveText(['7 days', '30 days', '3 months']);
await expect(timeframe.getByRole('button', { name: '30 days', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
const trend = page.getByRole('region', { name: 'Visits over time', exact: true });
const graph = trend.getByRole('img');
await expect(graph).toHaveAttribute('aria-busy', 'false');
const chartTable = trend.getByRole('table');
await expect(chartTable).toBeVisible();
await expect(chartTable).toHaveAccessibleName('Visits');
await expect(chartTable.getByRole('columnheader')).toHaveText(['Period (UTC)', 'Visits']);
await expect(chartTable.getByRole('row', { name: 'Total 3', exact: true })).toBeVisible();
await expect(chartTable).not.toContainText('(partial)');
await expect(trend.getByRole('region', { name: 'Visit data', exact: true })).toHaveAttribute(
'tabindex',
'0'
);
await expect(graph).toBeVisible();
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 3\./);
await expect(timeframe).toHaveCount(0);
const domainLink = page.getByRole('link', { name: 'go.example.org', exact: true });
const domainRow = page.getByRole('listitem').filter({ has: domainLink });
const domainCounts = domainRow.locator('.admin-inventory-number');
await expect(domainCounts).toHaveText(['6', '2']);
const selectionRequests: string[] = [];
const recordSelectionRequest = (request: Request) => {
const type = request.resourceType();
if (type === 'document' || type === 'fetch' || type === 'xhr') {
selectionRequests.push(request.url());
}
};
page.on('request', recordSelectionRequest);
await timeframe.getByRole('button', { name: '7 days', exact: true }).click();
await expect(page).toHaveURL(`${appServer.origin}/admin?period=7d`);
await expect(timeframe.getByRole('button', { name: '7 days', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('2');
await expect(domainCounts).toHaveText(['6', '1']);
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./);
await timeframe.getByRole('button', { name: '3 months', exact: true }).click();
await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('4');
await expect(domainCounts).toHaveText(['6', '3']);
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./);
await page.goBack();
await expect(timeframe.getByRole('button', { name: '7 days', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('2');
await expect(domainCounts).toHaveText(['6', '1']);
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./);
await page.goForward();
await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('4');
await expect(domainCounts).toHaveText(['6', '3']);
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./);
page.off('request', recordSelectionRequest);
expect(selectionRequests).toEqual([]);
const overviewResponse = await page.reload();
await expect(domainRow.locator('.admin-inventory-number')).toHaveText(['6', '3']);
const overviewResponse = await page.goto(`${appServer.origin}/admin?period=7d`);
expect(overviewResponse?.headers()['cache-control']).toBe('private, no-store');
await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('4');
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 4\./);
expect(navigationWarnings).toEqual([]);
await expect(totalVisits.getByText('5', { exact: true })).toBeVisible();
const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true });
const overviewLink = adminNav.getByRole('link', { name: 'GoTo', exact: true });
await expect(adminNav.getByText('GoTo', { exact: true })).toBeVisible();
@@ -156,33 +73,22 @@ test('shared credentials protect admin pages and sign-out removes access', async
const context = page.locator('.admin-context');
await expect(context).toHaveCount(0);
await expect(page).toHaveTitle('Domain — go.example.org — GoTo');
await expect(acceptedLanguages).toBeVisible();
await expect(browsers.getByRole('columnheader')).toHaveText(['Browser', 'Visits', 'Share']);
await expect(operatingSystems.getByRole('columnheader')).toHaveText([
'Operating system',
'Visits',
'Share'
]);
await expect(browsers.getByRole('rowheader', { name: 'Other', exact: true })).toBeVisible();
await expect(overviewLink).toHaveAttribute('href', '/admin?period=all');
await expect(timeframe).toHaveCount(0);
const trend = page.getByRole('region', { name: 'Visits over time', exact: true });
await expect(trend).toHaveCount(0);
await expect(overviewLink).toHaveAttribute('href', '/admin');
const appIcon = overviewLink.locator('img[src="/@static/favicon.svg"]');
await expect(appIcon).toBeVisible();
await expect
.poll(() => appIcon.evaluate((image: HTMLImageElement) => image.naturalWidth))
.toBeGreaterThan(0);
await expect(page.getByRole('link', { name: 'Overview', exact: true })).toHaveCount(0);
await expect(graph).toHaveAttribute('aria-busy', 'false');
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 3\./);
await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('3');
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
await expect(summary.locator('.admin-stat-label')).toHaveText([
'Links',
'Visits',
'Total Visits',
'Invalid clicks'
]);
await expect(totalVisits.getByText('3', { exact: true })).toBeVisible();
await expect(
page.getByRole('region', { name: 'Invalid clicks', exact: true }).locator('.admin-stat-value')
).toHaveText('1');
@@ -194,70 +100,66 @@ test('shared credentials protect admin pages and sign-out removes access', async
const rootLink = rootRow.getByRole('link', { name: '(root)', exact: true });
await expect(rootRow.locator('.admin-inventory-secondary')).toHaveText('[not found]');
await expect(rootRow.locator('.admin-inventory-state')).toHaveText('Active');
const columns = ['Path', 'Destination', 'State', 'Visits'];
const columns = ['Path', 'Destination', 'State', 'Total Visits'];
await expect(linksInventory.locator('.admin-inventory-heading > span')).toHaveText(columns);
const retainedLink = linksInventory
const percentLinkRow = linksInventory
.getByRole('listitem')
.filter({ has: page.getByRole('link', { name: '/a%2Fb', exact: true }) });
await expect(retainedLink.getByRole('link')).toHaveCount(1);
const retainedVisits = retainedLink.locator('.admin-inventory-number');
await expect(retainedVisits).toHaveText('1');
await page.setViewportSize({ width: 390, height: 844 });
const mobileTimeframe = page.getByRole('button', { name: /^Timeframe: / });
await expect(mobileTimeframe).toContainText('3 months');
await mobileTimeframe.click();
await page
.getByRole('listbox', { name: 'Timeframe', exact: true })
.getByRole('option', { name: '30 days', exact: true })
.click();
await expect(visitsValue).toHaveText('2');
await expect(retainedVisits).toHaveText('0');
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 2\./);
expect(
await linksInventory.evaluate((element) => element.scrollWidth <= element.clientWidth)
).toBe(true);
await page.setViewportSize({ width: 1280, height: 720 });
await timeframe.getByRole('button', { name: '3 months', exact: true }).click();
await expect(visitsValue).toHaveText('3');
await expect(retainedVisits).toHaveText('1');
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 3\./);
await expect(percentLinkRow.getByRole('link')).toHaveCount(1);
await expect(percentLinkRow.locator('.admin-inventory-number')).toHaveText('1');
const historicalInvalid = linksInventory
.getByRole('listitem')
.filter({ has: page.getByRole('link', { name: '/a/b', exact: true }) });
await expect(historicalInvalid.locator('.admin-inventory-number')).toHaveText('0');
await expect(domainDetails.getByRole('heading', { name: 'Details', exact: true })).toBeVisible();
await expect(domainDetails.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback']);
const domainReportPath = '/admin/analytics?domain=go.example.org';
await expect(domainDetails.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback', 'Analytics']);
await expect(domainDetails.locator('dd')).toHaveText([
'go.example.org',
'Uses fallback',
'404 Not found'
'404 Not found',
domainReportPath
]);
await expect(rootRow.locator('.admin-inventory-number')).toHaveText('1');
await expect(domainDetails.getByRole('link', { name: 'Root', exact: true })).toHaveCount(0);
await expect(domainDetails.getByRole('link', { name: 'Fallback', exact: true })).toHaveCount(0);
const domainAnalyticsLink = domainDetails.getByRole('link', {
name: domainReportPath,
exact: true
});
await expect(domainAnalyticsLink).toHaveAttribute('href', domainReportPath);
await expect(
linksInventory.getByText('https://example.org/first-domain', { exact: true })
).toBeVisible();
await expect(
linksInventory.getByRole('link', { name: 'https://example.org/first-domain', exact: true })
).toHaveCount(0);
await expect(rootLink).toHaveAttribute('href', '/admin/domains/go.example.org/links?period=all');
await expect(rootLink).toHaveAttribute('href', '/admin/domains/go.example.org/links');
const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true });
const settingsCard = page.getByRole('region', { name: 'Settings', exact: true });
const docsPath = '/admin/domains/go.example.org/links/docs';
await page.getByRole('link', { name: '/docs', exact: true }).click();
await expect(page).toHaveURL(`${appServer.origin}${docsPath}?period=all`);
await expect(page).toHaveURL(`${appServer.origin}${docsPath}`);
await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible();
const summaryVisitCount = page
.getByRole('region', { name: 'Summary', exact: true })
.getByRole('region', { name: 'Total Visits', exact: true })
.locator('.admin-stat-value');
const acceptedLanguages = page.getByRole('region', { name: 'Accepted languages', exact: true });
await expect(context).toHaveCount(0);
await expect(redirectCard.getByRole('heading', { name: 'Redirect', exact: true })).toBeVisible();
await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([
'Summary',
'Redirect',
'Settings'
]);
await expect(redirectCard.locator('dt')).toHaveText([
'Domain',
'Path',
'Title',
'Destination',
'Rules',
'Visits'
'Analytics'
]);
await expect(redirectCard.getByText(docsTitle, { exact: true })).toBeVisible();
await expect(settingsCard.locator('dt')).toHaveText([
@@ -284,7 +186,7 @@ test('shared credentials protect admin pages and sign-out removes access', async
).toHaveText(['work', 'docs', sharedTag]);
await expect(settingsCard.getByRole('link', { name: sharedTag, exact: true })).toHaveAttribute(
'href',
`${tagPath}?period=all`
tagPath
);
const destinations = redirectCard.getByRole('list', { name: 'Destinations', exact: true });
await expect(destinations.getByRole('link')).toHaveText([
@@ -300,82 +202,72 @@ test('shared credentials protect admin pages and sign-out removes access', async
await expect(domainField).toHaveText('go.example.org');
await expect(domainField.getByRole('link')).toHaveAttribute(
'href',
'/admin/domains/go.example.org?period=all'
'/admin/domains/go.example.org'
);
await expect(redirectCard.locator('dd').nth(1)).toHaveText('/docs');
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Visits', 'Status']);
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
'Total Visits',
'Status'
]);
await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active');
await expect(page).toHaveTitle('Link — go.example.org/docs — GoTo');
await expect(graph).toHaveAttribute('aria-busy', 'false');
await expect(chartTable).toHaveAccessibleName('Visits');
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./);
await expect(browsers.getByRole('row', { name: 'Firefox 1 100%', exact: true })).toBeVisible();
await expect(
acceptedLanguages.getByRole('row', { name: 'en 1 100%', exact: true })
).toBeVisible();
await expect(
acceptedLanguages.getByRole('row', { name: 'fr 1 100%', exact: true })
).toBeVisible();
const languageData = acceptedLanguages.getByRole('region', {
name: 'Accepted languages data',
exact: true
});
const sixthLanguage = acceptedLanguages.getByRole('row', { name: 'pt 1 100%', exact: true });
await languageData.scrollIntoViewIfNeeded();
await expect(
acceptedLanguages.getByRole('row', { name: 'de 1 100%', exact: true })
).toBeInViewport();
await expect(sixthLanguage).not.toBeInViewport();
await sixthLanguage.scrollIntoViewIfNeeded();
await expect(sixthLanguage).toBeInViewport();
await expect(
operatingSystems.getByRole('row', { name: 'Linux 1 100%', exact: true })
).toBeVisible();
await expect(visitsValue).toHaveText('1');
await timeframe.getByRole('button', { name: '7 days', exact: true }).click();
await expect(visitsValue).toHaveText('0');
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./);
await expect(browsers).toContainText('No visits in this period.');
await expect(operatingSystems).toContainText('No visits in this period.');
await expect(acceptedLanguages).toContainText('No visits in this period.');
await expect(chartTable.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
await timeframe.getByRole('button', { name: '3 months', exact: true }).click();
await expect(visitsValue).toHaveText('1');
await expect(overviewLink).toHaveAttribute('href', '/admin?period=all');
await expect(summaryVisitCount).toHaveText('1');
await expect(timeframe).toHaveCount(0);
await expect(trend).toHaveCount(0);
await expect(acceptedLanguages).toHaveCount(0);
await expect(overviewLink).toHaveAttribute('href', '/admin');
await expect(
page.getByRole('region', { name: 'Links on go.example.org', exact: true })
).toHaveCount(0);
await settingsCard.getByRole('link', { name: sharedTag, exact: true }).click();
await expect(page).toHaveURL(`${appServer.origin}${tagPath}?period=all`);
const tagHeading = page.getByRole('heading', { name: `Tag: ${sharedTag}`, exact: true });
await expect(tagHeading).toBeVisible();
await expect(tagHeading).toHaveAttribute('title', `Tag: ${sharedTag}`);
await expect(page).toHaveURL(`${appServer.origin}${tagPath}`);
await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible();
await expect(page).toHaveTitle(`Tag: ${sharedTag} — GoTo`);
await expect(page.getByRole('region', { name: 'Tag details', exact: true })).toHaveCount(0);
await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([
'Summary',
'Details',
'Links'
]);
const tagDetails = page.getByRole('region', { name: 'Details', exact: true });
const tagQuery = new URLSearchParams({ tag: sharedTag });
const tagReportPath = `/admin/analytics?${tagQuery}`;
await expect(tagDetails.locator('dt')).toHaveText(['Tag Name', 'Analytics']);
await expect(tagDetails.locator('dd')).toHaveText([sharedTag, tagReportPath]);
const tagAnalyticsLink = tagDetails.getByRole('link', { name: tagReportPath, exact: true });
await tagAnalyticsLink.click();
await expect(page).toHaveURL(`${appServer.origin}${tagReportPath}`);
const tagScopePicker = page.getByRole('combobox', { name: 'Report scope', exact: true });
await expect(tagScopePicker).toHaveAttribute('placeholder', `Tag: ${sharedTag}`);
await page.goBack();
const tagSummary = page.getByRole('region', { name: 'Summary', exact: true });
await expect(tagSummary.locator('.admin-stat-label')).toHaveText([
'Domains',
'Links',
'Total Visits'
]);
await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '2']);
await expect(timeframe).toHaveCount(0);
await expect(trend).toHaveCount(0);
const taggedLinks = page.getByRole('region', { name: `Links tagged ${sharedTag}`, exact: true });
await expect(taggedLinks.getByRole('link')).toHaveCount(2);
await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([
'Domain',
'Path',
'State',
'Visits'
'Total Visits'
]);
await expect(taggedLinks.locator('.admin-inventory-number')).toHaveText(['1', '1']);
const taggedDocs = taggedLinks.getByRole('link', { name: 'go.example.org/docs', exact: true });
await expect(taggedDocs.locator('.admin-inventory-primary')).toHaveText('go.example.org');
await expect(taggedDocs.locator('.admin-inventory-secondary')).toHaveText('/docs');
await expect(taggedDocs).toHaveAttribute('href', `${docsPath}?period=all`);
await expect(taggedDocs).toHaveAttribute('href', docsPath);
await expect(
taggedLinks.getByRole('link', { name: 'tiny.example.org/docs', exact: true })
).toBeVisible();
await expect(visitsValue).toHaveText('2');
await expect(acceptedLanguages).toBeVisible();
await timeframe.getByRole('button', { name: '7 days', exact: true }).click();
await expect(page).toHaveURL(`${appServer.origin}${tagPath}?period=7d`);
await expect(visitsValue).toHaveText('1');
await taggedDocs.click();
await expect(page).toHaveURL(`${appServer.origin}${docsPath}?period=7d`);
await timeframe.getByRole('button', { name: '3 months', exact: true }).click();
await expect(page).toHaveURL(`${appServer.origin}${docsPath}`);
await expect(summaryVisitCount).toHaveText('1');
await overviewLink.click();
await domainLink.click();
@@ -383,43 +275,67 @@ test('shared credentials protect admin pages and sign-out removes access', async
await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible();
await expect(page).toHaveTitle('Link — go.example.org/a%2Fb — GoTo');
await expect(redirectCard.getByText('Title', { exact: true })).toHaveCount(0);
await expect(page).toHaveURL(
`${appServer.origin}/admin/domains/go.example.org/links/a%252Fb?period=all`
await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a%252Fb`);
await expect(summaryVisitCount).toHaveText('1');
const literalPercentReportPath = `${domainReportPath}&path=%2Fa%252Fb`;
const literalPercentReport = redirectCard.getByRole('link', {
name: literalPercentReportPath,
exact: true
});
await expect(literalPercentReport).toHaveAttribute('href', literalPercentReportPath);
const linkSummary = page.getByRole('region', { name: 'Summary', exact: true });
await expect(linkSummary.getByRole('region', { name: 'Status', exact: true })).toContainText(
'Limit Exceeded'
);
await expect(visitsValue).toHaveText('1');
await expect(
linkSummary
.getByRole('region', { name: 'Max visits', exact: true })
.getByText('1', { exact: true })
).toBeVisible();
await page.goBack();
await page.getByRole('link', { name: '/a/b', exact: true }).click();
await expect(page).toHaveURL(
`${appServer.origin}/admin/domains/go.example.org/links/a/b?period=all`
);
await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links/a/b`);
await expect(page.getByRole('heading', { name: 'Link', exact: true })).toBeVisible();
await expect(page).toHaveTitle('Link — go.example.org/a/b — GoTo');
await expect(visitsValue).toHaveText('0');
await expect(summaryVisitCount).toHaveText('0');
const nestedReportPath = `${domainReportPath}&path=%2Fa%2Fb`;
const nestedReport = redirectCard.getByRole('link', { name: nestedReportPath, exact: true });
await expect(nestedReport).toHaveAttribute('href', nestedReportPath);
await page.goBack();
await rootLink.click();
await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links?period=all`);
await expect(page).toHaveURL(`${appServer.origin}/admin/domains/go.example.org/links`);
await expect(page.getByRole('heading', { name: 'Root', exact: true })).toBeVisible();
await expect(page).toHaveTitle('Root — go.example.org — GoTo');
await expect(acceptedLanguages).toBeVisible();
await expect(visitsValue).toHaveText('1');
await expect(page.getByRole('main').getByRole('heading', { level: 2 })).toHaveText([
'Summary',
'Root details',
'Fallback'
]);
await expect(timeframe).toHaveCount(0);
await expect(trend).toHaveCount(0);
await expect(summaryVisitCount).toHaveText('1');
await expect(page.getByRole('region', { name: 'Status', exact: true })).toHaveCount(0);
const rootDetails = page.getByRole('region', { name: 'Root details', exact: true });
await expect(rootDetails.locator('dt')).toHaveText([
'Domain',
'Address',
'Destination',
'Analytics'
]);
await expect(rootDetails.locator('dd')).toHaveText([
'go.example.org',
'go.example.org/',
'1',
'Uses fallback'
'Uses fallback',
domainReportPath
]);
await expect(page.getByRole('region', { name: 'Fallback', exact: true })).toContainText(
'404 Not found'
);
const rootAnalyticsLink = rootDetails.getByRole('link', { name: domainReportPath, exact: true });
await expect(rootAnalyticsLink).toHaveAttribute('href', domainReportPath);
await rootDetails.getByRole('link', { name: 'go.example.org', exact: true }).click();
await expect(timeframe.getByRole('button', { name: '3 months', exact: true })).toHaveAttribute(
'aria-pressed',
'true'
);
await expect(visitsValue).toHaveText('3');
await expect(totalVisits.getByText('3', { exact: true })).toBeVisible();
await page
.getByRole('navigation', { name: 'Administration', exact: true })
@@ -444,9 +360,203 @@ test('shared credentials protect admin pages and sign-out removes access', async
await expect(workerHealth.getByRole('alert')).toContainText('Worker is reachable.');
await expect(workerHealth.locator('time')).toBeVisible();
await page
.getByRole('navigation', { name: 'Administration', exact: true })
.getByRole('link', { name: 'Analytics', exact: true })
.click();
await expect(page.getByRole('heading', { name: 'Analytics', exact: true })).toBeVisible();
const analyticsVisits = page.getByRole('region', { name: 'Visits', exact: true });
const analyticsChart = page.getByRole('region', { name: 'Visits over time', exact: true });
await expect(analyticsVisits).toContainText('3');
await expect(analyticsChart.getByRole('row', { name: 'Total 3', exact: true })).toBeVisible();
const reportFilters = page.getByRole('group', { name: 'Report filters', exact: true });
const scopeInput = reportFilters.getByRole('combobox', { name: 'Report scope', exact: true });
const scopeOptions = page.getByRole('listbox', { name: 'Report scopes', exact: true });
async function chooseReportScope(option: string) {
await scopeInput.click();
await scopeOptions.getByRole('option', { name: option, exact: true }).click();
}
await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic');
const analyticsUrl = `${appServer.origin}/admin/analytics`;
const goReportUrl = `${analyticsUrl}?period=7d&domain=go.example.org`;
await timeframe.getByRole('button', { name: '7 days', exact: true }).click();
await expect(page).toHaveURL(`${analyticsUrl}?period=7d`);
await chooseReportScope('go.example.org');
await expect(page).toHaveURL(goReportUrl);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
const isHeldRedirectRequest = (url: URL) =>
url.pathname === '/admin/analytics/__data.json' &&
url.searchParams.get('domain') === 'go.example.org' &&
url.searchParams.get('path') === '/a/b';
const releaseRedirectReport = Promise.withResolvers<void>();
await page.route(
isHeldRedirectRequest,
async (route) => {
await releaseRedirectReport.promise;
await route.continue();
},
{ times: 1 }
);
try {
const [heldRequest] = await Promise.all([
page.waitForRequest((request) => isHeldRedirectRequest(new URL(request.url()))),
chooseReportScope('go.example.org/a/b')
]);
await expect(reportFilters).toHaveAttribute('aria-busy', 'true');
await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org');
await timeframe.getByRole('button', { name: '30 days', exact: true }).click();
await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`);
releaseRedirectReport.resolve();
const lateResponse = await heldRequest.response();
expect(lateResponse?.ok()).toBe(true);
await expect(reportFilters).toHaveAttribute('aria-busy', 'false');
await expect(page).toHaveURL(`${analyticsUrl}?domain=go.example.org`);
await expect(scopeInput).toHaveAttribute('placeholder', 'Domain: go.example.org');
await expect(analyticsVisits).toContainText('2');
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
} finally {
releaseRedirectReport.resolve();
}
await page.goBack();
await page.goBack();
await expect(page).toHaveURL(`${analyticsUrl}?period=7d`);
await expect(scopeInput).toHaveAttribute('placeholder', 'All traffic');
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
const searchRequests: string[] = [];
function recordSearchRequest(request: Request) {
const url = new URL(request.url());
if (url.origin === appServer.origin && url.pathname.startsWith('/admin/analytics')) {
searchRequests.push(url.href);
}
}
page.on('request', recordSearchRequest);
try {
await scopeInput.fill('/DOCS');
await expect(scopeOptions.getByRole('option')).toHaveText([
'go.example.org/docs',
'tiny.example.org/docs'
]);
await expect(page).toHaveURL(`${analyticsUrl}?period=7d`);
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
expect(searchRequests).toEqual([]);
} finally {
page.off('request', recordSearchRequest);
}
await scopeOptions.getByRole('option', { name: 'go.example.org/docs', exact: true }).click();
await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`);
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
await chooseReportScope('go.example.org/ (Root)');
await expect(page).toHaveURL(`${goReportUrl}&path=%2F`);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
await page.goBack();
await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/docs');
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
await chooseReportScope('tiny.example.org/docs');
const tinyReportUrl = `${analyticsUrl}?period=7d&domain=tiny.example.org`;
await expect(page).toHaveURL(`${tinyReportUrl}&path=%2Fdocs`);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
await scopeInput.click();
await expect(scopeOptions).toBeVisible();
const popupId = await scopeOptions.getAttribute('id');
expect(popupId).toBeTruthy();
await expect(scopeInput).toHaveAttribute('aria-controls', popupId ?? '');
await scopeInput.press('Home');
const allTraffic = scopeOptions.getByRole('option', { name: 'All traffic', exact: true });
await expect(scopeInput).toHaveAttribute(
'aria-activedescendant',
(await allTraffic.getAttribute('id')) ?? ''
);
await scopeInput.fill('work/100%');
await expect(scopeOptions.getByRole('option')).toHaveText([sharedTag]);
await scopeInput.press('ArrowDown');
await scopeInput.press('Enter');
const tagReportUrl = `${analyticsUrl}?period=7d&${new URLSearchParams({ tag: sharedTag })}`;
await expect(page).toHaveURL(tagReportUrl);
await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
await timeframe.getByRole('button', { name: '30 days', exact: true }).click();
await expect(page).toHaveURL(`${analyticsUrl}?${new URLSearchParams({ tag: sharedTag })}`);
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
await expect(acceptedLanguages.getByRole('row', { name: 'fr 1 50%', exact: true })).toBeVisible();
await page.goBack();
await expect(page).toHaveURL(tagReportUrl);
await page.reload();
await expect(scopeInput).toHaveAttribute('placeholder', `Tag: ${sharedTag}`);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
await scopeInput.click();
await expect(scopeOptions).toBeVisible();
await scopeInput.fill('long-picker-tag-');
const longTag = `long-picker-tag-${'w'.repeat(1400)}`;
await expect(scopeOptions.getByRole('option')).toHaveText([longTag]);
await scopeInput.press('ArrowDown');
await scopeInput.press('Enter');
await expect(page).toHaveURL(
`${analyticsUrl}?period=7d&${new URLSearchParams({ tag: longTag })}`
);
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
await page.goto(`${analyticsUrl}?period=7d&tag=Removed`);
await expect(page.getByRole('status')).toContainText(
'This report scope is no longer configured.'
);
await expect(analyticsChart).toHaveCount(0);
await chooseReportScope('All traffic');
await expect(page).toHaveURL(`${analyticsUrl}?period=7d`);
await expect(analyticsChart.getByRole('row', { name: 'Total 2', exact: true })).toBeVisible();
await chooseReportScope('go.example.org/docs');
await expect(page).toHaveURL(`${goReportUrl}&path=%2Fdocs`);
await page.setViewportSize({ width: 390, height: 844 });
const graph = analyticsChart.getByRole('img');
const browsers = page.getByRole('region', { name: 'Browsers', exact: true });
const operatingSystems = page.getByRole('region', { name: 'Operating systems', exact: true });
await expect(graph).toHaveAccessibleName(/^Visits by day\. Total: 0\./);
await expect(browsers).toContainText('No visits in this period.');
await expect(operatingSystems).toContainText('No visits in this period.');
await expect(acceptedLanguages).toContainText('No visits in this period.');
await page.getByRole('button', { name: 'Timeframe: 7 days', exact: true }).click();
await page
.getByRole('listbox', { name: 'Timeframe', exact: true })
.getByRole('option', { name: '90 days', exact: true })
.click();
const fullDomainUrl = `${analyticsUrl}?period=all&domain=go.example.org`;
await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fdocs`);
await expect(graph).toHaveAttribute('aria-busy', 'false');
await expect(graph).toHaveAccessibleName(/^Visits by week\. Total: 1\./);
await expect(browsers.getByRole('row', { name: 'Firefox 1 100%', exact: true })).toBeVisible();
await expect(
operatingSystems.getByRole('row', { name: 'Linux 1 100%', exact: true })
).toBeVisible();
await expect(
acceptedLanguages.getByRole('row', { name: 'fr 1 100%', exact: true })
).toBeVisible();
await page.setViewportSize({ width: 1280, height: 720 });
await chooseReportScope('go.example.org/a%2Fb');
const literalPathUrl = `${fullDomainUrl}&path=%2Fa%252Fb`;
await expect(page).toHaveURL(literalPathUrl);
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
await chooseReportScope('go.example.org/a/b');
await expect(page).toHaveURL(`${fullDomainUrl}&path=%2Fa%2Fb`);
await expect(analyticsChart.getByRole('row', { name: 'Total 0', exact: true })).toBeVisible();
await page.goBack();
await expect(page).toHaveURL(literalPathUrl);
await expect(scopeInput).toHaveAttribute('placeholder', 'go.example.org/a%2Fb');
await expect(analyticsChart.getByRole('row', { name: 'Total 1', exact: true })).toBeVisible();
const html = await page.content();
await expect(html).not.toContain('e2e-only-password');
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await page.setViewportSize({ width: 390, height: 844 });
await page
.getByRole('navigation', { name: 'Administration', exact: true })
.getByRole('button', { name: 'Sign out', exact: true })
.click();
await expect(page).toHaveURL(/\/signin\?/);
await page.goto(`${appServer.origin}${docsPath}`);
await expect(page).toHaveURL(/\/signin\?/);
@@ -465,7 +575,18 @@ test.describe('analytics disabled', () => {
await page.getByLabel('Password', { exact: true }).fill('e2e-only-password');
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Overview', exact: true })).toBeVisible();
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Domains', 'Links']);
const adminNav = page.getByRole('navigation', { name: 'Administration', exact: true });
await expect(adminNav.getByRole('link', { name: 'Analytics', exact: true })).toHaveCount(0);
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
'Domains',
'Links',
'Total Visits'
]);
await expect(
page
.getByRole('region', { name: 'Total Visits', exact: true })
.getByText('0', { exact: true })
).toBeVisible();
await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount(
@@ -481,10 +602,13 @@ test.describe('analytics disabled', () => {
page
.getByRole('region', { name: 'Domain inventory', exact: true })
.locator('.admin-inventory-heading > span')
).toHaveText(['Host', 'Links']);
await expect(page.getByRole('status')).toHaveText('Analytics disabled.');
).toHaveText(['Host', 'Links', 'Total Visits']);
await page.getByRole('link', { name: 'go.example.org', exact: true }).click();
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Links']);
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
'Links',
'Total Visits',
'Invalid clicks'
]);
await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount(
0
@@ -496,22 +620,36 @@ test.describe('analytics disabled', () => {
page
.getByRole('region', { name: 'Links on go.example.org', exact: true })
.locator('.admin-inventory-heading > span')
).toHaveText(['Path', 'Destination', 'State']);
await expect(
page.getByRole('region', { name: 'Details', exact: true }).locator('dt')
).toHaveText(['Domain', 'Root', 'Fallback']);
await expect(
page
.getByRole('region', { name: 'Links on go.example.org', exact: true })
.getByRole('link', { name: '(root)', exact: true })
).toBeVisible();
).toHaveText(['Path', 'Destination', 'State', 'Total Visits']);
const details = page.getByRole('region', { name: 'Details', exact: true });
const reportLinks = 'a[href^="/admin/analytics"]';
await expect(details.locator('dt')).toHaveText(['Domain', 'Root', 'Fallback']);
await expect(details.locator(reportLinks)).toHaveCount(0);
const rootLink = page
.getByRole('region', { name: 'Links on go.example.org', exact: true })
.getByRole('link', { name: '(root)', exact: true });
await rootLink.click();
const rootDetails = page.getByRole('region', { name: 'Root details', exact: true });
await expect(rootDetails).toBeVisible();
await expect(rootDetails.locator(reportLinks)).toHaveCount(0);
await page.goBack();
await page.getByRole('link', { name: '/docs', exact: true }).click();
await expect(page.getByRole('region', { name: 'Redirect', exact: true })).toBeVisible();
const redirectCard = page.getByRole('region', { name: 'Redirect', exact: true });
await expect(redirectCard).toBeVisible();
await expect(redirectCard.locator(reportLinks)).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Browsers', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Operating systems', exact: true })).toHaveCount(
0
);
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Status']);
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText([
'Total Visits',
'Status'
]);
await expect(
page
.getByRole('region', { name: 'Total Visits', exact: true })
.getByText('0', { exact: true })
).toBeVisible();
await expect(page.getByRole('region', { name: 'Status', exact: true })).toContainText('Active');
await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount(
@@ -520,10 +658,8 @@ test.describe('analytics disabled', () => {
await expect(page.getByRole('region', { name: 'Visits over time', exact: true })).toHaveCount(
0
);
await page
.getByRole('navigation', { name: 'Administration', exact: true })
.getByRole('link', { name: 'Health', exact: true })
.click();
await page.goto('/admin/analytics?period=7d');
await expect(page).toHaveURL(`${appServer.origin}/admin/health`);
await expect(
page.getByRole('region', { name: 'Analytics', exact: true }).locator('dd')
).toHaveText(['Disabled', 'Disabled', 'Disabled']);
@@ -538,10 +674,12 @@ test.describe('analytics disabled', () => {
.getByRole('link', { name: sharedTag, exact: true })
.click();
await expect(page).toHaveURL(`${appServer.origin}${tagPath}`);
await expect(
page.getByRole('heading', { name: `Tag: ${sharedTag}`, exact: true })
).toBeVisible();
await expect(page.locator('.admin-cards .admin-stat-label')).toHaveText(['Links']);
await expect(page.getByRole('heading', { level: 1, name: 'Tag', exact: true })).toBeVisible();
await expect(details.locator('dt')).toHaveText('Tag Name');
await expect(details.locator('dd')).toHaveText(sharedTag);
await expect(details.locator(reportLinks)).toHaveCount(0);
const tagSummary = page.getByRole('region', { name: 'Summary', exact: true });
await expect(tagSummary.locator('.admin-stat-value')).toHaveText(['2', '2', '0']);
await expect(page.getByRole('group', { name: 'Timeframe', exact: true })).toHaveCount(0);
await expect(page.getByRole('region', { name: 'Accepted languages', exact: true })).toHaveCount(
0
@@ -557,7 +695,8 @@ test.describe('analytics disabled', () => {
await expect(taggedLinks.locator('.admin-inventory-heading > span')).toHaveText([
'Domain',
'Path',
'State'
'State',
'Total Visits'
]);
});
});
+12 -3
View File
@@ -34,7 +34,7 @@ const configuration = {
'/schema.json': { url: 'https://example.org/public-schema' },
'/_app/version.json': { url: 'https://example.org/public-asset' },
'/a/b': { url: 'https://example.org/decoded' },
'/a%2Fb': { url: 'https://example.org/literal-percent' },
'/a%2Fb': { url: 'https://example.org/literal-percent', max_visits: 1 },
'/docs': {
title: 'New hire handbook',
url: 'https://example.org/first-domain',
@@ -49,7 +49,10 @@ const configuration = {
valid_until: '2100-01-01T00:00:00Z',
tags: ['work', 'docs', 'Work/100%é']
},
'/healthz': { url: 'https://example.org/public-health' }
'/healthz': {
url: 'https://example.org/public-health',
tags: [`long-picker-tag-${'w'.repeat(1400)}`]
}
}
},
'tiny.example.org': {
@@ -101,7 +104,13 @@ async function seedVisits() {
outcome: 'valid',
visited_at: Date.now() - 45 * 86_400_000
},
{ domain: 'tiny.example.org', path: '/docs', outcome: 'valid', accept_language: 'en' }
{ domain: 'tiny.example.org', path: '/docs', outcome: 'valid', accept_language: 'en' },
{
domain: 'retired.example.org',
path: '/docs',
outcome: 'valid',
visited_at: Date.now() - 120 * 86_400_000
}
];
for (const visit of visits) await insertVisit(db, { ...common, ...visit });
} finally {
@@ -1,15 +1,19 @@
<script lang="ts">
import { page } from '$app/state';
import { goto } from '$app/navigation';
import IconChartLineUp from 'virtual:icons/ph/chart-line-up';
import IconHeartbeat from 'virtual:icons/ph/heartbeat';
import IconSignOut from 'virtual:icons/ph/sign-out';
import { authClient } from '#lib/auth-client.js';
import ThemeToggle from '../ThemeToggle.svelte';
let { overviewHref }: { overviewHref: string } = $props();
let { overviewHref, analyticsEnabled }: { overviewHref: string; analyticsEnabled: boolean } =
$props();
let currentPath = $derived(page.url.pathname + page.url.search);
let onOverview = $derived(page.url.pathname === '/admin');
let pending = $state(false);
let signoutLabel = $derived(pending ? 'Signing out…' : 'Sign out');
let signoutError = $state<'rate' | 'network' | 'auth' | null>(null);
async function signOut(event: SubmitEvent) {
@@ -61,8 +65,19 @@
<a class="nav-title" href={overviewHref}>{@render titleWithIcon()}</a>
{/if}
<div class="nav-actions">
{#if analyticsEnabled}
<a
class="ui-button nav-icon"
href="/admin/analytics"
aria-label="Analytics"
title="Analytics"
aria-current={page.url.pathname === '/admin/analytics' ? 'page' : undefined}
>
<IconChartLineUp aria-hidden="true" focusable="false" />
</a>
{/if}
<a
class="ui-button health-link"
class="ui-button nav-icon"
href="/admin/health"
aria-label="Health"
title="Health"
@@ -74,11 +89,14 @@
<form method="POST" aria-label="Sign out" aria-busy={pending} onsubmit={signOut}>
<button
type="submit"
class="ui-button"
class="ui-button signout-button"
aria-label={signoutLabel}
title={signoutLabel}
aria-describedby={signoutError ? 'signout-error' : undefined}
disabled={pending}
>
{pending ? 'Signing out…' : 'Sign out'}
<span class="signout-text">{signoutLabel}</span>
<span class="signout-icon"><IconSignOut aria-hidden="true" focusable="false" /></span>
</button>
</form>
</div>
@@ -121,7 +139,7 @@
text-decoration: none;
}
.health-link {
.nav-icon {
width: var(--control-min-height);
padding: 0;
font-size: 1.25rem;
@@ -129,11 +147,39 @@
.nav-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-4);
}
.signout-icon {
display: none;
}
@media (max-width: 640px) {
.admin-nav {
padding-inline: var(--space-4);
}
.nav-container,
.nav-actions {
gap: var(--space-1);
}
.signout-button {
width: var(--control-min-height);
padding: 0;
font-size: 1.25rem;
}
.signout-text {
display: none;
}
.signout-icon {
display: flex;
}
}
.signout-error {
max-width: var(--content-admin-width);
margin: var(--space-4) auto 0;
@@ -6,6 +6,7 @@
let {
title: heading,
analyticsEnabled,
documentTitle,
context,
overviewHref = '/admin',
@@ -14,6 +15,7 @@
children
}: {
title: string;
analyticsEnabled: boolean;
documentTitle?: string;
context?: Snippet;
overviewHref?: string;
@@ -27,7 +29,7 @@
</script>
<svelte:head><title>{documentTitle ?? heading} — GoTo</title></svelte:head>
<AdminNav {overviewHref} />
<AdminNav {overviewHref} {analyticsEnabled} />
<main class="admin-page">
<header class="admin-heading">
<div class="admin-title-row">
@@ -0,0 +1,137 @@
<script lang="ts">
import { Select } from 'bits-ui';
import IconCaretDown from 'virtual:icons/ph/caret-down';
import IconCheck from 'virtual:icons/ph/check';
let {
label,
committedValue,
options,
onSelectionRequest,
mobileOnly = false
}: {
label: string;
committedValue: string;
options: { value: string; label: string; disabled?: boolean }[];
onSelectionRequest: (value: string) => void | Promise<void>;
mobileOnly?: boolean;
} = $props();
let selectedLabel = $derived(
options.find((option) => option.value === committedValue)?.label ?? committedValue
);
</script>
<Select.Root type="single" bind:value={() => committedValue, onSelectionRequest} items={options}>
<Select.Trigger aria-label={`${label}: ${selectedLabel}`} title={selectedLabel}>
{#snippet child({ props })}
<button {...props} type="button" class="ui-input ui-input--compact select-trigger">
<span class="trigger-label">{selectedLabel}</span>
<IconCaretDown class="select-icon" aria-hidden="true" focusable="false" />
</button>
{/snippet}
</Select.Trigger>
<Select.Portal>
<Select.Content aria-label={label} align="end" sideOffset={4}>
{#snippet child({ props, wrapperProps })}
<div {...wrapperProps}>
<div {...props} class="select-menu" class:mobile-only={mobileOnly}>
<Select.Viewport>
{#each options as option (option.value)}
<Select.Item
value={option.value}
label={option.label}
disabled={option.disabled ?? false}
>
{#snippet child({ props: itemProps, selected })}
<div {...itemProps} class="select-option">
<span class="option-label">{option.label}</span>
{#if selected}<IconCheck
class="select-icon"
aria-hidden="true"
focusable="false"
/>{/if}
</div>
{/snippet}
</Select.Item>
{/each}
</Select.Viewport>
</div>
</div>
{/snippet}
</Select.Content>
</Select.Portal>
</Select.Root>
<style>
.select-trigger {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
text-align: start;
}
.trigger-label {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.select-trigger :global(.select-icon),
.select-option :global(.select-icon) {
flex: none;
}
.select-menu {
display: flex;
flex-direction: column;
z-index: 100;
width: var(--bits-select-anchor-width);
max-height: var(--bits-select-content-available-height);
padding: var(--space-1);
font-size: var(--font-size-sm);
background: var(--color-surface-card);
border: var(--border-width) solid var(--color-border-subtle);
border-radius: var(--radius-control);
box-shadow: var(--shadow-card);
}
.select-option {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
min-height: var(--menu-option-min-height);
padding: var(--space-1) var(--space-4);
color: var(--color-text);
border-radius: var(--radius-sm);
cursor: pointer;
}
.option-label {
min-width: 0;
overflow-wrap: anywhere;
}
.select-option[data-highlighted]:not([data-selected]) {
background: var(--color-menu-option-highlight);
}
.select-option[data-selected] {
color: var(--color-on-primary);
background: var(--color-primary-fill);
}
.select-option[data-disabled] {
opacity: 0.5;
cursor: default;
}
@media (width > 640px) {
.select-menu.mobile-only {
visibility: hidden;
}
}
</style>
@@ -0,0 +1,24 @@
<script lang="ts">
import { analyticsHref, type AnalyticsScope } from '#lib/report-scopes.js';
let { scope }: { scope: AnalyticsScope } = $props();
let href = $derived(analyticsHref(scope));
</script>
<dt>Analytics</dt>
<dd><a class="analytics-link" {href}>{href}</a></dd>
<style>
.analytics-link {
color: var(--color-link);
text-decoration: underline;
}
.analytics-link:hover {
color: var(--color-link-hover);
}
.analytics-link:focus-visible {
outline-color: currentColor;
}
</style>
@@ -1,20 +0,0 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let { children }: { children: Snippet } = $props();
</script>
<section aria-labelledby="analytics-heading">
<h2 id="analytics-heading">Analytics</h2>
<div class="analytics-content">
{@render children()}
</div>
</section>
<style>
.analytics-content {
display: flex;
flex-direction: column;
gap: var(--space-8);
}
</style>
@@ -1,13 +1,11 @@
<script lang="ts">
import type { VisitCountsByTimeframe, VisitTimeframe } from '@goto/analytics/daily';
import type { LinkState } from '#lib/server/link-state.js';
import { formatCount } from './format.js';
let {
label,
links,
timeframe,
collectionEnabled,
visitLabel,
showDomain = false
}: {
label: string;
@@ -17,17 +15,16 @@
href: string;
url?: string | null;
state: LinkState;
countsByTimeframe: VisitCountsByTimeframe;
visits: number | null;
}>;
timeframe: VisitTimeframe;
collectionEnabled: boolean;
visitLabel: string | null;
showDomain?: boolean;
} = $props();
</script>
<div
class="admin-inventory admin-link-inventory"
class:with-visits={collectionEnabled}
class:with-visits={visitLabel !== null}
class:with-domains={showDomain}
role="region"
aria-label={label}
@@ -39,18 +36,14 @@
<span>Path</span><span>Destination</span>
{/if}
<span>State</span>
{#if collectionEnabled}<span class="admin-inventory-count">Visits</span>{/if}
{#if visitLabel}<span class="admin-inventory-count">{visitLabel}</span>{/if}
</div>
<ul class="admin-inventory-list">
{#each links as link (link.href)}
{@const pathLabel = link.path === '/' ? '(root)' : link.path}
{@const linkLabel = showDomain ? `${link.domain}${link.path}` : pathLabel}
<li>
<a
class="admin-inventory-row admin-inventory-link"
href={`${link.href}?period=${timeframe}`}
aria-label={linkLabel}
>
<a class="admin-inventory-row admin-inventory-link" href={link.href} aria-label={linkLabel}>
{#if showDomain}
<span class="admin-inventory-primary">{link.domain}</span>
<span class="admin-inventory-secondary"><code>{pathLabel}</code></span>
@@ -65,12 +58,10 @@
{:else if link.state === 'expired'}Expired
{:else if link.state === 'exhausted'}Limit Exceeded{/if}
</span>
{#if collectionEnabled}
{#if visitLabel}
<span class="admin-inventory-count">
<span class="admin-inventory-label">Visits</span>
<span class="admin-inventory-number"
>{formatCount(link.countsByTimeframe[timeframe]?.validVisits ?? null)}</span
>
<span class="admin-inventory-label">{visitLabel}</span>
<span class="admin-inventory-number">{formatCount(link.visits)}</span>
</span>
{/if}
</a>
@@ -1,14 +1,13 @@
<script lang="ts">
import type { VisitTimeframe } from '@goto/analytics/daily';
import { tagHref } from './urls.js';
let { tags, timeframe }: { tags: readonly string[]; timeframe?: VisitTimeframe } = $props();
let { tags }: { tags: readonly string[] } = $props();
let uniqueTags = $derived([...new Set(tags)]);
</script>
<ul class="tags" aria-label="Tags">
{#each uniqueTags as tag (tag)}
<li><a href={tagHref(tag, timeframe)}>{tag}</a></li>
<li><a href={tagHref(tag)}>{tag}</a></li>
{/each}
</ul>
@@ -1,10 +1,8 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { Select } from 'bits-ui';
import IconCaretDown from 'virtual:icons/ph/caret-down';
import IconCheck from 'virtual:icons/ph/check';
import { resolveVisitTimeframe, type VisitTimeframe } from '@goto/analytics/daily';
import AdminSelect from './AdminSelect.svelte';
let {
timeframes,
@@ -20,7 +18,7 @@
'7d': '7 days',
'30d': '30 days',
'90d': '90 days',
all: `${retentionMonths} months`
all: retentionMonths === 3 ? '90 days' : 'Full retention'
});
let options = $derived(
timeframes.map((timeframe) => ({ value: timeframe, label: labels[timeframe] }))
@@ -53,36 +51,13 @@
{/each}
</div>
<div class="mobile-select">
<Select.Root type="single" {value} items={options} onValueChange={changeTimeframe}>
<Select.Trigger aria-label={`Timeframe: ${labels[value]}`}>
{#snippet child({ props })}
<button {...props} type="button" class="ui-input timeframe-trigger">
<span>{labels[value]}</span>
<IconCaretDown aria-hidden="true" focusable="false" />
</button>
{/snippet}
</Select.Trigger>
<Select.Portal>
<Select.Content aria-label="Timeframe" align="end" sideOffset={4}>
{#snippet child({ props, wrapperProps })}
<div {...wrapperProps}>
<div {...props} class="timeframe-menu">
{#each options as option (option.value)}
<Select.Item value={option.value} label={option.label}>
{#snippet child({ props: itemProps, selected })}
<div {...itemProps} class="timeframe-option">
<span>{option.label}</span>
{#if selected}<IconCheck aria-hidden="true" focusable="false" />{/if}
</div>
{/snippet}
</Select.Item>
{/each}
</div>
</div>
{/snippet}
</Select.Content>
</Select.Portal>
</Select.Root>
<AdminSelect
label="Timeframe"
committedValue={value}
{options}
onSelectionRequest={changeTimeframe}
mobileOnly
/>
</div>
</div>
@@ -100,51 +75,9 @@
.mobile-select {
display: none;
}
.timeframe-trigger {
display: inline-flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
width: 8rem;
min-width: 8rem;
min-height: 2.5rem;
padding: var(--space-1) var(--space-4);
font-size: var(--font-size-sm);
}
.timeframe-menu {
visibility: hidden;
z-index: 100;
width: var(--bits-select-anchor-width);
max-height: var(--bits-select-content-available-height);
overflow-y: auto;
padding: var(--space-1);
font-size: var(--font-size-sm);
background: var(--color-surface-card);
border: var(--border-width) solid var(--color-border-subtle);
border-radius: var(--radius-control);
box-shadow: var(--shadow-card);
}
.timeframe-option {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
min-height: 2.25rem;
padding: var(--space-1) var(--space-4);
color: var(--color-text);
border-radius: var(--radius-sm);
cursor: pointer;
}
.timeframe-option[data-highlighted]:not([data-selected]) {
background: var(--color-surface-muted);
}
.timeframe-option[data-selected],
button[aria-pressed='true'],
button[aria-pressed='true']:hover {
color: var(--color-on-primary);
@@ -160,9 +93,5 @@
.mobile-select {
display: block;
}
.timeframe-menu {
visibility: visible;
}
}
</style>
@@ -1,7 +1,7 @@
import { expect, test } from 'vitest';
import { tagHref } from './urls.js';
test('encodes the whole literal tag as one segment and optionally carries the timeframe', () => {
test('encodes the whole literal tag as one segment', () => {
expect(tagHref(' Work/100%é ')).toBe('/admin/tags/%20Work%2F100%25%C3%A9%20');
expect(tagHref('%2F', '7d')).toBe('/admin/tags/%252F?period=7d');
expect(tagHref('%2F')).toBe('/admin/tags/%252F');
});
+2 -6
View File
@@ -1,5 +1,3 @@
import type { VisitTimeframe } from '@goto/analytics/daily';
export function linkHref(domain: string, path: string): string {
const base = `/admin/domains/${encodeURIComponent(domain)}/links`;
if (path === '/') return base;
@@ -7,8 +5,6 @@ export function linkHref(domain: string, path: string): string {
return `${base}/${segments.join('/')}`;
}
export function tagHref(tag: string, timeframe?: VisitTimeframe): string {
const href = `/admin/tags/${encodeURIComponent(tag)}`;
if (timeframe === undefined) return href;
return `${href}?period=${timeframe}`;
export function tagHref(tag: string): string {
return `/admin/tags/${encodeURIComponent(tag)}`;
}
+44
View File
@@ -0,0 +1,44 @@
import type { ReportScope } from '@goto/analytics';
export type AnalyticsScope = ReportScope | { kind: 'tag'; tag: string };
export type ScopeGroup = {
label: string;
scopes: AnalyticsScope[];
};
export function scopeLabel(scope: AnalyticsScope): string {
switch (scope.kind) {
case 'overview':
return 'All traffic';
case 'domain':
return scope.domain;
case 'link':
return `${scope.domain}${scope.path}${scope.path === '/' ? ' (Root)' : ''}`;
case 'tag':
return scope.tag;
}
}
export function analyticsHref(scope: AnalyticsScope): string {
const pathname = '/admin/analytics';
const query = new URLSearchParams();
setScope(query, scope);
if (query.size === 0) return pathname;
return `${pathname}?${query}`;
}
export function scopeValue(scope: AnalyticsScope): string {
const query = new URLSearchParams();
setScope(query, scope);
return query.toString() || 'all';
}
export function setScope(query: URLSearchParams, scope: AnalyticsScope): void {
query.delete('domain');
query.delete('path');
query.delete('tag');
if (scope.kind === 'domain' || scope.kind === 'link') query.set('domain', scope.domain);
if (scope.kind === 'link') query.set('path', scope.path);
if (scope.kind === 'tag') query.set('tag', scope.tag);
}
+22 -54
View File
@@ -12,13 +12,7 @@ import type { GotoConfiguration } from '@goto/config';
import { openDb, runMigrations } from '@goto/db';
import { addDailyVisitStatistics } from '@goto/db/visit-reports';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import {
readOverviewDetails,
readDomainDetails,
readLinkDetails,
readVisitDetails,
readLastActivity
} from './reports.js';
import { readLinkDetails, readVisitDetails, readLastActivity } from './reports.js';
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] });
@@ -66,6 +60,8 @@ test('reads daily output and derives zero scopes in a window from current time a
const domainDetails: VisitDetails = { ...details, scope: domainScope };
const linkScope = { kind: 'link', domain, path: '/docs' } as const;
const linkDetails: VisitDetails = { ...details, scope: linkScope };
const otherLink = { kind: 'link', domain: 'other.example.test', path: '/docs' } as const;
const otherLinkActivityAt = '2026-06-15T11:00:00.000Z';
const emptyDetails: VisitDetails = {
...details,
lastActivityAt: null,
@@ -92,7 +88,8 @@ test('reads daily output and derives zero scopes in a window from current time a
addDailyVisitStatistics(transaction, [
daily,
{ ...daily, scope: domainScope },
{ ...daily, scope: linkScope }
{ ...daily, scope: linkScope },
{ ...daily, scope: otherLink, lastVisitAt: Date.parse(otherLinkActivityAt) }
])
);
} finally {
@@ -100,25 +97,9 @@ test('reads daily output and derives zero scopes in a window from current time a
}
const close = vi.spyOn(DatabaseSync.prototype, 'close');
try {
expect(await readOverviewDetails(configuration, [domain, 'new.example.test'])).toEqual({
overview: details,
domains: [
{ domain, details: domainDetails },
{
domain: 'new.example.test',
details: { ...emptyDetails, scope: { kind: 'domain', domain: 'new.example.test' } }
}
]
});
expect(await readVisitDetails(configuration, details.scope)).toEqual(details);
expect(close).toHaveBeenCalledTimes(1);
expect(await readDomainDetails(configuration, domain, ['/docs', '/new'])).toEqual({
domain: domainDetails,
links: [
{ path: '/', details: { ...emptyDetails, scope: { ...linkScope, path: '/' } } },
{ path: '/docs', details: linkDetails },
{ path: '/new', details: { ...emptyDetails, scope: { ...linkScope, path: '/new' } } }
]
});
expect(await readVisitDetails(configuration, domainScope)).toEqual(domainDetails);
expect(close).toHaveBeenCalledTimes(2);
expect(await readVisitDetails(configuration, linkScope)).toEqual(linkDetails);
expect(close).toHaveBeenCalledTimes(3);
@@ -138,14 +119,15 @@ test('reads daily output and derives zero scopes in a window from current time a
expect(close).toHaveBeenCalledTimes(4);
expect(await readLastActivity(configuration)).toEqual({ available: true, lastActivityAt });
expect(close).toHaveBeenCalledTimes(5);
expect(await readLastActivity(configuration, [linkScope, otherLink])).toEqual({
available: true,
lastActivityAt: otherLinkActivityAt
});
expect(close).toHaveBeenCalledTimes(6);
configuration.analytics.retention_months = 9;
const longerPeriod = createVisitPeriod(9, Date.now());
expect((await readOverviewDetails(configuration, [domain]))?.overview.period).toEqual(
longerPeriod
);
expect((await readDomainDetails(configuration, domain, ['/docs']))?.domain.period).toEqual(
longerPeriod
);
expect((await readVisitDetails(configuration, details.scope))?.period).toEqual(longerPeriod);
expect((await readVisitDetails(configuration, domainScope))?.period).toEqual(longerPeriod);
expect((await readVisitDetails(configuration, linkScope))?.period).toEqual(longerPeriod);
expect((await readLinkDetails(configuration, [linkScope]))?.period).toEqual(longerPeriod);
vi.setSystemTime(new Date('2027-06-15T12:00:00.000Z'));
@@ -205,9 +187,11 @@ test('corrupt daily histograms are unavailable, sanitized and closed; activity u
}
const close = vi.spyOn(DatabaseSync.prototype, 'close');
try {
expect(await readOverviewDetails(configuration, ['go.example.test'])).toBeNull();
expect(await readVisitDetails(configuration, { kind: 'overview' })).toBeNull();
expect(close).toHaveBeenCalledTimes(1);
expect(await readDomainDetails(configuration, 'go.example.test', ['/docs'])).toBeNull();
expect(
await readVisitDetails(configuration, { kind: 'domain', domain: 'go.example.test' })
).toBeNull();
expect(close).toHaveBeenCalledTimes(2);
expect(
await readVisitDetails(configuration, {
@@ -251,7 +235,7 @@ test('a missing daily table remains unavailable without readonly schema repair',
try {
const db = await openDb(configuration.database.path);
await db.destroy();
expect(await readOverviewDetails(configuration, ['go.example.test'])).toBeNull();
expect(await readVisitDetails(configuration, { kind: 'overview' })).toBeNull();
expect(await readLastActivity(configuration)).toEqual({
available: false,
lastActivityAt: null
@@ -286,15 +270,7 @@ test('enabled collection fails safely without creating missing storage', async (
},
analytics: { retention_months: 3 as const }
};
expect(
await readVisitDetails(configuration, {
kind: 'link',
domain: 'go.example.test',
path: '/docs'
})
).toBeNull();
expect(await readOverviewDetails(configuration, ['go.example.test'])).toBeNull();
expect(await readDomainDetails(configuration, 'go.example.test', ['/docs'])).toBeNull();
expect(await readVisitDetails(configuration, { kind: 'overview' })).toBeNull();
expect(
await readLinkDetails(configuration, [{ domain: 'go.example.test', path: '/docs' }])
).toBeNull();
@@ -303,7 +279,7 @@ test('enabled collection fails safely without creating missing storage', async (
lastActivityAt: null
});
expect(warning.mock.calls).toEqual(
Array.from({ length: 5 }, () => ['Prepared visit reports unavailable'])
Array.from({ length: 3 }, () => ['Prepared visit reports unavailable'])
);
await expect(access(missing)).rejects.toMatchObject({ code: 'ENOENT' });
} finally {
@@ -319,15 +295,7 @@ test('disabled collection does not attempt to open missing storage', async () =>
database: { path: '/missing/not-used.sqlite', worker_path: '/missing/worker.sqlite' },
analytics: { retention_months: 0 as const }
};
expect(
await readVisitDetails(configuration, {
kind: 'link',
domain: 'go.example.test',
path: '/docs'
})
).toBeNull();
expect(await readOverviewDetails(configuration, ['go.example.test'])).toBeNull();
expect(await readDomainDetails(configuration, 'go.example.test', ['/docs'])).toBeNull();
expect(await readVisitDetails(configuration, { kind: 'overview' })).toBeNull();
expect(
await readLinkDetails(configuration, [{ domain: 'go.example.test', path: '/docs' }])
).toBeNull();
+3 -45
View File
@@ -2,58 +2,15 @@ import { createVisitPeriod, type ReportScope, type VisitDetails } from '@goto/an
import type { GotoConfiguration } from '@goto/config';
import { openDb } from '@goto/db';
import {
readOverviewVisitDetails,
readDomainVisitDetails,
readLinkVisitDetails,
readVisitDetails as readStoredDetails,
readLastVisitActivity,
type OverviewVisitDetails,
type DomainVisitDetails,
type LinkVisitDetails
} from '@goto/db/visit-reports';
import type { Immutable } from '../snapshot.js';
type ReportConfiguration = Immutable<Pick<GotoConfiguration, 'database' | 'analytics'>>;
export async function readOverviewDetails(
configuration: ReportConfiguration,
currentDomains: string[]
): Promise<OverviewVisitDetails | null> {
const months = configuration.analytics.retention_months;
if (months === 0) return null;
let db: Awaited<ReturnType<typeof openDb>> | undefined;
try {
db = await openDb(configuration.database.path, { readOnly: true });
const period = createVisitPeriod(months, Date.now());
return await readOverviewVisitDetails(db, currentDomains, period);
} catch {
warnUnavailable();
return null;
} finally {
await db?.destroy().catch(warnUnavailable);
}
}
export async function readDomainDetails(
configuration: ReportConfiguration,
domain: string,
currentPaths: string[]
): Promise<DomainVisitDetails | null> {
const months = configuration.analytics.retention_months;
if (months === 0) return null;
let db: Awaited<ReturnType<typeof openDb>> | undefined;
try {
db = await openDb(configuration.database.path, { readOnly: true });
const period = createVisitPeriod(months, Date.now());
return await readDomainVisitDetails(db, domain, currentPaths, period);
} catch {
warnUnavailable();
return null;
} finally {
await db?.destroy().catch(warnUnavailable);
}
}
export async function readLinkDetails(
configuration: ReportConfiguration,
currentLinks: readonly { domain: string; path: string }[]
@@ -93,7 +50,8 @@ export async function readVisitDetails(
}
export async function readLastActivity(
configuration: ReportConfiguration
configuration: ReportConfiguration,
scopeOrScopes: ReportScope | ReportScope[] = { kind: 'overview' }
): Promise<{ available: boolean; lastActivityAt: string | null }> {
const months = configuration.analytics.retention_months;
if (months === 0) return { available: true, lastActivityAt: null };
@@ -101,7 +59,7 @@ export async function readLastActivity(
try {
db = await openDb(configuration.database.path, { readOnly: true });
const period = createVisitPeriod(months, Date.now());
const lastActivityAt = await readLastVisitActivity(db, period);
const lastActivityAt = await readLastVisitActivity(db, period, scopeOrScopes);
return { available: true, lastActivityAt };
} catch {
warnUnavailable();
+28 -4
View File
@@ -1,16 +1,40 @@
import type { ReportScope, VisitTotals } from '@goto/analytics';
import type { GotoConfiguration } from '@goto/config';
import { openDb, readVisitTotals } from '@goto/db';
import { openDb, readDomainVisitTotals, readOverviewVisitTotals, readVisitTotals } from '@goto/db';
import type { Immutable } from '../snapshot.js';
export async function readLifetimeVisitTotals(
configuration: Immutable<Pick<GotoConfiguration, 'database'>>,
type VisitTotalsConfiguration = Immutable<Pick<GotoConfiguration, 'database'>>;
export function readLifetimeVisitTotals(
configuration: VisitTotalsConfiguration,
scope: ReportScope
): Promise<VisitTotals | null> {
return readPreparedTotals(configuration, (db) => readVisitTotals(db, scope));
}
export function readOverviewLifetimeVisitTotals(
configuration: VisitTotalsConfiguration,
domains: readonly string[]
) {
return readPreparedTotals(configuration, (db) => readOverviewVisitTotals(db, domains));
}
export function readDomainLifetimeVisitTotals(
configuration: VisitTotalsConfiguration,
domain: string,
paths: readonly string[]
) {
return readPreparedTotals(configuration, (db) => readDomainVisitTotals(db, domain, paths));
}
async function readPreparedTotals<T>(
configuration: VisitTotalsConfiguration,
read: (db: Awaited<ReturnType<typeof openDb>>) => Promise<T>
): Promise<T | null> {
let db: Awaited<ReturnType<typeof openDb>> | undefined;
try {
db = await openDb(configuration.database.path, { readOnly: true });
return await readVisitTotals(db, scope);
return await read(db);
} catch {
warnUnavailable();
return null;
+6
View File
@@ -32,6 +32,12 @@
border-radius: var(--radius-control);
}
.ui-input--compact {
min-height: 2.5rem;
padding: var(--space-1) var(--space-4);
font-size: var(--font-size-sm);
}
.ui-button:not(:disabled):hover {
background: var(--color-surface-muted);
box-shadow: inset 0 0 0 var(--border-width) var(--color-border-strong);
+7
View File
@@ -7,7 +7,13 @@
--color-border-subtle: light-dark(#dedede, #343b3d);
--color-text: light-dark(#171717, #f5f5f5);
--color-text-muted: light-dark(#525252, #b5babb);
--color-link: light-dark(#0f766e, #5eead4);
--color-link-hover: light-dark(#115e59, #99f6e4);
--color-border-strong: light-dark(#525252, #b5babb);
--color-menu-option-highlight: light-dark(
var(--color-surface-muted),
color-mix(in srgb, var(--color-text) 30%, var(--color-surface-card))
);
--space-1: 2px;
--space-4: 0.75rem;
@@ -26,6 +32,7 @@
--content-form-width: 25rem;
--content-admin-width: 72rem;
--control-min-height: 3rem;
--menu-option-min-height: 2.25rem;
--size-icon: 2rem;
--radius-sm: 0.25rem;
--radius-control: 0.5rem;
@@ -1,62 +1,28 @@
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { readOverviewDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readOverviewLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import type { PageServerLoad } from './$types';
export const load = (async ({ locals }) => {
const snapshot = locals.snapshot;
const configuration = snapshot.configuration;
const retentionMonths = configuration.analytics.retention_months;
const collectionEnabled = retentionMonths !== 0;
const currentDomains = Object.keys(snapshot.domains);
let report: Awaited<ReturnType<typeof readOverviewDetails>> = null;
if (collectionEnabled) {
report = await readOverviewDetails(configuration, currentDomains);
}
const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths);
const overview = report?.overview ?? null;
const windows = overview
? timeframes.map((timeframe) => ({
timeframe,
window: visitWindow(overview.period, timeframe)
}))
: [];
const detailsByDomain = new Map(report?.domains.map(({ domain, details }) => [domain, details]));
const domains = Object.entries(snapshot.domains).map(([domain, prepared]) => {
const daily = detailsByDomain.get(domain)?.daily;
const countsByTimeframe = countVisitWindows(daily, windows);
return {
domain,
linkCount: Object.keys(prepared.links).length,
countsByTimeframe,
href: `/admin/domains/${encodeURIComponent(domain)}`
};
});
const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(overview?.browsers, windows);
const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe(
overview?.operatingSystems,
windows
const { configuration, domains: configuredDomains } = locals.snapshot;
const analyticsEnabled = configuration.analytics.retention_months !== 0;
const totals = await readOverviewLifetimeVisitTotals(
configuration,
Object.keys(configuredDomains)
);
const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe(
overview?.acceptedLanguages,
windows
);
const lastActivityAt = overview?.lastActivityAt ? Date.parse(overview.lastActivityAt) : null;
const countsByTimeframe = countVisitWindows(overview?.daily, windows);
const chart = overview ? { daily: overview.daily, period: overview.period } : null;
const activity = analyticsEnabled ? await readLastActivity(configuration) : null;
const domains = Object.entries(configuredDomains).map(([domain, prepared]) => ({
domain,
linkCount: Object.keys(prepared.links).length,
totalVisits: totals?.byDomain.get(domain)?.validVisits ?? null,
href: `/admin/domains/${encodeURIComponent(domain)}`
}));
return {
collectionEnabled,
available: overview !== null,
retentionMonths,
lastActivityAt,
analyticsEnabled,
lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null,
domainCount: domains.length,
linkCount: domains.reduce((sum, row) => sum + row.linkCount, 0),
timeframes,
countsByTimeframe,
browserVisitsByTimeframe,
operatingSystemVisitsByTimeframe,
acceptedLanguageVisitsByTimeframe,
chart,
totalVisits: totals?.overview.validVisits ?? null,
domains
};
}) satisfies PageServerLoad;
@@ -1,61 +1,48 @@
<script lang="ts">
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import AnalyticsSection from '#lib/components/admin/AnalyticsSection.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import { formatCount } from '#lib/components/admin/format.js';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let window = $derived(data.chart ? visitWindow(data.chart.period, timeframe) : null);
let granularity = $derived(
data.chart ? visitGranularity(timeframe, data.chart.period.retentionMonths) : 'day'
);
let visits = $derived(data.countsByTimeframe[timeframe]?.validVisits ?? null);
let browserVisits = $derived(data.browserVisitsByTimeframe[timeframe] ?? null);
let operatingSystemVisits = $derived(data.operatingSystemVisitsByTimeframe[timeframe] ?? null);
let acceptedLanguageVisits = $derived(data.acceptedLanguageVisitsByTimeframe[timeframe] ?? null);
</script>
<AdminPage title="Overview" lastActivityAt={data.lastActivityAt}>
{#snippet actions()}
{#if data.available && data.timeframes.length > 0}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<AdminPage
title="Overview"
analyticsEnabled={data.analyticsEnabled}
lastActivityAt={data.lastActivityAt}
>
<section aria-labelledby="summary-heading">
<h2 id="summary-heading">Summary</h2>
<div class="summary-content">
{#if data.totalVisits === null}
<p class="admin-notice" role="status">Visit totals unavailable.</p>
{/if}
<div class="admin-cards">
<StatCard label="Domains" value={data.domainCount} />
<StatCard label="Links" value={data.linkCount} />
<StatCard label="Total Visits" value={data.totalVisits} />
</div>
</div>
</section>
<section>
<h2>Domains</h2>
{#if data.domains.length === 0}<p>No domains configured.</p>
{:else}
<div
class="admin-inventory admin-domain-inventory"
class:with-visits={data.collectionEnabled}
class="admin-inventory admin-domain-inventory with-visits"
role="region"
aria-label="Domain inventory"
>
<div class="admin-inventory-heading" aria-hidden="true">
<span>Host</span><span class="admin-inventory-count">Links</span
>{#if data.collectionEnabled}<span class="admin-inventory-count">Visits</span>{/if}
<span>Host</span><span class="admin-inventory-count">Links</span>
<span class="admin-inventory-count">Total Visits</span>
</div>
<ul class="admin-inventory-list">
{#each data.domains as row (row.domain)}
<li>
<a
class="admin-inventory-row admin-inventory-link"
href={`${row.href}?period=${timeframe}`}
href={row.href}
aria-label={row.domain}
>
<span class="admin-inventory-primary">{row.domain}</span>
@@ -63,14 +50,10 @@
<span class="admin-inventory-label">Links</span>
<span class="admin-inventory-number">{formatCount(row.linkCount)}</span>
</span>
{#if data.collectionEnabled}
<span class="admin-inventory-count">
<span class="admin-inventory-label">Visits</span>
<span class="admin-inventory-number"
>{formatCount(row.countsByTimeframe[timeframe]?.validVisits ?? null)}</span
>
</span>
{/if}
<span class="admin-inventory-count">
<span class="admin-inventory-label">Total Visits</span>
<span class="admin-inventory-number">{formatCount(row.totalVisits)}</span>
</span>
</a>
</li>
{/each}
@@ -78,26 +61,12 @@
</div>
{/if}
</section>
<AnalyticsSection>
<ReportNotice collectionEnabled={data.collectionEnabled} available={data.available} />
<div class="admin-cards">
<StatCard label="Domains" value={data.domainCount} />
<StatCard label="Links" value={data.linkCount} />
{#if data.collectionEnabled}
<StatCard label="Visits" value={visits} />
<StatCard label="Retention" value={`${data.retentionMonths} months`} />
{/if}
</div>
{#if data.chart && window}
<VisitsChart daily={data.chart.daily} {window} {granularity} />
{/if}
{#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null}
<VisitBreakdowns
{browserVisits}
{operatingSystemVisits}
{acceptedLanguageVisits}
totalVisits={visits}
/>
{/if}
</AnalyticsSection>
</AdminPage>
<style>
.summary-content {
display: flex;
flex-direction: column;
gap: var(--space-5);
}
</style>
@@ -0,0 +1,109 @@
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { isCanonicalPath, normalizeHost } from '@goto/config';
import { error, redirect } from '@sveltejs/kit';
import { scopeValue, type AnalyticsScope, type ScopeGroup } from '#lib/report-scopes.js';
import type { ConfigurationSnapshot } from '#lib/server/snapshot.js';
import { currentTags, tagMembers } from '#lib/server/tags/inventory.js';
import { combineTagVisits } from '#lib/server/tags/visits.js';
import { readLinkDetails, readVisitDetails } from '#lib/server/visits/reports.js';
import type { PageServerLoad } from './$types';
export const load = (async ({ locals, url }) => {
const snapshot = locals.snapshot;
const retentionMonths = snapshot.configuration.analytics.retention_months;
if (retentionMonths === 0) redirect(307, '/admin/health');
const scope = selectedScope(url.searchParams);
const groups = scopeGroups(snapshot.domains);
const scopeUnavailable = !isConfiguredScope(scope, groups);
const timeframes = availableVisitTimeframes(retentionMonths);
const selection = { scope, groups, scopeUnavailable, retentionMonths, timeframes };
if (scopeUnavailable) return { ...selection, report: null };
const details = await readScopeDetails(snapshot, scope);
if (!details) return { ...selection, report: null };
const windows = timeframes.map((timeframe) => ({
timeframe,
window: visitWindow(details.period, timeframe)
}));
return {
...selection,
report: {
period: details.period,
daily: details.daily,
lastActivityAt: details.lastActivityAt ? Date.parse(details.lastActivityAt) : null,
countsByTimeframe: countVisitWindows(details.daily, windows),
browserVisitsByTimeframe: countBreakdownVisitsByTimeframe(details.browsers, windows),
operatingSystemVisitsByTimeframe: countBreakdownVisitsByTimeframe(
details.operatingSystems,
windows
),
acceptedLanguageVisitsByTimeframe: countBreakdownVisitsByTimeframe(
details.acceptedLanguages,
windows
)
}
};
}) satisfies PageServerLoad;
function selectedScope(query: URLSearchParams): AnalyticsScope {
const domains = query.getAll('domain');
const paths = query.getAll('path');
const tags = query.getAll('tag');
if (domains.length > 1 || paths.length > 1 || tags.length > 1) {
error(400, 'Select only one report scope');
}
const [domain] = domains;
const [path] = paths;
const [tag] = tags;
if (tag !== undefined) {
const conflictsWithTag = domain !== undefined || path !== undefined;
const tagIsBlank = tag.trim() === '';
if (conflictsWithTag || tagIsBlank) error(400, 'Invalid tag selection');
return { kind: 'tag', tag };
}
if (domain !== undefined && normalizeHost(domain) !== domain) {
error(400, 'Invalid domain selection');
}
if (path !== undefined) {
if (domain === undefined || !isCanonicalPath(path)) error(400, 'Invalid redirect selection');
return { kind: 'link', domain, path };
}
return domain === undefined ? { kind: 'overview' } : { kind: 'domain', domain };
}
function scopeGroups(domains: ConfigurationSnapshot['domains']): ScopeGroup[] {
const hosts = Object.keys(domains).sort();
return [
{ label: 'Overview', scopes: [{ kind: 'overview' }] },
{ label: 'Domains', scopes: hosts.map((domain) => ({ kind: 'domain', domain })) },
{
label: 'Redirects',
scopes: hosts.flatMap((domain) =>
['/', ...Object.keys(domains[domain]!.links).sort()].map((path) => ({
kind: 'link',
domain,
path
}))
)
},
{ label: 'Tags', scopes: currentTags(domains).map((tag) => ({ kind: 'tag', tag })) }
];
}
function isConfiguredScope(scope: AnalyticsScope, groups: ScopeGroup[]): boolean {
const selectedValue = scopeValue(scope);
return groups.some(({ scopes }) => scopes.some((option) => scopeValue(option) === selectedValue));
}
async function readScopeDetails(snapshot: ConfigurationSnapshot, scope: AnalyticsScope) {
if (scope.kind !== 'tag') return readVisitDetails(snapshot.configuration, scope);
const members = tagMembers(snapshot.domains, scope.tag);
const identities = members.map(({ domain, path }) => ({ domain, path }));
const report = await readLinkDetails(snapshot.configuration, identities);
return report ? combineTagVisits(report) : null;
}
@@ -0,0 +1,136 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import { setScope, type AnalyticsScope } from '#lib/report-scopes.js';
import ReportScopePicker from './ReportScopePicker.svelte';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let report = $derived(data.report);
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let counts = $derived(report?.countsByTimeframe[timeframe]);
let selectionNavigationFailed = $state(false);
let pendingReportNavigations = $state(0);
async function selectScope(scope: AnalyticsScope): Promise<void> {
selectionNavigationFailed = false;
const committedUrl = currentUrl.href;
const next = new URL(committedUrl);
setScope(next.searchParams, scope);
pendingReportNavigations += 1;
try {
await goto(next, { reset: false });
} catch {
if (currentUrl.href === committedUrl) selectionNavigationFailed = true;
} finally {
pendingReportNavigations -= 1;
}
}
</script>
<AdminPage title="Analytics" analyticsEnabled lastActivityAt={report?.lastActivityAt ?? null}>
{#snippet actions()}
{#if report}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<div class="analytics-summary">
<div
class="report-filters"
role="group"
aria-label="Report filters"
aria-busy={pendingReportNavigations > 0}
>
<ReportScopePicker
groups={data.groups}
committedScope={data.scope}
onSelectionRequest={selectScope}
/>
</div>
{#if counts}
<div class="admin-cards report-totals">
<StatCard label="Visits" value={counts.validVisits} />
<StatCard label="Invalid clicks" value={counts.invalidVisits} />
</div>
{/if}
</div>
{#if selectionNavigationFailed}
<p class="admin-notice" role="alert">Could not change the report selection. Try again.</p>
{/if}
{#if data.scopeUnavailable}
<p class="admin-notice" role="status">
This report scope is no longer configured. Choose another scope or select All traffic.
</p>
{:else}
<ReportNotice collectionEnabled available={report !== null} />
{/if}
{#if report && counts}
<VisitsChart
daily={report.daily}
window={visitWindow(report.period, timeframe)}
granularity={visitGranularity(timeframe, report.period.retentionMonths)}
/>
<VisitBreakdowns
browserVisits={report.browserVisitsByTimeframe[timeframe] ?? []}
operatingSystemVisits={report.operatingSystemVisitsByTimeframe[timeframe] ?? []}
acceptedLanguageVisits={report.acceptedLanguageVisitsByTimeframe[timeframe] ?? []}
totalVisits={counts.validVisits}
/>
{/if}
</AdminPage>
<style>
.analytics-summary {
--summary-card-width: 12rem;
--summary-pair-width: calc(2 * var(--summary-card-width) + var(--space-5));
display: grid;
grid-template-columns: minmax(0, var(--summary-pair-width));
gap: var(--space-5);
align-items: start;
}
.report-filters {
min-width: 0;
}
.report-totals {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (width <= 400px) {
.analytics-summary {
grid-template-columns: minmax(0, var(--summary-card-width));
}
.report-totals {
grid-template-columns: minmax(0, 1fr);
}
}
@media (width > 640px) {
.analytics-summary {
grid-template-columns: repeat(2, minmax(0, var(--summary-pair-width)));
justify-content: space-between;
}
.report-filters {
align-self: center;
}
}
</style>
@@ -0,0 +1,268 @@
<script lang="ts">
import { Combobox } from 'bits-ui';
import { flushSync } from 'svelte';
import IconCaretDown from 'virtual:icons/ph/caret-down';
import IconCheck from 'virtual:icons/ph/check';
import {
scopeLabel,
scopeValue,
type AnalyticsScope,
type ScopeGroup
} from '#lib/report-scopes.js';
let {
groups,
committedScope,
onSelectionRequest
}: {
groups: ScopeGroup[];
committedScope: AnalyticsScope;
onSelectionRequest: (scope: AnalyticsScope) => Promise<void>;
} = $props();
const id = $props.id();
const popupId = `${id}-options`;
const descriptionId = `${id}-committed`;
let open = $state(false);
let searchQuery = $state('');
let viewport = $state<HTMLElement | null>(null);
let committedValue = $derived(scopeValue(committedScope));
let committedDescription = $derived.by(() => {
const label = scopeLabel(committedScope);
if (committedScope.kind === 'domain') return `Domain: ${label}`;
if (committedScope.kind === 'tag') return `Tag: ${label}`;
return label;
});
let optionGroups = $derived(
groups.map(({ label, scopes }) => ({
label,
options: scopes.map((scope) => ({
scope,
value: scopeValue(scope),
label: scopeLabel(scope)
}))
}))
);
let optionsByValue = $derived(
new Map(
optionGroups.flatMap(({ options }) =>
options.map((option) => [option.value, option] as const)
)
)
);
let matchingGroups = $derived.by(() => {
const terms = searchQuery.trim().toLowerCase().split(/\s+/);
return optionGroups
.map(({ label, options }) => ({
label,
options: options.filter((option) => {
const text = `${label} ${option.label}`.toLowerCase();
return terms.every((term) => text.includes(term));
})
}))
.filter(({ options }) => options.length > 0);
});
function requestSelection(value: string): void {
if (value === committedValue) return;
const option = optionsByValue.get(value);
if (option) void onSelectionRequest(option.scope);
}
function updateSearch(text: string): void {
// Bits UI highlights the first rendered match after this input handler.
flushSync(() => {
searchQuery = text;
open = true;
});
if (viewport) viewport.scrollTop = 0;
}
function moveFromMissingHighlight(
event: KeyboardEvent & { currentTarget: HTMLInputElement }
): void {
const isArrowDown = event.key === 'ArrowDown';
const isVerticalArrow = isArrowDown || event.key === 'ArrowUp';
const hasModifier = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
if (!isVerticalArrow || hasModifier || event.isComposing) return;
if (!open || !viewport || matchingGroups.length === 0) return;
const input = event.currentTarget;
const activeId = input.getAttribute('aria-activedescendant');
const activeOption = activeId ? input.ownerDocument.getElementById(activeId) : null;
if (viewport.contains(activeOption)) return;
// Bits UI's Home/End handling can activate a partially visible option.
event.preventDefault();
const key = isArrowDown ? 'Home' : 'End';
input.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }));
}
function handleOpenChange(isOpen: boolean): void {
if (!isOpen) searchQuery = '';
}
</script>
<Combobox.Root
type="single"
bind:value={() => committedValue, requestSelection}
bind:open
onOpenChange={handleOpenChange}
allowDeselect={false}
>
<div class="scope-picker">
<span id={descriptionId} hidden>Current report: {committedDescription}</span>
<Combobox.Input
aria-label="Report scope"
aria-describedby={descriptionId}
aria-controls={open ? popupId : undefined}
autocomplete="off"
onclick={() => {
open = true;
}}
oninput={(event) => updateSearch(event.currentTarget.value)}
onkeydown={moveFromMissingHighlight}
>
{#snippet child({ props })}
<!-- Keep the typed draft separate from the label Bits UI writes on selection. -->
<input
{...props}
class="ui-input ui-input--compact scope-input"
value={searchQuery}
placeholder={open ? 'Search domains, redirects, or tags…' : committedDescription}
title={committedDescription}
/>
{/snippet}
</Combobox.Input>
<Combobox.Trigger aria-label="Show report scopes">
{#snippet child({ props })}
<button {...props} type="button" class="scope-trigger">
<IconCaretDown aria-hidden="true" focusable="false" />
</button>
{/snippet}
</Combobox.Trigger>
</div>
<Combobox.Portal>
<Combobox.Content id={popupId} aria-label="Report scopes" align="start" sideOffset={4}>
{#snippet child({ props, wrapperProps })}
<div {...wrapperProps}>
<div {...props} id={popupId} class="scope-menu">
<Combobox.Viewport bind:ref={viewport}>
{#each matchingGroups as group (group.label)}
<Combobox.Group>
<Combobox.GroupHeading>
<span class="scope-group-label">{group.label}</span>
</Combobox.GroupHeading>
{#each group.options as option (option.value)}
<Combobox.Item value={option.value} label={option.label}>
{#snippet child({ props: optionProps, selected })}
<div {...optionProps} class="scope-option">
<span>{option.label}</span>
{#if selected}<IconCheck aria-hidden="true" focusable="false" />{/if}
</div>
{/snippet}
</Combobox.Item>
{/each}
</Combobox.Group>
{:else}
<p class="no-scopes" role="status">No matching report scopes.</p>
{/each}
</Combobox.Viewport>
</div>
</div>
{/snippet}
</Combobox.Content>
</Combobox.Portal>
</Combobox.Root>
<style>
.scope-picker {
position: relative;
}
.scope-input {
padding-inline-end: var(--size-icon);
text-overflow: ellipsis;
}
.scope-input::placeholder {
color: var(--color-text-muted);
opacity: 1;
}
.scope-input[aria-expanded='false']::placeholder {
color: var(--color-text);
}
.scope-trigger {
position: absolute;
inset-block: 0;
inset-inline-end: 0;
width: var(--size-icon);
display: grid;
place-items: center;
appearance: none;
padding: 0;
color: inherit;
background: transparent;
border: 0;
border-radius: var(--radius-control);
cursor: pointer;
}
.scope-trigger:focus-visible {
outline: var(--outline-focus);
outline-offset: calc(-1 * var(--space-1));
}
.scope-menu {
display: flex;
flex-direction: column;
z-index: 100;
width: var(--bits-combobox-anchor-width);
max-height: min(22rem, var(--bits-combobox-content-available-height));
padding: var(--space-1);
font-size: var(--font-size-sm);
background: var(--color-surface-card);
border: var(--border-width) solid var(--color-border-subtle);
border-radius: var(--radius-control);
box-shadow: var(--shadow-card);
}
.scope-group-label,
.no-scopes {
display: block;
padding: var(--space-1) var(--space-4);
color: var(--color-text-muted);
}
.scope-group-label {
font-weight: 600;
}
.scope-option {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
min-height: var(--menu-option-min-height);
padding: var(--space-1) var(--space-4);
border-radius: var(--radius-sm);
cursor: pointer;
}
.scope-option span {
min-width: 0;
overflow-wrap: anywhere;
white-space: break-spaces;
}
.scope-option[data-highlighted]:not([data-selected]) {
background: var(--color-menu-option-highlight);
}
.scope-option[data-selected] {
color: var(--color-on-primary);
background: var(--color-primary-fill);
}
</style>
@@ -0,0 +1,242 @@
import { createVisitPeriod } from '@goto/analytics';
import { loadConfig } from '@goto/config';
import { beforeEach, expect, test, vi } from 'vitest';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readLinkDetails, readVisitDetails } from '#lib/server/visits/reports.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({
readVisitDetails: vi.fn(),
readLinkDetails: vi.fn()
}));
beforeEach(() => vi.resetAllMocks());
const configuredDomain = 'go.example.test';
const tag = 'Work/100%é';
function request(retentionMonths: 0 | 3, query = '') {
const prepared = loadConfig(
{
auth: { credentials: { username: 'test', password: 'analytics-test-password' } },
analytics: { retention_months: retentionMonths },
domains: {
[configuredDomain]: {
links: {
'/a%2Fb': { url: 'https://example.test/literal' },
'/a/b': { title: 'Nested docs', url: 'https://example.test/nested', tags: [tag] }
}
},
'other.example.test': {
links: {
'/a/b': { url: 'https://example.test/other', tags: [tag] },
'/other': { url: 'https://example.test/untagged' }
}
}
}
},
{ env: {} }
);
return {
locals: { snapshot: prepareSnapshot(prepared) },
url: new URL(`https://admin.example.test/admin/analytics${query}`)
} as Parameters<typeof load>[0];
}
test('redirects to Health without reading a report when analytics is disabled', async () => {
await expect(load(request(0, `?${new URLSearchParams({ tag })}`))).rejects.toMatchObject({
status: 307,
location: '/admin/health'
});
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('does not redirect when the global report is unavailable', async () => {
vi.mocked(readVisitDetails).mockResolvedValueOnce(null);
const unavailable = await load(request(3));
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'overview'
});
expect(unavailable).toMatchObject({ retentionMonths: 3, report: null });
});
test('reads one report for the selected configured domain', async () => {
vi.mocked(readVisitDetails).mockResolvedValueOnce(null);
const data = await load(request(3, `?domain=${configuredDomain}`));
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'domain',
domain: configuredDomain
});
expect(data).toMatchObject({
scope: { kind: 'domain', domain: configuredDomain },
scopeUnavailable: false
});
expect(data.groups).toEqual([
{ label: 'Overview', scopes: [{ kind: 'overview' }] },
{
label: 'Domains',
scopes: [
{ kind: 'domain', domain: configuredDomain },
{ kind: 'domain', domain: 'other.example.test' }
]
},
{
label: 'Redirects',
scopes: [
{ kind: 'link', domain: configuredDomain, path: '/' },
{ kind: 'link', domain: configuredDomain, path: '/a%2Fb' },
{ kind: 'link', domain: configuredDomain, path: '/a/b' },
{ kind: 'link', domain: 'other.example.test', path: '/' },
{ kind: 'link', domain: 'other.example.test', path: '/a/b' },
{ kind: 'link', domain: 'other.example.test', path: '/other' }
]
},
{ label: 'Tags', scopes: [{ kind: 'tag', tag }] }
]);
});
test.each(['/', '/a%2Fb', '/a/b'])('reads one report for the exact redirect %s', async (path) => {
vi.mocked(readVisitDetails).mockResolvedValueOnce(null);
const query = new URLSearchParams({ domain: configuredDomain, path });
const data = await load(request(3, `?${query}`));
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'link',
domain: configuredDomain,
path
});
expect(data).toMatchObject({
scope: { kind: 'link', domain: configuredDomain, path },
scopeUnavailable: false
});
});
test.each([
'?path=%2F',
`?domain=${configuredDomain}&path=`,
`?domain=${configuredDomain}&path=%2Fa%2F..%2Fb`,
`?domain=${configuredDomain}&path=%2F&path=%2Fa%2Fb`
])('rejects an invalid redirect query without reading a report: %s', async (query) => {
await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 });
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('does not read a broader report for a redirect missing from the selected domain', async () => {
const data = await load(request(3, `?domain=${configuredDomain}&path=%2Fother`));
expect(data).toMatchObject({
scope: { kind: 'link', domain: configuredDomain, path: '/other' },
scopeUnavailable: true,
report: null
});
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test.each([`?domain=${configuredDomain}&domain=tiny.example.test`, '?domain=GO.EXAMPLE.TEST'])(
'rejects an invalid domain query without reading a report: %s',
async (query) => {
await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 });
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
}
);
test('keeps a removed domain selection without falling back to the global report', async () => {
const data = await load(request(3, '?domain=removed.example.test'));
expect(data).toMatchObject({
scope: { kind: 'domain', domain: 'removed.example.test' },
scopeUnavailable: true,
report: null
});
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('reads one batch for the exact tag across domains, excluding other paths', async () => {
vi.mocked(readLinkDetails).mockResolvedValueOnce(null);
const data = await load(request(3, `?${new URLSearchParams({ tag })}`));
expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
{ domain: configuredDomain, path: '/a/b' },
{ domain: 'other.example.test', path: '/a/b' }
]);
expect(readVisitDetails).not.toHaveBeenCalled();
expect(data).toMatchObject({
scope: { kind: 'tag', tag },
scopeUnavailable: false,
report: null
});
});
test.each([
'?tag=',
'?tag=Work&tag=Docs',
`?tag=Work&domain=${configuredDomain}`,
'?tag=Work&path=%2F'
])('rejects malformed or mixed tag selections: %s', async (query) => {
await expect(load(request(3, query))).rejects.toMatchObject({ status: 400 });
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('does not fall back to all traffic for a stale tag', async () => {
const data = await load(request(3, '?tag=Removed'));
expect(data).toMatchObject({
scope: { kind: 'tag', tag: 'Removed' },
scopeUnavailable: true,
report: null
});
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('projects global totals and keeps each breakdown tied to the selected window', async () => {
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const recent = { day: '2026-06-01', validVisits: 3, invalidVisits: 1 };
const older = { day: '2026-05-01', validVisits: 2, invalidVisits: 4 };
vi.mocked(readVisitDetails).mockResolvedValueOnce({
version: 5,
scope: { kind: 'overview' },
period,
lastActivityAt: '2026-06-01T12:00:00.000Z',
daily: [
{
start: '2026-05-01T00:00:00.000Z',
end: '2026-05-02T00:00:00.000Z',
partial: false,
validVisits: older.validVisits,
invalidVisits: older.invalidVisits
},
{
start: '2026-06-01T00:00:00.000Z',
end: '2026-06-02T00:00:00.000Z',
partial: false,
validVisits: recent.validVisits,
invalidVisits: recent.invalidVisits
}
],
browsers: [
{ ...older, name: 'Chrome' },
{ ...recent, name: 'Firefox' }
],
operatingSystems: [
{ ...older, name: 'Windows' },
{ ...recent, name: 'Linux' }
],
acceptedLanguages: [
{ ...older, name: 'fr' },
{ ...recent, name: 'en' }
]
});
const { report } = await load(request(3));
expect(report?.countsByTimeframe).toEqual({
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 3, invalidVisits: 1 },
all: { validVisits: 5, invalidVisits: 5 }
});
expect(report?.browserVisitsByTimeframe['30d']).toEqual([{ name: 'Firefox', visits: 3 }]);
expect(report?.operatingSystemVisitsByTimeframe['30d']).toEqual([{ name: 'Linux', visits: 3 }]);
expect(report?.acceptedLanguageVisitsByTimeframe['30d']).toEqual([{ name: 'en', visits: 3 }]);
});
@@ -1,89 +1,51 @@
import { error } from '@sveltejs/kit';
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { linkHref } from '#lib/components/admin/urls.js';
import { currentLinkState } from '#lib/server/link-state.js';
import { readDomainDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readDomainLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import type { PageServerLoad } from './$types';
export const load = (async ({ locals, params }) => {
const snapshot = locals.snapshot;
const { configuration, domains } = locals.snapshot;
const domain = params.domain;
if (!Object.hasOwn(snapshot.domains, domain)) throw error(404, 'Domain not configured');
const prepared = snapshot.domains[domain]!;
const configuration = snapshot.configuration;
const retentionMonths = configuration.analytics.retention_months;
const collectionEnabled = retentionMonths !== 0;
const currentPaths = Object.keys(prepared.links);
let report: Awaited<ReturnType<typeof readDomainDetails>> = null;
if (collectionEnabled) {
report = await readDomainDetails(configuration, domain, currentPaths);
}
const domainDetails = report?.domain ?? null;
const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths);
const windows = domainDetails
? timeframes.map((timeframe) => ({
timeframe,
window: visitWindow(domainDetails.period, timeframe)
}))
: [];
const detailsByPath = new Map(report?.links.map(({ path, details }) => [path, details]));
const countsByTimeframe = countVisitWindows(domainDetails?.daily, windows);
const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(
domainDetails?.browsers,
windows
if (!Object.hasOwn(domains, domain)) error(404, 'Domain not configured');
const prepared = domains[domain]!;
const namedLinks = Object.entries(prepared.links);
const analyticsEnabled = configuration.analytics.retention_months !== 0;
const totals = await readDomainLifetimeVisitTotals(
configuration,
domain,
Object.keys(prepared.links)
);
const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe(
domainDetails?.operatingSystems,
windows
);
const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe(
domainDetails?.acceptedLanguages,
windows
);
let rootUrl: string | null = null;
if (prepared.root !== null) rootUrl = prepared.root.url;
else if (prepared.fallback !== null) rootUrl = prepared.fallback.url;
const rootCountsByTimeframe = countVisitWindows(detailsByPath.get('/')?.daily, windows);
const rootHref = linkHref(domain, '/');
const activity = analyticsEnabled
? await readLastActivity(configuration, { kind: 'domain', domain })
: null;
const now = Date.now();
const links = [
{
path: '/',
url: rootUrl,
url: prepared.root?.url ?? prepared.fallback?.url ?? null,
state: 'active' as const,
countsByTimeframe: rootCountsByTimeframe,
href: rootHref
visits: totals?.byPath.get('/')?.validVisits ?? null,
href: linkHref(domain, '/')
},
...Object.entries(prepared.links).map(([path, link]) => {
const daily = detailsByPath.get(path)?.daily;
const countsByTimeframe = countVisitWindows(daily, windows);
return {
path,
url: link.url,
state: currentLinkState(link, now, locals.application.linkVisitCount(domain, path)),
countsByTimeframe,
href: linkHref(domain, path)
};
})
...namedLinks.map(([path, link]) => ({
path,
url: link.url,
state: currentLinkState(link, now, locals.application.linkVisitCount(domain, path)),
visits: totals?.byPath.get(path)?.validVisits ?? null,
href: linkHref(domain, path)
}))
];
const lastActivityAt = domainDetails?.lastActivityAt
? Date.parse(domainDetails.lastActivityAt)
: null;
const chart = domainDetails ? { daily: domainDetails.daily, period: domainDetails.period } : null;
return {
domain,
retentionMonths,
collectionEnabled,
available: domainDetails !== null,
lastActivityAt,
linkCount: currentPaths.length,
timeframes,
countsByTimeframe,
browserVisitsByTimeframe,
operatingSystemVisitsByTimeframe,
acceptedLanguageVisitsByTimeframe,
chart,
analyticsEnabled,
lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null,
linkCount: namedLinks.length,
totalVisits: totals?.domain.validVisits ?? null,
invalidClicks: totals?.domain.invalidVisits ?? null,
root: prepared.root,
fallback: prepared.fallback,
links
@@ -1,94 +1,65 @@
<script lang="ts">
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import AnalyticsSection from '#lib/components/admin/AnalyticsSection.svelte';
import AnalyticsField from '#lib/components/admin/AnalyticsField.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import LinkInventory from '#lib/components/admin/LinkInventory.svelte';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let window = $derived(data.chart ? visitWindow(data.chart.period, timeframe) : null);
let granularity = $derived(
data.chart ? visitGranularity(timeframe, data.chart.period.retentionMonths) : 'day'
);
let visits = $derived(data.countsByTimeframe[timeframe]?.validVisits ?? null);
let invalidClicks = $derived(data.countsByTimeframe[timeframe]?.invalidVisits ?? null);
let browserVisits = $derived(data.browserVisitsByTimeframe[timeframe] ?? null);
let operatingSystemVisits = $derived(data.operatingSystemVisitsByTimeframe[timeframe] ?? null);
let acceptedLanguageVisits = $derived(data.acceptedLanguageVisitsByTimeframe[timeframe] ?? null);
</script>
<AdminPage
title="Domain"
analyticsEnabled={data.analyticsEnabled}
documentTitle={`Domain — ${data.domain}`}
lastActivityAt={data.lastActivityAt}
overviewHref={`/admin?period=${timeframe}`}
>
{#snippet actions()}
{#if data.available && data.timeframes.length > 0}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<section class="admin-info" aria-labelledby="domain-details-heading">
<section aria-labelledby="summary-heading">
<h2 id="summary-heading">Summary</h2>
<div class="summary-content">
{#if data.totalVisits === null}
<p class="admin-notice" role="status">Visit totals unavailable.</p>
{/if}
<div class="admin-cards">
<StatCard label="Links" value={data.linkCount} />
<StatCard label="Total Visits" value={data.totalVisits} />
<StatCard label="Invalid clicks" value={data.invalidClicks} />
</div>
</div>
</section>
<section aria-labelledby="domain-details-heading">
<h2 id="domain-details-heading">Details</h2>
<dl>
<dt>Domain</dt>
<dd>{data.domain}</dd>
<dt>Root</dt>
<dd>
{#if data.root}
<a class="admin-destination" href={data.root.url}>{data.root.url}</a>
{:else}Uses fallback{/if}
</dd>
<dt>Fallback</dt>
<dd>
{#if data.fallback}
<a class="admin-destination" href={data.fallback.url}>{data.fallback.url}</a>
{:else}404 Not found{/if}
</dd>
</dl>
<div class="admin-info">
<dl>
<dt>Domain</dt>
<dd>{data.domain}</dd>
<dt>Root</dt>
<dd>
{#if data.root}
<a class="admin-destination" href={data.root.url}>{data.root.url}</a>
{:else}Uses fallback{/if}
</dd>
<dt>Fallback</dt>
<dd>
{#if data.fallback}
<a class="admin-destination" href={data.fallback.url}>{data.fallback.url}</a>
{:else}404 Not found{/if}
</dd>
{#if data.analyticsEnabled}
<AnalyticsField scope={{ kind: 'domain', domain: data.domain }} />
{/if}
</dl>
</div>
</section>
<section>
<h2>Links</h2>
<LinkInventory
label={`Links on ${data.domain}`}
links={data.links}
{timeframe}
collectionEnabled={data.collectionEnabled}
/>
<LinkInventory label={`Links on ${data.domain}`} links={data.links} visitLabel="Total Visits" />
</section>
<AnalyticsSection>
<ReportNotice collectionEnabled={data.collectionEnabled} available={data.available} />
<div class="admin-cards">
<StatCard label="Links" value={data.linkCount} />
{#if data.collectionEnabled}
<StatCard label="Visits" value={visits} />
<StatCard label="Invalid clicks" value={invalidClicks} />
{/if}
</div>
{#if data.chart && window}
<VisitsChart daily={data.chart.daily} {window} {granularity} />
{/if}
{#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null}
<VisitBreakdowns
{browserVisits}
{operatingSystemVisits}
{acceptedLanguageVisits}
totalVisits={visits}
/>
{/if}
</AnalyticsSection>
</AdminPage>
<style>
.summary-content {
display: flex;
flex-direction: column;
gap: var(--space-5);
}
</style>
@@ -1,7 +1,5 @@
import { error } from '@sveltejs/kit';
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { readVisitDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import type { PageServerLoad } from './$types';
@@ -13,47 +11,19 @@ export const load = (async ({ locals, params }) => {
const response = prepared.root;
const fallback = prepared.fallback;
const configuration = snapshot.configuration;
const retentionMonths = configuration.analytics.retention_months;
const collectionEnabled = retentionMonths !== 0;
const analyticsEnabled = configuration.analytics.retention_months !== 0;
const scope = { kind: 'link' as const, domain, path: '/' };
const lifetimeVisitTotals = await readLifetimeVisitTotals(configuration, scope);
let details: Awaited<ReturnType<typeof readVisitDetails>> = null;
if (collectionEnabled) {
details = await readVisitDetails(configuration, scope);
}
const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths);
const windows = details
? timeframes.map((timeframe) => ({ timeframe, window: visitWindow(details.period, timeframe) }))
: [];
const countsByTimeframe = countVisitWindows(details?.daily, windows);
const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(details?.browsers, windows);
const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe(
details?.operatingSystems,
windows
);
const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe(
details?.acceptedLanguages,
windows
);
const lastActivityAt = details?.lastActivityAt ? Date.parse(details.lastActivityAt) : null;
const chart = details ? { daily: details.daily, period: details.period } : null;
const totals = await readLifetimeVisitTotals(configuration, scope);
const activity = analyticsEnabled ? await readLastActivity(configuration, scope) : null;
return {
domain,
lifetimeVisitTotals,
totalVisits: totals?.validVisits ?? null,
domainHref: `/admin/domains/${encodeURIComponent(domain)}`,
response,
fallback,
fallbackSource: prepared.provenance.fallback,
retentionMonths,
collectionEnabled,
available: details !== null,
lastActivityAt,
timeframes,
countsByTimeframe,
browserVisitsByTimeframe,
operatingSystemVisitsByTimeframe,
acceptedLanguageVisitsByTimeframe,
chart
analyticsEnabled,
lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null
};
}) satisfies PageServerLoad;
@@ -1,115 +1,91 @@
<script lang="ts">
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import AnalyticsSection from '#lib/components/admin/AnalyticsSection.svelte';
import AnalyticsField from '#lib/components/admin/AnalyticsField.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import { formatCount } from '#lib/components/admin/format.js';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let window = $derived(data.chart ? visitWindow(data.chart.period, timeframe) : null);
let granularity = $derived(
data.chart ? visitGranularity(timeframe, data.chart.period.retentionMonths) : 'day'
);
let visits = $derived(data.countsByTimeframe[timeframe]?.validVisits ?? null);
let browserVisits = $derived(data.browserVisitsByTimeframe[timeframe] ?? null);
let operatingSystemVisits = $derived(data.operatingSystemVisitsByTimeframe[timeframe] ?? null);
let acceptedLanguageVisits = $derived(data.acceptedLanguageVisitsByTimeframe[timeframe] ?? null);
</script>
<AdminPage
title="Root"
analyticsEnabled={data.analyticsEnabled}
documentTitle={`Root — ${data.domain}`}
lastActivityAt={data.lastActivityAt}
overviewHref={`/admin?period=${timeframe}`}
>
{#snippet actions()}
{#if data.available && data.timeframes.length > 0}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<section class="admin-info" aria-labelledby="root-details-heading">
<h2 id="root-details-heading">Root details</h2>
<dl>
<dt>Domain</dt>
<dd><a href={`${data.domainHref}?period=${timeframe}`}>{data.domain}</a></dd>
<dt>Address</dt>
<dd>{data.domain}/</dd>
<dt>All-time visits</dt>
<dd>{formatCount(data.lifetimeVisitTotals?.validVisits ?? null)}</dd>
<dt>Destination</dt>
<dd>
{#if data.response}
<a class="admin-destination" href={data.response.url}>
{data.response.url}
</a>
{:else}
<a href="#fallback">Uses fallback</a>
{/if}
</dd>
{#if data.response}
<dt>HTTP status</dt>
<dd>{data.response.status_code}</dd>
<dt>Forward query</dt>
<dd>{data.response.forward_query ? 'Yes' : 'No'}</dd>
{/if}
</dl>
</section>
<section id="fallback" class="admin-info" aria-labelledby="fallback-heading">
<h2 id="fallback-heading">Fallback</h2>
<dl>
<dt>Source</dt>
<dd>
{#if data.fallbackSource === 'domain'}Domain
{:else if data.fallbackSource === 'global'}Global
{:else}Default{/if}
</dd>
<dt>Destination</dt>
<dd>
{#if data.fallback}
<a class="admin-destination" href={data.fallback.url}>
{data.fallback.url}
</a>
{:else}404 Not found{/if}
</dd>
{#if data.fallback}
<dt>HTTP status</dt>
<dd>{data.fallback.status_code}</dd>
<dt>Forward query</dt>
<dd>{data.fallback.forward_query ? 'Yes' : 'No'}</dd>
{/if}
</dl>
</section>
<AnalyticsSection>
<ReportNotice collectionEnabled={data.collectionEnabled} available={data.available} />
<div class="admin-cards">
{#if data.collectionEnabled}
<StatCard label="Visits" value={visits} />
<section aria-labelledby="summary-heading">
<h2 id="summary-heading">Summary</h2>
<div class="summary-content">
{#if data.totalVisits === null}
<p class="admin-notice" role="status">Visit totals unavailable.</p>
{/if}
<div class="admin-cards">
<StatCard label="Total Visits" value={data.totalVisits} />
</div>
</div>
{#if data.chart && window}
<VisitsChart daily={data.chart.daily} {window} {granularity} />
{/if}
{#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null}
<VisitBreakdowns
{browserVisits}
{operatingSystemVisits}
{acceptedLanguageVisits}
totalVisits={visits}
/>
{/if}
</AnalyticsSection>
</section>
<section aria-labelledby="root-details-heading">
<h2 id="root-details-heading">Root details</h2>
<div class="admin-info">
<dl>
<dt>Domain</dt>
<dd><a href={data.domainHref}>{data.domain}</a></dd>
<dt>Address</dt>
<dd>{data.domain}/</dd>
<dt>Destination</dt>
<dd>
{#if data.response}
<a class="admin-destination" href={data.response.url}>
{data.response.url}
</a>
{:else}
<a href="#fallback">Uses fallback</a>
{/if}
</dd>
{#if data.response}
<dt>HTTP status</dt>
<dd>{data.response.status_code}</dd>
<dt>Forward query</dt>
<dd>{data.response.forward_query ? 'Yes' : 'No'}</dd>
{/if}
{#if data.analyticsEnabled}
<AnalyticsField scope={{ kind: 'domain', domain: data.domain }} />
{/if}
</dl>
</div>
</section>
<section id="fallback" aria-labelledby="fallback-heading">
<h2 id="fallback-heading">Fallback</h2>
<div class="admin-info">
<dl>
<dt>Source</dt>
<dd>
{#if data.fallbackSource === 'domain'}Domain
{:else if data.fallbackSource === 'global'}Global
{:else}Default{/if}
</dd>
<dt>Destination</dt>
<dd>
{#if data.fallback}
<a class="admin-destination" href={data.fallback.url}>
{data.fallback.url}
</a>
{:else}404 Not found{/if}
</dd>
{#if data.fallback}
<dt>HTTP status</dt>
<dd>{data.fallback.status_code}</dd>
<dt>Forward query</dt>
<dd>{data.fallback.forward_query ? 'Yes' : 'No'}</dd>
{/if}
</dl>
</div>
</section>
</AdminPage>
<style>
.summary-content {
display: flex;
flex-direction: column;
gap: var(--space-5);
}
</style>
@@ -1,8 +1,6 @@
import { error } from '@sveltejs/kit';
import { countBreakdownVisitsByTimeframe } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { currentLinkState } from '#lib/server/link-state.js';
import { readVisitDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import type { PageServerLoad } from './$types';
export const load = (async ({ locals, params }) => {
@@ -29,29 +27,10 @@ export const load = (async ({ locals, params }) => {
const validFrom = link.valid_from ?? null;
const validUntil = link.valid_until ?? null;
const configuration = snapshot.configuration;
const retentionMonths = configuration.analytics.retention_months;
const collectionEnabled = retentionMonths !== 0;
const scope = { kind: 'link' as const, domain, path };
let details: Awaited<ReturnType<typeof readVisitDetails>> = null;
if (collectionEnabled) {
details = await readVisitDetails(configuration, scope);
}
const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths);
const windows = details
? timeframes.map((timeframe) => ({ timeframe, window: visitWindow(details.period, timeframe) }))
: [];
const countsByTimeframe = countVisitWindows(details?.daily, windows);
const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(details?.browsers, windows);
const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe(
details?.operatingSystems,
windows
);
const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe(
details?.acceptedLanguages,
windows
);
const lastActivityAt = details?.lastActivityAt ? Date.parse(details.lastActivityAt) : null;
const chart = details ? { daily: details.daily, period: details.period } : null;
const analyticsEnabled = configuration.analytics.retention_months !== 0;
const activity = analyticsEnabled
? await readLastActivity(configuration, { kind: 'link', domain, path })
: null;
return {
domain,
@@ -68,15 +47,7 @@ export const load = (async ({ locals, params }) => {
validFrom,
validUntil,
tags: link.tags,
retentionMonths,
collectionEnabled,
available: details !== null,
lastActivityAt,
timeframes,
countsByTimeframe,
browserVisitsByTimeframe,
operatingSystemVisitsByTimeframe,
acceptedLanguageVisitsByTimeframe,
chart
analyticsEnabled,
lastActivityAt: activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null
};
}) satisfies PageServerLoad;
@@ -1,177 +1,138 @@
<script lang="ts">
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import AnalyticsSection from '#lib/components/admin/AnalyticsSection.svelte';
import AnalyticsField from '#lib/components/admin/AnalyticsField.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import { formatCount, formatUtc } from '#lib/components/admin/format.js';
import { formatUtc } from '#lib/components/admin/format.js';
import TagPills from '#lib/components/admin/TagPills.svelte';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let window = $derived(data.chart ? visitWindow(data.chart.period, timeframe) : null);
let granularity = $derived(
data.chart ? visitGranularity(timeframe, data.chart.period.retentionMonths) : 'day'
);
let visits = $derived(data.countsByTimeframe[timeframe]?.validVisits ?? null);
let browserVisits = $derived(data.browserVisitsByTimeframe[timeframe] ?? null);
let operatingSystemVisits = $derived(data.operatingSystemVisitsByTimeframe[timeframe] ?? null);
let acceptedLanguageVisits = $derived(data.acceptedLanguageVisitsByTimeframe[timeframe] ?? null);
const statusLabels = {
active: 'Active',
disabled: 'Disabled',
scheduled: 'Scheduled',
expired: 'Expired',
exhausted: 'Limit Exceeded'
};
</script>
<AdminPage
title="Link"
analyticsEnabled={data.analyticsEnabled}
documentTitle={`Link — ${data.domain}${data.path}`}
lastActivityAt={data.lastActivityAt}
overviewHref={`/admin?period=${timeframe}`}
>
{#snippet actions()}
{#if data.available && data.timeframes.length > 0}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<section class="admin-info" aria-labelledby="redirect-heading">
<h2 id="redirect-heading">Redirect</h2>
<dl>
<dt>Domain</dt>
<dd>
<a href={`/admin/domains/${encodeURIComponent(data.domain)}?period=${timeframe}`}>
{data.domain}
</a>
</dd>
<dt>Path</dt>
<dd>{data.path}</dd>
{#if data.linkTitle}
<dt>Title</dt>
<dd>{data.linkTitle}</dd>
{/if}
<dt>Destination</dt>
<dd class:numbered-setting={data.redirectRules.length > 0}>
{#if data.redirectRules.length > 0}
<ol aria-label="Destinations">
{#each data.redirectRules as rule, index (index)}
<li>
<span aria-hidden="true">{index + 1}.</span>
<a class="admin-destination setting-value" href={rule.to}>{rule.to}</a>
</li>
{/each}
<li>
<span aria-hidden="true">{data.redirectRules.length + 1}.</span>
<a class="admin-destination setting-value" href={data.response.url}
>{data.response.url}</a
>
</li>
</ol>
{:else}
<a class="admin-destination" href={data.response.url}>{data.response.url}</a>
{/if}
</dd>
{#if data.redirectRules.length > 0}
<dt>Rules</dt>
<dd class="numbered-setting">
<ol aria-label="Rules">
{#each data.redirectRules as rule, index (index)}
<li>
<span aria-hidden="true">{index + 1}.</span>
<span class="setting-value">
{#if rule.language !== null && rule.os !== null}
language {rule.language} AND OS {rule.os}
{:else if rule.language !== null}
language {rule.language}
{:else}
OS {rule.os}
{/if}
</span>
</li>
{/each}
<li>
<span aria-hidden="true">{data.redirectRules.length + 1}.</span>
<span class="setting-value">default</span>
</li>
</ol>
</dd>
{/if}
<dt>Visits</dt>
<dd>{formatCount(data.lifetimeVisits)} (all time)</dd>
</dl>
</section>
<section class="admin-info" aria-labelledby="settings-heading">
<h2 id="settings-heading">Settings</h2>
<dl>
<dt>HTTP status</dt>
<dd>{data.response.status_code}</dd>
<dt>Case insensitive</dt>
<dd>{data.caseInsensitive ? 'Yes' : 'No'}</dd>
<dt>Trailing slash</dt>
<dd>{data.ignoreTrailingSlash ? 'Yes' : 'No'}</dd>
<dt>Path forwarding</dt>
<dd>{data.forwardPath ? 'Yes' : 'No'}</dd>
<dt>Query forwarding</dt>
<dd>{data.response.forward_query ? 'Yes' : 'No'}</dd>
{#if data.maxVisits !== null}
<dt>Max visits</dt>
<dd>{formatCount(data.maxVisits)}</dd>
{/if}
{#if data.validFrom}
<dt>Starts</dt>
<dd>
<time datetime={data.validFrom}>{formatUtc(data.validFrom)} UTC</time>
</dd>
{/if}
{#if data.validUntil}
<dt>Expires</dt>
<dd>
<time datetime={data.validUntil}>{formatUtc(data.validUntil)} UTC</time>
</dd>
{/if}
{#if data.tags.length > 0}
<dt>Tags</dt>
<dd><TagPills tags={data.tags} {timeframe} /></dd>
{/if}
</dl>
</section>
<AnalyticsSection>
<ReportNotice collectionEnabled={data.collectionEnabled} available={data.available} />
<section aria-labelledby="summary-heading">
<h2 id="summary-heading">Summary</h2>
<div class="admin-cards">
{#if data.collectionEnabled}
<StatCard label="Visits" value={visits} />
{/if}
{#if data.state === 'active'}
<StatCard label="Status" value="Active" />
{:else if data.state === 'disabled'}
<StatCard label="Status" value="Disabled" />
{:else if data.state === 'scheduled'}
<StatCard label="Status" value="Scheduled" />
{:else if data.state === 'expired'}
<StatCard label="Status" value="Expired" />
{:else if data.state === 'exhausted'}
<StatCard label="Status" value="Limit Exceeded" />
<StatCard label="Total Visits" value={data.lifetimeVisits} />
<StatCard label="Status" value={statusLabels[data.state]} />
{#if data.maxVisits !== null}
<StatCard label="Max visits" value={data.maxVisits} />
{/if}
</div>
{#if data.chart && window}
<VisitsChart daily={data.chart.daily} {window} {granularity} />
{/if}
{#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null}
<VisitBreakdowns
{browserVisits}
{operatingSystemVisits}
{acceptedLanguageVisits}
totalVisits={visits}
/>
{/if}
</AnalyticsSection>
</section>
<section aria-labelledby="redirect-heading">
<h2 id="redirect-heading">Redirect</h2>
<div class="admin-info">
<dl>
<dt>Domain</dt>
<dd>
<a href={`/admin/domains/${encodeURIComponent(data.domain)}`}>
{data.domain}
</a>
</dd>
<dt>Path</dt>
<dd>{data.path}</dd>
{#if data.linkTitle}
<dt>Title</dt>
<dd>{data.linkTitle}</dd>
{/if}
<dt>Destination</dt>
<dd class:numbered-setting={data.redirectRules.length > 0}>
{#if data.redirectRules.length > 0}
<ol aria-label="Destinations">
{#each data.redirectRules as rule, index (index)}
<li>
<span aria-hidden="true">{index + 1}.</span>
<a class="admin-destination setting-value" href={rule.to}>{rule.to}</a>
</li>
{/each}
<li>
<span aria-hidden="true">{data.redirectRules.length + 1}.</span>
<a class="admin-destination setting-value" href={data.response.url}
>{data.response.url}</a
>
</li>
</ol>
{:else}
<a class="admin-destination" href={data.response.url}>{data.response.url}</a>
{/if}
</dd>
{#if data.redirectRules.length > 0}
<dt>Rules</dt>
<dd class="numbered-setting">
<ol aria-label="Rules">
{#each data.redirectRules as rule, index (index)}
<li>
<span aria-hidden="true">{index + 1}.</span>
<span class="setting-value">
{#if rule.language !== null && rule.os !== null}
language {rule.language} AND OS {rule.os}
{:else if rule.language !== null}
language {rule.language}
{:else}
OS {rule.os}
{/if}
</span>
</li>
{/each}
<li>
<span aria-hidden="true">{data.redirectRules.length + 1}.</span>
<span class="setting-value">default</span>
</li>
</ol>
</dd>
{/if}
{#if data.analyticsEnabled}
<AnalyticsField scope={{ kind: 'link', domain: data.domain, path: data.path }} />
{/if}
</dl>
</div>
</section>
<section aria-labelledby="settings-heading">
<h2 id="settings-heading">Settings</h2>
<div class="admin-info">
<dl>
<dt>HTTP status</dt>
<dd>{data.response.status_code}</dd>
<dt>Case insensitive</dt>
<dd>{data.caseInsensitive ? 'Yes' : 'No'}</dd>
<dt>Trailing slash</dt>
<dd>{data.ignoreTrailingSlash ? 'Yes' : 'No'}</dd>
<dt>Path forwarding</dt>
<dd>{data.forwardPath ? 'Yes' : 'No'}</dd>
<dt>Query forwarding</dt>
<dd>{data.response.forward_query ? 'Yes' : 'No'}</dd>
{#if data.validFrom}
<dt>Starts</dt>
<dd>
<time datetime={data.validFrom}>{formatUtc(data.validFrom)} UTC</time>
</dd>
{/if}
{#if data.validUntil}
<dt>Expires</dt>
<dd>
<time datetime={data.validUntil}>{formatUtc(data.validUntil)} UTC</time>
</dd>
{/if}
{#if data.tags.length > 0}
<dt>Tags</dt>
<dd><TagPills tags={data.tags} /></dd>
{/if}
</dl>
</div>
</section>
</AdminPage>
<style>
@@ -1,13 +1,15 @@
import { loadConfig, type DomainConfiguration, type LinkConfiguration } from '@goto/config';
import { createVisitPeriod, visitDays, type VisitDetails } from '@goto/analytics';
import { beforeEach, expect, test, vi } from 'vitest';
import type { Application } from '#lib/server/application.js';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readVisitDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({ readVisitDetails: vi.fn() }));
beforeEach(() => vi.resetAllMocks());
vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() }));
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(readLastActivity).mockResolvedValue({ available: false, lastActivityAt: null });
});
const domain = 'go.example.test';
const linkMetadata = {
@@ -80,43 +82,13 @@ function request(
} as Parameters<typeof load>[0];
}
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const counts: Record<string, [number, number]> = {
'2026-03-17': [4, 1],
'2026-05-16': [3, 2],
'2026-06-08': [5, 1],
'2026-06-09': [2, 1],
'2026-06-15': [1, 0]
};
const browserOsCounts = Object.entries(counts).map(([day, [validVisits, invalidVisits]]) => ({
day,
name: 'Other',
validVisits,
invalidVisits
}));
const details: VisitDetails = {
version: 5,
lastActivityAt: '2026-06-15T10:00:00.000Z',
scope: { kind: 'link', domain, path: '/docs' },
period,
daily: visitDays(period).map((day) => {
const [validVisits, invalidVisits] = counts[day.start.slice(0, 10)] ?? [0, 0];
return { ...day, validVisits, invalidVisits };
}),
browsers: browserOsCounts,
operatingSystems: browserOsCounts,
acceptedLanguages: browserOsCounts.flatMap((row) => [
{ ...row, name: 'en' },
{ ...row, name: 'fr' }
])
};
test('projects only requested link settings, series and compact window counts and breakdowns', async () => {
vi.mocked(readVisitDetails).mockResolvedValue(details);
test('projects only link settings, live lifetime visits, and scoped last activity', async () => {
const lastActivityAt = '2026-06-15T10:00:00.000Z';
vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt });
const event = request();
const data = await load(event);
expect(event.locals.application.linkVisitCount).toHaveBeenCalledExactlyOnceWith(domain, '/docs');
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'link',
domain,
path: '/docs'
@@ -126,48 +98,12 @@ test('projects only requested link settings, series and compact window counts an
path: '/docs',
lifetimeVisits: 102,
...linkMetadata,
retentionMonths: 3,
collectionEnabled: true,
available: true,
lastActivityAt: Date.parse(details.lastActivityAt!),
timeframes: ['7d', '30d', 'all'],
countsByTimeframe: {
'7d': { validVisits: 3, invalidVisits: 1 },
'30d': { validVisits: 8, invalidVisits: 2 },
all: { validVisits: 15, invalidVisits: 5 }
},
acceptedLanguageVisitsByTimeframe: {
'7d': [
{ name: 'en', visits: 3 },
{ name: 'fr', visits: 3 }
],
'30d': [
{ name: 'en', visits: 8 },
{ name: 'fr', visits: 8 }
],
all: [
{ name: 'en', visits: 15 },
{ name: 'fr', visits: 15 }
]
},
browserVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 3 }],
'30d': [{ name: 'Other', visits: 8 }],
all: [{ name: 'Other', visits: 15 }]
},
operatingSystemVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 3 }],
'30d': [{ name: 'Other', visits: 8 }],
all: [{ name: 'Other', visits: 15 }]
},
chart: { daily: details.daily, period }
analyticsEnabled: true,
lastActivityAt: Date.parse(lastActivityAt)
});
});
test('keeps decoded nested and literal-percent identities distinct', async () => {
vi.mocked(readVisitDetails)
.mockResolvedValueOnce({ ...details, scope: { kind: 'link', domain, path: '/a/b' } })
.mockResolvedValueOnce({ ...details, scope: { kind: 'link', domain, path: '/a%2Fb' } });
const nestedEvent = request('/a/b');
const percentEvent = request('/a%2Fb');
const nested = await load(nestedEvent);
@@ -201,38 +137,34 @@ test('keeps decoded nested and literal-percent identities distinct', async () =>
expect(percent.redirectRules).toEqual([
{ language: 'fr', os: null, to: 'https://example.test/percent-fr' }
]);
expect(percent.countsByTimeframe.all?.validVisits).toBe(15);
expect(readVisitDetails).toHaveBeenNthCalledWith(1, expect.any(Object), {
expect(readLastActivity).toHaveBeenNthCalledWith(1, expect.any(Object), {
kind: 'link',
domain,
path: '/a/b'
});
expect(readVisitDetails).toHaveBeenNthCalledWith(2, expect.any(Object), {
expect(readLastActivity).toHaveBeenNthCalledWith(2, expect.any(Object), {
kind: 'link',
domain,
path: '/a%2Fb'
});
});
test('rejects unknown scopes before reading and keeps unavailable counts absent', async () => {
test('rejects unknown scopes and keeps lifetime visits when activity is unavailable', async () => {
await expect(load(request('/docs', { host: 'unknown.test' }))).rejects.toMatchObject({
status: 404
});
await expect(load(request('/not-configured'))).rejects.toMatchObject({ status: 404 });
const missing = request('/not-configured');
await expect(load(missing)).rejects.toMatchObject({ status: 404 });
await expect(load(request('/'))).rejects.toMatchObject({ status: 404 });
expect(readVisitDetails).not.toHaveBeenCalled();
vi.mocked(readVisitDetails).mockResolvedValue(null);
const data = await load(request());
expect(data.available).toBe(false);
expect(data.lifetimeVisits).toBe(102);
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.lastActivityAt).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data).toMatchObject(linkMetadata);
expect(data.retentionMonths).toBe(3);
expect(missing.locals.application.linkVisitCount).not.toHaveBeenCalled();
expect(readLastActivity).not.toHaveBeenCalled();
expect(await load(request())).toMatchObject({
...linkMetadata,
lifetimeVisits: 102,
analyticsEnabled: true,
lastActivityAt: null
});
});
test.each([
@@ -241,7 +173,6 @@ test.each([
])(
'projects configured max $maxVisits and $state from one lifetime lookup',
async ({ maxVisits, state }) => {
vi.mocked(readVisitDetails).mockResolvedValue(details);
const event = request('/docs', { link: { max_visits: maxVisits } });
const data = await load(event);
expect(data).toMatchObject({ maxVisits, state, lifetimeVisits: 102 });
@@ -249,24 +180,20 @@ test.each([
domain,
'/docs'
);
expect(data.countsByTimeframe.all).toEqual({ validVisits: 15, invalidVisits: 5 });
}
);
test('disabled analytics preserves a configured limit and exhaustion without a finite report read', async () => {
test('disabled analytics preserves a configured limit and exhaustion without reading activity', async () => {
const event = request('/docs', { retentionMonths: 0, link: { max_visits: 102 } });
const data = await load(event);
expect(data.lifetimeVisits).toBe(102);
expect(event.locals.application.linkVisitCount).toHaveBeenCalledExactlyOnceWith(domain, '/docs');
expect(readVisitDetails).not.toHaveBeenCalled();
expect(data.collectionEnabled).toBe(false);
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.available).toBe(false);
expect(data.retentionMonths).toBe(0);
expect(data.timeframes).toEqual([]);
expect(data.chart).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data).toMatchObject({ ...linkMetadata, maxVisits: 102, state: 'exhausted' });
expect(readLastActivity).not.toHaveBeenCalled();
expect(data).toMatchObject({
...linkMetadata,
lifetimeVisits: 102,
analyticsEnabled: false,
lastActivityAt: null,
maxVisits: 102,
state: 'exhausted'
});
});
@@ -1,204 +1,116 @@
import { loadConfig, type DomainConfiguration, type RedirectResponse } from '@goto/config';
import { createVisitPeriod, visitDays, type VisitDetails } from '@goto/analytics';
import { loadConfig, type RedirectResponse } from '@goto/config';
import { beforeEach, expect, test, vi } from 'vitest';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readVisitDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({ readVisitDetails: vi.fn() }));
vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() }));
vi.mock('#lib/server/visits/totals.js', () => ({ readLifetimeVisitTotals: vi.fn() }));
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(readLifetimeVisitTotals).mockResolvedValue(null);
vi.mocked(readLastActivity).mockResolvedValue({ available: false, lastActivityAt: null });
});
const domain = 'go.example.test';
const rootScope = { kind: 'link', domain, path: '/' };
const fallback: RedirectResponse = {
url: 'https://example.test/fallback',
status_code: 307,
forward_query: true
};
function request(options: { host?: string; root?: RedirectResponse } = {}) {
const domainConfiguration: Partial<DomainConfiguration> = {
fallback,
link_defaults: { forward_query: true },
links: {}
};
if (options.root) domainConfiguration.root = options.root;
function request({
host = domain,
root,
fallbackSource = 'domain',
retentionMonths = 3
}: {
host?: string;
root?: RedirectResponse;
fallbackSource?: 'domain' | 'global' | 'builtin';
retentionMonths?: 0 | 3;
} = {}) {
const prepared = loadConfig(
{
auth: { credentials: { username: 'test', password: 'link-test-password' } },
analytics: { retention_months: 3 },
analytics: { retention_months: retentionMonths },
link_defaults: { status_code: 301 },
domains: { [domain]: domainConfiguration }
...(fallbackSource === 'global' ? { fallback } : {}),
domains: {
[domain]: {
...(root ? { root } : {}),
...(fallbackSource === 'domain' ? { fallback } : {}),
link_defaults: { forward_query: true },
links: {}
}
}
},
{ env: {} }
);
return {
locals: { snapshot: prepareSnapshot(prepared) },
params: { domain: options.host ?? domain }
params: { domain: host }
} as Parameters<typeof load>[0];
}
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const rootBrowserOsCounts = [
{ day: period.from.slice(0, 10), name: 'Other', validVisits: 7, invalidVisits: 0 }
];
const rootDetails: VisitDetails = {
version: 5,
lastActivityAt: `${period.from.slice(0, 10)}T10:00:00.000Z`,
period,
scope: { kind: 'link', domain, path: '/' },
daily: visitDays(period).map((day, index) => ({
...day,
validVisits: index === 0 ? 7 : 0,
invalidVisits: 0
})),
browsers: rootBrowserOsCounts,
operatingSystems: rootBrowserOsCounts,
acceptedLanguages: rootBrowserOsCounts.flatMap((row) => [
{ ...row, name: 'en' },
{ ...row, name: 'fr' }
])
};
test('supports historical root traffic without a configured root and preserves unavailable metadata', async () => {
vi.mocked(readVisitDetails).mockResolvedValue(rootDetails);
test('reads lifetime Root totals and scoped activity even when Root uses fallback', async () => {
const lastActivityAt = '2026-06-15T10:00:00.000Z';
vi.mocked(readLifetimeVisitTotals).mockResolvedValue({ validVisits: 40, invalidVisits: 0 });
const data = await load(request());
expect(data.lifetimeVisitTotals).toEqual({ validVisits: 40, invalidVisits: 0 });
expect(readLifetimeVisitTotals).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'link',
domain,
path: '/'
});
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'link',
domain,
path: '/'
});
expect(data).toMatchObject({
vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt });
expect(await load(request())).toEqual({
domain,
totalVisits: 40,
domainHref: '/admin/domains/go.example.test',
response: null,
fallback,
fallbackSource: 'domain'
fallbackSource: 'domain',
analyticsEnabled: true,
lastActivityAt: Date.parse(lastActivityAt)
});
expect(data.lastActivityAt).toBe(Date.parse(rootDetails.lastActivityAt!));
expect(data.countsByTimeframe.all?.validVisits).toBe(7);
expect(data.browserVisitsByTimeframe).toEqual({
'7d': [],
'30d': [],
all: [{ name: 'Other', visits: 7 }]
});
expect(data.operatingSystemVisitsByTimeframe).toEqual({
'7d': [],
'30d': [],
all: [{ name: 'Other', visits: 7 }]
});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({
'7d': [],
'30d': [],
all: [
{ name: 'en', visits: 7 },
{ name: 'fr', visits: 7 }
]
});
vi.mocked(readVisitDetails).mockResolvedValue(null);
const unavailable = await load(request());
expect(unavailable.available).toBe(false);
expect(unavailable.lifetimeVisitTotals).toEqual({ validVisits: 40, invalidVisits: 0 });
expect(unavailable.chart).toBeNull();
expect(unavailable.browserVisitsByTimeframe).toEqual({});
expect(unavailable.operatingSystemVisitsByTimeframe).toEqual({});
expect(unavailable.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(unavailable.fallback).toEqual(fallback);
expect(readLifetimeVisitTotals).toHaveBeenCalledExactlyOnceWith(expect.any(Object), rootScope);
expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), rootScope);
});
test('keeps root HTTP settings independent of link defaults and fallback with historical analytics scope', async () => {
vi.mocked(readVisitDetails).mockResolvedValue(rootDetails);
const response: RedirectResponse = {
test('keeps configured Root settings and activity when lifetime totals are unavailable', async () => {
const root: RedirectResponse = {
url: 'https://example.test/start',
status_code: 302,
forward_query: false
};
const data = await load(request({ root: response }));
expect(readVisitDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'link',
domain,
path: '/'
});
expect(data).toMatchObject({
response,
const lastActivityAt = '2026-06-15T10:00:00.000Z';
vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt });
expect(await load(request({ root }))).toMatchObject({
totalVisits: null,
lastActivityAt: Date.parse(lastActivityAt),
response: root,
fallback,
fallbackSource: 'domain'
});
expect(data.countsByTimeframe.all).toEqual({ validVisits: 7, invalidVisits: 0 });
});
test('keeps lifetime root visit totals and fallback metadata usable without finite analytics', async () => {
vi.mocked(readLifetimeVisitTotals).mockResolvedValue({ validVisits: 40, invalidVisits: 0 });
const prepared = loadConfig(
{
auth: { credentials: { username: 'test', password: 'link-test-password' } },
analytics: { retention_months: 0 },
domains: { [domain]: { links: {} } }
},
{ env: {} }
);
const event = {
locals: { snapshot: prepareSnapshot(prepared) },
params: { domain }
} as Parameters<typeof load>[0];
const root = await load(event);
expect(root.lifetimeVisitTotals).toEqual({ validVisits: 40, invalidVisits: 0 });
expect(root.browserVisitsByTimeframe).toEqual({});
expect(root.operatingSystemVisitsByTimeframe).toEqual({});
expect(root.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(root).toMatchObject({
response: null,
fallback: null,
fallbackSource: 'builtin'
});
const global = loadConfig(
{
auth: { credentials: { username: 'test', password: 'link-test-password' } },
analytics: { retention_months: 0 },
fallback,
domains: { [domain]: { links: {} } }
},
{ env: {} }
);
event.locals.snapshot = prepareSnapshot(global);
const inherited = await load(event);
expect(inherited.lifetimeVisitTotals).toEqual({ validVisits: 40, invalidVisits: 0 });
expect(vi.mocked(readLifetimeVisitTotals).mock.calls.map(([, scope]) => scope)).toEqual([
{ kind: 'link', domain, path: '/' },
{ kind: 'link', domain, path: '/' }
]);
expect(inherited.browserVisitsByTimeframe).toEqual({});
expect(inherited.operatingSystemVisitsByTimeframe).toEqual({});
expect(inherited.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(inherited).toMatchObject({
response: null,
fallback,
fallbackSource: 'global'
});
expect(readVisitDetails).not.toHaveBeenCalled();
});
test.each(['global', 'builtin'] as const)(
'keeps Root totals and %s fallback at zero retention without reading activity',
async (fallbackSource) => {
vi.mocked(readLifetimeVisitTotals).mockResolvedValue({ validVisits: 40, invalidVisits: 0 });
expect(await load(request({ retentionMonths: 0, fallbackSource }))).toMatchObject({
totalVisits: 40,
analyticsEnabled: false,
lastActivityAt: null,
response: null,
fallback: fallbackSource === 'global' ? fallback : null,
fallbackSource
});
expect(readLifetimeVisitTotals).toHaveBeenCalledExactlyOnceWith(expect.any(Object), rootScope);
expect(readLastActivity).not.toHaveBeenCalled();
}
);
test('unavailable lifetime root visit totals do not suppress retained visits', async () => {
vi.mocked(readVisitDetails).mockResolvedValue(rootDetails);
const data = await load(request());
expect(data.lifetimeVisitTotals).toBeNull();
expect(data.available).toBe(true);
expect(data.countsByTimeframe.all).toEqual({ validVisits: 7, invalidVisits: 0 });
});
test('rejects unknown domains before reading root traffic', async () => {
test('rejects unknown domains before reading Root statistics', async () => {
await expect(load(request({ host: 'unknown.test' }))).rejects.toMatchObject({ status: 404 });
expect(readVisitDetails).not.toHaveBeenCalled();
expect(readLifetimeVisitTotals).not.toHaveBeenCalled();
expect(readLastActivity).not.toHaveBeenCalled();
});
@@ -1,50 +1,52 @@
import { loadConfig, type DomainConfiguration, type RedirectResponse } from '@goto/config';
import { createVisitPeriod, visitDays, type ReportScope, type VisitDetails } from '@goto/analytics';
import { loadConfig, type RedirectResponse } from '@goto/config';
import { beforeEach, expect, test, vi } from 'vitest';
import type { Application } from '#lib/server/application.js';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readDomainDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readDomainLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({ readDomainDetails: vi.fn() }));
vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() }));
vi.mock('#lib/server/visits/totals.js', () => ({ readDomainLifetimeVisitTotals: vi.fn() }));
beforeEach(() => vi.resetAllMocks());
const domain = 'go.example.test';
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const root: RedirectResponse = {
url: 'https://example.test/start',
status_code: 301,
forward_query: true
};
const fallback: RedirectResponse = {
url: 'https://example.test/missing',
status_code: 302,
forward_query: false
};
function request(
function request({
host = domain,
settings: {
root?: RedirectResponse;
fallback?: RedirectResponse;
globalFallback?: RedirectResponse;
retentionMonths?: number;
links?: Record<string, { url: string; enabled?: boolean; max_visits?: number }>;
visits?: Record<string, number>;
} = {}
) {
const links = settings.links ?? {
'/docs': { url: 'https://example.test/docs' },
'/a/b': { url: 'https://example.test/nested' },
'/a%2Fb': { url: 'https://example.test/percent', enabled: false }
};
const domainConfiguration: Pick<DomainConfiguration, 'root' | 'fallback'> & {
links: typeof links;
} = { links };
if (settings.root) domainConfiguration.root = settings.root;
if (settings.fallback) domainConfiguration.fallback = settings.fallback;
const configuration: Record<string, unknown> = {
auth: { credentials: { username: 'test', password: 'domain-test-password' } },
analytics: { retention_months: settings.retentionMonths ?? 3 },
domains: { [domain]: domainConfiguration }
};
if (settings.globalFallback) configuration.fallback = settings.globalFallback;
const prepared = loadConfig(configuration, { env: {} });
const snapshot = prepareSnapshot(prepared);
const linkVisitCount = vi.fn((host: string, path: string): number => {
if (host !== domain) throw new Error('Unexpected domain');
return settings.visits?.[path] ?? 0;
});
retentionMonths = 0,
configureRoot = true
}: { host?: string; retentionMonths?: 0 | 3; configureRoot?: boolean } = {}) {
const snapshot = prepareSnapshot(
loadConfig(
{
auth: { credentials: { username: 'test', password: 'domain-test-password' } },
analytics: { retention_months: retentionMonths },
fallback,
domains: {
[domain]: {
...(configureRoot ? { root } : {}),
links: {
'/docs': { url: 'https://example.test/docs', enabled: false, max_visits: 2 },
'/a%2Fb': { url: 'https://example.test/percent', max_visits: 8 }
}
}
}
},
{ env: {} }
)
);
const linkVisitCount = vi.fn((_domain: string, path: string) => (path === '/docs' ? 2 : 8));
const application: Application = { currentSnapshot: () => snapshot, linkVisitCount };
return {
locals: { snapshot, application },
@@ -52,339 +54,82 @@ function request(
} as Parameters<typeof load>[0];
}
function details(scope: ReportScope, counts: Record<string, [number, number]>): VisitDetails {
const daily = visitDays(period).map((day) => {
const [validVisits, invalidVisits] = counts[day.start.slice(0, 10)] ?? [0, 0];
return { ...day, validVisits, invalidVisits };
});
const browserOsCounts = daily
.filter(({ validVisits, invalidVisits }) => validVisits > 0 || invalidVisits > 0)
.map(({ start, validVisits, invalidVisits }) => ({
day: start.slice(0, 10),
name: 'Other',
validVisits,
invalidVisits
}));
const lastDay = Object.keys(counts).sort().at(-1);
return {
version: 5,
lastActivityAt: lastDay ? `${lastDay}T10:00:00.000Z` : null,
scope,
period,
daily,
browsers: browserOsCounts,
operatingSystems: browserOsCounts,
acceptedLanguages: browserOsCounts.flatMap((row) => [
{ ...row, name: 'en' },
{ ...row, name: 'fr' }
test('shows stored domain and link totals at zero retention but uses live counts for link limits', async () => {
vi.mocked(readDomainLifetimeVisitTotals).mockResolvedValueOnce({
domain: { validVisits: 15, invalidVisits: 4 },
byPath: new Map([
['/', { validVisits: 3, invalidVisits: 0 }],
['/docs', { validVisits: 1, invalidVisits: 0 }],
['/a%2Fb', { validVisits: 7, invalidVisits: 0 }]
])
};
}
});
const event = request();
const data = await load(event);
const domainDetails = details(
{ kind: 'domain', domain },
{
'2026-03-17': [4, 1],
'2026-05-16': [5, 4],
'2026-06-08': [3, 2],
'2026-06-09': [2, 1],
'2026-06-15': [5, 2]
}
);
const rootDetails = details(
{ kind: 'link', domain, path: '/' },
{
'2026-03-17': [4, 0],
'2026-06-08': [1, 0],
'2026-06-09': [1, 0],
'2026-06-15': [1, 0]
}
);
const docsDetails = details(
{ kind: 'link', domain, path: '/docs' },
{
'2026-05-16': [5, 1],
'2026-06-09': [1, 0],
'2026-06-15': [2, 0]
}
);
const emptyDetails = details({ kind: 'link', domain, path: '/a%2Fb' }, {});
const report = {
domain: domainDetails,
links: [
{ path: '/', details: rootDetails },
{ path: '/docs', details: docsDetails },
{
path: '/a/b',
details: { ...emptyDetails, scope: { kind: 'link' as const, domain, path: '/a/b' } }
},
{ path: '/a%2Fb', details: emptyDetails }
]
};
const rootCounts = {
'7d': { validVisits: 2, invalidVisits: 0 },
'30d': { validVisits: 3, invalidVisits: 0 },
all: { validVisits: 7, invalidVisits: 0 }
};
test('projects compact domain breakdowns without exposing link series or dated named counts', async () => {
vi.mocked(readDomainDetails).mockResolvedValue(report);
const data = await load(request());
expect(readDomainDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), domain, [
'/docs',
'/a/b',
'/a%2Fb'
]);
expect(data).toEqual({
expect(readDomainLifetimeVisitTotals).toHaveBeenCalledExactlyOnceWith(
expect.any(Object),
domain,
retentionMonths: 3,
collectionEnabled: true,
available: true,
lastActivityAt: Date.parse(domainDetails.lastActivityAt!),
linkCount: 3,
timeframes: ['7d', '30d', 'all'],
countsByTimeframe: {
'7d': { validVisits: 7, invalidVisits: 3 },
'30d': { validVisits: 10, invalidVisits: 5 },
all: { validVisits: 19, invalidVisits: 10 }
},
acceptedLanguageVisitsByTimeframe: {
'7d': [
{ name: 'en', visits: 7 },
{ name: 'fr', visits: 7 }
],
'30d': [
{ name: 'en', visits: 10 },
{ name: 'fr', visits: 10 }
],
all: [
{ name: 'en', visits: 19 },
{ name: 'fr', visits: 19 }
]
},
browserVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 7 }],
'30d': [{ name: 'Other', visits: 10 }],
all: [{ name: 'Other', visits: 19 }]
},
operatingSystemVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 7 }],
'30d': [{ name: 'Other', visits: 10 }],
all: [{ name: 'Other', visits: 19 }]
},
chart: { daily: domainDetails.daily, period },
root: null,
fallback: null,
links: [
{
path: '/',
url: null,
state: 'active',
countsByTimeframe: rootCounts,
href: '/admin/domains/go.example.test/links'
},
{
path: '/docs',
url: 'https://example.test/docs',
state: 'active',
countsByTimeframe: {
'7d': { validVisits: 3, invalidVisits: 0 },
'30d': { validVisits: 3, invalidVisits: 0 },
all: { validVisits: 8, invalidVisits: 1 }
},
href: '/admin/domains/go.example.test/links/docs'
},
{
path: '/a/b',
url: 'https://example.test/nested',
state: 'active',
countsByTimeframe: {
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 0, invalidVisits: 0 },
all: { validVisits: 0, invalidVisits: 0 }
},
href: '/admin/domains/go.example.test/links/a/b'
},
{
path: '/a%2Fb',
url: 'https://example.test/percent',
state: 'disabled',
countsByTimeframe: {
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 0, invalidVisits: 0 },
all: { validVisits: 0, invalidVisits: 0 }
},
href: '/admin/domains/go.example.test/links/a%252Fb'
}
]
});
});
test('keeps root and fallback responses separate and includes all normalized root history in valid domain visits', async () => {
vi.mocked(readDomainDetails).mockResolvedValue(report);
const root: RedirectResponse = {
url: 'https://example.test/start',
status_code: 307,
forward_query: true
};
const fallback: RedirectResponse = {
url: 'https://example.test/missing',
status_code: 308,
forward_query: false
};
const data = await load(
request(domain, {
root,
fallback,
globalFallback: { url: 'https://example.test/global', status_code: 302, forward_query: true }
})
['/docs', '/a%2Fb']
);
expect(data.root).toEqual(root);
expect(data.fallback).toEqual(fallback);
expect(data.links[0]).toEqual({
path: '/',
url: root.url,
state: 'active',
countsByTimeframe: rootCounts,
href: '/admin/domains/go.example.test/links'
expect(readLastActivity).not.toHaveBeenCalled();
expect(data).toMatchObject({
analyticsEnabled: false,
lastActivityAt: null,
linkCount: 2,
totalVisits: 15,
invalidClicks: 4,
root,
fallback
});
expect(data.countsByTimeframe.all).toEqual({ validVisits: 19, invalidVisits: 10 });
expect(data.linkCount).toBe(3);
expect(data.links.map(({ path }) => path)).toEqual(['/', '/docs', '/a/b', '/a%2Fb']);
});
test('keeps root reachable through the domain fallback with no named links', async () => {
vi.mocked(readDomainDetails).mockResolvedValue(report);
const fallback: RedirectResponse = {
url: 'https://example.test/missing',
status_code: 302,
forward_query: false
};
const data = await load(request(domain, { fallback, links: {} }));
expect(readDomainDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), domain, []);
expect(data.root).toBeNull();
expect(data.fallback).toEqual(fallback);
expect(data.linkCount).toBe(0);
expect(data.links).toEqual([
{
path: '/',
url: fallback.url,
url: root.url,
state: 'active',
countsByTimeframe: rootCounts,
href: '/admin/domains/go.example.test/links'
visits: 3,
href: `/admin/domains/${domain}/links`
},
{
path: '/docs',
url: 'https://example.test/docs',
state: 'disabled',
visits: 1,
href: `/admin/domains/${domain}/links/docs`
},
{
path: '/a%2Fb',
url: 'https://example.test/percent',
state: 'exhausted',
visits: 7,
href: `/admin/domains/${domain}/links/a%252Fb`
}
]);
expect(data.countsByTimeframe.all).toEqual({ validVisits: 19, invalidVisits: 10 });
expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith(2, domain, '/a%2Fb');
});
test('empty root history gives zero visits without hiding non-root invalid counts', async () => {
vi.mocked(readDomainDetails).mockResolvedValue({
...report,
links: report.links.map((link) =>
link.path === '/'
? {
path: '/',
details: { ...emptyDetails, scope: { kind: 'link' as const, domain, path: '/' } }
}
: link
)
});
const data = await load(request());
expect(data.available).toBe(true);
expect(data.links[0]).toEqual({
path: '/',
url: null,
state: 'active',
countsByTimeframe: {
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 0, invalidVisits: 0 },
all: { validVisits: 0, invalidVisits: 0 }
},
href: '/admin/domains/go.example.test/links'
});
expect(data.countsByTimeframe.all).toEqual({ validVisits: 19, invalidVisits: 10 });
test('rejects unknown domains before reading totals', async () => {
await expect(load(request({ host: 'unknown.test' }))).rejects.toMatchObject({ status: 404 });
expect(readDomainLifetimeVisitTotals).not.toHaveBeenCalled();
expect(readLastActivity).not.toHaveBeenCalled();
});
test('rejects unknown domains before reading and keeps unavailable inventory usable', async () => {
await expect(load(request('unknown.test'))).rejects.toMatchObject({ status: 404 });
expect(readDomainDetails).not.toHaveBeenCalled();
vi.mocked(readDomainDetails).mockResolvedValue(null);
const fallback: RedirectResponse = {
url: 'https://example.test/global',
status_code: 307,
forward_query: true
};
const data = await load(request(domain, { globalFallback: fallback }));
expect(data.root).toBeNull();
expect(data.fallback).toEqual(fallback);
expect(data.available).toBe(false);
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.links[0]).toEqual({
path: '/',
url: fallback.url,
state: 'active',
countsByTimeframe: {},
href: '/admin/domains/go.example.test/links'
});
expect(data.linkCount).toBe(3);
});
test('keeps fallback, inventory and scoped activity available when totals cannot be read', async () => {
const lastActivityAt = '2026-06-15T12:00:00.000Z';
vi.mocked(readDomainLifetimeVisitTotals).mockResolvedValueOnce(null);
vi.mocked(readLastActivity).mockResolvedValueOnce({ available: true, lastActivityAt });
const data = await load(request({ retentionMonths: 3, configureRoot: false }));
test.each([0, 3])(
'domain rows use canonical live counts with %i-month analytics',
async (retentionMonths) => {
vi.mocked(readDomainDetails).mockResolvedValue(report);
const event = request(domain, {
retentionMonths,
links: {
'/docs': { url: 'https://example.test/docs', enabled: false, max_visits: 2 },
'/a%2Fb': { url: 'https://example.test/percent', max_visits: 8 }
},
visits: { '/docs': 2, '/a%2Fb': 8 }
});
const data = await load(event);
expect(data.links.map(({ path, state, href }) => ({ path, state, href }))).toEqual([
{ path: '/', state: 'active', href: '/admin/domains/go.example.test/links' },
{ path: '/docs', state: 'disabled', href: '/admin/domains/go.example.test/links/docs' },
{ path: '/a%2Fb', state: 'exhausted', href: '/admin/domains/go.example.test/links/a%252Fb' }
]);
expect(event.locals.application.linkVisitCount).toHaveBeenCalledTimes(2);
expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith(1, domain, '/docs');
expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith(2, domain, '/a%2Fb');
}
);
test('disabled analytics preserves current inventory without reports', async () => {
const root: RedirectResponse = {
url: 'https://example.test/start',
status_code: 301,
forward_query: true
};
const fallback: RedirectResponse = {
url: 'https://example.test/missing',
status_code: 302,
forward_query: false
};
const data = await load(request(domain, { root, fallback, retentionMonths: 0 }));
expect(readDomainDetails).not.toHaveBeenCalled();
expect(data.collectionEnabled).toBe(false);
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.timeframes).toEqual([]);
expect(data.chart).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.root).toEqual(root);
expect(data.fallback).toEqual(fallback);
expect(data.links[0]).toEqual({
path: '/',
url: root.url,
state: 'active',
countsByTimeframe: {},
href: '/admin/domains/go.example.test/links'
expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), {
kind: 'domain',
domain
});
expect(data.linkCount).toBe(3);
expect(data).toMatchObject({
analyticsEnabled: true,
lastActivityAt: Date.parse(lastActivityAt),
root: null,
fallback,
totalVisits: null,
invalidClicks: null
});
expect(data.links[0]).toMatchObject({ path: '/', url: fallback.url, visits: null });
});
@@ -22,7 +22,7 @@
};
</script>
<AdminPage title="Health">
<AdminPage title="Health" analyticsEnabled={data.retentionMonths !== 0}>
<section class="admin-info" aria-labelledby="application-heading">
<h2 id="application-heading">Application</h2>
<dl>
@@ -1,269 +1,87 @@
import { loadConfig } from '@goto/config';
import {
createVisitPeriod,
visitDays,
type ReportPeriod,
type ReportScope,
type VisitDetails
} from '@goto/analytics';
import { beforeEach, expect, test, vi } from 'vitest';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readOverviewDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { readOverviewLifetimeVisitTotals } from '#lib/server/visits/totals.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({ readOverviewDetails: vi.fn() }));
vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() }));
vi.mock('#lib/server/visits/totals.js', () => ({ readOverviewLifetimeVisitTotals: vi.fn() }));
beforeEach(() => vi.resetAllMocks());
const domain = 'go.example.test';
const emptyDomain = 'empty.example.test';
const newDomain = 'new.example.test';
function request(retention_months = 3) {
const prepared = loadConfig(
{
auth: { credentials: { username: 'test', password: 'overview-test-password' } },
analytics: { retention_months },
domains: {
[domain]: {
links: {
'/docs': { url: 'https://example.test/docs' },
'/disabled': { url: 'https://example.test/disabled', enabled: false }
}
},
[emptyDomain]: { root: { url: 'https://example.test/' }, links: {} },
[newDomain]: { links: { '/new': { url: 'https://example.test/new' } } }
}
},
{ env: {} }
);
return { locals: { snapshot: prepareSnapshot(prepared) } } as Parameters<typeof load>[0];
}
function details(
scope: ReportScope,
period: ReportPeriod,
validVisits: (day: string) => number
): VisitDetails {
const daily = visitDays(period).map((day) => ({
...day,
validVisits: validVisits(day.start.slice(0, 10)),
invalidVisits: 1
}));
const browserOsCounts = daily
.filter(({ validVisits, invalidVisits }) => validVisits > 0 || invalidVisits > 0)
.map(({ start, validVisits, invalidVisits }) => ({
day: start.slice(0, 10),
name: 'Other',
validVisits,
invalidVisits
}));
return {
version: 5,
lastActivityAt: new Date(Date.parse(period.asOf) - 60_000).toISOString(),
scope,
period,
daily,
browsers: browserOsCounts,
operatingSystems: browserOsCounts,
acceptedLanguages: browserOsCounts.flatMap((row) => [
{ ...row, name: 'en' },
{ ...row, name: 'fr' }
])
};
}
test('projects compact global window counts while inventory stays current and history stays retained', async () => {
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const overviewCounts: Record<string, number> = {
'2026-03-17': 13,
'2026-04-01': 11,
'2026-05-16': 7,
'2026-05-17': 5,
'2026-06-08': 3,
'2026-06-09': 2,
'2026-06-15': 1
};
const domainCounts: Record<string, number> = {
'2026-03-17': 4,
'2026-05-16': 3,
'2026-05-17': 2,
'2026-06-08': 1,
'2026-06-09': 1,
'2026-06-15': 1
};
const overview = details({ kind: 'overview' }, period, (day) => overviewCounts[day] ?? 0);
const current = details({ kind: 'domain', domain }, period, (day) => domainCounts[day] ?? 0);
const empty = details({ kind: 'domain', domain: emptyDomain }, period, () => 0);
const newDomainDetails: VisitDetails = {
...empty,
scope: { kind: 'domain', domain: newDomain },
lastActivityAt: null,
daily: empty.daily.map((day) => ({ ...day, validVisits: 0, invalidVisits: 0 })),
browsers: [],
operatingSystems: [],
acceptedLanguages: []
};
vi.mocked(readOverviewDetails).mockResolvedValue({
overview,
domains: [
{ domain, details: current },
{ domain: emptyDomain, details: empty },
{ domain: newDomain, details: newDomainDetails }
]
});
const data = await load(request());
expect(readOverviewDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
domain,
emptyDomain,
newDomain
]);
expect(data).toEqual({
collectionEnabled: true,
available: true,
retentionMonths: 3,
lastActivityAt: Date.parse(overview.lastActivityAt!),
domainCount: 3,
linkCount: 3,
timeframes: ['7d', '30d', 'all'],
countsByTimeframe: {
'7d': { validVisits: 3, invalidVisits: 7 },
'30d': { validVisits: 11, invalidVisits: 30 },
all: { validVisits: 42, invalidVisits: 91 }
},
browserVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 3 }],
'30d': [{ name: 'Other', visits: 11 }],
all: [{ name: 'Other', visits: 42 }]
},
operatingSystemVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 3 }],
'30d': [{ name: 'Other', visits: 11 }],
all: [{ name: 'Other', visits: 42 }]
},
acceptedLanguageVisitsByTimeframe: {
'7d': [
{ name: 'en', visits: 3 },
{ name: 'fr', visits: 3 }
],
'30d': [
{ name: 'en', visits: 11 },
{ name: 'fr', visits: 11 }
],
all: [
{ name: 'en', visits: 42 },
{ name: 'fr', visits: 42 }
]
},
chart: { daily: overview.daily, period },
domains: [
function request(retentionMonths: 0 | 3) {
const snapshot = prepareSnapshot(
loadConfig(
{
domain,
linkCount: 2,
countsByTimeframe: {
'7d': { validVisits: 2, invalidVisits: 7 },
'30d': { validVisits: 5, invalidVisits: 30 },
all: { validVisits: 12, invalidVisits: 91 }
},
href: '/admin/domains/go.example.test'
auth: { credentials: { username: 'test', password: 'overview-test-password' } },
analytics: { retention_months: retentionMonths },
domains: {
[domain]: {
links: {
'/docs': { url: 'https://example.test/docs' },
'/disabled': { url: 'https://example.test/disabled', enabled: false }
}
},
[emptyDomain]: { root: { url: 'https://example.test/' }, links: {} }
}
},
{ env: {} }
)
);
return { locals: { snapshot } } as Parameters<typeof load>[0];
}
test('shows all-time totals and current inventory even when detailed analytics is disabled', async () => {
vi.mocked(readOverviewLifetimeVisitTotals).mockResolvedValueOnce({
overview: { validVisits: 40, invalidVisits: 7 },
byDomain: new Map([
[domain, { validVisits: 12, invalidVisits: 2 }],
[emptyDomain, { validVisits: 0, invalidVisits: 0 }]
])
});
const data = await load(request(0));
expect(readOverviewLifetimeVisitTotals).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
domain,
emptyDomain
]);
expect(readLastActivity).not.toHaveBeenCalled();
expect(data).toEqual({
analyticsEnabled: false,
lastActivityAt: null,
domainCount: 2,
linkCount: 2,
totalVisits: 40,
domains: [
{ domain, linkCount: 2, totalVisits: 12, href: '/admin/domains/go.example.test' },
{
domain: emptyDomain,
linkCount: 0,
countsByTimeframe: {
'7d': { validVisits: 0, invalidVisits: 7 },
'30d': { validVisits: 0, invalidVisits: 30 },
all: { validVisits: 0, invalidVisits: 91 }
},
totalVisits: 0,
href: '/admin/domains/empty.example.test'
},
{
domain: newDomain,
linkCount: 1,
countsByTimeframe: {
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 0, invalidVisits: 0 },
all: { validVisits: 0, invalidVisits: 0 }
},
href: '/admin/domains/new.example.test'
}
]
});
});
test.each([
{ months: 9 as const, retainedDays: 270 },
{ months: 12 as const, retainedDays: 360 }
])(
'offers four windows for $months months anchored to the latest included day',
async ({ months, retainedDays }) => {
const period = createVisitPeriod(months, Date.parse('2026-03-01T00:00:00.000Z'));
const overview = details({ kind: 'overview' }, period, () => 1);
vi.mocked(readOverviewDetails).mockResolvedValue({
overview,
domains: [domain, emptyDomain, newDomain].map((domain) => ({
domain,
details: {
...overview,
scope: { kind: 'domain' as const, domain },
lastActivityAt: null,
daily: overview.daily.map((day) => ({ ...day, validVisits: 0, invalidVisits: 0 })),
browsers: [],
operatingSystems: [],
acceptedLanguages: []
}
}))
});
const data = await load(request(months));
if (!data) throw new Error('Missing overview page');
expect(data.timeframes).toEqual(['7d', '30d', '90d', 'all']);
expect(data.countsByTimeframe).toEqual({
'7d': { validVisits: 7, invalidVisits: 7 },
'30d': { validVisits: 30, invalidVisits: 30 },
'90d': { validVisits: 90, invalidVisits: 90 },
all: { validVisits: retainedDays, invalidVisits: retainedDays }
});
expect(data.domains.map((row) => row.countsByTimeframe)).toEqual(
Array.from({ length: 3 }, () => ({
'7d': { validVisits: 0, invalidVisits: 0 },
'30d': { validVisits: 0, invalidVisits: 0 },
'90d': { validVisits: 0, invalidVisits: 0 },
all: { validVisits: 0, invalidVisits: 0 }
}))
);
}
);
test('keeps the inventory and last activity when stored totals are unavailable', async () => {
const lastActivityAt = '2026-06-15T12:00:00.000Z';
vi.mocked(readOverviewLifetimeVisitTotals).mockResolvedValueOnce(null);
vi.mocked(readLastActivity).mockResolvedValueOnce({ available: true, lastActivityAt });
test('unavailable storage keeps inventory usable without substituting zero counts', async () => {
vi.mocked(readOverviewDetails).mockResolvedValue(null);
const data = await load(request());
if (!data) throw new Error('Missing unavailable page');
expect(data.available).toBe(false);
expect(data.collectionEnabled).toBe(true);
expect(data.retentionMonths).toBe(3);
expect(data.domainCount).toBe(3);
expect(data.linkCount).toBe(3);
expect(data.lastActivityAt).toBeNull();
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.domains.map((row) => row.countsByTimeframe)).toEqual([{}, {}, {}]);
});
const data = await load(request(3));
test('disabled analytics keeps inventory while skipping reports', async () => {
const data = await load(request(0));
if (!data) throw new Error('Missing disabled page');
expect(data.collectionEnabled).toBe(false);
expect(data.available).toBe(false);
expect(data.domainCount).toBe(3);
expect(data.linkCount).toBe(3);
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.timeframes).toEqual([]);
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.domains.map((row) => row.countsByTimeframe)).toEqual([{}, {}, {}]);
expect(readOverviewDetails).not.toHaveBeenCalled();
expect(data).toMatchObject({
analyticsEnabled: true,
totalVisits: null,
lastActivityAt: Date.parse(lastActivityAt)
});
expect(data.domains).toMatchObject([
{ domain, linkCount: 2, totalVisits: null },
{ domain: emptyDomain, linkCount: 0, totalVisits: null }
]);
});
@@ -1,77 +1,38 @@
import { error } from '@sveltejs/kit';
import { countBreakdownVisitsByTimeframe, type VisitDetails } from '@goto/analytics';
import { availableVisitTimeframes, countVisitWindows, visitWindow } from '@goto/analytics/daily';
import { linkHref } from '#lib/components/admin/urls.js';
import { currentLinkState } from '#lib/server/link-state.js';
import { tagMembers } from '#lib/server/tags/inventory.js';
import { combineTagVisits } from '#lib/server/tags/visits.js';
import { readLinkDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import type { PageServerLoad } from './$types';
export const load = (async ({ locals, params }) => {
const snapshot = locals.snapshot;
const tag = params.tag;
const members = tagMembers(snapshot.domains, tag);
if (members.length === 0) throw error(404, 'Tag not configured');
const now = Date.now();
if (members.length === 0) error(404, 'Tag not configured');
const configuration = snapshot.configuration;
const retentionMonths = configuration.analytics.retention_months;
const collectionEnabled = retentionMonths !== 0;
const identities = members.map(({ domain, path }) => ({ domain, path }));
const report = collectionEnabled ? await readLinkDetails(configuration, identities) : null;
const tagDetails = report ? combineTagVisits(report) : null;
const timeframes = retentionMonths === 0 ? [] : availableVisitTimeframes(retentionMonths);
const windows = tagDetails
? timeframes.map((timeframe) => ({
timeframe,
window: visitWindow(tagDetails.period, timeframe)
}))
: [];
const countsByTimeframe = countVisitWindows(tagDetails?.daily, windows);
const browserVisitsByTimeframe = countBreakdownVisitsByTimeframe(tagDetails?.browsers, windows);
const operatingSystemVisitsByTimeframe = countBreakdownVisitsByTimeframe(
tagDetails?.operatingSystems,
windows
);
const acceptedLanguageVisitsByTimeframe = countBreakdownVisitsByTimeframe(
tagDetails?.acceptedLanguages,
windows
);
const detailsByDomain = new Map<string, Map<string, VisitDetails>>();
for (const { domain, path, details } of report?.links ?? []) {
let domainDetails = detailsByDomain.get(domain);
if (!domainDetails) {
domainDetails = new Map();
detailsByDomain.set(domain, domainDetails);
}
domainDetails.set(path, details);
}
const analyticsEnabled = configuration.analytics.retention_months !== 0;
const activity = analyticsEnabled
? await readLastActivity(
configuration,
members.map(({ domain, path }) => ({ kind: 'link' as const, domain, path }))
)
: null;
const now = Date.now();
const links = members.map(({ domain, path, link }) => {
const daily = detailsByDomain.get(domain)?.get(path)?.daily;
const countsByTimeframe = countVisitWindows(daily, windows);
const visits = locals.application.linkVisitCount(domain, path);
return {
domain,
path,
state: currentLinkState(link, now, locals.application.linkVisitCount(domain, path)),
countsByTimeframe,
state: currentLinkState(link, now, visits),
visits,
href: linkHref(domain, path)
};
});
const lastActivityAt = tagDetails?.lastActivityAt ? Date.parse(tagDetails.lastActivityAt) : null;
const chart = tagDetails ? { daily: tagDetails.daily, period: tagDetails.period } : null;
return {
tag,
retentionMonths,
collectionEnabled,
available: tagDetails !== null,
lastActivityAt,
linkCount: members.length,
timeframes,
countsByTimeframe,
browserVisitsByTimeframe,
operatingSystemVisitsByTimeframe,
acceptedLanguageVisitsByTimeframe,
chart,
links
};
const domainCount = new Set(links.map(({ domain }) => domain)).size;
const totalVisits = links.reduce((total, { visits }) => total + visits, 0);
const lastActivityAt = activity?.lastActivityAt ? Date.parse(activity.lastActivityAt) : null;
return { tag, analyticsEnabled, lastActivityAt, domainCount, totalVisits, links };
}) satisfies PageServerLoad;
@@ -1,75 +1,51 @@
<script lang="ts">
import { page } from '$app/state';
import { resolveVisitTimeframe, visitGranularity, visitWindow } from '@goto/analytics/daily';
import AdminPage from '#lib/components/admin/AdminPage.svelte';
import AnalyticsSection from '#lib/components/admin/AnalyticsSection.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import ReportNotice from '#lib/components/admin/ReportNotice.svelte';
import VisitBreakdowns from '#lib/components/admin/VisitBreakdowns.svelte';
import VisitsChart from '#lib/components/admin/VisitsChart.svelte';
import VisitTimeframes from '#lib/components/admin/VisitTimeframes.svelte';
import AnalyticsField from '#lib/components/admin/AnalyticsField.svelte';
import LinkInventory from '#lib/components/admin/LinkInventory.svelte';
import StatCard from '#lib/components/admin/StatCard.svelte';
import type { PageData } from './$types';
let { data }: { data: PageData } = $props();
let currentUrl = $derived(page.shallow?.url ?? page.url);
let timeframe = $derived(
resolveVisitTimeframe(data.timeframes, currentUrl.searchParams.get('period'))
);
let window = $derived(data.chart ? visitWindow(data.chart.period, timeframe) : null);
let granularity = $derived(
data.chart ? visitGranularity(timeframe, data.chart.period.retentionMonths) : 'day'
);
let visits = $derived(data.countsByTimeframe[timeframe]?.validVisits ?? null);
let invalidClicks = $derived(data.countsByTimeframe[timeframe]?.invalidVisits ?? null);
let browserVisits = $derived(data.browserVisitsByTimeframe[timeframe] ?? null);
let operatingSystemVisits = $derived(data.operatingSystemVisitsByTimeframe[timeframe] ?? null);
let acceptedLanguageVisits = $derived(data.acceptedLanguageVisitsByTimeframe[timeframe] ?? null);
</script>
<AdminPage
title={`Tag: ${data.tag}`}
analyticsEnabled={data.analyticsEnabled}
title="Tag"
documentTitle={`Tag: ${data.tag}`}
lastActivityAt={data.lastActivityAt}
overviewHref={`/admin?period=${timeframe}`}
>
{#snippet actions()}
{#if data.available && data.timeframes.length > 0}
<VisitTimeframes
timeframes={data.timeframes}
retentionMonths={data.retentionMonths}
value={timeframe}
/>
{/if}
{/snippet}
<section aria-labelledby="summary-heading">
<h2 id="summary-heading">Summary</h2>
<div class="admin-cards">
<StatCard label="Domains" value={data.domainCount} />
<StatCard label="Links" value={data.links.length} />
<StatCard label="Total Visits" value={data.totalVisits} />
</div>
</section>
<section aria-labelledby="tag-details-heading">
<h2 id="tag-details-heading">Details</h2>
<div class="admin-info">
<dl>
<dt>Tag Name</dt>
<dd class="tag-name">{data.tag}</dd>
{#if data.analyticsEnabled}
<AnalyticsField scope={{ kind: 'tag', tag: data.tag }} />
{/if}
</dl>
</div>
</section>
<section>
<h2>Links</h2>
<LinkInventory
label={`Links tagged ${data.tag}`}
links={data.links}
{timeframe}
collectionEnabled={data.collectionEnabled}
visitLabel="Total Visits"
showDomain
/>
</section>
<AnalyticsSection>
<ReportNotice collectionEnabled={data.collectionEnabled} available={data.available} />
<div class="admin-cards">
<StatCard label="Links" value={data.linkCount} />
{#if data.collectionEnabled}
<StatCard label="Visits" value={visits} />
<StatCard label="Invalid clicks" value={invalidClicks} />
{/if}
</div>
{#if data.chart && window}
<VisitsChart daily={data.chart.daily} {window} {granularity} />
{/if}
{#if browserVisits && operatingSystemVisits && acceptedLanguageVisits && visits !== null}
<VisitBreakdowns
{browserVisits}
{operatingSystemVisits}
{acceptedLanguageVisits}
totalVisits={visits}
/>
{/if}
</AnalyticsSection>
</AdminPage>
<style>
.tag-name {
white-space: break-spaces;
}
</style>
@@ -1,58 +1,54 @@
import { createVisitPeriod, visitDays, type VisitDetails } from '@goto/analytics';
import { loadConfig } from '@goto/config';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import { beforeEach, expect, test, vi } from 'vitest';
import type { Application } from '#lib/server/application.js';
import { prepareSnapshot } from '#lib/server/snapshot.js';
import { readLinkDetails } from '#lib/server/visits/reports.js';
import { readLastActivity } from '#lib/server/visits/reports.js';
import { load } from './+page.server.js';
vi.mock('#lib/server/visits/reports.js', () => ({ readLinkDetails: vi.fn() }));
vi.mock('#lib/server/visits/reports.js', () => ({ readLastActivity: vi.fn() }));
beforeEach(() => {
vi.resetAllMocks();
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-06-15T13:00:00.000Z'));
vi.mocked(readLastActivity).mockResolvedValue({ available: false, lastActivityAt: null });
});
afterEach(() => vi.useRealTimers());
const tag = 'Work/100%é';
const firstDomain = 'go.example.test';
const secondDomain = 'tiny.example.test';
const period = createVisitPeriod(3, Date.parse('2026-06-15T12:00:00.000Z'));
const domains = {
[firstDomain]: {
root: { url: 'https://example.test/start' },
links: {
'/docs': { url: 'https://example.test/docs', tags: [tag, tag, 'work'] },
'/a%2Fb': { url: 'https://example.test/percent', tags: ['%2F'], enabled: false }
}
},
[secondDomain]: {
links: {
'/docs': { url: 'https://example.test/other', tags: [tag], enabled: false },
'/other': { url: 'https://example.test/unrelated', tags: [] }
}
}
const visitsByDomain: Record<string, Record<string, number>> = {
[firstDomain]: { '/docs': 100, '/guide': 3, '/a%2Fb': 4 },
[secondDomain]: { '/docs': 6, '/other': 200 }
};
function request(
function request({
selectedTag = tag,
settings: {
retentionMonths?: number;
domains?: Record<string, unknown>;
visits?: Record<string, Record<string, number>>;
} = {}
) {
retentionMonths = 3,
firstLinkTags = [tag, tag, 'work']
}: { selectedTag?: string; retentionMonths?: 0 | 3; firstLinkTags?: string[] } = {}) {
const prepared = loadConfig(
{
auth: { credentials: { username: 'test', password: 'tag-page-test-password' } },
analytics: { retention_months: settings.retentionMonths ?? 3 },
domains: settings.domains ?? domains
analytics: { retention_months: retentionMonths },
domains: {
[firstDomain]: {
links: {
'/docs': { url: 'https://example.test/docs', tags: firstLinkTags, max_visits: 100 },
'/guide': { url: 'https://example.test/guide', tags: [tag] },
'/a%2Fb': { url: 'https://example.test/percent', tags: ['%2F'], enabled: false }
}
},
[secondDomain]: {
links: {
'/docs': { url: 'https://example.test/other', tags: [tag], max_visits: 100 },
'/other': { url: 'https://example.test/unrelated' }
}
}
}
},
{ env: {} }
);
const snapshot = prepareSnapshot(prepared);
const linkVisitCount = vi.fn(
(domain: string, path: string): number => settings.visits?.[domain]?.[path] ?? 0
(domain: string, path: string) => visitsByDomain[domain]?.[path] ?? 0
);
const application: Application = { currentSnapshot: () => snapshot, linkVisitCount };
return {
@@ -61,265 +57,88 @@ function request(
} as Parameters<typeof load>[0];
}
function details(
domain: string,
path: string,
counts: Record<string, [number, number]>,
browser: string
): VisitDetails {
const daily = visitDays(period).map((day) => {
const [validVisits, invalidVisits] = counts[day.start.slice(0, 10)] ?? [0, 0];
return { ...day, validVisits, invalidVisits };
});
const browsers = daily
.filter(({ validVisits, invalidVisits }) => validVisits > 0 || invalidVisits > 0)
.map(({ start, validVisits, invalidVisits }) => ({
day: start.slice(0, 10),
name: browser,
validVisits,
invalidVisits
}));
const lastDay = Object.keys(counts).sort().at(-1);
return {
version: 5,
lastActivityAt: lastDay ? `${lastDay}T10:00:00.000Z` : null,
scope: { kind: 'link', domain, path },
period,
daily,
browsers,
operatingSystems: browsers.map((row) => ({ ...row, name: 'Other' })),
acceptedLanguages: browsers.flatMap((row) => [
{ ...row, name: 'en' },
{ ...row, name: 'fr' }
])
};
}
test('uses each current link lifetime count once for the summary, inventory, and status', async () => {
const lastActivityAt = '2026-06-15T10:00:00.000Z';
vi.mocked(readLastActivity).mockResolvedValue({ available: true, lastActivityAt });
const event = request();
const data = await load(event);
const firstDetails = details(
firstDomain,
'/docs',
{
'2026-05-20': [2, 1],
'2026-06-15': [3, 2]
},
'Firefox'
);
const secondDetails = details(
secondDomain,
'/docs',
{
'2026-03-17': [5, 3],
'2026-06-09': [4, 1]
},
'Chrome'
);
const report = {
period,
links: [
{ domain: firstDomain, path: '/docs', details: firstDetails },
{ domain: secondDomain, path: '/docs', details: secondDetails }
]
};
test('projects complete tag traffic and globally distinct member rows without leaking member series', async () => {
vi.mocked(readLinkDetails).mockResolvedValue(report);
const data = await load(request());
expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
{ domain: firstDomain, path: '/docs' },
{ domain: secondDomain, path: '/docs' }
]);
expect(data).toEqual({
tag,
retentionMonths: 3,
collectionEnabled: true,
available: true,
lastActivityAt: Date.parse(firstDetails.lastActivityAt!),
linkCount: 2,
timeframes: ['7d', '30d', 'all'],
countsByTimeframe: {
'7d': { validVisits: 7, invalidVisits: 3 },
'30d': { validVisits: 9, invalidVisits: 4 },
all: { validVisits: 14, invalidVisits: 7 }
},
acceptedLanguageVisitsByTimeframe: {
'7d': [
{ name: 'en', visits: 7 },
{ name: 'fr', visits: 7 }
],
'30d': [
{ name: 'en', visits: 9 },
{ name: 'fr', visits: 9 }
],
all: [
{ name: 'en', visits: 14 },
{ name: 'fr', visits: 14 }
]
},
browserVisitsByTimeframe: {
'7d': [
{ name: 'Chrome', visits: 4 },
{ name: 'Firefox', visits: 3 }
],
'30d': [
{ name: 'Firefox', visits: 5 },
{ name: 'Chrome', visits: 4 }
],
all: [
{ name: 'Chrome', visits: 9 },
{ name: 'Firefox', visits: 5 }
]
},
operatingSystemVisitsByTimeframe: {
'7d': [{ name: 'Other', visits: 7 }],
'30d': [{ name: 'Other', visits: 9 }],
all: [{ name: 'Other', visits: 14 }]
},
chart: { period, daily: expect.any(Array) },
analyticsEnabled: true,
lastActivityAt: Date.parse(lastActivityAt),
domainCount: 2,
totalVisits: 109,
links: [
{
domain: firstDomain,
path: '/docs',
state: 'active',
countsByTimeframe: {
'7d': { validVisits: 3, invalidVisits: 2 },
'30d': { validVisits: 5, invalidVisits: 3 },
all: { validVisits: 5, invalidVisits: 3 }
},
state: 'exhausted',
visits: 100,
href: '/admin/domains/go.example.test/links/docs'
},
{
domain: firstDomain,
path: '/guide',
state: 'active',
visits: 3,
href: '/admin/domains/go.example.test/links/guide'
},
{
domain: secondDomain,
path: '/docs',
state: 'disabled',
countsByTimeframe: {
'7d': { validVisits: 4, invalidVisits: 1 },
'30d': { validVisits: 4, invalidVisits: 1 },
all: { validVisits: 9, invalidVisits: 4 }
},
state: 'active',
visits: 6,
href: '/admin/domains/tiny.example.test/links/docs'
}
]
});
expect(data.chart?.daily).toHaveLength(visitDays(period).length);
expect(data.chart?.daily.at(-1)).toMatchObject({
validVisits: 3,
invalidVisits: 2,
partial: true
});
expect(vi.mocked(event.locals.application.linkVisitCount).mock.calls).toEqual([
[firstDomain, '/docs'],
[firstDomain, '/guide'],
[secondDomain, '/docs']
]);
expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
{ kind: 'link', domain: firstDomain, path: '/docs' },
{ kind: 'link', domain: firstDomain, path: '/guide' },
{ kind: 'link', domain: secondDomain, path: '/docs' }
]);
});
test('current membership reassigns unchanged prepared history without tag-specific reports', async () => {
vi.mocked(readLinkDetails).mockResolvedValue({ period, links: [report.links[1]!] });
const data = await load(
request(tag, {
domains: {
[firstDomain]: {
links: { '/docs': { url: 'https://example.test/docs', tags: ['Different'] } }
},
[secondDomain]: domains[secondDomain]
test('keeps current-member totals when retained activity is unavailable', async () => {
const data = await load(request({ firstLinkTags: ['Different'] }));
expect(data.totalVisits).toBe(9);
expect(data.lastActivityAt).toBeNull();
expect(readLastActivity).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
{ kind: 'link', domain: firstDomain, path: '/guide' },
{ kind: 'link', domain: secondDomain, path: '/docs' }
]);
});
test('keeps literal percent identities and shows lifetime visits at zero retention', async () => {
const data = await load(request({ selectedTag: '%2F', retentionMonths: 0 }));
expect(readLastActivity).not.toHaveBeenCalled();
expect(data).toEqual({
tag: '%2F',
analyticsEnabled: false,
lastActivityAt: null,
domainCount: 1,
totalVisits: 4,
links: [
{
domain: firstDomain,
path: '/a%2Fb',
state: 'disabled',
visits: 4,
href: '/admin/domains/go.example.test/links/a%252Fb'
}
})
);
expect(readLinkDetails).toHaveBeenCalledExactlyOnceWith(expect.any(Object), [
{ domain: secondDomain, path: '/docs' }
]);
expect(data.linkCount).toBe(1);
expect(data.lastActivityAt).toBe(Date.parse(secondDetails.lastActivityAt!));
expect(data.countsByTimeframe.all).toEqual({ validVisits: 9, invalidVisits: 4 });
expect(data.links.map(({ domain, path }) => ({ domain, path }))).toEqual([
{ domain: secondDomain, path: '/docs' }
]);
});
test('uses the already decoded literal parameter without decoding percent escapes again', async () => {
const percentDetails = details(firstDomain, '/a%2Fb', {}, 'Other');
vi.mocked(readLinkDetails).mockResolvedValue({
period,
links: [{ domain: firstDomain, path: '/a%2Fb', details: percentDetails }]
]
});
const event = request('%2F');
const data = await load(event);
expect(event.locals.application.linkVisitCount).toHaveBeenCalledExactlyOnceWith(
firstDomain,
'/a%2Fb'
);
expect(data.tag).toBe('%2F');
expect(data.lastActivityAt).toBeNull();
expect(data.countsByTimeframe.all).toEqual({ validVisits: 0, invalidVisits: 0 });
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({ '7d': [], '30d': [], all: [] });
expect(data.links[0]?.href).toBe('/admin/domains/go.example.test/links/a%252Fb');
});
test('unknown literal labels return 404 before reading reports', async () => {
await expect(load(request('work/100%é'))).rejects.toMatchObject({ status: 404 });
expect(readLinkDetails).not.toHaveBeenCalled();
});
test('unavailable reports preserve all current members but expose no partial traffic', async () => {
vi.mocked(readLinkDetails).mockResolvedValue(null);
const data = await load(request());
expect(data.available).toBe(false);
expect(data.lastActivityAt).toBeNull();
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.linkCount).toBe(2);
expect(data.links.map(({ countsByTimeframe }) => countsByTimeframe)).toEqual([{}, {}]);
expect(data.links.map(({ href }) => href)).toEqual([
'/admin/domains/go.example.test/links/docs',
'/admin/domains/tiny.example.test/links/docs'
]);
});
test.each([0, 3])(
'tag rows use domain-specific live counts with %i-month analytics',
async (retentionMonths) => {
vi.mocked(readLinkDetails).mockResolvedValue(report);
const event = request(tag, {
retentionMonths,
domains: {
[firstDomain]: {
links: { '/docs': { url: 'https://example.test/docs', tags: [tag], max_visits: 100 } }
},
[secondDomain]: {
links: { '/docs': { url: 'https://example.test/other', tags: [tag], max_visits: 100 } }
}
},
visits: { [firstDomain]: { '/docs': 100 }, [secondDomain]: { '/docs': 3 } }
});
const data = await load(event);
expect(data.links.map(({ domain, path, state }) => ({ domain, path, state }))).toEqual([
{ domain: firstDomain, path: '/docs', state: 'exhausted' },
{ domain: secondDomain, path: '/docs', state: 'active' }
]);
expect(event.locals.application.linkVisitCount).toHaveBeenCalledTimes(2);
expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith(
1,
firstDomain,
'/docs'
);
expect(event.locals.application.linkVisitCount).toHaveBeenNthCalledWith(
2,
secondDomain,
'/docs'
);
}
);
test('zero retention skips the report reader and keeps tag inventory without traffic controls', async () => {
const data = await load(request(tag, { retentionMonths: 0 }));
expect(readLinkDetails).not.toHaveBeenCalled();
expect(data.collectionEnabled).toBe(false);
expect(data.available).toBe(false);
expect(data.lastActivityAt).toBeNull();
expect(data.timeframes).toEqual([]);
expect(data.countsByTimeframe).toEqual({});
expect(data.acceptedLanguageVisitsByTimeframe).toEqual({});
expect(data.browserVisitsByTimeframe).toEqual({});
expect(data.operatingSystemVisitsByTimeframe).toEqual({});
expect(data.chart).toBeNull();
expect(data.linkCount).toBe(2);
expect(data.links.map(({ countsByTimeframe }) => countsByTimeframe)).toEqual([{}, {}]);
test('rejects unknown literal labels before reading visits or activity', async () => {
const event = request({ selectedTag: 'work/100%é' });
await expect(load(event)).rejects.toMatchObject({ status: 404 });
expect(readLastActivity).not.toHaveBeenCalled();
expect(event.locals.application.linkVisitCount).not.toHaveBeenCalled();
});
+7 -1
View File
@@ -7,7 +7,13 @@ import type { Database } from './types.js';
export { runMigrations } from './migrate.js';
export { insertVisit, purgeVisits } from './visits.js';
export { addVisitTotals, readVisitTotals, readLinkVisitCounts } from './visit-totals.js';
export {
addVisitTotals,
readVisitTotals,
readOverviewVisitTotals,
readDomainVisitTotals,
readLinkVisitCounts
} from './visit-totals.js';
export {
captureVisitBoundary,
processVisitBatch,
+1 -8
View File
@@ -3,15 +3,8 @@ export {
subtractDailyVisitStatistics,
deleteExpiredDailyStatistics,
clearDailyVisitStatistics,
readOverviewVisitDetails,
readDomainVisitDetails,
readLinkVisitDetails,
readVisitDetails,
readLastVisitActivity
} from './storage.js';
export type {
DailyStatisticsMismatch,
OverviewVisitDetails,
DomainVisitDetails,
LinkVisitDetails
} from './storage.js';
export type { DailyStatisticsMismatch, LinkVisitDetails } from './storage.js';
+14 -55
View File
@@ -16,8 +16,6 @@ import {
clearDailyVisitStatistics,
deleteExpiredDailyStatistics,
readVisitDetails,
readOverviewVisitDetails,
readDomainVisitDetails,
readLinkVisitDetails,
readLastVisitActivity
} from './storage.js';
@@ -242,58 +240,17 @@ test('daily writes and raw processing share caller rollback, with no independent
expect(await db.selectFrom('visits').select('processed').execute()).toEqual([{ processed: 0 }]);
});
test('overview selects only current domains in one SQL read and derives zeros for new scopes', async () => {
const overview = daily(overviewScope, 8, 2);
const current = daily(domainScope, 3, 1);
await add(
overview,
current,
daily(rootScope),
daily({ kind: 'domain', domain: 'removed.example.test' })
);
await db
.updateTable('visit_daily_statistics')
.set({ browsers_json: '["private malformed cache"]' })
.where(({ or, eb }) =>
or([eb('scope_kind', '=', 'link'), eb('domain', '=', 'removed.example.test')])
)
.execute();
const before = await db.selectFrom('visit_daily_statistics').selectAll().execute();
const statements = vi.spyOn(DatabaseSync.prototype, 'prepare');
try {
expect(
await readOverviewVisitDetails(db, [domain, domain, 'new.example.test'], period)
).toEqual({
overview: projectVisitDetails(overviewScope, period, [overview]),
domains: [
{ domain, details: projectVisitDetails(domainScope, period, [current]) },
{
domain: 'new.example.test',
details: projectVisitDetails({ kind: 'domain', domain: 'new.example.test' }, period, [])
}
]
});
expect(statements).toHaveBeenCalledTimes(1);
const query = statements.mock.calls[0]![0];
expect(query).toContain('domain IN');
expect(query).not.toMatch(/\bvisits\b|\bjoin\b|\bsum\s*\(/i);
} finally {
statements.mockRestore();
}
expect(await db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual(before);
});
test('domain and selected-link readers bind exact path/domain pairs, include Root, and ignore distractors', async () => {
test('selected-link readers bind exact path/domain pairs and ignore distractors', async () => {
const path = "/' OR 1=1 --";
const link = { kind: 'link', domain, path } as const;
const other = { kind: 'link', domain: 'other.example.test', path: '/faq' } as const;
await add(
daily(domainScope, 6, 2),
daily(rootScope, 1),
daily(link, 5),
daily(other, 7),
daily({ kind: 'link', domain, path: '/faq' }, 99),
daily({ kind: 'link', domain: 'other.example.test', path }, 99)
daily(link, 5, 0, 11),
daily(other, 7, 0, 12),
daily({ kind: 'link', domain, path: '/faq' }, 99, 0, 13),
daily({ kind: 'link', domain: 'other.example.test', path }, 99, 0, 14)
);
await db
.updateTable('visit_daily_statistics')
@@ -302,10 +259,6 @@ test('domain and selected-link readers bind exact path/domain pairs, include Roo
.where('domain', '=', domain)
.where('path', '=', '/faq')
.execute();
const domainDetails = await readDomainVisitDetails(db, domain, [path, path, '/new'], period);
expect(domainDetails.links.map(({ path }) => path)).toEqual(['/', path, '/new']);
expect(domainDetails.links[0]!.details.daily[0]!.validVisits).toBe(1);
expect(domainDetails.links[2]!.details.lastActivityAt).toBeNull();
const selected = await readLinkVisitDetails(db, [link, other, link], period);
expect(
selected.links.map(({ domain, path, details }) => ({
@@ -318,12 +271,17 @@ test('domain and selected-link readers bind exact path/domain pairs, include Roo
{ domain: other.domain, path: other.path, visits: 7 }
]);
expect(await readLinkVisitDetails(db, [], period)).toEqual({ period, links: [] });
expect(await readLastVisitActivity(db, period, [link, other])).toBe('2026-04-01T12:00:00.000Z');
expect(await readLastVisitActivity(db, period, [])).toBeNull();
});
test('successful empty reads give zeros/activity null; view time advances without writes and zero clears derived rows', async () => {
const empty = await readOverviewVisitDetails(db, [domain], period);
expect(empty.overview).toEqual(projectVisitDetails(overviewScope, period, []));
expect(empty.domains[0]!.details).toEqual(projectVisitDetails(domainScope, period, []));
expect(await readVisitDetails(db, overviewScope, period)).toEqual(
projectVisitDetails(overviewScope, period, [])
);
expect(await readVisitDetails(db, domainScope, period)).toEqual(
projectVisitDetails(domainScope, period, [])
);
expect(await readLastVisitActivity(db, period)).toBeNull();
await add(daily(overviewScope), daily(domainScope, 1, 0, 11));
const before = await db.selectFrom('visit_daily_statistics').selectAll().execute();
@@ -332,6 +290,7 @@ test('successful empty reads give zeros/activity null; view time advances withou
expect(await readLastVisitActivity(db, nextPeriod)).toBeNull();
expect(await db.selectFrom('visit_daily_statistics').selectAll().execute()).toEqual(before);
expect(await readLastVisitActivity(db, period)).toBe('2026-04-01T10:00:00.000Z');
expect(await readLastVisitActivity(db, period, domainScope)).toBe('2026-04-01T11:00:00.000Z');
await clearDailyVisitStatistics(db);
expect((await readVisitDetails(db, overviewScope, period)).lastActivityAt).toBeNull();
});
+6 -49
View File
@@ -84,51 +84,6 @@ export async function clearDailyVisitStatistics(db: Kysely<Database>): Promise<v
await db.deleteFrom('visit_daily_statistics').execute();
}
export interface OverviewVisitDetails {
overview: VisitDetails;
domains: Array<{ domain: string; details: VisitDetails }>;
}
export async function readOverviewVisitDetails(
db: Kysely<Database>,
currentDomains: string[],
period: ReportPeriod
): Promise<OverviewVisitDetails> {
const domains = [...new Set(currentDomains)];
const [overview, ...details] = await readCurrentDetails(
db,
[{ kind: 'overview' }, ...domains.map((domain) => ({ kind: 'domain' as const, domain }))],
period
);
return {
overview: overview!,
domains: domains.map((domain, index) => ({ domain, details: details[index]! }))
};
}
export interface DomainVisitDetails {
domain: VisitDetails;
links: Array<{ path: string; details: VisitDetails }>;
}
export async function readDomainVisitDetails(
db: Kysely<Database>,
domain: string,
currentPaths: string[],
period: ReportPeriod
): Promise<DomainVisitDetails> {
const paths = [...new Set(['/', ...currentPaths])];
const [details, ...links] = await readCurrentDetails(
db,
[{ kind: 'domain', domain }, ...paths.map((path) => ({ kind: 'link' as const, domain, path }))],
period
);
return {
domain: details!,
links: paths.map((path, index) => ({ path, details: links[index]! }))
};
}
export interface LinkVisitDetails {
period: ReportPeriod;
links: Array<{ domain: string; path: string; details: VisitDetails }>;
@@ -162,13 +117,15 @@ export async function readVisitDetails(
export async function readLastVisitActivity(
db: Kysely<Database>,
period: ReportPeriod
period: ReportPeriod,
scopeOrScopes: ReportScope | ReportScope[] = { kind: 'overview' }
): Promise<string | null> {
const scopes = Array.isArray(scopeOrScopes) ? scopeOrScopes : [scopeOrScopes];
for (const selected of scopes) checkReportScope(selected);
const days = reportDays(period);
const row = await db
.selectFrom('visit_daily_statistics')
if (scopes.length === 0) return null;
const row = await selectedDays(db, scopes)
.select(({ fn }) => fn.max<number>('last_visit_at').as('lastVisitAt'))
.where('scope_kind', '=', 'overview')
.where('day', '>=', days.first)
.where('day', '<=', days.last)
.executeTakeFirstOrThrow();
+46
View File
@@ -3,6 +3,8 @@ import { afterEach, beforeEach, expect, test } from 'vitest';
import {
addVisitTotals,
openDb,
readDomainVisitTotals,
readOverviewVisitTotals,
readVisitTotals,
readLinkVisitCounts,
runMigrations,
@@ -42,6 +44,50 @@ test('adds numeric totals per scope inside a caller transaction and reads missin
});
});
test('reads the lifetime overview and only requested domain rows, filling absent domains with zero', async () => {
const formerDomain = { kind: 'domain' as const, domain: 'old.example.test' };
await db.transaction().execute((transaction) =>
addVisitTotals(transaction, [
{ scope: overview, totals: { validVisits: 6, invalidVisits: 2 } },
{ scope: domain, totals: { validVisits: 4, invalidVisits: 1 } },
{ scope: formerDomain, totals: { validVisits: 2, invalidVisits: 1 } },
{ scope: link, totals: { validVisits: 1, invalidVisits: 0 } }
])
);
expect(await readOverviewVisitTotals(db, [domain.domain, 'empty.example.test'])).toEqual({
overview: { validVisits: 6, invalidVisits: 2 },
byDomain: new Map([
[domain.domain, { validVisits: 4, invalidVisits: 1 }],
['empty.example.test', { validVisits: 0, invalidVisits: 0 }]
])
});
});
test('reads stored domain, Root, and current path totals without including other domains or paths', async () => {
await db.transaction().execute((transaction) =>
addVisitTotals(transaction, [
{ scope: domain, totals: { validVisits: 9, invalidVisits: 2 } },
{ scope: { ...link, path: '/' }, totals: { validVisits: 2, invalidVisits: 0 } },
{ scope: link, totals: { validVisits: 3, invalidVisits: 0 } },
{ scope: { ...link, path: '/retired' }, totals: { validVisits: 4, invalidVisits: 0 } },
{
scope: { ...link, domain: 'other.example.test' },
totals: { validVisits: 5, invalidVisits: 0 }
}
])
);
expect(await readDomainVisitTotals(db, domain.domain, ['/docs', '/new'])).toEqual({
domain: { validVisits: 9, invalidVisits: 2 },
byPath: new Map([
['/', { validVisits: 2, invalidVisits: 0 }],
['/docs', { validVisits: 3, invalidVisits: 0 }],
['/new', { validVisits: 0, invalidVisits: 0 }]
])
});
});
test('unsafe accumulated totals roll back the whole addition transaction', async () => {
await db
.transaction()
+68 -1
View File
@@ -1,4 +1,9 @@
import { checkReportScope, type ReportScope, type VisitTotals } from '@goto/analytics';
import {
checkReportScope,
zeroVisitTotals,
type ReportScope,
type VisitTotals
} from '@goto/analytics';
import { sql, type Kysely } from 'kysely';
import type { Database } from './types.js';
@@ -42,6 +47,68 @@ export async function readVisitTotals(
return checkTotals({ validVisits: row.valid_visits, invalidVisits: row.invalid_visits });
}
export async function readOverviewVisitTotals(
db: Kysely<Database>,
domains: readonly string[]
): Promise<{ overview: VisitTotals; byDomain: Map<string, VisitTotals> }> {
for (const domain of domains) checkReportScope({ kind: 'domain', domain });
const rows = await db
.selectFrom('visit_totals')
.select(['scope_kind', 'domain', 'valid_visits', 'invalid_visits'])
.where(
sql<boolean>`scope_kind = 'overview' OR (
scope_kind = 'domain' AND domain IN (SELECT value FROM json_each(${JSON.stringify(domains)}))
)`
)
.execute();
let overview = zeroVisitTotals();
const byDomain = new Map(domains.map((domain) => [domain, zeroVisitTotals()]));
for (const row of rows) {
const totals = checkTotals({
validVisits: row.valid_visits,
invalidVisits: row.invalid_visits
});
if (row.scope_kind === 'overview') overview = totals;
else if (row.domain !== null) byDomain.set(row.domain, totals);
}
return { overview, byDomain };
}
export async function readDomainVisitTotals(
db: Kysely<Database>,
domain: string,
currentPaths: readonly string[]
): Promise<{ domain: VisitTotals; byPath: Map<string, VisitTotals> }> {
checkReportScope({ kind: 'domain', domain });
const paths = ['/', ...currentPaths];
for (const path of paths) checkReportScope({ kind: 'link', domain, path });
const rows = await db
.selectFrom('visit_totals')
.select(['scope_kind', 'path', 'valid_visits', 'invalid_visits'])
.where('domain', '=', domain)
.where(
sql<boolean>`(
scope_kind = 'domain' OR (
scope_kind = 'link' AND path IN (SELECT value FROM json_each(${JSON.stringify(paths)}))
)
)`
)
.execute();
let domainTotals = zeroVisitTotals();
const byPath = new Map(paths.map((path) => [path, zeroVisitTotals()]));
for (const row of rows) {
const totals = checkTotals({
validVisits: row.valid_visits,
invalidVisits: row.invalid_visits
});
if (row.scope_kind === 'domain') domainTotals = totals;
else if (row.path !== null) byPath.set(row.path, totals);
}
return { domain: domainTotals, byPath };
}
export async function readLinkVisitCounts(
db: Kysely<Database>,
links: readonly { domain: string; path: string }[]