Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions php-transformer/src/ArtifactCompiler/ArtifactCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,9 @@ private function finalizeArtifact(array $artifact, array $reduction, ?\Automatti
foreach (array_unique(array_map(static fn (array $part): string => (string) ($part['block_markup'] ?? ''), $parts)) as $partMarkup) $sharedMarkup .= "\n" . $partMarkup;
foreach ($pageMarkup as &$markup) $markup .= "\n" . $sharedMarkup;
unset($markup);
// Keep source bytes intact through compilation: provenance, orphan
// assets and cross-route factoring all depend on the authored inventory.
// Only prune the published projections after that factoring is complete.
$authoredFiles = $normalized['files'];
$normalized['files'] = $this->applyAuthorStylesheetProjections($normalized['files'], $authorStylesheetProjections, $entryBlocks['author_stylesheet_projections'], (string) ($ownedBy(array(array()), $entryPath)[0]['owner'] ?? ''), $pageMarkup, $allDiagnostics, $sharedMarkup, $timer);
$normalized['files'] = $this->withoutUnreachableSelectors($normalized['files']);
Expand Down Expand Up @@ -2135,8 +2138,24 @@ private function withoutUnreachableSelectors(array $files): array
// Metadata carries captured interaction states.
if (is_array($file['metadata'] ?? null) && array() !== $file['metadata']) $texts[] = (string) json_encode($file['metadata']);
$text = $file['content'] ?? (in_array($file['kind'] ?? '', array('html', 'js', 'json', 'svg', 'text'), true) && is_string($file['content_base64'] ?? null) ? base64_decode($file['content_base64'], true) : null);
// Preserve inline author sheets as conservative evidence: partial
// documents and responsive variants need not contain their subjects.
// A complete document supplies subject evidence, not its style
// inventory. Otherwise an inline framework sheet keeps every one
// of its own unused selectors alive. Fragments remain conservative:
// their author rules may target subjects outside the supplied tree.
if ('html' === ($file['kind'] ?? '') && is_string($text) && preg_match('/<html\b/i', $text)) {
// Search tag boundaries rather than matching the entire body:
// captured sheets can exceed PCRE's backtracking limit. A null
// replacement would erase the document's subject evidence too.
$offset = 0;
while (preg_match('/<style\b[^>]*>/i', $text, $open, PREG_OFFSET_CAPTURE, $offset)) {
$start = $open[0][1];
$bodyStart = $start + strlen($open[0][0]);
if (!preg_match('/<\/style\s*>/i', $text, $close, PREG_OFFSET_CAPTURE, $bodyStart)) break;
$end = $close[0][1] + strlen($close[0][0]);
$text = substr_replace($text, '', $start, $end - $start);
$offset = $start;
}
}
if (is_string($text) && '' !== $text) $texts[] = $text;
}
if (0 === $documents) return $files;
Expand Down
12 changes: 12 additions & 0 deletions php-transformer/src/Css/UnreachableSelectorPruner.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,18 @@ public function prune(string $css): string
$pruned = (new CssStylesheetTransformer())->transformStyleRules($css, function (string $prelude, string $body): string {
$arms = CssStylesheetTransformer::splitSelectorList($prelude);
if (null === $arms) return $prelude . '{' . $body . '}';
// Matcher support is not selector validity: generated content and
// browser state pseudos can still have provably absent subjects.
// Malformed attribute syntax, however, makes a whole list uncertain.
foreach ($arms as $arm) {
for ($i = 0, $length = strlen($arm); $i < $length; ++$i) {
if ('\\' === $arm[$i]) { ++$i; continue; }
if ('[' !== $arm[$i]) continue;
$close = CssSyntaxScanner::matchingClose($arm, $i);
if (null === $close || !CssSelectorMatcher::parse('*' . substr($arm, $i, $close - $i + 1))['supported']) return $prelude . '{' . $body . '}';
$i = $close;
}
}
$kept = array_values(array_filter($arms, fn (string $arm): bool => $this->reachable($arm)));
if (count($kept) === count($arms)) return $prelude . '{' . $body . '}';
// Comments ahead of the rule (licenses, source maps) stay in place.
Expand Down
26 changes: 26 additions & 0 deletions php-transformer/tests/unit/complete-document-selector-liveness.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\ArtifactCompiler;

// The inline copy of a framework is inventory, not evidence that its unused
// components exist. Other routes and scripts still provide subject evidence.
$result = (new ArtifactCompiler())->compile(array(
'entrypoint' => 'index.html',
'files' => array(
'index.html' => '<!doctype html><html><head><link rel="stylesheet" href="framework.css"><style>.absent-widget{color:salmon}.other-route{color:teal}.dynamic-item{color:purple}.unused,.broken[foo=bar baz]{color:orchid}</style></head><body><main>Home</main><script>window.state="dynamic-" + "item";</script></body></html>',
'other.html' => '<main class="other-route">Other</main>',
'framework.css' => '.absent-widget{background:salmon}.other-route{background:teal}.dynamic-item{background:purple}',
),
))->toArray();
$css = implode("\n", array_map(
static fn (array $asset): string => (string) ($asset['content'] ?? ''),
array_filter($result['assets'], static fn (array $asset): bool => 'css' === ($asset['kind'] ?? null))
));
foreach (array('salmon' => false, 'teal' => true, 'purple' => true, 'orchid' => true) as $value => $expected) {
if (str_contains($css, $value) !== $expected) {
throw new RuntimeException('Complete document selector liveness: ' . $value);
}
}
echo "Complete document selector liveness passed\n";
21 changes: 21 additions & 0 deletions php-transformer/tests/unit/pseudo-element-selector-pruning.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\ArtifactCompiler;

$result = (new ArtifactCompiler())->compile(array(
'entrypoint' => 'index.html',
'files' => array(
'index.html' => '<!doctype html><html><head><link rel="stylesheet" href="site.css"></head><body><main class="present">Home</main></body></html>',
'site.css' => '.absent::before{content:"unused-pseudo"}.present::before{content:"live-pseudo"}.unused,.broken[foo=bar baz]{color:orchid}',
),
))->toArray();
$css = implode("\n", array_map(
static fn (array $asset): string => (string) ($asset['content'] ?? ''),
array_filter($result['assets'], static fn (array $asset): bool => 'css' === ($asset['kind'] ?? null))
));
foreach (array('unused-pseudo' => false, 'live-pseudo' => true, 'orchid' => true) as $needle => $expected) {
if (str_contains($css, $needle) !== $expected) throw new RuntimeException('Pseudo-element selector liveness: ' . $needle);
}
echo "Pseudo-element selector pruning passed\n";
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
)),
'files' => array(
array('path' => 'index.html', 'content' => '<!doctype html><html><head></head><body><main>Desktop</main></body></html>'),
array('path' => '.variants/mobile/index.html', 'content' => '<!doctype html><html><head><style media="screen">' . $largeVariantCss . '</style></head><body><main>Mobile</main></body></html>'),
array('path' => '.variants/mobile/index.html', 'content' => '<!doctype html><html><head><style media="screen">' . $largeVariantCss . '</style></head><body><main class="variant-large-first variant-large-last">Mobile</main></body></html>'),
),
);
$assert(strlen($largeVariantCss) > 1048576, 'Responsive variant regression CSS exceeds one megabyte.');
Expand Down
40 changes: 40 additions & 0 deletions php-transformer/tests/unit/state-pseudo-selector-pruning.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\ArtifactCompiler;

// Framework selectors unsupported by the matcher still have required source
// classes. Neither generated native identities nor state pseudos make those
// absent classes live. Malformed lists remain untouched. Pruning belongs to
// published projections, not source inventory: orphan assets keep their bytes.
$artifact = array(
'entrypoint' => 'index.html',
'files' => array(
'index.html' => '<!doctype html><html><head><link rel="stylesheet" href="site.css"></head><body><main><p class="present">Home</p><button>Action</button></main></body></html>',
'other.html' => '<main class="other-route">Other</main>',
'site.css' => '.absent:focus-within{color:salmon}.present:focus-within{color:teal}.other-route{color:purple}.unused,.broken[foo=bar baz]{color:orchid}',
'orphan.css' => '.inventory-only:focus-within{color:gold}',
),
);
$compiler = new ArtifactCompiler();
$shared = $compiler->prepareShared($artifact);
$pages = $compiler->preparePages($artifact, $shared);
$receipts = $compiler->compilePreparedPages($shared, $pages);
foreach (array(
$compiler->compile($artifact)->toArray(),
$compiler->compose($shared, array_values($receipts))->toArray(),
) as $result) {
$orphans = array_values(array_filter($result['assets'], static fn (array $asset): bool => 'orphan.css' === ($asset['path'] ?? null)));
if ('.inventory-only:focus-within{color:gold}' !== ($orphans[0]['content'] ?? null)) {
throw new RuntimeException('Selector pruning must preserve unreferenced source inventory');
}
$css = implode("\n", array_map(
static fn (array $asset): string => (string) ($asset['content'] ?? ''),
array_filter($result['assets'], static fn (array $asset): bool => 'css' === ($asset['kind'] ?? null))
));
foreach (array('salmon' => false, 'teal' => true, 'purple' => true, 'orchid' => true) as $needle => $expected) {
if (str_contains($css, $needle) !== $expected) throw new RuntimeException('Source selector pruning: ' . $needle);
}
}
echo "Projected selector pruning preserves source inventory\n";
Loading