-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathclass-static-site-importer-theme-materializer.php
More file actions
2191 lines (1926 loc) · 87.5 KB
/
Copy pathclass-static-site-importer-theme-materializer.php
File metadata and controls
2191 lines (1926 loc) · 87.5 KB
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Theme file materialization helpers.
*
* @package StaticSiteImporter
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Writes generated theme artifacts to disk.
*/
class Static_Site_Importer_Theme_Materializer {
/**
* Build static generated theme file writes.
*
* @param string $theme_dir Theme directory.
* @param string $theme_slug Theme slug.
* @param string $theme_name Theme name.
* @param string $css Source CSS.
* @param bool $has_header_part Whether a header template part exists.
* @param bool $has_footer_part Whether a footer template part exists.
* @param array<int,array<string,mixed>> $scripts Materialized script asset rows.
* @param array<int,array<string,mixed>> $stylesheets Materialized stylesheet asset rows.
* @param array<string,mixed> $artifacts Compiled website artifacts.
* @return array<string,string> Absolute write paths mapped to file contents.
*/
public static function base_theme_writes( string $theme_dir, string $theme_slug, string $theme_name, string $css, bool $has_header_part, bool $has_footer_part, array $scripts = array(), array $stylesheets = array(), array $artifacts = array() ): array {
return array(
$theme_dir . '/functions.php' => self::functions_php( $theme_slug, $scripts, $stylesheets ),
$theme_dir . '/theme.json' => self::theme_json( $theme_name, $css, $artifacts ),
$theme_dir . '/templates/404.html' => self::not_found_template( $has_header_part, $has_footer_part ),
$theme_dir . '/templates/archive.html' => self::archive_template( $has_header_part, $has_footer_part ),
$theme_dir . '/templates/front-page.html' => self::content_template( '', $has_header_part, $has_footer_part ),
$theme_dir . '/templates/page.html' => self::content_template( '', $has_header_part, $has_footer_part ),
$theme_dir . '/templates/index.html' => self::content_template( '', $has_header_part, $has_footer_part ),
);
}
/**
* Build the generated archive template.
*
* @param bool $has_header_part Whether a shared header template part was generated.
* @param bool $has_footer_part Whether a shared footer template part was generated.
* @return string
*/
private static function archive_template( bool $has_header_part, bool $has_footer_part ): string {
return self::content_template( '', $has_header_part, $has_footer_part );
}
/**
* Build the generated 404 template.
*
* @param bool $has_header_part Whether a shared header template part was generated.
* @param bool $has_footer_part Whether a shared footer template part was generated.
* @return string
*/
private static function not_found_template( bool $has_header_part, bool $has_footer_part ): string {
$body = '<!-- wp:heading {"level":1} --><h1 class="wp-block-heading">Page not found</h1><!-- /wp:heading -->' . "\n\n" .
'<!-- wp:paragraph --><p>The requested page could not be found.</p><!-- /wp:paragraph -->';
return self::content_template( $body, $has_header_part, $has_footer_part );
}
/**
* Build a template that renders imported page content.
*
* @param string $background_blocks Background decoration blocks.
* @param bool $has_header_part Whether a shared header template part was generated.
* @param bool $has_footer_part Whether a shared footer template part was generated.
* @return string
*/
public static function content_template( string $background_blocks, bool $has_header_part, bool $has_footer_part ): string {
$header_part = $has_header_part ? '<!-- wp:template-part {"slug":"header","tagName":"header"} /-->' : '';
$footer_part = $has_footer_part ? '<!-- wp:template-part {"slug":"footer","tagName":"footer"} /-->' : '';
return trim(
$header_part . "\n\n" .
$background_blocks . "\n\n" .
'<!-- wp:post-content /-->' . "\n\n" .
$footer_part
) . "\n";
}
/**
* Build a theme pattern file for an imported page body.
*
* @param string $title Pattern title.
* @param string $pattern_slug Pattern slug.
* @param string $content Block markup.
* @return string
*/
public static function pattern_file( string $title, string $pattern_slug, string $content ): string {
return "<?php\n" .
"/**\n" .
' * Title: ' . $title . "\n" .
' * Slug: ' . $pattern_slug . "\n" .
" * Categories: static-site-importer\n" .
" */\n" .
"?>\n" .
trim( $content ) . "\n";
}
/**
* Ensure theme directories exist.
*
* @param string $theme_dir Theme directory.
* @return true|WP_Error
*/
public static function ensure_dirs( string $theme_dir ) {
foreach ( array( $theme_dir, $theme_dir . '/templates', $theme_dir . '/parts', $theme_dir . '/patterns', $theme_dir . '/assets', $theme_dir . '/assets/css', $theme_dir . '/assets/icons', $theme_dir . '/assets/media' ) as $dir ) {
if ( ! wp_mkdir_p( $dir ) ) {
return new WP_Error( 'static_site_importer_mkdir_failed', sprintf( 'Failed to create directory: %s', $dir ) );
}
}
return true;
}
/**
* Write compiler-emitted files that can be consumed without re-importing HTML.
*
* @param string $theme_dir Theme directory.
* @param string $theme_uri Theme URI.
* @param array<string,mixed> $artifacts WordPress artifacts from Blocks Engine.
* @param bool $write_files Whether to write materialized asset files.
* @param string $svg_font_usage_markup Bounded page SVG candidates that can be promoted.
* @return array{css:string,js:string,assets:array<string,array<string,mixed>>,scripts:array<int,array<string,mixed>>,stylesheets:array<int,array<string,mixed>>,diagnostics:array<int,array<string,mixed>>}|WP_Error
*/
public static function materialize_website_artifact_files( string $theme_dir, string $theme_uri, array $artifacts, bool $write_files = true, string $svg_font_usage_markup = '' ) {
$native_plan = self::materialize_materialization_plan_assets( $theme_dir, $theme_uri, $artifacts, $write_files, $svg_font_usage_markup );
if ( is_wp_error( $native_plan ) || null !== $native_plan ) {
return $native_plan;
}
$files = isset( $artifacts['files'] ) && is_array( $artifacts['files'] ) ? $artifacts['files'] : array();
if ( isset( $artifacts['source_files'] ) && is_array( $artifacts['source_files'] ) ) {
$files = array_merge( $files, $artifacts['source_files'] );
}
$css = array();
$assets = array();
$diagnostics = array();
foreach ( $files as $file ) {
if ( ! is_array( $file ) ) {
continue;
}
$relative = self::normalize_artifact_materialization_path( isset( $file['path'] ) ? (string) $file['path'] : '' );
$retention = self::source_retention_policy( $file, $relative, 'website_artifact:files' );
if ( '' === $relative ) {
$diagnostics[] = array(
'type' => 'website_artifact_file_skipped',
'source' => 'website_artifact:files',
'reason' => 'unsafe_artifact_path',
'path' => isset( $file['path'] ) && is_scalar( $file['path'] ) ? (string) $file['path'] : '',
'message' => 'A website artifact file was skipped because its path is not safe to materialize inside the generated theme.',
);
continue;
}
if ( isset( $retention['diagnostic'] ) ) {
$diagnostics[] = $retention['diagnostic'];
}
$content = self::materialization_plan_asset_content( $file, $relative );
if ( is_wp_error( $content ) ) {
return $content;
}
$kind = isset( $file['kind'] ) ? (string) $file['kind'] : '';
$lower = strtolower( $relative );
if ( 'css' === $kind || str_ends_with( $lower, '.css' ) ) {
$css[] = trim( $content );
continue;
}
if ( 'js' === $kind || str_ends_with( $lower, '.js' ) ) {
$js[] = trim( $content );
continue;
}
$target_relative = 'assets/materialized/' . $relative;
$target = trailingslashit( $theme_dir ) . $target_relative;
if ( $write_files ) {
$dir = dirname( $target );
if ( ! wp_mkdir_p( $dir ) ) {
return new WP_Error( 'static_site_importer_artifact_asset_mkdir_failed', sprintf( 'Failed to create website artifact asset directory: %s', $dir ) );
}
$result = self::write_file( $target, $content );
if ( is_wp_error( $result ) ) {
return $result;
}
}
$assets[ $relative ] = array(
'source' => $relative,
'path' => $relative,
'url' => trailingslashit( $theme_uri ) . $target_relative,
'final_url' => trailingslashit( $theme_uri ) . $target_relative,
'mime_type' => self::mime_type( $target ),
'theme_path' => $target_relative,
'policy' => 'theme',
'source_role' => $retention['source_role'],
'keep_source' => $retention['keep_source'],
'deletion_allowed' => $retention['deletion_allowed'],
);
}
return array(
'css' => trim( implode( "\n\n", array_filter( $css ) ) ),
'js' => '',
'assets' => $assets,
'scripts' => array(),
'stylesheets' => array(),
'diagnostics' => $diagnostics,
);
}
/**
* Write native Blocks Engine asset materialization rows when the plan carries payloads.
*
* @param string $theme_dir Theme directory.
* @param string $theme_uri Theme URI.
* @param array<string,mixed> $artifacts WordPress artifacts from Blocks Engine.
* @param bool $write_files Whether to write materialized asset files.
* @return array{css:string,js:string,assets:array<string,array<string,mixed>>,scripts:array<int,array<string,mixed>>,stylesheets:array<int,array<string,mixed>>,diagnostics:array<int,array<string,mixed>>}|null|WP_Error
*/
private static function materialize_materialization_plan_assets( string $theme_dir, string $theme_uri, array $artifacts, bool $write_files = true, string $svg_font_usage_markup = '' ) {
$site = isset( $artifacts['site'] ) && is_array( $artifacts['site'] ) ? $artifacts['site'] : array();
if ( 'blocks-engine/php-transformer/materialization-plan/v1' !== (string) ( $site['schema'] ?? '' ) || ! array_key_exists( 'assets', $site ) ) {
return null;
}
if ( ! is_array( $site['assets'] ) ) {
return new WP_Error( 'static_site_importer_materialization_plan_assets_invalid', 'Blocks Engine materialization_plan.assets must be an array.' );
}
if ( ! self::materialization_plan_assets_include_payloads( $site['assets'] ) ) {
return null;
}
$css = array();
$assets = array();
$scripts = array();
$stylesheets = array();
$diagnostics = array();
$order = 0;
$svg_candidates = array_merge( $site['assets'], isset( $artifacts['files'] ) && is_array( $artifacts['files'] ) ? $artifacts['files'] : array(), isset( $artifacts['source_files'] ) && is_array( $artifacts['source_files'] ) ? $artifacts['source_files'] : array() );
$svg_font_faces = self::google_font_faces_for_svg_assets( $site, $svg_candidates, $diagnostics, $svg_font_usage_markup );
foreach ( $site['assets'] as $asset ) {
if ( ! is_array( $asset ) ) {
return new WP_Error( 'static_site_importer_materialization_plan_asset_invalid', 'Blocks Engine materialization_plan.assets entries must be arrays.' );
}
$relative = self::normalize_artifact_materialization_path( isset( $asset['path'] ) && is_scalar( $asset['path'] ) ? (string) $asset['path'] : '' );
$retention = self::source_retention_policy( $asset, $relative, 'materialization_plan.assets' );
if ( '' === $relative ) {
return new WP_Error( 'static_site_importer_materialization_plan_asset_path_invalid', 'Blocks Engine materialization_plan.assets entries must include safe relative paths.' );
}
if ( isset( $retention['diagnostic'] ) ) {
$diagnostics[] = $retention['diagnostic'];
}
$content = self::materialization_plan_asset_content( $asset, $relative );
if ( is_wp_error( $content ) ) {
return $content;
}
$kind = isset( $asset['kind'] ) && is_scalar( $asset['kind'] ) ? (string) $asset['kind'] : '';
$role = isset( $asset['role'] ) && is_scalar( $asset['role'] ) ? (string) $asset['role'] : '';
$lower = strtolower( $relative );
if ( 'html' === $kind || str_ends_with( $lower, '.html' ) || str_ends_with( $lower, '.htm' ) ) {
continue;
}
if ( '' !== $svg_font_faces && self::is_svg_asset( $asset, $relative ) ) {
$content = self::embed_svg_font_faces( $content, $svg_font_faces );
}
++$order;
$target_relative = 'assets/materialized/' . $relative;
$target = trailingslashit( $theme_dir ) . $target_relative;
if ( $write_files ) {
$dir = dirname( $target );
if ( ! wp_mkdir_p( $dir ) ) {
return new WP_Error( 'static_site_importer_materialization_plan_asset_mkdir_failed', sprintf( 'Failed to create materialization-plan asset directory: %s', $dir ) );
}
$result = self::write_file( $target, $content );
if ( is_wp_error( $result ) ) {
return $result;
}
}
$assets[ $relative ] = self::materialization_plan_asset_report( $asset, $relative, trailingslashit( $theme_uri ) . $target_relative, $target_relative, self::mime_type( $target ), $order, $retention );
if ( 'css' === $kind || 'stylesheet' === $role || str_ends_with( $lower, '.css' ) ) {
$css[] = array(
'path' => $relative,
'content' => trim( $content ),
);
$stylesheets[] = $assets[ $relative ];
continue;
}
if ( 'js' === $kind || 'script' === $role || str_ends_with( $lower, '.js' ) ) {
$scripts[] = $assets[ $relative ];
continue;
}
}
$supplemental = self::materialize_supplemental_artifact_file_assets( $theme_dir, $theme_uri, $artifacts, $assets, $order, $write_files, $svg_font_faces );
if ( is_wp_error( $supplemental ) ) {
return $supplemental;
}
foreach ( $supplemental['diagnostics'] as $diagnostic ) {
$diagnostics[] = $diagnostic;
}
$font_stylesheets = self::materialize_font_materialization_stylesheets( $theme_dir, $theme_uri, $site, $assets, $order, $write_files, $svg_font_faces );
if ( is_wp_error( $font_stylesheets ) ) {
return $font_stylesheets;
}
$stylesheets = array_merge( $font_stylesheets, $stylesheets );
return array(
'css' => trim( implode( "\n\n", array_filter( self::rewrite_materialized_css_chunks( $css, $assets ) ) ) ),
'js' => '',
'assets' => $assets,
'scripts' => $scripts,
'stylesheets' => $stylesheets,
'diagnostics' => $diagnostics,
'svg_font_faces' => $svg_font_faces,
);
}
/**
* Resolve trusted Google Fonts plan imports to CSS that external SVG images can use.
*
* @param array<string,mixed> $site Materialization plan site artifact.
* @param array<int,array<string,mixed>> $assets Candidate compiler asset rows.
* @param array<int,array<string,mixed>> $diagnostics Diagnostics, passed by reference.
* @return string Self-contained @font-face CSS, or an empty string.
*/
private static function google_font_faces_for_svg_assets( array $site, array $assets, array &$diagnostics, string $svg_font_usage_markup = '' ): string {
$plan = isset( $site['theme']['font_materialization'] ) && is_array( $site['theme']['font_materialization'] ) ? $site['theme']['font_materialization'] : array();
if ( 'blocks-engine/php-transformer/font-materialization-plan/v1' !== (string) ( $plan['schema'] ?? '' ) || 'google_fonts' !== (string) ( $plan['provider'] ?? '' ) || empty( $plan['fonts'] ) || ! is_array( $plan['fonts'] ) ) {
return '';
}
$families = self::google_font_plan_families( $plan['fonts'] );
if ( empty( $families ) ) {
return '';
}
$has_matching_svg = false;
foreach ( $assets as $asset ) {
if ( ! is_array( $asset ) || ! self::is_svg_asset( $asset, isset( $asset['path'] ) && is_scalar( $asset['path'] ) ? (string) $asset['path'] : '' ) ) {
continue;
}
$content = isset( $asset['content'] ) && is_scalar( $asset['content'] ) ? (string) $asset['content'] : '';
if ( self::svg_uses_font_family( $content, $families ) ) {
$has_matching_svg = true;
break;
}
}
if ( ! $has_matching_svg && self::svg_uses_font_family( $svg_font_usage_markup, $families ) ) {
$has_matching_svg = true;
}
if ( ! $has_matching_svg ) {
return '';
}
$imports = array();
foreach ( isset( $plan['stylesheets'] ) && is_array( $plan['stylesheets'] ) ? $plan['stylesheets'] : array() as $stylesheet ) {
$content = is_array( $stylesheet ) && isset( $stylesheet['content'] ) && is_scalar( $stylesheet['content'] ) ? (string) $stylesheet['content'] : '';
if ( preg_match_all( '/@import\s+(?:url\()?\s*["\']?([^"\'\s\)]+)["\']?\s*\)?/i', $content, $matches ) ) {
$imports = array_merge( $imports, $matches[1] );
}
}
$imports = array_values( array_unique( $imports ) );
if ( empty( $imports ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'stylesheet_import_missing', 'No Google Fonts stylesheet import was available for SVG font embedding.' );
return '';
}
foreach ( $imports as $import ) {
if ( ! self::is_google_fonts_stylesheet_url( $import ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'untrusted_stylesheet_url', 'Every stylesheet import must be an allowlisted Google Fonts CSS endpoint before SVG font embedding can begin.' );
return '';
}
}
$faces = array();
$font_payloads = array();
$font_payload_bytes = 0;
foreach ( $imports as $import ) {
$response = self::bounded_google_font_request( $import, 262144 );
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'stylesheet_fetch_failed', 'The allowlisted Google Fonts stylesheet could not be fetched for SVG embedding.' );
return '';
}
$css = (string) wp_remote_retrieve_body( $response );
if ( strlen( $css ) > 262144 ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'stylesheet_response_too_large', 'The Google Fonts stylesheet exceeded the SVG font embedding response limit.' );
return '';
}
$embedded = self::embed_google_font_face_sources( $css, $families, $diagnostics, $font_payloads, $font_payload_bytes );
if ( '' === $embedded ) {
return '';
}
$faces[] = $embedded;
}
return implode( "\n", $faces );
}
/** @param array<int,mixed> $fonts @return array<int,string> */
private static function google_font_plan_families( array $fonts ): array {
$families = array();
foreach ( $fonts as $font ) {
$family = is_array( $font ) ? ( $font['family'] ?? $font['font_family'] ?? '' ) : $font;
if ( is_scalar( $family ) && '' !== trim( (string) $family ) ) {
$families[] = trim( (string) $family );
}
}
return array_values( array_unique( $families ) );
}
private static function is_google_fonts_stylesheet_url( string $url ): bool {
$parts = wp_parse_url( $url );
return is_array( $parts ) && 'https' === strtolower( (string) ( $parts['scheme'] ?? '' ) ) && 'fonts.googleapis.com' === strtolower( (string) ( $parts['host'] ?? '' ) ) && ( ! isset( $parts['port'] ) || 443 === (int) $parts['port'] ) && ! isset( $parts['user'], $parts['pass'] ) && in_array( (string) ( $parts['path'] ?? '' ), array( '/css', '/css2' ), true );
}
private static function bounded_google_font_request( string $url, int $limit ) {
return wp_safe_remote_get(
$url,
array(
'timeout' => 15,
'redirection' => 0,
'limit_response_size' => $limit,
'headers' => array( 'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' ),
)
);
}
/** @param array<int,string> $families @param array<int,array<string,mixed>> $diagnostics @param array<string,string> $font_payloads */
private static function embed_google_font_face_sources( string $css, array $families, array &$diagnostics, array &$font_payloads, int &$font_payload_bytes ): string {
if ( ! preg_match_all( '/@font-face\s*\{([^{}]*)\}/is', $css, $faces ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'stylesheet_font_faces_missing', 'The Google Fonts stylesheet did not contain embeddable @font-face rules.' );
return '';
}
$embedded = array();
foreach ( $faces[0] as $index => $face ) {
$body = $faces[1][ $index ];
if ( ! preg_match( '/font-family\s*:\s*(["\']?)([^;"\']+)\1\s*;/i', $body, $family_match ) || ! in_array( trim( $family_match[2] ), $families, true ) ) {
continue;
}
if ( str_contains( $face, '<' ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'untrusted_font_url', 'A Google Fonts stylesheet referenced a non-allowlisted font payload URL.' );
return '';
}
if ( ! preg_match_all( '/url\(\s*(["\']?)([^"\'\s\)]+)\1\s*\)/i', $face, $urls ) ) {
continue;
}
$rewritten = $face;
$urls = array_unique( $urls[2] );
foreach ( $urls as $url ) {
$parts = wp_parse_url( $url );
$path = is_array( $parts ) ? strtolower( (string) ( $parts['path'] ?? '' ) ) : '';
if ( ! is_array( $parts ) || 'https' !== strtolower( (string) ( $parts['scheme'] ?? '' ) ) || 'fonts.gstatic.com' !== strtolower( (string) ( $parts['host'] ?? '' ) ) || ( isset( $parts['port'] ) && 443 !== (int) $parts['port'] ) || isset( $parts['user'], $parts['pass'] ) || ! preg_match( '/\.woff2?$/', $path ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'untrusted_font_url', 'A Google Fonts stylesheet referenced a non-allowlisted font payload URL.' );
return '';
}
}
foreach ( $urls as $url ) {
$parts = wp_parse_url( $url );
$path = is_array( $parts ) ? strtolower( (string) ( $parts['path'] ?? '' ) ) : '';
if ( ! isset( $font_payloads[ $url ] ) ) {
$response = self::bounded_google_font_request( $url, 2097152 );
$payload = is_wp_error( $response ) ? '' : (string) wp_remote_retrieve_body( $response );
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) || '' === $payload || strlen( $payload ) > 2097152 ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'font_payload_fetch_failed', 'An allowlisted Google Fonts payload could not be embedded within the response limit.' );
return '';
}
if ( 4194304 < $font_payload_bytes + strlen( $payload ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'font_payload_total_too_large', 'The unique Google Fonts payloads exceeded the SVG font embedding aggregate limit.' );
return '';
}
$font_payloads[ $url ] = $payload;
$font_payload_bytes += strlen( $payload );
}
$payload = $font_payloads[ $url ];
$mime = str_ends_with( $path, '.woff2' ) ? 'font/woff2' : 'font/woff';
$rewritten = str_replace( $url, 'data:' . $mime . ';base64,' . base64_encode( $payload ), $rewritten );
}
$embedded[] = $rewritten;
}
if ( empty( $embedded ) ) {
$diagnostics[] = self::google_font_svg_diagnostic( 'matching_font_faces_missing', 'No Google Fonts @font-face rules matched SVG text font-family usage.' );
}
return implode( "\n", $embedded );
}
/** @param array<string,mixed> $asset */
private static function is_svg_asset( array $asset, string $path ): bool {
return 'svg' === strtolower( (string) ( $asset['kind'] ?? '' ) ) || 'image/svg+xml' === strtolower( (string) ( $asset['mime_type'] ?? '' ) ) || str_ends_with( strtolower( $path ), '.svg' );
}
/** @param array<int,string> $families */
private static function svg_uses_font_family( string $svg, array $families ): bool {
if ( ! preg_match( '/<text\b/i', $svg ) ) {
return false;
}
foreach ( $families as $family ) {
if ( preg_match( '/font-family\s*[:=]\s*(["\']?)' . preg_quote( $family, '/' ) . '\\1/i', $svg ) ) {
return true;
}
}
return false;
}
public static function embed_svg_font_faces( string $svg, string $font_faces ): string {
if ( '' === $font_faces || ! self::svg_uses_font_family( $svg, self::font_families_from_faces( $font_faces ) ) || ! preg_match( '/<svg\b[^>]*>/i', $svg, $match, PREG_OFFSET_CAPTURE ) ) {
return $svg;
}
$offset = $match[0][1] + strlen( $match[0][0] );
return substr( $svg, 0, $offset ) . '<style type="text/css">' . $font_faces . '</style>' . substr( $svg, $offset );
}
/** @return array<int,string> */
private static function font_families_from_faces( string $css ): array {
preg_match_all( '/font-family\s*:\s*(["\']?)([^;"\']+)\1\s*;/i', $css, $matches );
return array_values( array_unique( array_map( 'trim', $matches[2] ?? array() ) ) );
}
/** @return array<string,string> */
private static function google_font_svg_diagnostic( string $reason, string $message ): array {
return array( 'type' => 'svg_font_embedding_failed', 'source' => 'static-site-importer/theme-materializer', 'reason' => $reason, 'message' => $message );
}
/**
* Materialize payload-bearing artifact files omitted from a native asset plan.
*
* Some generators emit CSS that references artifact-local files while their
* native materialization plan only lists assets observed in DOM nodes. SSI owns
* the final theme filesystem, so it keeps those file payloads available and in
* the asset map for CSS URL rewriting.
*
* @param string $theme_dir Theme directory.
* @param string $theme_uri Theme URI.
* @param array<string,mixed> $artifacts WordPress artifacts from Blocks Engine.
* @param array<string,array<string,mixed>> $assets Materialized asset rows keyed by source path.
* @param int $order Current materialization order.
* @param bool $write_files Whether to write materialized asset files.
* @param string $svg_font_faces Self-contained font CSS for matching SVG text.
* @return array{diagnostics:array<int,array<string,mixed>>}|WP_Error
*/
private static function materialize_supplemental_artifact_file_assets( string $theme_dir, string $theme_uri, array $artifacts, array &$assets, int &$order, bool $write_files = true, string $svg_font_faces = '' ) {
$files = isset( $artifacts['files'] ) && is_array( $artifacts['files'] ) ? $artifacts['files'] : array();
if ( isset( $artifacts['source_files'] ) && is_array( $artifacts['source_files'] ) ) {
$files = array_merge( $files, $artifacts['source_files'] );
}
$diagnostics = array();
foreach ( $files as $file ) {
if ( ! is_array( $file ) ) {
continue;
}
$relative = self::normalize_artifact_materialization_path( isset( $file['path'] ) && is_scalar( $file['path'] ) ? (string) $file['path'] : '' );
if ( '' === $relative || isset( $assets[ $relative ] ) ) {
continue;
}
$lower = strtolower( $relative );
$kind = isset( $file['kind'] ) && is_scalar( $file['kind'] ) ? (string) $file['kind'] : '';
if ( 'html' === $kind || 'css' === $kind || 'js' === $kind || str_ends_with( $lower, '.html' ) || str_ends_with( $lower, '.htm' ) || str_ends_with( $lower, '.css' ) || str_ends_with( $lower, '.js' ) ) {
continue;
}
$content = self::materialization_plan_asset_content( $file, $relative );
if ( is_wp_error( $content ) ) {
return $content;
}
if ( '' !== $svg_font_faces && self::is_svg_asset( $file, $relative ) ) {
$content = self::embed_svg_font_faces( $content, $svg_font_faces );
}
$retention = self::source_retention_policy( $file, $relative, 'website_artifact.files' );
if ( isset( $retention['diagnostic'] ) ) {
$diagnostics[] = $retention['diagnostic'];
}
$target_relative = 'assets/materialized/' . $relative;
$target = trailingslashit( $theme_dir ) . $target_relative;
if ( $write_files ) {
$dir = dirname( $target );
if ( ! wp_mkdir_p( $dir ) ) {
return new WP_Error( 'static_site_importer_supplemental_artifact_asset_mkdir_failed', sprintf( 'Failed to create supplemental artifact asset directory: %s', $dir ) );
}
$result = self::write_file( $target, $content );
if ( is_wp_error( $result ) ) {
return $result;
}
}
++$order;
$assets[ $relative ] = self::materialization_plan_asset_report(
array_merge( $file, array( 'origin' => 'website_artifact.files' ) ),
$relative,
trailingslashit( $theme_uri ) . $target_relative,
$target_relative,
self::mime_type( $target ),
$order,
$retention
);
}
return array( 'diagnostics' => $diagnostics );
}
/**
* Write theme font materialization stylesheet rows declared by Blocks Engine.
*
* @param string $theme_dir Theme directory.
* @param string $theme_uri Theme URI.
* @param array<string,mixed> $site Materialization plan site artifact.
* @param array<string,array<string,mixed>> $assets Materialized asset rows keyed by source path.
* @param int $order Current materialization order.
* @param bool $write_files Whether to write materialized asset files.
* @param string $embedded_font_faces Self-contained font-face CSS resolved for SVG assets.
* @return array<int,array<string,mixed>>|WP_Error
*/
private static function materialize_font_materialization_stylesheets( string $theme_dir, string $theme_uri, array $site, array &$assets, int &$order, bool $write_files = true, string $embedded_font_faces = '' ) {
$theme = isset( $site['theme'] ) && is_array( $site['theme'] ) ? $site['theme'] : array();
$plan = isset( $theme['font_materialization'] ) && is_array( $theme['font_materialization'] ) ? $theme['font_materialization'] : array();
if ( 'blocks-engine/php-transformer/font-materialization-plan/v1' !== (string) ( $plan['schema'] ?? '' ) ) {
return array();
}
$rows = isset( $plan['stylesheets'] ) && is_array( $plan['stylesheets'] ) ? $plan['stylesheets'] : array();
if ( empty( $rows ) && isset( $plan['css'] ) && is_scalar( $plan['css'] ) && '' !== trim( (string) $plan['css'] ) ) {
$rows[] = array(
'path' => 'assets/css/fonts.css',
'role' => 'stylesheet',
'mime_type' => 'text/css',
'content' => trim( (string) $plan['css'] ) . "\n",
);
}
if ( '' !== trim( $embedded_font_faces ) ) {
$rows[] = array(
'path' => 'assets/css/embedded-fonts.css',
'role' => 'stylesheet',
'mime_type' => 'text/css',
'content' => trim( $embedded_font_faces ) . "\n",
'source_role' => 'importer_owned',
'keep_source' => false,
);
}
$stylesheets = array();
foreach ( $rows as $row ) {
if ( ! is_array( $row ) ) {
return new WP_Error( 'static_site_importer_font_materialization_stylesheet_invalid', 'Blocks Engine font_materialization.stylesheets entries must be arrays.' );
}
$relative = self::normalize_artifact_materialization_path( isset( $row['path'] ) && is_scalar( $row['path'] ) ? (string) $row['path'] : '' );
if ( '' === $relative ) {
return new WP_Error( 'static_site_importer_font_materialization_stylesheet_path_invalid', 'Blocks Engine font_materialization.stylesheets entries must include safe relative paths.' );
}
$content = isset( $row['content'] ) && is_scalar( $row['content'] ) ? (string) $row['content'] : '';
if ( '' === trim( $content ) ) {
continue;
}
$target = trailingslashit( $theme_dir ) . $relative;
if ( $write_files ) {
$dir = dirname( $target );
if ( ! wp_mkdir_p( $dir ) ) {
return new WP_Error( 'static_site_importer_font_materialization_stylesheet_mkdir_failed', sprintf( 'Failed to create font materialization stylesheet directory: %s', $dir ) );
}
$result = self::write_file( $target, $content );
if ( is_wp_error( $result ) ) {
return $result;
}
}
++$order;
$asset = array_merge(
$row,
array(
'path' => $relative,
'role' => isset( $row['role'] ) && is_scalar( $row['role'] ) ? (string) $row['role'] : 'stylesheet',
'kind' => isset( $row['kind'] ) && is_scalar( $row['kind'] ) ? (string) $row['kind'] : 'css',
'origin' => 'theme.font_materialization',
)
);
$retention = self::source_retention_policy( $asset, $relative, 'theme.font_materialization' );
$assets[ $relative ] = self::materialization_plan_asset_report( $asset, $relative, trailingslashit( $theme_uri ) . $relative, $relative, self::mime_type( $target ), $order, $retention );
$stylesheets[] = $assets[ $relative ];
}
return $stylesheets;
}
/**
* Build an SSI asset report row while preserving native Blocks Engine metadata.
*
* @param array<string,mixed> $asset Blocks Engine asset row.
* @param string $relative Safe source-relative path.
* @param string $url Materialized theme URL.
* @param string $target_relative Materialized theme-relative path.
* @param string $fallback_mime MIME type inferred from written path.
* @param int $order Native asset order.
* @param array<string,mixed> $retention Source retention policy.
* @return array<string,mixed>
*/
private static function materialization_plan_asset_report( array $asset, string $relative, string $url, string $target_relative, string $fallback_mime, int $order, array $retention = array() ): array {
$mime_type = isset( $asset['mime_type'] ) && is_scalar( $asset['mime_type'] ) && '' !== (string) $asset['mime_type'] ? (string) $asset['mime_type'] : $fallback_mime;
$origin = isset( $asset['origin'] ) && is_scalar( $asset['origin'] ) && '' !== (string) $asset['origin'] ? (string) $asset['origin'] : 'materialization_plan.assets';
if ( empty( $retention ) ) {
$retention = self::source_retention_policy( $asset, $relative, $origin );
}
$report = array(
'source' => $relative,
'path' => $relative,
'url' => $url,
'final_url' => $url,
'mime_type' => $mime_type,
'theme_path' => $target_relative,
'policy' => 'theme',
'origin' => $origin,
'order' => $order,
'source_role' => $retention['source_role'],
'keep_source' => $retention['keep_source'],
'deletion_allowed' => $retention['deletion_allowed'],
);
foreach ( array( 'role', 'kind', 'type', 'media', 'as', 'crossorigin', 'integrity', 'placement', 'source_hash' ) as $key ) {
if ( isset( $asset[ $key ] ) && is_scalar( $asset[ $key ] ) && '' !== (string) $asset[ $key ] ) {
$report[ $key ] = (string) $asset[ $key ];
}
}
foreach ( array( 'defer', 'async' ) as $key ) {
if ( array_key_exists( $key, $asset ) ) {
$report[ $key ] = (bool) $asset[ $key ];
}
}
return $report;
}
/**
* Resolve source retention semantics for materialized artifact payloads.
*
* Canonical sources are retained unless the row explicitly declares an ephemeral/importer-owned source role.
*
* @param array<string,mixed> $source Source artifact row.
* @param string $path Source-relative path.
* @param string $origin Source origin label for diagnostics.
* @return array{source_role:string,keep_source:bool,deletion_allowed:bool,diagnostic?:array<string,mixed>}
*/
private static function source_retention_policy( array $source, string $path, string $origin ): array {
$source_role = isset( $source['source_role'] ) && is_scalar( $source['source_role'] ) && '' !== trim( (string) $source['source_role'] ) ? strtolower( preg_replace( '/[^a-z0-9_-]+/i', '_', trim( (string) $source['source_role'] ) ) ?? '' ) : 'canonical';
if ( '' === $source_role ) {
$source_role = 'canonical';
}
$keep_source = array_key_exists( 'keep_source', $source ) ? (bool) $source['keep_source'] : true;
$ephemeral = in_array( $source_role, array( 'ephemeral', 'importer_owned', 'importer-owned', 'temporary', 'temp' ), true );
$policy = array(
'source_role' => $source_role,
'keep_source' => $keep_source || ! $ephemeral,
'deletion_allowed' => $ephemeral && ! $keep_source,
);
if ( ! $keep_source && ! $ephemeral ) {
$policy['diagnostic'] = array(
'type' => 'website_artifact_source_retention_guard',
'severity' => 'warning',
'source' => $origin,
'source_path' => $path,
'path' => $path,
'source_role' => $source_role,
'keep_source' => true,
'deletion_allowed' => false,
'reason' => 'canonical_source_retained',
'message' => 'Website artifact source was retained because destructive source handling requires source_role=ephemeral or source_role=importer_owned.',
);
}
return $policy;
}
/**
* Rewrite CSS url(...) references to materialized theme URLs.
*
* @param array<int,array{path:string,content:string}> $chunks CSS chunks and their source paths.
* @param array<string,array<string,mixed>> $assets Materialized asset rows keyed by source path.
* @return array<int,string>
*/
private static function rewrite_materialized_css_chunks( array $chunks, array $assets ): array {
$rewritten = array();
foreach ( $chunks as $chunk ) {
$rewritten[] = self::rewrite_materialized_css_urls( $chunk['content'], $chunk['path'], $assets );
}
return $rewritten;
}
/**
* Rewrite one CSS payload's relative url(...) references.
*
* @param string $css CSS payload.
* @param string $stylesheet_path Source-relative stylesheet path.
* @param array<string,array<string,mixed>> $assets Materialized asset rows keyed by source path.
* @return string
*/
private static function rewrite_materialized_css_urls( string $css, string $stylesheet_path, array $assets ): string {
if ( '' === trim( $css ) || empty( $assets ) ) {
return $css;
}
$stylesheet_dir = dirname( $stylesheet_path );
return preg_replace_callback(
'/url\(\s*(["\']?)([^)"\']+)\1\s*\)/i',
static function ( array $matches ) use ( $assets, $stylesheet_dir ): string {
$url = trim( (string) $matches[2] );
if ( '' === $url || str_starts_with( $url, '#' ) || str_starts_with( strtolower( $url ), 'data:' ) || preg_match( '#^[a-z][a-z0-9+.-]*:#i', $url ) || str_starts_with( $url, '/' ) ) {
return $matches[0];
}
$candidate = self::resolve_materialized_relative_url( $stylesheet_dir, $url );
if ( '' === $candidate || ! isset( $assets[ $candidate ]['final_url'] ) || ! is_scalar( $assets[ $candidate ]['final_url'] ) ) {
return $matches[0];
}
return 'url(' . $matches[1] . (string) $assets[ $candidate ]['final_url'] . $matches[1] . ')';
},
$css
) ?? $css;
}
/**
* Resolve a relative asset URL against a source stylesheet path.
*
* @param string $base_dir Source stylesheet directory.
* @param string $url Relative CSS URL.
* @return string Safe source-relative path, or empty string when it escapes the artifact root.
*/
private static function resolve_materialized_relative_url( string $base_dir, string $url ): string {
$path = ( '.' === $base_dir ? '' : trim( $base_dir, '/' ) . '/' ) . strtok( $url, '?#' );
$segments = array();
foreach ( explode( '/', str_replace( '\\', '/', $path ) ) as $segment ) {
if ( '' === $segment || '.' === $segment ) {
continue;
}
if ( '..' === $segment ) {
if ( empty( $segments ) ) {
return '';
}
array_pop( $segments );
continue;
}
$segments[] = $segment;
}
return self::normalize_artifact_materialization_path( implode( '/', $segments ) );
}
/**
* Check whether native asset rows include write payloads.
*
* @param array<int,mixed> $assets Blocks Engine materialization-plan asset rows.
* @return bool
*/
private static function materialization_plan_assets_include_payloads( array $assets ): bool {
foreach ( $assets as $asset ) {
if ( is_array( $asset ) && ( array_key_exists( 'content', $asset ) || array_key_exists( 'content_base64', $asset ) ) ) {
return true;
}
}
return false;
}
/**
* Decode a native materialization-plan asset payload.
*
* @param array<string,mixed> $asset Blocks Engine asset row.
* @param string $relative Safe relative asset path.
* @return string|WP_Error
*/
private static function materialization_plan_asset_content( array $asset, string $relative ) {
if ( isset( $asset['content_base64'] ) ) {
if ( ! is_scalar( $asset['content_base64'] ) ) {
return new WP_Error( 'static_site_importer_materialization_plan_asset_content_invalid', sprintf( 'Blocks Engine materialization_plan.assets content_base64 must be scalar: %s', $relative ) );
}
$base64 = preg_replace( '/\s+/', '', (string) $asset['content_base64'] ) ?? '';
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Decodes declared artifact payload content, not executable code.
$decoded = base64_decode( $base64, true );
if ( false === $decoded ) {
return new WP_Error( 'static_site_importer_materialization_plan_asset_base64_invalid', sprintf( 'Blocks Engine materialization_plan.assets content_base64 is not valid base64: %s', $relative ) );
}
return $decoded;
}
if ( isset( $asset['content'] ) && is_scalar( $asset['content'] ) ) {
return (string) $asset['content'];
}
return new WP_Error( 'static_site_importer_materialization_plan_asset_content_missing', sprintf( 'Blocks Engine materialization_plan.assets entries must include content or content_base64: %s', $relative ) );
}
/**
* Normalize template part artifacts into generated theme writes.
*
* @param string $theme_dir Theme directory.
* @param array<string,mixed> $artifacts WordPress artifacts from Blocks Engine.
* @param array<string,array<string,mixed>> $assets Materialized assets keyed by source path.
* @param array<string,string> $permalinks Imported page permalinks keyed by source path.
* @return array{writes:array<string,string>,reports:array<int,array<string,mixed>>}|WP_Error Absolute write paths and report rows.
*/
public static function template_part_artifact_writes( string $theme_dir, array $artifacts, array $assets = array(), array $permalinks = array() ) {
$template_parts = self::template_part_artifacts_from_materialization_plan( $artifacts );
if ( is_wp_error( $template_parts ) ) {
return $template_parts;
}
if ( null === $template_parts ) {
$template_parts = self::navigation_template_parts_from_materialization_plan( $artifacts );
if ( is_wp_error( $template_parts ) ) {
return $template_parts;
}
}
if ( null === $template_parts ) {
$template_parts = isset( $artifacts['template_parts'] ) && is_array( $artifacts['template_parts'] ) ? $artifacts['template_parts'] : array();
}
if ( empty( $template_parts ) ) {
$template_parts = self::source_file_template_parts( $artifacts );
}
$writes = array();
$reports = array();
foreach ( $template_parts as $template_part ) {
if ( ! is_array( $template_part ) ) {
return new WP_Error( 'static_site_importer_template_part_invalid', 'Template part artifacts must be arrays.' );
}
$relative = self::template_part_artifact_relative_path( $template_part );
if ( '' === $relative ) {
return new WP_Error( 'static_site_importer_template_part_unsupported', 'Template part artifacts must resolve to a supported header or footer theme part.' );
}
if ( ! isset( $template_part['block_markup'] ) || ! is_scalar( $template_part['block_markup'] ) ) {
return new WP_Error( 'static_site_importer_template_part_markup_missing', 'Template part artifacts must include serialized block_markup.' );
}
$markup = (string) $template_part['block_markup'];
if ( '' === trim( $markup ) ) {
return new WP_Error( 'static_site_importer_template_part_markup_empty', 'Template part artifact block_markup must not be empty.' );
}
$source_path = isset( $template_part['source_path'] ) && is_scalar( $template_part['source_path'] ) ? (string) $template_part['source_path'] : '';
$source_path = (string) strtok( $source_path, '#' );
$markup = Static_Site_Importer_Page_Materializer::rewrite_materialized_asset_references( $markup, $assets, $source_path, $permalinks );
$writes[ trailingslashit( $theme_dir ) . $relative ] = $markup;
$reports[] = self::template_part_artifact_report_payload( $relative, $template_part, $markup );
}
return array(
'writes' => $writes,
'reports' => $reports,
);
}
/**
* Extract header/footer parts from source HTML files when the compiler has not
* emitted explicit template-part artifacts.
*
* @param array<string,mixed> $artifacts WordPress artifacts from Blocks Engine.
* @return array<int,array<string,mixed>>
*/
private static function source_file_template_parts( array $artifacts ): array {
$files = isset( $artifacts['source_files'] ) && is_array( $artifacts['source_files'] ) ? $artifacts['source_files'] : array();
$files = self::entrypoint_first_source_files( $files, $artifacts );
foreach ( $files as $file ) {
if ( ! is_array( $file ) || ! isset( $file['path'] ) || ! is_scalar( $file['path'] ) ) {
continue;
}
$path = (string) $file['path'];