From dcd8ee7388ec286efa15da3095687c4168c4af37 Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Wed, 2 Dec 2026 13:55:57 +0000 Subject: [PATCH] fix(evaluate): pass deeply nested arguments Serialized arguments now travel in the function source and not as protocol values, because browsers limit the nesting of protocol values. The utility script serializer encodes arrays, objects, maps and sets as tagged arrays, so that the serialized value is as deep as the original value. Storage state files in the old encoding are converted on the server. Fixes: https://github.com/microsoft/playwright/issues/44060 --- packages/injected/src/utilityScript.ts | 10 +- .../isomorphic/utilityScriptSerializers.ts | 142 ++++++++++------- .../src/server/bidi/bidiExecutionContext.ts | 7 +- .../server/bidi/third_party/bidiSerializer.ts | 150 ------------------ .../src/server/browserContext.ts | 66 +++++++- .../src/server/chromium/crExecutionContext.ts | 8 +- .../src/server/firefox/ffExecutionContext.ts | 8 +- .../playwright-core/src/server/javascript.ts | 19 ++- .../webkit/webview/wvExecutionContext.ts | 8 +- .../src/server/webkit/wkExecutionContext.ts | 8 +- .../browsercontext-storage-state.spec.ts | 87 ++++++++-- tests/page/page-evaluate.spec.ts | 13 +- tests/registry.md | 2 + 13 files changed, 262 insertions(+), 266 deletions(-) delete mode 100644 packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts diff --git a/packages/injected/src/utilityScript.ts b/packages/injected/src/utilityScript.ts index 5dc12744a417a..0b74e24facec6 100644 --- a/packages/injected/src/utilityScript.ts +++ b/packages/injected/src/utilityScript.ts @@ -16,6 +16,8 @@ import { parseEvaluationResultValue, serializeAsCallArgument } from '@isomorphic/utilityScriptSerializers'; +import type { SerializedValue } from '@isomorphic/utilityScriptSerializers'; + // Keep in sync with eslint.config.mjs export type Builtins = { setTimeout: Window['setTimeout'], @@ -65,9 +67,7 @@ export class UtilityScript { (global as any).builtins = this.builtins; } - evaluate(isFunction: boolean | undefined, returnByValue: boolean, expression: string, argCount: number, ...argsAndHandles: any[]) { - const args = argsAndHandles.slice(0, argCount); - const handles = argsAndHandles.slice(argCount); + evaluate(isFunction: boolean | undefined, returnByValue: boolean, expression: string, args: SerializedValue[], handles: any[]) { const parameters = []; for (let i = 0; i < args.length; i++) parameters[i] = parseEvaluationResultValue(args[i], handles); @@ -95,7 +95,7 @@ export class UtilityScript { return returnByValue ? this._jsonValueNoThrow(result) : result; } - jsonValue(returnByValue: true, value: any) { + jsonValue(value: any) { // Special handling of undefined to work-around multi-step returnByValue handling in WebKit. if (value === undefined) return undefined; @@ -104,7 +104,7 @@ export class UtilityScript { private _jsonValueNoThrow(value: any) { try { - return this.jsonValue(true, value); + return this.jsonValue(value); } catch (e) { return undefined; } diff --git a/packages/isomorphic/utilityScriptSerializers.ts b/packages/isomorphic/utilityScriptSerializers.ts index 7132bc86266a0..993d9f2e4bd53 100644 --- a/packages/isomorphic/utilityScriptSerializers.ts +++ b/packages/isomorphic/utilityScriptSerializers.ts @@ -23,6 +23,14 @@ export const kFunctionBindingPrefix = '__pw_fn_'; export const kBindingsControllerProperty = '__playwright__binding__controller__'; +// Arrays, objects, maps and sets are arrays that start with a tag, +// so that the serialized value is as deep as the original value, and not deeper: +// - ['a', item1, item2, ...] is an array; +// - ['o', key1, value1, key2, value2, ...] is an object; +// - ['m', key1, value1, key2, value2, ...] is a map; +// - ['s', item1, item2, ...] is a set. +// Each of them gets the next number, starting with 1, in the order of serialization, +// and { ref: number } refers to the one that was serialized before. export type SerializedValue = undefined | boolean | number | string | { v: 'null' | 'undefined' | 'NaN' | 'Infinity' | '-Infinity' | '-0' } | @@ -31,10 +39,7 @@ export type SerializedValue = { bi: string } | { e: { n: string, m: string, s: string } } | { r: { p: string, f: string } } | - { a: SerializedValue[], id: number } | - { o: { k: string, v: SerializedValue }[], id: number } | - { m: { k: SerializedValue, v: SerializedValue }[], id: number } | - { s: SerializedValue[], id: number } | + ['a' | 'o' | 'm' | 's', ...SerializedValue[]] | { ref: number } | { h: number } | { fn: string } | @@ -148,12 +153,53 @@ function base64ToTypedArray(base64: string, TypedArrayConstructor: any) { return new TypedArrayConstructor(bytes.buffer); } -export function parseEvaluationResultValue(value: SerializedValue, handles: any[] = [], refs: Map = new Map()): any { +// |refs| has the arrays, objects, maps and sets that are parsed so far, in the order of serialization. +// Arrays are filled by index, because the page can break Array.prototype.push. +export function parseEvaluationResultValue(value: SerializedValue, handles: any[] = [], refs: object[] = []): any { if (Object.is(value, undefined)) return undefined; + if (Array.isArray(value)) { + const tag = value[0]; + if (tag === 'a') { + const result: any[] = []; + refs[refs.length] = result; + for (let i = 1; i < value.length; i++) + result[i - 1] = parseEvaluationResultValue(value[i], handles, refs); + return result; + } + if (tag === 'o') { + const result: any = {}; + refs[refs.length] = result; + for (let i = 1; i < value.length; i += 2) { + const k = value[i] as string; + // Parse the value in any case, to keep the numbers in sync with the serializer. + const v = parseEvaluationResultValue(value[i + 1], handles, refs); + if (k !== '__proto__') + result[k] = v; + } + return result; + } + if (tag === 'm') { + const result = new Map(); + refs[refs.length] = result; + for (let i = 1; i < value.length; i += 2) { + const k = parseEvaluationResultValue(value[i], handles, refs); + result.set(k, parseEvaluationResultValue(value[i + 1], handles, refs)); + } + return result; + } + if (tag === 's') { + const result = new Set(); + refs[refs.length] = result; + for (let i = 1; i < value.length; i++) + result.add(parseEvaluationResultValue(value[i], handles, refs)); + return result; + } + return undefined; + } if (typeof value === 'object' && value) { if ('ref' in value) - return refs.get(value.ref); + return refs[value.ref - 1]; if ('v' in value) { if (value.v === 'undefined') return undefined; @@ -185,37 +231,6 @@ export function parseEvaluationResultValue(value: SerializedValue, handles: any[ } if ('r' in value) return new RegExp(value.r.p, value.r.f); - if ('a' in value) { - const result: any[] = []; - refs.set(value.id, result); - for (const a of value.a) - result.push(parseEvaluationResultValue(a, handles, refs)); - return result; - } - if ('o' in value) { - const result: any = {}; - refs.set(value.id, result); - for (const { k, v } of value.o) { - if (k === '__proto__') - continue; - result[k] = parseEvaluationResultValue(v, handles, refs); - } - return result; - } - if ('m' in value) { - const result = new Map(); - refs.set(value.id, result); - for (const { k, v } of value.m) - result.set(parseEvaluationResultValue(k, handles, refs), parseEvaluationResultValue(v, handles, refs)); - return result; - } - if ('s' in value) { - const result = new Set(); - refs.set(value.id, result); - for (const item of value.s) - result.add(parseEvaluationResultValue(item, handles, refs)); - return result; - } if ('h' in value) return handles[value.h]; if ('fn' in value) { @@ -310,23 +325,21 @@ function innerSerialize(value: any, handleSerializer: (value: any) => HandleOrVa if (visitorInfo.extendedSerialization) { if (isMap(value)) { - const m: { k: SerializedValue, v: SerializedValue }[] = []; - const id = ++visitorInfo.lastId; - visitorInfo.visited.set(value, id); + const m: SerializedValue = ['m']; + visitorInfo.visited.set(value, ++visitorInfo.lastId); const iterator = value.entries(); const next = new Map().entries().next; while (true) { const entry = next.call(iterator); if (entry.done) break; - m.push({ k: serialize(entry.value[0], handleSerializer, visitorInfo), v: serialize(entry.value[1], handleSerializer, visitorInfo) }); + m.push(serialize(entry.value[0], handleSerializer, visitorInfo), serialize(entry.value[1], handleSerializer, visitorInfo)); } - return { m, id }; + return m; } if (isSet(value)) { - const s: SerializedValue[] = []; - const id = ++visitorInfo.lastId; - visitorInfo.visited.set(value, id); + const s: SerializedValue = ['s']; + visitorInfo.visited.set(value, ++visitorInfo.lastId); const iterator = value.values(); const next = new Set().values().next; while (true) { @@ -335,23 +348,21 @@ function innerSerialize(value: any, handleSerializer: (value: any) => HandleOrVa break; s.push(serialize(entry.value, handleSerializer, visitorInfo)); } - return { s, id }; + return s; } } if (Array.isArray(value)) { - const a = []; - const id = ++visitorInfo.lastId; - visitorInfo.visited.set(value, id); + const a: SerializedValue = ['a']; + visitorInfo.visited.set(value, ++visitorInfo.lastId); for (let i = 0; i < value.length; ++i) a.push(serialize(value[i], handleSerializer, visitorInfo)); - return { a, id }; + return a; } if (typeof value === 'object') { - const o: { k: string, v: SerializedValue }[] = []; - const id = ++visitorInfo.lastId; - visitorInfo.visited.set(value, id); + const o: SerializedValue = ['o']; + visitorInfo.visited.set(value, ++visitorInfo.lastId); for (const name of Object.keys(value)) { let item; try { @@ -359,25 +370,36 @@ function innerSerialize(value: any, handleSerializer: (value: any) => HandleOrVa } catch (e) { continue; // native bindings will throw sometimes } - if (name === 'toJSON' && typeof item === 'function') - o.push({ k: name, v: { o: [], id: 0 } }); - else - o.push({ k: name, v: serialize(item, handleSerializer, visitorInfo) }); + if (name === 'toJSON' && typeof item === 'function') { + // An empty object, that takes a number like any other object. + ++visitorInfo.lastId; + o.push(name, ['o']); + } else { + o.push(name, serialize(item, handleSerializer, visitorInfo)); + } } let jsonWrapper; try { // If Object.keys().length === 0 we fall back to toJSON if it exists - if (o.length === 0 && value.toJSON && typeof value.toJSON === 'function') + if (o.length === 1 && value.toJSON && typeof value.toJSON === 'function') jsonWrapper = { value: value.toJSON() }; } catch (e) { } - if (jsonWrapper) + if (jsonWrapper) { + // This object is not in the result, so it must not take a number. + visitorInfo.visited.delete(value); + --visitorInfo.lastId; return innerSerialize(jsonWrapper.value, handleSerializer, visitorInfo); + } - return { o, id }; + return o; } if (typeof value === 'function' && value.name.startsWith(kFunctionBindingPrefix)) return { fn: value.name }; + + // Other functions are not serializable. JSON turns a bare undefined inside an array into null, + // so the value is explicit. + return { v: 'undefined' }; } diff --git a/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts b/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts index f9a3e48e543b0..4ad1d571b1a34 100644 --- a/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts +++ b/packages/playwright-core/src/server/bidi/bidiExecutionContext.ts @@ -14,12 +14,10 @@ * limitations under the License. */ -import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers'; import { assert } from '@isomorphic/assert'; import * as js from '../javascript'; import * as dom from '../dom'; import * as bidi from './third_party/bidiProtocol'; -import { BidiSerializer } from './third_party/bidiSerializer'; import { deserializeBidiValue } from './bidiDeserializer'; import type { BidiSession } from './bidiConnection'; @@ -80,13 +78,12 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate { throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response)); } - async evaluateWithArguments(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise { + async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise { const response = await this._session.send('script.callFunction', { functionDeclaration, target: this._target, arguments: [ { handle: utilityScript._objectId! }, - ...values.map(BidiSerializer.serialize), ...handles.map(handle => ({ handle: handle._objectId! })), ], resultOwnership: returnByValue ? undefined : bidi.Script.ResultOwnership.Root, // Necessary for the handle to be returned. @@ -98,7 +95,7 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate { throw new js.JavaScriptErrorInEvaluate(response.exceptionDetails.text); if (response.type === 'success') { if (returnByValue) - return parseEvaluationResultValue(deserializeBidiValue(response.result)); + return deserializeBidiValue(response.result); return createHandle(utilityScript._context, response.result); } throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response)); diff --git a/packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts b/packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts deleted file mode 100644 index 6f4df4dd12165..0000000000000 --- a/packages/playwright-core/src/server/bidi/third_party/bidiSerializer.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * @license - * Copyright 2024 Google Inc. - * Modifications copyright (c) Microsoft Corporation. - * SPDX-License-Identifier: Apache-2.0 - */ - -// Copied from upstream: https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/bidi/Serializer.ts - -import type * as Bidi from './bidiProtocol'; - -/* eslint-disable curly */ - -/** - * @internal - */ -class UnserializableError extends Error {} - -/** - * @internal - */ -export class BidiSerializer { - static serialize(arg: unknown): Bidi.Script.LocalValue { - switch (typeof arg) { - case 'symbol': - case 'function': - throw new UnserializableError(`Unable to serializable ${typeof arg}`); - case 'object': - return BidiSerializer._serializeObject(arg); - - case 'undefined': - return { - type: 'undefined', - }; - case 'number': - return BidiSerializer._serializeNumber(arg); - case 'bigint': - return { - type: 'bigint', - value: arg.toString(), - }; - case 'string': - return { - type: 'string', - value: arg, - }; - case 'boolean': - return { - type: 'boolean', - value: arg, - }; - } - } - - static _serializeNumber(arg: number): Bidi.Script.LocalValue { - let value: Bidi.Script.SpecialNumber | number; - if (Object.is(arg, -0)) { - value = '-0'; - } else if (Object.is(arg, Infinity)) { - value = 'Infinity'; - } else if (Object.is(arg, -Infinity)) { - value = '-Infinity'; - } else if (Object.is(arg, NaN)) { - value = 'NaN'; - } else { - value = arg; - } - return { - type: 'number', - value, - }; - } - - static _serializeObject(arg: object | null): Bidi.Script.LocalValue { - if (arg === null) { - return { - type: 'null', - }; - } else if (Array.isArray(arg)) { - const parsedArray = arg.map(subArg => { - return BidiSerializer.serialize(subArg); - }); - - return { - type: 'array', - value: parsedArray, - }; - } else if (isPlainObject(arg)) { - try { - JSON.stringify(arg); - } catch (error) { - if ( - error instanceof TypeError && - error.message.startsWith('Converting circular structure to JSON') - ) { - error.message += ' Recursive objects are not allowed.'; - } - throw error; - } - - const parsedObject: Bidi.Script.MappingLocalValue = []; - for (const key in arg) { - parsedObject.push([BidiSerializer.serialize(key), BidiSerializer.serialize(arg[key])]); - } - - return { - type: 'object', - value: parsedObject, - }; - } else if (isRegExp(arg)) { - return { - type: 'regexp', - value: { - pattern: arg.source, - flags: arg.flags, - }, - }; - } else if (isDate(arg)) { - return { - type: 'date', - value: arg.toISOString(), - }; - } - - throw new UnserializableError( - 'Custom object serialization not possible. Use plain objects instead.' - ); - } -} - -/** - * @internal - */ -export const isPlainObject = (obj: unknown): obj is Record => { - return typeof obj === 'object' && obj?.constructor === Object; -}; - -/** - * @internal - */ -export const isRegExp = (obj: unknown): obj is RegExp => { - return typeof obj === 'object' && obj?.constructor === RegExp; -}; - -/** - * @internal - */ -export const isDate = (obj: unknown): obj is Date => { - return typeof obj === 'object' && obj?.constructor === Date; -}; diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts index ff9b15a7f9c3e..8e4ea537026d4 100644 --- a/packages/playwright-core/src/server/browserContext.ts +++ b/packages/playwright-core/src/server/browserContext.ts @@ -45,7 +45,8 @@ import type { ClientCertificatesProxy } from './socksClientCertificatesIntercept import type { SerializedStorage } from '@injected/storageScript'; import type * as types from './types'; import type * as channels from './channels'; -import type { HttpCredentials } from '@protocol/structs'; +import type { HttpCredentials, SetOriginStorage } from '@protocol/structs'; +import type { SerializedValue } from '@isomorphic/utilityScriptSerializers'; const BrowserContextEvent = { Console: 'console', @@ -705,7 +706,7 @@ export abstract class BrowserContext extends Sdk const module = {}; ${rawStorageSource.source} const script = new (module.exports.StorageScript())(${JSON.stringify(this._browser.options.name)}); - return script.restore(${JSON.stringify(newOrigins.get(origin))}); + return script.restore(${JSON.stringify(upgradeEncodedIndexedDBRecords(newOrigins.get(origin)))}); })()`; await frame.evaluateExpression(progress, restoreScript, { world: 'utility' }); } @@ -779,6 +780,67 @@ export function findMatchingHttpCredentials(credentials: HttpCredentials[] | und return credentials?.find(c => !c.origin || c.origin.toLowerCase() === origin); } +// Storage state files from the older versions encode arrays, objects, maps and sets +// in IndexedDB keys and values in the old way: +// - { a: [item1, item2, ...], id } is an array; +// - { o: [{ k: key1, v: value1 }, ...], id } is an object; +// - { m: [{ k: key1, v: value1 }, ...], id } is a map; +// - { s: [item1, item2, ...], id } is a set; +// - { ref: id } refers to the one with this id. +// This function converts them to the current encoding, see SerializedValue. +// TODO: remove in March 2027. +function upgradeEncodedIndexedDBRecords(origin: SetOriginStorage | undefined): SetOriginStorage | undefined { + if (!origin?.indexedDB) + return origin; + return { + ...origin, + indexedDB: origin.indexedDB.map(db => ({ + ...db, + stores: db.stores.map(store => ({ + ...store, + records: store.records.map(record => { + const result = { ...record }; + if ('keyEncoded' in record) + result.keyEncoded = upgradeEncodedValue(record.keyEncoded); + if ('valueEncoded' in record) + result.valueEncoded = upgradeEncodedValue(record.valueEncoded); + return result; + }), + })), + })), + }; +} + +function upgradeEncodedValue(encoded: any): SerializedValue { + // Maps the id in the old encoding to the number in the current encoding. + const numbers = new Map(); + let lastNumber = 0; + const upgrade = (value: any): SerializedValue => { + // An array is a value in the current encoding. + if (typeof value !== 'object' || value === null || Array.isArray(value)) + return value; + if ('ref' in value) + return { ref: numbers.get(value.ref) ?? 0 }; + const tag = (['a', 'o', 'm', 's'] as const).find(tag => tag in value); + if (!tag) + return value; + numbers.set(value.id, ++lastNumber); + const result: SerializedValue = [tag]; + for (const item of value[tag]) { + if (tag === 'a' || tag === 's') + result.push(upgrade(item)); + else if (tag === 'o') + result.push(item.k, upgradeProperty(item.v)); + else + result.push(upgradeProperty(item.k), upgradeProperty(item.v)); + } + return result; + }; + // JSON turns undefined inside an array into null, so a missing key or value must be explicit. + const upgradeProperty = (value: any): SerializedValue => upgrade(value) ?? { v: 'undefined' }; + return upgrade(encoded); +} + export function verifyGeolocation(geolocation?: types.Geolocation): asserts geolocation is types.Geolocation { if (!geolocation) return; diff --git a/packages/playwright-core/src/server/chromium/crExecutionContext.ts b/packages/playwright-core/src/server/chromium/crExecutionContext.ts index dbdd0e9e58a82..cef635823103c 100644 --- a/packages/playwright-core/src/server/chromium/crExecutionContext.ts +++ b/packages/playwright-core/src/server/chromium/crExecutionContext.ts @@ -17,7 +17,6 @@ import { assert } from '@isomorphic/assert'; import { rewriteErrorMessage } from '@utils/stackTrace'; -import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers'; import { getExceptionMessage, releaseObject } from './crProtocolHelper'; import * as js from '../javascript'; import * as dom from '../dom'; @@ -56,13 +55,12 @@ export class CRExecutionContext implements js.ExecutionContextDelegate { return createHandle(context, remoteObject); } - async evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise { + async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise { const { exceptionDetails, result: remoteObject } = await this._client.send('Runtime.callFunctionOn', { - functionDeclaration: expression, + functionDeclaration, objectId: utilityScript._objectId, arguments: [ { objectId: utilityScript._objectId }, - ...values.map(value => ({ value })), ...handles.map(handle => ({ objectId: handle._objectId! })), ], returnByValue, @@ -71,7 +69,7 @@ export class CRExecutionContext implements js.ExecutionContextDelegate { }).catch(rewriteError); if (exceptionDetails) throw new js.JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); - return returnByValue ? parseEvaluationResultValue(remoteObject.value) : createHandle(utilityScript._context, remoteObject); + return returnByValue ? remoteObject.value : createHandle(utilityScript._context, remoteObject); } async getProperties(object: js.JSHandle): Promise> { diff --git a/packages/playwright-core/src/server/firefox/ffExecutionContext.ts b/packages/playwright-core/src/server/firefox/ffExecutionContext.ts index 9d5ca9dd93dd5..7c15383aa5dda 100644 --- a/packages/playwright-core/src/server/firefox/ffExecutionContext.ts +++ b/packages/playwright-core/src/server/firefox/ffExecutionContext.ts @@ -17,7 +17,6 @@ import { assert } from '@isomorphic/assert'; import { rewriteErrorMessage } from '@utils/stackTrace'; -import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers'; import * as js from '../javascript'; import * as dom from '../dom'; import { isSessionClosedError } from '../protocolError'; @@ -56,13 +55,12 @@ export class FFExecutionContext implements js.ExecutionContextDelegate { return createHandle(context, payload.result!); } - async evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise { + async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise { const payload = await this._session.send('Runtime.callFunction', { - functionDeclaration: expression, + functionDeclaration, userGesture: true, args: [ { objectId: utilityScript._objectId, value: undefined }, - ...values.map(value => ({ value })), ...handles.map(handle => ({ objectId: handle._objectId!, value: undefined })), ], returnByValue, @@ -70,7 +68,7 @@ export class FFExecutionContext implements js.ExecutionContextDelegate { }).catch(rewriteError); checkException(payload.exceptionDetails); if (returnByValue) - return parseEvaluationResultValue(payload.result!.value); + return payload.result!.value; return createHandle(utilityScript._context, payload.result!); } diff --git a/packages/playwright-core/src/server/javascript.ts b/packages/playwright-core/src/server/javascript.ts index ac9883dcef85b..27195692ef24f 100644 --- a/packages/playwright-core/src/server/javascript.ts +++ b/packages/playwright-core/src/server/javascript.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { serializeAsCallArgument } from '@isomorphic/utilityScriptSerializers'; +import { parseEvaluationResultValue, serializeAsCallArgument } from '@isomorphic/utilityScriptSerializers'; import { LongStandingScope } from '@isomorphic/manualPromise'; import { isUnderTest } from '@utils/debug'; import { SdkObject } from './instrumentation'; @@ -49,7 +49,7 @@ export type SmartHandle = T extends Node ? dom.ElementHandle : JSHandle export interface ExecutionContextDelegate { rawEvaluateJSON(expression: string): Promise; rawEvaluateHandle(context: ExecutionContext, expression: string): Promise; - evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: JSHandle, values: any[], handles: JSHandle[]): Promise; + callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: JSHandle, handles: JSHandle[]): Promise; getProperties(object: JSHandle): Promise>; releaseHandle(handle: JSHandle): Promise; shouldPrependErrorPrefix(): boolean; @@ -85,9 +85,10 @@ export class ExecutionContext extends SdkObject { return this.raceAgainstContextDestroyed(this.delegate.rawEvaluateHandle(this, expression)); } - async _evaluateWithArguments(expression: string, returnByValue: boolean, values: any[], handles: JSHandle[]): Promise { + async _callUtilityScript(functionDeclaration: string, returnByValue: boolean, handles: JSHandle[]): Promise { const utilityScript = await this._utilityScript(); - return this.raceAgainstContextDestroyed(this.delegate.evaluateWithArguments(expression, returnByValue, utilityScript, values, handles)); + const result = await this.raceAgainstContextDestroyed(this.delegate.callFunction(functionDeclaration, returnByValue, utilityScript, handles)); + return returnByValue ? parseEvaluationResultValue(result) : result; } getProperties(object: JSHandle): Promise> { @@ -204,8 +205,7 @@ export class JSHandle extends SdkObject { private async _jsonValue(): Promise { if (!this._objectId) return this._value; - const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`; - return this._context._evaluateWithArguments(script, true, [true], [this]); + return this._context._callUtilityScript(`(utilityScript, value) => utilityScript.jsonValue(value)`, true, [this]); } asElement(): dom.ElementHandle | null { @@ -286,11 +286,10 @@ export async function evaluateExpression(context: ExecutionContext, expression: } // See UtilityScript for arguments. - const utilityScriptValues = [options.isFunction, options.returnByValue, expression, args.length, ...args]; - - const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`; + const returnByValue = !!options.returnByValue; + const script = `(utilityScript, ...handles) => utilityScript.evaluate(${options.isFunction}, ${returnByValue}, ${JSON.stringify(expression)}, ${JSON.stringify(args)}, handles)`; try { - return await context._evaluateWithArguments(script, options.returnByValue || false, utilityScriptValues, utilityScriptObjects); + return await context._callUtilityScript(script, returnByValue, utilityScriptObjects); } finally { for (const handlePromise of toDispose) void handlePromise.then(handle => handle.dispose()); diff --git a/packages/playwright-core/src/server/webkit/webview/wvExecutionContext.ts b/packages/playwright-core/src/server/webkit/webview/wvExecutionContext.ts index a13a51581080c..3dad7fe3b0ff4 100644 --- a/packages/playwright-core/src/server/webkit/webview/wvExecutionContext.ts +++ b/packages/playwright-core/src/server/webkit/webview/wvExecutionContext.ts @@ -16,7 +16,6 @@ */ import { assert } from '@isomorphic/assert'; -import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers'; import * as js from '../../javascript'; import * as dom from '../../dom'; import { isSessionClosedError } from '../../protocolError'; @@ -63,14 +62,13 @@ export class WVExecutionContext implements js.ExecutionContextDelegate { } } - async evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise { + async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise { try { const response = await this._session.send('Runtime.callFunctionOn', { - functionDeclaration: expression, + functionDeclaration, objectId: utilityScript._objectId!, arguments: [ { objectId: utilityScript._objectId }, - ...values.map(value => ({ value })), ...handles.map(handle => ({ objectId: handle._objectId! })), ], returnByValue, @@ -80,7 +78,7 @@ export class WVExecutionContext implements js.ExecutionContextDelegate { if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description); if (returnByValue) - return parseEvaluationResultValue(response.result.value); + return response.result.value; return createHandle(utilityScript._context, response.result); } catch (error) { throw rewriteError(error); diff --git a/packages/playwright-core/src/server/webkit/wkExecutionContext.ts b/packages/playwright-core/src/server/webkit/wkExecutionContext.ts index e06f4e838ffbc..9fa7c87f50f13 100644 --- a/packages/playwright-core/src/server/webkit/wkExecutionContext.ts +++ b/packages/playwright-core/src/server/webkit/wkExecutionContext.ts @@ -16,7 +16,6 @@ */ import { assert } from '@isomorphic/assert'; -import { parseEvaluationResultValue } from '@isomorphic/utilityScriptSerializers'; import * as js from '../javascript'; import * as dom from '../dom'; import { isSessionClosedError } from '../protocolError'; @@ -63,14 +62,13 @@ export class WKExecutionContext implements js.ExecutionContextDelegate { } } - async evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: js.JSHandle, values: any[], handles: js.JSHandle[]): Promise { + async callFunction(functionDeclaration: string, returnByValue: boolean, utilityScript: js.JSHandle, handles: js.JSHandle[]): Promise { try { const response = await this._session.send('Runtime.callFunctionOn', { - functionDeclaration: expression, + functionDeclaration, objectId: utilityScript._objectId!, arguments: [ { objectId: utilityScript._objectId }, - ...values.map(value => ({ value })), ...handles.map(handle => ({ objectId: handle._objectId! })), ], returnByValue, @@ -80,7 +78,7 @@ export class WKExecutionContext implements js.ExecutionContextDelegate { if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description); if (returnByValue) - return parseEvaluationResultValue(response.result.value); + return response.result.value; return createHandle(utilityScript._context, response.result); } catch (error) { throw rewriteError(error); diff --git a/tests/library/browsercontext-storage-state.spec.ts b/tests/library/browsercontext-storage-state.spec.ts index 76693f6239562..d79d74117c287 100644 --- a/tests/library/browsercontext-storage-state.spec.ts +++ b/tests/library/browsercontext-storage-state.spec.ts @@ -585,19 +585,17 @@ it('ST-016 should support IndexedDB', async ({ page, server, contextFactory }) = keyPath: 'taskTitle', records: [ { - valueEncoded: { - id: 1, - o: [ - { k: 'taskTitle', v: 'Pet the cat' }, - { k: 'hours', v: '1' }, - { k: 'minutes', v: '1' }, - { k: 'day', v: '01' }, - { k: 'month', v: 'January' }, - { k: 'year', v: '2025' }, - { k: 'notified', v: 'no' }, - { k: 'binaryTitle', v: { ab: { b: 'UGV0IHRoZSBjYXQ=' } }, } - ] - }, + valueEncoded: [ + 'o', + 'taskTitle', 'Pet the cat', + 'hours', '1', + 'minutes', '1', + 'day', '01', + 'month', 'January', + 'year', '2025', + 'notified', 'no', + 'binaryTitle', { ab: { b: 'UGV0IHRoZSBjYXQ=' } }, + ], }, ], indexes: [ @@ -737,6 +735,69 @@ for (const restore of ['newContext', 'setStorageState'] as const) { }); } +it('ST-033 should read IndexedDB values in the encoding of older versions', async ({ contextFactory, server }) => { + const storageState = { + cookies: [], + origins: [{ + origin: server.PREFIX, + localStorage: [], + indexedDB: [{ + name: 'db', + version: 1, + stores: [{ + name: 'store', + autoIncrement: false, + indexes: [], + records: [{ + key: 'key', + // The ids are not the numbers in the order of serialization. + valueEncoded: { + id: 1, + o: [ + { k: 'list', v: { id: 3, a: [1, { d: '2020-01-01T00:00:00.000Z' }] } }, + { k: 'self', v: { ref: 1 } }, + { k: 'map', v: { id: 5, m: [{ k: 'mk', v: { ref: 3 } }] } }, + { k: 'set', v: { id: 6, s: ['item'] } }, + { k: 'sameSet', v: { ref: 6 } }, + ], + }, + }], + }], + }], + }], + }; + const context = await contextFactory({ storageState }); + const page = await context.newPage(); + await page.goto(server.EMPTY_PAGE); + const result = await page.evaluate(async () => { + const db = await new Promise((resolve, reject) => { + const request = indexedDB.open('db', 1); + request.onerror = () => reject(request.error); + request.onsuccess = () => resolve(request.result); + }); + const request = db.transaction('store', 'readonly').objectStore('store').get('key'); + const value = await new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + db.close(); + return { + list: [value.list[0], value.list[1].toISOString()], + self: value.self === value, + map: value.map.get('mk') === value.list, + set: [...value.set], + sameSet: value.sameSet === value.set, + }; + }); + expect(result).toEqual({ + list: [1, '2020-01-01T00:00:00.000Z'], + self: true, + map: true, + set: ['item'], + sameSet: true, + }); +}); + it('ST-018 should support empty indexedDB', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/35760' } }, async ({ page, server, contextFactory }) => { await page.goto(server.EMPTY_PAGE); await page.evaluate(() => new Promise(resolve => { diff --git a/tests/page/page-evaluate.spec.ts b/tests/page/page-evaluate.spec.ts index 04b4b4ef2353c..f229a8a47d790 100644 --- a/tests/page/page-evaluate.spec.ts +++ b/tests/page/page-evaluate.spec.ts @@ -276,6 +276,15 @@ it('EV-032 should return complex objects', async ({ page }) => { expect(result).toEqual(object); }); +it('EV-138 should pass a deeply nested argument', { + annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/44060' } +}, async ({ page }) => { + let argument: unknown = 0; + for (let i = 0; i < 100; i++) + argument = { children: [argument] }; + expect(await page.evaluate(value => JSON.stringify(value), argument)).toBe(JSON.stringify(argument)); +}); + it('EV-033 should return NaN', async ({ page }) => { const result = await page.evaluate(() => NaN); expect(Object.is(result, NaN)).toBe(true); @@ -456,6 +465,8 @@ it('EV-046 should properly serialize window.performance object', async ({ page } it('EV-047 should return undefined for non-serializable objects', async ({ page }) => { expect(await page.evaluate(() => function() {})).toBe(undefined); + expect(await page.evaluate(() => [function() {}, 1])).toStrictEqual([undefined, 1]); + expect(await page.evaluate(() => ({ f: function() {}, n: 1 }))).toStrictEqual({ f: undefined, n: 1 }); }); it('EV-048 should throw for too deep reference chain', { @@ -484,7 +495,7 @@ it('EV-049 should throw for too deep reference chain 2', { for (let i = 0; i < depth; i++) node = { child: node }; return node; - }, 200)).rejects.toThrow('Cannot serialize result: object reference chain is too long.'); + }, 400)).rejects.toThrow('Cannot serialize result: object reference chain is too long.'); }); it('EV-050 should throw usable message for unserializable shallow function', async ({ page }) => { diff --git a/tests/registry.md b/tests/registry.md index 2a92f44bca2b3..263695cd6dac9 100644 --- a/tests/registry.md +++ b/tests/registry.md @@ -2252,6 +2252,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `EV-135` | `page/page-evaluate-no-stall.spec.ts` | should work | | `EV-136` | `page/page-evaluate-no-stall.spec.ts` | should throw while pending navigation | | `EV-137` | `page/page-evaluate-no-stall.spec.ts` | should throw when no main execution context | +| `EV-138` | `page/page-evaluate.spec.ts` | should pass a deeply nested argument | ### EX — Expect @@ -5059,6 +5060,7 @@ subsystem, add a row to the Subsystems table. Then update this file: | `ST-030` | `page/page-localstorage.spec.ts` | localStorage and sessionStorage are independent | | `ST-031` | `page/page-localstorage.spec.ts` | storage methods are scoped to the current origin | | `ST-032` | `page/page-cache-storage.spec.ts` | CacheStorage entry should survive page.reload() | +| `ST-033` | `library/browsercontext-storage-state.spec.ts` | should read IndexedDB values in the encoding of older versions | ### TA — Tap