All source files

tests/site.test.mjs

Download raw file

import test from 'node:test';
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {readFile, access} from 'node:fs/promises';
import {dirname, isAbsolute, join, relative, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {PAGES, SITE_ORIGIN, renderNotFoundPage, renderPage} from '../src/page-template.mjs';
import {emitEvent} from '../src/analytics.mjs';
import {CONSENT_STORAGE_KEY, CONSENT_POLICY_VERSION, createTrackEvent} from '../src/consent.mjs';

const srcDir = fileURLToPath(new URL('../src/', import.meta.url));
const rootDir = fileURLToPath(new URL('../', import.meta.url));
const assetsDir = fileURLToPath(new URL('../dist/assets/', import.meta.url));
const WWW_ORIGIN = 'https://www.wordhintlab.com';
const configuredGtmId = (process.env.WORDHINT_GTM_ID || '').trim();

function staticImportSpecifiers(source) {
  const specifiers = [];
  const pattern = /(?:^|\n)\s*(?:import|export)\s+(?:[^'"]*?\bfrom\s*)?['"]([^'"]+)['"]/g;
  let match;
  while ((match = pattern.exec(source))) specifiers.push(match[1]);
  return specifiers;
}

async function staticImportClosure(entry) {
  const files = new Set();
  const pending = [entry];
  while (pending.length) {
    const file = pending.pop();
    if (files.has(file)) continue;
    files.add(file);
    const source = await readFile(file, 'utf8');
    for (const specifier of staticImportSpecifiers(source)) {
      if (specifier.startsWith('.')) pending.push(resolve(dirname(file), specifier));
    }
  }
  return [...files];
}

function gtmIdFrom(html) {
  return html.match(/<meta name="wordhint-gtm-id" content="(GTM-[A-Z0-9]+)">/)?.[1] || '';
}

function assertGatedGtmMarkup(html, id, label) {
  assert.ok(html.includes(`<meta name="wordhint-gtm-id" content="${id}">`), `${label} must expose the configured container through a meta tag`);
  assert.ok(html.includes('<script type="module" src="/assets/consent.mjs"></script>'), `${label} must load the consent gate`);
  assert.ok(html.includes('id="cookieBanner"'), `${label} must render the consent banner`);
  assert.equal((html.match(/id="cookieBanner"/g) || []).length, 1, `${label} must render exactly one consent banner`);
  assert.ok(html.includes('role="region"'), `${label} consent banner must expose a landmark`);
  assert.ok(html.includes('aria-labelledby="cookieBannerTitle"'), `${label} consent banner must be named`);
  assert.ok(html.includes('data-consent-accept'), `${label} must offer an accept control`);
  assert.ok(html.includes('data-consent-reject'), `${label} must offer a reject control`);
  assert.ok(html.includes('data-cookie-settings'), `${label} must offer a change-choice entry`);
  assert.ok(html.includes(CONSENT_STORAGE_KEY) || html.includes('/assets/consent.mjs'), `${label} must connect to the versioned consent record`);
  assert.ok(!html.includes('window.trackEvent'), `${label} must not expose trackEvent before a choice`);
  assert.ok(!html.includes('dataLayer'), `${label} must not define dataLayer before a choice`);
  assert.ok(!/<script[^>]+src="https?:\/\/[^"]*googletagmanager/i.test(html), `${label} must not inject a static Google script`);
  assert.ok(!/<iframe[^>]+googletagmanager/i.test(html), `${label} must not inject a Google noscript iframe`);
  assert.ok(!html.includes('googletagmanager.com'), `${label} must not embed a Google request URL in static HTML`);
}

const pages=[
  ['index.html','zh-CN','https://www.wordhintlab.com/'],
  ['practice/index.html','zh-CN','https://www.wordhintlab.com/practice/'],
  ['en/index.html','en','https://www.wordhintlab.com/en/'],
  ['en/practice/index.html','en','https://www.wordhintlab.com/en/practice/']
];
const infoPages=[
  ['privacy/index.html','zh-CN','https://www.wordhintlab.com/privacy/'],
  ['contact/index.html','zh-CN','https://www.wordhintlab.com/contact/'],
  ['en/privacy/index.html','en','https://www.wordhintlab.com/en/privacy/'],
  ['en/contact/index.html','en','https://www.wordhintlab.com/en/contact/']
];
const allPages=[...pages,...infoPages];

test('built pages are semantic, localized and keyboard/status ready', async () => {
  for(const [path,lang,canonical] of pages){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    assert.ok(html.includes(`lang="${lang}"`));
    assert.equal((html.match(/<h1[\s>]/g)||[]).length,1);
    assert.ok(html.includes(`rel="canonical" href="${canonical}"`));
    assert.ok(html.includes('rel="alternate" hreflang='));
    const alternates=[...html.matchAll(/<link\b[^>]*\brel="alternate"[^>]*\bhreflang="[^"]+"[^>]*>/g)].map(match=>match[0]);
    assert.ok(alternates.length>=1,`${path} must declare at least one hreflang alternate`);
    for(const tag of alternates){
      const href=tag.match(/\bhref="([^"]+)"/)?.[1];
      assert.ok(href,`${path} hreflang alternate must carry href`);
      assert.ok(/^https:\/\//.test(href),`${path} hreflang href must be an absolute https URL: ${href}`);
      assert.equal(new URL(href).origin,new URL(canonical).origin,`${path} hreflang ${href} must share the canonical origin`);
    }
    assert.ok(html.includes('role="status"'));
    assert.ok(html.includes('aria-live="polite"'));
    assert.ok(html.includes('id="keyboard"'));
    assert.ok(html.includes('id="revealDialog"'));
    assert.ok(!/\son(click|keydown|input)=/.test(html));
  }
});

test('built site carries local assets, license, sitemap and matches the configured GTM mode', async () => {
  const sitemap=await readFile(new URL('../dist/sitemap.xml',import.meta.url),'utf8');
  const robots=await readFile(new URL('../dist/robots.txt',import.meta.url),'utf8');
  assert.ok(robots.includes('Sitemap: https://www.wordhintlab.com/sitemap.xml'));
  for(const [, , canonical] of allPages)assert.ok(sitemap.includes(canonical));
  assert.deepEqual([...sitemap.matchAll(/<loc>([^<]+)<\/loc>/g)].map(match=>match[1]),PAGES.map(page=>page.canonical));
  await access(new URL('../dist/assets/scowl-Copyright.txt',import.meta.url));
  for(const [path] of allPages){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    assert.equal(gtmIdFrom(html),configuredGtmId,`${path} must match WORDHINT_GTM_ID=${configuredGtmId || '(unset)'}`);
    const externalScripts=[...html.matchAll(/<script[^>]+src="(https?:[^"]+)"/g)].map(match=>match[1]);
    const externalStyles=[...html.matchAll(/<link[^>]+rel="stylesheet"[^>]*href="(https?:[^"]+)"/g)].map(match=>match[1]);
    assert.deepEqual(externalStyles,[],`${path} must keep styles local`);
    if(configuredGtmId){
      assert.deepEqual(externalScripts,[],`${path} must let the consent gate inject GTM instead of a static external script`);
      assertGatedGtmMarkup(html,configuredGtmId,path);
    }else{
      assert.deepEqual(externalScripts,[],`${path} must not load any external script without WORDHINT_GTM_ID`);
      assert.ok(!html.includes('wordhint-gtm-id'),`${path} must not expose a GTM container without GTM`);
      assert.ok(!html.includes('id="cookieBanner"'),`${path} must not ask for analytics consent when no channel is configured`);
      assert.ok(!html.includes('/assets/consent.mjs'),`${path} must not load the consent UI without an analytics channel`);
      assert.ok(!html.includes('dataLayer'),`${path} must not define dataLayer without GTM`);
      assert.ok(!html.includes('trackEvent'),`${path} must not define trackEvent without GTM`);
    }
  }
});

test('robots.txt disallows raw source copies while keeping the site and source browser crawlable', async () => {
  const robots=await readFile(new URL('../dist/robots.txt',import.meta.url),'utf8');
  const lines=robots.split('\n').map(line=>line.trim()).filter(Boolean);
  assert.ok(lines.includes('User-agent: *'),'robots.txt must keep the wildcard user agent');
  assert.ok(lines.includes('Allow: /'),'robots.txt must keep the site crawlable');
  assert.ok(lines.includes('Disallow: /source/files/'),'robots.txt must disallow raw source file copies');
  assert.ok(!lines.includes('Disallow: /source/'),'robots.txt must not disallow the noindex source browser itself');
  assert.ok(lines.includes(`Sitemap: ${WWW_ORIGIN}/sitemap.xml`),'robots.txt must keep the sitemap declaration');
  const sitemap=await readFile(new URL('../dist/sitemap.xml',import.meta.url),'utf8');
  const locs=[...sitemap.matchAll(/<loc>([^<]+)<\/loc>/g)].map(match=>match[1]);
  assert.equal(locs.length,8,'robots.txt must not change the 8 production sitemap URLs');
  assert.deepEqual(locs,PAGES.map(page=>page.canonical),'sitemap entries must stay identical to the page canonicals');
});

test('privacy and contact pages are localized, indexable and linked from every production page', async () => {
  for(const [path,lang,canonical] of infoPages){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    assert.ok(html.includes(`<html lang="${lang}">`),`${path} must declare lang="${lang}"`);
    assert.equal((html.match(/<h1[\s>]/g)||[]).length,1,`${path} must have exactly one h1`);
    assert.ok(html.includes(`rel="canonical" href="${canonical}"`),`${path} must carry its canonical`);
    const alternates=[...html.matchAll(/<link\b[^>]*\brel="alternate"[^>]*>/g)].map(match=>match[0]);
    assert.equal(alternates.length,1,`${path} must declare one hreflang alternate`);
    const href=alternates[0].match(/\bhref="([^"]+)"/)?.[1];
    assert.ok(href&&href.startsWith('https://www.wordhintlab.com/'),`${path} alternate must be an absolute https URL`);
    assert.notEqual(href,canonical,`${path} alternate must point at the other locale`);
    assert.ok(!html.includes('/assets/app.mjs'),`${path} must not load the game bundle`);
    if(configuredGtmId){
      assertGatedGtmMarkup(html,configuredGtmId,path);
      const scripts=[...html.matchAll(/<script[^>]*>[\s\S]*?<\/script>/g)].map(match=>match[0]);
      assert.equal(scripts.length,1,`${path} must load only the consent module`);
      assert.ok(scripts[0].includes('/assets/consent.mjs'),`${path} must load the consent module`);
    }else{
      assert.ok(!/<script\b/i.test(html),`${path} must not load scripts`);
    }
    assert.ok(html.includes('rel="stylesheet" href="/assets/styles.css"'),`${path} must keep styles local`);
    assert.ok(html.includes('href="/source/"'),`${path} must keep the source link`);
  }
  for(const [path] of allPages){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    const prefix=path.startsWith('en/')?'/en':'';
    for(const target of [`${prefix}/privacy/`,`${prefix}/contact/`]){
      assert.ok(html.includes(`href="${target}"`),`${path} must link ${target}`);
    }
  }
});

test('privacy page discloses the actual storage, practice and analytics behavior', async () => {
  const zh=await readFile(new URL('../dist/privacy/index.html',import.meta.url),'utf8');
  const en=await readFile(new URL('../dist/en/privacy/index.html',import.meta.url),'utf8');
  for(const html of [zh,en]){
    for(const id of ['privacy-storage','privacy-practice','privacy-analytics','privacy-storage-failure','privacy-contact']){
      assert.ok(html.includes(`id="${id}"`),`privacy page must keep the ${id} section`);
    }
    for(const token of ['localStorage',CONSENT_STORAGE_KEY,CONSENT_POLICY_VERSION,'wordhint:daily:v1','wordhint:stats:v1','WORDHINT_ANALYTICS_ENDPOINT','WORDHINT_GTM_ID','credentials: omit','cookie','_ga','_gid','[email protected]']){
      assert.ok(html.includes(token),`privacy page must mention ${token}`);
    }
    assert.ok(html.includes('timestamp') || html.includes('时间戳'),'privacy page must explain the consent timestamp');
    if(configuredGtmId){
      assert.ok(html.includes('data-cookie-settings'),'configured privacy page must offer a change-choice control');
    }else{
      assert.ok(html.includes('当前构建未启用分析通道') || html.includes('No analytics channel is configured'),'unconfigured privacy page must explain that no analytics channel exists');
    }
  }
  assert.ok(zh.includes('练习模式不读取也不写入每日存档或每日统计'),'privacy page must state that practice does not write daily saves');
  assert.ok(zh.includes('不加载任何分析脚本'),'privacy page must state analytics is off by default');
  assert.ok(zh.includes('在你选择“允许分析”前'),'privacy page must state that no request happens before acceptance');
  assert.ok(zh.includes('不会包含猜测的单词'),'privacy page must state custom events exclude guesses');
  assert.ok(en.includes('Practice mode neither reads nor writes the daily save or daily stats'),'English privacy page must state practice does not write daily saves');
  assert.ok(en.includes('loads no analytics script'),'English privacy page must state analytics is off by default');
  assert.ok(en.includes('Before you choose “Allow analytics”'),'English privacy page must state that no request happens before acceptance');
  assert.ok(en.includes('Custom events never include the guessed word'),'English privacy page must state custom events exclude guesses');
});

test('contact page exposes only the confirmed email and no contact form', async () => {
  for(const path of ['contact/index.html','en/contact/index.html']){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    const emails=[...html.matchAll(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g)].map(match=>match[0]);
    assert.deepEqual([...new Set(emails)],['[email protected]'],`${path} must expose only the confirmed email`);
    assert.ok(html.includes('href="mailto:[email protected]"'),`${path} must link the confirmed email`);
    assert.ok(!/<form\b/i.test(html),`${path} must not add a contact form`);
  }
});

test('top-level 404 pages stop soft 404s and match the configured GTM mode', async () => {
  const notFoundPages=[['404.html','zh-CN'],['en/404.html','en']];
  for(const [path,lang] of notFoundPages){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    assert.ok(html.includes(`<html lang="${lang}">`),`${path} must declare lang="${lang}"`);
    assert.ok(html.includes('<meta name="robots" content="noindex">'),`${path} must opt out of indexing`);
    assert.ok(html.includes('Page not found'),`${path} must tell the visitor the page does not exist`);
    for(const href of ['/','/practice/','/en/','/en/practice/']){
      assert.ok(html.includes(`href="${href}"`),`${path} must link the real page ${href}`);
    }
    if(path==='404.html')assert.ok(html.includes('页面不存在'),'the top-level 404 page must be bilingual');
    assert.equal(gtmIdFrom(html),configuredGtmId,`${path} must match WORDHINT_GTM_ID=${configuredGtmId || '(unset)'}`);
    const external=[...html.matchAll(/\b(?:src|href)="((?:https?:)?\/\/[^"]*)"/g)].map(match=>match[1]);
    if(configuredGtmId){
      assert.deepEqual(external,[],`${path} must not reference external resources before consent`);
      assertGatedGtmMarkup(html,configuredGtmId,path);
      const scripts=[...html.matchAll(/<script[^>]*>[\s\S]*?<\/script>/g)].map(match=>match[0]);
      assert.equal(scripts.length,1,`${path} must load only the consent module`);
      assert.ok(scripts[0].includes('/assets/consent.mjs'),`${path} must load the consent module`);
    }else{
      assert.deepEqual(external,[],`${path} must not reference external resources without GTM`);
      assert.ok(!/<script\b/i.test(html),`${path} must not load scripts without GTM`);
    }
  }
});

test('renderers gate GTM behind consent and only ship the loader metadata when configured', () => {
  for(const page of PAGES){
    for(const gtmId of [undefined,'','   ']){
      const html=renderPage(page,gtmId===undefined?{}:{gtmId});
      assert.ok(!html.includes('wordhint-gtm-id'),`${page.path} must not expose a GTM container without GTM`);
      assert.ok(!html.includes('id="cookieBanner"'),`${page.path} must not ask for consent without a channel`);
      assert.ok(!html.includes('/assets/consent.mjs'),`${page.path} must not load the consent gate without a channel`);
      assert.ok(!html.includes('dataLayer'),`${page.path} must not define dataLayer without GTM`);
      assert.ok(!html.includes('window.trackEvent'),`${page.path} must not define trackEvent without GTM`);
    }
    const gtmHtml=renderPage(page,{gtmId:'GTM-TVV8RWFT'});
    assertGatedGtmMarkup(gtmHtml,'GTM-TVV8RWFT',page.path);
    assert.ok(!gtmHtml.includes('window.trackEvent'),`${page.path} must not expose trackEvent before consent`);
    assert.ok(!gtmHtml.includes('dataLayer'),`${page.path} must not define dataLayer before consent`);
  }
  const endpointOnly=renderPage(PAGES[0],{analyticsEndpoint:'https://collect.example/events'});
  assert.ok(endpointOnly.includes('wordhint-analytics-endpoint'),'endpoint-only page must keep its endpoint metadata');
  assert.ok(endpointOnly.includes('id="cookieBanner"'),'endpoint-only page must ask before sending');
  assert.ok(endpointOnly.includes('/assets/consent.mjs'),'endpoint-only page must load the consent gate');
  assert.ok(!endpointOnly.includes('wordhint-gtm-id'),'endpoint-only page must not invent a GTM container');
  for(const locale of ['zh','en']){
    const plain=renderNotFoundPage({locale});
    assert.ok(!plain.includes('<script'),`${locale} 404 must not load scripts without a channel`);
    assert.ok(!plain.includes('id="cookieBanner"'),`${locale} 404 must not ask for consent without a channel`);
    const gated=renderNotFoundPage({locale,gtmId:'GTM-TVV8RWFT'});
    assertGatedGtmMarkup(gated,'GTM-TVV8RWFT',`${locale} 404`);
  }
});

test('invalid GTM container IDs are rejected before injection', () => {
  for(const gtmId of ['GTM-','GTM-abc','UA-12345','GTM-123<script>','GTM-123 456']){
    assert.throws(()=>renderPage(PAGES[0],{gtmId}),/GTM/,`invalid id ${gtmId} must fail the build`);
    assert.throws(()=>renderNotFoundPage({gtmId}),/GTM/);
  }
});

test('shipped consent module keeps the only GTM loader behind the accepted decision', async () => {
  const source=await readFile(new URL('../dist/assets/consent.mjs',import.meta.url),'utf8');
  assert.ok(source.includes('googletagmanager.com/gtm.js'),'the shipped module must contain the runtime GTM loader');
  assert.ok(source.includes('injectGtm'),'the shipped module must expose the gated loader');
  assert.ok(source.includes('consentAllowsAnalytics(consent)'),'the loader must check the accepted decision before injecting');
  assert.ok(source.includes(CONSENT_STORAGE_KEY),'the shipped module must use the versioned storage key');
  assert.ok(!source.includes('<script'),'the shipped module must create the GTM script at runtime, not as static HTML');
});

test('createTrackEvent writes nothing before consent and forwards aggregate events after it', () => {
  const target={WordHintConsent:{isAnalyticsAllowed:()=>false}};
  const trackEvent=createTrackEvent(target);
  trackEvent('hint_viewed',{puzzle:2,hint_step:1,mode:'daily'});
  assert.equal(target.dataLayer,undefined,'pre-consent events must not enter dataLayer');
  target.WordHintConsent={isAnalyticsAllowed:()=>true};
  trackEvent('hint_viewed',{puzzle:2,hint_step:1,mode:'daily'});
  trackEvent('game_completed',{puzzle:2,outcome:'solved',attempts:3,hint_count:1,mode:'daily'});
  assert.deepEqual(JSON.parse(JSON.stringify(target.dataLayer)),[
    {event:'hint_viewed',puzzle:2,hint_step:1,mode:'daily'},
    {event:'game_completed',puzzle:2,outcome:'solved',attempts:3,hint_count:1,mode:'daily'}
  ]);
});

test('sanitized analytics events reach dataLayer without guess, answer or share text', () => {
  const target={WordHintConsent:{isAnalyticsAllowed:()=>true},dispatchEvent(){}};
  target.trackEvent=createTrackEvent(target);
  const returned=emitEvent('game_completed',{
    puzzle:4,outcome:'solved',attempts:3,hint_count:2,mode:'daily',
    guess:'apple',answer:'apple',state:{guesses:['crane']},share_text:'secret'
  },target);
  assert.deepEqual(returned,{name:'game_completed',puzzle:4,outcome:'solved',attempts:3,hint_count:2,mode:'daily'});
  const dataLayer=JSON.parse(JSON.stringify(target.dataLayer));
  assert.deepEqual(dataLayer,[{event:'game_completed',puzzle:4,outcome:'solved',attempts:3,hint_count:2,mode:'daily'}]);
  for(const key of ['name','guess','answer','state','share_text'])assert.ok(!(key in dataLayer[0]),`dataLayer event must not carry ${key}`);
  assert.ok(!JSON.stringify(dataLayer).includes('apple'));
});

test('every canonical derives from the single www SITE_ORIGIN and the bare domain is gone', async () => {
  assert.equal(SITE_ORIGIN, WWW_ORIGIN);
  assert.equal(PAGES.length, 8);
  assert.deepEqual(PAGES.map(page=>[page.locale,page.mode,page.path]),[
    ['zh','daily','index.html'],
    ['zh','practice','practice/index.html'],
    ['en','daily','en/index.html'],
    ['en','practice','en/practice/index.html'],
    ['zh','privacy','privacy/index.html'],
    ['zh','contact','contact/index.html'],
    ['en','privacy','en/privacy/index.html'],
    ['en','contact','en/contact/index.html']
  ]);
  for (const page of PAGES) {
    assert.ok(page.canonical.startsWith(`${WWW_ORIGIN}/`), `${page.path} canonical must start with ${WWW_ORIGIN}: ${page.canonical}`);
  }

  const bareOrigin = WWW_ORIGIN.replace('://www.', '://');
  assert.notEqual(bareOrigin, WWW_ORIGIN);
  let trackedFiles;
  try {
    trackedFiles = execFileSync('git', ['ls-files', '-z'], {cwd: rootDir, encoding: 'utf8'}).split('\0').filter(Boolean);
  } catch {
    const manifest = JSON.parse(await readFile(join(rootDir, 'dist/source-manifest.json'), 'utf8'));
    trackedFiles = manifest.files.map((item) => item.path);
  }
  assert.ok(trackedFiles.includes('src/page-template.mjs'), 'repository scan must enumerate tracked source files');
  const offenders = [];
  for (const file of trackedFiles) {
    if (file === 'docs/prd.md') continue;
    const source = await readFile(join(rootDir, file), 'utf8');
    if (source.includes(bareOrigin)) offenders.push(file);
  }
  assert.deepEqual(offenders, [], `bare origin ${bareOrigin} must not appear outside docs/prd.md: ${offenders.join(', ')}`);
});

test('every module statically imported by the browser entry is shipped in dist/assets', async () => {
  const files=await staticImportClosure(join(srcDir,'app.mjs'));
  const relativeFiles=files.map(file=>relative(srcDir,file));
  assert.ok(relativeFiles.length>1,'the browser entry must have transitive module dependencies');
  assert.ok(relativeFiles.includes('word-data.mjs'),'direct imports must be followed');
  assert.ok(relativeFiles.includes('five-letter-words.mjs'),'transitive imports must be followed');
  for(const file of relativeFiles){
    assert.ok(file&&!file.startsWith('..')&&!isAbsolute(file),`browser module ${file} must live under src/`);
    await access(join(assetsDir,file));
  }
});

test('every production page visibly links to the noindex source browser', async () => {
  for(const [path] of [...allPages,['404.html'],['en/404.html']]){
    const html=await readFile(new URL('../dist/'+path,import.meta.url),'utf8');
    assert.ok(html.includes('href="/source/"'),`${path} must link the public source browser`);
  }
  const browser=await readFile(new URL('../dist/source/index.html',import.meta.url),'utf8');
  assert.ok(browser.includes('<meta name="robots" content="noindex">'),'source browser must opt out of indexing');
  assert.ok(browser.includes('type="search"'),'source browser must offer a file filter');
  assert.ok(browser.includes('../source.zip'),'source browser must link the zip');
  assert.ok(browser.includes('../source-manifest.json'),'source browser must link the manifest');
});

test('source manifest follows the allowlist with hashes and excludes build state', async () => {
  const manifest=JSON.parse(await readFile(new URL('../dist/source-manifest.json',import.meta.url),'utf8'));
  assert.equal(manifest.version,1);
  assert.equal(manifest.schema_version,1);
  assert.equal(manifest.license,'All Rights Reserved');
  assert.match(manifest.generatedAt,/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);
  assert.deepEqual(manifest.entry,{source:'/source/',zip:'/source.zip'});
  assert.equal(manifest.build.command,'npm run build');
  assert.equal(manifest.build.output,'dist');
  const paths=manifest.files.map((item)=>item.path);
  for(const required of ['README.md','LICENSE','package.json','source-files.json','scripts/build.mjs','tools/publish_source.py','tools/verify_source.py','src/page-template.mjs','data/scowl/Copyright','data/scowl/SOURCE.md','data/scowl/english-words.95']){
    assert.ok(paths.includes(required),`source package must include ${required}`);
  }
  const forbidden=[".git","node_modules","dist","artifacts",".tower",".wrangler",".superpowers",".playwright-cli"];
  for(const item of manifest.files){
    assert.match(item.path,/^[A-Za-z0-9_./-]+$/,`manifest path must be safe: ${item.path}`);
    assert.match(item.sha256,/^[0-9a-f]{64}$/,`manifest sha256 must be a lowercase hex digest: ${item.path}`);
    assert.ok(Number.isInteger(item.bytes)&&item.bytes>0,`manifest bytes must be positive: ${item.path}`);
    assert.ok(item.media_type&&typeof item.media_type==='string',`manifest media_type is missing: ${item.path}`);
    for(const segment of item.path.split('/')){
      assert.ok(!forbidden.includes(segment),`${item.path} must not include ${segment}`);
      assert.ok(!segment.startsWith('.env'),`${item.path} must not include environment files`);
    }
    const viewer=await readFile(new URL(`../dist/source/view/${item.path}.viewer.html`,import.meta.url),'utf8');
    assert.ok(viewer.includes('<meta name="robots" content="noindex">'),`source viewer must opt out of indexing: ${item.path}`);
  }
});

test('independent source verifier passes against the built artifacts', () => {
  const output=execFileSync(process.env.PYTHON||'python3',['tools/verify_source.py','--root','.','--dist','dist'],{cwd:rootDir,encoding:'utf8'});
  assert.match(output,/^PASS: \d+ source files match the manifest and ZIP/);
});