Automattic\WooCommerce\Blocks

DependencyDetection::output_early_proxy_setuppublicWC 10.5.0

Output early inline script to set up the Proxy on window.wc.

This must run before any WooCommerce scripts to intercept access. The script is loaded from a separate file for better IDE support and testing, but output inline to ensure correct timing (before any enqueued scripts).

Method of the class: DependencyDetection{}

No Hooks.

Returns

null. Nothing (null).

Usage

$DependencyDetection = new DependencyDetection();
$DependencyDetection->output_early_proxy_setup(): void;

Changelog

Since 10.5.0 Introduced.

DependencyDetection::output_early_proxy_setup() code WC 10.7.0

public function output_early_proxy_setup(): void {
	// Only run on pages that have the tracked blocks.
	if ( ! $this->page_has_tracked_blocks() ) {
		return;
	}

	// Load from the production assets directory (built by webpack and copied during release build).
	$script_path = __DIR__ . '/../../assets/client/blocks/dependency-detection.js';

	if ( ! file_exists( $script_path ) ) {
		return;
	}

	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local file read for inline script output.
	$script_content = file_get_contents( $script_path );

	if ( ! $script_content ) {
		return;
	}

	// Inject the global-to-handle mapping from PHP (source of truth).
	$mapping_json = \wp_json_encode( self::WC_GLOBAL_EXPORTS );
	if ( false === $mapping_json ) {
		return;
	}
	$script_content = str_replace(
		'__WC_GLOBAL_EXPORTS_PLACEHOLDER__',
		$mapping_json,
		$script_content
	);

	// Inject the WooCommerce plugin URL for script origin detection.
	// This accounts for custom plugin directories (WP_PLUGIN_DIR, WP_CONTENT_DIR).
	$wc_plugin_url  = \plugins_url( '/', WC_PLUGIN_FILE );
	$script_content = str_replace(
		'__WC_PLUGIN_URL_PLACEHOLDER__',
		'"' . esc_js( $wc_plugin_url ) . '"',
		$script_content
	);

	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Script content is from a trusted local file, JSON is safely encoded.
	echo '<script id="wc-dependency-detection">' . $script_content . '</script>' . "\n";

	$this->proxy_output = true;
}