rtl-analyzer 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +76 -52
  2. package/dist/cli.js +18 -1
  3. package/dist/codemod.js +50 -12
  4. package/dist/companion-security.js +2 -0
  5. package/dist/contextual-preview-bridge.js +113 -0
  6. package/dist/contextual-preview.js +74 -0
  7. package/dist/controlled-apply.js +222 -0
  8. package/dist/css-directional.js +60 -0
  9. package/dist/css-icons.js +51 -0
  10. package/dist/css-spacing.js +64 -0
  11. package/dist/dashboard-client.js +57 -40
  12. package/dist/dashboard-contextual-preview.js +119 -0
  13. package/dist/dashboard-data.js +1 -1
  14. package/dist/dashboard-embedded-preview.js +200 -0
  15. package/dist/dashboard-html.js +11 -10
  16. package/dist/dashboard-review-details.js +175 -0
  17. package/dist/dashboard-review-workflow.js +151 -0
  18. package/dist/directional-properties.js +53 -0
  19. package/dist/discovery.js +1 -2
  20. package/dist/eligibility.js +8 -8
  21. package/dist/evidence-store.js +110 -0
  22. package/dist/example-preview-mappings.js +98 -0
  23. package/dist/manual-change-store.js +27 -0
  24. package/dist/migration-lifecycle.js +19 -0
  25. package/dist/original-preview-runtime.js +68 -0
  26. package/dist/output-path.js +65 -0
  27. package/dist/policy-validation.js +1 -1
  28. package/dist/preview-cli.js +22 -0
  29. package/dist/preview-companion.js +621 -0
  30. package/dist/preview-configuration.js +144 -0
  31. package/dist/preview-runtime.js +98 -0
  32. package/dist/project-configuration.js +48 -0
  33. package/dist/project-root.js +12 -0
  34. package/dist/react-inline.js +65 -0
  35. package/dist/report-publisher.js +4 -7
  36. package/dist/review-approval.js +9 -0
  37. package/dist/review-session.js +199 -54
  38. package/dist/review-store.js +175 -0
  39. package/dist/review-workflow.js +554 -0
  40. package/dist/rules.js +14 -13
  41. package/dist/runtime-process.js +35 -0
  42. package/dist/scan-history.js +35 -0
  43. package/dist/scan-manifest-store.js +26 -0
  44. package/dist/scan.js +55 -4
  45. package/dist/serialization.js +1 -0
  46. package/dist/source-context.js +93 -0
  47. package/dist/source-snippets.js +3 -3
  48. package/dist/standalone-cli.js +14 -1
  49. package/dist/tailwind.js +3 -1
  50. package/dist/transformations.js +20 -0
  51. package/dist/validation.js +71 -0
  52. package/dist/workflow-validation.js +46 -0
  53. package/package.json +17 -8
package/README.md CHANGED
@@ -1,83 +1,107 @@
1
- # RTL Analyzer CLI
1
+ # RTL Analyzer
2
2
 
3
- RTL Analyzer performs read-only RTL risk scans and can emit JSON, Markdown, structured Markdown, or a self-contained dashboard HTML report.
3
+ Find direction-dependent styles, inspect suggested fixes, and review changes for RTL and LTR interfaces.
4
+
5
+ [View on npm](https://www.npmjs.com/package/rtl-analyzer) · [Quick start](#quick-start) · [Review modes](#review-modes) · [Example](#example) · [Developer testing guide](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md)
4
6
 
5
7
  ## Quick start
6
8
 
7
- No global installation is required:
9
+ Requires **Node.js 22.12 or later**. Run from your frontend project's root:
8
10
 
9
- ```bash
11
+ ```sh
10
12
  npx rtl-analyzer
11
13
  ```
12
14
 
13
- With no arguments, RTL Analyzer recursively scans the current working directory, writes JSON, Markdown, structured Markdown, and HTML dashboard files to a unique temporary directory outside the project, then opens the dashboard in your default browser. When the dashboard is successfully generated, the CLI prints its path. If the browser cannot be opened, use that printed path instead.
15
+ Or install as a development dependency:
14
16
 
15
- On the first run, npm may ask for confirmation before installing the package. Confirm the prompt, or use `npx --yes rtl-analyzer` in scripts and other non-interactive environments.
17
+ ```sh
18
+ npm install --save-dev rtl-analyzer
19
+ npx --no-install rtl-analyzer
20
+ ```
16
21
 
17
- Use `--help` to see the available options:
22
+ The default command scans the current directory, writes reports to an external temporary directory and requests your default browser. It does not start the live review services. For a scan of a specific directory or command help:
18
23
 
19
- ```bash
24
+ ```sh
25
+ npx rtl-analyzer scan ./src --format json
20
26
  npx rtl-analyzer --help
21
- npx rtl-analyzer --version
27
+ npx rtl-analyzer preview --help
22
28
  ```
23
29
 
24
- For explicit scans, preserve control over the root, format, and output directory:
30
+ Read-only recursive scans need no configuration. **Live Fix Studio review requires configuration**: explicit scan/copy scope and validation scripts in `rtl-project.config.json`, source/selector/route bindings in `rtl-preview.config.json`, your project's installed dependencies, and Chromium. The current runtime adapter supports Vite-compatible development scripts. Follow the [developer testing guide](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md) to generate a source-enabled dashboard, serve it and start the companion with `npx --no-install rtl-analyzer preview`.
25
31
 
26
- ```bash
27
- npx rtl-analyzer scan . --format json
28
- npx rtl-analyzer scan ./src --format markdown --output-dir ./rtl-report
29
- npx rtl-analyzer scan . --format dashboard --output-dir ./rtl-report
30
- ```
32
+ ## What you can review
33
+
34
+ | In Fix Studio | What it helps you understand |
35
+ | --- | --- |
36
+ | Findings list | Which direction-dependent patterns need attention |
37
+ | Highlighted source | Where a finding appears in your code |
38
+ | Details | Why the pattern may affect RTL behavior |
39
+ | Before / After | What the suggested fix changes |
40
+ | Component Review | How the change fits the component's intended behavior |
41
+ | Decision | Whether to accept the proposed change |
42
+
43
+ ## Review modes
44
+
45
+ | Mode | Workflow | Choose it when… |
46
+ | --- | --- | --- |
47
+ | Prepare all, then review | Prepare supported suggestions in an isolated candidate, then inspect them together. | You want to review the proposals together. |
48
+ | Review one by one | Prepare and inspect a selected suggestion in isolation. | You want to examine each proposal individually. |
31
49
 
32
- Options include `--root <path>`, `--format <format>`, `--output-dir <path>`, `--fail-on-findings`, and `--embed-source-snippets` (dashboard output only). Explicit scans do not open a browser automatically.
50
+ Both modes start **Pending**. Preparation leaves your source unchanged. Explicitly accept the proposals you want, run **Validate changes** on that accepted set, then use the separate **Apply accepted changes to source** action. Receipt-backed rollback restores applied changes when the source still matches the receipt. The persisted batch-mode identifier remains `apply-first`.
33
51
 
34
- ## Developer build and pack
52
+ ## Example
35
53
 
36
- From a fresh checkout, install the repository dependencies, then build and pack the standalone package:
54
+ A card uses physical left and right spacing:
37
55
 
38
- ```bash
39
- npm ci
40
- npm run build --prefix packages/rtl-analyzer
41
- cd packages/rtl-analyzer
42
- npm pack --dry-run
43
- npm pack
56
+ ```css
57
+ .card {
58
+ margin-left: 16px;
59
+ padding-right: 24px;
60
+ text-align: left;
61
+ }
44
62
  ```
45
63
 
46
- The package `prepack` hook rebuilds `dist/` automatically, so packing cannot silently use a missing or stale CLI build. The tarball contains only the compiled scanner/reporting runtime, this README, and the MIT license.
64
+ A suggested change uses logical properties:
47
65
 
48
- ## Confirmed syntax coverage
66
+ ```css
67
+ .card {
68
+ margin-inline-start: 16px;
69
+ padding-inline-end: 24px;
70
+ text-align: start;
71
+ }
72
+ ```
49
73
 
50
- The standalone CLI supports the following tested patterns. These are syntax-level results, not claims of complete framework compatibility:
74
+ In horizontal writing mode (`horizontal-tb`), inline-start maps to the left in LTR and to the right in RTL. Use this change when the spacing should follow the text direction; keep physical positioning when the design requires a fixed side.
51
75
 
52
- | Area | Status | Tested scope |
53
- | --- | --- | --- |
54
- | React inline JSX/TSX styles | Verified | Static object properties including physical margins, padding, and text alignment. |
55
- | Emotion `styled` templates | Verified | Static tagged templates imported from `@emotion/styled`. |
56
- | Emotion `css` prop | Verified | `@emotion/react` tagged templates and static object expressions. |
57
- | MUI `sx` | Partial | Supported MUI imports and aliases such as `ml` and `pr`; wrapper semantics remain conservative. |
58
- | MUI `styled` templates | Verified | Static tagged templates imported from `@mui/material/styles`. |
59
- | Vanilla CSS/HTML | Verified | Tested physical declarations and HTML direction attributes. |
60
- | CSS Modules | Verified | Physical declarations in discovered `.module.css` files. |
61
- | Tailwind utilities | Partial | Static class strings recognize `ml-*`, `mr-*`, `pl-*`, `pr-*`, `left-*`, `right-*`, `border-l-*`, `border-r-*`, `text-left`, `text-right`, and identifiable `rtl:`/`ltr:` variants. Dynamic composition is not evaluated. |
62
- | Bootstrap 4 directional utilities | Partial | Static class strings recognize Bootstrap 4 `float-left/right`, responsive `float-{sm,md,lg,xl}-left/right`, `text-{sm,md,lg,xl}-left/right`, and `border-left/right[-0]`. Shared physical classes such as `ml-*` remain framework-neutral; Bootstrap version and runtime semantics are not inferred. |
63
- | SCSS/Sass | Unsupported with diagnostic | Files are skipped and reported through `SOURCE_COVERAGE`. |
76
+ ## A typical review
64
77
 
65
- MUI `styled` object syntax is unsupported. Tailwind responsive/state prefixes and arbitrary values are covered only when the final utility is statically identifiable; dynamic `clsx`, `classnames`, and template expressions are intentionally not guessed. Next.js `app/`, `src/app/`, `pages/`, and `src/pages/` layouts can be discovered as ordinary files, but this does not certify Next.js-specific behavior.
78
+ 1. Configure the project and scan it with source snippets enabled.
79
+ 2. Start the dashboard server and companion, then choose a review mode.
80
+ 3. Inspect a finding, its highlighted source and the mapped component.
81
+ 4. Compare the original code with the suggestion in RTL and LTR.
82
+ 5. Accept, reject or defer the proposal according to the component's intent.
83
+ 6. Validate the accepted set, then separately apply it to source.
84
+ 7. Verify the affected interface in both RTL and LTR.
66
85
 
67
- Bootstrap support is limited to the listed Bootstrap 4 physical utility forms. Bootstrap 5 logical utilities such as `ms-*`, `me-*`, `ps-*`, and `pe-*`, custom classes, project configuration, and dynamic class composition are not interpreted.
86
+ If source or accepted decisions change during review, freshness checks can invalidate suggestions or validation. Failed or unavailable required evidence blocks source Apply.
68
87
 
69
- To verify the tarball in an independent disposable project:
88
+ ## What a scan does—and what still needs checking
70
89
 
71
- ```bash
72
- npm run rtl:cli:package:smoke
73
- ```
90
+ | The tool helps with | You still need to check |
91
+ | --- | --- |
92
+ | Finding direction-dependent code patterns | Whether the pattern is actually a bug |
93
+ | Suggesting direction-aware alternatives | Whether the change matches the design |
94
+ | Showing source context and proposed changes | The rendered component in RTL and LTR |
95
+ | Identifying potentially stale suggestions | The latest source before applying a change |
74
96
 
75
- The smoke test installs with `npm install --ignore-scripts`, checks `--help` and `--version`, scans a disposable project in JSON, Markdown, and Dashboard formats, and checks that installed files contain no source-checkout paths.
97
+ Static HTML/CSS, CSS Modules, React inline styles, Emotion and MUI patterns are analyzed conservatively. Recognized utility classes and bounded SCSS declarations are detection-only; dynamic or ambiguous syntax may remain unsupported. A scan reports potential issues. It does not prove that a page renders correctly or replace browser testing.
76
98
 
77
- ```bash
78
- npm install rtl-analyzer
79
- rtl-analyzer --help
80
- rtl-analyzer scan . --format json
81
- ```
99
+ Report publication and protected source operations use a trusted POSIX filesystem profile on macOS/Linux. Windows protected operations are unsupported. Safari, other package managers and an existing real-world project's acceptance remain unverified; no general framework compatibility is certified. Project scripts must be trusted. See the [setup and limitations](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md) and [release evidence](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/releases/rtl-analyzer-0.3.0.md).
100
+
101
+ ## Demo
102
+
103
+ A video walkthrough and released-product screenshots have not been published yet.
104
+
105
+ ## Development
82
106
 
83
- Candidate Preview and Apply/Rollback are not included in this standalone CLI milestone.
107
+ The public package bundles the pinned implementation at build time. Consumers install `rtl-analyzer`; the internal `@atlas/rtl-scanner` package is private. Clone with submodules and follow the [build, pack and verification commands](https://github.com/FoushWare/rtl-analyzer/blob/main/docs/guides/developer-testing.md#build-pack-and-verify). The package is licensed under [MIT](https://github.com/FoushWare/rtl-analyzer/blob/main/packages/rtl-analyzer/LICENSE).
package/dist/cli.js CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  import { exitCode } from './coverage.js';
2
3
  import { scan } from './scan.js';
3
4
  import { json, markdown } from './report.js';
@@ -8,13 +9,29 @@ import { structuredMarkdown } from './structured-markdown.js';
8
9
  import { dashboardHtml } from './dashboard-html.js';
9
10
  import { extractSourceSnippets } from './source-snippets.js';
10
11
  import { pathToFileURL } from 'node:url';
12
+ import { realpathSync } from 'node:fs';
11
13
  const defaultDependencies = { scan, json, markdown, publishReports, publishArtifacts, extractSourceSnippets };
14
+ export const CLI_HELP = `Usage: rtl-scanner [options]
15
+
16
+ Read-only static analysis. Review and source Apply require the local rtl-preview companion.
17
+
18
+ --root <directory> Project root (default: current directory)
19
+ --format <format> json | markdown | markdown-structured | dashboard
20
+ --output-dir <directory> Existing external directory; never overwrites reports
21
+ --embed-source-snippets Opt-in source embedding; requires dashboard and output-dir
22
+ --fail-on-findings Exit 1 for actionable findings (incomplete analysis exits 2)
23
+ -h, --help Show this help
24
+ `;
12
25
  export async function runCli(argv, io, dependencies = defaultDependencies) {
13
26
  let root = process.cwd();
14
27
  let format = 'json';
15
28
  let gate = false;
16
29
  let outputDir;
17
30
  let embedSource = false;
31
+ if (argv.length === 1 && ['--help', '-h'].includes(argv[0])) {
32
+ io.writeStdout(CLI_HELP);
33
+ return 0;
34
+ }
18
35
  try {
19
36
  const args = argv.filter(a => { if (a === '--fail-on-findings') {
20
37
  gate = true;
@@ -70,7 +87,7 @@ export async function runCli(argv, io, dependencies = defaultDependencies) {
70
87
  return 2;
71
88
  }
72
89
  }
73
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
90
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
74
91
  const io = { writeStdout: (s) => process.stdout.write(s), writeStderr: (s) => console.error(s) };
75
92
  process.exitCode = await runCli(process.argv.slice(2), io);
76
93
  }
package/dist/codemod.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import ts from 'typescript';
2
2
  import { createHash } from 'node:crypto';
3
- import { REVIEW_SOURCE } from './review-session.js';
4
3
  import { applyReviewPatch } from './review-session.js';
5
4
  export const BIDI_TRANSFORMATION_ID = 'bidi-isolate-auto';
6
5
  export class TransformationRejected extends Error {
@@ -11,37 +10,76 @@ export class TransformationRejected extends Error {
11
10
  }
12
11
  }
13
12
  const sha = (value) => createHash('sha256').update(value).digest('hex');
14
- function hasIsolation(node) {
15
- for (let parent = node.parent; parent; parent = parent.parent) {
16
- if (ts.isJsxElement(parent) || ts.isJsxSelfClosingElement(parent)) {
17
- const opening = ts.isJsxElement(parent) ? parent.openingElement : parent;
18
- const tag = opening.tagName.getText();
19
- if (tag === 'bdi' || opening.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText() === 'dir'))
13
+ /** Detection keeps uncertain direction ancestors visible; proposals never overwrite them. */
14
+ export function hasIsolation(node, detection = false) {
15
+ for (let parent = node; parent; parent = parent.parent) {
16
+ if (!(ts.isJsxElement(parent) || ts.isJsxSelfClosingElement(parent)))
17
+ continue;
18
+ const opening = ts.isJsxElement(parent) ? parent.openingElement : parent;
19
+ const tag = opening.tagName.getText();
20
+ if (tag === 'bdi' || tag === 'bdo')
21
+ return true;
22
+ for (const p of opening.attributes.properties) {
23
+ if (ts.isJsxSpreadAttribute(p)) {
24
+ if (!detection)
25
+ return true;
26
+ continue;
27
+ }
28
+ if (p.name.getText() === 'dir' && (!detection || p.initializer && ts.isStringLiteral(p.initializer) && ['ltr', 'auto'].includes(p.initializer.text)))
20
29
  return true;
30
+ if (p.name.getText() !== 'style')
31
+ continue;
32
+ const expression = p.initializer && ts.isJsxExpression(p.initializer) ? p.initializer.expression : undefined;
33
+ if (!expression || !ts.isObjectLiteralExpression(expression)) {
34
+ if (!detection)
35
+ return true;
36
+ continue;
37
+ }
38
+ for (const prop of expression.properties) {
39
+ if (!ts.isPropertyAssignment(prop)) {
40
+ if (!detection)
41
+ return true;
42
+ continue;
43
+ }
44
+ const key = ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name) ? prop.name.text : prop.name.getText();
45
+ if (!detection && ['direction', 'unicodeBidi', 'writingMode'].includes(key))
46
+ return true;
47
+ if (detection && key === 'unicodeBidi' && ts.isStringLiteral(prop.initializer) && ['isolate', 'isolate-override', 'plaintext'].includes(prop.initializer.text))
48
+ return true;
49
+ }
21
50
  }
22
51
  }
23
52
  return false;
24
53
  }
25
54
  export function proposeBidiIsolation(finding, source) {
26
- if (finding.id !== 'RTL.BIDI.ISOLATION:741d2ce2aec3a86cf2db37ea' || finding.path !== REVIEW_SOURCE)
55
+ if (finding.ruleId !== 'RTL.BIDI.ISOLATION' || !/^RTL\.BIDI\.ISOLATION:[a-f0-9]{24,64}$/.test(finding.id) || !/[.][jt]sx$/.test(finding.path) || /[\\\x00-\x1f]/.test(finding.path) || finding.path.startsWith('/') || finding.path.split('/').some(p => !p || p === '.' || p === '..'))
27
56
  throw new TransformationRejected('UNSUPPORTED_FINDING_IDENTITY');
28
- const file = ts.createSourceFile(REVIEW_SOURCE, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
57
+ if (finding.exceptionReason || ['INTENTIONAL_LTR', 'INFORMATIONAL'].includes(finding.category))
58
+ throw new TransformationRejected('INTENTIONAL_CONTENT_REQUIRES_REVIEW');
59
+ const file = ts.createSourceFile(finding.path, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
29
60
  let target;
30
61
  function visit(node) { if (ts.isJsxExpression(node) && node.getStart(file) === finding.range.start.offset && node.end === finding.range.end.offset)
31
62
  target = node; ts.forEachChild(node, visit); }
32
63
  visit(file);
33
64
  if (!target)
34
65
  throw new TransformationRejected('UNSUPPORTED_AST_RANGE');
35
- if (!target.expression || !ts.isPropertyAccessExpression(target.expression) || target.expression.name.text !== 'id')
66
+ if (!target.expression || !ts.isPropertyAccessExpression(target.expression) || !ts.isIdentifier(target.expression.expression) || !['id', 'name', 'email', 'address'].includes(target.expression.name.text))
36
67
  throw new TransformationRejected('AMBIGUOUS_TOKEN_EXPRESSION');
37
68
  if (hasIsolation(target))
38
69
  throw new TransformationRejected('ALREADY_ISOLATED');
39
70
  if (!target.parent || !(ts.isJsxElement(target.parent) || ts.isJsxFragment(target.parent)))
40
71
  throw new TransformationRejected('UNSUPPORTED_WRAPPER');
72
+ const textContainers = new Set(['Link', 'a', 'span', 'div', 'p', 'strong', 'small', 'label', 'li', 'td', 'th', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
73
+ if (ts.isJsxElement(target.parent) && !textContainers.has(target.parent.openingElement.tagName.getText(file)))
74
+ throw new TransformationRejected('UNSUPPORTED_TEXT_CONTAINER');
75
+ for (let ancestor = target.parent; ancestor; ancestor = ancestor.parent) {
76
+ if (ts.isJsxElement(ancestor) && ['svg', 'math', 'script', 'style', 'textarea', 'title', 'option', 'select'].includes(ancestor.openingElement.tagName.getText(file)))
77
+ throw new TransformationRejected('UNSAFE_HTML_CONTEXT');
78
+ }
41
79
  const original = source.slice(finding.range.start.offset, finding.range.end.offset);
42
- if (original !== '{i.id}')
80
+ if (original !== finding.original)
43
81
  throw new TransformationRejected('SOURCE_RANGE_MISMATCH');
44
- return { transformationId: BIDI_TRANSFORMATION_ID, reason: 'Direct invoice ID property access in JSX; wrap the exact expression in auto-direction bidi isolation.', patch: { findingId: finding.id, path: REVIEW_SOURCE, startOffset: finding.range.start.offset, endOffset: finding.range.end.offset, expectedSha256: sha(original), replacement: '<bdi dir="auto">{i.id}</bdi>' } };
82
+ return { transformationId: BIDI_TRANSFORMATION_ID, reason: 'Requires semantic review: direct identifier.id/name/email/address text child in JSX; wrap only the verified expression in auto-direction bidi isolation. Preserve canonical text and copying; inspect punctuation in both directions.', patch: { findingId: finding.id, path: finding.path, startOffset: finding.range.start.offset, endOffset: finding.range.end.offset, expectedSha256: sha(original), replacement: '<bdi dir="auto">' + original + '</bdi>' } };
45
83
  }
46
84
  export async function dryRunBidiIsolation(session, finding, source) {
47
85
  const proposal = proposeBidiIsolation(finding, source);
@@ -0,0 +1,2 @@
1
+ export const DASHBOARD_ORIGIN = 'http://127.0.0.1:4320';
2
+ export function isAllowedDashboardOrigin(origin) { return origin === DASHBOARD_ORIGIN; }
@@ -0,0 +1,113 @@
1
+ /** Installed only by the generated local Vite preview config, before the real app entry. */
2
+ export const contextualBridgeSource = String.raw `
3
+ function installContextPreview(config){
4
+ if(!config.bindings.length)return;
5
+ const parent=window.parent,identity=config.identity,dashboardOrigin=config.dashboardOrigin;
6
+ const dataId=parent!==window&&/^rtl-preview:[a-f0-9-]{36}$/.test(window.name)?window.name.slice(12):null;
7
+ const storageKey=config.dataAdapter!=='none'&&dataId?'rtl-analyzer-preview:atlas-seed-v1:'+dataId:null;
8
+ window.__rtlPreviewStorageKey=storageKey;
9
+ let releaseData;window.__rtlPreviewDataReady=storageKey?new Promise(resolve=>releaseData=resolve):Promise.resolve();
10
+ let initialized=!storageKey,active=null,preparing=false,lastScroll='',layer=null,lastFingerprint='',lastBoxes='';
11
+ const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
12
+ const visible=node=>{const r=node.getBoundingClientRect(),s=getComputedStyle(node);return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'};
13
+ const select=(selector)=>{try{return [...document.querySelectorAll(selector)].filter(n=>!n.closest('[data-rtl-context-overlay]')).slice(0,500)}catch{return []}};
14
+ function validSeed(text){try{const rows=JSON.parse(text);return text.length<100000&&Array.isArray(rows)&&rows.length<=200&&rows.every(row=>row&&typeof row.id==='string'&&row.id.length<100&&typeof row.customerId==='string'&&Array.isArray(row.items)&&row.items.length<100)}catch{return false}}
15
+ async function fingerprint(text){const bytes=await crypto.subtle.digest('SHA-256',new TextEncoder().encode(text));return [...new Uint8Array(bytes)].map(n=>n.toString(16).padStart(2,'0')).join('')}
16
+ function resolveData(request){
17
+ if(initialized)return true;if(!Array.isArray(window.__rtlPreviewSeedInvoices))return false;
18
+ const existing=localStorage.getItem(storageKey),seed=request.seedData||JSON.stringify(window.__rtlPreviewSeedInvoices);
19
+ if(!validSeed(seed)||existing&&!validSeed(existing))return false;
20
+ if(identity.role==='candidate'&&!request.seedData)return false;
21
+ if(!existing)localStorage.setItem(storageKey,seed);
22
+ initialized=true;releaseData();return true;
23
+ }
24
+ function routeMatches(route,request){if(location.pathname!==route.path)return false;if(!route.urls)return true;if(!['ltr','rtl'].includes(request.mode))return false;const expected=new URL(route.urls[request.mode],location.origin),actual=new URL(location.href);return [...expected.searchParams].every(([key,value])=>actual.searchParams.get(key)===value);}
25
+ function inputValue(input,value){const setter=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;setter.call(input,value);input.dispatchEvent(new Event('input',{bubbles:true}));input.dispatchEvent(new Event('change',{bubbles:true}))}
26
+ async function until(fn){for(let i=0;i<70;i++){const result=fn();if(result)return result;await wait(40)}return null}
27
+ async function openCustomerMenu(){const combo=document.querySelector('.form-grid [role="combobox"]');if(!combo)return;combo.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,button:0}));await until(()=>document.querySelector('[role="listbox"]'))}
28
+ async function prepare(route,mapping){
29
+ if(['customer-menu','invoice-confirm'].includes(route.prepare))await until(()=>document.querySelector('.form-grid [role="combobox"]'));
30
+ if(route.prepare==='customer-dialog')await until(()=>document.querySelector('.customer-card button'));
31
+ if(route.prepare==='sidebar')await until(()=>document.querySelector('aside'));
32
+ if(route.prepare==='sidebar'){
33
+ const aside=document.querySelector('aside');if(aside&&aside.getBoundingClientRect().right<=1||aside&&aside.getBoundingClientRect().left>=innerWidth){document.querySelector('.mobile-menu')?.click();await wait(100)}
34
+ }
35
+ if(route.prepare==='customer-dialog'&&!document.querySelector('.MuiDialogContent-root')){document.querySelector('.customer-card button')?.click();await until(()=>document.querySelector('.MuiDialogContent-root'))}
36
+ if(route.prepare==='customer-menu'&&!document.querySelector('[role="listbox"]'))await openCustomerMenu();
37
+ if(route.prepare==='invoice-confirm'&&!document.querySelector('.MuiDialogContent-root')){
38
+ const combo=document.querySelector('.form-grid [role="combobox"]');
39
+ if(combo&&!combo.textContent.trim().replace(/\u200b/g,'')){await openCustomerMenu();document.querySelector('[role="option"]')?.click();await wait(60)}
40
+ const inputs=[...document.querySelectorAll('.line-item input')];if(inputs[0]&&!inputs[0].value){inputValue(inputs[0],'RTL preview scenario');await wait(80)}if(inputs[2]&&!(Number(inputs[2].value)>0))inputValue(inputs[2],'125');
41
+ await wait(60);document.querySelector('form button[type="submit"]')?.click();await until(()=>document.querySelector('.MuiDialogContent-root'));
42
+ }
43
+ }
44
+ let cssEpoch=0,cssSignature='',cssCache=new WeakMap();
45
+ const invalidateCss=()=>cssEpoch++;
46
+ new MutationObserver(records=>{if(records.some(record=>{const node=record.target.nodeType===1?record.target:record.target.parentElement;return !node?.closest('[data-rtl-context-overlay]')}))invalidateCss()}).observe(document.documentElement,{subtree:true,childList:true,attributes:true,characterData:true});
47
+ for(const type of ['pointerover','pointerout','focusin','focusout','input','change','click'])document.addEventListener(type,invalidateCss,true);
48
+ window.addEventListener('hashchange',invalidateCss);window.addEventListener('resize',invalidateCss);
49
+ function specificity(selector){const clean=selector.replace(/:where\([^)]*\)/g,'').replace(/::[\w-]+/g,'').replace(/:(is|not|has)\(/g,'(');return [(clean.match(/#[\w-]+/g)||[]).length,(clean.match(/\.[\w-]+|\[[^\]]+\]|:[\w-]+/g)||[]).length,(clean.replace(/#[\w-]+|\.[\w-]+|\[[^\]]+\]|:[\w-]+/g,'').match(/(?:^|[\s>+~(])([a-z][\w-]*)/gi)||[]).length]}
50
+ function styleRules(){const out=[];let order=0;function walk(rules,owner,conditions,enabled){for(const rule of rules){if(rule.selectorText&&rule.style)out.push({rule,owner,conditions,enabled,order:order++});else if(rule.cssRules){let active=enabled;const condition=rule.conditionText||'';if(rule.constructor.name==='CSSMediaRule')active=active&&matchMedia(condition).matches;else if(rule.constructor.name==='CSSSupportsRule')active=active&&CSS.supports(condition);walk(rule.cssRules,owner,condition?[...conditions,condition]:conditions,active)}}}for(const sheet of document.styleSheets){try{walk(sheet.cssRules,sheet.ownerNode,[],!sheet.disabled&&(!sheet.media?.mediaText||matchMedia(sheet.media.mediaText).matches))}catch{}}return out}
51
+ function cssResult(node,css,finding,rules){
52
+ const key=[cssEpoch,finding.id,css.property,document.documentElement.dir,innerWidth,innerHeight].join('|'),cached=cssCache.get(node);
53
+ if(cached?.key===key&&getComputedStyle(node).getPropertyValue(cached.result.resolvedProperty)===cached.result.computedValue)return cached.result;
54
+ let property=css.property;const opposite={'margin-left':'margin-right','margin-right':'margin-left','right':'left','left':'right'};
55
+ if(css.inline&&!node.style.getPropertyValue(property)&&document.documentElement.dir==='rtl'&&opposite[property]&&rules.some(r=>r.enabled&&r.rule.style.getPropertyValue(opposite[property])===css.value&&safeMatches(node,r.rule.selectorText)))property=opposite[property];
56
+ const applicable=[],sources=[];
57
+ for(const entry of rules){const {rule}=entry;if(!safeMatches(node,rule.selectorText))continue;const value=rule.style.getPropertyValue(property);if(!value)continue;const spec=rule.selectorText.split(',').filter(s=>safeMatches(node,s)).map(specificity).sort(compare).at(-1)||[0,0,0];const source=css.selector?entry.owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/').includes('/'+finding.path)&&rule.selectorText.split(',').map(s=>s.trim()).includes(css.selector):value.replace(/\s/g,'')===css.value.replace(/\s/g,'');
58
+ const candidate={...entry,value,source,rank:[rule.style.getPropertyPriority(property)==='important'?1:0,0,...spec,entry.order]};if(source)sources.push(candidate);if(entry.enabled)applicable.push(candidate);
59
+ }
60
+ if(node.style.getPropertyValue(property)){const candidate={value:node.style.getPropertyValue(property),source:!!css.inline,conditions:[],enabled:true,rank:[node.style.getPropertyPriority(property)==='important'?1:0,1,0,0,0,1e9]};applicable.push(candidate);if(candidate.source)sources.push(candidate)}
61
+ const winner=applicable.sort((a,b)=>compare(a.rank,b.rank)).at(-1),conditionActive=(!css.media||matchMedia(css.media).matches)&&(!css.rtlOnly||document.documentElement.dir==='rtl'&&!node.classList.contains('is-open'));
62
+ const result={sourceProperty:css.property,resolvedProperty:property,declaredValue:css.value,computedValue:getComputedStyle(node).getPropertyValue(property),selectorMatched:true,conditionActive,contribution:!conditionActive?'inactive':winner?.source?'contributing':sources.some(s=>s.enabled)?'overridden':'unresolved-cascade',winner:winner?{value:winner.value,selector:winner.rule?.selectorText||'style attribute',conditions:winner.conditions}:null,limitation:'CSSOM cascade attribution for these example rules (normal/important, specificity, order, media/supports, inline and generated sx); no universal layered/shadow stylesheet analysis. A contribution is not an RTL-defect verdict.'};cssCache.set(node,{key,result});return result;
63
+ }
64
+ function compare(a,b){for(let i=0;i<Math.max(a.length,b.length);i++){const delta=(a[i]||0)-(b[i]||0);if(delta)return delta}return 0}
65
+ function safeMatches(node,selector){try{return node.matches(selector)}catch{return false}}
66
+ function boxes(nodes,instance){const chosen=instance===-2?[]:instance<0?nodes:nodes.slice(instance,instance+1),signature=JSON.stringify([innerWidth,innerHeight,chosen.map(node=>{const r=node.getBoundingClientRect();return [nodes.indexOf(node),visible(node),r.x,r.y,r.width,r.height]})]);if(layer&&signature===lastBoxes)return;lastBoxes=signature;if(!layer){layer=document.createElement('div');layer.dataset.rtlContextOverlay='true';Object.assign(layer.style,{position:'fixed',inset:'0',pointerEvents:'none',zIndex:'2147483647',overflow:'hidden'});document.body.append(layer)}const selected=instance===-2?[]:instance<0?nodes:nodes.slice(instance,instance+1);layer.replaceChildren();for(const node of selected){if(!visible(node))continue;const r=node.getBoundingClientRect(),index=nodes.indexOf(node),box=document.createElement('div');box.className='rtl-context-highlight';box.dataset.targetIndex=String(index);const outside=r.right<=0||r.bottom<=0||r.left>=innerWidth||r.top>=innerHeight;Object.assign(box.style,{position:'absolute',left:Math.max(1,r.left)+'px',top:Math.max(1,r.top)+'px',width:Math.max(2,Math.min(r.width,innerWidth-Math.max(1,r.left)-2))+'px',height:Math.max(2,Math.min(r.height,innerHeight-Math.max(1,r.top)-2))+'px',outline:'3px solid #e26b00',outlineOffset:'-2px',background:'rgba(255,163,40,.07)',boxSizing:'border-box'});if(outside){box.style.left='4px';box.style.top='4px';box.style.width='230px';box.style.height='30px';box.textContent='Target '+(index+1)+' is outside the viewport';box.style.background='#fff4db';box.style.color='#6e3500'}layer.append(box)}}
67
+ document.addEventListener('click',event=>{const anchor=event.target.closest?.('a[href]');if(!anchor||!active)return;const url=new URL(anchor.href,location.href);if(['localhost','127.0.0.1'].includes(url.hostname)&&['4200','4201'].includes(url.port)&&url.origin!==location.origin){event.preventDefault();event.stopPropagation();parent.postMessage({type:'rtl-context-navigation',version:2,nonce:active.request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:active.request.sessionId,runtimeSessionId:identity.sessionId,findingId:active.request.findingId,sourcePath:active.request.sourcePath,sourceSha256:config.sourceHashes[active.request.sourcePath],routeId:active.request.routeId,nextApplication:url.port==='4201'?'procurement':'invoicing'},dashboardOrigin)}},true);
68
+ let paintPending=false;const repaint=()=>{if(paintPending||!active)return;paintPending=true;requestAnimationFrame(()=>{paintPending=false;if(active)boxes(select(active.mapping.selector),active.instance)})};
69
+ window.addEventListener('scroll',repaint,true);window.addEventListener('resize',repaint);
70
+ window.addEventListener('message',async event=>{
71
+ const request=event.data;
72
+ if(event.origin!==dashboardOrigin||event.source!==parent||!request||request.type!=='rtl-context-probe'||request.version!==2||typeof request.nonce!=='string'||request.nonce.length>100||request.role!==identity.role||request.application!==identity.application||request.runtimeSessionId!==identity.sessionId||request.projectRoot!==identity.projectRoot||typeof request.sessionId!=='string'||request.sessionId.length>100||typeof request.sourceSha256!=='string'||request.sourceSha256!==config.sourceHashes[request.sourcePath]||!Number.isInteger(request.instance)||request.instance< -2||request.instance>500)return;
73
+ const binding=config.bindings.find(b=>b.finding.id===request.findingId&&b.finding.path===request.sourcePath);if(!binding)return;
74
+ const route=binding.mapping.routes.find(r=>r.id===request.routeId&&r.application===identity.application);if(!route)return;
75
+ if(!resolveData(request))return;
76
+ const key=[request.nonce,request.findingId,request.routeId].join('|');
77
+ if(!active||active.key!==key){active={key,mapping:binding.mapping,instance:request.instance,request};lastScroll='';preparing=true;try{await until(()=>document.querySelector(config.readySelector||'#root > *'));if(routeMatches(route,request))await prepare(route,binding.mapping)}finally{if(active?.key===key)preparing=false}}
78
+ if(active?.key!==key)return;active.instance=request.instance;active.request=request;
79
+ if(request.command==='reveal-navigation'){document.querySelector('.mobile-menu')?.click();await wait(80)}
80
+ if(request.command==='reset-data'&&storageKey&&validSeed(request.seedData)){localStorage.setItem(storageKey,request.seedData);const next=new URL(route.path,location.origin);for(const key of ['demo','lang']){const value=new URLSearchParams(location.search).get(key);if(value)next.searchParams.set(key,value)}location.replace(next.href);return}
81
+ const nodes=routeMatches(route,request)?select(binding.mapping.selector):[];
82
+ if(request.command==='highlight')lastScroll='';
83
+ const scrollKey=key+':'+request.instance+':'+nodes.length;if(request.instance!==-2&&nodes.length&&lastScroll!==scrollKey){const node=nodes[Math.max(0,request.instance)]||nodes[0];if(visible(node))node.scrollIntoView({block:'center',inline:'nearest',behavior:'instant'});lastScroll=scrollKey}
84
+ boxes(nodes,request.instance);
85
+ const rules=binding.mapping.css?styleRules():[];
86
+ if(binding.mapping.css){const signature=rules.map(entry=>[entry.enabled,entry.conditions.join(' '),entry.rule.cssText].join('|')).join('\n');if(signature!==cssSignature){cssSignature=signature;cssEpoch++;cssCache=new WeakMap()}}
87
+ const sourceRules=binding.mapping.configured&&binding.mapping.sourceSelector?styleRules().filter(entry=>entry.owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\','/').endsWith('/'+binding.finding.path)&&entry.rule.selectorText.split(',').map(s=>s.trim()).includes(binding.mapping.sourceSelector)):[];
88
+ const sourceStatus=!binding.mapping.configured||!binding.mapping.sourceSelector?'not-required':!sourceRules.length?'source-not-observed':!nodes.length?'target-not-found':nodes.some(node=>sourceRules.some(entry=>safeMatches(node,entry.rule.selectorText)))?'source-rule-matched':'target-source-mismatch';
89
+ const targets=nodes.map((node,index)=>{const r=node.getBoundingClientRect();const explicitKey=node.getAttribute('id')||node.getAttribute('data-id')||node.getAttribute('data-key')||node.getAttribute('data-testid')||node.getAttribute('data-target-id');const nameSelector='h1,h2,h3,h4,h5,h6,strong,[data-name],.name,.contact-name';const h=(node.matches?.(nameSelector)?node:null)||node.querySelector?.(nameSelector);const nameText=(h?.textContent||node.getAttribute('aria-label')||node.getAttribute('title')||'').trim().replace(/\s+/g,' ');const emailSelector='.email,.contact-email,a[href^="mailto:"]';const emailEl=(node.matches?.(emailSelector)?node:null)||node.querySelector?.(emailSelector);const emailText=(emailEl?.textContent||emailEl?.getAttribute('href')?.replace(/^mailto:/,'')||'').trim();const cleanLabel=(binding.mapping.kind==='document'?'Whole document · '+document.title:(nameText||(emailText?emailText.split('@')[0]:'Target '+(index+1)))).slice(0,100);const rawCandidateKey=explicitKey||(nameText&&emailText?nameText+' · '+emailText:nameText||emailText||null);return {index,rawKey:rawCandidateKey,hasExplicitKey:!!explicitKey,label:cleanLabel,name:nameText||null,rendered:visible(node),inViewport:r.right>0&&r.bottom>0&&r.left<innerWidth&&r.top<innerHeight,rect:{x:r.x,y:r.y,width:r.width,height:r.height},...(binding.mapping.css?{css:cssResult(node,binding.mapping.css,binding.finding,rules)}:{})}});
90
+ const keyCounts={};targets.forEach(t=>{if(t.rawKey)keyCounts[t.rawKey]=(keyCounts[t.rawKey]||0)+1});
91
+ targets.forEach(t=>{
92
+ if(t.rawKey&&keyCounts[t.rawKey]===1){t.key=t.rawKey;t.keyGuaranteed=true;t.ambiguous=false}
93
+ else if(t.rawKey&&keyCounts[t.rawKey]>1){t.key=t.rawKey;t.keyGuaranteed=false;t.ambiguous=true}
94
+ else{t.key=null;t.keyGuaranteed=false;t.ambiguous=false}
95
+ });
96
+ const labelCounts={};targets.forEach(t=>{labelCounts[t.label]=(labelCounts[t.label]||0)+1});
97
+ targets.forEach(t=>{
98
+ if(labelCounts[t.label]>1){
99
+ if(t.key&&!t.ambiguous){
100
+ const disambig=t.key.includes(' · ')?t.key.split(' · ')[1]:t.key;
101
+ t.label+=' ('+disambig+')';
102
+ }else{
103
+ t.label+=' (#'+(t.index+1)+')';
104
+ }
105
+ }
106
+ });
107
+ const seedData=storageKey?localStorage.getItem(storageKey):null,defaultSeedData=JSON.stringify(window.__rtlPreviewSeedInvoices||[]);
108
+ const dataFingerprint=seedData?await fingerprint(seedData):null;if(active?.key!==key)return;lastFingerprint=dataFingerprint;
109
+ const routeReady=!!document.querySelector(config.readySelector||'#root > *');
110
+ parent.postMessage({type:'rtl-context-status',version:2,nonce:request.nonce,role:identity.role,application:identity.application,projectRoot:identity.projectRoot,sessionId:request.sessionId,runtimeSessionId:identity.sessionId,findingId:request.findingId,sourcePath:request.sourcePath,sourceSha256:config.sourceHashes[request.sourcePath],routeId:request.routeId,route:location.pathname,dir:document.documentElement.dir,routeReady,sourceStatus,targetStatus:preparing?'preparing':!routeReady?'route-not-ready':!routeMatches(route,request)?'navigated':sourceStatus==='source-not-observed'?'source-not-loaded':sourceStatus==='target-source-mismatch'?'target-mismatch':targets.some(t=>t.rendered)?binding.mapping.kind==='document'?'document':'verified':targets.length?'hidden':binding.mapping.configured?'missing-target':'unresolved',targets,dataFingerprint,seedData,defaultSeedData,dataScope:storageKey,fixtureData:config.dataAdapter==='none'?'application-data':'atlas-seed-v1'},dashboardOrigin);
111
+ });
112
+ }
113
+ `;
@@ -0,0 +1,74 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { loadPreviewConfiguration, configuredMapping, routeUrl } from './preview-configuration.js';
4
+ import { scan } from './scan.js';
5
+ import { validateProjectSourcePath, candidateApplicationRuntime } from './review-session.js';
6
+ import { composeWorkflowFile } from './review-workflow.js';
7
+ import { verifiedSourceTransition } from './source-context.js';
8
+ import { classifyEligibility } from './eligibility.js';
9
+ export const ORIGINAL_PREVIEW_ORIGINS = { invoicing: 'http://127.0.0.1:4200', procurement: 'http://127.0.0.1:4201' };
10
+ const sha = (value) => createHash('sha256').update(value).digest('hex');
11
+ export async function contextualPreview(root, query, workflow) {
12
+ const report = await scan(root);
13
+ if (report.inputDigest !== query.get('inputDigest') || report.policyDigest !== query.get('policyDigest'))
14
+ throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
15
+ const finding = report.findings.find(f => f.id === query.get('findingId'));
16
+ if (!finding)
17
+ throw Error('FINDING_NOT_IN_CURRENT_REPORT');
18
+ const historical = !!workflow && workflow.state !== 'Reviewing';
19
+ if (historical)
20
+ await verifiedSourceTransition(root, workflow);
21
+ else if (workflow && (workflow.root !== root || workflow.inputDigest !== report.inputDigest || workflow.policyDigest !== report.policyDigest))
22
+ throw Error('PREVIEW_SESSION_IDENTITY_MISMATCH');
23
+ const configuration = await loadPreviewConfiguration(root);
24
+ if (workflow && configuration.digest !== (workflow.previewConfigDigest ?? sha('')))
25
+ throw Error('PREVIEW_CONFIGURATION_CHANGED');
26
+ const mapping = configuredMapping(finding, configuration), route = mapping.routes.find(r => r.id === query.get('routeId')) || (!query.get('routeId') ? mapping.routes[0] : undefined);
27
+ const mode = query.get('mode') || 'ltr';
28
+ if (!['ltr', 'rtl'].includes(mode))
29
+ throw Error('INVALID_PREVIEW_DIRECTION');
30
+ if (mapping.routes.length && !route)
31
+ throw Error('UNAPPROVED_CONTEXT_ROUTE');
32
+ const source = await readFile(await validateProjectSourcePath(root, finding.path), 'utf8'), sourceHash = sha(source);
33
+ const identity = { projectRoot: root, inputDigest: report.inputDigest, policyDigest: report.policyDigest, findingId: finding.id, path: finding.path, line: finding.range.start.line, column: finding.range.start.column, sourceHash };
34
+ const entry = historical ? undefined : workflow?.entries.find(e => e.finding.id === finding.id);
35
+ const sessionId = historical ? null : workflow?.session?.id || null;
36
+ const eligibility = historical ? classifyEligibility(finding, true, source) : null;
37
+ const review = { inScope: historical || !workflow || !!entry, decision: entry?.decision || 'Pending', applied: entry?.applied || false, hasAutomaticFix: historical ? !!eligibility?.transformationId && !eligibility.blockers.length : !!entry?.patch, validation: historical ? 'Not run' : workflow?.validation?.state || 'Not run', workflowState: workflow?.state || 'No workflow', historical, patchInventory: historical ? [] : workflow?.entries.filter(e => e.patch && e.applied).map(e => ({ findingId: e.finding.id, path: e.finding.path, decision: e.decision })) || [] };
38
+ const candidateState = { prepared: !!sessionId, runtime: workflow?.session?.runtime?.status ?? 'not-started' };
39
+ if (!route)
40
+ return { contextVersion: 2, ...identity, mapping, route: null, original: { available: false, state: 'mapping-missing', reason: mapping.limitation }, candidate: { available: false, state: 'mapping-missing', reason: 'Preview mapping unavailable; ' + (sessionId ? 'candidate is prepared, but no route/target is configured.' : 'candidate has not been prepared.') }, candidateState, reason: mapping.limitation, sessionId, review };
41
+ const urlFor = (origin) => routeUrl(route, mode, origin);
42
+ async function runtime(origin, role, expectedRoot, sessionId, hash) {
43
+ try {
44
+ const response = await fetch(origin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(1500) });
45
+ const actual = await response.json();
46
+ if (!response.ok || actual.projectRoot !== expectedRoot || actual.role !== role || actual.sessionId !== sessionId || actual.application !== route.application || actual.previewConfigDigest !== configuration.digest || actual.inputDigest !== report.inputDigest || actual.policyDigest !== report.policyDigest || actual.sourceHashes?.[finding.path] !== hash)
47
+ return { available: false, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: 'Runtime identity/source is stale or belongs to another application. Restart the scoped preview runtime.' };
48
+ return { available: true, state: 'runtime-ready', urls: { ltr: routeUrl(route, 'ltr', origin), rtl: routeUrl(route, 'rtl', origin) }, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: null };
49
+ }
50
+ catch {
51
+ return { available: false, origin, url: urlFor(origin), sourceHash: hash, projectRoot: expectedRoot, runtimeSessionId: sessionId, reason: 'Runtime unavailable. Start the ' + route.application + ' original/candidate preview runtime; no unrelated process will be stopped.' };
52
+ }
53
+ }
54
+ const original = await runtime(configuration.applications[route.application]?.originalOrigin ?? ORIGINAL_PREVIEW_ORIGINS[route.application], 'original', root, 'original', sourceHash);
55
+ let candidate = null, candidateReason = historical ? 'No current candidate. Historical candidate, decisions and validation remain bound to the completed review; they do not validate this current analysis.' : 'No isolated candidate session. Original contextual review does not require a codemod or an apply action.';
56
+ if (workflow?.session && entry && workflow.state === 'Reviewing') {
57
+ // Verify the selected candidate file against its immutable baseline and actual patch membership.
58
+ for (const [path, baseline] of Object.entries(workflow.baseline)) {
59
+ const expected = composeWorkflowFile(baseline, workflow.entries.filter(e => e.patch?.path === path && e.applied && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision)).map(e => e.patch));
60
+ if (await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, path), 'utf8') !== expected)
61
+ throw Error('STALE_CANDIDATE_SOURCE');
62
+ }
63
+ const before = workflow.baseline[finding.path];
64
+ const expected = composeWorkflowFile(before, workflow.entries.filter(e => e.patch?.path === finding.path && e.applied && !['Rejected', 'Deferred', 'Flagged'].includes(e.decision)).map(e => e.patch));
65
+ const candidateSource = await readFile(await validateProjectSourcePath(workflow.session.candidateRoot, finding.path), 'utf8');
66
+ if (candidateSource !== expected)
67
+ throw Error('STALE_CANDIDATE_SOURCE');
68
+ const active = candidateApplicationRuntime(workflow.session, route.application);
69
+ if (active?.status === 'healthy')
70
+ candidate = await runtime(active.origin, 'candidate', workflow.session.candidateRoot, workflow.session.id, sha(candidateSource));
71
+ candidateReason = active?.status === 'healthy' ? '' : 'Candidate application runtime is stopped. Use the explicit Open candidate preview action; selecting/highlighting does not start runtimes.';
72
+ }
73
+ return { contextVersion: 2, ...identity, mapping, route, dataAdapter: configuration.applications[route.application]?.dataAdapter ?? 'atlas', original, candidate, candidateReason, candidateState, sessionId, review };
74
+ }