rtl-analyzer 0.2.0 → 0.4.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 (60) hide show
  1. package/README.md +90 -56
  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 +118 -0
  6. package/dist/contextual-preview.js +74 -0
  7. package/dist/controlled-apply.js +222 -0
  8. package/dist/css-configured-proposal.js +98 -0
  9. package/dist/css-directional.js +60 -0
  10. package/dist/css-icons.js +51 -0
  11. package/dist/css-spacing.js +65 -0
  12. package/dist/dashboard-batch-review.js +37 -0
  13. package/dist/dashboard-client.js +73 -50
  14. package/dist/dashboard-contextual-preview.js +127 -0
  15. package/dist/dashboard-data.js +4 -4
  16. package/dist/dashboard-embedded-preview.js +202 -0
  17. package/dist/dashboard-html.js +13 -10
  18. package/dist/dashboard-operation-flow.js +47 -0
  19. package/dist/dashboard-review-details.js +175 -0
  20. package/dist/dashboard-review-navigation.js +19 -0
  21. package/dist/dashboard-review-workflow.js +219 -0
  22. package/dist/dashboard-themes.js +34 -0
  23. package/dist/directional-properties.js +53 -0
  24. package/dist/discovery.js +1 -2
  25. package/dist/eligibility.js +8 -8
  26. package/dist/evidence-store.js +110 -0
  27. package/dist/example-preview-mappings.js +98 -0
  28. package/dist/manual-change-store.js +27 -0
  29. package/dist/migration-lifecycle.js +19 -0
  30. package/dist/original-preview-runtime.js +78 -0
  31. package/dist/output-path.js +65 -0
  32. package/dist/page-navigation.js +17 -0
  33. package/dist/policy-validation.js +7 -4
  34. package/dist/preview-cli.js +22 -0
  35. package/dist/preview-companion.js +649 -0
  36. package/dist/preview-configuration.js +171 -0
  37. package/dist/preview-runtime.js +102 -0
  38. package/dist/project-configuration.js +48 -0
  39. package/dist/project-root.js +12 -0
  40. package/dist/react-inline.js +65 -0
  41. package/dist/report-publisher.js +4 -7
  42. package/dist/review-approval.js +9 -0
  43. package/dist/review-session.js +211 -56
  44. package/dist/review-store.js +175 -0
  45. package/dist/review-workflow.js +820 -0
  46. package/dist/rules.js +27 -17
  47. package/dist/runtime-process.js +35 -0
  48. package/dist/scan-history.js +35 -0
  49. package/dist/scan-manifest-store.js +26 -0
  50. package/dist/scan.js +55 -4
  51. package/dist/scoped-direction-evidence.js +117 -0
  52. package/dist/serialization.js +1 -0
  53. package/dist/source-context.js +93 -0
  54. package/dist/source-snippets.js +3 -3
  55. package/dist/standalone-cli.js +14 -1
  56. package/dist/tailwind.js +3 -1
  57. package/dist/transformations.js +34 -0
  58. package/dist/validation.js +75 -0
  59. package/dist/workflow-validation.js +46 -0
  60. package/package.json +17 -8
package/dist/rules.js CHANGED
@@ -1,8 +1,12 @@
1
1
  import ts from 'typescript';
2
+ import { hasIsolation } from './codemod.js';
3
+ import { hasMirroredCssOffset } from './css-configured-proposal.js';
4
+ import { cssIconAnchors } from './css-icons.js';
2
5
  import { analyzeRuntimeDirection } from './runtime-direction.js';
3
6
  import valueParser from 'postcss-value-parser';
4
7
  import { hash, range } from './model.js';
5
8
  const plain = (v) => v.replace(/^['"`]|['"`]$/g, '');
9
+ const ownerIsLocalCss = (f) => f.ownership === 'custom-css' && f.sourceMechanism === 'css';
6
10
  const cssKey = (p) => p.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
7
11
  export function detect(evidence, sources, policy, diagnostics) {
8
12
  const findings = [];
@@ -16,9 +20,20 @@ export function detect(evidence, sources, policy, diagnostics) {
16
20
  const occurrence = findingOccurrences.get(key) ?? 0;
17
21
  findingOccurrences.set(key, occurrence + 1);
18
22
  findings.push({ id: ruleId + ':' + hash(a.id + '|' + occurrence).slice(0, 24), ruleId, ruleVersion: 1, category, severity: category === 'INFORMATIONAL' || category === 'INTENTIONAL_LTR' ? 'Info' : severity, confidence, title, sourceMechanism: 'mechanism' in a ? a.mechanism : 'typescript-structure', applications: a.path.startsWith('apps/') ? [a.path.split('/')[1]] : [], path: a.path, range: a.range, original: a.original, context: a.context, ownership, rationale, treatment, evidenceIds: refs.map(e => e.id).sort(), relatedLocations: refs.filter(e => e.id !== a.id).map(e => ({ path: e.path, range: e.range })), issueIds: policy.issueBindings.filter(b => b.ruleId === ruleId && b.path === a.path && a.context.includes(b.contextIncludes) && (!b.originalIncludes || a.original.includes(b.originalIncludes))).map(b => b.issueId).sort(), suggestion: exception ? null : suggestion, limitation, ...(exception ? { exceptionReason: exception.reason, originalCategory } : {}) });
19
- return findings.at(-1);
23
+ const finding = findings.at(-1);
24
+ if (!exception && ownerIsLocalCss(finding) && refs[0]?.id === a.id) {
25
+ const declaration = refs[0];
26
+ const intent = policy.cssProposals?.find(i => i.path === a.path && i.context === a.context && i.property === declaration.property && i.value === declaration.value);
27
+ if (intent)
28
+ finding.cssProposal = { kind: intent.kind, sourceDigest: intent.sourceDigest };
29
+ }
30
+ return finding;
20
31
  }
21
32
  for (const e of evidence) {
33
+ if (['tailwind-utility', 'bootstrap-utility'].includes(e.semantics)) {
34
+ add('RTL.UTILITY.PHYSICAL', 'Physical utility class requires compiler-aware review', e, 'MANUAL_REVIEW', 'Static class syntax does not establish the installed compiler, version or semantic intent.', 'Check utility framework/version/config and variants; review reading-edge intent. No utility patch is prepared.', 'utility-compiler', [e], 'Medium');
35
+ continue;
36
+ }
22
37
  if (cssKey(e.property) === 'position' && plain(e.value) === 'fixed') {
23
38
  const peers = evidence.filter(x => x.path === e.path && x.context === e.context);
24
39
  const width = peers.find(x => cssKey(x.property) === 'width');
@@ -38,7 +53,7 @@ export function detect(evidence, sources, policy, diagnostics) {
38
53
  const dynamic = diagnostics.some(d => d.path === e.path && d.blocking && d.range.start.offset >= e.range.start.offset && d.range.end.offset <= e.range.end.offset);
39
54
  if (/^(left|right)$/.test(p))
40
55
  add('RTL.GEOMETRY.EDGE', 'Physical positioned edge', e, 'MANUAL_REVIEW', 'Physical edge is coupled to placement, containing block and clearance; logical replacement alone does not select the correct side.', 'Review anchor, companion gutter, breakpoints and collision clearance as one layout contract.', owner, [e, ...(position ? [position] : [])], 'High');
41
- else if (/^(margin|padding|border)-(left|right)(-|$)/.test(p) || /^(border-top-left-radius|border-top-right-radius|border-bottom-left-radius|border-bottom-right-radius)$/.test(p) || (/^(text-align|float|clear)$/.test(p) && /^(left|right)$/.test(v))) {
56
+ else if (/^(margin|padding|border)-(left|right)(-|$)/.test(p) || /^(border-top-left-radius|border-top-right-radius|border-bottom-left-radius|border-bottom-right-radius)$/.test(p) || (/^(text-align|float|clear)$/.test(p) && /^(left|right)$/.test(valueParser(v).nodes.filter(n => n.type !== 'space' && n.type !== 'comment').map(n => valueParser.stringify(n)).join(' ')))) {
42
57
  const approval = policy.approvals.find(a => a.path === e.path && a.context === e.context && a.property === e.property && a.value === e.value && a.owner === owner && a.sourceDigest === hash(sources.get(e.path) ?? ''));
43
58
  const expectedLogical = p.replace(/^(margin|padding|border)-(left|right)(.*)$/, (_, group, side, suffix) => `${group}-inline-${side === 'left' ? 'start' : 'end'}${suffix}`);
44
59
  const safe = approval && cssKey(approval.logicalProperty) === expectedLogical && !evidence.some(x => cssKey(x.property) === 'writing-mode' && plain(x.value) !== 'horizontal-tb') && e.mechanism !== 'mui-sx' && !/^(inherit|initial|unset|revert|revert-layer)$/.test(v) && !/\b(var|env)\(/.test(v) && !dynamic && ['custom-css', 'custom-inline', 'custom-emotion-logical'].includes(owner) && /^(margin|padding|border)-(left|right)(-|$)/.test(p) && !diagnostics.some(d => d.blocking) && !peers.some(x => x !== e && cssKey(x.property) === p) && !position && !peers.some(x => /writing-mode|direction/.test(cssKey(x.property)));
@@ -49,12 +64,16 @@ export function detect(evidence, sources, policy, diagnostics) {
49
64
  const simple = tokens.every(n => n.type === 'word');
50
65
  const words = tokens.map(n => valueParser.stringify(n));
51
66
  const asymmetric = p === 'border-radius' ? words.length > 1 && new Set(words).size > 1 : words.length === 4 && words[1] !== words[3];
52
- if (asymmetric || !simple && words.length > 0 && !/^[-\d.%pxemauto ]+$/.test(v))
67
+ if (asymmetric || !simple && !(p !== 'border-radius' && words.length >= 1 && words.length <= 3 && tokens.every(n => n.type === 'word' || n.type === 'function' && n.value.toLowerCase() !== 'var')) && words.length > 0 && !/^[-\d.%pxemauto ]+$/.test(v))
53
68
  add('RTL.CSS.SHORTHAND', 'Shorthand needs side/corner review', e, 'MANUAL_REVIEW', 'Shorthand may encode unequal physical sides, elliptical corners or unresolved values.', 'Review tokenized values and cascade; do not split functions or reverse corner order blindly.', owner, [e], simple ? 'High' : 'Medium');
54
69
  }
55
- else if ((p === 'transform' && /translateX\((?!0\))/i.test(v)) || (/^(transform-origin|background-position|box-shadow)$/.test(p) && /left|right|\d/.test(v)) || p === 'order' || p === 'flex-direction' && v === 'row-reverse' || /^grid-(column|row|area)/.test(p) && !/^auto$/.test(v) && !/^1\s*\/\s*-1$/.test(v))
70
+ else if (!hasMirroredCssOffset(e, evidence) && ((p === 'transform' && /translateX\((?!0\))/i.test(v)) || (/^(transform-origin|background-position|box-shadow)$/.test(p) && /left|right|\d/.test(v)) || p === 'order' || p === 'flex-direction' && v === 'row-reverse' || /^grid-(column|row|area)/.test(p) && !/^auto$/.test(v) && !/^1\s*\/\s*-1$/.test(v)))
56
71
  add('RTL.GEOMETRY.ORDER', 'Directional geometry or explicit order', e, 'MANUAL_REVIEW', 'Transform/axis/order semantics require geometric and reading-order decisions.', 'Review spatial intent, focus order and companion positioning; no numeric sign reversal.', owner, [e], 'Medium');
57
72
  }
73
+ for (const [path, text] of sources)
74
+ if (path.endsWith('.css'))
75
+ for (const a of cssIconAnchors(path, text))
76
+ add('RTL.ICON.PROGRESSION', 'Explicit progression icon needs direction-aware rendering', a, 'MANUAL_REVIEW', 'Author supplied rtl-icon: progression-right semantic metadata; rendered ownership and icon-only targeting still require review.', 'Review icon-only targeting, LTR baseline, inherited direction and existing transforms before mirroring.', policy.ownership.css ?? 'unknown', [], 'High');
58
77
  // Generic syntax evidence: imports and JSX/data flow are inspected, never executed.
59
78
  const themes = [], rtl = evidence.filter(e => e.mechanism === 'html-root' && e.property === 'dir' && e.value === 'rtl'), providers = [], caches = [], cacheChecks = new Map();
60
79
  const entries = [...sources.entries()].filter(([p]) => /\.[jt]sx?$/.test(p));
@@ -82,17 +101,6 @@ export function detect(evidence, sources, policy, diagnostics) {
82
101
  return 'JsxText:' + n.getText(sf).trim(); if (ts.isIdentifier(n) || ts.isStringLiteral(n) || ts.isNumericLiteral(n))
83
102
  return ts.SyntaxKind[n.kind] + ':' + n.text; const parts = []; ts.forEachChild(n, x => { parts.push(identity(x)); }); return ts.SyntaxKind[n.kind] + '(' + parts.join('|') + ')'; }
84
103
  function anchor(n, context = ctx(n)) { const a = { path, range: range(text, n.getStart(sf), n.end), original: n.getText(sf), context, id: hash(path + '|' + context + '|' + ts.SyntaxKind[n.kind] + '|' + identity(n)) }; return a; }
85
- function isolated(n) { let p = n.parent; while (p && !ts.isFunctionDeclaration(p) && !ts.isVariableDeclaration(p)) {
86
- if (ts.isJsxElement(p)) {
87
- const o = p.openingElement;
88
- if (o.tagName.getText(sf) === 'bdi' || o.attributes.properties.some(x => ts.isJsxAttribute(x) && x.name.getText(sf) === 'dir' && x.initializer && ts.isStringLiteral(x.initializer) && ['ltr', 'auto'].includes(x.initializer.text)))
89
- return true;
90
- const style = o.attributes.properties.find(x => ts.isJsxAttribute(x) && x.name.getText(sf) === 'style');
91
- if (style && ts.isJsxAttribute(style) && style.initializer && ts.isJsxExpression(style.initializer) && style.initializer.expression && ts.isObjectLiteralExpression(style.initializer.expression) && style.initializer.expression.properties.some(x => ts.isPropertyAssignment(x) && x.name.getText(sf) === 'unicodeBidi' && ts.isStringLiteral(x.initializer) && x.initializer.text === 'isolate'))
92
- return true;
93
- }
94
- p = p.parent;
95
- } return false; }
96
104
  function visit(n) {
97
105
  for (const proof of runtimeProofs.filter(p => p.node === n)) {
98
106
  const cacheAnchor = anchor(n, ctx(n) + (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n) ? '/' + n.tagName.getText(sf) : ''));
@@ -124,7 +132,7 @@ export function detect(evidence, sources, policy, diagnostics) {
124
132
  if (values?.includes('rtl'))
125
133
  rtl.push(a);
126
134
  if (!values) {
127
- diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Document direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Potential output direction cannot be correlated safely.' });
135
+ diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Document direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: false, rationale: 'Static findings remain available; runtime direction is unknown and direction-dependent changes require verified runtime evidence.' });
128
136
  add('RTL.RUNTIME.DIRECTION_UNKNOWN', 'Dynamic document direction requires review', a, 'RUNTIME_CONFIG', 'Direction output comes from an unresolved expression.', 'Review output values and runtime synchronization; do not infer direction from strings in a condition.', 'document-runtime', [], 'Low');
129
137
  }
130
138
  }
@@ -161,6 +169,8 @@ export function detect(evidence, sources, policy, diagnostics) {
161
169
  }
162
170
  }
163
171
  const classAttr = n.attributes.properties.find(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'className');
172
+ if (classAttr && !evidence.some(e => e.path === path && ['tailwind-utility', 'bootstrap-utility'].includes(e.semantics) && e.range.start.offset >= classAttr.getStart(sf) && e.range.end.offset <= classAttr.end) && ts.isJsxAttribute(classAttr) && classAttr.initializer && ts.isStringLiteral(classAttr.initializer) && classAttr.initializer.text.split(/\s+/).some(c => /^(?:(?:sm|md|lg|xl|hover|focus|rtl|ltr):)*(?:-?(?:ml|mr|pl|pr|left|right)-[\w.[\]%-]+|text-(?:left|right)|border-(?:l|r)(?:-[\w-]+)?|rounded-(?:tl|tr|bl|br)(?:-[\w-]+)?)$/.test(c)))
173
+ add('RTL.UTILITY.PHYSICAL', 'Physical utility class requires compiler-aware review', anchor(classAttr), 'MANUAL_REVIEW', 'Static className contains recognized physical utility tokens; class names do not establish the installed compiler, version or semantic intent.', 'Check utility framework/version/config and variants; review reading-edge intent, then use compiler-supported logical utilities. No utility patch is prepared.', 'utility-compiler', [], 'Medium');
164
174
  if (classAttr && ts.isJsxAttribute(classAttr) && classAttr.initializer && ts.isStringLiteral(classAttr.initializer)) {
165
175
  const role = policy.roles.find(r => r.kind === 'brand' && r.path === path && classAttr.initializer && ts.isStringLiteral(classAttr.initializer) && classAttr.initializer.text.split(/\s+/).includes(r.className));
166
176
  if (role && !n.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'dir')) {
@@ -176,7 +186,7 @@ export function detect(evidence, sources, policy, diagnostics) {
176
186
  p = p.parent;
177
187
  } return false; })()))
178
188
  add('RTL.ICON.LITERAL', 'Literal directional arrow in rendered-copy call', anchor(n), 'MANUAL_REVIEW', 'A literal arrow occurs in a copy/function call; its progression meaning and translated rendering need review.', 'Review copy and navigation semantics rather than replacing every arrow.', 'custom-copy', [], 'Medium');
179
- if (ts.isJsxExpression(n) && n.expression && !isolated(n)) {
189
+ if (ts.isJsxExpression(n) && n.expression && !hasIsolation(n, true)) {
180
190
  let candidate = false;
181
191
  function token(x) { if (ts.isPropertyAccessExpression(x) && ['name', 'address', 'email', 'id'].includes(x.name.text))
182
192
  candidate = true; if (ts.isCallExpression(x) && ts.isIdentifier(x.expression) && imports.get(x.expression.text)?.endsWith(':money'))
@@ -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,117 @@
1
+ import { chromium } from '@playwright/test';
2
+ import { createHash } from 'node:crypto';
3
+ import { configuredMapping, loadPreviewConfiguration, routeUrl } from './preview-configuration.js';
4
+ import { contextualPreview } from './contextual-preview.js';
5
+ import { retryAcrossNavigation } from './page-navigation.js';
6
+ export function sameScopedDirectionEvidence(a, b) {
7
+ return !!a && a.version === 1 && JSON.stringify(a) === JSON.stringify(b);
8
+ }
9
+ export async function captureScopedDirectionEvidence(root, w, entries, prepare) {
10
+ if (!w.session || !entries.length)
11
+ throw Error('DIRECTION_EVIDENCE_CANDIDATE_REQUIRED');
12
+ const config = await loadPreviewConfiguration(root), records = [];
13
+ const browser = await chromium.launch({ headless: true });
14
+ try {
15
+ for (const entry of entries) {
16
+ const mapping = configuredMapping(entry.finding, config);
17
+ if (!mapping.configured || !mapping.routes.length || !entry.patch)
18
+ throw Error('DIRECTION_EVIDENCE_EXPLICIT_MAPPING_REQUIRED');
19
+ for (const route of mapping.routes) {
20
+ const app = config.applications[route.application];
21
+ if (!app)
22
+ throw Error('DIRECTION_EVIDENCE_APPLICATION_REQUIRED');
23
+ await prepare(route.application);
24
+ for (const mode of ['ltr', 'rtl']) {
25
+ const query = new URLSearchParams({ inputDigest: w.inputDigest, policyDigest: w.policyDigest, findingId: entry.finding.id, routeId: route.id, mode });
26
+ const info = await contextualPreview(root, query, w);
27
+ if (!info.original?.available || !info.candidate?.available || !('origin' in info.original) || !('origin' in info.candidate))
28
+ throw Error('DIRECTION_EVIDENCE_RUNTIME_IDENTITY_UNAVAILABLE');
29
+ const values = [];
30
+ for (const [role, descriptor] of [['original', info.original], ['candidate', info.candidate]]) {
31
+ const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, locale: 'en-US', timezoneId: 'UTC' }), errors = [];
32
+ page.on('pageerror', e => errors.push(e.message));
33
+ try {
34
+ const expected = routeUrl(route, mode, descriptor.origin);
35
+ await page.goto(expected, { waitUntil: 'domcontentloaded', timeout: 20000 });
36
+ const state = await retryAcrossNavigation(async () => {
37
+ await page.locator(app.readySelector).first().waitFor({ state: 'visible', timeout: 10000 });
38
+ await page.waitForFunction(expectedMode => getComputedStyle(document.documentElement).direction === expectedMode, mode, { timeout: 10000 });
39
+ await page.locator(mapping.selector).first().waitFor({ state: 'visible', timeout: 10000 });
40
+ // Sample the rendered state after startup transitions, not at a nondeterministic animation frame.
41
+ await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done()))));
42
+ await page.waitForFunction(selector => {
43
+ const targets = [...document.querySelectorAll(selector)];
44
+ const elements = new Set();
45
+ for (const target of targets)
46
+ for (let element = target; element; element = element.parentElement)
47
+ elements.add(element);
48
+ return targets.length > 0 && [...elements].every(element => element.getAnimations().every(animation => !(animation.pending || animation.playState === 'running') || !Number.isFinite(animation.effect?.getComputedTiming().endTime)));
49
+ }, mapping.selector, { timeout: 10000 });
50
+ return await page.evaluate(({ selector, expectedUrl, sourceSelector, path, icon }) => {
51
+ const nodes = [...document.querySelectorAll(selector)];
52
+ if (!nodes.length || nodes.length > 100)
53
+ throw Error('DIRECTION_EVIDENCE_TARGET_COUNT');
54
+ const url = new URL(location.href), expected = new URL(expectedUrl);
55
+ if (url.pathname !== expected.pathname || url.search !== expected.search || url.hash)
56
+ throw Error('DIRECTION_EVIDENCE_ROUTE_CHANGED');
57
+ if (sourceSelector) {
58
+ let matched = false;
59
+ for (const sheet of [...document.styleSheets]) {
60
+ try {
61
+ const owner = sheet.ownerNode, source = owner?.getAttribute('data-vite-dev-id')?.replaceAll('\\', '/');
62
+ const link = owner?.tagName === 'LINK' ? new URL(owner.href, location.href) : null;
63
+ if (!(source?.endsWith('/' + path) || link?.origin === location.origin && decodeURIComponent(link.pathname) === '/' + path))
64
+ continue;
65
+ const walk = (rules) => { for (const rule of rules) {
66
+ if ('selectorText' in rule) {
67
+ const r = rule;
68
+ if (r.selectorText.split(',').map(s => s.trim()).includes(sourceSelector) && nodes.some(n => n.matches(r.selectorText)))
69
+ matched = true;
70
+ }
71
+ else if ('cssRules' in rule)
72
+ walk(rule.cssRules);
73
+ } };
74
+ walk(sheet.cssRules);
75
+ }
76
+ catch { }
77
+ }
78
+ if (!matched)
79
+ throw Error('DIRECTION_EVIDENCE_SOURCE_TARGET_MISMATCH');
80
+ }
81
+ return { route: url.pathname + url.search, pageDirection: getComputedStyle(document.documentElement).direction, targets: nodes.map(node => { const el = node, style = getComputedStyle(el), r = el.getBoundingClientRect(), text = el.textContent || '', html = el.outerHTML; if (text.length > 2000 || html.length > 10000)
82
+ throw Error('DIRECTION_EVIDENCE_TARGET_TOO_LARGE'); if (r.width <= 0 || r.height <= 0 || style.display === 'none' || style.visibility === 'hidden')
83
+ throw Error('DIRECTION_EVIDENCE_HIDDEN_TARGET'); if (style.writingMode !== 'horizontal-tb')
84
+ throw Error('DIRECTION_EVIDENCE_WRITING_MODE_UNSUPPORTED'); if (icon && (el.matches(':dir(rtl)') !== (style.direction === 'rtl')))
85
+ throw Error('DIRECTION_EVIDENCE_CSS_HTML_DIRECTION_MISMATCH'); return { key: el.id || el.getAttribute('data-id') || el.getAttribute('data-testid') || null, text, html, direction: style.direction, writingMode: style.writingMode, computed: ['margin-left', 'margin-right', 'padding-left', 'padding-right', 'left', 'right', 'text-align', 'transform', 'scale', 'border-left-width', 'border-right-width', 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-left-radius', 'border-bottom-right-radius', 'flex-direction', 'box-shadow'].map(p => style.getPropertyValue(p)), rect: [r.x, r.y, r.width, r.height], inputs: [...el.querySelectorAll('input,textarea,select')].map(x => ({ value: x.value, checked: x.checked })) }; }) };
86
+ }, { selector: mapping.selector, expectedUrl: expected, sourceSelector: mapping.sourceSelector || '', path: entry.finding.path, icon: entry.finding.ruleId === 'RTL.ICON.PROGRESSION' });
87
+ });
88
+ if (errors.length)
89
+ throw Error('DIRECTION_EVIDENCE_PAGE_ERROR');
90
+ values.push({ role, sourceHash: descriptor.sourceHash, projectRoot: descriptor.projectRoot, runtimeSessionId: descriptor.runtimeSessionId, state });
91
+ }
92
+ finally {
93
+ await page.close();
94
+ }
95
+ }
96
+ const rechecked = await contextualPreview(root, query, w);
97
+ if (!rechecked.original?.available || !rechecked.candidate?.available || !('sourceHash' in rechecked.original) || !('sourceHash' in rechecked.candidate) || rechecked.original.sourceHash !== values[0].sourceHash || rechecked.candidate.sourceHash !== values[1].sourceHash || rechecked.original.runtimeSessionId !== values[0].runtimeSessionId || rechecked.candidate.runtimeSessionId !== values[1].runtimeSessionId)
98
+ throw Error('DIRECTION_EVIDENCE_RUNTIME_IDENTITY_CHANGED');
99
+ const [before, after] = values;
100
+ if (before.state.targets.length !== after.state.targets.length || before.state.targets.some((t, i) => t.direction !== after.state.targets[i].direction || t.writingMode !== after.state.targets[i].writingMode || t.text !== after.state.targets[i].text || t.key !== after.state.targets[i].key))
101
+ throw Error('DIRECTION_EVIDENCE_TARGET_MISMATCH');
102
+ const keys = before.state.targets.map(t => t.key);
103
+ if (keys.length > 1 && (keys.some(k => !k) || new Set(keys).size !== keys.length))
104
+ throw Error('DIRECTION_EVIDENCE_AMBIGUOUS_TARGETS');
105
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
106
+ // Do not persist application text, DOM or form values in the workflow record.
107
+ const bounded = values.map(v => ({ ...v, state: { ...v.state, targets: v.state.targets.map(t => ({ keyHash: hash(t.key), textHash: hash(t.text), htmlHash: hash(t.html), direction: t.direction, writingMode: t.writingMode, computed: t.computed, rect: t.rect, inputsHash: hash(t.inputs) })) } }));
108
+ records.push({ findingId: entry.finding.id, patchHash: hash(entry.patch), application: route.application, routeId: route.id, selector: mapping.selector, sourceSelector: mapping.sourceSelector || null, mode, viewport: { width: 1280, height: 800 }, values: bounded });
109
+ }
110
+ }
111
+ }
112
+ }
113
+ finally {
114
+ await browser.close();
115
+ }
116
+ return { version: 1, inputDigest: w.inputDigest, policyDigest: w.policyDigest, configurationDigest: config.digest, sessionId: w.session.id, records };
117
+ }
@@ -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;