managarten/packages/shared-utils/src/analytics-server.ts
Till JS e01b740dba refactor(analytics): centralize Umami tracking via env vars and shared utility
Move Umami analytics from hardcoded script tags in app.html to
server-side injection via hooks.server.ts. Website IDs are now
managed centrally in .env.development and distributed via
generate-env.mjs as PUBLIC_UMAMI_WEBSITE_ID.

- Add @manacore/shared-utils/analytics-server with injectUmamiAnalytics()
- Add UMAMI_WEBSITE_ID_* for all 17 web apps to .env.development
- Add PUBLIC_UMAMI_WEBSITE_ID mapping in generate-env.mjs for all web apps
- Update 10 existing hooks.server.ts to use shared utility
- Create 7 new hooks.server.ts (picture, planta, presi, photos, clock,
  questions, manadeck)
- Remove hardcoded Umami scripts from all 17 app.html files
- Add missing Umami tracking to Mukke and Questions
- Add shared-utils dependency to 6 web apps that lacked it
- Update ANALYTICS.md with architecture docs and "add new app" guide

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 18:27:31 +01:00

43 lines
1.4 KiB
TypeScript

/**
* Server-side Umami Analytics Utilities
*
* Used in SvelteKit hooks.server.ts to inject the Umami analytics script.
* Reads the website ID from the PUBLIC_UMAMI_WEBSITE_ID environment variable.
*
* @example
* ```typescript
* import { injectUmamiAnalytics } from '@manacore/shared-utils/analytics-server';
*
* export const handle: Handle = async ({ event, resolve }) => {
* return resolve(event, {
* transformPageChunk: ({ html }) => injectUmamiAnalytics(html),
* });
* };
* ```
*/
const UMAMI_SCRIPT_URL = 'https://stats.mana.how/script.js';
/**
* Get the Umami analytics script tag.
* Returns empty string if no website ID is configured.
*/
export function getUmamiScriptTag(websiteId?: string): string {
const id = websiteId || process.env.PUBLIC_UMAMI_WEBSITE_ID || '';
if (!id) return '';
return `<script defer src="${UMAMI_SCRIPT_URL}" data-website-id="${id}"></script>`;
}
/**
* Inject the Umami analytics script into HTML.
* Designed to be used in SvelteKit's transformPageChunk.
*
* @param html - The HTML string to inject the script into
* @param websiteId - Optional website ID override (defaults to PUBLIC_UMAMI_WEBSITE_ID env var)
* @returns The HTML with the Umami script injected before </head>
*/
export function injectUmamiAnalytics(html: string, websiteId?: string): string {
const scriptTag = getUmamiScriptTag(websiteId);
if (!scriptTag) return html;
return html.replace('</head>', `${scriptTag}\n</head>`);
}