Skip to content

Write HTML. Render video. Built for agents.

fix(studio-server): a rename rewrites only references that name the renamed path (#4915)

Miguel Ángel1168bb740d33
diff --git a/packages/studio-server/src/routes/files.renameReferences.test.ts b/packages/studio-server/src/routes/files.renameReferences.test.ts
new file mode 100644
index 0000000000..ca36ba442f
--- /dev/null
+++ b/packages/studio-server/src/routes/files.renameReferences.test.ts
@@ -0,0 +1,237 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Hono } from "hono";
+import { afterEach, describe, expect, it } from "vitest";
+import { referenceRewriter, registerFileRoutes } from "./files";
+import type { StudioApiAdapter } from "../types";
+
+const rewrite = (text: string, from: string, to: string, folder: boolean) =>
+ referenceRewriter(from, to, folder)(text);
+
+describe("rename references", () => {
+ it("rewrites a folder where files under it are named, in every form a project writes them", () => {
+ const text = [
+ '<img src="assets/a.png">',
+ "url(./assets/a.png)",
+ '"../assets/a.png"',
+ '{"poster":"assets/b/c.png"}',
+ ].join("\n");
+ expect(rewrite(text, "assets", "brand", true)).toBe(
+ [
+ '<img src="brand/a.png">',
+ "url(./brand/a.png)",
+ '"../brand/a.png"',
+ '{"poster":"brand/b/c.png"}',
+ ].join("\n"),
+ );
+ });
+
+ it("leaves a sibling folder with the same beginning, another folder's path and prose alone", () => {
+ const text = 'assets-backup/b.png my-assets/x.png other/assets/y.png "The assets folder"';
+ expect(rewrite(text, "assets", "brand", true)).toBe(text);
+ });
+
+ it("rewrites a file's path whole, not a longer name that starts with it", () => {
+ const text = '"assets/a.png" "assets/a.png2" "assets/a.png-old"';
+ expect(rewrite(text, "assets/a.png", "assets/b.png", false)).toBe(
+ '"assets/b.png" "assets/a.png2" "assets/a.png-old"',
+ );
+ expect(
+ rewrite('url(assets/a.png) srcset="assets/a.png 2x"', "assets/a.png", "x/b.png", false),
+ ).toBe('url(x/b.png) srcset="x/b.png 2x"');
+ });
+
+ it("keeps a root-relative lead, and reads JSON-escaped and Windows separators", () => {
+ const text = [
+ '<img src="/assets/a.png">',
+ "url(/assets/a.png)",
+ '{"src":"assets\\/a.png"}',
+ '{"path":"assets\\\\a.png"}',
+ ].join("\n");
+ expect(rewrite(text, "assets", "brand", true)).toBe(
+ [
+ '<img src="/brand/a.png">',
+ "url(/brand/a.png)",
+ '{"src":"brand\\/a.png"}',
+ '{"path":"brand\\\\a.png"}',
+ ].join("\n"),
+ );
+ });
+
+ it("leaves a longer path that exists alone, whatever characters its name holds", () => {
+ const rewriteWith = (
+ text: string,
+ from: string,
+ to: string,
+ folder: boolean,
+ existing: string[],
+ ) => referenceRewriter(from, to, folder, existing)(text);
+ const folders = '<img src="other assets/a.png"> <img src="other,assets/a.png">';
+ expect(
+ rewriteWith(folders, "assets", "brand", true, ["other assets", "other,assets", "assets"]),
+ ).toBe(folders);
+ const files =
+ '<img src="assets/a.png&backup.png"><img src="assets/a.png 2x.png"><img src="assets/a.png).png">';
+ expect(
+ rewriteWith(files, "assets/a.png", "assets/b.png", false, [
+ "assets/a.png&backup.png",
+ "assets/a.png 2x.png",
+ "assets/a.png).png",
+ ]),
+ ).toBe(files);
+ });
+
+ it("sees an existing path the match sits in the middle of, and in escaped spellings", () => {
+ const middle = '<img src="other a.png&backup.png">';
+ expect(referenceRewriter("a.png", "b.png", false, ["other a.png&backup.png"])(middle)).toBe(
+ middle,
+ );
+ const escaped = String.raw`{"path":"assets\\a.png&backup.png"} {"path":"assets\/a.png&backup.png"}`;
+ expect(
+ referenceRewriter("assets/a.png", "assets/b.png", false, ["assets/a.png&backup.png"])(
+ escaped,
+ ),
+ ).toBe(escaped);
+ });
+
+ it("compares escaped spellings by their text, not by offsets", () => {
+ const text = String.raw`"dir\/other a.png&backup.png" "dir\\other a.png&backup.png"`;
+ expect(referenceRewriter("a.png", "b.png", false, ["dir/other a.png&backup.png"])(text)).toBe(
+ text,
+ );
+ });
+
+ it("stays fast with thousands of existing paths and references", () => {
+ const existing = Array.from({ length: 5000 }, (_, i) => `archive/assets/image-${i}.png`);
+ const text = Array.from(
+ { length: 5000 },
+ (_, i) => `"assets/a${i}.png" "archive/assets/image-${i}.png"`,
+ ).join("\n");
+ const started = Date.now();
+ const out = referenceRewriter("assets", "brand", true, existing)(text);
+ expect(Date.now() - started).toBeLessThan(2000);
+ expect(out).toContain('"brand/a0.png" "archive/assets/image-0.png"');
+ });
+
+ it("does not multiply suffix and prefix lengths", () => {
+ const existing = Array.from(
+ { length: 200 },
+ (_, i) => `${"z".repeat(i + 1)} a/${"x".repeat(i + 1)}`,
+ );
+ const text = Array.from({ length: 3000 }, () => `"a/${"x".repeat(210)}.png"`).join("\n");
+ const started = Date.now();
+ referenceRewriter("a", "brand", true, existing)(text);
+ expect(Date.now() - started).toBeLessThan(3000);
+ });
+
+ it("rewrites references a bare scan could mistake: unquoted attributes, a space before a paren, srcset", () => {
+ const text =
+ '<img src=assets/a.png alt="x"> url(assets/a.png ) srcset="assets/a.png 1x, assets/a.png 2x"';
+ expect(rewrite(text, "assets/a.png", "x/b.png", false)).toBe(
+ '<img src=x/b.png alt="x"> url(x/b.png ) srcset="x/b.png 1x, x/b.png 2x"',
+ );
+ });
+
+ it("takes no path that is part of a longer one by its start: another root, a plus, a backslash", () => {
+ const text = String.raw`other\assets\a.png other\/assets\/a.png my+assets/a.png`;
+ expect(rewrite(text, "assets", "brand", true)).toBe(text);
+ });
+
+ it("does not stall on a long run of backslashes", () => {
+ const text = `${"\\".repeat(200)}unrelated`;
+ const started = Date.now();
+ expect(rewrite(text, "assets", "brand", true)).toBe(text);
+ expect(Date.now() - started).toBeLessThan(500);
+ });
+
+ it("does not take another folder's path whose middle matches", () => {
+ const text = "other/./assets/a.png other/../assets/a.png";
+ expect(rewrite(text, "assets", "brand", true)).toBe(text);
+ });
+});
+
+describe("renaming a folder over the route", () => {
+ const dirs: string[] = [];
+ afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })));
+
+ it("rewrites references under it and leaves a sibling folder's, and prose, alone", async () => {
+ const project = mkdtempSync(join(tmpdir(), "hf-rename-refs-"));
+ dirs.push(project);
+ mkdirSync(join(project, "assets"));
+ mkdirSync(join(project, "assets-backup"));
+ mkdirSync(join(project, "other assets"));
+ mkdirSync(join(project, "empty assets"));
+ writeFileSync(join(project, "other assets", "a.png"), "x");
+ writeFileSync(join(project, "assets", "a.png"), "x");
+ const html =
+ '<img src="assets/a.png"><img src="assets-backup/a.png"><img src="other assets/a.png"><a href="empty assets/">x</a><p>The assets folder</p>';
+ writeFileSync(join(project, "index.html"), html);
+ const adapter = {
+ resolveProject: async (id: string) => ({ id, dir: project }),
+ } as unknown as StudioApiAdapter;
+ const app = new Hono();
+ registerFileRoutes(app, adapter);
+
+ const response = await app.request("/projects/p/files/assets", {
+ method: "PATCH",
+ body: JSON.stringify({ newPath: "brand" }),
+ });
+
+ expect(response.status).toBe(200);
+ expect(readFileSync(join(project, "index.html"), "utf8")).toBe(
+ '<img src="brand/a.png"><img src="assets-backup/a.png"><img src="other assets/a.png"><a href="empty assets/">x</a><p>The assets folder</p>',
+ );
+ });
+
+ it("leaves a path reached through a linked folder alone", async () => {
+ const project = mkdtempSync(join(tmpdir(), "hf-rename-link-"));
+ dirs.push(project);
+ mkdirSync(join(project, "assets"));
+ mkdirSync(join(project, "shared"));
+ writeFileSync(join(project, "assets", "a.png"), "x");
+ writeFileSync(join(project, "shared", "a.png"), "y");
+ symlinkSync(join(project, "shared"), join(project, "other assets"), "dir");
+ writeFileSync(
+ join(project, "index.html"),
+ '<img src="assets/a.png"><img src="other assets/a.png">',
+ );
+ const adapter = {
+ resolveProject: async (id: string) => ({ id, dir: project }),
+ } as unknown as StudioApiAdapter;
+ const app = new Hono();
+ registerFileRoutes(app, adapter);
+
+ await app.request("/projects/p/files/assets/a.png", {
+ method: "PATCH",
+ body: JSON.stringify({ newPath: "assets/b.png" }),
+ });
+
+ expect(readFileSync(join(project, "index.html"), "utf8")).toBe(
+ '<img src="assets/b.png"><img src="other assets/a.png">',
+ );
+ });
+
+ it("moves a relative link whose target the move leaves behind, and still rewrites references", async () => {
+ const project = mkdtempSync(join(tmpdir(), "hf-rename-relink-"));
+ dirs.push(project);
+ mkdirSync(join(project, "assets"));
+ mkdirSync(join(project, "shared"));
+ writeFileSync(join(project, "shared", "logo.png"), "x");
+ symlinkSync("../shared/logo.png", join(project, "assets", "logo.png"), "file");
+ writeFileSync(join(project, "index.html"), '<img src="assets/logo.png">');
+ const adapter = {
+ resolveProject: async (id: string) => ({ id, dir: project }),
+ } as unknown as StudioApiAdapter;
+ const app = new Hono();
+ registerFileRoutes(app, adapter);
+
+ const response = await app.request("/projects/p/files/assets/logo.png", {
+ method: "PATCH",
+ body: JSON.stringify({ newPath: "logo.png" }),
+ });
+
+ expect(response.status).toBe(200);
+ expect(readFileSync(join(project, "index.html"), "utf8")).toBe('<img src="logo.png">');
+ });
+});
diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.ts
index 585bb38e23..3e78a854de 100644
--- a/packages/studio-server/src/routes/files.ts
+++ b/packages/studio-server/src/routes/files.ts
@@ -17,6 +17,7 @@ import {
fstatSync,
renameSync,
readdirSync,
+ realpathSync,
type Dirent,
} from "node:fs";
import { resolve, dirname, join } from "node:path";
@@ -665,26 +666,119 @@ function readableText(file: string): string | null {
}
}
+const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+const SEPARATOR = String.raw`\\{0,2}[\\/]`;
+const REFERENCE_START = String.raw`(?<![\w./\\+-])`;
+const FILE_END = String.raw`(?![\w-]|\.\w)`;
+
+function referencePattern(oldPath: string, isDirectory: boolean): RegExp {
+ const name = oldPath.split("/").map(escapeRegExp).join(SEPARATOR);
+ const end = isDirectory ? `(?=${SEPARATOR})` : FILE_END;
+ return new RegExp(
+ String.raw`${REFERENCE_START}(?<lead>(?:\.{1,2}${SEPARATOR}|${SEPARATOR}){0,4})${name}${end}`,
+ "g",
+ );
+}
+
+// A match inside the longer path of a file or folder that exists (`a.png&b.png`, `other assets/`) is that path's.
+// Existing paths are indexed by the text after the old path, then the text before it, so a match costs a few lookups.
+export function referenceRewriter(
+ oldPath: string,
+ newPath: string,
+ isDirectory: boolean,
+ existing: readonly string[] = [],
+): (text: string) => string {
+ const pattern = referencePattern(oldPath, isDirectory);
+ const around = new Map<string, Map<number, Set<string>>>();
+ const afterLengths = new Set<number>();
+ let window = 0;
+ for (const path of existing) {
+ if (path.length <= oldPath.length) continue;
+ for (const start of occurrences(path, oldPath)) {
+ const [before, after] = [path.slice(0, start), path.slice(start + oldPath.length)];
+ const befores = around.get(after) ?? around.set(after, new Map()).get(after)!;
+ (befores.get(before.length) ?? befores.set(before.length, new Set()).get(before.length)!).add(
+ before,
+ );
+ afterLengths.add(after.length);
+ window = Math.max(window, path.length * 3);
+ }
+ }
+ const normalized = (text: string) => text.replace(/\\{0,2}[\\/]/g, "/");
+ return (text) =>
+ text.replace(pattern, (...args) => {
+ const [match, offset] = [args[0] as string, args.at(-3) as number];
+ const { lead } = args.at(-1) as { lead: string };
+ const at = offset + lead.length;
+ const head = normalized(text.slice(Math.max(0, at - window), at));
+ const tail = normalized(text.slice(offset + match.length, offset + match.length + window));
+ const inLonger = [...afterLengths].some((after) => {
+ const befores = tail.length >= after && around.get(tail.slice(0, after));
+ return (
+ befores &&
+ [...befores].some(
+ ([length, set]) => head.length >= length && set.has(head.slice(head.length - length)),
+ )
+ );
+ });
+ return inLonger ? match : `${lead}${newPath}`;
+ });
+}
+
+function occurrences(text: string, part: string): number[] {
+ const at: number[] = [];
+ for (let i = text.indexOf(part); i >= 0; i = text.indexOf(part, i + 1)) at.push(i);
+ return at;
+}
+
+function projectPaths(
+ root: string,
+ dir = root,
+ prefix = "",
+ ancestors: ReadonlySet<string> = new Set(),
+): string[] {
+ return readableEntries(dir).flatMap((entry) => {
+ const [path, full] = [`${prefix}${entry.name}`, join(dir, entry.name)];
+ const real = entry.name === "node_modules" ? null : directoryReal(entry, full);
+ if (real === null || ancestors.has(real) || !isSafePath(root, full)) return [path];
+ return [path, ...projectPaths(root, full, `${path}/`, new Set([...ancestors, real]))];
+ });
+}
+
+// A directory's real path, through a link, or null for anything else: aliases are paths too.
+function directoryReal(entry: Dirent, full: string): string | null {
+ try {
+ return entry.isDirectory() || (entry.isSymbolicLink() && statSync(full).isDirectory())
+ ? realpathSync(full)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* After a rename, update all references to the old path in project files.
- * Scans HTML, CSS, JS, and JSON files for the old filename/path and replaces.
+ * Scans HTML, CSS, JS, and JSON files for the old path and replaces it where it names that path.
*/
-function updateReferences(projectDir: string, oldPath: string, newPath: string): number {
+function updateReferences(
+ projectDir: string,
+ oldPath: string,
+ newPath: string,
+ isDirectory: boolean,
+): number {
const textFiles = walkFiles(projectDir, (name) =>
/\.(html|css|js|jsx|ts|tsx|json|mjs|cjs|md|mdx)$/i.test(name),
);
+ const rewrite = referenceRewriter(oldPath, newPath, isDirectory, projectPaths(projectDir));
let updatedCount = 0;
for (const file of textFiles) {
if (!isSafePath(projectDir, file)) continue;
const content = readableText(file);
if (content === null) continue;
- // Only replace full relative paths — never bare filenames, which can
- // corrupt unrelated content (e.g. "logo.png" inside "my-logo.png").
- if (!content.includes(oldPath)) continue;
-
- const updated = content.split(oldPath).join(newPath);
+ const updated = rewrite(content);
if (updated !== content) {
replaceFileAtomically(file, updated, statSync(file).mode);
updatedCount++;
@@ -3230,11 +3324,12 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {
return c.json({ error: "already exists" }, 409);
}
+ const isDirectory = statSync(res.absPath, { throwIfNoEntry: false })?.isDirectory() ?? false;
ensureDir(res.project.dir, newAbs);
renameSync(res.absPath, newAbs);
// Update references to the old path across all project files
- const updatedFiles = updateReferences(res.project.dir, res.filePath, body.newPath);
+ const updatedFiles = updateReferences(res.project.dir, res.filePath, body.newPath, isDirectory);
return c.json({ ok: true, path: body.newPath, updatedReferences: updatedFiles });
});