rtl-analyzer 0.0.0-stage → 0.2.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.
@@ -0,0 +1,109 @@
1
+ import { hash, range } from './model.js';
2
+ import { detect } from './rules.js';
3
+ import { findingIdPattern, policyLocations, policyPath, ruleIds } from './policy-validation.js';
4
+ /** Audit policy against the unexcepted source catalog, never against a suppressed result. */
5
+ export function auditPolicy(policy, text, evidence, sources, findings, coverage) {
6
+ const locations = policyLocations(text), diagnostics = [];
7
+ function diagnostic(pointer, code, message, blocking) {
8
+ diagnostics.push({ path: policyPath, range: locations.get(pointer) ?? range(text, 0, 0), code,
9
+ message: `${blocking ? 'BLOCKING' : 'WARNING'} ${pointer}: ${message}`, blocking,
10
+ ...(blocking ? { impact: 'DIRECTIONAL_UNSUPPORTED' } : {}),
11
+ rationale: blocking ? 'This record cannot authorize a safe policy decision; analysis is incomplete.' : 'Informational association is unmatched; it cannot establish calibrated coverage.' });
12
+ }
13
+ const contextExists = (path, context) => evidence.some(e => e.path === path && e.context === context) || findings.some(f => f.path === path && f.context === context);
14
+ function unsupported(path, pointer, blocking) {
15
+ if (coverage.some(d => d.path === path && d.blocking && d.code !== 'DYNAMIC_VALUE')) {
16
+ diagnostic(pointer, 'POLICY_UNSUPPORTED', 'source coverage is incomplete; record applicability cannot be established', blocking);
17
+ return true;
18
+ }
19
+ return false;
20
+ }
21
+ const key = (property) => property.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
22
+ policy.approvals.forEach((a, i) => {
23
+ const p = `/approvals/${i}`;
24
+ if (unsupported(a.path, p, true))
25
+ return;
26
+ const matches = evidence.filter(e => e.path === a.path && e.context === a.context && e.property === a.property && e.value === a.value);
27
+ if (matches.length !== 1 || !sources.has(a.path) || a.sourceDigest !== hash(sources.get(a.path))) {
28
+ diagnostic(p, 'POLICY_STALE_APPROVAL', 'exact declaration/value or whole-file source pin no longer matches uniquely', true);
29
+ return;
30
+ }
31
+ const e = matches[0], override = policy.ownerOverrides?.find(o => o.path === e.path && o.context === e.context);
32
+ const owner = override?.owner ?? policy.ownership[e.mechanism] ?? 'unknown';
33
+ const expected = key(a.property).replace(/^(margin|padding|border)-(left|right)(.*)$/, (_, group, side, suffix) => `${group}-inline-${side === 'left' ? 'start' : 'end'}${suffix}`);
34
+ if (a.owner !== owner || !['custom-css', 'custom-inline', 'custom-emotion-logical'].includes(owner)) {
35
+ diagnostic(p, 'POLICY_CONFLICT', 'approval owner does not establish the declared source pipeline', true);
36
+ return;
37
+ }
38
+ if (key(a.logicalProperty) !== expected || !/^(margin|padding|border)-(left|right)(-|$)/.test(key(a.property)) || e.mechanism === 'mui-sx') {
39
+ diagnostic(p, 'POLICY_UNSUPPORTED_APPROVAL', 'logical equivalent or source mechanism is not a bounded supported candidate', true);
40
+ return;
41
+ }
42
+ if (policy.exceptions.some(x => x.ruleId === 'RTL.CSS.PHYSICAL' && x.path === e.path && x.context === e.context && x.originalDigest === hash(e.original))) {
43
+ diagnostic(p, 'POLICY_CONFLICT', 'the same declaration has both a semantic approval and an exception', true);
44
+ return;
45
+ }
46
+ // Reuse, rather than weaken or duplicate, the existing conservative candidate contract.
47
+ const admitted = detect(evidence, sources, { ...policy, approvals: [a], exceptions: [] }, coverage.map(d => ({ ...d })))
48
+ .some(f => f.category === 'AUTO_CANDIDATE' && f.evidenceIds.includes(e.id));
49
+ if (!admitted)
50
+ diagnostic(p, 'POLICY_UNSUPPORTED_APPROVAL', 'existing conservative admission safeguards do not support this declaration', true);
51
+ });
52
+ policy.exceptions.forEach((x, i) => {
53
+ const p = `/exceptions/${i}`, blocking = x.category !== 'INFORMATIONAL' || !['RTL.DOCUMENT.INITIAL', 'RTL.DOCUMENT.RUNTIME'].includes(x.ruleId);
54
+ if (unsupported(x.path, p, blocking))
55
+ return;
56
+ const matches = findings.filter(f => f.ruleId === x.ruleId && f.path === x.path && f.context === x.context && hash(f.original) === x.originalDigest);
57
+ if (matches.length !== 1)
58
+ diagnostic(p, blocking ? 'POLICY_STALE_EXCEPTION' : 'POLICY_STALE_INFORMATIONAL', 'exact finding anchor/declaration no longer matches uniquely', blocking);
59
+ });
60
+ policy.dynamicExceptions.forEach((x, i) => {
61
+ const p = `/dynamicExceptions/${i}`;
62
+ if (unsupported(x.path, p, true))
63
+ return;
64
+ const matches = evidence.filter(e => e.path === x.path && e.property === x.property && hash(e.value) === x.valueDigest);
65
+ if (!matches.length || !sources.has(x.path) || hash(sources.get(x.path)) !== x.sourceDigest) {
66
+ diagnostic(p, 'POLICY_STALE_DYNAMIC_EXCEPTION', 'expression or whole-file source pin no longer matches', true);
67
+ return;
68
+ }
69
+ if (!matches.some(e => coverage.some(d => d.path === e.path && d.code === 'DYNAMIC_VALUE' && d.range.start.offset >= e.range.start.offset && d.range.end.offset <= e.range.end.offset))) {
70
+ diagnostic(p, 'POLICY_STALE_DYNAMIC_EXCEPTION', 'record does not match an extracted dynamic-value diagnostic', true);
71
+ }
72
+ });
73
+ policy.ownerOverrides?.forEach((x, i) => {
74
+ const p = `/ownerOverrides/${i}`;
75
+ if (unsupported(x.path, p, true))
76
+ return;
77
+ if (!contextExists(x.path, x.context))
78
+ diagnostic(p, 'POLICY_STALE_OVERRIDE', 'source ownership context no longer exists', true);
79
+ else {
80
+ const mechanisms = evidence.filter(e => e.path === x.path && e.context === x.context).map(e => e.mechanism);
81
+ const compatible = (m) => x.owner === 'unknown' || (m === 'css' ? x.owner === 'custom-css' : m === 'react-inline' ? x.owner === 'custom-inline' : m === 'html-root' ? x.owner === 'document-runtime' : ['custom-emotion-review', 'custom-emotion-logical'].includes(x.owner));
82
+ if (!mechanisms.length || !mechanisms.every(compatible))
83
+ diagnostic(p, 'POLICY_CONFLICT', 'override does not establish a compatible extracted style mechanism', true);
84
+ }
85
+ });
86
+ policy.issueBindings.forEach((b, i) => {
87
+ const p = `/issueBindings/${i}`;
88
+ if (unsupported(b.path, p, false))
89
+ return;
90
+ if (!findings.some(f => f.ruleId === b.ruleId && f.path === b.path && f.context.includes(b.contextIncludes) && (!b.originalIncludes || f.original.includes(b.originalIncludes))))
91
+ diagnostic(p, 'POLICY_STALE_INFORMATIONAL', 'reference binding has no supported source finding; no issue coverage can be inferred', false);
92
+ });
93
+ policy.roles.forEach((role, i) => {
94
+ // A role must yield the existing role rule, not merely name a source file containing that string.
95
+ const p = `/roles/${i}`;
96
+ if (unsupported(role.path, p, false))
97
+ return;
98
+ if (!findings.some(f => f.ruleId === 'RTL.BRAND.ISLAND' && f.path === role.path && (f.original.match(/className\s*=\s*(['"])(.*?)\1/)?.[2].split(/\s+/).includes(role.className) ?? false)))
99
+ diagnostic(p, 'POLICY_STALE_INFORMATIONAL', 'brand association has no matched source rule; review role applicability', false);
100
+ });
101
+ const ids = new Set();
102
+ for (const f of findings) {
103
+ if (!findingIdPattern.test(f.id) || !f.id.startsWith(f.ruleId + ':') || !ruleIds.has(f.ruleId) || ids.has(f.id)) {
104
+ diagnostics.push({ path: f.path, range: f.range, code: 'POLICY_FINDING_ID_INVALID', message: 'BLOCKING: invalid, unsupported or duplicate generated finding identity', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy decisions cannot rely on ambiguous finding identities.' });
105
+ }
106
+ ids.add(f.id);
107
+ }
108
+ return diagnostics;
109
+ }
@@ -0,0 +1,137 @@
1
+ import ts from 'typescript';
2
+ import { range } from './model.js';
3
+ export const policyPath = 'rtl-scanner.config.json';
4
+ export const mechanisms = ['css', 'emotion-template', 'mui-sx', 'mui-theme', 'react-inline', 'html-root'];
5
+ const owners = ['custom-css', 'custom-inline', 'custom-emotion-review', 'custom-emotion-logical', 'mui-generated', 'document-runtime', 'unknown'];
6
+ export const ruleIds = new Set([
7
+ 'RTL.CSS.PHYSICAL', 'RTL.CSS.SHORTHAND', 'RTL.GEOMETRY.EDGE', 'RTL.GEOMETRY.COUPLED', 'RTL.GEOMETRY.ORDER',
8
+ 'RTL.OWNERSHIP.CONFLICT', 'RTL.RUNTIME.MISMATCH', 'RTL.RUNTIME.CACHE', 'RTL.RUNTIME.CACHE_UNVERIFIED',
9
+ 'RTL.RUNTIME.DIRECTION_UNKNOWN', 'RTL.RUNTIME.PAGINATION', 'RTL.RUNTIME.LOCALE', 'RTL.FORM.DIRECTION',
10
+ 'RTL.TABLE.ALIGNMENT', 'RTL.CHART.LABEL_FLOW', 'RTL.ICON.PROGRESSION', 'RTL.ICON.LITERAL',
11
+ 'RTL.BIDI.ISOLATION', 'RTL.BRAND.ISLAND', 'RTL.DOCUMENT.INITIAL', 'RTL.DOCUMENT.RUNTIME',
12
+ ]);
13
+ export const findingIdPattern = /^RTL\.[A-Z_]+(?:\.[A-Z_]+)*:[a-f0-9]{24}$/;
14
+ export class PolicyError extends Error {
15
+ diagnostic;
16
+ constructor(diagnostic) {
17
+ super(`Invalid scanner policy: ${diagnostic.path}:${diagnostic.range.start.line}:${diagnostic.range.start.column} ${diagnostic.code}: ${diagnostic.message}`);
18
+ this.diagnostic = diagnostic;
19
+ }
20
+ }
21
+ const pointerPart = (s) => s.replace(/~/g, '~0').replace(/\//g, '~1');
22
+ export function policyLocations(text) {
23
+ const sf = ts.parseJsonText(policyPath, text);
24
+ const locations = new Map();
25
+ function walk(n, pointer) {
26
+ locations.set(pointer, range(text, n.getStart(sf), n.end));
27
+ if (ts.isObjectLiteralExpression(n)) {
28
+ const seen = new Set();
29
+ for (const p of n.properties)
30
+ if (ts.isPropertyAssignment(p) && ts.isStringLiteral(p.name)) {
31
+ const child = `${pointer}/${pointerPart(p.name.text)}`;
32
+ if (seen.has(p.name.text))
33
+ throw new PolicyError({ path: policyPath, range: range(text, p.getStart(sf), p.end), code: 'POLICY_DUPLICATE', message: `BLOCKING ${child}: duplicate JSON member`, blocking: true, impact: 'SOURCE_FAILURE', rationale: 'JSON member overwrite is ambiguous; no policy decisions are applied.' });
34
+ seen.add(p.name.text);
35
+ walk(p.initializer, child);
36
+ }
37
+ }
38
+ else if (ts.isArrayLiteralExpression(n))
39
+ n.elements.forEach((e, i) => walk(e, `${pointer}/${i}`));
40
+ }
41
+ const statement = sf.statements[0];
42
+ if (statement && ts.isExpressionStatement(statement))
43
+ walk(statement.expression, '');
44
+ return locations;
45
+ }
46
+ export function validatePolicy(input, text) {
47
+ const locations = policyLocations(text);
48
+ const fail = (pointer, message, code = 'POLICY_INVALID') => {
49
+ const parent = pointer.slice(0, pointer.lastIndexOf('/'));
50
+ throw new PolicyError({ path: policyPath, range: locations.get(pointer) ?? locations.get(parent) ?? range(text, 0, 0), code, message: `BLOCKING ${pointer || '/'}: ${message}`, blocking: true, impact: 'SOURCE_FAILURE', rationale: 'Policy input is invalid, conflicting or unsupported; no policy decisions are applied.' });
51
+ };
52
+ function object(value, pointer, required, optional = []) {
53
+ if (!value || typeof value !== 'object' || Array.isArray(value))
54
+ fail(pointer, 'expected object');
55
+ const obj = value;
56
+ for (const key of Object.keys(obj).sort())
57
+ if (![...required, ...optional].includes(key))
58
+ fail(`${pointer}/${pointerPart(key)}`, 'unknown field');
59
+ for (const key of required)
60
+ if (!Object.hasOwn(obj, key))
61
+ fail(`${pointer}/${key}`, 'required field missing');
62
+ return obj;
63
+ }
64
+ const str = (v, p) => { if (typeof v !== 'string' || !v.trim() || v.length > 4096 || v.includes('\0'))
65
+ fail(p, 'expected nonempty bounded string'); return v; };
66
+ const enumValue = (v, p, values) => { const s = str(v, p); if (!values.includes(s))
67
+ fail(p, 'unsupported enum value'); return s; };
68
+ const pathValue = (v, p) => {
69
+ const s = str(v, p);
70
+ if (/^[\/\\]|^[A-Za-z]:|\\|[\r\n]/.test(s) || s.split('/').some(x => !x || x === '.' || x === '..'))
71
+ fail(p, 'expected normalized repository-relative POSIX path');
72
+ };
73
+ const digest = (v, p) => { if (!/^[a-f0-9]{64}$/.test(str(v, p)))
74
+ fail(p, 'expected lowercase SHA-256 digest'); };
75
+ const rule = (v, p) => { if (!ruleIds.has(str(v, p)))
76
+ fail(p, 'rule is not supported by this scanner', 'POLICY_UNSUPPORTED'); };
77
+ const top = object(input, '', ['schemaVersion', 'generatedStyleOwner', 'ownership', 'approvals', 'exceptions', 'issueBindings', 'dynamicExceptions', 'roles'], ['ownerOverrides']);
78
+ if (top.schemaVersion !== 1)
79
+ fail('/schemaVersion', 'only schemaVersion 1 is supported', 'POLICY_UNSUPPORTED');
80
+ enumValue(top.generatedStyleOwner, '/generatedStyleOwner', ['mui-generated', 'unknown']);
81
+ const ownership = object(top.ownership, '/ownership', [], [...mechanisms]);
82
+ for (const [k, v] of Object.entries(ownership)) {
83
+ enumValue(v, `/ownership/${k}`, owners);
84
+ const allowed = k === 'css' ? ['custom-css', 'unknown'] : k === 'react-inline' ? ['custom-inline', 'unknown'] : k === 'html-root' ? ['document-runtime', 'unknown'] : ['custom-emotion-review', 'custom-emotion-logical', 'unknown'];
85
+ enumValue(v, `/ownership/${k}`, allowed);
86
+ }
87
+ const shapes = {
88
+ approvals: [['path', 'context', 'property', 'value', 'owner', 'logicalProperty', 'reason', 'reviewedBy', 'sourceDigest'], []],
89
+ exceptions: [['ruleId', 'path', 'context', 'category', 'reason', 'reviewedBy', 'originalDigest'], []],
90
+ issueBindings: [['ruleId', 'path', 'contextIncludes', 'issueId'], ['originalIncludes']],
91
+ dynamicExceptions: [['path', 'property', 'valueDigest', 'sourceDigest', 'reason'], []],
92
+ roles: [['kind', 'path', 'className'], []],
93
+ ownerOverrides: [['path', 'context', 'owner', 'reason'], []],
94
+ };
95
+ const identities = {
96
+ approvals: ['path', 'context', 'property', 'value'], exceptions: ['ruleId', 'path', 'context', 'originalDigest'],
97
+ issueBindings: ['ruleId', 'path', 'contextIncludes', 'originalIncludes', 'issueId'],
98
+ dynamicExceptions: ['path', 'property', 'valueDigest'], roles: ['kind', 'path', 'className'], ownerOverrides: ['path', 'context'],
99
+ };
100
+ for (const [name, [required, optional]] of Object.entries(shapes)) {
101
+ if (name === 'ownerOverrides' && !Object.hasOwn(top, name))
102
+ continue;
103
+ const records = top[name];
104
+ if (!Array.isArray(records) || records.length > 10000)
105
+ fail(`/${name}`, 'expected bounded array');
106
+ const seen = new Map();
107
+ for (let i = 0; i < records.length; i++) {
108
+ const p = `/${name}/${i}`, entry = object(records[i], p, required, optional);
109
+ for (const [key, v] of Object.entries(entry))
110
+ str(v, `${p}/${key}`);
111
+ pathValue(entry.path, `${p}/path`);
112
+ for (const key of ['sourceDigest', 'originalDigest', 'valueDigest'])
113
+ if (key in entry)
114
+ digest(entry[key], `${p}/${key}`);
115
+ if ('ruleId' in entry)
116
+ rule(entry.ruleId, `${p}/ruleId`);
117
+ if ('owner' in entry)
118
+ enumValue(entry.owner, `${p}/owner`, owners);
119
+ if ('category' in entry)
120
+ enumValue(entry.category, `${p}/category`, ['INTENTIONAL_LTR', 'INFORMATIONAL']);
121
+ if (name === 'roles')
122
+ enumValue(entry.kind, `${p}/kind`, ['brand']);
123
+ if (name === 'dynamicExceptions')
124
+ enumValue(entry.property, `${p}/property`, ['background']);
125
+ if (name === 'issueBindings' && !/^RTL-0[1-9]$/.test(entry.issueId))
126
+ fail(`${p}/issueId`, 'unsupported reference issue ID');
127
+ const identity = JSON.stringify(identities[name].map(k => entry[k] ?? null));
128
+ const prior = seen.get(identity);
129
+ if (prior) {
130
+ const conflict = name === 'ownerOverrides' && prior.owner !== entry.owner || name === 'exceptions' && prior.category !== entry.category || name === 'approvals' && (prior.owner !== entry.owner || prior.logicalProperty !== entry.logicalProperty) || name === 'dynamicExceptions' && prior.sourceDigest !== entry.sourceDigest;
131
+ fail(p, conflict ? 'conflicting policy records' : 'duplicate policy record', conflict ? 'POLICY_CONFLICT' : 'POLICY_DUPLICATE');
132
+ }
133
+ seen.set(identity, entry);
134
+ }
135
+ }
136
+ return input;
137
+ }
package/dist/policy.js ADDED
@@ -0,0 +1,32 @@
1
+ import { readFile, lstat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { range } from './model.js';
4
+ import { PolicyError, policyPath, validatePolicy } from './policy-validation.js';
5
+ export const emptyPolicy = { schemaVersion: 1, generatedStyleOwner: 'unknown', ownership: {}, approvals: [], exceptions: [], issueBindings: [], dynamicExceptions: [], roles: [] };
6
+ const sourceTexts = new WeakMap();
7
+ export const policySourceText = (policy) => sourceTexts.get(policy) ?? JSON.stringify(policy, null, 2);
8
+ export async function loadPolicy(root) {
9
+ let text;
10
+ try {
11
+ if ((await lstat(join(root, policyPath))).isSymbolicLink())
12
+ throw new PolicyError({ path: policyPath, range: range('', 0, 0), code: 'POLICY_INVALID_PATH', message: 'BLOCKING /: symlink policy file not permitted', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy input must remain inside the read-only repository scope.' });
13
+ text = await readFile(join(root, policyPath), 'utf8');
14
+ }
15
+ catch (e) {
16
+ if (e.code === 'ENOENT')
17
+ return emptyPolicy;
18
+ throw e;
19
+ }
20
+ if (text.length > 1_000_000)
21
+ throw new PolicyError({ path: policyPath, range: range(text, 0, 0), code: 'POLICY_INVALID', message: 'BLOCKING /: policy exceeds size limit', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy input size is bounded.' });
22
+ let input;
23
+ try {
24
+ input = JSON.parse(text);
25
+ }
26
+ catch {
27
+ throw new PolicyError({ path: policyPath, range: range(text, 0, 0), code: 'POLICY_INVALID_JSON', message: 'BLOCKING /: invalid JSON', impact: 'SOURCE_FAILURE', blocking: true, rationale: 'Policy JSON cannot be interpreted; no policy decisions are applied.' });
28
+ }
29
+ const policy = validatePolicy(input, text);
30
+ sourceTexts.set(policy, text);
31
+ return policy;
32
+ }
@@ -0,0 +1,52 @@
1
+ function freezeDeep(value) {
2
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
3
+ for (const child of Object.values(value))
4
+ freezeDeep(child);
5
+ Object.freeze(value);
6
+ }
7
+ return value;
8
+ }
9
+ function clone(value) {
10
+ return JSON.parse(JSON.stringify(value));
11
+ }
12
+ /**
13
+ * Adapt the canonical report without changing its shape, ordering, or bytes.
14
+ * Renderers must not mutate the scan result through this view.
15
+ */
16
+ export function toSchemaV2Presentation(report) {
17
+ const evidence = clone(report.evidence);
18
+ const findings = clone(report.findings);
19
+ const evidenceById = new Map();
20
+ for (const item of evidence)
21
+ evidenceById.set(item.id, [...(evidenceById.get(item.id) ?? []), item]);
22
+ const evidenceReferences = findings.map((finding) => {
23
+ const evidenceForFinding = [];
24
+ const missingEvidenceIds = [];
25
+ const duplicateEvidenceIds = [];
26
+ const seen = new Set();
27
+ for (const id of finding.evidenceIds) {
28
+ const matches = evidenceById.get(id) ?? [];
29
+ if (seen.has(id))
30
+ duplicateEvidenceIds.push(id);
31
+ seen.add(id);
32
+ if (!matches.length)
33
+ missingEvidenceIds.push(id);
34
+ else
35
+ evidenceForFinding.push(matches[0]);
36
+ if (matches.length > 1)
37
+ duplicateEvidenceIds.push(id);
38
+ }
39
+ return { findingId: finding.id, evidenceIds: [...finding.evidenceIds], evidence: evidenceForFinding, missingEvidenceIds, duplicateEvidenceIds };
40
+ });
41
+ const presentation = {
42
+ schemaVersion: report.schemaVersion,
43
+ kind: report.kind,
44
+ policyDigest: report.policyDigest,
45
+ inputDigest: report.inputDigest,
46
+ files: clone(report.files), skipped: clone(report.skipped), evidence, diagnostics: clone(report.diagnostics), findings,
47
+ metrics: clone(report.metrics), complete: report.complete,
48
+ };
49
+ freezeDeep(evidenceReferences);
50
+ Object.defineProperty(presentation, 'evidenceReferences', { value: evidenceReferences, enumerable: false, writable: false, configurable: false });
51
+ return freezeDeep(presentation);
52
+ }
@@ -0,0 +1,15 @@
1
+ export const PREVIEW_MANIFEST_VERSION = 1;
2
+ export const PREVIEW_COMPANION_ORIGIN = 'http://127.0.0.1:4318';
3
+ export const previewManifest = { version: PREVIEW_MANIFEST_VERSION, mappings: [{ id: 'invoicing-invoice-table', source: 'apps/invoicing/src/components/InvoiceTable.tsx', application: 'invoicing', owningRoute: '/invoices', routes: { ltr: '/invoices', rtl: '/invoices?demo=unmigrated-rtl&lang=ar' } }] };
4
+ const mappingById = new Map(previewManifest.mappings.map((mapping) => [mapping.id, mapping]));
5
+ export function approvedPreviewForSource(source) { return previewManifest.mappings.find((mapping) => mapping.source === source) ?? null; }
6
+ export function validatedPreviewRoute(mappingId, mode) {
7
+ const mapping = mappingById.get(mappingId);
8
+ if (!mapping || (mode !== 'ltr' && mode !== 'rtl'))
9
+ return null;
10
+ const selectedMode = mode;
11
+ const route = mapping.routes[selectedMode];
12
+ if (!route.startsWith(mapping.owningRoute) || (selectedMode === 'rtl' && route !== '/invoices?demo=unmigrated-rtl&lang=ar'))
13
+ return null;
14
+ return { mapping, mode: selectedMode, route };
15
+ }
@@ -0,0 +1,110 @@
1
+ import { lstat, link, open, unlink } from 'node:fs/promises';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ export class PublicationError extends Error {
5
+ rollbackIncomplete;
6
+ published;
7
+ constructor(message, rollbackIncomplete = false, published = []) {
8
+ super(message);
9
+ this.rollbackIncomplete = rollbackIncomplete;
10
+ this.published = published;
11
+ }
12
+ }
13
+ const defaultFs = { lstat, open, link, unlink, platform: process.platform };
14
+ const unsupportedLinkCodes = new Set(['ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']);
15
+ function unsupportedLink(error) { return unsupportedLinkCodes.has(error?.code ?? ''); }
16
+ async function assertDirectory(path, root, fs) {
17
+ // The trusted-owner POSIX profile cannot eliminate a malicious directory
18
+ // replacement between validation and the hard-link call; the immediate
19
+ // lstat and same-directory no-overwrite link minimize that residual TOCTOU.
20
+ if (fs.platform !== 'darwin' && fs.platform !== 'linux' && fs.platform !== 'win32')
21
+ throw new PublicationError('unsupported platform/filesystem profile');
22
+ const absolute = resolve(path);
23
+ const rel = relative(root, absolute);
24
+ if (rel === '' || (!rel.startsWith('..') && !rel.startsWith('/')))
25
+ throw new PublicationError('output directory must be external to the scanner root');
26
+ for (let current = absolute;; current = resolve(current, '..')) {
27
+ const stat = await fs.lstat(current).catch(() => { throw new PublicationError('output directory and ancestors must already exist'); });
28
+ if (stat.isSymbolicLink() || !stat.isDirectory())
29
+ throw new PublicationError('output directory and ancestors must be non-symlink directories');
30
+ if (current === resolve(current, '..'))
31
+ break;
32
+ }
33
+ }
34
+ async function prepare(directory, name, contents, fs) {
35
+ let handle;
36
+ for (let attempt = 0; attempt < 4; attempt++) {
37
+ const temp = join(directory, `.${name}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`);
38
+ try {
39
+ handle = await fs.open(temp, 'wx', 0o600);
40
+ await handle.writeFile(contents, 'utf8');
41
+ await handle.sync();
42
+ await handle.close();
43
+ return { temp };
44
+ }
45
+ catch (error) {
46
+ await handle?.close().catch(() => undefined);
47
+ await fs.unlink(temp).catch(() => undefined);
48
+ if (error.code !== 'EEXIST')
49
+ throw error;
50
+ }
51
+ }
52
+ throw new PublicationError('could not create an unpredictable exclusive temporary file');
53
+ }
54
+ async function publish(directory, name, contents, fs) {
55
+ const prepared = await prepare(directory, name, contents, fs);
56
+ let created;
57
+ try {
58
+ await assertDirectory(directory, directory + '/__external-root-that-cannot-match', fs);
59
+ const destination = join(directory, name);
60
+ await fs.link(prepared.temp, destination);
61
+ const sourceStat = await fs.lstat(prepared.temp);
62
+ const destinationStat = await fs.lstat(destination);
63
+ if (sourceStat.dev !== destinationStat.dev || sourceStat.ino !== destinationStat.ino || destinationStat.isSymbolicLink())
64
+ throw new PublicationError('published destination identity mismatch');
65
+ created = { path: destination, dev: destinationStat.dev, ino: destinationStat.ino };
66
+ await fs.unlink(prepared.temp);
67
+ return created;
68
+ }
69
+ catch (error) {
70
+ await fs.unlink(prepared.temp).catch(() => undefined);
71
+ if (unsupportedLink(error))
72
+ throw new PublicationError('unsupported hard-link publication capability', false, created ? [created] : []);
73
+ if (created && error instanceof Error && !(error instanceof PublicationError))
74
+ throw new PublicationError(`published ${name} but temporary cleanup failed`, false, [created]);
75
+ if (created && error instanceof PublicationError && error.published.length === 0)
76
+ throw new PublicationError(error.message, error.rollbackIncomplete, [created]);
77
+ throw error;
78
+ }
79
+ }
80
+ async function removeIfOwned(file, fs) {
81
+ try {
82
+ const stat = await fs.lstat(file.path);
83
+ if (stat.dev !== file.dev || stat.ino !== file.ino || stat.isSymbolicLink())
84
+ return false;
85
+ await fs.unlink(file.path);
86
+ return true;
87
+ }
88
+ catch (error) {
89
+ if (error.code === 'ENOENT')
90
+ return true;
91
+ return false;
92
+ }
93
+ }
94
+ export async function publishArtifacts(root, outputDirectory, artifacts, fs = defaultFs) {
95
+ const directory = resolve(outputDirectory);
96
+ await assertDirectory(directory, resolve(root), fs);
97
+ const published = [];
98
+ try {
99
+ for (const artifact of artifacts)
100
+ published.push(await publish(directory, artifact.name, artifact.contents, fs));
101
+ }
102
+ catch (error) {
103
+ const allPublished = [...published, ...(error instanceof PublicationError ? error.published : [])];
104
+ const results = await Promise.all(allPublished.reverse().map(file => removeIfOwned(file, fs)));
105
+ if (results.some(result => !result))
106
+ throw new PublicationError('report publication failed; ROLLBACK_INCOMPLETE', true, allPublished);
107
+ throw error instanceof PublicationError ? error : new PublicationError(`report publication failed: ${error instanceof Error ? error.message : String(error)}`);
108
+ }
109
+ }
110
+ export async function publishReports(root, outputDirectory, json, markdown, fs = defaultFs) { return publishArtifacts(root, outputDirectory, [{ name: 'rtl-report.json', contents: json }, { name: 'rtl-report.md', contents: markdown }], fs); }
package/dist/report.js ADDED
@@ -0,0 +1,8 @@
1
+ export const json = (r) => JSON.stringify(r, null, 2) + '\n';
2
+ const escape = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').replace(/`/g, '\\`');
3
+ export function markdown(r) {
4
+ const counts = new Map();
5
+ for (const f of r.findings)
6
+ counts.set(f.category, (counts.get(f.category) ?? 0) + 1);
7
+ return `# Conservative RTL risk report\n\nStatic risks and documented exceptions, not automatic proof of visual failures.\n\nSchema: ${r.schemaVersion}; files: ${r.files.length}; extracted facts: ${r.evidence.length}; findings: ${r.findings.length}; diagnostics: ${r.diagnostics.length}; complete: ${r.complete}.\n\n` + [...counts].sort(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => `- ${k}: ${v}`).join('\n') + '\n\n## Findings\n\n' + r.findings.map(f => `### ${f.id}\n\n**${f.title}** — ${f.category}; ${f.severity}; ${f.confidence} confidence.\n\nSource: ${f.path}:${f.range.start.line}:${f.range.start.column}; mechanism: ${f.sourceMechanism}; application attribution: ${f.applications.join(', ') || 'shared reachability unresolved'}; context: ${escape(f.context)}; owner: ${f.ownership}.\n\nOriginal: ${escape(f.original)}\n\nRationale: ${f.rationale}\n\nTreatment: ${f.treatment}\n\nLimits: ${f.limitation}\n\nRelated issues: ${f.issueIds.join(', ') || 'none'}; evidence IDs: ${f.evidenceIds.join(', ') || 'structural AST evidence'}; related locations: ${f.relatedLocations.map(x => `${x.path}:${x.range.start.line}:${x.range.start.column}`).join(', ') || 'none'}.\n\n${f.exceptionReason ? `Exception: ${f.exceptionReason}; original category: ${f.originalCategory}.\n\n` : ''}${f.suggestion ? `Conditional suggestion: ${f.suggestion.property}: ${escape(f.suggestion.value)}\n\n` : ''}`).join('') + '## Coverage diagnostics\n\n' + r.diagnostics.map(d => `- ${d.path}:${d.range.start.line}:${d.range.start.column} ${d.code} — ${d.impact ?? 'POLICY'}, blocking=${d.blocking}: ${escape(d.message)} ${d.rationale}`).join('\n') + '\n\n## Source evidence inventory\n\n| Source | Mechanism | Context | Original declaration | Semantics |\n| --- | --- | --- | --- | --- |\n' + r.evidence.map(e => `| ${e.path}:${e.range.start.line}:${e.range.start.column} | ${e.mechanism} | ${escape(e.context)} | ${escape(e.original)} | ${e.semantics} |`).join('\n') + '\n';
8
+ }
@@ -0,0 +1,153 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { cp, lstat, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+ import { spawn } from 'node:child_process';
6
+ import { request as httpRequest } from 'node:http';
7
+ export const REVIEW_SOURCE = 'apps/invoicing/src/components/InvoiceTable.tsx';
8
+ export const REVIEW_FINDING_ID = 'RTL.ICON.PROGRESSION:237172da962fe4d0605ddd83';
9
+ export const CANDIDATE_PORT = 4202;
10
+ export const CANDIDATE_ORIGIN = `http://127.0.0.1:${CANDIDATE_PORT}`;
11
+ export function runtimeCacheDir(root, role) { return join(resolve(root), '.rtl-vite-cache', role); }
12
+ const runtimes = new Map();
13
+ const reviewRecords = new Map();
14
+ const digest = (text) => createHash('sha256').update(text).digest('hex');
15
+ const recordKey = (identity) => `${identity.findingId}|${identity.sourcePath}|${identity.inputDigest}|${identity.policyDigest}|${identity.schemaVersion}`;
16
+ export const reviewStatusTransitions = {
17
+ 'Not Reviewed': ['Needs Manual Investigation', 'Verified Correct', 'Candidate Proposed'],
18
+ 'Needs Manual Investigation': ['Verified Correct', 'Candidate Proposed', 'Rejected'],
19
+ 'Verified Correct': ['Needs Manual Investigation'],
20
+ 'Candidate Proposed': ['Validation Failed', 'Ready for Review', 'Needs Manual Investigation'],
21
+ 'Validation Failed': ['Candidate Proposed', 'Needs Manual Investigation'],
22
+ 'Ready for Review': ['Approved', 'Rejected', 'Needs Manual Investigation'],
23
+ 'Approved': ['Rejected', 'Needs Manual Investigation'],
24
+ 'Rejected': ['Candidate Proposed', 'Needs Manual Investigation'],
25
+ };
26
+ export function reviewRecordKey(identity) { return recordKey(identity); }
27
+ const validSerializedReviewPath = (path) => Boolean(path) && !path.includes('\0') && !path.includes('\\') && !/^[A-Za-z](?::|[\\/])/.test(path) && !posix.isAbsolute(path) && !path.endsWith('/') && !path.split('/').some(part => part === '' || part === '.' || part === '..') && posix.normalize(path) === path;
28
+ export function validateReviewIdentity(identity) { if (!identity || typeof identity.findingId !== 'string' || !identity.findingId.trim() || identity.findingId.length > 500 || typeof identity.sourcePath !== 'string' || !validSerializedReviewPath(identity.sourcePath) || identity.schemaVersion !== 2 || !identity.inputDigest || !identity.policyDigest)
29
+ throw new Error('INVALID_REVIEW_IDENTITY'); }
30
+ export function validateReviewRecordShape(input) { validateReviewIdentity(input); if (!Object.prototype.hasOwnProperty.call(input, 'status') || !reviewStatusTransitions[input.status])
31
+ throw new Error('INVALID_REVIEW_STATUS'); if (typeof input.reviewerNotes !== 'string' || input.reviewerNotes.length > 4000 || !Array.isArray(input.evidenceReferences) || input.evidenceReferences.length > 50 || input.evidenceReferences.some(reference => typeof reference !== 'string' || reference.length > 500))
32
+ throw new Error('REVIEW_EVIDENCE_TOO_LARGE'); if (input.candidateSessionId !== undefined && (typeof input.candidateSessionId !== 'string' || input.candidateSessionId.length > 100))
33
+ throw new Error('INVALID_CANDIDATE_SESSION_ID'); if (input.timestamp !== undefined && (!Number.isFinite(Date.parse(input.timestamp))))
34
+ throw new Error('INVALID_REVIEW_TIMESTAMP'); }
35
+ export function getReviewRecord(identity) { validateReviewIdentity(identity); return reviewRecords.get(recordKey(identity)) ?? null; }
36
+ export function saveReviewRecord(input) {
37
+ validateReviewRecordShape(input);
38
+ const key = recordKey(input);
39
+ const current = reviewRecords.get(key);
40
+ const previous = current?.status ?? 'Not Reviewed';
41
+ if (input.status !== previous && !reviewStatusTransitions[previous].includes(input.status))
42
+ throw new Error('INVALID_REVIEW_TRANSITION');
43
+ const record = { ...input, timestamp: input.timestamp ?? new Date().toISOString() };
44
+ reviewRecords.set(key, record);
45
+ return record;
46
+ }
47
+ export function clearReviewRecords() { reviewRecords.clear(); }
48
+ const inside = (root, target) => { const r = relative(root, target); return r === '' || (r !== '..' && !r.startsWith(`..${sep}`) && !isAbsolute(r)); };
49
+ export function validateReviewPath(root, path) {
50
+ if (!validSerializedReviewPath(path))
51
+ throw new Error('INVALID_REVIEW_PATH');
52
+ const target = resolve(root, path);
53
+ if (!inside(resolve(root), target) || path !== REVIEW_SOURCE)
54
+ throw new Error('REVIEW_SOURCE_NOT_ALLOWED');
55
+ return target;
56
+ }
57
+ export async function validateProjectSourcePath(root, path) {
58
+ if (!validSerializedReviewPath(path))
59
+ throw new Error('INVALID_REVIEW_PATH');
60
+ const canonicalRoot = await realpath(resolve(root));
61
+ const target = resolve(canonicalRoot, path);
62
+ if (!inside(canonicalRoot, target))
63
+ throw new Error('REVIEW_SOURCE_NOT_ALLOWED');
64
+ let canonicalTarget;
65
+ try {
66
+ canonicalTarget = await realpath(target);
67
+ }
68
+ catch (error) {
69
+ if (error.code === 'ENOENT')
70
+ throw new Error('PROJECT_SOURCE_UNAVAILABLE');
71
+ throw error;
72
+ }
73
+ if (!inside(canonicalRoot, canonicalTarget))
74
+ throw new Error('REVIEW_SOURCE_NOT_ALLOWED');
75
+ return canonicalTarget;
76
+ }
77
+ export function validatePatch(text, patch) {
78
+ if (!patch.findingId || patch.path !== REVIEW_SOURCE)
79
+ throw new Error('REVIEW_FINDING_NOT_ALLOWED');
80
+ if (!Number.isInteger(patch.startOffset) || !Number.isInteger(patch.endOffset) || patch.startOffset < 0 || patch.endOffset < patch.startOffset || patch.endOffset > text.length)
81
+ throw new Error('INVALID_REVIEW_RANGE');
82
+ if (digest(text.slice(patch.startOffset, patch.endOffset)) !== patch.expectedSha256)
83
+ throw new Error('STALE_REVIEW_SOURCE');
84
+ }
85
+ export async function createReviewSession(root) {
86
+ const source = validateReviewPath(root, REVIEW_SOURCE);
87
+ const sourceStat = await lstat(source);
88
+ if (!sourceStat.isFile())
89
+ throw new Error('REVIEW_SOURCE_NOT_REGULAR_FILE');
90
+ const candidateRoot = await mkdtemp(join(tmpdir(), 'rtl-review-'));
91
+ try {
92
+ const allowedTopLevel = new Set(['apps', 'libs', 'package.json', 'package-lock.json', 'nx.json', 'tsconfig.json', 'tsconfig.base.json', 'vite.config.ts', 'playwright.config.ts']);
93
+ await cp(root, candidateRoot, { recursive: true, dereference: false, filter: (sourcePath) => { const relativePath = relative(root, sourcePath); const top = relativePath.split(/[\\/]/)[0] ?? ''; return relativePath === '' || allowedTopLevel.has(top); } });
94
+ const copied = validateReviewPath(candidateRoot, REVIEW_SOURCE);
95
+ const text = await readFile(copied, 'utf8');
96
+ return { id: randomUUID(), root: resolve(root), candidateRoot, sourcePath: REVIEW_SOURCE, state: 'Candidate Proposed', classification: 'Manual', originalSha256: digest(text), createdAt: new Date().toISOString() };
97
+ }
98
+ catch (error) {
99
+ await rm(candidateRoot, { recursive: true, force: true });
100
+ throw error;
101
+ }
102
+ }
103
+ export async function applyReviewPatch(session, patch) {
104
+ const target = validateReviewPath(session.candidateRoot, patch.path);
105
+ const text = await readFile(target, 'utf8');
106
+ validatePatch(text, patch);
107
+ const next = text.slice(0, patch.startOffset) + patch.replacement + text.slice(patch.endOffset);
108
+ await writeFile(target, next, 'utf8');
109
+ return { ...session, state: 'Candidate Proposed', candidateSha256: digest(next) };
110
+ }
111
+ export async function reviewSessionDiff(session) {
112
+ const original = await readFile(validateReviewPath(session.root, REVIEW_SOURCE), 'utf8');
113
+ const candidate = await readFile(validateReviewPath(session.candidateRoot, REVIEW_SOURCE), 'utf8');
114
+ if (original === candidate)
115
+ return 'No candidate changes applied.';
116
+ const originalLine = original.split(/\r?\n/).find(line => line.includes('{i.id}')) ?? '';
117
+ const candidateLine = candidate.split(/\r?\n/).find(line => line.includes('{i.id}')) ?? '';
118
+ return `--- ${REVIEW_SOURCE} (original)\n+++ ${REVIEW_SOURCE} (candidate)\n@@\n- ${originalLine}\n+ ${candidateLine}`;
119
+ }
120
+ function health(origin, port) { return new Promise(resolveHealth => { const request = httpRequest(`${origin}/invoices`, { method: 'GET', host: '127.0.0.1', port, path: '/invoices', timeout: 1000 }, response => { response.resume(); resolveHealth(Boolean(response.statusCode && response.statusCode < 500)); }); request.on('error', () => resolveHealth(false)); request.on('timeout', () => { request.destroy(); resolveHealth(false); }); request.end(); }); }
121
+ export async function assertPortAvailable(port = CANDIDATE_PORT) { if (await health(`http://127.0.0.1:${port}`, port))
122
+ throw new Error('CANDIDATE_PORT_OCCUPIED'); }
123
+ export async function startCandidateRuntime(session) {
124
+ if (runtimes.has(session.id))
125
+ return { ...session, runtime: { port: CANDIDATE_PORT, origin: CANDIDATE_ORIGIN, status: 'healthy' } };
126
+ await assertPortAvailable();
127
+ const viteBin = join(session.root, 'node_modules/vite/bin/vite.js');
128
+ const dependencyMount = join(session.candidateRoot, 'node_modules');
129
+ await symlink(join(session.root, 'node_modules'), dependencyMount, 'dir');
130
+ const candidateConfig = join(session.candidateRoot, 'apps/invoicing/vite.config.ts');
131
+ const child = spawn(process.execPath, [viteBin, '--config', candidateConfig, '--host', '127.0.0.1', '--port', String(CANDIDATE_PORT), '--strictPort'], { cwd: session.root, env: { ...process.env, NODE_PATH: join(session.root, 'node_modules'), RTL_VITE_CACHE_DIR: runtimeCacheDir(session.candidateRoot, 'candidate') }, shell: false, stdio: ['ignore', 'ignore', 'pipe'] });
132
+ let startupError = '';
133
+ child.stderr?.on('data', chunk => { startupError = `${startupError}${String(chunk)}`.slice(-2000); });
134
+ runtimes.set(session.id, child);
135
+ const starting = { ...session, runtime: { port: CANDIDATE_PORT, origin: CANDIDATE_ORIGIN, status: 'starting' } };
136
+ for (let attempt = 0; attempt < 100; attempt++) {
137
+ if (await health(CANDIDATE_ORIGIN, CANDIDATE_PORT))
138
+ return { ...starting, runtime: { ...starting.runtime, status: 'healthy' } };
139
+ if (child.exitCode !== null)
140
+ break;
141
+ await new Promise(resolveDelay => setTimeout(resolveDelay, 100));
142
+ }
143
+ await stopCandidateRuntime(starting);
144
+ return { ...starting, runtime: { ...starting.runtime, status: 'failed', ...(startupError ? { error: startupError.trim() } : {}) } };
145
+ }
146
+ export async function stopCandidateRuntime(session) { const child = runtimes.get(session.id); if (child && child.exitCode === null) {
147
+ child.kill('SIGTERM');
148
+ await new Promise(resolveStop => { const timer = setTimeout(() => { if (child.exitCode === null)
149
+ child.kill('SIGKILL'); resolveStop(); }, 2000); child.once('exit', () => { clearTimeout(timer); resolveStop(); }); });
150
+ } runtimes.delete(session.id); return { ...session, runtime: session.runtime ? { ...session.runtime, status: 'stopped' } : undefined }; }
151
+ export async function disposeReviewSession(session) { if (!inside(tmpdir(), resolve(session.candidateRoot)))
152
+ throw new Error('INVALID_REVIEW_SESSION_ROOT'); await stopCandidateRuntime(session); await rm(session.candidateRoot, { recursive: true, force: true }); }
153
+ export const reviewSourceDirectory = (root) => dirname(validateReviewPath(root, REVIEW_SOURCE));