Skip to content

Commit cf14b27

Browse files
authored
refactor: consolidate safe json parsing (#99688)
1 parent 4682364 commit cf14b27

7 files changed

Lines changed: 34 additions & 41 deletions

File tree

‎packages/normalization-core/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
export * from "./boolean-coercion.js";
44
export * from "./error-coercion.js";
5+
export * from "./json-coercion.js";
56
export * from "./number-coercion.js";
67
export * from "./record-coerce.js";
78
export * from "./string-coerce.js";
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { describe, expect, it } from "vitest";
2+
import { safeParseJson } from "./json-coercion.js";
3+
4+
describe("json-coercion", () => {
5+
it.each<[string, unknown]>([
6+
['{"ok":true}', { ok: true }],
7+
["[1]", [1]],
8+
['"text"', "text"],
9+
["null", null],
10+
["{", undefined],
11+
])("parses %s", (value, expected) => expect(safeParseJson(value)).toEqual(expected));
12+
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
/** Parses JSON without throwing, returning undefined for invalid input. */
2+
export function safeParseJson(value: string): unknown {
3+
try {
4+
return JSON.parse(value) as unknown;
5+
} catch {
6+
return undefined;
7+
}
8+
}

‎src/acp/runtime/session-meta.ts‎

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
/** SQLite-backed ACP session metadata storage keyed through session-store entries. */
22
import type { DatabaseSync } from "node:sqlite";
3+
import { safeParseJson } from "@openclaw/normalization-core";
4+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
35
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
46
import type { Insertable, Selectable } from "kysely";
57
import { getRuntimeConfig } from "../../config/config.js";
@@ -29,7 +31,6 @@ import {
2931
type OpenClawStateDatabaseOptions,
3032
runOpenClawStateWriteTransaction,
3133
} from "../../state/openclaw-state-db.js";
32-
import { isRecord } from "../../utils.js";
3334

3435
/** ACP metadata joined with its legacy session-store row and config context. */
3536
export type AcpSessionStoreEntry = {
@@ -89,21 +90,11 @@ function getAcpSessionKysely(db: DatabaseSync) {
8990
return getNodeSqliteKysely<AcpSessionMetaDatabase>(db);
9091
}
9192

92-
function parseOptionalJsonRecord(raw: string | null): Record<string, unknown> | undefined {
93-
if (raw == null || raw === "") {
94-
return undefined;
95-
}
96-
try {
97-
const parsed = JSON.parse(raw) as unknown;
98-
return isRecord(parsed) ? parsed : undefined;
99-
} catch {
100-
return undefined;
101-
}
102-
}
103-
10493
function rowToAcpSessionMeta(row: AcpSessionRow): SessionAcpMeta {
105-
const identity = parseOptionalJsonRecord(row.identity_json) as SessionAcpIdentity | undefined;
106-
const runtimeOptions = parseOptionalJsonRecord(row.runtime_options_json) as
94+
const identity = asOptionalRecord(safeParseJson(row.identity_json ?? "")) as
95+
| SessionAcpIdentity
96+
| undefined;
97+
const runtimeOptions = asOptionalRecord(safeParseJson(row.runtime_options_json ?? "")) as
10798
| AcpSessionRuntimeOptions
10899
| undefined;
109100
return {

‎src/agents/embedded-agent-message-tool-source-reply.ts‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
/**
22
* Detects message-tool sends that delivered a visible reply to the current source.
33
*/
4+
import { safeParseJson } from "@openclaw/normalization-core";
5+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
46
import type { SourceReplyDeliveryMode } from "../auto-reply/get-reply-options.types.js";
57
import {
68
isMessageToolConversationCreateActionName,
@@ -70,14 +72,7 @@ function isBareSentDeliveryStatus(value: unknown): boolean {
7072
}
7173

7274
function parseJsonRecord(value: string): Record<string, unknown> | undefined {
73-
try {
74-
const parsed = JSON.parse(value);
75-
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
76-
? (parsed as Record<string, unknown>)
77-
: undefined;
78-
} catch {
79-
return undefined;
80-
}
75+
return asOptionalRecord(safeParseJson(value));
8176
}
8277

8378
function recordHasDeliveredMessageId(record: Record<string, unknown>): boolean {

‎src/agents/subagent-yield-output.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*
44
* Accepts provider-specific tool-call and tool-result shapes used by transcript repair and announce capture.
55
*/
6+
import { safeParseJson } from "@openclaw/normalization-core";
67
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
78
import { readTrimmedStringAlias } from "../utils/string-readers.js";
89

@@ -50,11 +51,7 @@ function parseJsonObject(text: string): Record<string, unknown> | undefined {
5051
if (!trimmed.startsWith("{")) {
5152
return undefined;
5253
}
53-
try {
54-
return asOptionalRecord(JSON.parse(trimmed));
55-
} catch {
56-
return undefined;
57-
}
54+
return asOptionalRecord(safeParseJson(trimmed));
5855
}
5956

6057
function readStructuredToolPayload(content: unknown): Record<string, unknown> | undefined {

‎src/chat/canvas-render.ts‎

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Renders chat canvas payloads into text and metadata for transcript output.
2+
import { safeParseJson } from "@openclaw/normalization-core";
23
import { asFiniteNumber } from "@openclaw/normalization-core/number-coercion";
34
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
45
import { parseFenceSpans } from "../../packages/markdown-core/src/fences.js";
@@ -19,18 +20,6 @@ type CanvasPreview = {
1920
style?: string;
2021
};
2122

22-
function tryParseJsonRecord(value: string | undefined): Record<string, unknown> | undefined {
23-
if (typeof value !== "string") {
24-
return undefined;
25-
}
26-
try {
27-
const parsed = JSON.parse(value);
28-
return asOptionalRecord(parsed);
29-
} catch {
30-
return undefined;
31-
}
32-
}
33-
3423
function getRecordStringField(
3524
record: Record<string, unknown> | undefined,
3625
key: string,
@@ -184,7 +173,7 @@ export function extractCanvasFromText(
184173
outputText: string | undefined,
185174
_toolName?: string,
186175
): CanvasPreview | undefined {
187-
const parsed = tryParseJsonRecord(outputText);
176+
const parsed = outputText ? asOptionalRecord(safeParseJson(outputText)) : undefined;
188177
return coerceCanvasPreview(parsed);
189178
}
190179

0 commit comments

Comments
 (0)