Skip to content

Commit df6f777

Browse files
committed
Serialize custom command results
1 parent dcd1ccd commit df6f777

7 files changed

Lines changed: 37 additions & 13 deletions

File tree

go/modcdp/translate/translate.go

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ func wrapCustomCommand(method string, params map[string]any, sessionID string) m
138138
m, _ := json.Marshal(method)
139139
p, _ := json.Marshal(params)
140140
sid, _ := json.Marshal(sessionID)
141-
return callFunctionParams(fmt.Sprintf(`async function() { return await globalThis.ModCDP.handleCommand(%s, %s, %s); }`, string(m), string(p), string(sid)))
141+
return callFunctionParams(fmt.Sprintf(`async function() { return JSON.stringify(await globalThis.ModCDP.handleCommand(%s, %s, %s)); }`, string(m), string(p), string(sid)))
142142
}
143143

144144
func wrapServiceWorkerCommand(method string, params map[string]any, sessionID string, targetSessionID string) []rawStep {
@@ -179,7 +179,11 @@ func wrapServiceWorkerCommand(method string, params map[string]any, sessionID st
179179
}
180180
runtimeParams = wrapCustomCommand(method, params, cdpSessionID)
181181
}
182-
return []rawStep{{Method: "Runtime.callFunctionOn", Params: runtimeParams, Unwrap: "runtime"}}
182+
unwrap := "runtime_json"
183+
if strings.HasPrefix(method, "Mod.") {
184+
unwrap = "runtime"
185+
}
186+
return []rawStep{{Method: "Runtime.callFunctionOn", Params: runtimeParams, Unwrap: unwrap}}
183187
}
184188

185189
func WrapCommandIfNeeded(method string, params map[string]any, routes map[string]string, sessionID string, targetSessionID ...string) (rawCommand, error) {
@@ -198,7 +202,7 @@ func WrapCommandIfNeeded(method string, params map[string]any, routes map[string
198202
}
199203

200204
func UnwrapResponseIfNeeded(result map[string]any, unwrap string) (any, error) {
201-
if unwrap != "runtime" {
205+
if unwrap != "runtime" && unwrap != "runtime_json" {
202206
return result, nil
203207
}
204208
if ex, ok := result["exceptionDetails"].(map[string]any); ok {
@@ -219,7 +223,17 @@ func UnwrapResponseIfNeeded(result map[string]any, unwrap string) (any, error) {
219223
return nil, fmt.Errorf("%s", msg)
220224
}
221225
inner, _ := result["result"].(map[string]any)
222-
return inner["value"], nil
226+
value := inner["value"]
227+
if unwrap == "runtime_json" {
228+
if raw, ok := value.(string); ok {
229+
var decoded any
230+
if err := json.Unmarshal([]byte(raw), &decoded); err != nil {
231+
return nil, err
232+
}
233+
return decoded, nil
234+
}
235+
}
236+
return value, nil
223237
}
224238

225239
func UnwrapEventIfNeeded(method string, params map[string]any, sessionID string, ourSessionID string) (string, any, bool) {

js/src/translate/translate.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ export function wrapCustomCommand(
175175
cdpSessionId: string | null = null,
176176
): cdp.types.ts.Runtime.EvaluateParams {
177177
return {
178-
functionDeclaration: `async function() { return await globalThis.ModCDP.handleCommand(${JSON.stringify(method)}, ${JSON.stringify(params)}, ${JSON.stringify(cdpSessionId)}); }`,
178+
functionDeclaration: `async function() { return JSON.stringify(await globalThis.ModCDP.handleCommand(${JSON.stringify(method)}, ${JSON.stringify(params)}, ${JSON.stringify(cdpSessionId)})); }`,
179179
awaitPromise: true,
180180
returnByValue: true,
181181
};
@@ -221,7 +221,7 @@ function wrapServiceWorkerCommand(method: string, params: ProtocolParams = {}, c
221221
{
222222
method: "Runtime.callFunctionOn",
223223
params: runtimeParams,
224-
unwrap: "runtime" as const,
224+
unwrap: method.startsWith("Mod.") ? ("runtime" as const) : ("runtime_json" as const),
225225
},
226226
];
227227
}
@@ -260,10 +260,16 @@ function unwrapRuntimeResponse(result: cdp.types.ts.Runtime.EvaluateResult) {
260260
return result?.result?.value;
261261
}
262262

263+
function unwrapRuntimeJsonResponse(result: cdp.types.ts.Runtime.EvaluateResult) {
264+
const value = unwrapRuntimeResponse(result);
265+
return typeof value === "string" ? JSON.parse(value) : value;
266+
}
267+
263268
export function unwrapResponseIfNeeded(
264269
result: ProtocolResult | cdp.types.ts.Runtime.EvaluateResult,
265270
unwrap: string | null = null,
266271
) {
272+
if (unwrap === "runtime_json") return unwrapRuntimeJsonResponse(result as cdp.types.ts.Runtime.EvaluateResult);
267273
return unwrap === "runtime" ? unwrapRuntimeResponse(result as cdp.types.ts.Runtime.EvaluateResult) : (result ?? {});
268274
}
269275

js/src/types/modcdp.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ export const TranslatedStepSchema = z
387387
method: z.string(),
388388
params: ProtocolParamsSchema.optional(),
389389
sessionId: z.string().nullable().optional(),
390-
unwrap: z.literal("runtime").optional(),
390+
unwrap: z.enum(["runtime", "runtime_json"]).optional(),
391391
})
392392
.passthrough();
393393
export type TranslatedStep = z.infer<typeof TranslatedStepSchema>;

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "modcdp",
3-
"version": "0.0.11",
3+
"version": "0.0.12",
44
"repository": {
55
"type": "git",
66
"url": "git+https://github.com/pirate/modcdp.git"

python/modcdp/translate/translate.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,8 @@ def _wrap_modcdp_add_middleware(params: ProtocolParams) -> RuntimeCallFunctionOn
153153

154154
def _wrap_custom_command(method: str, params: ProtocolParams, session_id: str) -> RuntimeCallFunctionOnParams:
155155
return _call_function_params(
156-
"async function() { return await globalThis.ModCDP.handleCommand("
157-
f"{json.dumps(method)}, {json.dumps(params)}, {json.dumps(session_id)}); }}"
156+
"async function() { return JSON.stringify(await globalThis.ModCDP.handleCommand("
157+
f"{json.dumps(method)}, {json.dumps(params)}, {json.dumps(session_id)})); }}"
158158
)
159159

160160

@@ -183,7 +183,8 @@ def _wrap_service_worker_command(
183183
runtime_params = _wrap_modcdp_add_middleware(params)
184184
else:
185185
runtime_params = _wrap_custom_command(method, params, target_session_id or _optional_string(params, "cdpSessionId") or session_id)
186-
return [{"method": "Runtime.callFunctionOn", "params": runtime_params, "unwrap": "runtime"}]
186+
unwrap = "runtime" if method.startswith("Mod.") else "runtime_json"
187+
return [{"method": "Runtime.callFunctionOn", "params": runtime_params, "unwrap": unwrap}]
187188

188189

189190
def wrap_command_if_needed(
@@ -231,6 +232,9 @@ def _unwrap_evaluate_response(result: ProtocolResult) -> JsonValue:
231232

232233

233234
def unwrap_response_if_needed(result: ProtocolResult, unwrap: str | None = None) -> JsonValue:
235+
if unwrap == "runtime_json":
236+
value = _unwrap_evaluate_response(result)
237+
return cast(JsonValue, json.loads(value)) if isinstance(value, str) else value
234238
return _unwrap_evaluate_response(result) if unwrap == "runtime" else (result or {})
235239

236240

python/modcdp/types/modcdp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ class _TranslatedStepRequired(TypedDict):
108108
class TranslatedStep(_TranslatedStepRequired, total=False):
109109
params: MessageParams
110110
sessionId: str | None
111-
unwrap: Literal["runtime"]
111+
unwrap: Literal["runtime", "runtime_json"]
112112

113113

114114
class TranslatedCommand(TypedDict):

python/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "modcdp"
7-
version = "0.0.11"
7+
version = "0.0.12"
88
description = "Python client for ModCDP."
99
readme = "README.md"
1010
requires-python = ">=3.11"

0 commit comments

Comments
 (0)