import { lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, } from 'node:fs/promises'; import { basename, dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { chromium } from '@playwright/test'; const LOCAL_HOSTS = new Set( [ 'localhost', '127.0.0.1' ] ); const REVIEW_PARENT_DIRECTORY = fileURLToPath( new URL( '../tmp/imagegen/', import.meta.url ) ); const OUTPUT_DIRECTORY = join( REVIEW_PARENT_DIRECTORY, 'grunge-stage-review.png' ); const OUTPUT_DIRECTORY_NAME = 'grunge-stage-review.png'; const STORAGE_KEY = 'chrnx-theme'; const THEMES = [ 'light', 'dark' ]; const VIEWPORTS = [ { width: 375, height: 812 }, { width: 768, height: 1024 }, { width: 1440, height: 900 }, { width: 2560, height: 1080 }, ]; const TARGETS = [ { name: 'music', path: '/music/' }, { name: 'podcasts', path: '/podcasts/' }, { name: 'podcasts-long-copy', path: '/podcasts/', longCopy: { titleSelector: '.chrnx-latest-podcast .chrnx-podcast-card__title', excerptSelector: '.chrnx-latest-podcast .chrnx-podcast-card__excerpt', title: 'Cuando la conversación se alarga: arquitectura, cultura digital y las decisiones incómodas que sostienen un podcast independiente', excerpt: 'Una descripción deliberadamente extensa para revisar el comportamiento real de la tarjeta más reciente cuando el título y el resumen ocupan varias líneas, sin modificar WordPress ni fabricar una segunda tarjeta.', }, }, ]; export const CAPTURE_PLAN = TARGETS.flatMap( ( target ) => VIEWPORTS.flatMap( ( viewport ) => THEMES.map( ( theme ) => ( { target, viewport, theme, filename: `grunge-stage-${ target.name }-${ viewport.width }-${ theme }.png`, } ) ), ), ); function normalizeReviewPath( pathname ) { const withLeadingSlash = pathname.startsWith( '/' ) ? pathname : `/${ pathname }`; return withLeadingSlash.endsWith( '/' ) ? withLeadingSlash : `${ withLeadingSlash }/`; } export function getBaseURL( value = process.env.CHRNX_REVIEW_URL || 'http://localhost:8888' ) { let url; try { url = new URL( value ); } catch { throw new Error( 'Capture URL must be a valid local HTTP URL.' ); } if ( url.protocol !== 'http:' || ! LOCAL_HOSTS.has( url.hostname ) || url.username || url.password || ( url.pathname !== '/' && url.pathname !== '' ) || url.search || url.hash ) { throw new Error( 'Capture URL must be credential-free HTTP on localhost or 127.0.0.1.' ); } return url; } export function assertFinalNavigation( baseURL, expectedPath, finalURL ) { const final = new URL( finalURL ); if ( final.origin !== baseURL.origin ) { throw new Error( `Capture redirected to unexpected origin ${ final.origin }.` ); } if ( normalizeReviewPath( final.pathname ) !== normalizeReviewPath( expectedPath ) ) { throw new Error( `Capture redirected to unexpected path ${ final.pathname }.` ); } } function getPngDimensions( buffer ) { if ( buffer.length < 33 || buffer.subarray( 0, 8 ).toString( 'hex' ) !== '89504e470d0a1a0a' || buffer.subarray( 12, 16 ).toString( 'ascii' ) !== 'IHDR' ) { throw new Error( 'Screenshot did not produce a valid nonempty PNG.' ); } return { width: buffer.readUInt32BE( 16 ), height: buffer.readUInt32BE( 20 ), }; } async function optionalLstat( path ) { try { return await lstat( path ); } catch ( error ) { if ( error.code === 'ENOENT' ) { return null; } throw error; } } async function assertSafeOutput( outputDirectory, allowedParentDirectory, capturePlan ) { const parentPath = resolve( allowedParentDirectory ); const outputPath = resolve( outputDirectory ); if ( dirname( outputPath ) !== parentPath || basename( outputPath ) !== OUTPUT_DIRECTORY_NAME ) { throw new Error( 'Review output must be the dedicated direct child of its approved parent.' ); } const parentStats = await lstat( parentPath ); if ( parentStats.isSymbolicLink() || ! parentStats.isDirectory() ) { throw new Error( 'Review output parent cannot be a symbolic link.' ); } const outputStats = await optionalLstat( outputPath ); if ( outputStats?.isSymbolicLink() ) { throw new Error( 'Review output cannot be a symbolic link.' ); } if ( outputStats && ! outputStats.isDirectory() ) { throw new Error( 'Review output must be a directory.' ); } if ( outputStats ) { for ( const capture of capturePlan ) { const fileStats = await optionalLstat( join( outputPath, capture.filename ) ); if ( fileStats?.isSymbolicLink() || ( fileStats && ! fileStats.isFile() ) ) { throw new Error( `Review output file cannot be a symbolic link: ${ capture.filename }.` ); } } } return { outputPath, parentPath, outputExists: Boolean( outputStats ) }; } async function removeLegacyEvidence( parentPath, capturePlan ) { for ( const capture of capturePlan ) { const legacyPath = join( parentPath, capture.filename ); const stats = await optionalLstat( legacyPath ); if ( stats?.isSymbolicLink() || ( stats && ! stats.isFile() ) ) { throw new Error( `Legacy review evidence cannot be a symbolic link: ${ capture.filename }.` ); } if ( stats ) { await rm( legacyPath ); } } } async function validateEvidence( directory, capturePlan ) { const expectedNames = capturePlan.map( ( capture ) => capture.filename ).sort(); const actualNames = ( await readdir( directory ) ).sort(); if ( new Set( expectedNames ).size !== 24 || actualNames.length !== 24 ) { throw new Error( 'Review evidence must contain exactly 24 fresh PNG files.' ); } if ( expectedNames.some( ( name, index ) => name !== actualNames[ index ] ) ) { throw new Error( 'Review evidence filenames do not match the approved set.' ); } for ( const capture of capturePlan ) { const path = join( directory, capture.filename ); const stats = await lstat( path ); if ( stats.isSymbolicLink() || ! stats.isFile() || stats.size === 0 ) { throw new Error( `Invalid review evidence file ${ capture.filename }.` ); } const dimensions = getPngDimensions( await readFile( path ) ); if ( dimensions.width !== capture.viewport.width || dimensions.height < 1 ) { throw new Error( `Invalid dimensions for ${ capture.filename }.` ); } } } export async function publishReviewEvidence( { outputDirectory, allowedParentDirectory, capturePlan, captureImage, } ) { const { outputPath, parentPath, outputExists } = await assertSafeOutput( outputDirectory, allowedParentDirectory, capturePlan, ); await removeLegacyEvidence( parentPath, capturePlan ); const stagingPath = await mkdtemp( join( parentPath, '.grunge-stage-staging-' ) ); const backupPath = join( parentPath, '.grunge-stage-backup' ); let backupCreated = false; let published = false; try { for ( const capture of capturePlan ) { await captureImage( capture, join( stagingPath, capture.filename ) ); } await validateEvidence( stagingPath, capturePlan ); if ( outputExists ) { if ( await optionalLstat( backupPath ) ) { throw new Error( 'A previous review backup must be resolved before publication.' ); } await rename( outputPath, backupPath ); backupCreated = true; } try { await rename( stagingPath, outputPath ); published = true; } catch ( error ) { if ( backupCreated ) { await rename( backupPath, outputPath ); backupCreated = false; } throw error; } if ( backupCreated ) { await rm( backupPath, { recursive: true } ); backupCreated = false; } } finally { if ( ! published ) { await rm( stagingPath, { recursive: true, force: true } ); } if ( backupCreated && ! await optionalLstat( outputPath ) ) { await rename( backupPath, outputPath ); } } } async function waitForStablePage( page ) { await page.addStyleTag( { content: '*,*::before,*::after{animation:none!important;transition:none!important}', } ); await page.evaluate( async () => { const timeout = new Promise( ( _, reject ) => setTimeout( () => reject( new Error( 'Timed out waiting for fonts and images.' ) ), 5_000 ), ); const ready = ( async () => { await document.fonts.ready; for ( let y = 0; y <= document.documentElement.scrollHeight; y += window.innerHeight ) { window.scrollTo( 0, y ); await new Promise( ( resolve ) => requestAnimationFrame( () => requestAnimationFrame( resolve ) ), ); } await Promise.all( [ ...document.images ].map( async ( image ) => { await image.decode(); if ( ! image.complete || image.naturalWidth === 0 ) { throw new Error( `Image failed to decode: ${ image.currentSrc || image.src }` ); } } ), ); window.scrollTo( 0, 0 ); } )(); await Promise.race( [ ready, timeout ] ); } ); } async function replaceLongCopy( page, target ) { if ( ! target.longCopy ) { return; } const title = page.locator( target.longCopy.titleSelector ); const excerpt = page.locator( target.longCopy.excerptSelector ); await title.waitFor( { state: 'visible', timeout: 5_000 } ); await excerpt.waitFor( { state: 'visible', timeout: 5_000 } ); await title.evaluate( ( element, value ) => { element.textContent = value; }, target.longCopy.title ); await excerpt.evaluate( ( element, value ) => { element.textContent = value; }, target.longCopy.excerpt ); } async function captureImage( baseURL, capture, outputPath ) { const { target, viewport, theme } = capture; const browser = await chromium.launch(); let context; try { context = await browser.newContext( { viewport, colorScheme: theme, reducedMotion: 'reduce', } ); await context.addInitScript( ( [ key, preference ] ) => { localStorage.clear(); localStorage.setItem( key, preference ); }, [ STORAGE_KEY, theme ], ); const page = await context.newPage(); page.setDefaultTimeout( 5_000 ); page.setDefaultNavigationTimeout( 15_000 ); await page.route( '**/*', async ( route ) => { const requestURL = new URL( route.request().url() ); if ( requestURL.origin === baseURL.origin ) { await route.continue(); } else { await route.abort( 'blockedbyclient' ); } } ); const response = await page.goto( new URL( target.path, baseURL ).href, { waitUntil: 'domcontentloaded', timeout: 15_000, } ); if ( ! response?.ok() ) { throw new Error( `Capture target ${ target.path } returned HTTP ${ response?.status() ?? 'unknown' }.`, ); } assertFinalNavigation( baseURL, target.path, page.url() ); await page.waitForFunction( ( expectedTheme ) => document.documentElement.dataset.theme === expectedTheme, theme, { timeout: 5_000 }, ); await page.locator( 'main' ).waitFor( { state: 'visible', timeout: 5_000 } ); await replaceLongCopy( page, target ); await waitForStablePage( page ); await page.screenshot( { path: outputPath, fullPage: true, animations: 'disabled', caret: 'hide', } ); } finally { try { await context?.close(); } finally { await browser.close(); } } } async function main() { const baseURL = getBaseURL(); await mkdir( REVIEW_PARENT_DIRECTORY, { recursive: true } ); await publishReviewEvidence( { outputDirectory: OUTPUT_DIRECTORY, allowedParentDirectory: REVIEW_PARENT_DIRECTORY, capturePlan: CAPTURE_PLAN, captureImage: ( capture, outputPath ) => captureImage( baseURL, capture, outputPath ), } ); for ( const capture of CAPTURE_PLAN ) { const buffer = await readFile( join( OUTPUT_DIRECTORY, capture.filename ) ); const dimensions = getPngDimensions( buffer ); process.stdout.write( `${ capture.filename } ${ dimensions.width }x${ dimensions.height }\n` ); } } if ( import.meta.url === pathToFileURL( process.argv[ 1 ] ?? '' ).href ) { await main(); }