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
@@ -0,0 +1,35 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { loadProjectConfiguration } from './project-configuration.js';
5
+ import { loadPreviewConfiguration } from './preview-configuration.js';
6
+ /** Vite adapter only: configured dev scripts must forward standard Vite CLI arguments. */
7
+ export async function spawnPreviewRuntime(root, application, config, port, options = {}) {
8
+ const app = (await loadPreviewConfiguration(root)).applications[application];
9
+ const project = await loadProjectConfiguration(root);
10
+ const flags = ['--config', config, '--host', '127.0.0.1', '--port', String(port), '--strictPort'];
11
+ let command = process.execPath, args = [join(root, 'node_modules/vite/bin/vite.js'), ...flags];
12
+ if (app?.startupScript) {
13
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
14
+ if (typeof pkg.scripts?.[app.startupScript] !== 'string')
15
+ throw Error('PREVIEW_STARTUP_SCRIPT_MISSING');
16
+ command = project?.packageManager ?? 'npm';
17
+ args = ['run', app.startupScript, ...(command === 'npm' ? ['--'] : []), ...flags];
18
+ }
19
+ // A separate process group includes npm's Vite child. Never signal a port owner or an adopted PID.
20
+ return spawn(command, args, { cwd: root, stdio: 'ignore', ...options, shell: false, detached: process.platform !== 'win32' });
21
+ }
22
+ export function signalOwnedRuntime(child, signal = 'SIGTERM') {
23
+ if (child.exitCode !== null || child.signalCode !== null || !child.pid)
24
+ return;
25
+ try {
26
+ if (process.platform === 'win32')
27
+ child.kill(signal);
28
+ else
29
+ process.kill(-child.pid, signal);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== 'ESRCH')
33
+ throw error;
34
+ }
35
+ }
@@ -0,0 +1,35 @@
1
+ import { createHash } from 'node:crypto';
2
+ const structuralKey = (f) => `${f.ruleId}|${f.path}|${f.sourceMechanism}|${f.context}|${f.original}`;
3
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
4
+ export function manifestFromReport(report, timestamp = new Date().toISOString()) { return { scanId: digest(`${report.inputDigest}|${timestamp}`), inputDigest: report.inputDigest, policyDigest: report.policyDigest, timestamp, findings: report.findings.map(f => ({ ...f, relatedLocations: [...f.relatedLocations], evidenceIds: [...f.evidenceIds] })) }; }
5
+ export function reconcileScans(previous, current) {
6
+ if (!previous)
7
+ return current.findings.map(f => ({ findingId: f.id, currentId: f.id, status: 'New', confidence: 'Exact' }));
8
+ const oldById = new Map(previous.findings.map(f => [f.id, f]));
9
+ const oldByStructure = new Map();
10
+ for (const f of previous.findings)
11
+ oldByStructure.set(structuralKey(f), [...(oldByStructure.get(structuralKey(f)) ?? []), f]);
12
+ const seen = new Set();
13
+ const result = [];
14
+ for (const f of current.findings) {
15
+ const exact = oldById.get(f.id);
16
+ if (exact) {
17
+ seen.add(exact.id);
18
+ result.push({ findingId: exact.id, currentId: f.id, status: structuralKey(exact) === structuralKey(f) ? 'Unresolved' : 'Changed', confidence: 'Exact' });
19
+ continue;
20
+ }
21
+ const matches = oldByStructure.get(structuralKey(f)) ?? [];
22
+ if (matches.length === 1) {
23
+ seen.add(matches[0].id);
24
+ result.push({ findingId: matches[0].id, currentId: f.id, status: 'Changed', confidence: 'Structural' });
25
+ }
26
+ else if (matches.length > 1)
27
+ result.push({ findingId: f.id, currentId: f.id, status: 'Stale', confidence: 'Ambiguous' });
28
+ else
29
+ result.push({ findingId: f.id, currentId: f.id, status: 'New', confidence: 'Exact' });
30
+ }
31
+ for (const f of previous.findings)
32
+ if (!seen.has(f.id))
33
+ result.push({ findingId: f.id, status: current.sourceCoverage?.complete === false ? 'Stale' : 'Resolved', confidence: 'Exact' });
34
+ return result;
35
+ }
@@ -0,0 +1,26 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ import { DEFAULT_MANUAL_CHANGE_STORE_PATH } from './manual-change-store.js';
4
+ import { reconcileScans } from './scan-history.js';
5
+ export const DEFAULT_SCAN_MANIFEST_STORE_PATH = process.env.RTL_SCAN_MANIFEST_STORE_PATH || `${dirname(DEFAULT_MANUAL_CHANGE_STORE_PATH)}/scan-manifests-v1.json`;
6
+ export class ScanManifestStore {
7
+ path;
8
+ scans = [];
9
+ loaded = false;
10
+ constructor(path = DEFAULT_SCAN_MANIFEST_STORE_PATH) {
11
+ this.path = path;
12
+ }
13
+ async load() { try {
14
+ this.scans = JSON.parse(await readFile(this.path, 'utf8'));
15
+ }
16
+ catch (error) {
17
+ if (error.code !== 'ENOENT')
18
+ throw new Error('SCAN_MANIFEST_STORE_UNAVAILABLE');
19
+ this.scans = [];
20
+ } this.loaded = true; }
21
+ list() { return this.scans.slice().reverse(); }
22
+ latest() { return this.scans.at(-1) ?? null; }
23
+ async append(manifest) { if (!this.loaded)
24
+ throw new Error('SCAN_MANIFEST_STORE_NOT_LOADED'); if (!manifest.scanId || !manifest.inputDigest || !manifest.policyDigest || !Array.isArray(manifest.findings))
25
+ throw new Error('INVALID_SCAN_MANIFEST'); if (manifest.sourceCoverage?.complete === false) { /* incomplete scans are retained but cannot resolve absences */ } const item = { manifest, reconciliation: reconcileScans(this.latest()?.manifest ?? null, manifest) }; this.scans.push(item); await mkdir(dirname(this.path), { recursive: true, mode: 0o700 }); const tmp = `${this.path}.${process.pid}.tmp`; await writeFile(tmp, `${JSON.stringify(this.scans, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); await rename(tmp, this.path); return item; }
26
+ }
package/dist/scan.js CHANGED
@@ -1,5 +1,5 @@
1
+ import { readdir, readFile, lstat } from 'node:fs/promises';
1
2
  import { join } from 'node:path';
2
- import { readFile } from 'node:fs/promises';
3
3
  import { extractCss, extractScss } from './css.js';
4
4
  import { extractHtml } from './html.js';
5
5
  import { extractTypescript } from './typescript.js';
@@ -8,11 +8,46 @@ import { loadPolicy, policySourceText } from './policy.js';
8
8
  import { auditPolicy } from './policy-audit.js';
9
9
  import { classifyDiagnostics } from './coverage.js';
10
10
  import { hash } from './model.js';
11
+ import { loadProjectConfiguration, PROJECT_CONFIGURATION } from './project-configuration.js';
11
12
  import { discover } from './discovery.js';
12
13
  export async function scan(root) {
13
- const discovery = await discover(root);
14
- const { files, skipped } = discovery;
15
- root = discovery.root;
14
+ const files = [], skipped = [];
15
+ async function walk(relative) {
16
+ for (const e of (await readdir(join(root, relative), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : 1)) {
17
+ const p = `${relative}/${e.name}`;
18
+ if (e.isSymbolicLink()) {
19
+ skipped.push(p);
20
+ continue;
21
+ }
22
+ if (e.isDirectory()) {
23
+ if (!['node_modules', 'dist', '.nx', '.git'].includes(e.name))
24
+ await walk(p);
25
+ }
26
+ else if (/\.(css|scss|tsx?|jsx?|html)$/.test(p) && !p.endsWith('.stories.tsx'))
27
+ files.push(p);
28
+ else
29
+ skipped.push(p);
30
+ }
31
+ }
32
+ const project = await loadProjectConfiguration(root);
33
+ if (project) {
34
+ for (const path of project.scanRoots) {
35
+ const info = await lstat(join(root, path));
36
+ if (info.isDirectory())
37
+ await walk(path);
38
+ else if (/\.(css|scss|tsx?|jsx?|html)$/.test(path))
39
+ files.push(path);
40
+ else
41
+ skipped.push(path);
42
+ }
43
+ }
44
+ else {
45
+ const discovered = await discover(root);
46
+ root = discovered.root;
47
+ files.push(...discovered.files);
48
+ skipped.push(...discovered.skipped);
49
+ }
50
+ files.splice(0, files.length, ...new Set(files));
16
51
  files.sort();
17
52
  const evidence = [], diagnostics = [], inputs = [], sources = new Map();
18
53
  const policy = await loadPolicy(root);
@@ -26,6 +61,22 @@ export async function scan(root) {
26
61
  evidence.push(...r.evidence);
27
62
  diagnostics.push(...r.diagnostics);
28
63
  }
64
+ // Preview declarations are data-only context identity, not analyzed source or semantic approval.
65
+ try {
66
+ const path = join(root, 'rtl-preview.config.json'), info = await lstat(path);
67
+ if (info.isSymbolicLink())
68
+ throw Error('PREVIEW_CONFIGURATION_SYMLINK');
69
+ const text = await readFile(path, 'utf8');
70
+ if (text.length > 200000)
71
+ throw Error('PREVIEW_CONFIGURATION_SIZE');
72
+ inputs.push('rtl-preview.config.json\0' + text);
73
+ }
74
+ catch (error) {
75
+ if (error.code !== 'ENOENT')
76
+ throw error;
77
+ }
78
+ if (project)
79
+ inputs.push(PROJECT_CONFIGURATION + '\0' + await readFile(join(root, PROJECT_CONFIGURATION), 'utf8'));
29
80
  const compare = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.range.start.offset - b.range.start.offset;
30
81
  evidence.sort(compare);
31
82
  diagnostics.sort(compare);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,93 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { previewConfigurationDigest, loadPreviewConfiguration, runtimeConfigName } from './preview-configuration.js';
5
+ import { scan } from './scan.js';
6
+ import { manifestFromReport, reconcileScans } from './scan-history.js';
7
+ import { composeWorkflowFile } from './review-workflow.js';
8
+ import { validateProjectSourcePath } from './review-session.js';
9
+ import { writePreviewRuntimeConfig } from './preview-runtime.js';
10
+ const sha = (text) => createHash('sha256').update(text).digest('hex');
11
+ /** Navigation correspondence is never approval correspondence. IDs may be reused at shifted ranges. */
12
+ export function reconcileSelectedFinding(previous, report, scope = []) {
13
+ const findings = report.findings.filter(f => !scope.length || scope.includes(f.path));
14
+ const location = (f) => [f.range.start.line, f.range.start.column];
15
+ const anchor = previous && ('range' in previous ? { line: previous.range.start.line, column: previous.range.start.column } : previous);
16
+ const nearest = (values) => values.slice().sort((a, b) => Math.abs(location(a)[0] - anchor.line) - Math.abs(location(b)[0] - anchor.line) || Math.abs(location(a)[1] - anchor.column) - Math.abs(location(b)[1] - anchor.column) || a.range.start.offset - b.range.start.offset)[0];
17
+ let selected;
18
+ if (previous) {
19
+ const sameRule = findings.filter(f => f.path === previous.path && f.ruleId === previous.ruleId);
20
+ if ('original' in previous) {
21
+ const current = manifestFromReport({ ...report, findings });
22
+ const correspondence = reconcileScans({ ...current, findings: [previous] }, current).find(c => c.findingId === previous.id && c.currentId && c.status !== 'Stale');
23
+ const sameSource = sameRule.filter(f => f.original === previous.original && f.context === previous.context && f.sourceMechanism === previous.sourceMechanism);
24
+ selected = nearest(sameSource);
25
+ // A reused ID alone cannot select a different expression. Structural/location checks above are required.
26
+ if (selected && correspondence?.currentId === selected.id)
27
+ return { findingId: selected.id, matched: true, reason: 'Selected finding reconciled by source, rule and location; fresh analysis has no inherited approval.' };
28
+ }
29
+ else
30
+ selected = nearest(sameRule);
31
+ }
32
+ if (selected)
33
+ return { findingId: selected.id, matched: true, reason: 'Corresponding source/rule location selected for fresh analysis; no historical approval transferred.' };
34
+ const actionable = findings.filter(f => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category));
35
+ selected = actionable.find(f => f.path === previous?.path) || actionable[0] || findings[0];
36
+ return { findingId: selected?.id ?? null, matched: false, reason: previous ? 'The selected finding no longer exists in the current report. ' + (selected ? 'Selected a remaining finding for fresh review.' : 'No findings remain in the configured review scope.') : 'Current report selected for fresh review.' };
37
+ }
38
+ /** A closed review is historical. Only its journaled source transition may authorize a new analysis. */
39
+ export async function verifiedSourceTransition(root, workflow) {
40
+ if (workflow.root !== root || await realpath(root) !== root || !['Applied', 'Rolled Back'].includes(workflow.state) || !workflow.receipts?.length)
41
+ throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
42
+ if (await previewConfigurationDigest(root) !== (workflow.previewConfigDigest ?? sha('')))
43
+ throw Error('PREVIEW_CONFIGURATION_CHANGED');
44
+ const applied = workflow.state === 'Applied';
45
+ for (const [path, before] of Object.entries(workflow.baseline)) {
46
+ const after = composeWorkflowFile(before, workflow.entries.filter(e => e.patch?.path === path && e.applied && e.decision === 'Accepted').map(e => e.patch));
47
+ if (after !== before) {
48
+ const receipt = workflow.receipts.find(r => r.path === path);
49
+ // Partial Apply can leave planned files unwritten and without receipts. After rollback,
50
+ // those files must still match baseline below; Applied always requires every receipt.
51
+ if ((applied || receipt) && (!receipt || receipt.originalSha256 !== sha(before) || receipt.appliedSha256 !== sha(after)))
52
+ throw Error('SOURCE_TRANSITION_RECEIPT_MISMATCH');
53
+ }
54
+ const target = await validateProjectSourcePath(root, path);
55
+ if (target !== workflow.sourcePaths[path] || sha(await readFile(target, 'utf8')) !== sha(applied ? after : before))
56
+ throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
57
+ }
58
+ const report = await scan(root);
59
+ const validatedScan = workflow.validation?.checks.find(c => c.name === 'scanner' && c.state === 'Passed');
60
+ const expectedDigest = applied && validatedScan ? JSON.parse(validatedScan.detail).after : workflow.inputDigest;
61
+ if (!report.complete || report.inputDigest !== expectedDigest || report.policyDigest !== workflow.policyDigest)
62
+ throw Error('DASHBOARD_SOURCE_IDENTITY_MISMATCH');
63
+ return report;
64
+ }
65
+ /** Refresh only generated, owned development wrappers after an authorized source transition.
66
+ * Vite observes its config and restarts the same original runtime; no candidate or patch is created.
67
+ */
68
+ export async function reconcileSourceRuntimes(root) {
69
+ const report = await scan(root);
70
+ const configuration = await loadPreviewConfiguration(root);
71
+ for (const application of [...new Set(['invoicing', 'procurement', ...Object.keys(configuration.applications)])]) {
72
+ const path = join(root, '.rtl-preview', runtimeConfigName(application));
73
+ const config = await readFile(path, 'utf8').catch(error => { if (error.code === 'ENOENT')
74
+ return ''; throw error; });
75
+ if (!config.includes("name:'rtl-local-preview'"))
76
+ continue;
77
+ const source = configuration.applications[application]?.entry ?? (application === 'invoicing' ? 'apps/invoicing/src/components/InvoiceTable.tsx' : 'apps/procurement/src/App.tsx');
78
+ await writePreviewRuntimeConfig(root, { role: 'original', sessionId: 'original', sourceSha256: sha(await readFile(join(root, source), 'utf8')) }, { application });
79
+ if (await readFile(path, 'utf8') !== config) {
80
+ const origin = configuration.applications[application]?.originalOrigin ?? (application === 'invoicing' ? 'http://127.0.0.1:4200' : 'http://127.0.0.1:4201');
81
+ const expected = sha(await readFile(join(root, source), 'utf8'));
82
+ for (let attempt = 0; attempt < 30; attempt++) {
83
+ try {
84
+ const actual = await fetch(origin + '/__rtl_preview_identity', { signal: AbortSignal.timeout(500) }).then(r => r.json());
85
+ if (actual.projectRoot === root && actual.role === 'original' && actual.application === application && actual.sourceSha256 === expected && actual.inputDigest === report.inputDigest)
86
+ break;
87
+ }
88
+ catch { /* Explicit unavailable descriptors remain available if the runtime is stopped. */ }
89
+ await new Promise(resolve => setTimeout(resolve, 100));
90
+ }
91
+ }
92
+ }
93
+ }
@@ -7,14 +7,14 @@ const unavailable = (findingId, reason) => ({ findingId, available: false, reaso
7
7
  async function validatePath(root, path) {
8
8
  if (pathError(path))
9
9
  return 'INVALID_PATH';
10
- const rootAbsolute = resolve(root), portablePath = path.split('/').join(sep), normalized = normalize(portablePath), absolute = resolve(rootAbsolute, normalized), rel = relative(rootAbsolute, absolute);
11
- if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || normalized !== portablePath)
10
+ const rootAbsolute = resolve(root), normalized = normalize(path), absolute = resolve(rootAbsolute, normalized), rel = relative(rootAbsolute, absolute);
11
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel) || normalized !== path)
12
12
  return 'INVALID_PATH';
13
13
  try {
14
14
  const rootStat = await lstat(rootAbsolute);
15
15
  if (rootStat.isSymbolicLink())
16
16
  return 'SYMLINK';
17
- const parts = path.split('/');
17
+ const parts = normalized.split('/');
18
18
  let current = rootAbsolute;
19
19
  for (const part of parts) {
20
20
  current = join(current, part);
@@ -12,7 +12,7 @@ async function version() {
12
12
  return packageJson.version ?? '0.0.0';
13
13
  }
14
14
  function help() {
15
- return `RTL Analyzer — conservative RTL risk scanning\n\nUsage:\n rtl-analyzer Scan the current directory and open a dashboard\n rtl-analyzer scan [path] [options]\n rtl-analyzer --help\n rtl-analyzer --version\n\nOptions:\n --root <path> Scan this project root\n --format <format> json, markdown, markdown-structured, or dashboard\n --output-dir <path> Write report artifacts to this directory\n --fail-on-findings Exit 1 when actionable findings exist\n --embed-source-snippets Embed bounded source snippets in dashboard output\n`;
15
+ return `RTL Analyzer — conservative RTL risk scanning\n\nUsage:\n rtl-analyzer Scan the current directory and open a dashboard\n rtl-analyzer scan [path] [options]\n rtl-analyzer preview [--help]\n rtl-analyzer --help\n rtl-analyzer --version\n\nOptions:\n --root <path> Scan this project root\n --format <format> json, markdown, markdown-structured, or dashboard\n --output-dir <path> Write report artifacts to this directory\n --fail-on-findings Exit 1 when actionable findings exist\n --embed-source-snippets Embed bounded source snippets in dashboard output\n`;
16
16
  }
17
17
  const io = {
18
18
  writeStdout: value => process.stdout.write(value),
@@ -90,6 +90,19 @@ export async function main(argv, output = io) {
90
90
  output.writeStdout(`${await version()}\n`);
91
91
  return 0;
92
92
  }
93
+ if (argv[0] === 'preview') {
94
+ // The preview CLI consumes process argv and stays lazy for read-only scans.
95
+ if (argv.slice(1).some(arg => !['--help', '-h'].includes(arg)) || argv.length > 2) {
96
+ output.writeStderr('Unknown option. Use rtl-analyzer preview --help.');
97
+ return 2;
98
+ }
99
+ if (argv.length === 2) {
100
+ output.writeStdout('Usage: RTL_PROJECT_ROOT=/absolute/project rtl-preview (or rtl-analyzer preview)\nServe dashboard reports on http://127.0.0.1:4320. See README for project, preview, Chromium and state prerequisites.\n');
101
+ return 0;
102
+ }
103
+ await import('./preview-companion.js');
104
+ return 0;
105
+ }
93
106
  if (argv[0] !== 'scan') {
94
107
  output.writeStderr(`Unknown command: ${argv[0]}. Use --help for usage.`);
95
108
  return 2;
package/dist/tailwind.js CHANGED
@@ -3,6 +3,8 @@ const utilities = {
3
3
  ml: 'margin-left', mr: 'margin-right', pl: 'padding-left', pr: 'padding-right',
4
4
  left: 'left', right: 'right', 'text-left': 'text-align', 'text-right': 'text-align',
5
5
  'border-l': 'border-left', 'border-r': 'border-right',
6
+ 'rounded-tl': 'border-top-left-radius', 'rounded-tr': 'border-top-right-radius',
7
+ 'rounded-bl': 'border-bottom-left-radius', 'rounded-br': 'border-bottom-right-radius',
6
8
  };
7
9
  export function extractTailwind(path, text, value, valueStart, context) {
8
10
  const evidence = [];
@@ -10,7 +12,7 @@ export function extractTailwind(path, text, value, valueStart, context) {
10
12
  const token = match[0];
11
13
  const parts = token.split(':');
12
14
  const utility = parts.at(-1);
13
- const key = /^(text-left|text-right)(?:-|$)/.test(utility) ? utility.startsWith('text-left') ? 'text-left' : 'text-right' : utility.match(/^(border-[lr]|(?:ml|mr|pl|pr|left|right))(?:-|$)/)?.[1];
15
+ const key = /^(text-left|text-right)(?:-|$)/.test(utility) ? utility.startsWith('text-left') ? 'text-left' : 'text-right' : utility.match(/^(rounded-(?:tl|tr|bl|br)|border-[lr]|(?:ml|mr|pl|pr|left|right))(?:-|$)/)?.[1];
14
16
  if (!key || !utilities[key])
15
17
  continue;
16
18
  const start = valueStart + match.index;
@@ -0,0 +1,20 @@
1
+ import { proposeBidiIsolation, BIDI_TRANSFORMATION_ID } from './codemod.js';
2
+ import { proposeCssSpacing, CSS_SPACING_TRANSFORMATION_ID } from './css-spacing.js';
3
+ import { proposeCssDirectional, CSS_DIRECTIONAL_TRANSFORMATION_ID } from './css-directional.js';
4
+ import { proposeReactInline, REACT_INLINE_TRANSFORMATION_ID } from './react-inline.js';
5
+ import { proposeCssIcon, CSS_ICON_TRANSFORMATION_ID } from './css-icons.js';
6
+ /** Shared dispatch for code review, eligibility and both persisted workflows. */
7
+ export const transformations = [
8
+ { key: 'RTL.BIDI.ISOLATION:direct-text', id: BIDI_TRANSFORMATION_ID, ruleId: 'RTL.BIDI.ISOLATION', matches: (f) => f.ruleId === 'RTL.BIDI.ISOLATION', propose: proposeBidiIsolation },
9
+ { key: 'RTL.CSS.PHYSICAL:spacing', id: CSS_SPACING_TRANSFORMATION_ID, ruleId: 'RTL.CSS.PHYSICAL', matches: (f) => f.ruleId === 'RTL.CSS.PHYSICAL' && f.sourceMechanism === 'css' && /^(margin|padding)-/.test(f.original), propose: proposeCssSpacing },
10
+ { key: 'RTL.CSS.PHYSICAL:logical', id: CSS_DIRECTIONAL_TRANSFORMATION_ID, ruleId: 'RTL.CSS.PHYSICAL', matches: (f) => ['RTL.CSS.PHYSICAL', 'RTL.GEOMETRY.EDGE'].includes(f.ruleId) && f.sourceMechanism === 'css', propose: proposeCssDirectional },
11
+ { key: 'RTL.CSS.PHYSICAL:react-inline', id: REACT_INLINE_TRANSFORMATION_ID, ruleId: 'RTL.CSS.PHYSICAL', matches: (f) => ['RTL.CSS.PHYSICAL', 'RTL.GEOMETRY.EDGE'].includes(f.ruleId) && f.sourceMechanism === 'react-inline', propose: proposeReactInline },
12
+ { key: 'RTL.ICON.PROGRESSION:css-opt-in', id: CSS_ICON_TRANSFORMATION_ID, ruleId: 'RTL.ICON.PROGRESSION', matches: (f) => f.ruleId === 'RTL.ICON.PROGRESSION', propose: proposeCssIcon },
13
+ ];
14
+ export function transformationFor(finding) { return transformations.find(t => t.matches(finding)); }
15
+ export function proposeTransformation(finding, source) {
16
+ const strategy = transformationFor(finding);
17
+ if (!strategy)
18
+ throw Error(finding.ruleId === 'RTL.UTILITY.PHYSICAL' ? 'UTILITY_COMPILER_VERSION_AND_VARIANT_REVIEW_REQUIRED' : finding.sourceMechanism === 'emotion-template' || finding.sourceMechanism === 'mui-sx' || finding.sourceMechanism === 'mui-theme' ? 'CSS_IN_JS_OWNER_AND_RTL_PROCESSOR_REVIEW_REQUIRED' : 'UNSUPPORTED_TRANSFORMATION_FAMILY');
19
+ return strategy.propose(finding, source);
20
+ }
@@ -0,0 +1,71 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { mkdir, readFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { promisify } from 'node:util';
8
+ import { chromium } from '@playwright/test';
9
+ import { REVIEW_SOURCE, validateReviewPath } from './review-session.js';
10
+ import { analyzeBidiIsolation } from './codemod.js';
11
+ const run = promisify(execFile);
12
+ const sha = (x) => createHash('sha256').update(x).digest('hex');
13
+ const active = new Set();
14
+ async function scan(targetRoot, findingId) { const cli = join(dirname(fileURLToPath(import.meta.url)), 'cli.js'); let stdout = ''; try {
15
+ const result = await run(process.execPath, [cli, '--root', targetRoot], { cwd: targetRoot, timeout: 30_000, maxBuffer: 512_000 });
16
+ stdout = result.stdout;
17
+ }
18
+ catch (error) {
19
+ const expected = error;
20
+ stdout = expected.stdout ?? '';
21
+ if (!stdout)
22
+ throw new Error('SCANNER_EXECUTION_FAILED');
23
+ } const report = JSON.parse(stdout); const ids = (report.findings ?? []).map(x => x.id); return { findingPresent: ids.includes(findingId), resultDigest: sha(stdout) }; }
24
+ export async function validateCandidate(session, finding, patch, startRuntime) { if (active.has(session.id))
25
+ throw new Error('VALIDATION_ALREADY_RUNNING'); active.add(session.id); const jobId = randomUUID(); const startedAt = new Date().toISOString(); try {
26
+ if (patch.path !== REVIEW_SOURCE || finding.id !== patch.findingId)
27
+ throw new Error('VALIDATION_IDENTITY_MISMATCH');
28
+ const originalPath = validateReviewPath(session.root, REVIEW_SOURCE);
29
+ const candidatePath = validateReviewPath(session.candidateRoot, REVIEW_SOURCE);
30
+ const original = await readFile(originalPath, 'utf8');
31
+ const candidate = await readFile(candidatePath, 'utf8');
32
+ if (sha(original) !== session.originalSha256)
33
+ throw new Error('STALE_ORIGINAL_SOURCE');
34
+ if (sha(candidate) !== session.candidateSha256)
35
+ throw new Error('STALE_CANDIDATE_SOURCE');
36
+ analyzeBidiIsolation(finding, original);
37
+ const runtime = await startRuntime(session);
38
+ if (runtime.runtime?.status !== 'healthy')
39
+ throw new Error('CANDIDATE_RUNTIME_UNAVAILABLE');
40
+ const before = await scan(session.root, finding.id);
41
+ const after = await scan(session.candidateRoot, finding.id);
42
+ const browserErrors = [];
43
+ const dom = [];
44
+ const screenshots = [];
45
+ const screenshotRoot = join(homedir(), '.rtl-migration-analyzer', 'screenshots');
46
+ await mkdir(screenshotRoot, { recursive: true, mode: 0o700 });
47
+ const browser = await chromium.launch({ headless: true });
48
+ try {
49
+ for (const [label, origin, dir] of [['original-ltr', 'http://127.0.0.1:4200', 'ltr'], ['original-rtl', 'http://127.0.0.1:4200', 'rtl'], ['candidate-ltr', runtime.runtime.origin, 'ltr'], ['candidate-rtl', runtime.runtime.origin, 'rtl']]) {
50
+ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'UTC' });
51
+ page.on('pageerror', error => browserErrors.push(`${label}:${error.message}`));
52
+ const suffix = dir === 'rtl' ? '/invoices?demo=unmigrated-rtl&lang=ar' : '/invoices';
53
+ await page.goto(origin + suffix, { waitUntil: 'domcontentloaded', timeout: 10_000 });
54
+ const direction = await page.locator('html').getAttribute('dir');
55
+ if (direction !== (dir === 'rtl' ? 'rtl' : 'ltr'))
56
+ throw new Error(`DOM_DIRECTION_${label}`);
57
+ dom.push(`${label}:html.dir=${direction}`);
58
+ const image = `screenshots/${jobId}-${label}.png`;
59
+ await page.screenshot({ path: join(homedir(), '.rtl-migration-analyzer', image), fullPage: true });
60
+ screenshots.push(image);
61
+ await page.close();
62
+ }
63
+ }
64
+ finally {
65
+ await browser.close();
66
+ }
67
+ return { state: before.findingPresent && !after.findingPresent && browserErrors.length === 0 ? 'Passed' : 'Failed', jobId, startedAt, finishedAt: new Date().toISOString(), originalSourceSha256: sha(original), candidateSourceSha256: sha(candidate), patch, scannerBefore: before, scannerAfter: after, browserDomValidation: dom, screenshotReferences: screenshots, browserErrors, environment: { node: process.version, viewport: '1440x1000', locale: 'en-US', timezone: 'UTC' } };
68
+ }
69
+ finally {
70
+ active.delete(session.id);
71
+ } }
@@ -0,0 +1,46 @@
1
+ export const projectCheckNames = ['typecheck', 'build', 'test'];
2
+ /** Read configuration from the protected review baseline, including on historical records. */
3
+ export function configuredWorkflowChecks(w) {
4
+ const project = w.baseline['rtl-project.config.json'] ? JSON.parse(w.baseline['rtl-project.config.json']) : undefined;
5
+ const pkg = JSON.parse(w.baseline['package.json']);
6
+ return projectCheckNames.map(name => {
7
+ const args = project ? project.validation[name] : pkg.scripts?.[name] ? ['run', name] : undefined;
8
+ const excluded = project?.validationExclusions?.[name];
9
+ return { name, kind: 'project', state: args ? 'Not run' : excluded ? 'Not applicable' : 'Not configured',
10
+ command: args ? [project?.packageManager ?? 'npm', ...args].map(a => JSON.stringify(a)).join(' ') : undefined,
11
+ scope: 'Accepted-only candidate snapshot. The configured command determines project or subset scope.',
12
+ detail: args ? 'Configured command has not executed for this accepted-change snapshot.' : excluded || 'No command supplied. This does not establish whether the project has tests.' };
13
+ });
14
+ }
15
+ /** Required execution evidence must exist; absent records are never successful checks. */
16
+ export function workflowValidationEvidenceIssue(w) {
17
+ if (!w.validation)
18
+ return 'Validation has not run.';
19
+ if (!Array.isArray(w.validation.checks))
20
+ return 'Required execution records are missing. Validate accepted changes.';
21
+ const missing = configuredWorkflowChecks(w).filter(c => c.state === 'Not run' && !w.validation.checks.some(result => result.name === c.name && result.state !== 'Not run')).map(c => c.name);
22
+ if (missing.length)
23
+ return 'Configured checks not run: ' + missing.join(', ') + '. Validate accepted changes.';
24
+ if (!w.validation.checks.some(c => c.name === 'scanner') || !w.validation.checks.some(c => c.name.startsWith('runtime')))
25
+ return 'Required scanner or runtime execution evidence is missing. Validate accepted changes.';
26
+ if (Object.keys(w.baseline).some(path => !w.validation.hashes?.[path]))
27
+ return 'Candidate hash evidence is missing. Validate accepted changes.';
28
+ }
29
+ export function workflowValidationPresentation(w, fresh) {
30
+ const configured = configuredWorkflowChecks(w), results = Array.isArray(w.validation?.checks) ? w.validation.checks : [];
31
+ const checks = configured.map(check => {
32
+ if (check.state !== 'Not run')
33
+ return check;
34
+ const result = results.find(c => c.name === check.name);
35
+ return result ? { ...check, ...result, kind: 'project', command: check.command, scope: check.scope } : check;
36
+ });
37
+ checks.push(...(results.filter(c => !projectCheckNames.includes(c.name)).map(c => ({ ...c, kind: c.name === 'scanner' ? 'scanner' : 'runtime', scope: c.name === 'scanner' ? 'Rescan of candidate; accepted findings must resolve.' : 'Recorded mapped routes and rendered targets only; not project unit tests.' })) ?? []));
38
+ const projects = checks.filter(c => c.kind === 'project');
39
+ const ran = projects.filter(c => ['Passed', 'Failed'].includes(c.state));
40
+ const missing = projects.filter(c => c.state === 'Not configured');
41
+ const blocked = checks.filter(c => ['Failed', 'Unavailable', 'Error'].includes(c.state) && !c.name.startsWith('live-preview:'));
42
+ const evidenceIssue = w.validation ? workflowValidationEvidenceIssue(w) : undefined;
43
+ const status = !w.validation ? 'Not run' : !fresh ? 'Unavailable' : (blocked.some(c => c.state === 'Failed') || w.validation.state === 'Failed') ? 'Failed' : blocked.length || evidenceIssue || w.validation.state === 'Unavailable' ? 'Unavailable' : !ran.length ? 'Technical validation unavailable' : missing.length ? 'Limited validation' : 'Passed';
44
+ const explanation = !w.validation ? 'Validate accepted changes to execute checks for the exact candidate snapshot.' : !fresh ? 'Validation is stale for the accepted candidate. Validate again.' : evidenceIssue ? evidenceIssue : 'Project commands executed: ' + (ran.map(c => c.name + ' (' + c.state + ')').join(', ') || 'none') + '. ' + (missing.length ? 'Not configured: ' + missing.map(c => c.name).join(', ') + '. ' : '') + 'Scanner and runtime evidence are listed separately. Build does not imply tests or typecheck.';
45
+ return { status, explanation, checks, coverage: 'Unknown', coverageDetail: 'No matching change coverage evidence is available for this source, accepted candidate and executed test run. Passing tests alone do not establish finding or component coverage. Execution coverage does not prove RTL visual correctness.' };
46
+ }
package/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "rtl-analyzer",
3
- "version": "0.2.0",
4
- "description": "Conservative RTL risk scanning and report generation",
3
+ "version": "0.3.0",
4
+ "description": "RTL analysis with isolated review, accepted-only Apply and receipt-backed rollback",
5
5
  "repository": {
6
6
  "type": "git",
7
- "url": "https://github.com/FoushWare/rtl-analyzer.git"
7
+ "url": "https://github.com/FoushWare/rtl-analyzer.git",
8
+ "directory": "packages/rtl-analyzer"
8
9
  },
9
10
  "type": "module",
10
11
  "bin": {
11
- "rtl-analyzer": "dist/standalone-cli.js"
12
+ "rtl-analyzer": "dist/standalone-cli.js",
13
+ "rtl-scanner": "dist/cli.js",
14
+ "rtl-preview": "dist/preview-cli.js"
12
15
  },
13
16
  "files": [
14
- "dist/**",
17
+ "dist/*.js",
15
18
  "README.md",
16
19
  "LICENSE"
17
20
  ],
@@ -19,7 +22,7 @@
19
22
  "node": ">=22.12.0"
20
23
  },
21
24
  "scripts": {
22
- "build": "tsc -p tsconfig.json",
25
+ "build": "node build.mjs",
23
26
  "prepack": "npm run build"
24
27
  },
25
28
  "dependencies": {
@@ -27,6 +30,12 @@
27
30
  "postcss": "8.5.29",
28
31
  "postcss-scss": "4.0.9",
29
32
  "postcss-value-parser": "4.2.0",
30
- "typescript": "~5.9.0"
31
- }
33
+ "typescript": "~5.9.0",
34
+ "@playwright/test": "1.64.0"
35
+ },
36
+ "rtlAnalyzerImplementation": {
37
+ "repository": "https://github.com/FoushWare/enterprise-rtl-migration-lab",
38
+ "commit": "8d3946a40b024a042cf315aa33cfcb560e69dc75"
39
+ },
40
+ "license": "MIT"
32
41
  }