rtl-analyzer 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +53 -2
- package/dist/bootstrap.js +27 -0
- package/dist/cli.js +76 -0
- package/dist/codemod.js +53 -0
- package/dist/coverage.js +36 -0
- package/dist/css.js +61 -0
- package/dist/dashboard-client.js +167 -0
- package/dist/dashboard-data.js +22 -0
- package/dist/dashboard-html.js +27 -0
- package/dist/discovery.js +71 -0
- package/dist/eligibility.js +19 -0
- package/dist/html.js +34 -0
- package/dist/model.js +9 -0
- package/dist/policy-audit.js +109 -0
- package/dist/policy-validation.js +137 -0
- package/dist/policy.js +32 -0
- package/dist/presentation-adapter.js +52 -0
- package/dist/preview-manifest.js +15 -0
- package/dist/report-publisher.js +110 -0
- package/dist/report.js +8 -0
- package/dist/review-session.js +153 -0
- package/dist/rules.js +215 -0
- package/dist/runtime-direction.js +334 -0
- package/dist/scan.js +59 -0
- package/dist/source-snippets.js +177 -0
- package/dist/standalone-cli.js +38 -0
- package/dist/structured-markdown.js +36 -0
- package/dist/tailwind.js +21 -0
- package/dist/typescript.js +191 -0
- package/package.json +26 -4
|
@@ -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, '&').replace(/</g, '<').replace(/>/g, '>').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));
|
package/dist/rules.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import { analyzeRuntimeDirection } from './runtime-direction.js';
|
|
3
|
+
import valueParser from 'postcss-value-parser';
|
|
4
|
+
import { hash, range } from './model.js';
|
|
5
|
+
const plain = (v) => v.replace(/^['"`]|['"`]$/g, '');
|
|
6
|
+
const cssKey = (p) => p.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
|
|
7
|
+
export function detect(evidence, sources, policy, diagnostics) {
|
|
8
|
+
const findings = [];
|
|
9
|
+
const findingOccurrences = new Map();
|
|
10
|
+
function add(ruleId, title, a, category, rationale, treatment, ownership = 'unknown', refs = [], confidence = 'High', severity = 'Minor', suggestion = null, limitation = 'Static evidence indicates a risk; rendered behavior is not established by this scan.') {
|
|
11
|
+
const exception = policy.exceptions.find(x => x.ruleId === ruleId && x.path === a.path && x.context === a.context && x.originalDigest === hash(a.original));
|
|
12
|
+
const originalCategory = category;
|
|
13
|
+
if (exception)
|
|
14
|
+
category = exception.category;
|
|
15
|
+
const key = ruleId + '|' + a.id;
|
|
16
|
+
const occurrence = findingOccurrences.get(key) ?? 0;
|
|
17
|
+
findingOccurrences.set(key, occurrence + 1);
|
|
18
|
+
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);
|
|
20
|
+
}
|
|
21
|
+
for (const e of evidence) {
|
|
22
|
+
if (cssKey(e.property) === 'position' && plain(e.value) === 'fixed') {
|
|
23
|
+
const peers = evidence.filter(x => x.path === e.path && x.context === e.context);
|
|
24
|
+
const width = peers.find(x => cssKey(x.property) === 'width');
|
|
25
|
+
const gutters = width ? evidence.filter(x => /^margin-(left|right)$/.test(cssKey(x.property)) && plain(x.value) === plain(width.value)) : [];
|
|
26
|
+
if (width && gutters.length)
|
|
27
|
+
add('RTL.GEOMETRY.COUPLED', 'Fixed shell width and physical content reservation', e, 'MANUAL_REVIEW', 'Fixed region width equals a separate physical content margin; independently flipping either can desynchronize shell geometry.', 'Review anchor, gutter, border, mobile transform and resets together.', policy.ownership[e.mechanism] ?? 'unknown', [e, ...peers.filter(x => /^(left|right|width|border-right|transform)$/.test(cssKey(x.property))), ...gutters], 'High');
|
|
28
|
+
}
|
|
29
|
+
if (e.mechanism === 'html-root')
|
|
30
|
+
continue;
|
|
31
|
+
const overrides = policy.ownerOverrides?.filter(x => x.path === e.path && x.context === e.context) ?? [];
|
|
32
|
+
const owners = new Set(overrides.map(x => x.owner));
|
|
33
|
+
const p = cssKey(e.property), v = plain(e.value), owner = owners.size > 1 ? 'conflicting' : overrides[0]?.owner ?? policy.ownership[e.mechanism] ?? 'unknown';
|
|
34
|
+
if (owner === 'conflicting' && !findings.some(f => f.ruleId === 'RTL.OWNERSHIP.CONFLICT' && f.path === e.path && f.context === e.context))
|
|
35
|
+
add('RTL.OWNERSHIP.CONFLICT', 'Conflicting style owners', e, 'MANUAL_REVIEW', 'Multiple data-only policy entries claim different ownership for the same style context.', 'Resolve ownership before proposing logical conversion or RTL processing.', owner, [e], 'High');
|
|
36
|
+
const peers = evidence.filter(x => x.path === e.path && x.context === e.context);
|
|
37
|
+
const position = peers.find(x => cssKey(x.property) === 'position');
|
|
38
|
+
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
|
+
if (/^(left|right)$/.test(p))
|
|
40
|
+
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))) {
|
|
42
|
+
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
|
+
const expectedLogical = p.replace(/^(margin|padding|border)-(left|right)(.*)$/, (_, group, side, suffix) => `${group}-inline-${side === 'left' ? 'start' : 'end'}${suffix}`);
|
|
44
|
+
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)));
|
|
45
|
+
add('RTL.CSS.PHYSICAL', 'Physical horizontal declaration', e, safe ? 'AUTO_CANDIDATE' : 'MANUAL_REVIEW', safe ? approval.reason : 'Physical syntax does not establish reading-start/end intent or styling ownership.', 'Review semantics, writing mode, cascade and owner before any conversion.', owner, [e], 'High', 'Minor', safe ? { property: approval.logicalProperty, value: e.value } : null);
|
|
46
|
+
}
|
|
47
|
+
else if (/^(margin|padding|inset|border-radius)$/.test(p)) {
|
|
48
|
+
const tokens = valueParser(v).nodes.filter(n => n.type !== 'space' && n.type !== 'comment');
|
|
49
|
+
const simple = tokens.every(n => n.type === 'word');
|
|
50
|
+
const words = tokens.map(n => valueParser.stringify(n));
|
|
51
|
+
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))
|
|
53
|
+
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
|
+
}
|
|
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))
|
|
56
|
+
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
|
+
}
|
|
58
|
+
// Generic syntax evidence: imports and JSX/data flow are inspected, never executed.
|
|
59
|
+
const themes = [], rtl = evidence.filter(e => e.mechanism === 'html-root' && e.property === 'dir' && e.value === 'rtl'), providers = [], caches = [], cacheChecks = new Map();
|
|
60
|
+
const entries = [...sources.entries()].filter(([p]) => /\.[jt]sx?$/.test(p));
|
|
61
|
+
for (const [path, text] of entries) {
|
|
62
|
+
const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
|
|
63
|
+
const runtimeProofs = analyzeRuntimeDirection(sf);
|
|
64
|
+
const provenThemes = new Set(runtimeProofs.flatMap(p => p.themeDirections));
|
|
65
|
+
const imports = new Map();
|
|
66
|
+
function importsVisit(n) { if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier)) {
|
|
67
|
+
if (n.importClause?.name)
|
|
68
|
+
imports.set(n.importClause.name.text, n.moduleSpecifier.text);
|
|
69
|
+
if (n.importClause?.namedBindings && ts.isNamedImports(n.importClause.namedBindings))
|
|
70
|
+
for (const x of n.importClause.namedBindings.elements)
|
|
71
|
+
imports.set(x.name.text, n.moduleSpecifier.text + ':' + (x.propertyName?.text ?? x.name.text));
|
|
72
|
+
} ts.forEachChild(n, importsVisit); }
|
|
73
|
+
importsVisit(sf);
|
|
74
|
+
function ctx(n) { let p = n; while (p) {
|
|
75
|
+
if (ts.isFunctionDeclaration(p) && p.name)
|
|
76
|
+
return p.name.text;
|
|
77
|
+
if (ts.isVariableDeclaration(p) && ts.isIdentifier(p.name))
|
|
78
|
+
return p.name.text;
|
|
79
|
+
p = p.parent;
|
|
80
|
+
} return 'module'; }
|
|
81
|
+
function identity(n) { if (ts.isJsxText(n))
|
|
82
|
+
return 'JsxText:' + n.getText(sf).trim(); if (ts.isIdentifier(n) || ts.isStringLiteral(n) || ts.isNumericLiteral(n))
|
|
83
|
+
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
|
+
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
|
+
function visit(n) {
|
|
97
|
+
for (const proof of runtimeProofs.filter(p => p.node === n)) {
|
|
98
|
+
const cacheAnchor = anchor(n, ctx(n) + (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n) ? '/' + n.tagName.getText(sf) : ''));
|
|
99
|
+
caches.push(cacheAnchor);
|
|
100
|
+
if (!proof.supported)
|
|
101
|
+
cacheChecks.set(cacheAnchor, proof.reasons);
|
|
102
|
+
}
|
|
103
|
+
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && imports.get(n.expression.text)?.endsWith(':createTheme'))
|
|
104
|
+
for (const arg of n.arguments)
|
|
105
|
+
if (ts.isObjectLiteralExpression(arg))
|
|
106
|
+
for (const p of arg.properties)
|
|
107
|
+
if (ts.isPropertyAssignment(p) && p.name.getText(sf) === 'direction') {
|
|
108
|
+
if (ts.isStringLiteral(p.initializer) && p.initializer.text === 'ltr' && !provenThemes.has(p))
|
|
109
|
+
themes.push(anchor(p));
|
|
110
|
+
else if (!ts.isStringLiteral(p.initializer)) {
|
|
111
|
+
const a = anchor(p);
|
|
112
|
+
diagnostics.push({ path, range: a.range, code: 'RUNTIME_DIRECTION_UNKNOWN', message: 'Theme direction expression not statically resolved.', impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Runtime direction cannot be safely correlated.' });
|
|
113
|
+
add('RTL.RUNTIME.DIRECTION_UNKNOWN', 'Dynamic runtime direction requires review', a, 'RUNTIME_CONFIG', 'Direction is supplied by an unresolved expression.', 'Review document/theme/cache synchronization without evaluating application code.', policy.generatedStyleOwner ?? 'unknown', [], 'Low');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken && ts.isPropertyAccessExpression(n.left) && n.left.getText(sf) === 'document.documentElement.dir') {
|
|
117
|
+
function options(x) { if (ts.isStringLiteral(x))
|
|
118
|
+
return [x.text]; if (ts.isParenthesizedExpression(x) || ts.isAsExpression(x))
|
|
119
|
+
return options(x.expression); if (ts.isConditionalExpression(x)) {
|
|
120
|
+
const a = options(x.whenTrue), b = options(x.whenFalse);
|
|
121
|
+
return a && b ? [...a, ...b] : undefined;
|
|
122
|
+
} return undefined; }
|
|
123
|
+
const values = options(n.right), a = anchor(n);
|
|
124
|
+
if (values?.includes('rtl'))
|
|
125
|
+
rtl.push(a);
|
|
126
|
+
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.' });
|
|
128
|
+
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
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) {
|
|
132
|
+
const name = n.tagName.getText(sf), binding = imports.get(name) ?? '';
|
|
133
|
+
const a = () => anchor(n, ctx(n) + '/' + name);
|
|
134
|
+
if (binding.endsWith(':ThemeProvider'))
|
|
135
|
+
providers.push(a());
|
|
136
|
+
if (binding.startsWith('@mui/icons-material') && /[/:](ArrowForward|ArrowBack|ChevronLeft|ChevronRight|KeyboardArrowLeft|KeyboardArrowRight|NavigateBefore|NavigateNext)(:|$)/.test(binding))
|
|
137
|
+
add('RTL.ICON.PROGRESSION', 'Directional icon requires semantic review', a(), 'MANUAL_REVIEW', 'Imported directional icon renders in JSX; navigation meaning and appropriate orientation need review.', 'Distinguish progression from trends/external-link conventions; coordinate MUI-owned roles before mirroring.', 'custom-icon', [], 'Medium');
|
|
138
|
+
if (binding === '@mui/material:Pagination')
|
|
139
|
+
add('RTL.RUNTIME.PAGINATION', 'Pagination direction depends on MUI theme', a(), 'RUNTIME_CONFIG', 'MUI supplies directional pagination roles through theme context, independently of HTML flow.', 'Verify synchronized theme/cache/document setup before adding custom icon swaps.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
140
|
+
if (binding === '@mui/material:TableCell' && !n.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'align'))
|
|
141
|
+
add('RTL.TABLE.ALIGNMENT', 'Table cell has no explicit alignment policy', a(), 'MANUAL_REVIEW', 'Generated default alignment and content-specific alignment policy are not declared at this cell.', 'Review text, numeric and token alignment with runtime configuration; absence of align alone is not a bug.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
142
|
+
if (binding === '@mui/material:TextField')
|
|
143
|
+
add('RTL.FORM.DIRECTION', 'Field geometry delegates to runtime styling', a(), 'RUNTIME_CONFIG', 'MUI field labels/notches/helpers depend on theme and generated style processing.', 'Verify document/theme/cache coordination and native input behavior; do not patch vendor geometry.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium');
|
|
144
|
+
if (name === 'svg' && ts.isJsxElement(n.parent)) {
|
|
145
|
+
const parent = n.parent;
|
|
146
|
+
let host = parent.parent;
|
|
147
|
+
if (!ts.isJsxElement(host))
|
|
148
|
+
host = parent;
|
|
149
|
+
const labels = [];
|
|
150
|
+
function check(x) { if (ts.isJsxAttribute(x) && x.name.getText(sf) === 'className' && x.initializer && ts.isStringLiteral(x.initializer)) {
|
|
151
|
+
const classNames = x.initializer.text.split(/\s+/);
|
|
152
|
+
for (const e of evidence)
|
|
153
|
+
if (e.mechanism === 'css' && classNames.some(c => e.context.endsWith('/.' + c)) && e.property === 'display' && e.value === 'flex')
|
|
154
|
+
labels.push(x);
|
|
155
|
+
} ts.forEachChild(x, check); }
|
|
156
|
+
check(host);
|
|
157
|
+
if (labels.length && parent.getText(sf).includes('<path')) {
|
|
158
|
+
const ar = a();
|
|
159
|
+
const refs = evidence.filter(e => labels.some(l => ts.isJsxAttribute(l) && l.initializer && ts.isStringLiteral(l.initializer) && e.context.endsWith('/.' + l.initializer.text)));
|
|
160
|
+
add('RTL.CHART.LABEL_FLOW', 'SVG geometry with separate flex labels', ar, 'MANUAL_REVIEW', 'Fixed SVG geometry and separate HTML flex labels can respond differently to document direction.', 'Review chronology, axis gutters, labels/data correspondence and accessible description together.', 'manual-chart', refs, 'Medium', 'Major');
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const classAttr = n.attributes.properties.find(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'className');
|
|
164
|
+
if (classAttr && ts.isJsxAttribute(classAttr) && classAttr.initializer && ts.isStringLiteral(classAttr.initializer)) {
|
|
165
|
+
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
|
+
if (role && !n.attributes.properties.some(p => ts.isJsxAttribute(p) && p.name.getText(sf) === 'dir')) {
|
|
167
|
+
const refs = evidence.filter(e => e.mechanism === 'css' && e.context.endsWith('/.' + role.className) && e.property === 'display' && e.value === 'flex');
|
|
168
|
+
if (refs.length)
|
|
169
|
+
add('RTL.BRAND.ISLAND', 'Brand flex composition has no explicit direction island', a(), 'MANUAL_REVIEW', 'Reviewed brand role uses inherited flex flow with separate visual children and no local direction contract.', 'Preserve the approved wordmark composition as a reviewed island; do not mirror glyphs.', 'manual-brand', refs, 'Medium');
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if ((ts.isJsxText(n) && /[→←]/.test(n.getText(sf))) || (ts.isStringLiteral(n) && /[→←]/.test(n.text) && (ts.isCallExpression(n.parent) || ts.isJsxExpression(n.parent)) && (() => { let p = n.parent; while (p) {
|
|
174
|
+
if (ts.isJsxExpression(p))
|
|
175
|
+
return true;
|
|
176
|
+
p = p.parent;
|
|
177
|
+
} return false; })()))
|
|
178
|
+
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)) {
|
|
180
|
+
let candidate = false;
|
|
181
|
+
function token(x) { if (ts.isPropertyAccessExpression(x) && ['name', 'address', 'email', 'id'].includes(x.name.text))
|
|
182
|
+
candidate = true; if (ts.isCallExpression(x) && ts.isIdentifier(x.expression) && imports.get(x.expression.text)?.endsWith(':money'))
|
|
183
|
+
candidate = true; ts.forEachChild(x, token); }
|
|
184
|
+
token(n.expression);
|
|
185
|
+
// Only text children, not event handlers, attributes or JSX render branches.
|
|
186
|
+
const direct = ts.isPropertyAccessExpression(n.expression) && ['name', 'address', 'email', 'id'].includes(n.expression.name.text) || ts.isCallExpression(n.expression) && ts.isIdentifier(n.expression.expression) && imports.get(n.expression.expression.text)?.endsWith(':money');
|
|
187
|
+
if (candidate && direct && (ts.isJsxElement(n.parent) || ts.isJsxFragment(n.parent)) && !ts.isJsxElement(n.expression) && !ts.isConditionalExpression(n.expression) && !ts.isBinaryExpression(n.expression))
|
|
188
|
+
add('RTL.BIDI.ISOLATION', 'Unisolated token/content text sink', anchor(n), 'MANUAL_REVIEW', 'Known-name/token expression is rendered without an explicit bdi/dir ancestor; actual run direction and punctuation remain data-dependent.', 'Review opposite-direction token isolation or auto-direction for human text; preserve canonical storage and copying.', 'manual-content', [], 'Medium');
|
|
189
|
+
}
|
|
190
|
+
if (ts.isNewExpression(n) && n.expression.getText(sf) === 'Intl.NumberFormat' && n.arguments?.[0] && ts.isStringLiteral(n.arguments[0]))
|
|
191
|
+
add('RTL.RUNTIME.LOCALE', 'Fixed locale formatter', anchor(n), 'RUNTIME_CONFIG', 'Formatting uses a fixed display locale; direction and locale formatting are separate contracts.', 'Approve locale display policy separately from canonical currency/date values and bidi isolation.', 'locale-runtime', [], 'High');
|
|
192
|
+
ts.forEachChild(n, visit);
|
|
193
|
+
}
|
|
194
|
+
visit(sf);
|
|
195
|
+
}
|
|
196
|
+
for (const e of evidence.filter(e => e.mechanism === 'html-root' && e.property === 'dir'))
|
|
197
|
+
add('RTL.DOCUMENT.INITIAL', 'Initial HTML direction', e, 'INFORMATIONAL', 'Initial HTML direction is a source fact, not the client runtime direction.', 'Preserve approved default English markup; evaluate runtime direction separately.', 'document-runtime', [e], 'High', 'Info');
|
|
198
|
+
for (const a of rtl.filter(a => a.context !== 'html'))
|
|
199
|
+
add('RTL.DOCUMENT.RUNTIME', 'Document-level RTL assignment exists', a, 'INFORMATIONAL', 'Document root direction can switch to RTL; body-mounted portals inherit root direction unless overridden.', 'Verify portal computed direction independently; do not report a wrapper-only portal failure.', 'document-runtime', [], 'High', 'Info');
|
|
200
|
+
if (rtl.length && themes.length) {
|
|
201
|
+
for (const a of themes) {
|
|
202
|
+
const f = add('RTL.RUNTIME.MISMATCH', 'RTL document capability with fixed LTR theme', a, 'RUNTIME_CONFIG', 'Analyzed source assigns document RTL while createTheme direction is fixed LTR. These are separate direction channels.', 'Review reachable provider synchronization; MUI theme alone does not rewrite generated physical styles.', policy.generatedStyleOwner ?? 'unknown', [], 'High', 'Major');
|
|
203
|
+
f.relatedLocations.push(...rtl.map(a => ({ path: a.path, range: a.range })));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (rtl.length && providers.length && !caches.length) {
|
|
207
|
+
for (const a of providers)
|
|
208
|
+
add('RTL.RUNTIME.CACHE', 'No owned Emotion cache found in analyzed provider scope', a, 'RUNTIME_CONFIG', 'The analyzed provider/import scope contains no CacheProvider despite document RTL capability; transitive cache packages do not establish configured RTL processing.', 'Review compatible LTR/RTL style processing and custom-style ownership; absence is a scoped inference.', policy.generatedStyleOwner ?? 'unknown', [], 'Medium', 'Minor', null, 'External providers, re-exported cache wrappers and unscanned configuration may invalidate this absence inference.');
|
|
209
|
+
}
|
|
210
|
+
for (const [a, reasons] of cacheChecks) {
|
|
211
|
+
diagnostics.push({ path: a.path, range: a.range, code: 'CACHE_CONFIGURATION_UNRESOLVED', message: 'CacheProvider configuration unresolved: ' + reasons.join(' '), impact: 'DIRECTIONAL_UNSUPPORTED', blocking: true, rationale: 'Cache presence alone cannot establish generated RTL processing or ownership.' });
|
|
212
|
+
add('RTL.RUNTIME.CACHE_UNVERIFIED', 'Emotion cache direction pipeline needs verification', a, 'RUNTIME_CONFIG', 'CacheProvider presence does not prove RTL plugin compatibility or exemption behavior.', 'Review cache creation/plugins and ownership as a separate configuration contract.', policy.generatedStyleOwner ?? 'unknown', [], 'Low');
|
|
213
|
+
}
|
|
214
|
+
return findings.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.range.start.offset - b.range.start.offset || a.ruleId.localeCompare(b.ruleId, 'en'));
|
|
215
|
+
}
|