Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Route matching retains Unicode component keys and rejects empty-key matches. Git literal backslashes do not invent directory separators; existing Windows-style API input remains supported. Static HTML filename segments are URL-encoded, and human-readable route tables escape terminal control characters. Filename decoding supports valid UTF-8 names; arbitrary non-UTF-8 Git pathname bytes are not supported.

- Git changed-file discovery now reads NUL-delimited pathnames in both merge-base and direct fallback diffs, preserving Korean names, whitespace, tabs and newlines instead of passing display-quoted strings to route inference (DEV-158).

## 0.1.1
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,11 @@ An opt-in local [livesay evidence-pack example](examples/livesay-pack/README.md)
uses the existing scene grammar to bind screenshots, DOM checks and simulated
announcement changes to one base/head pair. It generates proposed comment
Markdown only, with explicit unverified collection states.

### Git path inference API

When passing Git's slash-separated paths directly to `inferRoutes`, use
`inferRoutes(changed.files, { gitPaths: true })`, where `changed` is the result
of `changedFiles(...)`. CLI and compare set this automatically. This avoids
interpreting a literal POSIX backslash as a Windows directory separator.
Filename decoding supports valid UTF-8 names, not arbitrary non-UTF-8 bytes.
14 changes: 10 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { runCompare, type FailOn } from "./compare";
import { changedFiles } from "./git";
import { runInit, WORKFLOW_PATH } from "./init";
import { detectNextProject, discoverRouterRoutes, inferRoutes } from "./routes";
import { normalizeRoute } from './util';
import { normalizeRoute, routeIdentity } from './util';
import type { ViewportSpec } from "./types";

export interface CliContext {
Expand Down Expand Up @@ -235,13 +235,14 @@ async function commandRoutes(
? []
: discoverRouterRoutes(ctx.cwd);
const candidates = inferRoutes(diff.files, {
gitPaths: !explicitFiles,
config,
routerRoutes,
nextProject: detectNextProject(ctx.cwd),
});

if (parsed.flags.has("json")) {
const scenes = config.scenes?.map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => candidates.some(candidate => normalizeRoute(applyRouteParams(candidate.route, config.params).route) === scene.route));
const scenes = config.scenes?.map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => candidates.some(candidate => routeIdentity(applyRouteParams(candidate.route, config.params).route, candidate.framework === "static") === routeIdentity(scene.route, candidate.framework === "static")));
ctx.out(
JSON.stringify(
{ range: diff.range, files: diff.files, routes: candidates, ...(scenes?.length ? { scenes } : {}) },
Expand Down Expand Up @@ -273,11 +274,11 @@ async function commandRoutes(
);
for (const candidate of candidates) {
ctx.out(
`${candidate.route.padEnd(width)} ${candidate.framework.padEnd(frameworkWidth)} ${candidate.source}`,
`${terminalSafe(candidate.route).padEnd(width)} ${candidate.framework.padEnd(frameworkWidth)} ${terminalSafe(candidate.source)}`,
);
}
if (config.scenes?.length) {
for (const scene of config.scenes.map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => candidates.some(candidate => normalizeRoute(applyRouteParams(candidate.route, config.params).route) === scene.route))) ctx.out(`scene: ${scene.name} (${scene.route})`);
for (const scene of config.scenes.map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => candidates.some(candidate => routeIdentity(applyRouteParams(candidate.route, config.params).route, candidate.framework === "static") === routeIdentity(scene.route, candidate.framework === "static")))) ctx.out(`scene: ${scene.name} (${scene.route})`);
}
return 0;
}
Expand Down Expand Up @@ -471,3 +472,8 @@ export function resolveViewports(names: string[]): ViewportSpec[] {
if (!specs) throw new Error("no viewports given");
return specs;
}

/** Keep untrusted filenames from emitting terminal control sequences. JSON mode stays lossless. */
function terminalSafe(value: string): string {
return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4,'0')}`);
}
10 changes: 6 additions & 4 deletions src/compare.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { routeIdentity } from './util';
import { computeAxeDelta } from './axe';
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { basename, resolve } from "node:path";
Expand Down Expand Up @@ -77,7 +78,7 @@ export async function runCompare(options: CompareOptions = {}): Promise<CompareO
const outDir = resolve(cwd, options.outDir ?? config.outDir ?? "proofshot-out");
const collectA11y = options.collectA11y ?? config.a11y ?? true;

const { routes, routesSource } = resolveRoutes({
const { routes, routesSource, staticRoutes } = resolveRoutes({
cwd,
explicit: options.routes,
config,
Expand All @@ -94,7 +95,7 @@ export async function runCompare(options: CompareOptions = {}): Promise<CompareO
);
}

const scenes = normalizeScenes(options.scenes ?? config.scenes ?? []).map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => routes.includes(scene.route));
const scenes = normalizeScenes(options.scenes ?? config.scenes ?? []).map(scene => ({ ...scene, route: normalizeRoute(applyRouteParams(scene.route, config.params).route) })).filter(scene => routes.some(route => routeIdentity(route, staticRoutes.includes(route)) === routeIdentity(scene.route, staticRoutes.includes(route))));

await mkdir(outDir, { recursive: true });

Expand Down Expand Up @@ -217,7 +218,7 @@ function resolveRoutes(input: {
baseRef?: string;
headRef?: string;
notes: string[];
}): { routes: string[]; routesSource: string } {
}): { routes: string[]; routesSource: string; staticRoutes: string[] } {
let candidates;
let source: string;
const params = input.config.params;
Expand All @@ -242,6 +243,7 @@ function resolveRoutes(input: {
if (changed.warning) input.notes.push(changed.warning);
const routerRoutes = discoverRouterRoutes(input.cwd);
candidates = inferRoutes(changed.files, {
gitPaths: true,
config: input.config,
routerRoutes,
nextProject: detectNextProject(input.cwd),
Expand All @@ -263,7 +265,7 @@ function resolveRoutes(input: {
});

const unique = uniqueBy(resolved, (candidate) => candidate.route);
return { routes: unique.map((candidate) => candidate.route), routesSource: source };
return { routes: unique.map((candidate) => candidate.route), routesSource: source, staticRoutes: unique.filter(candidate => candidate.framework === "static").map(candidate => candidate.route) };
}

async function comparePair(input: {
Expand Down
19 changes: 11 additions & 8 deletions src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
} from "./util";

export interface InferRoutesOptions {
/** Git already uses slash separators; literal POSIX backslashes are unsupported route names. */
gitPaths?: boolean;
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
config?: ProofshotConfig;
/** Routes discovered from React Router definition files. */
routerRoutes?: RouterRoute[];
Expand Down Expand Up @@ -85,6 +87,7 @@ export function inferRoutes(
};

for (const rawFile of changedFiles) {
if (options.gitPaths && rawFile.includes("\\")) continue;
const file = toPosix(rawFile).replace(/^\.\//, "");
if (isIgnoredSource(file)) continue;

Expand Down Expand Up @@ -217,7 +220,7 @@ export function staticHtmlRoute(file: string): string | null {
} else {
segments[segments.length - 1] = base;
}
const route = `/${segments.join("/")}`;
const route = `/${segments.map(segment => encodeURIComponent(segment)).join("/")}`;
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
return normalizeRoute(route);
}

Expand Down Expand Up @@ -344,8 +347,8 @@ function matchRouterRoute(
return routerRoutes.filter(
(route) =>
routerFileSet.has(file) ||
(route.component !== undefined && componentKey(route.component) === key) ||
Boolean(route.ancestors?.some(component=>componentKey(component)===key)),
(key !== "" && route.component !== undefined && componentKey(route.component) === key) ||
Boolean(key && route.ancestors?.some(component=>componentKey(component)===key)),
);
}

Expand Down Expand Up @@ -532,13 +535,13 @@ export function parseRouterSource(source: string, file: string): RouterRoute[] {
const path = match[2] ?? "";
if (!path.startsWith("/") && path !== "*") continue;
const window = objectSource.slice(match.index, match.index + 400);
const element = /element\s*:\s*<\s*([A-Za-z0-9_$]+)/.exec(window);
const component = /(?:Component|component)\s*:\s*([A-Za-z0-9_$]+)/.exec(
const element = /element\s*:\s*<\s*([$\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)/u.exec(window);
const component = /(?:Component|component)\s*:\s*([$\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)/u.exec(
window,
);
routes.push({
route: path,
component: element?.[1] ?? component?.[1],
component: element && (!component || element.index < component.index) ? element[1] : component?.[1],
file,
});
}
Expand All @@ -561,10 +564,10 @@ function readPathAttribute(attrs: string): string | null {
}

function readComponentAttribute(attrs: string): string | undefined {
const element = /element\s*=\s*\{\s*<\s*([A-Za-z0-9_$]+)/.exec(attrs);
const element = /element\s*=\s*\{\s*<\s*([$\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)/u.exec(attrs);
if (element?.[1]) return element[1];
const component =
/(?:Component|component)\s*=\s*(?:\{\s*([A-Za-z0-9_$]+)|"([^"]+)")/.exec(
/(?:Component|component)\s*=\s*(?:\{\s*([$\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)|"([^"]+)")/u.exec(
attrs,
);
return component?.[1] ?? component?.[2];
Expand Down
9 changes: 8 additions & 1 deletion src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function stripExt(name: string): string {
/** A case-insensitive key used to match `Dashboard.tsx` with `<Dashboard />`. */
export function componentKey(value: string): string {
return stripExt(value)
.replace(/[^a-zA-Z0-9]/g, "")
.replace(/[^\p{L}\p{N}]/gu, "")
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
.toLowerCase();
}

Expand Down Expand Up @@ -112,3 +112,10 @@ export function isUrl(target: string): boolean {
export function sceneArtifactId(route: string, name: string): string {
return `scene-${createHash("sha256").update(JSON.stringify([normalizeRoute(route), name])).digest("hex")}`;
}

/** Browser-equivalent local route identity, without decoding encoded separators. */
export function routeIdentity(route: string, staticFilename = false): string {
const url = new URL(normalizeRoute(route), 'http://proofshot.invalid');
if (staticFilename) url.pathname = url.pathname.replace(/%[0-9a-f]{2}/gi, escape => escape.toUpperCase());
return url.href;
}
85 changes: 80 additions & 5 deletions test/git.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { changedFiles, revParse, shortSha } from '../src/git';
import { inferRoutes } from '../src/routes';
import { discoverRouterRoutes, inferRoutes } from '../src/routes';
import { runCli } from '../src/cli';
import { runCompare } from '../src/compare';
import { routeIdentity } from '../src/util';

const dirs: string[] = [];
function fixture() {
Expand Down Expand Up @@ -40,22 +43,94 @@ describe('real Git changed-file paths', () => {
expect(result.files).toEqual(expect.arrayContaining(['app/설정/page.tsx','app/pricing/page.tsx']));
expect(inferRoutes(result.files).map(r=>r.route).sort()).toEqual(['/pricing','/설정']);
});
it('preserves whitespace, quotes, backslashes and line boundaries without trimming', () => {
it.skipIf(process.platform === 'win32')('preserves whitespace, quotes, backslashes and line boundaries without trimming', () => {
const f=fixture();
const names=[' leading.tsx','trailing.tsx ','two words.tsx','tab\tname.tsx','line\nbreak.tsx','quote"name.tsx',...(process.platform==='win32'?[]:['back\\slash.tsx'])];
const names=[' leading.tsx','trailing.tsx ','two words.tsx','tab\tname.tsx','line\nbreak.tsx','quote"name.tsx','back\\slash.tsx'];
f.add(names);
expect(changedFiles({cwd:f.cwd,baseRef:f.base}).files.sort()).toEqual([...names].sort());
});
it('uses the same lossless parsing for unrelated-history direct fallback', () => {
const f=fixture();
f.git('checkout','--quiet','--orphan','unrelated');
f.add(['app/설정/page.tsx','tabs\tand\nlines.tsx',' trailing ']);
const names=['app/설정/page.tsx','two words.tsx',...(process.platform==='win32'?[]:['tabs\tand\nlines.tsx',' trailing '])];
f.add(names);
const result=changedFiles({cwd:f.cwd,baseRef:f.base,headRef:'HEAD'});
expect(result.range).toBe(`${f.base}..HEAD`);
expect(result.warning).toContain('used a direct diff');
expect(result.files.sort()).toEqual(['app/설정/page.tsx','tabs\tand\nlines.tsx',' trailing '].sort());
expect(result.files.sort()).toEqual(names.sort());
expect(inferRoutes(result.files).map(r=>r.route)).toContain('/설정');
});
it('selects only the changed Korean React Router component', () => {
const f=fixture(); f.add(['src/pages/설정.tsx']);
const routes=inferRoutes(changedFiles({cwd:f.cwd,baseRef:f.base}).files,{gitPaths:true,routerRoutes:[
{route:'/settings',component:'설정',file:'src/App.tsx'},
{route:'/help',component:'도움말',file:'src/App.tsx'},
]});
expect(routes.map(r=>r.route)).toEqual(['/settings']);
});
it('discovers full mixed Unicode object components before Git inference', () => {
const f=fixture();
mkdirSync(join(f.cwd,'src'),{recursive:true});
writeFileSync(join(f.cwd,'src/router.tsx'), `createBrowserRouter([{path:'/account',Component:Account설정},{path:'/help',element:<Help도움 />}])`);
f.git('add','--all'); f.git('commit','--quiet','-m','router');
const base=f.git('rev-parse','HEAD'); f.add(['src/screens/Account설정.tsx']);
expect(inferRoutes(changedFiles({cwd:f.cwd,baseRef:base}).files,{gitPaths:true,routerRoutes:discoverRouterRoutes(f.cwd)}).map(r=>r.route)).toEqual(['/account']);
});
it('lists and executes an unencoded Korean scene for an inferred static route', async () => {
const f=fixture(); f.add(['설정/index.html']);
writeFileSync(join(f.cwd,'설정/index.html'), '<main id="korean-page">unique Korean fixture</main>');
const config={scenes:[{name:'korean',route:'/설정',steps:[],expect:'#korean-page'},{name:'encoded',route:encodeURI('/설정').toLowerCase(),steps:[],expect:'#korean-page'}]};
writeFileSync(join(f.cwd,'.proofshot.json'),JSON.stringify(config));
const lines:string[]=[];
await runCli(['routes','--base-ref',f.base,'--json'],{cwd:f.cwd,stdout:l=>lines.push(l)});
expect(JSON.parse(lines.join('\n')).scenes).toHaveLength(2);
const result=await runCompare({cwd:f.cwd,base:f.cwd,head:f.cwd,baseRef:f.base,outDir:join(f.cwd,'artifacts'),viewports:[{name:'small',width:400,height:400}]});
expect(result.stats.errors).toBe(0);
expect(result.results.some(r=>r.scene==='korean')).toBe(true);
expect(result.results.some(r=>r.scene==='encoded')).toBe(true);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
expect(routeIdentity('/a%2fb',true)).not.toBe(routeIdentity('/a/b',true));
expect(routeIdentity('/search?q=%2f')).not.toBe(routeIdentity('/search?q=%2F'));
expect(routeIdentity('/search?q=%2f',true)).not.toBe(routeIdentity('/search?q=%2F',true));
},30000);
it('keeps explicit query escape casing exact in CLI and capture scene selection', async () => {
const f=fixture(); f.add(['index.html']);
const config={routes:['/search?q=%2F'],scenes:[{name:'not-selected',route:'/search?q=%2f',steps:[]}]};
writeFileSync(join(f.cwd,'.proofshot.json'),JSON.stringify(config));
const lines:string[]=[];
await runCli(['routes','--base-ref',f.base,'--json'],{cwd:f.cwd,stdout:l=>lines.push(l)});
expect(JSON.parse(lines.join('\n')).scenes).toBeUndefined();
const result=await runCompare({cwd:f.cwd,base:f.cwd,head:f.cwd,outDir:join(f.cwd,'artifacts'),viewports:[{name:'small',width:400,height:400}]});
expect(result.stats.errors).toBe(0);
expect(result.results).toHaveLength(1);
expect(result.results[0]?.scene).toBeUndefined();
},30000);
it('does not match empty component keys and preserves Windows-style API inputs', () => {
expect(inferRoutes(['src/pages/---.tsx'],{routerRoutes:[{route:'/wrong',component:'___',file:'src/App.tsx'}]}).map(r=>r.route)).not.toContain('/wrong');
expect(inferRoutes(['app\\settings\\page.tsx']).map(r=>r.route)).toEqual(['/settings']);
});
it.skipIf(process.platform === 'win32')('does not invent slash directories from Git literal backslashes', () => {
const f=fixture(); f.add(['app\\settings/page.tsx','app/pricing/page.tsx']);
const routes=inferRoutes(changedFiles({cwd:f.cwd,baseRef:f.base}).files,{gitPaths:true});
expect(routes.map(r=>r.route)).toEqual(['/pricing']);
});
it.skipIf(process.platform === 'win32')('escapes terminal controls but preserves JSON filenames', async () => {
const f=fixture(); f.add(['app/evil\x1b[2J\u009b/page.tsx']);
for(const json of [false,true]) {
const lines:string[]=[];
await runCli(['routes','--base-ref',f.base,...(json?['--json']:[])],{cwd:f.cwd,stdout:l=>lines.push(l)});
const text=lines.join('\n'); expect(text).not.toContain('\x1b'); if(!json) expect(text).not.toContain('\u009b');
if(json) expect(JSON.parse(text).files).toEqual(['app/evil\x1b[2J\u009b/page.tsx']);
}
});
it.skipIf(process.platform === 'win32')('captures the actual tab-named static page through Git inference', async () => {
const f=fixture(); f.add(['team\tupdates/index.html']);
const outcome=await runCompare({cwd:f.cwd,base:f.cwd,head:f.cwd,baseRef:f.base,
outDir:join(f.cwd,'artifacts'),viewports:[{name:'small',width:400,height:400}],
observer:{beforeScreenshot:async page=>{expect(await page.locator('body').textContent()).toContain('export default');}},
});
expect(outcome.stats.errors).toBe(0);
expect(outcome.results.map(r=>r.route)).toEqual(['/team%09updates']);
},30000);
it('returns no phantom file for an empty diff and keeps revision helpers trimmed', () => {
const f=fixture();
expect(changedFiles({cwd:f.cwd,baseRef:f.base}).files).toEqual([]);
Expand Down