A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Users/ssatheesh/refactor localization skill (#639)
Sandeep Satheesh3984770c9c43
diff --git a/evals/power-pages/add-localization/evals.json b/evals/power-pages/add-localization/evals.jsonindex 8bfe5b3f1..ea92b6ed7 100644--- a/evals/power-pages/add-localization/evals.json+++ b/evals/power-pages/add-localization/evals.json@@ -11,6 +11,7 @@"Uses runtime i18next plus react-i18next","Displays the Dataverse scope notice and AI translation warning","Validates en-US, fr-FR, and de-DE before implementation",+ "Renders and opens docs/add-localization-plan.html in the en-US source language before retaining the terminal approval gate","Adds selector persistence, fallback, lang, and dir behavior"]},@@ -30,40 +31,42 @@{"id": 3,"prompt": "Add localization to this Angular 19.1 Power Pages site. Support en-US and fr-FR. I am fine with the recommended option.",- "expected_output": "Recommend Angular's official matching @angular/localize package and static locale builds, then create XLF catalogs and locale build configuration.",+ "expected_output": "Use the currently available Angular runtime mode with Transloco and do not offer or plan the temporarily unavailable static mode.","files": [],"expectations": [- "Recommends static @angular/localize rather than Transloco",- "Uses a package version compatible with Angular 19.1",- "Configures Angular i18n locale builds and XLF resources",- "Adds navigation between equivalent locale builds",- "Does not add runtime browser persistence"+ "Reads Angular mode availability from the centralized localization capability registry",+ "Selects Angular runtime localization and recommends @jsverse/transloco while allowing a validated runtime alternative",+ "Does not offer or plan @angular/localize static builds",+ "Adds in-place language switching with browser-local persistence",+ "Validates the runtime implementation and manifest"]},{"id": 4,"prompt": "Our Angular site must switch language instantly without a reload. Add English and Arabic localization.",- "expected_output": "Offer the official static recommendation but allow the explicit runtime requirement to select Transloco, including persisted selection and RTL handling.",+ "expected_output": "Use the available Angular runtime mode, recommend Transloco while allowing validated runtime alternatives, and include persisted selection and RTL handling.","files": [],"expectations": ["Chooses Transloco only because runtime switching was explicitly requested","Configures runtime selection without page reload","Persists only the browser-local locale preference","Sets lang and rtl direction for Arabic",+ "Repairs native free-form inputs and textareas so empty, clear-after-RTL, and clear-after-LTR controls follow the active UI direction while populated controls use automatic value direction, preserving dirname metadata",+ "Keeps email, telephone, URL, path, code, GUID, and identifier controls explicitly LTR with adjacent bidi-fixed documentation while their surrounding field UI follows the locale","Flags RTL layout areas for manual visual review"]},{"id": 5,"prompt": "Make my Astro Power Pages site available at English and Japanese locale URLs.",- "expected_output": "Use Astro built-in i18n static routes and navigate between locale-specific URLs.",+ "expected_output": "Explain that Astro static localization is temporarily unavailable and stop before configuration, plan rendering, or file changes.","files": [],"expectations": [- "Uses Astro built-in i18n without an npm localization package",- "Creates static locale routes",- "Uses equivalent-route navigation in the selector",- "Configures explicit default-locale routing and fallback",- "Does not add client-side locale persistence"+ "Reads Astro availability from the centralized localization capability registry",+ "Shows the stable temporarily-unavailable reason",+ "Does not gather locale or package configuration",+ "Does not render an add-localization plan",+ "Does not install dependencies or change project files"]},{@@ -82,14 +85,15 @@{"id": 7,"prompt": "Repair localization in this Angular project. The manifest says Transloco runtime but angular.json and dependencies use @angular/localize static builds.",- "expected_output": "Surface the conflict, enter repair/reconfigure flow, ask which evidence-backed mode should remain, and change only the approved delta.",+ "expected_output": "Surface the conflict and static-mode availability block, then allow only explicit reconfiguration to the available Transloco runtime mode or a clean stop.","files": [],"expectations": [- "Does not guess which conflicting mode is authoritative",- "Shows manifest, dependency, and angular.json evidence",+ "Reports the manifest, dependency, and angular.json conflict",+ "Explains that Angular static localization is temporarily unavailable",+ "Offers reconfiguration to Angular runtime localization or Stop without changes",+ "Does not allow static mode to enter the plan","Requires a new plan approval before replacement",- "Preserves translations unless replacement is explicitly approved",- "Rewrites the manifest to match the repaired implementation"+ "Preserves translations unless replacement is explicitly approved"]},{@@ -182,8 +186,12 @@"Canonicalizes ar and he","Sets documentElement.dir to rtl for both","Restores ltr for non-RTL locales",- "Browser-tests at least one RTL locale",- "Flags directional icons and fixed left/right styling for review"+ "Runs real activation, localized content, script-font, formatting, lang/dir, resource, and console smoke checks independently for Arabic and Hebrew",+ "Chooses one newly added RTL locale as the representative for the full component-state and viewport matrix and puts the other locale's complex components in the maker review checklist",+ "Runs default-to-locale-to-default for every real non-default locale and requires the reverse round trip for representative locales in standard verification",+ "Offers extensive verification before finalization when the maker wants the full component matrix and both round trips repeated for every locale",+ "Groups compatible component states by route, viewport, and locale, uses explicit reset actions before navigation reuse, and runs independent groups with bounded concurrency while keeping locale transitions serial",+ "Flags directional icons, fixed direction, physical utility classes, asymmetric shorthands, and raw horizontal scrolling assumptions for remediation or review"]},{@@ -233,6 +241,7 @@"expectations": ["Does not treat this as add-languages mode","Asks for the new default only because change was explicit",+ "Keeps the rendered localization plan in the existing pre-change source/default language even though the resulting default changes to fr-FR","Shows affected fallback and route behavior","Preserves locale resources","Updates and validates the manifest default"@@ -259,10 +268,75 @@"expectations": ["Recognizes FROM_CREATE_SITE context","Runs the same localization implementation and verification path",+ "Renders and opens the dedicated source-language localization plan artifact before terminal approval","Records AddLocalization usage","Does not ask to deploy from add-localization","Returns control to create-site"]+ },+ {+ "id": 21,+ "prompt": "Add Hebrew to our existing English React customer portal. It has a contact form with helper text, a mobile drawer, an autocomplete menu rendered in a portal, and a third-party scheduling widget. Keep the existing brand and layout style.",+ "expected_output": "The workflow treats the first LTR-only to mixed-direction change as a targeted bidirectional adaptation, inventories and classifies the existing components and their applicable states/viewports before approval, preserves unrelated design choices, and keeps Hebrew unavailable if blocking remediation remains.",+ "files": [],+ "expectations": [+ "Detects the transition from LTR-only to mixed direction and runs the readiness audit before plan approval",+ "Builds a non-empty READINESS_DATA.componentScope from the actual existing implementation",+ "Classifies every visible or interactive shared and page-local component using the four language-agnostic classifications",+ "Plans separate applicable states and desktop or narrow viewports for the form, drawer, autocomplete, and scheduling widget",+ "Treats form labels, placeholders, hints, helper text, errors, prefixes, suffixes, values, and open panels as one compound direction surface",+ "Requires rendered checks for the portal-mounted autocomplete and third-party scheduling widget",+ "Builds an ephemeral rendered-verification specification and executes every applicable state and viewport in English LTR and Hebrew RTL",+ "Requires English to Hebrew to English and Hebrew to English to Hebrew runtime sequences without reload, route loss, form-state loss, or focus loss",+ "Records computed-direction, overflow, clipping, overlap, focus-order, portal, and third-party evidence with screenshots for failures or review findings",+ "Runs the expanded static audit before approval and parses its structured findings even when deterministic errors produce a nonzero exit",+ "Requires an adjacent bidi-fixed reason for intentional machine-oriented LTR values and does not permit that exception for localized labels, placeholders, hints, or errors",+ "Describes remediation as a targeted bidirectional adaptation that preserves branding, routes, features, and visual character",+ "Does not create a separate persistent component-inventory JSON file",+ "Keeps Hebrew unavailable when an externally owned or existing component has a blocking unremediated defect",+ "Records unresolved rendered blockers separately from static scanner findings and does not offer locale enablement while they remain",+ "Writes a provisional pending-remediation manifest before validation, keeping affected locales unavailable until static and rendered verification are complete",+ "Requires the approved review scope to be reconciled with components and states discovered during implementation",+ "Finalizes the manifest only after the maker decision: ready has no findings, approved limitations retain only review findings with maker-approved impact/evidence/timestamp, and unresolved work remains pending",+ "Reruns validation and affected locale activation checks after changing readiness or availability",+ "Final summary reports the manifest path, readiness status, available and unavailable locales, finding totals, rendered report, and every approved limitation"+ ]+ },+ {+ "id": 22,+ "prompt": "Add Arabic to our English React site. The third-party booking widget works in RTL, but its vendor-owned calendar arrow remains visually unchanged. If testing proves it is still understandable and usable, I may accept that limitation.",+ "expected_output": "The workflow verifies the widget in its open state, treats any deterministic functional or readability failure as blocking, and permits only an evidence-backed review-severity limitation to be explicitly approved after testing.",+ "files": [],+ "expectations": [+ "Plans the booking widget as unknown-third-party with its open state, desktop and narrow coverage, portal or iframe target, and exact rendered checks",+ "Begins from fail-closed Arabic availability, records an exclusive verification transaction, and tests Arabic through the real selector while completion and deployment remain blocked",+ "Does not treat the user's advance willingness as approval and asks again only after showing the rendered evidence and exact impact",+ "Does not offer approval if the widget is unreadable, clipped, unreachable, incorrectly directed, or otherwise has an error-severity finding",+ "If the remaining issue is review-severity usable degradation, offers Fix before enabling, Enable with documented limitations, Save but keep locale unavailable, and Request revisions",+ "On enablement, records only the accepted review finding with maker-approved disposition, impact, report or screenshot evidence, and ISO approval timestamp",+ "Keeps the verification transaction active through maker disposition, then finalizes Arabic as approved-with-limitations and available only after recording the approved evidence",+ "Reports the final readiness and limitation consistently in the manifest and final summary"+ ]+ },+ {+ "id": 23,+ "prompt": "Our English React portal already has Hebrew enabled and verified. Add Arabic now. Arabic has a serious language-specific font failure in its calendar, but Hebrew still passes regression testing. Save the Arabic work so we can fix it later without disabling Hebrew.",+ "expected_output": "The workflow tests Arabic independently, preserves Hebrew as ready and available because regression evidence shows it is unaffected, and keeps only Arabic pending and unavailable.",+ "files": [],+ "expectations": [+ "Starts Arabic fail-closed, then temporarily exposes only Arabic under an exclusive verification transaction without changing the previously ready Hebrew locale",+ "Runs Arabic resource, activation, lang and dir, font, formatting, wrapping, console, and accessibility checks and selects Arabic as the RTL component-matrix representative",+ "Runs Hebrew locale smoke coverage and places its high-risk complex components in the maker review checklist instead of automatically repeating the full RTL matrix",+ "Records the calendar font failure with locale scope and affectedLocales containing only ar-SA",+ "Keeps he-IL ready and available because current evidence does not identify it as affected",+ "Sets only ar-SA to pending-remediation and makes unavailableLocales exactly [ar-SA]",+ "Derives the overall bidirectional readiness status as pending-remediation while retaining per-locale readiness",+ "Applies the Arabic exclusion to selectors, automatic detection, alternate-language metadata, and production output",+ "Exercises Arabic through the real selector and public locale coordinator, then restores Arabic to unavailable after the failure",+ "Does not require all RTL locales to be unavailable merely because Arabic failed",+ "Runs English to Arabic to English and Arabic to English to Arabic because Arabic is the RTL representative; pseudo locales are not used for application switching",+ "Final summary clearly reports Hebrew as available and Arabic as unavailable"+ ]}]}diff --git a/evals/power-pages/create-site/evals.json b/evals/power-pages/create-site/evals.jsonindex 20eb635e3..3a527ad79 100644--- a/evals/power-pages/create-site/evals.json+++ b/evals/power-pages/create-site/evals.json@@ -8,6 +8,7 @@"files": [],"expectations": ["Discovery phase asks for site name, framework, purpose, audience, and project location via AskUserQuestion",+ "Because no content language was explicit, runs suggest-content-locale.js and offers its Dataverse base-language result as Suggested, silently falling back to en-US when unavailable","Site naming values are derived: __SITE_NAME__ = 'Contoso Solutions Portal', __SITE_SLUG__ = 'contoso-solutions-portal'","React template is copied from the assets/react/ directory and all __PLACEHOLDER__ tokens are replaced","gitignore file is renamed to .gitignore in the project root",@@ -19,7 +20,10 @@"Design references are read from ${PLUGIN_ROOT}/references/design-aesthetics.md and ${PLUGIN_ROOT}/references/page-blueprints.md, and an experience brief (audience and job, primary and secondary action, principal doubt, proof strategy, design thesis, hero concept, signature moment) is written before tokens are chosen","A component plan table is presented showing pages, shared components, design elements, and routes","Color tokens cover every role in design-aesthetics.md section 3 (background, surfaces, text, muted text, borders, primary and on-primary, accent, focus, success, warning, danger), with each text and background pair checked against WCAG AA contrast",- "The implementation plan is rendered to docs/create-site-plan.html with render-createsite-plan.js, including its Design direction section, and user approval is requested",+ "The implementation plan is rendered to docs/create-site-plan.html in the selected content language with a complete PLAN_LABELS dictionary, correct lang/dir metadata, RTL-safe layout, unchanged technical values, its Design direction section, and user approval is requested",+ "Implementation plan separates REVIEW_DATA.agentChecks from REVIEW_DATA.makerReview, includes create-stage bidirectional-readiness criteria, and makes clear that the agent executes technical checks while the maker reviews linguistic, cultural, brand, and visual quality",+ "Native free-form inputs and textareas use adaptive direction: active UI direction while empty or cleared and dir=auto only while populated; dirname metadata is preserved where appropriate",+ "Rendered form checks cover empty, RTL-valued, LTR-valued, clear-after-RTL, and clear-after-LTR free-form states under both UI directions, while machine-oriented controls remain documented bidi-fixed LTR","Design foundations are applied first: distinctive Google Fonts (not Inter/Roboto/Arial), CSS variables for colors, motion/animation utilities, and background treatments","The scaffold loading screen is completely replaced — no trace of Power Pages branded animation remains","Visuals follow design-aesthetics.md section 6: the site's own UI composed as a product moment or bespoke inline SVG first; any photography is task-specific Unsplash imagery found via WebSearch, sharing one art direction - never placeholder services",@@ -91,6 +95,7 @@"Each page gets its own dedicated git commit; each component gets its own commit","Playwright browser_snapshot checks each page's structure after creation; visual judgement comes from capture-design-review.js screenshots, not per-page browser_take_screenshot calls","The Phase 5.7 design critique captures every route at desktop and mobile with one capture-design-review.js call per round, sending the URL and routes as a JSON request on stdin, scores the 10-category rubric, and fixes failing critical gates and categories below 3; after three rounds, a critical gate that still fails goes to the user through the critique-blocked prompt",+ "Checks centralized localization availability and does not offer the add-localization child workflow because Astro has no currently available mode","axe-core audit script runs on all site routes, sent as a JSON request on stdin (--input -)","All critical/serious accessibility violations are fixed, committed, and re-verified","Accessibility summary table shows per-page violations found vs fixed",@@ -147,16 +152,45 @@{"id": 6,"prompt": "Create an Astro Power Pages site called Local Bakery. Keep it English-only.",- "expected_output": "The workflow builds the site, asks the fixed localization question in Phase 5.7, records the opt-out, and continues without invoking add-localization. It may suggest the skill later as an optional enhancement.",+ "expected_output": "The workflow builds the site, reads centralized localization availability in Phase 5.7, explains that Astro localization is temporarily unavailable, and continues without invoking or suggesting add-localization.","files": [],"expectations": [- "Asks the localization question only after the real pages are built",- "Shows the localization scope subtext",- "Offers exactly 'Yes — configure localization now' and 'No — keep this site single-language'",+ "Checks mode availability only after the real pages are built",+ "Uses the centralized Astro temporarily-unavailable reason",+ "Does not ask the additional-languages question","Records LOCALIZATION_REQUESTED=false","Does not invoke add-localization during implementation","Continues normal accessibility, review, and deployment phases",- "May list add-localization as an optional next step"+ "Does not list add-localization as an available optional next step"+ ]+ },+ {+ "id": 7,+ "prompt": "Create a Hebrew React Power Pages customer portal with a contact form, autocomplete address field, mobile navigation drawer, and a third-party date picker.",+ "expected_output": "The workflow plans every visible or interactive component using language-agnostic bidirectional classifications, treats form states and viewports as separate surfaces, and records rendered checks for the third-party date picker without creating a component-inventory manifest.",+ "files": [],+ "expectations": [+ "Resolves the Hebrew locale direction from its writing script rather than a hardcoded language-only allowlist",+ "Builds BIDIRECTIONAL_REVIEW_DATA for shared and page-local visible or interactive components before plan approval",+ "Classifies the contact form, address autocomplete, mobile drawer, and third-party date picker as direction-neutral, direction-aware, direction-fixed, or unknown-third-party with localized reasons",+ "Records only applicable component states, including form validation, autocomplete-open, drawer-open, and date-picker-open states",+ "Records desktop and/or narrow viewports independently for each component",+ "Treats form labels, placeholders, hints, validation messages, prefixes, suffixes, icons, and open panels as one compound direction surface",+ "Requires rendered checks for third-party open states and portal or overlay content",+ "Plans actual RTL and pseudo-LTR coverage because every new site receives selected and opposite-direction verification",+ "Runs the expanded static audit, fixes deterministic fixed-direction, physical-utility, shorthand, and unicode-bidi errors, and records raw horizontal scrolling assumptions for review and remediation when required",+ "Builds an ephemeral rendered-verification specification from the reconciled scope and runs every applicable component state and viewport in actual RTL and pseudo-LTR",+ "The rendered audit checks computed direction, page overflow, clipping, viewport escape, declared overlap, focus order, portals, and the third-party date-picker open state",+ "Blocks Phase 7 for rendered errors, triages every review finding with evidence and a proposed outcome, and never offers a deterministic error for maker override",+ "Allows only review-severity usable limitations to be accepted at the final maker gate and records their exact impact, evidence path, and approval time",+ "Consumes per-locale readiness from the localization workflow, keeps only locales with pending findings unavailable, and does not disable an unaffected locale merely because it shares a writing direction",+ "Reuses a successful add-localization rendered report only when it came from a full standard or extensive run and its source, resource, dependency, build-configuration, and availability fingerprint remains current",+ "Uses bounded concurrent route, viewport, and locale groups and reuses navigation only for states with a verified deterministic reset",+ "Persists only the rendered evidence report and failure or review screenshots, not a second authoritative component manifest",+ "Uses a narrowly scoped bidi-fixed directive only for intentional machine-oriented LTR values, never for localized form UI",+ "Does not create a separate persistent component-inventory JSON file",+ "Requires Phase 5 to reconcile the planned review scope with the actual source and rendered application",+ "Final summary reports bidirectional readiness, static and rendered finding totals, evidence, approved limitations, and any localization locales that remain unavailable"]}]diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 46fa58905..a175f7453 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -17,7 +17,11 @@ Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creatin- **Dataverse-backed validation** must stay opt-in for local runs only. Do not require live Dataverse connectivity in CI workflows or default test runs; gate it behind explicit local flags such as `--validate-dataverse-relationships`.- **Azure CLI `--allow-no-subscriptions`** — this flag is only valid on `az login`. Other `az` subcommands (`az account get-access-token`, `az account show`, etc.) reject it as an unrecognized argument and exit 2, so do NOT add it to anything other than `az login`. When the user is not logged in to the Azure CLI, suggest plain `az login` first; only suggest `az login --allow-no-subscriptions` as a fallback if they don't have any associated Azure subscription, since that variant lets subscription-less accounts sign in and still mint AAD-scoped Dataverse/Power Platform tokens via subsequent `az account get-access-token` calls. Reuse the shared `getAuthToken` helper in `scripts/lib/validation-helpers.js` instead of shelling out to `az` directly.- **Reference docs** shared across skills live in `references/` — reference via `${PLUGIN_ROOT}/references/` paths, don't duplicate.-- **Bidirectional by default** — All generated sites must follow `references/bidirectional-design.md`: resolve direction from the locale's writing script, prefer CSS logical properties, isolate mixed-direction content, use script-capable font profiles, and classify directional assets instead of mirroring everything. Intentional physical CSS requires an adjacent `/* bidi-physical: <specific reason>; verify=ltr,rtl */` directive. Run `scripts/audit-bidirectional-readiness.js` for deterministic readiness findings.+- **Bidirectional by default** — All generated sites must follow `references/bidirectional-design.md`: resolve direction from the locale's writing script, prefer CSS logical properties, isolate mixed-direction content, use script-capable font profiles, and classify every visible or interactive component as direction-neutral, direction-aware, direction-fixed, or unknown/third-party. Plan applicable states and viewports separately; form fields include labels, placeholders, hints, errors, prefixes/suffixes, and open overlays. Native free-form controls use adaptive direction (UI direction while empty/cleared, `auto` while populated) and preserve `dirname`; machine-oriented controls remain documented LTR. Intentional physical placement requires an adjacent `/* bidi-physical: <specific reason>; verify=ltr,rtl */` directive; intentional fixed-direction values require an adjacent `/* bidi-fixed: <specific reason>; verify=ltr,rtl */` directive. Run `scripts/audit-bidirectional-readiness.js` for deterministic readiness findings.+- **Readiness is fail-closed** — A locale cannot become available while a static or rendered bidirectional error remains. `ready` retains no findings; `approved-with-limitations` retains only review findings with explicit maker approval, impact, evidence, and timestamp; unresolved or undisposed findings remain `pending-remediation` with affected locales excluded at every activation boundary.+- **New locales use an optimistic verification transaction** — Begin from fail-closed pending availability, record the transaction, expose only its target locales through the normal selector for local Playwright testing, keep them available on success, return any target the maker defers to `unavailableLocales` at finalization, and restore them to `unavailableLocales` on failure. Active or abandoned transactions block completion and deployment: `scripts/validate-site-integrity.js` rejects any remaining transaction by default, and only add-localization's pre-review Phase 6 gate passes `--allow-verified-localization-review` to accept a `verified` transaction with current evidence while the maker decision is pending.+- **Localization rendered verification is profile-based** — Standard verification smoke-tests every real locale but runs the full component/state/viewport matrix only for representative LTR/RTL locales using conservative component risk. High-risk components in other locales require maker review or an explicit extensive run. Extensive verification runs the complete locale matrix; targeted verification is only for repair reruns. Reuse a report only when it came from a standard or extensive run and its project-input fingerprint is still current; targeted evidence is never reused.+- **Rendered cases use bounded grouped execution** — Group component cases by route, viewport, and locale and run independent groups with the bounded worker pool (default 3). State isolation defaults to reload; use resettable only with an explicit reset that proves route/locale/content/availability invariants, and isolated for destructive or global state. Runtime transitions remain serial.- **Local scaffold templates** use `__PLACEHOLDER__` tokens (e.g., `__SITE_NAME__`) replaced during from-scratch scaffolding. The `gitignore` file is stored without the dot prefix and renamed to `.gitignore` during scaffolding.- **Batch browser work into one script call** - every tool call re-sends the whole conversation, and each Playwright MCP `browser_navigate` also returns a full page snapshot, so per-page MCP calls multiply cost and trigger context compactions. `create-site` captures every route at both widths with one `capture-design-review.js` call and opens the screenshots in one turn; prefer that pattern whenever a skill needs the same browser work across several pages. Keep the design review inline rather than in a subagent: a fresh context re-loads every screenshot, which raises cost without improving the review.- **Browser review scripts** (`capture-design-review.js`, `axe-audit.js`) share their boundaries through `scripts/lib`, so add new browser work there rather than beside them:@@ -49,7 +53,10 @@ agents/scripts/generate-uuid.js ← Shared UUID v4 generator (used by multiple skills)detect-framework.js ← Reports explicit-project framework evidence without guessing ambiguous projects+ suggest-content-locale.js ← Best-effort Dataverse base-language suggestion for create-site+ render-add-localization-plan.js ← Validates and renders the source-language localization plan artifactaudit-bidirectional-readiness.js ← Audits generated source for deterministic bidirectional blockers and review findings+ audit-rendered-bidirectional-readiness.js ← Runs the component/state/viewport/direction matrix in Playwrightvalidate-site-integrity.js ← Shared post-modification/deployment localization and bidirectional integrity checkvalidate-i18n-package.js ← Validates npm localization package compatibility, stability, maintenance, mode, docs, and licenseemit-localization-completed-telemetry.js ← Emits add-localization completion only after final workflow verification@@ -95,7 +102,9 @@ skills/scripts/validate-seo.js ← Node script validating SEO assets (robots.txt, sitemap.xml, meta tags)add-localization/SKILL.md ← SPA localization workflow for React, Vue, Angular, and Astro- scripts/validate-localization.js ← Validates manifest, resources, selectors, lang/dir, opposite-direction readiness, and runtime coordinators+ assets/add-localization-plan.html ← Localized, RTL-safe implementation-plan template+ references/plan-data-contract.md ← Source-language plan schema, labels, persistence, and source-of-truth rules+ scripts/validate-localization.js ← Validates manifest, resources, selectors, lang/dir, per-locale bidirectional readiness, and runtime coordinatorsactivate-site/SKILL.md ← Site activation/provisioning skill definitionscripts/activate-site.js ← Activates a site via PP API + polls status@@ -178,7 +187,7 @@ User-invocable via `/power-pages:<skill-name>`:- `add-sample-data`: 6-step workflow — verify prerequisites, discover tables (from `.datamodel-manifest.json` or OData API), select tables & configure record count, generate & review sample data plan, insert records via OData API with relationship handling, verify & summarize.- `activate-site`: 5-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution + activation status check via shared script), gather parameters (site name, subdomain, website record ID), confirm with user, activate & poll via `skills/activate-site/scripts/activate-site.js`, present summary with site URL.- `add-seo`: 7-step workflow — verify site exists, gather SEO config (production URL, exclusions, meta description), plan & approve, create robots.txt, generate sitemap.xml from discovered routes, add meta tags (title, description, viewport, Open Graph, Twitter Card, favicon) to index.html, verify via Playwright & commit.-- `add-localization`: 8-phase workflow — detect framework/existing i18n, validate BCP-47 locales and package choices, approve exact file delta, configure framework localization, extract/generate translations, add runtime selector or static locale navigation, validate/build/browser-test, review, and conditionally deploy. React/Vue use runtime localization; Angular recommends official `@angular/localize` static builds with Transloco available for runtime; Astro uses built-in static locale routes.+- `add-localization`: 8-phase workflow — detect framework/existing i18n, enforce centralized mode availability, validate BCP-47 locales and package choices, approve exact file delta, configure framework localization, extract/generate translations, add runtime selection, validate/build/browser-test, review, and conditionally deploy. React/Vue/Angular runtime are active; Angular static and Astro static remain documented dormant capabilities and must not enter a plan or pass validation.- `create-webroles`: 6-step workflow — verify `.powerpages-site/web-roles/` exists (redirect to deploy-site if missing), discover existing roles, determine new roles needed, create web role YAML files with UUIDs from shared `scripts/generate-uuid.js`, verify web roles (validate files, UUIDs, uniqueness constraints), review & prompt deployment via deploy-site skill.- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `table-permissions-architect` and `webapi-settings-architect` agents (in parallel) to configure table permissions and site settings, review & deploy via `deploy-site` skill. Supports an `[AI-READ-ONLY]` sentinel that hardens the flow to read-only when invoked by `/add-ai-webapi`.- `add-ai-webapi`: 8-phase workflow — verify site/deployment, Explore-agent scan for search/data summarization candidates, review plan with user, **delegate Layer 1/2** (Web API site settings + table permissions) to `/integrate-webapi` in AI-only read mode and to `/create-webroles`, invoke `ai-webapi-integration` agent **sequentially per target** to create the summarization service + framework wrapper + UI wiring, invoke `ai-webapi-settings-architect` for Layer 3 (`Summarization/*` settings), verify (header-contract grep, `$select` grep, build, validator), review & deploy. This skill owns **Layer 3 only** and delegates everything else. Validator: `skills/add-ai-webapi/scripts/validate-ai-webapi.js`. AI summarization APIs are a **preview** feature gated by a three-level admin hierarchy.@@ -217,6 +226,7 @@ All skill folders are tracked. Skills without a `scripts/validate*.js` file areShared utility scripts live at `scripts/` and are referenced by multiple skills and agents via `${PLUGIN_ROOT}/scripts/`.- `generate-uuid.js`: Generates a random UUID v4. Self-contained, no dependencies. Used by `create-webroles` and the main agent when creating table permission / site setting files from the `webapi-permissions` agent plan.+- `suggest-content-locale.js`: Queries the selected Dataverse organization's `languagecode`, resolves the LCID through `languagelocale`, and returns a canonical BCP-47 content-language suggestion for `create-site`. It is read-only and always falls back silently to `en-US` when environment discovery, authentication, API access, or mapping is unavailable.- `update-skill-tracking.js`: Updates skill usage tracking site settings. Takes `--projectRoot`, `--skillName`, and `--authoringTool` args. The agent passes its own name as `--authoringTool` (e.g., `ClaudeCode`, `GitHubCopilot`). Creates/increments a per-skill counter (`Site-AI-<SkillName>.sitesetting.yml`) and records the authoring tool (`Site-AI-AuthoringTool.sitesetting.yml`). Exits silently if `.powerpages-site/site-settings/` does not exist. Used by every user-invocable skill (each skill calls it in its final phase per the skill-tracking convention).- `check-activation-status.js`: Checks whether a Power Pages site is already activated (provisioned) in the environment. Takes `--projectRoot` arg. **Site-identity resolution (`resolveSiteIdentity()`, exported + injectable for tests): (1) `powerpages.config.json` (code/SPA sites) → `siteName` + optional `websiteRecordId`; (2) else `.powerpages-site/website.yml` (declarative/data-model sites) → `name`→`siteName`, `id`→`websiteRecordId`; (3) `pac pages list` ONLY when the GUID is still unknown** — declarative sites (and code sites whose config included the GUID) skip the `pac pages list` exec entirely. Then queries the Power Platform GET websites API and matches by both `websiteRecordId` and `name`. Outputs JSON: `{ activated: true/false, siteName, websiteRecordId, websiteUrl }` or `{ error }`. The CLI flow is guarded by `require.main === module`; `module.exports = { resolveSiteIdentity, getWebsites }`. Used by `deploy-site` and `activate-site`.- `poll-async-operation.js`: Polls a Dataverse `asyncoperations` record until it reaches a terminal state (Succeeded/Failed/Canceled) or times out. Args: `--asyncJobId`, `--envUrl`, `--intervalMs` (default 5000), `--maxAttempts` (default 60). It acquires Azure CLI tokens internally so credentials never appear in process arguments. Outputs JSON status. Used by `export-solution` and `import-solution`.@@ -229,7 +239,7 @@ Shared utility scripts live at `scripts/` and are referenced by multiple skillsShared lib modules live at `scripts/lib/` and are imported by other scripts via `require('./validation-helpers')` or sibling requires. Never inline their logic in skill scripts — always require from `scripts/lib/`.- `scripts/lib/framework-detection.js`: Detects React, Vue, Angular, or Astro for an explicit project root from dependency declarations and primary configuration markers. Use this module as the single source of truth for explicit-project framework detection. It is intentionally separate from telemetry's workspace-oriented `detect-site-framework.js`.-- `scripts/lib/localization-config.js`: Detects existing localization, validates/canonicalizes BCP-47 tags against `references/bcp47-subtags.json`, visibly deduplicates locales, and extracts protected translation tokens. It consumes and temporarily re-exports the shared framework detector for compatibility; do not add generic framework-detection logic here.+- `scripts/lib/localization-config.js`: Detects existing localization, owns the selectable-mode availability registry and stable unavailability reasons, validates/canonicalizes BCP-47 tags against `references/bcp47-subtags.json`, visibly deduplicates locales, and extracts protected translation tokens. It consumes and temporarily re-exports the shared framework detector for compatibility; do not add generic framework-detection logic or duplicate mode availability elsewhere.- `scripts/lib/package-license-policy.js`: Owns normalization and classification for localization-package license metadata. Keep the unattended acceptance list here and require explicit maker confirmation for every other classification.- `scripts/lib/safe-untrusted-text.js`: Bounds and neutralizes control and bidirectional characters in project- or network-controlled values before they reach agent-visible output. Reuse it instead of adding one-off diagnostic escaping.@@ -460,6 +470,9 @@ These patterns have caused repeated PR review feedback. Check for them before su- **Validators must match the exact constraint** — If the rule is "no exports at all", block all `module.exports`/`exports` — don't just check if exported names are in an allowlist. If the rule is "try/catch required", verify both `try` AND `catch` exist. Re-read the exact constraint from SKILL.md and test the boundary cases.- **Hook scripts run on every Skill tool use** — The PostToolUse hook fires for all tracked skills, so unconditional `process.stderr.write` creates noise. Gate debug logging behind `process.env.DEBUG`. Only errors should go to stderr unconditionally.- **Template placeholders are context-encoded** — bare string placeholders render as HTML text, while structured values render as script-safe JSON. Use `__JSON_KEY__` for every JavaScript or `application/json` value, `__ATTR_KEY__` for attributes, and reserve `__RAW_KEY__` for code-owned trusted markup.+- **The create-site plan has a strict localization contract** — `render-createsite-plan.js` requires every maker-facing template phrase in `PLAN_LABELS` and validates that `SITE_LOCALE` matches `SITE_DIRECTION`. Keep routes, commands, CSS variables, framework/package names, locale tags, identifiers, and API names untranslated; inject localized labels through serialized JSON and DOM APIs rather than quoted HTML attributes or JavaScript string placeholders.+- **Create-site review responsibilities must stay explicit** — `REVIEW_DATA.agentChecks` contains deterministic source, browser, bidi, formatting, font, component, console, and accessibility checks the agent must execute and report. `REVIEW_DATA.makerReview` contains linguistic, cultural, brand, and subjective visual judgments. Never present an agent-owned check as work the maker must repeat, and never claim automation approved a maker-owned judgment.+- **The add-localization plan uses the current source locale** — Render `docs/add-localization-plan*.html` in the existing pre-change default locale, or the locale selected to represent an unlocalized site's existing UI. A resulting default-locale change does not change the plan language. The HTML persists for human reference only; implementation must use the approved configuration and final `.powerpages-localization.json`, never parse the plan artifact.- **Guidance must be consistent within a skill** — If one section says "always use raw fetch", a framework-specific table in the same file must not recommend a different HTTP client without qualification. Reviewers will flag contradictions.## Secure Coding Requirementsdiff --git a/plugins/power-pages/README.md b/plugins/power-pages/README.mdindex 2521bb521..7583075b4 100644--- a/plugins/power-pages/README.md+++ b/plugins/power-pages/README.md@@ -54,7 +54,15 @@ Starts a complete code site either from a curated SPA template or from a fresh f- Start from a curated SPA template or scaffold from scratch- Choose from React, Vue, Angular, or Astro-- Direction-neutral layouts work with LTR and RTL writing systems from the start+- Suggests the selected Dataverse environment's base language for site content,+ with a silent `en-US` fallback when the environment cannot be queried+- Renders the implementation plan in the selected content language, including+ correct `lang`/`dir` metadata and an RTL-safe layout+- Separates deterministic agent verification from linguistic, cultural, brand,+ and visual checks that require maker review+- Every visible or interactive component is classified for bidirectional+ behavior, with applicable states and desktop/narrow viewports planned+ separately; direction-neutral layouts work with LTR and RTL from the start- Script-aware fonts, locale-aware formatting, and mixed-direction content safety- Real images from Unsplash (no placeholders)- Live browser preview during development@@ -91,6 +99,15 @@ Runtime-tests a deployed, activated site using a real browser (via the bundled P- Console and network error capture- Screenshots on failure+Create-site and add-localization also run a component-scoped rendered+bidirectional audit against their development preview. It verifies computed+direction, overflow, clipping, focus order, portals/overlays, applicable+states and viewports, and runtime locale round trips. The run report is+validation evidence rather than a second component manifest. Deterministic+errors keep affected locales unavailable. Only usable review-severity+limitations can be enabled after the maker sees the exact impact and evidence;+that approval is recorded in the localization manifest.+### Data modeling#### `/setup-datamodel`@@ -403,23 +420,29 @@ The result is a scorecard plus prioritized recommendations, each naming the page> "Add French and German to my site"-Adds or extends multilingual localization for React, Vue, Angular, and Astro-Power Pages code-site SPAs.+Adds or extends multilingual localization for React, Vue, and Angular runtime+Power Pages code-site SPAs. Astro and Angular static localization are+temporarily unavailable.- Detects and preserves existing localization configuration and translations+- Renders and opens a persistent `docs/add-localization-plan.html` in the+ site's current source language before the terminal approval gate- Validates canonical BCP-47 language tags against the bundled IANA registry-- Recommends runtime localization for React/Vue, official static localization- for Angular, and built-in static locale routes for Astro+- Centralizes mode availability: React, Vue, and Angular runtime are active;+ Angular static and Astro static remain dormant for future re-enablement- Generates translations with the agent or creates blank values for manualcompletion- Resolves direction from each locale's writing script, including languageswritten in multiple scripts-- Audits the first opposite-direction locale and remediates blocking layout,- component, asset, mixed-content, and font issues+- Audits every added locale independently, classifies the existing components+ and their applicable states/viewports, and regression-tests shared+ direction-sensitive changes without redesigning unrelated branding or+ behavior- Adds an accessible language selector with fallback and safe runtime LTR/RTLswitching; runtime React, Vue, and Angular sites use a locale coordinator-- Keeps an unsafe new locale unavailable for later remediation, or records- explicit approval for usable non-blocking limitations+- Keeps only proven affected locales unavailable for later remediation while+ preserving previously verified locales, or records explicit approval for+ usable non-blocking limitations- Revalidates localization resources, bidirectional source rules, and text-expansion risks afterlater UI-modifying skills and again before deployment- Localizes only the SPA UI; it does not enable Dataverse environment languagesdiff --git a/plugins/power-pages/references/approval-gates.md b/plugins/power-pages/references/approval-gates.mdindex 9d0b36e38..62e6b4af8 100644--- a/plugins/power-pages/references/approval-gates.md+++ b/plugins/power-pages/references/approval-gates.md@@ -176,6 +176,7 @@ Required, normalized vocabulary:| Value | Meaning ||---|---|| `nothing` | Clean exit. No Dataverse write, no filesystem write, no state change anywhere. |+| `rendered-plan` | A human-readable HTML plan remains under `docs/`; no implementation files, dependencies, or external state changed. || `localized-site-files` | Localization changes remain in the site files but are not deployed. || `validated-stage-run` | A `deploymentstageruns` row remains on the host in validated-but-not-deployed state. || `partial-manifest` | `.solution-manifest.json` written but not all components added to Dataverse. |@@ -477,7 +478,7 @@ When **removing** a gate, also remove its catalog row in the same PR.| `create-site:1.5.creation-path` | not-a-gate | - | 1.5 | Route preference before catalog fetch; no project directory, Dataverse write, or durable skill state exists | - || `create-site:1.5.template-choice` | not-a-gate | — | 1.5 | Read-only route selection after template preview; only disposable temp preview files exist, with no project directory, Dataverse write, or durable skill state | — || `create-site:1.5.from-scratch-setup` | not-a-gate | — | 1.5 | Deferred framework and directory data-gathering before any scaffold files are written | — |-| `create-site:1.5.content-language` | not-a-gate | — | 1.5 | *"Which language should the site content use?"* — validates the single SPA content locale for the from-scratch path; Dataverse and Power Pages system messages remain English | — |+| `create-site:1.5.content-language` | not-a-gate | — | 1.5 | *"Which language should the site content use?"* — offers the Dataverse organization base language as Suggested when available, then validates the single SPA content locale for the from-scratch path; Dataverse and Power Pages system messages remain English | — || `create-site:1.5.confirm-environment` | gate | consent | 1.5 | Target environment resolved from PAC/Azure auth — confirm before any environment preflight or import mutation | template-cache || `create-site:1.5.unblock-js` | gate | consent | 1.5 | Target environment blocks `.js` in `blockedattachments` — remove only `js` before uploading website code | attachment-block-modified || `create-site:1.5.language-requirement` | not-a-gate | - | 1.5 | Route selection after blocking template-declared Dataverse language preflight; no override option exists and no org mutation has happened | - |@@ -491,7 +492,7 @@ When **removing** a gate, also remove its catalog row in the same PR.| `create-site:1.5.reinstall-unknown` | gate | consent | 1.5 | Installed-state detection failed for one discovered solution — confirm whether to import it anyway, start from scratch, or stop; fires per matching solution iteration | template-cache || `create-site:1.5.import-failed` | gate | progress | 1.5 | Import failed or partial — choose retry, from-scratch fallback, or stop; fires per failed solution iteration | partial-unmanaged-template-import || `create-site:3.requirements` | gate | plan | 3 | *"Which features? / Aesthetic / Mood / Brand"* - four sub-prompts sharing this gate, plus a free-text brand follow-up (website URL, or colors and logo) when the user has a brand to match; shape the rendered Phase 4 plan | nothing |-| `create-site:4.7.plan-approval` | gate | plan | 4.7 | HTML plan rendered — *"Approve and start building / I'd like to make changes"* | nothing |+| `create-site:4.7.plan-approval` | gate | plan | 4.7 | Localized HTML plan rendered with agent verification separated from maker review — *"Approve and start building / I'd like to make changes"* | nothing || `create-site:5.7.critique-blocked` | gate | progress | 5.7 | A critical design gate still fails after three critique rounds - *"Keep fixing / Continue and record it as a known issue / Stop here"* | nothing || `create-site:5.8.localization` | not-a-gate | — | 5.8 | *"Would you like to add more languages now?"* — selects whether to enter the child localization workflow after implementation and design critique; the child workflow preserves the detected document locale as its source/default and its Phase 3 gate approves every localization write | — || `create-site:7.review` | gate | plan | 7 | Live site ready — *"Would you like any changes?"* | nothing |@@ -762,7 +763,7 @@ Most prompts gather validated configuration before the Phase 3 plan gate.| `add-localization:2.prerelease` | not-a-gate | — | 2.4 | Explicitly acknowledge an npm prerelease before it may enter the plan | — || `add-localization:2.license-review` | not-a-gate | — | 2.4 | Use the recommendation, explicitly accept the reported package license, or cancel | — || `add-localization:2.translation` | not-a-gate | — | 2.5 | Agent-generated translations, blank targets, or cancel | — |-| `add-localization:3.plan-approval` | gate | plan | 3 | Approve exact package/mode/locale/file delta before installation or edits | nothing |+| `add-localization:3.plan-approval` | gate | plan | 3 | Review the opened source-language `docs/add-localization-plan*.html`, then approve the exact package/mode/locale/file delta before installation or edits | rendered-plan || `add-localization:7.review` | gate | plan | 7 | Accept verified localization or request revisions | localized-site-files || `add-localization:8.deploy` | gate | plan | 8 | Direct invocation only — deploy now or skip; create-site child invocation suppresses this prompt | localized-site-files |diff --git a/plugins/power-pages/references/bidirectional-design.md b/plugins/power-pages/references/bidirectional-design.mdindex d02b9df51..3d573a65e 100644--- a/plugins/power-pages/references/bidirectional-design.md+++ b/plugins/power-pages/references/bidirectional-design.md@@ -66,14 +66,40 @@ Classify inserted content at its rendering boundary:- Translated UI content inherits the active document direction.- Unknown or user-authored content such as names, comments, titles, and searchqueries uses `<bdi>` or `dir="auto"`.-- Machine-oriented values such as URLs, email addresses, source code, file- paths, GUIDs, and Latin identifiers use an isolated explicit direction,- normally `dir="ltr"`.+- Machine-oriented values such as URLs, email addresses, telephone numbers,+ source code, file paths, GUIDs, and Latin identifiers use an isolated+ explicit direction, normally `dir="ltr"`.- Never reverse strings. Format numbers, dates, currency, percentages, andrelative time with `Intl` APIs for the active locale.-Use `dir="auto"` on free-form multilingual inputs. Use the `dirname` form-attribute when the submitted value's detected direction must be preserved.+Free-form native inputs and textareas need adaptive direction rather than a+permanent `dir="auto"`:++- While the value is empty, set the control's native `dir` attribute to the+ active UI locale direction. Browsers do not consistently derive an empty+ control's base direction from its localized placeholder.+- While the value is non-empty, set `dir="auto"` so the entered value's first+ strong character determines direction.+- On clear, restore the active UI locale direction immediately. Also update an+ empty control when the active locale changes.+- Preserve or add `dirname` when form submission needs the browser-resolved+ value direction. Do not replace or remove existing mixed-direction metadata.++Keep this as one reusable control-direction helper or component behavior when+the application has multiple free-form fields:++```js+function freeFormDirection(value, uiDirection) {+ return value.length === 0 ? uiDirection : 'auto';+}+```++Bind the result to the native `dir` attribute using the framework's normal+reactive mechanism: `dir={freeFormDirection(value, uiDirection)}` in React,+`:dir="freeFormDirection(value, uiDirection)"` in Vue,+`[attr.dir]="freeFormDirection(value, uiDirection)"` in Angular, or an+`input` listener that updates `element.dir` in Astro/plain JavaScript. The+value, not the placeholder, selects automatic direction once populated.References:@@ -81,6 +107,95 @@ References:- https://www.w3.org/International/articles/inline-bidi-markup/- https://www.unicode.org/reports/tr9/+## Component classification and review scope++Classify every visible or interactive component, including page-local controls+that are not implemented as shared source components. The classification is a+review-planning tool, not a persisted source of truth:++| Classification | Meaning | Required evidence |+|---|---|---|+| `direction-neutral` | No inline-direction behavior; ordinary document inheritance is sufficient | Confirm inheritance in every applicable viewport |+| `direction-aware` | Placement, sequence, geometry, icons, interaction, or text depends on direction | Verify every applicable state in LTR and RTL |+| `direction-fixed` | A specific value or domain intentionally remains physical or LTR | Document the semantic reason and verify the surrounding UI in LTR and RTL |+| `unknown-third-party` | Behavior is owned by a package, iframe, web component, or external surface | Exercise the rendered integration, including overlays and open states |++Treat anything involving inline placement, text direction, horizontal+movement, sequence, directional meaning, mixed-script content, or rendering+outside the normal component subtree as a potential bidirectional surface.+This rule is deliberately broader than a fixed component list so custom and+future components receive the same review.++Plan applicable states and viewports separately. A form can have empty,+populated, focused, invalid, disabled, autofilled, and autocomplete-open+states, while a static logo may have only its default state. Do not create a+mechanical Cartesian product of irrelevant states and viewports; include every+combination in which the component's rendered or interactive behavior can+change.++The create-site plan records the expected scope, then reconciles it against the+actual implementation after pages and components exist. Add-localization+builds its scope from the existing implementation before plan approval. Keep+this scope in workflow context and the human-readable plan; do not create a+second project manifest for it.++## Forms and associated UI++Treat a form field as a compound surface rather than checking only its input:++- Localized labels, placeholders, hints, helper text, validation messages,+ prefixes, suffixes, and field icons inherit the active UI locale and use+ logical alignment such as `text-align: start`.+- Give free-form native inputs and textareas adaptive direction: active UI+ direction while empty, `auto` while populated, and active UI direction again+ after clearing. The surrounding localized field UI always follows the active+ document direction.+- Keep email addresses, telephone numbers, URLs, code, file paths, GUIDs, and+ identifiers LTR only when their machine-oriented semantics require it. The+ label, hint, error, placement, and focus behavior remain direction-aware.+- Preserve or add `dirname` where submitted direction metadata is useful.+- Include select menus, autocomplete/listbox panels, validation summaries,+ autofill, native control affordances, and disabled/read-only states when the+ field supports them.+- Preserve label and description associations, reading order, and keyboard+ reachability in both directions.++An intentional fixed direction requires an adjacent, item-scoped directive:++```css+/* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */+direction: ltr;+```++```html+<!-- bidi-fixed: Source-code text preserves authored character order; verify=ltr,rtl -->+<code dir="ltr">npm run build</code>+```++The directive applies to one immediately following fixed-direction declaration+or element. It requires a specific semantic reason and does not exempt the+surrounding component from LTR and RTL verification. Do not use it for+localized labels, placeholders, hints, helper text, errors, or other ordinary+UI prose.++Verify free-form controls in all behaviorally distinct states:++| State | Expected native/computed direction |+|---|---|+| Empty under an RTL UI locale | RTL |+| Empty under an LTR UI locale | LTR |+| Hebrew or Arabic value | RTL |+| English, Hindi, Spanish, or another LTR-script value | LTR |+| Cleared after RTL content | Active UI locale direction |+| Cleared after LTR content | Active UI locale direction |++The populated checks must run under both UI directions so they prove that the+entered value, rather than the surrounding locale, controls the result. Model+clear-after-RTL and clear-after-LTR as distinct rendered states: each state+must enter its non-empty value before clearing, not merely start empty.++Reference: https://www.w3.org/International/questions/qa-html-dir+## Typography and content flexibility- Select fonts for the scripts used by configured locales, including shaping,@@ -104,7 +219,8 @@ References:## Components, icons, and assets-Give every direction-sensitive component an explicit contract:+Give every direction-aware, direction-fixed, and unknown/third-party component+an explicit contract:- Navigation, drawers, tabs, pagination, breadcrumbs, forms, calendars,date-pickers, carousels, timelines, charts, drag/drop, and gestures must be@@ -121,6 +237,16 @@ Give every direction-sensitive component an explicit contract:scrolling must use semantic start/end operations rather than raw assumptionsabout `scrollLeft`.+Components rendered outside their apparent parent require separate review.+React portals, Vue teleports, Angular overlay containers, body-mounted dialogs,+tooltips, menus, autocomplete panels, Shadow DOM, and iframes may not inherit a+component-level `dir`, locale, font, or theme. Configure the package's public+direction API when available. Otherwise use a documented wrapper or supported+theme override and verify the rendered open state. Do not edit `node_modules`.+If a cross-origin or externally owned surface cannot be verified or adapted,+replace it, restrict it for the affected locale, or keep that locale+unavailable when the defect is blocking.+Reference: https://learn.microsoft.com/en-us/globalization/fonts-layout/mirroring## Localization modes and scoped coordination@@ -144,6 +270,15 @@ run the bidirectional-readiness audit before implementation approval. Includesafe remediation, intentional physical exceptions, typography, assets,mixed-content boundaries, and complex component behavior in the plan.+For an existing site, remediation is a targeted bidirectional adaptation, not+permission for an unrelated visual redesign. Preserve branding, routes,+features, and visual character while replacing direction-specific assumptions.+The required scope depends on the implementation: a logical-CSS site may need+only small changes, while absolute layouts, geometry-heavy widgets, or+third-party controls without direction support may require a substantial+component refactor. Show that scope before approval rather than adding the+locale and allowing the site to break.+Use a tiered disposition:- Build/runtime failures, incorrect `lang`/`dir`, unreadable text, unreachable@@ -159,19 +294,30 @@ Unavailable locale resources may remain on disk, but one managedexcludes those locales. Selectors, browser detection and switching,alternate-language metadata, and production static output must all apply it.The manifest is a record of that state, not the mechanism that enforces it.-While hard bidirectional blockers remain, every configured locale opposite to-the default locale's direction stays unavailable.+Every finding identifies its affected locales. Keep only those locales+unavailable; preserve a previously verified locale unless current regression+evidence shows that a shared or direction-wide defect affects it too.Do not describe a technically broken or inaccessible locale as successfullyenabled.## Verification+- Follow `rendered-bidirectional-verification.md` for the deterministic+ Playwright run specification, computed-style checks, failure evidence, and+ readiness disposition.- Audit every generated or modified site, not only the first RTL locale.+- Classify every implemented visible or interactive component and reconcile+ the review scope against the final source and rendered application.- Test every representative route in LTR and RTL at desktop and narrow/mobileviewports.-- For runtime modes, test LTR -> RTL -> LTR and RTL -> LTR -> RTL without- reload, stale requests, route loss, form-state loss, or focus loss.+- Test every applicable state of direction-aware, direction-fixed, and+ unknown/third-party components. For direction-neutral components, confirm+ that ordinary inheritance remains sufficient.+- For runtime modes, test default -> locale -> default and locale -> default+ -> locale for every real non-default locale, without reload, stale requests,+ route loss, form-state loss, or focus loss. Pseudo locales do not participate+ in application-switch transitions.- Verify calendars, gestures, overlays, charts, mixed-direction fixtures,script fonts, localized formatting, console output, and accessibility.- Use expanded pseudo-LTR and pseudo-RTL content during site creation so futurediff --git a/plugins/power-pages/references/i18n-frameworks.md b/plugins/power-pages/references/i18n-frameworks.mdindex f3f097f3f..aa531fa07 100644--- a/plugins/power-pages/references/i18n-frameworks.md+++ b/plugins/power-pages/references/i18n-frameworks.md@@ -4,27 +4,30 @@ Use this reference from `/power-pages:add-localization` after deterministicproject inspection. Localization affects only the code-site SPA. It does notinstall or enable languages in the Dataverse environment.-## Supported choices+## Current availability-| Framework | Recommended mode | Recommended tooling | Alternative |+| Framework | Available mode | Recommended tooling | Temporarily unavailable ||---|---|---|---|-| React | Runtime | `i18next` + `react-i18next` | Validated compatible runtime package |-| Vue | Runtime | Stable `vue-i18n` | Validated compatible runtime package |-| Angular | Static/build-time | Matching `@angular/localize` | `@jsverse/transloco` for runtime switching |-| Astro | Static locale routes | Built-in Astro i18n routing | No version-1 runtime mode |+| React | Runtime | `i18next` + `react-i18next` | — |+| Vue | Runtime | Stable `vue-i18n` | — |+| Angular | Runtime | `@jsverse/transloco` | Static/build-time localization (`@angular/localize`) |+| Astro | None | — | Static locale routes (built-in Astro i18n) |React and Vue use runtime localization because the current Vite templatesproduce one SPA build. Per-locale static output would require a separatelydesigned multi-build, routing, output-directory, and asset-path pipeline.-Angular recommends `@angular/localize` because it is Angular's official,-compiler-integrated localization package. It creates a build per locale.-Transloco remains available when the maker specifically needs in-place-language switching.+Angular currently uses Transloco for in-place runtime switching. Its+`@angular/localize` static implementation remains documented below but is not+selectable until the centralized availability registry re-enables it.-Astro uses static locale routes because its built-in i18n routing and-static-first output naturally produce fully localized HTML and shareable-locale URLs.+Astro's built-in static implementation remains documented below but is not+currently selectable. An Astro invocation stops before configuration or plan+rendering.++`scripts/lib/localization-config.js` is the source of truth. Workflows,+package validation, plan rendering, and final validation must consume that+registry rather than maintaining separate availability lists.## Shared implementation rules@@ -108,9 +111,11 @@ Ordinary components using logical CSS need no subscription.The language selector calls the coordinator; it must not independently mutatethe localization library, `lang`, `dir`, or persistence.-## Static locale behavior+## Dormant static locale behavior-Applies to Angular with `@angular/localize` and Astro.+This guidance is retained for Angular with `@angular/localize` and Astro so the+implementations can be re-enabled without reconstruction. Current workflows+must not execute it while those modes are `temporarily-unavailable`.- Generate a locale-specific build or route for every configured locale.- Include the active locale in the URL/build output.@@ -146,7 +151,7 @@ Install a stable `vue-i18n` release; never silently use an npm prerelease tag.Register the i18n plugin once in the app entry point. Use `$t` or`useI18n()` consistently with the existing Composition/Options API style.-## Angular static+## Angular static (dormant)Use `@angular/localize` matching the installed Angular major/version.@@ -173,7 +178,7 @@ Use `@jsverse/transloco`.- Use Transloco services/directives/pipes consistently.- Implement the shared runtime locale behavior above.-## Astro+## Astro static (dormant)Use Astro's built-in `i18n` configuration.@@ -223,7 +228,12 @@ Write `.powerpages-localization.json` after implementation using this shape:"unavailableLocales": [],"bidirectionalReadiness": {"status": "ready",- "findings": []+ "localeReadiness": {+ "en-US": { "status": "ready" },+ "fr-FR": { "status": "ready" }+ },+ "findings": [],+ "renderedFindings": []},"adoptedExistingConfiguration": false,"lastOperation": "create",@@ -258,20 +268,69 @@ implementation must expose one managed `localeAvailability` module with an`isLocaleAvailable` predicate that rejects the unavailable set. Every selector,switch/detection path, alternate-language metadata generator, and static outputconfiguration must apply that predicate; recording the array in the manifest-does not disable a locale by itself. During `pending-remediation`, all-configured locales opposite to the default locale's direction must remain-unavailable.-`bidirectionalReadiness` is optional for same-direction locale sets and required-when the configured set contains both LTR and RTL:+does not disable a locale by itself. `unavailableLocales` must exactly match+the locales whose individual `localeReadiness` status is+`pending-remediation`. A failure in one locale does not disable another locale+unless a scoped finding explicitly identifies both as affected.+`bidirectionalReadiness` is required for every schema-version-1 localization+manifest. Same-direction locale sets still require pseudo-opposite validation,+so omitting readiness metadata would expose a new locale before that check:- `ready` — no unresolved compatibility findings.- `approved-with-limitations` — the experience remains functional, readable,- accurate, and accessible; the maker explicitly accepted documented limits.+ accurate, and accessible; the maker explicitly accepted every documented+ limit.- `pending-remediation` — hard compatibility work remains; affected localesbelong in `unavailableLocales` and managed availability logic.-Each pending finding must preserve the exact scanner result with `file`, `line`, `rule`, and-`message`.+`localeReadiness` contains exactly one entry for every configured locale. The+top-level status is derived from those entries: any pending locale makes it+`pending-remediation`; otherwise any approved locale makes it+`approved-with-limitations`; otherwise it is `ready`. The default locale cannot+be pending because it cannot be safely hidden.++Each pending finding must preserve the exact scanner result with `file`, `line`,+`rule`, `message`, and `fingerprint`. The fingerprint binds the record to the+source context and occurrence that produced it, so replacing an item at the+same line does not inherit the old deferral.+Keep rendered browser blockers in `renderedFindings` with their `caseId`,+`rule`, `severity`, `message`, and `selector`. Rendered findings are validation+evidence and readiness state; they are not used to suppress later source+scanner findings.++Every static or rendered finding also records a nonempty `affectedLocales`+array and one scope:++- `"locale"` — one language-specific locale.+- `"direction"` — every configured locale of the recorded `"ltr"` or `"rtl"`+ direction.+- `"shared"` — an explicitly tested subset affected by shared implementation.+- `"global"` — every configured locale.++An error or undisposed review finding makes every affected locale pending.+Maker-approved review findings make an otherwise unblocked affected locale+`approved-with-limitations`; the locale remains pending if another error or+undisposed review finding still affects it. A ready locale cannot be named by+an unresolved finding. Existing ready locales keep their status unless+regression evidence shows the changed implementation affects them.++`ready` must not retain static or rendered findings. For+`approved-with-limitations`, retain only review-severity findings and add this+disposition to each one:++```json+"disposition": {+ "status": "maker-approved",+ "impact": "Exact usable degradation and affected component or page",+ "evidence": "docs/bidirectional-evidence/<run-id>/<screenshot-or-report>",+ "approvedAt": "2026-09-03T12:00:00.000Z"+}+```++The evidence path must identify the report or screenshot the maker reviewed.+An error finding can never receive this disposition. If the maker saves work+without accepting a review finding, keep the result `pending-remediation` and+the affected locale unavailable.Only those recorded physical-layout blockers are deferred by lifecycle validation; newlyintroduced findings, invisible bidi controls, and invalid exception directives still block.@@ -374,7 +433,8 @@ Offer repair/reconfiguration when one or more of these conditions apply:- Multiple localization packages or runtime/static modes conflict.- Package is missing, deprecated, incompatible, or the maker wants to changeit.-- Angular maker wants to switch between static and runtime localization.+- An existing Angular static setup must be explicitly reconfigured to the+ currently available runtime mode before this skill can modify it.- Default locale is missing, invalid, duplicated, conflicting, or explicitlybeing changed.- Locale resources/routes or translation keys are missing.diff --git a/plugins/power-pages/references/rendered-bidirectional-verification.md b/plugins/power-pages/references/rendered-bidirectional-verification.mdnew file mode 100644index 000000000..979ba2c0a--- /dev/null+++ b/plugins/power-pages/references/rendered-bidirectional-verification.md@@ -0,0 +1,525 @@+# Rendered Bidirectional Verification++Use the rendered audit after the static bidirectional-readiness audit and a+successful build. Static source checks find deterministic implementation+patterns; this audit verifies computed browser behavior for the actual+component, state, viewport, direction, portal, and locale-switch surfaces.++## Evidence, not project configuration++Build the run specification from the reconciled component scope and actual+implementation. Pass it inline, or write it to a temporary file and delete the+file after the run. Do not commit it as a second component manifest.++The JSON report and failure/review screenshots are run evidence. They may be+kept under `docs/bidirectional-evidence/<run-id>/`, but they do not replace the+source, localization manifest, or approved implementation plan as project+configuration.++## Command++The project must have `playwright` or `playwright-core` available. Create-site+already installs Playwright for the axe audit. For add-localization, reuse an+existing install or add `playwright` as a development dependency when absent.++For newly added pending locales, begin the verification transaction while they+are fail-closed, then expose only those targets through the normal application+availability path. Run the transaction-aware localization validator and start+a loopback-only development server:++```bash+node "${PLUGIN_ROOT}/scripts/manage-localization-verification.js" \+ --begin --profile standard --projectRoot "<PROJECT_ROOT>" --locales "ar-SA"++node "${PLUGIN_ROOT}/skills/add-localization/scripts/validate-localization.js" \+ --projectRoot "<PROJECT_ROOT>" --verification+```++```bash+node "${PLUGIN_ROOT}/scripts/audit-rendered-bidirectional-readiness.js" \+ --url "<DEV_SERVER_URL>" \+ --projectRoot "<PROJECT_ROOT>" \+ --spec "<TEMP_SPEC_PATH>" \+ --evidence-dir "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>" \+ --output "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>/report.json"+```++The command always prints the report JSON to stdout. Exit code `1` means the+report contains blocking rendered errors. Exit code `2` means the run could not+start or the specification is invalid. Parse stdout on exit code `1`; stderr+describes setup/specification failures on exit code `2`.++## Run specification++Use schema version 1:++```json+{+ "version": 1,+ "verificationProfile": "standard",+ "maxConcurrency": 3,+ "runtimeSwitching": true,+ "defaultLocaleId": "en",+ "viewports": [+ { "name": "desktop", "width": 1280, "height": 720 },+ { "name": "narrow", "width": 390, "height": 844 }+ ],+ "locales": [+ {+ "id": "en",+ "locale": "en-US",+ "direction": "ltr",+ "textExpansion": 1,+ "activate": [+ { "type": "click", "selector": "[data-locale='en-US']" }+ ],+ "expect": [+ { "selector": "h1", "text": "Contact us" }+ ]+ },+ {+ "id": "ar",+ "locale": "ar-SA",+ "direction": "rtl",+ "textExpansion": 1.2,+ "activate": [+ {+ "type": "activate-locale",+ "method": "click",+ "locale": "ar-SA",+ "selector": "[data-locale='ar-SA']"+ }+ ],+ "expect": [+ { "selector": "h1", "text": "اتصل بنا" }+ ]+ }+ ],+ "components": [+ {+ "id": "contact-email",+ "name": "Contact email field",+ "classification": "direction-fixed",+ "risk": "high",+ "reason": "Email addresses preserve LTR character order",+ "route": "/contact",+ "selector": "[data-bidi-id='contact-email']",+ "viewports": ["desktop", "narrow"],+ "states": [+ {+ "name": "invalid",+ "isolation": "resettable",+ "setup": [+ {+ "type": "fill",+ "selector": "[data-bidi-id='contact-email'] input",+ "value": "invalid"+ },+ {+ "type": "press",+ "selector": "[data-bidi-id='contact-email'] input",+ "key": "Tab"+ }+ ],+ "reset": [+ {+ "type": "fill",+ "selector": "[data-bidi-id='contact-email'] input",+ "value": ""+ }+ ],+ "targets": [+ {+ "selector": "[data-bidi-id='contact-email']",+ "expectedDirection": "inherit"+ },+ {+ "selector": "[data-bidi-id='contact-email'] input",+ "expectedDirection": "ltr"+ },+ {+ "selector": "[data-bidi-id='contact-email-error']",+ "expectedDirection": "inherit"+ }+ ],+ "focusOrder": [+ "[data-bidi-id='contact-email'] input",+ "[data-bidi-id='contact-submit']"+ ]+ }+ ]+ }+ ],+ "transitions": [+ {+ "name": "ltr-rtl-ltr",+ "route": "/contact",+ "sequence": ["en", "ar", "en"],+ "setup": [+ {+ "type": "fill",+ "selector": "[data-bidi-id='contact-name']",+ "value": "Ada"+ },+ {+ "type": "focus",+ "selector": "[data-bidi-id='contact-name']"+ }+ ],+ "preserve": [+ "[data-bidi-id='contact-name']",+ {+ "selector": "[data-bidi-id='details-panel']",+ "kind": "attribute",+ "name": "aria-expanded"+ }+ ],+ "preserveFocus": "[data-bidi-id='contact-name']",+ "preserveRoute": true,+ "viewport": "desktop"+ },+ {+ "name": "rtl-ltr-rtl",+ "route": "/contact",+ "sequence": ["ar", "en", "ar"],+ "preserve": [],+ "preserveRoute": true,+ "viewport": "desktop"+ }+ ]+}+```++## Verification profiles++`standard` is the default localization workflow profile. It separates checks+whose behavior varies by locale from checks whose behavior varies primarily by+writing direction:++- Every real locale receives application-driven activation, localized-content,+ exact `lang`/`dir`, resource/console, and formatting smoke coverage.+- The component matrix uses one representative LTR locale and one+ representative RTL locale. Prefer a newly added real locale, then greater+ measured text expansion, then the default/existing locale. Use a pseudo+ direction only when no real locale exists.+- `direction-neutral` components default to low risk and use their primary+ state and viewport. `direction-aware` components default to medium risk and+ use all declared states/viewports. `direction-fixed` and+ `unknown-third-party` components default to high risk and use all declared+ states/viewports.+- High-risk components in non-representative locales become explicit maker+ review items rather than an automatic full Cartesian matrix.++Set `risk` to `low`, `medium`, or `high` only when implementation evidence+justifies overriding the classification default. Unknown components remain+high risk. `textExpansion` is the target/source visible-text ratio used to+choose between same-direction target locales.++`extensive` runs every declared component, state, viewport, and locale. Offer+it after standard verification passes and before transaction finalization.+`targeted` accepts `targetCaseIds` and is for repair reruns after the complete+standard or extensive baseline exists; it is not sufficient to approve a new+locale by itself.++## Grouping and concurrency++Component cases are grouped by route, viewport, and locale. Independent locale+smoke cases and component groups run through a bounded worker pool. The+default `maxConcurrency` is `3`; specifications may set an integer from `1`+through `8`. Use `1` when the local development server or application cannot+serve independent browser contexts concurrently. Runtime locale-transition+sequences remain serial because they verify persistence, request ordering, and+state preservation.++State isolation controls navigation reuse:++- Omitted or `reload`: reuse the browser page object, but navigate and activate+ the locale again before the state. This preserves the previous clean-state+ behavior.+- `resettable`: after checking the state, execute its required non-empty+ `reset` actions. The runner verifies that reset preserved the route origin,+ active locale, localized-content evidence, and unavailable-locale+ boundaries. A successful reset allows the next resettable state in the same+ route/viewport/locale group to skip navigation and locale activation.+- `isolated`: use a group containing only that case. Choose this for+ authentication changes, destructive submission, reload-sensitive startup,+ or global state that cannot be reliably reset.++Reset actions cannot navigate or activate/change a locale. Do not mark a state+`resettable` merely for performance: its reset must restore the same baseline+that a fresh route navigation would provide.++When `runtimeSwitching` is `true`, `defaultLocaleId` identifies the real+default locale. Standard verification requires default -> locale -> default+for every real non-default locale and the reverse locale -> default -> locale+sequence for representative locales. Extensive verification requires both+sequences for every real non-default locale. This verifies each locale+independently without requiring every possible locale pair.+Pseudo locales do not participate in runtime transition pairs. Static+localization modes set `runtimeSwitching` to `false` and use locale-specific+navigation actions. Runtime switching requires+`.powerpages-localization.json`; the CLI requires the real run-spec locales and+default locale to exactly match the manifest so an existing configured locale+cannot be silently omitted. The expected direction for every real locale is+derived from its writing script rather than trusted from the run specification.+Every locale in a runtime transition, including the default, needs a reusable+application activation action because each round trip must be able to restore+it. `use-current` is therefore rejected for real runtime locales.++Each `preserve` entry may be a selector for an input, select, or textarea; the+runner automatically compares its value or checked state. For non-form+application state, use an object with `selector`, `kind`, and when needed+`name`. Supported kinds are `value`, `checked`, `text`, `attribute`, and+`property`. For example, preserve an expanded panel with+`{"selector":"#details","kind":"attribute","name":"aria-expanded"}`. A bare+selector that resolves to a non-form element is a blocking specification+error rather than an empty comparison that can pass without evidence.+Explicit value, checked, attribute, and property evidence must also exist on+the selected element; a misspelled or inapplicable field is blocking.++## Evidence reuse++Reports include a fingerprint of source, localization resources, package+metadata, build configuration, and locale availability. Readiness status,+timestamps, and finding disposition metadata do not invalidate otherwise+identical rendered evidence.++Create-site may reuse a successful add-localization report:++```bash+node "${PLUGIN_ROOT}/scripts/audit-rendered-bidirectional-readiness.js" \+ --projectRoot "<PROJECT_ROOT>" \+ --reuse-report "<REPORT_JSON>"+```++The command rejects failed evidence, incomplete reports, summaries that do not+match their detailed results and findings, reports from a `targeted` repair+run, and evidence whose project-input fingerprint is stale. It does not compare+run specifications: add-localization's `standard` or `extensive` run already+covers every visible or interactive component under these same rules, so with+unchanged project inputs it is the run create-site would otherwise repeat. Only+a targeted run is partial. When reuse is rejected, build the current temporary+specification, run a fresh audit, and delete the specification afterward.++## Locale activation and pseudo directions++`activate` is a sequence of supported browser actions. Prefer the site's real+selector or route behavior. A real locale must not use `set-document` or+`set-attribute`: it must activate through the application and provide at least+one `expect` assertion for localized text or a localized attribute. This+prevents direct DOM mutation from being mistaken for working localization.++Every transaction target is temporarily available through the normal+application path and must use its real selector or locale-navigation action:++```json+{+ "activate": [+ {+ "type": "activate-locale",+ "method": "click",+ "locale": "ar-SA",+ "selector": "[data-locale='ar-SA']"+ }+ ]+}+```++`activate-locale` binds the expected locale to one normal application control.+Use `method: "click"` for a button or menu item. For a `<select>`, use+`method: "select"` and provide its locale option as `value`. Transaction-target+activation may contain only this action and optional waits, preventing an+unrelated click or direct DOM mutation from being accepted as locale evidence.+The runner verifies that the action itself produces the expected+`document.documentElement.lang`.++Real locale entries must exactly match the currently available manifest+locales. A pre-existing pending locale that is not a target remains excluded+from activation. List every such locale and its normal selector surfaces in+the top-level `unavailableLocaleChecks` array:++```json+{+ "unavailableLocaleChecks": [+ {+ "locale": "fa-IR",+ "selectors": ["[data-locale='fa-IR']"]+ }+ ]+}+```++Before every component and transition case, the runner checks every matching+element for visibility. This supplies negative browser evidence that+pre-existing unavailable locales remain hidden while another locale is being+verified. For a `<select>` language control, target the locale's `<option>`+such as `option[value='fa-IR']`; the runner treats an enabled option in a+visible enabled parent `<select>` as exposed even though browsers do not render+the option as an independently visible box.++The project-root `.powerpages-localization-verification.json` transaction is+the safety boundary. It records target locales and their prior fail-closed+availability, permits only those pending targets to be temporarily omitted+from `unavailableLocales`, and blocks completion or deployment. While the+browser run is active, `.powerpages-localization-verification.json.audit`+holds an exclusive lease for that transaction. Finalization remains blocked+until the run records its result and releases the lease. If the process is+interrupted, `--fail` restores target readiness, manifest unavailability, and+the exact pre-exposure managed availability-module snapshot before recording+`remediation-required`, then clears the abandoned lease. The snapshot is written+only to the managed availability module that the manifest names, outside hidden+directories, and only while its backup still matches the recorded checksum.+Otherwise `--fail` writes no source file and reports the locales to exclude+manually; finalization stays blocked until the module excludes them. Do not+delete the transaction, lease, or availability snapshot to bypass recovery.+Transaction commands also reclaim a lock whose recorded owner process has+exited, while preserving locks held by live verification processes.++The audit URL must use `localhost`, `127.0.0.1`, or `[::1]`, and every+navigation, control action, wait, and redirect must remain on that exact+origin. A browser, setup, or rendered error changes the transaction to+`remediation-required` only after its targets are restored to pending+unavailable state.++After the maker decision, reconcile the manifest and managed availability+module, then run `manage-localization-verification.js --finalize`. Successful+targets are `ready` or `approved-with-limitations` and remain available.+Failed or deferred targets are `pending-remediation` and unavailable. Each+target of a successful run is decided independently, so one run can enable some+targets and defer others; a deferred target keeps its undisposed review+findings as its remediation record.+For a successful run, finalization also recomputes the project-input fingerprint+and rejects evidence made stale by source, resource, dependency, or build+configuration changes. When a target is deferred, returning it to+`unavailableLocales` and the managed availability module is the expected change,+so finalization compares a fingerprint recorded without those two availability+inputs; every other change still makes the evidence stale. Finalization validates the normal schema-version-1 invariant before removing+the transaction. Before retrying after either a failed run or maker-requested+revision, mark the old transaction failed, restore its targets to pending+unavailable state, finalize it, and begin a new transaction.++For a single-language site, add a pseudo-opposite locale using:++```json+{+ "id": "pseudo-rtl",+ "locale": "ar-XB",+ "direction": "rtl",+ "pseudo": true,+ "activate": [+ {+ "type": "set-document",+ "locale": "ar-XB",+ "direction": "rtl"+ }+ ]+}+```++Pseudo mode changes the root language/direction and expands visible text and+text-bearing attributes in the browser only. It does not modify project files.+Use pseudo-RTL for an LTR site and pseudo-LTR for an RTL site.++Supported actions are:++- `activate-locale` for the normal click/select control that activates a+ transaction target and proves the resulting document locale+- `click`, `fill`, `focus`, `hover`, `press`, `select`, `check`, `uncheck`+- `use-current` only when no runtime round trip needs to reactivate the locale+- `navigate` with a root-relative or absolute locale-specific URL+- `wait` with `ms` from 0 through 10000+- `set-document` with `locale` and `direction`+- `set-attribute` with `selector`, `name`, and string `value` for component+ setup/reset or pseudo-locale simulation, not real-locale activation++The action list deliberately excludes arbitrary JavaScript. Verification input+must not become a general code-execution channel.++## Component cases++Give stable `data-bidi-id` attributes to important rendered surfaces when+semantic selectors are not stable enough. These attributes are verification+anchors, not styling hooks.++Every component entry must preserve the approved classification and list only+its applicable states and viewports. The runner expands every+component/state/viewport across every verification locale, so each rendered+combination produces an independent result.++Each state may define:++- `setup` — actions required to reach the state.+- `targets` — the component root, compound form parts, portals, open menus,+ dialogs, tooltips, validation messages, or other separately rendered nodes.+- `computed` — exact computed-style expectations by direction.+- `attributes` — exact DOM attribute expectations such as preserved `dirname`+ metadata (`selector`, `name`, and string `expected`).+- `focusOrder` — expected keyboard Tab sequence.+- `nonOverlapping` — selector pairs that must not geometrically overlap.++For each native free-form input or textarea, include empty, RTL-valued,+LTR-valued, clear-after-RTL, and clear-after-LTR states. Each clear state must+first `fill` its non-empty value and then `fill` `""`; otherwise it only+retests initial emptiness. Use `computed` checks for the control's `direction`+property. Empty and cleared states expect the active UI direction. Hebrew or+Arabic values expect RTL under both UI directions; English, Hindi, Spanish,+and other LTR-script values expect LTR under both UI directions. Also preserve+and inspect any native `dirname` attribute needed for submitted direction+metadata. A machine-oriented control instead remains explicitly LTR, with the+required adjacent `bidi-fixed` directive in source, while its label, hint,+error, and field container remain locale-directed.++A target normally uses `"expectedDirection": "inherit"`. A specific+direction-fixed value uses `"ltr"` or `"rtl"`. Set `expectVisible: false` for+an intentionally restricted surface. Use `allowClipping` or+`allowOutsideViewport` only for a reviewed behavior where that geometry is the+component's intended function.++Open Shadow DOM is addressable through Playwright locators. Body-mounted+portals and overlay containers must be listed as separate targets even when+they are outside the component root.++For a visible cross-origin iframe or other opaque external surface, set+`externalOpaque: true`. The runner reports a blocking+`unverifiable-third-party-surface`. Hiding or restricting the nonessential+surface for the affected locale can be verified with `expectVisible: false`.+Do not mark a visible opaque critical surface ready without evidence.++## Automated findings++Blocking findings include:++- missing or unexpectedly visible/hidden targets;+- root or component computed-direction mismatches;+- page horizontal overflow;+- clipped text/content or targets outside the viewport;+- explicitly forbidden overlap;+- computed-style expectation failures;+- keyboard focus-order failures;+- browser console/page errors;+- visible opaque third-party surfaces;+- runtime switches that reload, change route, lose declared form/application+ state, lose focus, or leave stale `lang`/`dir`.++Use `manualChecks` for semantic behavior that requires a screenshot and maker+or agent judgment, such as whether a directional icon mirrors correctly,+whether a map/chart intentionally stays physical, or whether brand imagery+must be replaced. Manual checks produce review findings, not automatic passes.++The runner captures screenshots for failed and review cases when+`--evidence-dir` is supplied. A screenshot is supporting evidence; it does not+override a deterministic failure.++## Disposition++- Any rendered `error` keeps every locale in the finding's `affectedLocales`+ unavailable and sets those locale readiness entries to+ `pending-remediation`. Other locales remain available unless regression+ evidence shows they are also affected.+- A `review` finding must receive explicit evidence and disposition. A usable,+ noncritical limitation may become `approved-with-limitations`.+- A direction-aware, direction-fixed, or unknown/third-party case without+ evidence is incomplete, not implicitly passed.+- Record rendered blockers in+ `bidirectionalReadiness.renderedFindings`; keep static scanner findings in+ `bidirectionalReadiness.findings`.diff --git a/plugins/power-pages/references/site-modification-integrity.md b/plugins/power-pages/references/site-modification-integrity.mdindex 1735b0284..904a6b667 100644--- a/plugins/power-pages/references/site-modification-integrity.md+++ b/plugins/power-pages/references/site-modification-integrity.md@@ -38,6 +38,10 @@ extract them later, but do not introduce an i18n dependency or manifest.- Keep DOM, reading, focus, and visual order aligned. Do not use CSS reversal to simulate RTL.- Isolate user-generated or externally sourced mixed-direction values using semantic `dir`handling, normally `dir="auto"` at the smallest useful boundary.+- For native free-form inputs and textareas, use adaptive `dir`: active UI direction while empty,+ `auto` while populated, and active UI direction again after clearing. Preserve `dirname`+ submission metadata. Keep machine-oriented controls explicitly LTR with their adjacent+ `bidi-fixed` directive while their surrounding field UI follows the locale.- Use the active locale for `Intl` formatting and the locale coordinator for runtime language,direction, font-profile, and geometry-change updates.- Classify new directional images or icons as unchanged, mirrored, or replaced. Do not mirror@@ -63,9 +67,17 @@ node "${PLUGIN_ROOT}/scripts/validate-site-integrity.js" --projectRoot "<PROJECTThis is an explicit post-implementation gate. Validation performed before all planned file changesare complete does not satisfy this step. Do not present completion, create the final commit, or askto deploy until this command exits successfully. If further source changes are made during review,-rerun it.+rerun it. Run it exactly as shown: `--allow-verified-localization-review` is reserved for+add-localization's pre-review gate, and without it any remaining localization verification+transaction blocks completion and deployment.Deterministic localization or bidirectional errors block completion. Review findings such asfixed text geometry, visual reordering, transforms, gradients, and clipping must be inspected inboth directions and with expanded content; they do not fail the command by themselves. Deploymentruns the same validator as a final backstop for changes made outside a skill.++Rendered verification reports are reusable only when they came from a complete `standard` or+`extensive` run and their recorded input fingerprint matches the project; `targeted` repair+evidence is never reused. Source, resources, locale availability, dependencies, and build configuration+invalidate the evidence; readiness-only metadata does not. After a focused repair, rerun the+affected case IDs and a small locale smoke set rather than rebuilding an unchanged full matrix.diff --git a/plugins/power-pages/scripts/audit-rendered-bidirectional-readiness.js b/plugins/power-pages/scripts/audit-rendered-bidirectional-readiness.jsnew file mode 100644index 000000000..30ee601b5--- /dev/null+++ b/plugins/power-pages/scripts/audit-rendered-bidirectional-readiness.js@@ -0,0 +1,336 @@+#!/usr/bin/env node+'use strict';++const fs = require('fs');+const path = require('path');+const { detectBrowserLaunchOptions } = require('./lib/detect-browser');+const {+ MANIFEST_NAME,+ validateLocalizationManifestShape,+} = require('./lib/localization-config');+const {+ getRequiredLoopbackOrigin,+ runRenderedBidirectionalAudit,+} = require('./lib/rendered-bidirectional-readiness');+const {+ resolveVerificationProfile,+} = require('./lib/localization-verification-profile');+const {+ computeVerificationInputFingerprint,+ createVerificationEvidence,+ validateReusableVerificationReport,+} = require('./lib/verification-evidence');+const {+ AUDIT_LEASE_CONFLICT_CODE,+ beginLocalizationVerificationAudit,+ endLocalizationVerificationAudit,+ formatManualAvailabilityRestore,+ markLocalizationVerificationFailed,+ markLocalizationVerificationPassed,+ readLocalizationVerificationTransaction,+ validateTransactionAgainstManifest,+} = require('./lib/localization-verification-transaction');++const recoveryContext = {+ projectRoot: null,+ transactionRead: false,+ runId: null,+};++const ARGUMENTS = new Map([+ ['--url', 'url'],+ ['--projectRoot', 'projectRoot'],+ ['--spec', 'specPath'],+ ['--spec-inline', 'specInline'],+ ['--evidence-dir', 'evidenceDir'],+ ['--output', 'output'],+ ['--reuse-report', 'reuseReport'],+]);+const PATH_ARGUMENTS = new Set([+ 'projectRoot',+ 'specPath',+ 'evidenceDir',+ 'output',+ 'reuseReport',+]);+const USAGE =+ 'Usage: audit-rendered-bidirectional-readiness.js --projectRoot <path> ' ++ '((--url <base-url> (--spec <json-file> | --spec-inline <json>)) | ' ++ '--reuse-report <report-json>) ' ++ '[--evidence-dir <path>] [--output <report-json>]';++function parseArgs(argv) {+ const parsed = {};+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ const property = ARGUMENTS.get(arg);+ if (!property) {+ throw new Error(`Unknown or misplaced argument "${arg}".\n${USAGE}`);+ }+ if (Object.hasOwn(parsed, property)) {+ throw new Error(`Argument "${arg}" may be specified only once.\n${USAGE}`);+ }+ const value = argv[index + 1];+ if (typeof value !== 'string' || !value.trim() || value.startsWith('--')) {+ throw new Error(`Argument "${arg}" requires a value.\n${USAGE}`);+ }+ parsed[property] = PATH_ARGUMENTS.has(property)+ ? path.resolve(value)+ : value;+ index += 1;+ }+ const specCount = Number(Boolean(parsed.specPath)) ++ Number(Boolean(parsed.specInline));+ if (!parsed.projectRoot ||+ (!parsed.reuseReport && !parsed.url) ||+ (parsed.reuseReport ? specCount !== 0 : specCount !== 1) ||+ (parsed.reuseReport && parsed.url)) {+ throw new Error(USAGE);+ }+ return parsed;+}++function findProjectRootArg(argv) {+ const candidates = new Set();+ for (let index = 0; index < argv.length; index += 1) {+ if (argv[index] !== '--projectRoot') continue;+ const value = argv[index + 1];+ if (typeof value === 'string' && value.trim() &&+ !value.startsWith('--')) {+ candidates.add(path.resolve(value));+ }+ }+ return candidates.size === 1 ? [...candidates][0] : null;+}++function loadPlaywright(projectRoot) {+ const modulePaths = [+ 'playwright',+ path.join(projectRoot, 'node_modules', 'playwright'),+ 'playwright-core',+ path.join(projectRoot, 'node_modules', 'playwright-core'),+ ];+ for (const modulePath of modulePaths) {+ try {+ return require(modulePath);+ } catch (error) {+ if (error.code !== 'MODULE_NOT_FOUND') throw error;+ }+ }+ throw new Error('playwright not found. Run: npm install --save-dev playwright');+}++function isAuditLeaseConflict(error) {+ return error?.code === AUDIT_LEASE_CONFLICT_CODE;+}++let manualRestoreReported = false;++// Move the transaction to remediation-required. When the availability module+// could not be restored automatically, report the one manual step required+// before --finalize. The error paths can fail the same run twice, so the+// instruction is written at most once per process.+function failVerificationTransaction(projectRoot, runId) {+ const failed = markLocalizationVerificationFailed(projectRoot, runId);+ const message = formatManualAvailabilityRestore(failed);+ if (message && !manualRestoreReported) {+ manualRestoreReported = true;+ process.stderr.write(`${message}\n`);+ }+ return failed;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));+ recoveryContext.projectRoot = args.projectRoot;+ if (args.reuseReport) {+ const report = JSON.parse(fs.readFileSync(args.reuseReport, 'utf8'));+ const reuseErrors = validateReusableVerificationReport(+ args.projectRoot,+ report+ );+ if (reuseErrors.length > 0) {+ throw new Error(`Rendered verification evidence cannot be reused:\n- ${+ reuseErrors.join('\n- ')+ }`);+ }+ report.verification = {+ ...report.verification,+ reused: true,+ reusedAt: new Date().toISOString(),+ };+ const json = `${JSON.stringify(report, null, 2)}\n`;+ if (args.output) {+ fs.mkdirSync(path.dirname(args.output), { recursive: true });+ fs.writeFileSync(args.output, json);+ }+ process.stdout.write(json);+ return;+ }+ const spec = JSON.parse(+ args.specInline ?? fs.readFileSync(args.specPath, 'utf8')+ );+ getRequiredLoopbackOrigin(args.url);+ const manifestPath = path.join(args.projectRoot, MANIFEST_NAME);+ const transactionResult =+ readLocalizationVerificationTransaction(args.projectRoot);+ if (transactionResult.errors.length > 0) {+ throw new Error(transactionResult.errors.join('\n'));+ }+ const transaction = transactionResult.transaction;+ recoveryContext.transactionRead = true;+ recoveryContext.runId = transaction?.runId || null;+ let manifest = null;+ let localizationContext = null;+ if (fs.existsSync(manifestPath)) {+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ const manifestErrors = validateLocalizationManifestShape(manifest, {+ verificationLocales: transaction?.targetLocales || [],+ });+ if (manifestErrors.length > 0) {+ throw new Error(+ `${MANIFEST_NAME} is invalid:\n- ${manifestErrors.join('\n- ')}`+ );+ }+ if (transaction) {+ if (resolveVerificationProfile(spec) !==+ (transaction.verificationProfile || 'extensive')) {+ throw new Error(+ 'Rendered run specification profile must match the active localization transaction.'+ );+ }+ const transactionErrors = validateTransactionAgainstManifest(+ transaction,+ manifest,+ { requireExposed: true }+ );+ if (transactionErrors.length > 0) {+ throw new Error(transactionErrors.join('\n'));+ }+ }+ localizationContext = {+ locales: manifest.locales,+ defaultLocale: manifest.defaultLocale,+ mode: manifest.mode,+ unavailableLocales: Array.isArray(manifest.unavailableLocales)+ ? manifest.unavailableLocales+ : [],+ verificationLocales: transaction?.targetLocales || [],+ };+ } else if (spec.runtimeSwitching === true) {+ throw new Error(+ `${MANIFEST_NAME} is required when runtimeSwitching is enabled.`+ );+ }+ let auditLeaseStarted = false;+ const inputFingerprint = computeVerificationInputFingerprint(args.projectRoot);+ try {+ if (transaction) {+ beginLocalizationVerificationAudit(+ args.projectRoot,+ transaction.runId+ );+ auditLeaseStarted = true;+ }+ const { chromium } = loadPlaywright(args.projectRoot);+ const result = await runRenderedBidirectionalAudit({+ url: args.url,+ spec,+ chromium,+ localizationContext,+ browserLaunchOptions: detectBrowserLaunchOptions(),+ evidenceDir: args.evidenceDir,+ });+ const completedFingerprint =+ computeVerificationInputFingerprint(args.projectRoot);+ if (completedFingerprint !== inputFingerprint) {+ throw new Error(+ 'Project verification inputs changed while the rendered audit was running.'+ );+ }+ result.verification.evidence = createVerificationEvidence(+ args.projectRoot,+ spec+ );+ if (transaction && result.summary.errors > 0) {+ failVerificationTransaction(args.projectRoot, transaction.runId);+ }+ const json = `${JSON.stringify(result, null, 2)}\n`;+ if (args.output) {+ fs.mkdirSync(path.dirname(args.output), { recursive: true });+ fs.writeFileSync(args.output, json);+ }+ process.stdout.write(json);+ if (transaction && result.summary.errors === 0) {+ markLocalizationVerificationPassed(+ args.projectRoot,+ transaction.runId,+ result.verification+ );+ }+ process.exitCode = result.summary.errors > 0 ? 1 : 0;+ } catch (error) {+ if (transaction && !isAuditLeaseConflict(error)) {+ try {+ failVerificationTransaction(args.projectRoot, transaction.runId);+ } catch (transactionError) {+ transactionError.message += `\nThe audit also failed: ${error.message}`;+ throw transactionError;+ }+ }+ throw error;+ } finally {+ if (auditLeaseStarted) {+ endLocalizationVerificationAudit(args.projectRoot, transaction.runId);+ }+ }+}++function isLoopbackUrl(value) {+ try {+ getRequiredLoopbackOrigin(value);+ return true;+ } catch {+ return false;+ }+}++if (require.main === module) {+ main().catch((error) => {+ // A lease loser never owned the audit, so it must not change the shared+ // transaction or availability while the lease owner is still running.+ if (!isAuditLeaseConflict(error)) {+ try {+ const projectRoot = recoveryContext.projectRoot ||+ findProjectRootArg(process.argv.slice(2));+ if (!projectRoot) throw new Error('projectRoot is unavailable.');+ if (recoveryContext.transactionRead) {+ if (recoveryContext.runId) {+ failVerificationTransaction(+ projectRoot,+ recoveryContext.runId+ );+ }+ } else {+ const { transaction, errors } =+ readLocalizationVerificationTransaction(projectRoot);+ if (errors.length === 0 && transaction?.state === 'in-progress') {+ failVerificationTransaction(projectRoot, transaction.runId);+ }+ }+ } catch {+ // Preserve the original audit/setup error; the transaction remains as a+ // deployment blocker if it could not be moved to remediation-required.+ }+ }+ process.stderr.write(`${error.message}\n`);+ process.exitCode = 2;+ });+}++module.exports = {+ findProjectRootArg,+ isLoopbackUrl,+ loadPlaywright,+ parseArgs,+};diff --git a/plugins/power-pages/scripts/axe-audit.js b/plugins/power-pages/scripts/axe-audit.jsindex d092f56f1..10d588ae7 100644--- a/plugins/power-pages/scripts/axe-audit.js+++ b/plugins/power-pages/scripts/axe-audit.js@@ -18,7 +18,7 @@// Exit code: 1 when a critical or serious violation is found, a route could not be audited, or// the audit cannot run at all; 0 only when every route was audited and passed.-const { detectBrowser } = require('./lib/detect-browser');+const { detectBrowserLaunchOptions } = require('./lib/detect-browser');const { loadPlaywright } = require('./lib/load-playwright');const { downloadPinned } = require('./lib/pinned-download');const fs = require('node:fs');@@ -105,8 +105,11 @@ async function loadAxeSource({ download = downloadPinned } = {}) {return (await download(AXE_SCRIPT)).toString('utf8');}-async function auditRoutes({ playwright, channel, url, routes, axeSource }) {- const browser = await playwright.chromium.launch({ channel, headless: true });+async function auditRoutes({ playwright, channel, launchOptions, url, routes, axeSource }) {+ const browser = await playwright.chromium.launch({+ ...(launchOptions || (channel ? { channel } : {})),+ headless: true,+ });const results = [];try {// axe is injected as an inline <script> holding the verified source. A deployed site's@@ -142,7 +145,8 @@ async function main(argv = process.argv.slice(2), {writeError = (s) => process.stderr.write(s),loadPlaywrightFn = loadPlaywright,loadAxeSourceFn = loadAxeSource,- channel = detectBrowser,+ launchOptions = detectBrowserLaunchOptions,+ channel,readStdin,} = {}) {const args = parseArgs(argv, { readStdin });@@ -163,7 +167,16 @@ async function main(argv = process.argv.slice(2), {return 1;}try {- const results = await auditRoutes({ playwright, channel: channel(), url: args.url, routes: args.routes, axeSource });+ const browserOptions = channel+ ? { channel: channel() }+ : launchOptions();+ const results = await auditRoutes({+ playwright,+ launchOptions: browserOptions,+ url: args.url,+ routes: args.routes,+ axeSource,+ });write(`${JSON.stringify(results, null, 2)}\n`);return hasBlockingResult(results) ? 1 : 0;} catch (error) {diff --git a/plugins/power-pages/scripts/lib/bidirectional-finding-disposition.js b/plugins/power-pages/scripts/lib/bidirectional-finding-disposition.jsnew file mode 100644index 000000000..e6b568635--- /dev/null+++ b/plugins/power-pages/scripts/lib/bidirectional-finding-disposition.js@@ -0,0 +1,72 @@+'use strict';++const DEFERRABLE_RULES = new Set([+ 'directional-physical-css',+ 'directional-physical-utility',+ 'directional-physical-shorthand',+ 'fixed-direction',+]);++function partitionDeferredFindings(findings, recordedFindings, unavailableLocales) {+ const unavailable = new Set(unavailableLocales || []);+ const records = (recordedFindings || []).filter(+ (finding) =>+ finding &&+ typeof finding.file === 'string' &&+ Number.isInteger(finding.line) &&+ typeof finding.rule === 'string' &&+ typeof finding.message === 'string' &&+ typeof finding.fingerprint === 'string'+ );+ const unmatchedRecorded = [...records];+ for (const finding of findings) {+ const recordIndex = unmatchedRecorded.findIndex(+ (recorded) => sameSourceFinding(recorded, finding)+ );+ if (recordIndex !== -1) unmatchedRecorded.splice(recordIndex, 1);+ }++ const remainingDeferrals = records.filter(+ (finding) =>+ finding.severity === 'error' &&+ DEFERRABLE_RULES.has(finding.rule) &&+ Array.isArray(finding.affectedLocales) &&+ finding.affectedLocales.length > 0 &&+ finding.affectedLocales.every((locale) => unavailable.has(locale))+ );+ const blocking = [];+ const deferred = [];+ for (const finding of findings.filter((item) => item.severity === 'error')) {+ // Consume a record once so a second declaration with the same identity is+ // still a new defect. Source context fingerprints prevent line reuse.+ const recordIndex = DEFERRABLE_RULES.has(finding.rule)+ ? remainingDeferrals.findIndex(+ (recorded) => sameSourceFinding(recorded, finding)+ )+ : -1;+ if (recordIndex === -1) {+ blocking.push(finding);+ continue;+ }+ remainingDeferrals.splice(recordIndex, 1);+ deferred.push(finding);+ }+ return {+ blocking,+ deferred,+ unmatchedRecorded,+ };+}++function sameSourceFinding(left, right) {+ return left.severity === right.severity &&+ left.rule === right.rule &&+ left.file === right.file &&+ left.line === right.line &&+ left.message === right.message &&+ left.fingerprint === right.fingerprint;+}++module.exports = {+ partitionDeferredFindings,+};diff --git a/plugins/power-pages/scripts/lib/bidirectional-readiness.js b/plugins/power-pages/scripts/lib/bidirectional-readiness.jsindex dd9719084..f7051be36 100644--- a/plugins/power-pages/scripts/lib/bidirectional-readiness.js+++ b/plugins/power-pages/scripts/lib/bidirectional-readiness.js@@ -2,6 +2,7 @@const fs = require('fs');const path = require('path');+const crypto = require('crypto');const SOURCE_EXTENSIONS = new Set(['.css', '.scss', '.less', '.js', '.jsx', '.ts', '.tsx', '.vue', '.astro', '.html',@@ -9,10 +10,10 @@ const SOURCE_EXTENSIONS = new Set([const SKIPPED_DIRECTORIES = new Set(['.git', 'dist', 'build', 'node_modules', '.output', 'coverage',]);-const PHYSICAL_DIRECTIVE_RE =- /^\/\*\s*bidi-physical:\s*(\S(?:.*\S)?)\s*;\s*verify=ltr,rtl\s*\*\/$/i;-const MALFORMED_PHYSICAL_DIRECTIVE_RE =- /^(?:(?:\/\*|\/\/|<!--)\s*)?bidi-physical:/i;+const EXCEPTION_DIRECTIVE_RE =+ /^(\/\*|<!--)\s*bidi-(physical|fixed):\s*(\S(?:.*\S)?)\s*;\s*verify=ltr,rtl\s*(\*\/|-->)$/i;+const MALFORMED_EXCEPTION_DIRECTIVE_RE =+ /^(?:(?:\/\*|\/\/|<!--)\s*)?bidi-(physical|fixed):/i;const BLOCKING_PROPERTY_RE =/(?:^|[;{,"'])\s*['"]?(?:(?:margin|padding|border)-(?:left|right)(?:-(?:color|style|width))?|border-(?:top|bottom)-(?:left|right)-radius)['"]?\s*:/gi;const BLOCKING_STYLE_OBJECT_PROPERTY_RE =@@ -20,10 +21,34 @@ const BLOCKING_STYLE_OBJECT_PROPERTY_RE =const BLOCKING_ALIGNMENT_RE =/(?:^|[;{,"'])\s*['"]?(?:text-align|textAlign|float|clear)['"]?\s*:\s*['"]?(?:left|right)['"]?\s*(?:[;,!}]|$)/gi;const REVIEW_PROPERTY_RE = /(?:^|[;{,"'])\s*['"]?(?:left|right)['"]?\s*:/gi;+const FIXED_DIRECTION_PROPERTY_RE =+ /(?:^|[;{,"'])\s*['"]?direction['"]?\s*:\s*['"]?(?:ltr|rtl)['"]?\s*(?:[;,!}]|$)/gi;+const FIXED_DIRECTION_ATTRIBUTE_RE =+ /(?:(?<![\w-])dir|:dir|\[(?:attr\.)?dir\])\s*=\s*(?:["'](?:ltr|rtl)["']|\{\s*["'](?:ltr|rtl)["']\s*\}|["']\s*["'](?:ltr|rtl)["']\s*["'])/gi;+const CLASS_ATTRIBUTE_PATTERNS = [+ {+ regex: /(?<![:\w\[])(?:class|className)\s*=\s*(["'`])((?:(?!\1).)*)\1/gi,+ valueGroup: 2,+ },+ {+ regex: /\bclassName\s*=\s*\{\s*(["'`])((?:(?!\1).)*)\1\s*\}/gi,+ valueGroup: 2,+ },+ {+ regex: /(?::class|\[class\])\s*=\s*(["'])\s*(["'`])((?:(?!\2).)*)\2\s*\1/gi,+ valueGroup: 3,+ },+];+const PHYSICAL_UTILITY_RE =+ /^-?(?:text-(?:left|right)|float-(?:left|right)|(?:m|p)[lr]-.+|(?:left|right)-.+|border-[lr](?:-.+)?|rounded-[lr](?:-.+)?)$/i;+const PHYSICAL_SHORTHAND_PROPERTY_RE =+ /(?:^|[;{,"'])\s*['"]?(margin|padding|border-radius|borderRadius)['"]?\s*:\s*/gi;+const UNICODE_BIDI_OVERRIDE_RE =+ /(?:^|[;{,"'])\s*['"]?(?:unicode-bidi|unicodeBidi)['"]?\s*:\s*['"]?(?:bidi-override|isolate-override|embed)['"]?\s*(?:[;,!}]|$)/i;const VISUAL_ORDER_RE =/\b(?:flex-direction\s*:\s*(?:row|column)-reverse|order\s*:\s*-?\d+)/i;const GEOMETRY_RE =- /\b(?:translateX|transform-origin|linear-gradient\s*\([^)]*(?:left|right)|clip-path|mask(?:-image)?\s*:)/i;+ /\b(?:scaleX\s*\(\s*-1\s*\)|transform-origin|background-position\s*:\s*(?:left|right)|linear-gradient\s*\([^)]*(?:left|right)|clip-path|mask(?:-image)?\s*:)/i;const FIXED_TEXT_SIZE_RE =/(?:^|[;{])\s*(?:height|width|inline-size|block-size)\s*:\s*\d+(?:\.\d+)?(?:px|rem|em)\s*(?:;|(?=}))/i;const BIDI_CONTROL_RE = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/u;@@ -39,6 +64,12 @@ function collectSourceFiles(projectRoot) {return files;}+function stripHtmlCommentsPreservingLines(source) {+ return source.replace(/<!--[\s\S]*?-->/g, (comment) =>+ comment.replace(/[^\r\n]/g, ' ')+ );+}+function walk(target, files) {if (!fs.existsSync(target)) return;const stat = fs.lstatSync(target);@@ -59,61 +90,94 @@ function auditBidirectionalReadiness(projectRoot) {const findings = [];for (const filePath of collectSourceFiles(projectRoot)) {const relativePath = path.relative(projectRoot, filePath).replaceAll('\\', '/');- const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);+ const source = fs.readFileSync(filePath, 'utf8');+ const lines = source.split(/\r?\n/);+ const extension = path.extname(filePath).toLowerCase();+ const sourceWithoutComments = stripCommentsFromSource(source);+ const controlScanSource = stripCommentsFromSource(+ isMarkupFile(extension)+ ? stripHtmlCommentsPreservingLines(source)+ : source+ );+ const directionalScrollLines =+ collectDirectionalScrollLines(sourceWithoutComments);+ const firstFindingIndex = findings.length;let pendingDirective = null;+ let markupState = createMarkupState();+ let styleObjectDepth = 0;let commentState = { blockEnd: null, quote: null };+ for (const match of collectStaticAutoDirectionControls(+ controlScanSource+ )) {+ findings.push(finding(+ relativePath,+ lineNumberAtOffset(controlScanSource, match.index),+ 'static-auto-control-direction',+ 'error',+ `Native ${match.tagName} controls must use the active UI ` ++ 'direction while empty and switch to auto only when populated; a ' ++ 'permanent dir="auto" can misalign localized placeholders.'+ ));+ }+for (let index = 0; index < lines.length; index += 1) {const line = lines[index];const trimmed = line.trim();- const directiveMatch = commentState.blockEnd || commentState.quote+ const directive = commentState.blockEnd || commentState.quote? null- : trimmed.match(PHYSICAL_DIRECTIVE_RE);- if (directiveMatch) {- const reason = directiveMatch[1].trim();+ : parseExceptionDirective(trimmed);+ if (directive) {+ if (pendingDirective) {+ findings.push(unusedDirectiveFinding(relativePath, pendingDirective));+ pendingDirective = null;+ }+ const { kind, reason } = directive;if (reason.length < 12 || /^(?:needed|intentional|required|exception)$/i.test(reason)) {findings.push(finding(relativePath,index + 1,- 'invalid-physical-exception',+ `invalid-${kind}-exception`,'error',- 'A bidi-physical directive requires a specific reason of at least 12 characters.'+ `A bidi-${kind} directive requires a specific reason of at least 12 characters.`));continue;}pendingDirective = {+ kind,line: index + 1,reason,};continue;}- if (!commentState.blockEnd && !commentState.quote &&- MALFORMED_PHYSICAL_DIRECTIVE_RE.test(trimmed)) {+ const malformedDirective =+ !commentState.blockEnd && !commentState.quote+ ? trimmed.match(MALFORMED_EXCEPTION_DIRECTIVE_RE)+ : null;+ if (malformedDirective) {+ if (pendingDirective) {+ findings.push(unusedDirectiveFinding(relativePath, pendingDirective));+ pendingDirective = null;+ }+ const kind = malformedDirective[1].toLowerCase();findings.push(finding(relativePath,index + 1,- 'invalid-physical-exception',+ `invalid-${kind}-exception`,'error',- 'Use "bidi-physical: <specific reason>; verify=ltr,rtl" immediately before one declaration.'+ `Use "bidi-${kind}: <specific reason>; verify=ltr,rtl" immediately before one ` ++ `${kind === 'physical' ? 'physical declaration or utility' : 'fixed-direction declaration or element'}.`));continue;}- // Preserve string literals while removing code comments so documented- // physical-property examples cannot become blocking audit findings.const stripped = stripSourceComments(line, commentState);const scanLine = stripped.value;const scanTrimmed = scanLine.trim();commentState = stripped.state;if (!scanTrimmed) {- if (pendingDirective && !trimmed) {- findings.push(finding(- relativePath,- pendingDirective.line,- 'unused-physical-exception',- 'error',- 'A bidi-physical directive must be adjacent to the declaration it exempts.'- ));+ if (pendingDirective) {+ findings.push(unusedDirectiveFinding(relativePath, pendingDirective));pendingDirective = null;}if (BIDI_CONTROL_RE.test(line)) {@@ -123,43 +187,66 @@ function auditBidirectionalReadiness(projectRoot) {}const physicalMatches = collectPhysicalMatches(scanLine);+ const fixedDirectionMatches = collectFixedDirectionMatches(scanLine, {+ allowCssProperties:+ isCssFile(extension) || styleObjectDepth > 0 || isLikelyInlineStyle(scanLine),+ markupState,+ });+ const nextMarkupState = scanMarkupState(markupState, scanLine, scanLine.length);+ const nextStyleObjectDepth = updateStyleObjectDepth(styleObjectDepth, scanLine);if (pendingDirective) {- if (physicalMatches.length > 0) {+ const candidateMatches = pendingDirective.kind === 'physical'+ ? physicalMatches+ : fixedDirectionMatches;+ if (candidateMatches.length > 0) {// An exception is deliberately declaration-scoped. Minified CSS can// contain several declarations on one line, so consume exactly one// in source order instead of allowing it to hide the entire line or// a later, more severe declaration.- physicalMatches.shift();+ candidateMatches.shift();pendingDirective = null;+ } else if (nextMarkupState.tagName) {+ // An annotation applies to the following element even when its literal+ // attributes are formatted across several lines.} else {findings.push(finding(relativePath,pendingDirective.line,- 'unused-physical-exception',+ `unused-${pendingDirective.kind}-exception`,'error',- 'A bidi-physical directive may exempt only the immediately following physical declaration.'+ `A bidi-${pendingDirective.kind} directive may exempt only the immediately ` ++ `following ${pendingDirective.kind === 'physical' ? 'physical item' : 'fixed-direction item'}.`));pendingDirective = null;}}for (const physicalMatch of physicalMatches) {- if (physicalMatch.severity === 'error') {- findings.push(finding(- relativePath,- index + 1,- 'directional-physical-css',- 'error',- `Use a logical CSS property, or add an adjacent validated bidi-physical exception: ${scanTrimmed}`- ));- } else {- findings.push(finding(- relativePath,- index + 1,- 'physical-inset-review',- 'review',- `Confirm whether this is intentionally physical or should use an inline inset: ${trimmed}`- ));- }+ findings.push(finding(+ relativePath,+ index + 1,+ physicalMatch.rule,+ physicalMatch.severity,+ physicalMatch.message(scanTrimmed)+ ));+ }+ for (const fixedDirectionMatch of fixedDirectionMatches) {+ findings.push(finding(+ relativePath,+ index + 1,+ fixedDirectionMatch.rule,+ 'error',+ `Fixed ${fixedDirectionMatch.source} direction requires a specific adjacent ` ++ `bidi-fixed reason and LTR/RTL verification: ${scanTrimmed}`+ ));+ }+ if (UNICODE_BIDI_OVERRIDE_RE.test(scanLine)) {+ findings.push(finding(+ relativePath,+ index + 1,+ 'unicode-bidi-override',+ 'error',+ `Avoid bidi overrides in generated source; use semantic isolation instead: ${scanTrimmed}`+ ));}if (VISUAL_ORDER_RE.test(scanLine)) {@@ -171,7 +258,7 @@ function auditBidirectionalReadiness(projectRoot) {'Confirm visual reversal does not diverge from DOM reading and focus order.'));}- if (GEOMETRY_RE.test(scanLine)) {+ if (hasDirectionalGeometry(scanLine)) {findings.push(finding(relativePath,index + 1,@@ -180,6 +267,15 @@ function auditBidirectionalReadiness(projectRoot) {'Review this physical geometry, animation, gradient, clipping, or mask in both directions.'));}+ if (directionalScrollLines.has(index + 1)) {+ findings.push(finding(+ relativePath,+ index + 1,+ 'directional-scroll-review',+ 'review',+ 'Review this physical horizontal scrolling assumption in both directions.'+ ));+ }if (FIXED_TEXT_SIZE_RE.test(scanLine)) {findings.push(finding(relativePath,@@ -192,17 +288,20 @@ function auditBidirectionalReadiness(projectRoot) {if (BIDI_CONTROL_RE.test(line)) {findings.push(unexpectedBidiControl(relativePath, index + 1));}+ markupState = nextMarkupState;+ styleObjectDepth = nextStyleObjectDepth;}if (pendingDirective) {findings.push(finding(relativePath,pendingDirective.line,- 'unused-physical-exception',+ `unused-${pendingDirective.kind}-exception`,'error',- 'A bidi-physical directive must be followed by a physical declaration.'+ `A bidi-${pendingDirective.kind} directive must be followed by an applicable item.`));}+ attachFindingFingerprints(findings.slice(firstFindingIndex), lines);}return {@@ -212,6 +311,126 @@ function auditBidirectionalReadiness(projectRoot) {};}+function collectStaticAutoDirectionControls(source) {+ const matches = [];+ for (const match of source.matchAll(+ /<(input|textarea)(?=\s|\/?>)/gi+ )) {+ const end = findOpeningTagEnd(source, match.index);+ if (end < 0) continue;+ const openingTag = source.slice(match.index, end + 1);+ if (hasStaticAutoDirectionAttribute(openingTag)) {+ matches.push({+ index: match.index,+ tagName: match[1].toLowerCase(),+ });+ }+ }+ return matches;+}++function findOpeningTagEnd(source, start) {+ let quote = null;+ let escaped = false;+ let expressionDepth = 0;+ for (let index = start; index < source.length; index += 1) {+ const character = source[index];+ if (quote) {+ if (escaped) {+ escaped = false;+ } else if (character === '\\') {+ escaped = true;+ } else if (character === quote) {+ quote = null;+ }+ continue;+ }+ if (character === '"' || character === "'" || character === '`') {+ quote = character;+ } else if (character === '{') {+ expressionDepth += 1;+ } else if (character === '}') {+ expressionDepth = Math.max(0, expressionDepth - 1);+ } else if (character === '>' && expressionDepth === 0) {+ return index;+ }+ }+ return -1;+}++function hasStaticAutoDirectionAttribute(openingTag) {+ let index = openingTag.search(/\s/);+ while (index >= 0 && index < openingTag.length) {+ while (/\s/.test(openingTag[index] || '')) index += 1;+ if (openingTag[index] === '/' || openingTag[index] === '>') return false;+ const nameStart = index;+ while (index < openingTag.length &&+ !/[\s=/>]/.test(openingTag[index])) {+ index += 1;+ }+ const name = openingTag.slice(nameStart, index).toLowerCase();+ while (/\s/.test(openingTag[index] || '')) index += 1;+ if (openingTag[index] !== '=') continue;+ index += 1;+ while (/\s/.test(openingTag[index] || '')) index += 1;+ const parsed = readAttributeValue(openingTag, index);+ index = parsed.nextIndex;+ if (['dir', ':dir', 'v-bind:dir', '[dir]', '[attr.dir]'].includes(name) &&+ normalizeStaticAttributeValue(parsed.value) === 'auto') {+ return true;+ }+ }+ return false;+}++function readAttributeValue(openingTag, start) {+ const first = openingTag[start];+ if (first === '"' || first === "'" || first === '`') {+ let value = '';+ let escaped = false;+ for (let index = start + 1; index < openingTag.length; index += 1) {+ const character = openingTag[index];+ if (escaped) {+ escaped = false;+ } else if (character === '\\') {+ escaped = true;+ } else if (character === first) {+ return { value, nextIndex: index + 1 };+ }+ value += character;+ }+ return { value, nextIndex: openingTag.length };+ }+ if (first === '{') {+ const end = findMatchingDelimiter(openingTag, start, '{', '}');+ if (end >= 0) {+ return {+ value: openingTag.slice(start + 1, end),+ nextIndex: end + 1,+ };+ }+ }+ let index = start;+ while (index < openingTag.length && !/[\s>]/.test(openingTag[index])) {+ index += 1;+ }+ return {+ value: openingTag.slice(start, index),+ nextIndex: index,+ };+}++function normalizeStaticAttributeValue(value) {+ let normalized = value.trim();+ while (normalized.length >= 2 &&+ ((normalized.startsWith('"') && normalized.endsWith('"')) ||+ (normalized.startsWith("'") && normalized.endsWith("'")) ||+ (normalized.startsWith('`') && normalized.endsWith('`')))) {+ normalized = normalized.slice(1, -1).trim();+ }+ return normalized.toLowerCase();+}+function isInsideUnquotedUrl(value, index) {const prefix = value.slice(0, index);@@ -224,15 +443,315 @@ function isInsideUnquotedUrl(value, index) {/\b(?:https?|ftp|wss?|file):[^\s"'`<>]*$/i.test(prefix);}+function finding(file, line, rule, severity, message) {+ return { file, line, rule, severity, message };+}++function attachFindingFingerprints(fileFindings, lines) {+ const occurrences = new Map();+ for (const item of fileFindings) {+ const identity = `${item.line}\0${item.rule}\0${item.message}`;+ const occurrence = occurrences.get(identity) || 0;+ occurrences.set(identity, occurrence + 1);+ const start = Math.max(0, item.line - 3);+ const end = Math.min(lines.length, item.line + 2);+ const context = lines.slice(start, end).join('\n');+ item.fingerprint = crypto.createHash('sha256')+ .update(`${identity}\0${occurrence}\0${context}`)+ .digest('hex');+ }+}++function collectPhysicalMatches(value) {+ const matches = [];+ for (const pattern of [+ BLOCKING_PROPERTY_RE,+ BLOCKING_STYLE_OBJECT_PROPERTY_RE,+ BLOCKING_ALIGNMENT_RE,+ ]) {+ for (const match of value.matchAll(pattern)) {+ matches.push({+ index: match.index,+ severity: 'error',+ rule: 'directional-physical-css',+ message: (trimmed) =>+ `Use a logical CSS property, or add an adjacent validated bidi-physical exception: ${trimmed}`,+ });+ }+ }+ for (const match of value.matchAll(REVIEW_PROPERTY_RE)) {+ matches.push({+ index: match.index,+ severity: 'review',+ rule: 'physical-inset-review',+ message: (trimmed) =>+ `Confirm whether this is intentionally physical or should use an inline inset: ${trimmed}`,+ });+ }+ matches.push(...collectPhysicalUtilityMatches(value));+ matches.push(...collectPhysicalShorthandMatches(value));+ return matches.sort((left, right) => left.index - right.index);+}++function collectFixedDirectionMatches(value, options = {}) {+ const matches = [];+ if (options.allowCssProperties) {+ for (const match of value.matchAll(FIXED_DIRECTION_PROPERTY_RE)) {+ matches.push({ index: match.index, rule: 'fixed-direction', source: 'CSS' });+ }+ }+ for (const match of value.matchAll(FIXED_DIRECTION_ATTRIBUTE_RE)) {+ if (!isInsideMarkupTag(value, match.index, options.markupState) ||+ isInsideHtmlRootTag(value, match.index, options.markupState)) {+ continue;+ }+ matches.push({ index: match.index, rule: 'fixed-direction', source: 'markup' });+ }+ return matches.sort((left, right) => left.index - right.index);+}++function collectPhysicalUtilityMatches(value) {+ const matches = [];+ for (const pattern of CLASS_ATTRIBUTE_PATTERNS) {+ for (const classMatch of value.matchAll(pattern.regex)) {+ const classValue = classMatch[pattern.valueGroup].replace(/^(['"])(.*)\1$/, '$2');+ for (const tokenMatch of classValue.matchAll(/\S+/g)) {+ const baseToken = tokenMatch[0].split(':').at(-1);+ if (!PHYSICAL_UTILITY_RE.test(baseToken)) continue;+ matches.push({+ index: classMatch.index + tokenMatch.index,+ severity: 'error',+ rule: 'directional-physical-utility',+ message: () =>+ `Use a logical utility instead of the physical class "${tokenMatch[0]}", ` ++ 'or add an adjacent validated bidi-physical exception.',+ });+ }+ }+ }+ return matches.sort((left, right) => left.index - right.index);+}++function collectPhysicalShorthandMatches(value) {+ const matches = [];+ for (const match of value.matchAll(PHYSICAL_SHORTHAND_PROPERTY_RE)) {+ const property = match[1];+ const rawValue = readPropertyValue(value, match.index + match[0].length);+ const tokens = splitCssValues(rawValue).map((token) =>+ token.replace(/^[`'"]+|[`'",]+$/g, '')+ );+ const normalizedProperty = property === 'borderRadius' ? 'border-radius' : property;+ const isDirectionalSpacing =+ (normalizedProperty === 'margin' || normalizedProperty === 'padding') &&+ tokens.length === 4 &&+ tokens[1] !== tokens[3];+ const isDirectionalRadius =+ normalizedProperty === 'border-radius' && isDirectionalRadiusValue(rawValue);+ if (!isDirectionalSpacing && !isDirectionalRadius) continue;+ matches.push({+ index: match.index,+ severity: 'error',+ rule: 'directional-physical-shorthand',+ message: (trimmed) =>+ `Replace the asymmetric physical ${normalizedProperty} shorthand with logical ` ++ `properties, or add an adjacent validated bidi-physical exception: ${trimmed}`,+ });+ }+ return matches;+}++function readPropertyValue(value, start) {+ let index = start;+ while (/\s/.test(value[index] || '')) index += 1;+ const quote = value[index];+ if (quote === '"' || quote === "'" || quote === '`') {+ let result = '';+ for (index += 1; index < value.length; index += 1) {+ if (value[index] === quote && value[index - 1] !== '\\') break;+ result += value[index];+ }+ return result.trim();+ }++ let result = '';+ let depth = 0;+ for (; index < value.length; index += 1) {+ const character = value[index];+ if (character === '(') depth += 1;+ if (character === ')') depth = Math.max(0, depth - 1);+ if (depth === 0 && /[;,}]/.test(character)) break;+ result += character;+ }+ return result.trim();+}++function isDirectionalRadiusValue(value) {+ const sides = splitTopLevel(value, '/').map((side) => splitCssValues(side.trim()));+ if (sides.length > 2 || sides.some((side) => side.length < 1 || side.length > 4)) {+ return false;+ }+ return sides.some((side) => {+ const [topLeft, topRight, bottomRight, bottomLeft] = expandCornerValues(side);+ return topLeft !== topRight || bottomLeft !== bottomRight;+ });+}++function expandCornerValues(tokens) {+ if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];+ if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];+ if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];+ return tokens;+}++function splitCssValues(value) {+ const tokens = [];+ let current = '';+ let depth = 0;+ for (const character of value) {+ if (character === '(') depth += 1;+ if (character === ')') depth = Math.max(0, depth - 1);+ if (/\s/.test(character) && depth === 0) {+ if (current) tokens.push(current);+ current = '';+ } else {+ current += character;+ }+ }+ if (current) tokens.push(current);+ return tokens;+}++function isInsideMarkupTag(value, index, markupState) {+ return Boolean(scanMarkupState(markupState, value, index).tagName);+}++function isInsideHtmlRootTag(value, index, markupState) {+ return scanMarkupState(markupState, value, index).tagName === 'html';+}++function createMarkupState() {+ return {+ tagName: null,+ expressionDepth: 0,+ quote: null,+ escaped: false,+ };+}++function scanMarkupState(initialState, value, endIndex) {+ const state = initialState ? { ...initialState } : createMarkupState();++ for (let index = 0; index < endIndex; index += 1) {+ const character = value[index];+ if (!state.tagName) {+ if (character !== '<') continue;+ const match = value.slice(index).match(/^<([A-Za-z][\w.-]*)\b/);+ if (!match) continue;+ state.tagName = match[1].toLowerCase();+ state.expressionDepth = 0;+ state.quote = null;+ state.escaped = false;+ index += match[0].length - 1;+ continue;+ }+ if (state.quote) {+ if (state.escaped) {+ state.escaped = false;+ } else if (character === '\\') {+ state.escaped = true;+ } else if (character === state.quote) {+ state.quote = null;+ }+ continue;+ }+ if (character === '"' || character === "'" || character === '`') {+ state.quote = character;+ } else if (character === '{') {+ state.expressionDepth += 1;+ } else if (character === '}') {+ state.expressionDepth = Math.max(0, state.expressionDepth - 1);+ } else if (character === '>' && state.expressionDepth === 0) {+ state.tagName = null;+ }+ }+ return state;+}++function isCssFile(extension) {+ return extension === '.css' || extension === '.scss' || extension === '.less';+}++function isMarkupFile(extension) {+ return ['.html', '.astro', '.vue'].includes(extension);+}++function isLikelyInlineStyle(value) {+ return /\b\w*(?:style|styles|sx|css)\w*\s*(?:=|:)/i.test(value);+}++function updateStyleObjectDepth(currentDepth, value) {+ let depth = currentDepth;+ let start = 0;+ if (depth === 0) {+ const styleObject = value.match(/\b\w*(?:style|styles|sx|css)\w*\s*(?:=|:)\s*\{/i);+ if (!styleObject) return 0;+ start = styleObject.index + styleObject[0].lastIndexOf('{');+ }+ for (const character of stripQuotedText(value.slice(start))) {+ if (character === '{') depth += 1;+ if (character === '}') depth = Math.max(0, depth - 1);+ }+ return depth;+}++function stripQuotedText(value) {+ let result = '';+ let quote = null;+ let escaped = false;+ for (const character of value) {+ if (quote) {+ if (escaped) {+ escaped = false;+ } else if (character === '\\') {+ escaped = true;+ } else if (character === quote) {+ quote = null;+ }+ result += ' ';+ } else if (character === '"' || character === "'" || character === '`') {+ quote = character;+ result += ' ';+ } else {+ result += character;+ }+ }+ return result;+}++function parseExceptionDirective(value) {+ const match = value.match(EXCEPTION_DIRECTIVE_RE);+ if (!match) return null;+ const wrappersMatch =+ (match[1] === '/*' && match[4] === '*/') ||+ (match[1] === '<!--' && match[4] === '-->');+ if (!wrappersMatch) return null;+ return {+ kind: match[2].toLowerCase(),+ reason: match[3].trim(),+ };+}+function stripSourceComments(value, initialState) {const state = { ...initialState };let result = '';let quote = state.quote || null;let escaped = false;+ let hadComment = false;for (let index = 0; index < value.length; index += 1) {if (state.blockEnd) {const end = value.indexOf(state.blockEnd, index);+ hadComment = true;if (end < 0) {result += ' '.repeat(value.length - index);break;@@ -265,6 +784,7 @@ function stripSourceComments(value, initialState) {const startsLineComment =value.startsWith('//', index) && !isInsideUnquotedUrl(value, index);if (startsLineComment) {+ hadComment = true;result += ' '.repeat(value.length - index);break;}@@ -276,6 +796,7 @@ function stripSourceComments(value, initialState) {? '*/': null;if (blockEnd) {+ hadComment = true;state.blockEnd = blockEnd;result += ' '.repeat(blockEnd === '-->' ? 4 : 2);index += blockEnd === '-->' ? 3 : 1;@@ -283,32 +804,134 @@ function stripSourceComments(value, initialState) {}result += character;}-// Backticks routinely span lines in JavaScript, and quoted HTML attributes may also// be multiline. Carry quote state so comment-looking text inside them stays source.state.quote = quote;- return { value: result, state };+ return { value: result, state, hadComment };}-function finding(file, line, rule, severity, message) {- return { file, line, rule, severity, message };+function stripCommentsFromSource(source) {+ let state = { blockEnd: null, quote: null };+ return source.split(/\r?\n/).map((line) => {+ const stripped = stripSourceComments(line, state);+ state = stripped.state;+ return stripped.value;+ }).join('\n');}-function collectPhysicalMatches(value) {- const matches = [];+function hasDirectionalGeometry(value) {+ if (GEOMETRY_RE.test(value)) return true;for (const pattern of [- BLOCKING_PROPERTY_RE,- BLOCKING_STYLE_OBJECT_PROPERTY_RE,- BLOCKING_ALIGNMENT_RE,+ /\btranslateX\s*\(\s*([^)\s]+)/gi,+ /\btranslate(?:3d)?\s*\(\s*([^,\s)]+)/gi,+ /(?:^|[;{,"'])\s*['"]?translate['"]?\s*:\s*['"]?([^,\s;'"}]+)/gi,]) {for (const match of value.matchAll(pattern)) {- matches.push({ index: match.index, severity: 'error' });+ if (!isZeroCssValue(match[1])) return true;}}- for (const match of value.matchAll(REVIEW_PROPERTY_RE)) {- matches.push({ index: match.index, severity: 'review' });+ return false;+}++function collectDirectionalScrollLines(source) {+ const lines = new Set();+ for (const match of source.matchAll(/\.scrollLeft\b/g)) {+ lines.add(lineNumberAtOffset(source, match.index));}- return matches.sort((left, right) => left.index - right.index);+ for (const match of source.matchAll(/\.(?:scroll|scrollTo|scrollBy)\s*\(/g)) {+ const openingParen = source.indexOf('(', match.index);+ const closingParen = findMatchingDelimiter(source, openingParen, '(', ')');+ if (closingParen < 0) continue;+ const argumentsText = source.slice(openingParen + 1, closingParen).trim();+ const isOptionsObject =+ argumentsText.startsWith('{') && /\bleft\s*:/.test(argumentsText);+ const isPositional = splitTopLevel(argumentsText, ',').length > 1;+ if (isOptionsObject || isPositional) {+ lines.add(lineNumberAtOffset(source, match.index));+ }+ }+ return lines;+}++function findMatchingDelimiter(value, start, opening, closing) {+ let depth = 0;+ let quote = null;+ let escaped = false;+ for (let index = start; index < value.length; index += 1) {+ const character = value[index];+ if (quote) {+ if (escaped) {+ escaped = false;+ } else if (character === '\\') {+ escaped = true;+ } else if (character === quote) {+ quote = null;+ }+ continue;+ }+ if (character === '"' || character === "'" || character === '`') {+ quote = character;+ } else if (character === opening) {+ depth += 1;+ } else if (character === closing) {+ depth -= 1;+ if (depth === 0) return index;+ }+ }+ return -1;+}++function splitTopLevel(value, delimiter) {+ const parts = [];+ let current = '';+ let depth = 0;+ let quote = null;+ let escaped = false;+ for (const character of value) {+ if (quote) {+ current += character;+ if (escaped) {+ escaped = false;+ } else if (character === '\\') {+ escaped = true;+ } else if (character === quote) {+ quote = null;+ }+ continue;+ }+ if (character === '"' || character === "'" || character === '`') {+ quote = character;+ } else if (character === '(' || character === '[' || character === '{') {+ depth += 1;+ } else if (character === ')' || character === ']' || character === '}') {+ depth = Math.max(0, depth - 1);+ } else if (character === delimiter && depth === 0) {+ parts.push(current);+ current = '';+ continue;+ }+ current += character;+ }+ parts.push(current);+ return parts;+}++function lineNumberAtOffset(value, offset) {+ return value.slice(0, offset).split('\n').length;+}++function isZeroCssValue(value) {+ return /^[-+]?0(?:\.0+)?(?:[a-z%]+)?$/i.test(value);+}++function unusedDirectiveFinding(file, directive) {+ return finding(+ file,+ directive.line,+ `unused-${directive.kind}-exception`,+ 'error',+ `A bidi-${directive.kind} directive must be adjacent to the item it exempts.`+ );}function unexpectedBidiControl(file, line) {diff --git a/plugins/power-pages/scripts/lib/detect-browser.js b/plugins/power-pages/scripts/lib/detect-browser.jsindex 6b8461da9..8e4b05eb2 100644--- a/plugins/power-pages/scripts/lib/detect-browser.js+++ b/plugins/power-pages/scripts/lib/detect-browser.js@@ -1,8 +1,9 @@#!/usr/bin/env node// Detects the best available Chromium-based browser on the system.-// Returns a Playwright channel name ('msedge', 'chrome', 'chromium').-// Used by the Playwright MCP launcher and the axe-core audit script.+// Returns either the legacy Playwright channel name or launch options. Linux+// distro Chromium needs its executable path; channel "chromium" would instead+// select Playwright's separately downloaded browser.const { execFileSync } = require('child_process');const fs = require('fs');@@ -24,6 +25,17 @@ function whichExists(cmd) {}}+function whichPath(cmd, executeFile = execFileSync) {+ try {+ return executeFile('which', [cmd], {+ encoding: 'utf8',+ shell: false,+ }).trim() || null;+ } catch {+ return null;+ }+}+function detectBrowser() {const platform = os.platform();@@ -69,4 +81,29 @@ function detectBrowser() {return 'chromium';}-module.exports = { detectBrowser };+function detectBrowserLaunchOptions(options = {}) {+ const platform = options.platform || os.platform();+ const commandExists = options.whichExists || whichExists;+ const commandPath = options.whichPath || whichPath;+ if (platform === 'linux') {+ for (const command of ['google-chrome', 'google-chrome-stable']) {+ if (commandExists(command)) return { channel: 'chrome' };+ }+ for (const command of ['microsoft-edge', 'microsoft-edge-stable']) {+ if (commandExists(command)) return { channel: 'msedge' };+ }+ for (const command of ['chromium-browser', 'chromium']) {+ const executablePath = commandPath(command);+ if (executablePath) return { executablePath };+ }+ return {};+ }+ const channel = detectBrowser();+ return channel === 'chromium' ? {} : { channel };+}++module.exports = {+ detectBrowser,+ detectBrowserLaunchOptions,+ whichPath,+};diff --git a/plugins/power-pages/scripts/lib/localization-config.js b/plugins/power-pages/scripts/lib/localization-config.jsindex b90d7eba7..9945780c6 100644--- a/plugins/power-pages/scripts/lib/localization-config.js+++ b/plugins/power-pages/scripts/lib/localization-config.js@@ -25,38 +25,86 @@ function hasLocaleNavigationSignal(text) {return LOCALE_NAVIGATION_PATTERN.test(String(text || ''));}+function defineFrameworkCapability({+ modes,+ recommendedMode,+ recommendedPackages,+ frameworkPeers,+}) {+ const frozenModes = Object.freeze(Object.fromEntries(+ Object.entries(modes).map(([mode, availability]) => [+ mode,+ Object.freeze({ ...availability }),+ ])+ ));+ const supportedModes = Object.freeze(Object.keys(frozenModes));+ const availableModes = Object.freeze(supportedModes.filter(+ (mode) => frozenModes[mode].status === 'available'+ ));+ return Object.freeze({+ modes: frozenModes,+ supportedModes,+ availableModes,+ recommendedMode,+ recommendedPackages: Object.freeze(recommendedPackages),+ frameworkPeers: Object.freeze(frameworkPeers),+ });+}+const LOCALIZATION_CAPABILITIES = Object.freeze({frameworks: Object.freeze({- react: Object.freeze({- supportedModes: Object.freeze(['runtime']),+ react: defineFrameworkCapability({+ modes: {+ runtime: { status: 'available' },+ },recommendedMode: 'runtime',- recommendedPackages: Object.freeze({ runtime: 'react-i18next' }),- frameworkPeers: Object.freeze(['react', 'react-dom']),+ recommendedPackages: { runtime: 'react-i18next' },+ frameworkPeers: ['react', 'react-dom'],}),- vue: Object.freeze({- supportedModes: Object.freeze(['runtime']),+ vue: defineFrameworkCapability({+ modes: {+ runtime: { status: 'available' },+ },recommendedMode: 'runtime',- recommendedPackages: Object.freeze({ runtime: 'vue-i18n' }),- frameworkPeers: Object.freeze(['vue']),+ recommendedPackages: { runtime: 'vue-i18n' },+ frameworkPeers: ['vue'],}),- angular: Object.freeze({- supportedModes: Object.freeze(['runtime', 'static']),- recommendedMode: 'static',- recommendedPackages: Object.freeze({+ angular: defineFrameworkCapability({+ modes: {+ runtime: { status: 'available' },+ static: {+ status: 'temporarily-unavailable',+ reasonCode: 'angular-static-temporarily-unavailable',+ reason:+ 'Angular static localization is temporarily unavailable in this release. ' ++ 'Angular runtime localization is available; @jsverse/transloco is recommended, ' ++ 'and compatible validated runtime alternatives are allowed.',+ },+ },+ recommendedMode: 'runtime',+ recommendedPackages: {runtime: '@jsverse/transloco',static: '@angular/localize',- }),- frameworkPeers: Object.freeze([+ },+ frameworkPeers: ['@angular/core','@angular/compiler','@angular/compiler-cli',- ]),+ ],}),- astro: Object.freeze({- supportedModes: Object.freeze(['static']),- recommendedMode: 'static',- recommendedPackages: Object.freeze({ static: 'astro-built-in' }),- frameworkPeers: Object.freeze(['astro']),+ astro: defineFrameworkCapability({+ modes: {+ static: {+ status: 'temporarily-unavailable',+ reasonCode: 'astro-static-temporarily-unavailable',+ reason:+ 'Astro static localization is temporarily unavailable in this release. ' ++ 'No Astro localization mode is currently available.',+ },+ },+ recommendedMode: null,+ recommendedPackages: { static: 'astro-built-in' },+ frameworkPeers: ['astro'],}),}),packages: Object.freeze({@@ -69,6 +117,70 @@ const LOCALIZATION_CAPABILITIES = Object.freeze({}),});const KNOWN_PACKAGES = LOCALIZATION_CAPABILITIES.packages;++function getLocalizationModeAvailability(framework, mode) {+ const capability = LOCALIZATION_CAPABILITIES.frameworks[framework];+ if (!capability) {+ return {+ framework,+ mode,+ supported: false,+ available: false,+ status: 'unsupported',+ recommendedPackage: null,+ builtIn: false,+ reasonCode: 'unsupported-framework',+ reason: `Framework "${framework}" is not supported by add-localization.`,+ };+ }+ const availability = capability.modes[mode];+ if (!availability) {+ return {+ framework,+ mode,+ supported: false,+ available: false,+ status: 'unsupported',+ recommendedPackage: null,+ builtIn: false,+ reasonCode: 'unsupported-mode',+ reason: `${framework} does not support "${mode}" mode in add-localization.`,+ };+ }+ const recommendedPackage = capability.recommendedPackages[mode] || null;+ return {+ framework,+ mode,+ supported: true,+ available: availability.status === 'available',+ recommendedPackage,+ builtIn: Boolean(KNOWN_PACKAGES[recommendedPackage]?.builtIn),+ ...availability,+ };+}++function getFrameworkLocalizationAvailability(framework) {+ const capability = LOCALIZATION_CAPABILITIES.frameworks[framework];+ if (!capability) {+ return {+ framework,+ supported: false,+ availableModes: [],+ recommendedMode: null,+ modes: {},+ };+ }+ return {+ framework,+ supported: true,+ availableModes: [...capability.availableModes],+ recommendedMode: capability.recommendedMode,+ modes: Object.fromEntries(capability.supportedModes.map((mode) => [+ mode,+ getLocalizationModeAvailability(framework, mode),+ ])),+ };+}const DEFAULT_SOURCE_SCAN_LIMITS = Object.freeze({maxFileBytes: 1024 * 1024,maxTotalBytes: 10 * 1024 * 1024,@@ -206,6 +318,25 @@ function resolveProjectRelativePath(projectRoot, relativePath) {return { valid: true, reason: null, path: resolvedPath };}+// The managed locale availability module is recognized by file name, e.g.+// `src/i18n/localeAvailability.ts`, `src/app/locale-availability.ts`, or+// `src/i18n/locale_availability.js`. The localization validator, the+// verification transaction, and the evidence fingerprint must agree on which+// file it is, so they all share this rule.+const LOCALE_AVAILABILITY_FILE_PATTERN = /locale[-_.]?availability/i;++function isLocaleAvailabilityModulePath(relativePath) {+ return typeof relativePath === 'string' &&+ LOCALE_AVAILABILITY_FILE_PATTERN.test(path.basename(relativePath));+}++function findLocaleAvailabilityModulePaths(manifest) {+ return [...new Set([+ ...(Array.isArray(manifest?.generatedFiles) ? manifest.generatedFiles : []),+ ...(Array.isArray(manifest?.managedFiles) ? manifest.managedFiles : []),+ ])].filter(isLocaleAvailabilityModulePath);+}+function validateManifestPath(errors, field, relativePath, projectRoot) {const result = projectRoot? resolveProjectRelativePath(projectRoot, relativePath)@@ -222,7 +353,51 @@ function hasOnlyAllowedProperties(value, allowed) {return Object.keys(value).every((key) => allowed.has(key));}-function validateLocalizationManifestShape(manifest, projectRoot) {+function validateFindingDisposition(finding, prefix, errors, required) {+ const disposition = finding?.disposition;+ if (!required && disposition === undefined) return;+ if (!disposition || typeof disposition !== 'object' || Array.isArray(disposition)) {+ errors.push(`${prefix}.disposition must record the maker-approved limitation.`);+ return;+ }+ if (disposition.status !== 'maker-approved') {+ errors.push(`${prefix}.disposition.status must be "maker-approved".`);+ }+ for (const field of ['impact', 'evidence', 'approvedAt']) {+ if (typeof disposition[field] !== 'string' || !disposition[field].trim()) {+ errors.push(`${prefix}.disposition.${field} must be a non-empty string.`);+ }+ }+ if (typeof disposition.evidence === 'string' &&+ (!disposition.evidence.startsWith('docs/bidirectional-evidence/') ||+ disposition.evidence.includes('..') ||+ path.isAbsolute(disposition.evidence))) {+ errors.push(+ `${prefix}.disposition.evidence must be a repository-relative ` ++ 'docs/bidirectional-evidence/ path.'+ );+ }+ if (typeof disposition.approvedAt === 'string' &&+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(+ disposition.approvedAt+ )) {+ const normalized = disposition.approvedAt.includes('.')+ ? disposition.approvedAt+ : disposition.approvedAt.replace(/Z$/, '.000Z');+ if (!Number.isFinite(Date.parse(disposition.approvedAt)) ||+ new Date(disposition.approvedAt).toISOString() !== normalized) {+ errors.push(`${prefix}.disposition.approvedAt must be an ISO date-time.`);+ }+ } else if (typeof disposition.approvedAt === 'string') {+ errors.push(`${prefix}.disposition.approvedAt must be an ISO date-time.`);+ }+}++function validateLocalizationManifestShape(manifest, projectRootOrOptions = {}) {+ const options = typeof projectRootOrOptions === 'string'+ ? { projectRoot: projectRootOrOptions }+ : projectRootOrOptions || {};+ const projectRoot = options.projectRoot;if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {return ['Localization manifest must be a JSON object.'];}@@ -230,8 +405,8 @@ function validateLocalizationManifestShape(manifest, projectRoot) {if (!hasOnlyAllowedProperties(manifest, MANIFEST_FIELDS)) {errors.push('Localization manifest contains unsupported top-level properties.');}- if (typeof manifest.schemaVersion !== 'number') {- errors.push('Manifest schemaVersion must be a number.');+ if (manifest.schemaVersion !== 1) {+ errors.push('Manifest schemaVersion must be 1.');}for (const [field, maxChars] of Object.entries({framework: 50,@@ -501,32 +676,246 @@ function validateLocalizationManifestShape(manifest, projectRoot) {}}}- if (manifest.bidirectionalReadiness !== undefined) {- const readiness = manifest.bidirectionalReadiness;- if (!readiness || typeof readiness !== 'object' || Array.isArray(readiness)) {- errors.push('Manifest bidirectionalReadiness must be an object.');+ if (manifest.bidirectionalReadiness === undefined) {+ errors.push(+ 'Schema version 1 manifests require bidirectionalReadiness metadata.'+ );+ } else if (manifest.bidirectionalReadiness !== undefined) {+ validateBidirectionalReadiness(manifest, errors, options);+ }+ return errors;+}++function validateBidirectionalReadiness(manifest, errors, options = {}) {+ const readiness = manifest.bidirectionalReadiness;+ const statuses = new Set([+ 'ready',+ 'approved-with-limitations',+ 'pending-remediation',+ ]);+ if (!readiness || typeof readiness !== 'object' || Array.isArray(readiness)) {+ errors.push('Manifest bidirectionalReadiness must be an object.');+ return;+ }+ if (!statuses.has(readiness.status)) {+ errors.push(+ 'Manifest bidirectionalReadiness.status must be "ready", ' ++ '"approved-with-limitations", or "pending-remediation".'+ );+ }++ const localeReadiness = readiness.localeReadiness;+ if (!localeReadiness || typeof localeReadiness !== 'object' ||+ Array.isArray(localeReadiness)) {+ errors.push('Manifest bidirectionalReadiness.localeReadiness must be an object.');+ }+ const locales = Array.isArray(manifest.locales) ? manifest.locales : [];+ const localeSet = new Set(locales);+ const readinessLocales = localeReadiness &&+ typeof localeReadiness === 'object' &&+ !Array.isArray(localeReadiness)+ ? Object.keys(localeReadiness)+ : [];+ const missingLocales = locales.filter((locale) => !readinessLocales.includes(locale));+ const extraLocales = readinessLocales.filter((locale) => !localeSet.has(locale));+ if (missingLocales.length || extraLocales.length) {+ errors.push(+ 'Manifest bidirectionalReadiness.localeReadiness keys must exactly match locales.'+ );+ }++ const localeStatuses = new Map();+ for (const locale of readinessLocales) {+ const entry = localeReadiness[locale];+ const prefix = `Manifest bidirectionalReadiness.localeReadiness["${locale}"]`;+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {+ errors.push(`${prefix} must be an object.`);+ continue;+ }+ if (!statuses.has(entry.status)) {+ errors.push(+ `${prefix}.status must be "ready", "approved-with-limitations", ` ++ 'or "pending-remediation".'+ );} else {- if (!['ready', 'approved-with-limitations', 'pending-remediation'].includes(- readiness.status- )) {+ localeStatuses.set(locale, entry.status);+ }+ }+ if (localeStatuses.get(manifest.defaultLocale) === 'pending-remediation') {+ errors.push('The default locale cannot be pending remediation.');+ }++ const staticFindings = validateReadinessFindings(+ readiness.findings,+ 'findings',+ manifest,+ errors,+ true+ );+ const renderedFindings = validateReadinessFindings(+ readiness.renderedFindings,+ 'renderedFindings',+ manifest,+ errors,+ false+ );+ const allFindings = [...staticFindings, ...renderedFindings];++ for (const finding of allFindings) {+ for (const locale of finding.affectedLocales || []) {+ const status = localeStatuses.get(locale);+ if (finding.severity === 'error' && status !== 'pending-remediation') {errors.push(- 'Manifest bidirectionalReadiness.status must be "ready", ' +- '"approved-with-limitations", or "pending-remediation".'+ `Bidirectional error "${finding.rule}" requires locale ${locale} ` ++ 'to be pending-remediation.');}- if (readiness.findings !== undefined && !Array.isArray(readiness.findings)) {- errors.push('Manifest bidirectionalReadiness.findings must be an array.');+ if (finding.severity === 'review' && finding.disposition &&+ !['approved-with-limitations', 'pending-remediation'].includes(status)) {+ errors.push(+ `Maker-approved limitation "${finding.rule}" requires locale ${locale} ` ++ 'to be approved-with-limitations or pending-remediation.'+ );}- if (readiness.status === 'pending-remediation' &&- (!Array.isArray(manifest.unavailableLocales) ||- manifest.unavailableLocales.length === 0)) {+ if (finding.severity === 'review' && !finding.disposition &&+ status !== 'pending-remediation') {errors.push(- 'Pending bidirectional remediation requires at least one unavailable locale.'+ `Undisposed review finding "${finding.rule}" requires locale ${locale} ` ++ 'to be pending-remediation.');}}}- return errors;++ for (const [locale, status] of localeStatuses) {+ const localeFindings = allFindings.filter(+ (finding) => finding.affectedLocales?.includes(locale)+ );+ if (status === 'ready' && localeFindings.length > 0) {+ errors.push(`Ready locale ${locale} cannot have unresolved findings.`);+ }+ if (status === 'approved-with-limitations' &&+ (localeFindings.length === 0 ||+ localeFindings.some(+ (finding) => finding.severity !== 'review' || !finding.disposition+ ))) {+ errors.push(+ `Approved-with-limitations locale ${locale} requires only ` ++ 'maker-approved review findings.'+ );+ }+ }++ const expectedOverall = [...localeStatuses.values()].includes('pending-remediation')+ ? 'pending-remediation'+ : [...localeStatuses.values()].includes('approved-with-limitations')+ ? 'approved-with-limitations'+ : 'ready';+ if (localeStatuses.size > 0 && readiness.status !== expectedOverall) {+ errors.push(+ `Manifest bidirectionalReadiness.status must be "${expectedOverall}" ` ++ 'to summarize localeReadiness.'+ );+ }++ const verificationLocales = new Set(options.verificationLocales || []);+ const expectedUnavailable = [...localeStatuses.entries()]+ .filter(([, status]) => status === 'pending-remediation')+ .map(([locale]) => locale)+ .filter((locale) => !verificationLocales.has(locale))+ .sort();+ const actualUnavailable = Array.isArray(manifest.unavailableLocales)+ ? [...manifest.unavailableLocales].sort()+ : [];+ if (JSON.stringify(expectedUnavailable) !== JSON.stringify(actualUnavailable)) {+ errors.push(+ 'Manifest unavailableLocales must exactly match locales whose readiness ' ++ 'is pending-remediation.'+ );+ }+}++function validateReadinessFindings(value, field, manifest, errors, isStatic) {+ if (!Array.isArray(value)) {+ errors.push(`Manifest bidirectionalReadiness.${field} must be an array.`);+ return [];+ }+ const valid = [];+ for (const [index, finding] of value.entries()) {+ const prefix = `Manifest bidirectionalReadiness.${field}[${index}]`;+ if (!finding || typeof finding !== 'object' || Array.isArray(finding)) {+ errors.push(`${prefix} must be an object.`);+ continue;+ }+ const requiredFields = isStatic+ ? ['file', 'rule', 'message', 'fingerprint']+ : ['caseId', 'rule', 'message', 'selector'];+ for (const requiredField of requiredFields) {+ if (typeof finding[requiredField] !== 'string' ||+ !finding[requiredField].trim()) {+ errors.push(`${prefix}.${requiredField} must be a non-empty string.`);+ }+ }+ if (isStatic && (!Number.isInteger(finding.line) || finding.line < 1)) {+ errors.push(`${prefix}.line must be a positive integer.`);+ }+ if (!['error', 'review'].includes(finding.severity)) {+ errors.push(`${prefix}.severity must be "error" or "review".`);+ }+ validateFindingScope(finding, prefix, manifest, errors);+ if (finding.severity === 'error' && finding.disposition !== undefined) {+ errors.push(`${prefix} error findings cannot have maker-approved dispositions.`);+ } else {+ validateFindingDisposition(finding, prefix, errors, false);+ }+ valid.push(finding);+ }+ return valid;+}++function validateFindingScope(finding, prefix, manifest, errors) {+ const scopes = new Set(['locale', 'direction', 'shared', 'global']);+ if (!scopes.has(finding.scope)) {+ errors.push(`${prefix}.scope must be locale, direction, shared, or global.`);+ }+ const locales = Array.isArray(manifest.locales) ? manifest.locales : [];+ if (!Array.isArray(finding.affectedLocales) ||+ finding.affectedLocales.length === 0 ||+ finding.affectedLocales.some(+ (locale) => typeof locale !== 'string' || !locales.includes(locale)+ ) ||+ new Set(finding.affectedLocales).size !== finding.affectedLocales.length) {+ errors.push(+ `${prefix}.affectedLocales must contain unique configured locale tags.`+ );+ return;+ }+ if (finding.scope === 'global') {+ const expected = [...locales].sort();+ const actual = [...finding.affectedLocales].sort();+ if (JSON.stringify(expected) !== JSON.stringify(actual)) {+ errors.push(`${prefix} global findings must affect every configured locale.`);+ }+ }+ if (finding.scope === 'locale' && finding.affectedLocales.length !== 1) {+ errors.push(`${prefix} locale findings must affect exactly one locale.`);+ }+ if (finding.scope === 'direction') {+ if (!['ltr', 'rtl'].includes(finding.direction)) {+ errors.push(`${prefix}.direction must be ltr or rtl for direction scope.`);+ return;+ }+ const expected = locales+ .filter((locale) => getLocaleDirection(locale) === finding.direction)+ .sort();+ const actual = [...finding.affectedLocales].sort();+ if (JSON.stringify(expected) !== JSON.stringify(actual)) {+ errors.push(+ `${prefix} direction findings must affect every configured ` ++ `${finding.direction} locale.`+ );+ }+ }}function verifyInitializationEvidence(projectRoot, packageName, evidence) {@@ -968,6 +1357,46 @@ function detectLocalization(projectRoot) {if (modes.size > 1) conflicts.push('runtime and static localization packages are both installed');}+ // Preserve every source rather than only the inferred winner. A manifest can+ // claim runtime mode while stale @angular/localize/angular.json evidence+ // still leaves a dormant static implementation in the project.+ const modeEvidence = [];+ if (manifestMode) {+ modeEvidence.push({+ mode: manifestMode,+ source: MANIFEST_NAME,+ detail: `manifest mode "${manifestMode}"`,+ });+ }+ for (const packageName of packages) {+ modeEvidence.push({+ mode: KNOWN_PACKAGES[packageName].mode,+ source: 'package',+ detail: packageName,+ });+ }+ if (angularI18n) {+ modeEvidence.push({+ mode: 'static',+ source: 'angular.json',+ detail: 'Angular i18n build configuration',+ });+ }+ if (astroConfig) {+ modeEvidence.push({+ mode: 'static',+ source: astroConfig,+ detail: 'Astro i18n configuration',+ });+ }+ const detectedEvidenceModes = [...new Set(modeEvidence.map((entry) => entry.mode))];+ if (manifestMode && detectedEvidenceModes.some((mode) => mode !== manifestMode)) {+ conflicts.push(+ `manifest mode "${manifestMode}" conflicts with detected ` ++ `${detectedEvidenceModes.filter((mode) => mode !== manifestMode).join('/')} mode evidence`+ );+ }+const inferredMode = manifestMode || inferMode(packages, angularI18n, astroConfig);const inferredPackage = manifestPackage || inferPrimaryPackage(packages, astroConfig);const inferredResources = manifestResources ||@@ -1019,6 +1448,19 @@ function detectLocalization(projectRoot) {frameworkDetection.candidates.includes(manifestObject?.framework)? manifestObject.framework: null);+ const unavailableModeEvidence = implementationFramework+ ? modeEvidence.filter((entry) =>+ !getLocalizationModeAvailability(implementationFramework, entry.mode).available+ )+ : [];+ for (const mode of [...new Set(unavailableModeEvidence.map((entry) => entry.mode))]) {+ const availability = getLocalizationModeAvailability(implementationFramework, mode);+ const sources = unavailableModeEvidence+ .filter((entry) => entry.mode === mode)+ .map((entry) => entry.detail)+ .join(', ');+ conflicts.push(`${availability.reason} Detected evidence: ${sources}.`);+ }const implementation = discoverLocalizationImplementation(projectRoot,implementationFramework,@@ -1077,6 +1519,8 @@ function detectLocalization(projectRoot) {resourceDirectories: resourceCandidates,angularI18n,astroConfig: astroConfig || null,+ modeEvidence,+ unavailableModeEvidence,implementation,conflicts,};@@ -1669,6 +2113,9 @@ function inspectProject(projectRoot) {return {projectRoot: sanitizeUntrustedText(resolvedRoot, 1000),framework,+ availability: framework.framework+ ? getFrameworkLocalizationAvailability(framework.framework)+ : null,siteLanguage: safeSiteLanguage,localization: safeLocalization,};@@ -1865,11 +2312,22 @@ function runCli() {process.exitCode = result.valid ? 0 : 1;return;}+ if (args.command === 'mode-availability' && args.framework !== undefined) {+ const result = args.mode === undefined+ ? getFrameworkLocalizationAvailability(args.framework)+ : getLocalizationModeAvailability(args.framework, args.mode);+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);+ process.exitCode = args.mode === undefined+ ? (result.supported ? 0 : 1)+ : (result.available ? 0 : 1);+ return;+ }process.stderr.write('Usage: localization-config.js inspect --projectRoot <path> | ' +'detect-site-language --projectRoot <path> --framework <framework> | ' +'validate-locales --locales <comma-separated-tags> | ' +- 'resolve-locale --locale <language-tag>\n'+ 'resolve-locale --locale <language-tag> | ' ++ 'mode-availability --framework <framework> [--mode <runtime|static>]\n');process.exitCode = 1;}@@ -1889,11 +2347,15 @@ module.exports = {detectSiteLanguage,detectSiteLanguageForFramework,resolveSiteLanguageContext,+ getFrameworkLocalizationAvailability,getLocaleDirection,getLocaleMetadata,+ getLocalizationModeAvailability,inspectProject,isSafeLocaleCandidate,isSafeLocaleListCandidate,+ findLocaleAvailabilityModulePaths,+ isLocaleAvailabilityModulePath,loadRegistry,resolveProjectRelativePath,resolveLocale,diff --git a/plugins/power-pages/scripts/lib/localization-verification-profile.js b/plugins/power-pages/scripts/lib/localization-verification-profile.jsnew file mode 100644index 000000000..10bf09f82--- /dev/null+++ b/plugins/power-pages/scripts/lib/localization-verification-profile.js@@ -0,0 +1,149 @@+'use strict';++const VERIFICATION_PROFILES = new Set([+ 'standard',+ 'extensive',+ 'targeted',+]);+// Profiles that exercise the complete required matrix. `targeted` re-runs only+// selected repair cases, so its evidence can never stand in for a full run.+const FULL_VERIFICATION_PROFILES = new Set(['standard', 'extensive']);+const COMPONENT_RISKS = new Set(['low', 'medium', 'high']);++function resolveVerificationProfile(spec) {+ // Version 1 run specs predate profiles and represented the full Cartesian+ // matrix, so preserve that behavior unless a newer workflow opts into one.+ return spec?.verificationProfile || 'extensive';+}++function resolveComponentRisk(component) {+ if (COMPONENT_RISKS.has(component?.risk)) return component.risk;+ if (component?.classification === 'direction-neutral') return 'low';+ if (component?.classification === 'direction-aware') return 'medium';+ return 'high';+}++function selectRepresentativeLocales(locales, options = {}) {+ const targets = new Set(options.targetLocales || []);+ const defaultLocale = options.defaultLocale || null;+ const result = {};+ for (const direction of ['ltr', 'rtl']) {+ const candidates = locales+ .filter((locale) => locale?.direction === direction)+ .sort((left, right) =>+ compareCandidates(left, right, targets, defaultLocale)+ );+ if (candidates.length > 0) result[direction] = candidates[0].id;+ }+ return result;+}++function compareCandidates(left, right, targets, defaultLocale) {+ const leftRank = candidateRank(left, targets, defaultLocale);+ const rightRank = candidateRank(right, targets, defaultLocale);+ for (let index = 0; index < leftRank.length; index += 1) {+ if (leftRank[index] !== rightRank[index]) {+ return rightRank[index] - leftRank[index];+ }+ }+ return String(left.id).localeCompare(String(right.id));+}++function candidateRank(locale, targets, defaultLocale) {+ // A real target exercises the implementation being added. Text expansion+ // then chooses the candidate most likely to expose layout pressure; the+ // default locale is only the fallback baseline after those stronger signals.+ return [+ locale.pseudo === true ? 0 : 1,+ targets.has(locale.locale) ? 1 : 0,+ Number.isFinite(locale.textExpansion) ? locale.textExpansion : 0,+ locale.locale === defaultLocale ? 1 : 0,+ ];+}++function resolveRepresentatives(spec, localizationContext = null) {+ const selected = selectRepresentativeLocales(spec.locales || [], {+ targetLocales: localizationContext?.verificationLocales || [],+ defaultLocale: localizationContext?.defaultLocale || null,+ });+ return {+ ...selected,+ ...(spec.representativeLocaleIds || {}),+ };+}++function selectComponentDimensions(component, spec, representatives) {+ const profile = resolveVerificationProfile(spec);+ const risk = resolveComponentRisk(component);+ if (profile === 'extensive' || profile === 'targeted') {+ return {+ localeIds: spec.locales.map((locale) => locale.id),+ states: component.states,+ viewports: component.viewports,+ risk,+ };+ }++ const localeIds = [...new Set(+ ['ltr', 'rtl']+ .map((direction) => representatives[direction])+ .filter(Boolean)+ )];+ if (risk === 'low') {+ // Direction-neutral components still prove inheritance in both directions,+ // but repeating secondary states and viewports adds little layout evidence.+ return {+ localeIds,+ states: component.states.slice(0, 1),+ viewports: component.viewports.slice(0, 1),+ risk,+ };+ }+ return {+ localeIds,+ states: component.states,+ viewports: component.viewports,+ risk,+ };+}++function buildManualReviewChecklist(spec, representatives) {+ if (resolveVerificationProfile(spec) !== 'standard') return [];+ const representativeIds = new Set(Object.values(representatives));+ const remainingLocales = spec.locales.filter(+ (locale) => !locale.pseudo && !representativeIds.has(locale.id)+ );+ const complexComponents = spec.components.filter(+ (component) => resolveComponentRisk(component) === 'high'+ );+ const checks = [];+ for (const locale of remainingLocales) {+ for (const component of complexComponents) {+ checks.push({+ localeId: locale.id,+ locale: locale.locale,+ componentId: component.id,+ component: component.name,+ route: component.route,+ states: component.states.map((state) => state.name),+ viewports: [...component.viewports],+ review:+ 'Verify translated labels and values, text expansion, formatting, ' ++ 'visual clipping, and usability in the listed states and viewports.',+ });+ }+ }+ return checks;+}++module.exports = {+ COMPONENT_RISKS,+ FULL_VERIFICATION_PROFILES,+ VERIFICATION_PROFILES,+ buildManualReviewChecklist,+ resolveComponentRisk,+ resolveRepresentatives,+ resolveVerificationProfile,+ selectComponentDimensions,+ selectRepresentativeLocales,+};diff --git a/plugins/power-pages/scripts/lib/localization-verification-transaction.js b/plugins/power-pages/scripts/lib/localization-verification-transaction.jsnew file mode 100644index 000000000..4e22927f2--- /dev/null+++ b/plugins/power-pages/scripts/lib/localization-verification-transaction.js@@ -0,0 +1,1205 @@+'use strict';++const crypto = require('crypto');+const fs = require('fs');+const path = require('path');+const {+ MANIFEST_NAME,+ findLocaleAvailabilityModulePaths,+ resolveLocale,+ resolveProjectRelativePath,+ validateLocalizationManifestShape,+} = require('./localization-config');+const {+ VERIFICATION_PROFILES,+} = require('./localization-verification-profile');+const {+ quoteUntrustedText,+ sanitizeUntrustedText,+} = require('./safe-untrusted-text');+const {+ computeVerificationInputFingerprint,+} = require('./verification-evidence');++const TRANSACTION_FILE = '.powerpages-localization-verification.json';+const TRANSACTION_LOCK_FILE = `${TRANSACTION_FILE}.lock`;+const TRANSACTION_LOCK_RECOVERY_FILE = `${TRANSACTION_LOCK_FILE}.recovery`;+const TRANSACTION_AUDIT_FILE = `${TRANSACTION_FILE}.audit`;+const TRANSACTION_AVAILABILITY_FILE = `${TRANSACTION_FILE}.availability`;+const AUDIT_LEASE_CONFLICT_CODE = 'LOCALIZATION_AUDIT_LEASE_CONFLICT';+const TRANSACTION_STATES = new Set([+ 'in-progress',+ 'verified',+ 'remediation-required',+]);+const ENABLED_TARGET_STATUSES = new Set([+ 'ready',+ 'approved-with-limitations',+]);+const REVIEWABLE_TARGET_STATUSES = new Set([+ 'pending-remediation',+ ...ENABLED_TARGET_STATUSES,+]);++function readLocalizationVerificationTransaction(projectRoot) {+ const transactionPath = path.join(projectRoot, TRANSACTION_FILE);+ if (!fs.existsSync(transactionPath)) return { transaction: null, errors: [] };+ let transaction;+ try {+ transaction = JSON.parse(fs.readFileSync(transactionPath, 'utf8'));+ } catch {+ return {+ transaction: null,+ errors: [`${TRANSACTION_FILE} is not valid JSON.`],+ };+ }+ return {+ transaction,+ errors: validateTransactionShape(transaction),+ };+}++function validateTransactionShape(transaction) {+ if (!transaction || typeof transaction !== 'object' ||+ Array.isArray(transaction)) {+ return [`${TRANSACTION_FILE} must contain a JSON object.`];+ }+ const errors = [];+ if (transaction.schemaVersion !== 1) {+ errors.push(`${TRANSACTION_FILE} schemaVersion must be 1.`);+ }+ if (!TRANSACTION_STATES.has(transaction.state)) {+ errors.push(+ `${TRANSACTION_FILE} state must be "in-progress" or ` ++ '"verified" or "remediation-required".'+ );+ }+ if (transaction.verificationProfile !== undefined &&+ !VERIFICATION_PROFILES.has(transaction.verificationProfile)) {+ errors.push(+ `${TRANSACTION_FILE} verificationProfile must be standard, extensive, or targeted.`+ );+ }+ if (typeof transaction.runId !== 'string' ||+ !/^[0-9a-f-]{36}$/i.test(transaction.runId)) {+ errors.push(`${TRANSACTION_FILE} runId must be a UUID.`);+ }+ if (!isExactIsoDate(transaction.startedAt)) {+ errors.push(`${TRANSACTION_FILE} startedAt must be an ISO date-time.`);+ }+ if (transaction.state === 'verified' &&+ !isExactIsoDate(transaction.verifiedAt)) {+ errors.push(`${TRANSACTION_FILE} verifiedAt must be an ISO date-time.`);+ }+ if (transaction.state === 'verified') {+ if (!transaction.verification ||+ typeof transaction.verification !== 'object' ||+ Array.isArray(transaction.verification)) {+ errors.push(`${TRANSACTION_FILE} verified runs require verification evidence.`);+ } else if (transaction.verification.profile !==+ (transaction.verificationProfile || 'extensive')) {+ errors.push(+ `${TRANSACTION_FILE} verification evidence profile must match verificationProfile.`+ );+ }+ }+ if (transaction.state === 'remediation-required' &&+ !isExactIsoDate(transaction.failedAt)) {+ errors.push(`${TRANSACTION_FILE} failedAt must be an ISO date-time.`);+ }+ validateLocaleArray(transaction.targetLocales, 'targetLocales', errors, 1);+ validateLocaleArray(+ transaction.priorUnavailableLocales,+ 'priorUnavailableLocales',+ errors,+ 0+ );+ if (!transaction.availabilitySnapshot ||+ typeof transaction.availabilitySnapshot !== 'object' ||+ Array.isArray(transaction.availabilitySnapshot) ||+ typeof transaction.availabilitySnapshot.path !== 'string' ||+ !transaction.availabilitySnapshot.path.trim() ||+ !/^[0-9a-f]{64}$/.test(transaction.availabilitySnapshot.sha256 || '')) {+ errors.push(+ `${TRANSACTION_FILE} availabilitySnapshot must identify the captured ` ++ 'fail-closed locale availability module.'+ );+ }+ if (Array.isArray(transaction.targetLocales) &&+ Array.isArray(transaction.priorUnavailableLocales)) {+ for (const locale of transaction.targetLocales) {+ if (!transaction.priorUnavailableLocales.includes(locale)) {+ errors.push(+ `${TRANSACTION_FILE} target locale ${locale} must have been ` ++ 'unavailable when verification began.'+ );+ }+ }+ }+ return errors;+}++function validateTransactionAgainstManifest(+ transaction,+ manifest,+ options = {}+) {+ const errors = validateTransactionShape(transaction);+ if (errors.length > 0) return errors;+ const manifestLocales = new Set(manifest?.locales || []);+ const unavailable = new Set(manifest?.unavailableLocales || []);+ for (const locale of transaction.targetLocales) {+ if (!manifestLocales.has(locale)) {+ errors.push(+ `${TRANSACTION_FILE} target locale ${locale} is not configured in ` ++ `${MANIFEST_NAME}.`+ );+ continue;+ }+ const status =+ manifest?.bidirectionalReadiness?.localeReadiness?.[locale]?.status;+ if (options.requireExposed) {+ if (transaction.state !== 'in-progress') {+ errors.push(+ `${TRANSACTION_FILE} must be in-progress before rendered verification.`+ );+ }+ if (status !== 'pending-remediation') {+ errors.push(+ `${TRANSACTION_FILE} target locale ${locale} must remain ` ++ 'pending-remediation until verification passes.'+ );+ }+ if (unavailable.has(locale)) {+ errors.push(+ `${TRANSACTION_FILE} target locale ${locale} must be temporarily ` ++ 'available through the normal application path during verification.'+ );+ }+ }+ if (transaction.state === 'remediation-required' &&+ !options.requireExposed) {+ if (status !== 'pending-remediation' || !unavailable.has(locale)) {+ errors.push(+ `${TRANSACTION_FILE} failed target locale ${locale} must be restored ` ++ 'to pending-remediation and unavailable before finalization.'+ );+ }+ }+ if (transaction.state === 'verified' && !options.requireExposed) {+ const exposed = !unavailable.has(locale);+ if (options.allowVerifiedPendingReview) {+ // Phase 6 site integrity runs before the maker decides whether review+ // findings are resolved or retained, so the verified target can remain+ // temporarily exposed and pending until that decision.+ if (!REVIEWABLE_TARGET_STATUSES.has(status) || !exposed) {+ errors.push(+ `${TRANSACTION_FILE} verified target locale ${locale} must ` ++ 'remain available with a reviewable readiness status.'+ );+ }+ } else if (!isEnabledTarget(status, exposed) &&+ !isKeptUnavailableTarget(status, exposed)) {+ errors.push(+ `${TRANSACTION_FILE} verified target locale ${locale} must either ` ++ 'be ready or approved-with-limitations and available, or remain ' ++ 'pending-remediation and unavailable, before finalization.'+ );+ }+ }+ }+ const targetSet = new Set(transaction.targetLocales);+ const priorNonTargets = transaction.priorUnavailableLocales+ .filter((locale) => !targetSet.has(locale))+ .sort();+ const currentNonTargets = [...unavailable]+ .filter((locale) => !targetSet.has(locale))+ .sort();+ if (JSON.stringify(priorNonTargets) !== JSON.stringify(currentNonTargets)) {+ errors.push(+ `${TRANSACTION_FILE} cannot change the availability of locales outside ` ++ 'targetLocales.'+ );+ }+ return errors;+}++function validateVerifiedTransactionForFinalization(+ projectRoot,+ transaction,+ manifest+) {+ const errors = validateTransactionAgainstManifest(transaction, manifest);+ if (errors.length > 0) return errors;+ if (transaction.state !== 'verified') {+ return [+ `${TRANSACTION_FILE} must be verified before the final site-integrity gate.`,+ ];+ }+ return validateCurrentVerificationEvidence(projectRoot, transaction, {+ allowAvailabilityChanges:+ findKeptUnavailableTargets(transaction, manifest).length > 0,+ });+}++// After the maker decision, every verified target ends in exactly one of two+// states: enabled (ready or approved-with-limitations, and available) or kept+// unavailable (still pending-remediation and back in unavailableLocales).+// Keeping a target unavailable is the fail-closed direction, so it needs no new+// rendered evidence. The manage CLI's full validate-localization run before+// finalization separately proves that the managed availability module and+// selectors exclude every unavailable locale.+function isEnabledTarget(status, exposed) {+ return exposed && ENABLED_TARGET_STATUSES.has(status);+}++function isKeptUnavailableTarget(status, exposed) {+ return !exposed && status === 'pending-remediation';+}++function findKeptUnavailableTargets(transaction, manifest) {+ const unavailable = new Set(manifest?.unavailableLocales || []);+ const localeReadiness =+ manifest?.bidirectionalReadiness?.localeReadiness || {};+ return transaction.targetLocales.filter((locale) =>+ isKeptUnavailableTarget(+ localeReadiness[locale]?.status,+ !unavailable.has(locale)+ )+ );+}++function validateVerifiedTransactionForReview(+ projectRoot,+ transaction,+ manifest+) {+ const errors = validateTransactionAgainstManifest(transaction, manifest, {+ allowVerifiedPendingReview: true,+ });+ if (errors.length > 0) return errors;+ if (transaction.state !== 'verified') {+ return [+ `${TRANSACTION_FILE} must be verified before the final site-integrity gate.`,+ ];+ }+ return validateCurrentVerificationEvidence(projectRoot, transaction);+}++function validateCurrentVerificationEvidence(+ projectRoot,+ transaction,+ options = {}+) {+ const evidence = transaction.verification?.evidence;+ if (!evidence || evidence.schemaVersion !== 1 ||+ !/^[0-9a-f]{64}$/.test(evidence.inputFingerprint || '')) {+ return [+ `${TRANSACTION_FILE} verified evidence must contain a valid ` ++ 'project input fingerprint.',+ ];+ }+ const staleEvidenceError =+ `${TRANSACTION_FILE} rendered evidence is stale because project ` ++ 'verification inputs changed after the successful audit. Run the ' ++ 'rendered audit again before finalization.';+ if (options.allowAvailabilityChanges === true) {+ // Returning a deferred target to unavailable edits only unavailableLocales+ // and the managed availability module, so compare the fingerprint that+ // excludes exactly those inputs. Any other change is still stale.+ if (!/^[0-9a-f]{64}$/.test(+ evidence.inputFingerprintWithoutAvailability || ''+ )) {+ return [+ `${TRANSACTION_FILE} verified evidence predates finalization with ` ++ 'target locales kept unavailable. Run --fail and finalize this run, ' ++ 'or rerun the rendered audit.',+ ];+ }+ const currentFingerprint = computeVerificationInputFingerprint(+ projectRoot,+ { excludeAvailability: true }+ );+ return evidence.inputFingerprintWithoutAvailability === currentFingerprint+ ? []+ : [staleEvidenceError];+ }+ const currentFingerprint = computeVerificationInputFingerprint(projectRoot);+ if (evidence.inputFingerprint !== currentFingerprint) {+ return [staleEvidenceError];+ }+ return [];+}++function validateRenderedReviewFindingReconciliation(+ transaction,+ manifest,+ options = {}+) {+ const reviewFindings = transaction.verification?.reviewFindings;+ if (reviewFindings === undefined) return [];+ if (!Array.isArray(reviewFindings)) {+ return [+ `${TRANSACTION_FILE} rendered review findings must be an array.`,+ ];+ }+ const manifestFindings =+ manifest.bidirectionalReadiness?.renderedFindings || [];+ const unavailable = new Set(manifest.unavailableLocales || []);+ const localeReadiness =+ manifest.bidirectionalReadiness?.localeReadiness || {};+ // An open review finding may stay only while every locale it affects is kept+ // unavailable; it is then the remediation record for those hidden locales.+ const affectsOnlyUnavailableLocales = (finding) =>+ Array.isArray(finding.affectedLocales) &&+ finding.affectedLocales.length > 0 &&+ finding.affectedLocales.every((locale) =>+ isKeptUnavailableTarget(+ localeReadiness[locale]?.status,+ !unavailable.has(locale)+ )+ );+ const errors = [];+ for (const [index, finding] of reviewFindings.entries()) {+ const prefix = `${TRANSACTION_FILE} verification.reviewFindings[${index}]`;+ if (!isStoredRenderedReviewFinding(finding)) {+ errors.push(`${prefix} is malformed.`);+ continue;+ }+ const retained = manifestFindings.find((candidate) =>+ sameRenderedFinding(candidate, finding)+ );+ if (retained?.disposition?.status === 'maker-approved') continue;+ if (retained && affectsOnlyUnavailableLocales(retained)) continue;+ if (retained) {+ errors.push(+ `${prefix} remains in the manifest without a maker-approved ` ++ 'disposition while an affected locale is available.'+ );+ } else if (options.renderedReviewCompleted !== true) {+ errors.push(+ `${prefix} was removed without confirming that the maker reviewed it.`+ );+ }+ }+ return errors;+}++function isStoredRenderedReviewFinding(finding) {+ return finding &&+ typeof finding === 'object' &&+ !Array.isArray(finding) &&+ finding.severity === 'review' &&+ ['caseId', 'rule', 'message', 'selector'].every(+ (field) => typeof finding[field] === 'string' && finding[field].trim()+ );+}++function sameRenderedFinding(left, right) {+ return ['caseId', 'rule', 'severity', 'message', 'selector'].every(+ (field) => left?.[field] === right?.[field]+ );+}++function beginLocalizationVerification(+ projectRoot,+ targetLocales,+ verificationProfile = 'extensive'+) {+ return withTransactionLock(projectRoot, () => {+ const transactionPath = path.join(projectRoot, TRANSACTION_FILE);+ if (fs.existsSync(transactionPath)) {+ throw new Error(+ `${TRANSACTION_FILE} already exists. Recover or finalize that run first.`+ );+ }+ const availabilityBackupPath =+ path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE);+ if (fs.existsSync(availabilityBackupPath)) {+ fs.unlinkSync(availabilityBackupPath);+ }+ const manifest = readManifest(projectRoot);+ const manifestErrors = validateLocalizationManifestShape(+ manifest,+ projectRoot+ );+ if (manifestErrors.length > 0) {+ throw new Error(+ `${MANIFEST_NAME} must be valid before verification begins:\n- ` ++ manifestErrors.join('\n- ')+ );+ }+ const normalizedTargets = normalizeLocales(targetLocales);+ if (normalizedTargets.length === 0) {+ throw new Error('At least one target locale is required.');+ }+ if (!VERIFICATION_PROFILES.has(verificationProfile) ||+ verificationProfile === 'targeted') {+ throw new Error(+ 'New locale verification must use the standard or extensive profile.'+ );+ }+ const unavailable = new Set(manifest.unavailableLocales || []);+ for (const locale of normalizedTargets) {+ if (!manifest.locales.includes(locale)) {+ throw new Error(`Verification target ${locale} is not configured.`);+ }+ if (locale === manifest.defaultLocale) {+ throw new Error('The default locale cannot be a verification target.');+ }+ if (!unavailable.has(locale) ||+ manifest.bidirectionalReadiness.localeReadiness[locale]?.status !==+ 'pending-remediation') {+ throw new Error(+ `Verification target ${locale} must begin pending-remediation and unavailable.`+ );+ }+ }+ const availability = readLocaleAvailabilityModule(projectRoot, manifest);+ const transaction = {+ schemaVersion: 1,+ state: 'in-progress',+ runId: crypto.randomUUID(),+ startedAt: new Date().toISOString(),+ targetLocales: normalizedTargets,+ priorUnavailableLocales: [...unavailable].sort(),+ verificationProfile,+ availabilitySnapshot: {+ path: availability.relativePath,+ sha256: sha256(availability.source),+ },+ };+ publishExclusiveText(+ availabilityBackupPath,+ availability.source,+ `${TRANSACTION_AVAILABILITY_FILE} already exists.`+ );+ try {+ publishExclusiveJson(+ transactionPath,+ transaction,+ `${TRANSACTION_FILE} already exists. Recover or finalize that run first.`+ );+ } catch (error) {+ fs.unlinkSync(availabilityBackupPath);+ throw error;+ }+ return transaction;+ });+}++function extendLocalizationVerification(+ projectRoot,+ verificationProfile = 'extensive'+) {+ return withTransactionLock(projectRoot, () => {+ const transaction = readCurrentTransaction(projectRoot);+ if (transaction.state !== 'verified' ||+ (transaction.verificationProfile || 'extensive') !== 'standard' ||+ verificationProfile !== 'extensive') {+ throw new Error(+ 'Only a verified standard run can be extended to extensive verification.'+ );+ }+ const updated = {+ ...transaction,+ state: 'in-progress',+ verificationProfile,+ extendedAt: new Date().toISOString(),+ };+ delete updated.verifiedAt;+ delete updated.verification;+ atomicWriteJson(path.join(projectRoot, TRANSACTION_FILE), updated);+ return updated;+ });+}++function beginLocalizationVerificationAudit(projectRoot, expectedRunId) {+ return withTransactionLock(projectRoot, () => {+ const transaction = readCurrentTransaction(projectRoot, expectedRunId);+ if (transaction.state !== 'in-progress') {+ throw new Error(+ `${TRANSACTION_FILE} must be in-progress before its audit can begin.`+ );+ }+ const lease = {+ runId: transaction.runId,+ processId: process.pid,+ startedAt: new Date().toISOString(),+ };+ publishExclusiveJson(+ path.join(projectRoot, TRANSACTION_AUDIT_FILE),+ lease,+ `${TRANSACTION_AUDIT_FILE} already exists. Recover that audit first.`,+ AUDIT_LEASE_CONFLICT_CODE+ );+ return lease;+ });+}++function endLocalizationVerificationAudit(projectRoot, expectedRunId) {+ return withTransactionLock(projectRoot, () => {+ const lease = readAuditLease(projectRoot);+ if (!lease) return;+ if (lease.runId !== expectedRunId) {+ throw new Error(+ `${TRANSACTION_AUDIT_FILE} belongs to a different verification run.`+ );+ }+ fs.unlinkSync(path.join(projectRoot, TRANSACTION_AUDIT_FILE));+ });+}++function markLocalizationVerificationFailed(projectRoot, expectedRunId = null) {+ return withTransactionLock(projectRoot, () => {+ const transaction = readCurrentTransaction(projectRoot, expectedRunId);+ const manualRestore =+ restoreFailClosedAvailability(projectRoot, transaction);+ const updated = transaction.state === 'remediation-required'+ ? { ...transaction }+ : {+ ...transaction,+ state: 'remediation-required',+ failedAt: new Date().toISOString(),+ };+ delete updated.verifiedAt;+ delete updated.verification;+ // Persist the manual step so a repeated --fail, the audit runner, or a+ // person inspecting the transaction can still see which locales to hide.+ if (manualRestore) {+ updated.manualAvailabilityRestore = manualRestore;+ } else {+ delete updated.manualAvailabilityRestore;+ }+ atomicWriteJson(path.join(projectRoot, TRANSACTION_FILE), updated);+ return updated;+ });+}++function markLocalizationVerificationPassed(+ projectRoot,+ expectedRunId = null,+ verification = null+) {+ return withTransactionLock(projectRoot, () => {+ const transaction = readCurrentTransaction(projectRoot, expectedRunId);+ if (transaction.state !== 'in-progress') {+ throw new Error(+ `${TRANSACTION_FILE} must be in-progress before it can be verified.`+ );+ }+ if (!verification ||+ verification.profile !==+ (transaction.verificationProfile || 'extensive')) {+ throw new Error(+ `${TRANSACTION_FILE} requires verification evidence for its active profile.`+ );+ }+ const updated = {+ ...transaction,+ state: 'verified',+ verifiedAt: new Date().toISOString(),+ verification,+ };+ atomicWriteJson(path.join(projectRoot, TRANSACTION_FILE), updated);+ return updated;+ });+}++function finalizeLocalizationVerification(projectRoot, options = {}) {+ return withTransactionLock(projectRoot, () => {+ const transaction = readCurrentTransaction(projectRoot);+ const lease = readAuditLease(projectRoot);+ if (lease) {+ throw new Error(+ `${TRANSACTION_AUDIT_FILE} shows that rendered verification is still ` ++ 'active or was abandoned. Mark the run failed before finalization.'+ );+ }+ const manifest = readManifest(projectRoot);+ const manifestErrors = validateLocalizationManifestShape(manifest);+ if (manifestErrors.length > 0) {+ throw new Error(+ `${MANIFEST_NAME} must be fully reconciled before finalization:\n- ` ++ manifestErrors.join('\n- ')+ );+ }+ const relationErrors = transaction.state === 'verified'+ ? validateVerifiedTransactionForFinalization(+ projectRoot,+ transaction,+ manifest+ )+ : validateTransactionAgainstManifest(transaction, manifest);+ if (relationErrors.length > 0) {+ throw new Error(relationErrors.join('\n'));+ }+ if (transaction.state === 'in-progress') {+ throw new Error(+ `${TRANSACTION_FILE} cannot be finalized before the rendered audit ` ++ 'records a verified or remediation-required result.'+ );+ }+ const manualReview = transaction.verification?.manualReview || [];+ if ((transaction.verificationProfile || 'extensive') === 'standard' &&+ manualReview.length > 0 &&+ options.manualReviewCompleted !== true) {+ throw new Error(+ `${TRANSACTION_FILE} standard verification requires the maker to ` ++ 'complete the generated complex-component locale review or extend the ' ++ 'run to extensive verification.'+ );+ }+ const reviewErrors = validateRenderedReviewFindingReconciliation(+ transaction,+ manifest,+ options+ );+ if (reviewErrors.length > 0) {+ throw new Error(reviewErrors.join('\n'));+ }+ if (options.manualReviewCompleted === true) {+ transaction.manualReviewCompletedAt = new Date().toISOString();+ }+ if (options.renderedReviewCompleted === true) {+ transaction.renderedReviewCompletedAt = new Date().toISOString();+ }+ fs.unlinkSync(path.join(projectRoot, TRANSACTION_FILE));+ const availabilityBackupPath =+ path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE);+ if (fs.existsSync(availabilityBackupPath)) {+ fs.unlinkSync(availabilityBackupPath);+ }+ return transaction;+ });+}++function listVerificationTransactionArtifacts(projectRoot) {+ return fs.readdirSync(projectRoot).filter((name) =>+ name === TRANSACTION_FILE ||+ name === TRANSACTION_LOCK_FILE ||+ name === TRANSACTION_LOCK_RECOVERY_FILE ||+ name === TRANSACTION_AUDIT_FILE ||+ name === TRANSACTION_AVAILABILITY_FILE ||+ name.startsWith(`${TRANSACTION_FILE}.candidate-`) ||+ name.startsWith(`${TRANSACTION_LOCK_FILE}.candidate-`)+ );+}++function abandonLocalizationVerificationAudit(projectRoot, expectedRunId) {+ endLocalizationVerificationAudit(projectRoot, expectedRunId);+}++function readAuditLease(projectRoot) {+ const auditPath = path.join(projectRoot, TRANSACTION_AUDIT_FILE);+ if (!fs.existsSync(auditPath)) return null;+ let lease;+ try {+ lease = JSON.parse(fs.readFileSync(auditPath, 'utf8'));+ } catch {+ throw new Error(`${TRANSACTION_AUDIT_FILE} is not valid JSON.`);+ }+ if (!lease || typeof lease !== 'object' || Array.isArray(lease) ||+ typeof lease.runId !== 'string' ||+ !Number.isInteger(lease.processId) ||+ !isExactIsoDate(lease.startedAt)) {+ throw new Error(`${TRANSACTION_AUDIT_FILE} is invalid.`);+ }+ return lease;+}++function readCurrentTransaction(projectRoot, expectedRunId = null) {+ const { transaction, errors } =+ readLocalizationVerificationTransaction(projectRoot);+ if (errors.length > 0) throw new Error(errors.join('\n'));+ if (!transaction) {+ throw new Error(`${TRANSACTION_FILE} does not exist.`);+ }+ if (expectedRunId && transaction.runId !== expectedRunId) {+ throw new Error(+ `${TRANSACTION_FILE} runId changed while the rendered audit was running.`+ );+ }+ return transaction;+}++function withTransactionLock(projectRoot, operation) {+ const lockPath = path.join(projectRoot, TRANSACTION_LOCK_FILE);+ const owner = {+ schemaVersion: 1,+ processId: process.pid,+ token: crypto.randomUUID(),+ createdAt: new Date().toISOString(),+ };+ let acquired = false;+ for (let attempt = 0; attempt < 200; attempt += 1) {+ const recoveryPath =+ path.join(projectRoot, TRANSACTION_LOCK_RECOVERY_FILE);+ if (fs.existsSync(recoveryPath)) {+ recoverAbandonedTransactionLock(projectRoot);+ if (fs.existsSync(recoveryPath)) {+ Atomics.wait(+ new Int32Array(new SharedArrayBuffer(4)),+ 0,+ 0,+ 10+ );+ continue;+ }+ }+ if (tryAcquireTransactionLock(lockPath, owner)) {+ acquired = true;+ break;+ }+ recoverAbandonedTransactionLock(projectRoot);+ Atomics.wait(+ new Int32Array(new SharedArrayBuffer(4)),+ 0,+ 0,+ 10+ );+ }+ if (!acquired) {+ throw new Error(`${TRANSACTION_FILE} is busy; retry the operation.`);+ }+ try {+ return operation();+ } finally {+ removeOwnedTransactionLock(lockPath, owner.token);+ }+}++function tryAcquireTransactionLock(lockPath, owner) {+ const candidate =+ `${lockPath}.candidate-${process.pid}-${crypto.randomUUID()}`;+ writeSyncedFile(candidate, `${JSON.stringify(owner)}\n`);+ try {+ fs.linkSync(candidate, lockPath);+ return true;+ } catch (error) {+ if (error.code === 'EEXIST') return false;+ throw error;+ } finally {+ if (fs.existsSync(candidate)) fs.unlinkSync(candidate);+ }+}++function recoverAbandonedTransactionLock(projectRoot) {+ const lockPath = path.join(projectRoot, TRANSACTION_LOCK_FILE);+ const recoveryPath =+ path.join(projectRoot, TRANSACTION_LOCK_RECOVERY_FILE);+ if (fs.existsSync(recoveryPath)) {+ return finishTransactionLockRecovery(lockPath, recoveryPath);+ }+ if (!fs.existsSync(lockPath)) return false;+ const owner = readTransactionLockOwner(lockPath);+ if (!owner || isProcessRunning(owner.processId)) return false;+ try {+ // The fixed recovery hard link is an atomic claim. Every contender honors+ // it, so only one process can retire this exact abandoned lock.+ fs.linkSync(lockPath, recoveryPath);+ } catch (error) {+ if (error.code === 'EEXIST' || error.code === 'ENOENT') return false;+ throw error;+ }+ return finishTransactionLockRecovery(lockPath, recoveryPath);+}++function finishTransactionLockRecovery(lockPath, recoveryPath) {+ const owner = readTransactionLockOwner(recoveryPath);+ if (!owner || isProcessRunning(owner.processId)) return false;+ if (fs.existsSync(lockPath) &&+ pathsReferenceSameLock(lockPath, recoveryPath)) {+ fs.unlinkSync(lockPath);+ }+ fs.unlinkSync(recoveryPath);+ return true;+}++function pathsReferenceSameLock(lockPath, recoveryPath) {+ const lockOwner = readTransactionLockOwner(lockPath);+ const recoveryOwner = readTransactionLockOwner(recoveryPath);+ if (lockOwner?.token && recoveryOwner?.token) {+ return lockOwner.token === recoveryOwner.token;+ }+ const lockStat = fs.statSync(lockPath);+ const recoveryStat = fs.statSync(recoveryPath);+ return lockStat.dev === recoveryStat.dev && lockStat.ino === recoveryStat.ino;+}++function readTransactionLockOwner(lockPath) {+ let content;+ try {+ content = fs.readFileSync(lockPath, 'utf8').trim();+ } catch (error) {+ if (error.code === 'ENOENT') return null;+ throw error;+ }+ if (/^\d+$/.test(content)) {+ return { processId: Number(content), token: null };+ }+ try {+ const owner = JSON.parse(content);+ if (!owner || owner.schemaVersion !== 1 ||+ !Number.isInteger(owner.processId) || owner.processId <= 0 ||+ typeof owner.token !== 'string' ||+ !/^[0-9a-f-]{36}$/i.test(owner.token) ||+ !isExactIsoDate(owner.createdAt)) {+ return null;+ }+ return owner;+ } catch {+ return null;+ }+}++function isProcessRunning(processId) {+ if (processId === process.pid) return true;+ try {+ process.kill(processId, 0);+ return true;+ } catch (error) {+ if (error.code === 'ESRCH' || error.code === 'EINVAL') return false;+ return true;+ }+}++function removeOwnedTransactionLock(lockPath, token) {+ const owner = readTransactionLockOwner(lockPath);+ if (owner?.token !== token) return;+ try {+ fs.unlinkSync(lockPath);+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ }+}++function readManifest(projectRoot) {+ const manifestPath = path.join(projectRoot, MANIFEST_NAME);+ let manifest;+ try {+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ } catch {+ throw new Error(`${MANIFEST_NAME} is missing or is not valid JSON.`);+ }+ return manifest;+}++function normalizeLocales(locales) {+ if (!Array.isArray(locales)) return [];+ const normalized = [];+ for (const value of locales) {+ const resolved = resolveLocale(value);+ if (!resolved.valid || !resolved.locale) {+ throw new Error(`Invalid verification target locale: ${value}`);+ }+ if (!normalized.includes(resolved.locale)) normalized.push(resolved.locale);+ }+ return normalized.sort();+}++function readLocaleAvailabilityModule(projectRoot, manifest) {+ const availabilityPaths = findLocaleAvailabilityModulePaths(manifest);+ if (availabilityPaths.length !== 1) {+ throw new Error(+ 'Verification requires exactly one managed locale availability module.'+ );+ }+ const relativePath = availabilityPaths[0];+ const resolved = resolveProjectRelativePath(projectRoot, relativePath);+ if (!resolved.valid || !fs.existsSync(resolved.path)) {+ throw new Error(+ `Locale availability module ${relativePath} is missing or unsafe.`+ );+ }+ return {+ relativePath,+ source: fs.readFileSync(resolved.path, 'utf8'),+ };+}++// `--fail` must leave every target locale fail-closed, but the transaction file+// and its `.availability` backup are ordinary project files that can be+// deleted, edited, or crafted. The only file this function may write is the+// managed locale availability module that the manifest identifies by name, and+// only with backup content whose checksum still matches the transaction. In+// every other case it writes no source file and returns a manual-restore+// description; the manage CLI's full validate-localization run then blocks+// finalization until that module excludes every target locale again.+function restoreFailClosedAvailability(projectRoot, transaction) {+ const manifest = readManifest(projectRoot);+ const plan = planAvailabilityRestore(projectRoot, transaction, manifest);+ if (plan.automatic) {+ // Restore the runtime boundary before metadata so any interrupted rollback+ // leaves the locale inaccessible even if the manifest update has not landed.+ atomicWriteText(plan.path, plan.source);+ }++ const localeReadiness =+ manifest?.bidirectionalReadiness?.localeReadiness;+ if (!localeReadiness || typeof localeReadiness !== 'object' ||+ Array.isArray(localeReadiness)) {+ throw new Error(+ `${MANIFEST_NAME} does not contain locale readiness state to restore.`+ );+ }+ const unavailable = new Set([+ ...(Array.isArray(manifest.unavailableLocales)+ ? manifest.unavailableLocales+ : []),+ ...transaction.priorUnavailableLocales,+ ...transaction.targetLocales,+ ]);+ const restoredLocaleReadiness = { ...localeReadiness };+ for (const locale of transaction.targetLocales) {+ restoredLocaleReadiness[locale] = {+ ...(restoredLocaleReadiness[locale] || {}),+ status: 'pending-remediation',+ };+ }+ const restoredManifest = {+ ...manifest,+ unavailableLocales: [...unavailable].sort(),+ bidirectionalReadiness: {+ ...manifest.bidirectionalReadiness,+ status: 'pending-remediation',+ localeReadiness: restoredLocaleReadiness,+ },+ updatedAt: new Date().toISOString(),+ };+ atomicWriteJson(path.join(projectRoot, MANIFEST_NAME), restoredManifest);+ return plan.automatic+ ? null+ : {+ // Informational only and later shown to the agent, so bound and+ // neutralize the project-controlled path rather than trusting it.+ path: plan.relativePath === null+ ? null+ : sanitizeUntrustedText(plan.relativePath, 300),+ locales: [...transaction.targetLocales],+ reason: plan.reason,+ };+}++function planAvailabilityRestore(projectRoot, transaction, manifest) {+ const manual = (relativePath, reason) => ({+ automatic: false,+ relativePath,+ reason,+ });+ const candidates = findLocaleAvailabilityModulePaths(manifest);+ if (candidates.length !== 1) {+ return manual(+ null,+ `${MANIFEST_NAME} does not identify exactly one managed locale ` ++ 'availability module'+ );+ }+ const relativePath = candidates[0];+ const portablePath = toPortableRelativePath(relativePath);+ // Hidden directories such as .git or .github hold tooling state and+ // configuration, never site source, so they are never restore targets.+ if (portablePath.split('/').some((segment) => segment.startsWith('.'))) {+ return manual(+ relativePath,+ 'the managed locale availability module is inside a hidden directory'+ );+ }+ const target = resolveProjectRelativePath(projectRoot, relativePath);+ if (!target.valid) {+ return manual(+ relativePath,+ 'the managed locale availability module path is unsafe'+ );+ }+ if (!isMissingOrRegularFile(target.path)) {+ return manual(+ relativePath,+ 'the managed locale availability module is not a regular file'+ );+ }+ const snapshot = transaction.availabilitySnapshot;+ if (toPortableRelativePath(snapshot.path) !== portablePath) {+ return manual(+ relativePath,+ `the ${TRANSACTION_FILE} snapshot path does not match the managed ` ++ 'locale availability module'+ );+ }+ const backupPath = path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE);+ const backupState = regularFileState(backupPath);+ if (backupState !== 'file') {+ return manual(+ relativePath,+ backupState === 'missing'+ ? `${TRANSACTION_AVAILABILITY_FILE} is missing`+ : `${TRANSACTION_AVAILABILITY_FILE} is not a regular file`+ );+ }+ const source = fs.readFileSync(backupPath, 'utf8');+ if (sha256(source) !== snapshot.sha256) {+ return manual(+ relativePath,+ `${TRANSACTION_AVAILABILITY_FILE} no longer matches its recorded checksum`+ );+ }+ return { automatic: true, path: target.path, relativePath, source };+}++function toPortableRelativePath(relativePath) {+ return path.posix.normalize(String(relativePath).replace(/\\/g, '/'));+}++// lstat (not stat) so a symbolic link is never treated as the file it targets.+function regularFileState(filePath) {+ try {+ return fs.lstatSync(filePath).isFile() ? 'file' : 'other';+ } catch (error) {+ if (error.code === 'ENOENT') return 'missing';+ throw error;+ }+}++function isMissingOrRegularFile(filePath) {+ return regularFileState(filePath) !== 'other';+}++// Values read back from the transaction file are project-controlled, so every+// field is bounded and neutralized before it reaches agent-visible output.+function formatManualAvailabilityRestore(transaction) {+ const restore = transaction?.manualAvailabilityRestore;+ if (!restore || typeof restore !== 'object') return null;+ const locales = Array.isArray(restore.locales)+ ? restore.locales.map((locale) => quoteUntrustedText(locale, 100))+ .join(', ')+ : 'the transaction target locales';+ const target = restore.path+ ? quoteUntrustedText(restore.path, 300)+ : 'the managed locale availability module';+ return 'Automatic locale availability restore was skipped because ' ++ `${quoteUntrustedText(restore.reason, 300)}. Exclude ${locales} in ` ++ `${target}, then run --finalize; finalization validates that every ` ++ 'unavailable locale is excluded.';+}++function sha256(value) {+ return crypto.createHash('sha256').update(value, 'utf8').digest('hex');+}++function validateLocaleArray(value, field, errors, minimumLength) {+ if (!Array.isArray(value) || value.length < minimumLength) {+ errors.push(+ `${TRANSACTION_FILE} ${field} must be an array containing at least ` ++ `${minimumLength} locale${minimumLength === 1 ? '' : 's'}.`+ );+ return;+ }+ const normalized = [];+ for (const locale of value) {+ const resolved = resolveLocale(locale);+ if (!resolved.valid || resolved.locale !== locale) {+ errors.push(+ `${TRANSACTION_FILE} ${field} must contain canonical BCP-47 locale tags.`+ );+ return;+ }+ normalized.push(locale);+ }+ if (new Set(normalized).size !== normalized.length) {+ errors.push(`${TRANSACTION_FILE} ${field} must not contain duplicates.`);+ }+}++function isExactIsoDate(value) {+ if (typeof value !== 'string' || !value.trim()) return false;+ const normalized = value.includes('.')+ ? value+ : value.replace(/Z$/, '.000Z');+ return Number.isFinite(Date.parse(value)) &&+ new Date(value).toISOString() === normalized;+}++function publishExclusiveJson(+ filePath,+ value,+ existsMessage,+ existsCode = null+) {+ publishExclusiveText(+ filePath,+ `${JSON.stringify(value, null, 2)}\n`,+ existsMessage,+ existsCode+ );+}++function publishExclusiveText(+ filePath,+ content,+ existsMessage,+ existsCode = null+) {+ const candidate = `${filePath}.candidate-${process.pid}-${crypto.randomUUID()}`;+ writeSyncedFile(candidate, content);+ try {+ fs.linkSync(candidate, filePath);+ } catch (error) {+ if (error.code === 'EEXIST') {+ const existsError = new Error(existsMessage);+ if (existsCode) existsError.code = existsCode;+ throw existsError;+ }+ throw error;+ } finally {+ if (fs.existsSync(candidate)) fs.unlinkSync(candidate);+ }+}++function atomicWriteJson(filePath, value) {+ atomicWriteText(filePath, `${JSON.stringify(value, null, 2)}\n`);+}++function atomicWriteText(filePath, content) {+ const candidate = `${filePath}.candidate-${process.pid}-${crypto.randomUUID()}`;+ writeSyncedFile(candidate, content);+ try {+ fs.renameSync(candidate, filePath);+ } finally {+ if (fs.existsSync(candidate)) fs.unlinkSync(candidate);+ }+}++function writeSyncedFile(filePath, content) {+ const descriptor = fs.openSync(filePath, 'wx');+ try {+ fs.writeFileSync(descriptor, content, 'utf8');+ fs.fsyncSync(descriptor);+ } finally {+ fs.closeSync(descriptor);+ }+}++module.exports = {+ AUDIT_LEASE_CONFLICT_CODE,+ TRANSACTION_AUDIT_FILE,+ TRANSACTION_AVAILABILITY_FILE,+ TRANSACTION_FILE,+ TRANSACTION_LOCK_FILE,+ TRANSACTION_LOCK_RECOVERY_FILE,+ abandonLocalizationVerificationAudit,+ beginLocalizationVerificationAudit,+ beginLocalizationVerification,+ extendLocalizationVerification,+ endLocalizationVerificationAudit,+ finalizeLocalizationVerification,+ formatManualAvailabilityRestore,+ listVerificationTransactionArtifacts,+ markLocalizationVerificationFailed,+ markLocalizationVerificationPassed,+ recoverAbandonedTransactionLock,+ readLocalizationVerificationTransaction,+ validateTransactionAgainstManifest,+ validateVerifiedTransactionForFinalization,+ validateVerifiedTransactionForReview,+ validateTransactionShape,+};diff --git a/plugins/power-pages/scripts/lib/rendered-bidirectional-readiness.js b/plugins/power-pages/scripts/lib/rendered-bidirectional-readiness.jsnew file mode 100644index 000000000..f14be9ed3--- /dev/null+++ b/plugins/power-pages/scripts/lib/rendered-bidirectional-readiness.js@@ -0,0 +1,2146 @@+'use strict';++const fs = require('fs');+const path = require('path');+const {+ resolveLocale,+} = require('./localization-config');+const {+ COMPONENT_RISKS,+ VERIFICATION_PROFILES,+ buildManualReviewChecklist,+ resolveRepresentatives,+ resolveVerificationProfile,+ selectComponentDimensions,+} = require('./localization-verification-profile');++const CLASSIFICATIONS = new Set([+ 'direction-neutral',+ 'direction-aware',+ 'direction-fixed',+ 'unknown-third-party',+]);+const DIRECTIONS = new Set(['ltr', 'rtl']);+const PRESERVATION_KINDS = new Set([+ 'attribute',+ 'auto',+ 'checked',+ 'property',+ 'text',+ 'value',+]);+const ACTION_TYPES = new Set([+ 'activate-locale',+ 'check',+ 'click',+ 'fill',+ 'focus',+ 'hover',+ 'navigate',+ 'press',+ 'select',+ 'set-attribute',+ 'set-document',+ 'uncheck',+ 'use-current',+ 'wait',+]);+const STATE_ISOLATION = new Set(['isolated', 'reload', 'resettable']);+const DEFAULT_MAX_CONCURRENCY = 3;+const MAX_CONCURRENCY = 8;+const LOOPBACK_HOSTNAMES = new Set([+ 'localhost',+ '127.0.0.1',+ '[::1]',+]);++function validateRunSpec(spec, localizationContext = null) {+ const errors = [];+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {+ return ['The rendered bidirectional run specification must be an object.'];+ }+ if (spec.version !== 1) errors.push('version must be 1.');+ const verificationProfile = resolveVerificationProfile(spec);+ if (!VERIFICATION_PROFILES.has(verificationProfile)) {+ errors.push(+ 'verificationProfile must be standard, extensive, or targeted when provided.'+ );+ }+ if (spec.runtimeSwitching !== undefined &&+ typeof spec.runtimeSwitching !== 'boolean') {+ errors.push('runtimeSwitching must be boolean when provided.');+ }+ if (spec.maxConcurrency !== undefined &&+ (!Number.isInteger(spec.maxConcurrency) ||+ spec.maxConcurrency < 1 ||+ spec.maxConcurrency > MAX_CONCURRENCY)) {+ errors.push(+ `maxConcurrency must be an integer from 1 through ${MAX_CONCURRENCY}.`+ );+ }+ const viewports = Array.isArray(spec.viewports) ? spec.viewports : [];+ const locales = Array.isArray(spec.locales) ? spec.locales : [];+ const components = Array.isArray(spec.components) ? spec.components : [];+ const unavailableLocaleChecks = Array.isArray(spec.unavailableLocaleChecks)+ ? spec.unavailableLocaleChecks+ : [];+ const unavailableLocales = new Set(+ Array.isArray(localizationContext?.unavailableLocales)+ ? localizationContext.unavailableLocales+ : []+ );+ const verificationLocales = new Set(+ Array.isArray(localizationContext?.verificationLocales)+ ? localizationContext.verificationLocales+ : []+ );+ if (viewports.length === 0) errors.push('viewports must contain at least one viewport.');+ if (locales.length < 2) errors.push('locales must contain LTR and RTL verification locales.');+ if (components.length === 0) errors.push('components must contain the reconciled review scope.');++ const viewportNames = new Set();+ for (const [index, viewport] of viewports.entries()) {+ const prefix = `viewports[${index}]`;+ if (!isNonEmpty(viewport?.name)) errors.push(`${prefix}.name is required.`);+ if (viewportNames.has(viewport?.name)) errors.push(`${prefix}.name must be unique.`);+ viewportNames.add(viewport?.name);+ if (!Number.isInteger(viewport?.width) || viewport.width < 240) {+ errors.push(`${prefix}.width must be an integer of at least 240.`);+ }+ if (!Number.isInteger(viewport?.height) || viewport.height < 240) {+ errors.push(`${prefix}.height must be an integer of at least 240.`);+ }+ }++ const localeIds = new Set();+ const directions = new Set();+ for (const [index, locale] of locales.entries()) {+ const prefix = `locales[${index}]`;+ if (!isNonEmpty(locale?.id)) errors.push(`${prefix}.id is required.`);+ if (localeIds.has(locale?.id)) errors.push(`${prefix}.id must be unique.`);+ localeIds.add(locale?.id);+ if (!isNonEmpty(locale?.locale)) errors.push(`${prefix}.locale is required.`);+ if (!locale?.pseudo && isNonEmpty(locale?.locale)) {+ const resolved = resolveLocale(locale.locale);+ if (!resolved.valid || !resolved.locale) {+ errors.push(`${prefix}.locale must be a valid BCP-47 locale tag.`);+ } else if (resolved.direction !== locale.direction) {+ errors.push(+ `${prefix}.direction must be ${resolved.direction} for ${resolved.locale}.`+ );+ }+ }+ if (!DIRECTIONS.has(locale?.direction)) {+ errors.push(`${prefix}.direction must be ltr or rtl.`);+ } else {+ directions.add(locale.direction);+ }+ validateActions(locale?.activate, `${prefix}.activate`, errors);+ if (locale?.pseudo !== undefined && typeof locale.pseudo !== 'boolean') {+ errors.push(`${prefix}.pseudo must be boolean when provided.`);+ }+ if (locale?.textExpansion !== undefined &&+ (!Number.isFinite(locale.textExpansion) || locale.textExpansion < 0)) {+ errors.push(`${prefix}.textExpansion must be a non-negative number.`);+ }+ const activation = asArray(locale?.activate);+ if (locale?.pseudo === true) {+ if (!activation.some((action) => action.type === 'set-document')) {+ errors.push(`${prefix} pseudo locales require a set-document action.`);+ }+ } else {+ if (activation.length === 0) {+ errors.push(`${prefix} real locales require application-driven activation.`);+ }+ if (activation.some((action) => action.type === 'set-document')) {+ errors.push(`${prefix} real locales cannot use set-document.`);+ }+ if (activation.some((action) => action.type === 'set-attribute')) {+ errors.push(+ `${prefix} real locales cannot use set-attribute to synthesize ` ++ 'locale evidence.'+ );+ }+ if (!Array.isArray(locale?.expect) || locale.expect.length === 0) {+ errors.push(`${prefix} real locales require localized content expectations.`);+ }+ if (verificationLocales.has(locale.locale)) {+ const localeActivations = activation.filter(+ (action) => action.type === 'activate-locale'+ );+ if (localeActivations.length !== 1 ||+ localeActivations[0].locale !== locale.locale) {+ errors.push(+ `${prefix} verification targets require exactly one ` ++ `activate-locale action for ${locale.locale}.`+ );+ }+ if (activation.some(+ (action) => !['activate-locale', 'wait'].includes(action.type)+ )) {+ errors.push(+ `${prefix} verification target activation may contain only ` ++ 'activate-locale and wait actions.'+ );+ }+ }+ if (unavailableLocales.has(locale.locale) &&+ localizationContext) {+ errors.push(+ `${prefix} unavailable locales cannot be included as rendered ` ++ 'verification locales.'+ );+ }+ }+ if (locale?.expect !== undefined && !Array.isArray(locale.expect)) {+ errors.push(`${prefix}.expect must be an array.`);+ }+ for (const [expectIndex, expectation] of asArray(locale?.expect).entries()) {+ const expectPrefix = `${prefix}.expect[${expectIndex}]`;+ if (!isNonEmpty(expectation?.selector)) {+ errors.push(`${expectPrefix}.selector is required.`);+ }+ if (!isNonEmpty(expectation?.text) &&+ !(isNonEmpty(expectation?.attribute) && typeof expectation?.value === 'string')) {+ errors.push(+ `${expectPrefix} requires text, or an attribute and string value.`+ );+ }+ }+ }+ if (!directions.has('ltr') || !directions.has('rtl')) {+ errors.push('locales must include at least one LTR and one RTL verification locale.');+ }+ if (spec.representativeLocaleIds !== undefined) {+ if (!spec.representativeLocaleIds ||+ typeof spec.representativeLocaleIds !== 'object' ||+ Array.isArray(spec.representativeLocaleIds)) {+ errors.push('representativeLocaleIds must be an object when provided.');+ } else {+ for (const direction of ['ltr', 'rtl']) {+ const localeId = spec.representativeLocaleIds[direction];+ if (localeId === undefined) continue;+ const locale = locales.find((candidate) => candidate.id === localeId);+ if (!locale) {+ errors.push(+ `representativeLocaleIds.${direction} references unknown locale "${localeId}".`+ );+ } else if (locale.direction !== direction) {+ errors.push(+ `representativeLocaleIds.${direction} must reference a ${direction} locale.`+ );+ }+ }+ }+ }+ if (spec.localeSmoke !== undefined) {+ if (!spec.localeSmoke ||+ typeof spec.localeSmoke !== 'object' ||+ Array.isArray(spec.localeSmoke)) {+ errors.push('localeSmoke must be an object when provided.');+ } else {+ if (!isNonEmpty(spec.localeSmoke.route) ||+ !spec.localeSmoke.route.startsWith('/')) {+ errors.push('localeSmoke.route must start with "/".');+ }+ if (!viewportNames.has(spec.localeSmoke.viewport)) {+ errors.push('localeSmoke.viewport must reference a configured viewport.');+ }+ }+ }+ if (verificationProfile === 'targeted') {+ validateStringArray(spec.targetCaseIds, 'targetCaseIds', errors, 1);+ } else if (spec.targetCaseIds !== undefined) {+ errors.push('targetCaseIds is valid only for targeted verification.');+ }++ if (spec.unavailableLocaleChecks !== undefined &&+ !Array.isArray(spec.unavailableLocaleChecks)) {+ errors.push('unavailableLocaleChecks must be an array when provided.');+ }+ const checkedUnavailableLocales = new Set();+ for (const [index, check] of unavailableLocaleChecks.entries()) {+ const prefix = `unavailableLocaleChecks[${index}]`;+ if (!isNonEmpty(check?.locale)) {+ errors.push(`${prefix}.locale is required.`);+ } else if (checkedUnavailableLocales.has(check.locale)) {+ errors.push(`${prefix}.locale must be unique.`);+ } else {+ checkedUnavailableLocales.add(check.locale);+ }+ validateStringArray(check?.selectors, `${prefix}.selectors`, errors, 1);+ }++ const componentIds = new Set();+ for (const [index, component] of components.entries()) {+ const prefix = `components[${index}]`;+ if (!isNonEmpty(component?.id)) errors.push(`${prefix}.id is required.`);+ if (componentIds.has(component?.id)) errors.push(`${prefix}.id must be unique.`);+ componentIds.add(component?.id);+ if (!isNonEmpty(component?.name)) errors.push(`${prefix}.name is required.`);+ if (!CLASSIFICATIONS.has(component?.classification)) {+ errors.push(`${prefix}.classification is invalid.`);+ }+ if (component?.risk !== undefined && !COMPONENT_RISKS.has(component.risk)) {+ errors.push(`${prefix}.risk must be low, medium, or high.`);+ }+ if (!isNonEmpty(component?.route) || !component.route.startsWith('/')) {+ errors.push(`${prefix}.route must start with "/".`);+ }+ if (!isNonEmpty(component?.selector)) errors.push(`${prefix}.selector is required.`);+ if (component?.classification === 'direction-fixed' && !isNonEmpty(component?.reason)) {+ errors.push(`${prefix}.reason is required for direction-fixed components.`);+ }+ const states = Array.isArray(component?.states) ? component.states : [];+ if (states.length === 0) errors.push(`${prefix}.states must not be empty.`);+ const stateNames = new Set();+ for (const [stateIndex, state] of states.entries()) {+ const statePrefix = `${prefix}.states[${stateIndex}]`;+ if (!isNonEmpty(state?.name)) {+ errors.push(`${statePrefix}.name is required.`);+ } else if (stateNames.has(state.name)) {+ errors.push(+ `${statePrefix}.name duplicates state name "${state.name}" ` ++ `within ${prefix}.states.`+ );+ } else {+ stateNames.add(state.name);+ }+ validateActions(state?.setup, `${statePrefix}.setup`, errors);+ if (state?.isolation !== undefined &&+ !STATE_ISOLATION.has(state.isolation)) {+ errors.push(+ `${statePrefix}.isolation must be isolated, reload, or resettable.`+ );+ }+ validateActions(state?.reset, `${statePrefix}.reset`, errors);+ if (state?.isolation === 'resettable' &&+ (!Array.isArray(state.reset) || state.reset.length === 0)) {+ errors.push(+ `${statePrefix}.reset must contain at least one action for resettable states.`+ );+ }+ if (state?.isolation !== 'resettable' && state?.reset !== undefined) {+ errors.push(+ `${statePrefix}.reset is valid only when isolation is resettable.`+ );+ }+ if (state?.isolation === 'resettable' &&+ asArray(state.reset).some((action) =>+ ['activate-locale', 'navigate', 'set-document', 'use-current']+ .includes(action.type)+ )) {+ errors.push(+ `${statePrefix}.reset cannot navigate or change the active locale.`+ );+ }+ if (state?.targets !== undefined && !Array.isArray(state.targets)) {+ errors.push(`${statePrefix}.targets must be an array.`);+ }+ for (const [targetIndex, target] of asArray(state?.targets).entries()) {+ const targetPrefix = `${statePrefix}.targets[${targetIndex}]`;+ if (!isNonEmpty(target?.selector)) errors.push(`${targetPrefix}.selector is required.`);+ if (target?.expectedDirection &&+ !DIRECTIONS.has(target.expectedDirection) &&+ target.expectedDirection !== 'inherit') {+ errors.push(`${targetPrefix}.expectedDirection must be inherit, ltr, or rtl.`);+ }+ validateOptionalBoolean(target, 'expectVisible', targetPrefix, errors);+ validateOptionalBoolean(target, 'externalOpaque', targetPrefix, errors);+ validateOptionalBoolean(target, 'allowClipping', targetPrefix, errors);+ validateOptionalBoolean(target, 'allowOutsideViewport', targetPrefix, errors);+ }+ if (state?.computed !== undefined && !Array.isArray(state.computed)) {+ errors.push(`${statePrefix}.computed must be an array.`);+ }+ for (const [checkIndex, check] of asArray(state?.computed).entries()) {+ const checkPrefix = `${statePrefix}.computed[${checkIndex}]`;+ if (!isNonEmpty(check?.selector)) errors.push(`${checkPrefix}.selector is required.`);+ if (!isNonEmpty(check?.property)) errors.push(`${checkPrefix}.property is required.`);+ if (!check?.expected || typeof check.expected !== 'object') {+ errors.push(`${checkPrefix}.expected must provide direction-specific values.`);+ } else {+ for (const direction of ['ltr', 'rtl', 'default']) {+ if (check.expected[direction] !== undefined &&+ !isStringOrStringArray(check.expected[direction])) {+ errors.push(`${checkPrefix}.expected.${direction} must be a string or string array.`);+ }+ }+ if (check.expected.ltr === undefined &&+ check.expected.rtl === undefined &&+ check.expected.default === undefined) {+ errors.push(`${checkPrefix}.expected must define ltr, rtl, or default.`);+ }+ }+ }+ if (state?.attributes !== undefined &&+ !Array.isArray(state.attributes)) {+ errors.push(`${statePrefix}.attributes must be an array.`);+ }+ for (const [checkIndex, check] of asArray(state?.attributes).entries()) {+ const checkPrefix = `${statePrefix}.attributes[${checkIndex}]`;+ if (!isNonEmpty(check?.selector)) {+ errors.push(`${checkPrefix}.selector is required.`);+ }+ if (!isNonEmpty(check?.name)) {+ errors.push(`${checkPrefix}.name is required.`);+ }+ if (typeof check?.expected !== 'string') {+ errors.push(`${checkPrefix}.expected must be a string.`);+ }+ }+ if (state?.focusOrder !== undefined) {+ validateStringArray(state.focusOrder, `${statePrefix}.focusOrder`, errors, 2);+ }+ if (state?.nonOverlapping !== undefined && !Array.isArray(state.nonOverlapping)) {+ errors.push(`${statePrefix}.nonOverlapping must be an array.`);+ }+ for (const [pairIndex, pair] of asArray(state?.nonOverlapping).entries()) {+ if (!Array.isArray(pair) || pair.length !== 2 || pair.some((item) => !isNonEmpty(item))) {+ errors.push(+ `${statePrefix}.nonOverlapping[${pairIndex}] must contain two selectors.`+ );+ }+ }+ }+ if (component?.manualChecks !== undefined) {+ validateStringArray(component.manualChecks, `${prefix}.manualChecks`, errors, 1);+ }+ const componentViewports = Array.isArray(component?.viewports)+ ? component.viewports+ : [];+ if (componentViewports.length === 0) errors.push(`${prefix}.viewports must not be empty.`);+ for (const viewportName of componentViewports) {+ if (!viewportNames.has(viewportName)) {+ errors.push(`${prefix}.viewports references unknown viewport "${viewportName}".`);+ }+ }+ if (component?.classification === 'unknown-third-party') {+ const hasTarget = states.some((state) =>+ Array.isArray(state.targets) && state.targets.length > 0+ );+ if (!hasTarget) {+ errors.push(`${prefix} must identify the rendered third-party targets.`);+ }+ }+ }++ const transitionSequences = [];+ for (const [index, transition] of (spec.transitions || []).entries()) {+ const prefix = `transitions[${index}]`;+ if (!isNonEmpty(transition?.name)) errors.push(`${prefix}.name is required.`);+ if (!Array.isArray(transition?.sequence) || transition.sequence.length < 2) {+ errors.push(`${prefix}.sequence must contain at least two locale IDs.`);+ } else {+ for (const localeId of transition.sequence) {+ if (!localeIds.has(localeId)) {+ errors.push(`${prefix}.sequence references unknown locale "${localeId}".`);+ }+ }+ transitionSequences.push(transition.sequence.join(','));+ }+ if (!isNonEmpty(transition?.route) || !transition.route.startsWith('/')) {+ errors.push(`${prefix}.route must start with "/".`);+ }+ if (transition?.viewport !== undefined && !viewportNames.has(transition.viewport)) {+ errors.push(`${prefix}.viewport references unknown viewport "${transition.viewport}".`);+ }+ if (transition?.preserve !== undefined) {+ if (!Array.isArray(transition.preserve)) {+ errors.push(`${prefix}.preserve must be an array.`);+ } else {+ for (const [preserveIndex, entry] of transition.preserve.entries()) {+ const preservePrefix = `${prefix}.preserve[${preserveIndex}]`;+ if (isNonEmpty(entry)) continue;+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {+ errors.push(`${preservePrefix} must be a selector or preservation object.`);+ continue;+ }+ if (!isNonEmpty(entry.selector)) {+ errors.push(`${preservePrefix}.selector is required.`);+ }+ if (!PRESERVATION_KINDS.has(entry.kind)) {+ errors.push(+ `${preservePrefix}.kind must be auto, value, checked, text, attribute, or property.`+ );+ }+ if ((entry.kind === 'attribute' || entry.kind === 'property') &&+ !isNonEmpty(entry.name)) {+ errors.push(`${preservePrefix}.name is required for ${entry.kind}.`);+ }+ }+ }+ }+ if (transition?.preserveFocus !== undefined &&+ !isNonEmpty(transition.preserveFocus)) {+ errors.push(`${prefix}.preserveFocus must be a non-empty selector.`);+ }+ if (transition?.preserveRoute !== undefined &&+ typeof transition.preserveRoute !== 'boolean') {+ errors.push(`${prefix}.preserveRoute must be boolean when provided.`);+ }+ validateActions(transition?.setup, `${prefix}.setup`, errors);+ }++ function asArray(value) {+ return Array.isArray(value) ? value : [];+ }++ function validateOptionalBoolean(value, key, prefix, errors) {+ if (value?.[key] !== undefined && typeof value[key] !== 'boolean') {+ errors.push(`${prefix}.${key} must be boolean when provided.`);+ }+ }++ function validateStringArray(value, prefix, errors, minimumLength) {+ if (!Array.isArray(value) || value.length < minimumLength ||+ value.some((item) => !isNonEmpty(item))) {+ errors.push(+ `${prefix} must be an array of at least ${minimumLength} non-empty selector/string values.`+ );+ }+ }++ function isStringOrStringArray(value) {+ return isNonEmpty(value) ||+ (Array.isArray(value) && value.length > 0 && value.every(isNonEmpty));+ }+ if (localizationContext) {+ const expectedLocales = localizationContext.locales+ .filter((locale) => !unavailableLocales.has(locale))+ .sort();+ const actualLocales = locales+ .filter((locale) => !locale.pseudo)+ .map((locale) => locale.locale)+ .sort();+ if (JSON.stringify(expectedLocales) !== JSON.stringify(actualLocales)) {+ errors.push(+ 'Real locales must exactly match the currently available localization ' ++ 'manifest locales.'+ );+ }+ const expectedUnavailableChecks = [...unavailableLocales].sort();+ const actualUnavailableChecks = [...checkedUnavailableLocales].sort();+ if (JSON.stringify(expectedUnavailableChecks) !==+ JSON.stringify(actualUnavailableChecks)) {+ errors.push(+ 'unavailableLocaleChecks must exactly match manifest unavailableLocales.'+ );+ }+ if (localizationContext.mode === 'runtime' && spec.runtimeSwitching !== true) {+ errors.push('Runtime localization manifests require runtimeSwitching: true.');+ }+ if (localizationContext.mode === 'static' && spec.runtimeSwitching === true) {+ errors.push('Static localization manifests require runtimeSwitching: false.');+ }+ }+ if (spec.runtimeSwitching === true) {+ if (locales.some((locale) =>+ asArray(locale.activate).some((action) => action.type === 'navigate')+ )) {+ errors.push('runtimeSwitching locale activation cannot use navigate.');+ }+ if (locales.some((locale) =>+ !locale.pseudo &&+ asArray(locale.activate).some((action) => action.type === 'use-current')+ )) {+ errors.push(+ 'runtimeSwitching real locales require a reusable activation path; ' ++ 'use-current cannot restore a locale during round trips.'+ );+ }+ const defaultLocale = locales.find(+ (locale) => locale.id === spec.defaultLocaleId+ );+ if (!isNonEmpty(spec.defaultLocaleId) || !defaultLocale) {+ errors.push('runtimeSwitching requires a valid defaultLocaleId.');+ } else if (defaultLocale.pseudo) {+ errors.push('runtimeSwitching defaultLocaleId must identify a real locale.');+ } else {+ if (localizationContext &&+ defaultLocale.locale !== localizationContext.defaultLocale) {+ errors.push(+ 'runtimeSwitching defaultLocaleId must match the localization ' ++ 'manifest defaultLocale.'+ );+ }+ const representatives = new Set(+ Object.values(resolveRepresentatives(spec, localizationContext))+ );+ for (const locale of locales.filter(+ (candidate) => !candidate.pseudo && candidate.id !== spec.defaultLocaleId+ )) {+ const outward = `${spec.defaultLocaleId},${locale.id},${spec.defaultLocaleId}`;+ const returnTrip = `${locale.id},${spec.defaultLocaleId},${locale.id}`;+ if (verificationProfile !== 'targeted' &&+ !transitionSequences.includes(outward)) {+ errors.push(+ `runtimeSwitching requires ${spec.defaultLocaleId} -> ${locale.id} -> ` ++ `${spec.defaultLocaleId}.`+ );+ }+ if (verificationProfile === 'extensive' &&+ !transitionSequences.includes(returnTrip)) {+ errors.push(+ `runtimeSwitching requires ${locale.id} -> ${spec.defaultLocaleId} -> ` ++ `${locale.id}.`+ );+ }+ if (verificationProfile === 'standard' &&+ representatives.has(locale.id) &&+ !transitionSequences.includes(returnTrip)) {+ errors.push(+ `standard runtimeSwitching requires representative locale ` ++ `${locale.id} -> ${spec.defaultLocaleId} -> ${locale.id}.`+ );+ }+ }+ }+ }+ if (verificationProfile === 'targeted' &&+ Array.isArray(spec.targetCaseIds)) {+ const knownCaseIds = new Set();+ for (const component of components) {+ for (const state of asArray(component.states)) {+ for (const viewportName of asArray(component.viewports)) {+ for (const locale of locales) {+ knownCaseIds.add(+ `${component.id}--${state.name}--${viewportName}--${locale.id}`+ );+ }+ }+ }+ }+ const smokeViewport =+ spec.localeSmoke?.viewport || viewports[0]?.name;+ for (const locale of locales.filter((candidate) => !candidate.pseudo)) {+ knownCaseIds.add(`locale-smoke--${smokeViewport}--${locale.id}`);+ }+ for (const transition of spec.transitions || []) {+ knownCaseIds.add(`transition--${transition.name}`);+ }+ for (const caseId of spec.targetCaseIds) {+ if (!knownCaseIds.has(caseId)) {+ errors.push(`targetCaseIds references unknown case "${caseId}".`);+ }+ }+ }+ return errors;+}++function validateActions(actions, prefix, errors) {+ if (actions === undefined) return;+ if (!Array.isArray(actions)) {+ errors.push(`${prefix} must be an array.`);+ return;+ }+ for (const [index, action] of actions.entries()) {+ const actionPrefix = `${prefix}[${index}]`;+ if (!ACTION_TYPES.has(action?.type)) {+ errors.push(`${actionPrefix}.type is invalid.`);+ continue;+ }+ if (action.type !== 'wait' && action.type !== 'set-document' &&+ action.type !== 'navigate' &&+ action.type !== 'use-current' &&+ !isNonEmpty(action.selector)) {+ errors.push(`${actionPrefix}.selector is required.`);+ }+ if (action.type === 'activate-locale') {+ if (!isNonEmpty(action.locale)) {+ errors.push(`${actionPrefix}.locale must be a non-empty string.`);+ }+ if (!['click', 'select'].includes(action.method)) {+ errors.push(`${actionPrefix}.method must be click or select.`);+ }+ if (action.method === 'select' && !isStringOrStringArray(action.value)) {+ errors.push(+ `${actionPrefix}.value must be a string or string array for select.`+ );+ }+ }+ if (action.type === 'wait' &&+ (!Number.isInteger(action.ms) || action.ms < 0 || action.ms > 10000)) {+ errors.push(`${actionPrefix}.ms must be an integer from 0 through 10000.`);+ }+ if (action.type === 'set-document' &&+ (!isNonEmpty(action.locale) || !DIRECTIONS.has(action.direction))) {+ errors.push(`${actionPrefix} requires locale and direction.`);+ }+ if (action.type === 'navigate' &&+ (!isNonEmpty(action.url) ||+ (!action.url.startsWith('/') && !/^https?:\/\//i.test(action.url)))) {+ errors.push(`${actionPrefix}.url must be an absolute or root-relative HTTP URL.`);+ }+ if (action.type === 'set-attribute' &&+ (!isNonEmpty(action.name) || typeof action.value !== 'string')) {+ errors.push(`${actionPrefix} requires name and string value.`);+ }+ if (action.type === 'fill' && typeof action.value !== 'string') {+ errors.push(`${actionPrefix}.value must be a string.`);+ }+ if (action.type === 'press' && !isNonEmpty(action.key)) {+ errors.push(`${actionPrefix}.key must be a non-empty string.`);+ }+ if (action.type === 'select' && !isStringOrStringArray(action.value)) {+ errors.push(`${actionPrefix}.value must be a string or string array.`);+ }+ }+}++function buildVerificationCases(spec, localizationContext = null) {+ const viewportMap = new Map(spec.viewports.map((viewport) => [viewport.name, viewport]));+ const localeMap = new Map(spec.locales.map((locale) => [locale.id, locale]));+ const representatives = resolveRepresentatives(spec, localizationContext);+ const cases = [];+ for (const component of spec.components) {+ const dimensions = selectComponentDimensions(+ component,+ spec,+ representatives+ );+ for (const state of dimensions.states) {+ for (const viewportName of dimensions.viewports) {+ for (const localeId of dimensions.localeIds) {+ const locale = localeMap.get(localeId);+ if (!locale) continue;+ cases.push({+ id: `${component.id}--${state.name}--${viewportName}--${locale.id}`,+ component,+ state,+ viewport: viewportMap.get(viewportName),+ locale,+ risk: dimensions.risk,+ spec,+ });+ }+ }+ }+ }+ if (resolveVerificationProfile(spec) !== 'targeted') return cases;+ const targetCaseIds = new Set(spec.targetCaseIds || []);+ return cases.filter((verificationCase) =>+ targetCaseIds.has(verificationCase.id)+ );+}++function buildLocaleSmokeCases(spec) {+ const profile = resolveVerificationProfile(spec);+ if (!['standard', 'targeted'].includes(profile)) return [];+ const route = spec.localeSmoke?.route || spec.components[0]?.route;+ const viewportName =+ spec.localeSmoke?.viewport || spec.viewports[0]?.name;+ const viewport = spec.viewports.find(+ (candidate) => candidate.name === viewportName+ );+ const targetCaseIds = new Set(spec.targetCaseIds || []);+ return spec.locales+ .filter((locale) => !locale.pseudo)+ .map((locale) => ({+ id: `locale-smoke--${viewportName}--${locale.id}`,+ route,+ viewport,+ locale,+ spec,+ }))+ .filter((smokeCase) =>+ profile !== 'targeted' || targetCaseIds.has(smokeCase.id)+ );+}++function buildVerificationGroups(verificationCases) {+ const groups = new Map();+ for (const verificationCase of verificationCases) {+ const { component, state, viewport, locale } = verificationCase;+ // Isolated states retain the old one-page-per-case behavior. Other states+ // can safely share a page object; reload remains the default preparation+ // unless the spec supplies a reset action that restores a known baseline.+ const key = state.isolation === 'isolated'+ ? `isolated:${verificationCase.id}`+ : [+ component.route,+ viewport.name,+ locale.id,+ ].join('\0');+ if (!groups.has(key)) {+ groups.set(key, {+ id: key,+ route: component.route,+ viewport,+ locale,+ cases: [],+ });+ }+ groups.get(key).cases.push(verificationCase);+ }+ return [...groups.values()];+}++async function runWithConcurrency(items, limit, worker) {+ const results = new Array(items.length);+ let nextIndex = 0;+ async function runWorker() {+ while (nextIndex < items.length) {+ const index = nextIndex;+ nextIndex += 1;+ results[index] = await worker(items[index], index);+ }+ }+ const workerCount = Math.min(limit, items.length);+ await Promise.all(+ Array.from({ length: workerCount }, () => runWorker())+ );+ return results;+}++async function runRenderedBidirectionalAudit(options) {+ const errors = validateRunSpec(options.spec, options.localizationContext);+ if (errors.length > 0) {+ const error = new Error(`Invalid rendered bidirectional run specification:\n- ${errors.join('\n- ')}`);+ error.code = 'INVALID_SPEC';+ throw error;+ }+ const baseUrl = options.url.replace(/\/$/, '');+ const requiredOrigin = getRequiredLoopbackOrigin(baseUrl);+ const browser = await options.chromium.launch({+ ...(options.browserLaunchOptions || {}),+ headless: true,+ });+ const findings = [];+ const results = [];+ const representatives = resolveRepresentatives(+ options.spec,+ options.localizationContext+ );+ const smokeCases = buildLocaleSmokeCases(options.spec);+ const verificationGroups = buildVerificationGroups(+ buildVerificationCases(options.spec, options.localizationContext)+ );+ const maxConcurrency =+ options.spec.maxConcurrency || DEFAULT_MAX_CONCURRENCY;++ try {+ const independentTasks = [+ ...smokeCases.map((smokeCase) => ({+ type: 'locale-smoke',+ value: smokeCase,+ })),+ ...verificationGroups.map((group) => ({+ type: 'component-group',+ value: group,+ })),+ ];+ const taskResults = await runWithConcurrency(+ independentTasks,+ maxConcurrency,+ async (task) => {+ if (task.type === 'locale-smoke') {+ return [await runLocaleSmokeCase(+ browser,+ baseUrl,+ task.value,+ options.evidenceDir,+ requiredOrigin+ )];+ }+ return runVerificationGroup(+ browser,+ baseUrl,+ task.value,+ options.evidenceDir,+ requiredOrigin+ );+ }+ );+ for (const taskResult of taskResults) {+ for (const result of taskResult) {+ results.push(result);+ findings.push(...result.findings);+ }+ }+ // Runtime transitions deliberately remain serial. They verify persistence,+ // request ordering, and state preservation, so overlapping sequences would+ // make timing-sensitive failures harder to attribute.+ const targetCaseIds = new Set(options.spec.targetCaseIds || []);+ for (const transition of options.spec.transitions || []) {+ const transitionId = `transition--${transition.name}`;+ if (resolveVerificationProfile(options.spec) === 'targeted' &&+ !targetCaseIds.has(transitionId)) {+ continue;+ }+ const result = await runTransitionCase(+ browser,+ baseUrl,+ transition,+ options.spec,+ options.evidenceDir,+ requiredOrigin+ );+ results.push(result);+ findings.push(...result.findings);+ }+ } finally {+ await browser.close();+ }++ return {+ url: baseUrl,+ runAt: new Date().toISOString(),+ verification: {+ profile: resolveVerificationProfile(options.spec),+ representativeLocaleIds: representatives,+ localeSmokeCount: results.filter(+ (result) => result.type === 'locale-smoke'+ ).length,+ componentCaseCount: results.filter(+ (result) => result.type === 'component-state'+ ).length,+ componentGroupCount: verificationGroups.length,+ maxConcurrency,+ transitionCaseCount: results.filter(+ (result) => result.type === 'locale-transition'+ ).length,+ manualReview: buildManualReviewChecklist(+ options.spec,+ representatives+ ),+ reviewFindings: findings+ .filter((finding) => finding.severity === 'review')+ .map((finding) => ({+ caseId: finding.caseId,+ rule: finding.rule,+ severity: finding.severity,+ message: finding.message,+ selector: finding.selector,+ })),+ },+ summary: summarizeFindings(findings, results),+ findings,+ results,+ };+}++async function runLocaleSmokeCase(+ browser,+ baseUrl,+ smokeCase,+ evidenceDir,+ requiredOrigin+) {+ const { locale, route, viewport } = smokeCase;+ const page = await browser.newPage({+ viewport: { width: viewport.width, height: viewport.height },+ });+ const findings = [];+ const consoleErrors = [];+ page.on('console', (message) => {+ if (message.type() === 'error') consoleErrors.push(message.text());+ });+ page.on('pageerror', (error) => consoleErrors.push(error.message));++ try {+ await navigateWithinOrigin(page, route, baseUrl, requiredOrigin);+ await verifyUnavailableLocaleChecks(+ page,+ smokeCase.spec.unavailableLocaleChecks || [],+ smokeCase.id,+ findings+ );+ await executeActions(page, locale.activate || [], baseUrl, requiredOrigin);+ await page.waitForTimeout(100);+ await assertPageOrigin(page, requiredOrigin);+ await assertDocumentLocale(page, locale, findings, smokeCase.id);+ await assertLocaleEvidence(page, locale, findings, smokeCase.id);+ for (const message of consoleErrors) {+ findings.push(makeFinding(+ smokeCase.id,+ 'browser-console-error',+ 'error',+ message,+ 'html'+ ));+ }+ } catch (error) {+ findings.push(makeFinding(+ smokeCase.id,+ 'locale-smoke-failure',+ 'error',+ error.message,+ 'html'+ ));+ }++ const screenshot = findings.length > 0+ ? await captureEvidence(page, evidenceDir, smokeCase.id)+ : null;+ await page.close();+ return {+ id: smokeCase.id,+ type: 'locale-smoke',+ route,+ viewport: viewport.name,+ locale: locale.locale,+ direction: locale.direction,+ status: findings.some((finding) => finding.severity === 'error')+ ? 'failed'+ : findings.length > 0 ? 'review' : 'passed',+ screenshot,+ findings,+ };+}++async function runVerificationGroup(+ browser,+ baseUrl,+ group,+ evidenceDir,+ requiredOrigin+) {+ const page = await browser.newPage({+ viewport: {+ width: group.viewport.width,+ height: group.viewport.height,+ },+ });+ const consoleErrors = [];+ page.on('console', (message) => {+ if (message.type() === 'error') consoleErrors.push(message.text());+ });+ page.on('pageerror', (error) => consoleErrors.push(error.message));+ const results = [];+ let reusableBaseline = false;++ try {+ for (const verificationCase of group.cases) {+ const consoleStart = consoleErrors.length;+ const canReset =+ verificationCase.state.isolation === 'resettable' &&+ !verificationCase.locale.pseudo;+ try {+ let initializationFindings = [];+ if (!reusableBaseline || !canReset) {+ initializationFindings = await initializeVerificationPage(+ page,+ baseUrl,+ verificationCase,+ requiredOrigin+ );+ }+ const outcome = await runVerificationCaseOnPage(+ page,+ baseUrl,+ verificationCase,+ evidenceDir,+ requiredOrigin,+ consoleErrors,+ consoleStart,+ initializationFindings+ );+ results.push(outcome.result);+ reusableBaseline = canReset && outcome.resetSucceeded;+ } catch (error) {+ const findings = [makeFinding(+ verificationCase.id,+ 'rendered-case-failure',+ 'error',+ error.message,+ verificationCase.component.selector+ )];+ const screenshot = await captureEvidence(+ page,+ evidenceDir,+ verificationCase.id+ );+ results.push(buildVerificationCaseResult(+ verificationCase,+ findings,+ screenshot+ ));+ reusableBaseline = false;+ }+ }+ } finally {+ await page.close();+ }+ return results;+}++async function initializeVerificationPage(+ page,+ baseUrl,+ verificationCase,+ requiredOrigin+) {+ const { component, locale } = verificationCase;+ await navigateWithinOrigin(+ page,+ component.route,+ baseUrl,+ requiredOrigin+ );+ const initializationFindings = [];+ await verifyUnavailableLocaleChecks(+ page,+ verificationCase.spec.unavailableLocaleChecks || [],+ verificationCase.id,+ initializationFindings+ );+ await executeActions(page, locale.activate || [], baseUrl, requiredOrigin);+ await verifyUnavailableLocaleChecks(+ page,+ verificationCase.spec.unavailableLocaleChecks || [],+ verificationCase.id,+ initializationFindings+ );+ return initializationFindings;+}++async function runVerificationCaseOnPage(+ page,+ baseUrl,+ verificationCase,+ evidenceDir,+ requiredOrigin,+ consoleErrors,+ consoleStart,+ initializationFindings+) {+ const { component, state, viewport, locale } = verificationCase;+ const findings = [...initializationFindings];+ let screenshot = null;+ let resetSucceeded = state.isolation !== 'resettable';++ try {+ await executeActions(page, state.setup || [], baseUrl, requiredOrigin);+ await verifyUnavailableLocaleChecks(+ page,+ verificationCase.spec.unavailableLocaleChecks || [],+ verificationCase.id,+ findings+ );+ if (locale.pseudo) await applyPseudoContent(page, locale.direction);+ await page.waitForTimeout(100);+ await assertPageOrigin(page, requiredOrigin);+ await assertDocumentLocale(page, locale, findings, verificationCase.id);+ await assertLocaleEvidence(page, locale, findings, verificationCase.id);++ const documentSnapshot = await inspectDocument(page);+ if (documentSnapshot.horizontalOverflow) {+ findings.push(makeFinding(+ verificationCase.id,+ 'page-horizontal-overflow',+ 'error',+ `The page is ${documentSnapshot.overflowPixels}px wider than the viewport.`,+ 'html'+ ));+ }+ const targets = state.targets?.length+ ? state.targets+ : [{ selector: component.selector, expectedDirection: 'inherit' }];+ for (const target of targets) {+ const snapshot = await inspectTarget(page, target.selector);+ evaluateTarget(+ snapshot,+ target,+ component,+ locale,+ verificationCase.id,+ findings+ );+ }+ for (const check of state.computed || []) {+ await evaluateComputedCheck(page, check, locale, verificationCase.id, findings);+ }+ for (const check of state.attributes || []) {+ await evaluateAttributeCheck(page, check, verificationCase.id, findings);+ }+ if (state.focusOrder?.length) {+ await verifyFocusOrder(page, state.focusOrder, verificationCase.id, findings);+ }+ for (const pair of state.nonOverlapping || []) {+ await verifyNoOverlap(page, pair, verificationCase.id, findings);+ }+ for (const manualCheck of component.manualChecks || []) {+ findings.push(makeFinding(+ verificationCase.id,+ 'rendered-semantic-review',+ 'review',+ manualCheck,+ component.selector+ ));+ }+ await assertPageOrigin(page, requiredOrigin);+ } catch (error) {+ findings.push(makeFinding(+ verificationCase.id,+ 'rendered-case-failure',+ 'error',+ error.message,+ component.selector+ ));+ }++ if (findings.length > 0) {+ screenshot = await captureEvidence(+ page,+ evidenceDir,+ verificationCase.id+ );+ }+ if (state.isolation === 'resettable') {+ try {+ const findingCountBeforeReset = findings.length;+ await executeActions(+ page,+ state.reset,+ baseUrl,+ requiredOrigin+ );+ await verifyUnavailableLocaleChecks(+ page,+ verificationCase.spec.unavailableLocaleChecks || [],+ verificationCase.id,+ findings+ );+ await assertPageOrigin(page, requiredOrigin);+ await assertDocumentLocale(+ page,+ locale,+ findings,+ verificationCase.id+ );+ await assertLocaleEvidence(+ page,+ locale,+ findings,+ verificationCase.id+ );+ resetSucceeded = findings.length === findingCountBeforeReset;+ if (!resetSucceeded && !screenshot) {+ screenshot = await captureEvidence(+ page,+ evidenceDir,+ verificationCase.id+ );+ }+ } catch (error) {+ findings.push(makeFinding(+ verificationCase.id,+ 'rendered-case-reset-failure',+ 'error',+ `The declared state reset failed: ${error.message}`,+ component.selector+ ));+ if (!screenshot) {+ screenshot = await captureEvidence(+ page,+ evidenceDir,+ verificationCase.id+ );+ }+ }+ }+ for (const message of consoleErrors.slice(consoleStart)) {+ findings.push(makeFinding(+ verificationCase.id,+ 'browser-console-error',+ 'error',+ message,+ component.selector+ ));+ }+ if (state.isolation === 'resettable' &&+ findings.some((finding) => finding.rule === 'browser-console-error')) {+ resetSucceeded = false;+ }+ if (findings.length > 0 && !screenshot) {+ screenshot = await captureEvidence(+ page,+ evidenceDir,+ verificationCase.id+ );+ }+ return {+ resetSucceeded,+ result: buildVerificationCaseResult(+ verificationCase,+ findings,+ screenshot+ ),+ };+}++function buildVerificationCaseResult(verificationCase, findings, screenshot) {+ const { component, state, viewport, locale } = verificationCase;+ return {+ id: verificationCase.id,+ type: 'component-state',+ component: component.name,+ classification: component.classification,+ state: state.name,+ viewport: viewport.name,+ locale: locale.locale,+ direction: locale.direction,+ status: findings.some((finding) => finding.severity === 'error')+ ? 'failed'+ : findings.length > 0 ? 'review' : 'passed',+ screenshot,+ findings,+ };+}++async function executeActions(page, actions, baseUrl, requiredOrigin = null) {+ for (const action of actions) {+ if (action.type === 'wait') {+ await page.waitForTimeout(action.ms);+ await assertPageOrigin(page, requiredOrigin);+ continue;+ }+ if (action.type === 'use-current') continue;+ if (action.type === 'activate-locale') {+ const locator = page.locator(action.selector).first();+ if (action.method === 'select') {+ await locator.selectOption(action.value);+ } else {+ await locator.click();+ }+ await assertPageOrigin(page, requiredOrigin);+ const activeDocument = await page.evaluate(() => ({+ lang: document.documentElement.lang,+ }));+ if (activeDocument?.lang !== action.locale) {+ throw new Error(+ `Locale control ${action.selector} activated ` ++ `"${activeDocument?.lang || ''}" ` ++ `instead of "${action.locale}".`+ );+ }+ continue;+ }+ if (action.type === 'set-document') {+ await page.evaluate(({ locale, direction }) => {+ document.documentElement.lang = locale;+ document.documentElement.dir = direction;+ }, { locale: action.locale, direction: action.direction });+ continue;+ }+ if (action.type === 'navigate') {+ await navigateWithinOrigin(+ page,+ action.url,+ baseUrl,+ requiredOrigin+ );+ continue;+ }+ const locator = page.locator(action.selector).first();+ if (action.type === 'click') await locator.click();+ else if (action.type === 'fill') await locator.fill(action.value ?? '');+ else if (action.type === 'focus') await locator.focus();+ else if (action.type === 'hover') await locator.hover();+ else if (action.type === 'press') await locator.press(action.key);+ else if (action.type === 'select') await locator.selectOption(action.value);+ else if (action.type === 'check') await locator.check();+ else if (action.type === 'uncheck') await locator.uncheck();+ else if (action.type === 'set-attribute') {+ await locator.evaluate((element, attribute) => {+ element.setAttribute(attribute.name, attribute.value);+ }, { name: action.name, value: action.value });+ }+ await assertPageOrigin(page, requiredOrigin);+ }+}++async function assertLocaleEvidence(page, locale, findings, caseId) {+ for (const expectation of locale.expect || []) {+ const locator = page.locator(expectation.selector).first();+ if (await locator.count() === 0) {+ findings.push(makeFinding(+ caseId,+ 'localized-content-target-missing',+ 'error',+ 'A target required to prove the real locale was activated was not found.',+ expectation.selector+ ));+ continue;+ }+ const actual = expectation.attribute+ ? await locator.getAttribute(expectation.attribute)+ : await locator.textContent();+ const expected = expectation.attribute ? expectation.value : expectation.text;+ if (expectation.exact ? actual !== expected : !String(actual || '').includes(expected)) {+ findings.push(makeFinding(+ caseId,+ 'localized-content-mismatch',+ 'error',+ `Expected localized content "${expected}" but found "${actual || ''}".`,+ expectation.selector+ ));+ }+ }+}++async function assertPageOrigin(page, requiredOrigin) {+ if (typeof page.url !== 'function') {+ throw new Error('The browser page does not expose its current URL.');+ }+ const currentUrl = page.url();+ let currentOrigin;+ try {+ currentOrigin = new URL(currentUrl).origin;+ } catch {+ throw new Error(`The browser reported an invalid current URL: ${currentUrl}`);+ }+ if (currentOrigin !== requiredOrigin) {+ throw new Error(+ `Rendered verification left the required loopback origin ` ++ `${requiredOrigin}: ${currentUrl}`+ );+ }+}++function getRequiredLoopbackOrigin(value) {+ let parsed;+ try {+ parsed = new URL(value);+ } catch {+ throw new Error(+ 'Rendered verification must use a loopback development URL with HTTP or HTTPS.'+ );+ }+ const protocol = parsed.protocol.toLowerCase();+ const hostname = parsed.hostname.toLowerCase();+ if ((protocol !== 'http:' && protocol !== 'https:') ||+ !LOOPBACK_HOSTNAMES.has(hostname)) {+ throw new Error(+ 'Rendered verification must use a loopback development URL with HTTP or HTTPS.'+ );+ }+ return parsed.origin;+}++function resolveSameOriginNavigationUrl(value, baseUrl, requiredOrigin) {+ let target;+ try {+ target = new URL(value, baseUrl);+ } catch {+ throw new Error('Rendered verification navigation URL is invalid.');+ }+ if ((target.protocol !== 'http:' && target.protocol !== 'https:') ||+ target.origin !== requiredOrigin) {+ throw new Error(+ `Rendered verification navigation must remain on the required ` ++ `loopback origin ${requiredOrigin}.`+ );+ }+ return target.href;+}++async function navigateWithinOrigin(+ page,+ value,+ baseUrl,+ requiredOrigin+) {+ const target = resolveSameOriginNavigationUrl(+ value,+ baseUrl,+ requiredOrigin+ );+ await page.goto(target, {+ waitUntil: 'networkidle',+ timeout: 20000,+ });+ await assertPageOrigin(page, requiredOrigin);+}++async function assertDocumentLocale(page, locale, findings, caseId) {+ const documentState = await page.evaluate(() => ({+ lang: document.documentElement.lang,+ direction: getComputedStyle(document.documentElement).direction,+ }));+ if (documentState.lang.toLowerCase() !== locale.locale.toLowerCase()) {+ findings.push(makeFinding(+ caseId,+ 'document-language-mismatch',+ 'error',+ `Expected html lang "${locale.locale}" but found "${documentState.lang}".`,+ 'html'+ ));+ }+ if (documentState.direction !== locale.direction) {+ findings.push(makeFinding(+ caseId,+ 'document-direction-mismatch',+ 'error',+ `Expected html direction "${locale.direction}" but found "${documentState.direction}".`,+ 'html'+ ));+ }+}++async function inspectTarget(page, selector) {+ const locator = page.locator(selector).first();+ if (await locator.count() === 0) {+ return { exists: false, visible: false };+ }+ return locator.evaluate((element) => {+ const style = getComputedStyle(element);+ const rect = element.getBoundingClientRect();+ const visible =+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ Number(style.opacity) !== 0 &&+ rect.width > 0 &&+ rect.height > 0;+ const clipsContent =+ /hidden|clip/.test(style.overflowX) || /hidden|clip/.test(style.overflowY);+ let clippedByAncestor = false;+ let ancestor = element.parentElement;+ while (ancestor) {+ const ancestorStyle = getComputedStyle(ancestor);+ if (/hidden|clip|auto|scroll/.test(+ `${ancestorStyle.overflowX} ${ancestorStyle.overflowY}`+ )) {+ const ancestorRect = ancestor.getBoundingClientRect();+ const clientLeft = ancestorRect.left + ancestor.clientLeft;+ const clientTop = ancestorRect.top + ancestor.clientTop;+ const clientRight = clientLeft + ancestor.clientWidth;+ const clientBottom = clientTop + ancestor.clientHeight;+ if (rect.left < clientLeft - 1 ||+ rect.top < clientTop - 1 ||+ rect.right > clientRight + 1 ||+ rect.bottom > clientBottom + 1) {+ clippedByAncestor = true;+ break;+ }+ }+ const root = ancestor.getRootNode();+ ancestor = ancestor.parentElement || root.host || null;+ }+ return {+ exists: true,+ visible,+ direction: style.direction,+ textAlign: style.textAlign,+ overflowX: style.overflowX,+ overflowY: style.overflowY,+ clipped:+ clipsContent &&+ (element.scrollWidth > element.clientWidth + 1 ||+ element.scrollHeight > element.clientHeight + 1) ||+ clippedByAncestor,+ outsideViewport:+ rect.left < -1 ||+ rect.top < -1 ||+ rect.right > window.innerWidth + 1 ||+ rect.bottom > window.innerHeight + 1,+ rect: {+ left: rect.left,+ top: rect.top,+ right: rect.right,+ bottom: rect.bottom,+ width: rect.width,+ height: rect.height,+ },+ };+ });+}++async function inspectDocument(page) {+ return page.evaluate(() => {+ const width = Math.max(+ document.documentElement.scrollWidth,+ document.body?.scrollWidth || 0+ );+ return {+ horizontalOverflow: width > window.innerWidth + 1,+ overflowPixels: Math.max(0, width - window.innerWidth),+ };+ });+}++function evaluateTarget(snapshot, target, component, locale, caseId, findings) {+ const expectVisible = target.expectVisible !== false;+ if (!snapshot.exists && !expectVisible) return;+ if (snapshot.visible !== expectVisible) {+ findings.push(makeFinding(+ caseId,+ 'rendered-visibility-mismatch',+ 'error',+ `Expected visibility ${expectVisible} but rendered visibility was ${snapshot.visible}.`,+ target.selector+ ));+ return;+ }+ if (!snapshot.visible) return;+ if (target.externalOpaque) {+ findings.push(makeFinding(+ caseId,+ 'unverifiable-third-party-surface',+ 'error',+ 'The visible external surface cannot be inspected for direction and must be adapted, restricted, replaced, or keep the locale unavailable.',+ target.selector+ ));+ return;+ }+ const expectedDirection =+ target.expectedDirection === 'inherit' || !target.expectedDirection+ ? locale.direction+ : target.expectedDirection;+ if (snapshot.direction !== expectedDirection) {+ findings.push(makeFinding(+ caseId,+ 'computed-direction-mismatch',+ 'error',+ `Expected computed direction "${expectedDirection}" but found "${snapshot.direction}".`,+ target.selector+ ));+ }+ if (snapshot.clipped && !target.allowClipping) {+ findings.push(makeFinding(+ caseId,+ 'rendered-content-clipped',+ 'error',+ 'Rendered content exceeds a clipping container.',+ target.selector+ ));+ }+ if (snapshot.outsideViewport && !target.allowOutsideViewport) {+ findings.push(makeFinding(+ caseId,+ 'rendered-outside-viewport',+ 'error',+ 'The rendered target extends outside the viewport.',+ target.selector+ ));+ }+ if (component.classification === 'direction-fixed' && !component.reason) {+ findings.push(makeFinding(+ caseId,+ 'missing-fixed-direction-reason',+ 'error',+ 'Direction-fixed rendered content requires a semantic reason.',+ target.selector+ ));+ }+}++async function evaluateComputedCheck(page, check, locale, caseId, findings) {+ const actual = await page.locator(check.selector).first().evaluate(+ (element, property) => getComputedStyle(element).getPropertyValue(property).trim(),+ check.property+ );+ const expected = check.expected[locale.direction] ?? check.expected.default;+ const accepted = Array.isArray(expected) ? expected : [expected];+ if (!accepted.includes(actual)) {+ findings.push(makeFinding(+ caseId,+ 'computed-style-mismatch',+ 'error',+ `Expected ${check.property} to be ${accepted.join(' or ')}, but found "${actual}".`,+ check.selector+ ));+ }+}++async function evaluateAttributeCheck(page, check, caseId, findings) {+ const actual = await page.locator(check.selector).first()+ .getAttribute(check.name);+ if (actual !== check.expected) {+ findings.push(makeFinding(+ caseId,+ 'attribute-mismatch',+ 'error',+ `Expected ${check.name}="${check.expected}" but found ` ++ `${actual === null ? 'no attribute' : `"${actual}"`}.`,+ check.selector+ ));+ }+}++async function verifyFocusOrder(page, selectors, caseId, findings) {+ await page.locator(selectors[0]).first().focus();+ for (let index = 1; index < selectors.length; index += 1) {+ await page.keyboard.press('Tab');+ const matches = await page.locator(selectors[index]).first().evaluate(+ (element) => {+ let active = document.activeElement;+ while (active?.shadowRoot?.activeElement) {+ active = active.shadowRoot.activeElement;+ }+ return element === active;+ }+ );+ if (!matches) {+ findings.push(makeFinding(+ caseId,+ 'focus-order-mismatch',+ 'error',+ `Tab order did not reach expected target ${index + 1}.`,+ selectors[index]+ ));+ return;+ }+ }+}++async function verifyNoOverlap(page, pair, caseId, findings) {+ const [left, right] = await Promise.all([+ page.locator(pair[0]).first().boundingBox(),+ page.locator(pair[1]).first().boundingBox(),+ ]);+ const overlaps = !left || !right+ ? null+ : !(+ left.x + left.width <= right.x ||+ right.x + right.width <= left.x ||+ left.y + left.height <= right.y ||+ right.y + right.height <= left.y+ );+ if (overlaps === null) {+ findings.push(makeFinding(+ caseId,+ 'overlap-target-missing',+ 'error',+ 'A target required for overlap verification was not found.',+ pair.join(' / ')+ ));+ } else if (overlaps) {+ findings.push(makeFinding(+ caseId,+ 'unexpected-rendered-overlap',+ 'error',+ 'Targets that must remain separate overlap in this rendered state.',+ pair.join(' / ')+ ));+ }+}++async function applyPseudoContent(page, direction) {+ await page.evaluate((pseudoDirection) => {+ const transform = (value) => {+ if (!value || !value.trim()) return value;+ const expanded = `${value} ${value}`;+ return pseudoDirection === 'rtl'+ ? `\u27e6\u0646\u0635 ${expanded}\u27e7`+ : `\u27e6${expanded} extra\u27e7`;+ };+ const processRoot = (root) => {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ const nodes = [];+ while (walker.nextNode()) {+ const parent = walker.currentNode.parentElement;+ if (parent && !/^(SCRIPT|STYLE|CODE|PRE|SVG)$/.test(parent.tagName)) {+ nodes.push(walker.currentNode);+ }+ }+ for (const node of nodes) node.nodeValue = transform(node.nodeValue);+ for (const element of root.querySelectorAll(+ 'input[placeholder], textarea[placeholder], [aria-label], [title], ' ++ 'input[type="button"][value], input[type="submit"][value], input[type="reset"][value]'+ )) {+ for (const attribute of ['placeholder', 'aria-label', 'title', 'value']) {+ if (attribute === 'value' &&+ !/^(button|submit|reset)$/i.test(element.getAttribute('type') || '')) {+ continue;+ }+ if (element.hasAttribute(attribute)) {+ element.setAttribute(attribute, transform(element.getAttribute(attribute)));+ }+ }+ }+ for (const element of root.querySelectorAll('*')) {+ if (element.shadowRoot) processRoot(element.shadowRoot);+ }+ };+ processRoot(document.body);+ }, direction);+}++async function runTransitionCase(+ browser,+ baseUrl,+ transition,+ spec,+ evidenceDir,+ requiredOrigin+) {+ const sequence = transition.sequence.map((localeId) =>+ spec.locales.find((locale) => locale.id === localeId)+ );+ const viewport = spec.viewports.find((candidate) =>+ candidate.name === (transition.viewport || spec.viewports[0].name)+ );+ const id = `transition--${transition.name}`;+ const page = await browser.newPage({+ viewport: { width: viewport.width, height: viewport.height },+ });+ const findings = [];+ const consoleErrors = [];+ page.on('console', (message) => {+ if (message.type() === 'error') consoleErrors.push(message.text());+ });+ page.on('pageerror', (error) => consoleErrors.push(error.message));+ try {+ await navigateWithinOrigin(+ page,+ transition.route,+ baseUrl,+ requiredOrigin+ );+ await verifyUnavailableLocaleChecks(+ page,+ spec.unavailableLocaleChecks || [],+ id,+ findings+ );+ await executeActions(+ page,+ sequence[0].activate || [],+ baseUrl,+ requiredOrigin+ );+ await verifyUnavailableLocaleChecks(+ page,+ spec.unavailableLocaleChecks || [],+ id,+ findings+ );+ await executeActions(+ page,+ transition.setup || [],+ baseUrl,+ requiredOrigin+ );+ await verifyUnavailableLocaleChecks(+ page,+ spec.unavailableLocaleChecks || [],+ id,+ findings+ );+ await assertPageOrigin(page, requiredOrigin);+ const baseline = await captureTransitionState(page, transition);+ await assertPageOrigin(page, requiredOrigin);+ addMissingTransitionTargets(baseline, id, findings);+ addUnsupportedTransitionTargets(baseline, id, findings);+ if (transition.preserveFocus && !baseline.focused) {+ findings.push(makeFinding(+ id,+ 'locale-switch-focus-baseline-missing',+ 'error',+ 'The focus preservation target was not focused before switching.',+ transition.preserveFocus+ ));+ }+ await assertDocumentLocale(page, sequence[0], findings, id);+ await assertLocaleEvidence(page, sequence[0], findings, id);+ for (const locale of sequence.slice(1)) {+ await verifyUnavailableLocaleChecks(+ page,+ spec.unavailableLocaleChecks || [],+ id,+ findings+ );+ await executeActions(+ page,+ locale.activate || [],+ baseUrl,+ requiredOrigin+ );+ await verifyUnavailableLocaleChecks(+ page,+ spec.unavailableLocaleChecks || [],+ id,+ findings+ );+ await page.waitForTimeout(100);+ await assertPageOrigin(page, requiredOrigin);+ const current = await captureTransitionState(page, transition);+ addMissingTransitionTargets(current, id, findings);+ addUnsupportedTransitionTargets(current, id, findings);+ await assertDocumentLocale(page, locale, findings, id);+ await assertLocaleEvidence(page, locale, findings, id);+ if (baseline.timeOrigin !== current.timeOrigin) {+ findings.push(makeFinding(+ id,+ 'locale-switch-reloaded-page',+ 'error',+ 'The runtime locale switch caused a page reload.',+ 'html'+ ));+ }+ if (transition.preserveRoute !== false && baseline.route !== current.route) {+ findings.push(makeFinding(+ id,+ 'locale-switch-lost-route',+ 'error',+ `The route changed from "${baseline.route}" to "${current.route}".`,+ 'html'+ ));+ }+ for (const [index, preserved] of baseline.preserved.entries()) {+ const currentPreserved = current.preserved[index];+ if (!preserved || preserved.unsupported || !currentPreserved ||+ currentPreserved.unsupported) {+ continue;+ }+ if (JSON.stringify(currentPreserved.value) !== JSON.stringify(preserved.value)) {+ findings.push(makeFinding(+ id,+ 'locale-switch-lost-state',+ 'error',+ `The preserved ${preserved.kind} state changed during locale switching.`,+ preserved.selector+ ));+ }+ }+ if (transition.preserveFocus && baseline.focused && !current.focused) {+ findings.push(makeFinding(+ id,+ 'locale-switch-lost-focus',+ 'error',+ 'The focused control changed during locale switching.',+ transition.preserveFocus+ ));+ }+ }+ await assertPageOrigin(page, requiredOrigin);+ } catch (error) {+ findings.push(makeFinding(id, 'locale-switch-failure', 'error', error.message, 'html'));+ }+ for (const message of consoleErrors) {+ findings.push(makeFinding(+ id,+ 'browser-console-error',+ 'error',+ message,+ 'html'+ ));+ }+ const screenshot = findings.length > 0+ ? await captureEvidence(page, evidenceDir, id)+ : null;+ await page.close();+ return {+ id,+ type: 'locale-transition',+ name: transition.name,+ sequence: sequence.map((locale) => locale.locale),+ status: findings.some((finding) => finding.severity === 'error') ? 'failed' : 'passed',+ screenshot,+ findings,+ };+}++async function verifyUnavailableLocaleChecks(page, checks, caseId, findings) {+ for (const check of checks) {+ for (const selector of check.selectors) {+ const locator = page.locator(selector);+ const count = await locator.count();+ let exposed = false;+ for (let index = 0; index < count && !exposed; index += 1) {+ const candidate = locator.nth(index);+ const elementType = await candidate.evaluate(+ (element) => element.tagName.toLowerCase()+ );+ if (elementType === 'option') {+ exposed = await candidate.evaluate((option) => {+ const select = option.closest('select');+ const optionGroup = option.closest('optgroup');+ if (!select || option.disabled || optionGroup?.disabled ||+ select.disabled) {+ return false;+ }+ if (typeof select.checkVisibility === 'function') {+ return select.checkVisibility({+ checkOpacity: true,+ checkVisibilityCSS: true,+ });+ }+ const style = getComputedStyle(select);+ const rect = select.getBoundingClientRect();+ return !select.hidden &&+ select.getAttribute('aria-hidden') !== 'true' &&+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ Number(style.opacity) !== 0 &&+ rect.width > 0 &&+ rect.height > 0;+ });+ } else {+ exposed = await candidate.isVisible();+ }+ }+ if (exposed) {+ findings.push(makeFinding(+ caseId,+ 'unavailable-locale-exposed',+ 'error',+ `Unavailable locale ${check.locale} is exposed by a normal activation selector.`,+ selector+ ));+ }+ }+ }+}++async function captureTransitionState(page, transition) {+ const pageState = await page.evaluate(() => ({+ route: `${location.pathname}${location.search}${location.hash}`,+ timeOrigin: performance.timeOrigin,+ }));+ const preserved = [];+ const missing = [];+ const unsupported = [];+ for (const entry of transition.preserve || []) {+ const preservation = normalizePreservationEntry(entry);+ const locator = page.locator(preservation.selector).first();+ if (await locator.count() === 0) {+ missing.push(preservation.selector);+ preserved.push(null);+ continue;+ }+ const captured = await locator.evaluate((element, requested) => {+ let kind = requested.kind;+ if (kind === 'auto') {+ const tagName = element.tagName.toLowerCase();+ if (tagName === 'input' &&+ (element.type === 'checkbox' || element.type === 'radio')) {+ kind = 'checked';+ } else if (tagName === 'input' || tagName === 'select' ||+ tagName === 'textarea') {+ kind = 'value';+ } else {+ return { unsupported: true, kind };+ }+ }+ if (kind === 'checked') {+ if (!('checked' in element)) return { unsupported: true, kind };+ return { unsupported: false, kind, value: Boolean(element.checked) };+ }+ if (kind === 'value') {+ if (!('value' in element)) return { unsupported: true, kind };+ return { unsupported: false, kind, value: element.value };+ }+ if (kind === 'text') {+ return { unsupported: false, kind, value: element.textContent };+ }+ if (kind === 'attribute') {+ if (!element.hasAttribute(requested.name)) {+ return { unsupported: true, kind };+ }+ return {+ unsupported: false,+ kind,+ value: element.getAttribute(requested.name),+ };+ }+ if (!(requested.name in element)) return { unsupported: true, kind };+ const value = element[requested.name];+ return {+ unsupported:+ value === undefined ||+ (value !== null && (typeof value === 'object' || typeof value === 'function')),+ kind,+ value,+ };+ }, preservation);+ const result = {+ ...captured,+ selector: preservation.selector,+ };+ if (captured.unsupported) unsupported.push(preservation.selector);+ preserved.push(result);+ }+ let focused = null;+ if (transition.preserveFocus) {+ const locator = page.locator(transition.preserveFocus).first();+ if (await locator.count() === 0) {+ missing.push(transition.preserveFocus);+ focused = false;+ } else {+ focused = await locator.evaluate((element) => {+ let active = document.activeElement;+ while (active?.shadowRoot?.activeElement) {+ active = active.shadowRoot.activeElement;+ }+ return element === active;+ });+ }+ }+ return { ...pageState, preserved, missing, unsupported, focused };+}++function addMissingTransitionTargets(state, caseId, findings) {+ for (const selector of new Set(state.missing)) {+ findings.push(makeFinding(+ caseId,+ 'locale-switch-preservation-target-missing',+ 'error',+ 'A selector required for locale-switch preservation evidence was not found.',+ selector+ ));+ }+}++function addUnsupportedTransitionTargets(state, caseId, findings) {+ for (const selector of new Set(state.unsupported)) {+ findings.push(makeFinding(+ caseId,+ 'locale-switch-preservation-unsupported',+ 'error',+ 'This preservation selector does not identify a form control. Specify text, attribute, or property evidence explicitly.',+ selector+ ));+ }+}++function normalizePreservationEntry(entry) {+ return typeof entry === 'string'+ ? { selector: entry, kind: 'auto' }+ : entry;+}++async function captureEvidence(page, evidenceDir, id) {+ if (!evidenceDir) return null;+ fs.mkdirSync(evidenceDir, { recursive: true });+ const output = path.join(evidenceDir, `${sanitizeFileName(id)}.png`);+ await page.screenshot({ path: output, fullPage: true });+ return output;+}++function makeFinding(caseId, rule, severity, message, selector) {+ return { caseId, rule, severity, message, selector };+}++function summarizeFindings(findings, results) {+ return {+ cases: results.length,+ passed: results.filter((result) => result.status === 'passed').length,+ review: results.filter((result) => result.status === 'review').length,+ failed: results.filter((result) => result.status === 'failed').length,+ errors: findings.filter((finding) => finding.severity === 'error').length,+ reviewFindings: findings.filter((finding) => finding.severity === 'review').length,+ };+}++function sanitizeFileName(value) {+ return value.replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 160);+}++function isNonEmpty(value) {+ return typeof value === 'string' && value.trim().length > 0;+}++module.exports = {+ buildLocaleSmokeCases,+ buildVerificationGroups,+ buildVerificationCases,+ getRequiredLoopbackOrigin,+ resolveSameOriginNavigationUrl,+ runRenderedBidirectionalAudit,+ runWithConcurrency,+ summarizeFindings,+ validateRunSpec,+};diff --git a/plugins/power-pages/scripts/lib/site-integrity.js b/plugins/power-pages/scripts/lib/site-integrity.jsindex d27c123e2..1e2898751 100644--- a/plugins/power-pages/scripts/lib/site-integrity.js+++ b/plugins/power-pages/scripts/lib/site-integrity.js@@ -3,18 +3,19 @@const fs = require('fs');const path = require('path');const {- classifyLocaleDirections,- getLocaleDirection,MANIFEST_NAME,} = require('./localization-config');const {auditBidirectionalReadiness,} = require('./bidirectional-readiness');+const {+ partitionDeferredFindings,+} = require('./bidirectional-finding-disposition');const {validateLocalization,} = require('../../skills/add-localization/scripts/validate-localization');-function validateSiteIntegrity(projectRoot) {+function validateSiteIntegrity(projectRoot, options = {}) {const configPath = path.join(projectRoot, 'powerpages.config.json');if (!fs.existsSync(configPath)) {return {@@ -26,29 +27,28 @@ function validateSiteIntegrity(projectRoot) {};}- const localizationErrors = validateLocalization(projectRoot);+ // A verified-but-unfinalized localization transaction is acceptable only at+ // add-localization's own pre-review gate, where the maker has not yet decided+ // whether the exposed target locales are ready, approved with limitations, or+ // kept unavailable. Every other caller — deploy-site and the final gate of+ // every other source-mutating skill — keeps this off, so a remaining+ // transaction still blocks completion and deployment (fail-closed).+ const localizationErrors = options.skipLocalization === true+ ? []+ : validateLocalization(projectRoot, {+ allowVerifiedTransactionReview:+ options.allowVerifiedLocalizationReview === true,+ });const bidiAudit = auditBidirectionalReadiness(projectRoot);const manifest = readJson(path.join(projectRoot, MANIFEST_NAME));- const directionSet = Array.isArray(manifest?.locales)- ? classifyLocaleDirections(manifest.locales)- : null;const unavailableLocales = new Set(Array.isArray(manifest?.unavailableLocales)? manifest.unavailableLocales: []);- const defaultDirection = manifest?.defaultLocale- ? getLocaleDirection(manifest.defaultLocale)- : null;- const oppositeLocales = Array.isArray(manifest?.locales) && defaultDirection- ? manifest.locales.filter((locale) => getLocaleDirection(locale) !== defaultDirection)- : [];const remediationPending =manifest?.bidirectionalReadiness?.status === 'pending-remediation' &&- directionSet?.classification === 'mixed' &&- oppositeLocales.length > 0 &&- oppositeLocales.every((locale) => unavailableLocales.has(locale)) &&- localizationErrors.length === 0;+ unavailableLocales.size > 0;const recordedFindings = remediationPending? manifest.bidirectionalReadiness.findings || []: [];@@ -56,19 +56,26 @@ function validateSiteIntegrity(projectRoot) {blocking: blockingBidiFindings,deferred,} = partitionDeferredFindings(- bidiAudit.findings.filter((finding) => finding.severity === 'error'),- recordedFindings+ bidiAudit.findings,+ recordedFindings,+ unavailableLocales);const deferredFindings = deferred.map((finding) => ({...finding,severity: 'review',- message: `Deferred while opposite-direction locales are unavailable: ${finding.message}`,+ message: `Deferred while affected locales are unavailable: ${finding.message}`,}));+ const errors = [+ ...new Set([+ ...localizationErrors,+ ...blockingBidiFindings.map(formatBidiFinding),+ ]),+ ];return {projectRoot,skipped: false,- errors: [...localizationErrors, ...blockingBidiFindings.map(formatBidiFinding)],+ errors,reviewFindings: [...bidiAudit.findings.filter((finding) => finding.severity === 'review'),...deferredFindings,@@ -76,33 +83,6 @@ function validateSiteIntegrity(projectRoot) {};}-function partitionDeferredFindings(findings, recordedFindings) {- const remainingRecords = [...recordedFindings];- const blocking = [];- const deferred = [];- for (const finding of findings) {- // Only a concrete layout blocker may be carried as pending work. Match the- // complete scanner identity and consume it once, so changing or adding a- // declaration on the same line is still a new blocking defect.- const recordIndex = finding.rule === 'directional-physical-css'- ? remainingRecords.findIndex((recorded) =>- recorded &&- recorded.rule === finding.rule &&- recorded.file === finding.file &&- recorded.line === finding.line &&- recorded.message === finding.message- )- : -1;- if (recordIndex === -1) {- blocking.push(finding);- continue;- }- remainingRecords.splice(recordIndex, 1);- deferred.push(finding);- }- return { blocking, deferred };-}-function readJson(filePath) {if (!fs.existsSync(filePath)) return null;try {diff --git a/plugins/power-pages/scripts/lib/verification-evidence.js b/plugins/power-pages/scripts/lib/verification-evidence.jsnew file mode 100644index 000000000..2c45e4e59--- /dev/null+++ b/plugins/power-pages/scripts/lib/verification-evidence.js@@ -0,0 +1,254 @@+'use strict';++const crypto = require('crypto');+const fs = require('fs');+const path = require('path');+const {+ findLocaleAvailabilityModulePaths,+} = require('./localization-config');+const {+ FULL_VERIFICATION_PROFILES,+} = require('./localization-verification-profile');+const {+ summarizeFindings,+} = require('./rendered-bidirectional-readiness');++const MANIFEST_FILE = '.powerpages-localization.json';+const SOURCE_ROOTS = ['src', 'public'];+const SOURCE_FILES = [+ MANIFEST_FILE,+ 'angular.json',+ 'astro.config.js',+ 'astro.config.mjs',+ 'astro.config.ts',+ 'index.html',+ 'package-lock.json',+ 'package.json',+ 'pnpm-lock.yaml',+ 'powerpages.config.json',+ 'tsconfig.json',+ 'vite.config.js',+ 'vite.config.ts',+ 'yarn.lock',+];++// `excludeAvailability` produces a second fingerprint that ignores exactly the+// two inputs a maker decision to keep a verified locale unavailable edits:+// `unavailableLocales` in the manifest and the managed locale availability+// module. Hiding a locale is the fail-closed direction, so finalization can+// accept that change without new browser evidence while any other source,+// resource, dependency, or build-configuration change still invalidates it.+function computeVerificationInputFingerprint(projectRoot, options = {}) {+ const excludeAvailability = options.excludeAvailability === true;+ const excludedPaths = excludeAvailability+ ? readAvailabilityModulePaths(projectRoot)+ : new Set();+ const hash = crypto.createHash('sha256');+ for (const relativePath of collectVerificationInputs(projectRoot)) {+ const portablePath = relativePath.replaceAll(path.sep, '/');+ if (excludedPaths.has(portablePath)) continue;+ const absolutePath = path.join(projectRoot, relativePath);+ hash.update(portablePath);+ hash.update('\0');+ if (relativePath === MANIFEST_FILE) {+ hash.update(normalizeLocalizationManifest(absolutePath, {+ excludeAvailability,+ }));+ } else {+ hash.update(fs.readFileSync(absolutePath));+ }+ hash.update('\0');+ }+ return hash.digest('hex');+}++function computeSpecFingerprint(spec) {+ return crypto+ .createHash('sha256')+ .update(stableStringify(spec))+ .digest('hex');+}++function createVerificationEvidence(projectRoot, spec) {+ return {+ schemaVersion: 1,+ inputFingerprint: computeVerificationInputFingerprint(projectRoot),+ inputFingerprintWithoutAvailability: computeVerificationInputFingerprint(+ projectRoot,+ { excludeAvailability: true }+ ),+ specFingerprint: computeSpecFingerprint(spec),+ };+}++// Reuse lets create-site skip repeating add-localization's browser run. That+// run must be complete and passed, and the project inputs must be unchanged.+// The run specification is intentionally not compared: add-localization's full+// run already covers every visible or interactive component under the same+// shared rules, so a matching plan adds no coverage proof. Only a targeted+// repair run is partial, so its evidence is refused.+function validateReusableVerificationReport(projectRoot, report) {+ const errors = [];+ if (!report || typeof report !== 'object' || Array.isArray(report)) {+ return ['Rendered verification report must contain a JSON object.'];+ }+ const summaryClaimsFailure =+ report.summary?.errors !== 0 || report.summary?.failed !== 0;+ if (summaryClaimsFailure) {+ errors.push('Rendered verification report contains failed checks.');+ }+ const hasResults = Array.isArray(report.results) && report.results.length > 0;+ const hasFindings = Array.isArray(report.findings);+ if (!hasResults || !hasFindings) {+ errors.push(+ 'Rendered verification report must contain detailed results and findings.'+ );+ } else {+ const malformedResult = report.results.some((result) =>+ !result || typeof result !== 'object' || Array.isArray(result) ||+ !isNonEmptyString(result.id) ||+ !['locale-smoke', 'component-state', 'locale-transition'].includes(+ result.type+ ) ||+ !Array.isArray(result.findings) ||+ !['passed', 'review', 'failed'].includes(result.status)+ );+ const malformedFinding = report.findings.some((finding) =>+ !finding || typeof finding !== 'object' || Array.isArray(finding) ||+ !isNonEmptyString(finding.caseId) ||+ !isNonEmptyString(finding.rule) ||+ !isNonEmptyString(finding.message) ||+ !['error', 'review'].includes(finding.severity)+ );+ if (malformedResult || malformedFinding) {+ errors.push(+ 'Rendered verification report contains malformed detailed evidence.'+ );+ } else {+ const computedSummary = summarizeFindings(+ report.findings,+ report.results+ );+ const summaryMatches = report.summary &&+ typeof report.summary === 'object' &&+ !Array.isArray(report.summary) &&+ Object.entries(computedSummary).every(+ ([field, value]) => report.summary[field] === value+ );+ if (!summaryMatches) {+ errors.push(+ 'Rendered verification report summary does not match its detailed evidence.'+ );+ }+ if (computedSummary.failed > 0 || computedSummary.errors > 0) {+ if (!summaryClaimsFailure) {+ errors.push('Rendered verification report contains failed checks.');+ }+ }+ }+ }+ if (!FULL_VERIFICATION_PROFILES.has(report.verification?.profile)) {+ errors.push(+ 'Rendered verification report must come from a standard or extensive ' ++ 'run; targeted repair evidence cannot be reused.'+ );+ }+ const evidence = report.verification?.evidence;+ if (!evidence || evidence.schemaVersion !== 1) {+ errors.push('Rendered verification report has no supported evidence fingerprint.');+ return errors;+ }+ const current = computeVerificationInputFingerprint(projectRoot);+ if (evidence.inputFingerprint !== current) {+ errors.push(+ 'Rendered verification evidence is stale because project verification inputs changed.'+ );+ }+ return errors;+}++function isNonEmptyString(value) {+ return typeof value === 'string' && value.trim().length > 0;+}++function collectVerificationInputs(projectRoot) {+ const files = [];+ for (const relativePath of SOURCE_FILES) {+ if (fs.existsSync(path.join(projectRoot, relativePath))) {+ files.push(relativePath);+ }+ }+ for (const root of SOURCE_ROOTS) {+ collectFiles(projectRoot, root, files);+ }+ return files.sort();+}++function collectFiles(projectRoot, relativePath, files) {+ const absolutePath = path.join(projectRoot, relativePath);+ if (!fs.existsSync(absolutePath)) return;+ for (const entry of fs.readdirSync(absolutePath, { withFileTypes: true })) {+ const child = path.join(relativePath, entry.name);+ if (entry.isDirectory()) {+ collectFiles(projectRoot, child, files);+ } else if (entry.isFile()) {+ files.push(child);+ }+ }+}++function normalizeLocalizationManifest(manifestPath, options = {}) {+ try {+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ // Finalization changes readiness/disposition metadata after the browser+ // run without changing what the application builds or renders. Availability+ // remains included because exposing or hiding a locale changes behavior.+ delete manifest.updatedAt;+ delete manifest.bidirectionalReadiness;+ if (options.excludeAvailability === true) {+ delete manifest.unavailableLocales;+ }+ return stableStringify(manifest);+ } catch {+ return fs.readFileSync(manifestPath);+ }+}++function readAvailabilityModulePaths(projectRoot) {+ // The manifest is read only to learn which managed file is the availability+ // module. If it cannot be parsed, nothing is excluded, so any availability+ // change still makes the evidence stale (fail-closed).+ let manifest;+ try {+ manifest = JSON.parse(+ fs.readFileSync(path.join(projectRoot, MANIFEST_FILE), 'utf8')+ );+ } catch {+ return new Set();+ }+ return new Set(+ findLocaleAvailabilityModulePaths(manifest).map((relativePath) =>+ path.posix.normalize(relativePath.replace(/\\/g, '/'))+ )+ );+}++function stableStringify(value) {+ if (Array.isArray(value)) {+ return `[${value.map(stableStringify).join(',')}]`;+ }+ if (value && typeof value === 'object') {+ return `{${Object.keys(value).sort().map((key) =>+ `${JSON.stringify(key)}:${stableStringify(value[key])}`+ ).join(',')}}`;+ }+ return JSON.stringify(value);+}++module.exports = {+ collectVerificationInputs,+ computeSpecFingerprint,+ computeVerificationInputFingerprint,+ createVerificationEvidence,+ validateReusableVerificationReport,+};diff --git a/plugins/power-pages/scripts/manage-localization-verification.js b/plugins/power-pages/scripts/manage-localization-verification.jsnew file mode 100644index 000000000..1359264f6--- /dev/null+++ b/plugins/power-pages/scripts/manage-localization-verification.js@@ -0,0 +1,156 @@+#!/usr/bin/env node+'use strict';++const path = require('path');+const {+ abandonLocalizationVerificationAudit,+ beginLocalizationVerification,+ extendLocalizationVerification,+ finalizeLocalizationVerification,+ formatManualAvailabilityRestore,+ markLocalizationVerificationFailed,+} = require('./lib/localization-verification-transaction');++const USAGE =+ 'Usage: manage-localization-verification.js ' ++ '(--begin --locales <tag[,tag]> [--profile <standard|extensive>] | ' ++ '--extend --profile extensive | --fail | ' ++ '--finalize [--manual-review-completed] [--rendered-review-completed]) ' ++ '--projectRoot <path>';++function parseArgs(argv) {+ const parsed = {};+ const seen = new Set();+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (['--begin', '--extend', '--fail', '--finalize'].includes(arg)) {+ if (parsed.operation) throw new Error('Choose exactly one operation.');+ parsed.operation = arg.slice(2);+ continue;+ }+ if (arg === '--manual-review-completed') {+ if (parsed.manualReviewCompleted) {+ throw new Error(+ 'Argument "--manual-review-completed" may be specified only once.'+ );+ }+ parsed.manualReviewCompleted = true;+ continue;+ }+ if (arg === '--rendered-review-completed') {+ if (parsed.renderedReviewCompleted) {+ throw new Error(+ 'Argument "--rendered-review-completed" may be specified only once.'+ );+ }+ parsed.renderedReviewCompleted = true;+ continue;+ }+ if (!['--projectRoot', '--locales', '--profile'].includes(arg)) {+ throw new Error(`Unknown or misplaced argument "${arg}".\n${USAGE}`);+ }+ if (seen.has(arg)) {+ throw new Error(`Argument "${arg}" may be specified only once.\n${USAGE}`);+ }+ seen.add(arg);+ const value = argv[index + 1];+ if (typeof value !== 'string' || !value.trim() ||+ value.startsWith('--')) {+ throw new Error(`Argument "${arg}" requires a value.\n${USAGE}`);+ }+ if (arg === '--projectRoot') {+ parsed.projectRoot = path.resolve(value);+ } else if (arg === '--locales') {+ parsed.locales = value+ .split(',')+ .map((locale) => locale.trim())+ .filter(Boolean);+ } else {+ parsed.profile = value;+ }+ index += 1;+ }+ if (!parsed.operation || !parsed.projectRoot) {+ throw new Error(USAGE);+ }+ if (parsed.operation === 'begin' && (!parsed.locales || !parsed.locales.length)) {+ throw new Error('--begin requires --locales.');+ }+ if (parsed.operation !== 'begin' && parsed.locales) {+ throw new Error('--locales is valid only with --begin.');+ }+ if (parsed.operation === 'extend' && parsed.profile !== 'extensive') {+ throw new Error('--extend requires --profile extensive.');+ }+ if (!['begin', 'extend'].includes(parsed.operation) && parsed.profile) {+ throw new Error('--profile is valid only with --begin or --extend.');+ }+ if (parsed.manualReviewCompleted && parsed.operation !== 'finalize') {+ throw new Error(+ '--manual-review-completed is valid only with --finalize.'+ );+ }+ if (parsed.renderedReviewCompleted && parsed.operation !== 'finalize') {+ throw new Error(+ '--rendered-review-completed is valid only with --finalize.'+ );+ }+ return parsed;+}++function main() {+ const args = parseArgs(process.argv.slice(2));+ let transaction;+ if (args.operation === 'begin') {+ transaction = beginLocalizationVerification(+ args.projectRoot,+ args.locales,+ args.profile || 'extensive'+ );+ } else if (args.operation === 'extend') {+ transaction = extendLocalizationVerification(+ args.projectRoot,+ args.profile+ );+ } else if (args.operation === 'fail') {+ transaction = markLocalizationVerificationFailed(args.projectRoot);+ abandonLocalizationVerificationAudit(args.projectRoot, transaction.runId);+ // The transaction is now failed either way; a manual restore only adds one+ // step before --finalize, so report it without failing this command.+ const manualRestoreMessage = formatManualAvailabilityRestore(transaction);+ if (manualRestoreMessage) {+ process.stderr.write(`${manualRestoreMessage}\n`);+ }+ } else {+ const {+ validateLocalization,+ } = require('../skills/add-localization/scripts/validate-localization');+ const errors = validateLocalization(args.projectRoot, {+ allowTransactionFinalization: true,+ });+ if (errors.length > 0) {+ throw new Error(+ `Localization must be fully valid before finalization:\n- ` ++ errors.join('\n- ')+ );+ }+ transaction = finalizeLocalizationVerification(args.projectRoot, {+ manualReviewCompleted: args.manualReviewCompleted,+ renderedReviewCompleted: args.renderedReviewCompleted,+ });+ }+ process.stdout.write(`${JSON.stringify(transaction, null, 2)}\n`);+}++if (require.main === module) {+ try {+ main();+ } catch (error) {+ process.stderr.write(`${error.message}\n`);+ process.exitCode = 1;+ }+}++module.exports = {+ parseArgs,+};diff --git a/plugins/power-pages/scripts/render-add-localization-plan.js b/plugins/power-pages/scripts/render-add-localization-plan.jsnew file mode 100644index 000000000..61dc5cc16--- /dev/null+++ b/plugins/power-pages/scripts/render-add-localization-plan.js@@ -0,0 +1,719 @@+#!/usr/bin/env node+/**+ * Renders the add-localization implementation plan.+ *+ * The HTML artifact is human-readable approval evidence only. Later phases use+ * the approved in-memory configuration and the final localization manifest,+ * not this document, as their source of truth.+ */++'use strict';++const fs = require('fs');+const path = require('path');+const { renderTemplate, parseArgs } = require('./lib/render-template');+const {+ KNOWN_PACKAGES,+ getLocalizationModeAvailability,+ resolveLocale,+} = require('./lib/localization-config');++const args = parseArgs(process.argv);++if (!args.output || (!args['data-inline'] && !args.data)) {+ console.error(+ 'Usage: node render-add-localization-plan.js --output <path> --data-inline \'<json>\'\n' ++ ' node render-add-localization-plan.js --output <path> --data <json-file>'+ );+ process.exit(1);+}++const templatePath = path.join(+ __dirname,+ '..',+ 'skills',+ 'add-localization',+ 'assets',+ 'add-localization-plan.html'+);++const requiredKeys = [+ 'SITE_NAME',+ 'PLAN_TITLE',+ 'SOURCE_LANGUAGE',+ 'SOURCE_LOCALE',+ 'SOURCE_DIRECTION',+ 'FRAMEWORK',+ 'INVOCATION_CONTEXT',+ 'OPERATION',+ 'EXISTING_LOCALIZATION_DETECTED',+ 'SUMMARY',+ 'PLAN_LABELS',+ 'DISCOVERY_DATA',+ 'CONFIGURATION_DATA',+ 'LOCALES_DATA',+ 'FILES_DATA',+ 'READINESS_DATA',+ 'VALIDATION_DATA',+ 'LIMITATIONS_DATA',+];++const requiredLabelPaths = [+ 'navigation.group',+ 'navigation.overview',+ 'navigation.languages',+ 'navigation.changes',+ 'navigation.readiness',+ 'navigation.verification',+ 'overview.title',+ 'overview.description',+ 'overview.framework',+ 'overview.invocation',+ 'overview.operation',+ 'overview.existingSetup',+ 'overview.configuration',+ 'overview.frameworkEvidence',+ 'overview.existingDetails',+ 'overview.conflicts',+ 'overview.noConflicts',+ 'configuration.package',+ 'configuration.mode',+ 'configuration.defaultLocale',+ 'configuration.translation',+ 'configuration.selector',+ 'configuration.verification',+ 'configuration.selection',+ 'configuration.evidenceSource',+ 'configuration.evidence',+ 'configuration.initialization',+ 'configuration.rootRepair',+ 'languages.title',+ 'languages.description',+ 'languages.language',+ 'languages.locale',+ 'languages.direction',+ 'languages.roles',+ 'languages.availability',+ 'changes.title',+ 'changes.description',+ 'changes.path',+ 'changes.action',+ 'changes.reason',+ 'readiness.title',+ 'readiness.description',+ 'readiness.transition',+ 'readiness.findings',+ 'readiness.noFindings',+ 'readiness.location',+ 'readiness.rule',+ 'readiness.scope',+ 'readiness.affectedLocales',+ 'readiness.remediation',+ 'readiness.componentScope',+ 'readiness.component',+ 'readiness.classification',+ 'readiness.reason',+ 'readiness.states',+ 'readiness.viewports',+ 'readiness.checks',+ 'readiness.physicalExceptions',+ 'readiness.scriptFonts',+ 'readiness.unavailableLocales',+ 'readiness.none',+ 'verification.title',+ 'verification.description',+ 'verification.checks',+ 'verification.limitations',+ 'verification.noLimitations',+ 'status.new',+ 'status.preserved',+ 'status.changed',+ 'status.create',+ 'status.update',+ 'status.preserve',+ 'status.replace',+ 'status.skip',+ 'status.source',+ 'status.default',+ 'status.existing',+ 'status.added',+ 'status.available',+ 'status.pendingRemediation',+ 'status.verified',+ 'status.unverified',+ 'status.yes',+ 'status.no',+ 'packageSelection.recommended',+ 'packageSelection.alternative',+ 'packageSelection.preserved',+ 'evidenceSource.knownCapability',+ 'evidenceSource.packageDocumentation',+ 'evidenceSource.officialDocumentation',+ 'evidenceSource.userApproved',+ 'severity.error',+ 'severity.review',+ 'classification.directionNeutral',+ 'classification.directionAware',+ 'classification.directionFixed',+ 'classification.unknownThirdParty',+ 'viewport.desktop',+ 'viewport.narrow',+ 'operation.create',+ 'operation.addLanguages',+ 'operation.repair',+ 'operation.reconfigure',+ 'invocation.direct',+ 'invocation.createSite',+ 'footer.aiWarning',+];++const CHANGE_STATUSES = new Set(['new', 'preserved', 'changed']);+const FILE_ACTIONS = new Set(['create', 'update', 'preserve', 'replace', 'skip']);+const LOCALE_ROLES = new Set(['source', 'default', 'existing', 'added']);+const AVAILABILITY = new Set(['available', 'pending-remediation']);+const FINDING_SCOPES = new Set(['locale', 'direction', 'shared', 'global']);+const OPERATIONS = new Set(['create', 'add-languages', 'repair', 'reconfigure']);+const INVOCATIONS = new Set(['direct', 'create-site']);+const PACKAGE_SELECTIONS = new Set(['recommended', 'alternative', 'preserved']);+const EVIDENCE_SOURCES = new Set([+ 'known-capability',+ 'package-documentation',+ 'official-documentation',+ 'user-approved',+]);+const TRANSLATION_METHODS = new Set(['agent', 'blank']);+const BIDIRECTIONAL_CLASSIFICATIONS = new Set([+ 'direction-neutral',+ 'direction-aware',+ 'direction-fixed',+ 'unknown-third-party',+]);+const BIDIRECTIONAL_VIEWPORTS = new Set(['desktop', 'narrow']);+const REQUIRED_VALIDATION_IDS = [+ 'independent-validator',+ 'project-build',+ 'package-initialization',+ 'resource-completeness',+ 'protected-tokens',+ 'locale-navigation',+ 'locale-state',+ 'fallback-behavior',+ 'document-lang-dir',+ 'browser-console',+ 'representative-routes',+ 'bidirectional-content',+ 'localized-formatting',+ 'script-fonts',+ 'directional-components',+ 'accessibility',+];++function getNestedValue(value, dottedPath) {+ return dottedPath.split('.').reduce(+ (current, key) => current && current[key],+ value+ );+}++function validateString(value, name, errors) {+ if (typeof value !== 'string' || !value.trim()) {+ errors.push(`${name} must be a non-empty string.`);+ }+}++function validatePlanData(data) {+ const errors = [];+ for (const key of ['SITE_NAME', 'PLAN_TITLE', 'SOURCE_LANGUAGE', 'SUMMARY']) {+ validateString(data[key], key, errors);+ }+ if (!['React', 'Vue', 'Angular', 'Astro'].includes(data.FRAMEWORK)) {+ errors.push('FRAMEWORK must be React, Vue, Angular, or Astro.');+ }+ const source = resolveLocale(data.SOURCE_LOCALE);+ if (!source.valid || !source.locale) {+ errors.push(`SOURCE_LOCALE must be a valid BCP-47 locale: ${data.SOURCE_LOCALE}`);+ } else {+ if (source.locale !== data.SOURCE_LOCALE) {+ errors.push(`SOURCE_LOCALE must be canonical BCP-47. Use "${source.locale}".`);+ }+ if (source.direction !== data.SOURCE_DIRECTION) {+ errors.push(+ `SOURCE_DIRECTION "${data.SOURCE_DIRECTION}" does not match ` ++ `${source.locale}, which resolves to "${source.direction}".`+ );+ }+ }++ if (!OPERATIONS.has(data.OPERATION)) {+ errors.push('OPERATION must be create, add-languages, repair, or reconfigure.');+ }+ if (!INVOCATIONS.has(data.INVOCATION_CONTEXT)) {+ errors.push('INVOCATION_CONTEXT must be direct or create-site.');+ }+ if (typeof data.EXISTING_LOCALIZATION_DETECTED !== 'boolean') {+ errors.push('EXISTING_LOCALIZATION_DETECTED must be boolean.');+ }++ const discovery = data.DISCOVERY_DATA;+ if (!discovery || Array.isArray(discovery) || typeof discovery !== 'object') {+ errors.push('DISCOVERY_DATA must be an object.');+ } else {+ for (const key of ['frameworkEvidence', 'existingSetup', 'conflicts']) {+ if (!Array.isArray(discovery[key]) ||+ discovery[key].some((entry) => typeof entry !== 'string' || !entry.trim())) {+ errors.push(`DISCOVERY_DATA.${key} must be an array of non-empty strings.`);+ }+ }+ if (!discovery.frameworkEvidence?.length) {+ errors.push('DISCOVERY_DATA.frameworkEvidence must not be empty.');+ }+ }++ const missingLabels = requiredLabelPaths.filter((labelPath) => {+ const label = getNestedValue(data.PLAN_LABELS, labelPath);+ return typeof label !== 'string' || !label.trim();+ });+ if (missingLabels.length) {+ errors.push(`PLAN_LABELS is missing localized values: ${missingLabels.join(', ')}`);+ } else if (!getNestedValue(data.PLAN_LABELS, 'overview.description').includes('{siteName}')) {+ errors.push('PLAN_LABELS.overview.description must preserve {siteName}.');+ }++ const config = data.CONFIGURATION_DATA;+ if (!config || Array.isArray(config) || typeof config !== 'object') {+ errors.push('CONFIGURATION_DATA must be an object.');+ } else {+ for (const key of ['package', 'mode', 'defaultLocale']) {+ const item = config[key];+ if (!item || typeof item !== 'object') {+ errors.push(`CONFIGURATION_DATA.${key} must be an object.`);+ continue;+ }+ validateString(item.value, `CONFIGURATION_DATA.${key}.value`, errors);+ if (!CHANGE_STATUSES.has(item.status)) {+ errors.push(+ `CONFIGURATION_DATA.${key}.status must be new, preserved, or changed.`+ );+ }+ }+ if (typeof data.FRAMEWORK === 'string' &&+ typeof config.mode?.value === 'string') {+ const availability = getLocalizationModeAvailability(+ data.FRAMEWORK.toLowerCase(),+ config.mode.value+ );+ if (!availability.available) {+ errors.push(availability.reason);+ }+ }+ if (config.package && typeof config.package === 'object') {+ validateString(config.package.name, 'CONFIGURATION_DATA.package.name', errors);+ validateString(config.package.version, 'CONFIGURATION_DATA.package.version', errors);+ const knownPackage = KNOWN_PACKAGES[config.package.name];+ if (knownPackage && typeof data.FRAMEWORK === 'string' &&+ typeof config.mode?.value === 'string' &&+ (knownPackage.framework !== data.FRAMEWORK.toLowerCase() ||+ knownPackage.mode !== config.mode.value)) {+ errors.push(+ `Package "${config.package.name}" is for ${knownPackage.framework} ` ++ `${knownPackage.mode} localization, not ` ++ `${data.FRAMEWORK.toLowerCase()} ${config.mode.value}.`+ );+ }+ }+ for (const key of ['translation', 'selector']) {+ if (!config[key] || typeof config[key] !== 'object') {+ errors.push(`CONFIGURATION_DATA.${key} must be an object.`);+ } else {+ validateString(+ config[key].value,+ `CONFIGURATION_DATA.${key}.value`,+ errors+ );+ validateString(+ config[key].description,+ `CONFIGURATION_DATA.${key}.description`,+ errors+ );+ if ('status' in config[key]) {+ errors.push(`CONFIGURATION_DATA.${key} must not define status.`);+ }+ }+ }+ if (config.translation && !TRANSLATION_METHODS.has(config.translation.method)) {+ errors.push('CONFIGURATION_DATA.translation.method must be agent or blank.');+ }+ if (config.translation?.method === 'agent') {+ validateString(+ config.translation.warning,+ 'CONFIGURATION_DATA.translation.warning',+ errors+ );+ }+ if (config.package && !['verified', 'unverified'].includes(config.package.verification)) {+ errors.push('CONFIGURATION_DATA.package.verification must be verified or unverified.');+ }+ if (config.package && !PACKAGE_SELECTIONS.has(config.package.selection)) {+ errors.push(+ 'CONFIGURATION_DATA.package.selection must be recommended, alternative, or preserved.'+ );+ }+ if (config.package && !EVIDENCE_SOURCES.has(config.package.evidenceSource)) {+ errors.push('CONFIGURATION_DATA.package.evidenceSource is invalid.');+ }+ if (config.package?.verification === 'unverified' &&+ config.package?.evidenceSource !== 'user-approved') {+ errors.push(+ 'An unverified package must use evidenceSource "user-approved".'+ );+ }+ if (config.package?.evidenceSource === 'official-documentation' &&+ !config.package?.evidenceUrl) {+ errors.push(+ 'Official-documentation package evidence requires an HTTPS evidenceUrl.'+ );+ }+ if (config.package?.evidenceUrl !== undefined &&+ !/^https:\/\//i.test(config.package.evidenceUrl)) {+ errors.push('CONFIGURATION_DATA.package.evidenceUrl must be an HTTPS URL.');+ }+ if (config.package?.initializationEvidence !== null &&+ config.package?.initializationEvidence !== undefined) {+ const evidence = config.package.initializationEvidence;+ if (!evidence || typeof evidence !== 'object') {+ errors.push('CONFIGURATION_DATA.package.initializationEvidence must be null or an object.');+ } else {+ validateString(+ evidence.file,+ 'CONFIGURATION_DATA.package.initializationEvidence.file',+ errors+ );+ validateString(+ evidence.marker,+ 'CONFIGURATION_DATA.package.initializationEvidence.marker',+ errors+ );+ }+ }+ if (config.rootDocumentRepair !== null &&+ config.rootDocumentRepair !== undefined) {+ const repair = config.rootDocumentRepair;+ if (!repair || typeof repair !== 'object') {+ errors.push('CONFIGURATION_DATA.rootDocumentRepair must be null or an object.');+ } else {+ validateString(repair.file, 'CONFIGURATION_DATA.rootDocumentRepair.file', errors);+ validateString(repair.lang, 'CONFIGURATION_DATA.rootDocumentRepair.lang', errors);+ if (!['ltr', 'rtl'].includes(repair.dir)) {+ errors.push('CONFIGURATION_DATA.rootDocumentRepair.dir must be ltr or rtl.');+ } else {+ const repairLocale = resolveLocale(repair.lang);+ if (!repairLocale.valid || repairLocale.locale !== repair.lang ||+ repairLocale.direction !== repair.dir) {+ errors.push(+ 'CONFIGURATION_DATA.rootDocumentRepair lang/dir must be a canonical matching locale pair.'+ );+ }+ }+ }+ }+ }++ if (!Array.isArray(data.LOCALES_DATA) || data.LOCALES_DATA.length < 2) {+ errors.push('LOCALES_DATA must contain at least two locale entries.');+ } else {+ let sourceCount = 0;+ let defaultCount = 0;+ const localeTags = [];+ for (const [index, localeEntry] of data.LOCALES_DATA.entries()) {+ const prefix = `LOCALES_DATA[${index}]`;+ const resolved = resolveLocale(localeEntry?.locale);+ validateString(localeEntry?.language, `${prefix}.language`, errors);+ if (!resolved.valid || !resolved.locale || resolved.locale !== localeEntry?.locale) {+ errors.push(`${prefix}.locale must be a canonical BCP-47 locale.`);+ } else if (resolved.direction !== localeEntry.direction) {+ errors.push(`${prefix}.direction does not match ${resolved.locale}.`);+ } else {+ localeTags.push(resolved.locale);+ }+ if (new Set(localeTags).size !== localeTags.length) {+ errors.push('LOCALES_DATA must not contain duplicate locale tags.');+ }+ if (!Array.isArray(localeEntry?.roles) || !localeEntry.roles.length ||+ localeEntry.roles.some((role) => !LOCALE_ROLES.has(role))) {+ errors.push(`${prefix}.roles contains an invalid or empty role set.`);+ } else {+ if (new Set(localeEntry.roles).size !== localeEntry.roles.length) {+ errors.push(`${prefix}.roles must not contain duplicates.`);+ }+ const lifecycleRoles = localeEntry.roles.filter(+ (role) => role === 'existing' || role === 'added'+ );+ if (lifecycleRoles.length !== 1) {+ errors.push(`${prefix}.roles must identify exactly one of existing or added.`);+ }+ if (localeEntry.roles.includes('source')) sourceCount += 1;+ if (localeEntry.roles.includes('default')) defaultCount += 1;+ }+ if (!AVAILABILITY.has(localeEntry?.availability)) {+ errors.push(`${prefix}.availability must be available or pending-remediation.`);+ }+ }+ if (sourceCount !== 1) errors.push('LOCALES_DATA must identify exactly one source locale.');+ if (defaultCount !== 1) errors.push('LOCALES_DATA must identify exactly one default locale.');+ const sourceEntry = data.LOCALES_DATA.find((entry) => entry.roles?.includes('source'));+ if (sourceEntry && sourceEntry.locale !== data.SOURCE_LOCALE) {+ errors.push('SOURCE_LOCALE must match the locale with the source role.');+ }+ if (sourceEntry && sourceEntry.availability !== 'available') {+ errors.push('The source locale must remain available.');+ }+ if (sourceEntry && !sourceEntry.roles.includes('existing')) {+ errors.push('The source locale must use the existing role, not added.');+ }+ const defaultEntry = data.LOCALES_DATA.find((entry) => entry.roles?.includes('default'));+ if (defaultEntry && config?.defaultLocale?.value !== defaultEntry.locale) {+ errors.push('CONFIGURATION_DATA.defaultLocale.value must match the default locale role.');+ }+ if (defaultEntry && defaultEntry.availability !== 'available') {+ errors.push('The default locale must remain available.');+ }+ }++ if (!Array.isArray(data.FILES_DATA) || !data.FILES_DATA.length) {+ errors.push('FILES_DATA must contain at least one file or package change.');+ } else {+ data.FILES_DATA.forEach((entry, index) => {+ validateString(entry?.path, `FILES_DATA[${index}].path`, errors);+ validateString(entry?.reason, `FILES_DATA[${index}].reason`, errors);+ if (!FILE_ACTIONS.has(entry?.action)) {+ errors.push(`FILES_DATA[${index}].action is invalid.`);+ }+ });+ }++ const readiness = data.READINESS_DATA;+ if (!readiness || Array.isArray(readiness) || typeof readiness !== 'object') {+ errors.push('READINESS_DATA must be an object.');+ } else {+ validateString(readiness.transition, 'READINESS_DATA.transition', errors);+ for (const key of [+ 'findings',+ 'componentScope',+ 'physicalExceptions',+ 'scriptFonts',+ 'unavailableLocales',+ ]) {+ if (!Array.isArray(readiness[key])) {+ errors.push(`READINESS_DATA.${key} must be an array.`);+ }+ }+ if (Array.isArray(readiness.findings)) {+ readiness.findings.forEach((finding, index) => {+ const prefix = `READINESS_DATA.findings[${index}]`;+ if (!['error', 'review'].includes(finding?.severity)) {+ errors.push(`${prefix}.severity must be error or review.`);+ }+ for (const key of ['file', 'rule', 'message']) {+ validateString(finding?.[key], `${prefix}.${key}`, errors);+ }+ if (!Number.isInteger(finding?.line) || finding.line < 1) {+ errors.push(`${prefix}.line must be a positive integer.`);+ }+ validateString(finding?.remediation, `${prefix}.remediation`, errors);+ if (!FINDING_SCOPES.has(finding?.scope)) {+ errors.push(`${prefix}.scope must be locale, direction, shared, or global.`);+ }+ const configuredLocales = Array.isArray(data.LOCALES_DATA)+ ? data.LOCALES_DATA.map((entry) => entry.locale)+ : [];+ if (!Array.isArray(finding?.affectedLocales) ||+ finding.affectedLocales.length === 0 ||+ finding.affectedLocales.some(+ (locale) => !configuredLocales.includes(locale)+ ) ||+ new Set(finding.affectedLocales).size !== finding.affectedLocales.length) {+ errors.push(+ `${prefix}.affectedLocales must contain unique configured locale tags.`+ );+ } else if (finding.scope === 'locale' &&+ finding.affectedLocales.length !== 1) {+ errors.push(`${prefix} locale findings must affect exactly one locale.`);+ } else if (finding.scope === 'global') {+ const expected = [...configuredLocales].sort();+ const actual = [...finding.affectedLocales].sort();+ if (JSON.stringify(expected) !== JSON.stringify(actual)) {+ errors.push(`${prefix} global findings must affect every configured locale.`);+ }+ } else if (finding.scope === 'direction') {+ if (!['ltr', 'rtl'].includes(finding.direction)) {+ errors.push(`${prefix}.direction must be ltr or rtl for direction scope.`);+ } else {+ const expected = data.LOCALES_DATA+ .filter((entry) => entry.direction === finding.direction)+ .map((entry) => entry.locale)+ .sort();+ const actual = [...finding.affectedLocales].sort();+ if (JSON.stringify(expected) !== JSON.stringify(actual)) {+ errors.push(+ `${prefix} direction findings must affect every configured ` ++ `${finding.direction} locale.`+ );+ }+ }+ }+ });+ }+ if (Array.isArray(readiness.componentScope)) {+ if (!readiness.componentScope.length) {+ errors.push(+ 'READINESS_DATA.componentScope must contain every visible or interactive component.'+ );+ }+ readiness.componentScope.forEach((entry, index) => {+ const prefix = `READINESS_DATA.componentScope[${index}]`;+ for (const key of ['component', 'reason']) {+ validateString(entry?.[key], `${prefix}.${key}`, errors);+ }+ if (!BIDIRECTIONAL_CLASSIFICATIONS.has(entry?.classification)) {+ errors.push(+ `${prefix}.classification must be direction-neutral, direction-aware, ` ++ 'direction-fixed, or unknown-third-party.'+ );+ }+ for (const key of ['states', 'checks']) {+ if (!Array.isArray(entry?.[key]) || !entry[key].length ||+ entry[key].some((value) => typeof value !== 'string' || !value.trim())) {+ errors.push(`${prefix}.${key} must be a non-empty array of localized strings.`);+ }+ }+ if (!Array.isArray(entry?.viewports) || !entry.viewports.length ||+ entry.viewports.some((value) => !BIDIRECTIONAL_VIEWPORTS.has(value)) ||+ new Set(entry.viewports).size !== entry.viewports.length) {+ errors.push(`${prefix}.viewports must contain unique desktop and/or narrow values.`);+ }+ });+ }+ for (const key of ['physicalExceptions', 'scriptFonts', 'unavailableLocales']) {+ if (Array.isArray(readiness[key]) &&+ readiness[key].some((entry) => typeof entry !== 'string' || !entry.trim())) {+ errors.push(`READINESS_DATA.${key} must contain only non-empty strings.`);+ }+ }+ if (Array.isArray(readiness.unavailableLocales) && Array.isArray(data.LOCALES_DATA)) {+ const expectedUnavailable = data.LOCALES_DATA+ .filter((entry) => entry.availability === 'pending-remediation')+ .map((entry) => entry.locale)+ .sort();+ const actualUnavailable = [...readiness.unavailableLocales].sort();+ if (JSON.stringify(expectedUnavailable) !== JSON.stringify(actualUnavailable)) {+ errors.push(+ 'READINESS_DATA.unavailableLocales must match locales marked pending-remediation.'+ );+ }+ if (Array.isArray(readiness.findings)) {+ const localeAvailability = new Map(+ data.LOCALES_DATA.map((entry) => [entry.locale, entry.availability])+ );+ for (const finding of readiness.findings) {+ for (const locale of finding?.affectedLocales || []) {+ if (localeAvailability.get(locale) !== 'pending-remediation') {+ errors.push(+ `Readiness finding "${finding.rule || 'unknown'}" requires affected ` ++ `locale ${locale} to remain pending-remediation.`+ );+ }+ }+ }+ }+ }+ }++ if (!Array.isArray(data.VALIDATION_DATA)) {+ errors.push('VALIDATION_DATA must be an array.');+ } else {+ const ids = [];+ data.VALIDATION_DATA.forEach((entry, index) => {+ validateString(entry?.id, `VALIDATION_DATA[${index}].id`, errors);+ validateString(+ entry?.description,+ `VALIDATION_DATA[${index}].description`,+ errors+ );+ if (typeof entry?.id === 'string') ids.push(entry.id);+ });+ if (new Set(ids).size !== ids.length) {+ errors.push('VALIDATION_DATA ids must be unique.');+ }+ const missingValidation = REQUIRED_VALIDATION_IDS.filter((id) => !ids.includes(id));+ if (missingValidation.length) {+ errors.push(+ `VALIDATION_DATA is missing required checks: ${missingValidation.join(', ')}`+ );+ }+ }+ if (!Array.isArray(data.LIMITATIONS_DATA) ||+ data.LIMITATIONS_DATA.some(+ (entry) => typeof entry !== 'string' || !entry.trim()+ )) {+ errors.push('LIMITATIONS_DATA must be an array of non-empty strings.');+ }++ return errors;+}++function withDerivedData(data) {+ return {+ ...data,+ SITE_NAME_DATA: { text: String(data.SITE_NAME ?? '') },+ SUMMARY_DATA: { text: String(data.SUMMARY ?? '') },+ META_DATA: {+ framework: data.FRAMEWORK,+ invocationContext: data.INVOCATION_CONTEXT,+ operation: data.OPERATION,+ existingLocalizationDetected: data.EXISTING_LOCALIZATION_DETECTED,+ },+ };+}++function render(data) {+ const errors = validatePlanData(data);+ if (errors.length) {+ console.error(`Invalid add-localization plan data:\n- ${errors.join('\n- ')}`);+ process.exit(1);+ }++ renderTemplate({+ templatePath,+ outputPath: path.resolve(args.output),+ dataObject: withDerivedData(data),+ requiredKeys,+ escapeStringValues: true,+ });+}++if (args['data-inline']) {+ try {+ render(JSON.parse(args['data-inline']));+ } catch (error) {+ if (error instanceof SyntaxError) {+ console.error('Error: --data-inline value is not valid JSON');+ process.exit(1);+ }+ throw error;+ }+} else {+ const dataPath = path.resolve(args.data);+ if (!fs.existsSync(dataPath)) {+ console.error(`Data file not found: ${dataPath}`);+ process.exit(1);+ }+ try {+ render(JSON.parse(fs.readFileSync(dataPath, 'utf8')));+ } catch (error) {+ if (error instanceof SyntaxError) {+ console.error('Error: --data file is not valid JSON');+ process.exit(1);+ }+ throw error;+ }+}diff --git a/plugins/power-pages/scripts/render-createsite-plan.js b/plugins/power-pages/scripts/render-createsite-plan.jsindex 22b72c78e..9c6e2337d 100644--- a/plugins/power-pages/scripts/render-createsite-plan.js+++ b/plugins/power-pages/scripts/render-createsite-plan.js@@ -16,14 +16,16 @@** Required keys in the data:* SITE_NAME, PLAN_TITLE, FRAMEWORK, SITE_LANGUAGE, SITE_LOCALE, SITE_DIRECTION,- * AESTHETIC, MOOD, SUMMARY,+ * AESTHETIC, MOOD, SUMMARY, PLAN_LABELS,* DESIGN_DIRECTION_DATA, TYPOGRAPHY_DATA, PALETTE_DATA, MOTION_DATA, BACKGROUNDS_DATA,- * PAGES_DATA, COMPONENTS_DATA, ROUTES_DATA, REVIEW_DATA, DEPLOYMENT_DATA+ * PAGES_DATA, COMPONENTS_DATA, ROUTES_DATA, BIDIRECTIONAL_REVIEW_DATA,+ * REVIEW_DATA, DEPLOYMENT_DATA*/const path = require('path');const fs = require('fs');const { renderTemplate, parseArgs } = require('./lib/render-template');+const { resolveLocale } = require('./lib/localization-config');const args = parseArgs(process.argv);@@ -56,6 +58,7 @@ const requiredKeys = ['MOOD','SUMMARY','DESIGN_DIRECTION_DATA',+ 'PLAN_LABELS','TYPOGRAPHY_DATA','PALETTE_DATA','MOTION_DATA',@@ -63,23 +66,206 @@ const requiredKeys = ['PAGES_DATA','COMPONENTS_DATA','ROUTES_DATA',+ 'BIDIRECTIONAL_REVIEW_DATA','REVIEW_DATA','DEPLOYMENT_DATA',];+const requiredLabelPaths = [+ 'navigation.group',+ 'navigation.overview',+ 'navigation.design',+ 'navigation.pages',+ 'navigation.deployment',+ 'overview.title',+ 'overview.description',+ 'overview.stats.pages',+ 'overview.stats.components',+ 'overview.stats.routes',+ 'overview.nextSteps.title',+ 'overview.nextSteps.design.title',+ 'overview.nextSteps.design.description',+ 'overview.nextSteps.components.title',+ 'overview.nextSteps.components.descriptionOne',+ 'overview.nextSteps.components.descriptionOther',+ 'overview.nextSteps.pages.title',+ 'overview.nextSteps.pages.descriptionOne',+ 'overview.nextSteps.pages.descriptionOther',+ 'overview.nextSteps.critique.title',+ 'overview.nextSteps.critique.description',+ 'overview.nextSteps.verify.title',+ 'overview.nextSteps.verify.description',+ 'design.title',+ 'design.description',+ 'design.direction.title',+ 'design.direction.heroConcept',+ 'design.direction.signatureMoment',+ 'design.direction.primaryAction',+ 'design.direction.secondaryAction',+ 'design.direction.principalDoubt',+ 'design.direction.proofStrategy',+ 'design.direction.brandSource',+ 'design.direction.audience',+ 'design.typography',+ 'design.palette',+ 'design.motion',+ 'design.backgrounds',+ 'design.primaryRole',+ 'design.secondaryRole',+ 'pages.title',+ 'pages.description',+ 'pages.pages',+ 'pages.components',+ 'pages.routing',+ 'pages.path',+ 'pages.page',+ 'pages.content',+ 'pages.componentsUsed',+ 'pages.usedBy',+ 'pages.noComponents',+ 'bidirectional.title',+ 'bidirectional.description',+ 'bidirectional.classification',+ 'bidirectional.reason',+ 'bidirectional.states',+ 'bidirectional.viewports',+ 'bidirectional.checks',+ 'bidirectional.classifications.directionNeutral',+ 'bidirectional.classifications.directionAware',+ 'bidirectional.classifications.directionFixed',+ 'bidirectional.classifications.unknownThirdParty',+ 'bidirectional.viewport.desktop',+ 'bidirectional.viewport.narrow',+ 'deployment.title',+ 'deployment.description',+ 'deployment.verify',+ 'deployment.agentChecks',+ 'deployment.agentChecksDescription',+ 'deployment.makerReview',+ 'deployment.makerReviewDescription',+ 'deployment.options',+ 'deployment.recommended',+ 'common.noneSpecified',+ 'footer.aiWarning',+];++const BIDIRECTIONAL_CLASSIFICATIONS = new Set([+ 'direction-neutral',+ 'direction-aware',+ 'direction-fixed',+ 'unknown-third-party',+]);+const BIDIRECTIONAL_VIEWPORTS = new Set(['desktop', 'narrow']);++function getNestedValue(value, dottedPath) {+ return dottedPath.split('.').reduce(+ (current, key) => current && current[key],+ value+ );+}++function validatePlanData(dataObject) {+ const locale = resolveLocale(dataObject.SITE_LOCALE);+ if (!locale.valid || !locale.locale) {+ return [`SITE_LOCALE must be a valid BCP-47 locale: ${dataObject.SITE_LOCALE}`];+ }+ if (locale.locale !== dataObject.SITE_LOCALE) {+ return [+ `SITE_LOCALE must be canonical BCP-47. Use "${locale.locale}" instead of ` ++ `"${dataObject.SITE_LOCALE}".`,+ ];+ }+ if (!['ltr', 'rtl'].includes(dataObject.SITE_DIRECTION)) {+ return ['SITE_DIRECTION must be either "ltr" or "rtl".'];+ }+ if (locale.direction !== dataObject.SITE_DIRECTION) {+ return [+ `SITE_DIRECTION "${dataObject.SITE_DIRECTION}" does not match ` ++ `${locale.locale}, which resolves to "${locale.direction}".`,+ ];+ }++ if (!dataObject.REVIEW_DATA || Array.isArray(dataObject.REVIEW_DATA) ||+ typeof dataObject.REVIEW_DATA !== 'object') {+ return ['REVIEW_DATA must be an object with agentChecks and makerReview arrays.'];+ }+ const invalidReviewGroups = ['agentChecks', 'makerReview'].filter((group) => {+ const entries = dataObject.REVIEW_DATA[group];+ return !Array.isArray(entries) || !entries.length ||+ entries.some((entry) => typeof entry !== 'string' || !entry.trim());+ });+ if (invalidReviewGroups.length) {+ return [+ `REVIEW_DATA requires non-empty string arrays: ${invalidReviewGroups.join(', ')}`,+ ];+ }++ if (!Array.isArray(dataObject.BIDIRECTIONAL_REVIEW_DATA) ||+ !dataObject.BIDIRECTIONAL_REVIEW_DATA.length) {+ return ['BIDIRECTIONAL_REVIEW_DATA must contain every planned visible or interactive component.'];+ }+ for (let index = 0; index < dataObject.BIDIRECTIONAL_REVIEW_DATA.length; index += 1) {+ const entry = dataObject.BIDIRECTIONAL_REVIEW_DATA[index];+ const prefix = `BIDIRECTIONAL_REVIEW_DATA[${index}]`;+ for (const key of ['component', 'reason']) {+ if (typeof entry?.[key] !== 'string' || !entry[key].trim()) {+ return [`${prefix}.${key} must be a non-empty localized string.`];+ }+ }+ if (!BIDIRECTIONAL_CLASSIFICATIONS.has(entry?.classification)) {+ return [+ `${prefix}.classification must be direction-neutral, direction-aware, ` ++ 'direction-fixed, or unknown-third-party.',+ ];+ }+ for (const key of ['states', 'checks']) {+ if (!Array.isArray(entry?.[key]) || !entry[key].length ||+ entry[key].some((value) => typeof value !== 'string' || !value.trim())) {+ return [`${prefix}.${key} must be a non-empty array of localized strings.`];+ }+ }+ if (!Array.isArray(entry?.viewports) || !entry.viewports.length ||+ entry.viewports.some((value) => !BIDIRECTIONAL_VIEWPORTS.has(value)) ||+ new Set(entry.viewports).size !== entry.viewports.length) {+ return [`${prefix}.viewports must contain unique desktop and/or narrow values.`];+ }+ }++ const missingLabels = requiredLabelPaths.filter((labelPath) => {+ const label = getNestedValue(dataObject.PLAN_LABELS, labelPath);+ return typeof label !== 'string' || !label.trim();+ });+ if (missingLabels.length) {+ return [`PLAN_LABELS is missing localized values: ${missingLabels.join(', ')}`];+ }++ const requiredTokens = [+ ['overview.description', '{siteName}'],+ ['overview.nextSteps.components.descriptionOne', '{count}'],+ ['overview.nextSteps.components.descriptionOther', '{count}'],+ ['overview.nextSteps.pages.descriptionOne', '{count}'],+ ['overview.nextSteps.pages.descriptionOther', '{count}'],+ ];+ const missingTokens = requiredTokens+ .filter(([labelPath, token]) => !getNestedValue(dataObject.PLAN_LABELS, labelPath).includes(token))+ .map(([labelPath, token]) => `${labelPath} (${token})`);+ return missingTokens.length+ ? [`PLAN_LABELS must preserve renderer tokens: ${missingTokens.join(', ')}`]+ : [];+}+function withDerivedTemplateData(dataObject) {return {...dataObject,SUMMARY_DATA: { text: String(dataObject.SUMMARY ?? '') },+ SITE_NAME_DATA: { text: String(dataObject.SITE_NAME ?? '') },};}-if (args['data-inline']) {- let dataObject;- try {- dataObject = JSON.parse(args['data-inline']);- } catch {- console.error('Error: --data-inline value is not valid JSON');+function render(dataObject) {+ const validationErrors = validatePlanData(dataObject);+ if (validationErrors.length) {+ console.error(`Invalid create-site plan data:\n- ${validationErrors.join('\n- ')}`);process.exit(1);}renderTemplate({@@ -87,7 +273,19 @@ if (args['data-inline']) {outputPath: path.resolve(args.output),dataObject: withDerivedTemplateData(dataObject),requiredKeys,+ escapeStringValues: true,});+}++if (args['data-inline']) {+ let dataObject;+ try {+ dataObject = JSON.parse(args['data-inline']);+ } catch {+ console.error('Error: --data-inline value is not valid JSON');+ process.exit(1);+ }+ render(dataObject);} else if (args.data === '-') {let dataObject;try {@@ -96,12 +294,7 @@ if (args['data-inline']) {console.error('Error: the JSON on stdin is not valid');process.exit(1);}- renderTemplate({- templatePath,- outputPath: path.resolve(args.output),- dataObject: withDerivedTemplateData(dataObject),- requiredKeys,- });+ render(dataObject);} else {const dataPath = path.resolve(args.data);if (!fs.existsSync(dataPath)) {@@ -117,10 +310,5 @@ if (args['data-inline']) {process.exit(1);}- renderTemplate({- templatePath,- outputPath: path.resolve(args.output),- dataObject: withDerivedTemplateData(dataObject),- requiredKeys,- });+ render(dataObject);}diff --git a/plugins/power-pages/scripts/suggest-content-locale.js b/plugins/power-pages/scripts/suggest-content-locale.jsnew file mode 100644index 000000000..970cce2bd--- /dev/null+++ b/plugins/power-pages/scripts/suggest-content-locale.js@@ -0,0 +1,109 @@+#!/usr/bin/env node+'use strict';++const {+ getAuthToken,+ getEnvironmentUrl,+ makeRequest,+ odataGet,+} = require('./lib/validation-helpers');+const { resolveLocale } = require('./lib/localization-config');++const FALLBACK_LOCALE = Object.freeze({+ locale: 'en-US',+ language: 'English (United States)',+ direction: 'ltr',+ lcid: 1033,+ source: 'fallback',+});++function fallbackLocale() {+ return { ...FALLBACK_LOCALE };+}++function readableLanguage(row, locale) {+ for (const value of [row?.name, row?.language]) {+ if (typeof value === 'string' && value.trim()) return value.trim();+ }+ return locale;+}++async function suggestContentLocale(dependencies = {}) {+ const resolveEnvironmentUrl = dependencies.getEnvironmentUrl || getEnvironmentUrl;+ const resolveAuthToken = dependencies.getAuthToken || getAuthToken;+ const request = dependencies.makeRequest || makeRequest;+ const getOData = dependencies.odataGet || odataGet;+ const resolve = dependencies.resolveLocale || resolveLocale;++ try {+ const environmentUrl = resolveEnvironmentUrl();+ if (!environmentUrl) return fallbackLocale();++ const token = resolveAuthToken(environmentUrl);+ if (!token) return fallbackLocale();++ // `organization.languagecode` is the Dataverse base-language LCID.+ // `localeid` controls regional formatting and can differ, so it must not+ // determine the language used for site content.+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/organization+ const organizationResponse = await getOData(+ `${environmentUrl}/api/data/v9.2/organizations?$select=languagecode&$top=1`,+ token,+ request+ );+ const lcid = Number(organizationResponse?.value?.[0]?.languagecode);+ if (!Number.isInteger(lcid) || lcid <= 0) return fallbackLocale();++ // Ask Dataverse for its LCID-to-BCP-47 mapping instead of maintaining a+ // separate Windows LCID table that could drift from the platform.+ // Example row:+ // { "localeid": 1033, "code": "en-US", "name": "English (United States)" }+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/languagelocale+ const languageResponse = await getOData(+ `${environmentUrl}/api/data/v9.2/languagelocale` ++ `?$select=localeid,code,language,name&$filter=localeid eq ${lcid}&$top=1`,+ token,+ request+ );+ const languageRow = languageResponse?.value?.[0];+ if (typeof languageRow?.code !== 'string' || !languageRow.code.trim()) {+ return fallbackLocale();+ }++ const resolved = resolve(languageRow.code.trim());+ if (!resolved.valid || !resolved.locale || !resolved.direction) {+ return fallbackLocale();+ }++ return {+ locale: resolved.locale,+ language: readableLanguage(languageRow, resolved.locale),+ direction: resolved.direction,+ lcid,+ source: 'dataverse',+ };+ } catch {+ // The lookup only improves a question default. Missing CLIs, expired auth,+ // inaccessible APIs, malformed responses, and unknown mappings must never+ // delay or prevent the maker from creating a site.+ return fallbackLocale();+ }+}++async function main() {+ const result = await suggestContentLocale();+ process.stdout.write(`${JSON.stringify(result)}\n`);+}++if (require.main === module) {+ main().catch(() => {+ process.stdout.write(`${JSON.stringify(fallbackLocale())}\n`);+ });+}++module.exports = {+ FALLBACK_LOCALE,+ fallbackLocale,+ readableLanguage,+ suggestContentLocale,+};diff --git a/plugins/power-pages/scripts/tests/bidirectional-readiness.test.js b/plugins/power-pages/scripts/tests/bidirectional-readiness.test.jsindex c2d4faa06..9b193d35d 100644--- a/plugins/power-pages/scripts/tests/bidirectional-readiness.test.js+++ b/plugins/power-pages/scripts/tests/bidirectional-readiness.test.js@@ -2,17 +2,17 @@const test = require('node:test');const assert = require('node:assert/strict');-const fs = require('fs');-const os = require('os');-const { spawnSync } = require('child_process');-const path = require('path');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');const { auditBidirectionalReadiness } = require('../lib/bidirectional-readiness');const {parseArgs,} = require('../audit-bidirectional-readiness');const { createTempProject, writeProjectFile } = require('./test-utils');-const AUDIT_PATH = path.join(__dirname, '..', 'audit-bidirectional-readiness.js');+const cliPath = path.join(__dirname, '..', 'audit-bidirectional-readiness.js');function createSymlinkOrSkip(t, target, linkPath, type) {try {@@ -55,7 +55,7 @@ test('parses an optional project root without consuming other options', () => {test('CLI reports malformed project-root usage without auditing another path', () => {const result = spawnSync(process.execPath,- [AUDIT_PATH, '--projectRoot', '--unexpected'],+ [cliPath, '--projectRoot', '--unexpected'],{ encoding: 'utf8' });@@ -386,16 +386,346 @@ test('carries quote state across lines so literal comment markers cannot hide coassert.equal(result.findings[0].rule, 'directional-physical-css');});-test('audit CLI exits nonzero when blocking findings exist', (t) => {+test('blocks fixed CSS and element direction but allows the root document direction', (t) => {const projectRoot = createTempProject(t);- writeProjectFile(projectRoot, 'src/theme.css', '.card { margin-left: 1rem; }');+ writeProjectFile(projectRoot, 'index.html', '<html lang="he-IL" dir="rtl"><body></body></html>');+ writeProjectFile(projectRoot, 'src/Form.tsx', `+ const styles = { direction: 'ltr' };+ const multilineStyles = {+ direction: 'rtl',+ };+ export const Form = () => <input dir="ltr" style={styles} />;+ `);+ writeProjectFile(projectRoot, 'src/Menu.vue', `<Menu :dir="'ltr'" />`);+ writeProjectFile(projectRoot, 'src/dialog.component.html', `<dialog [attr.dir]="'ltr'"></dialog>`);+ writeProjectFile(projectRoot, 'src/Multiline.tsx', `+ export const Input = () => <input+ onChange={() =>+ update()+ }+ dir="ltr"+ />;+ `);+ writeProjectFile(projectRoot, 'src/locale.ts', `+ export const localeMetadata = { direction: 'ltr' };+ export const multilineLocaleMetadata = {+ direction: 'rtl',+ };+ `);+ writeProjectFile(projectRoot, 'src/data.html', `<div data-dir="ltr"></div>`);- const result = spawnSync(+ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 6, JSON.stringify(result.findings));+ assert.ok(result.findings.every((item) => item.rule === 'fixed-direction'));+ assert.ok(result.findings.every((item) => /^[a-f0-9]{64}$/.test(item.fingerprint)));+});++test('ignores examples in comments and comment braces do not leak style context', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Example.astro', `+ <!-- Example only:+ <code dir="ltr">npm run build</code>+ -->+ `);+ writeProjectFile(projectRoot, 'src/styles.ts', `+ const styles = {+ color: 'red', // {+ };+ // track.scrollTo({ left: 100 });+ const localeMetadata = {+ direction: 'ltr',+ };+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+ assert.equal(result.summary.review, 0, JSON.stringify(result.findings));+});++test('accepts one adjacent documented fixed-direction exception', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/machine-values.css', `+ .email-value {+ /* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */+ direction: ltr;+ }+ `);+ writeProjectFile(projectRoot, 'src/Code.astro', `+ <!-- bidi-fixed: Source-code text preserves authored character order; verify=ltr,rtl -->+ <code dir="ltr">npm run build</code>+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+});++test('blocks permanent auto direction on native free-form controls', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Message.tsx', `+ export const Message = () => (+ <textarea+ dir="auto"+ dirname="message.dir"+ placeholder="Type a message"+ />+ );+ `);+ writeProjectFile(projectRoot, 'src/Search.vue', `+ <input :dir="'auto'" placeholder="Search" />+ `);+ writeProjectFile(projectRoot, 'src/comment.component.html', `+ <textarea [attr.dir]="'auto'"></textarea>+ <input [dir]="'auto'" />+ `);+ writeProjectFile(projectRoot, 'src/LongForm.vue', `+ <textarea+ v-bind:dir="'auto'"+ placeholder="Details"></textarea>+ `);+ writeProjectFile(projectRoot, 'src/plain.html', `+ <input dir=auto placeholder="Name">+ `);+ writeProjectFile(projectRoot, 'src/NotDirection.tsx', `+ export const NotDirection = () => (+ <>+ <input aria-label={"Example text: dir='auto'"} />+ <input-field dir="auto" />+ <textarea-wrapper dir="auto" />+ </>+ );+ `);+ writeProjectFile(projectRoot, 'src/TemplateDirection.tsx', `+ export const TemplateDirection = () => <input dir={\`auto\`} />;+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ const findings = result.findings.filter(+ (item) => item.rule === 'static-auto-control-direction'+ );+ assert.equal(findings.length, 7, JSON.stringify(result.findings));+ assert.ok(findings.every((item) =>+ /active UI direction while empty/.test(item.message)+ ));+});++test('accepts adaptive free-form direction and documented machine controls', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Message.tsx', `+ const freeFormDirection = (value, uiDirection) =>+ value.length === 0 ? uiDirection : 'auto';+ export const Message = ({ value, uiDirection }) => (+ <textarea+ dir={freeFormDirection(value, uiDirection)}+ dirname="message.dir"+ value={value}+ />+ );+ `);+ writeProjectFile(projectRoot, 'src/Search.vue', `+ <input :dir="query.length === 0 ? uiDirection : 'auto'" v-model="query" />+ `);+ writeProjectFile(projectRoot, 'src/comment.component.html', `+ <textarea+ [attr.dir]="comment.length === 0 ? uiDirection : 'auto'"+ dirname="comment.dir"></textarea>+ `);+ writeProjectFile(projectRoot, 'src/Contact.astro', `+ <textarea id="message" dirname="message.dir"></textarea>+ <script>+ const control = document.querySelector('#message');+ const syncDirection = () => {+ control.dir = control.value.length === 0+ ? document.documentElement.dir+ : 'auto';+ };+ control.addEventListener('input', syncDirection);+ new MutationObserver(syncDirection).observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['dir'],+ });+ syncDirection();+ </script>+ `);+ writeProjectFile(projectRoot, 'src/Email.astro', `+ <!-- bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl -->+ <input type="email" dir="ltr" dirname="email.dir" />+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+});++test('ignores commented controls after apostrophes in HTML text', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/form.html', `+ <p>Don't submit the archived example.</p>+ <!--+ <textarea dir="auto" placeholder="Old example"></textarea>+ -->+ <textarea :dir="message.length === 0 ? uiDirection : 'auto'"></textarea>+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+});++test('rejects vague, non-adjacent, and mismatched fixed-direction exceptions', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/invalid.css', `+ /* bidi-fixed: needed; verify=ltr,rtl */+ direction: ltr;++ /* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */++ direction: ltr;++ /* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */+ margin-left: 1rem;++ /* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */+ /* unrelated comment */+ direction: ltr;++ /* bidi-fixed: First stale reason must not disappear; verify=ltr,rtl */+ /* bidi-fixed: Email addresses preserve LTR character order; verify=ltr,rtl */+ direction: ltr;+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.ok(result.findings.some((item) => item.rule === 'invalid-fixed-exception'));+ assert.ok(result.findings.some((item) => item.rule === 'unused-fixed-exception'));+ assert.ok(result.findings.some((item) => item.rule === 'fixed-direction'));+ assert.ok(result.findings.some((item) => item.rule === 'directional-physical-css'));+});++test('blocks physical utility classes including responsive variants', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Card.tsx', `+ export const Card = () =>+ <div className="ml-4 text-left md:right-0 rtl:-mr-2">Card</div>;+ export const ReactBound = () => <div className={"pl-2"} />;+ `);+ writeProjectFile(projectRoot, 'src/Card.vue', `<div :class="'mr-4'"></div>`);+ writeProjectFile(projectRoot, 'src/card.component.html', `<div [class]="'left-0'"></div>`);++ const result = auditBidirectionalReadiness(projectRoot);+ const utilityFindings = result.findings.filter(+ (item) => item.rule === 'directional-physical-utility'+ );+ assert.equal(utilityFindings.length, 7, JSON.stringify(result.findings));+});++test('allows logical utility classes', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Card.tsx', `+ export const Card = () =>+ <div className="ms-4 text-start md:end-0 ps-2">Card</div>;+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+});++test('blocks asymmetric physical spacing and corner-radius shorthands', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/theme.css', `+ .field { padding: 0 1rem 0 2rem; }+ .card { border-radius: 1rem 0.5rem 0.25rem 0; }+ .safe { margin: 0 1rem; padding: 0 2rem 0 2rem; border-radius: 1rem; }+ .safe-ellipse { border-radius: 50% / 25%; }+ .unsafe-calculated { border-radius: calc(10px / 2) calc(20px / 2); }+ `);+ writeProjectFile(projectRoot, 'src/styles.ts', `+ const unsafe = { padding: '0 1rem 0 2rem', color: 'red' };+ const safe = { margin: '0 1rem 0 1rem' };+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ const shorthandFindings = result.findings.filter(+ (item) => item.rule === 'directional-physical-shorthand'+ );+ assert.equal(shorthandFindings.length, 4, JSON.stringify(result.findings));+});++test('blocks unicode bidi overrides', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/theme.css', `+ .unsafe { unicode-bidi: bidi-override; }+ .safe { unicode-bidi: isolate; }+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 1, JSON.stringify(result.findings));+ assert.equal(result.findings[0].rule, 'unicode-bidi-override');+});++test('reports raw horizontal scrolling and additional physical geometry for review', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Carousel.ts', `+ track.scrollLeft += 100;+ track.scrollTo({ left: 0, behavior: 'smooth' });+ track.scrollTo(100, 0);+ track.scrollBy(100, 0);+ track.scroll({ left: 100 });+ track.scrollTo({+ left: offset,+ behavior: 'smooth',+ });+ track.scrollBy(+ offset,+ 0+ );+ `);+ writeProjectFile(projectRoot, 'src/icons.css', `+ .next { transform: scaleX(-1); }+ .hero { background-position: left center; }+ .move { transform: translate(20px, 0); }+ .individual { translate: 20px 0; }+ .vertical { transform: translate3d(0, 20px, 0); }+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(+ result.findings.filter((item) => item.rule === 'directional-scroll-review').length,+ 7+ );+ assert.equal(+ result.findings.filter((item) => item.rule === 'directional-geometry-review').length,+ 4+ );+});++test('allows a fixed-direction annotation on a multiline element', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'src/Code.tsx', `+ /* bidi-fixed: Source-code text preserves authored character order; verify=ltr,rtl */+ export const Code = () => <code+ dir="ltr"+ >npm run build</code>;+ `);++ const result = auditBidirectionalReadiness(projectRoot);+ assert.equal(result.summary.error, 0, JSON.stringify(result.findings));+});++test('CLI prints findings and exits nonzero only for deterministic errors', (t) => {+ const failingRoot = createTempProject(t);+ writeProjectFile(failingRoot, 'src/theme.css', '.field { text-align: left; }');+ const failing = spawnSync(process.execPath,- [AUDIT_PATH, '--projectRoot', projectRoot],+ [cliPath, '--projectRoot', failingRoot],{ encoding: 'utf8' });+ assert.equal(failing.status, 1);+ assert.equal(JSON.parse(failing.stdout).summary.error, 1);- assert.equal(result.status, 1);- assert.equal(JSON.parse(result.stdout).summary.error, 1);+ const reviewRoot = createTempProject(t);+ writeProjectFile(reviewRoot, 'src/Carousel.ts', 'track.scrollLeft += 100;');+ const review = spawnSync(+ process.execPath,+ [cliPath, '--projectRoot', reviewRoot],+ { encoding: 'utf8' }+ );+ assert.equal(review.status, 0);+ assert.equal(JSON.parse(review.stdout).summary.review, 1);});diff --git a/plugins/power-pages/scripts/tests/detect-browser.test.js b/plugins/power-pages/scripts/tests/detect-browser.test.jsnew file mode 100644index 000000000..14a094b77--- /dev/null+++ b/plugins/power-pages/scripts/tests/detect-browser.test.js@@ -0,0 +1,56 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const {+ detectBrowserLaunchOptions,+ whichPath,+} = require('../lib/detect-browser');++test('whichPath uses a fixed executable and keeps the candidate in argv', () => {+ const calls = [];+ const result = whichPath('chromium;not-shell-syntax', (...args) => {+ calls.push(args);+ return '/usr/bin/chromium\n';+ });++ assert.equal(result, '/usr/bin/chromium');+ assert.deepEqual(calls, [[+ 'which',+ ['chromium;not-shell-syntax'],+ { encoding: 'utf8', shell: false },+ ]]);+});++test('whichPath returns null when executable lookup fails', () => {+ const result = whichPath('chromium', () => {+ throw new Error('not found');+ });++ assert.equal(result, null);+});++test('Linux launch options use the installed distro Chromium path', () => {+ const requestedPaths = [];+ const result = detectBrowserLaunchOptions({+ platform: 'linux',+ whichExists: () => false,+ whichPath: (command) => {+ requestedPaths.push(command);+ return command === 'chromium' ? '/usr/bin/chromium' : null;+ },+ });++ assert.deepEqual(requestedPaths, ['chromium-browser', 'chromium']);+ assert.deepEqual(result, { executablePath: '/usr/bin/chromium' });+});++test('Linux launch options fall back when no system browser exists', () => {+ const result = detectBrowserLaunchOptions({+ platform: 'linux',+ whichExists: () => false,+ whichPath: () => null,+ });++ assert.deepEqual(result, {});+});diff --git a/plugins/power-pages/scripts/tests/localization-config.test.js b/plugins/power-pages/scripts/tests/localization-config.test.jsindex 10b454911..5b2bd5859 100644--- a/plugins/power-pages/scripts/tests/localization-config.test.js+++ b/plugins/power-pages/scripts/tests/localization-config.test.js@@ -14,7 +14,9 @@ const {detectSiteLanguage,detectSiteLanguageForFramework,discoverLocalizationImplementation,+ getFrameworkLocalizationAvailability,getLocaleDirection,+ getLocalizationModeAvailability,inspectProject,isSafeLocaleCandidate,isSafeLocaleListCandidate,@@ -27,7 +29,6 @@ const {validateLocales,} = require('../lib/localization-config');const { createTempProject, writeProjectFile } = require('./test-utils');-const CONFIG_PATH = path.join(__dirname, '..', 'lib', 'localization-config.js');function writePackage(projectRoot, dependencies) {@@ -49,6 +50,13 @@ function verifiedNpmArtifact(packageName, version) {test('centralizes framework modes, recommendations, packages, and peers', () => {assert.deepEqual(LOCALIZATION_CAPABILITIES.frameworks.react.supportedModes, ['runtime']);+ assert.deepEqual(LOCALIZATION_CAPABILITIES.frameworks.react.availableModes, ['runtime']);+ assert.deepEqual(+ LOCALIZATION_CAPABILITIES.frameworks.angular.supportedModes,+ ['runtime', 'static']+ );+ assert.deepEqual(LOCALIZATION_CAPABILITIES.frameworks.angular.availableModes, ['runtime']);+ assert.equal(LOCALIZATION_CAPABILITIES.frameworks.angular.recommendedMode, 'runtime');assert.equal(LOCALIZATION_CAPABILITIES.frameworks.angular.recommendedPackages.static,'@angular/localize'@@ -61,6 +69,82 @@ test('centralizes framework modes, recommendations, packages, and peers', () =>LOCALIZATION_CAPABILITIES.packages['astro-built-in'],{ framework: 'astro', mode: 'static', builtIn: true });+ assert.deepEqual(LOCALIZATION_CAPABILITIES.frameworks.astro.availableModes, []);+ assert.equal(LOCALIZATION_CAPABILITIES.frameworks.astro.recommendedMode, null);+});++test('reports centralized localization mode availability and stable reasons', () => {+ assert.deepEqual(getLocalizationModeAvailability('react', 'runtime'), {+ framework: 'react',+ mode: 'runtime',+ supported: true,+ available: true,+ status: 'available',+ recommendedPackage: 'react-i18next',+ builtIn: false,+ });++ const angularStatic = getLocalizationModeAvailability('angular', 'static');+ assert.equal(angularStatic.supported, true);+ assert.equal(angularStatic.available, false);+ assert.equal(angularStatic.status, 'temporarily-unavailable');+ assert.equal(+ angularStatic.reasonCode,+ 'angular-static-temporarily-unavailable'+ );+ assert.match(angularStatic.reason, /Angular runtime localization is available/);+ assert.match(angularStatic.reason, /validated runtime alternatives are allowed/);++ const astro = getFrameworkLocalizationAvailability('astro');+ assert.deepEqual(astro.availableModes, []);+ assert.equal(astro.modes.static.available, false);+ assert.equal(astro.modes.static.recommendedPackage, 'astro-built-in');+ assert.equal(astro.modes.static.builtIn, true);+ assert.equal(+ astro.modes.static.reasonCode,+ 'astro-static-temporarily-unavailable'+ );+});++test('includes detected framework availability in project inspection', (t) => {+ const projectRoot = createTempProject(t);+ writePackage(projectRoot, { astro: '^6.1.0' });++ const inspection = inspectProject(projectRoot);+ assert.equal(inspection.framework.framework, 'astro');+ assert.deepEqual(inspection.availability.availableModes, []);+ assert.equal(+ inspection.availability.modes.static.reasonCode,+ 'astro-static-temporarily-unavailable'+ );+});++test('exposes mode availability through the shared CLI', () => {+ const frameworkResult = spawnSync(+ process.execPath,+ [CONFIG_PATH, 'mode-availability', '--framework', 'astro'],+ { encoding: 'utf8' }+ );+ assert.equal(frameworkResult.status, 0, frameworkResult.stderr);+ assert.deepEqual(JSON.parse(frameworkResult.stdout).availableModes, []);++ const modeResult = spawnSync(+ process.execPath,+ [+ CONFIG_PATH,+ 'mode-availability',+ '--framework',+ 'angular',+ '--mode',+ 'static',+ ],+ { encoding: 'utf8' }+ );+ assert.equal(modeResult.status, 1);+ assert.equal(+ JSON.parse(modeResult.stdout).reasonCode,+ 'angular-static-temporarily-unavailable'+ );});test('accepts the documented Astro built-in manifest package metadata', () => {@@ -137,6 +221,16 @@ test('accepts structured official-documentation package verification evidence',generatedFiles: ['src/components/LanguageSelector.tsx'],managedFiles: ['src/i18n/index.ts'],adoptedExistingConfiguration: false,+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },lastOperation: 'create',updatedAt: '2026-10-02T00:00:00.000Z',});@@ -448,25 +542,383 @@ test('validates bidirectional readiness and unavailable locale manifest fields',unavailableLocales: ['ar-SA'],bidirectionalReadiness: {status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },findings: [],+ renderedFindings: [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'computed-direction-mismatch',+ severity: 'error',+ message: 'Expected rtl but found ltr.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],},};assert.deepEqual(validateLocalizationManifestShape(manifest), []);+ assert.match(+ validateLocalizationManifestShape({+ ...manifest,+ schemaVersion: 2,+ }).join('\n'),+ /schemaVersion must be 1/+ );assert.match(validateLocalizationManifestShape({...manifest,unavailableLocales: undefined,}).join('\n'),- /Pending bidirectional remediation requires at least one unavailable locale/+ /unavailableLocales must exactly match/);assert.match(validateLocalizationManifestShape({...manifest,- bidirectionalReadiness: { status: 'unknown', findings: [] },+ bidirectionalReadiness: {+ status: 'unknown',+ localeReadiness: manifest.bidirectionalReadiness.localeReadiness,+ findings: [],+ renderedFindings: [],+ },}).join('\n'),/bidirectionalReadiness\.status must be/);+ assert.match(+ validateLocalizationManifestShape({+ ...manifest,+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: manifest.bidirectionalReadiness.renderedFindings,+ },+ }).join('\n'),+ /requires locale ar-SA to be pending-remediation/+ );+ assert.match(+ validateLocalizationManifestShape({+ ...manifest,+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: manifest.bidirectionalReadiness.renderedFindings,+ },+ }).join('\n'),+ /requires locale ar-SA to be pending-remediation/+ );+ assert.match(+ validateLocalizationManifestShape({+ ...manifest,+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: manifest.bidirectionalReadiness.localeReadiness,+ findings: [],+ renderedFindings: [{ severity: 'error' }],+ },+ }).join('\n'),+ /renderedFindings\[0\]\.caseId/+ );+});++test('requires explicit maker disposition for approved bidirectional limitations', () => {+ const base = {+ schemaVersion: 1,+ framework: 'react',+ mode: 'runtime',+ packageName: 'i18next',+ packageVersion: '25.0.0',+ defaultLocale: 'en-US',+ locales: ['en-US', 'ar-SA'],+ translationMethod: 'agent',+ lastOperation: 'add-languages',+ updatedAt: '2026-01-01T00:00:00.000Z',+ generatedFiles: [],+ managedFiles: [],+ resourcePaths: {},+ adoptedExistingConfiguration: false,+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ ...verifiedNpmArtifact('i18next', '25.0.0'),+ },+ unavailableLocales: [],+ };+ const limitation = {+ caseId: 'calendar--open--desktop--ar',+ rule: 'rendered-semantic-review',+ severity: 'review',+ message: 'The vendor calendar uses a culturally neutral next-page icon.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ };++ assert.match(+ validateLocalizationManifestShape({+ ...base,+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: [limitation],+ },+ }).join('\n'),+ /requires only maker-approved review findings/+ );++ assert.deepEqual(validateLocalizationManifestShape({+ ...base,+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: [{+ ...limitation,+ disposition: {+ status: 'maker-approved',+ impact: 'Calendar navigation remains usable; only the icon treatment differs.',+ evidence: 'docs/bidirectional-evidence/run-1/calendar.png',+ approvedAt: '2026-01-01T00:00:00.000Z',+ },+ }],+ },+ }), []);++ assert.deepEqual(validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ ...limitation,+ disposition: {+ status: 'maker-approved',+ impact: 'Calendar navigation remains usable; only the icon treatment differs.',+ evidence: 'docs/bidirectional-evidence/run-1/calendar.png',+ approvedAt: '2026-01-01T00:00:00.000Z',+ },+ }, {+ caseId: 'calendar--open--narrow--ar',+ rule: 'rendered-clipping',+ severity: 'error',+ message: 'The calendar clips at narrow width.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ },+ }), []);++ assert.match(+ validateLocalizationManifestShape({+ ...base,+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: [{+ ...limitation,+ disposition: {+ status: 'maker-approved',+ impact: 'Calendar navigation remains usable.',+ evidence: 'docs/bidirectional-evidence/run-1/calendar.png',+ approvedAt: '2026-02-30T00:00:00.000Z',+ },+ }],+ },+ }).join('\n'),+ /approvedAt must be an ISO date-time/+ );++ assert.match(+ validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [{+ severity: 'error',+ file: 'src/app.tsx',+ line: 1,+ rule: 'fixed-direction',+ message: 'Fixed direction must be remediated.',+ fingerprint: 'abc123',+ scope: 'direction',+ affectedLocales: ['ar-SA'],+ }],+ renderedFindings: [],+ },+ }).join('\n'),+ /findings\[0\]\.direction must be/+ );++ assert.match(+ validateLocalizationManifestShape({+ ...base,+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [{+ severity: 'review',+ file: 'src/styles.css',+ line: 1,+ rule: 'horizontal-scroll-review',+ message: 'Review horizontal scrolling.',+ fingerprint: 'abc123',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ renderedFindings: [],+ },+ }).join('\n'),+ /Undisposed review finding/+ );++ assert.match(+ validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ ...limitation,+ severity: 'error',+ disposition: {+ status: 'maker-approved',+ impact: 'Attempted override.',+ evidence: 'docs/bidirectional-evidence/run-1/report.json',+ approvedAt: '2026-01-01T00:00:00.000Z',+ },+ }],+ },+ }).join('\n'),+ /error findings cannot have maker-approved dispositions/+ );+});++test('scopes readiness findings to only the locales proven affected', () => {+ const base = {+ schemaVersion: 1,+ framework: 'react',+ mode: 'runtime',+ packageName: 'i18next',+ packageVersion: '25.0.0',+ defaultLocale: 'en-US',+ locales: ['en-US', 'he-IL', 'ar-SA'],+ translationMethod: 'agent',+ lastOperation: 'add-languages',+ updatedAt: '2026-01-01T00:00:00.000Z',+ generatedFiles: [],+ managedFiles: [],+ resourcePaths: {},+ adoptedExistingConfiguration: false,+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ ...verifiedNpmArtifact('i18next', '25.0.0'),+ },+ };+ const arabicFinding = {+ caseId: 'arabic-calendar--open--desktop--ar',+ rule: 'localized-font-failure',+ severity: 'error',+ message: 'The Arabic calendar font is unreadable.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ };++ assert.deepEqual(validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'he-IL': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [arabicFinding],+ },+ }), []);++ const directionErrors = validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'he-IL': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ ...arabicFinding,+ scope: 'direction',+ direction: 'rtl',+ }],+ },+ }).join('\n');+ assert.match(directionErrors, /must affect every configured rtl locale/);++ assert.deepEqual(validateLocalizationManifestShape({+ ...base,+ unavailableLocales: ['he-IL', 'ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'he-IL': { status: 'pending-remediation' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ ...arabicFinding,+ scope: 'direction',+ direction: 'rtl',+ affectedLocales: ['he-IL', 'ar-SA'],+ }],+ },+ }), []);});test('detects the persisted single-site language from document attributes', (t) => {@@ -1003,6 +1455,69 @@ test('derives mode, locales, default, and resources for a manifestless existingassert.equal(result.resourcePaths['fr-FR'], 'src/i18n/locales/fr-FR.json');});+test('reports unavailable static evidence even when an Angular manifest claims runtime', (t) => {+ const projectRoot = createTempProject(t);+ writePackage(projectRoot, {+ '@angular/core': '^19.1.0',+ '@angular/compiler': '^19.1.0',+ '@angular/compiler-cli': '^19.1.0',+ '@angular/localize': '^19.1.0',+ '@jsverse/transloco': '^7.6.0',+ });+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify({+ projects: {+ portal: {+ i18n: { sourceLocale: 'en-US' },+ },+ },+ }));+ writeProjectFile(projectRoot, 'src/assets/i18n/en-US.json', '{"home":"Home"}');+ writeProjectFile(projectRoot, 'src/assets/i18n/fr-FR.json', '{"home":"Accueil"}');+ writeProjectFile(+ projectRoot,+ 'src/app/i18n.ts',+ "provideTransloco({}); setActiveLang('fr-FR'); document.documentElement.lang='fr-FR'; document.documentElement.dir='ltr';"+ );+ writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({+ schemaVersion: 1,+ framework: 'angular',+ mode: 'runtime',+ packageName: '@jsverse/transloco',+ packageVersion: '^7.6.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ },+ locales: ['en-US', 'fr-FR'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/assets/i18n/en-US.json',+ 'fr-FR': 'src/assets/i18n/fr-FR.json',+ },+ generatedFiles: [],+ managedFiles: ['src/app/i18n.ts'],+ adoptedExistingConfiguration: false,+ lastOperation: 'create',+ updatedAt: '2026-07-30T00:00:00.000Z',+ }));++ const result = detectLocalization(projectRoot);+ assert.equal(result.mode, 'runtime');+ assert.deepEqual(+ result.unavailableModeEvidence.map((entry) => entry.detail).sort(),+ ['@angular/localize', 'Angular i18n build configuration']+ );+ assert.match(+ result.conflicts.join('\n'),+ /manifest mode "runtime" conflicts with detected static mode evidence/+ );+ assert.match(+ result.conflicts.join('\n'),+ /Angular static localization is temporarily unavailable/+ );+});+test('scans source files incrementally and stops after all signals are found', (t) => {const projectRoot = createTempProject(t);const implementation =diff --git a/plugins/power-pages/scripts/tests/localization-verification-profile.test.js b/plugins/power-pages/scripts/tests/localization-verification-profile.test.jsnew file mode 100644index 000000000..8cbdcd19a--- /dev/null+++ b/plugins/power-pages/scripts/tests/localization-verification-profile.test.js@@ -0,0 +1,119 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const {+ buildManualReviewChecklist,+ resolveComponentRisk,+ resolveRepresentatives,+ selectComponentDimensions,+ selectRepresentativeLocales,+} = require('../lib/localization-verification-profile');++const locales = [+ { id: 'en', locale: 'en-US', direction: 'ltr', textExpansion: 1 },+ { id: 'es', locale: 'es-ES', direction: 'ltr', textExpansion: 1.4 },+ { id: 'ar', locale: 'ar-SA', direction: 'rtl', textExpansion: 1.2 },+ {+ id: 'pseudo-rtl',+ locale: 'ar-XB',+ direction: 'rtl',+ pseudo: true,+ textExpansion: 3,+ },+];++test('prefers real target locales and then greater text expansion', () => {+ assert.deepEqual(selectRepresentativeLocales(locales, {+ targetLocales: ['es-ES', 'ar-SA'],+ defaultLocale: 'en-US',+ }), {+ ltr: 'es',+ rtl: 'ar',+ });+});++test('falls back to a pseudo direction only when no real locale exists', () => {+ assert.deepEqual(selectRepresentativeLocales(+ locales.filter((locale) => locale.id !== 'ar'),+ { targetLocales: ['es-ES'], defaultLocale: 'en-US' }+ ), {+ ltr: 'es',+ rtl: 'pseudo-rtl',+ });+});++test('uses explicit representative overrides after automatic selection', () => {+ const spec = {+ locales,+ representativeLocaleIds: { ltr: 'en' },+ };+ assert.deepEqual(resolveRepresentatives(spec, {+ verificationLocales: ['es-ES', 'ar-SA'],+ defaultLocale: 'en-US',+ }), {+ ltr: 'en',+ rtl: 'ar',+ });+});++test('maps component classifications to conservative default risks', () => {+ assert.equal(resolveComponentRisk({ classification: 'direction-neutral' }), 'low');+ assert.equal(resolveComponentRisk({ classification: 'direction-aware' }), 'medium');+ assert.equal(resolveComponentRisk({ classification: 'direction-fixed' }), 'high');+ assert.equal(resolveComponentRisk({ classification: 'unknown-third-party' }), 'high');+});++test('standard profile limits low-risk dimensions but keeps complex coverage', () => {+ const spec = {+ verificationProfile: 'standard',+ locales,+ };+ const representatives = { ltr: 'es', rtl: 'ar' };+ const low = {+ classification: 'direction-neutral',+ states: [{ name: 'default' }, { name: 'expanded' }],+ viewports: ['desktop', 'narrow'],+ };+ const high = {+ classification: 'unknown-third-party',+ states: [{ name: 'closed' }, { name: 'open' }],+ viewports: ['desktop', 'narrow'],+ };++ assert.deepEqual(selectComponentDimensions(low, spec, representatives), {+ localeIds: ['es', 'ar'],+ states: [{ name: 'default' }],+ viewports: ['desktop'],+ risk: 'low',+ });+ assert.deepEqual(selectComponentDimensions(high, spec, representatives), {+ localeIds: ['es', 'ar'],+ states: high.states,+ viewports: high.viewports,+ risk: 'high',+ });+});++test('manual review covers high-risk components in non-representative locales', () => {+ const spec = {+ verificationProfile: 'standard',+ locales,+ components: [{+ id: 'calendar',+ name: 'Calendar',+ classification: 'unknown-third-party',+ route: '/calendar',+ states: [{ name: 'closed' }, { name: 'open' }],+ viewports: ['desktop', 'narrow'],+ }],+ };++ assert.deepEqual(+ buildManualReviewChecklist(spec, { ltr: 'es', rtl: 'ar' })+ .map((entry) => [entry.locale, entry.componentId]),+ [+ ['en-US', 'calendar'],+ ]+ );+});diff --git a/plugins/power-pages/scripts/tests/localization-verification-transaction.test.js b/plugins/power-pages/scripts/tests/localization-verification-transaction.test.jsnew file mode 100644index 000000000..4a509f8d3--- /dev/null+++ b/plugins/power-pages/scripts/tests/localization-verification-transaction.test.js@@ -0,0 +1,1110 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const {+ AUDIT_LEASE_CONFLICT_CODE,+ TRANSACTION_AVAILABILITY_FILE,+ TRANSACTION_FILE,+ TRANSACTION_LOCK_FILE,+ TRANSACTION_LOCK_RECOVERY_FILE,+ abandonLocalizationVerificationAudit,+ beginLocalizationVerificationAudit,+ beginLocalizationVerification,+ extendLocalizationVerification,+ finalizeLocalizationVerification,+ formatManualAvailabilityRestore,+ markLocalizationVerificationFailed,+ markLocalizationVerificationPassed,+ readLocalizationVerificationTransaction,+ recoverAbandonedTransactionLock,+ validateTransactionAgainstManifest,+} = require('../lib/localization-verification-transaction');+const {+ validateLocalizationManifestShape,+} = require('../lib/localization-config');+const {+ computeVerificationInputFingerprint,+} = require('../lib/verification-evidence');+const {+ parseArgs: parseManagerArgs,+} = require('../manage-localization-verification');+const { createTempProject, writeProjectFile } = require('./test-utils');+const VERIFICATION_MANAGER_PATH =+ path.join(__dirname, '..', 'manage-localization-verification.js');++function manifest(overrides = {}) {+ return {+ schemaVersion: 1,+ framework: 'react',+ mode: 'runtime',+ packageName: 'react-i18next',+ packageVersion: '^16.0.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact: {+ version: '16.0.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl:+ 'https://registry.npmjs.org/react-i18next/-/react-i18next-16.0.0.tgz',+ integrity: 'sha512-dGVzdA==',+ },+ },+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/i18n/locales/en-US.json',+ 'ar-SA': 'src/i18n/locales/ar-SA.json',+ },+ generatedFiles: [],+ managedFiles: ['src/i18n/localeAvailability.ts'],+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'add-languages',+ updatedAt: '2026-09-03T00:00:00.000Z',+ ...overrides,+ };+}++const AVAILABILITY_MODULE = 'src/i18n/localeAvailability.ts';+const CALENDAR_REVIEW_FINDING = {+ caseId: 'calendar--open--desktop--ar',+ rule: 'rendered-semantic-review',+ severity: 'review',+ message: 'Confirm that the calendar navigation remains understandable.',+ selector: '.calendar',+};++function availabilitySource(unavailableLocales) {+ return `const unavailableLocales = new Set(${JSON.stringify(+ unavailableLocales+ )});\n` ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n';+}++function writeManifest(projectRoot, value) {+ if (!fs.existsSync(path.join(projectRoot, AVAILABILITY_MODULE))) {+ writeProjectFile(+ projectRoot,+ AVAILABILITY_MODULE,+ availabilitySource(value.unavailableLocales || [])+ );+ }+ writeProjectFile(+ projectRoot,+ '.powerpages-localization.json',+ `${JSON.stringify(value, null, 2)}\n`+ );+}++// Exposing or hiding a locale edits both the manifest and the managed+// availability module, exactly as the add-localization workflow does.+function writeManifestAndAvailability(projectRoot, value) {+ writeProjectFile(+ projectRoot,+ AVAILABILITY_MODULE,+ availabilitySource(value.unavailableLocales || [])+ );+ writeManifest(projectRoot, value);+}++function verificationEvidence(+ profile = 'extensive',+ manualReview = [],+ reviewFindings = []+) {+ return {+ profile,+ representativeLocaleIds: { ltr: 'en', rtl: 'ar' },+ manualReview,+ reviewFindings,+ evidence: {+ schemaVersion: 1,+ inputFingerprint: 'a'.repeat(64),+ inputFingerprintWithoutAvailability: 'c'.repeat(64),+ specFingerprint: 'b'.repeat(64),+ },+ };+}++function currentVerificationEvidence(+ projectRoot,+ profile = 'extensive',+ manualReview = [],+ reviewFindings = []+) {+ const verification = verificationEvidence(+ profile,+ manualReview,+ reviewFindings+ );+ verification.evidence.inputFingerprint =+ computeVerificationInputFingerprint(projectRoot);+ verification.evidence.inputFingerprintWithoutAvailability =+ computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ });+ return verification;+}++function writeExitedProcessLock(lockPath) {+ const result = spawnSync(+ process.execPath,+ [+ '-e',+ "require('node:fs').writeFileSync(process.argv[1], `${process.pid}\\n`);",+ lockPath,+ ],+ { encoding: 'utf8' }+ );+ assert.equal(result.status, 0, result.stderr);+}++test('begins an exclusive verification transaction from a fail-closed manifest', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());++ const transaction = beginLocalizationVerification(projectRoot, ['ar-sa']);++ assert.deepEqual(transaction.targetLocales, ['ar-SA']);+ assert.deepEqual(transaction.priorUnavailableLocales, ['ar-SA']);+ assert.equal(transaction.state, 'in-progress');+ assert.deepEqual(+ readLocalizationVerificationTransaction(projectRoot).transaction,+ transaction+ );+ assert.throws(+ () => beginLocalizationVerification(projectRoot, ['ar-SA']),+ /already exists/+ );+});++test('recovers a transaction lock left by an exited process', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const lockPath = path.join(projectRoot, TRANSACTION_LOCK_FILE);+ writeExitedProcessLock(lockPath);++ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);++ assert.equal(transaction.state, 'in-progress');+ assert.ok(!fs.existsSync(lockPath));+ assert.ok(!fs.existsSync(+ path.join(projectRoot, TRANSACTION_LOCK_RECOVERY_FILE)+ ));+});++test('--fail recovers an interrupted transaction with an abandoned lock', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeExitedProcessLock(path.join(projectRoot, TRANSACTION_LOCK_FILE));++ const result = spawnSync(+ process.execPath,+ [+ VERIFICATION_MANAGER_PATH,+ '--fail',+ '--projectRoot',+ projectRoot,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+});++test('does not reclaim a transaction lock owned by a live process', (t) => {+ const projectRoot = createTempProject(t);+ const lockPath = path.join(projectRoot, TRANSACTION_LOCK_FILE);+ fs.writeFileSync(lockPath, `${JSON.stringify({+ schemaVersion: 1,+ processId: process.pid,+ token: '11111111-1111-4111-8111-111111111111',+ createdAt: new Date().toISOString(),+ })}\n`);++ assert.equal(recoverAbandonedTransactionLock(projectRoot), false);+ assert.ok(fs.existsSync(lockPath));+});++test('finishes an interrupted abandoned-lock recovery claim', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const lockPath = path.join(projectRoot, TRANSACTION_LOCK_FILE);+ const recoveryPath =+ path.join(projectRoot, TRANSACTION_LOCK_RECOVERY_FILE);+ writeExitedProcessLock(lockPath);+ fs.linkSync(lockPath, recoveryPath);+ fs.unlinkSync(lockPath);++ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);++ assert.equal(transaction.state, 'in-progress');+ assert.ok(!fs.existsSync(recoveryPath));+ assert.ok(!fs.existsSync(lockPath));+});++test('allows only transaction targets to be temporarily exposed', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ const exposedManifest = manifest({ unavailableLocales: [] });++ assert.deepEqual(+ validateLocalizationManifestShape(exposedManifest, {+ verificationLocales: transaction.targetLocales,+ }),+ []+ );+ assert.match(+ validateLocalizationManifestShape(exposedManifest).join('\n'),+ /unavailableLocales must exactly match/+ );+ assert.deepEqual(+ validateTransactionAgainstManifest(+ transaction,+ exposedManifest,+ { requireExposed: true }+ ),+ []+ );+});++test('moves a failed browser run to remediation-required without deleting evidence', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);++ const failed = markLocalizationVerificationFailed(projectRoot);++ assert.equal(failed.runId, transaction.runId);+ assert.equal(failed.state, 'remediation-required');+ assert.ok(failed.failedAt);+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('failed verification restores manifest and runtime availability', (t) => {+ const projectRoot = createTempProject(t);+ const failClosedManifest = manifest({+ locales: ['en-US', 'ar-SA', 'he-IL'],+ resourcePaths: {+ 'en-US': 'src/i18n/locales/en-US.json',+ 'ar-SA': 'src/i18n/locales/ar-SA.json',+ 'he-IL': 'src/i18n/locales/he-IL.json',+ },+ unavailableLocales: ['ar-SA', 'he-IL'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ 'he-IL': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ writeManifest(projectRoot, failClosedManifest);+ const availabilityPath =+ path.join(projectRoot, 'src/i18n/localeAvailability.ts');+ const failClosedSource = fs.readFileSync(availabilityPath, 'utf8');+ const transaction = beginLocalizationVerification(+ projectRoot,+ ['ar-SA', 'he-IL']+ );+ writeManifest(projectRoot, {+ ...failClosedManifest,+ unavailableLocales: [],+ });+ fs.writeFileSync(+ availabilityPath,+ "const unavailableLocales = new Set([]);\n" ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n',+ 'utf8'+ );++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );+ const restoredManifest = JSON.parse(+ fs.readFileSync(+ path.join(projectRoot, '.powerpages-localization.json'),+ 'utf8'+ )+ );++ assert.equal(failed.state, 'remediation-required');+ assert.equal(failed.manualAvailabilityRestore, undefined);+ assert.deepEqual(restoredManifest.unavailableLocales, ['ar-SA', 'he-IL']);+ for (const locale of ['ar-SA', 'he-IL']) {+ assert.equal(+ restoredManifest.bidirectionalReadiness.localeReadiness[locale].status,+ 'pending-remediation'+ );+ }+ assert.equal(restoredManifest.bidirectionalReadiness.status, 'pending-remediation');+ assert.equal(fs.readFileSync(availabilityPath, 'utf8'), failClosedSource);+ assert.ok(+ fs.existsSync(path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE))+ );++ assert.equal(+ markLocalizationVerificationFailed(projectRoot, transaction.runId).state,+ 'remediation-required'+ );+ assert.equal(fs.readFileSync(availabilityPath, 'utf8'), failClosedSource);+});++function exposedTransactionProject(t) {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifestAndAvailability(projectRoot, manifest({ unavailableLocales: [] }));+ return { projectRoot, transaction };+}++function assertManualRestore(projectRoot, failed, reasonPattern) {+ assert.equal(failed.state, 'remediation-required');+ assert.deepEqual(failed.manualAvailabilityRestore.locales, ['ar-SA']);+ assert.match(failed.manualAvailabilityRestore.reason, reasonPattern);+ // Manual mode writes no source file, so the module still exposes ar-SA...+ assert.equal(+ fs.readFileSync(path.join(projectRoot, AVAILABILITY_MODULE), 'utf8'),+ availabilitySource([])+ );+ // ...while the manifest metadata is restored to its fail-closed state.+ const restored = JSON.parse(fs.readFileSync(+ path.join(projectRoot, '.powerpages-localization.json'),+ 'utf8'+ ));+ assert.deepEqual(restored.unavailableLocales, ['ar-SA']);+ assert.equal(+ restored.bidirectionalReadiness.localeReadiness['ar-SA'].status,+ 'pending-remediation'+ );+}++function sha256(value) {+ return crypto.createHash('sha256').update(value, 'utf8').digest('hex');+}++test('falls back to a manual restore when the availability backup is missing', (t) => {+ const { projectRoot, transaction } = exposedTransactionProject(t);+ fs.unlinkSync(path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE));++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );++ assertManualRestore(projectRoot, failed, /is missing/);+ assert.match(+ formatManualAvailabilityRestore(failed),+ /Exclude "ar-SA" in "src\/i18n\/localeAvailability\.ts", then run --finalize/+ );+ // A repeated --fail keeps the instruction and still writes no source file.+ assertManualRestore(+ projectRoot,+ markLocalizationVerificationFailed(projectRoot),+ /is missing/+ );+});++test('falls back to a manual restore when the availability backup changed', (t) => {+ const { projectRoot, transaction } = exposedTransactionProject(t);+ // For example, line endings rewritten by git after the backup was committed.+ fs.writeFileSync(+ path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE),+ availabilitySource(['ar-SA']).replace(/\n/g, '\r\n')+ );++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );++ assertManualRestore(projectRoot, failed, /no longer matches its recorded checksum/);+});++test('never restores the backup to a path taken from a tampered transaction', (t) => {+ for (const tamperedPath of [+ '.git/config',+ 'src/i18n/../../.git/config',+ 'package.json',+ ]) {+ const { projectRoot, transaction } = exposedTransactionProject(t);+ const originalContent = 'ORIGINAL-CONTENT\n';+ const targetPath = writeProjectFile(+ projectRoot,+ path.posix.normalize(tamperedPath),+ originalContent+ );+ // The backup checksum matches, so only the path check can stop the write.+ const backupContent = 'BENIGN-TEST-MARKER\n';+ fs.writeFileSync(+ path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE),+ backupContent+ );+ const transactionPath = path.join(projectRoot, TRANSACTION_FILE);+ const tampered = JSON.parse(fs.readFileSync(transactionPath, 'utf8'));+ tampered.availabilitySnapshot = {+ path: tamperedPath,+ sha256: sha256(backupContent),+ };+ fs.writeFileSync(transactionPath, JSON.stringify(tampered));++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );++ assert.equal(+ fs.readFileSync(targetPath, 'utf8'),+ originalContent,+ `${tamperedPath} must not be overwritten`+ );+ assertManualRestore(projectRoot, failed, /snapshot path does not match/);+ }+});++test('never restores into a hidden directory even when the manifest names it', (t) => {+ const projectRoot = createTempProject(t);+ const hiddenModule = '.config/localeAvailability.ts';+ writeProjectFile(projectRoot, hiddenModule, availabilitySource(['ar-SA']));+ writeManifest(projectRoot, manifest({ managedFiles: [hiddenModule] }));+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeProjectFile(projectRoot, hiddenModule, availabilitySource([]));+ writeManifest(projectRoot, manifest({+ managedFiles: [hiddenModule],+ unavailableLocales: [],+ }));++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );++ assert.match(failed.manualAvailabilityRestore.reason, /hidden directory/);+ assert.equal(+ fs.readFileSync(path.join(projectRoot, hiddenModule), 'utf8'),+ availabilitySource([])+ );+});++test('rejects a stale audit outcome after a replacement transaction begins', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const stale = beginLocalizationVerification(projectRoot, ['ar-SA']);+ markLocalizationVerificationFailed(projectRoot, stale.runId);+ finalizeLocalizationVerification(projectRoot);+ const current = beginLocalizationVerification(projectRoot, ['ar-SA']);++ assert.throws(+ () => markLocalizationVerificationPassed(projectRoot, stale.runId),+ /runId changed/+ );+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.runId,+ current.runId+ );+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'in-progress'+ );+});++test('failure wins if successful and failed outcomes race for one run', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );++ const failed = markLocalizationVerificationFailed(+ projectRoot,+ transaction.runId+ );++ assert.equal(failed.state, 'remediation-required');+ assert.equal(failed.verifiedAt, undefined);+ assert.throws(+ () => markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ verificationEvidence()+ ),+ /must be in-progress/+ );+});++test('blocks finalization while the rendered audit is active or abandoned', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ beginLocalizationVerificationAudit(projectRoot, transaction.runId);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /still active or was abandoned/+ );++ abandonLocalizationVerificationAudit(projectRoot, transaction.runId);+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));+ finalizeLocalizationVerification(projectRoot);+ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('allows only one rendered audit lease for a transaction', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ beginLocalizationVerificationAudit(projectRoot, transaction.runId);++ assert.throws(() => {+ beginLocalizationVerificationAudit(projectRoot, transaction.runId);+ }, (error) => {+ assert.match(error.message, /already exists/);+ assert.equal(error.code, AUDIT_LEASE_CONFLICT_CODE);+ return true;+ });++ abandonLocalizationVerificationAudit(projectRoot, transaction.runId);+});++test('transaction manager rejects unknown and duplicate arguments', () => {+ assert.throws(+ () => parseManagerArgs([+ '--begin',+ '--projectRoot', '.',+ '--locales', 'ar-SA',+ '--bogus', 'value',+ ]),+ /Unknown or misplaced argument "--bogus"/+ );+ assert.throws(+ () => parseManagerArgs([+ '--begin',+ '--projectRoot', '.',+ '--projectRoot', '..',+ '--locales', 'ar-SA',+ ]),+ /"--projectRoot" may be specified only once/+ );+ assert.throws(+ () => parseManagerArgs([+ '--extend',+ '--projectRoot', '.',+ '--profile', 'standard',+ ]),+ /requires --profile extensive/+ );+ assert.deepEqual(+ parseManagerArgs([+ '--finalize',+ '--projectRoot', '.',+ '--manual-review-completed',+ '--rendered-review-completed',+ ]).manualReviewCompleted,+ true+ );+ assert.equal(+ parseManagerArgs([+ '--finalize',+ '--projectRoot', '.',+ '--rendered-review-completed',+ ]).renderedReviewCompleted,+ true+ );+});++test('finalizes a successful verification only after the manifest is ready', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ null,+ currentVerificationEvidence(projectRoot)+ );+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));++ finalizeLocalizationVerification(projectRoot);++ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+ assert.ok(+ !fs.existsSync(path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE))+ );+});++test('blocks verified finalization before the maker decides an exposed target', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ const exposedManifest = manifest({ unavailableLocales: [] });+ writeManifestAndAvailability(projectRoot, exposedManifest);+ const verified = markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );++ // Still exposed and still pending: the maker decision was never recorded.+ assert.match(+ validateTransactionAgainstManifest(verified, exposedManifest).join('\n'),+ /verified target locale ar-SA must either be ready or approved-with-limitations and available, or remain pending-remediation and unavailable/+ );+ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /must be fully reconciled before finalization/+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('finalizes a verified target that the maker keeps unavailable', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifestAndAvailability(projectRoot, manifest({ unavailableLocales: [] }));+ const verification = currentVerificationEvidence(+ projectRoot,+ 'extensive',+ [],+ [CALENDAR_REVIEW_FINDING]+ );+ markLocalizationVerificationPassed(projectRoot, transaction.runId, verification);++ // "Save but keep locale unavailable": hide ar-SA again and keep its open+ // review finding as the remediation record.+ writeManifestAndAvailability(projectRoot, manifest({+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ ...CALENDAR_REVIEW_FINDING,+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ },+ }));+ // Hiding the locale changed availability inputs, so only the+ // availability-neutral fingerprint can accept this outcome.+ assert.notEqual(+ computeVerificationInputFingerprint(projectRoot),+ verification.evidence.inputFingerprint+ );++ finalizeLocalizationVerification(projectRoot);++ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+ assert.ok(+ !fs.existsSync(path.join(projectRoot, TRANSACTION_AVAILABILITY_FILE))+ );+});++test('finalizes one target enabled and another kept unavailable', (t) => {+ const projectRoot = createTempProject(t);+ const threeLocaleManifest = (unavailableLocales, hebrewStatus) => manifest({+ locales: ['en-US', 'ar-SA', 'he-IL'],+ resourcePaths: {+ 'en-US': 'src/i18n/locales/en-US.json',+ 'ar-SA': 'src/i18n/locales/ar-SA.json',+ 'he-IL': 'src/i18n/locales/he-IL.json',+ },+ unavailableLocales,+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ 'he-IL': { status: hebrewStatus },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ writeManifest(+ projectRoot,+ threeLocaleManifest(['ar-SA', 'he-IL'], 'pending-remediation')+ );+ const transaction = beginLocalizationVerification(+ projectRoot,+ ['ar-SA', 'he-IL']+ );+ writeManifestAndAvailability(+ projectRoot,+ threeLocaleManifest([], 'pending-remediation')+ );+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );++ // Maker: enable Hebrew, keep Arabic unavailable.+ writeManifestAndAvailability(+ projectRoot,+ threeLocaleManifest(['ar-SA'], 'ready')+ );++ finalizeLocalizationVerification(projectRoot);++ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('rejects other input changes when a target is kept unavailable', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifestAndAvailability(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );+ writeManifestAndAvailability(projectRoot, manifest());+ writeProjectFile(+ projectRoot,+ 'src/App.tsx',+ 'export const App = () => <main>Changed after verification</main>;\n'+ );++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /rendered evidence is stale.*inputs changed.*audit again/is+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('requires availability-neutral evidence to keep a target unavailable', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifestAndAvailability(projectRoot, manifest({ unavailableLocales: [] }));+ const verification = currentVerificationEvidence(projectRoot);+ delete verification.evidence.inputFingerprintWithoutAvailability;+ markLocalizationVerificationPassed(projectRoot, transaction.runId, verification);+ writeManifestAndAvailability(projectRoot, manifest());++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /predates finalization with target locales kept unavailable/+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('finalizes a verified target approved with limitations and available', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot, 'extensive', [], [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'third-party-surface-review',+ severity: 'review',+ message: 'The external calendar remains usable with limited RTL mirroring.',+ selector: '.calendar',+ }])+ );+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'third-party-surface-review',+ severity: 'review',+ message: 'The external calendar remains usable with limited RTL mirroring.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ disposition: {+ status: 'maker-approved',+ impact: 'The calendar keeps its vendor-provided navigation layout.',+ evidence: 'docs/bidirectional-evidence/calendar-ar.png',+ approvedAt: '2026-09-03T00:00:00.000Z',+ },+ }],+ },+ }));++ finalizeLocalizationVerification(projectRoot);++ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('requires confirmation before dropping rendered review findings', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot, 'extensive', [], [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'rendered-semantic-review',+ severity: 'review',+ message: 'Confirm that the calendar navigation remains understandable.',+ selector: '.calendar',+ }])+ );+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /removed without confirming that the maker reviewed it/+ );+ const finalized = finalizeLocalizationVerification(projectRoot, {+ renderedReviewCompleted: true,+ });+ assert.ok(finalized.renderedReviewCompletedAt);+});++test('rejects verified finalization after project inputs change', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot)+ );+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));+ writeProjectFile(+ projectRoot,+ 'src/App.tsx',+ 'export const App = () => <main>Changed after verification</main>;\n'+ );++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /rendered evidence is stale.*inputs changed.*audit again/is+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('finalizes failed verification only after fail-closed availability is restored', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ markLocalizationVerificationFailed(projectRoot);++ finalizeLocalizationVerification(projectRoot);++ assert.ok(!fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('requires manual review before finalizing standard verification', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(+ projectRoot,+ ['ar-SA'],+ 'standard'+ );+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ currentVerificationEvidence(projectRoot, 'standard', [{+ locale: 'ar-SA',+ componentId: 'calendar',+ }])+ );+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /requires the maker to complete/+ );+ const finalized = finalizeLocalizationVerification(projectRoot, {+ manualReviewCompleted: true,+ });+ assert.ok(finalized.manualReviewCompletedAt);+});++test('extends verified standard verification to the extensive profile', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ const transaction = beginLocalizationVerification(+ projectRoot,+ ['ar-SA'],+ 'standard'+ );+ markLocalizationVerificationPassed(+ projectRoot,+ transaction.runId,+ verificationEvidence('standard')+ );++ const extended = extendLocalizationVerification(projectRoot, 'extensive');++ assert.equal(extended.state, 'in-progress');+ assert.equal(extended.verificationProfile, 'extensive');+ assert.equal(extended.verification, undefined);+});++test('does not promote a remediation-required transaction without a new audit', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ markLocalizationVerificationFailed(projectRoot);+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /must be restored to pending-remediation and unavailable/+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('does not finalize an exposed locale that is still pending verification', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({ unavailableLocales: [] }));++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /fully reconciled/+ );+ assert.ok(fs.existsSync(path.join(projectRoot, TRANSACTION_FILE)));+});++test('does not finalize a ready locale before a successful rendered audit', (t) => {+ const projectRoot = createTempProject(t);+ writeManifest(projectRoot, manifest());+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ writeManifest(projectRoot, manifest({+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ }));++ assert.throws(+ () => finalizeLocalizationVerification(projectRoot),+ /cannot be finalized before the rendered audit/+ );+});diff --git a/plugins/power-pages/scripts/tests/render-add-localization-plan.test.js b/plugins/power-pages/scripts/tests/render-add-localization-plan.test.jsnew file mode 100644index 000000000..1a2073ee3--- /dev/null+++ b/plugins/power-pages/scripts/tests/render-add-localization-plan.test.js@@ -0,0 +1,860 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { spawnSync } = require('node:child_process');++const scriptPath = path.join(__dirname, '..', 'render-add-localization-plan.js');++const ENGLISH_LABELS = {+ navigation: {+ group: 'Localization plan',+ overview: 'Overview',+ languages: 'Languages',+ changes: 'Changes',+ readiness: 'Bidirectional readiness',+ verification: 'Verification',+ },+ overview: {+ title: 'Localization overview',+ description: 'Localization implementation plan for {siteName}',+ framework: 'Framework',+ invocation: 'Invocation',+ operation: 'Operation',+ existingSetup: 'Existing localization',+ configuration: 'Approved configuration',+ frameworkEvidence: 'Framework evidence',+ existingDetails: 'Existing setup',+ conflicts: 'Conflicts',+ noConflicts: 'No conflicts detected.',+ },+ configuration: {+ package: 'Package',+ mode: 'Mode',+ defaultLocale: 'Default locale',+ translation: 'Translation population',+ selector: 'Language selector',+ verification: 'Package verification',+ selection: 'Package selection',+ evidenceSource: 'Evidence source',+ evidence: 'Evidence',+ initialization: 'Initialization evidence',+ rootRepair: 'Root document repair',+ },+ languages: {+ title: 'Languages',+ description: 'Source, existing, and newly added locales',+ language: 'Language',+ locale: 'Locale',+ direction: 'Direction',+ roles: 'Roles',+ availability: 'Availability',+ },+ changes: {+ title: 'Files and packages',+ description: 'Exact implementation delta after approval',+ path: 'Path or package',+ action: 'Action',+ reason: 'Reason',+ },+ readiness: {+ title: 'Bidirectional readiness',+ description: 'Direction transition, findings, and planned remediation',+ transition: 'Direction-set transition',+ findings: 'Readiness findings',+ noFindings: 'No readiness findings.',+ location: 'Location',+ rule: 'Rule',+ scope: 'Scope',+ affectedLocales: 'Affected locales',+ remediation: 'Planned remediation',+ componentScope: 'Component review scope',+ component: 'Component',+ classification: 'Classification',+ reason: 'Reason',+ states: 'Applicable states',+ viewports: 'Applicable viewports',+ checks: 'Planned checks',+ physicalExceptions: 'Physical exceptions',+ scriptFonts: 'Script font changes',+ unavailableLocales: 'Locales pending remediation',+ none: 'None.',+ },+ verification: {+ title: 'Verification and limitations',+ description: 'Checks that will run before maker review',+ checks: 'Verification checks',+ limitations: 'Known limitations',+ noLimitations: 'No known limitations.',+ },+ status: {+ new: 'New',+ preserved: 'Preserved',+ changed: 'Changed',+ create: 'Create',+ update: 'Update',+ preserve: 'Preserve',+ replace: 'Replace',+ skip: 'Skip',+ source: 'Source',+ default: 'Default',+ existing: 'Existing',+ added: 'Added',+ available: 'Available',+ pendingRemediation: 'Pending remediation',+ verified: 'Verified',+ unverified: 'Unverified',+ yes: 'Yes',+ no: 'No',+ },+ packageSelection: {+ recommended: 'Recommended',+ alternative: 'Alternative',+ preserved: 'Preserved',+ },+ evidenceSource: {+ knownCapability: 'Known capability',+ packageDocumentation: 'Package documentation',+ officialDocumentation: 'Official documentation',+ userApproved: 'User approved',+ },+ severity: { error: 'Error', review: 'Review' },+ classification: {+ directionNeutral: 'Direction-neutral',+ directionAware: 'Direction-aware',+ directionFixed: 'Direction-fixed',+ unknownThirdParty: 'Unknown or third-party',+ },+ viewport: {+ desktop: 'Desktop',+ narrow: 'Narrow or mobile',+ },+ operation: {+ create: 'Create localization',+ addLanguages: 'Add languages',+ repair: 'Repair',+ reconfigure: 'Reconfigure',+ },+ invocation: { direct: 'Direct', createSite: 'From create-site' },+ footer: { aiWarning: 'AI-generated content may be incorrect' },+};++const SAMPLE_DATA = {+ SITE_NAME: 'Contoso Portal',+ PLAN_TITLE: 'Localization Implementation Plan',+ SOURCE_LANGUAGE: 'English (United States)',+ SOURCE_LOCALE: 'en-US',+ SOURCE_DIRECTION: 'ltr',+ FRAMEWORK: 'React',+ INVOCATION_CONTEXT: 'direct',+ OPERATION: 'create',+ EXISTING_LOCALIZATION_DETECTED: false,+ SUMMARY: 'Add French runtime localization while preserving English as the source and default.',+ PLAN_LABELS: ENGLISH_LABELS,+ DISCOVERY_DATA: {+ frameworkEvidence: ['package.json contains react and react-dom dependencies.'],+ existingSetup: ['No existing localization package, resources, or manifest were detected.'],+ conflicts: [],+ },+ CONFIGURATION_DATA: {+ package: {+ value: 'react-i18next 15.0.0',+ name: 'react-i18next',+ version: '15.0.0',+ status: 'new',+ verification: 'verified',+ selection: 'recommended',+ evidenceSource: 'known-capability',+ evidenceUrl: 'https://www.npmjs.com/package/react-i18next',+ initializationEvidence: null,+ },+ mode: { value: 'runtime', status: 'new' },+ defaultLocale: { value: 'en-US', status: 'preserved' },+ translation: {+ method: 'agent',+ value: 'Agent-generated translations',+ description: 'Translate from the approved English source resources.',+ warning: 'AI translations may contain errors - please verify them before publishing.',+ },+ selector: {+ value: 'Shared navigation',+ description: 'Switch locales without reloading and persist the browser preference.',+ },+ rootDocumentRepair: null,+ },+ LOCALES_DATA: [+ {+ language: 'English (United States)',+ locale: 'en-US',+ direction: 'ltr',+ roles: ['source', 'default', 'existing'],+ availability: 'available',+ },+ {+ language: 'French (France)',+ locale: 'fr-FR',+ direction: 'ltr',+ roles: ['added'],+ availability: 'pending-remediation',+ },+ ],+ FILES_DATA: [+ {+ path: 'package.json',+ action: 'update',+ reason: 'Add the approved runtime localization dependencies.',+ },+ {+ path: 'src/i18n/index.ts',+ action: 'create',+ reason: 'Initialize the locale coordinator and fallback behavior.',+ },+ ],+ READINESS_DATA: {+ transition: 'ltr-only → ltr-only',+ findings: [+ {+ severity: 'review',+ file: 'src/components/Carousel.tsx',+ line: 42,+ rule: 'directional-geometry-review',+ message: 'Review carousel movement in both directions.',+ remediation: 'Use semantic next and previous movement and browser-test both directions.',+ scope: 'locale',+ affectedLocales: ['fr-FR'],+ },+ ],+ componentScope: [+ {+ component: 'Shared navigation',+ classification: 'direction-aware',+ reason: 'Navigation placement, order, and directional icons follow reading direction.',+ states: ['Default', 'Mobile menu open'],+ viewports: ['desktop', 'narrow'],+ checks: ['Verify reading order, focus order, placement, and icons in both directions.'],+ },+ {+ component: 'Search input',+ classification: 'direction-aware',+ reason: 'The free-form value and localized field UI can use different directions.',+ states: ['Empty', 'Focused', 'Populated'],+ viewports: ['desktop', 'narrow'],+ checks: ['Verify label, placeholder, hint, value, and results alignment.'],+ },+ ],+ physicalExceptions: [],+ scriptFonts: ['Existing font supports Latin source and target content.'],+ unavailableLocales: ['fr-FR'],+ },+ VALIDATION_DATA: [+ ['independent-validator', 'Run the independent localization validator.'],+ ['project-build', 'Run the existing project build.'],+ ['package-initialization', 'Verify package initialization.'],+ ['resource-completeness', 'Verify every locale resource has every source key.'],+ ['protected-tokens', 'Verify protected tokens are unchanged.'],+ ['locale-navigation', 'Verify the selector or static locale navigation.'],+ ['locale-state', 'Verify runtime persistence or static navigation state.'],+ ['fallback-behavior', 'Verify invalid and missing locale fallback.'],+ ['document-lang-dir', 'Verify the active document language and direction.'],+ ['browser-console', 'Verify the browser console has no localization errors.'],+ ['representative-routes', 'Verify representative routes and viewports.'],+ ['bidirectional-content', 'Verify RTL and mixed-direction content.'],+ ['localized-formatting', 'Verify locale-aware dates and numbers.'],+ ['script-fonts', 'Verify script font coverage and loading.'],+ ['directional-components', 'Verify directional components and assets.'],+ ['accessibility', 'Verify no serious accessibility regression.'],+ ].map(([id, description]) => ({ id, description })),+ LIMITATIONS_DATA: [],+};++function run(data, outputPath, mode = 'inline') {+ if (mode === 'file') {+ const dataPath = path.join(path.dirname(outputPath), 'plan-data.json');+ fs.writeFileSync(dataPath, JSON.stringify(data), 'utf8');+ return spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data', dataPath],+ { encoding: 'utf8' }+ );+ }+ return spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(data)],+ { encoding: 'utf8' }+ );+}++test('renders the localization plan in the source locale', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const result = run(SAMPLE_DATA, outputPath, 'file');++ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /<html lang="en-US" dir="ltr">/);+ assert.match(html, /Localization Implementation Plan/);+ assert.match(html, /Contoso Portal/);+ assert.match(html, /react-i18next 15\.0\.0/);+ assert.match(html, /package\.json contains react and react-dom/);+ assert.match(html, /Known capability/);+ assert.match(html, /fr-FR/);+ assert.match(html, /src\/i18n\/index\.ts/);+ assert.match(html, /directional-geometry-review/);+ assert.match(html, /Component review scope/);+ assert.match(html, /Direction-aware/);+ assert.match(html, /Mobile menu open/);+ assert.match(html, /Search input/);+ assert.match(html, /AI translations may contain errors/);+ assert.ok(+ html.indexOf('data-label="footer.aiWarning"') < html.indexOf('<script id="siteNameData"'),+ 'localized footer must exist before the script applies data-label text'+ );+ assert.ok(fs.existsSync(path.join(tempDir, 'power-pages-icon.png')));+});++test('keeps the plan in the source locale when the resulting default changes', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const data = {+ ...SAMPLE_DATA,+ OPERATION: 'reconfigure',+ EXISTING_LOCALIZATION_DETECTED: true,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ defaultLocale: { value: 'fr-FR', status: 'changed' },+ },+ LOCALES_DATA: [+ {+ language: 'English (United States)',+ locale: 'en-US',+ direction: 'ltr',+ roles: ['source', 'existing'],+ availability: 'available',+ },+ {+ language: 'French (France)',+ locale: 'fr-FR',+ direction: 'ltr',+ roles: ['default', 'existing'],+ availability: 'available',+ },+ ],+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ findings: [],+ unavailableLocales: [],+ },+ };++ const result = run(data, outputPath);+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /<html lang="en-US" dir="ltr">/);+ assert.match(html, /"value":"fr-FR","status":"changed"/);+});++test('renders an RTL source-language plan with logical layout CSS', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const data = {+ ...SAMPLE_DATA,+ PLAN_TITLE: 'خطة تنفيذ الترجمة',+ SOURCE_LANGUAGE: 'العربية',+ SOURCE_LOCALE: 'ar-SA',+ SOURCE_DIRECTION: 'rtl',+ SUMMARY: 'إضافة اللغة الإنجليزية مع الحفاظ على العربية كلغة المصدر.',+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ navigation: {+ group: 'خطة الترجمة',+ overview: 'نظرة عامة',+ languages: 'اللغات',+ changes: 'التغييرات',+ readiness: 'جاهزية الاتجاهين',+ verification: 'التحقق',+ },+ overview: {+ ...ENGLISH_LABELS.overview,+ title: 'نظرة عامة على الترجمة',+ description: 'خطة تنفيذ الترجمة لـ {siteName}',+ },+ footer: { aiWarning: 'قد يكون المحتوى الذي تم إنشاؤه بواسطة الذكاء الاصطناعي غير صحيح' },+ },+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ defaultLocale: { value: 'ar-SA', status: 'preserved' },+ },+ LOCALES_DATA: [+ {+ language: 'العربية',+ locale: 'ar-SA',+ direction: 'rtl',+ roles: ['source', 'default', 'existing'],+ availability: 'available',+ },+ {+ language: 'الإنجليزية',+ locale: 'en-US',+ direction: 'ltr',+ roles: ['added'],+ availability: 'pending-remediation',+ },+ ],+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ findings: [{+ ...SAMPLE_DATA.READINESS_DATA.findings[0],+ affectedLocales: ['en-US'],+ }],+ unavailableLocales: ['en-US'],+ },+ };++ const result = run(data, outputPath);+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /<html lang="ar-SA" dir="rtl">/);+ assert.match(html, /نظرة عامة على الترجمة/);+ assert.match(html, /border-inline-start/);+ assert.match(html, /border-inline-end/);+ assert.doesNotMatch(+ html,+ /(?:border|padding|margin)-(?:left|right)|text-align:\s*(?:left|right)|(?:^|[;{])(?:left|right):/m+ );+});++test('escapes localized and plan data embedded in HTML', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const data = {+ ...SAMPLE_DATA,+ SUMMARY: '</script><script>window.__summaryPwned=1</script>',+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ navigation: {+ ...ENGLISH_LABELS.navigation,+ overview: '</script><script>window.__labelPwned=1</script>',+ },+ },+ FILES_DATA: [+ {+ path: '</script><script>window.__filePwned=1</script>',+ action: 'create',+ reason: '<img src=x onerror=alert(1)>',+ },+ ],+ };++ const result = run(data, outputPath);+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.doesNotMatch(html, /<\/script><script>window\.__(?:summary|label|file)Pwned/);+ assert.match(html, /\\u003c\/script\\u003e/);+});++test('rejects source locale and direction mismatches', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const result = run(+ { ...SAMPLE_DATA, SOURCE_LOCALE: 'ar-SA', SOURCE_DIRECTION: 'ltr' },+ outputPath+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /SOURCE_DIRECTION "ltr" does not match ar-SA/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('rejects missing localized labels', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const data = {+ ...SAMPLE_DATA,+ PLAN_LABELS: { ...ENGLISH_LABELS, footer: {} },+ };+ const result = run(data, outputPath);++ assert.equal(result.status, 1);+ assert.match(result.stderr, /footer\.aiWarning/);+});++test('rejects inconsistent default and locale-role data', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const data = {+ ...SAMPLE_DATA,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ defaultLocale: { value: 'de-DE', status: 'changed' },+ },+ };+ const result = run(data, outputPath);++ assert.equal(result.status, 1);+ assert.match(result.stderr, /defaultLocale\.value must match the default locale role/);+});++test('rejects unsafe unexpected statuses and incomplete verification coverage', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const statusOutput = path.join(tempDir, 'status.html');+ const unsafeStatus = {+ ...SAMPLE_DATA,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ translation: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.translation,+ status: '" onmouseover="window.__pwned=1',+ },+ },+ };+ const statusResult = run(unsafeStatus, statusOutput);+ assert.equal(statusResult.status, 1);+ assert.match(statusResult.stderr, /translation must not define status/);++ const coverageOutput = path.join(tempDir, 'coverage.html');+ const incomplete = {+ ...SAMPLE_DATA,+ VALIDATION_DATA: [+ { id: 'project-build', description: 'Run the project build.' },+ ],+ };+ const coverageResult = run(incomplete, coverageOutput);+ assert.equal(coverageResult.status, 1);+ assert.match(coverageResult.stderr, /missing required checks/);+ assert.match(coverageResult.stderr, /independent-validator/);+});++test('accepts package documentation evidence and rejects invalid unverified evidence', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const validOutput = path.join(tempDir, 'package-docs.html');+ const packageDocs = {+ ...SAMPLE_DATA,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ package: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.package,+ selection: 'alternative',+ evidenceSource: 'package-documentation',+ evidenceUrl: undefined,+ },+ },+ };+ const valid = run(packageDocs, validOutput);+ assert.equal(valid.status, 0, valid.stderr || valid.stdout);++ const invalidOutput = path.join(tempDir, 'unverified.html');+ const invalid = {+ ...SAMPLE_DATA,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ package: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.package,+ verification: 'unverified',+ evidenceSource: 'package-documentation',+ },+ },+ };+ const invalidResult = run(invalid, invalidOutput);+ assert.equal(invalidResult.status, 1);+ assert.match(invalidResult.stderr, /must use evidenceSource "user-approved"/);++ const officialOutput = path.join(tempDir, 'official.html');+ const officialWithoutUrl = {+ ...SAMPLE_DATA,+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ package: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.package,+ selection: 'alternative',+ evidenceSource: 'official-documentation',+ evidenceUrl: undefined,+ },+ },+ };+ const officialResult = run(officialWithoutUrl, officialOutput);+ assert.equal(officialResult.status, 1);+ assert.match(officialResult.stderr, /requires an HTTPS evidenceUrl/);+});++test('rejects contradictory source roles, duplicate locales, and incomplete findings', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const localeOutput = path.join(tempDir, 'locales.html');+ const invalidLocales = {+ ...SAMPLE_DATA,+ LOCALES_DATA: [+ {+ language: 'English (United States)',+ locale: 'en-US',+ direction: 'ltr',+ roles: ['source', 'default', 'added'],+ availability: 'available',+ },+ {+ language: 'English duplicate',+ locale: 'en-US',+ direction: 'ltr',+ roles: ['existing'],+ availability: 'available',+ },+ ],+ };+ const localeResult = run(invalidLocales, localeOutput);+ assert.equal(localeResult.status, 1);+ assert.match(localeResult.stderr, /must not contain duplicate locale tags/);+ assert.match(localeResult.stderr, /source locale must use the existing role/);++ const findingOutput = path.join(tempDir, 'finding.html');+ const incompleteFinding = {+ ...SAMPLE_DATA,+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ findings: [+ {+ severity: 'error',+ file: 'src/styles.css',+ line: 0,+ rule: 'directional-physical-css',+ message: 'Physical CSS blocks RTL.',+ },+ ],+ },+ };+ const findingResult = run(incompleteFinding, findingOutput);+ assert.equal(findingResult.status, 1);+ assert.match(findingResult.stderr, /line must be a positive integer/);+ assert.match(findingResult.stderr, /remediation must be a non-empty string/);++ const scopeOutput = path.join(tempDir, 'component-scope.html');+ const incompleteScope = {+ ...SAMPLE_DATA,+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ componentScope: [+ {+ component: 'Contact form',+ classification: 'direction-aware',+ reason: 'Form controls depend on the active direction.',+ states: [],+ viewports: ['desktop'],+ checks: ['Verify both directions.'],+ },+ ],+ },+ };+ const scopeResult = run(incompleteScope, scopeOutput);+ assert.equal(scopeResult.status, 1);+ assert.match(scopeResult.stderr, /componentScope\[0\]\.states/);+});++test('requires only the locales named by a readiness finding to remain unavailable', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'unsafe-locale.html');+ const unsafePlan = {+ ...SAMPLE_DATA,+ LOCALES_DATA: [+ SAMPLE_DATA.LOCALES_DATA[0],+ {+ language: 'Arabic',+ locale: 'ar-SA',+ direction: 'rtl',+ roles: ['added'],+ availability: 'available',+ },+ ],+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ transition: 'ltr-only → mixed',+ findings: [{+ severity: 'error',+ file: 'src/styles.css',+ line: 42,+ rule: 'directional-physical-css',+ message: 'Physical alignment blocks RTL.',+ remediation: 'Replace the physical property with its logical equivalent.',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ unavailableLocales: [],+ },+ };++ const result = run(unsafePlan, outputPath);++ assert.equal(result.status, 1);+ assert.match(+ result.stderr,+ /requires affected locale ar-SA to remain pending-remediation/+ );+});++test('rejects a plan that makes the selected default locale pending', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'pending-default.html');+ const pendingDefault = {+ ...SAMPLE_DATA,+ OPERATION: 'reconfigure',+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ defaultLocale: { value: 'fr-FR', status: 'changed' },+ },+ LOCALES_DATA: [+ {+ ...SAMPLE_DATA.LOCALES_DATA[0],+ roles: ['source', 'existing'],+ },+ {+ ...SAMPLE_DATA.LOCALES_DATA[1],+ roles: ['default', 'added'],+ },+ ],+ };++ const result = run(pendingDefault, outputPath);++ assert.equal(result.status, 1);+ assert.match(result.stderr, /default locale must remain available/i);+});++test('keeps an existing ready RTL locale available when only a new RTL locale is affected', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const outputPath = path.join(tempDir, 'isolated-arabic-finding.html');+ const isolatedPlan = {+ ...SAMPLE_DATA,+ LOCALES_DATA: [+ SAMPLE_DATA.LOCALES_DATA[0],+ {+ language: 'Hebrew',+ locale: 'he-IL',+ direction: 'rtl',+ roles: ['existing'],+ availability: 'available',+ },+ {+ language: 'Arabic',+ locale: 'ar-SA',+ direction: 'rtl',+ roles: ['added'],+ availability: 'pending-remediation',+ },+ ],+ READINESS_DATA: {+ ...SAMPLE_DATA.READINESS_DATA,+ transition: 'mixed -> mixed',+ findings: [{+ severity: 'error',+ file: 'src/components/ArabicCalendar.tsx',+ line: 42,+ rule: 'localized-font-failure',+ message: 'The Arabic calendar font is unreadable.',+ remediation: 'Load the approved Arabic script font for this component.',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ unavailableLocales: ['ar-SA'],+ },+ };++ const result = run(isolatedPlan, outputPath);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.existsSync(outputPath), true);+});++test('rejects plans for temporarily unavailable localization modes', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const angularOutput = path.join(tempDir, 'angular-static.html');+ const angularStatic = {+ ...SAMPLE_DATA,+ FRAMEWORK: 'Angular',+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ package: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.package,+ value: '@angular/localize 19.1.0',+ name: '@angular/localize',+ version: '19.1.0',+ },+ mode: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.mode,+ value: 'static',+ },+ },+ };+ const angularResult = run(angularStatic, angularOutput);+ assert.equal(angularResult.status, 1);+ assert.match(angularResult.stderr, /Angular static localization is temporarily unavailable/);+ assert.equal(fs.existsSync(angularOutput), false);++ const astroOutput = path.join(tempDir, 'astro-static.html');+ const astroStatic = {+ ...angularStatic,+ FRAMEWORK: 'Astro',+ CONFIGURATION_DATA: {+ ...angularStatic.CONFIGURATION_DATA,+ package: {+ ...angularStatic.CONFIGURATION_DATA.package,+ value: 'Astro built-in i18n',+ name: 'astro-built-in',+ version: 'built-in',+ },+ },+ };+ const astroResult = run(astroStatic, astroOutput);+ assert.equal(astroResult.status, 1);+ assert.match(astroResult.stderr, /No Astro localization mode is currently available/);+ assert.equal(fs.existsSync(astroOutput), false);+});++test('rejects a known package that does not match the planned framework mode', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const output = path.join(tempDir, 'package-mismatch.html');+ const mismatch = {+ ...SAMPLE_DATA,+ FRAMEWORK: 'Angular',+ CONFIGURATION_DATA: {+ ...SAMPLE_DATA.CONFIGURATION_DATA,+ package: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.package,+ value: '@angular/localize 19.1.0',+ name: '@angular/localize',+ version: '19.1.0',+ },+ mode: {+ ...SAMPLE_DATA.CONFIGURATION_DATA.mode,+ value: 'runtime',+ },+ },+ };++ const result = run(mismatch, output);+ assert.equal(result.status, 1);+ assert.match(+ result.stderr,+ /@angular\/localize.*angular static localization, not angular runtime/+ );+ assert.equal(fs.existsSync(output), false);+});++test('rejects invalid JSON and refuses to overwrite an existing plan', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'localization-plan-'));+ const invalidOutput = path.join(tempDir, 'invalid.html');+ const invalid = spawnSync(+ process.execPath,+ [scriptPath, '--output', invalidOutput, '--data-inline', '{bad json}'],+ { encoding: 'utf8' }+ );+ assert.equal(invalid.status, 1);+ assert.match(invalid.stderr, /not valid JSON/);++ const outputPath = path.join(tempDir, 'add-localization-plan.html');+ const first = run(SAMPLE_DATA, outputPath);+ assert.equal(first.status, 0, first.stderr || first.stdout);+ const original = fs.readFileSync(outputPath, 'utf8');+ const second = run(SAMPLE_DATA, outputPath);+ assert.equal(second.status, 1);+ assert.match(second.stderr, /Output file already exists/);+ assert.equal(fs.readFileSync(outputPath, 'utf8'), original);+});diff --git a/plugins/power-pages/scripts/tests/render-createsite-plan.test.js b/plugins/power-pages/scripts/tests/render-createsite-plan.test.jsindex 8bc63b7fc..f0df3baf5 100644--- a/plugins/power-pages/scripts/tests/render-createsite-plan.test.js+++ b/plugins/power-pages/scripts/tests/render-createsite-plan.test.js@@ -7,16 +7,123 @@ const { spawnSync } = require('node:child_process');const scriptPath = path.join(__dirname, '..', 'render-createsite-plan.js');+const ENGLISH_LABELS = {+ navigation: {+ group: 'Plan',+ overview: 'Overview',+ design: 'Design',+ pages: 'Pages & Components',+ deployment: 'Deployment & Review',+ },+ overview: {+ title: 'Overview',+ description: 'Implementation plan for {siteName}',+ stats: { pages: 'Pages', components: 'Shared Components', routes: 'Routes' },+ nextSteps: {+ title: 'What happens next',+ design: {+ title: 'Apply design tokens',+ description: 'Fonts, palette, motion, and backgrounds written into your theme',+ },+ components: {+ title: 'Build shared components',+ descriptionOne: '{count} reusable component used across pages',+ descriptionOther: '{count} reusable components used across pages',+ },+ pages: {+ title: 'Create pages',+ descriptionOne: '{count} page with routing and navigation',+ descriptionOther: '{count} pages with routing and navigation',+ },+ critique: {+ title: 'Critique the design',+ description: 'Desktop and mobile screenshots scored and refined against the design rubric',+ },+ verify: {+ title: 'Verify & accessibility',+ description: 'axe-core audit, Playwright checks, and user review',+ },+ },+ },+ design: {+ title: 'Design',+ description: 'Design direction, typography, palette, motion, and background treatments',+ direction: {+ title: 'Design direction',+ heroConcept: 'Hero concept',+ signatureMoment: 'Signature moment',+ primaryAction: 'Primary action',+ secondaryAction: 'Secondary action',+ principalDoubt: 'Principal doubt',+ proofStrategy: 'Proof strategy',+ brandSource: 'Brand source',+ audience: 'Audience and job',+ },+ typography: 'Typography',+ palette: 'Color palette',+ motion: 'Motion & animation',+ backgrounds: 'Background treatment',+ primaryRole: 'Primary — body & UI',+ secondaryRole: 'Secondary — headings',+ },+ pages: {+ title: 'Pages & Components',+ description: 'Pages to build, their content outline, and the shared components they rely on',+ pages: 'Pages',+ components: 'Shared components',+ routing: 'Routing',+ path: 'Path',+ page: 'Page',+ content: 'Content',+ componentsUsed: 'Components used',+ usedBy: 'Used by',+ noComponents: 'No shared components planned yet.',+ },+ bidirectional: {+ title: 'Bidirectional review scope',+ description: 'Planned component, state, and viewport coverage',+ classification: 'Classification',+ reason: 'Reason',+ states: 'Applicable states',+ viewports: 'Applicable viewports',+ checks: 'Planned checks',+ classifications: {+ directionNeutral: 'Direction-neutral',+ directionAware: 'Direction-aware',+ directionFixed: 'Direction-fixed',+ unknownThirdParty: 'Unknown or third-party',+ },+ viewport: {+ desktop: 'Desktop',+ narrow: 'Narrow or mobile',+ },+ },+ deployment: {+ title: 'Deployment & Review',+ description: 'Verification checklist and deployment options',+ verify: 'Before handoff — verify',+ agentChecks: 'Agent verification',+ agentChecksDescription: 'The agent will run and report these checks before handoff.',+ makerReview: 'Maker review',+ makerReviewDescription: 'Review these judgment-based items in the live preview.',+ options: 'Deployment options',+ recommended: 'Recommended',+ },+ common: { noneSpecified: 'None specified.' },+ footer: { aiWarning: 'AI-generated content may be incorrect' },+};+const SAMPLE_DATA = {SITE_NAME: 'Contoso Portal',PLAN_TITLE: 'Implementation Plan',FRAMEWORK: 'React',- SITE_LANGUAGE: 'Spanish',- SITE_LOCALE: 'es-ES',+ SITE_LANGUAGE: 'English (United States)',+ SITE_LOCALE: 'en-US',SITE_DIRECTION: 'ltr',AESTHETIC: 'Minimal & Clean',MOOD: 'Professional & Trustworthy',SUMMARY: 'An internal portal for Contoso consultants with directory, announcements, and docs.',+ PLAN_LABELS: ENGLISH_LABELS,DESIGN_DIRECTION_DATA: {thesis: 'Calm and precise: warm paper surfaces, Schibsted Grotesk headlines, one deep-teal action color.',brandSource: 'Fresh identity',@@ -67,10 +174,34 @@ const SAMPLE_DATA = {{ path: '/', page: 'Home' },{ path: '/directory', page: 'Directory' },],- REVIEW_DATA: [- 'All pages load without console errors',- 'Navigation links work and highlight the active page',+ BIDIRECTIONAL_REVIEW_DATA: [+ {+ component: 'Navbar',+ classification: 'direction-aware',+ reason: 'Navigation order, placement, and directional icons follow reading direction.',+ states: ['Default', 'Mobile menu open'],+ viewports: ['desktop', 'narrow'],+ checks: ['Verify reading order, focus order, placement, and icons in both directions.'],+ },+ {+ component: 'Consultant search input',+ classification: 'direction-aware',+ reason: 'The free-form value and localized field UI can use different text directions.',+ states: ['Empty', 'Focused', 'Populated'],+ viewports: ['desktop', 'narrow'],+ checks: ['Verify the label, placeholder, hint, value, and results alignment.'],+ },],+ REVIEW_DATA: {+ agentChecks: [+ 'All pages load without console errors',+ 'Logical CSS and mixed-direction boundaries pass the bidirectional-readiness audit',+ ],+ makerReview: [+ 'Language and terminology are appropriate',+ 'Visual hierarchy feels natural in both directions',+ ],+ },DEPLOYMENT_DATA: [{ title: 'Deploy now to Power Pages', description: 'Runs /deploy-site to publish.', recommended: true },{ title: 'Skip for now', description: 'Continue locally, deploy later.' },@@ -95,15 +226,27 @@ test('render-createsite-plan renders HTML from --data file', () => {assert.match(html, /Contoso Portal/);assert.match(html, /Implementation Plan/);assert.match(html, /React/);- assert.match(html, /Spanish \(es-ES, ltr\)/);+ assert.match(html, /English \(United States\)<\/span> <bdi dir="ltr">\(en-US, ltr\)<\/bdi>/);assert.match(html, /Minimal & Clean|Minimal & Clean/);assert.match(html, /DM Sans/);assert.match(html, /#1E3A5F/);assert.match(html, /Directory/);assert.match(html, /Navbar/);+ assert.match(html, /Bidirectional review scope/);+ assert.match(html, /Direction-aware/);+ assert.match(html, /Consultant search input/);+ assert.match(html, /Mobile menu open/);+ assert.match(html, /"agentChecks":\["All pages load without console errors"/);+ assert.match(html, /"makerReview":\["Language and terminology are appropriate"/);+ assert.match(html, /Agent verification/);+ assert.match(html, /Maker review/);assert.match(html, /Deploy now to Power Pages/);assert.match(html, /<script id="designDirectionData" type="application\/json">\{"thesis":"Calm and precise/);assert.match(html, /Directory filters instantly with an animated reflow/);+ assert.ok(+ html.indexOf('data-label="footer.aiWarning"') < html.indexOf('<script id="typographyData"'),+ 'localized footer must exist before the script applies data-label text'+ );assert.match(html, /<img class="logo" src="\.\/power-pages-icon\.png" alt="Power Pages" \/>/);const iconPath = path.join(tempDir, 'power-pages-icon.png');@@ -154,6 +297,157 @@ test('render-createsite-plan renders HTML from --data-inline JSON', () => {assert.match(html, /Space Grotesk/);});+test('render-createsite-plan rejects incomplete bidirectional review scope', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'invalid-bidi-plan.html');+ const invalid = {+ ...SAMPLE_DATA,+ BIDIRECTIONAL_REVIEW_DATA: [+ {+ component: 'Contact form',+ classification: 'direction-aware',+ reason: 'Form controls depend on the active direction.',+ states: [],+ viewports: ['desktop'],+ checks: ['Verify both directions.'],+ },+ ],+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(invalid)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /BIDIRECTIONAL_REVIEW_DATA\[0\]\.states/);+});++test('render-createsite-plan renders localized LTR labels and locale metadata', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan-es.html');+ const spanish = {+ ...SAMPLE_DATA,+ PLAN_TITLE: 'Plan de implementación',+ SITE_LANGUAGE: 'Español (España)',+ SITE_LOCALE: 'es-ES',+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ navigation: {+ group: 'Plan',+ overview: 'Resumen',+ design: 'Diseño',+ pages: 'Páginas y componentes',+ deployment: 'Implementación y revisión',+ },+ overview: {+ ...ENGLISH_LABELS.overview,+ title: 'Resumen',+ description: 'Plan de implementación para {siteName}',+ },+ deployment: {+ ...ENGLISH_LABELS.deployment,+ agentChecks: 'Verificación del agente',+ agentChecksDescription: 'El agente ejecutará e informará estas comprobaciones.',+ makerReview: 'Revisión del creador',+ makerReviewDescription: 'Revise estos elementos de criterio en la vista previa.',+ },+ footer: { aiWarning: 'El contenido generado por IA puede ser incorrecto' },+ },+ SUMMARY: 'Un portal interno para consultores de Contoso.',+ REVIEW_DATA: {+ agentChecks: ['La dirección del documento coincide con la configuración regional'],+ makerReview: ['La jerarquía visual resulta natural'],+ },+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(spanish)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /<html lang="es-ES" dir="ltr">/);+ assert.match(html, /Plan de implementación/);+ assert.match(html, /"overview":"Resumen"/);+ assert.match(html, /Plan de implementación para \{siteName\}/);+ assert.match(html, /Un portal interno para consultores de Contoso/);+ assert.match(html, /"agentChecks":"Verificación del agente"/);+ assert.match(html, /"makerReview":"Revisión del creador"/);+ assert.match(html, /La dirección del documento coincide/);+ assert.match(html, /La jerarquía visual resulta natural/);+ assert.match(html, /React/);+ assert.match(html, /--color-primary/);+ assert.match(html, /"route":"\/directory"/);+ assert.match(html, /<bdi class="pill pill-framework" dir="ltr">React<\/bdi>/);+});++test('render-createsite-plan renders RTL metadata and direction-safe layout', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan-ar.html');+ const arabic = {+ ...SAMPLE_DATA,+ PLAN_TITLE: 'خطة التنفيذ',+ SITE_LANGUAGE: 'العربية (المملكة العربية السعودية)',+ SITE_LOCALE: 'ar-SA',+ SITE_DIRECTION: 'rtl',+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ navigation: {+ group: 'الخطة',+ overview: 'نظرة عامة',+ design: 'التصميم',+ pages: 'الصفحات والمكونات',+ deployment: 'النشر والمراجعة',+ },+ overview: {+ ...ENGLISH_LABELS.overview,+ title: 'نظرة عامة',+ description: 'خطة التنفيذ لـ {siteName}',+ },+ deployment: {+ ...ENGLISH_LABELS.deployment,+ agentChecks: 'تحقق الوكيل',+ agentChecksDescription: 'سيقوم الوكيل بتنفيذ هذه الفحوصات والإبلاغ عنها.',+ makerReview: 'مراجعة المنشئ',+ makerReviewDescription: 'راجع عناصر الحكم هذه في المعاينة المباشرة.',+ },+ footer: { aiWarning: 'قد يكون المحتوى الذي تم إنشاؤه بواسطة الذكاء الاصطناعي غير صحيح' },+ },+ REVIEW_DATA: {+ agentChecks: ['يتطابق اتجاه المستند مع الإعدادات المحلية'],+ makerReview: ['يبدو التسلسل الهرمي المرئي طبيعياً'],+ },+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(arabic)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(outputPath, 'utf8');+ assert.match(html, /<html lang="ar-SA" dir="rtl">/);+ assert.match(html, /"overview":"نظرة عامة"/);+ assert.match(html, /"agentChecks":"تحقق الوكيل"/);+ assert.match(html, /"makerReview":"مراجعة المنشئ"/);+ assert.match(html, /border-inline-start/);+ assert.match(html, /border-inline-end/);+ assert.match(html, /padding-inline-start/);+ assert.match(html, /inset-inline-end/);+ assert.doesNotMatch(+ html,+ /(?:border|padding|margin)-(?:left|right)|text-align:\s*(?:left|right)|(?:^|[;{])(?:left|right):/m+ );+ assert.match(html, /\.page-route,[^{]+\{direction:ltr;unicode-bidi:isolate;\}/);+ assert.match(html, /id="agentChecksContainer"/);+ assert.match(html, /id="makerReviewContainer"/);+});+test('render-createsite-plan escapes string placeholders used in HTML text contexts', () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));const outputPath = path.join(tempDir, 'plan-strings.html');@@ -249,6 +543,17 @@ test('render-createsite-plan escapes </script> and < inside JSON data to preventconst malicious = {...SAMPLE_DATA,SUMMARY: 'Summary with </script><script>window.__summaryPwned=1;</script> and <strong>markup</strong>.',+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ navigation: {+ ...ENGLISH_LABELS.navigation,+ overview: '</script><script>window.__labelPwned=1;</script>',+ },+ deployment: {+ ...ENGLISH_LABELS.deployment,+ recommended: '" onmouseover="window.__attributePwned=1',+ },+ },PAGES_DATA: [{name: '</script><script>window.__pwned=1;</script>',@@ -258,6 +563,10 @@ test('render-createsite-plan escapes </script> and < inside JSON data to preventcomponents: ['OK'],},],+ REVIEW_DATA: {+ agentChecks: ['</script><script>window.__reviewPwned=1;</script>'],+ makerReview: ['" onmouseover="window.__makerPwned=1'],+ },};const result = spawnSync(@@ -278,10 +587,141 @@ test('render-createsite-plan escapes </script> and < inside JSON data to prevent!html.includes('</script><script>window.__summaryPwned=1;</script>'),'rendered HTML leaks a literal </script> from SUMMARY');+ assert.ok(+ !html.includes('</script><script>window.__labelPwned=1;</script>'),+ 'rendered HTML leaks a literal </script> from PLAN_LABELS'+ );+ assert.ok(+ !html.includes('</script><script>window.__reviewPwned=1;</script>'),+ 'rendered HTML leaks a literal </script> from REVIEW_DATA'+ );+ assert.doesNotMatch(html, /data-recommended-label="[^"]*onmouseover=/);assert.match(html, /"text":"Summary with \\u003c\/script\\u003e\\u003cscript\\u003ewindow\.__summaryPwned=1;\\u003c\/script\\u003e/);assert.match(html, /\\u003c\/script\\u003e/);});+test('render-createsite-plan rejects missing localized labels', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const incomplete = {+ ...SAMPLE_DATA,+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ footer: {},+ },+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(incomplete)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /PLAN_LABELS is missing localized values/);+ assert.match(result.stderr, /footer\.aiWarning/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('render-createsite-plan rejects the legacy flat review checklist', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const legacy = {+ ...SAMPLE_DATA,+ REVIEW_DATA: ['All pages load without console errors'],+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(legacy)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /REVIEW_DATA must be an object with agentChecks and makerReview arrays/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('render-createsite-plan requires both review responsibility groups', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const missingMakerReview = {+ ...SAMPLE_DATA,+ REVIEW_DATA: {+ agentChecks: ['Automated checks pass'],+ makerReview: [],+ },+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(missingMakerReview)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /requires non-empty string arrays: makerReview/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('render-createsite-plan rejects locale and direction mismatches', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const mismatched = { ...SAMPLE_DATA, SITE_LOCALE: 'ar-SA', SITE_DIRECTION: 'ltr' };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(mismatched)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /does not match ar-SA/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('render-createsite-plan rejects non-canonical locale tags', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const nonCanonical = { ...SAMPLE_DATA, SITE_LOCALE: 'EN-us' };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(nonCanonical)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /Use "en-US" instead/);+ assert.equal(fs.existsSync(outputPath), false);+});++test('render-createsite-plan rejects translated labels that drop renderer tokens', () => {+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));+ const outputPath = path.join(tempDir, 'plan.html');+ const missingToken = {+ ...SAMPLE_DATA,+ PLAN_LABELS: {+ ...ENGLISH_LABELS,+ overview: {+ ...ENGLISH_LABELS.overview,+ description: 'Implementation plan',+ },+ },+ };++ const result = spawnSync(+ process.execPath,+ [scriptPath, '--output', outputPath, '--data-inline', JSON.stringify(missingToken)],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 1);+ assert.match(result.stderr, /must preserve renderer tokens/);+ assert.match(result.stderr, /overview\.description \(\{siteName\}\)/);+ assert.equal(fs.existsSync(outputPath), false);+});+test('render-createsite-plan refuses to overwrite existing file', () => {const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'createsite-plan-'));const dataPath = path.join(tempDir, 'data.json');diff --git a/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js b/plugins/power-pages/scripts/tests/render-generated-plan-security.test.jsindex 0187555ab..f659c9502 100644--- a/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js+++ b/plugins/power-pages/scripts/tests/render-generated-plan-security.test.js@@ -17,6 +17,102 @@ const ICON_RATIONALE_DATA = [{ icon: '⚙<img src=x>', title: 'Mixed input', desc: 'Must remain escaped text.' },{ icon: '&#xZZ;', title: 'Malformed entity', desc: 'Must remain escaped text.' },];+const CREATE_SITE_PLAN_LABELS = {+ navigation: {+ group: 'Plan',+ overview: 'Overview',+ design: 'Design',+ pages: 'Pages and components',+ deployment: 'Deployment and review',+ },+ overview: {+ title: 'Overview',+ description: 'Implementation plan for {siteName}',+ stats: { pages: 'Pages', components: 'Components', routes: 'Routes' },+ nextSteps: {+ title: 'Next steps',+ design: { title: 'Apply design', description: 'Apply the approved design.' },+ components: {+ title: 'Build components',+ descriptionOne: 'Build {count} component.',+ descriptionOther: 'Build {count} components.',+ },+ pages: {+ title: 'Create pages',+ descriptionOne: 'Create {count} page.',+ descriptionOther: 'Create {count} pages.',+ },+ critique: {+ title: 'Critique the design',+ description: 'Review desktop and mobile screenshots.',+ },+ verify: { title: 'Verify', description: 'Run verification before handoff.' },+ },+ },+ design: {+ title: 'Design',+ description: 'Approved design system',+ direction: {+ title: 'Design direction',+ heroConcept: 'Hero concept',+ signatureMoment: 'Signature moment',+ primaryAction: 'Primary action',+ secondaryAction: 'Secondary action',+ principalDoubt: 'Principal doubt',+ proofStrategy: 'Proof strategy',+ brandSource: 'Brand source',+ audience: 'Audience and job',+ },+ typography: 'Typography',+ palette: 'Palette',+ motion: 'Motion',+ backgrounds: 'Backgrounds',+ primaryRole: 'Primary',+ secondaryRole: 'Secondary',+ },+ pages: {+ title: 'Pages and components',+ description: 'Planned pages and reusable components',+ pages: 'Pages',+ components: 'Components',+ routing: 'Routing',+ path: 'Path',+ page: 'Page',+ content: 'Content',+ componentsUsed: 'Components used',+ usedBy: 'Used by',+ noComponents: 'No components specified.',+ },+ bidirectional: {+ title: 'Bidirectional review',+ description: 'Direction-aware review coverage',+ classification: 'Classification',+ reason: 'Reason',+ states: 'States',+ viewports: 'Viewports',+ checks: 'Checks',+ classifications: {+ directionNeutral: 'Direction-neutral',+ directionAware: 'Direction-aware',+ directionFixed: 'Direction-fixed',+ unknownThirdParty: 'Unknown or third-party',+ },+ viewport: { desktop: 'Desktop', narrow: 'Narrow' },+ },+ deployment: {+ title: 'Deployment and review',+ description: 'Verification and deployment options',+ verify: 'Verify before handoff',+ agentChecks: 'Agent checks',+ agentChecksDescription: 'Automated checks performed before handoff.',+ makerReview: 'Maker review',+ makerReviewDescription: 'Judgment-based checks for the maker.',+ options: 'Options',+ recommended: 'Recommended',+ },+ common: { noneSpecified: 'None specified.' },+ footer: { aiWarning: 'AI-generated content may be incorrect.' },+};const DATA_MODEL_DATA = {SITE_NAME: 'Contoso Portal',@@ -118,7 +214,23 @@ class FakeElement {}addEventListener() {}- appendChild() {}+ append(...nodes) {+ for (const node of nodes) {+ if (node instanceof FakeElement) {+ this._textContent += node.textContent;+ this._innerHTML += node.innerHTML;+ } else {+ const textNode = new FakeElement();+ textNode.textContent = node;+ this._textContent += textNode.textContent;+ this._innerHTML += textNode.innerHTML;+ }+ }+ }+ appendChild(node) {+ this.append(node);+ return node;+ }querySelector() { return null; }querySelectorAll() { return []; }setAttribute() {}@@ -161,6 +273,11 @@ function executeInlineRenderer(html, { skipMermaid = false, svg = null } = {}) {querySelectorAll() { return []; },addEventListener() {},createElement() { return new FakeElement(); },+ createTextNode(value) {+ const node = new FakeElement();+ node.textContent = value;+ return node;+ },importNode(node) { return node; },};@@ -462,6 +579,7 @@ test('backend and create-site plans allowlist dynamic attributes and escape nestAESTHETIC: attack,MOOD: attack,SUMMARY: attack,+ PLAN_LABELS: CREATE_SITE_PLAN_LABELS,DESIGN_DIRECTION_DATA: {thesis: attack,brandSource: attack,@@ -483,7 +601,18 @@ test('backend and create-site plans allowlist dynamic attributes and escape nestPAGES_DATA: [{ name: attack, route: attack, description: attack, content: [attack], components: [attack] }],COMPONENTS_DATA: [{ name: attack, purpose: attack, usedBy: [attack] }],ROUTES_DATA: [{ path: attack, page: attack }],- REVIEW_DATA: [attack],+ BIDIRECTIONAL_REVIEW_DATA: [{+ component: attack,+ classification: 'direction-aware',+ reason: attack,+ states: [attack],+ viewports: ['desktop'],+ checks: [attack],+ }],+ REVIEW_DATA: {+ agentChecks: [attack],+ makerReview: [attack],+ },DEPLOYMENT_DATA: [{ title: attack, description: attack, recommended: true }],});const createSiteElements = executeInlineRenderer(createSiteHtml);@@ -497,7 +626,9 @@ test('backend and create-site plans allowlist dynamic attributes and escape nest'pagesContainer','componentsContainer','routesBody',- 'reviewContainer',+ 'bidirectionalReviewContainer',+ 'agentChecksContainer',+ 'makerReviewContainer','deploymentContainer',].map(id => createSiteElements.get(id).innerHTML).join('');assert.doesNotMatch(createSiteRendered, /<img\b|<script\b|onclick=/i);diff --git a/plugins/power-pages/scripts/tests/rendered-bidirectional-readiness.test.js b/plugins/power-pages/scripts/tests/rendered-bidirectional-readiness.test.jsnew file mode 100644index 000000000..6aa1ac99e--- /dev/null+++ b/plugins/power-pages/scripts/tests/rendered-bidirectional-readiness.test.js@@ -0,0 +1,2086 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { spawnSync } = require('node:child_process');+const {+ buildLocaleSmokeCases,+ buildVerificationGroups,+ buildVerificationCases,+ getRequiredLoopbackOrigin,+ resolveSameOriginNavigationUrl,+ runRenderedBidirectionalAudit,+ runWithConcurrency,+ summarizeFindings,+ validateRunSpec,+} = require('../lib/rendered-bidirectional-readiness');+const {+ TRANSACTION_AUDIT_FILE,+ beginLocalizationVerificationAudit,+ beginLocalizationVerification,+ endLocalizationVerificationAudit,+ readLocalizationVerificationTransaction,+} = require('../lib/localization-verification-transaction');+const {+ createVerificationEvidence,+} = require('../lib/verification-evidence');+const { createTempProject, writeProjectFile } = require('./test-utils');++const cliPath = path.join(__dirname, '..', 'audit-rendered-bidirectional-readiness.js');++function validSpec() {+ return {+ version: 1,+ runtimeSwitching: false,+ viewports: [+ { name: 'desktop', width: 1280, height: 720 },+ { name: 'narrow', width: 390, height: 844 },+ ],+ locales: [+ {+ id: 'en',+ locale: 'en-US',+ direction: 'ltr',+ activate: [{ type: 'use-current' }],+ expect: [{ selector: 'h1', text: 'Home' }],+ },+ {+ id: 'pseudo-rtl',+ locale: 'ar-XB',+ direction: 'rtl',+ pseudo: true,+ activate: [{ type: 'set-document', locale: 'ar-XB', direction: 'rtl' }],+ },+ ],+ components: [{+ id: 'search-form',+ name: 'Search form',+ classification: 'direction-aware',+ route: '/',+ selector: '[data-bidi-id="search-form"]',+ viewports: ['desktop', 'narrow'],+ states: [{+ name: 'empty',+ targets: [{+ selector: '[data-bidi-id="search-form"]',+ expectedDirection: 'inherit',+ }],+ }],+ }],+ };+}++function pendingRuntimeSpec() {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[0].activate = [{+ type: 'click',+ selector: '[data-locale="en-US"]',+ }];+ spec.locales[1] = {+ id: 'ar',+ locale: 'ar-SA',+ direction: 'rtl',+ activate: [{+ type: 'activate-locale',+ method: 'click',+ locale: 'ar-SA',+ selector: '[data-locale="ar-SA"]',+ }],+ expect: [{ selector: 'h1', text: 'مرحبا' }],+ };+ spec.transitions = [+ { name: 'en-ar-en', route: '/', sequence: ['en', 'ar', 'en'] },+ { name: 'ar-en-ar', route: '/', sequence: ['ar', 'en', 'ar'] },+ ];+ return spec;+}++function pendingRuntimeManifest(options = {}) {+ return {+ schemaVersion: 1,+ framework: 'react',+ mode: 'runtime',+ packageName: 'react-i18next',+ packageVersion: '^16.0.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact: {+ version: '16.0.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl:+ 'https://registry.npmjs.org/react-i18next/-/react-i18next-16.0.0.tgz',+ integrity: 'sha512-dGVzdA==',+ },+ },+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/i18n/locales/en-US.json',+ 'ar-SA': 'src/i18n/locales/ar-SA.json',+ },+ generatedFiles: [],+ managedFiles: [+ 'src/i18n/localeCoordinator.ts',+ 'src/i18n/localeAvailability.ts',+ ],+ unavailableLocales: options.exposed ? [] : ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'localized-font-failure',+ severity: 'error',+ message: 'Arabic font rendering failed.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'add',+ updatedAt: '2026-09-03T00:00:00.000Z',+ };+}++function beginPendingVerification(projectRoot) {+ const availabilityPath = writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ "const unavailableLocales = new Set(['ar-SA']);\n" ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n'+ );+ const manifestPath = writeProjectFile(+ projectRoot,+ '.powerpages-localization.json',+ JSON.stringify(pendingRuntimeManifest())+ );+ const transaction = beginLocalizationVerification(projectRoot, ['ar-SA']);+ fs.writeFileSync(+ manifestPath,+ JSON.stringify(pendingRuntimeManifest({ exposed: true }))+ );+ fs.writeFileSync(+ availabilityPath,+ "const unavailableLocales = new Set([]);\n" ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n',+ 'utf8'+ );+ return transaction;+}++test('validates a complete LTR and RTL rendered verification specification', () => {+ assert.deepEqual(validateRunSpec(validSpec()), []);+});++test('requires HTTP(S) loopback origins and exact-origin navigation', () => {+ assert.equal(+ getRequiredLoopbackOrigin('http://localhost:4173/site'),+ 'http://localhost:4173'+ );+ assert.equal(+ getRequiredLoopbackOrigin('https://[::1]:4173'),+ 'https://[::1]:4173'+ );+ assert.throws(+ () => getRequiredLoopbackOrigin('https://preview.example.test'),+ /must use a loopback development URL/i+ );+ assert.throws(+ () => getRequiredLoopbackOrigin('file://localhost/site/index.html'),+ /must use a loopback development URL/i+ );+ assert.equal(+ resolveSameOriginNavigationUrl(+ '/contact',+ 'http://localhost:4173',+ 'http://localhost:4173'+ ),+ 'http://localhost:4173/contact'+ );+ assert.throws(+ () => resolveSameOriginNavigationUrl(+ 'http://localhost:5173/contact',+ 'http://localhost:4173',+ 'http://localhost:4173'+ ),+ /must remain on the required loopback origin/i+ );+});++test('requires complete component, viewport, direction, and runtime round-trip coverage', () => {+ const spec = validSpec();+ spec.locales.pop();+ spec.components[0].viewports.push('tablet');+ spec.components.push({+ id: 'vendor-calendar',+ name: 'Vendor calendar',+ classification: 'unknown-third-party',+ route: '/calendar',+ selector: '.calendar',+ viewports: ['desktop'],+ states: [{ name: 'open' }],+ });+ spec.runtimeSwitching = true;++ const errors = validateRunSpec(spec);++ assert.ok(errors.some((error) => /LTR and RTL/.test(error)));+ assert.ok(errors.some((error) => /unknown viewport "tablet"/.test(error)));+ assert.ok(errors.some((error) => /third-party targets/.test(error)));+ assert.ok(errors.some((error) => /valid defaultLocaleId/.test(error)));+});++test('rejects malformed nested checks instead of silently weakening coverage', () => {+ const spec = validSpec();+ const state = spec.components[0].states[0];+ spec.locales[1].activate.push({ type: 'execute-script' });+ state.setup = [{ type: 'execute-script' }];+ state.targets = [{+ selector: '.target',+ expectedDirection: 'inherit',+ allowClipping: 'false',+ externalOpaque: 'false',+ }];+ state.focusOrder = 42;+ state.computed = [{+ selector: '.target',+ property: 'text-align',+ expected: { rtl: 42 },+ }];+ state.attributes = [{+ selector: '.target',+ name: '',+ expected: 42,+ }];+ spec.components[0].manualChecks = 'mirror the icon';+ spec.transitions = [{+ name: 'invalid',+ route: '/',+ sequence: ['en', 'pseudo-rtl'],+ viewport: 'tablet',+ preserve: '#field',+ preserveFocus: '',+ preserveRoute: 'true',+ setup: [{ type: 'execute-script' }],+ }];++ const errors = validateRunSpec(spec);++ assert.ok(errors.some((error) => /allowClipping must be boolean/.test(error)));+ assert.ok(errors.some((error) => /externalOpaque must be boolean/.test(error)));+ assert.ok(errors.some((error) => /focusOrder must be an array/.test(error)));+ assert.ok(errors.some((error) => /expected\.rtl must be a string/.test(error)));+ assert.ok(errors.some((error) => /attributes\[0\]\.name is required/.test(error)));+ assert.ok(errors.some((error) => /attributes\[0\]\.expected must be a string/.test(error)));+ assert.ok(errors.some((error) => /manualChecks must be an array/.test(error)));+ assert.ok(errors.some((error) => /unknown viewport "tablet"/.test(error)));+ assert.ok(errors.some((error) => /preserve must be an array/.test(error)));+ assert.ok(errors.some((error) => /preserveFocus must be a non-empty/.test(error)));+ assert.ok(errors.some((error) => /preserveRoute must be boolean/.test(error)));+ assert.equal(+ errors.filter((error) => /\.type is invalid/.test(error)).length,+ 3+ );+});++test('requires state names to be unique within each component', () => {+ const spec = validSpec();+ spec.components[0].states.push({+ ...spec.components[0].states[0],+ });+ spec.components.push({+ ...spec.components[0],+ id: 'secondary-search-form',+ selector: '[data-bidi-id="secondary-search-form"]',+ states: [{+ ...spec.components[0].states[0],+ }],+ });++ const errors = validateRunSpec(spec);+ const duplicateStateErrors = errors.filter((error) =>+ /duplicates state name "empty"/.test(error)+ );++ assert.deepEqual(duplicateStateErrors, [+ 'components[0].states[1].name duplicates state name "empty" ' ++ 'within components[0].states.',+ ]);+});++test('validates explicit application-state preservation entries', () => {+ const spec = validSpec();+ spec.transitions = [{+ name: 'state',+ route: '/',+ sequence: ['en', 'pseudo-rtl'],+ preserve: [+ { selector: '#panel', kind: 'attribute' },+ { selector: '#counter', kind: 'unsupported' },+ ],+ }];++ const errors = validateRunSpec(spec);++ assert.ok(errors.some((error) => /name is required for attribute/.test(error)));+ assert.ok(errors.some((error) => /kind must be auto, value, checked/.test(error)));+});++test('requires runtime round trips for every real non-default locale', () => {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[1] = {+ id: 'ar',+ locale: 'ar-SA',+ direction: 'rtl',+ activate: [{ type: 'click', selector: '[data-locale="ar-SA"]' }],+ expect: [{ selector: 'h1', text: 'مرحبا' }],+ };+ spec.locales.push({+ id: 'fr',+ locale: 'fr-FR',+ direction: 'ltr',+ activate: [{ type: 'click', selector: '[data-locale="fr-FR"]' }],+ expect: [{ selector: 'h1', text: 'Accueil' }],+ });+ spec.transitions = [+ { name: 'en-ar-en', route: '/', sequence: ['en', 'ar', 'en'] },+ { name: 'ar-en-ar', route: '/', sequence: ['ar', 'en', 'ar'] },+ ];++ const errors = validateRunSpec(spec);++ assert.ok(errors.some((error) => /en -> fr -> en/.test(error)));+ assert.ok(errors.some((error) => /fr -> en -> fr/.test(error)));+ assert.ok(!errors.some((error) => /en -> ar -> en/.test(error)));+});++test('reconciles runtime verification locales with the localization manifest', () => {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[0].activate = [{+ type: 'click',+ selector: '[data-locale="en-US"]',+ }];+ spec.locales[1] = {+ id: 'ar',+ locale: 'ar-SA',+ direction: 'rtl',+ activate: [{ type: 'click', selector: '[data-locale="ar-SA"]' }],+ expect: [{ selector: 'h1', text: 'مرحبا' }],+ };+ spec.transitions = [+ { name: 'en-ar-en', route: '/', sequence: ['en', 'ar', 'en'] },+ { name: 'ar-en-ar', route: '/', sequence: ['ar', 'en', 'ar'] },+ ];++ const missingLocaleErrors = validateRunSpec(spec, {+ locales: ['en-US', 'he-IL', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ });+ assert.ok(missingLocaleErrors.some((error) =>+ /real locales must exactly match/i.test(error)+ ));++ const wrongDefaultErrors = validateRunSpec(spec, {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'ar-SA',+ mode: 'runtime',+ });+ assert.ok(wrongDefaultErrors.some((error) =>+ /defaultLocaleId must match/i.test(error)+ ));++ spec.locales[1].direction = 'ltr';+ const directionErrors = validateRunSpec(spec, {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ });+ assert.ok(directionErrors.some((error) =>+ /direction must be rtl for ar-SA/i.test(error)+ ));++ spec.locales[1].direction = 'rtl';+ const unavailableErrors = validateRunSpec(spec, {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: ['ar-SA'],+ });+ assert.ok(unavailableErrors.some((error) =>+ /currently available localization manifest locales/i.test(error)+ ));+ assert.ok(unavailableErrors.some((error) =>+ /unavailableLocaleChecks must exactly match/i.test(error)+ ));++ const unavailableSpec = validSpec();+ unavailableSpec.runtimeSwitching = true;+ unavailableSpec.defaultLocaleId = 'en';+ unavailableSpec.locales[0].activate = [{+ type: 'click',+ selector: '[data-locale="en-US"]',+ }];+ unavailableSpec.unavailableLocaleChecks = [{+ locale: 'ar-SA',+ selectors: ['[data-locale="ar-SA"]'],+ }];+ assert.deepEqual(validateRunSpec(unavailableSpec, {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: ['ar-SA'],+ }), []);+});++test('requires transaction targets to use one locale-bound application control', () => {+ const spec = pendingRuntimeSpec();+ spec.locales[1].activate = [+ {+ type: 'set-attribute',+ selector: 'html',+ name: 'lang',+ value: 'ar-SA',+ },+ ];++ const errors = validateRunSpec(spec, {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: [],+ verificationLocales: ['ar-SA'],+ });++ assert.ok(errors.some((error) => /exactly one activate-locale action/i.test(error)));+ assert.ok(errors.some((error) => /only activate-locale and wait actions/i.test(error)));+});++test('rejects direct attribute mutation for real locale activation', () => {+ const spec = validSpec();+ spec.locales[0].activate = [+ { type: 'click', selector: '[data-locale="en-US"]' },+ {+ type: 'set-attribute',+ selector: 'html',+ name: 'lang',+ value: 'en-US',+ },+ ];+ spec.locales[1].activate.push({+ type: 'set-attribute',+ selector: 'html',+ name: 'data-pseudo',+ value: 'rtl',+ });++ const errors = validateRunSpec(spec);++ assert.deepEqual(+ errors.filter((error) => /cannot use set-attribute/.test(error)),+ [+ 'locales[0] real locales cannot use set-attribute to synthesize ' ++ 'locale evidence.',+ ]+ );+});++test('does not allow a runtime manifest to disable runtime transition checks', () => {+ const errors = validateRunSpec(validSpec(), {+ locales: ['en-US'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: [],+ });++ assert.ok(errors.some((error) =>+ /runtime localization manifests require runtimeSwitching: true/i.test(error)+ ));+});++test('expands every applicable state, viewport, and locale into a separate case', () => {+ const spec = validSpec();+ spec.components[0].states.push({ name: 'focused' });++ const cases = buildVerificationCases(spec);++ assert.equal(cases.length, 8);+ assert.deepEqual(+ new Set(cases.map((item) => item.state.name)),+ new Set(['empty', 'focused'])+ );+});++test('validates bounded concurrency and explicit resettable state isolation', () => {+ const spec = validSpec();+ spec.maxConcurrency = 9;+ spec.components[0].states[0].isolation = 'resettable';+ spec.components[0].states[0].reset = [{+ type: 'navigate',+ url: '/',+ }];++ const errors = validateRunSpec(spec);++ assert.ok(errors.some((error) => /maxConcurrency must be an integer/.test(error)));+ assert.ok(errors.some((error) => /cannot navigate or change the active locale/.test(error)));+});++test('groups compatible cases by route, viewport, and locale', () => {+ const spec = validSpec();+ spec.components[0].states.push({+ name: 'focused',+ isolation: 'isolated',+ });+ const groups = buildVerificationGroups(buildVerificationCases(spec));++ assert.equal(groups.length, 8);+ assert.deepEqual(+ groups.map((group) => group.cases.length).sort(),+ [1, 1, 1, 1, 1, 1, 1, 1]+ );++ spec.components[0].states[1].isolation = 'reload';+ const reusableGroups = buildVerificationGroups(buildVerificationCases(spec));+ assert.equal(reusableGroups.length, 4);+ assert.deepEqual(+ reusableGroups.map((group) => group.cases.length).sort(),+ [2, 2, 2, 2]+ );+});++test('bounded worker pool preserves task order and concurrency limit', async () => {+ let active = 0;+ let maximumActive = 0;+ const results = await runWithConcurrency(+ [30, 5, 20, 10],+ 2,+ async (delay, index) => {+ active += 1;+ maximumActive = Math.max(maximumActive, active);+ await new Promise((resolve) => setTimeout(resolve, delay));+ active -= 1;+ return index;+ }+ );++ assert.deepEqual(results, [0, 1, 2, 3]);+ assert.equal(maximumActive, 2);+});++test('resettable states reuse one navigation per route, viewport, and locale', async () => {+ const spec = validSpec();+ spec.maxConcurrency = 1;+ spec.locales[1] = {+ id: 'ar',+ locale: 'ar-SA',+ direction: 'rtl',+ activate: [{ type: 'click', selector: '[data-locale="ar-SA"]' }],+ expect: [{ selector: 'h1', text: 'مرحبا' }],+ };+ spec.locales[0].activate = [{+ type: 'click',+ selector: '[data-locale="en-US"]',+ }];+ spec.components[0].states = [+ {+ name: 'empty',+ isolation: 'resettable',+ setup: [{ type: 'fill', selector: '#field', value: '' }],+ reset: [{ type: 'fill', selector: '#field', value: '' }],+ },+ {+ name: 'filled',+ isolation: 'resettable',+ setup: [{ type: 'fill', selector: '#field', value: 'Ada' }],+ reset: [{ type: 'fill', selector: '#field', value: '' }],+ },+ ];+ spec.components[0].viewports = ['desktop'];+ spec.components[0].manualChecks = [+ 'Confirm that the resettable search states remain understandable.',+ ];++ let newPageCount = 0;+ let navigationCount = 0;+ class Locator {+ constructor(page, selector) {+ this.page = page;+ this.selector = selector;+ }+ first() { return this; }+ async count() { return 1; }+ async click() {+ const arabic = this.selector.includes('ar-SA');+ this.page.locale = arabic ? 'ar-SA' : 'en-US';+ this.page.direction = arabic ? 'rtl' : 'ltr';+ }+ async fill() {}+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate() {+ return {+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40,+ },+ };+ }+ }+ class Page {+ constructor() {+ this.locale = 'en-US';+ this.direction = 'ltr';+ }+ on() {}+ async goto() { navigationCount += 1; }+ url() { return 'http://localhost:4173/'; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ }+ async close() {}+ }+ const browser = {+ async newPage() {+ newPageCount += 1;+ return new Page();+ },+ async close() {},+ };+ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ chromium: { launch: async () => browser },+ });++ assert.equal(report.summary.errors, 0);+ assert.equal(report.verification.componentCaseCount, 4);+ assert.equal(report.verification.componentGroupCount, 2);+ assert.equal(report.verification.reviewFindings.length, 4);+ assert.ok(report.verification.reviewFindings.every((finding) =>+ finding.rule === 'rendered-semantic-review' &&+ finding.severity === 'review'+ ));+ assert.equal(newPageCount, 2);+ assert.equal(navigationCount, 2);+});++test('standard profile uses representative directions and locale smoke coverage', () => {+ const spec = validSpec();+ spec.verificationProfile = 'standard';+ spec.locales.splice(1, 0, {+ id: 'es',+ locale: 'es-ES',+ direction: 'ltr',+ textExpansion: 1.5,+ activate: [{ type: 'click', selector: '[data-locale="es-ES"]' }],+ expect: [{ selector: 'h1', text: 'Inicio' }],+ });+ spec.locales.splice(2, 0, {+ id: 'ar',+ locale: 'ar-SA',+ direction: 'rtl',+ activate: [{ type: 'click', selector: '[data-locale="ar-SA"]' }],+ expect: [{ selector: 'h1', text: 'الرئيسية' }],+ });+ spec.components[0].classification = 'unknown-third-party';+ spec.components[0].states[0].targets = [{+ selector: '[data-bidi-id="search-form"]',+ expectedDirection: 'inherit',+ }];++ const context = {+ verificationLocales: ['es-ES'],+ defaultLocale: 'en-US',+ };+ const cases = buildVerificationCases(spec, context);+ const smokeCases = buildLocaleSmokeCases(spec);++ assert.deepEqual(+ new Set(cases.map((item) => item.locale.id)),+ new Set(['es', 'ar'])+ );+ assert.deepEqual(+ smokeCases.map((item) => item.locale.id),+ ['en', 'es', 'ar']+ );+});++test('standard runtime switching requires reverse round trips only for representatives', () => {+ const spec = pendingRuntimeSpec();+ spec.verificationProfile = 'standard';+ spec.locales.push({+ id: 'fr',+ locale: 'fr-FR',+ direction: 'ltr',+ activate: [{ type: 'click', selector: '[data-locale="fr-FR"]' }],+ expect: [{ selector: 'h1', text: 'Accueil' }],+ });+ spec.transitions.push({+ name: 'en-fr-en',+ route: '/',+ sequence: ['en', 'fr', 'en'],+ });++ assert.deepEqual(validateRunSpec(spec), []);+});++test('targeted profile can rerun a non-representative locale case', () => {+ const spec = validSpec();+ spec.locales.splice(1, 0, {+ id: 'es',+ locale: 'es-ES',+ direction: 'ltr',+ activate: [{ type: 'click', selector: '[data-locale="es-ES"]' }],+ expect: [{ selector: 'h1', text: 'Inicio' }],+ });+ spec.verificationProfile = 'targeted';+ spec.targetCaseIds = ['search-form--empty--desktop--en'];++ assert.deepEqual(validateRunSpec(spec), []);+ assert.deepEqual(+ buildVerificationCases(spec).map((verificationCase) => verificationCase.id),+ ['search-form--empty--desktop--en']+ );+});++test('summarizes failed, review, and passed rendered cases', () => {+ const findings = [+ { severity: 'error' },+ { severity: 'review' },+ ];+ const results = [+ { status: 'failed' },+ { status: 'review' },+ { status: 'passed' },+ ];++ assert.deepEqual(summarizeFindings(findings, results), {+ cases: 3,+ passed: 1,+ review: 1,+ failed: 1,+ errors: 1,+ reviewFindings: 1,+ });+});++test('CLI runs the complete case matrix and emits JSON through a project Playwright install', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(+ projectRoot,+ 'node_modules/playwright/index.js',+ `+ class Locator {+ constructor(page, selector) { this.page = page; this.selector = selector; }+ first() { return this; }+ async count() { return 1; }+ async click() {+ if (this.selector.includes('ar-SA')) {+ this.page.locale = 'ar-SA';+ this.page.direction = 'rtl';+ }+ }+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate() {+ return {+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: { left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 }+ };+ }+ }+ class Page {+ constructor() { this.locale = 'en-US'; this.direction = 'ltr'; }+ on() {}+ async goto() {}+ url() { return 'http://localhost:4173/'; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('document.documentElement.lang =')) {+ this.locale = arg.locale;+ this.direction = arg.direction;+ return;+ }+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ }+ async close() {}+ }+ class Browser {+ async newPage() { return new Page(); }+ async close() {}+ }+ module.exports = { chromium: { launch: async () => new Browser() } };+ `+ );+ const spec = validSpec();+ spec.locales[1].pseudo = false;+ spec.locales[1].locale = 'ar-SA';+ spec.locales[1].activate = [{ type: 'click', selector: '[data-locale="ar-SA"]' }];+ spec.locales[1].expect = [{ selector: 'h1', text: 'مرحبا' }];+ const outputPath = path.join(projectRoot, 'docs', 'bidi', 'report.json');+ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(spec),+ '--output', outputPath,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, `${result.stderr}\n${result.stdout}`);+ const report = JSON.parse(result.stdout);+ assert.equal(report.summary.cases, 4);+ assert.equal(report.summary.failed, 0);+ assert.equal(report.summary.errors, 0);+ assert.deepEqual(JSON.parse(fs.readFileSync(outputPath, 'utf8')), report);+});++test('CLI exits 2 for an invalid run specification', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(+ projectRoot,+ 'node_modules/playwright/index.js',+ 'module.exports = { chromium: { launch: async () => ({ close: async () => {} }) } };'+ );+ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', '{}',+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /Invalid rendered bidirectional run specification/);+});++test('CLI reuses a successful report while verification inputs are unchanged', (t) => {+ const projectRoot = createTempProject(t);+ const spec = validSpec();+ writeProjectFile(projectRoot, 'package.json', '{}');+ writeProjectFile(projectRoot, 'src/App.tsx', 'export const App = null;');+ const reportPath = writeProjectFile(+ projectRoot,+ 'docs/bidirectional-evidence/run/report.json',+ JSON.stringify({+ summary: {+ cases: 2,+ passed: 2,+ review: 0,+ failed: 0,+ errors: 0,+ reviewFindings: 0,+ },+ verification: {+ profile: 'standard',+ evidence: createVerificationEvidence(projectRoot, spec),+ },+ findings: [],+ results: [+ {+ id: 'locale-smoke--en',+ type: 'locale-smoke',+ status: 'passed',+ findings: [],+ },+ {+ id: 'header--default--desktop--en',+ type: 'component-state',+ status: 'passed',+ findings: [],+ },+ ],+ })+ );++ const reused = spawnSync(+ process.execPath,+ [+ cliPath,+ '--projectRoot', projectRoot,+ '--reuse-report', reportPath,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(reused.status, 0, reused.stderr);+ assert.equal(JSON.parse(reused.stdout).verification.reused, true);++ const targetedReport = JSON.parse(fs.readFileSync(reportPath, 'utf8'));+ targetedReport.verification.profile = 'targeted';+ const targetedPath = writeProjectFile(+ projectRoot,+ 'docs/bidirectional-evidence/targeted/report.json',+ JSON.stringify(targetedReport)+ );+ const targeted = spawnSync(+ process.execPath,+ [+ cliPath,+ '--projectRoot', projectRoot,+ '--reuse-report', targetedPath,+ ],+ { encoding: 'utf8' }+ );+ assert.equal(targeted.status, 2);+ assert.match(targeted.stderr, /targeted repair evidence cannot be reused/);++ fs.writeFileSync(path.join(projectRoot, 'src/App.tsx'), 'export const App = 1;');+ const stale = spawnSync(+ process.execPath,+ [+ cliPath,+ '--projectRoot', projectRoot,+ '--reuse-report', reportPath,+ ],+ { encoding: 'utf8' }+ );+ assert.equal(stale.status, 2);+ assert.match(stale.stderr, /evidence is stale/);+});++test('CLI rejects a run specification when reusing a report', (t) => {+ const projectRoot = createTempProject(t);+ const reportPath = writeProjectFile(+ projectRoot,+ 'report.json',+ JSON.stringify({})+ );++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--projectRoot', projectRoot,+ '--reuse-report', reportPath,+ '--spec-inline', '{}',+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /Usage:/);+});++test('CLI argument errors mark an active verification transaction failed', (t) => {+ const projectRoot = createTempProject(t);+ beginPendingVerification(projectRoot);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /Usage:/);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+ const restoredManifest = JSON.parse(+ fs.readFileSync(+ path.join(projectRoot, '.powerpages-localization.json'),+ 'utf8'+ )+ );+ assert.deepEqual(restoredManifest.unavailableLocales, ['ar-SA']);+ assert.match(+ fs.readFileSync(+ path.join(projectRoot, 'src/i18n/localeAvailability.ts'),+ 'utf8'+ ),+ /new Set\(\['ar-SA'\]\)/+ );+});++test('CLI rejects unknown arguments and marks an active transaction failed', (t) => {+ const projectRoot = createTempProject(t);+ beginPendingVerification(projectRoot);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(pendingRuntimeSpec()),+ '--ouptut', path.join(projectRoot, 'report.json'),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /Unknown or misplaced argument "--ouptut"/);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+});++test('CLI requires the localization manifest for runtime switching', (t) => {+ const projectRoot = createTempProject(t);+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(spec),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /is required when runtimeSwitching is enabled/);+});++test('CLI marks an active verification transaction failed when browser startup fails', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(+ projectRoot,+ 'node_modules/playwright/index.js',+ "const error = new Error('synthetic browser load failure');\n" ++ "error.code = 'SYNTHETIC_FAILURE';\n" ++ 'throw error;\n'+ );+ beginPendingVerification(projectRoot);+ const spec = pendingRuntimeSpec();++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(spec),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /synthetic browser load failure/);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+});++test('CLI lease contention preserves the active verification transaction', (t) => {+ const projectRoot = createTempProject(t);+ const transaction = beginPendingVerification(projectRoot);+ beginLocalizationVerificationAudit(projectRoot, transaction.runId);+ const manifestPath = path.join(+ projectRoot,+ '.powerpages-localization.json'+ );+ const availabilityPath = path.join(+ projectRoot,+ 'src/i18n/localeAvailability.ts'+ );+ const leasePath = path.join(projectRoot, TRANSACTION_AUDIT_FILE);+ const outputPath = path.join(projectRoot, 'report.json');+ const manifestBefore = fs.readFileSync(manifestPath, 'utf8');+ const availabilityBefore = fs.readFileSync(availabilityPath, 'utf8');+ const leaseBefore = fs.readFileSync(leasePath, 'utf8');++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(pendingRuntimeSpec()),+ '--output', outputPath,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /already exists.*Recover that audit first/);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'in-progress'+ );+ assert.equal(fs.readFileSync(manifestPath, 'utf8'), manifestBefore);+ assert.equal(fs.readFileSync(availabilityPath, 'utf8'), availabilityBefore);+ assert.equal(fs.readFileSync(leasePath, 'utf8'), leaseBefore);+ assert.equal(fs.existsSync(outputPath), false);+ endLocalizationVerificationAudit(projectRoot, transaction.runId);+ assert.equal(fs.existsSync(leasePath), false);+});++test('CLI refuses non-loopback locale verification URLs', (t) => {+ const projectRoot = createTempProject(t);+ beginPendingVerification(projectRoot);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'https://preview.example.test',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(pendingRuntimeSpec()),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /must use a loopback development URL/i);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+});++test('CLI refuses non-loopback URLs without an active transaction', (t) => {+ const projectRoot = createTempProject(t);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'https://preview.example.test',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(validSpec()),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /must use a loopback development URL/i);+});++test('CLI rejects non-HTTP loopback URLs', (t) => {+ const projectRoot = createTempProject(t);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'file://localhost/site/index.html',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(validSpec()),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.match(result.stderr, /with HTTP or HTTPS/i);+});++test('CLI marks verification failed when report output cannot be written', (t) => {+ const projectRoot = createTempProject(t);+ beginPendingVerification(projectRoot);+ writeProjectFile(+ projectRoot,+ 'node_modules/playwright/index.js',+ `+ class Locator {+ constructor(page, selector) { this.page = page; this.selector = selector; }+ first() { return this; }+ async count() { return 1; }+ async click() {+ const isArabic = this.selector.includes('ar-SA');+ this.page.locale = isArabic ? 'ar-SA' : 'en-US';+ this.page.direction = isArabic ? 'rtl' : 'ltr';+ }+ async textContent() { return this.page.direction === 'rtl' ? 'مرحبا' : 'Home'; }+ async getAttribute() { return null; }+ async evaluate() {+ return {+ exists: true, visible: true, direction: this.page.direction,+ textAlign: 'start', overflowX: 'visible', overflowY: 'visible',+ clipped: false, outsideViewport: false,+ rect: { left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 }+ };+ }+ }+ class Page {+ constructor() { this.locale = 'en-US'; this.direction = 'ltr'; }+ on() {}+ async goto() {}+ url() { return 'http://localhost:4173/'; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }+ module.exports = {+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {}+ })+ }+ };+ `+ );+ const outputDirectory = path.join(projectRoot, 'report-target');+ fs.mkdirSync(outputDirectory);++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(pendingRuntimeSpec()),+ '--output', outputDirectory,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 2);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'remediation-required'+ );+});++test('CLI verifies an in-progress locale through its normal selector', (t) => {+ const projectRoot = createTempProject(t);+ beginPendingVerification(projectRoot);+ writeProjectFile(+ projectRoot,+ 'node_modules/playwright/index.js',+ `+ class Locator {+ constructor(page, selector) { this.page = page; this.selector = selector; }+ first() { return this; }+ nth() { return this; }+ async count() { return 1; }+ async isVisible() { return true; }+ async click() {+ const isArabic = this.selector.includes('ar-SA');+ this.page.locale = isArabic ? 'ar-SA' : 'en-US';+ this.page.direction = isArabic ? 'rtl' : 'ltr';+ }+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate() {+ return {+ exists: true,+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40+ }+ };+ }+ }+ class Page {+ constructor() {+ this.locale = 'en-US';+ this.direction = 'ltr';+ }+ on() {}+ async goto() {}+ url() { return 'http://localhost:4173/'; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }+ class Browser {+ async newPage() { return new Page(); }+ async close() {}+ }+ module.exports = { chromium: { launch: async () => new Browser() } };+ `+ );++ const result = spawnSync(+ process.execPath,+ [+ cliPath,+ '--url', 'http://localhost:4173',+ '--projectRoot', projectRoot,+ '--spec-inline', JSON.stringify(pendingRuntimeSpec()),+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, `${result.stderr}\n${result.stdout}`);+ assert.equal(JSON.parse(result.stdout).summary.errors, 0);+ assert.equal(+ readLocalizationVerificationTransaction(projectRoot).transaction.state,+ 'verified'+ );+});++test('transaction verification fails if a locale control leaves loopback', async () => {+ const spec = pendingRuntimeSpec();+ spec.locales[1].activate.push({ type: 'wait', ms: 50 });++ class Locator {+ constructor(page, selector) {+ this.page = page;+ this.selector = selector;+ }+ first() { return this; }+ async count() { return 1; }+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate() {+ return {+ exists: true,+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40,+ },+ };+ }+ async click() {+ const isArabic = this.selector.includes('ar-SA');+ this.page.locale = isArabic ? 'ar-SA' : 'en-US';+ this.page.direction = isArabic ? 'rtl' : 'ltr';+ if (isArabic) this.page.pendingRedirect = true;+ }+ }+ class Page {+ constructor() {+ this.locale = 'en-US';+ this.direction = 'ltr';+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto() { this.currentUrl = 'http://localhost:4173/'; }+ url() { return this.currentUrl; }+ async waitForTimeout() {+ if (this.pendingRedirect) {+ this.currentUrl = 'https://preview.example.test/ar-SA';+ this.pendingRedirect = false;+ }+ }+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ localizationContext: {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: [],+ verificationLocales: ['ar-SA'],+ },+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'rendered-case-failure' &&+ /left the required loopback origin/.test(finding.message)+ ));+});++test('navigation actions are rejected before visiting another origin', async () => {+ const spec = validSpec();+ spec.components[0].states[0].setup = [{+ type: 'navigate',+ url: 'https://preview.example.test/contact',+ }];+ const visited = [];++ class Page {+ constructor() {+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto(target) {+ visited.push(target);+ this.currentUrl = target;+ }+ url() { return this.currentUrl; }+ async waitForTimeout() {}+ locator() {+ return {+ first() { return this; },+ async count() { return 1; },+ };+ }+ async evaluate(fn, value) {+ const source = String(fn);+ if (source.includes('document.documentElement.lang = locale')) {+ return value;+ }+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: 'en-US', direction: 'ltr' };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'rendered-case-failure' &&+ /must remain on the required loopback origin/.test(finding.message)+ ));+ assert.ok(visited.length > 0);+ assert.ok(visited.every((target) =>+ new URL(target).origin === 'http://localhost:4173'+ ));+});++test('accepts an intentionally absent restricted target', async () => {+ const spec = validSpec();+ spec.components[0].states[0].targets = [{+ selector: '#restricted-vendor-surface',+ expectVisible: false,+ externalOpaque: true,+ }];++ class Locator {+ constructor(page, selector) {+ this.page = page;+ this.selector = selector;+ }+ first() { return this; }+ async count() { return this.selector === '#restricted-vendor-surface' ? 0 : 1; }+ async textContent() { return 'Home'; }+ async getAttribute() { return null; }+ }+ class Page {+ constructor() {+ this.keyboard = { press: async () => {} };+ this.locale = 'en-US';+ this.direction = 'ltr';+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto(target) { this.currentUrl = target; }+ url() { return this.currentUrl; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('document.documentElement.lang =')) {+ this.locale = arg.locale;+ this.direction = arg.direction;+ } else if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ } else if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.equal(report.summary.failed, 0);+ assert.equal(report.summary.errors, 0);+});++test('reports missing direction submission metadata as blocking', async () => {+ const spec = validSpec();+ spec.components[0].states[0].targets = [{+ selector: '#message',+ expectedDirection: 'inherit',+ }];+ spec.components[0].states[0].attributes = [{+ selector: '#message',+ name: 'dirname',+ expected: 'message.dir',+ }];++ class Locator {+ first() { return this; }+ async count() { return 1; }+ async textContent() { return 'Home'; }+ async getAttribute() { return null; }+ async evaluate(fn) {+ if (String(fn).includes('getComputedStyle')) return 'start';+ return {+ exists: true,+ visible: true,+ direction: 'ltr',+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40,+ },+ };+ }+ }+ class Page {+ constructor() {+ this.keyboard = { press: async () => {} };+ this.locale = 'en-US';+ this.direction = 'ltr';+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto(target) { this.currentUrl = target; }+ url() { return this.currentUrl; }+ async waitForTimeout() {}+ locator() { return new Locator(); }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('document.documentElement.lang =')) {+ this.locale = arg.locale;+ this.direction = arg.direction;+ } else if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ } else if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'attribute-mismatch' &&+ /Expected dirname="message.dir"/.test(finding.message)+ ));+ assert.ok(report.summary.errors > 0);+});++test('checks every selector match for locales excluded from rendered activation', async () => {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[0].activate = [{+ type: 'click',+ selector: '[data-locale="en-US"]',+ }];+ spec.unavailableLocaleChecks = [{+ locale: 'ar-SA',+ selectors: ['[data-locale="ar-SA"]'],+ }];++ class Locator {+ constructor(page, selector, index = 0) {+ this.page = page;+ this.selector = selector;+ this.index = index;+ }+ first() { return this.nth(0); }+ nth(index) { return new Locator(this.page, this.selector, index); }+ async count() {+ return this.selector.includes('ar-SA') ? 2 : 1;+ }+ async isVisible() {+ return false;+ }+ async click() { this.page.exposed = true; }+ async textContent() { return 'Home'; }+ async getAttribute() { return null; }+ async evaluate(fn) {+ const source = String(fn);+ if (this.selector.includes('ar-SA') &&+ source.includes('tagName.toLowerCase')) {+ return 'option';+ }+ if (this.selector.includes('ar-SA') &&+ source.includes("closest('select')")) {+ return this.index === 1 && this.page.exposed;+ }+ return {+ exists: true,+ visible: true,+ direction: 'ltr',+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 40,+ width: 100,+ height: 40,+ },+ };+ }+ }+ class Page {+ constructor() {+ this.keyboard = { press: async () => {} };+ this.exposed = false;+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto(target) { this.currentUrl = target; }+ url() { return this.currentUrl; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: 'en-US', direction: 'ltr' };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ localizationContext: {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: ['ar-SA'],+ },+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'unavailable-locale-exposed'+ ));+});++test('runtime transitions fail when preservation selectors do not exist', async () => {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[0].activate = [{ type: 'click', selector: '[data-locale="en-US"]' }];+ spec.locales[1].pseudo = false;+ spec.locales[1].locale = 'ar-SA';+ spec.locales[1].activate = [{ type: 'click', selector: '[data-locale="ar-SA"]' }];+ spec.locales[1].expect = [{ selector: 'h1', text: 'مرحبا' }];+ spec.transitions = [+ {+ name: 'ltr-rtl-ltr',+ route: '/',+ sequence: ['en', 'pseudo-rtl', 'en'],+ preserve: ['#missing'],+ preserveFocus: '#missing',+ },+ {+ name: 'rtl-ltr-rtl',+ route: '/',+ sequence: ['pseudo-rtl', 'en', 'pseudo-rtl'],+ preserve: ['#missing'],+ preserveFocus: '#missing',+ },+ ];++ class Locator {+ constructor(page, selector) {+ this.page = page;+ this.selector = selector;+ }+ first() { return this; }+ async count() { return this.selector === '#missing' ? 0 : 1; }+ async click() {+ if (this.selector.includes('ar-SA')) {+ this.page.locale = 'ar-SA';+ this.page.direction = 'rtl';+ } else if (this.selector.includes('en-US')) {+ this.page.locale = 'en-US';+ this.page.direction = 'ltr';+ }+ }+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate(fn) {+ const source = String(fn);+ if (source.includes('getComputedStyle')) {+ return {+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: { left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 },+ };+ }+ return '';+ }+ }+ class Page {+ constructor() {+ this.locale = 'en-US';+ this.direction = 'ltr';+ this.keyboard = { press: async () => {} };+ this.currentUrl = 'http://localhost:4173/';+ }+ on() {}+ async goto(target) { this.currentUrl = target; }+ url() { return this.currentUrl; }+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('document.documentElement.lang =')) {+ this.locale = arg.locale;+ this.direction = arg.direction;+ return;+ }+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }+ const chromium = {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ };++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ chromium,+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'locale-switch-preservation-target-missing'+ ));+ assert.equal(report.summary.failed, 2);+});++test('runtime transitions capture console errors and explicit application-state loss', async () => {+ const spec = validSpec();+ spec.runtimeSwitching = true;+ spec.defaultLocaleId = 'en';+ spec.locales[0].activate = [{ type: 'click', selector: '[data-locale="en-US"]' }];+ spec.locales[1].pseudo = false;+ spec.locales[1].locale = 'ar-SA';+ spec.locales[1].activate = [{+ type: 'activate-locale',+ method: 'click',+ locale: 'ar-SA',+ selector: '[data-locale="ar-SA"]',+ }];+ spec.locales[1].expect = [{ selector: 'h1', text: 'مرحبا' }];+ spec.transitions = [+ {+ name: 'ltr-rtl-ltr',+ route: '/',+ sequence: ['en', 'pseudo-rtl', 'en'],+ preserve: [+ { selector: '#panel', kind: 'attribute', name: 'aria-expanded' },+ { selector: '#panel', kind: 'checked' },+ ],+ },+ {+ name: 'rtl-ltr-rtl',+ route: '/',+ sequence: ['pseudo-rtl', 'en', 'pseudo-rtl'],+ preserve: [+ { selector: '#panel', kind: 'attribute', name: 'aria-expanded' },+ { selector: '#panel', kind: 'checked' },+ ],+ },+ ];++ class Locator {+ constructor(page, selector) {+ this.page = page;+ this.selector = selector;+ }+ first() { return this.nth(0); }+ nth(index) {+ const locator = new Locator(this.page, this.selector);+ locator.index = index;+ return locator;+ }+ async count() { return 1; }+ async isVisible() { return true; }+ async click() {+ this.page.activate(+ this.selector.includes('ar-SA') ? 'ar-SA' : 'en-US'+ );+ }+ async textContent() {+ return this.page.direction === 'rtl' ? 'مرحبا' : 'Home';+ }+ async getAttribute() { return null; }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('requested.kind')) {+ if (arg.kind === 'checked') {+ return { unsupported: true, kind: arg.kind };+ }+ return {+ unsupported: false,+ kind: arg.kind,+ value: this.page.expanded,+ };+ }+ return {+ exists: true,+ visible: true,+ direction: this.page.direction,+ textAlign: 'start',+ overflowX: 'visible',+ overflowY: 'visible',+ clipped: false,+ outsideViewport: false,+ rect: { left: 0, top: 0, right: 100, bottom: 40, width: 100, height: 40 },+ };+ }+ }+ class Page {+ constructor() {+ this.locale = 'en-US';+ this.direction = 'ltr';+ this.expanded = 'true';+ this.clicks = 0;+ this.handlers = {};+ this.keyboard = { press: async () => {} };+ }+ on(name, handler) { this.handlers[name] = handler; }+ url() { return 'http://localhost:4173/'; }+ activate(locale) {+ this.clicks += 1;+ this.locale = locale;+ this.direction = locale === 'ar-SA' ? 'rtl' : 'ltr';+ if (this.clicks === 2) {+ this.expanded = 'false';+ this.handlers.console?.({+ type: () => 'error',+ text: () => 'locale transition failed internally',+ });+ }+ }+ async goto() {}+ async waitForTimeout() {}+ locator(selector) { return new Locator(this, selector); }+ async evaluate(fn, arg) {+ const source = String(fn);+ if (source.includes('lang: document.documentElement.lang')) {+ return { lang: this.locale, direction: this.direction };+ }+ if (source.includes('horizontalOverflow')) {+ return { horizontalOverflow: false, overflowPixels: 0 };+ }+ if (source.includes('timeOrigin: performance.timeOrigin')) {+ return { route: '/', timeOrigin: 1 };+ }+ }+ async close() {}+ }++ const report = await runRenderedBidirectionalAudit({+ url: 'http://localhost:4173',+ spec,+ localizationContext: {+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ mode: 'runtime',+ unavailableLocales: [],+ verificationLocales: ['ar-SA'],+ },+ chromium: {+ launch: async () => ({+ newPage: async () => new Page(),+ close: async () => {},+ }),+ },+ });++ assert.ok(report.findings.some(+ (finding) => finding.rule === 'browser-console-error' &&+ finding.caseId.startsWith('transition--')+ ));+ assert.ok(report.findings.some(+ (finding) => finding.rule === 'locale-switch-lost-state'+ ));+ assert.ok(report.findings.some(+ (finding) => finding.rule === 'locale-switch-preservation-unsupported'+ ));+ assert.equal(report.summary.failed, 2);+});diff --git a/plugins/power-pages/scripts/tests/site-integrity.test.js b/plugins/power-pages/scripts/tests/site-integrity.test.jsindex bc122b3ba..3542c6f5a 100644--- a/plugins/power-pages/scripts/tests/site-integrity.test.js+++ b/plugins/power-pages/scripts/tests/site-integrity.test.js@@ -5,11 +5,15 @@ const assert = require('node:assert/strict');const path = require('path');const { spawnSync } = require('child_process');const {+ partitionDeferredFindings,validateSiteIntegrity,} = require('../lib/site-integrity');const {parseArgs,} = require('../validate-site-integrity');+const {+ auditBidirectionalReadiness,+} = require('../lib/bidirectional-readiness');const {createTempProject,writeProjectFile,@@ -18,32 +22,6 @@ const {const CLI_PATH = path.join(__dirname, '..', 'validate-site-integrity.js');const LOCALE_COORDINATOR_PATH = 'src/i18n/localeCoordinator.ts';-function verifiedNpmArtifact(packageName, version) {- return {- license: 'MIT',- licenseReview: { status: 'automatically-accepted' },- artifact: {- version,- registry: 'https://registry.npmjs.org/',- tarballUrl: `https://registry.npmjs.org/${packageName}/-/${packageName}-${version}.tgz`,- integrity: 'sha512-dGVzdA==',- },- };-}--function writeVerifiedPackageLock(projectRoot, packageName, version) {- const { artifact } = verifiedNpmArtifact(packageName, version);- writeProjectFile(projectRoot, 'package-lock.json', JSON.stringify({- packages: {- [`node_modules/${packageName}`]: {- version: artifact.version,- resolved: artifact.tarballUrl,- integrity: artifact.integrity,- },- },- }));-}-function writeRuntimeCoordinator(projectRoot) {writeProjectFile(projectRoot, LOCALE_COORDINATOR_PATH, `import i18next from 'i18next';@@ -59,8 +37,38 @@ function writeRuntimeCoordinator(projectRoot) {}test('parses an optional project root without consuming other options', () => {- assert.deepEqual(parseArgs([]), {});+ assert.deepEqual(parseArgs([]), {+ skipLocalization: false,+ allowVerifiedLocalizationReview: false,+ });assert.equal(parseArgs(['--projectRoot', '.']).projectRoot, path.resolve('.'));+ assert.equal(+ parseArgs(['--skip-localization']).skipLocalization,+ true+ );+ assert.throws(+ () => parseArgs(['--skip-localization', '--skip-localization']),+ /may be specified only once/+ );+ assert.equal(+ parseArgs(['--allow-verified-localization-review'])+ .allowVerifiedLocalizationReview,+ true+ );+ assert.throws(+ () => parseArgs([+ '--allow-verified-localization-review',+ '--allow-verified-localization-review',+ ]),+ /may be specified only once/+ );+ assert.throws(+ () => parseArgs([+ '--skip-localization',+ '--allow-verified-localization-review',+ ]),+ /cannot be combined with "--skip-localization"/+ );assert.throws(() => parseArgs(['--projectRoot']),/"--projectRoot" requires a value/@@ -96,6 +104,139 @@ test('CLI reports malformed project-root usage without validating another path',assert.match(result.stderr, /Usage: validate-site-integrity/);});+function runtimeIndex() {+ return "import i18next from 'i18next'; i18next.init({ fallbackLng: 'en-US' });\n" ++ "import { isLocaleAvailable } from './localeAvailability';\n" ++ "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);\n";+}++function verifiedReactPackage(projectRoot) {+ const artifact = {+ version: '16.0.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl:+ 'https://registry.npmjs.org/react-i18next/-/react-i18next-16.0.0.tgz',+ integrity: 'sha512-dGVzdA==',+ };+ writeProjectFile(projectRoot, 'package-lock.json', JSON.stringify({+ packages: {+ 'node_modules/react-i18next': {+ version: artifact.version,+ resolved: artifact.tarballUrl,+ integrity: artifact.integrity,+ },+ },+ }));+ return {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact,+ };+}++test('defers exact recorded static bidi blockers but not unsafe or changed findings', () => {+ const recorded = [+ {+ file: 'src/Form.tsx',+ line: 10,+ rule: 'fixed-direction',+ message: 'fixed direction',+ fingerprint: 'fixed-fingerprint',+ severity: 'error',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ },+ {+ file: 'src/Card.tsx',+ line: 20,+ rule: 'directional-physical-utility',+ message: 'physical utility',+ fingerprint: 'utility-fingerprint',+ severity: 'error',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ },+ ];+ const result = partitionDeferredFindings([+ ...recorded,+ {+ file: 'src/theme.css',+ line: 30,+ rule: 'unicode-bidi-override',+ message: 'unsafe override',+ severity: 'error',+ },+ {+ file: 'src/Card.tsx',+ line: 20,+ rule: 'directional-physical-utility',+ message: 'changed physical utility',+ fingerprint: 'changed-fingerprint',+ severity: 'error',+ },+ ], recorded, ['ar-SA']);++ assert.deepEqual(result.deferred, recorded);+ assert.deepEqual(+ result.blocking.map((finding) => finding.rule),+ ['unicode-bidi-override', 'directional-physical-utility']+ );+ assert.deepEqual(result.unmatchedRecorded, []);+});++test('does not defer a replacement defect with the same legacy message identity', () => {+ const recorded = [{+ file: 'src/Code.tsx',+ line: 10,+ rule: 'fixed-direction',+ message: 'Fixed markup direction: dir="ltr"',+ fingerprint: 'original-element',+ severity: 'error',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }];+ const replacement = [{+ ...recorded[0],+ fingerprint: 'replacement-element',+ }];++ const result = partitionDeferredFindings(replacement, recorded, ['ar-SA']);++ assert.deepEqual(result.deferred, []);+ assert.deepEqual(result.blocking, replacement);+ assert.deepEqual(result.unmatchedRecorded, recorded);+});++test('reports stale recorded review and non-deferrable source findings', () => {+ const recorded = [{+ file: 'src/Carousel.tsx',+ line: 10,+ rule: 'directional-geometry-review',+ message: 'Review physical carousel movement.',+ fingerprint: 'review-fingerprint',+ severity: 'review',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }, {+ file: 'src/Code.tsx',+ line: 20,+ rule: 'unicode-bidi-override',+ message: 'Remove the bidi override control.',+ fingerprint: 'unsafe-fingerprint',+ severity: 'error',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }];++ const result = partitionDeferredFindings([], recorded, ['ar-SA']);++ assert.deepEqual(result.blocking, []);+ assert.deepEqual(result.deferred, []);+ assert.deepEqual(result.unmatchedRecorded, recorded);+});+test('skips declarative Power Pages projects', (t) => {const projectRoot = createTempProject(t);const result = validateSiteIntegrity(projectRoot);@@ -112,7 +253,7 @@ test('blocks deterministic bidirectional regressions without requiring localizatconst result = validateSiteIntegrity(projectRoot);assert.equal(result.skipped, false);- assert.equal(result.errors.length, 1);+ assert.equal(result.errors.length, 1, JSON.stringify(result, null, 2));assert.match(result.errors[0], /directional-physical-css/);});@@ -186,7 +327,7 @@ test('CLI reports malformed unavailableLocales as a validation error', (t) => {assert.doesNotMatch(result.stderr, /not iterable/i);});-test('defers known bidi blockers while opposite-direction locales remain unavailable', (t) => {+test('defers known bidi blockers while affected locales remain unavailable', (t) => {const projectRoot = createTempProject(t);const availabilityPath = 'src/i18n/localeAvailability.ts';writeProjectFile(projectRoot, 'powerpages.config.json', '{}');@@ -198,15 +339,12 @@ test('defers known bidi blockers while opposite-direction locales remain unavail'react-i18next': '^16.0.0',},}));- writeVerifiedPackageLock(projectRoot, 'react-i18next', '16.0.0');writeProjectFile(projectRoot, 'src/i18n/locales/en-US.json', '{"title":"Home"}');writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', '{"title":"الرئيسية"}');writeProjectFile(projectRoot,'src/i18n/index.ts',- "import i18next from 'i18next'; i18next.init({ fallbackLng: 'en-US' });\n" +- "import { isLocaleAvailable } from './localeAvailability';\n" +- "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);"+ runtimeIndex());writeProjectFile(projectRoot, availabilityPath, `const unavailableLocales = new Set(['ar-SA']);@@ -216,23 +354,23 @@ test('defers known bidi blockers while opposite-direction locales remain unavailwriteProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `import { isLocaleAvailable } from '../i18n/localeAvailability';export function LanguageSelector() {- document.documentElement.lang = 'en-US';- document.documentElement.dir = 'ltr';+ const locale = 'en-US';+ document.documentElement.lang = locale;+ document.documentElement.dir = locale === 'ar-SA' ? 'rtl' : 'ltr';return ['en-US', 'ar-SA'].filter(isLocaleAvailable).map((locale) => locale);}`);writeProjectFile(projectRoot, 'src/theme.css', '.card { margin-left: 1rem; }');+ const recordedFinding = auditBidirectionalReadiness(projectRoot).findings.find(+ (finding) => finding.rule === 'directional-physical-css'+ );writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({schemaVersion: 1,framework: 'react',mode: 'runtime',packageName: 'react-i18next',packageVersion: '^16.0.0',- packageVerification: {- status: 'verified',- source: 'known-capability',- ...verifiedNpmArtifact('react-i18next', '16.0.0'),- },+ packageVerification: verifiedReactPackage(projectRoot),locales: ['en-US', 'ar-SA'],defaultLocale: 'en-US',translationMethod: 'agent',@@ -245,12 +383,16 @@ test('defers known bidi blockers while opposite-direction locales remain unavailunavailableLocales: ['ar-SA'],bidirectionalReadiness: {status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },findings: [{- file: 'src/theme.css',- line: 1,- rule: 'directional-physical-css',- message: 'Use a logical CSS property, or add an adjacent validated bidi-physical exception: .card { margin-left: 1rem; }',+ ...recordedFinding,+ scope: 'locale',+ affectedLocales: ['ar-SA'],}],+ renderedFindings: [],},adoptedExistingConfiguration: false,lastOperation: 'extend',@@ -262,7 +404,13 @@ test('defers known bidi blockers while opposite-direction locales remain unavailassert.deepEqual(result.errors, []);assert.ok(result.reviewFindings.some((finding) =>finding.rule === 'directional-physical-css' &&- /Deferred while opposite-direction locales are unavailable/.test(finding.message)+ /Deferred while affected locales are unavailable/.test(finding.message)+ ));++ writeProjectFile(projectRoot, 'src/theme.css', '.card { margin-inline-start: 1rem; }');+ const staleResult = validateSiteIntegrity(projectRoot);+ assert.ok(staleResult.errors.some((error) =>+ /no longer exactly matches the source audit/i.test(error)));});@@ -278,15 +426,12 @@ test('pending remediation still blocks newly introduced bidi defects', (t) => {'react-i18next': '^16.0.0',},}));- writeVerifiedPackageLock(projectRoot, 'react-i18next', '16.0.0');writeProjectFile(projectRoot, 'src/i18n/locales/en-US.json', '{"title":"Home"}');writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', '{"title":"الرئيسية"}');writeProjectFile(projectRoot,'src/i18n/index.ts',- "import i18next from 'i18next'; i18next.init({ fallbackLng: 'en-US' });\n" +- "import { isLocaleAvailable } from './localeAvailability';\n" +- "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);"+ runtimeIndex());writeProjectFile(projectRoot, availabilityPath, `const unavailableLocales = new Set(['ar-SA']);@@ -296,8 +441,9 @@ test('pending remediation still blocks newly introduced bidi defects', (t) => {writeProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `import { isLocaleAvailable } from '../i18n/localeAvailability';export function LanguageSelector() {- document.documentElement.lang = 'en-US';- document.documentElement.dir = 'ltr';+ const locale = 'en-US';+ document.documentElement.lang = locale;+ document.documentElement.dir = locale === 'ar-SA' ? 'rtl' : 'ltr';return ['en-US', 'ar-SA'].filter(isLocaleAvailable).map((locale) => locale);}`);@@ -306,17 +452,18 @@ test('pending remediation still blocks newly introduced bidi defects', (t) => {'src/theme.css','.known { margin-left: 1rem; }\n.new { padding-right: 1rem; }');+ const recordedFinding = auditBidirectionalReadiness(projectRoot).findings.find(+ (finding) =>+ finding.rule === 'directional-physical-css' &&+ finding.line === 1+ );writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({schemaVersion: 1,framework: 'react',mode: 'runtime',packageName: 'react-i18next',packageVersion: '^16.0.0',- packageVerification: {- status: 'verified',- source: 'known-capability',- ...verifiedNpmArtifact('react-i18next', '16.0.0'),- },+ packageVerification: verifiedReactPackage(projectRoot),locales: ['en-US', 'ar-SA'],defaultLocale: 'en-US',translationMethod: 'agent',@@ -329,12 +476,16 @@ test('pending remediation still blocks newly introduced bidi defects', (t) => {unavailableLocales: ['ar-SA'],bidirectionalReadiness: {status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },findings: [{- file: 'src/theme.css',- line: 1,- rule: 'directional-physical-css',- message: 'Use a logical CSS property, or add an adjacent validated bidi-physical exception: .known { margin-left: 1rem; }',+ ...recordedFinding,+ scope: 'locale',+ affectedLocales: ['ar-SA'],}],+ renderedFindings: [],},adoptedExistingConfiguration: false,lastOperation: 'extend',@@ -343,7 +494,7 @@ test('pending remediation still blocks newly introduced bidi defects', (t) => {const result = validateSiteIntegrity(projectRoot);- assert.equal(result.errors.length, 1);+ assert.equal(result.errors.length, 1, JSON.stringify(result, null, 2));assert.match(result.errors[0], /src\/theme\.css:2/);assert.equal(result.reviewFindings.length, 1);});@@ -360,15 +511,12 @@ test('one recorded finding cannot defer a second same-line declaration', (t) =>'react-i18next': '^16.0.0',},}));- writeVerifiedPackageLock(projectRoot, 'react-i18next', '16.0.0');writeProjectFile(projectRoot, 'src/i18n/locales/en-US.json', '{"title":"Home"}');writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', '{"title":"الرئيسية"}');writeProjectFile(projectRoot,'src/i18n/index.ts',- "import i18next from 'i18next'; i18next.init({ fallbackLng: 'en-US' });\n" +- "import { isLocaleAvailable } from './localeAvailability';\n" +- "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);"+ runtimeIndex());writeProjectFile(projectRoot, availabilityPath, `const unavailableLocales = new Set(['ar-SA']);@@ -378,24 +526,24 @@ test('one recorded finding cannot defer a second same-line declaration', (t) =>writeProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `import { isLocaleAvailable } from '../i18n/localeAvailability';export function LanguageSelector() {- document.documentElement.lang = 'en-US';- document.documentElement.dir = 'ltr';+ const locale = 'en-US';+ document.documentElement.lang = locale;+ document.documentElement.dir = locale === 'ar-SA' ? 'rtl' : 'ltr';return ['en-US', 'ar-SA'].filter(isLocaleAvailable).map((locale) => locale);}`);const cssLine = '.known { margin-left: 1rem; padding-right: 1rem; }';writeProjectFile(projectRoot, 'src/theme.css', cssLine);+ const recordedFinding = auditBidirectionalReadiness(projectRoot).findings.find(+ (finding) => finding.rule === 'directional-physical-css'+ );writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({schemaVersion: 1,framework: 'react',mode: 'runtime',packageName: 'react-i18next',packageVersion: '^16.0.0',- packageVerification: {- status: 'verified',- source: 'known-capability',- ...verifiedNpmArtifact('react-i18next', '16.0.0'),- },+ packageVerification: verifiedReactPackage(projectRoot),locales: ['en-US', 'ar-SA'],defaultLocale: 'en-US',translationMethod: 'agent',@@ -408,12 +556,16 @@ test('one recorded finding cannot defer a second same-line declaration', (t) =>unavailableLocales: ['ar-SA'],bidirectionalReadiness: {status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },findings: [{- file: 'src/theme.css',- line: 1,- rule: 'directional-physical-css',- message: `Use a logical CSS property, or add an adjacent validated bidi-physical exception: ${cssLine}`,+ ...recordedFinding,+ scope: 'locale',+ affectedLocales: ['ar-SA'],}],+ renderedFindings: [],},adoptedExistingConfiguration: false,lastOperation: 'extend',@@ -422,7 +574,7 @@ test('one recorded finding cannot defer a second same-line declaration', (t) =>const result = validateSiteIntegrity(projectRoot);- assert.equal(result.errors.length, 1);+ assert.equal(result.errors.length, 1, JSON.stringify(result, null, 2));assert.equal(result.reviewFindings.length, 1);});diff --git a/plugins/power-pages/scripts/tests/suggest-content-locale.test.js b/plugins/power-pages/scripts/tests/suggest-content-locale.test.jsnew file mode 100644index 000000000..3401751c9--- /dev/null+++ b/plugins/power-pages/scripts/tests/suggest-content-locale.test.js@@ -0,0 +1,115 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');++const {+ FALLBACK_LOCALE,+ readableLanguage,+ suggestContentLocale,+} = require('../suggest-content-locale');++function odataSequence(responses, calls = []) {+ return async (url, token, request) => {+ calls.push({ url, token, request });+ const response = responses.shift();+ if (response instanceof Error) throw response;+ return response;+ };+}++test('suggests the Dataverse organization base language', async () => {+ const calls = [];+ const request = () => {};+ const result = await suggestContentLocale({+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: (resourceUrl) => {+ assert.equal(resourceUrl, 'https://contoso.crm.dynamics.com');+ return 'token';+ },+ makeRequest: request,+ odataGet: odataSequence([+ { value: [{ languagecode: 1036 }] },+ {+ value: [{+ localeid: 1036,+ code: 'fr-FR',+ language: 'French',+ name: 'French (France)',+ }],+ },+ ], calls),+ });++ assert.deepEqual(result, {+ locale: 'fr-FR',+ language: 'French (France)',+ direction: 'ltr',+ lcid: 1036,+ source: 'dataverse',+ });+ assert.equal(calls.length, 2);+ assert.match(calls[0].url, /organizations\?\$select=languagecode&\$top=1$/);+ assert.match(calls[1].url, /languagelocale.*\$filter=localeid eq 1036/);+ assert.equal(calls[0].token, 'token');+ assert.equal(calls[0].request, request);+});++test('resolves the direction of an RTL Dataverse language', async () => {+ const result = await suggestContentLocale({+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => 'token',+ odataGet: odataSequence([+ { value: [{ languagecode: 1025 }] },+ { value: [{ localeid: 1025, code: 'ar-SA', name: 'Arabic (Saudi Arabia)' }] },+ ]),+ });++ assert.equal(result.locale, 'ar-SA');+ assert.equal(result.direction, 'rtl');+ assert.equal(result.source, 'dataverse');+});++test('uses the locale tag when Dataverse omits a readable language name', () => {+ assert.equal(readableLanguage({ code: 'ja-JP' }, 'ja-JP'), 'ja-JP');+});++for (const [scenario, dependencies] of [+ ['no selected environment', {+ getEnvironmentUrl: () => null,+ }],+ ['no Azure CLI token', {+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => null,+ }],+ ['organization query failure', {+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => 'token',+ odataGet: odataSequence([new Error('HTTP 401')]),+ }],+ ['missing organization language code', {+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => 'token',+ odataGet: odataSequence([{ value: [{}] }]),+ }],+ ['unmapped organization language code', {+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => 'token',+ odataGet: odataSequence([+ { value: [{ languagecode: 99999 }] },+ { value: [] },+ ]),+ }],+ ['invalid mapped language tag', {+ getEnvironmentUrl: () => 'https://contoso.crm.dynamics.com',+ getAuthToken: () => 'token',+ odataGet: odataSequence([+ { value: [{ languagecode: 99999 }] },+ { value: [{ code: 'not_a_locale', name: 'Invalid' }] },+ ]),+ }],+]) {+ test(`silently falls back to en-US when there is ${scenario}`, async () => {+ assert.deepEqual(await suggestContentLocale(dependencies), FALLBACK_LOCALE);+ });+}diff --git a/plugins/power-pages/scripts/tests/validate-i18n-package.test.js b/plugins/power-pages/scripts/tests/validate-i18n-package.test.jsindex dad86377d..7496d72db 100644--- a/plugins/power-pages/scripts/tests/validate-i18n-package.test.js+++ b/plugins/power-pages/scripts/tests/validate-i18n-package.test.js@@ -23,6 +23,7 @@ const {validateOfficialArtifactMetadata,validatePackageLockProvenance,validateModeEvidenceClassification,+ validateRequestedMode,validateModeEvidenceUrl,versionSatisfiesRangeWithNpm,} = require('../validate-i18n-package');@@ -256,6 +257,26 @@ test('uses shared package capabilities for known framework support', () => {assert.equal(packageSupportsFramework('astro-built-in', 'astro'), true);});+test('blocks package validation for temporarily unavailable modes', () => {+ assert.equal(validateRequestedMode('angular', 'runtime').available, true);+ assert.throws(+ () => validateRequestedMode('angular', 'static'),+ (error) => {+ assert.equal(error.code, 'angular-static-temporarily-unavailable');+ assert.match(error.message, /temporarily unavailable/);+ return true;+ }+ );+ assert.throws(+ () => validateRequestedMode('astro', 'static'),+ (error) => {+ assert.equal(error.code, 'astro-static-temporarily-unavailable');+ assert.match(error.message, /No Astro localization mode is currently available/);+ return true;+ }+ );+});+test('rejects prereleases without explicit confirmation', () => {const result = evaluatePackage(metadata({version: '17.0.0-rc.1',diff --git a/plugins/power-pages/scripts/tests/validate-localization.test.js b/plugins/power-pages/scripts/tests/validate-localization.test.jsindex cc0024919..3a95b0052 100644--- a/plugins/power-pages/scripts/tests/validate-localization.test.js+++ b/plugins/power-pages/scripts/tests/validate-localization.test.js@@ -7,6 +7,18 @@ const path = require('path');const { spawnSync } = require('child_process');const { createTempProject, writeProjectFile } = require('./test-utils');+const {+ beginLocalizationVerification,+ markLocalizationVerificationFailed,+ markLocalizationVerificationPassed,+} = require('../lib/localization-verification-transaction');+const {+ computeVerificationInputFingerprint,+ createVerificationEvidence,+} = require('../lib/verification-evidence');+const {+ validateSiteIntegrity,+} = require('../lib/site-integrity');const VALIDATOR_PATH = path.join(__dirname,@@ -22,8 +34,35 @@ const {compareXlfResources,extractXlfMessages,} = require(VALIDATOR_PATH);+const VERIFICATION_MANAGER_PATH = path.join(+ __dirname,+ '..',+ 'manage-localization-verification.js'+);+const SITE_INTEGRITY_CLI_PATH = path.join(+ __dirname,+ '..',+ 'validate-site-integrity.js'+);+const ALLOW_VERIFIED_REVIEW = { allowVerifiedLocalizationReview: true };+const UNFINISHED_TRANSACTION_ERROR = /verification is still active/;++function runSiteIntegrity(projectRoot, extraArgs = []) {+ return spawnSync(+ process.execPath,+ [SITE_INTEGRITY_CLI_PATH, '--projectRoot', projectRoot, ...extraArgs],+ { encoding: 'utf8' }+ );+}-function runValidator(projectRoot) {+function runValidator(projectRoot, options = {}) {+ if (options.verification) {+ return spawnSync(+ process.execPath,+ [VALIDATOR_PATH, '--projectRoot', projectRoot, '--verification'],+ { encoding: 'utf8' }+ );+ }return spawnSync(process.execPath, [VALIDATOR_PATH], {input: JSON.stringify({ cwd: projectRoot }),encoding: 'utf8',@@ -63,7 +102,345 @@ test('fails closed when hook input omits the working directory', () => {);});+test('allows an explicitly active Phase 6 verification but blocks completion', (t) => {+ const projectRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(projectRoot, ['fr-FR']);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ manifest.unavailableLocales = [];+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));++ const verificationResult = runValidator(projectRoot, { verification: true });+ assert.equal(verificationResult.status, 0, verificationResult.stderr);++ const completionResult = runValidator(projectRoot);+ assert.equal(completionResult.status, 2);+ assert.match(+ completionResult.stderr,+ /unavailableLocales must exactly match|verification is still active/i+ );+});++test('finalizes an active verification only after full localization validation', (t) => {+ const projectRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(projectRoot, ['fr-FR']);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ manifest.unavailableLocales = [];+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));+ markLocalizationVerificationPassed(projectRoot, null, {+ profile: 'extensive',+ representativeLocaleIds: { ltr: 'en', rtl: 'pseudo-rtl' },+ manualReview: [],+ evidence: {+ schemaVersion: 1,+ inputFingerprint: computeVerificationInputFingerprint(projectRoot),+ specFingerprint: 'b'.repeat(64),+ },+ });++ // Interrupted-session shape: the target passed but is still exposed and still+ // pending the maker decision. Only add-localization's pre-review gate may+ // accept it; the default gate that deploy-site runs must refuse it.+ const awaitingReview = validateSiteIntegrity(+ projectRoot,+ ALLOW_VERIFIED_REVIEW+ );+ assert.deepEqual(+ awaitingReview.errors,+ [],+ JSON.stringify(awaitingReview, null, 2)+ );+ const deployGate = validateSiteIntegrity(projectRoot);+ assert.ok(deployGate.errors.some((error) =>+ UNFINISHED_TRANSACTION_ERROR.test(error)+ ), JSON.stringify(deployGate, null, 2));+ const deployCli = runSiteIntegrity(projectRoot);+ assert.equal(deployCli.status, 2, deployCli.stdout);+ assert.match(deployCli.stderr, UNFINISHED_TRANSACTION_ERROR);+ const reviewCli = runSiteIntegrity(projectRoot, [+ '--allow-verified-localization-review',+ ]);+ assert.equal(reviewCli.status, 0, reviewCli.stderr);++ manifest.bidirectionalReadiness = {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ };+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));++ const result = spawnSync(+ process.execPath,+ [+ VERIFICATION_MANAGER_PATH,+ '--finalize',+ '--projectRoot',+ projectRoot,+ ],+ { encoding: 'utf8' }+ );++ assert.equal(result.status, 0, result.stderr);+ assert.ok(!fs.existsSync(+ path.join(projectRoot, '.powerpages-localization-verification.json')+ ));+});++test('site integrity accepts a current verified transaction only at the pre-review gate', (t) => {+ const projectRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(projectRoot, ['fr-FR']);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ manifest.unavailableLocales = [];+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));+ markLocalizationVerificationPassed(projectRoot, null, {+ profile: 'extensive',+ representativeLocaleIds: { ltr: 'en', rtl: 'pseudo-rtl' },+ manualReview: [],+ evidence: {+ schemaVersion: 1,+ inputFingerprint: computeVerificationInputFingerprint(projectRoot),+ specFingerprint: 'b'.repeat(64),+ },+ });+ manifest.bidirectionalReadiness = {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ };+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));++ const verified = validateSiteIntegrity(projectRoot, ALLOW_VERIFIED_REVIEW);+ assert.deepEqual(verified.errors, [], JSON.stringify(verified, null, 2));+ const deployGate = validateSiteIntegrity(projectRoot);+ assert.ok(deployGate.errors.some((error) =>+ UNFINISHED_TRANSACTION_ERROR.test(error)+ ), JSON.stringify(deployGate, null, 2));++ writeProjectFile(projectRoot, 'src/App.tsx', 'export const changed = true;');+ const stale = validateSiteIntegrity(projectRoot, ALLOW_VERIFIED_REVIEW);+ assert.ok(stale.errors.some((error) =>+ /rendered evidence is stale/.test(error)+ ), JSON.stringify(stale, null, 2));+});++test('site integrity blocks unfinished and failed transactions', (t) => {+ const inProgressRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(inProgressRoot, ['fr-FR']);+ const inProgress = validateSiteIntegrity(+ inProgressRoot,+ ALLOW_VERIFIED_REVIEW+ );+ assert.ok(inProgress.errors.some((error) =>+ /must be verified before the final site-integrity gate/.test(error)+ ), JSON.stringify(inProgress, null, 2));+ const inProgressDeploy = validateSiteIntegrity(inProgressRoot);+ assert.ok(inProgressDeploy.errors.some((error) =>+ UNFINISHED_TRANSACTION_ERROR.test(error)+ ), JSON.stringify(inProgressDeploy, null, 2));++ const failedRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(failedRoot, ['fr-FR']);+ markLocalizationVerificationFailed(failedRoot);+ const failed = validateSiteIntegrity(failedRoot, ALLOW_VERIFIED_REVIEW);+ assert.ok(failed.errors.some((error) =>+ /must be verified before the final site-integrity gate/.test(error)+ ), JSON.stringify(failed, null, 2));+ const failedDeploy = validateSiteIntegrity(failedRoot);+ assert.ok(failedDeploy.errors.some((error) =>+ UNFINISHED_TRANSACTION_ERROR.test(error)+ ), JSON.stringify(failedDeploy, null, 2));+});++// Realistic localized site where ar-SA was exposed for a browser run that has+// not been finalized yet. `hide()` returns ar-SA to its fail-closed state.+function createExposedArabicTransaction(t) {+ const hiddenAvailability =+ "const unavailableLocales = new Set(['ar-SA']);\n" ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n';+ const projectRoot = createUnavailableLocaleProject(t, hiddenAvailability);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const hiddenManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ hiddenManifest.bidirectionalReadiness.renderedFindings = [];+ fs.writeFileSync(manifestPath, JSON.stringify(hiddenManifest));+ beginLocalizationVerification(projectRoot, ['ar-SA']);+ fs.writeFileSync(+ manifestPath,+ JSON.stringify({ ...hiddenManifest, unavailableLocales: [] })+ );+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ hiddenAvailability.replace("['ar-SA']", '[]')+ );+ return {+ projectRoot,+ hide() {+ fs.writeFileSync(manifestPath, JSON.stringify(hiddenManifest));+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ hiddenAvailability+ );+ },+ };+}++function runVerificationManager(projectRoot, operation) {+ return spawnSync(+ process.execPath,+ [VERIFICATION_MANAGER_PATH, operation, '--projectRoot', projectRoot],+ { encoding: 'utf8' }+ );+}++test('manage CLI finalizes a verified locale that the maker keeps unavailable', (t) => {+ const { projectRoot, hide } = createExposedArabicTransaction(t);+ markLocalizationVerificationPassed(projectRoot, null, {+ profile: 'extensive',+ representativeLocaleIds: { ltr: 'en-US', rtl: 'ar-SA' },+ manualReview: [],+ evidence: createVerificationEvidence(projectRoot, {}),+ });++ // Phase 7 "Save but keep locale unavailable": hide ar-SA again.+ hide();++ const finalized = runVerificationManager(projectRoot, '--finalize');+ assert.equal(finalized.status, 0, finalized.stderr);+ assert.ok(!fs.existsSync(+ path.join(projectRoot, '.powerpages-localization-verification.json')+ ));+ const deployCli = runSiteIntegrity(projectRoot);+ assert.equal(deployCli.status, 0, deployCli.stderr);+});++test('manage CLI recovers a run whose availability backup is missing', (t) => {+ const { projectRoot, hide } = createExposedArabicTransaction(t);+ fs.unlinkSync(path.join(+ projectRoot,+ '.powerpages-localization-verification.json.availability'+ ));++ const failed = runVerificationManager(projectRoot, '--fail');+ assert.equal(failed.status, 0, failed.stderr);+ assert.match(+ failed.stderr,+ /restore was skipped.*Exclude "ar-SA" in "src\/i18n\/localeAvailability\.ts"/s+ );++ // ar-SA is still exposed in source, so finalization and deployment stay+ // blocked until the manual step is done.+ const blocked = runVerificationManager(projectRoot, '--finalize');+ assert.notEqual(blocked.status, 0);+ assert.match(blocked.stderr, /does not exclude ar-SA/);+ assert.equal(runSiteIntegrity(projectRoot).status, 2);++ hide();+ const finalized = runVerificationManager(projectRoot, '--finalize');+ assert.equal(finalized.status, 0, finalized.stderr);+ const deployCli = runSiteIntegrity(projectRoot);+ assert.equal(deployCli.status, 0, deployCli.stderr);+});++test('keeps verification blocking when its localization manifest is missing', (t) => {+ const projectRoot = createLocalizedReactProject(t, {+ includeAvailabilitySnapshot: true,+ unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },+ });+ beginLocalizationVerification(projectRoot, ['fr-FR']);+ fs.unlinkSync(path.join(projectRoot, '.powerpages-localization.json'));++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /cannot continue or complete without a valid manifest/i);+});+function createLocalizedReactProject(t, overrides = {}) {+ const {+ includeAvailabilitySnapshot = false,+ ...manifestOverrides+ } = overrides;const projectRoot = createTempProject(t);writeProjectFile(projectRoot, 'powerpages.config.json', '{}');writeProjectFile(projectRoot, 'package.json', JSON.stringify({@@ -122,11 +499,41 @@ function createLocalizedReactProject(t, overrides = {}) {},generatedFiles: ['src/components/LanguageSelector.tsx'],managedFiles: ['src/i18n/index.ts'],+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },adoptedExistingConfiguration: false,lastOperation: 'create',updatedAt: '2026-07-30T00:00:00.000Z',- ...overrides,+ ...manifestOverrides,};+ if (includeAvailabilitySnapshot &&+ (manifest.unavailableLocales || []).length > 0 &&+ ![...manifest.generatedFiles, ...manifest.managedFiles].some(+ (relativePath) =>+ /locale[-_.]?availability/i.test(path.basename(relativePath))+ )) {+ manifest.managedFiles = [+ ...manifest.managedFiles,+ 'src/i18n/localeAvailability.ts',+ ];+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ `const unavailableLocales = new Set(${JSON.stringify(+ manifest.unavailableLocales+ )});\n` ++ 'export const isLocaleAvailable = (locale: string) => ' ++ '!unavailableLocales.has(locale);\n'+ );+ }writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify(manifest));if (manifest.packageName !== 'astro-built-in' &&manifest.packageVerification?.artifact) {@@ -164,14 +571,26 @@ function createUnavailableLocaleProject(],bidirectionalReadiness: {status: 'pending-remediation',- findings: [{ rule: 'directional-physical-css' }],+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'arabic-menu--open--desktop--ar',+ rule: 'localized-font-failure',+ severity: 'error',+ message: 'The Arabic menu font is unreadable.',+ selector: '.menu',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],},});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',navigation: { home: 'الرئيسية' },}));- writeProjectFile(projectRoot, 'src/theme.css', '.callout { padding-left: 1rem; }');writeProjectFile(projectRoot, availabilityPath, availabilitySource);writeProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `import { isLocaleAvailable } from '../i18n/localeAvailability';@@ -184,7 +603,17 @@ function createUnavailableLocaleProject(fs.appendFileSync(path.join(projectRoot, 'src/i18n/index.ts'),"\nimport { isLocaleAvailable } from './localeAvailability';\n" +- "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);\n"+ "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);\n" ++ "async function activateLocaleForAudit(locale) {\n" ++ " await i18next.changeLanguage(locale);\n" ++ " document.documentElement.lang = locale;\n" ++ " document.documentElement.dir = locale === 'ar-SA' ? 'rtl' : 'ltr';\n" ++ "}\n" ++ "if (import.meta.env.DEV) {\n" ++ " window.__powerPagesLocalizationAudit = {\n" ++ " activate: (locale) => activateLocaleForAudit(locale),\n" ++ " };\n" ++ "}\n");if (includeCoordinator) {writeProjectFile(projectRoot, coordinatorPath, `@@ -202,6 +631,220 @@ function createUnavailableLocaleProject(return projectRoot;}+function createManifestlessAngularStaticProject(t) {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({+ dependencies: {+ '@angular/core': '^19.1.0',+ '@angular/compiler': '^19.1.0',+ '@angular/compiler-cli': '^19.1.0',+ '@angular/localize': '^19.1.0',+ },+ }));+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify({+ projects: {+ portal: {+ i18n: { sourceLocale: 'en-US' },+ },+ },+ }));+ writeProjectFile(projectRoot, 'src/locale/messages.en-US.xlf', '<xliff></xliff>');+ writeProjectFile(projectRoot, 'src/locale/messages.fr-FR.xlf', '<xliff></xliff>');+ writeProjectFile(+ projectRoot,+ 'src/app/language-selector.ts',+ "export class LanguageSelector { switchLanguage(){ document.documentElement.lang='fr-FR'; document.documentElement.dir='ltr'; } }"+ );+ const artifact = {+ version: '19.1.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl: 'https://registry.npmjs.org/@angular/localize/-/localize-19.1.0.tgz',+ integrity: 'sha512-dGVzdA==',+ };+ writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({+ schemaVersion: 1,+ framework: 'angular',+ mode: 'static',+ packageName: '@angular/localize',+ packageVersion: '19.1.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact,+ },+ locales: ['en-US', 'fr-FR'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/locale/messages.en-US.xlf',+ 'fr-FR': 'src/locale/messages.fr-FR.xlf',+ },+ generatedFiles: ['src/app/language-selector.ts'],+ managedFiles: ['angular.json'],+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'create',+ updatedAt: '2026-07-30T00:00:00.000Z',+ }));+ writeProjectFile(projectRoot, 'package-lock.json', JSON.stringify({+ packages: {+ 'node_modules/@angular/localize': {+ version: artifact.version,+ resolved: artifact.tarballUrl,+ integrity: artifact.integrity,+ },+ },+ }));+ return projectRoot;+}++function createManifestlessAstroStaticProject(t) {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({+ dependencies: { astro: '^6.1.0' },+ }));+ writeProjectFile(+ projectRoot,+ 'astro.config.mjs',+ "export default { i18n: { defaultLocale: 'en-US', locales: ['en-US', 'ja-JP'] } };"+ );+ writeProjectFile(projectRoot, 'src/i18n/en-US.json', '{"home":"Home"}');+ writeProjectFile(projectRoot, 'src/i18n/ja-JP.json', '{"home":"Home JA"}');+ writeProjectFile(+ projectRoot,+ 'src/pages/index.astro',+ "---\nconst href = getRelativeLocaleUrl('ja-JP');\n---\n<html lang=\"en-US\" dir=\"ltr\"><a href={href}>LanguageSelector</a></html>"+ );+ writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({+ schemaVersion: 1,+ framework: 'astro',+ mode: 'static',+ packageName: 'astro-built-in',+ packageVersion: '6.1.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ },+ locales: ['en-US', 'ja-JP'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/i18n/en-US.json',+ 'ja-JP': 'src/i18n/ja-JP.json',+ },+ generatedFiles: ['src/pages/index.astro'],+ managedFiles: ['astro.config.mjs'],+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ja-JP': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'create',+ updatedAt: '2026-07-30T00:00:00.000Z',+ }));+ return projectRoot;+}++function createAngularRuntimeProjectWithStaticResidue(t) {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({+ dependencies: {+ '@angular/core': '^19.1.0',+ '@angular/compiler': '^19.1.0',+ '@angular/compiler-cli': '^19.1.0',+ '@angular/localize': '^19.1.0',+ '@jsverse/transloco': '^7.6.0',+ },+ }));+ writeProjectFile(projectRoot, 'angular.json', JSON.stringify({+ projects: {+ portal: {+ i18n: { sourceLocale: 'en-US' },+ },+ },+ }));+ writeProjectFile(projectRoot, 'src/assets/i18n/en-US.json', '{"home":"Home"}');+ writeProjectFile(projectRoot, 'src/assets/i18n/fr-FR.json', '{"home":"Accueil"}');+ writeProjectFile(+ projectRoot,+ 'src/app/i18n/locale-coordinator.service.ts',+ "import '@jsverse/transloco'; provideTransloco({}); setActiveLang('fr-FR'); document.documentElement.lang='fr-FR'; const direction = locale === 'ar-SA' ? 'rtl' : 'ltr'; document.documentElement.dir=direction; export class LanguageSelector {}"+ );+ writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({+ schemaVersion: 1,+ framework: 'angular',+ mode: 'runtime',+ packageName: '@jsverse/transloco',+ packageVersion: '^7.6.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact: {+ version: '7.6.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl:+ 'https://registry.npmjs.org/@jsverse/transloco/-/transloco-7.6.0.tgz',+ integrity: 'sha512-dGVzdA==',+ },+ },+ locales: ['en-US', 'fr-FR'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/assets/i18n/en-US.json',+ 'fr-FR': 'src/assets/i18n/fr-FR.json',+ },+ generatedFiles: ['src/app/i18n/locale-coordinator.service.ts'],+ managedFiles: [],+ unavailableLocales: [],+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'reconfigure',+ updatedAt: '2026-07-30T00:00:00.000Z',+ }));+ writeProjectFile(projectRoot, 'package-lock.json', JSON.stringify({+ packages: {+ 'node_modules/@jsverse/transloco': {+ version: '7.6.0',+ resolved:+ 'https://registry.npmjs.org/@jsverse/transloco/-/transloco-7.6.0.tgz',+ integrity: 'sha512-dGVzdA==',+ },+ },+ }));+ return projectRoot;+}+test('approves when no localization manifest exists', (t) => {const projectRoot = createTempProject(t);writeProjectFile(projectRoot, 'powerpages.config.json', '{}');@@ -500,7 +1143,15 @@ test('blocks mixed-direction runtime localization without a locale coordinator','en-US': 'src/i18n/locales/en-US.json','ar-SA': 'src/i18n/locales/ar-SA.json',},- bidirectionalReadiness: { status: 'ready', findings: [] },+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',@@ -521,7 +1172,15 @@ test('approves a mixed-direction runtime localization with a coordinator', (t) ='ar-SA': 'src/i18n/locales/ar-SA.json',},managedFiles: ['src/i18n/index.ts', coordinatorPath],- bidirectionalReadiness: { status: 'ready', findings: [] },+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',@@ -550,7 +1209,15 @@ test('blocks a mixed-direction coordinator with a fixed document direction', (t)'ar-SA': 'src/i18n/locales/ar-SA.json',},managedFiles: ['src/i18n/index.ts', coordinatorPath],- bidirectionalReadiness: { status: 'ready', findings: [] },+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',@@ -574,6 +1241,15 @@ test('blocks a mixed-direction coordinator with a fixed document direction', (t)test('enforces unavailable locales for same-direction locale sets', (t) => {const projectRoot = createLocalizedReactProject(t, {unavailableLocales: ['fr-FR'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [],+ },});const result = runValidator(projectRoot);@@ -585,6 +1261,54 @@ test('enforces unavailable locales for same-direction locale sets', (t) => {assert.doesNotMatch(result.stderr, /Pending bidirectional remediation requires one/i);});+test('requires readiness metadata for same-direction localization', (t) => {+ const projectRoot = createLocalizedReactProject(t, {+ bidirectionalReadiness: undefined,+ });++ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /require bidirectionalReadiness metadata/i);+});++test('requires maker-approved limitation evidence to exist in the project', (t) => {+ const evidence = 'docs/bidirectional-evidence/run-1/calendar.png';+ const projectRoot = createLocalizedReactProject(t, {+ bidirectionalReadiness: {+ status: 'approved-with-limitations',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'fr-FR': { status: 'approved-with-limitations' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'calendar--open--desktop--fr',+ rule: 'rendered-semantic-review',+ severity: 'review',+ message: 'The vendor-owned calendar arrow remains unchanged.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['fr-FR'],+ disposition: {+ status: 'maker-approved',+ impact: 'Calendar navigation remains understandable and usable.',+ evidence,+ approvedAt: '2026-09-03T12:00:00.000Z',+ },+ }],+ },+ });++ let result = runValidator(projectRoot);+ assert.equal(result.status, 2);+ assert.match(result.stderr, /limitation evidence does not exist/i);++ writeProjectFile(projectRoot, evidence, 'screenshot evidence');+ result = runValidator(projectRoot);+ assert.equal(result.status, 0, result.stderr);+});+test('allows a mixed-direction locale to remain unavailable pending remediation', (t) => {const projectRoot = createUnavailableLocaleProject(t, `const unavailableLocales = new Set(['ar-SA']);@@ -766,31 +1490,47 @@ test('rejects inverted unavailable-locale predicates', (t) => {}});-test('does not let pending remediation hide an available opposite-direction locale', (t) => {+test('keeps a previously ready RTL locale available when only a new RTL locale is pending', (t) => {const availabilityPath = 'src/i18n/localeAvailability.ts';+ const coordinatorPath = 'src/i18n/localeCoordinator.ts';const projectRoot = createLocalizedReactProject(t, {- locales: ['en-US', 'ar-SA', 'fr-FR'],+ locales: ['en-US', 'he-IL', 'ar-SA'],resourcePaths: {'en-US': 'src/i18n/locales/en-US.json',+ 'he-IL': 'src/i18n/locales/he-IL.json','ar-SA': 'src/i18n/locales/ar-SA.json',- 'fr-FR': 'src/i18n/locales/fr-FR.json',},- unavailableLocales: ['fr-FR'],- managedFiles: ['src/i18n/index.ts', availabilityPath],+ unavailableLocales: ['ar-SA'],+ managedFiles: ['src/i18n/index.ts', availabilityPath, coordinatorPath],bidirectionalReadiness: {status: 'pending-remediation',- findings: [{ rule: 'directional-physical-css' }],+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'he-IL': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'arabic-calendar--open--desktop--ar',+ rule: 'localized-font-failure',+ severity: 'error',+ message: 'The Arabic calendar font is unreadable.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],},});- const resource = JSON.stringify({- greeting: 'Hello {{name}}',- navigation: { home: 'Home' },- });- writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', resource);- writeProjectFile(projectRoot, 'src/i18n/locales/fr-FR.json', resource);- writeProjectFile(projectRoot, 'src/theme.css', '.callout { padding-left: 1rem; }');+ writeProjectFile(projectRoot, 'src/i18n/locales/he-IL.json', JSON.stringify({+ greeting: 'שלום {{name}}',+ navigation: { home: 'בית' },+ }));+ writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({+ greeting: 'مرحبا {{name}}',+ navigation: { home: 'الرئيسية' },+ }));writeProjectFile(projectRoot, availabilityPath, `- const unavailableLocales = new Set(['fr-FR']);+ const unavailableLocales = new Set(['ar-SA']);export const isLocaleAvailable = (locale: string) => !unavailableLocales.has(locale);`);writeProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `@@ -798,22 +1538,28 @@ test('does not let pending remediation hide an available opposite-direction locaexport const LanguageSelector = () => {document.documentElement.lang = 'en-US';document.documentElement.dir = 'ltr';- return ['en-US', 'ar-SA'].filter(isLocaleAvailable).map((locale) => locale);+ return ['en-US', 'he-IL', 'ar-SA'].filter(isLocaleAvailable).map((locale) => locale);};`);+ writeProjectFile(projectRoot, coordinatorPath, `+ import i18next from 'i18next';+ import { isLocaleAvailable } from './localeAvailability';+ export async function switchLocale(locale: string) {+ if (!isLocaleAvailable(locale)) return;+ await i18next.changeLanguage(locale);+ document.documentElement.lang = locale;+ document.documentElement.dir = locale === 'he-IL' ? 'rtl' : 'ltr';+ localStorage.setItem('site-locale', locale);+ }+ `);fs.appendFileSync(path.join(projectRoot, 'src/i18n/index.ts'),"\nimport { isLocaleAvailable } from './localeAvailability';\n" +- "export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);\n"+ "export const selectorLocales = ['en-US', 'he-IL', 'ar-SA'].filter(isLocaleAvailable);\n");const result = runValidator(projectRoot);- assert.equal(result.status, 2);- assert.match(- result.stderr,- /every locale opposite to the default direction to be unavailable/i- );- assert.match(result.stderr, /directional-physical-css/i);+ assert.equal(result.status, 0, result.stderr);});test('requires pending locale availability to be applied at activation boundaries', (t) => {@@ -828,23 +1574,41 @@ test('requires pending locale availability to be applied at activation boundariemanagedFiles: ['src/i18n/index.ts', availabilityPath],bidirectionalReadiness: {status: 'pending-remediation',- findings: [{ rule: 'directional-physical-css' }],+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [],+ renderedFindings: [{+ caseId: 'calendar--open--desktop--ar',+ rule: 'computed-direction-mismatch',+ severity: 'error',+ message: 'Expected rtl but found ltr.',+ selector: '.calendar',+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],},});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',navigation: { home: 'الرئيسية' },}));- writeProjectFile(projectRoot, 'src/theme.css', '.callout { padding-left: 1rem; }');writeProjectFile(projectRoot, availabilityPath, `const unavailableLocales = new Set(['ar-SA']);export const isLocaleAvailable = (locale: string) => !unavailableLocales.has(locale);`);+ fs.appendFileSync(+ path.join(projectRoot, 'src/i18n/index.ts'),+ "\nimport { isLocaleAvailable } from './localeAvailability';\n" ++ "isLocaleAvailable('en-US');\n" ++ "export const diagnostics = ['en-US'].filter(isLocaleAvailable);\n"+ );const result = runValidator(projectRoot);assert.equal(result.status, 2);assert.match(result.stderr, /does not apply isLocaleAvailable/i);- assert.match(result.stderr, /directional-physical-css/i);+ assert.match(result.stderr, /managed availability logic/i);});test('requires readiness metadata for mixed-direction localization', (t) => {@@ -854,6 +1618,7 @@ test('requires readiness metadata for mixed-direction localization', (t) => {'en-US': 'src/i18n/locales/en-US.json','ar-SA': 'src/i18n/locales/ar-SA.json',},+ bidirectionalReadiness: undefined,});writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', JSON.stringify({greeting: 'مرحبا {{name}}',@@ -862,7 +1627,7 @@ test('requires readiness metadata for mixed-direction localization', (t) => {const result = runValidator(projectRoot);assert.equal(result.status, 2);- assert.match(result.stderr, /requires manifest bidirectionalReadiness metadata/i);+ assert.match(result.stderr, /require bidirectionalReadiness metadata/i);});test('approves an explicitly unverified custom package with initialization evidence', (t) => {@@ -1050,10 +1815,38 @@ test('blocks a framework-package-mode mismatch', (t) => {const projectRoot = createLocalizedReactProject(t, { mode: 'static' });const result = runValidator(projectRoot);assert.equal(result.status, 2);- assert.match(result.stderr, /does not support the configured localization mode/);+ assert.match(result.stderr, /react does not support "static" mode in add-localization/);assert.match(result.stderr, /does not match the manifest framework and mode/);});+test('blocks manifests that select temporarily unavailable localization modes', (t) => {+ const angularRoot = createManifestlessAngularStaticProject(t);+ const angularResult = runValidator(angularRoot);+ assert.equal(angularResult.status, 2);+ assert.match(+ angularResult.stderr,+ /Angular static localization is temporarily unavailable/+ );++ const astroRoot = createManifestlessAstroStaticProject(t);+ const astroResult = runValidator(astroRoot);+ assert.equal(astroResult.status, 2);+ assert.match(+ astroResult.stderr,+ /No Astro localization mode is currently available/+ );+});++test('blocks Angular runtime validation while static implementation residue remains', (t) => {+ const projectRoot = createAngularRuntimeProjectWithStaticResidue(t);+ const result = runValidator(projectRoot);++ assert.equal(result.status, 2);+ assert.match(result.stderr, /Angular static localization is temporarily unavailable/);+ assert.match(result.stderr, /Remove or migrate detected @angular\/localize/);+ assert.match(result.stderr, /Remove or migrate detected Angular i18n build configuration/);+});+test('blocks noncanonical manifest locale values', (t) => {const projectRoot = createLocalizedReactProject(t, {locales: ['en-us', 'fr-FR'],@@ -1062,6 +1855,15 @@ test('blocks noncanonical manifest locale values', (t) => {'en-us': 'src/i18n/locales/en-US.json','fr-FR': 'src/i18n/locales/fr-FR.json',},+ bidirectionalReadiness: {+ status: 'ready',+ localeReadiness: {+ 'en-us': { status: 'ready' },+ 'fr-FR': { status: 'ready' },+ },+ findings: [],+ renderedFindings: [],+ },});const result = runValidator(projectRoot);assert.equal(result.status, 2);diff --git a/plugins/power-pages/scripts/tests/validate-site.test.js b/plugins/power-pages/scripts/tests/validate-site.test.jsindex 501a76c76..7093a4485 100644--- a/plugins/power-pages/scripts/tests/validate-site.test.js+++ b/plugins/power-pages/scripts/tests/validate-site.test.js@@ -7,6 +7,9 @@ const path = require('path');const { spawnSync } = require('child_process');const { createTempProject, writeProjectFile } = require('./test-utils');+const {+ auditBidirectionalReadiness,+} = require('../lib/bidirectional-readiness');const VALIDATOR_PATH = path.join(__dirname,@@ -221,7 +224,7 @@ test('create-site validator rejects incomplete or unknown direct arguments', (t)assert.match(unknown.stderr, /Usage: validate-site\.js/);});-test('create-site validator blocks direction-sensitive physical CSS', (t) => {+test('create-site validator leaves cross-cutting bidi checks to the shared hook', (t) => {const projectRoot = createProject(t,'<html lang="en-US" dir="ltr"><body><div id="root"></div></body></html>'@@ -229,6 +232,109 @@ test('create-site validator blocks direction-sensitive physical CSS', (t) => {writeProjectFile(projectRoot, 'src/theme.css', '.callout { padding-left: 1rem; }');const result = runValidator(projectRoot);- assert.equal(result.status, 2);- assert.match(result.stderr, /Bidirectional readiness.*directional-physical-css/);+ assert.equal(result.status, 0, result.stderr);+});++test('create-site validator allows an exact blocker isolated behind an unavailable locale', (t) => {+ const projectRoot = createProject(+ t,+ '<html lang="en-US" dir="ltr"><body><div id="root"></div></body></html>'+ );+ writeProjectFile(projectRoot, 'package.json', JSON.stringify({+ scripts: { build: 'vite build', dev: 'vite' },+ dependencies: {+ react: '^19.0.0',+ 'react-dom': '^19.0.0',+ i18next: '^25.0.0',+ 'react-i18next': '^16.0.0',+ },+ }));+ writeProjectFile(projectRoot, 'src/i18n/locales/en-US.json', '{"title":"Home"}');+ writeProjectFile(projectRoot, 'src/i18n/locales/ar-SA.json', '{"title":"الرئيسية"}');+ writeProjectFile(projectRoot, 'src/i18n/index.ts', `+ import i18next from 'i18next';+ import { isLocaleAvailable } from './localeAvailability';+ i18next.init({ fallbackLng: 'en-US' });+ export const selectorLocales = ['en-US', 'ar-SA'].filter(isLocaleAvailable);+ `);+ writeProjectFile(projectRoot, 'src/i18n/localeAvailability.ts', `+ const unavailableLocales = new Set(['ar-SA']);+ export const isLocaleAvailable = (locale: string) => !unavailableLocales.has(locale);+ `);+ writeProjectFile(projectRoot, 'src/components/LanguageSelector.tsx', `+ import { isLocaleAvailable } from '../i18n/localeAvailability';+ export function LanguageSelector() {+ const locale = 'en-US';+ document.documentElement.lang = locale;+ document.documentElement.dir = locale === 'ar-SA' ? 'rtl' : 'ltr';+ return ['en-US', 'ar-SA'].filter(isLocaleAvailable).map((item) => item);+ }+ `);+ writeProjectFile(projectRoot, 'src/theme.css', '.card { margin-left: 1rem; }');+ const packageArtifact = {+ version: '16.0.0',+ registry: 'https://registry.npmjs.org/',+ tarballUrl:+ 'https://registry.npmjs.org/react-i18next/-/react-i18next-16.0.0.tgz',+ integrity: 'sha512-dGVzdA==',+ };+ writeProjectFile(projectRoot, 'package-lock.json', JSON.stringify({+ packages: {+ 'node_modules/react-i18next': {+ version: packageArtifact.version,+ resolved: packageArtifact.tarballUrl,+ integrity: packageArtifact.integrity,+ },+ },+ }));+ const recordedFinding = auditBidirectionalReadiness(projectRoot).findings.find(+ (finding) => finding.rule === 'directional-physical-css'+ );+ writeProjectFile(projectRoot, '.powerpages-localization.json', JSON.stringify({+ schemaVersion: 1,+ framework: 'react',+ mode: 'runtime',+ packageName: 'react-i18next',+ packageVersion: '^16.0.0',+ packageVerification: {+ status: 'verified',+ source: 'known-capability',+ license: 'MIT',+ licenseReview: { status: 'automatically-accepted' },+ artifact: packageArtifact,+ },+ locales: ['en-US', 'ar-SA'],+ defaultLocale: 'en-US',+ translationMethod: 'agent',+ resourcePaths: {+ 'en-US': 'src/i18n/locales/en-US.json',+ 'ar-SA': 'src/i18n/locales/ar-SA.json',+ },+ generatedFiles: ['src/components/LanguageSelector.tsx'],+ managedFiles: [+ 'src/i18n/index.ts',+ 'src/i18n/localeAvailability.ts',+ ],+ unavailableLocales: ['ar-SA'],+ bidirectionalReadiness: {+ status: 'pending-remediation',+ localeReadiness: {+ 'en-US': { status: 'ready' },+ 'ar-SA': { status: 'pending-remediation' },+ },+ findings: [{+ ...recordedFinding,+ scope: 'locale',+ affectedLocales: ['ar-SA'],+ }],+ renderedFindings: [],+ },+ adoptedExistingConfiguration: false,+ lastOperation: 'create',+ updatedAt: '2026-09-03T12:00:00.000Z',+ }));++ const result = runValidator(projectRoot);++ assert.equal(result.status, 0, result.stderr);});diff --git a/plugins/power-pages/scripts/tests/verification-evidence.test.js b/plugins/power-pages/scripts/tests/verification-evidence.test.jsnew file mode 100644index 000000000..e65fd0130--- /dev/null+++ b/plugins/power-pages/scripts/tests/verification-evidence.test.js@@ -0,0 +1,234 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const {+ computeVerificationInputFingerprint,+ createVerificationEvidence,+ validateReusableVerificationReport,+} = require('../lib/verification-evidence');+const { createTempProject, writeProjectFile } = require('./test-utils');++function createProject(t) {+ const root = createTempProject(t);+ writeProjectFile(root, 'package.json', '{"scripts":{"build":"vite build"}}');+ writeProjectFile(root, 'src/App.tsx', 'export const App = () => <main>Hello</main>;');+ writeProjectFile(root, '.powerpages-localization.json', JSON.stringify({+ locales: ['en-US', 'ar-SA'],+ unavailableLocales: [],+ updatedAt: '2026-09-01T00:00:00.000Z',+ bidirectionalReadiness: { status: 'pending-remediation' },+ }));+ return root;+}++function createSuccessfulReport(projectRoot, spec) {+ return {+ summary: {+ cases: 1,+ passed: 1,+ review: 0,+ failed: 0,+ errors: 0,+ reviewFindings: 0,+ },+ findings: [],+ results: [{+ id: 'home--default--desktop--en',+ type: 'component-state',+ status: 'passed',+ findings: [],+ }],+ verification: {+ profile: 'standard',+ evidence: createVerificationEvidence(projectRoot, spec),+ },+ };+}++test('ignores readiness-only manifest changes when fingerprinting build inputs', (t) => {+ const projectRoot = createProject(t);+ const before = computeVerificationInputFingerprint(projectRoot);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ manifest.updatedAt = '2026-09-02T00:00:00.000Z';+ manifest.bidirectionalReadiness = { status: 'ready' };+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));++ assert.equal(computeVerificationInputFingerprint(projectRoot), before);+});++test('availability-neutral fingerprint ignores only locale availability changes', (t) => {+ const projectRoot = createProject(t);+ const manifestPath = path.join(projectRoot, '.powerpages-localization.json');+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ manifest.managedFiles = ['src/i18n/localeAvailability.ts'];+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ 'const hidden = new Set([]);\n'+ );+ const fullBefore = computeVerificationInputFingerprint(projectRoot);+ const neutralBefore = computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ });+ assert.equal(+ createVerificationEvidence(projectRoot, {})+ .inputFingerprintWithoutAvailability,+ neutralBefore+ );++ // Keeping ar-SA unavailable edits only the two availability inputs.+ manifest.unavailableLocales = ['ar-SA'];+ fs.writeFileSync(manifestPath, JSON.stringify(manifest));+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ "const hidden = new Set(['ar-SA']);\n"+ );+ assert.notEqual(computeVerificationInputFingerprint(projectRoot), fullBefore);+ assert.equal(+ computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ }),+ neutralBefore+ );++ writeProjectFile(projectRoot, 'src/App.tsx', 'export const App = null;');+ assert.notEqual(+ computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ }),+ neutralBefore+ );+});++test('availability-neutral fingerprint covers an availability file the manifest does not list', (t) => {+ const projectRoot = createProject(t);+ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ 'const hidden = new Set([]);\n'+ );+ const before = computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ });++ writeProjectFile(+ projectRoot,+ 'src/i18n/localeAvailability.ts',+ "const hidden = new Set(['ar-SA']);\n"+ );++ assert.notEqual(+ computeVerificationInputFingerprint(projectRoot, {+ excludeAvailability: true,+ }),+ before+ );+});++test('invalidates evidence when source or locale availability changes', (t) => {+ const projectRoot = createProject(t);+ const spec = { version: 1 };+ const report = createSuccessfulReport(projectRoot, spec);++ assert.deepEqual(+ validateReusableVerificationReport(projectRoot, report),+ []+ );+ fs.writeFileSync(path.join(projectRoot, 'src/App.tsx'), 'export const App = null;');+ assert.match(+ validateReusableVerificationReport(projectRoot, report).join('\n'),+ /evidence is stale/+ );+});++test('invalidates evidence when any supported Astro config changes', (t) => {+ for (const configName of [+ 'astro.config.js',+ 'astro.config.mjs',+ 'astro.config.ts',+ ]) {+ const projectRoot = createProject(t);+ const configPath = writeProjectFile(+ projectRoot,+ configName,+ "export default { output: 'static' };\n"+ );+ const before = computeVerificationInputFingerprint(projectRoot);++ fs.writeFileSync(+ configPath,+ "export default { output: 'static', trailingSlash: 'always' };\n"+ );++ assert.notEqual(+ computeVerificationInputFingerprint(projectRoot),+ before,+ `${configName} must affect the verification fingerprint`+ );+ }+});++test('reuses only reports from a full standard or extensive run', (t) => {+ const projectRoot = createProject(t);+ const spec = { version: 1, targetCaseIds: ['navigation--open'] };++ for (const profile of ['standard', 'extensive']) {+ const report = createSuccessfulReport(projectRoot, spec);+ report.verification.profile = profile;+ assert.deepEqual(validateReusableVerificationReport(projectRoot, report), []);+ }+ for (const profile of ['targeted', undefined]) {+ const report = createSuccessfulReport(projectRoot, spec);+ report.verification.profile = profile;+ assert.match(+ validateReusableVerificationReport(projectRoot, report).join('\n'),+ /targeted repair evidence cannot be reused/+ );+ }+});++test('rejects failed and unsupported reports', (t) => {+ const projectRoot = createProject(t);+ assert.match(+ validateReusableVerificationReport(projectRoot, {+ summary: { errors: 1, failed: 1 },+ }).join('\n'),+ /failed checks/+ );+});++test('rejects missing or contradictory detailed report evidence', (t) => {+ const projectRoot = createProject(t);+ const spec = { version: 1 };+ const truncated = createSuccessfulReport(projectRoot, spec);+ delete truncated.results;+ assert.match(+ validateReusableVerificationReport(+ projectRoot,+ truncated+ ).join('\n'),+ /must contain detailed results and findings/+ );++ const contradictory = createSuccessfulReport(projectRoot, spec);+ contradictory.results[0].status = 'failed';+ contradictory.findings.push({+ caseId: contradictory.results[0].id,+ rule: 'synthetic-failure',+ severity: 'error',+ message: 'Synthetic failure.',+ selector: 'main',+ });+ const errors = validateReusableVerificationReport(+ projectRoot,+ contradictory+ ).join('\n');+ assert.match(errors, /summary does not match its detailed evidence/);+ assert.match(errors, /contains failed checks/);+});diff --git a/plugins/power-pages/scripts/validate-i18n-package.js b/plugins/power-pages/scripts/validate-i18n-package.jsindex 6d56bc694..92107dde2 100644--- a/plugins/power-pages/scripts/validate-i18n-package.js+++ b/plugins/power-pages/scripts/validate-i18n-package.js@@ -12,6 +12,7 @@ const {LOCALIZATION_CAPABILITIES,MAX_MODE_EVIDENCE_ENTRIES,resolveProjectRelativePath,+ getLocalizationModeAvailability,} = require('./lib/localization-config');const { detectFramework } = require('./lib/framework-detection');const {@@ -574,6 +575,16 @@ function selectFramework(detection, requestedFramework) {return null;}+function validateRequestedMode(framework, mode) {+ const availability = getLocalizationModeAvailability(framework, mode);+ if (!availability.available) {+ const error = new Error(availability.reason);+ error.code = availability.reasonCode;+ throw error;+ }+ return availability;+}+function evaluatePackage(metadata, options) {const { packageName, framework, frameworkVersion, mode, now = new Date() } = options;const version = metadata.version;@@ -919,6 +930,7 @@ async function runCli() {'Cannot validate package because the selected framework is not supported by project evidence.');}+ validateRequestedMode(framework, args.mode);const frameworkPeers =LOCALIZATION_CAPABILITIES.frameworks[framework]?.frameworkPeers || [];const frameworkDependency = frameworkPeers[0];@@ -1101,4 +1113,5 @@ module.exports = {resolvePackage,selectFramework,validateModeEvidenceClassification,+ validateRequestedMode,};diff --git a/plugins/power-pages/scripts/validate-site-integrity.js b/plugins/power-pages/scripts/validate-site-integrity.jsindex 5b008b8a0..0bb68891a 100644--- a/plugins/power-pages/scripts/validate-site-integrity.js+++ b/plugins/power-pages/scripts/validate-site-integrity.js@@ -13,9 +13,46 @@ const {} = require('./lib/site-integrity');const USAGE =- 'Usage: validate-site-integrity.js [--projectRoot <path>]';+ 'Usage: validate-site-integrity.js [--projectRoot <path>] ' ++ '[--skip-localization | --allow-verified-localization-review]';-const parseArgs = (argv) => parseOptionalProjectRootArgs(argv, USAGE);+function parseArgs(argv) {+ let skipLocalization = false;+ let allowVerifiedLocalizationReview = false;+ const remaining = [];+ for (const arg of argv) {+ if (arg === '--skip-localization') {+ if (skipLocalization) {+ throw new Error(+ 'Argument "--skip-localization" may be specified only once.'+ );+ }+ skipLocalization = true;+ } else if (arg === '--allow-verified-localization-review') {+ if (allowVerifiedLocalizationReview) {+ throw new Error(+ 'Argument "--allow-verified-localization-review" may be specified only once.'+ );+ }+ allowVerifiedLocalizationReview = true;+ } else {+ remaining.push(arg);+ }+ }+ // The review exception configures localization validation, so pairing it with+ // a run that skips localization is contradictory and most likely a misuse.+ if (skipLocalization && allowVerifiedLocalizationReview) {+ throw new Error(+ '"--allow-verified-localization-review" cannot be combined with ' ++ `"--skip-localization".\n${USAGE}`+ );+ }+ return {+ ...parseOptionalProjectRootArgs(remaining, USAGE),+ skipLocalization,+ allowVerifiedLocalizationReview,+ };+}function main() {const args = parseArgs(process.argv.slice(2));@@ -26,7 +63,10 @@ function main() {return 0;}- const result = validateSiteIntegrity(projectRoot);+ const result = validateSiteIntegrity(projectRoot, {+ skipLocalization: args.skipLocalization,+ allowVerifiedLocalizationReview: args.allowVerifiedLocalizationReview,+ });if (result.skipped) {process.stdout.write(`[power-pages] Site integrity skipped: ${result.reason}\n`);return 0;diff --git a/plugins/power-pages/skills/add-localization/SKILL.md b/plugins/power-pages/skills/add-localization/SKILL.mdindex ae24ad915..e7e435a15 100644--- a/plugins/power-pages/skills/add-localization/SKILL.md+++ b/plugins/power-pages/skills/add-localization/SKILL.md@@ -30,7 +30,10 @@ site changes.## Core principles- Detect framework and existing localization from project evidence.-- Preserve valid package, mode, default locale, and non-empty translations.+- Read mode availability only from `localization-config.js`; never plan or+ preserve a mode that is currently unavailable.+- Preserve valid available package/mode choices, the default locale, and+ non-empty translations.- Ask questions in the fixed order below; skip only documented conditionalquestions.- Validate language tags and package alternatives with deterministic scripts.@@ -41,13 +44,13 @@ site changes.- Treat `[FROM_CREATE_SITE]` in `$ARGUMENTS` as invocation context. It suppressesthis skill's deploy prompt so create-site remains deployment owner.- Generate a locale coordinator only for React, Vue, and runtime Angular.- Single-language, Angular static, and Astro static sites do not receive it.+ Single-language and dormant static implementations do not receive it.## Workflow1. Detect project and existing localization.2. Gather and validate configuration.-3. Present and approve the implementation plan.+3. Render, open, and approve the implementation plan.4. Configure localization infrastructure.5. Extract and localize content.6. Verify localization independently.@@ -103,6 +106,34 @@ If inspection returns no supported framework and no evidence-backed candidatecan be selected, stop without making changes. Do not use root-document languageattributes from an unsupported project as localization evidence.+After resolving one evidence-backed framework, use the inspection result's+`availability` object. If framework ambiguity required a maker selection, run:++```bash+node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" mode-availability --framework "<SELECTED_FRAMEWORK>"+```++This centralized result is the source of truth for selectable modes.++If `availableModes` is empty, show each centralized temporarily-unavailable+reason and stop without gathering configuration, rendering a plan, installing+dependencies, or editing files. This currently applies to Astro.++If `localization.unavailableModeEvidence` is non-empty, do not offer+add-languages while preserving that evidence, even when the manifest claims an+available mode:++- Angular static: explain that static localization is temporarily unavailable+ and use `AskUserQuestion` with **Reconfigure to Angular runtime localization**+ and **Stop without changes**. Continue only when the maker explicitly selects+ reconfiguration; set `OPERATION=reconfigure`. Phase 2.4 then offers the+ recommended `@jsverse/transloco` package or a validated runtime alternative.+- Any framework with no available alternative: stop without changes and show+ the centralized reason.++Never render a plan for a temporarily unavailable mode. The renderer and final+validator enforce the same registry as a backstop.+When no localization is detected and this is a direct invocation, display:> **Localization scope**@@ -137,6 +168,11 @@ resource paths, and conflicts.<!-- not-a-gate: choosing add/repair/stop selects workflow scope before any write -->+Skip the generic existing-localization question when Phase 1 already forced+`OPERATION=reconfigure` because unavailable mode evidence was detected; the+maker already chose reconfiguration instead of stopping, and add-languages+must not be offered again.+Use `AskUserQuestion`:| Question | Header | Options |@@ -197,14 +233,16 @@ mode, ask only when missing, invalid, conflicting, or explicitly being changed.<!-- not-a-gate: mode selection shapes the upcoming plan and writes nothing -->-- React: runtime; state the decision without asking.-- Vue: runtime; state the decision without asking.-- Angular new setup: use `AskUserQuestion` with **Static locale builds with- @angular/localize (Recommended)** and **Runtime switching with Transloco**.-- Astro: static locale routes; state the decision without asking.-- Add-languages mode: preserve the detected mode without asking.-- Repair mode: ask only when Angular mode is changing or mode evidence- conflicts.+- If `availableModes` contains one mode, select it and state the decision+ without asking.+- If a future registry change exposes multiple modes, use `AskUserQuestion`+ with only those modes and identify `recommendedMode` as recommended.+- Use the selected mode's centralized `recommendedPackage`; do not reconstruct+ framework-specific mode/package mappings in this workflow.+- Add-languages mode: preserve the detected mode without asking only when its+ registry availability is `available`.+- Repair/reconfigure mode: allow only modes listed in+ `availability.availableModes`.### 2.4 Package@@ -216,9 +254,9 @@ For new setup or relevant repair, use `AskUserQuestion`:|---|---|---|| Which localization package should be used? | Package | Framework recommendation (Recommended), Suggest a different package, Cancel |-Skip this question for Astro built-in i18n and add-languages mode. For every-npm-backed package selected during a new setup or repair, including the-framework recommendation and any alternative, run:+Skip this question for add-languages mode or when the selected mode reports+`builtIn: true`. For every npm-backed package selected during a new setup or+repair, including the framework recommendation and any alternative, run:```bashnode "${PLUGIN_ROOT}/scripts/validate-i18n-package.js" --projectRoot "<PROJECT_ROOT>" --framework "<FRAMEWORK>" --package "<PACKAGE>" --version "<VERSION_OR_RANGE>" --mode "<runtime|static>" --telemetryLocales "<CANONICAL_RESULTING_LOCALES>" --telemetryOperation "<create|add-languages|repair|reconfigure>" --telemetryPackageSelection "<recommended|alternative|preserved>"@@ -391,17 +429,58 @@ When this operation first changes an LTR-only or RTL-only site to `mixed`, run:node "${PLUGIN_ROOT}/scripts/audit-bidirectional-readiness.js" --projectRoot "<PROJECT_ROOT>"```-Add every finding to the Phase 3 plan. Include logical-CSS remediation,+The command prints structured JSON and exits nonzero when deterministic errors+exist; parse the JSON even on that expected failure path. Add every finding to+the Phase 3 plan. Include logical-CSS remediation,validated physical exceptions, mixed/user content, localized formatting,script font coverage, directional assets, calendars/date-pickers, gestures,drawers, breadcrumbs, tables, charts, carousels, overlays, SVG/canvas, andthird-party components. Do not modify files before plan approval.+For every localization plan, build `READINESS_DATA.componentScope` from the+existing implementation. Include+every visible or interactive shared or page-local component and classify it as+`direction-neutral`, `direction-aware`, `direction-fixed`, or+`unknown-third-party`. For each entry, record the localized reason, every+applicable state, applicable `desktop`/`narrow` viewports, and planned checks.+Treat anything involving inline placement, text direction, horizontal+movement, sequence, directional meaning, mixed-script content, or rendering+outside the normal component subtree as a potential bidirectional surface.++Treat a form as a compound surface: include its labels, values, placeholders,+hints, helper text, validation messages, prefixes, suffixes, icons, autofill,+select/autocomplete panels, and validation summary when applicable. Include+portals, teleports, overlay containers, Shadow DOM, iframes, and other+third-party open states. This scope is plan data retained in workflow context+and the human-readable HTML; do not persist a separate component-inventory+JSON file.+---## Phase 3: Plan and approve-Present:+Read+`${PLUGIN_ROOT}/skills/add-localization/references/plan-data-contract.md`, then+build and render the localization plan before asking for approval.++### 3.1 Determine the plan language++Render the artifact in the site's current source locale:++- Existing valid localization: the existing pre-change default locale.+- New setup with a valid detected root language: the detected locale.+- New setup with missing/invalid root language: the Phase 2 locale selected to+ represent the existing UI.++Keep that source locale as the plan language even if this operation changes the+resulting default. Resolve its canonical locale and direction with+`localization-config.js`; use them as `SOURCE_LOCALE` and `SOURCE_DIRECTION`.+Do not choose one of the added target locales merely because it is being added.++### 3.2 Build the plan data++Follow the exact contract in `references/plan-data-contract.md`. The artifact+must include:- Framework evidence and invocation context.- Existing setup and conflicts.@@ -416,17 +495,49 @@ Present:- Language-selector placement and runtime/static behavior.- Build, validator, browser, RTL, and token checks.- Direction-set transition, readiness findings, proposed remediations, physical- exceptions, script-font changes, and whether any locale may remain- unavailable pending remediation.+ exceptions, script-font changes, the classified component/state/viewport+ review scope, and whether any locale may remain unavailable pending+ remediation.- Known limitations and any approved translation replacements.-<!-- gate: add-localization:3.plan-approval | category=plan | cancel-leaves=nothing -->+Write maker-facing plan text in `SOURCE_LOCALE`; preserve technical values+unchanged. The renderer rejects malformed locale roles, default/source+inconsistency, invalid actions/statuses, incomplete labels, and incorrect+source direction.++### 3.3 Render and open the plan++Pick an output path under `<PROJECT_ROOT>/docs/`. Use+`add-localization-plan.html` when available; otherwise choose a descriptive+variant such as `add-localization-plan-v2.html`. Never overwrite an earlier+plan.++```bash+node "${PLUGIN_ROOT}/scripts/render-add-localization-plan.js" --output "<PROJECT_ROOT>/docs/add-localization-plan.html" --data-inline '<json-string>'+```++Use `--data-inline` so no plan-data JSON file is persisted. If the command is+too large, use a temporary JSON file with `--data`, then delete that temporary+file after rendering. Capture the renderer's returned output path and open that+exact HTML file in the user's default browser.++The HTML is a durable human-reference artifact only. Do not parse it during+implementation or treat it as workflow state. Before implementation, retain+the approved configuration in context; after implementation,+`.powerpages-localization.json` and the site files are authoritative.++Present a brief terminal summary with the artifact path, source/default/target+locales, package/mode, file counts by action, readiness blockers, unavailable+locales, and known limitations. Keep the terminal approval gate below; the HTML+does not contain an approve button and opening it does not imply approval.++<!-- gate: add-localization:3.plan-approval | category=plan | cancel-leaves=rendered-plan -->> 🚦 **Gate (plan · add-localization:3.plan-approval):** Approves the complete localization delta before dependencies or site files change.>-> **Trigger:** The deterministic plan and file inventory have been presented.+> **Trigger:** The deterministic plan and file inventory have been rendered to `docs/add-localization-plan*.html`, opened in the browser, and summarized in the terminal.> **Why we ask:** A wrong package, mode, default locale, or extraction scope can touch most visible UI files.-> **Cancel leaves:** Nothing — discovery and validation were read-only.+> **Cancel leaves:** The rendered HTML plan remains under `docs/` for reference; no dependencies, site implementation files, or external state changed.Use `AskUserQuestion`:@@ -434,7 +545,9 @@ Use `AskUserQuestion`:|---|---|---|| How should the localization plan proceed? | Plan | Approve and implement (Recommended), Revise configuration, Cancel |-Loop through Phase 2 for revisions. Do not install or edit before approval.+Loop through Phase 2 for revisions. Render revisions to a new descriptive HTML+filename and reopen the latest artifact. Do not install or edit before+approval.After approval, emit the final configuration before Phase 4 changes any files:@@ -509,6 +622,10 @@ or resource hierarchy. In repair mode, apply only the approved delta. Neverremove a package, switch Angular mode, or replace custom initialization unlessthe approved plan names that change.+The Angular static and Astro static implementation guidance remains documented+for future re-enablement, but current runs must never execute those dormant+paths.+For runtime mode, create or adopt exactly one locale coordinator at the pathdefined in the framework reference. The language selector must call`switchLocale`; it must not independently update translations, persistence,@@ -550,8 +667,47 @@ machine values, `Intl` formatting for locale-sensitive data, and script-awarefont profiles only where the configured scripts need them. Preserve brandcharacter across font profiles.-Write `.powerpages-localization.json` using reference schema version 1-after the approved implementation is complete. Record `packageVerification`+For an existing site, this is a targeted bidirectional adaptation rather than+an unrelated visual redesign. Preserve branding, routes, features, and visual+character while replacing direction-specific assumptions. Reconcile the+approved component scope against the files and components actually changed,+adding any visible or interactive surface or state discovered during+implementation.++Localized form labels, placeholders, hints, helper text, validation messages,+prefixes, suffixes, icons, and open menus follow the active UI direction and+use logical alignment. Native free-form inputs and textareas use adaptive+`dir`: active UI direction while empty, `auto` while populated, and active UI+direction again after clearing. Preserve or add `dirname` where submitted+direction metadata is appropriate; do not remove existing mixed-direction+submission metadata.+Machine-oriented email addresses, telephone numbers, URLs, code, paths, GUIDs,+and identifiers may remain LTR only when classified as direction-fixed and+accompanied by the adjacent+`bidi-fixed: <specific reason>; verify=ltr,rtl` directive required by the+shared standard; their surrounding field UI remains direction-aware.+Verify empty, RTL-valued, LTR-valued, clear-after-RTL, and clear-after-LTR+free-form states under both UI directions. Each clear state must first enter+the corresponding non-empty value. Populated direction must follow the entered+value rather than the active locale.++For unknown or third-party components, prefer the package's public locale and+direction API. If none exists, use a documented wrapper or supported theme+override and verify the rendered integration, including body-mounted portals+or overlays. Do not edit `node_modules`. If an externally owned surface cannot+be adapted or verified and the impact is blocking, keep the affected locale+unavailable.++Write `.powerpages-localization.json` using reference schema version 1 before+Phase 6 validation. At this point it is a provisional safety state, not a+readiness claim: set `bidirectionalReadiness.status` to+`pending-remediation`, create one `localeReadiness` entry for every configured+locale, record the current static findings, leave `renderedFindings` empty,+and keep every newly added or otherwise affected locale unavailable until+verification and disposition finish. Mark those locale entries+`pending-remediation`. Preserve the readiness and availability of existing+locales unless current regression evidence shows they are affected. Record+`packageVerification`from the package-validator result. For an alternative verified from officialdocumentation, record `status: verified`, `source: official-documentation`,the accepted URL, requested mode, `classification: supported`, explanation,@@ -582,7 +738,9 @@ For Astro built-in i18n, no npm package-validator result exists. Record}```-For mixed-direction sets, also record `bidirectionalReadiness`. Keep a locale+Record `bidirectionalReadiness` for every new or changed localization setup,+including same-direction sets whose pseudo-opposite audit can still find a+future compatibility defect. Keep a localein `unavailableLocales` when technical blockers remain. It must be excludedfrom selectors, browser auto-detection, alternate-language metadata, andproduction static output. Its resources may remain available in development@@ -590,15 +748,46 @@ for remediation. Generate one managed `localeAvailability` module that exports`isLocaleAvailable`, rejects entries in `unavailableLocales`, and is appliedby every selector, locale switch/detection path, alternate-language metadatagenerator, and static locale output configuration. The manifest alone does not-disable a locale. While readiness is `pending-remediation`, every configured-locale whose direction is opposite to the default locale remains unavailable.-Record each pending scanner finding with its exact `file`, `line`, `rule`, and `message`-so lifecycle validation can defer known work without allowing new regressions.+disable a locale. `unavailableLocales` must exactly match locale entries whose+individual readiness is `pending-remediation`.++Assign every static and rendered finding a `scope` and explicit+`affectedLocales`:++- `locale` for a language-specific problem affecting one locale.+- `direction` for a shared LTR or RTL problem; include every configured locale+ of that direction and record `direction`.+- `shared` for a shared implementation problem affecting an explicitly tested+ subset.+- `global` for a problem affecting every configured locale.++Do not infer that all locales of one direction are affected merely because a+new locale of that direction fails. Regression-test an existing locale when+shared direction-sensitive implementation changed, and include it only when+the evidence shows it is affected. If impact cannot be isolated safely,+include every potentially affected locale. Record each pending scanner finding+with its exact `file`, `line`, `rule`, `message`, and `fingerprint` so lifecycle+validation can defer the same known source item only while all explicitly+affected locales remain unavailable, without allowing a replacement or newly+introduced regression.---## Phase 6: Verify localization+If `.powerpages-localization-verification.json` already exists, treat it as an+interrupted run. Invoke `manage-localization-verification.js --fail`, restore+every recorded target locale to fail-closed `pending-remediation` availability,+and finalize that transaction before beginning another one. The failure command+restores the manifest and the exact managed availability-module snapshot that+the transaction captured before exposure. If that snapshot cannot be used+safely, because its backup is missing or changed or it does not point at the+module the manifest names, `--fail` still restores the manifest but writes no+source file and prints the locales to exclude and the module to edit. Exclude+them there, then finalize; finalization validates that every unavailable locale+is excluded. Never delete or overwrite the transaction or its availability+snapshot to bypass recovery.+Run the independent validator:```bash@@ -608,27 +797,169 @@ Fix all reported errors.If the errors cannot be remediated and the workflow must end, emit failurecompletion with `localization-validation-failed` before stopping.-Run the project's existing build. If the build cannot be remediated, emit-failure completion with `localization-build-failed` before stopping. Start or-reuse its dev server and verify with Playwright:+Before exposing newly added pending locales, begin an exclusive verification+transaction while they are still listed in `unavailableLocales`:++```bash+node "${PLUGIN_ROOT}/scripts/manage-localization-verification.js" \+ --begin \+ --profile standard \+ --projectRoot "<PROJECT_ROOT>" \+ --locales "<NEW_LOCALE[,NEW_LOCALE]>"+```++Then remove only those transaction target locales from `unavailableLocales`+and from the managed availability module. Leave their readiness entries+`pending-remediation` until verification succeeds. This is the only permitted+temporary mismatch: the transaction records the prior fail-closed state,+blocks completion and deployment, and allows the Phase 6 validator to+distinguish deliberate local verification from an accidentally exposed+pending locale. Do not change the availability of any non-target locale.-- Default locale and one target locale.+Run the transaction-aware validator:++```bash+node "${PLUGIN_ROOT}/skills/add-localization/scripts/validate-localization.js" \+ --projectRoot "<PROJECT_ROOT>" \+ --verification+```++Run the project's existing build. If the build cannot be remediated, emit+failure completion with `localization-build-failed` before stopping. Start a+loopback-only dev server. Read+`${PLUGIN_ROOT}/references/rendered-bidirectional-verification.md` and build an+ephemeral run specification from the reconciled `componentScope` and actual+implementation. Do not persist the specification as a component manifest.+Use stable semantic selectors or add focused `data-bidi-id` verification+anchors where necessary.++Set `maxConcurrency: 3` unless project evidence requires a lower value.+Classify each component state as `reload`, `resettable`, or `isolated`.+`reload` is the safe default. Use `resettable` only when the specification can+provide deterministic `reset` actions that restore the same baseline while+preserving route, locale, localized content, and unavailable-locale+boundaries. Use `isolated` for authentication, destructive submission,+reload-sensitive initialization, or global state. Grouping then reuses one+page per route/viewport/locale, and independent groups run concurrently;+runtime transition sequences remain serial.++Reuse the project's Playwright dependency. If neither `playwright` nor+`playwright-core` is installed, add `playwright` as a development dependency;+do not download a separate bundled browser when a supported system browser is+available.++Set `verificationProfile: "standard"`. The specification must include every+currently available real locale, including every transaction target, because+each receives a locale smoke check. Exclude pre-existing unavailable locales+from activation and list them in `unavailableLocaleChecks` with every selector+surface that must remain hidden. The CLI reconciles both sets with+`.powerpages-localization.json`.++Select one representative LTR locale and one representative RTL locale for+the component matrix. Prefer newly added real locales, then the target with+the greatest measured text expansion, then the default/existing locale. Use a+pseudo direction only when no real locale exists. Record optional+`textExpansion` ratios and any explicit `representativeLocaleIds` override in+the temporary specification. The specification must cover:++- The default locale and every newly added locale independently.+- Application-driven activation plus representative localized-content+ assertions for every real locale; `set-document` is pseudo-only.- Selector behavior or equivalent static locale navigation.- Representative translated content.- `html[lang]` and `html[dir]`.- Browser console has no localization errors.- One RTL locale when configured.-- Every representative route in one LTR and one RTL locale at desktop and- narrow/mobile viewports when the configured set is mixed.+- Every representative route in the selected LTR and RTL locales.+- Risk-based component coverage. Direction-neutral components default to low+ risk and use the primary state/viewport. Direction-aware components default+ to medium risk and use all applicable states/viewports in both directions.+ Direction-fixed and unknown/third-party components default to high risk and+ use all applicable states/viewports in both directions, including supported+ open states and out-of-subtree overlays. Escalate uncertain components; do+ not lower risk merely to reduce the matrix.- Script font loading, mixed-direction names/comments/URLs/identifiers,locale-aware dates/numbers/percentages, directional icons, calendars, andany audited complex component.+- Existing locales on every shared or direction-sensitive surface changed by+ this operation, so a regression is assigned only to locales proven affected.++Use real configured locales for both directions when the resulting locale set+is mixed. For a same-direction set, add a browser-only pseudo-opposite locale+so this localization change cannot introduce a future LTR/RTL regression.++For static modes, verify equivalent locale URLs/builds. For runtime modes, set+`runtimeSwitching: true`, set `defaultLocaleId`, include default -> locale ->+default for every real non-default locale, and include locale -> default ->+locale for the representative real locales. Extensive verification adds the+reverse sequence for every real non-default locale. Do not require every+possible locale pair, and do not use pseudo locales for application-switch+transitions. Preserve route, form state, focus, and application state without+page reload. Use bare `preserve`+selectors only for form controls; declare text, attribute, or property+preservation evidence for tabs, panels, counters, and other non-form state.+Every real locale, including the default, needs a reusable application+activation action. Do not use `use-current` for a real runtime locale because+the round trip must be able to restore it after switching away.+Separately verify persisted selection, browser-language matching, invalid+saved-value fallback, and that stale resource requests cannot overwrite a+newer selection.++Activate every transaction target through the site's real selector or+locale-navigation control using one locale-bound `activate-locale` action with+`method: click` or `method: select`. Allow only optional waits beside that+action. Do not add an exported bypass, test-only locale function, or arbitrary+browser JavaScript. The target is locally available only while the transaction+blocks completion and deployment.+Pre-existing unavailable locales remain excluded from selector, switching,+detection, metadata, and production output, and their selectors are checked+through `unavailableLocaleChecks`.-For static modes, verify equivalent locale URLs/builds. For runtime modes,-verify persisted selection, browser-language matching, invalid saved-value-fallback, no page reload, and both LTR -> RTL -> LTR and RTL -> LTR -> RTL-round trips. Preserve route, form state, focus, and application state. Verify-that stale resource requests cannot overwrite a newer selection.+Run:++```bash+node "${PLUGIN_ROOT}/scripts/audit-rendered-bidirectional-readiness.js" \+ --url "<DEV_SERVER_URL>" \+ --projectRoot "<PROJECT_ROOT>" \+ --spec "<TEMP_SPEC_PATH>" \+ --evidence-dir "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>" \+ --output "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>/report.json"+```++Parse stdout even when the expected blocking exit code is `1`. Exit code `2`+means the runner or specification failed. Either outcome moves the transaction+to `remediation-required` and automatically restores each target to+`unavailableLocales`, `pending-remediation`, and the captured managed+availability module before retrying. If the snapshot cannot be used safely, the+command instead reports the locales to exclude manually before finalization.+Delete the temporary specification after the report is written. A blocking+error fails the new-locale transaction and restores fail-closed availability;+after fixing it, begin a new standard transaction because targeted evidence+alone cannot approve a new locale. For repair or reconfiguration of already+available locales, rerun affected cases with+`verificationProfile: "targeted"` and exact `targetCaseIds` instead of an+unchanged full matrix. Give every review finding explicit evidence and a+proposed disposition for the Phase 7 maker decision.++Re-run the static audit after remediation and reconcile its exact current+findings with the rendered report. Update each locale's provisional readiness before Phase 7, then derive the+overall status: any pending locale makes the overall status+`pending-remediation`; otherwise any locale approved with limitations makes it+`approved-with-limitations`; otherwise it is `ready`.++- With any static or rendered error, retain the unresolved finding and mark+ every locale in its `affectedLocales` as `pending-remediation`.+- With review findings but no errors, keep each affected locale+ `pending-remediation` until the maker disposes every review item.+- For a locale with no unresolved findings, set its entry to `ready`. Remove it+ from `unavailableLocales` and update every managed availability boundary.+- Do not change an existing ready locale merely because another locale remains+ pending.++A known usable limitation may become `approved-with-limitations` only after+maker approval in Phase 7. A visible opaque third-party surface, unreadable or+clipped text, incorrect direction, unreachable control, broken focus order,+or state-losing locale switch cannot be approved as ready.For an explicitly unverified package, all build, initialization, switching orroute navigation, resource loading, `lang`/`dir`, and console checks are@@ -644,9 +975,15 @@ After localization implementation, the localization validator, the build, and brare complete, run:```bash-node "${PLUGIN_ROOT}/scripts/validate-site-integrity.js" --projectRoot "<PROJECT_ROOT>"+node "${PLUGIN_ROOT}/scripts/validate-site-integrity.js" --projectRoot "<PROJECT_ROOT>" --allow-verified-localization-review```+This gate runs before the Phase 7 maker decision, so+`--allow-verified-localization-review` lets it accept a `verified` transaction+whose evidence is still current while its targets await review. Use the flag+only here: every other integrity run, including deployment, omits it so any+remaining transaction blocks completion and deployment until it is finalized.+Fix every blocking error before reviewing or completing the skill. If theblocking errors cannot be remediated, emit failure completion with`site-integrity-validation-failed` before stopping. Inspect and report review@@ -660,9 +997,18 @@ any subsequent source change.Present files as **Created**, **Updated**, **Preserved**, or **Skipped**, eachwith a one-line reason. Include locale/key counts, blank/stale values,translation warning, build result, browser checks, and RTL areas needing-manual visual review.--Classify the result as:+manual visual review. Present the reconciled component scope with each+classification and the applicable states/viewports exercised. The+pre-implementation plan is scope, not evidence; report the implementation and+rendered checks that satisfied each direction-aware, direction-fixed, and+unknown/third-party entry.+Include the rendered report path, passed/review/failed case totals, and+failure/review screenshots. State the verification profile, representative+LTR/RTL locales, locale-smoke count, component-case count, and generated+manual-review checklist. The run specification is temporary workflow input,+not a new project inventory.++Classify each newly added or regression-tested locale as:- **Ready** — the new locale may be enabled.- **Approved with limitations** — only usable degradation remains; show the@@ -671,6 +1017,37 @@ Classify the result as:unreadable text, unreachable critical controls, or serious accessibilityfailure remains; keep the affected locale unavailable.+<!-- not-a-gate: verification-depth selection configures evidence collection within the already approved implementation scope -->+After standard verification passes, always offer the verification-depth+choice before transaction finalization. When the report contains manual-review+items for high-risk components in non-representative locales, first show each+locale, route, component, states, and viewports. Use `AskUserQuestion` with:++- **Continue with standard verification (Recommended)** — when a manual+ checklist exists, require the maker to confirm that they completed it and+ checked translated labels/values, expansion, formatting, clipping, and+ usability.+- **Run extensive automated verification** — first return each transaction+ target's provisional readiness entry to `pending-remediation`; keep it+ exposed only because the transaction still blocks completion and+ deployment. Then invoke:++```bash+node "${PLUGIN_ROOT}/scripts/manage-localization-verification.js" \+ --extend --profile extensive --projectRoot "<PROJECT_ROOT>"+```++Then rebuild the temporary specification with+`verificationProfile: "extensive"` and rerun the rendered audit. Extensive+verification covers every declared locale, component, state, and viewport and+requires both runtime round trips for every real non-default locale. Any+extensive error returns the transaction to fail-closed remediation.++In repair or reconfiguration mode, use targeted verification for a known+affected case set, standard verification for normal completion, and extensive+verification only when the maker explicitly requests the full regression+matrix. Targeted verification alone cannot approve a newly added locale.+<!-- gate: add-localization:7.review | category=plan | cancel-leaves=localized-site-files -->> 🚦 **Gate (plan · add-localization:7.review):** Maker accepts the verified localization result or requests a focused revision.@@ -690,8 +1067,62 @@ Use `AskUserQuestion`:Explicit acceptance applies only to usable degradation. It cannot override abuild/runtime failure, incorrect direction, unreadable content, unreachablecritical control, or serious accessibility failure. Apply requested revisions,-then repeat Phase 6 and this gate. If the maker saves a pending locale, do not-offer deployment in Phase 8.+then repeat Phase 6 and this gate. Before repeating after a verified or failed+run, invoke `manage-localization-verification.js --fail`, restore every target+to pending unavailable state, finalize the old transaction, and begin a new+transaction. Each rendered run must have its own fail-closed starting point and+cannot reuse a prior verified result.++After the maker's choice, finalize `.powerpages-localization.json`:++- **Accept changes:** set the reviewed locale entries to `ready` and remove+ findings that affected only those locales.+- **Enable with documented limitations:** retain only the accepted+ review-severity findings, set each affected locale entry to+ `approved-with-limitations`, remove those locales from+ `unavailableLocales`, and add a `disposition` to every retained finding with+ `status: maker-approved`, the exact component/page impact, the report or+ screenshot evidence path, and an ISO `approvedAt` timestamp. Accepted review+ checks that are not limitations are removed from the unresolved finding+ arrays.+- **Save but keep locale unavailable:** keep the affected locale entries+ `pending-remediation`, retain the undisposed findings, and return only those+ affected locales to `unavailableLocales` and the managed availability module.+ The choice is per locale: in the same finalization, other targets can still+ be accepted or enabled with documented limitations.++Never add a maker-approved disposition to an error finding. After changing+status or availability, finalize the transaction:++```bash+node "${PLUGIN_ROOT}/scripts/manage-localization-verification.js" \+ --finalize \+ [--manual-review-completed] \+ [--rendered-review-completed] \+ --projectRoot "<PROJECT_ROOT>"+```++Pass `--manual-review-completed` only after the maker chose that standard-path+option and completed the generated checklist. Pass+`--rendered-review-completed` when the successful browser report contained+review findings that the maker inspected and accepted as resolved checks rather+than retained limitations. A retained limitation instead remains in+`renderedFindings` with its maker-approved disposition and does not require this+flag. Extensive runs do not use `--manual-review-completed`, but may require+`--rendered-review-completed`.+A target kept unavailable needs no `--fail`, extra flag, or new browser run:+finalization accepts it when locale availability is the only input that changed+since the successful audit. Any other source, resource, dependency, or build+configuration change still requires a new audit.+Finalization succeeds only when the normal manifest invariant and all+localization checks pass. Rebuild only when source, resources, dependencies,+build configuration, or locale availability changed after the successful+build; readiness status and finding-disposition metadata alone do not require+another build. Rerun only locale activation cases affected by final+availability changes. Do not complete the workflow until the transaction file+is gone and the final manifest, selector/detection boundaries, and actual+rendered availability agree. If the maker saves a pending locale, do not offer+deployment in Phase 8.---@@ -701,6 +1132,12 @@ offer deployment in Phase 8.Record usage with skill name `AddLocalization`.+Present a final localization summary before returning or offering deployment.+Include the final readiness status, available and unavailable locales, static+and rendered finding totals, the rendered report path, every maker-approved+limitation with its impact/evidence, and the manifest path. Do not describe a+locale as enabled when it remains in `unavailableLocales`.+After usage is recorded, emit completion telemetry. This command runs onlyafter implementation, validation, build, browser verification, and makerreview are complete:diff --git a/plugins/power-pages/skills/add-localization/assets/add-localization-plan.html b/plugins/power-pages/skills/add-localization/assets/add-localization-plan.htmlnew file mode 100644index 000000000..56eb22bdd--- /dev/null+++ b/plugins/power-pages/skills/add-localization/assets/add-localization-plan.html@@ -0,0 +1,180 @@+<!DOCTYPE html>+<html lang="__SOURCE_LOCALE__" dir="__SOURCE_DIRECTION__">+<head>+<meta charset="UTF-8"/>+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>+<title>__PLAN_TITLE__ - __SITE_NAME__</title>+<style>+:root{+ --bg:#faf9f8;--surface:#fff;--surface2:#f3f2f1;--border:#e1dfdd;--text:#323130;+ --text-dim:#605e5c;--text-bright:#201f1e;--accent:#0078d4;--accent-bg:#0078d40a;+ --accent-border:#0078d425;--pass:#107c10;--pass-bg:#107c100a;--warn:#ca5010;+ --warn-bg:#ca50100a;--purple:#8764b8;--purple-bg:#8764b80a;+ --mono:'Cascadia Code','Consolas',monospace;+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;+ --radius:8px;--shadow:0 1.6px 3.6px rgba(0,0,0,.132),0 .3px .9px rgba(0,0,0,.108);+}+*{box-sizing:border-box;margin:0;padding:0}+body{background:var(--bg);color:var(--text);font:14px/1.6 var(--sans)}+.topbar{position:sticky;inset-block-start:0;z-index:10;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 28px;background:var(--surface);box-shadow:var(--shadow)}+.topbar-main{display:flex;align-items:center;gap:14px}.logo{width:36px;height:36px;object-fit:contain}+.topbar-title{font-weight:700;color:var(--text-bright)}.topbar-sub{font-size:11px;color:var(--text-dim)}+.pill{display:inline-flex;padding:3px 9px;border:1px solid var(--accent-border);border-radius:999px;background:var(--accent-bg);color:var(--accent);font-size:11px;font-weight:600}+.layout{display:flex;min-height:calc(100vh - 65px)}.sidebar{flex:0 0 230px;padding:20px 0;background:var(--surface);border-inline-end:1px solid var(--border)}+.nav-group{padding:14px 22px 6px;color:var(--text-dim);font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;border:0;border-inline-start:2px solid transparent;background:transparent;color:var(--text-dim);font:500 13px var(--sans);text-align:start;cursor:pointer}+.nav-btn:hover{background:var(--surface2);color:var(--text)}.nav-btn.active{border-inline-start-color:var(--accent);background:var(--accent-bg);color:var(--accent);font-weight:700}+.content{flex:1;max-width:1080px;padding:32px 40px 72px}.section{display:none}.section.active{display:block}+h2{color:var(--text-bright);font-size:21px;margin-block-end:5px}.section-desc{color:var(--text-dim);font-size:13px;margin-block-end:20px}+h3{color:var(--text-bright);font-size:15px;margin-block:24px 12px}.summary{padding:20px 22px;border:1px solid var(--border);border-radius:12px;background:var(--surface);line-height:1.75}+.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.card{padding:16px 18px;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);box-shadow:var(--shadow)}+.field-label{color:var(--text-dim);font-size:10px;font-weight:700;letter-spacing:.5px;text-transform:uppercase}.field-value{margin-block-start:4px;color:var(--text-bright);font-weight:700}.field-desc{margin-block-start:4px;color:var(--text-dim);font-size:12px}+.status{display:inline-flex;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:700;text-transform:uppercase}.status-new,.status-create,.status-added{background:var(--accent-bg);color:var(--accent)}.status-preserved,.status-preserve,.status-existing,.status-available,.status-verified{background:var(--pass-bg);color:var(--pass)}.status-changed,.status-update,.status-replace,.status-pending-remediation,.status-unverified{background:var(--warn-bg);color:var(--warn)}.status-skip,.status-source,.status-default{background:var(--purple-bg);color:var(--purple)}+.config-head{display:flex;justify-content:space-between;gap:10px;align-items:flex-start}.mono{font-family:var(--mono);direction:ltr;unicode-bidi:isolate;word-break:break-word}+.locale-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:12px}.locale-card{padding:16px 18px;border:1px solid var(--border);border-block-start:3px solid var(--accent);border-radius:var(--radius);background:var(--surface);box-shadow:var(--shadow)}+.locale-name{font-weight:700;color:var(--text-bright)}.locale-code{margin-block:4px 10px;color:var(--accent);font:700 13px var(--mono);direction:ltr;unicode-bidi:isolate}.chip-row{display:flex;gap:5px;flex-wrap:wrap;margin-block-start:8px}+.table-wrap{overflow:auto;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface)}table{width:100%;border-collapse:collapse}th,td{padding:11px 14px;border-block-end:1px solid var(--border);text-align:start;vertical-align:top}th{background:var(--surface2);color:var(--text-dim);font-size:10px;text-transform:uppercase}tr:last-child td{border-block-end:0}+.finding{padding:16px 18px;border:1px solid var(--border);border-inline-start:3px solid var(--warn);border-radius:var(--radius);background:var(--surface);margin-block-end:10px}.finding.review{border-inline-start-color:var(--purple)}.finding-title{display:flex;justify-content:space-between;gap:10px;font-weight:700}.finding-meta{margin-block-start:4px;color:var(--text-dim);font-size:11px}.finding-body{margin-block-start:8px;font-size:13px}.finding-remediation{margin-block-start:8px;padding:8px 10px;background:var(--surface2);border-radius:4px;font-size:12px}+.scope-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px}.scope-card{padding:16px 18px;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);box-shadow:var(--shadow)}.scope-head{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;flex-wrap:wrap}.scope-name{font-weight:700;color:var(--text-bright)}.scope-meta{margin-block-start:10px}.scope-chips{display:flex;gap:5px;flex-wrap:wrap;margin-block-start:5px}+.list{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface)}.list-item{display:flex;gap:10px;padding:12px 16px;border-block-end:1px solid var(--border)}.list-item:last-child{border-block-end:0}.list-mark{color:var(--accent);font-weight:700}.empty{padding:14px 16px;color:var(--text-dim);font-style:italic}+.warning{margin-block-start:12px;padding:12px 14px;border:1px solid #ca501025;border-radius:var(--radius);background:var(--warn-bg);color:var(--text)}+a{color:var(--accent)}footer{position:fixed;inset-block-end:0;inset-inline:0;padding:9px;text-align:center;background:var(--surface);border-block-start:1px solid var(--border);color:var(--text-dim);font-size:11px}+@media(max-width:800px){.layout{display:block}.sidebar{display:flex;flex-wrap:wrap;border-inline-end:0;border-block-end:1px solid var(--border);padding:8px}.nav-group{width:100%}.nav-btn{width:auto;border-inline-start:0;border-block-end:2px solid transparent}.nav-btn.active{border-inline-start:0;border-block-end-color:var(--accent)}.content{padding:20px 16px 72px}.grid{grid-template-columns:1fr}}+</style>+</head>+<body>+<header class="topbar">+ <div class="topbar-main">+ <img class="logo" src="./power-pages-icon.png" alt="Power Pages"/>+ <div>+ <div class="topbar-title">__PLAN_TITLE__</div>+ <div class="topbar-sub"><bdi dir="auto">__SITE_NAME__</bdi> · <span>__SOURCE_LANGUAGE__</span> <bdi dir="ltr">(__SOURCE_LOCALE__)</bdi></div>+ </div>+ </div>+ <bdi class="pill" dir="ltr">__FRAMEWORK__</bdi>+</header>+<div class="layout">+ <nav class="sidebar">+ <div class="nav-group" data-label="navigation.group"></div>+ <button class="nav-btn active" data-tab="overview"><span>◉</span><span data-label="navigation.overview"></span></button>+ <button class="nav-btn" data-tab="languages"><span>文</span><span data-label="navigation.languages"></span></button>+ <button class="nav-btn" data-tab="changes"><span>▦</span><span data-label="navigation.changes"></span></button>+ <button class="nav-btn" data-tab="readiness"><span>↔</span><span data-label="navigation.readiness"></span></button>+ <button class="nav-btn" data-tab="verification"><span>✓</span><span data-label="navigation.verification"></span></button>+ </nav>+ <main class="content">+ <section class="section active" id="tab-overview">+ <h2 data-label="overview.title"></h2>+ <p class="section-desc" id="overviewDescription"></p>+ <div class="summary" id="summary"></div>+ <div class="grid" id="overviewGrid" style="margin-block-start:14px"></div>+ <div class="grid">+ <div><h3 data-label="overview.frameworkEvidence"></h3><div class="list" id="frameworkEvidence"></div></div>+ <div><h3 data-label="overview.existingDetails"></h3><div class="list" id="existingDetails"></div></div>+ </div>+ <h3 data-label="overview.conflicts"></h3><div class="list" id="conflicts"></div>+ <h3 data-label="overview.configuration"></h3>+ <div class="grid" id="configurationGrid"></div>+ <div id="rootRepair"></div>+ </section>+ <section class="section" id="tab-languages">+ <h2 data-label="languages.title"></h2>+ <p class="section-desc" data-label="languages.description"></p>+ <div class="locale-grid" id="localesGrid"></div>+ </section>+ <section class="section" id="tab-changes">+ <h2 data-label="changes.title"></h2>+ <p class="section-desc" data-label="changes.description"></p>+ <div class="table-wrap"><table><thead><tr>+ <th data-label="changes.path"></th><th data-label="changes.action"></th><th data-label="changes.reason"></th>+ </tr></thead><tbody id="filesBody"></tbody></table></div>+ </section>+ <section class="section" id="tab-readiness">+ <h2 data-label="readiness.title"></h2>+ <p class="section-desc" data-label="readiness.description"></p>+ <div class="card"><div class="field-label" data-label="readiness.transition"></div><div class="field-value" id="directionTransition"></div></div>+ <h3 data-label="readiness.findings"></h3><div id="findings"></div>+ <h3 data-label="readiness.componentScope"></h3><div class="scope-grid" id="componentScope"></div>+ <div class="grid">+ <div><h3 data-label="readiness.physicalExceptions"></h3><div class="list" id="physicalExceptions"></div></div>+ <div><h3 data-label="readiness.scriptFonts"></h3><div class="list" id="scriptFonts"></div></div>+ </div>+ <h3 data-label="readiness.unavailableLocales"></h3><div class="list" id="unavailableLocales"></div>+ </section>+ <section class="section" id="tab-verification">+ <h2 data-label="verification.title"></h2>+ <p class="section-desc" data-label="verification.description"></p>+ <h3 data-label="verification.checks"></h3><div class="list" id="validationChecks"></div>+ <h3 data-label="verification.limitations"></h3><div class="list" id="limitations"></div>+ </section>+ </main>+</div>+<footer data-label="footer.aiWarning"></footer>+<script id="siteNameData" type="application/json">__SITE_NAME_DATA__</script>+<script id="summaryData" type="application/json">__SUMMARY_DATA__</script>+<script id="metaData" type="application/json">__META_DATA__</script>+<script id="labelsData" type="application/json">__PLAN_LABELS__</script>+<script id="discoveryData" type="application/json">__DISCOVERY_DATA__</script>+<script id="configData" type="application/json">__CONFIGURATION_DATA__</script>+<script id="localesData" type="application/json">__LOCALES_DATA__</script>+<script id="filesData" type="application/json">__FILES_DATA__</script>+<script id="readinessData" type="application/json">__READINESS_DATA__</script>+<script id="validationData" type="application/json">__VALIDATION_DATA__</script>+<script id="limitationsData" type="application/json">__LIMITATIONS_DATA__</script>+<script>+function readData(id){return JSON.parse(document.getElementById(id).textContent)}+function esc(value){const node=document.createElement('div');node.textContent=value==null?'':String(value);return node.innerHTML}+const LABELS=readData('labelsData'),CONFIG=readData('configData'),LOCALES=readData('localesData');+const FILES=readData('filesData'),READINESS=readData('readinessData'),VALIDATION=readData('validationData'),LIMITATIONS=readData('limitationsData');+const META=readData('metaData'),DISCOVERY=readData('discoveryData');+function label(path){return path.split('.').reduce((value,key)=>value&&value[key],LABELS)||path}+function status(value){return label('status.'+String(value).replace(/-([a-z])/g,(_,c)=>c.toUpperCase()))}+function list(containerId,items,emptyLabel,technical){+ const node=document.getElementById(containerId);+ node.innerHTML=items.length?items.map(item=>'<div class="list-item"><span class="list-mark">✓</span><div'+(technical?' class="mono"':'')+'>'+esc(item)+'</div></div>').join(''):'<div class="empty">'+esc(label(emptyLabel))+'</div>';+}+document.querySelectorAll('[data-label]').forEach(node=>{node.textContent=label(node.dataset.label)});+document.querySelectorAll('.nav-btn').forEach(button=>button.addEventListener('click',()=>{+ document.querySelectorAll('.nav-btn').forEach(item=>item.classList.remove('active'));+ document.querySelectorAll('.section').forEach(item=>item.classList.remove('active'));+ button.classList.add('active');document.getElementById('tab-'+button.dataset.tab).classList.add('active');+}));+const overview=document.getElementById('overviewDescription'),parts=label('overview.description').split('{siteName}');+overview.append(document.createTextNode(parts[0]));const siteName=document.createElement('bdi');siteName.dir='auto';siteName.textContent=readData('siteNameData').text;overview.append(siteName);overview.append(document.createTextNode(parts.slice(1).join('{siteName}')));+document.getElementById('summary').textContent=readData('summaryData').text;+const overviewItems=[+ [label('overview.framework'),META.framework,true],+ [label('overview.invocation'),label('invocation.'+(META.invocationContext==='create-site'?'createSite':'direct'))],+ [label('overview.operation'),label('operation.'+({'add-languages':'addLanguages'}[META.operation]||META.operation))],+ [label('overview.existingSetup'),label('status.'+(META.existingLocalizationDetected?'yes':'no'))]+];+document.getElementById('overviewGrid').innerHTML=overviewItems.map(item=>'<div class="card"><div class="field-label">'+esc(item[0])+'</div><div class="field-value'+(item[2]?' mono':'')+'">'+esc(item[1])+'</div></div>').join('');+list('frameworkEvidence',DISCOVERY.frameworkEvidence,'readiness.none');+list('existingDetails',DISCOVERY.existingSetup,'readiness.none');+list('conflicts',DISCOVERY.conflicts,'overview.noConflicts');+function configCard(labelPath,item,extra,technical,showStatus){+ return '<div class="card"><div class="config-head"><div><div class="field-label">'+esc(label(labelPath))+'</div><div class="field-value'+(technical?' mono':'')+'">'+esc(item.value)+'</div></div>'+(showStatus?'<span class="status status-'+item.status+'">'+esc(status(item.status))+'</span>':'')+'</div>'+(item.description?'<div class="field-desc">'+esc(item.description)+'</div>':'')+(extra||'')+'</div>';+}+let packageExtra='<div class="field-desc"><strong>'+esc(label('configuration.verification'))+':</strong> '+esc(status(CONFIG.package.verification))+'</div>';+packageExtra+='<div class="field-desc"><strong>'+esc(label('configuration.selection'))+':</strong> '+esc(label('packageSelection.'+CONFIG.package.selection))+'</div>';+packageExtra+='<div class="field-desc"><strong>'+esc(label('configuration.evidenceSource'))+':</strong> '+esc(label('evidenceSource.'+CONFIG.package.evidenceSource.replace(/-([a-z])/g,(_,c)=>c.toUpperCase())))+'</div>';+if(CONFIG.package.evidenceUrl)packageExtra+='<div class="field-desc"><strong>'+esc(label('configuration.evidence'))+':</strong> <span class="mono">'+esc(CONFIG.package.evidenceUrl)+'</span></div>';+if(CONFIG.package.initializationEvidence)packageExtra+='<div class="field-desc"><strong>'+esc(label('configuration.initialization'))+':</strong> <span class="mono">'+esc(CONFIG.package.initializationEvidence.file)+' · '+esc(CONFIG.package.initializationEvidence.marker)+'</span></div>';+document.getElementById('configurationGrid').innerHTML=+ configCard('configuration.package',CONFIG.package,packageExtra,true,true)+configCard('configuration.mode',CONFIG.mode,'',true,true)+configCard('configuration.defaultLocale',CONFIG.defaultLocale,'',true,true)+configCard('configuration.translation',CONFIG.translation,'',false,false)+configCard('configuration.selector',CONFIG.selector,'',false,false);+if(CONFIG.translation.warning)document.getElementById('configurationGrid').insertAdjacentHTML('afterend','<div class="warning">'+esc(CONFIG.translation.warning)+'</div>');+if(CONFIG.rootDocumentRepair){const repair=CONFIG.rootDocumentRepair;document.getElementById('rootRepair').innerHTML='<h3>'+esc(label('configuration.rootRepair'))+'</h3><div class="card mono">'+esc(repair.file)+' · lang="'+esc(repair.lang)+'" dir="'+esc(repair.dir)+'"</div>'}+document.getElementById('localesGrid').innerHTML=LOCALES.map(locale=>'<div class="locale-card"><div class="locale-name">'+esc(locale.language)+'</div><div class="locale-code">'+esc(locale.locale)+'</div><div class="field-desc">'+esc(label('languages.direction'))+': <bdi dir="ltr">'+esc(locale.direction)+'</bdi></div><div class="chip-row">'+locale.roles.map(role=>'<span class="status status-'+esc(role)+'">'+esc(status(role))+'</span>').join('')+'<span class="status status-'+esc(locale.availability)+'">'+esc(status(locale.availability))+'</span></div></div>').join('');+document.getElementById('filesBody').innerHTML=FILES.map(file=>'<tr><td class="mono">'+esc(file.path)+'</td><td><span class="status status-'+esc(file.action)+'">'+esc(status(file.action))+'</span></td><td>'+esc(file.reason)+'</td></tr>').join('');+document.getElementById('directionTransition').textContent=READINESS.transition;+document.getElementById('findings').innerHTML=READINESS.findings.length?READINESS.findings.map(finding=>'<article class="finding '+(finding.severity==='review'?'review':'')+'"><div class="finding-title"><span>'+esc(finding.message)+'</span><span class="status status-'+esc(finding.severity==='review'?'pending-remediation':'changed')+'">'+esc(label('severity.'+finding.severity))+'</span></div><div class="finding-meta"><span class="mono">'+esc(finding.file)+(finding.line?' · '+esc(finding.line):'')+'</span> · '+esc(label('readiness.rule'))+': <span class="mono">'+esc(finding.rule)+'</span> · '+esc(label('readiness.scope'))+': <span class="mono">'+esc(finding.scope)+'</span> · '+esc(label('readiness.affectedLocales'))+': <span class="mono">'+esc((finding.affectedLocales||[]).join(', '))+'</span></div>'+(finding.remediation?'<div class="finding-remediation"><strong>'+esc(label('readiness.remediation'))+':</strong> '+esc(finding.remediation)+'</div>':'')+'</article>').join(''):'<div class="empty">'+esc(label('readiness.noFindings'))+'</div>';+const classificationLabels={'direction-neutral':'directionNeutral','direction-aware':'directionAware','direction-fixed':'directionFixed','unknown-third-party':'unknownThirdParty'};+document.getElementById('componentScope').innerHTML=READINESS.componentScope.map(item=>'<article class="scope-card"><div class="scope-head"><div class="scope-name">'+esc(item.component)+'</div><span class="status status-existing">'+esc(label('classification.'+classificationLabels[item.classification]))+'</span></div><div class="field-desc"><strong>'+esc(label('readiness.reason'))+':</strong> '+esc(item.reason)+'</div><div class="scope-meta"><div class="field-label">'+esc(label('readiness.states'))+'</div><div class="scope-chips">'+item.states.map(value=>'<span class="status status-source">'+esc(value)+'</span>').join('')+'</div></div><div class="scope-meta"><div class="field-label">'+esc(label('readiness.viewports'))+'</div><div class="scope-chips">'+item.viewports.map(value=>'<span class="status status-default">'+esc(label('viewport.'+value))+'</span>').join('')+'</div></div><div class="scope-meta"><div class="field-label">'+esc(label('readiness.checks'))+'</div><div class="list">'+item.checks.map(value=>'<div class="list-item"><span class="list-mark">✓</span><div>'+esc(value)+'</div></div>').join('')+'</div></div></article>').join('');+list('physicalExceptions',READINESS.physicalExceptions,'readiness.none');+list('scriptFonts',READINESS.scriptFonts,'readiness.none');+list('unavailableLocales',READINESS.unavailableLocales,'readiness.none',true);+list('validationChecks',VALIDATION.map(item=>item.description),'readiness.none');+list('limitations',LIMITATIONS,'verification.noLimitations');+</script>+</body>+</html>diff --git a/plugins/power-pages/skills/add-localization/references/plan-data-contract.md b/plugins/power-pages/skills/add-localization/references/plan-data-contract.mdnew file mode 100644index 000000000..4e6a207f1--- /dev/null+++ b/plugins/power-pages/skills/add-localization/references/plan-data-contract.md@@ -0,0 +1,463 @@+# Add-localization plan data contract++Use this contract when Phase 3 renders `docs/add-localization-plan.html`.++## Presentation language++Render the artifact in the site's **current source locale**:++- Existing valid localization: use the existing pre-change `defaultLocale`.+- New localization with a valid root document language: use that detected+ locale.+- New localization with a missing or invalid root language: use the locale the+ maker selected in Phase 2 to represent the existing UI.++The source locale remains the plan language even when a repair/reconfigure+operation changes the resulting default locale. A target locale must never be+chosen merely because it is being added.++Set `SOURCE_LOCALE` to the canonical BCP-47 tag and `SOURCE_DIRECTION` to its+resolved `ltr` or `rtl` direction. Write `PLAN_TITLE`, `SUMMARY`,+`PLAN_LABELS`, reasons, descriptions, findings, remediations, checks, and+limitations in `SOURCE_LOCALE`.++Keep technical values unchanged: framework/package names, versions, file paths,+commands, locale tags, CSS properties, identifiers, API names, audit rule+names, URLs, and code markers.++## Mode availability++Before building this data, read the selected framework/mode from+`scripts/lib/localization-config.js`. A plan may use only a mode whose+centralized status is `available`.++Currently available:++- React runtime localization+- Vue runtime localization+- Angular runtime localization++The recommended packages are `react-i18next`, `vue-i18n`, and+`@jsverse/transloco`, respectively. A compatible validated alternative runtime+package may be selected.++Angular static and Astro static remain known implementation capabilities but+are `temporarily-unavailable`. Do not represent them as proposed, preserved, or+changed plan modes. Astro has no currently available localization mode, so an+Astro invocation stops before rendering this artifact. The renderer enforces+this policy independently.++## Required top-level data++```json+{+ "SITE_NAME": "Existing site/brand name",+ "PLAN_TITLE": "Localized title",+ "SOURCE_LANGUAGE": "Localized readable source-language name",+ "SOURCE_LOCALE": "en-US",+ "SOURCE_DIRECTION": "ltr",+ "FRAMEWORK": "React",+ "INVOCATION_CONTEXT": "direct",+ "OPERATION": "create",+ "EXISTING_LOCALIZATION_DETECTED": false,+ "SUMMARY": "Localized plan summary",+ "PLAN_LABELS": {},+ "DISCOVERY_DATA": {},+ "CONFIGURATION_DATA": {},+ "LOCALES_DATA": [],+ "FILES_DATA": [],+ "READINESS_DATA": {},+ "VALIDATION_DATA": [],+ "LIMITATIONS_DATA": []+}+```++Allowed technical enums:++- `FRAMEWORK`: `React`, `Vue`, `Angular`, `Astro`+- `INVOCATION_CONTEXT`: `direct`, `create-site`+- `OPERATION`: `create`, `add-languages`, `repair`, `reconfigure`++## Configuration++First include deterministic discovery evidence:++```json+{+ "frameworkEvidence": ["Localized evidence with unchanged technical names"],+ "existingSetup": ["Localized existing-configuration detail"],+ "conflicts": []+}+```++`frameworkEvidence` must not be empty. Use an empty `conflicts` array when no+conflicts were found.++```json+{+ "package": {+ "value": "react-i18next 15.0.0",+ "name": "react-i18next",+ "version": "15.0.0",+ "status": "new",+ "verification": "verified",+ "selection": "recommended",+ "evidenceSource": "known-capability",+ "evidenceUrl": "https://www.npmjs.com/package/react-i18next",+ "initializationEvidence": null+ },+ "mode": {+ "value": "runtime",+ "status": "new",+ "description": "Optional localized detail"+ },+ "defaultLocale": {+ "value": "en-US",+ "status": "preserved",+ "description": "Optional localized detail"+ },+ "translation": {+ "method": "agent",+ "value": "Localized translation-method label",+ "description": "Localized method explanation",+ "warning": "AI translations may contain errors - please verify them before publishing."+ },+ "selector": {+ "value": "Localized placement label",+ "description": "Localized runtime/static behavior"+ },+ "rootDocumentRepair": null+}+```++`package`, `mode`, and `defaultLocale` use `new`, `preserved`, or `changed`.+`package.value` is localized presentation text. `package.name` and+`package.version` are required technical identities and remain untranslated.+The renderer validates known packages against `FRAMEWORK` and `mode.value`, so+a static package cannot enter a runtime plan under a different display label.+`package.verification` is `verified` or `unverified`. For a custom package,+`initializationEvidence` is `{ "file": "<path>", "marker": "<exact API marker>" }`.+`package.selection` is `recommended`, `alternative`, or `preserved`.+`package.evidenceSource` is `known-capability`, `official-documentation`,+`package-documentation`, or `user-approved`. `unverified` packages must use+`user-approved`; `official-documentation` requires an HTTPS `evidenceUrl`.+`translation.method` is `agent` or `blank`; `agent` requires the AI translation+warning.+For a missing/invalid root language, `rootDocumentRepair` is:++```json+{+ "file": "framework root-document path",+ "lang": "canonical locale",+ "dir": "ltr or rtl"+}+```++For Astro built-in localization, use a localized `package.value` such as+"Astro built-in i18n" while keeping `Astro` technical and set verification to+`verified`.++## Locales++Include every resulting locale:++```json+[+ {+ "language": "Localized readable language name",+ "locale": "en-US",+ "direction": "ltr",+ "roles": ["source", "default", "existing"],+ "availability": "available"+ },+ {+ "language": "Localized readable language name",+ "locale": "ar-SA",+ "direction": "rtl",+ "roles": ["added"],+ "availability": "pending-remediation"+ }+]+```++There must be exactly one `source` and one `default` role. They may belong to+different locales when the operation changes the default. Other role values+are `existing` and `added`; availability is `available` or+`pending-remediation`.++## Files and packages++List the complete delta, including packages and files that will intentionally+remain unchanged:++```json+[+ {+ "path": "package.json",+ "action": "update",+ "reason": "Localized reason"+ }+]+```++Actions are `create`, `update`, `preserve`, `replace`, or `skip`. Never use a+generic directory entry when exact files are known.++## Bidirectional readiness++```json+{+ "transition": "ltr-only → mixed",+ "findings": [+ {+ "severity": "error",+ "file": "src/styles.css",+ "line": 42,+ "rule": "directional-physical-css",+ "message": "Localized explanation",+ "remediation": "Localized proposed remediation",+ "scope": "locale",+ "affectedLocales": ["ar-SA"]+ }+ ],+ "componentScope": [+ {+ "component": "Localized component or surface name",+ "classification": "direction-aware",+ "reason": "Localized classification reason",+ "states": ["Localized applicable state"],+ "viewports": ["desktop", "narrow"],+ "checks": ["Localized planned verification"]+ }+ ],+ "physicalExceptions": ["Localized description with unchanged CSS details"],+ "scriptFonts": ["Localized script/font change"],+ "unavailableLocales": ["ar-SA"]+}+```++Finding severity is `error` or `review`. Preserve the audit's exact `file`,+positive `line`, and `rule`, and provide the proposed `remediation`. Every+finding also has a `scope` and nonempty, unique `affectedLocales`:++- `locale` affects exactly one language-specific locale.+- `direction` affects every configured locale in its `ltr` or `rtl`+ `direction`.+- `shared` affects an explicitly tested subset of configured locales.+- `global` affects every configured locale.++An empty array is valid for findings, physical exceptions, script fonts, and+unavailable locales.++`componentScope` must be non-empty and cover every visible or interactive+component in the existing implementation, including page-local controls.+Classifications are `direction-neutral`, `direction-aware`,+`direction-fixed`, or `unknown-third-party`. `reason`, `states`, and `checks`+are localized. `states` contains every applicable rendered or interactive+state, not a mechanical list of states the component does not support.+`viewports` contains one or both stable values `desktop` and `narrow`.++Treat anything involving inline placement, text direction, horizontal+movement, sequence, directional meaning, mixed-script content, or rendering+outside the normal component subtree as a potential bidirectional surface.+Direction-aware entries require planned LTR and RTL checks. Direction-fixed+entries require a semantic reason and surrounding-UI checks.+Unknown/third-party entries require rendered checks for their supported open+states, including portals, teleports, overlay containers, Shadow DOM, or+iframes. This plan data is human-reference scope, not a new project manifest;+reconcile it against the implementation during Phase 5.++The source locale must be `existing` and `available`, locale tags must be+unique, and `unavailableLocales` must exactly match locales marked+`pending-remediation`. The selected default locale must also remain available.+When a newly proposed default is still pending, preserve the previous default+until that locale is verified and can be enabled.+Every locale named by an unresolved finding must be+`pending-remediation`. A finding for a newly added Arabic locale therefore+does not disable an already verified Hebrew locale unless the finding is+direction-scoped or shared evidence identifies Hebrew as affected. Plan+approval authorizes the proposed remediation; it does not authorize enabling+an affected locale while that blocker remains.++## Verification and limitations++`VALIDATION_DATA` uses stable technical IDs with localized descriptions:++```json+[+ {+ "id": "independent-validator",+ "description": "Localized verification description"+ }+]+```++Include one entry for every required ID; additional unique project-specific+checks are allowed:++`independent-validator`, `project-build`, `package-initialization`,+`resource-completeness`, `protected-tokens`, `locale-navigation`,+`locale-state`, `fallback-behavior`, `document-lang-dir`, `browser-console`,+`representative-routes`, `bidirectional-content`, `localized-formatting`,+`script-fonts`, `directional-components`, and `accessibility`.++`LIMITATIONS_DATA` is an array of localized known or anticipated limitations+and approved translation replacements. A pre-implementation plan may describe+a possible usable limitation, but final maker approval is obtained only after+rendered evidence exists in Phase 7. Use an empty array when none are known.++## Required localized labels++Translate every value below into `SOURCE_LOCALE`. Keep the stable keys+unchanged and preserve `{siteName}` exactly.++```json+{+ "navigation": {+ "group": "Localization plan",+ "overview": "Overview",+ "languages": "Languages",+ "changes": "Changes",+ "readiness": "Bidirectional readiness",+ "verification": "Verification"+ },+ "overview": {+ "title": "Localization overview",+ "description": "Localization implementation plan for {siteName}",+ "framework": "Framework",+ "invocation": "Invocation",+ "operation": "Operation",+ "existingSetup": "Existing localization",+ "configuration": "Approved configuration",+ "frameworkEvidence": "Framework evidence",+ "existingDetails": "Existing setup",+ "conflicts": "Conflicts",+ "noConflicts": "No conflicts detected."+ },+ "configuration": {+ "package": "Package",+ "mode": "Mode",+ "defaultLocale": "Default locale",+ "translation": "Translation population",+ "selector": "Language selector",+ "verification": "Package verification",+ "selection": "Package selection",+ "evidenceSource": "Evidence source",+ "evidence": "Evidence",+ "initialization": "Initialization evidence",+ "rootRepair": "Root document repair"+ },+ "languages": {+ "title": "Languages",+ "description": "Source, existing, and newly added locales",+ "language": "Language",+ "locale": "Locale",+ "direction": "Direction",+ "roles": "Roles",+ "availability": "Availability"+ },+ "changes": {+ "title": "Files and packages",+ "description": "Exact implementation delta after approval",+ "path": "Path or package",+ "action": "Action",+ "reason": "Reason"+ },+ "readiness": {+ "title": "Bidirectional readiness",+ "description": "Direction transition, findings, and planned remediation",+ "transition": "Direction-set transition",+ "findings": "Readiness findings",+ "noFindings": "No readiness findings.",+ "location": "Location",+ "rule": "Rule",+ "scope": "Scope",+ "affectedLocales": "Affected locales",+ "remediation": "Planned remediation",+ "componentScope": "Component review scope",+ "component": "Component",+ "classification": "Classification",+ "reason": "Reason",+ "states": "Applicable states",+ "viewports": "Applicable viewports",+ "checks": "Planned checks",+ "physicalExceptions": "Physical exceptions",+ "scriptFonts": "Script font changes",+ "unavailableLocales": "Locales pending remediation",+ "none": "None."+ },+ "verification": {+ "title": "Verification and limitations",+ "description": "Checks that will run before maker review",+ "checks": "Verification checks",+ "limitations": "Known limitations",+ "noLimitations": "No known limitations."+ },+ "status": {+ "new": "New",+ "preserved": "Preserved",+ "changed": "Changed",+ "create": "Create",+ "update": "Update",+ "preserve": "Preserve",+ "replace": "Replace",+ "skip": "Skip",+ "source": "Source",+ "default": "Default",+ "existing": "Existing",+ "added": "Added",+ "available": "Available",+ "pendingRemediation": "Pending remediation",+ "verified": "Verified",+ "unverified": "Unverified",+ "yes": "Yes",+ "no": "No"+ },+ "packageSelection": {+ "recommended": "Recommended",+ "alternative": "Alternative",+ "preserved": "Preserved"+ },+ "evidenceSource": {+ "knownCapability": "Known capability",+ "packageDocumentation": "Package documentation",+ "officialDocumentation": "Official documentation",+ "userApproved": "User approved"+ },+ "severity": {+ "error": "Error",+ "review": "Review"+ },+ "classification": {+ "directionNeutral": "Direction-neutral",+ "directionAware": "Direction-aware",+ "directionFixed": "Direction-fixed",+ "unknownThirdParty": "Unknown or third-party"+ },+ "viewport": {+ "desktop": "Desktop",+ "narrow": "Narrow or mobile"+ },+ "operation": {+ "create": "Create localization",+ "addLanguages": "Add languages",+ "repair": "Repair",+ "reconfigure": "Reconfigure"+ },+ "invocation": {+ "direct": "Direct",+ "createSite": "From create-site"+ },+ "footer": {+ "aiWarning": "AI-generated content may be incorrect"+ }+}+```++## Persistence and source of truth++The rendered HTML remains under `docs/` for human reference. It is not parsed+or consumed by implementation, validation, deployment, or later skill runs.+Before implementation, the approved in-memory configuration remains+authoritative. After implementation, `.powerpages-localization.json` and the+site files become the durable source of truth.diff --git a/plugins/power-pages/skills/add-localization/scripts/validate-localization.js b/plugins/power-pages/skills/add-localization/scripts/validate-localization.jsindex 0bc3bdb00..2c7e4fdcf 100644--- a/plugins/power-pages/skills/add-localization/scripts/validate-localization.js+++ b/plugins/power-pages/skills/add-localization/scripts/validate-localization.js@@ -12,12 +12,12 @@ const {} = require('../../../scripts/lib/validation-helpers');const {KNOWN_PACKAGES,- LOCALIZATION_CAPABILITIES,MANIFEST_NAME,classifyLocaleDirections,detectLocalization,hasLocaleNavigationSignal,- getLocaleDirection,+ getLocalizationModeAvailability,+ isLocaleAvailabilityModulePath,protectedTokenSignature,resolveProjectRelativePath,validateLocalizationManifestShape,@@ -29,6 +29,16 @@ const {const {auditBidirectionalReadiness,} = require('../../../scripts/lib/bidirectional-readiness');+const {+ partitionDeferredFindings,+} = require('../../../scripts/lib/bidirectional-finding-disposition');+const {+ TRANSACTION_AVAILABILITY_FILE,+ listVerificationTransactionArtifacts,+ readLocalizationVerificationTransaction,+ validateTransactionAgainstManifest,+ validateVerifiedTransactionForReview,+} = require('../../../scripts/lib/localization-verification-transaction');const MAX_REPORTED_RESOURCE_IDS = 20;const MAX_RESOURCE_FILE_BYTES = 1024 * 1024;@@ -404,9 +414,32 @@ function compareXlfResources(projectRoot, manifest, errors, options = {}) {}}-function validateLocalization(projectRoot, warnings = []) {+function validateLocalization(projectRoot, options = {}) {+ const warnings = options.warnings || [];const manifestPath = path.join(projectRoot, MANIFEST_NAME);+ const transactionResult =+ readLocalizationVerificationTransaction(projectRoot);+ const transactionArtifacts = listVerificationTransactionArtifacts(projectRoot);+ const earlyTransactionErrors = [...transactionResult.errors];+ for (const artifact of transactionArtifacts) {+ const isExpectedAvailabilitySnapshot =+ artifact === TRANSACTION_AVAILABILITY_FILE &&+ transactionResult.transaction;+ if (artifact !== '.powerpages-localization-verification.json' &&+ !isExpectedAvailabilitySnapshot) {+ earlyTransactionErrors.push(+ `Localization verification transaction candidate ${artifact} remains ` ++ 'in the project.'+ );+ }+ }if (!fs.existsSync(manifestPath)) {+ if (transactionResult.transaction || earlyTransactionErrors.length > 0) {+ return [+ ...earlyTransactionErrors,+ 'Localization verification cannot continue or complete without a valid manifest.',+ ];+ }const detected = detectLocalization(projectRoot);if (!detected.detected) return [];return [@@ -416,10 +449,94 @@ function validateLocalization(projectRoot, warnings = []) {}const manifest = readJson(manifestPath);- if (!manifest) return [`${MANIFEST_NAME} is not valid JSON.`];- const shapeErrors = validateLocalizationManifestShape(manifest, projectRoot);- if (shapeErrors.length) return shapeErrors;+ if (!manifest) {+ return [+ ...earlyTransactionErrors,+ ...(transactionResult.transaction+ ? ['Localization verification is blocked until the manifest is restored.']+ : []),+ `${MANIFEST_NAME} is not valid JSON.`,+ ];+ }const errors = [];+ errors.push(...earlyTransactionErrors);+ const transaction = transactionResult.errors.length === 0+ ? transactionResult.transaction+ : null;+ const allowActiveVerification =+ options.allowActiveVerification === true &&+ transaction?.state === 'in-progress';+ const allowVerifiedReview =+ options.allowVerifiedTransactionReview === true &&+ transaction?.state === 'verified';+ // Without a transaction-specific option (deploy-site, every other skill's+ // final integrity gate), any remaining transaction blocks completion. Report+ // that root cause even when the manifest invariant also fails: a target left+ // exposed while still pending-remediation breaks the invariant, and the+ // invariant message alone would hide that the localization review was never+ // finalized.+ const blockedByUnfinishedTransaction = Boolean(transaction) &&+ options.allowActiveVerification !== true &&+ options.allowTransactionFinalization !== true &&+ options.allowVerifiedTransactionReview !== true;+ const unfinishedTransactionError =+ 'Localization verification is still active. Reconcile the target locales ' ++ 'and finalize the transaction before completing or deploying the site.';+ const shapeErrors = validateLocalizationManifestShape(manifest, {+ projectRoot,+ verificationLocales: allowActiveVerification || allowVerifiedReview+ ? transaction.targetLocales+ : [],+ });+ if (shapeErrors.length) {+ return [+ ...errors,+ ...(blockedByUnfinishedTransaction ? [unfinishedTransactionError] : []),+ ...shapeErrors,+ ];+ }+ if (options.allowActiveVerification === true && !transaction) {+ errors.push(+ 'Phase 6 verification requires an active localization verification transaction.'+ );+ } else if (options.allowActiveVerification === true &&+ transaction?.state !== 'in-progress') {+ errors.push(+ 'The localization verification transaction requires remediation before testing.'+ );+ } else if (transaction &&+ options.allowVerifiedTransactionReview === true) {+ errors.push(...validateVerifiedTransactionForReview(+ projectRoot,+ transaction,+ manifest+ ));+ } else if (blockedByUnfinishedTransaction) {+ errors.push(unfinishedTransactionError);+ }+ if (allowActiveVerification) {+ errors.push(...validateTransactionAgainstManifest(+ transaction,+ manifest,+ { requireExposed: true }+ ));+ }+ for (const finding of [+ ...(manifest.bidirectionalReadiness?.findings || []),+ ...(manifest.bidirectionalReadiness?.renderedFindings || []),+ ]) {+ const evidence = finding?.disposition?.evidence;+ if (!evidence) continue;+ const evidencePath = path.resolve(projectRoot, evidence);+ const evidenceRoot = path.resolve(projectRoot, 'docs', 'bidirectional-evidence');+ if (!evidencePath.startsWith(`${evidenceRoot}${path.sep}`) ||+ !fs.existsSync(evidencePath) ||+ !fs.statSync(evidencePath).isFile()) {+ errors.push(+ `Maker-approved bidirectional limitation evidence does not exist: ${evidence}`+ );+ }+ }if (manifest.schemaVersion !== 1) errors.push('Manifest schemaVersion must be 1.');const frameworkDetection = detectFramework(projectRoot);@@ -538,51 +655,40 @@ function validateLocalization(projectRoot, warnings = []) {: true;if (Array.isArray(manifest.locales) && manifest.locales.length >= 2) {- const directionSet = classifyLocaleDirections(manifest.locales);- if (directionSet.classification === 'mixed') {- const bidiAudit = auditBidirectionalReadiness(projectRoot);- const readinessPending =- manifest.bidirectionalReadiness?.status === 'pending-remediation';- if (!manifest.bidirectionalReadiness) {- errors.push(- 'Mixed-direction localization requires manifest bidirectionalReadiness metadata.'- );- }- const unavailableLocaleSet = new Set(unavailableLocales);- const defaultDirection = getLocaleDirection(manifest.defaultLocale);- const oppositeDirectionLocales = manifest.locales.filter(- (locale) => getLocaleDirection(locale) !== defaultDirection+ const bidiAudit = auditBidirectionalReadiness(projectRoot);+ const { blocking, unmatchedRecorded } = partitionDeferredFindings(+ bidiAudit.findings,+ manifest.bidirectionalReadiness?.findings || [],+ unavailableLocales+ );+ for (const finding of unmatchedRecorded) {+ errors.push(+ `Recorded bidirectional finding ${finding.file}:${finding.line} ` ++ `[${finding.rule}] no longer exactly matches the source audit. ` ++ 'Rerun the audit and remove or replace the stale manifest finding.');- const allOppositeLocalesUnavailable = oppositeDirectionLocales.every(- (locale) => unavailableLocaleSet.has(locale)+ }+ for (const finding of blocking) {+ errors.push(+ `Bidirectional readiness ${finding.file}:${finding.line} ` ++ `[${finding.rule}]: ${finding.message}`+ );+ }+ if (unavailableLocales.length > 0 && !hasAvailabilityImplementation) {+ errors.push(+ 'Pending bidirectional remediation requires managed availability logic ' ++ 'that excludes each unavailable locale.');- if (readinessPending && !allOppositeLocalesUnavailable) {- errors.push(- 'Pending bidirectional remediation requires every locale opposite to the ' +- 'default direction to be unavailable.'- );- }- if (readinessPending && !hasAvailabilityImplementation) {- errors.push(- 'Pending bidirectional remediation requires managed availability logic that ' +- 'excludes each unavailable opposite-direction locale.'- );- }- const canSuppressReadinessErrors =- readinessPending &&- allOppositeLocalesUnavailable &&- hasAvailabilityImplementation;- if (!canSuppressReadinessErrors) {- for (const finding of bidiAudit.findings.filter((item) => item.severity === 'error')) {- errors.push(- `Bidirectional readiness ${finding.file}:${finding.line} ` +- `[${finding.rule}]: ${finding.message}`- );- }- }- if (manifest.mode === 'runtime') {- validateRuntimeCoordinator(projectRoot, allManagedFiles, errors);- }+ }+ const unavailableLocaleSet = new Set(unavailableLocales);+ const availableLocales = manifest.locales.filter(+ (locale) => !unavailableLocaleSet.has(locale)+ );+ const availableDirectionSet = classifyLocaleDirections(availableLocales);+ if (manifest.mode === 'runtime' &&+ (availableDirectionSet.classification === 'mixed' ||+ unavailableLocales.length > 0)) {+ validateRuntimeCoordinator(projectRoot, allManagedFiles, errors);}}@@ -881,8 +987,8 @@ function validateLocaleAvailability(unavailableLocales,errors) {- const availabilityPaths = allManagedFiles.filter((relativePath) =>- /locale[-_.]?availability/i.test(path.basename(relativePath))+ const availabilityPaths = allManagedFiles.filter(+ isLocaleAvailabilityModulePath);if (availabilityPaths.length !== 1) {errors.push(@@ -921,8 +1027,28 @@ function validateLocaleAvailability(source: fs.readFileSync(path.join(projectRoot, relativePath), 'utf8'),})).filter(({ source }) => boundaryPattern.test(source));+ const filteredLocaleCollection =+ /\.filter\s*\(\s*(?:isLocaleAvailable\b|(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*isLocaleAvailable\s*\()/s;+ const guardedLocaleCandidate =+ /if\s*\(\s*!\s*isLocaleAvailable\s*\([^)]+\)\s*\)\s*(?:\{[^}]*\b(?:return|continue)\b|(?:return|continue)\b)/s;for (const { relativePath, source } of boundaryFiles) {- if (!/\bisLocaleAvailable\s*\(|\bfilter\s*\(\s*isLocaleAvailable\b/.test(source)) {+ const exposesSelector =+ /LanguageSelector|language selector|locale-switcher/i.test(source);+ const filtersEveryUnavailableSelectorLocale = unavailableLocales.every((locale) => {+ const escaped = locale.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return new RegExp(+ `\\[[^\\]]*['"]${escaped}['"][^\\]]*\\]\\s*` ++ '\\.filter\\s*\\(\\s*(?:isLocaleAvailable\\b|' ++ '(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>\\s*' ++ 'isLocaleAvailable\\s*\\()',+ 's'+ ).test(source);+ });+ const appliesAvailability = exposesSelector+ ? filtersEveryUnavailableSelectorLocale+ : filteredLocaleCollection.test(source) ||+ guardedLocaleCandidate.test(source);+ if (!appliesAvailability) {errors.push(`Locale activation boundary ${relativePath} does not apply isLocaleAvailable.`);@@ -938,6 +1064,33 @@ function validateLocaleAvailability(return valid;}+function collectProjectFiles(projectRoot, includeFile) {+ const excludedDirectories = new Set([+ '.git',+ '.powerpages-site',+ 'build',+ 'coverage',+ 'dist',+ 'docs',+ 'node_modules',+ ]);+ const files = [];+ const pending = [projectRoot];+ while (pending.length > 0) {+ const directory = pending.pop();+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {+ const fullPath = path.join(directory, entry.name);+ if (entry.isSymbolicLink()) continue;+ if (entry.isDirectory()) {+ if (!excludedDirectories.has(entry.name)) pending.push(fullPath);+ } else if (entry.isFile() && includeFile(entry)) {+ files.push(fullPath);+ }+ }+ }+ return files;+}+function validateRuntimeCoordinator(projectRoot, allManagedFiles, errors) {const coordinatorPaths = allManagedFiles.filter((relativePath) =>/locale[-_.]?coordinator/i.test(path.basename(relativePath))@@ -990,10 +1143,23 @@ function validateRuntimeCoordinator(projectRoot, allManagedFiles, errors) {}function validateFrameworkModePackage(projectRoot, manifest, dependencies, detected, errors) {- const frameworkCapability = LOCALIZATION_CAPABILITIES.frameworks[manifest.framework];- if (frameworkCapability &&- !frameworkCapability.supportedModes.includes(manifest.mode)) {- errors.push('The manifest framework does not support the configured localization mode.');+ const modeAvailability = getLocalizationModeAvailability(+ manifest.framework,+ manifest.mode+ );+ if (!modeAvailability.available) {+ errors.push(modeAvailability.reason);+ }+ for (const evidence of detected.unavailableModeEvidence || []) {+ if (evidence.mode === manifest.mode) continue;+ const availability = getLocalizationModeAvailability(+ manifest.framework,+ evidence.mode+ );+ errors.push(+ `${availability.reason} Remove or migrate detected ${evidence.detail} ` ++ 'before validation can pass.'+ );}const knownPackage = KNOWN_PACKAGES[manifest.packageName];@@ -1035,9 +1201,12 @@ function validateFrameworkModePackage(projectRoot, manifest, dependencies, detec}-function finishValidation(projectRoot) {+function finishValidation(projectRoot, options = {}) {const warnings = [];- const errors = validateLocalization(projectRoot, warnings);+ const errors = validateLocalization(projectRoot, {+ ...options,+ warnings,+ });if (warnings.length) {process.stderr.write(`Localization validation warnings (preserved, nonblocking):\n- ${warnings.join('\n- ')}\n`@@ -1047,9 +1216,9 @@ function finishValidation(projectRoot) {approve();}-function finishValidationFailClosed(projectRoot) {+function finishValidationFailClosed(projectRoot, options = {}) {try {- finishValidation(projectRoot);+ finishValidation(projectRoot, options);} catch {block('Localization validation failed unexpectedly and must be reviewed before continuing.'@@ -1064,7 +1233,9 @@ if (require.main === module && process.argv.includes('--projectRoot')) {process.stderr.write('Usage: validate-localization.js --projectRoot <path>\n');process.exit(1);}- finishValidationFailClosed(path.resolve(projectRoot));+ finishValidationFailClosed(path.resolve(projectRoot), {+ allowActiveVerification: process.argv.includes('--verification'),+ });} else if (require.main === module) {runValidation((cwd) => {const projectRoot = findLocalizationProjectRoot(cwd);diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.mdindex 75b272641..ddb99d9e5 100644--- a/plugins/power-pages/skills/create-site/SKILL.md+++ b/plugins/power-pages/skills/create-site/SKILL.md@@ -716,11 +716,29 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read<!-- not-a-gate: the locale is validated before it can affect scaffolding -->- When the content language was not explicit, use `AskUserQuestion`:+ When the content language was not explicit, get a best-effort suggestion:++ ```bash+ node "${PLUGIN_ROOT}/scripts/suggest-content-locale.js"+ ```++ The script returns the selected Dataverse environment's base language as a+ canonical BCP-47 locale when PAC and Azure CLI authentication are available.+ It silently returns `en-US` with `"source": "fallback"` when the environment,+ authentication, API response, or LCID mapping is unavailable. Do not retry,+ display an error, or block site creation when the lookup falls back.++ Use `AskUserQuestion`:| Question | Header | Options ||----------|--------|---------|- | Which language should the site content use?<br><br>Pages, navigation, buttons, forms, and accessibility text will use this language. Dataverse and Power Pages system messages will remain in English. | Site content language | English (`en-US`) (Recommended) |+ | Which language should the site content use?<br><br>Pages, navigation, buttons, forms, and accessibility text will use this language. Dataverse and Power Pages system messages will remain in English. | Site content language | `<language> (<locale>) (Suggested)`, English (`en-US`) |++ Replace `<language>` and `<locale>` with the script result. If that result is+ `en-US`, show only `English (United States) (en-US) (Suggested)` rather than+ adding a duplicate English option. Label the environment-derived choice+ **Suggested**, not **Recommended**: an environment's base language is useful+ context but may not match the intended language of a public site.The question UI's free-text option lets the maker enter another language orlocale, such as `Spanish (es-ES)`, `Japanese (ja-JP)`, or `Arabic (ar-SA)`.@@ -1007,6 +1025,21 @@ Immediately after the dev server starts, verify the scaffold is working:| Routes | 4 | /, /about, /services, /contact |```+ Build `BIDIRECTIONAL_REVIEW_DATA` for every planned visible or interactive+ component, including page-local controls that are not shared source+ components. Classify each entry as `direction-neutral`, `direction-aware`,+ `direction-fixed`, or `unknown-third-party` using the shared bidirectional+ standard. Record the localized reason, applicable states, applicable+ `desktop`/`narrow` viewports, and planned checks. Treat anything involving+ inline placement, text direction, horizontal movement, sequence,+ directional meaning, mixed-script content, or rendering outside the normal+ component subtree as a potential bidirectional surface.++ This is the expected review scope, not a project manifest. Phase 5 must+ reconcile it against the actual source and rendered application, adding+ components or states discovered during implementation. Do not write a+ separate component-inventory JSON file.+8. Choose the final color tokens - every color role in design-aesthetics.md section 3 - from the brief and brand source. Check each text and background pair against WCAG AA now, before the values reach the plan. These are written fresh into a new `theme.css` during Implementation (Phase 5) when the scaffold loading screen is completely replaced.**Output**: Confirmed list of pages (with narrative beats), components, design elements, and routes to create, plus the experience brief and color tokens@@ -1032,14 +1065,15 @@ Assemble a single JSON object with the following keys. The plan template rejects| Key | Type | Content ||-----|------|---------|| `SITE_NAME` | string | Site/brand name from Phase 1, preserved as entered |-| `PLAN_TITLE` | string | Always `"Implementation Plan"` |+| `PLAN_TITLE` | string | Localized equivalent of `"Implementation Plan"` in `SITE_LOCALE` || `FRAMEWORK` | string | `React` / `Vue` / `Angular` / `Astro` |-| `SITE_LANGUAGE` | string | Readable content-language name from Phase 1 |+| `SITE_LANGUAGE` | string | Readable content-language name from Phase 1, written in that language when practical || `SITE_LOCALE` | string | Canonical BCP-47 content locale || `SITE_DIRECTION` | string | `ltr` or `rtl` || `AESTHETIC` | string | Chosen aesthetic (e.g., `Minimal & Clean`) || `MOOD` | string | Chosen mood (e.g., `Professional & Trustworthy`) |-| `SUMMARY` | string | One paragraph describing what the site is and who it serves |+| `SUMMARY` | string | One localized paragraph describing what the site is and who it serves |+| `PLAN_LABELS` | object | Complete localized template-label dictionary defined below || `DESIGN_DIRECTION_DATA` | object | The experience brief: `{ thesis, brandSource, audience, primaryAction, secondaryAction, principalDoubt, proofStrategy, heroConcept, signatureMoment }` - all strings. `brandSource` says where tokens came from (e.g., `"Fresh identity"`, `"Matched to https://contoso.com"`) || `TYPOGRAPHY_DATA` | object | `{ primary: { name, sample, reason }, secondary: { name, sample, reason } }` - `primary` is the body face, `secondary` the display face; `name` must be a family from the verified faces table in design-aesthetics.md (or the brand's own Google Font) || `PALETTE_DATA` | array | `[{ var, hex, description }]` - one entry per color token from design-aesthetics.md section 3 |@@ -1048,10 +1082,183 @@ Assemble a single JSON object with the following keys. The plan template rejects| `PAGES_DATA` | array | `[{ name, route, description, content: [...], components: [...] }]` - `content` is the page's narrative beats in order, one line per section with its purpose; `components` is shared component names used || `COMPONENTS_DATA` | array | `[{ name, purpose, usedBy: [...] }]` — shared components with the page names that consume them || `ROUTES_DATA` | array | `[{ path, page }]` — every route the router will register |-| `REVIEW_DATA` | array of strings | Verification checklist items - include "Design critique: no critical gate fails; after up to three rounds, every category below 3 is recorded with its reason" alongside items like "All pages load without console errors" |+| `BIDIRECTIONAL_REVIEW_DATA` | array | Every planned visible or interactive component as `{ component, classification, reason, states: [...], viewports: ["desktop" or "narrow"], checks: [...] }`; all maker-facing strings are localized |+| `REVIEW_DATA` | object | `{ agentChecks: [...], makerReview: [...] }` using the responsibility contract below || `DEPLOYMENT_DATA` | array | `[{ title, description, recommended?: boolean }]` — mark exactly one as `recommended: true` |-**Write the data for the user**, not for internal tooling — phrase `description` and `reason` fields in plain language.+`PLAN_LABELS` must contain every key below. The English values describe each+label's meaning; translate every value into `SITE_LOCALE`. Preserve `{siteName}`+and `{count}` exactly because the renderer substitutes those tokens at runtime.+Do not omit keys or fall back to English for individual labels.++```json+{+ "navigation": {+ "group": "Plan",+ "overview": "Overview",+ "design": "Design",+ "pages": "Pages & Components",+ "deployment": "Deployment & Review"+ },+ "overview": {+ "title": "Overview",+ "description": "Implementation plan for {siteName}",+ "stats": {+ "pages": "Pages",+ "components": "Shared Components",+ "routes": "Routes"+ },+ "nextSteps": {+ "title": "What happens next",+ "design": {+ "title": "Apply design tokens",+ "description": "Fonts, palette, motion, and backgrounds written into your theme"+ },+ "components": {+ "title": "Build shared components",+ "descriptionOne": "{count} reusable component used across pages",+ "descriptionOther": "{count} reusable components used across pages"+ },+ "pages": {+ "title": "Create pages",+ "descriptionOne": "{count} page with routing and navigation",+ "descriptionOther": "{count} pages with routing and navigation"+ },+ "critique": {+ "title": "Critique the design",+ "description": "Desktop and mobile screenshots scored and refined against the design rubric"+ },+ "verify": {+ "title": "Verify & accessibility",+ "description": "axe-core audit, Playwright checks, and user review"+ }+ }+ },+ "design": {+ "title": "Design",+ "description": "Design direction, typography, palette, motion, and background treatments",+ "direction": {+ "title": "Design direction",+ "heroConcept": "Hero concept",+ "signatureMoment": "Signature moment",+ "primaryAction": "Primary action",+ "secondaryAction": "Secondary action",+ "principalDoubt": "Principal doubt",+ "proofStrategy": "Proof strategy",+ "brandSource": "Brand source",+ "audience": "Audience and job"+ },+ "typography": "Typography",+ "palette": "Color palette",+ "motion": "Motion & animation",+ "backgrounds": "Background treatment",+ "primaryRole": "Primary — body & UI",+ "secondaryRole": "Secondary — headings"+ },+ "pages": {+ "title": "Pages & Components",+ "description": "Pages to build, their content outline, and the shared components they rely on",+ "pages": "Pages",+ "components": "Shared components",+ "routing": "Routing",+ "path": "Path",+ "page": "Page",+ "content": "Content",+ "componentsUsed": "Components used",+ "usedBy": "Used by",+ "noComponents": "No shared components planned yet."+ },+ "bidirectional": {+ "title": "Bidirectional review scope",+ "description": "Planned component, state, and viewport coverage; reconciled with the actual implementation before handoff",+ "classification": "Classification",+ "reason": "Reason",+ "states": "Applicable states",+ "viewports": "Applicable viewports",+ "checks": "Planned checks",+ "classifications": {+ "directionNeutral": "Direction-neutral",+ "directionAware": "Direction-aware",+ "directionFixed": "Direction-fixed",+ "unknownThirdParty": "Unknown or third-party"+ },+ "viewport": {+ "desktop": "Desktop",+ "narrow": "Narrow or mobile"+ }+ },+ "deployment": {+ "title": "Deployment & Review",+ "description": "Verification checklist and deployment options",+ "verify": "Before handoff — verify",+ "agentChecks": "Agent verification",+ "agentChecksDescription": "The agent will run and report these checks before handoff.",+ "makerReview": "Maker review",+ "makerReviewDescription": "Review these judgment-based items in the live preview.",+ "options": "Deployment options",+ "recommended": "Recommended"+ },+ "common": {+ "noneSpecified": "None specified."+ },+ "footer": {+ "aiWarning": "AI-generated content may be incorrect"+ }+}+```++**Write all maker-facing plan data in the selected content language.** This+includes `PLAN_TITLE`, `SUMMARY`, `PLAN_LABELS`, descriptive `AESTHETIC` and+`MOOD` names, typography reasons/samples, palette descriptions, motion and+background labels/descriptions, page display names/descriptions/content+outlines, component display names/purposes, route page labels, review items,+and deployment titles/descriptions.++Keep technical values unchanged: framework and package names, file paths,+routes, commands, locale tags, CSS variables, hex colors, identifiers, API+names, and brand/product names. When a page or component `name` is also the+planned code identifier, keep it unchanged; localize only human-readable+display names. Use complete translated phrases rather than joining translated+fragments in English word order.++Build `REVIEW_DATA` as two non-empty localized string arrays:++```json+{+ "agentChecks": [+ "The root document uses the canonical site locale and resolved writing direction",+ "The bidirectional-readiness audit reports no errors; layout uses logical CSS and every physical exception is documented and verified",+ "Every visible or interactive component is classified, and the planned review scope is reconciled with the actual source and rendered application",+ "Every applicable state and viewport of direction-aware, direction-fixed, and unknown or third-party components has verification evidence",+ "Localized form labels, placeholders, hints, helper text, validation messages, prefixes, suffixes, and overlays follow the active UI direction; only classified machine-oriented values remain LTR",+ "Representative routes work in the selected direction and a pseudo-opposite direction at desktop and narrow widths without console errors, broken reading order, or broken focus order",+ "Unknown-direction content uses bdi or dir=auto, while URLs, email addresses, code, paths, GUIDs, and identifiers are explicitly isolated",+ "Dates, numbers, currency, percentages, and relative time use locale-aware Intl formatting",+ "Typography covers the selected script and expanded or opposite-direction text does not clip or overlap",+ "Directional components, interactions, icons, and assets behave according to their reviewed mirror, preserve, or replace classification",+ "Every route has zero critical or serious axe-core accessibility violations"+ ],+ "makerReview": [+ "Language, terminology, tone, regional wording, and regulated content are appropriate",+ "Visual hierarchy and reading flow feel natural in the selected direction and the opposite-direction preview",+ "Typography remains readable and preserves the intended brand character",+ "Icon and image direction choices are culturally and semantically appropriate",+ "Text wrapping, expansion, and narrow-screen layouts remain visually acceptable"+ ]+}+```++Translate these as complete criteria rather than copying the English wording.+The two groups communicate responsibility:++- `agentChecks` are objective commitments the agent must execute and report+ during Phases 5–7. They are not instructions for the maker.+- `makerReview` contains linguistic, cultural, brand, and visual judgments that+ automation cannot approve. The maker reviews them in the live preview during+ Phase 7.++Do not move subjective maker judgments into `agentChecks`, and do not ask the+maker to repeat deterministic source, browser, or accessibility checks.### 4.3 Render the HTML Plan@@ -1187,10 +1394,23 @@ The scaffold is a temporary loading screen — it must be **completely replaced*- For every locale, use logical CSS properties and preserve meaningful DOMreading/focus order. Do not reverse arrays or use `row-reverse` to simulateRTL. Initial RTL sites must also be visually verified in RTL.+- Treat each form field as one compound direction surface: localized labels,+ placeholders, hints, helper text, validation messages, prefixes, suffixes,+ icons, and open menus follow the active UI direction and use logical+ alignment. Native free-form inputs and textareas use adaptive `dir`: the+ active UI direction while empty, `auto` while populated, and the active UI+ direction again after clearing. Preserve or add `dirname` where submitted+ direction metadata is appropriate. Keep only+ classified machine-oriented values such as email addresses, telephone+ numbers, URLs, code, paths, GUIDs, and identifiers LTR; add the adjacent+ `/* bidi-fixed: <specific reason>; verify=ltr,rtl */` or equivalent HTML+ directive required by the shared standard. Their surrounding field UI+ remains direction-aware.- Wrap independently inserted unknown-direction content (names, comments,titles, search queries) with `<bdi>` or `dir="auto"`. Keep URLs, email,code, file paths, GUIDs, and other machine values explicitly isolated,- normally LTR. Use `dir="auto"` for free-form multilingual inputs.+ normally LTR. Free-form native controls must not use permanent `dir="auto"`;+ bind their native direction to value emptiness and the active UI direction.- Format dates, numbers, currency, percentages, and relative time with `Intl`APIs rather than concatenating locale-sensitive punctuation or symbols.- Classify directional icons and assets as unchanged, mirrored, or replaced.@@ -1255,12 +1475,66 @@ Run the deterministic readiness audit after all pages and components exist:node "${PLUGIN_ROOT}/scripts/audit-bidirectional-readiness.js" --projectRoot "<PROJECT_ROOT>"```-Fix every `error` finding. Review every physical-geometry finding in the live-site. For an intentionally physical product requirement, keep the declaration,-add the validated adjacent `bidi-physical` directive, and verify that component-in both LTR and RTL. Use pseudo-opposite-direction content to check wrapping,-navigation, forms, mixed names/identifiers, icons, calendars, and narrow/mobile-layout even when no second real locale exists yet.+The command prints structured JSON and exits nonzero when deterministic errors+exist; parse the JSON even on that expected failure path. Fix every `error`+finding. Review every geometry, scrolling, visual-order, and content-expansion+finding in the live site. For an intentionally physical product requirement,+keep the declaration, add the validated adjacent `bidi-physical` directive,+and verify that component in both LTR and RTL. For intentionally fixed+machine-oriented text, add the adjacent `bidi-fixed` directive and verify the+surrounding UI in both directions. Use pseudo-opposite-direction content to+check wrapping, navigation, forms, mixed names/identifiers, icons, calendars,+and narrow/mobile layout even when no second real locale exists yet. For every+free-form native input or textarea, verify empty, RTL-valued, LTR-valued,+clear-after-RTL, and clear-after-LTR states under both UI directions. Each+clear state must enter the corresponding value before clearing it; empty and+cleared states follow the UI locale, while populated states follow the entered+value.++Reconcile `BIDIRECTIONAL_REVIEW_DATA` against the completed source and rendered+routes. Add every implemented visible or interactive component that was not+known during planning, and add every applicable state or viewport discovered+during implementation. Verify the selected direction and pseudo-opposite+direction for every site: LTR sites receive pseudo-RTL coverage, and RTL sites+receive pseudo-LTR coverage. Direction-neutral components need an inheritance+check; direction-aware components need all applicable states in both+directions; direction-fixed components need a semantic reason plus surrounding+UI checks; unknown/third-party components need rendered checks including+dialogs, menus, autocomplete panels, tooltips, teleports, portals, overlays,+Shadow DOM, or iframes they open.++Build the ephemeral rendered-verification specification described in+`${PLUGIN_ROOT}/references/rendered-bidirectional-verification.md`. Derive it+from the reconciled component scope and actual selectors; do not commit it as a+component manifest. Give unstable but important verification surfaces a+`data-bidi-id` attribute. Include every applicable state and viewport, compound+form parts, body-mounted overlays, explicit focus sequences, non-overlap pairs,+and direction-specific computed-style expectations. Use the real configured+LTR and RTL locales when both exist; otherwise add a browser-only+pseudo-opposite locale. Real locales must be activated through the application+and prove representative localized content; only pseudo locales may use the+browser-only `set-document` action. If runtime localization was added, include both+default -> locale -> default and locale -> default -> locale transition+sequences for every real non-default locale, with route, form-state,+application-state, and focus preservation checks. Pseudo locales do not+participate in application-switch transitions. Every real locale, including+the default, needs a reusable application activation action; `use-current`+cannot restore a locale during a round trip. For a newly added runtime locale,+use the localization verification transaction defined by add-localization:+temporarily expose only the recorded target through the normal selector, run+Playwright against a loopback dev server, keep it available on success, and+restore fail-closed availability on failure. Exclude pre-existing unavailable+locales from activation and declare them in `unavailableLocaleChecks`. Do not+complete creation or offer deployment while the verification transaction+exists. Bare `preserve` selectors are only for form controls; use explicit+text, attribute, or property preservation entries for tabs, panels, counters,+and other application state.++Retain evidence for every applicable `REVIEW_DATA.agentChecks` item: audit+result, routes/viewports exercised, direction used, mixed-content fixtures,+font/text-expansion observations, component/asset classifications, console+result, and any remediations. Do not mark an agent-owned criterion complete+based only on visual inspection by the maker.### 5.6 Clean Up the Live Status File@@ -1313,6 +1587,19 @@ Use `AskUserQuestion`, naming each failing critical gate and its evidence in the### 5.8 Offer Additional Languages+Query the centralized add-localization availability before offering the child+workflow:++```bash+node "${PLUGIN_ROOT}/scripts/lib/localization-config.js" mode-availability --framework "<react|vue|angular|astro>"+```++If `availableModes` is empty, explain that localization is temporarily+unavailable for the selected framework using the returned reason, set+`LOCALIZATION_REQUESTED=false`, and do not ask the additional-languages+question. This currently applies to Astro. Do not hardcode a separate+framework availability list in create-site.+Ask whether more languages should be added now:> **Would you like to add more languages now?**@@ -1397,6 +1684,73 @@ Parse the returned JSON array of per-route results. Each result contains `violatParse the JSON output and record all violations.+### 6.2b Run Rendered Bidirectional Audit++Read `${PLUGIN_ROOT}/references/rendered-bidirectional-verification.md`. If+add-localization returned a successful report, first validate and reuse it:++```bash+node "${PLUGIN_ROOT}/scripts/audit-rendered-bidirectional-readiness.js" \+ --projectRoot "<PROJECT_ROOT>" \+ --reuse-report "<ADD_LOCALIZATION_REPORT_PATH>"+```++This succeeds only when the child report came from a complete `standard` or+`extensive` run that passed, and source, resources, dependencies, build+configuration, and locale availability still match it. A `targeted` repair+report is never reused. Readiness-only metadata does not invalidate it. If reuse+succeeds, do not build a specification or repeat the matrix. If reuse is+stale—such as after accessibility remediation changed relevant source—build+the component/state/viewport specification from the current implementation and+run it:++```bash+node "${PLUGIN_ROOT}/scripts/audit-rendered-bidirectional-readiness.js" \+ --url "<DEV_SERVER_URL>" \+ --projectRoot "<PROJECT_ROOT>" \+ --spec "<TEMP_SPEC_PATH>" \+ --evidence-dir "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>" \+ --output "<PROJECT_ROOT>/docs/bidirectional-evidence/<RUN_ID>/report.json"+```++The command prints JSON and exits `1` when blocking rendered findings exist;+parse stdout on that expected path. Exit `2` is a runner/specification failure+and must be fixed before continuing. Delete the temporary specification after+the report is written.++Fix every rendered `error` and rerun the complete affected matrix. Review+findings require screenshot-backed disposition; they are not automatic passes.+The audit must cover computed `lang`/`dir`, component and compound-field+direction, clipping, page overflow, viewport escape, declared non-overlap,+focus order, portals/overlays, unknown/third-party surfaces, and runtime+round-trip preservation when applicable. A visible opaque external surface is+blocking unless it is replaced or intentionally unavailable for the affected+locale.++Use the rendered-verification reference's grouped execution model:+`maxConcurrency: 3` by default, `reload` state isolation unless a deterministic+reset exists, `resettable` only with explicit reset actions, and `isolated`+for global or destructive state. Independent route/viewport/locale groups may+run concurrently; locale-transition sequences remain serial.++> **GATE: Do NOT proceed to Phase 7 while the create-site report contains an+> error affecting an available locale or the available site experience, or an+> untriaged review finding.** Every review item must have evidence and a+> proposed resolution, judgment-based pass, or usable-limitation disposition+> for maker review. An add-localization blocker may continue only when its+> affected locale is verifiably unavailable at every activation boundary; keep+> that child report as pending evidence and audit the remaining available+> experience with a real locale plus pseudo-opposite direction. A screenshot+> documents what rendered; it does not override a deterministic failure.++For each review finding, record whether it was resolved, accepted as a+judgment-based pass, or proposed as a usable limitation. A usable limitation+must name the affected component/page, user impact, and report or screenshot+evidence. Never offer an error finding for maker override. If the+add-localization child returned `pending-remediation`, verify that every+affected locale remains excluded from selectors, detection, metadata, and+production output before continuing with the available site experience.+### 6.3 Fix Accessibility ViolationsFor each violation found, identify the source file and apply the fix:@@ -1440,6 +1794,10 @@ Present a summary table to the user:> **GATE: Do NOT proceed to Phase 7 until all pages pass axe-core with zero `critical` and `serious` violations.** Minor and moderate violations should also be fixed where possible, but are not blocking.+Record the final axe-core result against the corresponding+`REVIEW_DATA.agentChecks` item. Accessibility remains agent-owned; the maker is+not asked to reproduce the automated audit.+**Output**: Accessibility-verified site with zero critical/serious axe-core violations---@@ -1450,7 +1808,7 @@ Present a summary table to the user:<!-- gate: create-site:7.review | category=plan | cancel-leaves=nothing -->-> 🚦 **Gate (plan · create-site:7.review):** Live-site review — last chance to request changes before the deploy prompt. Cancel branch lets the user keep iterating. Fires at step 4 of the action list below.+> 🚦 **Gate (plan · create-site:7.review):** Live-site review — last chance to request changes before the deploy prompt. Cancel branch lets the user keep iterating. Fires at step 5 of the action list below.>> **Trigger:** Phase 7 has verified all pages render via Playwright.> **Why we ask:** User loses the chance to spot UI issues before deploy; broken pages get pushed.@@ -1470,15 +1828,65 @@ Present a summary table to the user:| Git Commits | 9 | scaffold + 8 feature and critique commits |```- Follow it with the design thesis in one sentence and the scorecard (category, score, one-line evidence), including any category recorded below 3 and why. Include `SITE_LANGUAGE`, `SITE_LOCALE`, and `SITE_DIRECTION`, and ask the maker- to review linguistic correctness, terminology, tone, regional wording, and- any legal, medical, financial, or regulated text; automated checks cannot- validate language quality. Then list the sample content still in the site - search `src` for `SAMPLE CONTENT` markers and give each marker's file and what it stands in for - so the user can supply real content in this review.+ Follow it with the design thesis in one sentence and the scorecard+ (category, score, one-line evidence), including any category recorded below+ 3 and why. Include `SITE_LANGUAGE`, `SITE_LOCALE`, and `SITE_DIRECTION`.++ Present the reconciled bidirectional review scope with each component's+ classification and the applicable states/viewports exercised. Report+ direction-aware, direction-fixed, and unknown/third-party evidence+ separately; do not treat the pre-implementation plan as proof that the+ implemented component was verified.++ Link each scope entry to its rendered report cases and any captured+ screenshots. Show case totals for passed, review, and failed. Do not expose+ temporary specification internals as project configuration.++ Then report the `REVIEW_DATA.agentChecks` criteria separately with the+ evidence gathered in Phases 5–6. Every criterion must be reported as+ **Passed** or **Blocked**, never as maker verification. Fix blocked+ technical criteria before requesting approval.++ Present `REVIEW_DATA.makerReview` as the maker's live-preview checklist.+ Ask the maker to assess linguistic correctness, terminology, tone, regional+ wording, regulated content, visual hierarchy and reading flow, brand+ typography, directional imagery/icons, and text expansion. Automated checks+ cannot approve these judgment-based criteria.++ Finally, list the sample content still in the site - search `src` for+ `SAMPLE CONTENT` markers and give each marker's file and what it stands in+ for - so the user can supply real content in this review.3. Share the dev server URL with the user and list all available routes-4. Ask the user to review using `AskUserQuestion`:+4. Classify bidirectional readiness as:+ - **Ready** when no unresolved static or rendered findings remain.+ - **Ready with proposed limitations** only when all remaining findings are+ review-severity, the site remains functional/readable/accessible, and+ each finding has exact impact plus evidence.+ - **Blocked** when a deterministic error affects an available locale or the+ available site experience. Return to Phases 5–6; do not ask the maker to+ accept the defect.+ - **Ready for available locales; localization pending** when every remaining+ error belongs only to an add-localization locale that is excluded from all+ activation boundaries. Show the unavailable locale and blocker, and do+ not offer that locale for approval or enablement.+5. Ask the user to review using `AskUserQuestion`:> "The site is ready for review at `<dev server URL>`. Please check it out in your browser. Would you like any changes?"-5. If the user requests changes, apply them, re-verify by browsing via `browser_snapshot`, and re-run the axe-core audit (6.2) on every affected route - a new control, form field, or restructured section can add violations without any visual change. When a change affects what the page looks like, also run a review round on the affected routes before moving on+ For **Ready**, offer **Accept changes** and **Request revisions**. For+ proposed usable limitations, offer **Fix before handoff**, **Accept with+ documented limitations**, and **Request revisions**. Acceptance applies+ only to review-severity limitations; record the approval timestamp, impact,+ and evidence path in the final summary. If localization is configured,+ finalize the same disposition in `.powerpages-localization.json`, update+ every selector, detection, metadata, and static-output availability+ boundary, then rerun the localization validator, project build, and affected+ real-locale activation cases before proceeding.+6. If the user requests changes, apply them and repeat the applicable static,+ rendered, accessibility, and browser checks before returning to this gate.+ Re-run the axe-core audit (6.2) on every affected route because a new+ control, form field, or restructured section can add violations without any+ visual change. When a change affects appearance, also run another design+ review round on the affected routes.### 7.1 Final site-integrity gate@@ -1532,10 +1940,16 @@ Do not enter the deployment phase until it exits successfully.- Key files and their purposes- Total file count and git commit count- Sample content to replace before launch - every `SAMPLE CONTENT` marker with its file, or "None"+ - Final bidirectional readiness status, static/rendered finding totals, and+ rendered evidence path+ - Every maker-approved limitation with exact impact and evidence+ - When localization is configured, available and unavailable locales from+ the final manifest; never describe an unavailable locale as enabled7. Suggest optional enhancement skills:- `/setup-datamodel` — Create Dataverse tables for dynamic content- `/add-localization` — Add or extend SPA languages (suggest only when- `LOCALIZATION_REQUESTED=false`)+ `LOCALIZATION_REQUESTED=false` and the centralized availability result+ contains at least one available mode)- `/add-seo` — Add meta tags, robots.txt, sitemap.xml, favicon- `/add-tests` — Add unit tests (Vitest) and E2E tests (Playwright)- `/add-ai-webapi` — Add generative-AI summaries (Search Summary and Data Summarization). **Recommend first when `AI_SUMMARY_PLACEMENTS` from Phase 3 is non-empty** — the pages already carry `POWERPAGES:AI-SLOT` comment markers at the intended insertion points, so the follow-up skill's explore step finds them deterministically and the user gets the AI surface they picked during discovery without any page redesign.diff --git a/plugins/power-pages/skills/create-site/assets/create-site-plan.html b/plugins/power-pages/skills/create-site/assets/create-site-plan.htmlindex 4e5468f8c..76fe26aa5 100644--- a/plugins/power-pages/skills/create-site/assets/create-site-plan.html+++ b/plugins/power-pages/skills/create-site/assets/create-site-plan.html@@ -1,5 +1,5 @@<!DOCTYPE html>-<html lang="en">+<html lang="__SITE_LOCALE__" dir="__SITE_DIRECTION__"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/>@@ -17,11 +17,11 @@*{margin:0;padding:0;box-sizing:border-box;}html{scroll-behavior:smooth;}body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}-.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;position:sticky;top:0;}+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;position:sticky;inset-block-start:0;}.topbar-left{display:flex;align-items:center;gap:14px;}.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}-.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;}+.topbar-sub{font-size:11px;color:var(--text-dim);margin-block-start:1px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;}.topbar-sep{opacity:0.5;}.topbar-right{display:flex;gap:6px;flex-wrap:wrap;}.pill{font-size:11px;padding:4px 10px;border-radius:999px;font-weight:600;letter-spacing:0.2px;border:1px solid transparent;}@@ -29,11 +29,11 @@ body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14.pill-mood{background:var(--purple-bg);color:var(--purple);border-color:var(--purple-border);}.pill-framework{background:var(--pass-bg);color:var(--pass);border-color:var(--pass-border);}.layout{display:flex;min-height:calc(100vh - 65px);}-.sidebar{width:240px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;}+.sidebar{width:240px;background:var(--surface);border-inline-end:1px solid var(--border);padding:20px 0;flex-shrink:0;}.nav-group-label{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1.2px;padding:16px 22px 6px;}-.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;}+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-inline-start:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:start;transition:all 0.15s;}.nav-btn:hover{color:var(--text);background:var(--surface2);}-.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}+.nav-btn.active{color:var(--accent);font-weight:600;border-inline-start-color:var(--accent);background:var(--accent-bg);}.nav-btn .nav-icon{font-size:15px;opacity:0.5;width:18px;text-align:center;}.nav-btn.active .nav-icon{opacity:0.9;}.content{flex:1;padding:32px 40px 72px;max-width:1060px;}@@ -47,7 +47,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.summary-box{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;margin-bottom:22px;font-size:14px;color:var(--text);line-height:1.75;}.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:24px;}.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;position:relative;overflow:hidden;box-shadow:var(--shadow-4);}-.stat-card::after{content:'';position:absolute;top:0;left:50%;transform:translateX(-50%);width:40px;height:2px;border-radius:0 0 2px 2px;background:var(--accent);}+.stat-card::after{content:'';position:absolute;inset-block-start:0;inset-inline-start:calc(50% - 20px);width:40px;height:2px;border-radius:0 0 2px 2px;background:var(--accent);}.stat-card:nth-child(2)::after{background:var(--purple);}.stat-card:nth-child(3)::after{background:var(--warn);}.stat-num{font-size:30px;font-weight:800;font-family:var(--mono);line-height:1;color:var(--text-bright);}@@ -55,7 +55,7 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:10px;transition:box-shadow 0.2s,border-color 0.2s;}.card:hover{box-shadow:var(--shadow-4);}.field-label{font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}-.chip{display:inline-flex;align-items:center;gap:5px;font-size:11px;padding:3px 10px;border-radius:4px;font-weight:600;background:var(--surface2);border:1px solid var(--border);color:var(--text);margin:0 4px 4px 0;}+.chip{display:inline-flex;align-items:center;gap:5px;font-size:11px;padding:3px 10px;border-radius:4px;font-weight:600;background:var(--surface2);border:1px solid var(--border);color:var(--text);margin-block:0 4px;margin-inline:0 4px;}.chip-accent{background:var(--accent-bg);border-color:var(--accent-border);color:var(--accent);}/* Design tab */@@ -84,21 +84,25 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.list-item-desc{font-size:12px;color:var(--text-dim);line-height:1.55;}/* Pages tab */-.page-card{background:var(--surface);border:1px solid var(--border);border-left:3px solid var(--accent);border-radius:var(--radius);padding:18px 22px;margin-bottom:10px;box-shadow:var(--shadow-4);}+.page-card{background:var(--surface);border:1px solid var(--border);border-inline-start:3px solid var(--accent);border-radius:var(--radius);padding:18px 22px;margin-bottom:10px;box-shadow:var(--shadow-4);}.page-head{display:flex;justify-content:space-between;align-items:baseline;gap:12px;flex-wrap:wrap;margin-bottom:8px;}.page-name{font-size:15px;font-weight:700;color:var(--text-bright);}.page-route{font-size:12px;font-family:var(--mono);color:var(--accent);background:var(--accent-bg);padding:2px 8px;border-radius:4px;}.page-desc{font-size:13px;color:var(--text-dim);margin-bottom:12px;}.page-subsection{margin-top:10px;}.bullet-list{list-style:none;padding:0;margin:6px 0 0;}-.bullet-list li{position:relative;padding-left:16px;font-size:12px;color:var(--text);margin-bottom:4px;}-.bullet-list li::before{content:'';position:absolute;left:4px;top:8px;width:5px;height:5px;border-radius:50%;background:var(--accent);}+.bullet-list li{position:relative;padding-inline-start:16px;font-size:12px;color:var(--text);margin-bottom:4px;}+.bullet-list li::before{content:'';position:absolute;inset-inline-start:4px;inset-block-start:8px;width:5px;height:5px;border-radius:50%;background:var(--accent);}.component-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 20px;margin-bottom:8px;}.component-head{display:flex;justify-content:space-between;gap:12px;margin-bottom:6px;flex-wrap:wrap;}.component-name{font-size:14px;font-weight:700;color:var(--text-bright);}.component-purpose{font-size:12px;color:var(--text-dim);margin-bottom:8px;}+.bidi-scope{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:10px;}+.bidi-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px;}+.bidi-card-head{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;flex-wrap:wrap;margin-bottom:8px;}+.bidi-meta{margin-top:10px;}.routes-table{width:100%;border-collapse:separate;border-spacing:0;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}-.routes-table th{text-align:left;font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;padding:10px 16px;background:var(--surface2);border-bottom:1px solid var(--border);}+.routes-table th{text-align:start;font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;padding:10px 16px;background:var(--surface2);border-bottom:1px solid var(--border);}.routes-table td{font-size:13px;padding:10px 16px;border-bottom:1px solid var(--border);}.routes-table tr:last-child td{border-bottom:none;}.routes-table td.path{font-family:var(--mono);color:var(--accent);}@@ -108,24 +112,36 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi.checklist-item{display:flex;align-items:flex-start;gap:12px;padding:12px 18px;border-bottom:1px solid var(--border);font-size:13px;color:var(--text);}.checklist-item:last-child{border-bottom:none;}.checklist-check{flex-shrink:0;width:18px;height:18px;border:1.5px solid var(--border-light);border-radius:4px;margin-top:1px;}+.review-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px;}+.review-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;box-shadow:var(--shadow-4);}+.review-card-head{padding:16px 18px;border-bottom:1px solid var(--border);background:var(--surface2);}+.review-card-title{font-size:14px;font-weight:700;color:var(--text-bright);}+.review-card-desc{font-size:12px;color:var(--text-dim);margin-block-start:3px;line-height:1.5;}+.review-card-agent{border-block-start:3px solid var(--accent);}+.review-card-maker{border-block-start:3px solid var(--purple);}+.review-card .checklist{border:0;border-radius:0;}+.review-card-agent .checklist-check{border-color:var(--accent);background:var(--accent-bg);}+.review-card-maker .checklist-check{border-color:var(--purple);background:var(--purple-bg);}.deploy-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;}.deploy-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;box-shadow:var(--shadow-4);position:relative;}.deploy-card.recommended{border-color:var(--accent-border);background:linear-gradient(135deg,var(--accent-bg),transparent);}-.deploy-card.recommended::before{content:'Recommended';position:absolute;top:-9px;right:14px;font-size:10px;font-weight:700;color:#fff;background:var(--accent);padding:3px 10px;border-radius:999px;letter-spacing:0.5px;text-transform:uppercase;}+.deploy-card.recommended::before{content:attr(data-recommended-label);position:absolute;inset-block-start:-9px;inset-inline-end:14px;font-size:10px;font-weight:700;color:#fff;background:var(--accent);padding:3px 10px;border-radius:999px;letter-spacing:0.5px;text-transform:uppercase;}.deploy-title{font-size:14px;font-weight:700;color:var(--text-bright);margin-bottom:4px;}.deploy-desc{font-size:12px;color:var(--text-dim);line-height:1.55;}.empty-note{font-size:12px;color:var(--text-dim);font-style:italic;padding:12px 0;}+.page-route,.routes-table td.path,.swatch-var,.swatch-hex,.type-name{direction:ltr;unicode-bidi:isolate;}@media (max-width:900px){.layout{flex-direction:column;}- .sidebar{width:100%;border-right:none;border-bottom:1px solid var(--border);display:flex;flex-wrap:wrap;padding:8px;}+ .sidebar{width:100%;border-inline-end:none;border-bottom:1px solid var(--border);display:flex;flex-wrap:wrap;padding:8px;}.nav-group-label{width:100%;}- .nav-btn{width:auto;border-left:none;border-bottom:2px solid transparent;padding:10px 14px;}- .nav-btn.active{border-left:none;border-bottom-color:var(--accent);}+ .nav-btn{width:auto;border-inline-start:none;border-bottom:2px solid transparent;padding:10px 14px;}+ .nav-btn.active{border-inline-start:none;border-bottom-color:var(--accent);}.content{padding:20px;}.type-grid{grid-template-columns:1fr;}.stats-grid{grid-template-columns:repeat(3,1fr);}+ .review-grid{grid-template-columns:1fr;}}</style></head>@@ -136,10 +152,10 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<div><div class="topbar-title">__PLAN_TITLE__</div><div class="topbar-sub">- <span>__SITE_NAME__</span>+ <bdi dir="auto">__SITE_NAME__</bdi><span class="topbar-sep">·</span>- <span class="pill pill-framework">__FRAMEWORK__</span>- <span class="pill">__SITE_LANGUAGE__ (__SITE_LOCALE__, __SITE_DIRECTION__)</span>+ <bdi class="pill pill-framework" dir="ltr">__FRAMEWORK__</bdi>+ <span class="pill"><span>__SITE_LANGUAGE__</span> <bdi dir="ltr">(__SITE_LOCALE__, __SITE_DIRECTION__)</bdi></span></div></div></div>@@ -151,86 +167,106 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<div class="layout"><div class="sidebar">- <div class="nav-group-label">Plan</div>- <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span> Overview</button>- <button class="nav-btn" data-tab="design"><span class="nav-icon">☀</span> Design</button>- <button class="nav-btn" data-tab="pages"><span class="nav-icon">▦</span> Pages & Components</button>- <button class="nav-btn" data-tab="deploy"><span class="nav-icon">✓</span> Deployment & Review</button>+ <div class="nav-group-label" data-label="navigation.group"></div>+ <button class="nav-btn active" data-tab="overview"><span class="nav-icon">◉</span><span data-label="navigation.overview"></span></button>+ <button class="nav-btn" data-tab="design"><span class="nav-icon">☀</span><span data-label="navigation.design"></span></button>+ <button class="nav-btn" data-tab="pages"><span class="nav-icon">▦</span><span data-label="navigation.pages"></span></button>+ <button class="nav-btn" data-tab="deploy"><span class="nav-icon">✓</span><span data-label="navigation.deployment"></span></button></div><div class="content"><!-- Overview Tab --><div class="section active" id="tab-overview">- <h2>Overview</h2>- <p class="section-desc">Implementation plan for <code>__SITE_NAME__</code></p>+ <h2 data-label="overview.title"></h2>+ <p class="section-desc" id="overviewDescription"></p><div class="summary-box" id="summaryBox"></div><script id="summaryData" type="application/json">__JSON_SUMMARY_DATA__</script>+ <script id="siteNameData" type="application/json">__JSON_SITE_NAME_DATA__</script><div class="stats-grid">- <div class="stat-card"><div class="stat-num" id="statPages">0</div><div class="stat-label">Pages</div></div>- <div class="stat-card"><div class="stat-num" id="statComponents">0</div><div class="stat-label">Shared Components</div></div>- <div class="stat-card"><div class="stat-num" id="statRoutes">0</div><div class="stat-label">Routes</div></div>+ <div class="stat-card"><div class="stat-num" id="statPages">0</div><div class="stat-label" data-label="overview.stats.pages"></div></div>+ <div class="stat-card"><div class="stat-num" id="statComponents">0</div><div class="stat-label" data-label="overview.stats.components"></div></div>+ <div class="stat-card"><div class="stat-num" id="statRoutes">0</div><div class="stat-label" data-label="overview.stats.routes"></div></div></div>- <h3>What happens next</h3>+ <h3 data-label="overview.nextSteps.title"></h3><div class="list-card" id="nextStepsList"></div></div><!-- Design Tab --><div class="section" id="tab-design">- <h2>Design</h2>- <p class="section-desc">Design direction, typography, palette, motion, and background treatments</p>+ <h2 data-label="design.title"></h2>+ <p class="section-desc" data-label="design.description"></p>- <h3>Design direction</h3>+ <h3 data-label="design.direction.title"></h3><div class="thesis" id="thesisBox"></div><div class="direction-grid" id="directionContainer"></div>- <h3>Typography</h3>+ <h3 data-label="design.typography"></h3><div class="type-grid" id="typographyContainer"></div>- <h3>Color palette</h3>+ <h3 data-label="design.palette"></h3><div class="palette-grid" id="paletteContainer"></div>- <h3>Motion & animation</h3>+ <h3 data-label="design.motion"></h3><div class="list-card" id="motionContainer"></div>- <h3>Background treatment</h3>+ <h3 data-label="design.backgrounds"></h3><div class="list-card" id="backgroundsContainer"></div></div><!-- Pages & Components Tab --><div class="section" id="tab-pages">- <h2>Pages & Components</h2>- <p class="section-desc">Pages to build, their content outline, and the shared components they rely on</p>+ <h2 data-label="pages.title"></h2>+ <p class="section-desc" data-label="pages.description"></p>- <h3>Pages</h3>+ <h3 data-label="pages.pages"></h3><div id="pagesContainer"></div>- <h3>Shared components</h3>+ <h3 data-label="pages.components"></h3><div id="componentsContainer"></div>-- <h3>Routing</h3>+ <h3 data-label="bidirectional.title"></h3>+ <p class="section-desc" data-label="bidirectional.description"></p>+ <div class="bidi-scope" id="bidirectionalReviewContainer"></div>+ <h3 data-label="pages.routing"></h3><table class="routes-table" id="routesTable">- <thead><tr><th>Path</th><th>Page</th></tr></thead>+ <thead><tr><th data-label="pages.path"></th><th data-label="pages.page"></th></tr></thead><tbody id="routesBody"></tbody></table></div><!-- Deployment & Review Tab --><div class="section" id="tab-deploy">- <h2>Deployment & Review</h2>- <p class="section-desc">Verification checklist and deployment options</p>-- <h3>Before handoff — verify</h3>- <div class="checklist" id="reviewContainer"></div>+ <h2 data-label="deployment.title"></h2>+ <p class="section-desc" data-label="deployment.description"></p>++ <h3 data-label="deployment.verify"></h3>+ <div class="review-grid">+ <section class="review-card review-card-agent">+ <div class="review-card-head">+ <div class="review-card-title" data-label="deployment.agentChecks"></div>+ <div class="review-card-desc" data-label="deployment.agentChecksDescription"></div>+ </div>+ <div class="checklist" id="agentChecksContainer"></div>+ </section>+ <section class="review-card review-card-maker">+ <div class="review-card-head">+ <div class="review-card-title" data-label="deployment.makerReview"></div>+ <div class="review-card-desc" data-label="deployment.makerReviewDescription"></div>+ </div>+ <div class="checklist" id="makerReviewContainer"></div>+ </section>+ </div>- <h3>Deployment options</h3>+ <h3 data-label="deployment.options"></h3><div class="deploy-grid" id="deploymentContainer"></div></div></div></div>+<footer style="position:fixed;inset-block-end:0;inset-inline:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;" data-label="footer.aiWarning"></footer>+<script id="designDirectionData" type="application/json">__JSON_DESIGN_DIRECTION_DATA__</script><script id="typographyData" type="application/json">__JSON_TYPOGRAPHY_DATA__</script><script id="paletteData" type="application/json">__JSON_PALETTE_DATA__</script>@@ -239,8 +275,10 @@ h3{font-size:15px;font-weight:700;color:var(--text-bright);margin-top:24px;margi<script id="pagesData" type="application/json">__JSON_PAGES_DATA__</script><script id="componentsData" type="application/json">__JSON_COMPONENTS_DATA__</script><script id="routesData" type="application/json">__JSON_ROUTES_DATA__</script>+<script id="bidirectionalReviewData" type="application/json">__JSON_BIDIRECTIONAL_REVIEW_DATA__</script><script id="reviewData" type="application/json">__JSON_REVIEW_DATA__</script><script id="deploymentData" type="application/json">__JSON_DEPLOYMENT_DATA__</script>+<script id="planLabelsData" type="application/json">__JSON_PLAN_LABELS__</script><script>function readJsonData(id){@@ -256,8 +294,10 @@ const BACKGROUNDS = readJsonData('backgroundsData');const PAGES = readJsonData('pagesData');const COMPONENTS = readJsonData('componentsData');const ROUTES = readJsonData('routesData');+const BIDIRECTIONAL_REVIEW = readJsonData('bidirectionalReviewData');const REVIEW = readJsonData('reviewData');const DEPLOYMENT = readJsonData('deploymentData');+const LABELS = readJsonData('planLabelsData');function esc(s){const d=document.createElement('div');d.textContent=s==null?'':String(s);return d.innerHTML;}function safeFontName(value) {@@ -268,6 +308,27 @@ function safeColor(value) {const color = String(value ?? '');return /^#[0-9a-f]{3,8}$/i.test(color) ? color : 'transparent';}+function label(path){+ return path.split('.').reduce((value,key)=>value&&value[key],LABELS)||path;+}+function formatLabel(path,values){+ return Object.entries(values||{}).reduce(+ (text,[key,value])=>text.split('{'+key+'}').join(String(value)),+ label(path)+ );+}++document.querySelectorAll('[data-label]').forEach(node=>{+ node.textContent=label(node.dataset.label);+});+const overviewDescription = document.getElementById('overviewDescription');+const overviewParts = label('overview.description').split('{siteName}');+overviewDescription.append(document.createTextNode(overviewParts[0]));+const siteName = document.createElement('bdi');+siteName.dir = 'auto';+siteName.textContent = readJsonData('siteNameData').text;+overviewDescription.append(siteName);+overviewDescription.append(document.createTextNode(overviewParts.slice(1).join('{siteName}')));// --- Load chosen Google Fonts for the typography preview ---(function loadFonts(){@@ -299,14 +360,14 @@ document.getElementById('statComponents').textContent = COMPONENTS.length;document.getElementById('statRoutes').textContent = ROUTES.length;const nextSteps = [- { icon:'✎', label:'Apply design tokens', desc:'Color roles, fonts, spacing, motion, and backgrounds written into your theme' },- { icon:'▦', label:'Build shared components', desc:COMPONENTS.length+' reusable component'+(COMPONENTS.length===1?'':'s')+' used across pages' },- { icon:'📄', label:'Create pages', desc:PAGES.length+' page'+(PAGES.length===1?'':'s')+' with routing and navigation, starting with Home and its hero' },- { icon:'👁', label:'Critique the design', desc:'Desktop and mobile screenshots scored against a ten-category rubric and refined in review rounds - normally up to three - with any category still short of crafted listed with its reason in your review' },- { icon:'✓', label:'Verify & accessibility', desc:'axe-core audit, Playwright checks, and user review' },+ { icon:'✎', label:label('overview.nextSteps.design.title'), desc:label('overview.nextSteps.design.description') },+ { icon:'▦', label:label('overview.nextSteps.components.title'), desc:formatLabel(COMPONENTS.length===1?'overview.nextSteps.components.descriptionOne':'overview.nextSteps.components.descriptionOther',{count:COMPONENTS.length}) },+ { icon:'📄', label:label('overview.nextSteps.pages.title'), desc:formatLabel(PAGES.length===1?'overview.nextSteps.pages.descriptionOne':'overview.nextSteps.pages.descriptionOther',{count:PAGES.length}) },+ { icon:'👁', label:label('overview.nextSteps.critique.title'), desc:label('overview.nextSteps.critique.description') },+ { icon:'✓', label:label('overview.nextSteps.verify.title'), desc:label('overview.nextSteps.verify.description') },];document.getElementById('nextStepsList').innerHTML = nextSteps.map(s =>- '<div class="list-item"><div class="list-item-icon">'+s.icon+'</div><div><div class="list-item-label">'+s.label+'</div><div class="list-item-desc">'+s.desc+'</div></div></div>'+ '<div class="list-item"><div class="list-item-icon">'+s.icon+'</div><div><div class="list-item-label">'+esc(s.label)+'</div><div class="list-item-desc">'+esc(s.desc)+'</div></div></div>').join('');// --- Design: direction (the experience brief from Phase 3) ---@@ -314,14 +375,14 @@ const thesisBox = document.getElementById('thesisBox');thesisBox.textContent = DIRECTION.thesis || '';thesisBox.hidden = !DIRECTION.thesis;const directionFields = [- { key:'heroConcept', label:'Hero concept' },- { key:'signatureMoment', label:'Signature moment' },- { key:'primaryAction', label:'Primary action' },- { key:'secondaryAction', label:'Secondary action' },- { key:'principalDoubt', label:'Principal doubt' },- { key:'proofStrategy', label:'Proof strategy' },- { key:'audience', label:'Audience and job' },- { key:'brandSource', label:'Brand source' },+ { key:'heroConcept', label:label('design.direction.heroConcept') },+ { key:'signatureMoment', label:label('design.direction.signatureMoment') },+ { key:'primaryAction', label:label('design.direction.primaryAction') },+ { key:'secondaryAction', label:label('design.direction.secondaryAction') },+ { key:'principalDoubt', label:label('design.direction.principalDoubt') },+ { key:'proofStrategy', label:label('design.direction.proofStrategy') },+ { key:'audience', label:label('design.direction.audience') },+ { key:'brandSource', label:label('design.direction.brandSource') },];document.getElementById('directionContainer').innerHTML = directionFields.filter(f => DIRECTION[f.key])@@ -333,8 +394,8 @@ document.getElementById('directionContainer').innerHTML = directionFields// --- Design: typography ---const typeContainer = document.getElementById('typographyContainer');const typeSlots = [- { slot:'primary', role:'Primary — body & UI' },- { slot:'secondary', role:'Secondary — headings' },+ { slot:'primary', role:label('design.primaryRole') },+ { slot:'secondary', role:label('design.secondaryRole') },];typeContainer.innerHTML = typeSlots.map(s => {const t = TYPOGRAPHY && TYPOGRAPHY[s.slot];@@ -342,8 +403,8 @@ typeContainer.innerHTML = typeSlots.map(s => {const fontName = safeFontName(t.name);const fam = fontName ? "'"+fontName+"', var(--sans)" : 'var(--sans)';return '<div class="type-card">'- + '<div class="type-role">'+s.role+'</div>'- + '<div class="type-sample" style="font-family:'+fam+';">'+esc(t.sample || 'Aa Bb Cc')+'</div>'+ + '<div class="type-role">'+esc(s.role)+'</div>'+ + '<div class="type-sample" style="font-family:'+fam+';">'+esc(t.sample || '')+'</div>'+ '<div class="type-name">'+esc(t.name || '')+'</div>'+ '<div class="type-reason">'+esc(t.reason || '')+'</div>'+ '</div>';@@ -362,7 +423,7 @@ document.getElementById('paletteContainer').innerHTML = PALETTE.map(c =>// --- Design: motion & backgrounds ---function renderList(arr) {- if(!arr || !arr.length) return '<div class="empty-note" style="padding:12px 18px;">None specified.</div>';+ if(!arr || !arr.length) return '<div class="empty-note" style="padding:12px 18px;">'+esc(label('common.noneSpecified'))+'</div>';return arr.map(item =>'<div class="list-item"><div class="list-item-icon">◈</div>'+ '<div><div class="list-item-label">'+esc(item.label || '')+'</div>'@@ -375,12 +436,12 @@ document.getElementById('backgroundsContainer').innerHTML = renderList(BACKGROUN// --- Pages ---document.getElementById('pagesContainer').innerHTML = PAGES.map(p => {const content = (p.content && p.content.length)- ? '<div class="page-subsection"><div class="field-label">Content</div><ul class="bullet-list">'+ ? '<div class="page-subsection"><div class="field-label">'+esc(label('pages.content'))+'</div><ul class="bullet-list">'+ p.content.map(c => '<li>'+esc(c)+'</li>').join('')+ '</ul></div>': '';const comps = (p.components && p.components.length)- ? '<div class="page-subsection"><div class="field-label">Components used</div>'+ ? '<div class="page-subsection"><div class="field-label">'+esc(label('pages.componentsUsed'))+'</div>'+ p.components.map(c => '<span class="chip">'+esc(c)+'</span>').join('')+ '</div>': '';@@ -397,28 +458,54 @@ document.getElementById('pagesContainer').innerHTML = PAGES.map(p => {// --- Components ---const compsContainer = document.getElementById('componentsContainer');if (!COMPONENTS.length) {- compsContainer.innerHTML = '<div class="empty-note">No shared components planned yet.</div>';+ compsContainer.innerHTML = '<div class="empty-note">'+esc(label('pages.noComponents'))+'</div>';} else {compsContainer.innerHTML = COMPONENTS.map(c =>'<div class="component-card">'+ '<div class="component-head"><div class="component-name">'+esc(c.name)+'</div></div>'+ (c.purpose ? '<div class="component-purpose">'+esc(c.purpose)+'</div>' : '')+ (c.usedBy && c.usedBy.length- ? '<div><div class="field-label">Used by</div>'+c.usedBy.map(u => '<span class="chip chip-accent">'+esc(u)+'</span>').join('')+'</div>'+ ? '<div><div class="field-label">'+esc(label('pages.usedBy'))+'</div>'+c.usedBy.map(u => '<span class="chip chip-accent">'+esc(u)+'</span>').join('')+'</div>': '')+ '</div>').join('');}+// --- Planned bidirectional review scope ---+const classificationLabels = {+ 'direction-neutral':'directionNeutral',+ 'direction-aware':'directionAware',+ 'direction-fixed':'directionFixed',+ 'unknown-third-party':'unknownThirdParty'+};+document.getElementById('bidirectionalReviewContainer').innerHTML =+ BIDIRECTIONAL_REVIEW.map(item =>+ '<article class="bidi-card">'+ + '<div class="bidi-card-head"><div class="component-name">'+esc(item.component)+'</div>'+ + '<span class="chip chip-accent">'+esc(label('bidirectional.classifications.'+classificationLabels[item.classification]))+'</span></div>'+ + '<div class="component-purpose"><strong>'+esc(label('bidirectional.reason'))+':</strong> '+esc(item.reason)+'</div>'+ + '<div class="bidi-meta"><div class="field-label">'+esc(label('bidirectional.states'))+'</div>'+ + item.states.map(value=>'<span class="chip">'+esc(value)+'</span>').join('')+'</div>'+ + '<div class="bidi-meta"><div class="field-label">'+esc(label('bidirectional.viewports'))+'</div>'+ + item.viewports.map(value=>'<span class="chip">'+esc(label('bidirectional.viewport.'+value))+'</span>').join('')+'</div>'+ + '<div class="bidi-meta"><div class="field-label">'+esc(label('bidirectional.checks'))+'</div>'+ + '<ul class="bullet-list">'+item.checks.map(value=>'<li>'+esc(value)+'</li>').join('')+'</ul></div>'+ + '</article>'+ ).join('');+// --- Routes ---document.getElementById('routesBody').innerHTML = ROUTES.map(r =>'<tr><td class="path">'+esc(r.path)+'</td><td>'+esc(r.page)+'</td></tr>').join('');-// --- Review checklist ----document.getElementById('reviewContainer').innerHTML = REVIEW.map(item =>- '<div class="checklist-item"><div class="checklist-check"></div><div>'+esc(item)+'</div></div>'-).join('');+// --- Review responsibilities ---+function renderChecklist(containerId, items) {+ document.getElementById(containerId).innerHTML = items.map(item =>+ '<div class="checklist-item"><div class="checklist-check"></div><div>'+esc(item)+'</div></div>'+ ).join('');+}+renderChecklist('agentChecksContainer', REVIEW.agentChecks);+renderChecklist('makerReviewContainer', REVIEW.makerReview);// --- Deployment options ---document.getElementById('deploymentContainer').innerHTML = DEPLOYMENT.map(d =>@@ -427,7 +514,9 @@ document.getElementById('deploymentContainer').innerHTML = DEPLOYMENT.map(d =>+ '<div class="deploy-desc">'+esc(d.description || '')+'</div>'+ '</div>').join('');+document.querySelectorAll('.deploy-card.recommended').forEach(card=>{+ card.dataset.recommendedLabel=label('deployment.recommended');+});</script>-<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer></body></html>diff --git a/plugins/power-pages/skills/create-site/scripts/validate-site.js b/plugins/power-pages/skills/create-site/scripts/validate-site.jsindex fbd515fbd..dbeb0226a 100644--- a/plugins/power-pages/skills/create-site/scripts/validate-site.js+++ b/plugins/power-pages/skills/create-site/scripts/validate-site.js@@ -11,9 +11,6 @@ const {resolveLocale,resolveSiteLanguageContext,} = require('../../../scripts/lib/localization-config');-const {- auditBidirectionalReadiness,-} = require('../../../scripts/lib/bidirectional-readiness');function validateSite(cwd, input = {}) {const configPath = findPath(cwd, 'powerpages.config.json');@@ -130,17 +127,6 @@ function validateSite(cwd, input = {}) {}}- // 8. New sites must be structurally safe for either writing direction. The- // audit blocks only deterministic defects; geometry that may be intentionally- // physical remains a review finding for the create-site browser pass.- const bidiAudit = auditBidirectionalReadiness(projectRoot);- for (const finding of bidiAudit.findings.filter((item) => item.severity === 'error')) {- errors.push(- `Bidirectional readiness ${finding.file}:${finding.line} ` +- `[${finding.rule}]: ${finding.message}`- );- }-if (errors.length > 0) {block('Power Pages site validation failed:\n- ' + errors.join('\n- '));}