-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathcommon.tsx
More file actions
83 lines (73 loc) · 2.16 KB
/
Copy pathcommon.tsx
File metadata and controls
83 lines (73 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
export type JsonRpcResult = {
jsonrpc: string;
id: number;
result?: {
content: Array<{
type: string;
text: string;
}>;
};
error?: {
code: number;
message: string;
}
}
export const UNKNOWN_JSONRPC_RESULT: JsonRpcResult = {
jsonrpc: "2.0",
id: -1,
error: {
code: -1,
message: "Unknown JSONRPC result",
},
}
const isValidJsonRpcResult = (obj: any): obj is JsonRpcResult => {
// Check if obj is an object and not null
if (typeof obj !== 'object' || obj === null) {
return false;
}
// Check required properties
if (typeof obj.jsonrpc !== 'string' || typeof obj.id !== 'number') {
return false;
}
// Check that either result or error is present (but not both required)
const hasResult = obj.result !== undefined;
const hasError = obj.error !== undefined;
// Validate result structure if present
if (hasResult) {
if (typeof obj.result !== 'object' || obj.result === null) {
return false;
}
if (obj.result.content !== undefined) {
if (!Array.isArray(obj.result.content)) {
return false;
}
// Validate each content item
for (const item of obj.result.content) {
if (typeof item !== 'object' || item === null ||
typeof item.type !== 'string' || typeof item.text !== 'string') {
return false;
}
}
}
}
// Validate error structure if present
if (hasError) {
if (typeof obj.error !== 'object' || obj.error === null ||
typeof obj.error.code !== 'number' || typeof obj.error.message !== 'string') {
return false;
}
}
return true;
};
export const parseJsonRpcResult = (message: string): JsonRpcResult | undefined => {
try {
const json = JSON.parse(message);
// Validate the structure before casting
if (isValidJsonRpcResult(json)) {
return json;
}
return undefined;
} catch (error) {
return undefined;
}
}