` blocks and prevents
+ * `@alpinejs/csp` (used by Hyvä Checkout under strict CSP) from evaluating
+ * `x-data` on MageForge root elements before their `Alpine.data()` factories
+ * have been registered.
+ */
+
+const LOCAL_ALPINE_URL = new URL("./lib/alpine.min.js", import.meta.url).href;
+const ALPINE_RUNTIME_FILE_PATTERN =
+ /^alpine(?:js)?(?:\d+)?(?:-csp|\.csp)?(?:\.esm)?(?:\.min)?\.m?js$/i;
+const ALPINE_PACKAGE_PATH_PATTERN = /\/(?:@alpinejs\/csp|alpinejs)(?:@|\/)/i;
+
+let fallbackScheduled = false;
+
+function isAlpineRuntimeScript(script) {
+ const rawSrc = script.getAttribute("src");
+ if (!rawSrc || rawSrc.includes("OpenForgeProject_MageForge/")) {
+ return false;
+ }
+
+ try {
+ const pathname = new URL(rawSrc, window.location.href).pathname;
+ const filename = pathname.split("/").pop() || "";
+ return (
+ ALPINE_RUNTIME_FILE_PATTERN.test(filename) ||
+ ALPINE_PACKAGE_PATH_PATTERN.test(pathname)
+ );
+ } catch {
+ return false;
+ }
+}
+
+function findCandidateAlpineScripts() {
+ return Array.from(
+ document.querySelectorAll(
+ "script[src]:not([data-mageforge-alpine-fallback])",
+ ),
+ ).filter(isAlpineRuntimeScript);
+}
+
+function injectLocalAlpineFallback() {
+ if (
+ typeof window.Alpine !== "undefined" ||
+ document.querySelector("script[data-mageforge-alpine-fallback]")
+ ) {
+ return;
+ }
+
+ const alpineScript = document.createElement("script");
+ alpineScript.src = LOCAL_ALPINE_URL;
+ alpineScript.defer = true;
+ alpineScript.setAttribute("data-mageforge-alpine-fallback", "1");
+ alpineScript.onerror = () => {
+ console.error("[MageForge Inspector] Failed to load bundled Alpine.js");
+ };
+ document.head.appendChild(alpineScript);
+}
+
+function resolveAlpineOrLoadFallback() {
+ if (typeof window.Alpine !== "undefined") {
+ return;
+ }
+
+ const candidates = findCandidateAlpineScripts();
+ if (candidates.length === 0 || document.readyState === "complete") {
+ injectLocalAlpineFallback();
+ return;
+ }
+
+ const recheckAfterLoad = () => setTimeout(injectLocalAlpineFallback, 0);
+ candidates.forEach((script) => {
+ script.addEventListener("load", recheckAfterLoad, { once: true });
+ script.addEventListener("error", recheckAfterLoad, { once: true });
+ });
+ window.addEventListener("load", recheckAfterLoad, { once: true });
+}
+
+/**
+ * Load the bundled local Alpine.js script only when the active theme does not
+ * provide Alpine.js itself (e.g. Luma / Blank).
+ */
+export function ensureAlpineFallback() {
+ if (fallbackScheduled || typeof window.Alpine !== "undefined") {
+ return;
+ }
+ fallbackScheduled = true;
+
+ const scheduleCheck = () => setTimeout(resolveAlpineOrLoadFallback, 0);
+ if (document.readyState === "loading") {
+ document.addEventListener("DOMContentLoaded", scheduleCheck, {
+ once: true,
+ });
+ } else {
+ scheduleCheck();
+ }
+}
+
+/**
+ * Register an Alpine.data() component and initialize matching `[x-data]` roots
+ * regardless of whether Alpine.js (standard or CSP build) executes before or
+ * after this ES module.
+ *
+ * @param {string} name
+ * @param {() => object} factory
+ */
+export function bootstrapAlpineComponent(name, factory) {
+ const selector = `[x-data="${name}"]`;
+ ensureAlpineFallback();
+
+ const registerAndUnignore = () => {
+ Alpine.data(name, factory);
+ document.querySelectorAll(selector).forEach((el) => {
+ el.removeAttribute("x-ignore");
+ delete el._x_ignore;
+ });
+ };
+
+ if (typeof Alpine !== "undefined") {
+ registerAndUnignore();
+ queueMicrotask(() => {
+ document.querySelectorAll(selector).forEach((el) => {
+ if (!el._x_dataStack && typeof Alpine.initTree === "function") {
+ Alpine.initTree(el);
+ }
+ });
+ });
+ } else {
+ document.addEventListener("alpine:init", registerAndUnignore, {
+ once: true,
+ });
+ }
+}
diff --git a/src/view/frontend/web/js/inspector.js b/src/view/frontend/web/js/inspector.js
index 51cff9c0..e56a5cfc 100644
--- a/src/view/frontend/web/js/inspector.js
+++ b/src/view/frontend/web/js/inspector.js
@@ -2,6 +2,7 @@
* MageForge Inspector - Unified DevTools Element & Magento Block Inspector
*/
+import { bootstrapAlpineComponent } from "./alpine-loader.js";
import { domMethods } from "./inspector/dom.js";
import { uiMethods } from "./inspector/ui.js";
import { pickerMethods } from "./inspector/picker.js";
@@ -16,8 +17,8 @@ import { blockDataMap } from "./inspector/blockData.js";
const ICON_PICKER_CURSOR =
'
';
-function _registerMageforgeInspector() {
- Alpine.data("mageforgeInspector", () => ({
+function _createMageforgeInspector() {
+ return {
isOpen: false,
isPickerActive: false,
isPinned: false,
@@ -365,18 +366,7 @@ function _registerMageforgeInspector() {
...vitalsMethods,
...draggableMethods,
...ideMethods,
- }));
+ };
}
-if (typeof Alpine !== "undefined") {
- _registerMageforgeInspector();
- document
- .querySelectorAll('[x-data="mageforgeInspector"]')
- .forEach(function (el) {
- if (typeof Alpine.initTree === "function") {
- Alpine.initTree(el);
- }
- });
-} else {
- document.addEventListener("alpine:init", _registerMageforgeInspector);
-}
+bootstrapAlpineComponent("mageforgeInspector", _createMageforgeInspector);
diff --git a/src/view/frontend/web/js/inspector/performance.js b/src/view/frontend/web/js/inspector/performance.js
index 4b70af06..797287d7 100644
--- a/src/view/frontend/web/js/inspector/performance.js
+++ b/src/view/frontend/web/js/inspector/performance.js
@@ -56,7 +56,7 @@ export const performanceMethods = {
warningDiv.innerHTML = `
-
Full Page Cache Bypassed
+
Full Page Cache Bypassed
Layout XML declares cacheable="false" on this page.
`;
diff --git a/src/view/frontend/web/js/inspector/tabs.js b/src/view/frontend/web/js/inspector/tabs.js
index 64ec3acb..c956d72f 100644
--- a/src/view/frontend/web/js/inspector/tabs.js
+++ b/src/view/frontend/web/js/inspector/tabs.js
@@ -112,7 +112,7 @@ export const tabsMethods = {
inheritanceNote.innerHTML = `
${ICON_INHERITED}
-
Rendered inside Parent Block
+
Rendered inside Parent Block
Element <${element.tagName.toLowerCase()}> belongs to the Magento block below.
`;
@@ -164,7 +164,7 @@ export const tabsMethods = {
inheritanceNote.innerHTML = `
${ICON_INHERITED}
-
Inherited from Parent Block
+
Inherited from Parent Block
Element <${element.tagName.toLowerCase()}> is rendered inside this Magento block.
`;
diff --git a/src/view/frontend/web/js/toolbar.js b/src/view/frontend/web/js/toolbar.js
index ecae5a9f..c2662e6f 100644
--- a/src/view/frontend/web/js/toolbar.js
+++ b/src/view/frontend/web/js/toolbar.js
@@ -2,12 +2,13 @@
* MageForge Toolbar – Unified DevTools Dock & Audit Center.
*/
+import { bootstrapAlpineComponent } from "./alpine-loader.js";
import { matchesShortcut } from "./shortcut-parser.js";
import { uiMethods } from "./toolbar/ui.js";
import { auditMethods } from "./toolbar/audits.js";
-function _registerMageforgeToolbar() {
- Alpine.data("mageforgeToolbar", () => ({
+function _createMageforgeToolbar() {
+ return {
menuOpen: false,
/** @type {Set
} Keys of currently active audits */
@@ -160,18 +161,7 @@ function _registerMageforgeToolbar() {
...uiMethods,
...auditMethods,
- }));
+ };
}
-if (typeof Alpine !== "undefined") {
- _registerMageforgeToolbar();
- document
- .querySelectorAll('[x-data="mageforgeToolbar"]')
- .forEach(function (el) {
- if (typeof Alpine.initTree === "function") {
- Alpine.initTree(el);
- }
- });
-} else {
- document.addEventListener("alpine:init", _registerMageforgeToolbar);
-}
+bootstrapAlpineComponent("mageforgeToolbar", _createMageforgeToolbar);
diff --git a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php
index fc0cf1a9..0b1da9fe 100644
--- a/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php
+++ b/tests/Unit/Model/TemplateEngine/Decorator/InspectorHintsTest.php
@@ -12,6 +12,7 @@
use Magento\Framework\View\TemplateEngineInterface;
use OpenForgeProject\MageForge\Model\TemplateEngine\Decorator\InspectorHints;
use OpenForgeProject\MageForge\Service\Inspector\Cache\BlockCacheCollector;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\Stub;
use PHPUnit\Framework\TestCase;
@@ -242,4 +243,130 @@ public function testRenderDetectsParentBlockAndAlias(): void
$this->assertSame('parent.block', $metadata['parent']);
$this->assertSame('child.block', $metadata['alias']);
}
+
+ /**
+ * @return array
+ */
+ public static function nonInspectableRootTagProvider(): array
+ {
+ return [
+ 'inline script with CSP nonce' => [
+ '',
+ ],
+ 'uppercase script tag' => [
+ '',
+ ],
+ 'inline style with CSP nonce' => [
+ '',
+ ],
+ 'stylesheet link' => [
+ '',
+ ],
+ 'meta element' => [
+ '',
+ ],
+ 'alpine template fragment' => [
+ 'Content
',
+ ],
+ ];
+ }
+
+ #[DataProvider('nonInspectableRootTagProvider')]
+ public function testRenderSkipsNonInspectableAndCspGovernedRootElements(string $markup): void
+ {
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($markup);
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/script.phtml');
+
+ $this->assertSame($markup, $result);
+ }
+
+ public function testRenderSkipsDuplicateInjectionWhenRootElementAlreadyAnnotated(): void
+ {
+ $alreadyAnnotated = 'Hello
';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($alreadyAnnotated);
+ $this->random->method('getRandomString')->willReturn('outer456');
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/container.phtml');
+
+ $this->assertSame($alreadyAnnotated, $result);
+ }
+
+ public function testRenderStillAnnotatesOuterElementWhenOnlyChildIsAnnotated(): void
+ {
+ $nestedMarkup = '';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($nestedMarkup);
+ $this->random->method('getRandomString')->willReturn('parent999');
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/outer.phtml');
+
+ $this->assertStringStartsWith('assertStringContainsString('data-mageforge-id="mageforge-child"', $result);
+ }
+
+ public function testRenderHandlesGreaterThanInsideQuotedRootAttribute(): void
+ {
+ $markup = 'Visible
';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($markup);
+ $this->random->method('getRandomString')->willReturn('quote123');
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/alpine.phtml');
+
+ $this->assertStringStartsWith('assertStringContainsString('x-show="items.length > 0" class="wrapper">Visible
', $result);
+ }
+
+ public function testRenderAnnotatesRootElementWhenMageforgeAttributeOnlyAppearsInsideQuotedValue(): void
+ {
+ $markup = 'Hi
';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($markup);
+ $this->random->method('getRandomString')->willReturn('quoted789');
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/quoted-attr.phtml');
+
+ $this->assertStringStartsWith('assertStringContainsString(
+ 'x-data="{ html: \'Hi\' }">Hi
',
+ $result,
+ );
+ }
+
+ public function testRenderSkipsCaseInsensitiveExistingInspectorAttributes(): void
+ {
+ $alreadyAnnotated = 'Hello
';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($alreadyAnnotated);
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/container.phtml');
+
+ $this->assertSame($alreadyAnnotated, $result);
+ }
+
+ public function testRenderAnnotatesRootElementWhenUnquotedUrlContainsMageforgeAttributeName(): void
+ {
+ $markup = 'Link';
+ $block = $this->createBlock();
+ $this->subject->method('render')->willReturn($markup);
+ $this->random->method('getRandomString')->willReturn('unquotedurl');
+
+ $inspector = $this->createInspectorHints();
+ $result = $inspector->render($block, '/var/www/html/link.phtml');
+
+ $this->assertStringStartsWith('assertStringContainsString('href=/data-mageforge-id class=card>Link', $result);
+ }
}