All files / src/constants build-info-meta.ts

100% Statements 4/4
100% Branches 0/0
100% Functions 1/1
100% Lines 4/4

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48                                                                    170x 170x     170x 170x                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Constants/BuildInfoMeta
 * @description Shared helper that emits the `<head>` freshness tags every
 * generator must include so the PWA layer (`js/pwa-register.js`) can:
 *
 *   - Read the embedded build commit SHA + timestamp from `<meta>` tags.
 *   - Load the same-origin service-worker registration script.
 *   - Tell browsers + intermediate proxies to revalidate every navigation
 *     (`Cache-Control: no-cache`, `Pragma: no-cache`).
 *
 * Every value is HTML-escaped — `BUILD_ID`/`BUILD_TIME` are tightly
 * formatted (40-char hex / ISO 8601) but defence-in-depth is cheap.
 *
 * The output is a multi-line string; callers should drop it into the
 * `<head>` block alongside other `<meta>` tags. CSP stays `script-src
 * 'self'` because the only emitted `<script>` references a same-origin
 * file with a `defer` attribute.
 */
 
import { BUILD_ID, BUILD_TIME } from './config.js';
import { escapeHTML } from '../utils/file-utils.js';
 
/**
 * Build the shared freshness/PWA `<head>` block.
 *
 * @param pathPrefix - Asset path prefix (`''` for root pages, `'../'`
 *                     for `news/` pages).
 * @returns Multi-line HTML string. Caller is responsible for placing it
 *          inside `<head>…</head>`. The result is already HTML-escaped.
 */
export function buildHeadFreshnessTags(pathPrefix: string): string {
  const safeBuildId = escapeHTML(BUILD_ID);
  const safeBuildTime = escapeHTML(BUILD_TIME);
  // Path prefix is built from controlled string literals (`''` or `'../'`),
  // but escape it anyway to keep the helper safe under future callers.
  const safePrefix = escapeHTML(pathPrefix);
  return [
    `  <meta name="build-id" content="${safeBuildId}">`,
    `  <meta name="build-time" content="${safeBuildTime}">`,
    `  <meta http-equiv="Cache-Control" content="no-cache">`,
    `  <meta http-equiv="Pragma" content="no-cache">`,
    `  <script src="${safePrefix}js/pwa-register.js" defer></script>`,
  ].join('\n');
}