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
3 changes: 2 additions & 1 deletion php-transformer/src/ArtifactCompiler/ArtifactCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2535,7 +2535,8 @@ private function compileSharedInlineShells(array $files, string $entryPath, stri
// same compilation group and its canonical support assets.
}
unset($areaRows, $row);
$documents[(string) $file['path']] = array('content' => (string) $file['content'], 'rows' => $rows);
// Shared stylesheet comparison must not see route-specific capture IDs.
$documents[(string) $file['path']] = array('content' => $dom->documentElement instanceof DOMElement ? SourceDom::outerHtml($dom->documentElement) : (string) $file['content'], 'rows' => $rows);
}
if (count($documents) < 2) return array('artifacts' => array(), 'assets' => array(), 'author_stylesheet_projections' => array(), 'runtime_script_projections' => array());

Expand Down
7 changes: 6 additions & 1 deletion php-transformer/src/ArtifactCompiler/SourceShells.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static function ancestorContext(\DOMElement $landmark): array
$context = array();
for ($cursor = $landmark->parentNode; $cursor instanceof \DOMElement; $cursor = $cursor->parentNode) {
$attributes = array();
foreach ($cursor->attributes ?? array() as $attribute) $attributes[strtolower($attribute->name)] = $attribute->value;
$attributes = SourceDom::htmlAttributes($cursor);
array_unshift($context, array('tag' => strtolower($cursor->tagName), 'attributes' => $attributes));
}
return $context;
Expand Down Expand Up @@ -129,6 +129,11 @@ public static function identity(string $markup, bool $ignoreViewportEntrance = t
{
$dom = HtmlSerialization::parseDocument('<body>' . $markup . '</body>');
$xpath = new \DOMXPath($dom);
foreach ($dom->getElementsByTagName('*') as $node) {
foreach (iterator_to_array($node->attributes) as $attribute) {
if (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($attribute->name)) $node->removeAttributeNode($attribute);
}
}
if ($ignoreViewportEntrance) {
foreach ($xpath->query('//*[@' . CaptureEvidence::VIEWPORT_ENTRANCE . ']') ?: array() as $node) {
if (!$node instanceof \DOMElement) continue;
Expand Down
12 changes: 12 additions & 0 deletions php-transformer/src/Contract/BoxTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ final class BoxTree
'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height',
);

/** Capture identity is only meaningful to box-tree lookup, never authored markup. */
public static function isEvidenceAttribute(string $name): bool
{
return self::NODE_ATTRIBUTE === strtolower($name);
}

/** @return list<\DOMAttr> Authored attributes, without capture-only identity. */
public static function authoredAttributes(DOMElement $element): array
{
return array_values(array_filter(iterator_to_array($element->attributes), static fn (\DOMAttr $attribute): bool => ! self::isEvidenceAttribute($attribute->name)));
}

public static function validId(mixed $id): bool
{
return is_string($id) && 1 === preg_match('/^[A-Za-z0-9._:-]{1,80}$/D', $id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ private function hasAttributePrefix(array $elements, string $prefix): bool
{
foreach ( $elements as $element ) {
foreach ( $element->attributes ?? array() as $attribute ) {
if ( str_starts_with(strtolower($attribute->nodeName), $prefix) ) {
if ( ! \Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($attribute->nodeName) && str_starts_with(strtolower($attribute->nodeName), $prefix) ) {
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ private function isInheritedTextWrapper(DOMElement $element): bool
foreach ($element->childNodes as $node) {
if (XML_TEXT_NODE === $node->nodeType && '' !== trim((string) $node->nodeValue)) return false;
}
foreach ($element->attributes as $attribute) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($element) as $attribute) {
if (! in_array(strtolower($attribute->nodeName), array('class', 'style', 'data-node-view-wrapper', 'data-node-view-content', 'data-node-view-content-inner'), true)) return false;
}
foreach ($this->session->authorStyleRuleCandidates($element) as $rule) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ private function matchesCoreArtwork(DOMElement $svg, ?string $service): bool
foreach ($element->getElementsByTagName('*') as $child) {
if (in_array(strtolower($child->tagName), array('title', 'desc'), true)) continue;
$attrs = array();
foreach ($child->attributes as $attr) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($child) as $attr) {
$attrs[$attr->name] = preg_replace('/[\s,]+/', '', $attr->value);
}
ksort($attrs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ private function signature(DOMNode $node, bool $shapeOnly, array &$state): ?stri
$attributes = array();
foreach ($node->attributes as $attribute) {
$name = strtolower($attribute->name);
if ( \Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($name) ) continue;
$value = $this->normalizedAttributeValue($name, $attribute->value);
if (null === $value) continue;
$attributes[] = $shapeOnly ? $name : ($this->isContentSlot($name) ? $name . '=#slot' : $name . '=' . $value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private static function isPresentationSpan(DOMElement $element): bool
if ('span' !== strtolower($element->tagName)) return false;
// Identity, language, accessibility and runtime attributes are boundaries,
// not disposable styling. Projected presentation markers live in class.
foreach ($element->attributes as $attribute) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($element) as $attribute) {
if (!in_array($attribute->name, array('class', 'style'), true)) return false;
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ private function startTagIdentity(DOMElement $element, bool $observable = false)
$tag = strtolower($element->tagName);
$attributes = array();
foreach ( $element->attributes ?? array() as $attribute ) {
if ( \Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($attribute->nodeName) ) continue;
$attributes[strtolower($attribute->nodeName)] = (string) $attribute->nodeValue;
}
if ( $observable ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ public function project(
if ($anchor instanceof DOMElement) {
$identity = array();
if ($anchor->hasAttribute('class')) $identity['data-blocks-engine-social-source-class'] = $anchor->getAttribute('class');
foreach ($anchor->attributes as $attribute) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($anchor) as $attribute) {
if (in_array($attribute->name, array('id', 'class', 'style', 'role', 'title', 'tabindex', 'target', 'rel'), true) || str_starts_with($attribute->name, 'data-') || str_starts_with($attribute->name, 'aria-')) $identity[$attribute->name] = $attribute->value;
}
$classes = $this->sourceProjectionClassName($anchor, $context, (string) ($identity['class'] ?? ''));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ final class AddressableInlineLayoutLeaf
public static function isPlainTextSpan(DOMElement $element): bool
{
if ('span' !== strtolower($element->tagName) || 0 !== SourceDom::childElementCount($element) || '' === trim($element->textContent)) return false;
foreach ($element->attributes as $attribute) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($element) as $attribute) {
if ('class' !== strtolower($attribute->name) && 'data-blocks-engine-richtext-marker' !== strtolower($attribute->name)) return false;
}
for ($ancestor = $element->parentNode; $ancestor instanceof DOMElement; $ancestor = $ancestor->parentNode) {
Expand All @@ -35,7 +35,7 @@ public static function identity(DOMElement $element, StyleResolver $styles): ?ar
) return null;
$id = SourceDom::attr($element, 'id');
if (1 !== preg_match('/^[A-Za-z][A-Za-z0-9_-]{0,199}$/', $id)) return null;
foreach ($element->attributes as $attribute) {
foreach (\Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::authoredAttributes($element) as $attribute) {
if (!in_array(strtolower($attribute->name), array('id', 'class'), true)) return null;
}
$display = $styles->declaredPresentation($element, 'display');
Expand Down
12 changes: 5 additions & 7 deletions php-transformer/src/HtmlToBlocks/Support/SourceDom.php
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,9 @@ public static function canonicalizedSerializationClone(DOMElement $element, ?cal
if (null !== $inlineStyleFor) self::projectInlineStyles($element, $clone, $inlineStyleFor);
// Capture node identity binds evidence to the source document, not the output.
foreach ( self::subtreeElements($clone) as $node ) {
$node->removeAttribute(BoxTree::NODE_ATTRIBUTE);
foreach ( iterator_to_array($node->attributes) as $attribute ) {
if ( BoxTree::isEvidenceAttribute($attribute->nodeName) ) $node->removeAttributeNode($attribute);
}
}
return $clone;
}
Expand Down Expand Up @@ -804,7 +806,7 @@ public static function htmlAttributes(DOMElement $element): array
{
$attributes = array();
foreach ( $element->attributes ?? array() as $attribute ) {
if ( HtmlAttributeName::isIntegerKey($attribute->nodeName) ) {
if ( HtmlAttributeName::isIntegerKey($attribute->nodeName) || BoxTree::isEvidenceAttribute($attribute->nodeName) ) {
continue;
}
$attributes[$attribute->nodeName] = $attribute->nodeValue ?? '';
Expand Down Expand Up @@ -2102,7 +2104,7 @@ public static function staticGraphicOnlyCustomElement(DOMElement $element): bool
}
while ( in_array(strtolower($child->tagName), array( 'span', 'div' ), true) ) {
foreach ( $child->attributes as $attribute ) {
if ( ! in_array(strtolower($attribute->nodeName), array( 'class', 'id', 'style' ), true) ) {
if ( ! BoxTree::isEvidenceAttribute($attribute->nodeName) && ! in_array(strtolower($attribute->nodeName), array( 'class', 'id', 'style' ), true) ) {
return false;
}
}
Expand Down Expand Up @@ -2318,10 +2320,6 @@ public static function safeDataAttributes(DOMElement $element): array
{
$data = array();
foreach ( self::htmlAttributes($element) as $name => $value ) {
// Capture node identity binds evidence; it is not authored data.
if ( BoxTree::NODE_ATTRIBUTE === $name ) {
continue;
}
if ( preg_match('/^data-[a-z0-9_-]+$/i', $name) && strlen($value) <= 300 && ! preg_match('/javascript\s*:/i', $value) ) {
$data[$name] = $value;
}
Expand Down
7 changes: 4 additions & 3 deletions php-transformer/src/Support/SourceAttribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ final class SourceAttribute

public static function isSelectorAttribute(string $name): bool
{
return in_array($name, self::SELECTOR_NAMES, true)
|| 1 === preg_match('/' . self::SELECTOR_PATTERN . '/', $name);
return ! \Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($name)
&& (in_array($name, self::SELECTOR_NAMES, true)
|| 1 === preg_match('/' . self::SELECTOR_PATTERN . '/', $name));
}

public static function isDeclaredEventAttribute(string $name): bool
Expand Down Expand Up @@ -76,7 +77,7 @@ public static function staticAttributes(array $attributes, array $ownedNames = a
$safe = array();
$policy = self::staticPolicy();
foreach ($attributes as $name => $value) {
if (!is_string($name) || !is_string($value) || in_array($name, $ownedNames, true)
if (!is_string($name) || !is_string($value) || \Automattic\BlocksEngine\PhpTransformer\Contract\BoxTree::isEvidenceAttribute($name) || in_array($name, $ownedNames, true)
|| in_array($name, $policy['excludedNames'], true) || str_starts_with($name, $policy['excludedPrefix'])) {
continue;
}
Expand Down
10 changes: 9 additions & 1 deletion php-transformer/tests/contract/shared-shell-plan.php
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,15 @@
$styledSvgAssetPaths = array_column(array_filter($styledSvgCompiled['assets'] ?? array(), static fn(array $asset): bool => 'inline-svg' === ($asset['source'] ?? null)), 'path');
$styledSvgShellPaths = array();
foreach ($styledSvgCompiled['inline_shell_artifacts'] ?? array() as $artifact) if (preg_match_all('@assets/materialized-svg/[^" ]+@', $artifact['block_markup'] ?? '', $matches)) $styledSvgShellPaths = array_merge($styledSvgShellPaths, $matches[0]);
$assert('failed' !== ($styledSvgResult['status'] ?? null) && 2 === count($styledSvgAssetPaths) && array() === array_diff($styledSvgShellPaths, $styledSvgAssetPaths), 'Shared shell compilation declares its CSS-context-specific materialized SVG asset instead of leaving an unresolved local browser reference.');
$assert('failed' !== ($styledSvgResult['status'] ?? null) && 1 === count($styledSvgAssetPaths) && 2 === count($styledSvgShellPaths) && array() === array_diff($styledSvgShellPaths, $styledSvgAssetPaths), 'Shared shells with identical CSS-baked SVG payloads share one declared materialized asset without unresolved local browser references.');

$distinctSvgDocument = static fn(string $title): string => str_replace('</style>', '.mobile-header .logo svg{width:32px;height:32px}</style>', $styledSvgDocument($title));
$distinctSvgResult = (new ArtifactCompiler())->compile(array('entrypoint' => 'index.html', 'files' => array('index.html' => $distinctSvgDocument('Home'), 'about.html' => $distinctSvgDocument('About'))))->toArray();
$distinctSvgCompiled = $distinctSvgResult['source_reports']['compiled_site'] ?? array();
$distinctSvgAssetPaths = array_column(array_filter($distinctSvgCompiled['assets'] ?? array(), static fn(array $asset): bool => 'inline-svg' === ($asset['source'] ?? null)), 'path');
$distinctSvgShellPaths = array();
foreach ($distinctSvgCompiled['inline_shell_artifacts'] ?? array() as $artifact) if (preg_match_all('@assets/materialized-svg/[^" ]+@', $artifact['block_markup'] ?? '', $matches)) $distinctSvgShellPaths = array_merge($distinctSvgShellPaths, $matches[0]);
$assert('failed' !== ($distinctSvgResult['status'] ?? null) && 2 === count($distinctSvgAssetPaths) && 2 === count(array_unique($distinctSvgShellPaths)) && array() === array_diff($distinctSvgShellPaths, $distinctSvgAssetPaths), 'Shared shells with distinct CSS-baked SVG payloads declare both context-specific assets without unresolved local browser references.');

$responsiveDivergentResult = $responsiveResult;
foreach ($responsiveDivergentResult['source_reports']['compiled_site']['pages'] as &$responsivePage) $responsivePage['block_markup'] = $responsiveMarkup('index.html' === $responsivePage['source_path'] ? 'Home' : 'About', 'about.html' === $responsivePage['source_path'] ? 'Different mobile header' : 'Mobile header'); unset($responsivePage);
Expand Down
55 changes: 41 additions & 14 deletions php-transformer/tests/unit/box-tree-node-id-neutral.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,49 @@
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\ArtifactCompiler\ArtifactCompiler;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\HtmlTransformer;

// Capture node IDs bind box-tree evidence. They must not change the block tree
// (wrapper coalescing) or reach output markup (attribute-inlined labels).
$source = '<!doctype html><html><head><style>.c{display:flex;gap:10px}</style></head><body>'
. '<nav><ul><li><a href="/about"><span class="w"><span class="label">About</span></span></a></li><li><a href="/contact">Contact</a></li></ul></nav>'
. '<main><div class="c"><div class="w"><div class="w"><div class="w"><p>Hello world</p></div></div></div>'
// Route-specific capture IDs must affect neither conversion nor shared chrome.
$document = static fn(string $title): string => '<!doctype html><html><head><title>' . $title . '</title><style>.c{display:flex;gap:10px}.hero{display:flex;gap:24px}.hero img{width:240px;height:160px;object-fit:cover}</style></head><body>'
. '<header><nav><ul><li><a href="/about"><span class="w"><span class="label">About</span></span></a></li><li><a href="/contact">Contact</a></li></ul></nav>'
. '<section class="hero"><img src="https://example.com/hero.png" alt="Hero"><div><h2>Welcome</h2><p>Shared introduction</p></div></section></header>'
. '<main><h1>' . $title . '</h1><div class="c"><div class="w"><div class="w"><div class="w"><p>Hello world</p></div></div></div>'
. '<div class="w"><div class="w"><img src="https://example.com/a.png" alt="x"></div></div></div></main></body></html>';
$index = 0;
$stamped = preg_replace_callback('/<([a-z]+)\b/', static function (array $match) use (&$index): string {
return '<' . $match[1] . ' data-blocks-engine-node-id="n' . $index++ . '"';
}, $source);

$plain = (new HtmlTransformer())->transform($source)->toArray()['serialized_blocks'];
$withIds = (new HtmlTransformer())->transform((string) $stamped)->toArray()['serialized_blocks'];
if ($plain !== $withIds) {
throw new RuntimeException("Node IDs changed the block output:\n--- plain\n{$plain}\n--- stamped\n{$withIds}");
$stamp = static function (string $source, string $route): string {
$index = 0;
return preg_replace_callback('/<([a-z][a-z0-9]*)\b/', static function (array $match) use (&$index, $route): string {
return '<' . $match[1] . ' data-blocks-engine-node-id="' . $route . '-' . $index++ . '"';
}, $source);
};
$cases = array(
'single page' => static function (bool $stamped) use ($document, $stamp): array {
$html = $document('Home');
return (new HtmlTransformer())->transform($stamped ? $stamp($html, 'home') : $html)->toArray();
},
'two routes with shared header' => static function (bool $stamped) use ($document, $stamp): array {
$files = array();
foreach (array('index.html' => 'Home', 'about.html' => 'About') as $path => $title) {
$html = $document($title);
$files[$path] = $stamped ? $stamp($html, $title) : $html;
}
return (new ArtifactCompiler())->compile(array('entrypoint' => 'index.html', 'files' => $files))->toArray();
},
);
foreach ($cases as $name => $compile) {
$plain = $compile(false);
$withIds = $compile(true);
if (array() === $plain['assets']) throw new RuntimeException("{$name}: fixture must emit CSS assets");
if ('two routes with shared header' === $name && array() === ($plain['source_reports']['wordpress_site_plan']['template_parts'] ?? array())) {
throw new RuntimeException('Two-route fixture must extract a shared header');
}
foreach (array(
'serialized_blocks' => static fn(array $result): mixed => $result['serialized_blocks'],
'CSS assets' => static fn(array $result): array => array_values(array_filter($result['assets'], static fn(array $asset): bool => 'css' === ($asset['kind'] ?? '') || str_ends_with($asset['path'] ?? $asset['source_path'] ?? '', '.css'))),
'site-plan parts' => static fn(array $result): array => $result['source_reports']['wordpress_site_plan']['template_parts'] ?? array(),
) as $output => $select) {
if ($select($plain) !== $select($withIds)) throw new RuntimeException("{$name}: capture node IDs changed {$output}");
}
if (!str_contains($plain['serialized_blocks'], 'blocks-engine-media-text-image-')) throw new RuntimeException("{$name}: fixture must exercise media-text marker identity");
}
echo "ok\n";
Loading