refactor(runtime): centralize safe JSON parsing and preserve error causes (#629)

* refactor(domain): consolidate canonical ordering and digest helpers (#624)

* refactor(domain): consolidate canonical ordering and digest helpers

Single owner for code-point ordering (domain/canonicalOrdering.ts)
and canonical JSON digests (domain/comparisonSemantics.ts). Delete
all local compareCodePoints/compareText/digestCanonical duplicates
and migrate every importer. No re-export shims.

* fix(ci): allow slower real browser startup

* chore(config): remove dead eslint, dedupe scripts, cacheable turbo tasks

Delete eslint.config.js (oxlint is the linter), drop lint:dead alias,
pin smol-toml, fold jscpd/scan:todos into check:pr, make test:run
cacheable, align oxlint ignores.

* fix(config): hash all test inputs for cached runs

* docs: fix architecture diagram and pretty-print tool catalog

Drop dangling REPLAY edges, add dotnet/reference/error/evaluation
nodes. Emit 2-space JSON from the catalog generator and regenerate.

* test: extract shared fixtures, drop knip carve-outs

Dedupe android/apple session tests, bundler adapter headers, and
reconstruction helpers into tests/support fixtures. Delete unused
type aliases and the knip ignoreIssues block. Lower jscpd threshold
2.7 to 2.5.

* refactor(app): split Setup and ProcessOwnership modules

Extract SetupTypes/SetupHost from Setup.ts and move observation
helpers into ProcessOwnershipObservation/ProcessTree. Migrate all
importers including CLI commands. No re-export shims.

* refactor(runtime): centralize safe JSON parsing and preserve error causes

Add domain/safeJson.safeParseJson and migrate all raw JSON.parse
call sites. Name catch causes and preserve failure reasons instead
of swallowing; annotate genuine best-effort cleanup.

* fix(runtime): retain JSON parse error causes
This commit is contained in:
morluto
2026-10-06 05:00:54 +08:00
committed by GitHub
parent 3c84080aab
commit e7f54b3310
31 changed files with 228 additions and 105 deletions
+1
View File
@@ -264,6 +264,7 @@ const report = async (
completed: number,
message: string,
): Promise<void> => {
// best-effort cleanup: progress reporting must not fail session cleanup.
await progress
?.report({
phase: "hopper_cleanup",
+7 -1
View File
@@ -175,7 +175,11 @@ export class HopperClient {
release();
if (!result.ok) reset();
},
() => {
(cause: unknown) => {
this.#logger.debug(
{ error: cause instanceof Error ? cause.message : String(cause) },
"Hopper startup promise rejected during bookkeeping",
);
release();
reset();
},
@@ -323,6 +327,8 @@ export class HopperClient {
options: HopperClientCloseOptions,
): Promise<Result<null, AnalysisError>> {
try {
// best-effort cleanup: a rejected startup must not mask close/cleanup;
// #cleanup reports the authoritative close result.
await starting?.catch(() => undefined);
return await this.#cleanup(options);
} finally {
+16 -14
View File
@@ -8,6 +8,7 @@ import {
} from "node:net";
import { join, resolve } from "node:path";
import { HopperStartError } from "../domain/errors.js";
import { safeParseJson } from "../domain/safeJson.js";
interface HopperTargetLeaseOwner {
readonly runId: string;
@@ -144,22 +145,23 @@ const readOwner = (
response += chunk.toString("utf8");
const newline = response.indexOf("\n");
if (newline < 0) return;
try {
const value: unknown = JSON.parse(response.slice(0, newline));
if (
typeof value === "object" &&
value !== null &&
typeof Reflect.get(value, "runId") === "string" &&
typeof Reflect.get(value, "processId") === "number"
)
finish({
runId: Reflect.get(value, "runId") as string,
processId: Reflect.get(value, "processId") as number,
});
else finish(undefined);
} catch {
const parsed = safeParseJson(response.slice(0, newline));
if (!parsed.ok) {
finish(undefined);
return;
}
const value: unknown = parsed.value;
if (
typeof value === "object" &&
value !== null &&
typeof Reflect.get(value, "runId") === "string" &&
typeof Reflect.get(value, "processId") === "number"
)
finish({
runId: Reflect.get(value, "runId") as string,
processId: Reflect.get(value, "processId") as number,
});
else finish(undefined);
});
socket.on("error", () => finish(undefined));
socket.on("end", () => finish(undefined));
+8 -9
View File
@@ -4,6 +4,7 @@ import {
isHopperStartupFailureCode,
type HopperStartupDiagnostic,
} from "../domain/hopperStartupFailure.js";
import { safeParseJson } from "../domain/safeJson.js";
export const LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX = "REA_X11_DIAGNOSTIC=";
@@ -70,13 +71,11 @@ export const parseLinuxPrivateDisplayDiagnostic = (
if (records.length !== 1) return { ok: false, reason: "diagnostic_multiple" };
const record = records[0];
if (record === undefined) return { ok: false, reason: "diagnostic_missing" };
try {
const parsed = diagnosticSchema.safeParse(
JSON.parse(record.slice(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX.length)),
);
if (!parsed.success) return { ok: false, reason: "diagnostic_malformed" };
return { ok: true, value: parsed.data };
} catch {
return { ok: false, reason: "diagnostic_malformed" };
}
const decoded = safeParseJson(
record.slice(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX.length),
);
if (!decoded.ok) return { ok: false, reason: "diagnostic_malformed" };
const parsed = diagnosticSchema.safeParse(decoded.value);
if (!parsed.success) return { ok: false, reason: "diagnostic_malformed" };
return { ok: true, value: parsed.data };
};
+7 -6
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { HopperProtocolError, HopperRemoteError } from "../domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { safeParseJson } from "../domain/safeJson.js";
const remoteErrorSchema = z
.object({
@@ -82,14 +83,14 @@ export type HopperBridgeMessage = z.infer<typeof messageSchema>;
export const parseBridgeMessageLine = (
line: string,
): Result<HopperBridgeMessage, HopperProtocolError> => {
let decoded: unknown;
try {
decoded = JSON.parse(line);
} catch (cause: unknown) {
const decodedResult = safeParseJson(line);
if (!decodedResult.ok)
return err(
new HopperProtocolError("Hopper returned malformed JSON", { cause }),
new HopperProtocolError("Hopper returned malformed JSON", {
cause: decodedResult.cause,
}),
);
}
const decoded: unknown = decodedResult.value;
const parsed = messageSchema.safeParse(decoded);
return parsed.success