@tansy/analytics-google 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/analytics-google`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ No changes of its own. Released beside `tansy` 0.1.1, from which every package moves on its own
9
+ version, and it now requires it: the `tansy` peer range is ^0.1.1.
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-google
4
+
5
+ Google Analytics for @tansy/analytics: the tracker on every page, and its numbers on the dashboard.
6
+
7
+ ```bash
8
+ npm install @tansy/analytics-google
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/index.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export interface GoogleAnalyticsOptions {
2
+ /** The web stream's measurement id, such as G-XXXXXXXXXX, until one is saved in the settings. */
3
+ measurementId?: string;
4
+ /** The GA4 property's number, for the dashboard, until one is saved in the settings. */
5
+ propertyId?: string;
6
+ /** For tests: called instead of fetch. */
7
+ fetcher?: typeof fetch;
8
+ }
9
+ interface ServiceAccount {
10
+ client_email: string;
11
+ private_key: string;
12
+ }
13
+ /** A signed request for an access token, as Google's OAuth for service accounts expects. */
14
+ export declare function serviceAccountAssertion(account: ServiceAccount, now?: number): string;
15
+ /** Google Analytics 4. It sets cookies unless cookieless is on, so most EU sites need visitors' consent. */
16
+ export declare const googleAnalytics: ({ measurementId: defaultId, propertyId: defaultProperty, fetcher }?: GoogleAnalyticsOptions) => import("@tansy/analytics/provider").AnalyticsProvider;
17
+ export {};
package/index.js ADDED
@@ -0,0 +1,131 @@
1
+ import { createSign } from "node:crypto";
2
+ import { breakdown, defineAnalyticsProvider, fillDays, num, requestJson, str } from "@tansy/analytics/provider";
3
+ const MEASUREMENT_ID = /^G-[A-Z0-9]{4,20}$/;
4
+ const SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
5
+ const TOKEN_URL = "https://oauth2.googleapis.com/token";
6
+ const measurementId = (settings) => str(settings.googleMeasurementId).toUpperCase();
7
+ const propertyId = (settings) => str(settings.googlePropertyId).replace(/^properties\//, "");
8
+ /** The service account's key file, as pasted into the setting. Null when it isn't one. */
9
+ function serviceAccount(settings) {
10
+ try {
11
+ const parsed = JSON.parse(str(settings.googleServiceAccount));
12
+ return typeof parsed.client_email === "string" && typeof parsed.private_key === "string" ? { client_email: parsed.client_email, private_key: parsed.private_key } : null;
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ const base64url = (value) => Buffer.from(value).toString("base64url");
19
+ /** A signed request for an access token, as Google's OAuth for service accounts expects. */
20
+ export function serviceAccountAssertion(account, now = Math.floor(Date.now() / 1000)) {
21
+ const head = base64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
22
+ const claims = base64url(JSON.stringify({ iss: account.client_email, scope: SCOPE, aud: TOKEN_URL, iat: now, exp: now + 3600 }));
23
+ const signature = createSign("RSA-SHA256").update(`${head}.${claims}`).sign(account.private_key);
24
+ return `${head}.${claims}.${base64url(signature)}`;
25
+ }
26
+ /** Google Analytics 4. It sets cookies unless cookieless is on, so most EU sites need visitors' consent. */
27
+ export const googleAnalytics = ({ measurementId: defaultId = "", propertyId: defaultProperty = "", fetcher } = {}) => {
28
+ // One token at a time, shared by a report's parallel queries, until a minute before it expires.
29
+ let token = null;
30
+ function accessToken(account) {
31
+ if (token && token.account === account.client_email && token.expires > Date.now() + 60_000)
32
+ return token.value;
33
+ const value = requestJson(TOKEN_URL, {
34
+ method: "POST",
35
+ headers: { "content-type": "application/x-www-form-urlencoded" },
36
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: serviceAccountAssertion(account) }),
37
+ }, fetcher).then((answer) => {
38
+ if (!answer.access_token)
39
+ throw new Error("Google gave no access token.");
40
+ if (token?.value === value)
41
+ token.expires = Date.now() + (answer.expires_in ?? 3600) * 1000;
42
+ return answer.access_token;
43
+ });
44
+ token = { account: account.client_email, value, expires: Date.now() + 3_000_000 };
45
+ // A failed request isn't kept, so the next report asks again.
46
+ value.catch(() => { if (token?.value === value)
47
+ token = null; });
48
+ return value;
49
+ }
50
+ async function run(settings, range, metrics, dimension, limit) {
51
+ const account = serviceAccount(settings);
52
+ if (!account)
53
+ throw new Error("The service account key isn't a Google key file.");
54
+ const answer = await requestJson(`https://analyticsdata.googleapis.com/v1beta/properties/${encodeURIComponent(propertyId(settings))}:runReport`, {
55
+ method: "POST",
56
+ headers: { authorization: `Bearer ${await accessToken(account)}`, "content-type": "application/json" },
57
+ body: JSON.stringify({
58
+ dateRanges: [{ startDate: range.from, endDate: range.to }],
59
+ metrics: metrics.map((name) => ({ name })),
60
+ ...(dimension ? { dimensions: [{ name: dimension }] } : {}),
61
+ ...(limit ? { limit, orderBys: [{ metric: { metricName: metrics[0] }, desc: true }] } : {}),
62
+ }),
63
+ }, fetcher);
64
+ return (answer.rows ?? []).map((row) => ({ name: row.dimensionValues?.[0]?.value, values: (row.metricValues ?? []).map((value) => num(value.value)) }));
65
+ }
66
+ const table = async (settings, range, dimension, metric = "totalUsers") => breakdown((await run(settings, range, [metric], dimension, 11)).map((row) => ({ name: row.name, count: row.values[0] })));
67
+ return defineAnalyticsProvider({
68
+ id: "google",
69
+ label: "Google Analytics",
70
+ messages: {
71
+ ar: {
72
+ settings: {
73
+ googleMeasurementId: { label: "معرّف القياس في Google Analytics", description: "من Google Analytics ← المشرف ← مصادر البيانات، لمصدر الويب. يبدأ بـ G-." },
74
+ googleCookieless: { label: "دون ملفات تعريف الارتباط", description: "يرسل المشاهدات دون ملفات تعريف ارتباط، ويقدّر Google الباقي. لا حاجة عندها إلى موافقة الزوار في أغلب الحالات، والأرقام أقل دقة." },
75
+ googlePropertyId: { label: "رقم الموقع (Property) في Google Analytics", description: "اختياري، لعرض الأرقام هنا. من المشرف ← إعدادات الموقع، مثل 123456789." },
76
+ googleServiceAccount: { label: "مفتاح حساب الخدمة", description: "اختياري، لعرض الأرقام هنا. ملف JSON لحساب خدمة في Google Cloud مفعّل فيه Analytics Data API، ومضاف كمشاهد (Viewer) للموقع." },
77
+ },
78
+ },
79
+ },
80
+ settings: () => [
81
+ { name: "googleMeasurementId", type: "text", default: defaultId, maxLength: 30, label: "Google Analytics measurement id", description: "From Google Analytics → Admin → Data streams, for the web stream. It starts with G-." },
82
+ { name: "googleCookieless", type: "boolean", default: false, label: "Without cookies", description: "Sends page views without cookies, and Google models the rest. Most places then need no consent from visitors, and the numbers are less exact." },
83
+ { name: "googlePropertyId", type: "text", default: defaultProperty, maxLength: 20, label: "Google Analytics property number", description: "Optional, to show the numbers here. From Admin → Property settings, such as 123456789." },
84
+ { name: "googleServiceAccount", type: "secret", env: "GOOGLE_ANALYTICS_CREDENTIALS", label: "Service account key", description: "Optional, to show the numbers here. The JSON key of a Google Cloud service account with the Analytics Data API turned on, added to the property as a Viewer." },
85
+ ],
86
+ ready: (settings) => MEASUREMENT_ID.test(measurementId(settings)),
87
+ reportReady: (settings) => /^\d{1,20}$/.test(propertyId(settings)) && serviceAccount(settings) !== null,
88
+ tracker: (settings) => {
89
+ const id = measurementId(settings);
90
+ return {
91
+ script: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(id)}`,
92
+ stubs: [{ type: "queue", name: "gtag", into: "dataLayer" }],
93
+ setup: [
94
+ ...(settings.googleCookieless === true ? [{ fn: "gtag", args: ["consent", "default", { analytics_storage: "denied", ad_storage: "denied", ad_user_data: "denied", ad_personalization: "denied" }] }] : []),
95
+ { fn: "gtag", args: ["js", "$now"] },
96
+ // The tracker sends each page view itself, including moves between pages without a reload. Nothing for ads.
97
+ { fn: "gtag", args: ["config", id, { send_page_view: false, allow_google_signals: false, allow_ad_personalization_signals: false }] },
98
+ ],
99
+ pageview: [{ fn: "gtag", args: ["event", "page_view", { page_location: "$url", page_title: "$title", page_referrer: "$referrer" }] }],
100
+ };
101
+ },
102
+ async report(range, settings) {
103
+ const [totals, daily, pages, referrers, countries, devices, browsers] = await Promise.all([
104
+ run(settings, range, ["screenPageViews", "totalUsers"]),
105
+ run(settings, range, ["screenPageViews", "totalUsers"], "date"),
106
+ table(settings, range, "pagePath", "screenPageViews"),
107
+ table(settings, range, "sessionSource"),
108
+ table(settings, range, "countryId"),
109
+ table(settings, range, "deviceCategory"),
110
+ table(settings, range, "browser"),
111
+ ]);
112
+ // GA writes days as YYYYMMDD.
113
+ const days = new Map(daily.map((row) => [String(row.name ?? "").replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3"), { views: row.values[0] ?? 0, visitors: row.values[1] ?? 0 }]));
114
+ const known = (rows) => rows.filter((row) => !/^\(.+\)$/.test(row.name)).slice(0, 10);
115
+ return {
116
+ totals: { views: totals[0]?.values[0] ?? 0, visitors: totals[0]?.values[1] ?? 0 },
117
+ days: fillDays(range, days),
118
+ pages: known(pages),
119
+ referrers: known(referrers),
120
+ countries: known(countries),
121
+ devices: known(devices),
122
+ browsers: known(browsers),
123
+ };
124
+ },
125
+ dashboardUrl: (settings) => (propertyId(settings) ? `https://analytics.google.com/analytics/web/#/p${propertyId(settings)}/reports/intelligenthome` : "https://analytics.google.com/"),
126
+ csp: {
127
+ connect: ["https://www.googletagmanager.com", "https://www.google-analytics.com", "https://region1.google-analytics.com", "https://analytics.google.com", "https://region1.analytics.google.com", "https://stats.g.doubleclick.net"],
128
+ img: ["https://www.googletagmanager.com", "https://www.google-analytics.com"],
129
+ },
130
+ });
131
+ };
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@tansy/analytics-google",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Google Analytics for @tansy/analytics: the tracker on every page, and its numbers on the dashboard.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-analytics-provider"
8
+ ],
9
+ "license": "MIT",
10
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
11
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
15
+ "directory": "plugins/analytics-google"
16
+ },
17
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.ts",
21
+ "default": "./index.js"
22
+ }
23
+ },
24
+ "peerDependencies": {
25
+ "@tansy/analytics": "^0.1.1",
26
+ "tansy": "^0.1.1"
27
+ }
28
+ }