Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(setup): preserve JSONC trivia when removing registrations

morluto4fd28fc9e0c4
diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts
index c6c99e1e9..bd4169019 100644
--- a/src/application/ClientConfigurationDocument.ts
+++ b/src/application/ClientConfigurationDocument.ts
@@ -14,12 +14,14 @@ import {
} from "./HermesConfigurationYaml.js";
import {
applyEdits,
+ createScanner,
findNodeAtLocation,
modify,
parse as parseJsonc,
parseTree,
printParseErrorCode,
type ParseError,
+ type SyntaxKind,
} from "jsonc-parser";
import { z } from "zod";
@@ -1247,44 +1249,27 @@ const tomlTextHolds = (
}
};
-/** Comments in the trivia between two properties. `undefined` when there are none. */
-const commentsBetweenProperties = (gap: string): string | undefined => {
- const pieces: string[] = [];
- let index = 0;
- while (index < gap.length) {
- const line = gap.indexOf("//", index);
- const block = gap.indexOf("/*", index);
- if (line < 0 && block < 0) break;
- const start = line < 0 ? block : block < 0 ? line : Math.min(line, block);
- const lineComment = start === line;
- const close = lineComment
- ? gap.indexOf("\n", start)
- : gap.indexOf("*/", start + 2);
- if (!lineComment && close < 0) return undefined;
- const end = lineComment ? (close < 0 ? gap.length : close) : close + 2;
- const comment = gap.slice(start, end);
- const lineBreak = gap.lastIndexOf("\n", start - 1);
- if (lineBreak < 0) pieces.push(` ${comment}`);
- else {
- const prefix = gap.slice(lineBreak + 1, start);
- let indentEnd = 0;
- while (prefix[indentEnd] === " " || prefix[indentEnd] === "\t")
- indentEnd += 1;
- const newline =
- lineBreak > 0 && gap[lineBreak - 1] === "\r" ? "\r\n" : "\n";
- pieces.push(`${newline}${prefix.slice(0, indentEnd)}${comment}`);
- }
- index = end;
- }
- return pieces.length === 0 ? undefined : pieces.join("");
+// jsonc-parser declares SyntaxKind as an ambient const enum, so keep its token
+// code local and type-checked as in the JSON scanner used by IDA diagnostics.
+const JSON_COMMA = 5 satisfies SyntaxKind;
+
+/** Find the next non-trivia JSONC token at or after `offset`. */
+const nextJsoncToken = (
+ text: string,
+ offset: number,
+): { readonly kind: SyntaxKind; readonly offset: number } => {
+ const scanner = createScanner(text, true);
+ scanner.setPosition(offset);
+ const kind = scanner.scan();
+ return { kind, offset: scanner.getTokenOffset() };
};
/**
- * Delete an object property without taking a comment from the gap before it.
- * jsonc-parser's removal span includes that gap, so a trailing comment on the
- * previous property would disappear. Returns `undefined` to keep the stock edit.
+ * Delete a property by its JSONC AST span and the separator needed to keep its
+ * parent object valid. All whitespace and comments outside those tokens stay
+ * byte-for-byte in place.
*/
-const deleteJsonPropertyPreservingComments = (
+const deleteJsonProperty = (
text: string,
path: readonly string[],
): string | undefined => {
@@ -1301,54 +1286,26 @@ const deleteJsonPropertyPreservingComments = (
)
return undefined;
const propertyIndex = parent.children.indexOf(property);
+ if (propertyIndex < 0) return undefined;
const previous = parent.children[propertyIndex - 1];
- if (propertyIndex <= 0 || previous === undefined) return undefined;
- const comments = commentsBetweenProperties(
- text.slice(previous.offset + previous.length, property.offset),
- );
- if (comments === undefined) return undefined;
- let removeEnd = property.offset + property.length;
- const hasNext = parent.children[propertyIndex + 1] !== undefined;
- if (hasNext) {
- let comma = removeEnd;
- while (comma < text.length) {
- const char = text[comma];
- if (char === " " || char === "\t" || char === "\r" || char === "\n") {
- comma += 1;
- continue;
- }
- if (text.startsWith("/*", comma)) {
- const close = text.indexOf("*/", comma + 2);
- if (close < 0) return undefined;
- comma = close + 2;
- continue;
- }
- if (text.startsWith("//", comma)) {
- while (
- comma < text.length &&
- text[comma] !== "\n" &&
- text[comma] !== "\r"
- )
- comma += 1;
- continue;
- }
- break;
- }
- if (text[comma] !== ",") return undefined;
- removeEnd = comma + 1;
+ const next = parent.children[propertyIndex + 1];
+ let commaOffset: number | undefined;
+ if (previous !== undefined) {
+ const comma = nextJsoncToken(text, previous.offset + previous.length);
+ if (comma.kind !== JSON_COMMA) return undefined;
+ commaOffset = comma.offset;
+ } else {
+ const token = nextJsoncToken(text, property.offset + property.length);
+ if (token.kind === JSON_COMMA) commaOffset = token.offset;
+ else if (next !== undefined) return undefined;
}
- // A line comment runs to the next break. Keep the following token outside it.
- const remainder = text.slice(removeEnd);
- let suffix = `${hasNext ? "," : ""}${comments}`;
- if (
- suffix.includes("//") &&
- !suffix.endsWith("\n") &&
- !suffix.endsWith("\r") &&
- !remainder.startsWith("\n") &&
- !remainder.startsWith("\r")
- )
- suffix += "\n";
- return `${text.slice(0, previous.offset + previous.length)}${suffix}${remainder}`;
+ const edits = [
+ { offset: property.offset, length: property.length, content: "" },
+ ...(commaOffset === undefined
+ ? []
+ : [{ offset: commaOffset, length: 1, content: "" }]),
+ ];
+ return applyEdits(text, edits);
};
/** Serialize a validated client document, retaining JSONC and TOML comments. */
@@ -1377,7 +1334,7 @@ export const serializeClientConfiguration = (
return editedPaths.reduce((text, path) => {
const value = valueAt(document, path);
if (value === undefined) {
- const preserved = deleteJsonPropertyPreservingComments(text, path);
+ const preserved = deleteJsonProperty(text, path);
if (preserved !== undefined) return preserved;
}
return applyEdits(
diff --git a/tests/boundary/filesystem/clientConfigurationBom.test.ts b/tests/boundary/filesystem/clientConfigurationBom.test.ts
index 0fe946d52..b742db420 100644
--- a/tests/boundary/filesystem/clientConfigurationBom.test.ts
+++ b/tests/boundary/filesystem/clientConfigurationBom.test.ts
@@ -125,7 +125,7 @@ it.each(['\uFEFF{"servers": {"rea": @}}', '\uFEFF{"setting":\uFEFFtrue}'])(
},
);
-it("restores original BOM-prefixed JSONC bytes after update and removal", async () => {
+it("preserves BOM-prefixed JSONC values and comments through update and removal", async () => {
const home = await createTestTempDirectory("rea-client-config-bom-cycle-");
const client = supportedClients(home, "linux", {}).find(
(candidate) => candidate.name === "cursor",
@@ -158,7 +158,17 @@ it("restores original BOM-prefixed JSONC bytes after update and removal", async
name: "cursor",
status: "removed",
});
- expect(await readFile(client.configPath, "utf8")).toBe(original);
+ const removed = await readFile(client.configPath, "utf8");
+ expect(removed.startsWith("\uFEFF")).toBe(true);
+ expect(removed).toContain("\r\n // Keep prefix \uFEFF comment.\r\n");
+ expect(removed).toContain("\r\n // Keep suffix comment.\r\n");
+ expect(removed).toContain("// Keep this unrelated registration.");
+ expect(parseClientConfiguration(removed, client.format).document).toEqual(
+ parseClientConfiguration(original, client.format).document,
+ );
+ expect(await readFile(`${client.configPath}.rea.backup`)).toEqual(
+ Buffer.from(original),
+ );
});
it.each(["", "\n \n", "\uFEFF"])(
diff --git a/tests/boundary/filesystem/clientConfigurationDialects.test.ts b/tests/boundary/filesystem/clientConfigurationDialects.test.ts
index e4955a6ac..fce0fdb96 100644
--- a/tests/boundary/filesystem/clientConfigurationDialects.test.ts
+++ b/tests/boundary/filesystem/clientConfigurationDialects.test.ts
@@ -2,7 +2,12 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join, relative, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { parse as parseJsonc, type ParseError } from "jsonc-parser";
+import {
+ findNodeAtLocation,
+ parse as parseJsonc,
+ parseTree,
+ type ParseError,
+} from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
@@ -239,6 +244,173 @@ describe("OpenCode JSONC registration edits", () => {
});
});
+it.each([
+ {
+ name: "a sole registration without a trailing comma",
+ hasBeforeSibling: false,
+ hasAfterSibling: false,
+ hasGapComment: false,
+ afterRegistration: "",
+ expectedComment: undefined,
+ },
+ {
+ name: "a sole registration with a trailing comma",
+ hasBeforeSibling: false,
+ hasAfterSibling: false,
+ hasGapComment: false,
+ afterRegistration: ",",
+ expectedComment: undefined,
+ },
+ {
+ name: "a sole registration with a block comment before its trailing comma",
+ hasBeforeSibling: false,
+ hasAfterSibling: false,
+ hasGapComment: false,
+ afterRegistration: " /* Keep this note. */,",
+ expectedComment: "/* Keep this note. */",
+ },
+ {
+ name: "a sole registration with a line comment before its trailing comma",
+ hasBeforeSibling: false,
+ hasAfterSibling: false,
+ hasGapComment: false,
+ afterRegistration: " // Keep this note.\n ,",
+ expectedComment: "// Keep this note.",
+ },
+ {
+ name: "a registration with a surviving sibling and block comment before its comma",
+ hasBeforeSibling: true,
+ hasAfterSibling: true,
+ hasGapComment: true,
+ afterRegistration:
+ ' /* Keep this note. */,\n "after": { "command": "after" }',
+ expectedComment: "/* Keep this note. */",
+ },
+ {
+ name: "a registration with a surviving sibling and line comment before its comma",
+ hasBeforeSibling: true,
+ hasAfterSibling: true,
+ hasGapComment: true,
+ afterRegistration:
+ ' // Keep this note.\n ,\n "after": { "command": "after" }',
+ expectedComment: "// Keep this note.",
+ },
+ {
+ name: "a first registration with a surviving sibling and block comment before its comma",
+ hasBeforeSibling: false,
+ hasAfterSibling: true,
+ hasGapComment: false,
+ afterRegistration:
+ ' /* Keep this note. */ ,\n "after": { "command": "after" }',
+ expectedComment: "/* Keep this note. */",
+ },
+] as const)(
+ "Cursor removes $name and preserves surrounding configuration",
+ async ({
+ hasBeforeSibling,
+ hasAfterSibling,
+ hasGapComment,
+ afterRegistration,
+ expectedComment,
+ }) => {
+ const home = await createTestTempDirectory("rea-cursor-jsonc-remove-");
+ const client = supportedClients(home).find(({ name }) => name === "cursor");
+ if (client === undefined) throw new Error("missing Cursor client");
+ await mkdir(client.markerPath ?? home, { recursive: true });
+
+ const original = `{
+ // Keep unrelated client preferences.
+ "theme": "dark",
+ "mcpServers": {
+${hasBeforeSibling ? ' "before": { "command": "before" },\n' : ""} }
+}\n`;
+ await writeFile(client.configPath, original);
+ expect(
+ await configureClientConfiguration(client, {}, command),
+ ).toMatchObject({
+ status: "configured",
+ backupPath: `${client.configPath}.rea.backup`,
+ });
+
+ const configured = await readFile(client.configPath, "utf8");
+ let edited = configured;
+ if (hasGapComment) {
+ const root = parseTree(edited, [], { allowTrailingComma: true });
+ const registration =
+ root === undefined
+ ? undefined
+ : findNodeAtLocation(root, [
+ "mcpServers",
+ PRODUCT_IDENTITY.mcpServerKey,
+ ]);
+ const property = registration?.parent;
+ if (property === undefined)
+ throw new Error("configured Cursor registration property is missing");
+ edited =
+ edited.slice(0, property.offset) +
+ "// Keep the comment before the registration.\n " +
+ edited.slice(property.offset);
+ }
+ const root = parseTree(edited, [], { allowTrailingComma: true });
+ const registration =
+ root === undefined
+ ? undefined
+ : findNodeAtLocation(root, [
+ "mcpServers",
+ PRODUCT_IDENTITY.mcpServerKey,
+ ]);
+ if (registration === undefined)
+ throw new Error("configured Cursor registration is missing");
+ const registrationEnd = registration.offset + registration.length;
+ edited =
+ edited.slice(0, registrationEnd) +
+ afterRegistration +
+ edited.slice(registrationEnd);
+ await writeFile(client.configPath, edited);
+
+ const backup = await readFile(`${client.configPath}.rea.backup`, "utf8");
+ const removed = await systemUninstallHost(home).removeClient(client);
+ expect(removed.status).toBe("removed");
+ const removedText = await readFile(client.configPath, "utf8");
+ const errors: ParseError[] = [];
+ const document = parseJsonc(removedText, errors, {
+ allowTrailingComma: true,
+ }) as Record<string, unknown>;
+ expect(errors).toEqual([]);
+ expect(document.theme).toBe("dark");
+ expect(removedText).toContain("// Keep unrelated client preferences.");
+ if (expectedComment !== undefined)
+ expect(removedText).toContain(expectedComment);
+ if (hasGapComment)
+ expect(removedText).toContain(
+ "// Keep the comment before the registration.",
+ );
+ expect(
+ (document.mcpServers as Record<string, unknown>).rea,
+ ).toBeUndefined();
+ if (hasBeforeSibling)
+ expect(document.mcpServers).toMatchObject({
+ before: { command: "before" },
+ });
+ if (hasAfterSibling)
+ expect(document.mcpServers).toMatchObject({
+ after: { command: "after" },
+ });
+ if (!hasBeforeSibling && !hasAfterSibling)
+ expect(document.mcpServers).toEqual({});
+ expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
+ backup,
+ );
+
+ const repeated = await systemUninstallHost(home).removeClient(client);
+ expect(repeated.status).toBe("skipped");
+ expect(await readFile(client.configPath, "utf8")).toBe(removedText);
+ expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
+ backup,
+ );
+ },
+);
+
const parseOpenCode = (text: string): Record<string, unknown> => {
const errors: ParseError[] = [];
const document = parseJsonc(text, errors, {