Back

91.09% Statements 307/337
73.68% Branches 42/57
100% Functions 13/13
91.09% Lines 307/337

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 3383x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 21x 21x 21x 3x 3x 3x 3x 3x 3x 3x 3x 11x 11x 11x 11x 11x 11x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 51x 51x 3x 3x 3x 3x 3x 3x 3x 3x 3x 18x 18x 18x 18x 18x 18x 17x 38x 38x     38x 38x 38x 38x 38x 38x 17x 18x 18x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 18x 18x     18x 18x 18x 18x 3x 3x 3x 3x 3x 3x 3x 3x 28x 28x 28x 28x     28x 3x 3x 3x 3x 3x 3x 3x 12x 12x 12x     12x 12x 80x 380x 380x 68x 380x 156x 156x 380x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 16x 16x 16x 16x     16x 16x 16x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 16x 16x     16x 16x       16x                   16x 16x 16x 16x 16x 16x 4x 4x 4x 12x 12x     12x 12x     12x 48x 48x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 48x 12x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x  
/* global __dirname, process */
/**
 * Export-contract validation: assert every symbol a consumer package imports from
 * a polyfilled provider actually exists in the shipped provider's public exports.
 * A missing symbol resolves to `undefined` at runtime (blank dashboard, no build
 * error) — the Jetpack 16.0 failure mode. Shared by the post-build CLI and tests.
 */
 
const { readFileSync, readdirSync, existsSync } = require( 'fs' );
const path = require( 'path' );
 
/**
 * Map a classic-script handle to its npm package name (`wp-theme` → `@wordpress/theme`).
 *
 * @param {string} handle - A `wp-*` script handle.
 * @return {string} The `@wordpress/*` package name.
 */
function handleToPackage( handle ) {
	return '@wordpress/' + handle.replace( /^wp-/, '' );
}
 
/**
 * Extract the string values of a `const NAME = array( 'a', 'b' );` PHP class constant.
 *
 * @param {string} phpSource - PHP file contents.
 * @param {string} constName - Constant name.
 * @return {string[]} The array's string values, or [] if not found.
 */
function parsePhpConstArray( phpSource, constName ) {
	const match = phpSource.match(
		new RegExp( `const\\s+${ constName }\\s*=\\s*array\\(([^)]*)\\)` )
	);
	return match ? match[ 1 ].match( /'([^']+)'/g )?.map( s => s.replace( /'/g, '' ) ) ?? [] : [];
}
 
/**
 * Derive the shipped provider/consumer lists from the class constants in
 * class-wp-build-polyfills.php (SCRIPT_HANDLES + MODULE_IDS) — the single source of
 * truth that also registers them at runtime. Providers are the classic-script globals
 * whose exports we verify; consumers are the ESM modules that import them.
 *
 * @param {string} packageRoot - Polyfill package root.
 * @return {{ providers: string[], consumers: string[] }} Providers and consumers.
 */
function getShippedPackages( packageRoot ) {
	const php = readFileSync(
		path.join( packageRoot, 'src', 'class-wp-build-polyfills.php' ),
		'utf8'
	);
	return {
		providers: parsePhpConstArray( php, 'SCRIPT_HANDLES' ).map( handleToPackage ),
		consumers: parsePhpConstArray( php, 'MODULE_IDS' ),
	};
}
 
/**
 * Original names of the symbols named-imported from a provider in ESM source.
 * Handles `import { A, B as C } from '@wordpress/x'` and the mixed default form
 * `import Def, { A } from '@wordpress/x'` (imported name is before `as`); a pure
 * default or namespace import has no `{ … }` and is ignored (can't be a missing
 * named export).
 *
 * @param {string} source      - ESM source text.
 * @param {string} providerPkg - e.g. '@wordpress/theme'.
 * @return {string[]} Sorted, de-duplicated imported symbol names.
 */
function parseNamedImports( source, providerPkg ) {
	const found = new Set();
	const escaped = providerPkg.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' );
	// Optional `Default,` before the named block covers `import Def, { A } from …`.
	const re = new RegExp(
		`import\\s*(?:[\\w$]+\\s*,\\s*)?\\{([^}]*)\\}\\s*from\\s*['"]${ escaped }['"]`,
		'g'
	);
	let match;
	while ( ( match = re.exec( source ) ) !== null ) {
		for ( const specifier of match[ 1 ].split( ',' ) ) {
			const name = specifier
				.trim()
				.split( /\s+as\s+/ )[ 0 ]
				.trim();
			if ( name ) {
				found.add( name );
			}
		}
	}
	return [ ...found ].sort();
}
 
/**
 * Public export names from a provider's built ESM index. Handles `export { A, B as C }`
 * (public name is after `as`); flags wildcard `export *` as opaque so callers skip it
 * rather than emit a false "missing export".
 *
 * @param {string} indexSource - Contents of the package's `module`/`main` entry.
 * @return {{ names: string[], opaque: boolean }} Public export names + opacity flag.
 */
function parsePublicExports( indexSource ) {
	const names = new Set();
	const opaque = /export\s*\*/.test( indexSource );
	const re = /export\s*\{([^}]*)\}/g;
	let match;
	while ( ( match = re.exec( indexSource ) ) !== null ) {
		for ( const specifier of match[ 1 ].split( ',' ) ) {
			const trimmed = specifier.trim();
			if ( ! trimmed ) {
				continue;
			}
			const parts = trimmed.split( /\s+as\s+/ );
			const name = parts[ parts.length - 1 ].trim();
			if ( name ) {
				names.add( name );
			}
		}
	}
	return { names: [ ...names ].sort(), opaque };
}
 
/**
 * Contract check for one (consumer → provider) pair.
 *
 * @param {object}   args          - The pair and its symbols.
 * @param {string}   args.consumer - Consumer package name.
 * @param {string}   args.provider - Provider package name.
 * @param {string[]} args.imported - Symbols the consumer imports.
 * @param {string[]} args.exported - Provider's public export names.
 * @param {boolean}  [args.opaque] - True when the provider's exports can't be enumerated.
 * @return {{ ok: boolean, consumer: string, provider: string, missing: string[], skipped?: boolean }} Result.
 */
function checkContract( { consumer, provider, imported, exported, opaque = false } ) {
	if ( opaque ) {
		return { ok: true, consumer, provider, missing: [], skipped: true };
	}
	const exportedSet = new Set( exported );
	const missing = imported.filter( name => ! exportedSet.has( name ) );
	return { ok: missing.length === 0, consumer, provider, missing };
}
 
/**
 * Resolve a package's directory from a base dir (same resolution the build uses).
 *
 * @param {string} pkgName - e.g. '@wordpress/theme'.
 * @param {string} fromDir - Directory to resolve from.
 * @return {string|null} Absolute package directory, or null if unresolvable.
 */
function resolvePackageDir( pkgName, fromDir ) {
	try {
		return path.dirname( require.resolve( `${ pkgName }/package.json`, { paths: [ fromDir ] } ) );
	} catch {
		return null;
	}
}
 
/**
 * Concatenated ESM source of every `*.mjs` under a package's `build-module` dir.
 *
 * @param {string} pkgDir - Absolute package directory.
 * @return {string} Concatenated source, or '' if no build-module dir.
 */
function readBuildModuleSource( pkgDir ) {
	const dir = path.join( pkgDir, 'build-module' );
	if ( ! existsSync( dir ) ) {
		return '';
	}
	const chunks = [];
	const walk = current => {
		for ( const entry of readdirSync( current, { withFileTypes: true } ) ) {
			const full = path.join( current, entry.name );
			if ( entry.isDirectory() ) {
				walk( full );
			} else if ( entry.name.endsWith( '.mjs' ) ) {
				chunks.push( readFileSync( full, 'utf8' ) );
			}
		}
	};
	walk( dir );
	return chunks.join( '\n' );
}
 
/**
 * Read a provider's public export names from its ESM entry point.
 *
 * @param {string} pkgDir - Absolute package directory.
 * @return {{ names: string[], opaque: boolean } | null} Exports, or null if unreadable.
 */
function readPackageExports( pkgDir ) {
	const pkg = JSON.parse( readFileSync( path.join( pkgDir, 'package.json' ), 'utf8' ) );
	const entry = pkg.module || pkg.main;
	if ( ! entry ) {
		return null;
	}
	const entryPath = path.join( pkgDir, entry );
	return existsSync( entryPath ) ? parsePublicExports( readFileSync( entryPath, 'utf8' ) ) : null;
}
 
/**
 * Format an actionable error message for failed contracts.
 *
 * @param {object[]} failures - Failed contract results.
 * @param {string[]} errors   - Non-contract errors (unreadable packages).
 * @return {string} Formatted message.
 */
function formatError( failures, errors ) {
	const lines = [];
	if ( failures.length ) {
		lines.push(
			'Export-contract violation: a polyfilled package imports symbols the shipped',
			'version of another polyfilled package does not export — this resolves to',
			'`undefined` at runtime (blank dashboard, no build error; the Jetpack 16.0',
			'failure mode). Bump the provider so its public API matches, keeping the',
			'`@wordpress/*` set version-aligned.',
			''
		);
		for ( const f of failures ) {
			lines.push(
				`   ${ f.consumer } imports from ${ f.provider }: [ ${ f.missing.join(
					', '
				) } ] — not exported.`
			);
		}
	}
	if ( errors.length ) {
		lines.push( '', ...errors );
	}
	return lines.join( '\n' );
}
 
/**
 * Parse WP_BUILD_POLYFILLS_SIMULATE_MISSING (`pkg:Symbol,pkg:Symbol`) into a
 * `{ pkg: [ symbol ] }` drop-map. This is a TEST-ONLY hook that lets the CLI's
 * failure path be exercised end-to-end (see the CLI test); it is not a
 * user-facing feature.
 *
 * @param {string|undefined} raw - Raw env value.
 * @return {object} Map of provider package → symbol[] to drop.
 */
function parseSimulateEnv( raw ) {
	const map = {};
	for ( const pair of ( raw || '' ).split( ',' ) ) {
		const idx = pair.lastIndexOf( ':' );
		const pkg = idx === -1 ? '' : pair.slice( 0, idx ).trim();
		const symbol = idx === -1 ? '' : pair.slice( idx + 1 ).trim();
		if ( pkg && symbol ) {
			( map[ pkg ] = map[ pkg ] || [] ).push( symbol );
		}
	}
	return map;
}
 
/**
 * Validate the export contracts across the shipped package set. Reads the shipped
 * versions from the polyfill's own resolution context (same as the build).
 *
 * @param {object}   [options]                 - Options.
 * @param {string}   [options.packageRoot]     - Polyfill package root. Defaults to this package.
 * @param {string[]} [options.providers]       - Override provider list (tests).
 * @param {string[]} [options.consumers]       - Override consumer list (tests).
 * @param {object}   [options.simulateMissing] - Map of providerPkg → symbol[] to drop, to simulate a skew (tests).
 * @return {{ ok: boolean, results: object[], errors: string[], error?: string }} Aggregate result.
 */
function validateExportContracts( options = {} ) {
	const packageRoot = options.packageRoot || path.join( __dirname, '..' );
	const shipped = getShippedPackages( packageRoot );
	const providers = options.providers || shipped.providers;
	const consumers = options.consumers || shipped.consumers;
	const simulateMissing =
		options.simulateMissing || parseSimulateEnv( process.env.WP_BUILD_POLYFILLS_SIMULATE_MISSING );
 
	const errors = [];
	const providerExports = {};
	for ( const provider of providers ) {
		const dir = resolvePackageDir( provider, packageRoot );
		if ( ! dir ) {
			continue; // Not installed → not shipped.
		}
		const exp = readPackageExports( dir );
		if ( ! exp ) {
			errors.push( `Could not read exports for ${ provider }.` );
			continue;
		}
		if ( exp.opaque ) {
			// A barrel (`export *`) can't be statically enumerated, so we can't verify
			// this provider — warn loudly rather than skip it silently, which would be
			// a hole in exactly the protection this check exists for.
			// eslint-disable-next-line no-console
			console.warn(
				`[export-contract] Not verifying ${ provider }: its index uses \`export *\`, ` +
					'so its public exports can’t be enumerated statically.'
			);
		}
		const dropped = simulateMissing[ provider ] || [];
		providerExports[ provider ] = {
			names: exp.names.filter( n => ! dropped.includes( n ) ),
			opaque: exp.opaque,
		};
	}
 
	const results = [];
	for ( const consumer of consumers ) {
		const dir = resolvePackageDir( consumer, packageRoot );
		if ( ! dir ) {
			continue;
		}
		const source = readBuildModuleSource( dir );
		if ( ! source ) {
			continue;
		}
		for ( const provider of Object.keys( providerExports ) ) {
			const imported = parseNamedImports( source, provider );
			if ( imported.length ) {
				results.push(
					checkContract( {
						consumer,
						provider,
						imported,
						exported: providerExports[ provider ].names,
						opaque: providerExports[ provider ].opaque,
					} )
				);
			}
		}
	}
 
	const failures = results.filter( r => ! r.ok );
	const ok = failures.length === 0 && errors.length === 0;
	return { ok, results, errors, error: ok ? undefined : formatError( failures, errors ) };
}
 
module.exports = {
	handleToPackage,
	parsePhpConstArray,
	getShippedPackages,
	parseNamedImports,
	parsePublicExports,
	checkContract,
	validateExportContracts,
};