From 88d60e4f64b2391ba9e2965a721ade86aec0809b Mon Sep 17 00:00:00 2001
From: Pascal Birchler <pascalb@google.com>
Date: Sat, 28 Sep 2024 20:51:04 +0200
Subject: [PATCH] Fix output buffering for cross-origin isolation (#65701)

---
 lib/experimental/media/load.php | 31 ++++++++++++++++++++++---------
 1 file changed, 22 insertions(+), 9 deletions(-)

diff --git a/lib/experimental/media/load.php b/lib/experimental/media/load.php
index 5cb16d84e1d8d..bcb02accf62a6 100644
--- a/lib/experimental/media/load.php
+++ b/lib/experimental/media/load.php
@@ -186,6 +186,24 @@ function gutenberg_rest_get_attachment_filesize( array $post ): ?int {
 	return null;
 }
 
+/**
+ * Filters the list of rewrite rules formatted for output to an .htaccess file.
+ *
+ * Adds support for serving wasm-vips locally.
+ *
+ * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
+ * @return string Filtered rewrite rules.
+ */
+function gutenberg_filter_mod_rewrite_rules( string $rules ): string {
+	$rules .= "\n# BEGIN Gutenberg client-side media processing experiment\n" .
+				"AddType application/wasm wasm\n" .
+				"# END Gutenberg client-side media processing experiment\n";
+
+	return $rules;
+}
+
+add_filter( 'mod_rewrite_rules', 'gutenberg_filter_mod_rewrite_rules' );
+
 /**
  * Enables cross-origin isolation in the block editor.
  *
@@ -236,16 +254,11 @@ function gutenberg_start_cross_origin_isolation_output_buffer(): void {
 	$coep = $is_safari ? 'require-corp' : 'credentialless';
 
 	ob_start(
-		function ( string $output, ?int $phase ) use ( $coep ): string {
-			// Only send the header when the buffer is not being cleaned.
-			if ( ( $phase & PHP_OUTPUT_HANDLER_CLEAN ) === 0 ) {
-				header( 'Cross-Origin-Opener-Policy: same-origin' );
-				header( "Cross-Origin-Embedder-Policy: $coep" );
-
-				$output = gutenberg_add_crossorigin_attributes( $output );
-			}
+		function ( string $output ) use ( $coep ): string {
+			header( 'Cross-Origin-Opener-Policy: same-origin' );
+			header( "Cross-Origin-Embedder-Policy: $coep" );
 
-			return $output;
+			return gutenberg_add_crossorigin_attributes( $output );
 		}
 	);
 }