Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore(protocol): auto-serialize SerializedValue in validators (#40798)
Dmitry Gozmane67f2a3f9ba0
diff --git a/packages/playwright-core/src/browserServerImpl.ts b/packages/playwright-core/src/browserServerImpl.tsindex d0776eae0a..1d4fa9b29d 100644--- a/packages/playwright-core/src/browserServerImpl.ts+++ b/packages/playwright-core/src/browserServerImpl.ts@@ -46,7 +46,8 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {tChannelImpl: (names: '*' | string[], arg: any, path: string) => {throw new validatorPrimitives.ValidationError(`${path}: channels are not expected in launchServer`);},- binary: 'buffer',+ direction: 'fromWire',+ rawBuffers: true,isUnderTest,} satisfies validatorPrimitives.ValidatorContext;let launchOptions = {diff --git a/packages/playwright-core/src/client/channelOwner.ts b/packages/playwright-core/src/client/channelOwner.tsindex 7542265254..b539fc925c 100644--- a/packages/playwright-core/src/client/channelOwner.ts+++ b/packages/playwright-core/src/client/channelOwner.ts@@ -137,7 +137,8 @@ export abstract class ChannelOwner<T extends channels.Channel = channels.Channelprivate _validatorToWireContext(): ValidatorContext {return {tChannelImpl: tChannelImplToWire,- binary: this._connection.rawBuffers() ? 'buffer' : 'toBase64',+ direction: 'toWire',+ rawBuffers: this._connection.rawBuffers(),isUnderTest: () => this._platform.isUnderTest(),};}diff --git a/packages/playwright-core/src/client/connection.ts b/packages/playwright-core/src/client/connection.tsindex 4e72253fb1..8bea42ebb0 100644--- a/packages/playwright-core/src/client/connection.ts+++ b/packages/playwright-core/src/client/connection.ts@@ -205,7 +205,8 @@ export class Connection extends EventEmitter {private _validatorFromWireContext(): ValidatorContext {return {tChannelImpl: this._tChannelImplFromWire.bind(this),- binary: this._rawBuffers ? 'buffer' : 'fromBase64',+ direction: 'fromWire',+ rawBuffers: this._rawBuffers,isUnderTest: () => this._platform.isUnderTest(),};}diff --git a/packages/playwright-core/src/client/electron.ts b/packages/playwright-core/src/client/electron.tsindex 2399aa61ff..0b3290b560 100644--- a/packages/playwright-core/src/client/electron.ts+++ b/packages/playwright-core/src/client/electron.ts@@ -20,7 +20,7 @@ import { envObjectToArray } from './clientHelper';import { ConsoleMessage } from './consoleMessage';import { TargetClosedError, isTargetClosedError } from './errors';import { Events } from './events';-import { JSHandle, parseResult, serializeArgument } from './jsHandle';+import { JSHandle, serializeArgument } from './jsHandle';import { Waiter } from './waiter';import { TimeoutSettings } from './timeoutSettings';@@ -159,7 +159,7 @@ export class ElectronApplication extends ChannelOwner<channels.ElectronApplicatiasync evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<ElectronAppType, Arg, R>, arg: Arg): Promise<R> {const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<ElectronAppType, Arg, R>, arg: Arg): Promise<structs.SmartHandle<R>> {diff --git a/packages/playwright-core/src/client/elementHandle.ts b/packages/playwright-core/src/client/elementHandle.tsindex 99e3c555d9..676356caa6 100644--- a/packages/playwright-core/src/client/elementHandle.ts+++ b/packages/playwright-core/src/client/elementHandle.ts@@ -18,7 +18,7 @@ import { assert } from '@isomorphic/assert';import { isString } from '@isomorphic/rtti';import { getMimeTypeForPath } from '@isomorphic/mimeType';import { Frame } from './frame';-import { JSHandle, parseResult, serializeArgument } from './jsHandle';+import { JSHandle, serializeArgument } from './jsHandle';import { fileUploadSizeLimit, mkdirIfNeeded } from './fileUtils';import { WritableStream } from './writableStream';@@ -214,12 +214,12 @@ export class ElementHandle<T extends Node = Node> extends JSHandle<T> implementsasync $eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element, Arg, R>, arg?: Arg): Promise<R> {const result = await this._elementChannel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async $$eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg): Promise<R> {const result = await this._elementChannel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async waitForElementState(state: 'visible' | 'hidden' | 'stable' | 'enabled' | 'disabled', options: TimeoutOptions = {}): Promise<void> {diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.tsindex aaadf17b46..ed288e398c 100644--- a/packages/playwright-core/src/client/frame.ts+++ b/packages/playwright-core/src/client/frame.ts@@ -23,7 +23,7 @@ import { ChannelOwner } from './channelOwner';import { addSourceUrlToScript } from './clientHelper';import { ElementHandle, convertInputFiles, convertSelectOptionValues } from './elementHandle';import { Events } from './events';-import { JSHandle, assertMaxArguments, parseResult, serializeArgument } from './jsHandle';+import { JSHandle, assertMaxArguments, serializeArgument } from './jsHandle';import { FrameLocator, Locator, testIdAttributeName } from './locator';import * as network from './network';import { kLifecycleEvents } from './types';@@ -200,13 +200,13 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frasync evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {assertMaxArguments(arguments.length, 2);const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async _evaluateExposeUtilityScript<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {assertMaxArguments(arguments.length, 2);const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async $(selector: string, options?: { strict?: boolean }): Promise<ElementHandle<SVGElement | HTMLElement> | null> {@@ -232,13 +232,13 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frasync $eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element, Arg, R>, arg?: Arg): Promise<R> {assertMaxArguments(arguments.length, 3);const result = await this._channel.evalOnSelector({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async $$eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg): Promise<R> {assertMaxArguments(arguments.length, 3);const result = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async $$(selector: string): Promise<ElementHandle<SVGElement | HTMLElement>[]> {@@ -490,25 +490,14 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frasync _expect(expression: string, options: Omit<channels.FrameExpectParams, 'expression'>): Promise<ExpectResult> {const params: channels.FrameExpectParams = { expression, ...options, isNot: !!options.isNot };params.expectedValue = serializeArgument(options.expectedValue);- const channelResult = await this._channel.expect(params);- const result: ExpectResult = {- matches: channelResult.matches,- log: channelResult.log,- timedOut: channelResult.timedOut,- errorMessage: channelResult.errorMessage,- };- if (channelResult.received !== undefined && channelResult.matches === !!options.isNot) {- result.received = {- value: channelResult.received.value !== undefined ? parseResult(channelResult.received.value) : undefined,- ariaSnapshot: channelResult.received.ariaSnapshot,- };- }+ const result = await this._channel.expect(params);+ if (result.matches !== !!options.isNot)+ delete result.received;return result;}}-export type ExpectReceived = { value?: any, ariaSnapshot?: string };-export type ExpectResult = { matches: boolean, received?: ExpectReceived, log?: string[], timedOut?: boolean, errorMessage?: string };+export type ExpectResult = channels.FrameExpectResult;export function verifyLoadState(name: string, waitUntil: LifecycleEvent): LifecycleEvent {if (waitUntil as unknown === 'networkidle0')diff --git a/packages/playwright-core/src/client/jsHandle.ts b/packages/playwright-core/src/client/jsHandle.tsindex 62a54950d5..d5e8a25d98 100644--- a/packages/playwright-core/src/client/jsHandle.ts+++ b/packages/playwright-core/src/client/jsHandle.ts@@ -16,7 +16,7 @@import { ChannelOwner } from './channelOwner';import { isTargetClosedError } from './errors';-import { parseSerializedValue, serializeValue } from '../protocol/serializers';+import { serializeValue } from '../protocol/serializers';import type * as structs from '../../types/structs';import type * as api from '../../types/types';@@ -38,7 +38,7 @@ export class JSHandle<T = any> extends ChannelOwner<channels.JSHandleChannel> imasync evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg): Promise<R> {const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {@@ -59,7 +59,7 @@ export class JSHandle<T = any> extends ChannelOwner<channels.JSHandleChannel> im}async jsonValue(): Promise<T> {- return parseResult((await this._channel.jsonValue()).value);+ return (await this._channel.jsonValue()).value;}asElement(): T extends Node ? api.ElementHandle<T> : null {@@ -101,10 +101,6 @@ export function serializeArgument(arg: any): channels.SerializedArgument {return { value, handles };}-export function parseResult(value: channels.SerializedValue): any {- return parseSerializedValue(value, undefined);-}-export function assertMaxArguments(count: number, max: number): asserts count {if (count > max)throw new Error('Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object.');diff --git a/packages/playwright-core/src/client/page.ts b/packages/playwright-core/src/client/page.tsindex f2b3811276..0dfe2efc6b 100644--- a/packages/playwright-core/src/client/page.ts+++ b/packages/playwright-core/src/client/page.ts@@ -35,7 +35,7 @@ import { Frame, verifyLoadState } from './frame';import { HarRouter } from './harRouter';import { Keyboard, Mouse, Touchscreen } from './input';import { WebStorage } from './webStorage';-import { assertMaxArguments, parseResult, serializeArgument } from './jsHandle';+import { assertMaxArguments, serializeArgument } from './jsHandle';import { Request, Response, Route, RouteHandler, WebSocket, WebSocketRoute, WebSocketRouteHandler, validateHeaders } from './network';import { Video } from './video';import { Screencast } from './screencast';@@ -900,7 +900,7 @@ export class BindingCall extends ChannelOwner<channels.BindingCallChannel> {page: frame._page!,frame};- const result = await func(source, ...this._initializer.args.map(parseResult));+ const result = await func(source, ...this._initializer.args);this._channel.resolve({ result: serializeArgument(result) }).catch(() => {});} catch (e) {this._channel.reject({ error: serializeError(e) }).catch(() => {});diff --git a/packages/playwright-core/src/client/worker.ts b/packages/playwright-core/src/client/worker.tsindex ee98e35779..e24f4faf89 100644--- a/packages/playwright-core/src/client/worker.ts+++ b/packages/playwright-core/src/client/worker.ts@@ -19,7 +19,7 @@ import { ChannelOwner } from './channelOwner';import { ConsoleMessage } from './consoleMessage';import { isTargetClosedError, TargetClosedError } from './errors';import { Events } from './events';-import { JSHandle, assertMaxArguments, parseResult, serializeArgument } from './jsHandle';+import { JSHandle, assertMaxArguments, serializeArgument } from './jsHandle';import { TimeoutSettings } from './timeoutSettings';import { Waiter } from './waiter';@@ -77,7 +77,7 @@ export class Worker extends ChannelOwner<channels.WorkerChannel> implements api.async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {assertMaxArguments(arguments.length, 2);const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });- return parseResult(result.value);+ return result.value;}async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {diff --git a/packages/playwright-core/src/protocol/serializers.ts b/packages/playwright-core/src/protocol/serializers.tsindex c6d0d926bc..f53e4af6a8 100644--- a/packages/playwright-core/src/protocol/serializers.ts+++ b/packages/playwright-core/src/protocol/serializers.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { SerializedValue } from '@protocol/channels';+import type { SerializedArgumentValue } from '@protocol/channels';-export function parseSerializedValue(value: SerializedValue, handles: any[] | undefined): any {- return innerParseSerializedValue(value, handles, new Map(), []);+export function parseSerializedValue(value: SerializedArgumentValue, handles: any[] | undefined): any {+ return innerParseSerializedArgumentValue(value, handles, new Map(), []);}-function innerParseSerializedValue(value: SerializedValue, handles: any[] | undefined, refs: Map<number, object>, accessChain: Array<string | number>): any {+function innerParseSerializedArgumentValue(value: SerializedArgumentValue, handles: any[] | undefined, refs: Map<number, object>, accessChain: Array<string | number>): any {if (value.ref !== undefined)return refs.get(value.ref);if (value.n !== undefined)@@ -66,14 +66,14 @@ function innerParseSerializedValue(value: SerializedValue, handles: any[] | undeconst result: any[] = [];refs.set(value.id!, result);for (let i = 0; i < value.a.length; i++)- result.push(innerParseSerializedValue(value.a[i], handles, refs, [...accessChain, i]));+ result.push(innerParseSerializedArgumentValue(value.a[i], handles, refs, [...accessChain, i]));return result;}if (value.o !== undefined) {const result: any = {};refs.set(value.id!, result);for (const { k, v } of value.o)- result[k] = innerParseSerializedValue(v, handles, refs, [...accessChain, k]);+ result[k] = innerParseSerializedArgumentValue(v, handles, refs, [...accessChain, k]);return result;}if (value.h !== undefined) {@@ -90,15 +90,15 @@ type VisitorInfo = {lastId: number;};-export function serializeValue(value: any, handleSerializer: (value: any) => HandleOrValue): SerializedValue {+export function serializeValue(value: any, handleSerializer: (value: any) => HandleOrValue): SerializedArgumentValue {return innerSerializeValue(value, handleSerializer, { lastId: 0, visited: new Map() }, []);}-export function serializePlainValue(arg: any): SerializedValue {+export function serializePlainValue(arg: any): SerializedArgumentValue {return serializeValue(arg, value => ({ fallThrough: value }));}-function innerSerializeValue(value: any, handleSerializer: (value: any) => HandleOrValue, visitorInfo: VisitorInfo, accessChain: Array<string | number>): SerializedValue {+function innerSerializeValue(value: any, handleSerializer: (value: any) => HandleOrValue, visitorInfo: VisitorInfo, accessChain: Array<string | number>): SerializedArgumentValue {const handle = handleSerializer(value);if ('fallThrough' in handle)value = handle.fallThrough;@@ -153,7 +153,7 @@ function innerSerializeValue(value: any, handleSerializer: (value: any) => Handlreturn { a, id };}if (typeof value === 'object') {- const o: { k: string, v: SerializedValue }[] = [];+ const o: { k: string, v: SerializedArgumentValue }[] = [];const id = ++visitorInfo.lastId;visitorInfo.visited.set(value, id);for (const name of Object.keys(value))@@ -192,7 +192,7 @@ function isError(obj: any): obj is Error {}-type TypedArrayKind = NonNullable<SerializedValue['ta']>['k'];+type TypedArrayKind = NonNullable<SerializedArgumentValue['ta']>['k'];const typedArrayKindToConstructor: Record<TypedArrayKind, Function> = {i8: Int8Array,ui8: Uint8Array,diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.tsindex c2e1b77177..1d643a548f 100644--- a/packages/playwright-core/src/protocol/validator.ts+++ b/packages/playwright-core/src/protocol/validator.ts@@ -16,7 +16,7 @@// This file is generated by generate_channels.js, do not edit manually.-import { scheme, tOptional, tObject, tBoolean, tInt, tFloat, tString, tAny, tEnum, tArray, tBinary, tChannel, tType } from './validatorPrimitives';+import { scheme, tOptional, tObject, tBoolean, tInt, tFloat, tString, tAny, tEnum, tArray, tBinary, tChannel, tType, tSerializedValue } from './validatorPrimitives';export type { Validator, ValidatorContext } from './validatorPrimitives';export { ValidationError, findValidator, maybeFindValidator, createMetadataValidator, createWaitInfoValidator } from './validatorPrimitives';@@ -1171,7 +1171,7 @@ scheme.ElectronApplicationEvaluateExpressionParams = tObject({arg: tType('SerializedArgument'),});scheme.ElectronApplicationEvaluateExpressionResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.ElectronApplicationEvaluateExpressionHandleParams = tObject({expression: tString,@@ -1212,7 +1212,7 @@ scheme.FrameEvalOnSelectorParams = tObject({arg: tType('SerializedArgument'),});scheme.FrameEvalOnSelectorResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.FrameEvalOnSelectorAllParams = tObject({selector: tString,@@ -1221,7 +1221,7 @@ scheme.FrameEvalOnSelectorAllParams = tObject({arg: tType('SerializedArgument'),});scheme.FrameEvalOnSelectorAllResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.FrameAddScriptTagParams = tObject({url: tOptional(tString),@@ -1340,7 +1340,7 @@ scheme.FrameEvaluateExpressionParams = tObject({arg: tType('SerializedArgument'),});scheme.FrameEvaluateExpressionResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.FrameEvaluateExpressionHandleParams = tObject({expression: tString,@@ -1624,7 +1624,7 @@ scheme.FrameExpectParams = tObject({scheme.FrameExpectResult = tObject({matches: tBoolean,received: tOptional(tObject({- value: tOptional(tType('SerializedValue')),+ value: tOptional(tSerializedValue),ariaSnapshot: tOptional(tString),})),timedOut: tOptional(tBoolean),@@ -1649,7 +1649,7 @@ scheme.JSHandleEvaluateExpressionParams = tObject({});scheme.ElementHandleEvaluateExpressionParams = tType('JSHandleEvaluateExpressionParams');scheme.JSHandleEvaluateExpressionResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.ElementHandleEvaluateExpressionResult = tType('JSHandleEvaluateExpressionResult');scheme.JSHandleEvaluateExpressionHandleParams = tObject({@@ -1682,7 +1682,7 @@ scheme.ElementHandleGetPropertyResult = tType('JSHandleGetPropertyResult');scheme.JSHandleJsonValueParams = tOptional(tObject({}));scheme.ElementHandleJsonValueParams = tType('JSHandleJsonValueParams');scheme.JSHandleJsonValueResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.ElementHandleJsonValueResult = tType('JSHandleJsonValueResult');scheme.ElementHandleInitializer = tObject({@@ -1696,7 +1696,7 @@ scheme.ElementHandleEvalOnSelectorParams = tObject({arg: tType('SerializedArgument'),});scheme.ElementHandleEvalOnSelectorResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.ElementHandleEvalOnSelectorAllParams = tObject({selector: tString,@@ -1705,7 +1705,7 @@ scheme.ElementHandleEvalOnSelectorAllParams = tObject({arg: tType('SerializedArgument'),});scheme.ElementHandleEvalOnSelectorAllResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.ElementHandleBoundingBoxParams = tOptional(tObject({}));scheme.ElementHandleBoundingBoxResult = tObject({@@ -2907,7 +2907,7 @@ scheme.CDPSessionDetachResult = tOptional(tObject({}));scheme.BindingCallInitializer = tObject({frame: tChannel(['Frame']),name: tString,- args: tArray(tType('SerializedValue')),+ args: tArray(tSerializedValue),});scheme.BindingCallRejectParams = tObject({error: tType('SerializedError'),@@ -2955,7 +2955,7 @@ scheme.DialogAcceptParams = tObject({scheme.DialogAcceptResult = tOptional(tObject({}));scheme.DialogDismissParams = tOptional(tObject({}));scheme.DialogDismissResult = tOptional(tObject({}));-scheme.SerializedValue = tObject({+scheme.SerializedArgumentValue = tObject({n: tOptional(tFloat),b: tOptional(tBoolean),s: tOptional(tString),@@ -2976,17 +2976,17 @@ scheme.SerializedValue = tObject({p: tString,f: tString,})),- a: tOptional(tArray(tType('SerializedValue'))),+ a: tOptional(tArray(tType('SerializedArgumentValue'))),o: tOptional(tArray(tObject({k: tString,- v: tType('SerializedValue'),+ v: tType('SerializedArgumentValue'),}))),h: tOptional(tInt),id: tOptional(tInt),ref: tOptional(tInt),});scheme.SerializedArgument = tObject({- value: tType('SerializedValue'),+ value: tType('SerializedArgumentValue'),handles: tArray(tChannel('*')),});scheme.SerializedError = tObject({@@ -2995,7 +2995,7 @@ scheme.SerializedError = tObject({name: tString,stack: tOptional(tString),})),- value: tOptional(tType('SerializedValue')),+ value: tOptional(tSerializedValue),});scheme.StackFrame = tObject({file: tString,@@ -3102,7 +3102,7 @@ scheme.WorkerEvaluateExpressionParams = tObject({arg: tType('SerializedArgument'),});scheme.WorkerEvaluateExpressionResult = tObject({- value: tType('SerializedValue'),+ value: tSerializedValue,});scheme.WorkerEvaluateExpressionHandleParams = tObject({expression: tString,diff --git a/packages/playwright-core/src/protocol/validatorPrimitives.ts b/packages/playwright-core/src/protocol/validatorPrimitives.tsindex ba15b856d8..a2afe7c348 100644--- a/packages/playwright-core/src/protocol/validatorPrimitives.ts+++ b/packages/playwright-core/src/protocol/validatorPrimitives.ts@@ -14,11 +14,14 @@* limitations under the License.*/+import { parseSerializedValue, serializeValue } from './serializers';+export class ValidationError extends Error {}export type Validator = (arg: any, path: string, context: ValidatorContext) => any;export type ValidatorContext = {tChannelImpl: (names: '*' | string[], arg: any, path: string, context: ValidatorContext) => any;- binary: 'toBase64' | 'fromBase64' | 'buffer';+ direction: 'toWire' | 'fromWire';+ rawBuffers?: boolean;isUnderTest: () => boolean;};export const scheme: { [key: string]: Validator } = {};@@ -74,25 +77,32 @@ export const tString: Validator = (arg: any, path: string, context: ValidatorConthrow new ValidationError(`${path}: expected string, got ${typeof arg}`);};export const tBinary: Validator = (arg: any, path: string, context: ValidatorContext) => {- if (context.binary === 'fromBase64') {+ if (context.rawBuffers) {+ // TODO: support custom binary types.+ if (!(arg instanceof Buffer) && !(arg instanceof Object))+ throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);+ return arg;+ }+ if (context.direction === 'fromWire') {if (arg instanceof String)return Buffer.from(arg.valueOf(), 'base64');if (typeof arg === 'string')return Buffer.from(arg, 'base64');throw new ValidationError(`${path}: expected base64-encoded buffer, got ${typeof arg}`);}- if (context.binary === 'toBase64') {+ if (context.direction === 'toWire') {if (!(arg instanceof Buffer))throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);return (arg as Buffer).toString('base64');}- if (context.binary === 'buffer') {- // TODO: support custom binary types.- if (!(arg instanceof Buffer) && !(arg instanceof Object))- throw new ValidationError(`${path}: expected Buffer, got ${typeof arg}`);- return arg;- }- throw new ValidationError(`Unsupported binary behavior "${context.binary}"`);+ throw new ValidationError(`Unsupported direction "${context.direction}"`);+};+export const tSerializedValue: Validator = (arg: any, path: string, context: ValidatorContext) => {+ if (context.direction === 'toWire')+ return serializeValue(arg, value => ({ fallThrough: value }));+ if (context.direction === 'fromWire')+ return parseSerializedValue(arg, undefined);+ throw new ValidationError(`Unsupported direction "${context.direction}"`);};export const tUndefined: Validator = (arg: any, path: string, context: ValidatorContext) => {if (Object.is(arg, undefined))diff --git a/packages/playwright-core/src/server/dispatchers/dispatcher.ts b/packages/playwright-core/src/server/dispatchers/dispatcher.tsindex 7e91fc1e7f..660e6221a1 100644--- a/packages/playwright-core/src/server/dispatchers/dispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/dispatcher.ts@@ -229,7 +229,8 @@ export class DispatcherConnection {private _validatorToWireContext(): ValidatorContext {return {tChannelImpl: this._tChannelImplToWire.bind(this),- binary: this._isLocal ? 'buffer' : 'toBase64',+ direction: 'toWire',+ rawBuffers: this._isLocal,isUnderTest,};}@@ -237,7 +238,8 @@ export class DispatcherConnection {private _validatorFromWireContext(): ValidatorContext {return {tChannelImpl: this._tChannelImplFromWire.bind(this),- binary: this._isLocal ? 'buffer' : 'fromBase64',+ direction: 'fromWire',+ rawBuffers: this._isLocal,isUnderTest,};}@@ -358,7 +360,7 @@ export class DispatcherConnection {const result = await dispatcher._runCommand(callMetadata, method, validParams);const validator = findValidator(dispatcher._type, method, 'Result');response.result = validator(result, '', this._validatorToWireContext());- callMetadata.result = result;+ callMetadata.result = response.result; // Use the wire-format result for the trace recorder.} catch (e) {if (isTargetClosedError(e)) {const reason = sdkObject.closeReason();diff --git a/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts b/packages/playwright-core/src/server/dispatchers/electronDispatcher.tsindex 4dcf68d0d1..7fdb16befb 100644--- a/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/electronDispatcher.ts@@ -16,7 +16,7 @@import { BrowserContextDispatcher } from './browserContextDispatcher';import { Dispatcher } from './dispatcher';-import { JSHandleDispatcher, parseArgument, serializeResult } from './jsHandleDispatcher';+import { JSHandleDispatcher, parseArgument } from './jsHandleDispatcher';import { ElectronApplication } from '../electron/electron';import type { RootDispatcher } from './dispatcher';@@ -77,7 +77,7 @@ export class ElectronApplicationDispatcher extends Dispatcher<ElectronApplicatioasync evaluateExpression(params: channels.ElectronApplicationEvaluateExpressionParams, progress: Progress): Promise<channels.ElectronApplicationEvaluateExpressionResult> {const handle = await progress.race(this._object._nodeElectronHandlePromise);- return { value: serializeResult(await handle.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) };+ return { value: await handle.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)) };}async evaluateExpressionHandle(params: channels.ElectronApplicationEvaluateExpressionHandleParams, progress: Progress): Promise<channels.ElectronApplicationEvaluateExpressionHandleResult> {diff --git a/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts b/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.tsindex 899c71a0db..8706bf6a3a 100644--- a/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/elementHandlerDispatcher.ts@@ -16,7 +16,7 @@import { BrowserContextDispatcher } from './browserContextDispatcher';import { FrameDispatcher } from './frameDispatcher';-import { JSHandleDispatcher, parseArgument, serializeResult } from './jsHandleDispatcher';+import { JSHandleDispatcher, parseArgument } from './jsHandleDispatcher';import type { ElementHandle } from '../dom';import type { Frame } from '../frames';@@ -197,11 +197,11 @@ export class ElementHandleDispatcher extends JSHandleDispatcher<FrameDispatcher>}async evalOnSelector(params: channels.ElementHandleEvalOnSelectorParams, progress: Progress): Promise<channels.ElementHandleEvalOnSelectorResult> {- return { value: serializeResult(await this._elementHandle.evalOnSelector(progress, params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg))) };+ return { value: await this._elementHandle.evalOnSelector(progress, params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg)) };}async evalOnSelectorAll(params: channels.ElementHandleEvalOnSelectorAllParams, progress: Progress): Promise<channels.ElementHandleEvalOnSelectorAllResult> {- return { value: serializeResult(await this._elementHandle.evalOnSelectorAll(progress, params.selector, params.expression, params.isFunction, parseArgument(params.arg))) };+ return { value: await this._elementHandle.evalOnSelectorAll(progress, params.selector, params.expression, params.isFunction, parseArgument(params.arg)) };}async waitForElementState(params: channels.ElementHandleWaitForElementStateParams, progress: Progress): Promise<void> {diff --git a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts b/packages/playwright-core/src/server/dispatchers/frameDispatcher.tsindex 9c038ccc20..29cf5587ec 100644--- a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts@@ -20,7 +20,7 @@ import { renderTitleForCall } from '@isomorphic/protocolFormatter';import { Frame } from '../frames';import { Dispatcher } from './dispatcher';import { ElementHandleDispatcher } from './elementHandlerDispatcher';-import { parseArgument, serializeResult } from './jsHandleDispatcher';+import { parseArgument } from './jsHandleDispatcher';import { ResponseDispatcher } from './networkDispatchers';import { RequestDispatcher } from './networkDispatchers';import type { Progress } from '../progress';@@ -84,7 +84,7 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Br}async evaluateExpression(params: channels.FrameEvaluateExpressionParams, progress: Progress): Promise<channels.FrameEvaluateExpressionResult> {- return { value: serializeResult(await this._frame.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg))) };+ return { value: await this._frame.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg)) };}async evaluateExpressionHandle(params: channels.FrameEvaluateExpressionHandleParams, progress: Progress): Promise<channels.FrameEvaluateExpressionHandleResult> {@@ -100,11 +100,11 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Br}async evalOnSelector(params: channels.FrameEvalOnSelectorParams, progress: Progress): Promise<channels.FrameEvalOnSelectorResult> {- return { value: serializeResult(await this._frame.evalOnSelector(progress, params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg))) };+ return { value: await this._frame.evalOnSelector(progress, params.selector, !!params.strict, params.expression, params.isFunction, parseArgument(params.arg)) };}async evalOnSelectorAll(params: channels.FrameEvalOnSelectorAllParams, progress: Progress): Promise<channels.FrameEvalOnSelectorAllResult> {- return { value: serializeResult(await this._frame.evalOnSelectorAll(progress, params.selector, params.expression, params.isFunction, parseArgument(params.arg))) };+ return { value: await this._frame.evalOnSelectorAll(progress, params.selector, params.expression, params.isFunction, parseArgument(params.arg)) };}async querySelector(params: channels.FrameQuerySelectorParams, progress: Progress): Promise<channels.FrameQuerySelectorResult> {@@ -277,19 +277,6 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Brif (params.expression === 'to.match.aria' && expectedValue)expectedValue = parseAriaSnapshotUnsafe(yaml, expectedValue);progress.log(`${renderTitleForCall(progress.metadata)}${params.timeout ? ` with timeout ${params.timeout}ms` : ''}`);- const result = await this._frame.expect(progress, params.selector, { ...params, expectedValue });- const channelResult: channels.FrameExpectResult = {- matches: result.matches,- log: result.log,- timedOut: result.timedOut,- errorMessage: result.errorMessage,- };- if (result.received !== undefined) {- channelResult.received = {- value: result.received.value !== undefined ? serializeResult(result.received.value) : undefined,- ariaSnapshot: result.received.ariaSnapshot,- };- }- return channelResult;+ return await this._frame.expect(progress, params.selector, { ...params, expectedValue });}}diff --git a/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts b/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.tsindex 0155587d1a..b7c1bcacf1 100644--- a/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/jsHandleDispatcher.ts@@ -16,7 +16,7 @@import { Dispatcher } from './dispatcher';import { ElementHandleDispatcher } from './elementHandlerDispatcher';-import { parseSerializedValue, serializeValue } from '../../protocol/serializers';+import { parseSerializedValue } from '../../protocol/serializers';import type * as js from '../javascript';import type { ElectronApplicationDispatcher } from './electronDispatcher';@@ -44,7 +44,7 @@ export class JSHandleDispatcher<ParentScope extends JSHandleDispatcherParentScopasync evaluateExpression(params: channels.JSHandleEvaluateExpressionParams, progress: Progress): Promise<channels.JSHandleEvaluateExpressionResult> {const jsHandle = await this._object.evaluateExpression(progress, params.expression, { isFunction: params.isFunction }, parseArgument(params.arg));- return { value: serializeResult(jsHandle) };+ return { value: jsHandle };}async evaluateExpressionHandle(params: channels.JSHandleEvaluateExpressionHandleParams, progress: Progress): Promise<channels.JSHandleEvaluateExpressionHandleResult> {@@ -70,7 +70,7 @@ export class JSHandleDispatcher<ParentScope extends JSHandleDispatcherParentScop}async jsonValue(params: channels.JSHandleJsonValueParams, progress: Progress): Promise<channels.JSHandleJsonValueResult> {- return { value: serializeResult(await this._object.jsonValue(progress)) };+ return { value: await this._object.jsonValue(progress) };}async dispose(_: any, progress: Progress) {@@ -84,11 +84,3 @@ export class JSHandleDispatcher<ParentScope extends JSHandleDispatcherParentScopexport function parseArgument(arg: channels.SerializedArgument): any {return parseSerializedValue(arg.value, arg.handles.map(a => (a as JSHandleDispatcher)._object));}--export function parseValue(v: channels.SerializedValue): any {- return parseSerializedValue(v, []);-}--export function serializeResult(arg: any): channels.SerializedValue {- return serializeValue(arg, value => ({ fallThrough: value }));-}diff --git a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts b/packages/playwright-core/src/server/dispatchers/pageDispatcher.tsindex 1e2e7d0c0f..d8ba2b63ca 100644--- a/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/pageDispatcher.ts@@ -22,7 +22,7 @@ import { parseError, serializeError } from '../errors';import { ArtifactDispatcher } from './artifactDispatcher';import { ElementHandleDispatcher } from './elementHandlerDispatcher';import { FrameDispatcher } from './frameDispatcher';-import { JSHandleDispatcher, parseArgument, serializeResult } from './jsHandleDispatcher';+import { JSHandleDispatcher, parseArgument } from './jsHandleDispatcher';import { RequestDispatcher } from './networkDispatchers';import { ResponseDispatcher } from './networkDispatchers';import { RouteDispatcher, WebSocketDispatcher } from './networkDispatchers';@@ -545,7 +545,7 @@ export class WorkerDispatcher extends Dispatcher<Worker, channels.WorkerChannel,}async evaluateExpression(params: channels.WorkerEvaluateExpressionParams, progress: Progress): Promise<channels.WorkerEvaluateExpressionResult> {- return { value: serializeResult(await this._object.evaluateExpression(progress, params.expression, params.isFunction, parseArgument(params.arg))) };+ return { value: await this._object.evaluateExpression(progress, params.expression, params.isFunction, parseArgument(params.arg)) };}async evaluateExpressionHandle(params: channels.WorkerEvaluateExpressionHandleParams, progress: Progress): Promise<channels.WorkerEvaluateExpressionHandleResult> {@@ -571,7 +571,7 @@ export class BindingCallDispatcher extends Dispatcher<SdkObject, channels.Bindinsuper(scope, new SdkObject(scope._object, 'bindingCall'), 'BindingCall', {frame: frameDispatcher,name,- args: args.map(serializeResult),+ args,});this._promise = new Promise((resolve, reject) => {this._resolve = resolve;diff --git a/packages/playwright-core/src/server/socksInterceptor.ts b/packages/playwright-core/src/server/socksInterceptor.tsindex c410ff19bc..7e5df6b152 100644--- a/packages/playwright-core/src/server/socksInterceptor.ts+++ b/packages/playwright-core/src/server/socksInterceptor.ts@@ -43,7 +43,7 @@ export class SocksInterceptor {const id = --lastId;this._ids.add(id);const validator = findValidator('SocksSupport', prop, 'Params');- params = validator(params, '', { tChannelImpl: tChannelForSocks, binary: 'toBase64', isUnderTest });+ params = validator(params, '', { tChannelImpl: tChannelForSocks, direction: 'toWire', isUnderTest });transport.send({ id, guid: this._socksSupportObjectGuid, method: prop, params, metadata: { stack: [], apiName: '', internal: true } } as any);} catch (e) {}@@ -75,7 +75,7 @@ export class SocksInterceptor {}if (this._socksSupportObjectGuid && message.guid === this._socksSupportObjectGuid) {const validator = findValidator('SocksSupport', message.method, 'Event');- const params = validator(message.params, '', { tChannelImpl: tChannelForSocks, binary: 'fromBase64', isUnderTest });+ const params = validator(message.params, '', { tChannelImpl: tChannelForSocks, direction: 'fromWire', isUnderTest });this._channel.emit(message.method, params);return true;}diff --git a/packages/protocol/spec/serialized.yml b/packages/protocol/spec/serialized.ymlindex 1457d5f891..2046064a41 100644--- a/packages/protocol/spec/serialized.yml+++ b/packages/protocol/spec/serialized.yml@@ -12,7 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.-SerializedValue:+SerializedArgumentValue:type: object# Exactly one of the properties must be present.properties:@@ -68,7 +68,7 @@ SerializedValue:f: stringa:type: array?- items: SerializedValue+ items: SerializedArgumentValue# Object with keys and values.o:type: array?@@ -76,7 +76,7 @@ SerializedValue:type: objectproperties:k: string- v: SerializedValue+ v: SerializedArgumentValue# An index in the handles array from SerializedArgument.h: int?# Index of the object in value-type for circular reference resolution.@@ -87,7 +87,7 @@ SerializedValue:SerializedArgument:type: objectproperties:- value: SerializedValue+ value: SerializedArgumentValuehandles:type: arrayitems: Channeldiff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.tsindex d3acc2cc95..11443e0976 100644--- a/packages/protocol/src/channels.d.ts+++ b/packages/protocol/src/channels.d.ts@@ -20,6 +20,7 @@ import type { CallMetadata } from './callMetadata';import type { Progress } from './progress';export type Binary = Buffer;+export type UnserializedValue = any;export interface Channel {}@@ -2217,7 +2218,7 @@ export type ElectronApplicationEvaluateExpressionOptions = {isFunction?: boolean,};export type ElectronApplicationEvaluateExpressionResult = {- value: SerializedValue,+ value: UnserializedValue,};export type ElectronApplicationEvaluateExpressionHandleParams = {expression: string,@@ -2331,7 +2332,7 @@ export type FrameEvalOnSelectorOptions = {isFunction?: boolean,};export type FrameEvalOnSelectorResult = {- value: SerializedValue,+ value: UnserializedValue,};export type FrameEvalOnSelectorAllParams = {selector: string,@@ -2343,7 +2344,7 @@ export type FrameEvalOnSelectorAllOptions = {isFunction?: boolean,};export type FrameEvalOnSelectorAllResult = {- value: SerializedValue,+ value: UnserializedValue,};export type FrameAddScriptTagParams = {url?: string,@@ -2539,7 +2540,7 @@ export type FrameEvaluateExpressionOptions = {isFunction?: boolean,};export type FrameEvaluateExpressionResult = {- value: SerializedValue,+ value: UnserializedValue,};export type FrameEvaluateExpressionHandleParams = {expression: string,@@ -2966,7 +2967,7 @@ export type FrameExpectOptions = {export type FrameExpectResult = {matches: boolean,received?: {- value?: SerializedValue,+ value?: UnserializedValue,ariaSnapshot?: string,},timedOut?: boolean,@@ -3010,7 +3011,7 @@ export type JSHandleEvaluateExpressionOptions = {isFunction?: boolean,};export type JSHandleEvaluateExpressionResult = {- value: SerializedValue,+ value: UnserializedValue,};export type JSHandleEvaluateExpressionHandleParams = {expression: string,@@ -3043,7 +3044,7 @@ export type JSHandleGetPropertyResult = {export type JSHandleJsonValueParams = {};export type JSHandleJsonValueOptions = {};export type JSHandleJsonValueResult = {- value: SerializedValue,+ value: UnserializedValue,};export interface JSHandleEvents {@@ -3105,7 +3106,7 @@ export type ElementHandleEvalOnSelectorOptions = {isFunction?: boolean,};export type ElementHandleEvalOnSelectorResult = {- value: SerializedValue,+ value: UnserializedValue,};export type ElementHandleEvalOnSelectorAllParams = {selector: string,@@ -3117,7 +3118,7 @@ export type ElementHandleEvalOnSelectorAllOptions = {isFunction?: boolean,};export type ElementHandleEvalOnSelectorAllResult = {- value: SerializedValue,+ value: UnserializedValue,};export type ElementHandleBoundingBoxParams = {};export type ElementHandleBoundingBoxOptions = {};@@ -5139,7 +5140,7 @@ export interface CDPSessionEvents {export type BindingCallInitializer = {frame: FrameChannel,name: string,- args: SerializedValue[],+ args: UnserializedValue[],};export interface BindingCallEventTarget {}@@ -5242,7 +5243,7 @@ export type DialogDismissResult = void;export interface DialogEvents {}-export type SerializedValue = {+export type SerializedArgumentValue = {n?: number,b?: boolean,s?: string,@@ -5263,10 +5264,10 @@ export type SerializedValue = {p: string,f: string,},- a?: SerializedValue[],+ a?: SerializedArgumentValue[],o?: {k: string,- v: SerializedValue,+ v: SerializedArgumentValue,}[],h?: number,id?: number,@@ -5274,7 +5275,7 @@ export type SerializedValue = {};export type SerializedArgument = {- value: SerializedValue,+ value: SerializedArgumentValue,handles: Channel[],};@@ -5284,7 +5285,7 @@ export type SerializedError = {name: string,stack?: string,},- value?: SerializedValue,+ value?: UnserializedValue,};export type StackFrame = {@@ -5461,7 +5462,7 @@ export type WorkerEvaluateExpressionOptions = {isFunction?: boolean,};export type WorkerEvaluateExpressionResult = {- value: SerializedValue,+ value: UnserializedValue,};export type WorkerEvaluateExpressionHandleParams = {expression: string,diff --git a/packages/trace-viewer/src/ui/callTab.tsx b/packages/trace-viewer/src/ui/callTab.tsxindex 69da4e94c1..38e7cd092a 100644--- a/packages/trace-viewer/src/ui/callTab.tsx+++ b/packages/trace-viewer/src/ui/callTab.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import type { SerializedValue } from '@protocol/channels';+import type { SerializedArgumentValue } from '@protocol/channels';import type { ActionTraceEvent } from '@trace/trace';import { clsx } from '@web/uiUtils';import { msToString } from '@isomorphic/formatUtils';@@ -127,7 +127,7 @@ function propertyToString(event: ActionTraceEvent, name: string, value: any, sdkreturn { text: JSON.stringify(value), type: 'object', name };}-function parseSerializedValue(value: SerializedValue, handles: any[] | undefined): any {+function parseSerializedValue(value: SerializedArgumentValue, handles: any[] | undefined): any {if (value.n !== undefined)return value.n;if (value.s !== undefined)diff --git a/utils/generate_channels.js b/utils/generate_channels.jsindex cd33d24177..82e1fca406 100755--- a/utils/generate_channels.js+++ b/utils/generate_channels.js@@ -40,6 +40,8 @@ function inlineType(type, indent, wrapEnums = false) {return { ts: 'Binary', scheme: 'tBinary', optional };if (type === 'json')return { ts: 'any', scheme: 'tAny', optional };+ if (type === 'SerializedValue')+ return { ts: 'UnserializedValue', scheme: 'tSerializedValue', optional };if (['string', 'boolean', 'undefined'].includes(type))return { ts: type, scheme: `t${titleCase(type)}`, optional };if (type === 'number')@@ -132,6 +134,7 @@ import type { CallMetadata } from './callMetadata';import type { Progress } from './progress';export type Binary = Buffer;+export type UnserializedValue = any;export interface Channel {}@@ -156,7 +159,7 @@ const validator_ts = [// This file is generated by ${path.basename(__filename)}, do not edit manually.-import { scheme, tOptional, tObject, tBoolean, tInt, tFloat, tString, tAny, tEnum, tArray, tBinary, tChannel, tType } from './validatorPrimitives';+import { scheme, tOptional, tObject, tBoolean, tInt, tFloat, tString, tAny, tEnum, tArray, tBinary, tChannel, tType, tSerializedValue } from './validatorPrimitives';export type { Validator, ValidatorContext } from './validatorPrimitives';export { ValidationError, findValidator, maybeFindValidator, createMetadataValidator, createWaitInfoValidator } from './validatorPrimitives';`];