Skip to content

Commit

Permalink
refactor: move defaults to Realm (#2066)
Browse files Browse the repository at this point in the history
Moves the defaults to the `Realm` class rather then the
`ScriptProcessor`, so we can use them from anywhere.
Also some small changes that I will mark as comments.
  • Loading branch information
Lightning00Blade authored Mar 22, 2024
1 parent c44e1e0 commit 405b995
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 104 deletions.
27 changes: 7 additions & 20 deletions src/bidiMapper/domains/context/BrowsingContextImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -789,15 +789,7 @@ export class BrowsingContextImpl {
}
}
const realm = await this.getOrCreateSandbox(undefined);
const originResult = await realm.callFunction(
script,
{type: 'undefined'},
[],
false,
Script.ResultOwnership.None,
{},
false
);
const originResult = await realm.callFunction(script, false);
assert(originResult.type === 'success');
const origin = deserializeDOMRect(originResult.result);
assert(origin);
Expand Down Expand Up @@ -929,11 +921,9 @@ export class BrowsingContextImpl {
String((element: unknown) => {
return element instanceof Element;
}),
{type: 'undefined'},
[clip.element],
false,
Script.ResultOwnership.None,
{}
{type: 'undefined'},
[clip.element]
);
if (result.type === 'exception') {
throw new NoSuchElementException(
Expand All @@ -957,11 +947,9 @@ export class BrowsingContextImpl {
width: rect.width,
};
}),
{type: 'undefined'},
[clip.element],
false,
Script.ResultOwnership.None,
{}
{type: 'undefined'},
[clip.element]
);
assert(result.type === 'success');
const rect = deserializeDOMRect(result.result);
Expand Down Expand Up @@ -1235,12 +1223,11 @@ export class BrowsingContextImpl {

const locatorResult = await realm.callFunction(
locatorDelegate.functionDeclaration,
false,
{type: 'undefined'},
locatorDelegate.argumentsLocalValues,
false,
Script.ResultOwnership.None,
serializationOptions,
false
serializationOptions
);

if (locatorResult.type !== 'success') {
Expand Down
4 changes: 3 additions & 1 deletion src/bidiMapper/domains/context/BrowsingContextStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ export class BrowsingContextStorage {
return result;
}

verifyContextsList(contexts: BrowsingContext.BrowsingContext[] | undefined) {
verifyTopLevelContextsList(
contexts: BrowsingContext.BrowsingContext[] | undefined
) {
const foundContexts = new Set<BrowsingContextImpl>();
if (!contexts) {
return foundContexts;
Expand Down
17 changes: 4 additions & 13 deletions src/bidiMapper/domains/input/ActionDispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
InvalidArgumentException,
MoveTargetOutOfBoundsException,
NoSuchElementException,
Script,
type Script,
} from '../../../protocol/protocol.js';
import {assert} from '../../../utils/assert.js';
import type {BrowsingContextImpl} from '../context/BrowsingContextImpl.js';
Expand Down Expand Up @@ -56,11 +56,9 @@ async function getElementCenter(
const sandbox = await context.getOrCreateSandbox(undefined);
const result = await sandbox.callFunction(
CALCULATE_IN_VIEW_CENTER_PT_DECL,
{type: 'undefined'},
[element],
false,
Script.ResultOwnership.None,
{}
{type: 'undefined'},
[element]
);
if (result.type === 'exception') {
throw new NoSuchElementException(
Expand All @@ -82,14 +80,7 @@ export class ActionDispatcher {
static isMacOS = async (context: BrowsingContextImpl) => {
const result = await (
await context.getOrCreateSandbox(undefined)
).callFunction(
IS_MAC_DECL,
{type: 'undefined'},
[],
false,
Script.ResultOwnership.None,
{}
);
).callFunction(IS_MAC_DECL, false);
assert(result.type !== 'exception');
assert(result.result.type === 'boolean');
return result.result.value;
Expand Down
25 changes: 6 additions & 19 deletions src/bidiMapper/domains/input/InputProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,9 @@ export class InputProcessor {
}
return;
}),
params.element,
[{type: 'number', value: params.files.length}],
false,
Script.ResultOwnership.None,
{},
false
params.element,
[{type: 'number', value: params.files.length}]
);
} catch {
throw new NoSuchElementException(
Expand Down Expand Up @@ -171,12 +168,8 @@ export class InputProcessor {
);
this.dispatchEvent(new Event('change', {bubbles: true}));
}),
params.element,
[],
false,
Script.ResultOwnership.None,
{},
false
params.element
);
return {};
}
Expand All @@ -189,12 +182,10 @@ export class InputProcessor {
String(function getFiles(this: HTMLInputElement, index: number) {
return this.files?.item(index);
}),
false,
params.element,
[{type: 'number', value: 0}],
false,
Script.ResultOwnership.Root,
{},
false
Script.ResultOwnership.Root
);
assert(result.type === 'success');
if (result.result.type !== 'object') {
Expand Down Expand Up @@ -238,12 +229,8 @@ export class InputProcessor {
})
);
}),
params.element,
[],
false,
Script.ResultOwnership.None,
{},
false
params.element
);
}
return {};
Expand Down
19 changes: 5 additions & 14 deletions src/bidiMapper/domains/network/NetworkProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
NoSuchRequestException,
InvalidArgumentException,
} from '../../../protocol/protocol.js';
import {assert} from '../../../utils/assert.js';
import type {BrowsingContextStorage} from '../context/BrowsingContextStorage.js';

import type {NetworkRequest} from './NetworkRequest.js';
Expand All @@ -48,7 +47,7 @@ export class NetworkProcessor {
async addIntercept(
params: Network.AddInterceptParameters
): Promise<Network.AddInterceptResult> {
this.#browsingContextStorage.verifyContextsList(params.contexts);
this.#browsingContextStorage.verifyTopLevelContextsList(params.contexts);

const urlPatterns: Network.UrlPattern[] = params.urlPatterns ?? [];
const parsedUrlPatterns: Network.UrlPattern[] =
Expand All @@ -75,7 +74,7 @@ export class NetworkProcessor {
async continueRequest(
params: Network.ContinueRequestParameters
): Promise<EmptyResult> {
const networkId = params.request;
const {url, method, headers, request: networkId} = params;

if (params.url !== undefined) {
NetworkProcessor.parseUrlString(params.url);
Expand All @@ -85,14 +84,12 @@ export class NetworkProcessor {
Network.InterceptPhase.BeforeRequestSent,
]);

const {url, method, headers} = params;
// TODO: Set / expand.
// ; Step 9. cookies
// ; Step 10. body

const requestHeaders: Protocol.Fetch.HeaderEntry[] | undefined =
cdpFetchHeadersFromBidiNetworkHeaders(headers);

// TODO: Set / expand.
// ; Step 9. cookies
// ; Step 10. body
await request.continueRequest(url, method, requestHeaders);

return {};
Expand Down Expand Up @@ -160,12 +157,6 @@ export class NetworkProcessor {

username = credentials.username;
password = credentials.password;
// TODO: This should be invalid argument exception.
// Spec may need to be updated.
assert(
credentials.type === 'password',
`Credentials type ${credentials.type} must be 'password'`
);
}

const response = cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction(
Expand Down
14 changes: 8 additions & 6 deletions src/bidiMapper/domains/script/Realm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,8 +189,8 @@ export abstract class Realm {
async evaluate(
expression: string,
awaitPromise: boolean,
resultOwnership: Script.ResultOwnership,
serializationOptions: Script.SerializationOptions,
resultOwnership: Script.ResultOwnership = Script.ResultOwnership.None,
serializationOptions: Script.SerializationOptions = {},
userActivation = false
): Promise<Script.EvaluateResult> {
const cdpEvaluateResult = await this.cdpClient.sendCommand(
Expand Down Expand Up @@ -362,11 +362,13 @@ export abstract class Realm {

async callFunction(
functionDeclaration: string,
thisLocalValue: Script.LocalValue,
argumentsLocalValues: Script.LocalValue[],
awaitPromise: boolean,
resultOwnership: Script.ResultOwnership,
serializationOptions: Script.SerializationOptions,
thisLocalValue: Script.LocalValue = {
type: 'undefined',
},
argumentsLocalValues: Script.LocalValue[] = [],
resultOwnership: Script.ResultOwnership = Script.ResultOwnership.None,
serializationOptions: Script.SerializationOptions = {},
userActivation = false
): Promise<Script.EvaluateResult> {
const callFunctionAndSerializeScript = `(...args) => {
Expand Down
36 changes: 14 additions & 22 deletions src/bidiMapper/domains/script/ScriptProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import {
type EmptyResult,
Script,
type Script,
NoSuchScriptException,
} from '../../../protocol/protocol';
import type {LoggerFn} from '../../../utils/log';
Expand Down Expand Up @@ -50,7 +50,7 @@ export class ScriptProcessor {
async addPreloadScript(
params: Script.AddPreloadScriptParameters
): Promise<Script.AddPreloadScriptResult> {
const contexts = this.#browsingContextStorage.verifyContextsList(
const contexts = this.#browsingContextStorage.verifyTopLevelContextsList(
params.contexts
);

Expand Down Expand Up @@ -78,23 +78,17 @@ export class ScriptProcessor {
async removePreloadScript(
params: Script.RemovePreloadScriptParameters
): Promise<EmptyResult> {
const bidiId = params.script;
const {script: id} = params;

const scripts = this.#preloadScriptStorage.find({
id: bidiId,
});
const scripts = this.#preloadScriptStorage.find({id});

if (scripts.length === 0) {
throw new NoSuchScriptException(
`No preload script with BiDi ID '${bidiId}'`
);
throw new NoSuchScriptException(`No preload script with id '${id}'`);
}

await Promise.all(scripts.map((script) => script.remove()));

this.#preloadScriptStorage.remove({
id: bidiId,
});
this.#preloadScriptStorage.remove({id});

return {};
}
Expand All @@ -105,14 +99,12 @@ export class ScriptProcessor {
const realm = await this.#getRealm(params.target);
return await realm.callFunction(
params.functionDeclaration,
params.this ?? {
type: 'undefined',
}, // `this` is `undefined` by default.
params.arguments ?? [], // `arguments` is `[]` by default.
params.awaitPromise,
params.resultOwnership ?? Script.ResultOwnership.None,
params.serializationOptions ?? {},
params.userActivation ?? false
params.this,
params.arguments,
params.resultOwnership,
params.serializationOptions,
params.userActivation
);
}

Expand All @@ -123,9 +115,9 @@ export class ScriptProcessor {
return await realm.evaluate(
params.expression,
params.awaitPromise,
params.resultOwnership ?? Script.ResultOwnership.None,
params.serializationOptions ?? {},
params.userActivation ?? false
params.resultOwnership,
params.serializationOptions,
params.userActivation
);
}

Expand Down
4 changes: 2 additions & 2 deletions src/bidiMapper/domains/script/WindowRealm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,9 @@ export class WindowRealm extends Realm {

override async callFunction(
functionDeclaration: string,
awaitPromise: boolean,
thisLocalValue: Script.LocalValue,
argumentsLocalValues: Script.LocalValue[],
awaitPromise: boolean,
resultOwnership: Script.ResultOwnership,
serializationOptions: Script.SerializationOptions,
userActivation?: boolean
Expand All @@ -228,9 +228,9 @@ export class WindowRealm extends Realm {

return await super.callFunction(
functionDeclaration,
awaitPromise,
thisLocalValue,
argumentsLocalValues,
awaitPromise,
resultOwnership,
serializationOptions,
userActivation
Expand Down
13 changes: 6 additions & 7 deletions tests/script/test_remove_preload_script.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def test_preloadScript_remove_nonExistingScript_fails(websocket):
with pytest.raises(Exception,
match=str({
'error': 'no such script',
'message': "No preload script with BiDi ID '42'"
'message': "No preload script with id '42'"
})):
await execute_command(websocket, {
"method": "script.removePreloadScript",
Expand Down Expand Up @@ -70,12 +70,11 @@ async def test_preloadScript_remove_addAndRemoveIsNoop_secondRemoval_fails(
assert result["result"] == {"type": "undefined"}

# Ensure script was removed
with pytest.raises(
Exception,
match=str({
'error': 'no such script',
'message': f"No preload script with BiDi ID '{bidi_id}'"
})):
with pytest.raises(Exception,
match=str({
'error': 'no such script',
'message': f"No preload script with id '{bidi_id}'"
})):
await execute_command(
websocket, {
"method": "script.removePreloadScript",
Expand Down

0 comments on commit 405b995

Please sign in to comment.