@tansy/analytics 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/analytics
4
+
5
+ Page views for tansy: counted by the CMS with no cookies and nothing personal kept, or sent to Plausible, Umami, Google Analytics, Fathom or Matomo through a provider package, with the numbers on the dashboard.
6
+
7
+ ```bash
8
+ npm install @tansy/analytics
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the analytics plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/analytics.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/admin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminPluginParts;
2
+ export default _default;
package/admin.js ADDED
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { adminPath, defineAdminPlugin, PageHeader, TabLinks } from "tansy/admin";
3
+ import { getT } from "tansy/server";
4
+ import { AnalyticsReportView, AnalyticsWidget } from "./dashboard";
5
+ /** Three rising bars, in the navigation's 16 by 16 box. */
6
+ const ICON = {
7
+ paths: ["M2 13.25a.75.75 0 0 1 .75-.75h10.5a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1-.75-.75ZM3 9.5A1 1 0 0 1 4 8.5h1a1 1 0 0 1 1 1v1.5H3V9.5Zm3.5-3A1 1 0 0 1 7.5 5.5h1a1 1 0 0 1 1 1V11h-3V6.5ZM10 3a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v8h-3V3Z"],
8
+ };
9
+ async function Analytics({ user }) {
10
+ const { t } = await getT(user.id);
11
+ const word = (key) => t(`ext.analytics.${key}`);
12
+ const canSet = user.permissions.includes("setting:update");
13
+ return (_jsxs("div", { className: "cms-gutter", children: [_jsx(PageHeader, { title: word("pages.analytics"), description: word("description") }), canSet && (_jsx(TabLinks, { label: word("pages.analytics"), links: [
14
+ { href: adminPath("/ext/analytics"), label: word("pages.analytics"), active: true },
15
+ { href: adminPath("/extensions/analytics/settings"), label: word("tabs.settings") },
16
+ ] })), _jsx(AnalyticsReportView, {})] }));
17
+ }
18
+ export default defineAdminPlugin({
19
+ pages: [{ path: "analytics", title: "Analytics", permission: "ext.analytics:read", component: Analytics }],
20
+ widgets: [{ id: "analytics-overview", title: "Visitors", permission: "ext.analytics:read", component: AnalyticsWidget }],
21
+ section: { title: "Analytics", icon: ICON, items: [{ page: "analytics" }, { settings: true }] },
22
+ });
package/counter.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { ExtensionScope, PluginStore } from "tansy/plugin";
2
+ import { type Hit } from "./logic";
3
+ export declare const dayKey: (date: string) => string;
4
+ export declare const INDEX_KEY = "days";
5
+ export declare function createCounter(store: () => PluginStore, now?: () => Date): {
6
+ count: (hit: Omit<Hit, "newVisitor">, visitor: {
7
+ site: string;
8
+ ip: string | null;
9
+ userAgent: string;
10
+ }, scope?: ExtensionScope) => void;
11
+ flush: () => Promise<void>;
12
+ };
13
+ export type Counter = ReturnType<typeof createCounter>;
package/counter.js ADDED
@@ -0,0 +1,109 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { addHit, emptyDay, mergeDay, readDay, today } from "./logic";
3
+ /**
4
+ * Counts page views in memory and writes them to the plugin's store every few seconds.
5
+ * The CMS runs as one server process, so this is the only writer of these keys, and one
6
+ * flush at a time is enough to never lose an update. A crash loses at most the last few
7
+ * seconds of counts.
8
+ *
9
+ * Telling visitors apart: a hash of a salt, the site, the visitor's address and browser,
10
+ * as Plausible does. The salt is random, kept only in memory and replaced each day, along
11
+ * with the hashes seen. Nothing about a visitor is ever written, and a hash can't be
12
+ * traced back to anyone once the salt is gone. The cost: after a restart, someone who
13
+ * already came that day counts as a new visitor once more.
14
+ *
15
+ * With a scope provider, such as multi-tenant, each scope value's views are kept apart and
16
+ * written in that value, so they land in its own store and never in another tenant's.
17
+ */
18
+ const FLUSH_MS = 5_000;
19
+ /** Far more than one server sees in a day. Past it, visitors aren't told apart until tomorrow. */
20
+ const MAX_SEEN = 500_000;
21
+ export const dayKey = (date) => `day:${date}`;
22
+ export const INDEX_KEY = "days";
23
+ export function createCounter(store, now = () => new Date()) {
24
+ let salt = { day: "", value: Buffer.alloc(0) };
25
+ let seen = new Set();
26
+ let pending = new Map();
27
+ const here = (work) => work();
28
+ function pendingFor(key, run) {
29
+ let entry = pending.get(key);
30
+ if (!entry)
31
+ pending.set(key, entry = { run, days: new Map() });
32
+ return entry;
33
+ }
34
+ let flushing = Promise.resolve();
35
+ let timer = null;
36
+ function saltFor(day) {
37
+ if (salt.day !== day) {
38
+ salt = { day, value: randomBytes(32) };
39
+ seen = new Set();
40
+ }
41
+ return salt.value;
42
+ }
43
+ /** Whether this is the visitor's first page view today. */
44
+ function firstToday(day, site, ip, userAgent) {
45
+ const hash = createHash("sha256").update(saltFor(day)).update(`${site}\n${ip ?? ""}\n${userAgent}`).digest("base64url").slice(0, 22);
46
+ if (seen.has(hash))
47
+ return false;
48
+ if (seen.size >= MAX_SEEN)
49
+ return false;
50
+ seen.add(hash);
51
+ return true;
52
+ }
53
+ function schedule() {
54
+ if (timer)
55
+ return;
56
+ timer = setTimeout(() => {
57
+ timer = null;
58
+ void flush().catch((error) => console.error("[analytics] counts couldn't be saved", error));
59
+ }, FLUSH_MS);
60
+ timer.unref?.();
61
+ }
62
+ function count(hit, visitor, scope) {
63
+ const day = today(now());
64
+ const { days } = pendingFor(scope?.value() ?? "", scope ? scope.bind(here) : here);
65
+ const delta = days.get(day) ?? emptyDay();
66
+ addHit(delta, { ...hit, newVisitor: firstToday(day, visitor.site, visitor.ip, visitor.userAgent) });
67
+ days.set(day, delta);
68
+ schedule();
69
+ }
70
+ async function writeDay(day, delta) {
71
+ const kv = store();
72
+ const stored = await kv.get(dayKey(day));
73
+ await kv.set(dayKey(day), mergeDay(readDay(stored), delta));
74
+ if (stored === null) {
75
+ const index = await kv.get(INDEX_KEY);
76
+ const days = Array.isArray(index) ? index.filter((value) => typeof value === "string") : [];
77
+ if (!days.includes(day))
78
+ await kv.set(INDEX_KEY, [...days, day].sort());
79
+ }
80
+ }
81
+ async function write() {
82
+ const batch = pending;
83
+ pending = new Map();
84
+ let failure = null;
85
+ for (const [key, { run, days }] of batch) {
86
+ for (const [day, delta] of days) {
87
+ try {
88
+ await run(() => writeDay(day, delta));
89
+ }
90
+ catch (error) {
91
+ // Put it back for the next flush rather than lose it.
92
+ const entry = pendingFor(key, run);
93
+ entry.days.set(day, mergeDay(delta, entry.days.get(day) ?? emptyDay()));
94
+ schedule();
95
+ failure ??= error;
96
+ }
97
+ }
98
+ }
99
+ if (failure)
100
+ throw failure;
101
+ }
102
+ /** Writes what's counted so far. Runs one at a time. */
103
+ function flush() {
104
+ const next = flushing.then(write, write);
105
+ flushing = next.catch(() => { });
106
+ return next;
107
+ }
108
+ return { count, flush };
109
+ }
package/dashboard.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** The numbers, from the CMS's own count or the provider's API, with a choice of range and source. */
2
+ export declare function AnalyticsReportView(): import("react").JSX.Element;
3
+ /** The last week on the dashboard's home page. */
4
+ export declare function AnalyticsWidget(): import("react").JSX.Element | null;
package/dashboard.js ADDED
@@ -0,0 +1,83 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect, useState } from "react";
4
+ import { adminPath, Alert, apiPath, ButtonLink, SegmentedControl, useT } from "tansy/admin";
5
+ function useWords() {
6
+ const { t, locale } = useT();
7
+ const words = (key, values) => t(`ext.analytics.${key}`, values);
8
+ const number = (value) => value.toLocaleString(locale);
9
+ const date = (value) => new Date(`${value}T00:00:00Z`).toLocaleDateString(locale, { month: "short", day: "numeric", timeZone: "UTC" });
10
+ let regions = null;
11
+ try {
12
+ regions = new Intl.DisplayNames([locale], { type: "region" });
13
+ }
14
+ catch {
15
+ regions = null;
16
+ }
17
+ const country = (code) => (/^[A-Z]{2}$/.test(code) ? regions?.of(code) ?? code : code);
18
+ return { t: words, number, date, country };
19
+ }
20
+ function useReport(days, source) {
21
+ const [answer, setAnswer] = useState(null);
22
+ const [error, setError] = useState(false);
23
+ useEffect(() => {
24
+ let live = true;
25
+ const query = new URLSearchParams({ days, ...(source ? { source } : {}) });
26
+ fetch(apiPath(`/ext/analytics/report?${query}`), { cache: "no-store" })
27
+ .then((response) => (response.ok ? response.json() : Promise.reject(new Error(String(response.status)))))
28
+ .then((value) => { if (live) {
29
+ setAnswer(value);
30
+ setError(false);
31
+ } })
32
+ .catch(() => { if (live)
33
+ setError(true); });
34
+ return () => { live = false; };
35
+ }, [days, source]);
36
+ return { answer, error };
37
+ }
38
+ /** Views a day as bars, with visitors as a darker bar inside each. Each bar names its day for screen readers. */
39
+ function DayChart({ days, height = 140 }) {
40
+ const { t, number, date } = useWords();
41
+ const most = Math.max(1, ...days.map((day) => day.views));
42
+ const width = 100 / Math.max(1, days.length);
43
+ return (_jsx("svg", { viewBox: `0 0 100 ${height}`, preserveAspectRatio: "none", width: "100%", height: height, role: "img", "aria-label": t("chart"), style: { display: "block" }, children: days.map((day, index) => {
44
+ const views = (day.views / most) * (height - 4);
45
+ const visitors = (day.visitors / most) * (height - 4);
46
+ const label = t("day", { date: date(day.date), views: number(day.views), visitors: number(day.visitors) });
47
+ return (_jsxs("g", { children: [_jsx("title", { children: label }), _jsx("rect", { x: index * width + width * 0.1, y: height - views, width: width * 0.8, height: views, fill: "var(--cms-color-accent-tint)" }), _jsx("rect", { x: index * width + width * 0.1, y: height - visitors, width: width * 0.8, height: visitors, fill: "var(--cms-color-accent)" })] }, day.date));
48
+ }) }));
49
+ }
50
+ function Table({ title, rows, name }) {
51
+ const { t, number } = useWords();
52
+ if (!rows)
53
+ return null;
54
+ const most = Math.max(1, ...rows.map((row) => row.count));
55
+ return (_jsxs("section", { className: "cms-panel", style: { padding: "var(--cms-space-4)" }, children: [_jsx("h2", { className: "cms-medium cms-strong cms-mb-2", children: title }), rows.length === 0 ? _jsx("p", { className: "cms-muted cms-text-sm", children: t("none") }) : (_jsx("ol", { className: "cms-stack-1", style: { listStyle: "none", padding: 0, margin: 0 }, children: rows.map((row) => (_jsxs("li", { className: "cms-text-sm", style: { position: "relative", display: "flex", justifyContent: "space-between", gap: "var(--cms-space-2)", padding: "0.25rem 0.5rem" }, children: [_jsx("span", { "aria-hidden": "true", style: { position: "absolute", insetBlock: 0, insetInlineStart: 0, width: `${(row.count / most) * 100}%`, background: "var(--cms-color-accent-surface)", borderRadius: "var(--cms-radius-sm)" } }), _jsx("span", { style: { position: "relative", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, dir: "auto", children: name ? name(row.name) : row.name }), _jsx("span", { style: { position: "relative" }, children: number(row.count) })] }, row.name))) }))] }));
56
+ }
57
+ const RANGES = ["7", "30", "90"];
58
+ /** The numbers, from the CMS's own count or the provider's API, with a choice of range and source. */
59
+ export function AnalyticsReportView() {
60
+ const { t, number, country } = useWords();
61
+ const [days, setDays] = useState("30");
62
+ const [source, setSource] = useState(null);
63
+ const { answer, error } = useReport(days, source);
64
+ if (error)
65
+ return _jsx(Alert, { kind: "error", children: t("failed", { provider: t("pages.analytics") }) });
66
+ if (!answer)
67
+ return _jsx("div", { className: "cms-panel", "aria-busy": "true", style: { height: 240 } });
68
+ const current = answer.sources.find((candidate) => candidate.id === answer.source);
69
+ const label = (item) => item.label || t("own");
70
+ const report = answer.report;
71
+ return (_jsxs("div", { className: "cms-stack-4", children: [!answer.collecting && !answer.tracking && _jsx(Alert, { kind: "info", children: t("off") }), answer.tracking && answer.source === "cms" && (answer.collecting
72
+ ? _jsx("p", { className: "cms-muted cms-text-sm", children: t("sentTo", { provider: answer.tracking }) })
73
+ : _jsx(Alert, { kind: "info", children: t("noKey", { provider: answer.tracking }) })), _jsxs("div", { className: "cms-row cms-wrap cms-gap-2", children: [answer.sources.length > 1 && _jsx(SegmentedControl, { label: t("pages.analytics"), options: answer.sources.map((item) => ({ id: item.id, label: label(item) })), value: answer.source, onChange: setSource }), _jsxs("div", { className: "cms-row cms-wrap cms-gap-2 cms-ml-auto", children: [current?.dashboardUrl && _jsx(ButtonLink, { variant: "secondary", href: current.dashboardUrl, target: "_blank", rel: "noopener noreferrer", children: t("openProvider", { provider: current.label }) }), _jsx(SegmentedControl, { label: t("range"), options: RANGES.map((range) => ({ id: range, label: t(`ranges.${range}`) })), value: days, onChange: setDays })] })] }), answer.failed && _jsx(Alert, { kind: "warning", children: t("failed", { provider: current ? label(current) : "" }) }), report && (_jsxs(_Fragment, { children: [_jsxs("div", { className: "cms-grid cms-gap-3 cms-sm-3", children: [_jsxs("div", { className: "cms-stat", children: [_jsx("p", { className: "cms-muted cms-text-sm", children: t("totals.views") }), _jsx("p", { className: "cms-stat-value", children: number(report.totals.views) })] }), _jsxs("div", { className: "cms-stat", children: [_jsx("p", { className: "cms-muted cms-text-sm", children: t("totals.visitors") }), _jsx("p", { className: "cms-stat-value", children: number(report.totals.visitors) })] })] }), _jsx("div", { className: "cms-panel", style: { padding: "var(--cms-space-4)" }, children: _jsx(DayChart, { days: report.days }) }), answer.source === "cms" && _jsx("p", { className: "cms-muted cms-text-sm", children: t("visitorsNote") }), _jsxs("div", { className: "cms-grid cms-gap-3 cms-sm-2", children: [_jsx(Table, { title: t("tables.pages"), rows: report.pages }), _jsx(Table, { title: t("tables.referrers"), rows: report.referrers }), _jsx(Table, { title: t("tables.countries"), rows: report.countries, name: country }), _jsx(Table, { title: t("tables.devices"), rows: report.devices }), _jsx(Table, { title: t("tables.browsers"), rows: report.browsers })] })] }))] }));
74
+ }
75
+ /** The last week on the dashboard's home page. */
76
+ export function AnalyticsWidget() {
77
+ const { t, number } = useWords();
78
+ const { answer, error } = useReport("7", null);
79
+ if (error || !answer?.report)
80
+ return error ? _jsx("p", { className: "cms-muted cms-text-sm", children: t("none") }) : null;
81
+ const { totals, days } = answer.report;
82
+ return (_jsxs("div", { className: "cms-stack-2", children: [_jsx("p", { className: "cms-muted cms-text-sm", children: t("widget.summary", { views: number(totals.views), visitors: number(totals.visitors) }) }), _jsx(DayChart, { days: days, height: 48 }), _jsx("a", { className: "cms-text-sm", href: adminPath("/ext/analytics"), children: t("widget.more") })] }));
83
+ }
package/index.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { AnalyticsProvider } from "./provider";
2
+ export type { AnalyticsProvider } from "./provider";
3
+ export type { AnalyticsReport, TrackerConfig } from "./tracker";
4
+ export interface AnalyticsOptions {
5
+ /**
6
+ * Outside services the site can send page views to, each from its own package, such as
7
+ * `plausible()` from @tansy/analytics-plausible. Owners choose one under Analytics →
8
+ * Settings. Without any, the CMS counts page views itself.
9
+ */
10
+ providers?: AnalyticsProvider[];
11
+ /** Which of them is used until changed in the settings. The first when left out, "none" without any. */
12
+ provider?: string;
13
+ /** Whether the CMS counts page views itself until changed in the settings. On when left out. */
14
+ collect?: boolean;
15
+ /** How many days of the CMS's own counts to keep until changed in the settings. Two years when left out. */
16
+ retentionDays?: number;
17
+ }
18
+ /**
19
+ * Page views, counted by the CMS with no cookies and nothing personal kept, or sent to
20
+ * Plausible, Umami, Google Analytics, Fathom or Matomo through adapter packages, with the
21
+ * numbers on the dashboard. See docs/plugins/analytics.md.
22
+ */
23
+ export declare function analytics(options?: AnalyticsOptions): import("tansy/plugin").CmsPlugin;
package/index.js ADDED
@@ -0,0 +1,243 @@
1
+ import { z } from "zod";
2
+ import { definePlugin, defineRoute, mergeMessagesByLanguage } from "tansy/plugin";
3
+ import { createCounter, dayKey, INDEX_KEY } from "./counter";
4
+ import { browserOf, cleanPath, countryOf, deviceOf, isBot, lastDays, readDay, referrerOf, reportFrom, today } from "./logic";
5
+ import { messages } from "./messages";
6
+ import { checkedTracker, excluded } from "./tracker";
7
+ const PROVIDER_ID = /^[a-z][a-z0-9]{0,19}$/;
8
+ const PERMISSION = "ext.analytics:read";
9
+ const RANGES = [7, 30, 90];
10
+ /** The CMS's own count, as a report source. */
11
+ const OWN = "cms";
12
+ const optionsSchema = z.strictObject({
13
+ providers: z.array(z.object({ id: z.string().regex(PROVIDER_ID, "A provider's id is lowercase letters and digits."), label: z.string().min(1) }).loose()),
14
+ provider: z.string(),
15
+ collect: z.boolean(),
16
+ retentionDays: z.number().int().min(30).max(3650),
17
+ }).superRefine((value, issues) => {
18
+ const ids = value.providers.map((provider) => provider.id);
19
+ const twice = ids.find((id, index) => ids.indexOf(id) !== index);
20
+ if (twice)
21
+ issues.addIssue({ code: "custom", path: ["providers"], message: `The provider "${twice}" is listed twice.` });
22
+ if (ids.includes(OWN) || ids.includes("none"))
23
+ issues.addIssue({ code: "custom", path: ["providers"], message: `A provider can't be called "${OWN}" or "none".` });
24
+ if (value.provider !== "none" && !ids.includes(value.provider))
25
+ issues.addIssue({ code: "custom", path: ["provider"], message: `"${value.provider}" isn't one of the providers listed.` });
26
+ });
27
+ /**
28
+ * Every setting's name starts with its provider's id, so two providers can't claim one. Each
29
+ * tenant, with a scope provider, has its own site at the service, so they're per scope value
30
+ * unless the provider says otherwise.
31
+ */
32
+ function providerSettings(providers) {
33
+ return providers.flatMap((provider) => provider.settings().map((field) => {
34
+ if (!field.name.startsWith(provider.id))
35
+ throw new Error(`Analytics provider "${provider.id}": the setting "${field.name}" must start with "${provider.id}".`);
36
+ return { ...field, perScope: field.perScope ?? true };
37
+ }));
38
+ }
39
+ /** Every installed provider's origins, as the provider can change without a rebuild. */
40
+ function cspOf(providers) {
41
+ const all = (key) => [...new Set(providers.flatMap((provider) => provider.csp[key] ?? []))];
42
+ return { frame: all("frame"), connect: all("connect"), img: all("img") };
43
+ }
44
+ const sharedSettings = (value, providers) => [
45
+ { name: "collect", type: "boolean", default: value.collect, perScope: true, label: "Count page views here", description: "Counts views, visitors, pages and where visitors came from, with no cookies and nothing that could identify anyone. Shown on the dashboard." },
46
+ ...(providers.length ? [{ name: "provider", type: "select", default: value.provider, perScope: true, label: "Also send page views to", description: "An analytics service of your own. Fill in its settings below. Until they're set, nothing is sent to it.", options: [{ value: "none", label: "None" }, ...providers.map((provider) => ({ value: provider.id, label: provider.label }))] }] : []),
47
+ { name: "exclude", type: "text", default: "", perScope: true, multiline: true, maxLength: 2000, label: "Addresses not to count", description: "One per line, such as /members. Each counts with everything under it." },
48
+ { name: "respectOptOut", type: "boolean", default: true, perScope: true, label: "Respect visitors who opt out", description: "Visitors whose browser sends Global Privacy Control or Do Not Track aren't sent to the outside service. The count here identifies no one, so it still counts them." },
49
+ { name: "retentionDays", type: "number", default: value.retentionDays, min: 30, max: 3650, integer: true, label: "Keep counts for (days)", description: "Older days are deleted each night." },
50
+ ];
51
+ const SETTINGS_TTL_MS = 30_000;
52
+ const REPORT_TTL_MS = 5 * 60_000;
53
+ /**
54
+ * Page views, counted by the CMS with no cookies and nothing personal kept, or sent to
55
+ * Plausible, Umami, Google Analytics, Fathom or Matomo through adapter packages, with the
56
+ * numbers on the dashboard. See docs/plugins/analytics.md.
57
+ */
58
+ export function analytics(options = {}) {
59
+ const providers = options.providers ?? [];
60
+ const value = optionsSchema.parse({ providers, provider: providers[0]?.id ?? "none", collect: true, retentionDays: 730, ...Object.fromEntries(Object.entries(options).filter(([, option]) => option !== undefined)) });
61
+ const byId = new Map(providers.map((provider) => [provider.id, provider]));
62
+ const csp = cspOf(providers);
63
+ // The store the counter writes to: the plugin's own, from whichever context last ran.
64
+ let store = null;
65
+ const counter = createCounter(() => {
66
+ if (!store)
67
+ throw new Error("[analytics] No store yet.");
68
+ return store;
69
+ });
70
+ // Read on every page and page view, so kept for a little while there: a change reaches pages
71
+ // within half a minute. The dashboard reads them fresh. One entry per scope value, as each
72
+ // tenant can have its own.
73
+ const cached = new Map();
74
+ async function settingsOf(context, { fresh = false } = {}) {
75
+ store = context.store;
76
+ const key = context.scope.value() ?? "";
77
+ const hit = cached.get(key);
78
+ if (!fresh && hit && Date.now() - hit.at < SETTINGS_TTL_MS)
79
+ return hit.settings;
80
+ const settings = { provider: "none", ...(await context.settings.get()) };
81
+ if (cached.size > 1000)
82
+ cached.clear();
83
+ cached.set(key, { at: Date.now(), settings });
84
+ return settings;
85
+ }
86
+ const excludeOf = (settings) => String(settings.exclude ?? "").split(/\r?\n/).map((line) => cleanPath(line.trim())).filter((path) => path !== null && path !== "/");
87
+ /** The outside provider in use, once its settings are complete. */
88
+ const activeProvider = (settings) => {
89
+ const provider = byId.get(settings.provider);
90
+ return provider?.ready(settings) ? provider : null;
91
+ };
92
+ async function trackerConfig(context) {
93
+ const settings = await settingsOf(context);
94
+ const provider = activeProvider(settings);
95
+ let tracker = null;
96
+ if (provider) {
97
+ try {
98
+ tracker = checkedTracker(provider.id, provider.tracker(settings), provider.csp.connect ?? []);
99
+ }
100
+ catch (error) {
101
+ console.error(`[analytics] ${provider.id}: tracker failed`, error);
102
+ }
103
+ }
104
+ const collect = settings.collect === true;
105
+ if (!collect && !tracker)
106
+ return null;
107
+ return { collect, provider: tracker, exclude: excludeOf(settings), respectOptOut: settings.respectOptOut !== false };
108
+ }
109
+ /** The CMS's own days in the range, with what's still in memory written first. */
110
+ async function ownReport(context, range) {
111
+ store = context.store;
112
+ await counter.flush().catch((error) => console.error("[analytics] counts couldn't be saved", error));
113
+ const days = new Map();
114
+ const dates = reportFrom(range, new Map()).days.map((day) => day.date);
115
+ const stored = await Promise.all(dates.map((date) => context.store.get(dayKey(date))));
116
+ dates.forEach((date, index) => { if (stored[index] !== null)
117
+ days.set(date, readDay(stored[index])); });
118
+ return reportFrom(range, days);
119
+ }
120
+ const reports = new Map();
121
+ async function providerReport(provider, settings, range, scope) {
122
+ const key = `${scope}:${provider.id}:${range.from}:${range.to}`;
123
+ const hit = reports.get(key);
124
+ if (hit && Date.now() - hit.at < REPORT_TTL_MS)
125
+ return hit.report;
126
+ const report = await provider.report(range, settings);
127
+ if (reports.size > 50)
128
+ reports.clear();
129
+ reports.set(key, { at: Date.now(), report });
130
+ return report;
131
+ }
132
+ /** Where the dashboard can read numbers from: the CMS's own count, and the provider when it has an API and a key. */
133
+ function sourcesOf(settings) {
134
+ const sources = [];
135
+ const provider = byId.get(settings.provider);
136
+ if (provider?.report && provider.ready(settings) && (provider.reportReady?.(settings) ?? true))
137
+ sources.push({ id: provider.id, label: provider.label, dashboardUrl: provider.dashboardUrl?.(settings) ?? null });
138
+ if (settings.collect === true || !sources.length)
139
+ sources.push({ id: OWN, label: "", dashboardUrl: null });
140
+ return sources;
141
+ }
142
+ return definePlugin({
143
+ name: "analytics",
144
+ version: "0.1.0",
145
+ apiVersion: 1,
146
+ requires: { cms: "^0.1.0" },
147
+ admin: { server: "@tansy/analytics/admin", render: "@tansy/analytics/render" },
148
+ options: { schema: optionsSchema, value },
149
+ messages: mergeMessagesByLanguage(messages, ...providers.map((provider) => provider.messages)),
150
+ permissions: { "ext.analytics": ["read"] },
151
+ settings: { fields: [...sharedSettings(value, providers), ...providerSettings(providers)] },
152
+ csp,
153
+ everyPage: {
154
+ // Editors' previews of unpublished content aren't visits.
155
+ "analytics-tracker": async (context) => (context.page.preview ? null : trackerConfig(context)),
156
+ },
157
+ routes: [
158
+ defineRoute({
159
+ method: "POST",
160
+ path: "/hit",
161
+ access: "public",
162
+ reason: "Every visitor's browser reports the page it opened, signed out. It adds one to the day's counts and keeps nothing about the visitor.",
163
+ // A person opens a few pages a minute. A page reloaded on a loop gets cut off.
164
+ rateLimit: { window: 60, max: 60 },
165
+ body: z.object({ path: z.string().max(1000), referrer: z.string().max(2000).nullish(), source: z.string().max(100).nullish(), width: z.number().int().min(0).max(100_000).nullish() }),
166
+ handler: async (context) => {
167
+ const { body, request, ip } = context;
168
+ const settings = await settingsOf(context);
169
+ const done = new Response(null, { status: 204 });
170
+ if (settings.collect !== true)
171
+ return done;
172
+ const userAgent = request.headers.get("user-agent");
173
+ const path = cleanPath(body.path);
174
+ if (isBot(userAgent) || !path || excluded(path, excludeOf(settings)))
175
+ return done;
176
+ const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
177
+ counter.count({ path, referrer: referrerOf(body.referrer, body.source, host), country: countryOf(request.headers), device: deviceOf(body.width), browser: browserOf(userAgent) }, { site: host ?? "", ip, userAgent: userAgent }, context.scope);
178
+ return done;
179
+ },
180
+ }),
181
+ defineRoute({
182
+ method: "GET",
183
+ path: "/tracker",
184
+ access: "public",
185
+ reason: "A headless site's pages load the tracker signed out. It's what every page already shows: the provider's public site id and script, never a key.",
186
+ handler: async (context) => (await trackerConfig(context)) ?? { collect: false, provider: null, exclude: [], respectOptOut: true },
187
+ }),
188
+ defineRoute({
189
+ method: "GET",
190
+ path: "/report",
191
+ access: "permission",
192
+ permission: PERMISSION,
193
+ query: z.object({ days: z.enum(RANGES.map(String)).default("30"), source: z.string().max(40).optional() }),
194
+ handler: async (context) => {
195
+ const settings = await settingsOf(context, { fresh: true });
196
+ const sources = sourcesOf(settings);
197
+ const source = sources.find((candidate) => candidate.id === context.query.source) ?? sources[0];
198
+ const range = lastDays(Number(context.query.days));
199
+ const provider = byId.get(source.id);
200
+ let report = null;
201
+ let failed = false;
202
+ try {
203
+ report = provider ? await providerReport(provider, settings, range, context.scope.value() ?? "") : await ownReport(context, range);
204
+ }
205
+ catch (error) {
206
+ console.error(`[analytics] ${source.id}: report failed`, error instanceof Error ? error.message : error);
207
+ failed = true;
208
+ }
209
+ return { sources, source: source.id, range, report, failed, collecting: settings.collect === true, tracking: activeProvider(settings)?.label ?? null };
210
+ },
211
+ }),
212
+ ],
213
+ jobs: [
214
+ {
215
+ name: "analytics.flush",
216
+ cron: "* * * * *",
217
+ handler: async (context) => {
218
+ store = context.store;
219
+ await counter.flush();
220
+ },
221
+ },
222
+ {
223
+ name: "analytics.prune",
224
+ cron: "17 3 * * *",
225
+ // Each tenant keeps its own days, so each is pruned.
226
+ perScope: true,
227
+ handler: async (context) => {
228
+ const settings = await settingsOf(context, { fresh: true });
229
+ const keep = Math.max(30, Number(settings.retentionDays) || value.retentionDays);
230
+ const cutoff = lastDays(keep).from;
231
+ const index = await context.store.get(INDEX_KEY);
232
+ const days = Array.isArray(index) ? index.filter((day) => typeof day === "string") : [];
233
+ const old = days.filter((day) => day < cutoff);
234
+ if (!old.length)
235
+ return;
236
+ for (const day of old)
237
+ await context.store.delete(dayKey(day));
238
+ await context.store.set(INDEX_KEY, days.filter((day) => day >= cutoff || day === today()));
239
+ },
240
+ },
241
+ ],
242
+ });
243
+ }
package/logic.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { type ReportRange } from "./provider";
2
+ import type { AnalyticsReport } from "./tracker";
3
+ /**
4
+ * The CMS's own count, as pure functions. Nothing here keeps an address, a browser's full
5
+ * name or anything else that could pick a person out: a page view becomes counts by day.
6
+ */
7
+ /** One day's counts, as stored. Each table keeps its biggest entries and folds the rest into "(other)". */
8
+ export interface DayStats {
9
+ views: number;
10
+ visitors: number;
11
+ pages: Record<string, number>;
12
+ referrers: Record<string, number>;
13
+ countries: Record<string, number>;
14
+ devices: Record<string, number>;
15
+ browsers: Record<string, number>;
16
+ }
17
+ export type Table = Exclude<keyof DayStats, "views" | "visitors">;
18
+ export declare const TABLES: Table[];
19
+ /** Enough for the pages anyone looks at, small enough to keep a day under the store's limit. */
20
+ export declare const TABLE_LIMITS: Record<Table, number>;
21
+ export declare const OTHER = "(other)";
22
+ export declare const emptyDay: () => DayStats;
23
+ /** What one page view adds. Null fields add nothing to their table. */
24
+ export interface Hit {
25
+ path: string;
26
+ referrer: string | null;
27
+ country: string | null;
28
+ device: string;
29
+ browser: string;
30
+ /** The visitor's first page view today. */
31
+ newVisitor: boolean;
32
+ }
33
+ export declare function addHit(day: DayStats, hit: Hit): void;
34
+ /** Keeps the biggest `limit` entries, and adds the rest to "(other)". */
35
+ export declare function capTable(table: Record<string, number>, limit: number): Record<string, number>;
36
+ /** A stored day, read defensively: anything that isn't a count is left out. */
37
+ export declare function readDay(value: unknown): DayStats;
38
+ /** Adds `delta` to `day`, capping each table. */
39
+ export declare function mergeDay(day: DayStats, delta: DayStats): DayStats;
40
+ /** Days' counts as a report. Visitors add up per day, so one person on two days counts twice. */
41
+ export declare function reportFrom(range: ReportRange, days: Map<string, DayStats>): AnalyticsReport;
42
+ /** Whether a page view comes from a program rather than a person. A missing browser name counts as a program. */
43
+ export declare const isBot: (userAgent: string | null) => boolean;
44
+ /** The browser's family, never its version. */
45
+ export declare function browserOf(userAgent: string): string;
46
+ /** From the screen's width, as Plausible does: it says nothing about the person. */
47
+ export declare function deviceOf(width: number | null | undefined): string;
48
+ /** The country a CDN in front of the site says the visitor is in, when one does. The address itself is never looked at. */
49
+ export declare function countryOf(headers: Headers): string | null;
50
+ /** Where the visitor came from: a campaign's `utm_source` or `ref`, or the other site's host. Links within the site count as none. */
51
+ export declare function referrerOf(referrer: string | null | undefined, source: string | null | undefined, ownHost: string | null): string | null;
52
+ /** The address without its query or fragment, or null for anything that isn't a site address. */
53
+ export declare function cleanPath(path: unknown): string | null;
54
+ /** Today in UTC, as YYYY-MM-DD. */
55
+ export declare const today: (now?: Date) => string;
56
+ /** The last `days` days up to today, inclusive. */
57
+ export declare function lastDays(days: number, now?: Date): ReportRange;