diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java index 9d4f42379..d6377c8a4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -14,73 +14,105 @@ * limitations under the License. */ +// Port of fetch.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.*; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSyntaxException; import com.microsoft.playwright.APIRequestContext; import com.microsoft.playwright.APIResponse; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.Request; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.Cookie; import com.microsoft.playwright.options.FilePayload; import com.microsoft.playwright.options.RequestOptions; -import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Base64; +import java.util.Arrays; import java.util.Collections; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import static com.microsoft.playwright.impl.Serialization.*; -import static com.microsoft.playwright.impl.Utils.toFilePayload; -import static com.microsoft.playwright.impl.Utils.toProtocol; -import static java.util.Arrays.asList; +import static com.microsoft.playwright.impl.Errors.isTargetClosedError; +import static com.microsoft.playwright.impl.isomorphic.Headers.headersObjectToArray; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Serialization.jsonDataSerializer; +import static com.microsoft.playwright.impl.Serialization.toClearCookiesParams; public class APIRequestContextImpl extends ChannelOwner implements APIRequestContext { - private final TracingImpl tracing; - private String disposeReason; - - protected TimeoutSettings timeoutSettings = new TimeoutSettings(); + APIRequestImpl request; + final TracingImpl tracing; + private String closeReason; + TimeoutSettings timeoutSettings; final APIRequestContextChannel channel = new APIRequestContextChannel(this); + // java: from is not ported, generated results already hold the impl object. + APIRequestContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - this.tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString()); + this.tracing = connection.protocolGson().fromJson(initializer, APIRequestContextInitializer.class).tracing; + this.timeoutSettings = new TimeoutSettings(); } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + @Override - public TracingImpl tracing() { - return tracing; + public void dispose(DisposeOptions options) { + if (options == null) { + options = new DisposeOptions(); + } + closeReason = options.reason; + instrumentation.runBeforeCloseRequestContext(this); + tracing.exportAllHars(); + try { + APIRequestContextDisposeParams params = new APIRequestContextDisposeParams(); + params.reason = options.reason; + channel.dispose(params, NO_TIMEOUT); + } catch (PlaywrightException e) { + if (isTargetClosedError(e)) { + return; + } + throw e; + } + tracing.resetStackCounter(); + if (request != null) { + request.contexts.remove(this); + } } + // java: the string | string[] parameter is two overloads, a null url means all cookies. @Override - public List cookies(String url) { - return cookies(url == null ? new ArrayList<>() : Collections.singletonList(url)); + public List cookies(String urls) { + return cookies(urls == null ? Collections.emptyList() : Collections.singletonList(urls)); } @Override public List cookies(List urls) { - APIRequestContextCookiesParams params = new APIRequestContextCookiesParams(); if (urls == null) { urls = new ArrayList<>(); } + APIRequestContextCookiesParams params = new APIRequestContextCookiesParams(); params.urls = urls; - APIRequestContextCookiesResult result = channel.cookies(params, NO_TIMEOUT); - Cookie[] cookies = gson().fromJson(gson().toJsonTree(result.cookies), Cookie[].class); - return asList(cookies); + List cookies = channel.cookies(params, NO_TIMEOUT).cookies; + // java: the protocol cookies are converted to the API type. + return Arrays.asList(gson().fromJson(gson().toJsonTree(cookies), Cookie[].class)); } @Override public void addCookies(List cookies) { APIRequestContextAddCookiesParams params = new APIRequestContextAddCookiesParams(); - params.cookies = gson().fromJson(gson().toJsonTree(cookies), new TypeToken>() {}.getType()); + // java: the API cookies are converted to the protocol type. + params.cookies = new ArrayList<>(); + for (Cookie cookie : cookies) { + params.cookies.add(Utils.toProtocol(cookie, SetNetworkCookie.class)); + } channel.addCookies(params, NO_TIMEOUT); } @@ -89,217 +121,180 @@ public void clearCookies(ClearCookiesOptions options) { if (options == null) { options = new ClearCookiesOptions(); } - APIRequestContextClearCookiesParams params = gson().fromJson( + // java: toClearCookiesParams of network.ts is the seed Serialization.toClearCookiesParams. + APIRequestContextClearCookiesParams params = connection.protocolGson().fromJson( toClearCookiesParams(options.name, options.domain, options.path), APIRequestContextClearCookiesParams.class); channel.clearCookies(params, NO_TIMEOUT); } @Override public APIResponse delete(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "DELETE")); + return fetch(url, withMethod(options, "DELETE")); } @Override - public void dispose(DisposeOptions options) { - if (options == null) { - options = new DisposeOptions(); - } - disposeReason = options.reason; - try { - channel.dispose(toProtocol(options, APIRequestContextDisposeParams.class), NO_TIMEOUT); - } catch (TargetClosedError e) { - return; - } - tracing.resetStackCounter(); + public APIResponse head(String url, RequestOptions options) { + return fetch(url, withMethod(options, "HEAD")); + } + + @Override + public APIResponse get(String url, RequestOptions options) { + return fetch(url, withMethod(options, "GET")); + } + + @Override + public APIResponse patch(String url, RequestOptions options) { + return fetch(url, withMethod(options, "PATCH")); } + @Override + public APIResponse post(String url, RequestOptions options) { + return fetch(url, withMethod(options, "POST")); + } + + @Override + public APIResponse put(String url, RequestOptions options) { + return fetch(url, withMethod(options, "PUT")); + } + + // java: the string | Request parameter is two overloads. @Override public APIResponse fetch(String urlOrRequest, RequestOptions options) { - return fetchImpl(urlOrRequest, (RequestOptionsImpl) options); + return wrapApiCall(() -> innerFetch(urlOrRequest, null, (RequestOptionsImpl) options, null), null, false); } @Override - public APIResponse fetch(Request request, RequestOptions optionsArg) { - RequestOptionsImpl options = (RequestOptionsImpl) optionsArg; + public APIResponse fetch(Request urlOrRequest, RequestOptions options) { + return wrapApiCall(() -> innerFetch(null, urlOrRequest, (RequestOptionsImpl) options, null), null, false); + } + + // java: upstream takes one object { url, request, ...options }. RequestOptions holds the object form of + // params only; paramsString is the string or URLSearchParams form, which RequestOptions has no setter for. + APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl options, String paramsString) { if (options == null) { options = new RequestOptionsImpl(); } - if (options.method == null) { - options.method = request.method(); + if (closeReason != null) { + throw new TargetClosedError(closeReason); } - if (options.headers == null) { - options.headers = request.headers(); + if (request == null && url == null) { + throw new PlaywrightException("First argument must be either URL string or Request"); } - if (options.data == null && options.form == null && options.multipart == null) { - options.data = request.postDataBuffer(); + if ((options.data == null ? 0 : 1) + (options.form == null ? 0 : 1) + (options.multipart == null ? 0 : 1) > 1) { + throw new PlaywrightException("Only one of 'data', 'form' or 'multipart' can be specified"); } - return fetch(request.url(), options); - } - - private APIResponse fetchImpl(String url, RequestOptionsImpl options) { - if (disposeReason != null) { - throw new PlaywrightException(disposeReason); + if (options.maxRedirects != null && options.maxRedirects < 0) { + throw new PlaywrightException("'maxRedirects' must be greater than or equal to '0'"); } - if (options == null) { - options = new RequestOptionsImpl(); + if (options.maxRetries != null && options.maxRetries < 0) { + throw new PlaywrightException("'maxRetries' must be greater than or equal to '0'"); } - options.timeout = timeoutSettings.timeout(options.timeout); - APIRequestContextFetchParams params = new APIRequestContextFetchParams(); - params.url = url; - if (options.params != null) { - Map queryParams = new LinkedHashMap<>(); - for (Map.Entry e : options.params.entrySet()) { - queryParams.put(e.getKey(), "" + e.getValue()); - } - params.params = toNameValues(toNameValueArray(queryParams.entrySet())); + if (url == null) { + url = request.url(); } - params.method = options.method; - if (options.headers != null) { - params.headers = toNameValues(Serialization.toProtocol(options.headers)); + String method = options.method != null ? options.method : (request != null ? request.method() : null); + String encodedParams = null; + // java: a URLSearchParams is its toString() in paramsString too. + if (paramsString != null) { + encodedParams = paramsString; } - + // Cannot call allHeaders() here as the request may be paused inside route handler. + Map headersObj = options.headers != null ? options.headers : (request != null ? request.headers() : null); + List headers = headersObj != null ? headersObjectToArray(headersObj) : null; + String jsonData = null; + List formData = null; + List multipartData = null; + byte[] postDataBuffer = null; if (options.data != null) { - byte[] bytes = null; - if (options.data instanceof byte[]) { - bytes = (byte[]) options.data; - } else if (options.data instanceof String) { - String stringData = (String) options.data; - if (!isJsonContentType(options.headers) || isJsonParsable(stringData)) { - bytes = (stringData).getBytes(StandardCharsets.UTF_8); + if (options.data instanceof String) { + String data = (String) options.data; + if (APIResponseImpl.isJsonContentType(headers)) { + jsonData = isJsonParsable(data) ? data : jsonDataSerializer.toJson(data); + } else { + postDataBuffer = data.getBytes(StandardCharsets.UTF_8); } - } - if (bytes == null) { - params.jsonData = jsonDataSerializer.toJson(options.data); + } else if (options.data instanceof byte[]) { + postDataBuffer = (byte[]) options.data; } else { - params.postData = bytes; + // java: every other Java value is an object, a number or a boolean, so there is no "Unexpected 'data' type" error. + jsonData = jsonDataSerializer.toJson(options.data); + } + } else if (options.form != null) { + // java: FormData is the only form type of the Java API. + formData = new ArrayList<>(); + for (FormDataImpl.Field field : options.form.fields) { + if (field.value instanceof FilePayload || field.value instanceof Path) { + throw new PlaywrightException("Expected string for options.form[\"" + field.name + "\"], found File. Please use options.multipart instead."); + } + formData.add(nameValue(field.name, String.valueOf(field.value))); + } + } else if (options.multipart != null) { + multipartData = new ArrayList<>(); + // Convert file-like values to ServerFilePayload structs. + for (FormDataImpl.Field field : options.multipart.fields) { + multipartData.add(toFormField(field.name, field.value)); } } - if (options.form != null) { - params.formData = toNameValues(toNameValueArray(options.form.fields)); - } - if (options.multipart != null) { - params.multipartData = serializeMultipartData(options.multipart.fields); + if (postDataBuffer == null && jsonData == null && formData == null && multipartData == null) { + postDataBuffer = request != null ? request.postDataBuffer() : null; } + // java: no __testHookLookup fixture, a test hook function cannot be sent to the driver from Java. + APIRequestContextFetchParams params = new APIRequestContextFetchParams(); + params.url = url; + params.params = APIResponseImpl.objectToArray(options.params); + params.encodedParams = encodedParams; + params.method = method; + params.headers = headers; + params.postData = postDataBuffer; + params.jsonData = jsonData; + params.formData = formData; + params.multipartData = multipartData; params.failOnStatusCode = options.failOnStatusCode; params.ignoreHTTPSErrors = options.ignoreHTTPSErrors; - if (options.maxRedirects != null) { - if (options.maxRedirects < 0) { - throw new PlaywrightException("'maxRedirects' should be greater than or equal to '0'"); - } - params.maxRedirects = options.maxRedirects; - } - if (options.maxRetries != null) { - if (options.maxRetries < 0) { - throw new PlaywrightException("'maxRetries' must be greater than or equal to '0'"); - } - params.maxRetries = options.maxRetries; - } + params.maxRedirects = options.maxRedirects; + params.maxRetries = options.maxRetries; APIRequestContextFetchResult result = channel.fetch(params, timeoutSettings.timeout(options.timeout)); return new APIResponseImpl(this, result.response); } - private static List toNameValues(JsonArray array) { - List result = new ArrayList<>(); - for (JsonElement element : array) { - JsonObject item = element.getAsJsonObject(); - NameValue nv = new NameValue(); - nv.name = item.get("name").getAsString(); - nv.value = item.get("value").getAsString(); - result.add(nv); - } - return result; - } - - private static boolean isJsonContentType(Map headers) { - if (headers == null) { - return false; - } - for (Map.Entry e : headers.entrySet()) { - if ("content-type".equalsIgnoreCase(e.getKey())) { - return "application/json".equals(e.getValue().split(";", -1)[0].trim().toLowerCase()); - } - } - return false; - } - - private static List serializeMultipartData(List> data) { - List result = new ArrayList<>(); - for (Map.Entry e : data) { - FilePayload filePayload = null; - if (e.getValue() instanceof FilePayload) { - filePayload = (FilePayload) e.getValue(); - } else if (e.getValue() instanceof Path) { - filePayload = toFilePayload((Path) e.getValue()); - } else if (e.getValue() instanceof File) { - filePayload = toFilePayload(((File) e.getValue()).toPath()); - } - FormField item = new FormField(); - item.name = e.getKey(); - if (filePayload == null) { - item.value = "" + e.getValue(); - } else { - item.file = new FormField.FormFieldFile(); - item.file.name = filePayload.name; - item.file.mimeType = filePayload.mimeType; - item.file.buffer = filePayload.buffer; - } - result.add(item); - } - return result; - } - - @Override - public APIResponse get(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "GET")); - } - - @Override - public APIResponse head(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "HEAD")); - } - - @Override - public APIResponse patch(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "PATCH")); - } - - @Override - public APIResponse post(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "POST")); - } - - @Override - public APIResponse put(String url, RequestOptions options) { - return fetch(url, ensureOptions(options, "PUT")); - } - @Override public String storageState(StorageStateOptions options) { if (options == null) { options = new StorageStateOptions(); } - APIRequestContextStorageStateParams params = toProtocol(options, APIRequestContextStorageStateParams.class); - // Keep the raw reply: re-serializing the typed result would turn "expires":-1 into -1.0 and change the string - // that is compared with BrowserContext.storageState(). - String storageState = sendMessage("storageState", connection.protocolGson().toJsonTree(params).getAsJsonObject(), NO_TIMEOUT).toString(); + APIRequestContextStorageStateParams params = new APIRequestContextStorageStateParams(); + params.indexedDB = options.indexedDB; + params.opfs = options.opfs; + // java: the API returns the raw JSON of the reply; re-serializing the typed result would turn "expires":-1 + // into -1.0 and change the string that is compared with BrowserContext.storageState(). + String state = sendMessage("storageState", connection.protocolGson().toJsonTree(params).getAsJsonObject(), NO_TIMEOUT).toString(); if (options.path != null) { - Utils.writeToFile(Serialization.toPrettyJson(storageState).getBytes(StandardCharsets.UTF_8), options.path); + // java: writeToFile creates the parent directories, as mkdirIfNeeded does upstream. + Utils.writeToFile(Serialization.toPrettyJson(state).getBytes(StandardCharsets.UTF_8), options.path); } - return storageState; + return state; } - private static RequestOptionsImpl ensureOptions(RequestOptions options, String method) { - RequestOptionsImpl impl = Utils.clone((RequestOptionsImpl) options); - if (impl == null) { - impl = new RequestOptionsImpl(); - } - if (impl.method == null) { - impl.method = method; + // java: FormData values are String, Boolean, Integer, Path (upstream's ReadStream) or FilePayload. + static FormField toFormField(String name, Object value) { + FormField field = new FormField(); + field.name = name; + if (APIResponseImpl.isFilePayload(value)) { + FilePayload payload = (FilePayload) value; + if (payload.buffer == null) { + throw new PlaywrightException("Unexpected buffer type of 'data." + name + "'"); + } + field.file = APIResponseImpl.filePayloadToJson(payload); + } else if (value instanceof String || value instanceof Number || value instanceof Boolean) { + field.value = String.valueOf(value); + } else { + field.file = APIResponseImpl.readStreamToJson((Path) value); } - return impl; + return field; } - private static boolean isJsonParsable(String value) { + // java: Gson parses some non-JSON text leniently (a bare word is a string), JSON.parse does not. + static boolean isJsonParsable(String value) { if (value.trim().isEmpty()) { return false; } @@ -308,14 +303,36 @@ private static boolean isJsonParsable(String value) { if (result != null && result.isJsonPrimitive()) { JsonPrimitive primitive = result.getAsJsonPrimitive(); if (primitive.isString() && value.equals(primitive.getAsString())) { - // Gson parses unquoted strings too, but we don't want to treat them - // as valid JSON. return false; } } return true; - } catch (JsonSyntaxException error) { + } catch (JsonSyntaxException e) { return false; } } + + // java: class APIResponse and the module functions after it are in APIResponseImpl.java. + + // java: the accessor of the tracing field, the { ...options, method } of the get/post/... shortcuts and the { name, value } literal. + @Override + public TracingImpl tracing() { + return tracing; + } + + private static RequestOptionsImpl withMethod(RequestOptions options, String method) { + RequestOptionsImpl impl = Utils.clone((RequestOptionsImpl) options); + if (impl == null) { + impl = new RequestOptionsImpl(); + } + impl.method = method; + return impl; + } + + private static NameValue nameValue(String name, String value) { + NameValue nv = new NameValue(); + nv.name = name; + nv.value = value; + return nv; + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java index 3122ba2bb..004dcc0f7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -14,28 +14,29 @@ * limitations under the License. */ +// Port of fetch.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.microsoft.playwright.APIRequest; import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.PlaywrightNewRequestParams; import com.microsoft.playwright.options.ClientCertificate; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; +import java.util.Set; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Utils.toProtocol; class APIRequestImpl implements APIRequest { private final PlaywrightImpl playwright; + final Set contexts = new LinkedHashSet<>(); APIRequestImpl(PlaywrightImpl playwright) { this.playwright = playwright; @@ -43,67 +44,41 @@ class APIRequestImpl implements APIRequest { @Override public APIRequestContextImpl newContext(NewContextOptions options) { - if (options == null) { - options = new NewContextOptions(); - } else { - options = Utils.clone(options); - } + options = options == null ? new NewContextOptions() : Utils.clone(options); + playwright.instrumentation.runBeforeCreateRequestContext(options); + // java: storageState is the JSON text and storageStatePath the file, upstream takes a path string or an object. + String storageStateJson = options.storageState; if (options.storageStatePath != null) { try { - byte[] bytes = Files.readAllBytes(options.storageStatePath); - options.storageState = new String(bytes, StandardCharsets.UTF_8); - options.storageStatePath = null; + storageStateJson = new String(Files.readAllBytes(options.storageStatePath), StandardCharsets.UTF_8); } catch (IOException e) { throw new PlaywrightException("Failed to read storage state from file", e); } } - PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState storageState = null; - if (options.storageState != null) { - storageState = gson().fromJson(options.storageState, PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState.class); - options.storageState = null; - } - List clientCertificateList = options.clientCertificates; - options.clientCertificates = null; - // The protocol always takes a list (mirrors toHttpCredentialsProtocol() in the JS client). + PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState storageState = storageStateJson == null ? null : + gson().fromJson(storageStateJson, PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState.class); + Map extraHTTPHeaders = options.extraHTTPHeaders; + List clientCertificates = options.clientCertificates; Object httpCredentials = options.httpCredentials; + // java: the fields that the spread of upstream replaces are cleared before the options are copied into the params. + options.storageState = null; + options.storageStatePath = null; + options.extraHTTPHeaders = null; + options.clientCertificates = null; options.httpCredentials = null; - Double timeout = options.timeout; - // Timeout is handled on the client. - options.timeout = null; - PlaywrightNewRequestParams params = toProtocol(options, PlaywrightNewRequestParams.class); - if (storageState != null) { - params.storageState = storageState; - } - if (clientCertificateList != null) { - params.clientCertificates = new ArrayList<>(); - for (ClientCertificate cert : clientCertificateList) { - PlaywrightNewRequestParams.PlaywrightNewRequestParamsClientCertificates c = new PlaywrightNewRequestParams.PlaywrightNewRequestParamsClientCertificates(); - c.origin = cert.origin; - try { - c.cert = cert.certPath != null ? Files.readAllBytes(cert.certPath) : cert.cert; - c.key = cert.keyPath != null ? Files.readAllBytes(cert.keyPath) : cert.key; - c.pfx = cert.pfxPath != null ? Files.readAllBytes(cert.pfxPath) : cert.pfx; - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); - } - c.passphrase = cert.passphrase; - params.clientCertificates.add(c); - } - } - if (httpCredentials != null) { - JsonElement credentials = gson().toJsonTree(httpCredentials); - JsonArray list = new JsonArray(); - if (credentials.isJsonArray()) { - list.addAll(credentials.getAsJsonArray()); - } else { - list.add(credentials); - } - if (list.size() > 0) { - params.httpCredentials = gson().fromJson(list, new TypeToken>() {}.getType()); - } - } + PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class); + params.extraHTTPHeaders = extraHTTPHeaders != null ? Headers.headersObjectToArray(extraHTTPHeaders) : null; + params.storageState = storageState; + // We do not expose tracesDir in the API, so do not allow options to accidentally override it. + params.tracesDir = playwright.defaultLaunchOptions != null && playwright.defaultLaunchOptions.tracesDir != null ? playwright.defaultLaunchOptions.tracesDir.toString() : null; + params.clientCertificates = BrowserContextImpl.toClientCertificatesProtocol(clientCertificates); + params.httpCredentials = BrowserContextImpl.toHttpCredentialsProtocol(httpCredentials); APIRequestContextImpl context = playwright.channel.newRequest(params, NO_TIMEOUT).request; - context.timeoutSettings.setDefaultTimeout(timeout); + contexts.add(context); + context.request = this; + context.timeoutSettings.setDefaultTimeout(options.timeout != null ? options.timeout : playwright.defaultContextTimeout); + context.tracing.tracesDir = playwright.defaultLaunchOptions != null ? playwright.defaultLaunchOptions.tracesDir : null; + context.instrumentation.runAfterCreateRequestContext(context); return context; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java index 48693a031..bc6f0086b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java @@ -14,71 +14,71 @@ * limitations under the License. */ +// Port of fetch.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonElement; import com.microsoft.playwright.APIResponse; import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.APIRequestContextDisposeAPIResponseParams; +import com.microsoft.playwright.impl.protocol.APIRequestContextFetchLogParams; +import com.microsoft.playwright.impl.protocol.APIRequestContextFetchResponseBodyParams; +import com.microsoft.playwright.impl.protocol.APIRequestContextFetchResponseBodyResult; +import com.microsoft.playwright.impl.protocol.FormField; +import com.microsoft.playwright.impl.protocol.NameValue; +import com.microsoft.playwright.impl.protocol.ResourceTiming; +import com.microsoft.playwright.options.FilePayload; import com.microsoft.playwright.options.HttpHeader; import com.microsoft.playwright.options.SecurityDetails; import com.microsoft.playwright.options.ServerAddr; import com.microsoft.playwright.options.Timing; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.function.Supplier; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Errors.isSafeCloseError; -import static java.util.Arrays.asList; +import static com.microsoft.playwright.impl.Errors.isTargetClosedError; class APIResponseImpl implements APIResponse { - final APIRequestContextImpl context; - private final com.microsoft.playwright.impl.protocol.APIResponse response; + private final com.microsoft.playwright.impl.protocol.APIResponse initializer; private final RawHeaders headers; + final APIRequestContextImpl request; + String apiName = "APIResponse"; - APIResponseImpl(APIRequestContextImpl apiRequestContext, com.microsoft.playwright.impl.protocol.APIResponse response) { - context = apiRequestContext; - this.response = response; - List headerList = new ArrayList<>(); - for (NameValue nv : response.headers) { - HttpHeader h = new HttpHeader(); - h.name = nv.name; - h.value = nv.value; - headerList.add(h); - } - headers = new RawHeaders(headerList); + APIResponseImpl(APIRequestContextImpl context, com.microsoft.playwright.impl.protocol.APIResponse initializer) { + this.request = context; + this.initializer = initializer; + this.headers = new RawHeaders(this.initializer.headers); + + // java: no inspect.custom, Node.js inspection has no Java counterpart. + } + + R wrapApiCall(Supplier func, String title, boolean internal) { + return request.wrapApiCall(func, title, internal); } @Override - public byte[] body() { - try { - APIRequestContextFetchResponseBodyParams params = new APIRequestContextFetchResponseBodyParams(); - params.fetchUid = fetchUid(); - APIRequestContextFetchResponseBodyResult result = context.channel.fetchResponseBody(params, NO_TIMEOUT); - if (result.binary == null) { - throw new PlaywrightException("Response has been disposed"); - } - return result.binary; - } catch (PlaywrightException e) { - if (isSafeCloseError(e)) { - throw new PlaywrightException("Response has been disposed"); - } - throw e; - } + public boolean ok() { + return initializer.status >= 200 && initializer.status <= 299; } @Override - public void dispose() { - APIRequestContextDisposeAPIResponseParams params = new APIRequestContextDisposeAPIResponseParams(); - params.fetchUid = fetchUid(); - context.channel.disposeAPIResponse(params, NO_TIMEOUT); + public String url() { + return initializer.url; + } + + @Override + public int status() { + return initializer.status; + } + + @Override + public String statusText() { + return initializer.statusText; } @Override @@ -91,99 +91,161 @@ public List headersArray() { return headers.headersArray(); } - @Override - public boolean ok() { - int status = status(); - return status == 0 || (status >= 200 && status <= 299); - } - + // java: the protocol SecurityDetails and RemoteAddr are converted to the API types. @Override public SecurityDetails securityDetails() { - com.microsoft.playwright.impl.protocol.SecurityDetails d = response.securityDetails; - if (d == null) { - return null; - } - SecurityDetails result = new SecurityDetails(); - result.issuer = d.issuer; - result.protocol = d.protocol; - result.subjectName = d.subjectName; - result.validFrom = d.validFrom; - result.validTo = d.validTo; - return result; + return Utils.convertType(initializer.securityDetails, SecurityDetails.class); } @Override public ServerAddr serverAddr() { - if (response.serverAddr == null) { - return null; - } - ServerAddr result = new ServerAddr(); - result.ipAddress = response.serverAddr.ipAddress; - result.port = response.serverAddr.port == null ? 0 : response.serverAddr.port; - return result; + return Utils.convertType(initializer.serverAddr, ServerAddr.class); } @Override - public int status() { - return response.status; + public Timing timing() { + ResourceTiming t = initializer.timing; + Timing timing = new Timing(); + timing.startTime = -1; + timing.domainLookupStart = -1; + timing.domainLookupEnd = -1; + timing.connectStart = -1; + timing.secureConnectionStart = -1; + timing.connectEnd = -1; + timing.requestStart = -1; + timing.responseStart = -1; + // java: the spread of this._initializer.timing, field by field. + if (t != null) { + if (t.startTime != null) { + timing.startTime = t.startTime; + } + if (t.domainLookupStart != null) { + timing.domainLookupStart = t.domainLookupStart; + } + if (t.domainLookupEnd != null) { + timing.domainLookupEnd = t.domainLookupEnd; + } + if (t.connectStart != null) { + timing.connectStart = t.connectStart; + } + if (t.secureConnectionStart != null) { + timing.secureConnectionStart = t.secureConnectionStart; + } + if (t.connectEnd != null) { + timing.connectEnd = t.connectEnd; + } + if (t.requestStart != null) { + timing.requestStart = t.requestStart; + } + if (t.responseStart != null) { + timing.responseStart = t.responseStart; + } + } + timing.responseEnd = initializer.responseEndTiming != null ? initializer.responseEndTiming : -1; + return timing; } @Override - public String statusText() { - return response.statusText; + public byte[] body() { + return wrapApiCall(() -> { + try { + APIRequestContextFetchResponseBodyParams params = new APIRequestContextFetchResponseBodyParams(); + params.fetchUid = fetchUid(); + APIRequestContextFetchResponseBodyResult result = request.channel.fetchResponseBody(params, NO_TIMEOUT); + // java: the channel returns null for an empty reply. + if (result == null || result.binary == null) { + throw new PlaywrightException("Response has been disposed"); + } + return result.binary; + } catch (PlaywrightException e) { + if (isTargetClosedError(e)) { + throw new PlaywrightException("Response has been disposed"); + } + throw e; + } + }, null, true); } @Override public String text() { - return new String(body(), StandardCharsets.UTF_8); + byte[] content = body(); + return new String(content, StandardCharsets.UTF_8); } - @Override - public Timing timing() { - Timing timing; - ResourceTiming t = response.timing; - if (t != null) { - timing = new Timing(); - timing.startTime = orZero(t.startTime); - timing.domainLookupStart = orZero(t.domainLookupStart); - timing.domainLookupEnd = orZero(t.domainLookupEnd); - timing.connectStart = orZero(t.connectStart); - timing.secureConnectionStart = orZero(t.secureConnectionStart); - timing.connectEnd = orZero(t.connectEnd); - timing.requestStart = orZero(t.requestStart); - timing.responseStart = orZero(t.responseStart); - } else { - timing = new Timing(); - timing.startTime = -1; - timing.domainLookupStart = -1; - timing.domainLookupEnd = -1; - timing.connectStart = -1; - timing.secureConnectionStart = -1; - timing.connectEnd = -1; - timing.requestStart = -1; - timing.responseStart = -1; - } - timing.responseEnd = response.responseEndTiming != null ? response.responseEndTiming : -1; - return timing; + // java: the parsed JSON is a JsonElement. + JsonElement json() { + String content = text(); + return RequestImpl.parseJSON(content); } - private static double orZero(Double value) { - return value == null ? 0 : value; - } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. @Override - public String url() { - return response.url; + public void dispose() { + APIRequestContextDisposeAPIResponseParams params = new APIRequestContextDisposeAPIResponseParams(); + params.fetchUid = fetchUid(); + request.channel.disposeAPIResponse(params, NO_TIMEOUT); } + // java: _inspect is not ported, Node.js inspection has no Java counterpart. + String fetchUid() { - return response.fetchUid; + return initializer.fetchUid; } List fetchLog() { APIRequestContextFetchLogParams params = new APIRequestContextFetchLogParams(); params.fetchUid = fetchUid(); - return context.channel.fetchLog(params, NO_TIMEOUT).log; + return request.channel.fetchLog(params, NO_TIMEOUT).log; + } + + static FormField.FormFieldFile filePayloadToJson(FilePayload payload) { + FormField.FormFieldFile file = new FormField.FormFieldFile(); + file.name = payload.name; + file.mimeType = payload.mimeType; + file.buffer = payload.buffer; + return file; + } + + // java: a file Path stands in for upstream's fs.ReadStream. + static FormField.FormFieldFile readStreamToJson(Path path) { + FilePayload payload = Utils.toFilePayload(path); + FormField.FormFieldFile file = new FormField.FormFieldFile(); + file.name = payload.name; + file.buffer = payload.buffer; + return file; + } + + static boolean isJsonContentType(List headers) { + if (headers == null) { + return false; + } + for (NameValue header : headers) { + if ("content-type".equals(header.name.toLowerCase())) { + return "application/json".equals(header.value.split(";", -1)[0].trim().toLowerCase()); + } + } + return false; } + static List objectToArray(Map map) { + if (map == null) { + return null; + } + List result = new ArrayList<>(); + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() != null) { + NameValue nameValue = new NameValue(); + nameValue.name = entry.getKey(); + nameValue.value = String.valueOf(entry.getValue()); + result.add(nameValue); + } + } + return result; + } + + // java: the Java type decides it; a FilePayload with an empty name or mimeType is still a file payload. + static boolean isFilePayload(Object value) { + return value instanceof FilePayload; + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ApiCallData.java b/playwright/src/main/java/com/microsoft/playwright/impl/ApiCallData.java new file mode 100644 index 000000000..c16eb5d97 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ApiCallData.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of clientInstrumentation.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonArray; + +// Instrumentation can mutate the data, for example assign the callId. +// java: upstream's interface with fields is a class; ApiZone extends it as it matches it structurally upstream. +class ApiCallData { + String title; + // java: the stack frames are the JsonArray that StackTraceCollector builds. + JsonArray frames; + Object userData; + String callId; + RuntimeException error; +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java index 5f0ccaa47..a073a73ff 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of artifact.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -31,15 +32,42 @@ public class ArtifactImpl extends ChannelOwner { final ArtifactChannel channel = new ArtifactChannel(this); + // java: from is not ported, generated results already hold the impl object. + public ArtifactImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } + public Path pathAfterFinished() { + if (connection.isRemote()) { + throw new PlaywrightException("Path is not available when connecting remotely. Use saveAs() to save a local copy."); + } + return FileSystems.getDefault().getPath(channel.pathAfterFinished(NO_TIMEOUT).value); + } + + public void saveAs(Path path) { + if (!connection.isRemote()) { + ArtifactSaveAsParams params = new ArtifactSaveAsParams(); + params.path = path.toString(); + channel.saveAs(params, NO_TIMEOUT); + return; + } + + Stream stream = channel.saveAsStream(NO_TIMEOUT).stream; + // java: writeToFile creates the parent directories and pipes the stream, as mkdirIfNeeded and pipe do upstream. + writeToFile(stream.stream(), path); + } + + public String failure() { + return channel.failure(NO_TIMEOUT).error; + } + public InputStream createReadStream() { return channel.stream(NO_TIMEOUT).stream.stream(); } - byte[] readAllBytes() { + // java: the 'data' chunks of the stream are read in a loop. + byte[] readIntoBuffer() { final int bufLen = 1024 * 1024; byte[] buf = new byte[bufLen]; int readLen; @@ -61,26 +89,8 @@ public void delete() { channel.delete(NO_TIMEOUT); } - public String failure() { - return channel.failure(NO_TIMEOUT).error; - } - - public Path pathAfterFinished() { - if (connection.isRemote()) { - throw new PlaywrightException("Path is not available when connecting remotely. Use saveAs() to save a local copy."); - } - return FileSystems.getDefault().getPath(channel.pathAfterFinished(NO_TIMEOUT).value); - } - - public void saveAs(Path path) { - if (connection.isRemote()) { - Stream stream = channel.saveAsStream(NO_TIMEOUT).stream; - writeToFile(stream.stream(), path); - return; - } - - ArtifactSaveAsParams params = new ArtifactSaveAsParams(); - params.path = path.toString(); - channel.saveAs(params, NO_TIMEOUT); + // java: the old name of readIntoBuffer, BrowserImpl calls it. + byte[] readAllBytes() { + return readIntoBuffer(); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java index a74c8d91c..ee4481027 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java @@ -14,15 +14,15 @@ * limitations under the License. */ +// Port of page.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.BrowserContext; import com.microsoft.playwright.Frame; -import com.microsoft.playwright.JSHandle; import com.microsoft.playwright.Page; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.BindingCallback; import java.util.ArrayList; @@ -31,21 +31,64 @@ import static com.microsoft.playwright.impl.Serialization.*; public class BindingCall extends ChannelOwner { - private static class SourceImpl implements BindingCallback.Source { + final BindingCallChannel channel = new BindingCallChannel(this); + // java: the initializer parsed once, upstream reads this._initializer. + final BindingCallInitializer bindingCallInitializer; + + // java: from is not ported, generated results already hold the impl object. + + BindingCall(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + bindingCallInitializer = connection.protocolGson().fromJson(initializer, BindingCallInitializer.class); + } + + void call(BindingCallback func) { + try { + FrameImpl frame = bindingCallInitializer.frame; + BindingCallback.Source source = new Source(frame.page.context(), frame.page, frame); + List args = new ArrayList<>(); + for (SerializedValue arg : bindingCallInitializer.args) { + args.add(deserialize(arg)); + } + Object result = func.call(source, args.toArray()); + BindingCallResolveParams params = new BindingCallResolveParams(); + params.result = serializeArgument(result); + // java: channel.resolve(...).catch(() => {}) is not awaited upstream; sendMessageAsync does not pump. + try { + sendMessageAsync("resolve", params); + } catch (PlaywrightException e) { + } + } catch (RuntimeException e) { + // java: an Error thrown by the callback, such as a failed assertion, reaches the caller instead. + BindingCallRejectParams params = new BindingCallRejectParams(); + params.error = serializeError(e); + try { + sendMessageAsync("reject", params); + } catch (PlaywrightException e2) { + } + } + } + + // java: the { context, page, frame } object literal of call(). + private static class Source implements BindingCallback.Source { + private final BrowserContext context; + private final Page page; private final Frame frame; - public SourceImpl(Frame frame) { + Source(BrowserContext context, Page page, Frame frame) { + this.context = context; + this.page = page; this.frame = frame; } @Override public BrowserContext context() { - return page().context(); + return context; } @Override public Page page() { - return frame.page(); + return page; } @Override @@ -53,47 +96,4 @@ public Frame frame() { return frame; } } - - final BindingCallChannel channel = new BindingCallChannel(this); - - BindingCall(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } - - String name() { - return initializer.get("name").getAsString(); - } - - void call(BindingCallback binding) { - String method; - Object params; - try { - BindingCallResolveParams resolveParams = new BindingCallResolveParams(); - resolveParams.result = serializeArgument(invoke(binding)); - params = resolveParams; - method = "resolve"; - } catch (RuntimeException exception) { - BindingCallRejectParams rejectParams = new BindingCallRejectParams(); - rejectParams.error = serializeError(exception); - params = rejectParams; - method = "reject"; - } - // Like the Node client, do not fail when the page was closed before the result arrived. - sendMessageAsync(method, params); - } - - private Object invoke(BindingCallback binding) { - Frame frame = connection.getExistingObject(initializer.getAsJsonObject("frame").get("guid").getAsString()); - BindingCallback.Source source = new SourceImpl(frame); - List args = new ArrayList<>(); - if (initializer.has("handle")) { - JSHandle handle = connection.getExistingObject(initializer.getAsJsonObject("handle").get("guid").getAsString()); - args.add(handle); - } else { - for (JsonElement arg : initializer.getAsJsonArray("args")) { - args.add(deserialize(gson().fromJson(arg, SerializedValue.class))); - } - } - return binding.call(source, args.toArray()); - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java index 35225faee..d57fb9559 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -14,58 +14,123 @@ * limitations under the License. */ +// Port of browserContext.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.*; -import com.microsoft.playwright.options.*; +import com.microsoft.playwright.APIRequestContext; +import com.microsoft.playwright.Browser; +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.CDPSession; +import com.microsoft.playwright.ConsoleMessage; +import com.microsoft.playwright.Credentials; +import com.microsoft.playwright.Dialog; +import com.microsoft.playwright.Download; +import com.microsoft.playwright.Frame; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.Request; +import com.microsoft.playwright.Response; +import com.microsoft.playwright.Route; +import com.microsoft.playwright.WebError; +import com.microsoft.playwright.WebSocketRoute; +import com.microsoft.playwright.impl.protocol.*; +import com.microsoft.playwright.options.BindingCallback; +import com.microsoft.playwright.options.ClientCertificate; +import com.microsoft.playwright.options.Cookie; +import com.microsoft.playwright.options.FunctionCallback; +import com.microsoft.playwright.options.Geolocation; +import com.microsoft.playwright.options.HarContentPolicy; +import com.microsoft.playwright.options.HarMode; +import com.microsoft.playwright.options.HarNotFound; +import com.microsoft.playwright.options.WebErrorLocation; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.*; -import static com.microsoft.playwright.impl.Utils.*; -import static com.microsoft.playwright.impl.Errors.isSafeCloseError; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.nio.file.Files.readAllBytes; -import static java.util.Arrays.asList; +import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; +import static com.microsoft.playwright.impl.Serialization.assertEvaluateOptions; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toProtocol; public class BrowserContextImpl extends ChannelOwner implements BrowserContext { - protected BrowserImpl browser; - private final TracingImpl tracing; - private final DebuggerImpl debugger; - private final APIRequestContextImpl request; - private final ClockImpl clock; - private final CredentialsImpl credentials; - final List pages = new ArrayList<>(); - - final Router routes = new Router(); - final WebSocketRouter webSocketRoutes = new WebSocketRouter(); - private boolean closingOrClosed; - private final WaitableEvent closePromise; - final Map bindings = new HashMap<>(); + // java: the optional methods are default no-ops; actions.Action and actions.Signal are the raw JSON of the event. + interface RecorderEventSink { + default void actionAdded(PageImpl page, JsonElement action, String code) { + } + + default void actionUpdated(PageImpl page, JsonElement action, String code) { + } + + default void signalAdded(PageImpl page, JsonElement signal, String code) { + } + } + + final Set pages = new LinkedHashSet<>(); + List routes = new ArrayList<>(); + List webSocketRoutes = new ArrayList<>(); + // Browser is null for browser contexts created outside of normal browser, e.g. android or electron. + BrowserImpl browser = null; + final Map bindings = new LinkedHashMap<>(); + final TimeoutSettings timeoutSettings; PageImpl ownerPage; + boolean forReuse = false; + private final WaitableEvent closedPromise; + final BrowserContextInitializer.BrowserContextInitializerOptions options; + + final DebuggerImpl debugger; + final APIRequestContextImpl request; + final TracingImpl tracing; + final ClockImpl clock; + final CredentialsImpl credentials; + + final Set serviceWorkers = new LinkedHashSet<>(); + private String closingStatus = "none"; private String closeReason; - - final TimeoutSettings timeoutSettings = new TimeoutSettings(); + private List harRouters = new ArrayList<>(); + private RecorderEventSink onRecorderEventSink; final BrowserContextChannel channel = new BrowserContextChannel(this); + // java: from and fromNullable are not ported, generated results already hold the impl object. + BrowserContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - Map mapping = new HashMap<>(); + BrowserContextInitializer contextInitializer = connection.protocolGson().fromJson(initializer, BrowserContextInitializer.class); + this.options = contextInitializer.options; + this.timeoutSettings = new TimeoutSettings(); + this.debugger = contextInitializer.debugger; + this.tracing = contextInitializer.tracing; + this.request = contextInitializer.requestContext; + this.request.timeoutSettings = this.timeoutSettings; + this.clock = new ClockImpl(this); + this.credentials = new CredentialsImpl(this); + + this.closedPromise = new WaitableEvent<>(this, Events.BrowserContext.CLOSE); + + Map mapping = new LinkedHashMap<>(); mapping.put(Events.BrowserContext.CONSOLE, "console"); mapping.put(Events.BrowserContext.DIALOG, "dialog"); mapping.put(Events.BrowserContext.DIALOG_CLOSED, "dialogClosed"); @@ -74,247 +139,598 @@ public class BrowserContextImpl extends ChannelOwner implements BrowserContext { mapping.put(Events.BrowserContext.REQUEST_FINISHED, "requestFinished"); mapping.put(Events.BrowserContext.REQUEST_FAILED, "requestFailed"); setEventToSubscriptionMapping(mapping); - tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString()); - debugger = connection.getExistingObject(initializer.getAsJsonObject("debugger").get("guid").getAsString()); - request = connection.getExistingObject(initializer.getAsJsonObject("requestContext").get("guid").getAsString()); - request.timeoutSettings = timeoutSettings; - clock = new ClockImpl(this); - credentials = new CredentialsImpl(this); - closePromise = new WaitableEvent<>(this, Events.BrowserContext.CLOSE); } - URL baseUrl() { - JsonElement url = initializer.getAsJsonObject("options").get("baseURL"); - if (url != null) { - try { - return new URL(url.getAsString()); - } catch (MalformedURLException e) { + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. + @Override + void handleEvent(String event, JsonObject params) { + switch (event) { + case "bindingCall": { + BrowserContextBindingCallEvent e = connection.protocolGson().fromJson(params, BrowserContextBindingCallEvent.class); + onBinding(e.binding); + break; + } + case "close": + onClose(); + break; + case "page": { + BrowserContextPageEvent e = connection.protocolGson().fromJson(params, BrowserContextPageEvent.class); + onPage(e.page); + break; + } + case "route": { + BrowserContextRouteEvent e = connection.protocolGson().fromJson(params, BrowserContextRouteEvent.class); + onRoute(e.route); + break; + } + case "webSocketRoute": { + BrowserContextWebSocketRouteEvent e = connection.protocolGson().fromJson(params, BrowserContextWebSocketRouteEvent.class); + onWebSocketRoute(e.webSocketRoute); + break; + } + case "serviceWorker": { + BrowserContextServiceWorkerEvent e = connection.protocolGson().fromJson(params, BrowserContextServiceWorkerEvent.class); + WorkerImpl serviceWorker = e.worker; + serviceWorker.context = this; + serviceWorkers.add(serviceWorker); + emit(Events.BrowserContext.SERVICE_WORKER, serviceWorker); + break; + } + case "console": { + BrowserContextConsoleEvent e = connection.protocolGson().fromJson(params, BrowserContextConsoleEvent.class); + WorkerImpl worker = e.worker; + PageImpl page = e.page; + ConsoleMessageImpl consoleMessage = new ConsoleMessageImpl(e); + if (worker != null) { + worker.emit(Events.Worker.CONSOLE, consoleMessage); + } + if (page != null) { + page.emit(Events.Page.CONSOLE, consoleMessage); + } + if (worker != null && serviceWorkers.contains(worker)) { + String scope = serviceWorkerScope(worker); + // java: a copy, a listener that closes a page would modify the set while it is iterated. + for (PageImpl p : new ArrayList<>(pages)) { + if (scope != null && p.url().startsWith(scope)) { + p.emit(Events.Page.CONSOLE, consoleMessage); + } + } + } + emit(Events.BrowserContext.CONSOLE, consoleMessage); + break; + } + case "pageError": { + BrowserContextPageErrorEvent e = connection.protocolGson().fromJson(params, BrowserContextPageErrorEvent.class); + PageImpl pageObject = e.page; + // java: the error is the formatted string that Page.onPageError and WebError.error() return. + String parsedError = Serialization.parseError(params.getAsJsonObject("error")); + WebErrorLocation location = null; + if (params.has("location")) { + location = gson().fromJson(params.getAsJsonObject("location"), WebErrorLocation.class); + } + emit(Events.BrowserContext.WEB_ERROR, new WebErrorImpl(pageObject, parsedError, location)); + if (pageObject != null) { + pageObject.emit(Events.Page.PAGE_ERROR, parsedError); + } + break; + } + case "dialog": { + BrowserContextDialogEvent e = connection.protocolGson().fromJson(params, BrowserContextDialogEvent.class); + DialogImpl dialogObject = e.dialog; + // java: emit() does not report whether there were listeners, they are counted before. + boolean hasListeners = listenerCount(Events.BrowserContext.DIALOG) > 0; + emit(Events.BrowserContext.DIALOG, dialogObject); + PageImpl page = dialogObject.page(); + if (page != null) { + hasListeners = page.listenerCount(Events.Page.DIALOG) > 0 || hasListeners; + page.emit(Events.Page.DIALOG, dialogObject); + } + if (!hasListeners) { + // Although we do similar handling on the server side, we still need this logic + // on the client side due to a possible race condition between two async calls: + // a) removing "dialog" listener subscription (client->server) + // b) actual "dialog" event (server->client) + try { + if ("beforeunload".equals(dialogObject.type())) { + dialogObject.channel.accept(new DialogAcceptParams(), NO_TIMEOUT); + } else { + dialogObject.channel.dismiss(new DialogDismissParams(), NO_TIMEOUT); + } + } catch (PlaywrightException ex) { + } + } + break; + } + case "dialogClosed": { + BrowserContextDialogClosedEvent e = connection.protocolGson().fromJson(params, BrowserContextDialogClosedEvent.class); + DialogImpl dialogObject = e.dialog; + emit(Events.BrowserContext.DIALOG_CLOSED, dialogObject); + PageImpl page = dialogObject.page(); + if (page != null) { + page.emit(Events.Page.DIALOG_CLOSED, dialogObject); + } + break; + } + case "request": { + BrowserContextRequestEvent e = connection.protocolGson().fromJson(params, BrowserContextRequestEvent.class); + onRequest(e.request, e.page); + break; + } + case "requestFailed": { + BrowserContextRequestFailedEvent e = connection.protocolGson().fromJson(params, BrowserContextRequestFailedEvent.class); + onRequestFailed(e.request, e.responseEndTiming, e.failureText, e.page); + break; + } + case "requestFinished": { + BrowserContextRequestFinishedEvent e = connection.protocolGson().fromJson(params, BrowserContextRequestFinishedEvent.class); + onRequestFinished(e); + break; + } + case "response": { + BrowserContextResponseEvent e = connection.protocolGson().fromJson(params, BrowserContextResponseEvent.class); + onResponse(e.response, e.page); + break; + } + case "recorderEvent": { + BrowserContextRecorderEventEvent e = connection.protocolGson().fromJson(params, BrowserContextRecorderEventEvent.class); + if ("actionAdded".equals(e.event)) { + if (onRecorderEventSink != null) { + onRecorderEventSink.actionAdded(e.page, e.data, e.code); + } + } else if ("actionUpdated".equals(e.event)) { + if (onRecorderEventSink != null) { + onRecorderEventSink.actionUpdated(e.page, e.data, e.code); + } + } else if ("signalAdded".equals(e.event)) { + if (onRecorderEventSink != null) { + onRecorderEventSink.signalAdded(e.page, e.data, e.code); + } + } + break; } } - return null; } - String effectiveCloseReason() { - if (closeReason != null) { - return closeReason; + // java: upstream takes options.recordHar; Java has the flat recordHar* options. + void initializeHarFromOptions(Browser.NewContextOptions recordHar) { + if (recordHar == null || recordHar.recordHarPath == null) { + return; } - if (browser != null) { - return browser.closeReason; + HarContentPolicy defaultContent = Pattern.compile("\\.zip$", Pattern.CASE_INSENSITIVE).matcher(recordHar.recordHarPath.toString()).find() ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED; + HarContentPolicy content = recordHar.recordHarContent != null ? recordHar.recordHarContent + : (recordHar.recordHarOmitContent != null && recordHar.recordHarOmitContent ? HarContentPolicy.OMIT : defaultContent); + tracing.recordIntoHAR(recordHar.recordHarPath, null, recordHar.recordHarUrlFilter, content, + recordHar.recordHarMode != null ? recordHar.recordHarMode : HarMode.FULL, null); + } + + private void onPage(PageImpl page) { + pages.add(page); + emit(Events.BrowserContext.PAGE, page); + if (page.opener != null && !page.opener.isClosed()) { + page.opener.emit(Events.Page.POPUP, page); } - return null; } - @Override - public void onBackgroundPage(Consumer handler) { + private void onRequest(RequestImpl request, PageImpl page) { + emit(Events.BrowserContext.REQUEST, request); + if (page != null) { + page.emit(Events.Page.REQUEST, request); + } } - @Override - public void offBackgroundPage(Consumer handler) { + private void onResponse(ResponseImpl response, PageImpl page) { + emit(Events.BrowserContext.RESPONSE, response); + if (page != null) { + page.emit(Events.Page.RESPONSE, response); + } } - @Override - public void onDownload(Consumer handler) { - on(Events.BrowserContext.DOWNLOAD, handler); + private void onRequestFailed(RequestImpl request, Double responseEndTiming, String failureText, PageImpl page) { + request.failureText = failureText == null || failureText.isEmpty() ? null : failureText; + request.setResponseEndTiming(responseEndTiming); + emit(Events.BrowserContext.REQUEST_FAILED, request); + if (page != null) { + page.emit(Events.Page.REQUEST_FAILED, request); + } } - @Override - public void offDownload(Consumer handler) { - off(Events.BrowserContext.DOWNLOAD, handler); + private void onRequestFinished(BrowserContextRequestFinishedEvent params) { + Double responseEndTiming = params.responseEndTiming; + RequestImpl request = params.request; + ResponseImpl response = params.response; + PageImpl page = params.page; + request.setResponseEndTiming(responseEndTiming); + emit(Events.BrowserContext.REQUEST_FINISHED, request); + if (page != null) { + page.emit(Events.Page.REQUEST_FINISHED, request); + } + if (response != null) { + response.finishedPromise.complete(null); + } + } + + void onRoute(RouteImpl route) { + route.context = this; + PageImpl page = ((RequestImpl) route.request()).safePage(); + List routeHandlers = this.routes; + for (RouteHandler routeHandler : new ArrayList<>(routeHandlers)) { + // If the page or the context was closed we stall all requests right away. + if ((page != null && page.closeWasCalled) || isClosed()) { + return; + } + if (!routeHandler.matches(route.request().url())) { + continue; + } + int index = this.routes.indexOf(routeHandler); + if (index == -1) { + continue; + } + if (routeHandler.willExpire()) { + this.routes.remove(index); + } + boolean handled = routeHandler.handle(route); + // unrouteAll() replaces _routes and updates interception after waiting for handlers. + if (routeHandlers == this.routes && this.routes.isEmpty()) { + try { + disableInterception(); + } catch (PlaywrightException e) { + } + } + if (handled) { + return; + } + } + // If the page is closed or unrouteAll() was called without waiting and interception disabled, + // the method will throw an error - silence it. + try { + route.innerContinue(true /* isFallback */); + } catch (PlaywrightException e) { + } + } + + void onWebSocketRoute(WebSocketRouteImpl webSocketRoute) { + WebSocketRouteHandler routeHandler = null; + for (WebSocketRouteHandler route : webSocketRoutes) { + if (route.matches(webSocketRoute.url())) { + routeHandler = route; + break; + } + } + if (routeHandler != null) { + routeHandler.handle(webSocketRoute); + } else { + webSocketRoute.connectToServer(); + } + } + + void onBinding(BindingCall bindingCall) { + BindingCallback func = bindings.get(bindingCall.bindingCallInitializer.name); + if (func == null) { + return; + } + bindingCall.call(func); } - void notifyDownload(Download download) { - emit(Events.BrowserContext.DOWNLOAD, download); + private String serviceWorkerScope(WorkerImpl serviceWorker) { + try { + String url = new URL(new URL(serviceWorker.url()), ".").toString(); + if (!url.endsWith("/")) { + url += "/"; + } + return url; + } catch (MalformedURLException e) { + return null; + } } @Override - public void onClose(Consumer handler) { - on(Events.BrowserContext.CLOSE, handler); + public void setDefaultNavigationTimeout(double timeout) { + timeoutSettings.setDefaultNavigationTimeout(timeout); } @Override - public void offClose(Consumer handler) { - off(Events.BrowserContext.CLOSE, handler); + public void setDefaultTimeout(double timeout) { + timeoutSettings.setDefaultTimeout(timeout); } @Override - public void onConsoleMessage(Consumer handler) { - on(Events.BrowserContext.CONSOLE, handler); + public BrowserImpl browser() { + return browser; } @Override - public void offConsoleMessage(Consumer handler) { - off(Events.BrowserContext.CONSOLE, handler); + public List pages() { + return new ArrayList<>(pages); } @Override - public void onDialog(Consumer handler) { - on(Events.BrowserContext.DIALOG, handler); + public boolean isClosed() { + return !"none".equals(closingStatus); } @Override - public void offDialog(Consumer handler) { - off(Events.BrowserContext.DIALOG, handler); + public PageImpl newPage() { + if (ownerPage != null) { + throw new PlaywrightException("Please use browser.newContext()"); + } + return channel.newPage(new BrowserContextNewPageParams(), NO_TIMEOUT).page; } @Override - public void onDialogClosed(Consumer handler) { - on(Events.BrowserContext.DIALOG_CLOSED, handler); + public List cookies(String urls) { + return cookies(urls == null ? new ArrayList<>() : Collections.singletonList(urls)); } @Override - public void offDialogClosed(Consumer handler) { - off(Events.BrowserContext.DIALOG_CLOSED, handler); + public List cookies(List urls) { + if (urls == null) { + urls = new ArrayList<>(); + } + BrowserContextCookiesParams params = new BrowserContextCookiesParams(); + params.urls = urls; + List cookies = channel.cookies(params, NO_TIMEOUT).cookies; + // java: the protocol cookies are converted to the public Cookie type. + return Arrays.asList(gson().fromJson(connection.protocolGson().toJsonTree(cookies), Cookie[].class)); } @Override - public void onPage(Consumer handler) { - on(Events.BrowserContext.PAGE, handler); + public void addCookies(List cookies) { + BrowserContextAddCookiesParams params = new BrowserContextAddCookiesParams(); + // java: the public Cookie type is converted to the protocol one. + params.cookies = connection.protocolGson().fromJson(gson().toJsonTree(cookies), new TypeToken>() {}.getType()); + channel.addCookies(params, NO_TIMEOUT); } @Override - public void offPage(Consumer handler) { - off(Events.BrowserContext.PAGE, handler); + public void clearCookies(ClearCookiesOptions options) { + if (options == null) { + options = new ClearCookiesOptions(); + } + BrowserContextClearCookiesParams params = connection.protocolGson().fromJson( + Serialization.toClearCookiesParams(options.name, options.domain, options.path), BrowserContextClearCookiesParams.class); + channel.clearCookies(params, NO_TIMEOUT); } @Override - public void onFrameAttached(Consumer handler) { - on(Events.BrowserContext.FRAME_ATTACHED, handler); + public void grantPermissions(List permissions, GrantPermissionsOptions options) { + if (options == null) { + options = new GrantPermissionsOptions(); + } + BrowserContextGrantPermissionsParams params = toProtocol(options, BrowserContextGrantPermissionsParams.class); + params.permissions = permissions; + channel.grantPermissions(params, NO_TIMEOUT); } @Override - public void offFrameAttached(Consumer handler) { - off(Events.BrowserContext.FRAME_ATTACHED, handler); + public void clearPermissions() { + channel.clearPermissions(new BrowserContextClearPermissionsParams(), NO_TIMEOUT); } - void notifyFrameAttached(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_ATTACHED, frame); + @Override + public void setGeolocation(Geolocation geolocation) { + BrowserContextSetGeolocationParams params = new BrowserContextSetGeolocationParams(); + params.geolocation = geolocation == null ? null + : toProtocol(geolocation, BrowserContextSetGeolocationParams.BrowserContextSetGeolocationParamsGeolocation.class); + channel.setGeolocation(params, NO_TIMEOUT); } @Override - public void onFrameDetached(Consumer handler) { - on(Events.BrowserContext.FRAME_DETACHED, handler); + public void setExtraHTTPHeaders(Map headers) { + RawHeaders.validateHeaders(headers); + BrowserContextSetExtraHTTPHeadersParams params = new BrowserContextSetExtraHTTPHeadersParams(); + params.headers = Headers.headersObjectToArray(headers); + channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @Override - public void offFrameDetached(Consumer handler) { - off(Events.BrowserContext.FRAME_DETACHED, handler); + public void setOffline(boolean offline) { + BrowserContextSetOfflineParams params = new BrowserContextSetOfflineParams(); + params.offline = offline; + channel.setOffline(params, NO_TIMEOUT); } - void notifyFrameDetached(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_DETACHED, frame); + // java: httpCredentials is an HttpCredentials, a List of them or null. + void setHTTPCredentials(Object httpCredentials) { + BrowserContextSetHTTPCredentialsParams params = new BrowserContextSetHTTPCredentialsParams(); + params.httpCredentials = toHttpCredentialsProtocol(httpCredentials); + channel.setHTTPCredentials(params, NO_TIMEOUT); } @Override - public void onFrameNavigated(Consumer handler) { - on(Events.BrowserContext.FRAME_NAVIGATED, handler); + public AutoCloseable addInitScript(String script) { + return addInitScript(script, null, null); } @Override - public void offFrameNavigated(Consumer handler) { - off(Events.BrowserContext.FRAME_NAVIGATED, handler); + public AutoCloseable addInitScript(Path script) { + return addInitScript(script, null, null); } - void notifyFrameNavigated(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_NAVIGATED, frame); + // java: the core of the String and Path overloads. evaluationScript takes no arg: a Java script is not a function. + AutoCloseable addInitScript(Object script, Object arg, Serialization.ExposeFunctionsOptions options) { + assertEvaluateOptions(options); + if (options != null && Boolean.TRUE.equals(options.exposeFunctions)) { + return PageImpl.addInitScriptWithExposedFunctions(this, script, arg); + } + String source = evaluationScript(script, true); + BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); + params.source = source; + return channel.addInitScript(params, NO_TIMEOUT).disposable; } @Override - public void onPageClose(Consumer handler) { - on(Events.BrowserContext.PAGE_CLOSE, handler); + public AutoCloseable exposeBinding(String name, BindingCallback callback) { + BrowserContextExposeBindingParams params = new BrowserContextExposeBindingParams(); + params.name = name; + BrowserContextExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + bindings.put(name, callback); + return result.disposable; + } + + // java: the JS Function callback is a FunctionCallback. + DisposableObject exposeCallbackBinding(String name, FunctionCallback callback) { + bindings.put(name, (source, args) -> callback.call(args)); + BrowserContextExposeBindingParams params = new BrowserContextExposeBindingParams(); + params.name = name; + params.noGlobal = true; + BrowserContextExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + return result.disposable; } @Override - public void offPageClose(Consumer handler) { - off(Events.BrowserContext.PAGE_CLOSE, handler); + public AutoCloseable exposeFunction(String name, FunctionCallback callback) { + BrowserContextExposeBindingParams params = new BrowserContextExposeBindingParams(); + params.name = name; + BrowserContextExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + BindingCallback binding = (source, args) -> callback.call(args); + bindings.put(name, binding); + return result.disposable; } - void notifyPageClose(PageImpl page) { - emit(Events.BrowserContext.PAGE_CLOSE, page); + @Override + public AutoCloseable route(String url, Consumer handler, RouteOptions options) { + return route(UrlMatcher.forGlob(baseUrl(), url, connection.localUtils(), false), handler, options); } @Override - public void onPageLoad(Consumer handler) { - on(Events.BrowserContext.PAGE_LOAD, handler); + public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { + return route(new UrlMatcher(url), handler, options); } @Override - public void offPageLoad(Consumer handler) { - off(Events.BrowserContext.PAGE_LOAD, handler); + public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { + return route(new UrlMatcher(url), handler, options); } - void notifyPageLoad(PageImpl page) { - emit(Events.BrowserContext.PAGE_LOAD, page); + AutoCloseable route(UrlMatcher url, Consumer handler, RouteOptions options) { + return withTitle("Route requests", () -> { + routes.add(0, new RouteHandler(this.options.baseURL, url, handler, options == null ? null : options.times)); + updateInterceptionPatterns(); + return new DisposableStub(() -> unroute(url, handler)); + }); } @Override - public void onWebError(Consumer handler) { - on(Events.BrowserContext.WEB_ERROR, handler); + public void routeWebSocket(String url, Consumer handler) { + routeWebSocket(UrlMatcher.forGlob(baseUrl(), url, connection.localUtils(), true), handler); } @Override - public void offWebError(Consumer handler) { - off(Events.BrowserContext.WEB_ERROR, handler); + public void routeWebSocket(Pattern url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); } @Override - public void onRequest(Consumer handler) { - on(Events.BrowserContext.REQUEST, handler); + public void routeWebSocket(Predicate url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); } - @Override - public void offRequest(Consumer handler) { - off(Events.BrowserContext.REQUEST, handler); + private void routeWebSocket(UrlMatcher url, Consumer handler) { + withTitle("Route WebSockets", () -> { + webSocketRoutes.add(0, new WebSocketRouteHandler(options.baseURL, url, handler)); + updateWebSocketInterceptionPatterns(); + }); } @Override - public void onRequestFailed(Consumer handler) { - on(Events.BrowserContext.REQUEST_FAILED, handler); + public void routeFromHAR(Path har, RouteFromHAROptions options) { + if (options == null) { + options = new RouteFromHAROptions(); + } + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Route from har is not supported in thin clients"); + } + if (options.update != null && options.update) { + tracing.recordIntoHAR(har, null, options.url, convertType(options.updateContent, HarContentPolicy.class), options.updateMode, null); + return; + } + HarRouter harRouter = HarRouter.create(localUtils, har, options.notFound != null ? options.notFound : HarNotFound.ABORT, options.url); + harRouters.add(harRouter); + harRouter.addContextRoute(this); } - @Override - public void offRequestFailed(Consumer handler) { - off(Events.BrowserContext.REQUEST_FAILED, handler); + private void disposeHarRouters() { + for (HarRouter router : harRouters) { + router.dispose(); + } + harRouters = new ArrayList<>(); } + // java: the Java API has no behavior option, unrouteAll() passes none. @Override - public void onRequestFinished(Consumer handler) { - on(Events.BrowserContext.REQUEST_FINISHED, handler); + public void unrouteAll() { + withTitle("Unroute requests", () -> { + unrouteInternal(routes, new ArrayList<>(), null); + disposeHarRouters(); + }); } @Override - public void offRequestFinished(Consumer handler) { - off(Events.BrowserContext.REQUEST_FINISHED, handler); + public void unroute(String url, Consumer handler) { + unroute(UrlMatcher.forGlob(baseUrl(), url, connection.localUtils(), false), handler); } @Override - public void onResponse(Consumer handler) { - on(Events.BrowserContext.RESPONSE, handler); + public void unroute(Pattern url, Consumer handler) { + unroute(new UrlMatcher(url), handler); } @Override - public void offResponse(Consumer handler) { - off(Events.BrowserContext.RESPONSE, handler); + public void unroute(Predicate url, Consumer handler) { + unroute(new UrlMatcher(url), handler); } - @Override - public ClockImpl clock() { - return clock; + void unroute(UrlMatcher url, Consumer handler) { + withTitle("Unroute requests", () -> { + List removed = new ArrayList<>(); + List remaining = new ArrayList<>(); + for (RouteHandler route : routes) { + if (route.url.equals(url) && (handler == null || route.handler == handler)) { + removed.add(route); + } else { + remaining.add(route); + } + } + unrouteInternal(removed, remaining, "default"); + }); } - @Override - public Credentials credentials() { - return credentials; + private void unrouteInternal(List removed, List remaining, String behavior) { + routes = remaining; + if (behavior != null && !"default".equals(behavior)) { + // java: Promise.all over the removed handlers is a loop, each stop() returns when done. + for (RouteHandler routeHandler : removed) { + routeHandler.stop(behavior); + } + } + updateInterceptionPatterns(); } - @Override - public Page waitForPage(WaitForPageOptions options, Runnable code) { - if (options == null) { - options = new WaitForPageOptions(); + private void disableInterception() { + wrapApiCall(() -> updateInterceptionPatterns(), null, true); + } + + private void updateInterceptionPatterns() { + BrowserContextSetNetworkInterceptionPatternsParams params = new BrowserContextSetNetworkInterceptionPatternsParams(); + params.patterns = RouteHandler.prepareInterceptionPatterns(routes); + channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); + } + + private void updateWebSocketInterceptionPatterns() { + BrowserContextSetWebSocketInterceptionPatternsParams params = new BrowserContextSetWebSocketInterceptionPatternsParams(); + params.patterns = WebSocketRouteHandler.prepareInterceptionPatterns(webSocketRoutes); + channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); + } + + String effectiveCloseReason() { + if (closeReason != null) { + return closeReason; } - return waitForEvent(Events.BrowserContext.PAGE, options.predicate, options.timeout, code); + return browser != null ? browser.closeReason : null; } - // waitForEvent in browserContext.ts + // java: the predicate and timeout are passed separately and the code to run is a Runnable. private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { double timeoutMs = timeoutSettings.timeout(timeout); Waiter waiter = Waiter.createForEvent(this, event); @@ -328,165 +744,297 @@ private T waitForEvent(String event, Predicate predicate, Double timeout, } @Override - public CDPSession newCDPSession(Page page) { + public String storageState(StorageStateOptions options) { + if (options == null) { + options = new StorageStateOptions(); + } + BrowserContextStorageStateParams params = new BrowserContextStorageStateParams(); + params.indexedDB = options.indexedDB; + params.opfs = options.opfs; + params.credentials = options.credentials; + // java: the state is returned as the raw JSON of the reply: a typed round trip would print -1 as -1.0 + // and differ from the string of APIRequestContext.storageState(). + JsonElement state = sendMessage("storageState", connection.protocolGson().toJsonTree(params).getAsJsonObject(), NO_TIMEOUT); + String storageState = state.toString(); + if (options.path != null) { + FileUtils.mkdirIfNeeded(options.path); + Utils.writeToFile(Serialization.toPrettyJson(storageState).getBytes(StandardCharsets.UTF_8), options.path); + } + return storageState; + } + + @Override + public void setStorageState(Path storageState) { + JsonElement state = prepareStorageState(storageState); + BrowserContextSetStorageStateParams params = new BrowserContextSetStorageStateParams(); + params.storageState = connection.protocolGson().fromJson(state, BrowserContextSetStorageStateParams.BrowserContextSetStorageStateParamsStorageState.class); + channel.setStorageState(params, NO_TIMEOUT); + } + + @Override + public List backgroundPages() { + return Collections.emptyList(); + } + + List serviceWorkers() { + return new ArrayList<>(serviceWorkers); + } + + // java: the 'page: expected Page or Frame' check is not ported, the overloads take a Page or a Frame. + @Override + public CDPSession newCDPSession(Page page) { BrowserContextNewCDPSessionParams params = new BrowserContextNewCDPSessionParams(); params.page = (PageImpl) page; return channel.newCDPSession(params, NO_TIMEOUT).session; } @Override - public CDPSession newCDPSession(Frame frame) { + public CDPSession newCDPSession(Frame page) { BrowserContextNewCDPSessionParams params = new BrowserContextNewCDPSessionParams(); - params.frame = (FrameImpl) frame; + params.frame = (FrameImpl) page; return channel.newCDPSession(params, NO_TIMEOUT).session; } - @Override - public boolean isClosed() { - return closingOrClosed; + void onClose() { + closingStatus = "closed"; + if (browser != null) { + browser.contexts.remove(this); + browser.browserType.contexts.remove(this); + browser.browserType.playwright.selectors.contextsForSelectors.remove(this); + } + disposeHarRouters(); + tracing.resetStackCounter(); + request.tracing.resetStackCounter(); + emit(Events.BrowserContext.CLOSE, this); } + // java: Symbol.asyncDispose is not ported. + @Override public void close(CloseOptions options) { + if (options == null) { + options = new CloseOptions(); + } + if (isClosed()) { + return; + } + closeReason = options.reason; + closingStatus = "closing"; + request.dispose(convertType(options, APIRequestContext.DisposeOptions.class)); + instrumentation.runBeforeCloseBrowserContext(this); RuntimeException harError = null; - if (!closingOrClosed) { - closingOrClosed = true; - if (options == null) { - options = new CloseOptions(); - } - closeReason = options.reason; - try { - request.dispose(convertType(options, APIRequestContext.DisposeOptions.class)); - } catch (TargetClosedError e) { - // The request context was disposed by the user already. - } - try { - tracing.exportAllHars(); - } catch (RuntimeException e) { - harError = e; - } - BrowserContextCloseParams params = toProtocol(options, BrowserContextCloseParams.class); - channel.close(params, NO_TIMEOUT); + try { + tracing.exportAllHars(); + } catch (RuntimeException e) { + harError = e; } - runUntil(() -> {}, closePromise); + channel.close(toProtocol(options, BrowserContextCloseParams.class), NO_TIMEOUT); + runUntil(() -> {}, closedPromise); if (harError != null) { throw harError; } } - @Override - public List cookies(String url) { - return cookies(url == null ? new ArrayList<>() : Collections.singletonList(url)); + void showRecorder(BrowserContextShowRecorderParams params) { + channel.showRecorder(params, NO_TIMEOUT); } - - @Override - public void addCookies(List cookies) { - BrowserContextAddCookiesParams params = new BrowserContextAddCookiesParams(); - params.cookies = connection.protocolGson().fromJson(gson().toJsonTree(cookies), TypeToken.getParameterized(List.class, SetNetworkCookie.class).getType()); - channel.addCookies(params, NO_TIMEOUT); + void startRecording(BrowserContextStartRecordingParams params, RecorderEventSink eventSink) { + onRecorderEventSink = eventSink; + channel.startRecording(params, NO_TIMEOUT); } - @Override - public AutoCloseable addInitScript(String script) { - BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); - params.source = script; - return channel.addInitScript(params, NO_TIMEOUT).disposable; - } - - @Override - public AutoCloseable addInitScript(Path path) { + void stopRecording() { try { - byte[] bytes = readAllBytes(path); - return addInitScript(new String(bytes, UTF_8)); - } catch (IOException e) { - throw new PlaywrightException("Failed to read script from file", e); + channel.stopRecording(NO_TIMEOUT); + } finally { + onRecorderEventSink = null; } } - @Override - public List backgroundPages() { - return Collections.emptyList(); + void exposeConsoleApi() { + channel.exposeConsoleApi(NO_TIMEOUT); } - @Override - public BrowserImpl browser() { - return browser; + // java: upstream reads a path given as a string and passes an object through; Java options hold a Path. + static JsonElement prepareStorageState(Path storageState) { + try { + return JsonParser.parseString(new String(Files.readAllBytes(storageState), StandardCharsets.UTF_8)); + } catch (IOException e) { + // java: the message the Java client always had, tests match on it. + throw new PlaywrightException("Failed to read storage state from file", e); + } catch (JsonParseException e) { + throw new PlaywrightException("Error reading storage state from " + storageState + ":\n" + e.getMessage(), e); + } } - @Override - public void clearCookies(ClearCookiesOptions options) { + // java: the result is the params of Browser.newContext, BrowserType.launchPersistentContext copies it into its own params. + static BrowserNewContextParams prepareBrowserContextParams(Browser.NewContextOptions options) { if (options == null) { - options = new ClearCookiesOptions(); + options = new Browser.NewContextOptions(); } - BrowserContextClearCookiesParams params = connection.protocolGson().fromJson(toClearCookiesParams(options.name, options.domain, options.path), BrowserContextClearCookiesParams.class); - channel.clearCookies(params, NO_TIMEOUT); + if (options.extraHTTPHeaders != null) { + RawHeaders.validateHeaders(options.extraHTTPHeaders); + } + // java: the options whose Java type differs from the protocol are converted one by one below, + // the others are copied by toProtocol, which also maps an empty Optional to 'no-override' + // for colorScheme, reducedMotion, forcedColors and contrast. + Browser.NewContextOptions rest = Utils.clone(options); + rest.viewportSize = null; + rest.extraHTTPHeaders = null; + rest.screenSize = null; + rest.storageState = null; + rest.storageStatePath = null; + rest.acceptDownloads = null; + rest.clientCertificates = null; + rest.httpCredentials = null; + rest.recordVideoDir = null; + rest.recordVideoSize = null; + rest.recordVideoFps = null; + rest.recordHarContent = null; + rest.recordHarMode = null; + rest.recordHarOmitContent = null; + rest.recordHarPath = null; + rest.recordHarUrlFilter = null; + BrowserNewContextParams contextParams = toProtocol(rest, BrowserNewContextParams.class); + if (options.viewportSize != null && options.viewportSize.isPresent()) { + contextParams.viewport = new BrowserNewContextParams.BrowserNewContextParamsViewport(); + contextParams.viewport.width = options.viewportSize.get().width; + contextParams.viewport.height = options.viewportSize.get().height; + } + contextParams.noDefaultViewport = options.viewportSize != null && !options.viewportSize.isPresent(); + contextParams.extraHTTPHeaders = options.extraHTTPHeaders != null ? Headers.headersObjectToArray(options.extraHTTPHeaders) : null; + if (options.screenSize != null) { + contextParams.screen = new BrowserNewContextParams.BrowserNewContextParamsScreen(); + contextParams.screen.width = options.screenSize.width; + contextParams.screen.height = options.screenSize.height; + } + // java: storageState is the JSON text of the state, storageStatePath the file to read it from. + JsonElement storageState = null; + if (options.storageState != null) { + storageState = JsonParser.parseString(options.storageState); + } else if (options.storageStatePath != null) { + storageState = prepareStorageState(options.storageStatePath); + } + if (storageState != null) { + contextParams.storageState = toProtocol(storageState, BrowserNewContextParams.BrowserNewContextParamsStorageState.class); + } + contextParams.acceptDownloads = toAcceptDownloadsProtocol(options.acceptDownloads); + List clientCertificates = toClientCertificatesProtocol(options.clientCertificates); + if (clientCertificates != null) { + contextParams.clientCertificates = new ArrayList<>(); + for (PlaywrightNewRequestParams.PlaywrightNewRequestParamsClientCertificates cert : clientCertificates) { + contextParams.clientCertificates.add(convertType(cert, BrowserNewContextParams.BrowserNewContextParamsClientCertificates.class)); + } + } + contextParams.httpCredentials = toHttpCredentialsProtocol(options.httpCredentials); + // java: recordVideo is the flat recordVideoDir, recordVideoSize and recordVideoFps options; a size or fps + // without a dir is an error instead of being dropped. + if (options.recordVideoDir != null) { + contextParams.recordVideo = new BrowserNewContextParams.BrowserNewContextParamsRecordVideo(); + contextParams.recordVideo.dir = options.recordVideoDir.toAbsolutePath().toString(); + if (options.recordVideoSize != null) { + contextParams.recordVideo.size = new BrowserNewContextParams.BrowserNewContextParamsRecordVideo.BrowserNewContextParamsRecordVideoSize(); + contextParams.recordVideo.size.width = options.recordVideoSize.width; + contextParams.recordVideo.size.height = options.recordVideoSize.height; + } + contextParams.recordVideo.fps = options.recordVideoFps; + } else if (options.recordVideoSize != null) { + throw new PlaywrightException("recordVideoSize is set but recordVideoDir is null"); + } else if (options.recordVideoFps != null) { + throw new PlaywrightException("recordVideoFps is set but recordVideoDir is null"); + } + // java: the flat recordHar* options are checked here, initializeHarFromOptions starts the recording. + if (options.recordHarPath == null) { + if (options.recordHarOmitContent != null) { + throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null"); + } + if (options.recordHarUrlFilter != null) { + throw new PlaywrightException("recordHarUrlFilter is set but recordHarPath is null"); + } + if (options.recordHarMode != null) { + throw new PlaywrightException("recordHarMode is set but recordHarPath is null"); + } + if (options.recordHarContent != null) { + throw new PlaywrightException("recordHarContent is set but recordHarPath is null"); + } + } + return contextParams; } - @Override - public void clearPermissions() { - channel.clearPermissions(NO_TIMEOUT); + // java: the option is a single HttpCredentials or a list of them. + @SuppressWarnings("unchecked") + static List toHttpCredentialsProtocol(Object credentials) { + if (credentials == null) { + return null; + } + List list = credentials instanceof List + ? (List) credentials + : Collections.singletonList((com.microsoft.playwright.options.HttpCredentials) credentials); + if (list.isEmpty()) { + return null; + } + // java: converted to the protocol struct, the send enum becomes its lower-case name. + return gson().fromJson(gson().toJsonTree(list), new TypeToken>() {}.getType()); } - @Override - public List cookies(List urls) { - BrowserContextCookiesParams params = new BrowserContextCookiesParams(); - params.urls = urls == null ? new ArrayList<>() : urls; - BrowserContextCookiesResult result = channel.cookies(params, NO_TIMEOUT); - Cookie[] cookies = gson().fromJson(gson().toJsonTree(result.cookies), Cookie[].class); - return asList(cookies); + private static String toAcceptDownloadsProtocol(Boolean acceptDownloads) { + if (acceptDownloads == null) { + return null; + } + if (acceptDownloads) { + return "accept"; + } + return "deny"; } - @Override - public AutoCloseable exposeBinding(String name, BindingCallback playwrightBinding) { - return exposeBindingImpl(name, playwrightBinding); + static List toClientCertificatesProtocol(List certs) { + if (certs == null) { + return null; + } + List result = new ArrayList<>(); + for (ClientCertificate cert : certs) { + PlaywrightNewRequestParams.PlaywrightNewRequestParamsClientCertificates c = new PlaywrightNewRequestParams.PlaywrightNewRequestParamsClientCertificates(); + c.origin = cert.origin; + c.cert = bufferizeContent(cert.cert, cert.certPath); + c.key = bufferizeContent(cert.key, cert.keyPath); + c.pfx = bufferizeContent(cert.pfx, cert.pfxPath); + c.passphrase = cert.passphrase; + result.add(c); + } + return result; } - private AutoCloseable exposeBindingImpl(String name, BindingCallback playwrightBinding) { - if (bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered"); + // java: the local function of toClientCertificatesProtocol. + private static byte[] bufferizeContent(byte[] value, Path filePath) { + if (value != null) { + return value; } - for (PageImpl page : pages) { - if (page.bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered in one of the pages"); + if (filePath != null) { + try { + return Files.readAllBytes(filePath); + } catch (IOException e) { + throw new PlaywrightException("Failed to read from file", e); } } - bindings.put(name, playwrightBinding); - - BrowserContextExposeBindingParams params = new BrowserContextExposeBindingParams(); - params.name = name; - return channel.exposeBinding(params, NO_TIMEOUT).disposable; - } - - @Override - public AutoCloseable exposeFunction(String name, FunctionCallback playwrightFunction) { - return exposeBindingImpl(name, (BindingCallback.Source source, Object... args) -> playwrightFunction.call(args)); + return null; } + // java: members of the generated BrowserContext interface without an upstream counterpart: + // the fields' accessors, typed listeners, callback waits, waitForCondition, and the parsed baseURL. @Override - public void grantPermissions(List permissions, GrantPermissionsOptions options) { - if (options == null) { - options = new GrantPermissionsOptions(); - } - if (permissions == null) { - permissions = new ArrayList<>(); - } - BrowserContextGrantPermissionsParams params = toProtocol(options, BrowserContextGrantPermissionsParams.class); - params.permissions = permissions; - channel.grantPermissions(params, NO_TIMEOUT); + public ClockImpl clock() { + return clock; } @Override - public PageImpl newPage() { - if (ownerPage != null) { - throw new PlaywrightException("Please use browser.newContext()"); - } - return channel.newPage(NO_TIMEOUT).page; + public Credentials credentials() { + return credentials; } @Override - public List pages() { - return new ArrayList<>(pages); + public DebuggerImpl debugger() { + return debugger; } @Override @@ -495,429 +1043,217 @@ public APIRequestContextImpl request() { } @Override - public AutoCloseable route(String url, Consumer handler, RouteOptions options) { - route(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils(), false), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + public TracingImpl tracing() { + return tracing; + } + + URL baseUrl() { + if (options.baseURL != null) { + try { + return new URL(options.baseURL); + } catch (MalformedURLException e) { + } + } + return null; } @Override - public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + public void onBackgroundPage(Consumer handler) { + on(Events.BrowserContext.BACKGROUND_PAGE, handler); } @Override - public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + public void offBackgroundPage(Consumer handler) { + off(Events.BrowserContext.BACKGROUND_PAGE, handler); } @Override - public void routeFromHAR(Path har, RouteFromHAROptions options) { - if (options == null) { - options = new RouteFromHAROptions(); - } - if (options.update != null && options.update) { - recordIntoHar(null, har, options, null); - return; - } - UrlMatcher matcher = UrlMatcher.forOneOf(baseUrl(), options.url, this.connection.localUtils(), false); - HARRouter harRouter = new HARRouter(connection.localUtils(), har, options.notFound); - onClose(context -> harRouter.dispose()); - route(matcher, route -> harRouter.handle(route), null); + public void onClose(Consumer handler) { + on(Events.BrowserContext.CLOSE, handler); } - private void route(UrlMatcher matcher, Consumer handler, RouteOptions options) { - routes.add(matcher, handler, options == null ? null : options.times); - updateInterceptionPatterns(); + @Override + public void offClose(Consumer handler) { + off(Events.BrowserContext.CLOSE, handler); } @Override - public void routeWebSocket(String url, Consumer handler) { - routeWebSocketImpl(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils(), true), handler); + public void onConsoleMessage(Consumer handler) { + on(Events.BrowserContext.CONSOLE, handler); } @Override - public void routeWebSocket(Pattern pattern, Consumer handler) { - routeWebSocketImpl(new UrlMatcher(pattern), handler); + public void offConsoleMessage(Consumer handler) { + off(Events.BrowserContext.CONSOLE, handler); } @Override - public void routeWebSocket(Predicate predicate, Consumer handler) { - routeWebSocketImpl(new UrlMatcher(predicate), handler); + public void onDialog(Consumer handler) { + on(Events.BrowserContext.DIALOG, handler); } - private void routeWebSocketImpl(UrlMatcher matcher, Consumer handler) { - webSocketRoutes.add(matcher, handler); - updateWebSocketInterceptionPatterns(); + @Override + public void offDialog(Consumer handler) { + off(Events.BrowserContext.DIALOG, handler); } - void recordIntoHar(PageImpl page, Path har, RouteFromHAROptions options, HarContentPolicy contentPolicy) { - if (contentPolicy == null) { - contentPolicy = Utils.convertType(options.updateContent, HarContentPolicy.class); - } - tracing.recordIntoHar(page, har, options.url, contentPolicy, options.updateMode, null); + @Override + public void onDialogClosed(Consumer handler) { + on(Events.BrowserContext.DIALOG_CLOSED, handler); } @Override - public void setDefaultNavigationTimeout(double timeout) { - timeoutSettings.setDefaultNavigationTimeout(timeout); + public void offDialogClosed(Consumer handler) { + off(Events.BrowserContext.DIALOG_CLOSED, handler); } @Override - public void setDefaultTimeout(double timeout) { - timeoutSettings.setDefaultTimeout(timeout); + public void onDownload(Consumer handler) { + on(Events.BrowserContext.DOWNLOAD, handler); } @Override - public void setExtraHTTPHeaders(Map headers) { - BrowserContextSetExtraHTTPHeadersParams params = new BrowserContextSetExtraHTTPHeadersParams(); - params.headers = new ArrayList<>(); - for (Map.Entry e : headers.entrySet()) { - NameValue header = new NameValue(); - header.name = e.getKey(); - header.value = e.getValue(); - params.headers.add(header); - } - channel.setExtraHTTPHeaders(params, NO_TIMEOUT); + public void offDownload(Consumer handler) { + off(Events.BrowserContext.DOWNLOAD, handler); } @Override - public void setGeolocation(Geolocation geolocation) { - BrowserContextSetGeolocationParams params = new BrowserContextSetGeolocationParams(); - if (geolocation != null) { - params.geolocation = toProtocol(geolocation, BrowserContextSetGeolocationParams.BrowserContextSetGeolocationParamsGeolocation.class); - } - channel.setGeolocation(params, NO_TIMEOUT); + public void onFrameAttached(Consumer handler) { + on(Events.BrowserContext.FRAME_ATTACHED, handler); } @Override - public void setOffline(boolean offline) { - BrowserContextSetOfflineParams params = new BrowserContextSetOfflineParams(); - params.offline = offline; - channel.setOffline(params, NO_TIMEOUT); + public void offFrameAttached(Consumer handler) { + off(Events.BrowserContext.FRAME_ATTACHED, handler); } @Override - public void setStorageState(Path storageState) { - try { - String state = new String(readAllBytes(storageState), UTF_8); - BrowserContextSetStorageStateParams params = new BrowserContextSetStorageStateParams(); - params.storageState = connection.protocolGson().fromJson(state, BrowserContextSetStorageStateParams.BrowserContextSetStorageStateParamsStorageState.class); - channel.setStorageState(params, NO_TIMEOUT); - } catch (IOException e) { - throw new PlaywrightException("Failed to read storage state from file", e); - } + public void onFrameDetached(Consumer handler) { + on(Events.BrowserContext.FRAME_DETACHED, handler); } @Override - public String storageState(StorageStateOptions options) { - if (options == null) { - options = new StorageStateOptions(); - } - BrowserContextStorageStateParams params = toProtocol(options, BrowserContextStorageStateParams.class); - // The reply is returned to the user verbatim: a typed round trip would print -1 as -1.0 and - // differ from the raw string of APIRequestContext.storageState(), so the typed params go through - // the JsonObject overload and the result stays a JsonElement. - JsonElement json = sendMessage("storageState", connection.protocolGson().toJsonTree(params).getAsJsonObject(), NO_TIMEOUT); + public void offFrameDetached(Consumer handler) { + off(Events.BrowserContext.FRAME_DETACHED, handler); + } - String storageState = json.toString(); - if (options.path != null) { - Utils.writeToFile(Serialization.toPrettyJson(storageState).getBytes(StandardCharsets.UTF_8), options.path); - } - return storageState; + @Override + public void onFrameNavigated(Consumer handler) { + on(Events.BrowserContext.FRAME_NAVIGATED, handler); } @Override - public DebuggerImpl debugger() { - return debugger; + public void offFrameNavigated(Consumer handler) { + off(Events.BrowserContext.FRAME_NAVIGATED, handler); } - void setTracesDir(Path tracesDir) { - tracing.setTracesDir(tracesDir); - request.tracing().setTracesDir(tracesDir); + @Override + public void onPage(Consumer handler) { + on(Events.BrowserContext.PAGE, handler); } @Override - public TracingImpl tracing() { - return tracing; + public void offPage(Consumer handler) { + off(Events.BrowserContext.PAGE, handler); } @Override - public void unrouteAll() { - routes.removeAll(); - updateInterceptionPatterns(); + public void onPageClose(Consumer handler) { + on(Events.BrowserContext.PAGE_CLOSE, handler); } @Override - public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(this.baseUrl(), url, this.connection.localUtils(), false), handler); + public void offPageClose(Consumer handler) { + off(Events.BrowserContext.PAGE_CLOSE, handler); } @Override - public void unroute(Pattern url, Consumer handler) { - unroute(new UrlMatcher(url), handler); + public void onPageLoad(Consumer handler) { + on(Events.BrowserContext.PAGE_LOAD, handler); } @Override - public void unroute(Predicate url, Consumer handler) { - unroute(new UrlMatcher(url), handler); + public void offPageLoad(Consumer handler) { + off(Events.BrowserContext.PAGE_LOAD, handler); } @Override - public void waitForCondition(BooleanSupplier predicate, WaitForConditionOptions options) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableContextClose<>()); - waitables.add(timeoutSettings.createWaitable(options == null ? null : options.timeout)); - waitables.add(new WaitablePredicate<>(predicate)); - runUntil(() -> {}, new WaitableRace<>(waitables)); + public void onWebError(Consumer handler) { + on(Events.BrowserContext.WEB_ERROR, handler); } @Override - public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - if (options == null) { - options = new WaitForConsoleMessageOptions(); - } - return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, code); + public void offWebError(Consumer handler) { + off(Events.BrowserContext.WEB_ERROR, handler); } - private class WaitableContextClose extends WaitableEvent { - WaitableContextClose() { - super(BrowserContextImpl.this, Events.BrowserContext.CLOSE); - } + @Override + public void onRequest(Consumer handler) { + on(Events.BrowserContext.REQUEST, handler); + } - @Override - public R get() { - throw new TargetClosedError(effectiveCloseReason()); - } + @Override + public void offRequest(Consumer handler) { + off(Events.BrowserContext.REQUEST, handler); } - private void unroute(UrlMatcher matcher, Consumer handler) { - routes.remove(matcher, handler); - updateInterceptionPatterns(); + @Override + public void onRequestFailed(Consumer handler) { + on(Events.BrowserContext.REQUEST_FAILED, handler); } - private void updateInterceptionPatterns() { - BrowserContextSetNetworkInterceptionPatternsParams params = connection.protocolGson().fromJson(routes.interceptionPatterns(), BrowserContextSetNetworkInterceptionPatternsParams.class); - channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); + @Override + public void offRequestFailed(Consumer handler) { + off(Events.BrowserContext.REQUEST_FAILED, handler); } - private void updateWebSocketInterceptionPatterns() { - BrowserContextSetWebSocketInterceptionPatternsParams params = connection.protocolGson().fromJson(webSocketRoutes.interceptionPatterns(), BrowserContextSetWebSocketInterceptionPatternsParams.class); - channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); + @Override + public void onRequestFinished(Consumer handler) { + on(Events.BrowserContext.REQUEST_FINISHED, handler); } - void handleRoute(RouteImpl route) { - Router.HandleResult handled = routes.handle(route); - if (handled != Router.HandleResult.NoMatchingHandler) { - try { - updateInterceptionPatterns(); - } catch (PlaywrightException e) { - // Like the Node.js client, ignore the error when the page or the context was closed meanwhile. - if (!isSafeCloseError(e)) { - throw e; - } - } - } - if (handled == Router.HandleResult.NoMatchingHandler || handled == Router.HandleResult.Fallback) { - route.continueAsFallback(); - } + @Override + public void offRequestFinished(Consumer handler) { + off(Events.BrowserContext.REQUEST_FINISHED, handler); } - void handleWebSocketRoute(WebSocketRouteImpl route) { - if (!webSocketRoutes.handle(route)) { - route.connectToServer(); - } + @Override + public void onResponse(Consumer handler) { + on(Events.BrowserContext.RESPONSE, handler); } - WaitableResult pause() { - return sendMessageAsync("pause", new BrowserContextPauseParams()); + @Override + public void offResponse(Consumer handler) { + off(Events.BrowserContext.RESPONSE, handler); } @Override - protected void handleEvent(String event, JsonObject params) { - if ("dialog".equals(event)) { - String guid = params.getAsJsonObject("dialog").get("guid").getAsString(); - DialogImpl dialog = connection.getExistingObject(guid); - boolean hasListeners = false; - if (listenerCount(Events.BrowserContext.DIALOG) > 0) { - hasListeners = true; - emit(Events.BrowserContext.DIALOG, dialog); - } - PageImpl page = dialog.page(); - if (page != null) { - if (page.listenerCount(Events.Page.DIALOG) > 0) { - hasListeners = true; - page.emit(Events.Page.DIALOG, dialog); - } - } - // Although we do similar handling on the server side, we still need this logic - // on the client side due to a possible race condition between two async calls: - // a) removing "dialog" listener subscription (client->server) - // b) actual "dialog" event (server->client) - if (!hasListeners) { - if ("beforeunload".equals(dialog.type())) { - try { - dialog.accept(); - } catch (PlaywrightException e) { - } - } else { - dialog.dismiss(); - } - } - } else if ("dialogClosed".equals(event)) { - DialogImpl dialog = connection.getExistingObject(params.getAsJsonObject("dialog").get("guid").getAsString()); - emit(Events.BrowserContext.DIALOG_CLOSED, dialog); - PageImpl page = dialog.page(); - if (page != null) { - page.emit(Events.Page.DIALOG_CLOSED, dialog); - } - } else if ("route".equals(event)) { - RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString()); - route.browserContext = this; - handleRoute(route); - } else if ("webSocketRoute".equals(event)) { - WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString()); - handleWebSocketRoute(route); - } else if ("page".equals(event)) { - PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - pages.add(page); - emit(Events.BrowserContext.PAGE, page); - if (page.opener() != null && !page.opener().isClosed()) { - page.opener().notifyPopup(page); - } - } else if ("bindingCall".equals(event)) { - BindingCall bindingCall = connection.getExistingObject(params.getAsJsonObject("binding").get("guid").getAsString()); - BindingCallback binding = bindings.get(bindingCall.name()); - if (binding != null) { - bindingCall.call(binding); - } - } else if ("console".equals(event)) { - BrowserContextConsoleEvent consoleEvent = connection.protocolGson().fromJson(params, BrowserContextConsoleEvent.class); - PageImpl page = consoleEvent.page; - WorkerImpl worker = consoleEvent.worker; - ConsoleMessageImpl message = new ConsoleMessageImpl(consoleEvent); - emit(Events.BrowserContext.CONSOLE, message); - if (worker != null) { - worker.emit(Events.Worker.CONSOLE, message); - } - if (page != null) { - page.emit(Events.Page.CONSOLE, message); - } - } else if ("request".equals(event)) { - String guid = params.getAsJsonObject("request").get("guid").getAsString(); - RequestImpl request = connection.getExistingObject(guid); - emit(Events.BrowserContext.REQUEST, request); - if (params.has("page")) { - PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.emit(Events.Page.REQUEST, request); - } - } else if ("requestFailed".equals(event)) { - String guid = params.getAsJsonObject("request").get("guid").getAsString(); - RequestImpl request = connection.getExistingObject(guid); - request.didFailOrFinish = true; - if (params.has("failureText")) { - request.failure = params.get("failureText").getAsString(); - } - if (request.timing != null) { - request.setResponseEndTiming(params.get("responseEndTiming").getAsDouble()); - } - emit(Events.BrowserContext.REQUEST_FAILED, request); - if (params.has("page")) { - PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.emit(Events.Page.REQUEST_FAILED, request); - } - } else if ("requestFinished".equals(event)) { - String guid = params.getAsJsonObject("request").get("guid").getAsString(); - RequestImpl request = connection.getExistingObject(guid); - request.didFailOrFinish = true; - if (request.timing != null) { - request.setResponseEndTiming(params.get("responseEndTiming").getAsDouble()); - } - emit(Events.BrowserContext.REQUEST_FINISHED, request); - if (params.has("page")) { - PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.emit(Events.Page.REQUEST_FINISHED, request); - } - } else if ("response".equals(event)) { - String guid = params.getAsJsonObject("response").get("guid").getAsString(); - ResponseImpl response = connection.getExistingObject(guid); - emit(Events.BrowserContext.RESPONSE, response); - if (params.has("page")) { - PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.emit(Events.Page.RESPONSE, response); - } - } else if ("pageError".equals(event)) { - String errorStr = parseError(params.getAsJsonObject("error")); - PageImpl page; - try { - page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - } catch (PlaywrightException e) { - page = null; - } - WebErrorLocation location = null; - if (params.has("location")) { - location = gson().fromJson(params.getAsJsonObject("location"), WebErrorLocation.class); - } - emit(Events.BrowserContext.WEB_ERROR, new WebErrorImpl(page, errorStr, location)); - if (page != null) { - page.emit(Events.Page.PAGE_ERROR, errorStr); - } - } else if ("close".equals(event)) { - didClose(); + public Page waitForPage(WaitForPageOptions options, Runnable callback) { + if (options == null) { + options = new WaitForPageOptions(); } + return waitForEvent(Events.BrowserContext.PAGE, options.predicate, options.timeout, callback); } - void didClose() { - closingOrClosed = true; - if (browser != null) { - browser.contexts.remove(this); - browser.browserType.playwright.selectors.contextsForSelectors.remove(this); + @Override + public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable callback) { + if (options == null) { + options = new WaitForConsoleMessageOptions(); } - tracing.resetStackCounter(); - request.tracing().resetStackCounter(); - emit(Events.BrowserContext.CLOSE, this); + return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, callback); } - protected void initializeHarFromOptions(Browser.NewContextOptions options) { - if (options.recordHarPath == null) { - if (options.recordHarOmitContent != null) { - throw new PlaywrightException("recordHarOmitContent is set but recordHarPath is null"); - } - if (options.recordHarUrlFilter != null) { - throw new PlaywrightException("recordHarUrlFilter is set but recordHarPath is null"); - } - if (options.recordHarMode != null) { - throw new PlaywrightException("recordHarMode is set but recordHarPath is null"); - } - if (options.recordHarContent != null) { - throw new PlaywrightException("recordHarContent is set but recordHarPath is null"); + @Override + public void waitForCondition(BooleanSupplier condition, WaitForConditionOptions options) { + List> waitables = new ArrayList<>(); + waitables.add(new WaitableEvent(this, Events.BrowserContext.CLOSE) { + @Override + public Void get() { + throw new TargetClosedError(effectiveCloseReason()); } - return; - } - - HarContentPolicy contentPolicy = options.recordHarContent; - if (contentPolicy == null && options.recordHarOmitContent != null && options.recordHarOmitContent == true) { - contentPolicy = HarContentPolicy.OMIT; - } - if (contentPolicy == null) { - contentPolicy = TracingImpl.isZip(options.recordHarPath) ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED; - } - RouteFromHAROptions routeFromHAROptions = new RouteFromHAROptions(); - - if (options.recordHarUrlFilter instanceof String) { - routeFromHAROptions.setUrl((String) options.recordHarUrlFilter); - } else if (options.recordHarUrlFilter instanceof Pattern) { - routeFromHAROptions.setUrl((Pattern) options.recordHarUrlFilter); - } - - if (options.recordHarMode != null) { - routeFromHAROptions.updateMode = options.recordHarMode; - } else { - routeFromHAROptions.updateMode = HarMode.FULL; - } - routeFromHAROptions.url = options.recordHarUrlFilter; - - recordIntoHar(null, options.recordHarPath, routeFromHAROptions, contentPolicy); + }); + waitables.add(timeoutSettings.createWaitable(options == null ? null : options.timeout)); + waitables.add(new WaitablePredicate<>(condition)); + runUntil(() -> {}, new WaitableRace<>(waitables)); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java index 5a0c23e26..e7115e833 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -14,209 +14,180 @@ * limitations under the License. */ +// Port of browser.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.Gson; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.*; +import com.microsoft.playwright.Browser; +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.BrowserType; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.BindResult; -import com.microsoft.playwright.options.ClientCertificate; -import com.microsoft.playwright.options.HttpCredentials; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; import java.util.function.Consumer; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Utils.*; import static com.microsoft.playwright.impl.Errors.isSafeCloseError; +import static com.microsoft.playwright.impl.Errors.isTargetClosedError; +import static com.microsoft.playwright.impl.FileUtils.mkdirIfNeeded; +import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toProtocol; +import static com.microsoft.playwright.impl.Utils.writeToFile; public class BrowserImpl extends ChannelOwner implements Browser { - // Insertion order, so that browser.contexts() lists the contexts in creation order like the other clients. final Set contexts = new LinkedHashSet<>(); - boolean isConnectedOverWebSocket; private boolean isConnected = true; + private final WaitableResult closedPromise; + boolean shouldCloseConnectionOnClose = false; BrowserTypeImpl browserType; - BrowserType.LaunchOptions launchOptions; - private Path tracePath; + private BrowserType.LaunchOptions options = new BrowserType.LaunchOptions(); + final String name; + final String browserName; + private Path path; String closeReason; final BrowserChannel channel = new BrowserChannel(this); + // java: from is not ported, generated results already hold the impl object. + BrowserImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); + BrowserInitializer browserInitializer = connection.protocolGson().fromJson(initializer, BrowserInitializer.class); + name = browserInitializer.name; + browserName = browserInitializer.browserName; + // java: the promise is a WaitableResult completed by a listener that removes itself, the once() of upstream. + closedPromise = new WaitableResult<>(); + on(Events.Browser.DISCONNECTED, new Consumer() { + @Override + public void accept(BrowserImpl browser) { + off(Events.Browser.DISCONNECTED, this); + closedPromise.complete(null); + } + }); } @Override - public void onContext(Consumer handler) { - on(Events.Browser.CONTEXT, handler); - } - - @Override - public void offContext(Consumer handler) { - off(Events.Browser.CONTEXT, handler); + void handleEvent(String event, JsonObject params) { + switch (event) { + case "context": + didCreateContext(connection.protocolGson().fromJson(params, BrowserContextEvent.class).context); + break; + case "close": + didClose(); + break; + } } @Override - public void onDisconnected(Consumer handler) { - on(Events.Browser.DISCONNECTED, handler); + public BrowserType browserType() { + return browserType; } @Override - public void offDisconnected(Consumer handler) { - off(Events.Browser.DISCONNECTED, handler); + public BrowserContextImpl newContext(NewContextOptions options) { + return innerNewContext(options, false); } - @Override - public BrowserType browserType() { - return browserType; + BrowserContextImpl newContextForReuse(NewContextOptions options) { + return innerNewContext(options, true); } - @Override - public void close(CloseOptions options) { - if (options == null) { - options = new CloseOptions(); - } - closeReason = options.reason; - if (isConnectedOverWebSocket) { - try { - // java: the message of a call that fails because of this, the default close reason of JsonPipe. - connection.close("Browser has been closed"); - } catch (IOException e) { - throw new PlaywrightException("Failed to close browser connection", e); + void disconnectFromReusedContext(String reason) { + BrowserContextImpl context = null; + for (BrowserContextImpl c : contexts) { + if (c.forReuse) { + context = c; + break; } + } + if (context == null) { return; } - try { - channel.close(new BrowserCloseParams(), NO_TIMEOUT); - } catch (PlaywrightException e) { - if (!isSafeCloseError(e)) { - throw e; - } + instrumentation.runBeforeCloseBrowserContext(context); + for (Page page : context.pages()) { + ((PageImpl) page).onClose(); } + context.onClose(); + BrowserDisconnectFromReusedContextParams params = new BrowserDisconnectFromReusedContextParams(); + params.reason = reason; + channel.disconnectFromReusedContext(params, NO_TIMEOUT); } - void notifyRemoteClosed() { - // Emulate all pages, contexts and the browser closing upon disconnect. - for (BrowserContextImpl context : new ArrayList<>(contexts)) { - for (PageImpl page : new ArrayList<>(context.pages)) { - page.didClose(); - } - context.didClose(); + BrowserContextImpl innerNewContext(NewContextOptions userOptions, boolean forReuse) { + if (userOptions == null) { + userOptions = new NewContextOptions(); } - didClose(); - } - - @Override - public List contexts() { - return new ArrayList<>(contexts); + // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params below. + NewContextOptions options = userOptions; + instrumentation.runBeforeCreateBrowserContext(options); + BrowserNewContextParams contextOptions = BrowserContextImpl.prepareBrowserContextParams(options); + contextOptions.selectorEngines = new ArrayList<>(browserType.playwright.selectors.selectorEngines); + contextOptions.testIdAttributeName = browserType.playwright.selectors.testIdAttributeName; + // java: newContextForReuse takes its own params class with the same fields. + BrowserContextImpl context = forReuse + ? channel.newContextForReuse(connection.protocolGson().fromJson(connection.protocolGson().toJsonTree(contextOptions), BrowserNewContextForReuseParams.class), NO_TIMEOUT).context + : channel.newContext(contextOptions, NO_TIMEOUT).context; + if (forReuse) { + context.forReuse = true; + } + // java: no options.logger to set on the context, the Java options have no logger. + // java: the HAR options are the recordHar* fields of the options, upstream passes options.recordHar. + context.initializeHarFromOptions(options); + instrumentation.runAfterCreateBrowserContext(context); + return context; } - @Override - public boolean isConnected() { - return isConnected; + // java: logger is Object, the Java API has no Logger. + void connectToBrowserType(BrowserTypeImpl browserType, BrowserType.LaunchOptions browserOptions, Object logger) { + // Note: when using connect(), `browserType` is different from `this._parent`. + // This is why browser type is not wired up in the constructor, + // and instead this separate method is called later on. + this.browserType = browserType; + this.options = browserOptions; + this.logger = logger; + for (BrowserContextImpl context : contexts) { + setupBrowserContext(context); + } } - @Override - public BrowserContextImpl newContext(NewContextOptions options) { - if (options == null) { - options = new NewContextOptions(); - } else { - // Make a copy so that we can nullify some fields below. - options = convertType(options, NewContextOptions.class); + private void didCreateContext(BrowserContextImpl context) { + context.browser = this; + contexts.add(context); + // Note: when connecting to a browser, initial contexts arrive before `browserType` is set, + // and will be configured later in `_connectToBrowserType`. + if (browserType != null) { + setupBrowserContext(context); } + emit(Events.Browser.CONTEXT, context); + } - NewContextOptions harOptions = Utils.clone(options); - options.recordHarContent = null; - options.recordHarMode = null; - options.recordHarPath = null; - options.recordHarOmitContent = null; - options.recordHarUrlFilter = null; - - if (options.storageStatePath != null) { - try { - byte[] bytes = Files.readAllBytes(options.storageStatePath); - options.storageState = new String(bytes, StandardCharsets.UTF_8); - options.storageStatePath = null; - } catch (IOException e) { - throw new PlaywrightException("Failed to read storage state from file", e); - } - } - BrowserNewContextParams.BrowserNewContextParamsStorageState storageState = null; - if (options.storageState != null) { - storageState = connection.protocolGson().fromJson(options.storageState, BrowserNewContextParams.BrowserNewContextParamsStorageState.class); - options.storageState = null; - } - // These two are converted below, their option types differ from the protocol ones. - Object httpCredentials = options.httpCredentials; - options.httpCredentials = null; - List clientCertificates = options.clientCertificates; - options.clientCertificates = null; - BrowserNewContextParams params = toProtocol(options, BrowserNewContextParams.class); - params.storageState = storageState; - if (options.recordVideoDir != null) { - BrowserNewContextParams.BrowserNewContextParamsRecordVideo recordVideo = new BrowserNewContextParams.BrowserNewContextParamsRecordVideo(); - recordVideo.dir = options.recordVideoDir.toAbsolutePath().toString(); - if (options.recordVideoSize != null) { - recordVideo.size = new BrowserNewContextParams.BrowserNewContextParamsRecordVideo.BrowserNewContextParamsRecordVideoSize(); - recordVideo.size.width = options.recordVideoSize.width; - recordVideo.size.height = options.recordVideoSize.height; - } - if (options.recordVideoFps != null) { - recordVideo.fps = options.recordVideoFps; - } - params.recordVideo = recordVideo; - } else if (options.recordVideoSize != null) { - throw new PlaywrightException("recordVideoSize is set but recordVideoDir is null"); - } else if (options.recordVideoFps != null) { - throw new PlaywrightException("recordVideoFps is set but recordVideoDir is null"); - } - if (options.viewportSize != null) { - if (options.viewportSize.isPresent()) { - params.viewport = new BrowserNewContextParams.BrowserNewContextParamsViewport(); - params.viewport.width = options.viewportSize.get().width; - params.viewport.height = options.viewportSize.get().height; - } else { - params.noDefaultViewport = true; - } - } - if (options.screenSize != null) { - params.screen = new BrowserNewContextParams.BrowserNewContextParamsScreen(); - params.screen.width = options.screenSize.width; - params.screen.height = options.screenSize.height; - } - params.clientCertificates = clientCertificatesToProtocol(clientCertificates); - params.httpCredentials = httpCredentialsToProtocol(httpCredentials); - params.acceptDownloads = options.acceptDownloads == null ? null : (options.acceptDownloads ? "accept" : "deny"); - params.selectorEngines = new ArrayList<>(browserType.playwright.selectors.selectorEngines); - params.testIdAttributeName = browserType.playwright.selectors.testIdAttributeName; - BrowserContextImpl context = channel.newContext(params, NO_TIMEOUT).context; - context.initializeHarFromOptions(harOptions); - return context; + private void setupBrowserContext(BrowserContextImpl context) { + context.logger = this.logger; + context.tracing.tracesDir = options.tracesDir; + context.request.tracing.tracesDir = options.tracesDir; + browserType.contexts.add(context); + browserType.playwright.selectors.contextsForSelectors.add(context); + // java: setDefaultTimeout and setDefaultNavigationTimeout of the Java API take a double, an unset (null) + // default goes to the TimeoutSettings directly. + context.timeoutSettings.setDefaultTimeout(browserType.playwright.defaultContextTimeout); + context.timeoutSettings.setDefaultNavigationTimeout(browserType.playwright.defaultContextNavigationTimeout); } @Override - public Page newPage(NewPageOptions options) { - return withTitle("Create Page", () -> newPageImpl(options)); + public List contexts() { + return new ArrayList<>(contexts); } @Override - public void startTracing(Page page, StartTracingOptions options) { - if (options == null) { - options = new StartTracingOptions(); - } - tracePath = options.path; - BrowserStartTracingParams params = toProtocol(options, BrowserStartTracingParams.class); - if (page != null) { - params.page = (PageImpl) page; - } - channel.startTracing(params, NO_TIMEOUT); + public String version() { + return initializer.get("version").getAsString(); } @Override @@ -234,136 +205,109 @@ public void unbind() { channel.stopServer(NO_TIMEOUT); } + @Override + public PageImpl newPage(NewPageOptions options) { + return withTitle("Create page", () -> { + BrowserContextImpl context = newContext(convertType(options, NewContextOptions.class)); + PageImpl page = (PageImpl) context.newPage(); + page.ownedContext = context; + context.ownerPage = page; + return page; + }); + } + + @Override + public boolean isConnected() { + return isConnected; + } + + @Override + public CDPSessionImpl newBrowserCDPSession() { + return channel.newBrowserCDPSession(NO_TIMEOUT).session; + } + + @Override + public void startTracing(Page page, StartTracingOptions options) { + if (options == null) { + options = new StartTracingOptions(); + } + path = options.path; + BrowserStartTracingParams params = toProtocol(options, BrowserStartTracingParams.class); + params.page = (PageImpl) page; + channel.startTracing(params, NO_TIMEOUT); + } + @Override public byte[] stopTracing() { ArtifactImpl artifact = channel.stopTracing(NO_TIMEOUT).artifact; - byte[] data = artifact.readAllBytes(); + // java: readAllBytes is readIntoBuffer. + byte[] buffer = artifact.readAllBytes(); artifact.delete(); - if (tracePath != null) { - try { - Files.createDirectories(tracePath.getParent()); - Files.write(tracePath, data); - } catch (IOException e) { - throw new PlaywrightException("Failed to write trace file", e); - } finally { - tracePath = null; - } + if (path != null) { + mkdirIfNeeded(path); + writeToFile(buffer, path); + path = null; } - return data; + return buffer; } - // The protocol takes a list of http credentials, the option is a single value or a list. - @SuppressWarnings("unchecked") - static List httpCredentialsToProtocol(Object httpCredentials) { - if (httpCredentials == null) { - return null; - } - List list = new ArrayList<>(); - if (httpCredentials instanceof List) { - list.addAll((List) httpCredentials); - } else { - list.add((HttpCredentials) httpCredentials); - } - if (list.isEmpty()) { - return null; - } - List result = new ArrayList<>(); - for (HttpCredentials credentials : list) { - com.microsoft.playwright.impl.protocol.HttpCredentials c = new com.microsoft.playwright.impl.protocol.HttpCredentials(); - c.username = credentials.username; - c.password = credentials.password; - c.origin = credentials.origin; - c.send = credentials.send == null ? null : credentials.send.name().toLowerCase(); - result.add(c); - } - return result; - } + // java: Symbol.asyncDispose is not ported. - static List clientCertificatesToProtocol(List clientCertificates) { - if (clientCertificates == null) { - return null; + @Override + public void close(CloseOptions options) { + if (options == null) { + options = new CloseOptions(); } - List result = new ArrayList<>(); - for (ClientCertificate cert : clientCertificates) { - BrowserNewContextParams.BrowserNewContextParamsClientCertificates c = new BrowserNewContextParams.BrowserNewContextParamsClientCertificates(); - c.origin = cert.origin; - try { - c.cert = cert.certPath != null ? Files.readAllBytes(cert.certPath) : cert.cert; - c.key = cert.keyPath != null ? Files.readAllBytes(cert.keyPath) : cert.key; - c.pfx = cert.pfxPath != null ? Files.readAllBytes(cert.pfxPath) : cert.pfx; - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); + closeReason = options.reason; + try { + if (shouldCloseConnectionOnClose) { + // java: the reason is what a pending call of the connection fails with, the default close reason of JsonPipe. + closeConnection("Browser has been closed"); + } else { + channel.close(toProtocol(options, BrowserCloseParams.class), NO_TIMEOUT); + } + runUntil(() -> {}, closedPromise); + } catch (PlaywrightException e) { + // java: also the safe close errors of the driver, which do not all arrive as TargetClosedError. + if (isTargetClosedError(e) || isSafeCloseError(e)) { + return; } - c.passphrase = cert.passphrase; - result.add(c); + throw e; } - return result; } - private Page newPageImpl(NewPageOptions options) { - BrowserContextImpl context = newContext(convertType(options, NewContextOptions.class)); - PageImpl page = context.newPage(); - page.ownedContext = context; - context.ownerPage = page; - return page; - } - - private String name() { - return initializer.get("name").getAsString(); - } - - boolean isChromium() { - return "chromium".equals(name()); + void didClose() { + isConnected = false; + emit(Events.Browser.DISCONNECTED, this); } + // java: typed listeners of the Java API. @Override - public String version() { - return initializer.get("version").getAsString(); + public void onContext(Consumer handler) { + on(Events.Browser.CONTEXT, handler); } @Override - void handleEvent(String event, JsonObject parameters) { - switch (event) { - case "context": - didCreateContext(connection.getExistingObject(parameters.getAsJsonObject("context").get("guid").getAsString())); - break; - case "close": - didClose(); - break; - } + public void offContext(Consumer handler) { + off(Events.Browser.CONTEXT, handler); } @Override - public CDPSession newBrowserCDPSession() { - return channel.newBrowserCDPSession(NO_TIMEOUT).session; + public void onDisconnected(Consumer handler) { + on(Events.Browser.DISCONNECTED, handler); } - protected void connectToBrowserType(BrowserTypeImpl browserType, Path tracesDir){ - // Note: when using connect(), `browserType` is different from `this.parent`. - // This is why browser type is not wired up in the constructor, and instead this separate method is called later on. - this.browserType = browserType; - this.tracePath = tracesDir; - - for (BrowserContextImpl context : contexts) { - context.setTracesDir(tracesDir); - browserType.playwright.selectors.contextsForSelectors.add(context); - } + @Override + public void offDisconnected(Consumer handler) { + off(Events.Browser.DISCONNECTED, handler); } - private void didCreateContext(BrowserContextImpl context) { - context.browser = this; - contexts.add(context); - // Note: when connecting to a browser, initial contexts arrive before `_browserType` is set, - // and will be configured later in `ConnectToBrowserType`. - if (browserType != null) { - context.setTracesDir(tracePath); - browserType.playwright.selectors.contextsForSelectors.add(context); + // java: Connection.close declares IOException. + private void closeConnection(String reason) { + try { + connection.close(reason); + } catch (IOException e) { + throw new PlaywrightException("Failed to close browser connection", e); } - emit(Events.Browser.CONTEXT, context); - } - - private void didClose() { - isConnected = false; - emit(Events.Browser.DISCONNECTED, this); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java index 971834010..5cb55bcc6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -14,31 +14,48 @@ * limitations under the License. */ +// Port of browserType.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.Gson; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.TimeoutError; -import com.microsoft.playwright.options.ClientCertificate; +import com.microsoft.playwright.impl.protocol.*; -import java.io.IOException; -import java.nio.file.Files; +import java.lang.reflect.Field; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; -import static com.microsoft.playwright.impl.BrowserImpl.httpCredentialsToProtocol; import static com.microsoft.playwright.impl.Utils.convertType; import static com.microsoft.playwright.impl.Utils.toProtocol; public class BrowserTypeImpl extends ChannelOwner implements BrowserType { - protected PlaywrightImpl playwright; + // java: LaunchServerOptions has no Java type, the launch options stand in for it. + interface BrowserServerLauncher { + BrowserServer launchServer(LaunchOptions options); + } + + // This is here just for api generation and checking. + // java: ChildProcess is a java.lang.Process. + interface BrowserServer { + Process process(); + + String wsEndpoint(); + + void close(); + + void kill(); + } + + BrowserServerLauncher serverLauncher; + final Set contexts = new LinkedHashSet<>(); + PlaywrightImpl playwright; final BrowserTypeChannel channel = new BrowserTypeChannel(this); @@ -46,193 +63,162 @@ public class BrowserTypeImpl extends ChannelOwner implements BrowserType { super(parent, type, guid, initializer); } + // java: from is not ported, generated results already hold the impl object. + + @Override + public String executablePath() { + JsonElement executablePath = initializer.get("executablePath"); + if (executablePath == null || executablePath.isJsonNull() || executablePath.getAsString().isEmpty()) { + throw new PlaywrightException("Browser is not supported on current platform"); + } + return executablePath.getAsString(); + } + + @Override + public String name() { + return initializer.get("name").getAsString(); + } + @Override public BrowserImpl launch(LaunchOptions options) { + LaunchOptions userOptions = options == null ? new LaunchOptions() : options; + return wrapApiCall(() -> { + // java: the userDataDir and port asserts are not ported, LaunchOptions has no such fields. + + // java: LaunchOptions has no logger, so options.logger and _defaultLaunchOptions?.logger are always unset. + Object logger = null; + LaunchOptions launchOptions = withDefaults(playwright.defaultLaunchOptions, userOptions, LaunchOptions.class); + // java: ignoreDefaultArgs and ignoreAllDefaultArgs are separate options and env is serialized as a name/value array. + BrowserTypeLaunchParams params = toProtocol(launchOptions, BrowserTypeLaunchParams.class); + BrowserImpl browser = channel.launch(params, new TimeoutSettings().launchTimeout(launchOptions.timeout)).browser; + browser.connectToBrowserType(this, launchOptions, logger); + return browser; + }, null, false); + } + + BrowserServer launchServer(LaunchOptions options) { if (options == null) { options = new LaunchOptions(); } - BrowserTypeLaunchParams params = toProtocol(options, BrowserTypeLaunchParams.class); - BrowserImpl browser = channel.launch(params, new TimeoutSettings().launchTimeout(options.timeout)).browser; - browser.browserType = this; - browser.launchOptions = options; - return browser; + if (serverLauncher == null) { + throw new PlaywrightException("Launching server is not supported"); + } + options = withDefaults(playwright.defaultLaunchOptions, options, LaunchOptions.class); + return serverLauncher.launchServer(options); } @Override - public Browser connect(String wsEndpoint, ConnectOptions options) { - if (options == null) { - options = new ConnectOptions(); - } - // We don't use gson() here as the headers map should be serialized to a json object. - // Serializing the options object itself (not field by field) keeps fields added by subclasses, like the tests do. - JsonObject optionsJson = new Gson().toJsonTree(options).getAsJsonObject(); - LocalUtilsConnectParams params = connection.protocolGson().fromJson(optionsJson, LocalUtilsConnectParams.class); - params.endpoint = wsEndpoint; - JsonObject headers = options.headers == null ? new JsonObject() : optionsJson.getAsJsonObject("headers"); - boolean foundBrowserHeader = false; - for (String name : headers.keySet()) { - if ("x-playwright-browser".equalsIgnoreCase(name)) { - foundBrowserHeader = true; - break; + public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options) { + LaunchPersistentContextOptions userOptions = options == null ? new LaunchPersistentContextOptions() : options; + return wrapApiCall(() -> { + // java: the port assert is not ported, LaunchPersistentContextOptions has no such field. + // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params below. + LaunchPersistentContextOptions persistentOptions = withDefaults(playwright.defaultLaunchOptions, userOptions, LaunchPersistentContextOptions.class); + instrumentation.runBeforeCreateBrowserContext(persistentOptions); + + // java: LaunchPersistentContextOptions has no logger, so options.logger and _defaultLaunchOptions?.logger are always unset. + Object logger = null; + // java: the context part of the options goes through prepareBrowserContextParams, the launch part through + // toProtocol of LaunchOptions; upstream spreads one options object into both. + Browser.NewContextOptions contextOptions = convertType(persistentOptions, Browser.NewContextOptions.class); + LaunchOptions launchOptions = convertType(persistentOptions, LaunchOptions.class); + BrowserNewContextParams contextParams = BrowserContextImpl.prepareBrowserContextParams(contextOptions); + contextParams.selectorEngines = new ArrayList<>(playwright.selectors.selectorEngines); + contextParams.testIdAttributeName = playwright.selectors.testIdAttributeName; + Gson gson = connection.protocolGson(); + JsonObject json = gson.toJsonTree(contextParams).getAsJsonObject(); + for (Map.Entry entry : gson.toJsonTree(toProtocol(launchOptions, BrowserTypeLaunchParams.class)).getAsJsonObject().entrySet()) { + json.add(entry.getKey(), entry.getValue()); } - } - if (!foundBrowserHeader) { - headers.addProperty("x-playwright-browser", name()); - } - params.headers = headers; + BrowserTypeLaunchPersistentContextParams persistentParams = gson.fromJson(json, BrowserTypeLaunchPersistentContextParams.class); + persistentParams.userDataDir = (userDataDir.isAbsolute() || userDataDir.toString().isEmpty()) ? userDataDir.toString() : userDataDir.toAbsolutePath().normalize().toString(); + BrowserTypeLaunchPersistentContextResult result = channel.launchPersistentContext(persistentParams, new TimeoutSettings().launchTimeout(persistentOptions.timeout)); + BrowserImpl browser = result.browser; + browser.connectToBrowserType(this, launchOptions, logger); + BrowserContextImpl context = result.context; + // java: the HAR options are the recordHar* fields of the options, upstream passes options.recordHar. + context.initializeHarFromOptions(contextOptions); + instrumentation.runAfterCreateBrowserContext(context); + return context; + }, null, false); + } - Double timeout = options.timeout; - if (timeout == null) { - timeout = 0.0; - } + // java: only the endpoint overload, the Java API has no options object with wsEndpoint, so there is no + // 'options.wsEndpoint is required' assert. + @Override + public BrowserImpl connect(String endpoint, ConnectOptions options) { + ConnectOptions params = options == null ? new ConnectOptions() : options; + return wrapApiCall(() -> connectImpl(endpoint, params), null, false); + } - long deadline = timeout == 0 ? 0 : System.nanoTime() + (long) (timeout * 1_000_000); - JsonPipe pipe = connection.localUtils().channel.connect(params, timeout).pipe; - Connection connection = new Connection(pipe, this.connection.env, this.connection.localUtils()); - PlaywrightImpl playwright; - if (deadline == 0) { - playwright = connection.initializePlaywright(); - } else { - try { - playwright = connection.initializePlaywright(deadline, timeout); - } catch (TimeoutError e) { - try { - connection.close(); - } catch (IOException ioe) { - ioe.printStackTrace(System.err); - } - throw e; - } - } - if (!playwright.initializer.has("preLaunchedBrowser")) { - try { - connection.close(); - } catch (IOException e) { - e.printStackTrace(System.err); - } - throw new PlaywrightException("Malformed endpoint. Did you use launchServer method?"); - } - playwright.selectors = this.playwright.selectors; - BrowserImpl browser = connection.getExistingObject(playwright.initializer.getAsJsonObject("preLaunchedBrowser").get("guid").getAsString()); - browser.isConnectedOverWebSocket = true; - browser.connectToBrowserType(this, null); - Consumer connectionCloseListener = t -> browser.notifyRemoteClosed(); - pipe.onClose(connectionCloseListener); - browser.onDisconnected(b -> { - pipe.offClose(connectionCloseListener); - try { - connection.close(); - } catch (IOException e) { - e.printStackTrace(System.err); - } - }); + // java: _connect is connectImpl, connect(endpoint, options) is the public method; upstream's params is one + // ConnectOptions object with the endpoint in it. + BrowserImpl connectImpl(String endpoint, ConnectOptions params) { + BrowserImpl browser = Connect.connectToBrowser(playwright, name(), endpoint, params); + browser.connectToBrowserType(this, new LaunchOptions(), null); return browser; } + // java: only the endpointURL overload, the Java API has no options object with wsEndpoint and no + // ConnectOverCDPTransport, so the isConnectionTransport branch and the wsEndpoint assert are not ported. @Override - public Browser connectOverCDP(String endpointURL, ConnectOverCDPOptions options) { - if (!"chromium".equals(name()) && !"webkit".equals(name())) { - throw new PlaywrightException("Connecting over CDP is only supported in Chromium and WebKit."); - } + public BrowserImpl connectOverCDP(String endpointURL, ConnectOverCDPOptions options) { if (options == null) { options = new ConnectOverCDPOptions(); } + if (endpointURL != null && !"chromium".equals(name()) && !"webkit".equals(name())) { + throw new PlaywrightException("Connecting over CDP is only supported in Chromium and WebKit."); + } BrowserTypeConnectOverCDPParams params = toProtocol(options, BrowserTypeConnectOverCDPParams.class); params.endpointURL = endpointURL; - BrowserImpl browser = channel.connectOverCDP(params, new TimeoutSettings().launchTimeout(options.timeout)).browser; - browser.connectToBrowserType(this, null); - return browser; + BrowserTypeConnectOverCDPResult result = channel.connectOverCDP(params, new TimeoutSettings().timeout(options.timeout)); + return browserFromConnectResult(result); } - public String executablePath() { - return initializer.get("executablePath").getAsString(); + private BrowserImpl browserFromConnectResult(BrowserTypeConnectOverCDPResult result) { + BrowserImpl browser = result.browser; + browser.connectToBrowserType(this, new LaunchOptions(), null); + if (result.defaultContext != null) { + instrumentation.runAfterCreateBrowserContext(result.defaultContext); + } + return browser; } - @Override - public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options) { - if (options == null) { - options = new LaunchPersistentContextOptions(); - } else { - // Make a copy so that we can nullify some fields below. - options = convertType(options, LaunchPersistentContextOptions.class); + // java: the { timeout } options are a plain parameter. + WorkerImpl connectToWorker(String endpoint, Double timeout) { + if (!"chromium".equals(name())) { + throw new PlaywrightException("Connecting to workers is only supported in Chromium."); } + BrowserTypeConnectToWorkerParams params = new BrowserTypeConnectToWorkerParams(); + params.endpoint = endpoint; + BrowserTypeConnectToWorkerResult result = channel.connectToWorker(params, new TimeoutSettings().timeout(timeout)); + return result.worker; + } - Browser.NewContextOptions harOptions = convertType(options, Browser.NewContextOptions.class); - options.recordHarContent = null; - options.recordHarMode = null; - options.recordHarPath = null; - options.recordHarOmitContent = null; - options.recordHarUrlFilter = null; - - // These two are converted below, their option types differ from the protocol ones. - Object httpCredentials = options.httpCredentials; - options.httpCredentials = null; - List clientCertificates = options.clientCertificates; - options.clientCertificates = null; - BrowserTypeLaunchPersistentContextParams params = toProtocol(options, BrowserTypeLaunchPersistentContextParams.class); - if (!userDataDir.isAbsolute() && !userDataDir.toString().isEmpty()) { - Path cwd = Paths.get("").toAbsolutePath(); - userDataDir = cwd.resolve(userDataDir); - } - params.userDataDir = userDataDir.toString(); - if (options.recordVideoDir != null) { - BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsRecordVideo recordVideo = new BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsRecordVideo(); - recordVideo.dir = options.recordVideoDir.toAbsolutePath().toString(); - if (options.recordVideoSize != null) { - recordVideo.size = new BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsRecordVideo.BrowserTypeLaunchPersistentContextParamsRecordVideoSize(); - recordVideo.size.width = options.recordVideoSize.width; - recordVideo.size.height = options.recordVideoSize.height; - } - if (options.recordVideoFps != null) { - recordVideo.fps = options.recordVideoFps; - } - params.recordVideo = recordVideo; - } else if (options.recordVideoSize != null) { - throw new PlaywrightException("recordVideoSize is set but recordVideoDir is null"); - } else if (options.recordVideoFps != null) { - throw new PlaywrightException("recordVideoFps is set but recordVideoDir is null"); - } - if (options.viewportSize != null) { - if (options.viewportSize.isPresent()) { - params.viewport = new BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsViewport(); - params.viewport.width = options.viewportSize.get().width; - params.viewport.height = options.viewportSize.get().height; - } else { - params.noDefaultViewport = true; - } + // java: isConnectionTransport is not ported, it is a JS typing check (typeof value.send === 'function') for an + // overload the Java API does not have. + + // java: the spread { ...defaults, ...options }, the fields set in options win; without defaults the options + // object itself is returned. + private static T withDefaults(LaunchOptions defaults, T options, Class optionsClass) { + if (defaults == null) { + return options; } - if (clientCertificates != null) { - params.clientCertificates = new ArrayList<>(); - for (ClientCertificate cert : clientCertificates) { - BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsClientCertificates c = new BrowserTypeLaunchPersistentContextParams.BrowserTypeLaunchPersistentContextParamsClientCertificates(); - c.origin = cert.origin; - try { - c.cert = cert.certPath != null ? Files.readAllBytes(cert.certPath) : cert.cert; - c.key = cert.keyPath != null ? Files.readAllBytes(cert.keyPath) : cert.key; - c.pfx = cert.pfxPath != null ? Files.readAllBytes(cert.pfxPath) : cert.pfx; - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); + T result = convertType(defaults, optionsClass); + try { + for (Field field : optionsClass.getDeclaredFields()) { + if (field.isSynthetic()) { + continue; + } + Object value = field.get(options); + if (value != null) { + field.set(result, value); } - c.passphrase = cert.passphrase; - params.clientCertificates.add(c); } + } catch (IllegalAccessException e) { + throw new PlaywrightException("Internal error", e); } - params.httpCredentials = httpCredentialsToProtocol(httpCredentials); - params.acceptDownloads = options.acceptDownloads == null ? null : (options.acceptDownloads ? "accept" : "deny"); - params.selectorEngines = new ArrayList<>(playwright.selectors.selectorEngines); - params.testIdAttributeName = playwright.selectors.testIdAttributeName; - BrowserTypeLaunchPersistentContextResult result = channel.launchPersistentContext(params, new TimeoutSettings().launchTimeout(options.timeout)); - BrowserImpl browser = result.browser; - browser.connectToBrowserType(this, options.tracesDir); - BrowserContextImpl context = result.context; - context.initializeHarFromOptions(harOptions); - context.setTracesDir(options.tracesDir); - return context; - } - - public String name() { - return initializer.get("name").getAsString(); + return result; } - } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java index 2e785a0cc..b3591b664 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of cdpSession.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -27,10 +28,13 @@ public class CDPSessionImpl extends ChannelOwner implements CDPSession { final CDPSessionChannel channel = new CDPSessionChannel(this); + // java: from is not ported, generated results already hold the impl object. + protected CDPSessionImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. @Override void handleEvent(String event, JsonObject parameters) { super.handleEvent(event, parameters); @@ -47,20 +51,21 @@ void handleEvent(String event, JsonObject parameters) { } } + // java: upstream rebinds on/addListener/off/removeListener/once to the EventEmitter ones; here the raw-typed overrides + // below do that, since the raw parameter type implements CDPSession.on and overrides EventEmitter.on at once. @Override - public void onClose(Consumer handler) { - on(Events.CDPSession.CLOSE, handler); + @SuppressWarnings("rawtypes") + public void on(String event, Consumer handler) { + super.on(event, handler); } @Override - public void offClose(Consumer handler) { - off(Events.CDPSession.CLOSE, handler); - } - - public JsonObject send(String method) { - return send(method, null); + @SuppressWarnings("rawtypes") + public void off(String event, Consumer handler) { + super.off(event, handler); } + // java: the AbortSignal of options.signal is not ported. @Override public JsonObject send(String method, JsonObject params, SendOptions options) { CDPSessionSendParams args = new CDPSessionSendParams(); @@ -68,25 +73,28 @@ public JsonObject send(String method, JsonObject params, SendOptions options) { args.method = method; Double timeout = options == null || options.timeout == null ? Double.valueOf(0) : options.timeout; CDPSessionSendResult response = channel.send(args, timeout); + // java: a missing result maps to null instead of throwing. if (response == null) return null; else return response.result.getAsJsonObject(); } - // java: the raw parameter type overrides EventEmitter.on(String, Consumer) and implements CDPSession.on at once. @Override - @SuppressWarnings("rawtypes") - public void on(String event, Consumer handler) { - super.on(event, handler); + public void detach() { + channel.detach(NO_TIMEOUT); } + // java: typed close handlers and the no-options overload of the generated CDPSession interface. @Override - @SuppressWarnings("rawtypes") - public void off(String event, Consumer handler) { - super.off(event, handler); + public void onClose(Consumer handler) { + on(Events.CDPSession.CLOSE, handler); } @Override - public void detach() { - channel.detach(NO_TIMEOUT); + public void offClose(Consumer handler) { + off(Events.CDPSession.CLOSE, handler); + } + + public JsonObject send(String method) { + return send(method, null); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index a52b5e8ae..a5c944ed9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -14,34 +14,36 @@ * limitations under the License. */ -// Port of packages/playwright-core/src/client/channelOwner.ts +// Port of channelOwner.ts. package com.microsoft.playwright.impl; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Consumer; -import java.util.function.Function; import java.util.function.Supplier; public class ChannelOwner extends EventEmitter { final Connection connection; private ChannelOwner parent; - private final Map objects = new HashMap<>(); + private final Map objects = new LinkedHashMap<>(); final String type; final String guid; + // java: _channel is the generated Channel field of each subclass. final JsonObject initializer; + // java: the Java API has no Logger, the field keeps upstream's Logger | undefined as an opaque Object. + Object logger; + final ClientInstrumentation instrumentation; private Map eventToSubscriptionMapping = new HashMap<>(); boolean wasCollected; - // java: a call without a timeout; the server does not enforce one. - static Double NO_TIMEOUT = null; - protected ChannelOwner(ChannelOwner parent, String type, String guid, JsonObject initializer) { this(parent.connection, parent, type, guid, initializer); } @@ -52,16 +54,20 @@ protected ChannelOwner(Connection connection, String type, String guid) { } private ChannelOwner(Connection connection, ChannelOwner parent, String type, String guid, JsonObject initializer) { + setMaxListeners(0); this.connection = connection; this.type = type; this.guid = guid; this.parent = parent; + this.instrumentation = this.connection.instrumentation; this.connection.registerObject(guid, this); if (this.parent != null) { this.parent.objects.put(guid, this); + this.logger = this.parent.logger; } + // java: _channel = _createChannel(new EventEmitter()) is the channel field of the subclass. this.initializer = initializer; } @@ -86,7 +92,10 @@ void updateSubscription(String event, boolean enabled) { // java: the listener is added first so that a null listener fails before anything is sent. @Override void on(String event, Consumer listener) { - addListener(event, listener); + super.on(event, listener); + if (listenerCount(event) == 1) { + updateSubscription(event, true); + } } @Override @@ -97,9 +106,18 @@ void addListener(String event, Consumer listener) { } } + @Override + void prependListener(String event, Consumer listener) { + super.prependListener(event, listener); + if (listenerCount(event) == 1) { + updateSubscription(event, true); + } + } + + // java: super.off calls removeListener below, which updates the subscription; upstream updates it a second time here. @Override void off(String event, Consumer listener) { - removeListener(event, listener); + super.off(event, listener); } @Override @@ -144,21 +162,44 @@ void dispose(String reason) { objects.clear(); } + JsonObject debugScopeState() { + JsonObject result = new JsonObject(); + result.addProperty("_guid", guid); + JsonArray objects = new JsonArray(); + for (ChannelOwner o : this.objects.values()) { + objects.add(o.debugScopeState()); + } + result.add("objects", objects); + return result; + } + + // java: _validatorToWireContext is not ported, there are no protocol validators; Connection.protocolGson() + // serializes the params (channel owners as {guid}, binary as base64). + // java: upstream's createChannel() wraps every channel call in wrapApiCall and sends the message - // from there. This builds the options of that message; the zone of a call without wrapApiCall is - // not installed, so that the calls of event handlers dispatched while the call waits are reported on their own. - private Connection.CallOptions callOptions(Double timeout) { + // from there; the sendMessage family at the bottom sends it, and this builds the options of that message. + // The zone of a call without wrapApiCall is not installed, so that the calls of event handlers dispatched + // while the call waits are reported on their own. The metainfo `internal` flag of a method has no Java counterpart. + private Connection.CallOptions callOptions(String method, JsonObject params, Double timeout) { ApiZone apiZone = connection.apiZone; if (apiZone == null) { - apiZone = new ApiZone(null, false); + apiZone = new ApiZone(null, null, false); } Connection.CallOptions options = new Connection.CallOptions(); options.timeout = timeout; if (!apiZone.internal && !apiZone.reported) { // Reporting/tracing/logging this api call for the first time. apiZone.reported = true; + // java: the stack trace is captured by the first reported message, not by wrapApiCall. + apiZone.frames = connection.captureLibraryStackTrace(); + instrumentation.onApiCallBegin(apiZone, type, method, params); + // java: without an api name from the stack, the log names the protocol call. + apiZone.logName = apiZone.apiName != null ? apiZone.apiName : Character.toLowerCase(type.charAt(0)) + type.substring(1) + "." + method; + logApiCall(logger, "=> " + apiZone.logName + " started"); + options.apiName = apiZone.apiName; options.title = apiZone.title; - options.frames = connection.captureLibraryStackTrace(); + options.frames = apiZone.frames; + options.callId = apiZone.callId; } else { // Since this api call is either internal, or has already been reported/traced once, // passing as internal. @@ -168,19 +209,73 @@ private Connection.CallOptions callOptions(Double timeout) { } R wrapApiCall(Supplier func, String title, boolean internal) { - if (connection.apiZone != null) { + Object logger = this.logger; + ApiZone existingApiZone = connection.apiZone; + if (existingApiZone != null) { return func.get(); } - // java: no stack trace is captured here, the first message of the call does it (see callOptions). - ApiZone apiZone = new ApiZone(title, internal); - connection.apiZone = apiZone; + + // java: captureLibraryStackTrace() runs on the first reported message (see callOptions); its apiName + // is not computed (see StackTraceCollector), the title stands in for it. + String apiName = title; + ApiZone apiZone = new ApiZone(title, apiName, internal); + try { - return func.get(); - } finally { - connection.apiZone = null; + R result; + connection.apiZone = apiZone; + try { + result = func.get(); + } finally { + connection.apiZone = null; + } + if (!internal) { + if (apiZone.logName != null) { + logApiCall(logger, "<= " + apiZone.logName + " succeeded"); + } + instrumentation.onApiCallEnd(apiZone); + } + return result; + } catch (RuntimeException e) { + // java: the message is not prefixed with the api name and the stack is not rewritten with the + // library frames; Java exceptions keep the message of the server and their own stack. + if (!internal) { + apiZone.error = e; + if (apiZone.logName != null) { + logApiCall(logger, "<= " + apiZone.logName + " failed"); + } + instrumentation.onApiCallEnd(apiZone); + } + throw e; } } + // java: upstream's toJSON keeps Jest from printing the object graph. + JsonObject toJSON() { + // Jest's expect library tries to print objects sometimes. + // RPC objects can contain links to lots of other objects, + // which can cause jest to crash. Let's help it out + // by just returning the important values. + JsonObject result = new JsonObject(); + result.addProperty("_type", type); + result.addProperty("_guid", guid); + return result; + } + + // java: the apiCall and internal decorators and wrapApiCallDecorator are withTitle(title, ...) and + // wrapApiCall(..., title, internal) below. + + // java: the logger is an opaque Object, nothing logs to it; debugLogger.log('api', ...) is logApiIfEnabled. + static void logApiCall(Object logger, String message) { + logApiIfEnabled(message); + } + + // java: tChannelImplToWire is toProtocolRef() below and the channel owner adapter of Connection.protocolGson(). + + // java: the members below have no counterpart in channelOwner.ts. + + // java: a call without a timeout; the server does not enforce one. + static Double NO_TIMEOUT = null; + // java: the Runnable overload for calls without a result. void wrapApiCall(Runnable func, String title, boolean internal) { wrapApiCall(() -> { @@ -204,7 +299,7 @@ WaitableResult sendMessageAsync(String method) { } WaitableResult sendMessageAsync(String method, JsonObject params) { - return connection.sendMessageToServer(this, method, params, callOptions(null)); + return connection.sendMessageToServer(this, method, params, callOptions(method, params, null)); } /** Typed counterpart of {@link #sendMessageAsync(String, JsonObject)}; {@code null} params mean an empty object. */ @@ -229,7 +324,7 @@ private JsonObject paramsToJson(Object params) { // Fire-and-forget: Connection.sendMessageToServer registers no callback for __waitInfo__, the only caller, // and drops it silently when the object was collected. void sendMessageNoReply(String method, JsonObject params) { - connection.sendMessageToServer(this, method, params, callOptions(null)); + connection.sendMessageToServer(this, method, params, callOptions(method, params, null)); } JsonElement sendMessage(String method) { @@ -243,7 +338,7 @@ JsonElement sendMessage(String method, JsonObject params, Double timeout) { } else if (params.has("timeout")) { throw new PlaywrightException("Internal error: timeout must be passed explicitly."); } - return connection.sendMessage(this, method, params, callOptions(timeout)); + return connection.sendMessage(this, method, params, callOptions(method, params, timeout)); } /** @@ -286,7 +381,7 @@ T runUntil(Runnable code, Waitable waitable) { } } - // java: upstream's Connection.dispatch emits the event on the channel; subclasses override this until EventEmitter is ported. + // java: upstream's Connection.dispatch emits the event on the channel; subclasses override this. void handleEvent(String event, JsonObject parameters) { } @@ -298,13 +393,18 @@ JsonObject toProtocolRef() { } } -class ApiZone { - String title; +// java: the ApiZone type of channelOwner.ts; ApiCallData is its structural supertype upstream. +class ApiZone extends ApiCallData { + String apiName; final boolean internal; boolean reported; - ApiZone(String title, boolean internal) { + // java: the name the pw:api log prints for the call, set by its first reported message. + String logName; + + ApiZone(String title, String apiName, boolean internal) { this.title = title; + this.apiName = apiName; this.internal = internal; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java new file mode 100644 index 000000000..725f6336a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java @@ -0,0 +1,237 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of clientHelper.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.NameValue; +import com.microsoft.playwright.options.FunctionCallback; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.math.BigInteger; +import java.net.URL; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Function; + +import static com.microsoft.playwright.impl.Serialization.kFunctionBindingPrefix; +import static com.microsoft.playwright.impl.Utils.createGuid; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +import static java.nio.charset.StandardCharsets.UTF_8; + +class ClientHelper { + static List envObjectToArray(Map env) { + List result = new ArrayList<>(); + for (String name : env.keySet()) { + if (env.get(name) != null) { + NameValue nameValue = new NameValue(); + nameValue.name = name; + nameValue.value = String.valueOf(env.get(name)); + result.add(nameValue); + } + } + return result; + } + + // java: fun is a script String or a file Path, the { path, content } object of upstream. The + // typeof fun === 'function' branch is not ported, a Java value has no JavaScript source; a null arg is undefined. + static String evaluationScript(Object fun, Object arg, boolean addSourceUrl) { + if (arg != null) + throw new PlaywrightException("Cannot evaluate a string with arguments"); + if (fun instanceof String) + return (String) fun; + if (fun instanceof Path) { + Path path = (Path) fun; + String source; + try { + source = new String(Files.readAllBytes(path), UTF_8); + } catch (IOException e) { + throw new PlaywrightException("Failed to read script from file", e); + } + if (addSourceUrl) + source = addSourceUrlToScript(source, path); + return source; + } + throw new PlaywrightException("Either path or content property must be present"); + } + + // java: fun is the source of the function; a FunctionCallback stands for a JS function in arg; expose returns + // once the callback is exposed, so there is no Promise.all. + static String initScriptSourceWithExposedFunctions(String fun, Object arg, BiConsumer expose) { + JsonElement serialized = serializeAsCallArgument(arg, value -> { + if (value instanceof FunctionCallback) { + String name = kFunctionBindingPrefix + createGuid(); + expose.accept(name, (FunctionCallback) value); + JsonObject fn = new JsonObject(); + fn.addProperty("fn", name); + return fn; + } + return null; + }); + // Bindings backing the functions are registered through their own init scripts + // that are guaranteed to run first, so the controller is available here. + return "(" + fun + ")(globalThis['" + kBindingsControllerProperty + "'].parseInitScriptArg(" + new Gson().toJson(serialized) + "))"; + } + + static String addSourceUrlToScript(String source, Path path) { + return source + "\n//# sourceURL=" + path.toString().replace("\n", ""); + } + + // java: helpers with no counterpart in clientHelper.ts. + + // java: kBindingsControllerProperty of isomorphic/utilityScriptSerializers.ts, which has no Java port. + static final String kBindingsControllerProperty = "__playwright__binding__controller__"; + + // java: serializeAsCallArgument of isomorphic/utilityScriptSerializers.ts, which has no Java port, for the + // values a Java arg can hold (the Java types Serialization.serializeValue accepts, without typed arrays and the + // extended Map/Set serialization). The handle serializer returns the { fn } value, or null for { fallThrough: value }. + // A null is undefined, as in Serialization. + private static JsonElement serializeAsCallArgument(Object value, Function handleSerializer) { + return innerSerializeAsCallArgument(value, handleSerializer, new IdentityHashMap<>(), new int[] {0}); + } + + private static JsonElement innerSerializeAsCallArgument(Object value, Function handleSerializer, Map visited, int[] lastId) { + JsonElement handle = handleSerializer.apply(value); + if (handle != null) + return handle; + + if (value == null) + return specialValue("undefined"); + if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + if (Double.isNaN(number)) + return specialValue("NaN"); + if (number == Double.POSITIVE_INFINITY) + return specialValue("Infinity"); + if (number == Double.NEGATIVE_INFINITY) + return specialValue("-Infinity"); + if (number == 0 && 1 / number < 0) + return specialValue("-0"); + } + + if (value instanceof Boolean) + return new JsonPrimitive((Boolean) value); + if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double) + return new JsonPrimitive((Number) value); + if (value instanceof String) + return new JsonPrimitive((String) value); + if (value instanceof BigInteger) { + JsonObject result = new JsonObject(); + result.addProperty("bi", value.toString()); + return result; + } + + if (value instanceof Throwable) { + Throwable error = (Throwable) value; + String name = error.getClass().getSimpleName(); + StringWriter stack = new StringWriter(); + error.printStackTrace(new PrintWriter(stack)); + JsonObject e = new JsonObject(); + e.addProperty("n", name); + e.addProperty("m", error.getMessage()); + e.addProperty("s", name + ": " + error.getMessage() + "\n" + stack); + JsonObject result = new JsonObject(); + result.add("e", e); + return result; + } + if (value instanceof Date || value instanceof LocalDateTime) { + JsonObject result = new JsonObject(); + result.addProperty("d", (value instanceof Date ? ((Date) value).toInstant() : ((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant()).toString()); + return result; + } + if (value instanceof URL) { + JsonObject result = new JsonObject(); + result.addProperty("u", value.toString()); + return result; + } + if (value instanceof java.util.regex.Pattern) { + JsonObject r = new JsonObject(); + r.addProperty("p", ((java.util.regex.Pattern) value).pattern()); + r.addProperty("f", toJsRegexFlags((java.util.regex.Pattern) value)); + JsonObject result = new JsonObject(); + result.add("r", r); + return result; + } + + Integer id = visited.get(value); + if (id != null) { + JsonObject result = new JsonObject(); + result.addProperty("ref", id); + return result; + } + + if (value instanceof List || value instanceof Object[]) { + List array = value instanceof List ? (List) value : Arrays.asList((Object[]) value); + JsonArray a = new JsonArray(); + id = ++lastId[0]; + visited.put(value, id); + for (Object item : array) + a.add(innerSerializeAsCallArgument(item, handleSerializer, visited, lastId)); + JsonObject result = new JsonObject(); + result.add("a", a); + result.addProperty("id", id); + return result; + } + + if (value instanceof Map) { + JsonArray o = new JsonArray(); + id = ++lastId[0]; + visited.put(value, id); + for (Map.Entry entry : ((Map) value).entrySet()) { + JsonObject item = new JsonObject(); + item.addProperty("k", String.valueOf(entry.getKey())); + item.add("v", innerSerializeAsCallArgument(entry.getValue(), handleSerializer, visited, lastId)); + o.add(item); + } + JsonObject result = new JsonObject(); + result.add("o", o); + result.addProperty("id", id); + return result; + } + + // java: any other value, a function without the binding prefix upstream, serializes as undefined. + return specialValue("undefined"); + } + + private static JsonObject specialValue(String v) { + JsonObject result = new JsonObject(); + result.addProperty("v", v); + return result; + } + + // java: the overload without arg, the Java API never passes one. + static String evaluationScript(Object fun, boolean addSourceUrl) { + return evaluationScript(fun, null, addSourceUrl); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentation.java b/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentation.java new file mode 100644 index 000000000..80b1bab2a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentation.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of clientInstrumentation.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +// java: the channel { type, method, params } and the { keepTestTimeout } options are plain parameters; +// BrowserContextOptions is Browser.NewContextOptions or BrowserType.LaunchPersistentContextOptions and +// NewContextOptions is APIRequest.NewContextOptions in Java, which share no type, so the options are Object. +interface ClientInstrumentation { + void addListener(ClientInstrumentationListener listener); + + void removeListener(ClientInstrumentationListener listener); + + void removeAllListeners(); + + default void onApiCallBegin(ApiCallData apiCall, String type, String method, JsonObject params) { + } + + default void onApiCallEnd(ApiCallData apiCall) { + } + + default void onWillPause(boolean keepTestTimeout) { + } + + default void onPage(PageImpl page) { + } + + default void runBeforeCreateBrowserContext(Object options) { + } + + default void runBeforeCreateRequestContext(Object options) { + } + + default void runAfterCreateBrowserContext(BrowserContextImpl context) { + } + + default void runAfterCreateRequestContext(APIRequestContextImpl context) { + } + + default void runBeforeCloseBrowserContext(BrowserContextImpl context) { + } + + default void runBeforeCloseRequestContext(APIRequestContextImpl context) { + } + + static ClientInstrumentation createInstrumentation() { + List listeners = new ArrayList<>(); + // java: upstream returns a Proxy that forwards every on*/run* hook to the listeners; this class forwards each hook. + return new ClientInstrumentation() { + @Override + public void addListener(ClientInstrumentationListener listener) { + listeners.add(listener); + } + + @Override + public void removeListener(ClientInstrumentationListener listener) { + // java: splice(indexOf(listener), 1) removes the last listener for an unknown one; remove(Object) removes nothing. + listeners.remove(listener); + } + + @Override + public void removeAllListeners() { + listeners.clear(); + } + + @Override + public void onApiCallBegin(ApiCallData apiCall, String type, String method, JsonObject params) { + for (ClientInstrumentationListener listener : listeners) + listener.onApiCallBegin(apiCall, type, method, params); + } + + @Override + public void onApiCallEnd(ApiCallData apiCall) { + for (ClientInstrumentationListener listener : listeners) + listener.onApiCallEnd(apiCall); + } + + @Override + public void onWillPause(boolean keepTestTimeout) { + for (ClientInstrumentationListener listener : listeners) + listener.onWillPause(keepTestTimeout); + } + + @Override + public void onPage(PageImpl page) { + for (ClientInstrumentationListener listener : listeners) + listener.onPage(page); + } + + @Override + public void runBeforeCreateBrowserContext(Object options) { + for (ClientInstrumentationListener listener : listeners) + listener.runBeforeCreateBrowserContext(options); + } + + @Override + public void runBeforeCreateRequestContext(Object options) { + for (ClientInstrumentationListener listener : listeners) + listener.runBeforeCreateRequestContext(options); + } + + @Override + public void runAfterCreateBrowserContext(BrowserContextImpl context) { + for (ClientInstrumentationListener listener : listeners) + listener.runAfterCreateBrowserContext(context); + } + + @Override + public void runAfterCreateRequestContext(APIRequestContextImpl context) { + for (ClientInstrumentationListener listener : listeners) + listener.runAfterCreateRequestContext(context); + } + + @Override + public void runBeforeCloseBrowserContext(BrowserContextImpl context) { + for (ClientInstrumentationListener listener : listeners) + listener.runBeforeCloseBrowserContext(context); + } + + @Override + public void runBeforeCloseRequestContext(APIRequestContextImpl context) { + for (ClientInstrumentationListener listener : listeners) + listener.runBeforeCloseRequestContext(context); + } + }; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentationListener.java b/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentationListener.java new file mode 100644 index 000000000..294fee940 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentationListener.java @@ -0,0 +1,54 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of clientInstrumentation.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; + +// java: the optional methods of upstream's listener are default no-ops; the channel { type, method, params } +// and the { keepTestTimeout } options are plain parameters; the context options are Object, see ClientInstrumentation. +interface ClientInstrumentationListener { + default void onApiCallBegin(ApiCallData apiCall, String type, String method, JsonObject params) { + } + + default void onApiCallEnd(ApiCallData apiCall) { + } + + default void onWillPause(boolean keepTestTimeout) { + } + + default void onPage(PageImpl page) { + } + + default void runBeforeCreateBrowserContext(Object options) { + } + + default void runBeforeCreateRequestContext(Object options) { + } + + default void runAfterCreateBrowserContext(BrowserContextImpl context) { + } + + default void runAfterCreateRequestContext(APIRequestContextImpl context) { + } + + default void runBeforeCloseBrowserContext(BrowserContextImpl context) { + } + + default void runBeforeCloseRequestContext(APIRequestContextImpl context) { + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java index 08773c758..8d350c62a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java @@ -1,12 +1,33 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of clock.ts. package com.microsoft.playwright.impl; +import com.google.gson.JsonObject; import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.Clock; import java.util.Date; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +import static com.microsoft.playwright.impl.Serialization.gson; +// java: each number | string | Date parameter is one public overload per type of the generated Clock interface, +// all delegating to one private core that takes an Object. class ClockImpl implements Clock { private final BrowserContextImpl browserContext; @@ -14,68 +35,47 @@ class ClockImpl implements Clock { this.browserContext = browserContext; } - @Override - public void fastForward(long ticks) { - BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); - params.ticksNumber = (double) ticks; - browserContext.channel.clockFastForward(params, NO_TIMEOUT); - } - - @Override - public void fastForward(String ticks) { - BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); - params.ticksString = ticks; - browserContext.channel.clockFastForward(params, NO_TIMEOUT); - } - @Override public void install(InstallOptions options) { - BrowserContextClockInstallParams params = new BrowserContextClockInstallParams(); - if (options != null) { - Object time = options.time; - if (time instanceof Long) { - params.timeNumber = (double) (Long) time; - } else if (time instanceof Date) { - params.timeNumber = (double) ((Date) time).getTime(); - } else if (time instanceof String) { - params.timeString = (String) time; - } + if (options == null) { + options = new InstallOptions(); } + BrowserContextClockInstallParams params = gson().fromJson(options.time != null ? parseTime(options.time) : new JsonObject(), BrowserContextClockInstallParams.class); browserContext.channel.clockInstall(params, NO_TIMEOUT); } @Override - public void runFor(long ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); - params.ticksNumber = (double) ticks; - browserContext.channel.clockRunFor(params, NO_TIMEOUT); + public void fastForward(long ticks) { + fastForward((Object) ticks); } @Override - public void runFor(String ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); - params.ticksString = ticks; - browserContext.channel.clockRunFor(params, NO_TIMEOUT); + public void fastForward(String ticks) { + fastForward((Object) ticks); + } + + private void fastForward(Object ticks) { + BrowserContextClockFastForwardParams params = gson().fromJson(parseTicks(ticks), BrowserContextClockFastForwardParams.class); + browserContext.channel.clockFastForward(params, NO_TIMEOUT); } @Override public void pauseAt(long time) { - BrowserContextClockPauseAtParams params = new BrowserContextClockPauseAtParams(); - params.timeNumber = (double) time; - browserContext.channel.clockPauseAt(params, NO_TIMEOUT); + pauseAt((Object) time); } @Override public void pauseAt(String time) { - BrowserContextClockPauseAtParams params = new BrowserContextClockPauseAtParams(); - params.timeString = time; - browserContext.channel.clockPauseAt(params, NO_TIMEOUT); + pauseAt((Object) time); } @Override public void pauseAt(Date time) { - BrowserContextClockPauseAtParams params = new BrowserContextClockPauseAtParams(); - params.timeNumber = (double) time.getTime(); + pauseAt((Object) time); + } + + private void pauseAt(Object time) { + BrowserContextClockPauseAtParams params = gson().fromJson(parseTime(time), BrowserContextClockPauseAtParams.class); browserContext.channel.clockPauseAt(params, NO_TIMEOUT); } @@ -84,45 +84,85 @@ public void resume() { browserContext.channel.clockResume(NO_TIMEOUT); } + @Override + public void runFor(long ticks) { + runFor((Object) ticks); + } + + @Override + public void runFor(String ticks) { + runFor((Object) ticks); + } + + private void runFor(Object ticks) { + BrowserContextClockRunForParams params = gson().fromJson(parseTicks(ticks), BrowserContextClockRunForParams.class); + browserContext.channel.clockRunFor(params, NO_TIMEOUT); + } + @Override public void setFixedTime(long time) { - BrowserContextClockSetFixedTimeParams params = new BrowserContextClockSetFixedTimeParams(); - params.timeNumber = (double) time; - browserContext.channel.clockSetFixedTime(params, NO_TIMEOUT); + setFixedTime((Object) time); } @Override public void setFixedTime(String time) { - BrowserContextClockSetFixedTimeParams params = new BrowserContextClockSetFixedTimeParams(); - params.timeString = time; - browserContext.channel.clockSetFixedTime(params, NO_TIMEOUT); + setFixedTime((Object) time); } @Override public void setFixedTime(Date time) { - BrowserContextClockSetFixedTimeParams params = new BrowserContextClockSetFixedTimeParams(); - params.timeNumber = (double) time.getTime(); + setFixedTime((Object) time); + } + + private void setFixedTime(Object time) { + BrowserContextClockSetFixedTimeParams params = gson().fromJson(parseTime(time), BrowserContextClockSetFixedTimeParams.class); browserContext.channel.clockSetFixedTime(params, NO_TIMEOUT); } @Override public void setSystemTime(long time) { - BrowserContextClockSetSystemTimeParams params = new BrowserContextClockSetSystemTimeParams(); - params.timeNumber = (double) time; - browserContext.channel.clockSetSystemTime(params, NO_TIMEOUT); + setSystemTime((Object) time); } @Override public void setSystemTime(String time) { - BrowserContextClockSetSystemTimeParams params = new BrowserContextClockSetSystemTimeParams(); - params.timeString = time; - browserContext.channel.clockSetSystemTime(params, NO_TIMEOUT); + setSystemTime((Object) time); } @Override public void setSystemTime(Date time) { - BrowserContextClockSetSystemTimeParams params = new BrowserContextClockSetSystemTimeParams(); - params.timeNumber = (double) time.getTime(); + setSystemTime((Object) time); + } + + private void setSystemTime(Object time) { + BrowserContextClockSetSystemTimeParams params = gson().fromJson(parseTime(time), BrowserContextClockSetSystemTimeParams.class); browserContext.channel.clockSetSystemTime(params, NO_TIMEOUT); } + + // java: the returned { timeNumber?, timeString? } is a JsonObject, spread into the params by Gson. + static JsonObject parseTime(Object time) { + JsonObject result = new JsonObject(); + if (time instanceof Long) { + result.addProperty("timeNumber", (Long) time); + return result; + } + if (time instanceof String) { + result.addProperty("timeString", (String) time); + return result; + } + // java: the isFinite(time.getTime()) check is not ported, a Java Date always holds a finite time. + result.addProperty("timeNumber", ((Date) time).getTime()); + return result; + } + + static JsonObject parseTicks(Object ticks) { + JsonObject result = new JsonObject(); + if (ticks instanceof Long) { + result.addProperty("ticksNumber", (Long) ticks); + } + if (ticks instanceof String) { + result.addProperty("ticksString", (String) ticks); + } + return result; + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java new file mode 100644 index 000000000..e979d43ec --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of connect.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.microsoft.playwright.Browser; +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.BrowserType; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.TimeoutError; +import com.microsoft.playwright.impl.protocol.*; + +import java.io.IOException; +import java.util.Map; +import java.util.function.Consumer; + +import static com.microsoft.playwright.impl.isomorphic.Time.monotonicTime; + +final class Connect { + private Connect() { + } + + // java: upstream's params is one ConnectOptions object with browserName and endpoint in it. + static BrowserImpl connectToBrowser(PlaywrightImpl playwright, String browserName, String endpoint, BrowserType.ConnectOptions params) { + double timeout = params.timeout == null ? 0 : params.timeout; + double deadline = timeout != 0 ? monotonicTime() + timeout : 0; + JsonObject headers = new JsonObject(); + if (browserName != null) { + headers.addProperty("x-playwright-browser", browserName); + } + if (params.headers != null) { + for (Map.Entry entry : params.headers.entrySet()) { + headers.addProperty(entry.getKey(), entry.getValue()); + } + } + LocalUtilsConnectParams connectParams = new LocalUtilsConnectParams(); + connectParams.endpoint = endpoint; + connectParams.headers = headers; + connectParams.exposeNetwork = params.exposeNetwork; + connectParams.slowMo = params.slowMo; + // java: __testHookRedirectPortForwarding is a socksProxyRedirectPortForTest field of a ConnectOptions subclass in the tests. + JsonElement redirectPort = new Gson().toJsonTree(params).getAsJsonObject().get("socksProxyRedirectPortForTest"); + if (redirectPort != null && !redirectPort.isJsonNull()) { + connectParams.socksProxyRedirectPortForTest = redirectPort.getAsInt(); + } + BrowserImpl[] browser = {null}; + Connection connection = connectToEndpoint(playwright.connection, connectParams, timeout, () -> { + // Emulate all pages, contexts and the browser closing upon disconnect. + if (browser[0] != null) { + for (BrowserContext context : browser[0].contexts()) { + for (Page page : context.pages()) { + ((PageImpl) page).onClose(); + } + ((BrowserContextImpl) context).onClose(); + } + // java: no setTimeout, the browser is closed right after its contexts. + browser[0].didClose(); + } + }); + + // java: raceAgainstDeadline is the deadline of Connection.initializePlaywright, which throws a TimeoutError + // with the message "Timeout ms exceeded". + try { + // For tests. + // java: __testHookBeforeCreateBrowser is a public Runnable field testHookBeforeCreateBrowser of a ConnectOptions + // subclass; it runs before the deadline race, which is inside initializePlaywright. + Runnable testHookBeforeCreateBrowser = testHook(params, "testHookBeforeCreateBrowser"); + if (testHookBeforeCreateBrowser != null) { + testHookBeforeCreateBrowser.run(); + } + + PlaywrightImpl remotePlaywright = deadline == 0 ? connection.initializePlaywright() : connection.initializePlaywright(deadline, timeout); + BrowserImpl preLaunchedBrowser = connection.protocolGson().fromJson(remotePlaywright.initializer, PlaywrightInitializer.class).preLaunchedBrowser; + if (preLaunchedBrowser == null) { + closeConnection(connection); + throw new PlaywrightException("Malformed endpoint. Did you use BrowserType.launchServer method?"); + } + // java: upstream assigns the inner `playwright` to itself; here the remote Playwright shares the selectors of + // this one, because getByTestId reads the test id attribute through connection.playwright. + remotePlaywright.selectors = playwright.selectors; + browser[0] = preLaunchedBrowser; + browser[0].shouldCloseConnectionOnClose = true; + browser[0].on(Events.Browser.DISCONNECTED, (Consumer) b -> closeConnection(connection)); + return browser[0]; + } catch (TimeoutError e) { + closeConnection(connection); + throw e; + } + } + + // java: the Connection emits no 'close' event, onClose is the 'close' listener of connectToBrowser; it runs when the + // pipe closes, which happens both when the server goes away and when Connection.close closes the pipe. + static Connection connectToEndpoint(Connection parentConnection, LocalUtilsConnectParams params, double timeout, Runnable onClose) { + LocalUtils localUtils = parentConnection.localUtils(); + // java: the JsonPipe is the transport (JsonPipeTransport upstream); there is no WebSocketTransport for a + // connection without localUtils. The headers of the connect result are not used by the Java Connection. + JsonPipe transport = localUtils.channel.connect(params, timeout).pipe; + Connection connection = new Connection(transport, parentConnection.env, localUtils, parentConnection.instrumentation); + connection.markAsRemote(); + // java: Connection.close closes the transport itself, there is no connection.on('close', () => transport.close()). + + transport.onClose(pipe -> { + // java: JsonPipe.closeReason() defaults to "Browser has been closed" when the server gives no reason. + closeConnection(connection, pipe.closeReason()); + onClose.run(); + }); + // java: there is no onmessage/onMessage wiring, the Connection sends to the JsonPipe and polls it for messages, + // and an error of dispatch propagates out of the call that pumped the message. + return connection; + } + + // java: class JsonPipeTransport is the transport part of JsonPipe.java. + + // java: class WebSocketTransport is not ported, it wraps the browser's window.WebSocket and the JDK 8 has no + // WebSocket client; the Java client always connects through LocalUtils. + + // java: the helpers below have no counterpart in connect.ts. + private static Runnable testHook(Object params, String name) { + try { + Object value = params.getClass().getField(name).get(params); + return value instanceof Runnable ? (Runnable) value : null; + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } + + // java: Connection.close declares IOException. + private static void closeConnection(Connection connection) { + closeConnection(connection, null); + } + + private static void closeConnection(Connection connection, String reason) { + try { + connection.close(reason); + } catch (IOException e) { + throw new PlaywrightException("Failed to close the connection", e); + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java index a8f5f586a..8783b790d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of packages/playwright-core/src/client/connection.ts +// Port of connection.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -37,12 +37,14 @@ import java.util.Arrays; import java.util.Base64; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.isomorphic.Time.monotonicTime; class Root extends ChannelOwner { Root(Connection connection) { @@ -57,15 +59,15 @@ PlaywrightImpl initialize() { } // java: the deadline of raceAgainstDeadline in connect.ts, the wait pumps the connection until then. - PlaywrightImpl initialize(long deadlineNanos, double timeout) { + PlaywrightImpl initialize(double deadline, double timeout) { RootInitializeParams params = new RootInitializeParams(); params.sdkLanguage = "java"; params.supportsLoneSurrogates = true; WaitableResult result = sendMessageAsync("initialize", params); - Waitable deadline = new Waitable() { + Waitable deadlineWaitable = new Waitable() { @Override public boolean isDone() { - return System.nanoTime() > deadlineNanos; + return monotonicTime() > deadline; } @Override @@ -77,7 +79,7 @@ public JsonElement get() { public void dispose() { } }; - JsonElement json = runUntil(() -> {}, new WaitableRace<>(Arrays.asList(result, deadline))); + JsonElement json = runUntil(() -> {}, new WaitableRace<>(Arrays.asList(result, deadlineWaitable))); return connection.protocolGson().fromJson(json, RootInitializeResult.class).playwright; } } @@ -92,22 +94,28 @@ interface ChannelOwnerFactory { ChannelOwner create(ChannelOwner parent, String type, String guid, JsonObject initializer); } -public class Connection { +public class Connection extends EventEmitter { final Map objects = new HashMap<>(); + // java: onmessage is the transport, sendMessageToServer sends to it. + // Upstream creates the ids with createCallIdGenerator(); the prefix is unique for each client to avoid id clashes in a trace. + private final String callIdPrefix = createCallIdPrefix(); + private int lastId = 0; // java: upstream keeps { resolve, reject, signal, title, type, method } per call, nothing but the result is needed here. private final Map> callbacks = new HashMap<>(); private final Root rootObject; private TargetClosedError closedError; private boolean isRemote = false; private LocalUtils localUtils; + private boolean rawBuffers = false; + // java: toImpl is not ported, there are no in-process dispatchers. private int tracingCount; + final ClientInstrumentation instrumentation; + // Used from @playwright/test fixtures -> TODO remove? + final List headers; private final Map objectFactories = new HashMap<>(); // java: everything below has no counterpart in connection.ts. private final Transport transport; - // Upstream creates the ids with createCallIdGenerator(); the prefix is unique for each client to avoid id clashes in a trace. - private final String callIdPrefix = createCallIdPrefix(); - private int lastId = 0; private final StackTraceCollector stackTraceCollector; private final Gson protocolGson = gson().newBuilder() .registerTypeAdapterFactory(new ChannelOwnerAdapterFactory()) @@ -126,75 +134,94 @@ public class Connection { /** The options of upstream's sendMessageToServer; {@code timeout == null} means that no timeout is sent. */ static class CallOptions { + String apiName; String title; boolean internal; - Double timeout; JsonArray frames; + String callId; + // java: the AbortSignal is not ported. + Double timeout; } // java: the connection of a connect() call is remote and shares LocalUtils with the driver connection. Connection(Transport pipe, Map env, LocalUtils localUtils) { - this(pipe, env, localUtils, true); + this(pipe, env, localUtils, null, new ArrayList<>(), true); + } + + // java: connect.ts passes the instrumentation of the parent connection. + Connection(Transport pipe, Map env, LocalUtils localUtils, ClientInstrumentation instrumentation) { + this(pipe, env, localUtils, instrumentation, new ArrayList<>(), true); + } + + // java: connect.ts also passes the headers of the connect result. + Connection(Transport pipe, Map env, LocalUtils localUtils, ClientInstrumentation instrumentation, List headers) { + this(pipe, env, localUtils, instrumentation, headers, true); } Connection(Transport transport, Map env) { - this(transport, env, null, false); + this(transport, env, null, null, new ArrayList<>(), false); } - private Connection(Transport transport, Map env, LocalUtils localUtils, boolean remote) { + private Connection(Transport transport, Map env, LocalUtils localUtils, ClientInstrumentation instrumentation, List headers, boolean remote) { this.env = env; if (isLogging) { transport = new TransportLogger(transport); } this.transport = transport; stackTraceCollector = StackTraceCollector.createFromEnv(env); + this.instrumentation = instrumentation != null ? instrumentation : ClientInstrumentation.createInstrumentation(); this.localUtils = localUtils; this.rootObject = new Root(this); + this.headers = headers; if (remote) { markAsRemote(); } - registerObjectFactories(); - } - - private void registerObjectFactories() { - // java: Android and Electron are not ported, their objects are ignored. - objectFactories.put("Android", (parent, type, guid, init) -> null); - objectFactories.put("AndroidDevice", (parent, type, guid, init) -> null); - objectFactories.put("AndroidSocket", (parent, type, guid, init) -> null); - objectFactories.put("APIRequestContext", (parent, type, guid, init) -> new APIRequestContextImpl(parent, type, guid, init)); - objectFactories.put("Artifact", (parent, type, guid, init) -> new ArtifactImpl(parent, type, guid, init)); - objectFactories.put("BindingCall", (parent, type, guid, init) -> new BindingCall(parent, type, guid, init)); - objectFactories.put("Browser", (parent, type, guid, init) -> new BrowserImpl(parent, type, guid, init)); - objectFactories.put("BrowserContext", (parent, type, guid, init) -> new BrowserContextImpl(parent, type, guid, init)); - objectFactories.put("BrowserType", (parent, type, guid, init) -> new BrowserTypeImpl(parent, type, guid, init)); - objectFactories.put("CDPSession", (parent, type, guid, init) -> new CDPSessionImpl(parent, type, guid, init)); - objectFactories.put("Debugger", (parent, type, guid, init) -> new DebuggerImpl(parent, type, guid, init)); - objectFactories.put("Dialog", (parent, type, guid, init) -> new DialogImpl(parent, type, guid, init)); - objectFactories.put("Disposable", (parent, type, guid, init) -> new DisposableObject(parent, type, guid, init)); - objectFactories.put("Electron", (parent, type, guid, init) -> null); - objectFactories.put("ElementHandle", (parent, type, guid, init) -> new ElementHandleImpl(parent, type, guid, init)); - objectFactories.put("Frame", (parent, type, guid, init) -> new FrameImpl(parent, type, guid, init)); - objectFactories.put("JSHandle", (parent, type, guid, init) -> new JSHandleImpl(parent, type, guid, init)); - objectFactories.put("JsonPipe", (parent, type, guid, init) -> new JsonPipe(parent, type, guid, init)); - objectFactories.put("LocalUtils", (parent, type, guid, init) -> { + Map factories = new LinkedHashMap<>(); + // java: android.ts and electron.ts are not ported, their objects are ignored. + factories.put("Android", (parent, type, guid, init) -> null); + factories.put("AndroidDevice", (parent, type, guid, init) -> null); + factories.put("AndroidSocket", (parent, type, guid, init) -> null); + factories.put("APIRequestContext", (parent, type, guid, init) -> new APIRequestContextImpl(parent, type, guid, init)); + factories.put("Artifact", (parent, type, guid, init) -> new ArtifactImpl(parent, type, guid, init)); + factories.put("BindingCall", (parent, type, guid, init) -> new BindingCall(parent, type, guid, init)); + factories.put("Browser", (parent, type, guid, init) -> new BrowserImpl(parent, type, guid, init)); + factories.put("BrowserContext", (parent, type, guid, init) -> new BrowserContextImpl(parent, type, guid, init)); + factories.put("BrowserType", (parent, type, guid, init) -> new BrowserTypeImpl(parent, type, guid, init)); + factories.put("CDPSession", (parent, type, guid, init) -> new CDPSessionImpl(parent, type, guid, init)); + factories.put("Debugger", (parent, type, guid, init) -> new DebuggerImpl(parent, type, guid, init)); + factories.put("Dialog", (parent, type, guid, init) -> new DialogImpl(parent, type, guid, init)); + factories.put("Disposable", (parent, type, guid, init) -> new DisposableObject(parent, type, guid, init)); + factories.put("Electron", (parent, type, guid, init) -> null); + factories.put("ElectronApplication", (parent, type, guid, init) -> null); + factories.put("ElementHandle", (parent, type, guid, init) -> new ElementHandleImpl(parent, type, guid, init)); + factories.put("Frame", (parent, type, guid, init) -> new FrameImpl(parent, type, guid, init)); + factories.put("JSHandle", (parent, type, guid, init) -> new JSHandleImpl(parent, type, guid, init)); + factories.put("JsonPipe", (parent, type, guid, init) -> new JsonPipe(parent, type, guid, init)); + factories.put("LocalUtils", (parent, type, guid, init) -> { LocalUtils result = new LocalUtils(parent, type, guid, init); - if (localUtils == null) { - localUtils = result; + if (this.localUtils == null) { + this.localUtils = result; } return result; }); - objectFactories.put("Page", (parent, type, guid, init) -> new PageImpl(parent, type, guid, init)); - objectFactories.put("Playwright", (parent, type, guid, init) -> new PlaywrightImpl(parent, type, guid, init)); - objectFactories.put("Request", (parent, type, guid, init) -> new RequestImpl(parent, type, guid, init)); - objectFactories.put("Response", (parent, type, guid, init) -> new ResponseImpl(parent, type, guid, init)); - objectFactories.put("Route", (parent, type, guid, init) -> new RouteImpl(parent, type, guid, init)); - objectFactories.put("Stream", (parent, type, guid, init) -> new Stream(parent, type, guid, init)); - objectFactories.put("SocksSupport", (parent, type, guid, init) -> new DummyChannelOwner(parent, type, guid, init)); - objectFactories.put("Tracing", (parent, type, guid, init) -> new TracingImpl(parent, type, guid, init)); - objectFactories.put("WebSocket", (parent, type, guid, init) -> new WebSocketImpl(parent, type, guid, init)); - objectFactories.put("WebSocketRoute", (parent, type, guid, init) -> new WebSocketRouteImpl(parent, type, guid, init)); - objectFactories.put("Worker", (parent, type, guid, init) -> new WorkerImpl(parent, type, guid, init)); - objectFactories.put("WritableStream", (parent, type, guid, init) -> new WritableStream(parent, type, guid, init)); + factories.put("Page", (parent, type, guid, init) -> new PageImpl(parent, type, guid, init)); + factories.put("Playwright", (parent, type, guid, init) -> new PlaywrightImpl(parent, type, guid, init)); + factories.put("Request", (parent, type, guid, init) -> new RequestImpl(parent, type, guid, init)); + factories.put("Response", (parent, type, guid, init) -> new ResponseImpl(parent, type, guid, init)); + factories.put("Route", (parent, type, guid, init) -> new RouteImpl(parent, type, guid, init)); + factories.put("Stream", (parent, type, guid, init) -> new Stream(parent, type, guid, init)); + factories.put("SocksSupport", (parent, type, guid, init) -> new DummyChannelOwner(parent, type, guid, init)); + factories.put("Tracing", (parent, type, guid, init) -> new TracingImpl(parent, type, guid, init)); + factories.put("WebSocket", (parent, type, guid, init) -> new WebSocketImpl(parent, type, guid, init)); + factories.put("WebSocketRoute", (parent, type, guid, init) -> new WebSocketRouteImpl(parent, type, guid, init)); + factories.put("Worker", (parent, type, guid, init) -> new WorkerImpl(parent, type, guid, init)); + factories.put("WritableStream", (parent, type, guid, init) -> new WritableStream(parent, type, guid, init)); + registerObjectFactories(factories); + } + + void registerObjectFactories(Map factories) { + for (Map.Entry entry : factories.entrySet()) + objectFactories.put(entry.getKey(), entry.getValue()); } void markAsRemote() { @@ -205,6 +232,15 @@ boolean isRemote() { return isRemote; } + void useRawBuffers() { + rawBuffers = true; + } + + // java: protocolGson() always converts binary to base64; the flag is kept but changes nothing. + boolean rawBuffers() { + return rawBuffers; + } + LocalUtils localUtils() { return localUtils; } @@ -216,32 +252,21 @@ public PlaywrightImpl initializePlaywright() { } // java: connect.ts races the initialization against the deadline of connect(). - PlaywrightImpl initializePlaywright(long deadlineNanos, double timeout) { - playwright = rootObject.initialize(deadlineNanos, timeout); + PlaywrightImpl initializePlaywright(double deadline, double timeout) { + playwright = rootObject.initialize(deadline, timeout); return playwright; } - // java: upstream has getObjectWithKnownName(guid) for the same lookup; this one throws for an unknown guid. - public T getExistingObject(String guid) { - @SuppressWarnings("unchecked") T result = (T) objects.get(guid); - if (result == null) - throw new PlaywrightException("Object doesn't exist: " + guid); - return result; - } - - void registerObject(String guid, ChannelOwner object) { - objects.put(guid, object); - } - - void unregisterObject(String guid) { - objects.remove(guid); + @SuppressWarnings("unchecked") + T getObjectWithKnownName(String guid) { + return (T) objects.get(guid); } - void setIsTracing(boolean tracing) { - if (tracing) { - ++tracingCount; + void setIsTracing(boolean isTracing) { + if (isTracing) { + tracingCount++; } else { - --tracingCount; + tracingCount--; } } @@ -260,14 +285,17 @@ WaitableResult sendMessageToServer(ChannelOwner object, String meth throw new PlaywrightException("The object has been collected to prevent unbounded heap growth."); } + // java: the signal.aborted check is not ported, there is no AbortSignal. + String guid = object.guid; String type = object.type; - String id = callIdPrefix + "@" + (++lastId); + String id = options.callId != null ? options.callId : nextCallId(); JsonObject message = new JsonObject(); message.addProperty("id", id); message.addProperty("guid", guid); message.addProperty("method", method); message.add("params", params); + // java: the debugLogger 'channel' log is TransportLogger, installed for DEBUG=pw:channel. JsonObject metadata = new JsonObject(); if (options.title != null) { metadata.addProperty("title", options.title); @@ -295,6 +323,7 @@ WaitableResult sendMessageToServer(ChannelOwner object, String meth if (expectsReply) { callbacks.put(id, result); } + // java: the stack goes to tracing after the message is sent, the zones of emptyZone.run are not ported. transport.send(message); if (tracingCount > 0 && options.frames != null && !"LocalUtils".equals(type)) { JsonObject callData = new JsonObject(); @@ -302,56 +331,18 @@ WaitableResult sendMessageToServer(ChannelOwner object, String meth callData.add("stack", options.frames); JsonObject stackParams = new JsonObject(); stackParams.add("callData", callData); - // LocalUtils belongs to the driver connection, which is not this one when the browser came from connect(). - CallOptions stackOptions = new CallOptions(); - stackOptions.internal = true; - localUtils.connection.sendMessageToServer(localUtils, "addStackToTracingNoReply", stackParams, stackOptions); + // java: LocalUtils belongs to the driver connection, which is not this one when the browser came from connect(). + localUtils.addStackToTracingNoReply(stackParams); } + // java: the abort listener is not ported, there is no AbortSignal. return expectsReply ? result : completed(); } - private static WaitableResult completed() { - WaitableResult result = new WaitableResult<>(); - result.complete(null); - return result; - } + // java: _validatorFromWireContext is not ported, there are no protocol validators; protocolGson() parses + // the results, events and initializers (channel owners from {guid}, binary from base64). - // java: sends the message and pumps messages until the reply arrives; upstream awaits the promise of sendMessageToServer. - JsonElement sendMessage(ChannelOwner object, String method, JsonObject params, CallOptions options) { - if (closedError != null && transport instanceof JsonPipe) { - // java: a call over a closed JsonPipe fails like the pipe does, with the reason the server gave - // ('Browser closed' after it went away); async calls and waits get the closedError. - throw new TargetClosedError(((JsonPipe) transport).closeReason(), closedError); - } - WaitableResult result = sendMessageToServer(object, method, params, options); - Double timeout = options.timeout; - if (timeout == null || timeout == 0) { - return rootObject.runUntil(() -> {}, result); - } - // The driver enforces the timeout, but the driver itself may hang. - long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.longValue() + DRIVER_RESPONSE_GRACE_MS); - while (!result.isDone()) { - if (!processOneMessage() && System.nanoTime() - deadline > 0) { - result.completeExceptionally(new TimeoutError("Timeout " + timeout.longValue() + "ms exceeded while waiting for the driver to respond to " + - method + ". The driver is not responding.")); - } - } - return result.get(); - } - - // java: upstream receives messages through onmessage(); here the pump polls the transport. - boolean processOneMessage() { - JsonObject message = transport.poll(Duration.ofMillis(10)); - if (message == null) { - return false; - } - Gson gson = gson(); - Message messageObj = gson.fromJson(message, Message.class); - dispatch(messageObj); - return true; - } - - private void dispatch(Message message) { + // java: the message is the parsed wire shape, see Message below. + void dispatch(Message message) { if (closedError != null) { return; } @@ -362,19 +353,24 @@ private void dispatch(Message message) { throw new PlaywrightException("Cannot find command to respond: " + message.id); } callbacks.remove(message.id); - if (message.error == null) { - callback.complete(message.result); - } else { + if (message.error != null && message.result == null) { + // java: the AbortError cause is not ported, there is no AbortSignal. The call log is appended by parseError; + // the log and the error details (not validated, there are no validators) are kept by ServerErrorWithDetails. PlaywrightException parsedError = Errors.parseError(message.error, formatCallLog(message.log)); if (message.errorDetails != null) { parsedError = new ServerErrorWithDetails(parsedError, message.errorDetails, message.log); } callback.completeExceptionally(parsedError); + } else { + // java: the result is parsed by the caller with protocolGson(), there are no validators. + callback.complete(message.result); } return; } - // TODO: throw? + // java: the debugLogger 'channel' log is TransportLogger. + + // java: a message with neither id nor method is ignored. if (message.method == null) { return; } @@ -385,13 +381,13 @@ private void dispatch(Message message) { ChannelOwner object = objects.get(message.guid); if (object == null) { - throw new PlaywrightException("Cannot find object to call " + message.method + ": " + message.guid); + throw new PlaywrightException("Cannot find object to \"" + message.method + "\": " + message.guid); } if (message.method.equals("__adopt__")) { String childGuid = message.params.get("guid").getAsString(); ChannelOwner child = objects.get(childGuid); if (child == null) { - throw new PlaywrightException("Unknown new child: " + childGuid); + throw new PlaywrightException("Unknown new child: " + childGuid); } object.adopt(child); return; @@ -402,7 +398,8 @@ private void dispatch(Message message) { return; } - // java: upstream emits the event on the channel, ChannelOwner.handleEvent does the same until EventEmitter is ported. + // java: upstream validates the params and emits the event on the channel; ChannelOwner.handleEvent of the + // object parses them with protocolGson() and handles the event. object.handleEvent(message.method, message.params); } @@ -419,10 +416,28 @@ void close(String cause) throws IOException { callback.completeExceptionally(closedError); } callbacks.clear(); - // java: upstream emits 'close' here; the transport has to be closed as well. + emit("close", null); + // java: the transport is closed here, the 'close' listener of connect.ts closes it upstream. transport.close(); } + // java: _tChannelImplFromWire is the read() of ChannelOwnerAdapterFactory below, through getExistingObject. + + private ChannelOwner createRemoteObject(String parentGuid, String type, String guid, JsonObject initializer) { + ChannelOwner parent = objects.get(parentGuid); + if (parent == null) { + throw new PlaywrightException("Cannot find parent object " + parentGuid + " to create " + guid); + } + // java: the initializer is not validated, there are no validators; each object parses it with protocolGson(). + ChannelOwnerFactory factory = objectFactories.get(type); + if (factory == null) { + throw new PlaywrightException("Missing type " + type); + } + return factory.create(parent, type, guid, initializer); + } + + // java: helpers with no counterpart in connection.ts. + // java: upstream's _tChannelImplFromWire and, in channelOwner.ts, tChannelImplToWire; Gson adapters instead of validator hooks. /** Gson that serializes channel owners as {guid} and resolves them back through this connection. */ Gson protocolGson() { @@ -484,21 +499,72 @@ public byte[] read(JsonReader in) throws IOException { } } - private ChannelOwner createRemoteObject(String parentGuid, String type, String guid, JsonObject initializer) { - ChannelOwner parent = objects.get(parentGuid); - if (parent == null) { - throw new PlaywrightException("Cannot find parent object " + parentGuid + " to create " + guid); + // java: upstream's captureLibraryStackTrace() lives in clientStackTrace.ts; null when PLAYWRIGHT_JAVA_SRC is not set. + JsonArray captureLibraryStackTrace() { + return stackTraceCollector == null ? null : stackTraceCollector.captureLibraryStackTrace(); + } + + // java: the generator function of _nextCallId. + private String nextCallId() { + return callIdPrefix + "@" + (++lastId); + } + + // java: upstream has getObjectWithKnownName(guid) for the same lookup; this one throws for an unknown guid. + public T getExistingObject(String guid) { + @SuppressWarnings("unchecked") T result = (T) objects.get(guid); + if (result == null) + throw new PlaywrightException("Object doesn't exist: " + guid); + return result; + } + + // java: the _objects.set / _objects.delete of channelOwner.ts. + void registerObject(String guid, ChannelOwner object) { + objects.put(guid, object); + } + + void unregisterObject(String guid) { + objects.remove(guid); + } + + private static WaitableResult completed() { + WaitableResult result = new WaitableResult<>(); + result.complete(null); + return result; + } + + // java: sends the message and pumps messages until the reply arrives; upstream awaits the promise of sendMessageToServer. + JsonElement sendMessage(ChannelOwner object, String method, JsonObject params, CallOptions options) { + if (closedError != null && transport instanceof JsonPipe) { + // java: a call over a closed JsonPipe fails like the pipe does, with the reason the server gave + // ('Browser closed' after it went away); async calls and waits get the closedError. + throw new TargetClosedError(((JsonPipe) transport).closeReason(), closedError); } - ChannelOwnerFactory factory = objectFactories.get(type); - if (factory == null) { - throw new PlaywrightException("Unknown type " + type); + WaitableResult result = sendMessageToServer(object, method, params, options); + Double timeout = options.timeout; + if (timeout == null || timeout == 0) { + return rootObject.runUntil(() -> {}, result); } - return factory.create(parent, type, guid, initializer); + // The driver enforces the timeout, but the driver itself may hang. + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.longValue() + DRIVER_RESPONSE_GRACE_MS); + while (!result.isDone()) { + if (!processOneMessage() && System.nanoTime() - deadline > 0) { + result.completeExceptionally(new TimeoutError("Timeout " + timeout.longValue() + "ms exceeded while waiting for the driver to respond to " + + method + ". The driver is not responding.")); + } + } + return result.get(); } - // java: upstream's captureLibraryStackTrace() lives in clientStackTrace.ts; null when PLAYWRIGHT_JAVA_SRC is not set. - JsonArray captureLibraryStackTrace() { - return stackTraceCollector == null ? null : stackTraceCollector.captureLibraryStackTrace(); + // java: upstream receives messages through onmessage(); here the pump polls the transport. + boolean processOneMessage() { + JsonObject message = transport.poll(Duration.ofMillis(10)); + if (message == null) { + return false; + } + Gson gson = gson(); + Message messageObj = gson.fromJson(message, Message.class); + dispatch(messageObj); + return true; } private static String createCallIdPrefix() { @@ -510,6 +576,7 @@ private static String createCallIdPrefix() { return prefix.toString(); } + // java: each line is prefixed with "- " and not dimmed, as the Java client always printed it. private static String formatCallLog(JsonArray log) { if (log == null) { return ""; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java index 6b2e0e400..cc0aa6a0e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of consoleMessage.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -35,14 +36,20 @@ public class ConsoleMessageImpl implements ConsoleMessage { private final int columnNumber; private final double timestamp; - ConsoleMessageImpl(BrowserContextConsoleEvent event) { - this(event.page, event.worker, event.type, event.text, event.args, + // java: the event is one of three generated types, its fields are copied by one constructor per type. + ConsoleMessageImpl(BrowserContextConsoleEvent event, PageImpl page, WorkerImpl worker) { + this(page, worker, event.type, event.text, event.args, event.location.url, event.location.lineNumber, event.location.columnNumber, event.timestamp); } - ConsoleMessageImpl(PageImpl page, PageConsoleMessagesResult.PageConsoleMessagesResultMessages message) { - this(page, null, message.type, message.text, message.args, - message.location.url, message.location.lineNumber, message.location.columnNumber, message.timestamp); + ConsoleMessageImpl(WorkerConsoleEvent event, PageImpl page, WorkerImpl worker) { + this(page, worker, event.type, event.text, event.args, + event.location.url, event.location.lineNumber, event.location.columnNumber, event.timestamp); + } + + ConsoleMessageImpl(PageConsoleMessagesResult.PageConsoleMessagesResultMessages event, PageImpl page, WorkerImpl worker) { + this(page, worker, event.type, event.text, event.args, + event.location.url, event.location.lineNumber, event.location.columnNumber, event.timestamp); } private ConsoleMessageImpl(PageImpl page, WorkerImpl worker, String type, String text, List args, @@ -56,22 +63,25 @@ private ConsoleMessageImpl(PageImpl page, WorkerImpl worker, String type, String this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.timestamp = timestamp; + // java: inspect.custom is not ported, Java has no inspect hook. } @Override - public double timestamp() { - return timestamp; + public Worker worker() { + return worker; } - public String type() { - return type; + @Override + public PageImpl page() { + return page; } @Override - public Worker worker() { - return worker; + public String type() { + return type; } + @Override public String text() { return text; } @@ -83,11 +93,23 @@ public List args() { @Override public String location() { + // java: the public API returns a formatted string, upstream returns { url, line, column }. return url + ":" + lineNumber + ":" + columnNumber; } @Override - public PageImpl page() { - return page; + public double timestamp() { + return timestamp; + } + + // java: _inspect is not ported, Java has no inspect hook. + + // java: the constructors BrowserContextImpl and PageImpl call. + ConsoleMessageImpl(BrowserContextConsoleEvent event) { + this(event, event.page, event.worker); + } + + ConsoleMessageImpl(PageImpl page, PageConsoleMessagesResult.PageConsoleMessagesResultMessages message) { + this(message, page, null); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Coverage.java b/playwright/src/main/java/com/microsoft/playwright/impl/Coverage.java new file mode 100644 index 000000000..662e25a8a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Coverage.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of coverage.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.impl.protocol.*; + +import java.util.List; + +import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; + +// java: no public Coverage interface in the Java API, the class is package-private. +class Coverage { + private final PageChannel channel; + + Coverage(PageChannel channel) { + this.channel = channel; + } + + void startJSCoverage(PageStartJSCoverageParams options) { + if (options == null) { + options = new PageStartJSCoverageParams(); + } + channel.startJSCoverage(options, NO_TIMEOUT); + } + + List stopJSCoverage() { + return channel.stopJSCoverage(new PageStopJSCoverageParams(), NO_TIMEOUT).entries; + } + + void startCSSCoverage(PageStartCSSCoverageParams options) { + if (options == null) { + options = new PageStartCSSCoverageParams(); + } + channel.startCSSCoverage(options, NO_TIMEOUT); + } + + List stopCSSCoverage() { + return channel.stopCSSCoverage(new PageStopCSSCoverageParams(), NO_TIMEOUT).entries; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java index cae934527..53e20e1cc 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of credentials.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -28,36 +29,36 @@ import static java.util.Arrays.asList; class CredentialsImpl implements Credentials { - private final BrowserContextImpl context; + private final BrowserContextImpl browserContext; - CredentialsImpl(BrowserContextImpl context) { - this.context = context; + CredentialsImpl(BrowserContextImpl browserContext) { + this.browserContext = browserContext; } @Override public void install() { - context.channel.credentialsInstall(NO_TIMEOUT); + browserContext.channel.credentialsInstall(NO_TIMEOUT); } @Override public VirtualCredential create(String rpId, CreateOptions options) { BrowserContextCredentialsCreateParams params = toProtocol(options, BrowserContextCredentialsCreateParams.class); params.rpId = rpId; - BrowserContextCredentialsCreateResult result = context.channel.credentialsCreate(params, NO_TIMEOUT); + BrowserContextCredentialsCreateResult result = browserContext.channel.credentialsCreate(params, NO_TIMEOUT); return gson().fromJson(gson().toJsonTree(result.credential), VirtualCredential.class); } - @Override - public void delete(String id) { - BrowserContextCredentialsDeleteParams params = new BrowserContextCredentialsDeleteParams(); - params.id = id; - context.channel.credentialsDelete(params, NO_TIMEOUT); - } - @Override public List get(GetOptions options) { BrowserContextCredentialsGetParams params = toProtocol(options, BrowserContextCredentialsGetParams.class); - BrowserContextCredentialsGetResult result = context.channel.credentialsGet(params, NO_TIMEOUT); + BrowserContextCredentialsGetResult result = browserContext.channel.credentialsGet(params, NO_TIMEOUT); return asList(gson().fromJson(gson().toJsonTree(result.credentials), VirtualCredential[].class)); } + + @Override + public void delete(String id) { + BrowserContextCredentialsDeleteParams params = new BrowserContextCredentialsDeleteParams(); + params.id = id; + browserContext.channel.credentialsDelete(params, NO_TIMEOUT); + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java index 10073539e..57c592b84 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of debugger.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -22,49 +23,48 @@ import com.microsoft.playwright.options.Location; import com.microsoft.playwright.options.DebuggerPausedDetails; +import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.toProtocol; public class DebuggerImpl extends ChannelOwner implements Debugger { - private final List pausedStateChangedHandlers = new ArrayList<>(); private DebuggerPausedDetails pausedDetails; final DebuggerChannel channel = new DebuggerChannel(this); + // java: from is not ported, generated results already hold the impl object. + DebuggerImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. @Override protected void handleEvent(String event, JsonObject params) { - if ("pausedStateChanged".equals(event)) { - if (params.has("pausedDetails") && !params.get("pausedDetails").isJsonNull()) { - pausedDetails = gson().fromJson(params.get("pausedDetails"), DebuggerPausedDetails.class); - } else { - pausedDetails = null; + switch (event) { + case "pausedStateChanged": { + if (params.has("pausedDetails") && !params.get("pausedDetails").isJsonNull()) { + pausedDetails = gson().fromJson(params.get("pausedDetails"), DebuggerPausedDetails.class); + } else { + pausedDetails = null; + } + emit(Events.Debugger.PAUSED_STATE_CHANGED, null); + break; } - for (Runnable handler : new ArrayList<>(pausedStateChangedHandlers)) { - handler.run(); + case "apiCallsUpdated": { + DebuggerApiCallsUpdatedEvent e = connection.protocolGson().fromJson(params, DebuggerApiCallsUpdatedEvent.class); + emit(Events.Debugger.API_CALLS_UPDATED, e.apiCalls); + break; } } } - @Override - public void onPausedStateChanged(Runnable handler) { - pausedStateChangedHandlers.add(handler); - } - - @Override - public void offPausedStateChanged(Runnable handler) { - pausedStateChangedHandlers.remove(handler); - } - - @Override - public DebuggerPausedDetails pausedDetails() { - return pausedDetails; + void enable() { + channel.enable(NO_TIMEOUT); } @Override @@ -88,4 +88,29 @@ public void runTo(Location location) { params.location = toProtocol(location, DebuggerRunToParams.DebuggerRunToParamsLocation.class); channel.runTo(params, NO_TIMEOUT); } + + @Override + public DebuggerPausedDetails pausedDetails() { + return pausedDetails; + } + + // java: the Runnable handlers of the public API, each registered as a listener of Events.Debugger.PAUSED_STATE_CHANGED. + private final List>> pausedStateChangedListeners = new ArrayList<>(); + + @Override + public void onPausedStateChanged(Runnable handler) { + Consumer listener = unused -> handler.run(); + pausedStateChangedListeners.add(new SimpleEntry<>(handler, listener)); + on(Events.Debugger.PAUSED_STATE_CHANGED, listener); + } + + @Override + public void offPausedStateChanged(Runnable handler) { + for (int i = 0; i < pausedStateChangedListeners.size(); i++) { + if (pausedStateChangedListeners.get(i).getKey() == handler) { + off(Events.Debugger.PAUSED_STATE_CHANGED, pausedStateChangedListeners.remove(i).getValue()); + return; + } + } + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java index 5094095f4..3b4d1ab54 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java @@ -14,15 +14,17 @@ * limitations under the License. */ +// Port of dialog.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; import com.microsoft.playwright.Dialog; -import com.microsoft.playwright.Page; public class DialogImpl extends ChannelOwner implements Dialog { final DialogChannel channel = new DialogChannel(this); + // java: from is not ported, generated results already hold the impl object. + private PageImpl page; DialogImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { @@ -35,38 +37,39 @@ public class DialogImpl extends ChannelOwner implements Dialog { } @Override - public void accept(String promptText) { - DialogAcceptParams params = new DialogAcceptParams(); - params.promptText = promptText; - channel.accept(params, NO_TIMEOUT); + public PageImpl page() { + return page; } @Override - public void dismiss() { - try { - channel.dismiss(NO_TIMEOUT); - } catch (TargetClosedError e) { - // Swallow TargetClosedErrors for beforeunload dialogs. - } + public String type() { + return initializer.get("type").getAsString(); } @Override - public String defaultValue() { - return initializer.get("defaultValue").getAsString(); + public String message() { + return initializer.get("message").getAsString(); } @Override - public String message() { - return initializer.get("message").getAsString(); + public String defaultValue() { + return initializer.get("defaultValue").getAsString(); } @Override - public PageImpl page() { - return page; + public void accept(String promptText) { + DialogAcceptParams params = new DialogAcceptParams(); + params.promptText = promptText; + channel.accept(params, NO_TIMEOUT); } @Override - public String type() { - return initializer.get("type").getAsString(); + public void dismiss() { + try { + channel.dismiss(NO_TIMEOUT); + } catch (TargetClosedError e) { + // java: isTargetClosedError(e) is an instanceof check on TargetClosedError. + return; + } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DisposableObject.java b/playwright/src/main/java/com/microsoft/playwright/impl/DisposableObject.java index 724a6eb03..bc0f4b40a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DisposableObject.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DisposableObject.java @@ -14,11 +14,16 @@ * limitations under the License. */ +// Port of disposable.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.List; + +// java: upstream's Disposable interface is AutoCloseable. public class DisposableObject extends ChannelOwner implements AutoCloseable { final DisposableChannel channel = new DisposableChannel(this); @@ -26,8 +31,34 @@ public class DisposableObject extends ChannelOwner implements AutoCloseable { super(parent, type, guid, initializer); } + // java: from is not ported, generated results already hold the impl object. + + // java: Symbol.asyncDispose is AutoCloseable.close(). @Override public void close() { - channel.dispose(NO_TIMEOUT); + dispose(); + } + + void dispose() { + try { + channel.dispose(NO_TIMEOUT); + } catch (TargetClosedError e) { + return; + } + } + + // java: the module function of disposable.ts; Promise.all runs the disposals one after another. + static void disposeAll(List disposables) { + List copy = new ArrayList<>(disposables); + disposables.clear(); + for (AutoCloseable d : copy) { + try { + d.close(); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DisposableStub.java b/playwright/src/main/java/com/microsoft/playwright/impl/DisposableStub.java index 83f396399..6e3b94c57 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DisposableStub.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DisposableStub.java @@ -14,8 +14,10 @@ * limitations under the License. */ +// Port of disposable.ts. package com.microsoft.playwright.impl; +// java: the dispose function is a Runnable. class DisposableStub implements AutoCloseable { private Runnable dispose; @@ -23,12 +25,21 @@ class DisposableStub implements AutoCloseable { this.dispose = dispose; } + // java: Symbol.asyncDispose is AutoCloseable.close(). @Override public void close() { + dispose(); + } + + void dispose() { if (dispose == null) return; - Runnable d = dispose; - dispose = null; - d.run(); + try { + Runnable dispose = this.dispose; + this.dispose = null; + dispose.run(); + } catch (TargetClosedError e) { + return; + } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java index ed6ae1810..56f760e5b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of download.ts. package com.microsoft.playwright.impl; import com.google.gson.JsonObject; @@ -25,38 +26,40 @@ class DownloadImpl implements Download { private final PageImpl page; + private final String url; + private final String suggestedFilename; private final ArtifactImpl artifact; - private final JsonObject initializer; - DownloadImpl(PageImpl page, ArtifactImpl artifact, JsonObject initializer) { + DownloadImpl(PageImpl page, String url, String suggestedFilename, ArtifactImpl artifact) { this.page = page; + this.url = url; + this.suggestedFilename = suggestedFilename; this.artifact = artifact; - this.initializer = initializer; } @Override - public String url() { - return initializer.get("url").getAsString(); + public Page page() { + return page; } @Override - public String suggestedFilename() { - return initializer.get("suggestedFilename").getAsString(); + public String url() { + return url; } @Override - public void cancel() { - artifact.cancel(); + public String suggestedFilename() { + return suggestedFilename; } @Override - public InputStream createReadStream() { - return artifact.createReadStream(); + public Path path() { + return artifact.pathAfterFinished(); } @Override - public void delete() { - artifact.delete(); + public void saveAs(Path path) { + artifact.saveAs(path); } @Override @@ -65,17 +68,22 @@ public String failure() { } @Override - public Page page() { - return page; + public InputStream createReadStream() { + return artifact.createReadStream(); } @Override - public Path path() { - return artifact.pathAfterFinished(); + public void cancel() { + artifact.cancel(); } @Override - public void saveAs(Path path) { - artifact.saveAs(path); + public void delete() { + artifact.delete(); + } + + // java: the constructor PageImpl calls, it reads url and suggestedFilename from the download event. + DownloadImpl(PageImpl page, ArtifactImpl artifact, JsonObject initializer) { + this(page, initializer.get("url").getAsString(), initializer.get("suggestedFilename").getAsString(), artifact); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java index 502d160ac..45a750ab3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -1,12 +1,12 @@ /* * Copyright (c) Microsoft Corporation. - *

+ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - *

+ * * http://www.apache.org/licenses/LICENSE-2.0 - *

+ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -14,38 +14,50 @@ * limitations under the License. */ +// Port of elementHandle.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; import com.microsoft.playwright.ElementHandle; -import com.microsoft.playwright.Frame; import com.microsoft.playwright.Locator; +import com.microsoft.playwright.Page; import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.BoundingBox; import com.microsoft.playwright.options.ElementState; import com.microsoft.playwright.options.FilePayload; +import com.microsoft.playwright.options.ScreenshotType; import com.microsoft.playwright.options.SelectOption; +import java.io.IOException; +import java.io.OutputStream; import java.nio.file.Files; +import java.nio.file.NoSuchFileException; import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Base64; +import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static com.microsoft.playwright.impl.Serialization.*; -import static com.microsoft.playwright.impl.Utils.*; -import static com.microsoft.playwright.impl.Utils.addFilePathUploadParams; +import static com.microsoft.playwright.impl.FileUtils.fileUploadSizeLimit; +import static com.microsoft.playwright.impl.isomorphic.MimeType.getMimeTypeForPath; +import static com.microsoft.playwright.impl.Serialization.deserialize; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toProtocol; public class ElementHandleImpl extends JSHandleImpl implements ElementHandle { - private final FrameImpl frame; + FrameImpl frame; + final ElementHandleChannel elementChannel = new ElementHandleChannel(this); - // Hides JSHandleImpl.channel on purpose: upstream ElementHandle narrows the type of _channel the same way. - final ElementHandleChannel channel = new ElementHandleChannel(this); + // java: no from and fromNullable, generated results already hold the ElementHandleImpl. ElementHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - this.frame = (FrameImpl)parent; + this.frame = (FrameImpl) parent; } @Override @@ -54,311 +66,265 @@ public ElementHandle asElement() { } @Override - public ElementHandle querySelector(String selector) { - ElementHandleQuerySelectorParams params = new ElementHandleQuerySelectorParams(); - params.selector = selector; - return channel.querySelector(params, NO_TIMEOUT).element; + public FrameImpl ownerFrame() { + return elementChannel.ownerFrame(NO_TIMEOUT).frame; } @Override - public List querySelectorAll(String selector) { - ElementHandleQuerySelectorAllParams params = new ElementHandleQuerySelectorAllParams(); - params.selector = selector; - List elements = channel.querySelectorAll(params, NO_TIMEOUT).elements; - if (elements == null) { - return null; - } - return new ArrayList(elements); + public FrameImpl contentFrame() { + return elementChannel.contentFrame(NO_TIMEOUT).frame; } @Override - public Object evalOnSelector(String selector, String pageFunction, Object arg) { - ElementHandleEvalOnSelectorParams params = new ElementHandleEvalOnSelectorParams(); - params.selector = selector; - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evalOnSelector(params, NO_TIMEOUT).value); + public String getAttribute(String name) { + ElementHandleGetAttributeParams params = new ElementHandleGetAttributeParams(); + params.name = name; + return elementChannel.getAttribute(params, NO_TIMEOUT).value; } + // java: InputValueOptions has a timeout; like upstream, it is not used. @Override - public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { - ElementHandleEvalOnSelectorAllParams params = new ElementHandleEvalOnSelectorAllParams(); - params.selector = selector; - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evalOnSelectorAll(params, NO_TIMEOUT).value); + public String inputValue(InputValueOptions options) { + return elementChannel.inputValue(NO_TIMEOUT).value; } @Override - public BoundingBox boundingBox() { - Rect value = channel.boundingBox(NO_TIMEOUT).value; - if (value == null) { - return null; - } - BoundingBox box = new BoundingBox(); - box.x = value.x; - box.y = value.y; - box.width = value.width; - box.height = value.height; - return box; + public String textContent() { + return elementChannel.textContent(NO_TIMEOUT).value; } @Override - public void check(CheckOptions options) { - if (options == null) { - options = new CheckOptions(); - } - ElementHandleCheckParams params = Utils.toProtocol(options, ElementHandleCheckParams.class); - channel.check(params, frame.timeout(options.timeout)); + public String innerText() { + return elementChannel.innerText(NO_TIMEOUT).value; } @Override - public void click(ClickOptions options) { - if (options == null) { - options = new ClickOptions(); - } - ElementHandleClickParams params = Utils.toProtocol(options, ElementHandleClickParams.class); - channel.click(params, frame.timeout(options.timeout)); + public String innerHTML() { + return elementChannel.innerHTML(NO_TIMEOUT).value; } @Override - public Frame contentFrame() { - return channel.contentFrame(NO_TIMEOUT).frame; + public boolean isChecked() { + return elementChannel.isChecked(NO_TIMEOUT).value; } @Override - public void dblclick(DblclickOptions options) { - if (options == null) { - options = new DblclickOptions(); - } - ElementHandleDblclickParams params = Utils.toProtocol(options, ElementHandleDblclickParams.class); - channel.dblclick(params, frame.timeout(options.timeout)); + public boolean isDisabled() { + return elementChannel.isDisabled(NO_TIMEOUT).value; } @Override - public void dispatchEvent(String type, Object eventInit) { - ElementHandleDispatchEventParams params = new ElementHandleDispatchEventParams(); - params.type = type; - params.eventInit = serializeArgument(eventInit); - channel.dispatchEvent(params, NO_TIMEOUT); + public boolean isEditable() { + return elementChannel.isEditable(NO_TIMEOUT).value; } @Override - public void fill(String value, FillOptions options) { - if (options == null) { - options = new FillOptions(); - } - ElementHandleFillParams params = Utils.toProtocol(options, ElementHandleFillParams.class); - params.value = value; - channel.fill(params, frame.timeout(options.timeout)); + public boolean isEnabled() { + return elementChannel.isEnabled(NO_TIMEOUT).value; } @Override - public void focus() { - channel.focus(NO_TIMEOUT); + public boolean isHidden() { + return elementChannel.isHidden(NO_TIMEOUT).value; } @Override - public String getAttribute(String name) { - ElementHandleGetAttributeParams params = new ElementHandleGetAttributeParams(); - params.name = name; - return channel.getAttribute(params, NO_TIMEOUT).value; + public boolean isVisible() { + return elementChannel.isVisible(NO_TIMEOUT).value; } @Override - public void hover(HoverOptions options) { - if (options == null) { - options = new HoverOptions(); + public void dispatchEvent(String type, Object eventInit) { + if (eventInit == null) { + eventInit = Collections.emptyMap(); } - ElementHandleHoverParams params = Utils.toProtocol(options, ElementHandleHoverParams.class); - channel.hover(params, frame.timeout(options.timeout)); + ElementHandleDispatchEventParams params = new ElementHandleDispatchEventParams(); + params.type = type; + params.eventInit = serializeArgument(eventInit); + elementChannel.dispatchEvent(params, NO_TIMEOUT); } @Override - public String innerHTML() { - return channel.innerHTML(NO_TIMEOUT).value; + public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { + if (options == null) { + options = new ScrollIntoViewIfNeededOptions(); + } + ElementHandleScrollIntoViewIfNeededParams params = toProtocol(options, ElementHandleScrollIntoViewIfNeededParams.class); + elementChannel.scrollIntoViewIfNeeded(params, frame.timeout(options.timeout)); } @Override - public String innerText() { - return channel.innerText(NO_TIMEOUT).value; + public void hover(HoverOptions options) { + if (options == null) { + options = new HoverOptions(); + } + ElementHandleHoverParams params = toProtocol(options, ElementHandleHoverParams.class); + elementChannel.hover(params, frame.timeout(options.timeout)); } @Override - public String inputValue(InputValueOptions options) { + public void click(ClickOptions options) { if (options == null) { - options = new InputValueOptions(); + options = new ClickOptions(); } - ElementHandleInputValueParams params = Utils.toProtocol(options, ElementHandleInputValueParams.class); - return channel.inputValue(params, NO_TIMEOUT).value; + ElementHandleClickParams params = toProtocol(options, ElementHandleClickParams.class); + elementChannel.click(params, frame.timeout(options.timeout)); } @Override - public boolean isChecked() { - return channel.isChecked(NO_TIMEOUT).value; + public void dblclick(DblclickOptions options) { + if (options == null) { + options = new DblclickOptions(); + } + ElementHandleDblclickParams params = toProtocol(options, ElementHandleDblclickParams.class); + elementChannel.dblclick(params, frame.timeout(options.timeout)); } @Override - public boolean isDisabled() { - return channel.isDisabled(NO_TIMEOUT).value; + public void tap(TapOptions options) { + if (options == null) { + options = new TapOptions(); + } + ElementHandleTapParams params = toProtocol(options, ElementHandleTapParams.class); + elementChannel.tap(params, frame.timeout(options.timeout)); } + // java: one overload per value type of the public API, all delegating to selectOption(Object, ...). @Override - public boolean isEditable() { - return channel.isEditable(NO_TIMEOUT).value; + public List selectOption(String values, SelectOptionOptions options) { + return selectOption((Object) values, options); } @Override - public boolean isEnabled() { - return channel.isEnabled(NO_TIMEOUT).value; + public List selectOption(ElementHandle values, SelectOptionOptions options) { + return selectOption((Object) values, options); } @Override - public boolean isHidden() { - return channel.isHidden(NO_TIMEOUT).value; + public List selectOption(String[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); } @Override - public boolean isVisible() { - return channel.isVisible(NO_TIMEOUT).value; + public List selectOption(SelectOption values, SelectOptionOptions options) { + return selectOption((Object) values, options); } @Override - public FrameImpl ownerFrame() { - return channel.ownerFrame(NO_TIMEOUT).frame; + public List selectOption(ElementHandle[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); } @Override - public void press(String key, PressOptions options) { + public List selectOption(SelectOption[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + private List selectOption(Object values, SelectOptionOptions options) { if (options == null) { - options = new PressOptions(); + options = new SelectOptionOptions(); } - ElementHandlePressParams params = Utils.toProtocol(options, ElementHandlePressParams.class); - params.key = key; - channel.press(params, frame.timeout(options.timeout)); + ElementHandleSelectOptionParams converted = convertSelectOptionValues(values); + ElementHandleSelectOptionParams params = toProtocol(options, ElementHandleSelectOptionParams.class); + params.elements = converted.elements; + params.options = converted.options; + ElementHandleSelectOptionResult result = elementChannel.selectOption(params, frame.timeout(options.timeout)); + return result.values; } @Override - public byte[] screenshot(ScreenshotOptions options) { + public void fill(String value, FillOptions options) { if (options == null) { - options = new ScreenshotOptions(); - } - if (options.type == null && options.path != null) { - options.type = Utils.screenshotTypeForPath(options.path); - } - // The mask locators cannot be read back through Gson, they are converted below. - JsonObject json = gson().toJsonTree(options).getAsJsonObject(); - json.remove("mask"); - ElementHandleScreenshotParams params = gson().fromJson(json, ElementHandleScreenshotParams.class); - if (options.mask != null) { - params.mask = new ArrayList<>(); - for (Locator locator : options.mask) { - ElementHandleScreenshotParams.ElementHandleScreenshotParamsMask item = new ElementHandleScreenshotParams.ElementHandleScreenshotParamsMask(); - item.frame = ((LocatorImpl) locator).frame; - item.selector = ((LocatorImpl) locator).selector; - params.mask.add(item); - } - } - byte[] buffer = channel.screenshot(params, frame.timeout(options.timeout)).binary; - if (options.path != null) { - Utils.writeToFile(buffer, options.path); + options = new FillOptions(); } - return buffer; + ElementHandleFillParams params = toProtocol(options, ElementHandleFillParams.class); + params.value = value; + elementChannel.fill(params, frame.timeout(options.timeout)); } @Override - public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { + public void selectText(SelectTextOptions options) { if (options == null) { - options = new ScrollIntoViewIfNeededOptions(); + options = new SelectTextOptions(); } - ElementHandleScrollIntoViewIfNeededParams params = Utils.toProtocol(options, ElementHandleScrollIntoViewIfNeededParams.class); - channel.scrollIntoViewIfNeeded(params, frame.timeout(options.timeout)); + ElementHandleSelectTextParams params = toProtocol(options, ElementHandleSelectTextParams.class); + elementChannel.selectText(params, frame.timeout(options.timeout)); } + // java: one overload per file type of the public API, all delegating to setInputFiles(Object, ...). @Override - public List selectOption(String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(values, options); + public void setInputFiles(Path files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); } @Override - public List selectOption(ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{ value }; - return selectOption(values, options); + public void setInputFiles(Path[] files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); } @Override - public List selectOption(String[] values, SelectOptionOptions options) { + public void setInputFiles(FilePayload files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); + } + + @Override + public void setInputFiles(FilePayload[] files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); + } + + private void setInputFiles(Object files, SetInputFilesOptions options) { if (options == null) { - options = new SelectOptionOptions(); + options = new SetInputFilesOptions(); } - ElementHandleSelectOptionParams params = Utils.toProtocol(options, ElementHandleSelectOptionParams.class); - if (values != null) { - Utils.assertNoNullItems(values); - params.options = new ArrayList<>(); - for (String value : values) { - ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); - option.valueOrLabel = value; - params.options.add(option); - } + FrameImpl frame = ownerFrame(); + if (frame == null) { + throw new PlaywrightException("Cannot set input files to detached element"); } - return selectOption(params, options.timeout); + ElementHandleSetInputFilesParams converted = convertInputFiles(files, (BrowserContextImpl) frame.page().context()); + elementChannel.setInputFiles(converted, this.frame.timeout(options.timeout)); } @Override - public List selectOption(SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{ value }; - return selectOption(values, options); + public void focus() { + elementChannel.focus(NO_TIMEOUT); } - @Override - public List selectOption(SelectOption[] values, SelectOptionOptions options) { + public void type(String text, TypeOptions options) { if (options == null) { - options = new SelectOptionOptions(); - } - ElementHandleSelectOptionParams params = Utils.toProtocol(options, ElementHandleSelectOptionParams.class); - if (values != null) { - Utils.assertNoNullItems(values); - params.options = new ArrayList<>(); - for (SelectOption value : values) { - ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); - option.value = value.value; - option.label = value.label; - option.index = value.index; - params.options.add(option); - } + options = new TypeOptions(); } - return selectOption(params, options.timeout); + ElementHandleTypeParams params = toProtocol(options, ElementHandleTypeParams.class); + params.text = text; + elementChannel.type(params, frame.timeout(options.timeout)); } @Override - public List selectOption(ElementHandle[] values, SelectOptionOptions options) { + public void press(String key, PressOptions options) { if (options == null) { - options = new SelectOptionOptions(); - } - ElementHandleSelectOptionParams params = Utils.toProtocol(options, ElementHandleSelectOptionParams.class); - if (values != null) { - Utils.assertNoNullItems(values); - params.elements = new ArrayList<>(); - for (ElementHandle value : values) { - params.elements.add((ElementHandleImpl) value); - } + options = new PressOptions(); } - return selectOption(params, options.timeout); + ElementHandlePressParams params = toProtocol(options, ElementHandlePressParams.class); + params.key = key; + elementChannel.press(params, frame.timeout(options.timeout)); } - private List selectOption(ElementHandleSelectOptionParams params, Double timeout) { - return channel.selectOption(params, frame.timeout(timeout)).values; + @Override + public void check(CheckOptions options) { + if (options == null) { + options = new CheckOptions(); + } + ElementHandleCheckParams params = toProtocol(options, ElementHandleCheckParams.class); + elementChannel.check(params, frame.timeout(options.timeout)); } @Override - public void selectText(SelectTextOptions options) { + public void uncheck(UncheckOptions options) { if (options == null) { - options = new SelectTextOptions(); + options = new UncheckOptions(); } - ElementHandleSelectTextParams params = Utils.toProtocol(options, ElementHandleSelectTextParams.class); - channel.selectText(params, frame.timeout(options.timeout)); + ElementHandleUncheckParams params = toProtocol(options, ElementHandleUncheckParams.class); + elementChannel.uncheck(params, frame.timeout(options.timeout)); } @Override @@ -371,86 +337,63 @@ public void setChecked(boolean checked, SetCheckedOptions options) { } @Override - public void setInputFiles(Path files, SetInputFilesOptions options) { - setInputFiles(new Path[]{files}, options); + public BoundingBox boundingBox() { + Rect value = elementChannel.boundingBox(NO_TIMEOUT).value; + return value == null ? null : convertType(value, BoundingBox.class); } - @Override - public void setInputFiles(Path[] files, SetInputFilesOptions options) { - FrameImpl frame = ownerFrame(); - if (frame == null) { - throw new Error("Cannot set input files to detached element"); - } + public byte[] screenshot(ScreenshotOptions options) { if (options == null) { - options = new SetInputFilesOptions(); - } - ElementHandleSetInputFilesParams params = Utils.toProtocol(options, ElementHandleSetInputFilesParams.class); - Utils.UploadParams upload = addFilePathUploadParams(files, frame.page().context()); - if (upload.emptyPayloads) { - params.payloads = new ArrayList<>(); + options = new ScreenshotOptions(); } - params.localDirectory = upload.localDirectory; - params.directoryStream = upload.directoryStream; - params.localPaths = upload.localPaths; - params.streams = upload.streams; - channel.setInputFiles(params, frame.timeout(options.timeout)); - } - - @Override - public void setInputFiles(FilePayload files, SetInputFilesOptions options) { - setInputFiles(new FilePayload[]{files}, options); - } - - @Override - public void setInputFiles(FilePayload[] files, SetInputFilesOptions options) { - checkFilePayloadSize(files); - if (options == null) { - options = new SetInputFilesOptions(); + // java: toProtocol converts the mask locators to { frame, selector }. + ElementHandleScreenshotParams copy = toProtocol(this, options, ElementHandleScreenshotParams.class); + if (copy.type == null) { + copy.type = determineScreenshotType(options); } - ElementHandleSetInputFilesParams params = Utils.toProtocol(options, ElementHandleSetInputFilesParams.class); - params.payloads = new ArrayList<>(); - for (FilePayload file : files) { - ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads payload = new ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads(); - payload.name = file.name; - payload.mimeType = file.mimeType; - payload.buffer = file.buffer; - params.payloads.add(payload); + ElementHandleScreenshotResult result = elementChannel.screenshot(copy, frame.timeout(options.timeout)); + if (options.path != null) { + Utils.writeToFile(result.binary, options.path); } - channel.setInputFiles(params, frame.timeout(options.timeout)); + return result.binary; } @Override - public void tap(TapOptions options) { - if (options == null) { - options = new TapOptions(); - } - ElementHandleTapParams params = Utils.toProtocol(options, ElementHandleTapParams.class); - channel.tap(params, frame.timeout(options.timeout)); + public ElementHandle querySelector(String selector) { + ElementHandleQuerySelectorParams params = new ElementHandleQuerySelectorParams(); + params.selector = selector; + return elementChannel.querySelector(params, NO_TIMEOUT).element; } @Override - public String textContent() { - return channel.textContent(NO_TIMEOUT).value; + public List querySelectorAll(String selector) { + ElementHandleQuerySelectorAllParams params = new ElementHandleQuerySelectorAllParams(); + params.selector = selector; + ElementHandleQuerySelectorAllResult result = elementChannel.querySelectorAll(params, NO_TIMEOUT); + return new ArrayList(result.elements); } @Override - public void type(String text, TypeOptions options) { - if (options == null) { - options = new TypeOptions(); - } - ElementHandleTypeParams params = Utils.toProtocol(options, ElementHandleTypeParams.class); - params.text = text; - channel.type(params, frame.timeout(options.timeout)); + public Object evalOnSelector(String selector, String pageFunction, Object arg) { + ElementHandleEvalOnSelectorParams params = new ElementHandleEvalOnSelectorParams(); + params.selector = selector; + params.expression = pageFunction; + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializeArgument(arg); + ElementHandleEvalOnSelectorResult result = elementChannel.evalOnSelector(params, NO_TIMEOUT); + return deserialize(result.value); } @Override - public void uncheck(UncheckOptions options) { - if (options == null) { - options = new UncheckOptions(); - } - ElementHandleUncheckParams params = Utils.toProtocol(options, ElementHandleUncheckParams.class); - channel.uncheck(params, frame.timeout(options.timeout)); + public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { + ElementHandleEvalOnSelectorAllParams params = new ElementHandleEvalOnSelectorAllParams(); + params.selector = selector; + params.expression = pageFunction; + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializeArgument(arg); + ElementHandleEvalOnSelectorAllResult result = elementChannel.evalOnSelectorAll(params, NO_TIMEOUT); + return deserialize(result.value); } @Override @@ -458,12 +401,9 @@ public void waitForElementState(ElementState state, WaitForElementStateOptions o if (options == null) { options = new WaitForElementStateOptions(); } - if (state == null) { - throw new IllegalArgumentException("State cannot be null"); - } - ElementHandleWaitForElementStateParams params = Utils.toProtocol(options, ElementHandleWaitForElementStateParams.class); + ElementHandleWaitForElementStateParams params = toProtocol(options, ElementHandleWaitForElementStateParams.class); params.state = state.toString().toLowerCase(); - channel.waitForElementState(params, frame.timeout(options.timeout)); + elementChannel.waitForElementState(params, frame.timeout(options.timeout)); } @Override @@ -471,8 +411,201 @@ public ElementHandle waitForSelector(String selector, WaitForSelectorOptions opt if (options == null) { options = new WaitForSelectorOptions(); } - ElementHandleWaitForSelectorParams params = Utils.toProtocol(options, ElementHandleWaitForSelectorParams.class); + ElementHandleWaitForSelectorParams params = toProtocol(options, ElementHandleWaitForSelectorParams.class); params.selector = selector; - return channel.waitForSelector(params, frame.timeout(options.timeout)).element; + ElementHandleWaitForSelectorResult result = elementChannel.waitForSelector(params, frame.timeout(options.timeout)); + return result.element; + } + + // java: values is any of String, String[], SelectOption, SelectOption[], ElementHandle, ElementHandle[] or null; + // the result holds only elements and options, the caller copies them into its own params. + static ElementHandleSelectOptionParams convertSelectOptionValues(Object values) { + ElementHandleSelectOptionParams result = new ElementHandleSelectOptionParams(); + if (values == null) { + return result; + } + Object[] items = values instanceof Object[] ? (Object[]) values : new Object[] { values }; + if (items.length == 0) { + return result; + } + for (int i = 0; i < items.length; i++) { + if (items[i] == null) { + throw new PlaywrightException("options[" + i + "]: expected object, got null"); + } + } + if (items[0] instanceof ElementHandle) { + result.elements = new ArrayList<>(); + for (Object v : items) { + result.elements.add((ElementHandleImpl) v); + } + return result; + } + if (items[0] instanceof String) { + result.options = new ArrayList<>(); + for (Object valueOrLabel : items) { + ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); + option.valueOrLabel = (String) valueOrLabel; + result.options.add(option); + } + return result; + } + result.options = new ArrayList<>(); + for (Object v : items) { + SelectOption value = (SelectOption) v; + ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); + option.value = value.value; + option.label = value.label; + option.index = value.index; + result.options.add(option); + } + return result; + } + + private static boolean filePayloadExceedsSizeLimit(List payloads) { + long size = 0; + for (FilePayload item : payloads) { + size += item.buffer != null ? item.buffer.length : 0; + } + return size >= fileUploadSizeLimit; + } + + // java: returns the directory and adds the files to localPaths, which stays empty when there are none. + private static Path resolvePathsAndDirectoryForInputFiles(List items, List localPaths) { + Path localDirectory = null; + for (Object item : items) { + BasicFileAttributes stat = stat((Path) item); + if (stat.isDirectory()) { + if (localDirectory != null) { + throw new PlaywrightException("Multiple directories are not supported"); + } + localDirectory = ((Path) item).toAbsolutePath().normalize(); + } else { + localPaths.add(((Path) item).toAbsolutePath().normalize()); + } + } + if (!localPaths.isEmpty() && localDirectory != null) { + throw new PlaywrightException("File paths must be all files or a single directory"); + } + return localDirectory; + } + + // java: files is any of Path, Path[], FilePayload or FilePayload[]; a Path stands for upstream's string. + // The result holds only the file fields, the caller copies them into its own params. + static ElementHandleSetInputFilesParams convertInputFiles(Object files, BrowserContextImpl context) { + List items = files instanceof Object[] ? new ArrayList<>(Arrays.asList((Object[]) files)) : new ArrayList<>(Collections.singletonList(files)); + + if (items.stream().anyMatch(item -> item instanceof Path)) { + if (!items.stream().allMatch(item -> item instanceof Path)) { + throw new PlaywrightException("File paths cannot be mixed with buffers"); + } + + List localPaths = new ArrayList<>(); + Path localDirectory = resolvePathsAndDirectoryForInputFiles(items, localPaths); + + if (context.connection.isRemote()) { + List filesToStream = localDirectory != null ? listFilesRecursively(localDirectory) : localPaths; + BrowserContextCreateTempFilesResult tempFiles = context.wrapApiCall(() -> { + BrowserContextCreateTempFilesParams params = new BrowserContextCreateTempFilesParams(); + params.rootDirName = localDirectory != null ? localDirectory.getFileName().toString() : null; + params.items = new ArrayList<>(); + for (Path file : filesToStream) { + double lastModifiedMs = (double) stat(file).lastModifiedTime().toMillis(); + BrowserContextCreateTempFilesParams.BrowserContextCreateTempFilesParamsItems item = new BrowserContextCreateTempFilesParams.BrowserContextCreateTempFilesParamsItems(); + item.name = localDirectory != null ? localDirectory.relativize(file).toString() : file.getFileName().toString(); + item.lastModifiedMs = lastModifiedMs; + params.items.add(item); + } + return context.channel.createTempFiles(params, NO_TIMEOUT); + }, null, true); + List writableStreams = tempFiles.writableStreams; + WritableStream rootDir = tempFiles.rootDir; + for (int i = 0; i < filesToStream.size(); i++) { + WritableStream writable = writableStreams.get(i); + // java: Files.copy into the stream of the WritableStream stands for stream.pipeline. + try (OutputStream out = writable.stream()) { + Files.copy(filesToStream.get(i), out); + } catch (IOException e) { + throw new PlaywrightException("Failed to copy file to remote server.", e); + } + } + ElementHandleSetInputFilesParams result = new ElementHandleSetInputFilesParams(); + result.directoryStream = rootDir; + result.streams = localDirectory != null ? null : writableStreams; + return result; + } + ElementHandleSetInputFilesParams result = new ElementHandleSetInputFilesParams(); + if (!localPaths.isEmpty()) { + result.localPaths = new ArrayList<>(); + for (Path path : localPaths) { + result.localPaths.add(path.toString()); + } + } + result.localDirectory = localDirectory != null ? localDirectory.toString() : null; + return result; + } + + List payloads = new ArrayList<>(); + for (Object item : items) { + payloads.add((FilePayload) item); + } + if (filePayloadExceedsSizeLimit(payloads)) { + throw new PlaywrightException("Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead."); + } + ElementHandleSetInputFilesParams result = new ElementHandleSetInputFilesParams(); + result.payloads = new ArrayList<>(); + for (FilePayload file : payloads) { + ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads payload = new ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads(); + payload.name = file.name; + payload.mimeType = file.mimeType; + payload.buffer = file.buffer; + result.payloads.add(payload); + } + return result; + } + + // java: one overload per screenshot options class; the result is the protocol string. + static String determineScreenshotType(ElementHandle.ScreenshotOptions options) { + return determineScreenshotType(options.path, options.type); + } + + static String determineScreenshotType(Page.ScreenshotOptions options) { + return determineScreenshotType(options.path, options.type); + } + + static String determineScreenshotType(Locator.ScreenshotOptions options) { + return determineScreenshotType(options.path, options.type); + } + + private static String determineScreenshotType(Path path, ScreenshotType type) { + if (path != null) { + String mimeType = getMimeTypeForPath(path.toString()); + if ("image/png".equals(mimeType)) + return "png"; + else if ("image/jpeg".equals(mimeType)) + return "jpeg"; + else if ("image/webp".equals(mimeType)) + return "webp"; + throw new PlaywrightException("path: unsupported mime type \"" + mimeType + "\""); + } + return type == null ? null : type.toString().toLowerCase(); + } + + // java: fs.promises.stat and fs.promises.readdir with recursive: true. + private static BasicFileAttributes stat(Path path) { + try { + return Files.readAttributes(path, BasicFileAttributes.class); + } catch (NoSuchFileException e) { + throw new PlaywrightException("ENOENT: no such file or directory, stat '" + path + "'", e); + } catch (IOException e) { + throw new PlaywrightException("Failed to read file attributes: " + path, e); + } + } + + private static List listFilesRecursively(Path directory) { + try (Stream paths = Files.walk(directory)) { + return paths.filter(Files::isRegularFile).collect(Collectors.toList()); + } catch (IOException e) { + throw new PlaywrightException("Failed to traverse directory", e); + } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java index b0e4100e9..9b50ebe2b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -14,26 +14,54 @@ * limitations under the License. */ -// Port of packages/playwright-core/src/client/errors.ts +// Port of errors.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.TimeoutError; -// java: errors.ts declares the error classes (PlaywrightError, TimeoutError, TargetClosedError) -// and the functions next to them. Here the classes stay in their own files (TimeoutError is -// public API, TargetClosedError is public, DriverException is upstream's generic PlaywrightError) -// and this class holds the functions. +import java.io.PrintWriter; +import java.io.StringWriter; + +import static com.microsoft.playwright.impl.Serialization.serializeValue; + +// java: errors.ts declares the error classes and the functions next to them; this class holds the functions. class Errors { private Errors() { } + // java: class PlaywrightError is DriverException.java (its log and details are ServerErrorWithDetails.java), + // class TimeoutError is the public com.microsoft.playwright.TimeoutError, class TargetClosedError is TargetClosedError.java. + // java: class AbortError is not ported, there is no AbortSignal. + static boolean isTargetClosedError(Throwable error) { return error instanceof TargetClosedError; } - // serializeError is not needed: the client never sends errors to the server. + // java: isError(e) is the Throwable check; e.name is the simple class name and e.stack the printed + // stack trace; a Java exception has no system error code. + static SerializedError serializeError(Object e) { + if (e instanceof Throwable) { + Throwable error = (Throwable) e; + SerializedError result = new SerializedError(); + result.error = new SerializedError.SerializedErrorError(); + result.error.message = error.getMessage(); + StringWriter stack = new StringWriter(); + error.printStackTrace(new PrintWriter(stack)); + result.error.stack = stack.toString(); + result.error.name = error.getClass().getSimpleName(); + return result; + } + SerializedError result = new SerializedError(); + result.value = serializeValue(e, value -> { + Serialization.HandleOrValue handle = new Serialization.HandleOrValue(); + handle.hasFallThrough = true; + handle.fallThrough = value; + return handle; + }); + return result; + } // java: the message is built the way the Java client always did, see errorToString, because the // tests match on it. Upstream uses error.error.message and appends the call log in Connection.dispatch. @@ -45,7 +73,11 @@ static PlaywrightException parseError(SerializedError error) { // is built; upstream rewrites the message afterwards (rewriteErrorMessage in Connection.dispatch). static PlaywrightException parseError(SerializedError error, String callLog) { if (error.error == null) { - // java: upstream parses error.value back into a value; here the structure is only printed. + if (error.value == null) { + throw new PlaywrightException("Serialized error must have either an error or a value"); + } + // java: upstream returns parseSerializedValue(error.value), a thrown non-Error value; a Java + // exception cannot be a value, so the structure is only printed. return new PlaywrightException(errorToString(error) + callLog); } String message = errorToString(error.error) + callLog; @@ -55,10 +87,13 @@ static PlaywrightException parseError(SerializedError error, String callLog) { if ("TargetClosedError".equals(error.error.name)) { return new TargetClosedError(message); } + // java: the AbortError branch is not ported, there is no AbortSignal; it falls through to the generic error. + // java: e.stack (the server stack) and e.code are not kept, the Java exception has its own stack and no code. return new DriverException(message); } - // java: the "has been closed" family that close paths swallow; not in errors.ts. + // java: helpers with no counterpart in errors.ts. + // java: the "has been closed" family that close paths swallow. static boolean isSafeCloseError(PlaywrightException exception) { return isSafeCloseError(exception.getMessage()); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java index 5d35e5533..3d700b459 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java @@ -13,76 +13,293 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Port of packages/playwright-core/src/client/eventEmitter.ts + +// Port of eventEmitter.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Consumer; // java: upstream's ChannelOwner and the rest of the client reach the logging helpers through // imports; here they stay reachable as inherited statics. +// java: event types are strings, Java has no symbols; listeners are Consumers of the one event argument. class EventEmitter extends LoggingSupport { - private final Map>> events = new HashMap<>(); - void emit(String type, T arg) { - List> handlers = events.get(type); - if (handlers == null) { - return; + // java: upstream keeps one function or an array of them per type; here it is always a list. + private Map>> events = new LinkedHashMap<>(); + private int eventsCount = 0; + private Integer maxListeners = null; + // java: _pendingHandlers and _rejectionHandler are not ported, a Consumer returns no promise to track. + + // java: the constructor resets the _events of the prototype and aliases on/off to addListener/removeListener; + // the Java fields start fresh and on/off are methods below. + + EventEmitter setMaxListeners(int n) { + // java: typeof n and Number.isNaN(n) checks are not ported, n is an int. + if (n < 0) { + throw new IllegalArgumentException("The value of \"n\" is out of range. It must be a non-negative number. Received " + n + "."); } - // The handlers are copied, a handler may remove itself. - for (Consumer handler : new ArrayList<>(handlers)) { - ((Consumer) handler).accept(arg); + maxListeners = n; + return this; + } + + int getMaxListeners() { + return maxListeners == null ? defaultMaxListeners : maxListeners; + } + + boolean emit(String type, T arg) { + List> handler = events.get(type); + if (handler == null) { + return false; } + // java: the handler is always a list; the listeners are copied, a handler may remove itself. + List> listeners = new ArrayList<>(handler); + for (Consumer listener : listeners) { + callHandler(type, listener, arg); + } + return true; } - void addListener(String type, Consumer listener) { - if (listener == null) { - throw new PlaywrightException("Can't add a null listener"); + @SuppressWarnings("unchecked") + private void callHandler(String type, Consumer handler, T arg) { + try { + ((Consumer) handler).accept(arg); + } catch (RuntimeException error) { + handleListenerError(type, error); } - List> list = events.get(type); - if (list == null) { - list = new ArrayList<>(); - events.put(type, list); + // java: the branch for a handler that returns a promise is not ported, a Consumer returns nothing. + } + + private void handleListenerError(String type, RuntimeException error) { + if ("error".equals(type) || listenerCount("error") == 0) { + throw error; } - list.add(listener); + emit("error", error); + } + + void addListener(String type, Consumer listener) { + addListener(type, listener, false); } void on(String type, Consumer listener) { - addListener(type, listener); + addListener(type, listener, false); + } + + private void addListener(String type, Consumer listener, boolean prepend) { + checkListener(listener); + // java: the newListener event is not emitted, upstream passes it two arguments and Java listeners take one. + List> existing = events.get(type); + + if (existing == null) { + // java: a list of one, upstream stores the function itself. + existing = new ArrayList<>(); + existing.add(listener); + events.put(type, existing); + ++eventsCount; + } else { + if (prepend) { + existing.add(0, listener); + } else { + existing.add(listener); + } + + // Check for listener leak + int m = getMaxListeners(); + if (m > 0 && existing.size() > m && !warned.contains(existing)) { + warned.add(existing); + // No error code for this since it is a Warning + // java: console.warn(w) of the MaxListenersExceededWarning error; isUnderTest() has no Java counterpart. + System.err.println("MaxListenersExceededWarning: Possible EventEmitter memory leak detected. " + + existing.size() + " " + type + " listeners " + + "added. Use emitter.setMaxListeners() to " + + "increase limit"); + } + } + } + + void prependListener(String type, Consumer listener) { + addListener(type, listener, true); + } + + void once(String type, Consumer listener) { + checkListener(listener); + on(type, new OnceWrapper(this, type, listener).wrapperFunction); + } + + void prependOnceListener(String type, Consumer listener) { + checkListener(listener); + prependListener(type, new OnceWrapper(this, type, listener).wrapperFunction); } void removeListener(String type, Consumer listener) { + // java: checkListener(listener) is not called, removing a null listener stays a no-op as it always was in Java. + List> list = events.get(type); if (list == null) { return; } + // java: removes every registration of the listener, upstream removes the last one only. - list.removeAll(java.util.Collections.singleton(listener)); + list.removeIf(l -> l == listener || wrappedListener(l) == listener); if (list.isEmpty()) { events.remove(type); + --eventsCount; } + // java: the removeListener event is not emitted, upstream passes it two arguments and Java listeners take one. } void off(String type, Consumer listener) { removeListener(type, listener); } + void removeAllListeners() { + removeAllListeners(null); + } + void removeAllListeners(String type) { - events.remove(type); + removeAllListenersImpl(type); } - int listenerCount(String type) { - List> list = events.get(type); - return list == null ? 0 : list.size(); + // java: the options bag { behavior } is the behavior string; upstream returns a promise for this overload. + void removeAllListeners(String type, String behavior) { + removeAllListenersImpl(type); + + if ("wait".equals(behavior)) { + // java: _waitFor and the errors collected by _rejectionHandler are not ported, a Consumer leaves + // no pending promise behind. + return; + } + + if ("ignoreErrors".equals(behavior)) { + // java: _rejectionHandler is not ported, a Consumer leaves no rejection to ignore. + } + } + + // java: _removeAllListeners; the Impl suffix avoids the clash with removeAllListeners(type). + private void removeAllListenersImpl(String type) { + // not listening for removeListener, no need to emit + // java: the removeListener event is never emitted, so the branch that emits it for every listener is not ported. + if (type == null) { + events = new LinkedHashMap<>(); + eventsCount = 0; + } else if (events.get(type) != null) { + if (--eventsCount == 0) { + events = new LinkedHashMap<>(); + } else { + events.remove(type); + } + } } List> listeners(String type) { - List> list = events.get(type); - return list == null ? new ArrayList>() : new ArrayList<>(list); + return listeners(this, type, true); + } + + List> rawListeners(String type) { + return listeners(this, type, false); + } + + int listenerCount(String type) { + List> listener = events.get(type); + if (listener != null) { + return listener.size(); + } + return 0; + } + + List eventNames() { + return eventsCount > 0 ? new ArrayList<>(events.keySet()) : new ArrayList<>(); + } + + // java: _waitFor is not ported, a Consumer leaves no pending promise to wait for. + + private List> listeners(EventEmitter target, String type, boolean unwrap) { + List> listener = target.events.get(type); + if (listener == null) { + return new ArrayList<>(); + } + + return unwrap ? unwrapListeners(listener) : new ArrayList<>(listener); + } + + // java: the message of the existing Java client, tests match on it; upstream throws a TypeError + // 'The "listener" argument must be of type Function. Received type ...'. + private static void checkListener(Consumer listener) { + if (listener == null) { + throw new PlaywrightException("Can't add a null listener"); + } + } + + private static class OnceWrapper { + private boolean fired = false; + final WrapperFunction wrapperFunction; + final Consumer listener; + private final EventEmitter eventEmitter; + private final String eventType; + + OnceWrapper(EventEmitter eventEmitter, String eventType, Consumer listener) { + this.eventEmitter = eventEmitter; + this.eventType = eventType; + this.listener = listener; + this.wrapperFunction = new WrapperFunction(this::handle, listener); + } + + @SuppressWarnings("unchecked") + private void handle(Object arg) { + if (fired) { + return; + } + fired = true; + eventEmitter.removeListener(eventType, wrapperFunction); + ((Consumer) listener).accept(arg); + } + } + + private static Consumer unwrapListener(Consumer l) { + Consumer wrapped = wrappedListener(l); + return wrapped != null ? wrapped : l; + } + + private static List> unwrapListeners(List> arr) { + List> result = new ArrayList<>(); + for (Consumer l : arr) { + result.add(unwrapListener(l)); + } + return result; + } + + private static Consumer wrappedListener(Consumer l) { + return l instanceof WrapperFunction ? ((WrapperFunction) l).listener : null; + } + + // java: helpers with no counterpart in eventEmitter.ts. + // java: NodeEventEmitter.defaultMaxListeners. + static final int defaultMaxListeners = 10; + + // java: the warned flag that upstream sets on the listener array. + private final Set>> warned = Collections.newSetFromMap(new IdentityHashMap<>()); + + // java: the wrapper function of OnceWrapper with its listener property. + private static class WrapperFunction implements Consumer { + private final Consumer handle; + final Consumer listener; + + WrapperFunction(Consumer handle, Consumer listener) { + this.handle = handle; + this.listener = listener; + } + + @Override + public void accept(Object arg) { + handle.accept(arg); + } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Events.java b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java index 37400a6fc..37ab4478a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Events.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java @@ -13,13 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Port of packages/playwright-core/src/client/events.ts + +// Port of events.ts. package com.microsoft.playwright.impl; final class Events { private Events() { } + static final class AndroidDevice { + static final String WEB_VIEW = "webview"; + static final String CLOSE = "close"; + } + + static final class AndroidSocket { + static final String DATA = "data"; + static final String CLOSE = "close"; + } + + static final class AndroidWebView { + static final String CLOSE = "close"; + } + static final class Browser { static final String CONTEXT = "context"; static final String DISCONNECTED = "disconnected"; @@ -43,6 +58,7 @@ static final class BrowserContext { static final String PAGE_CLOSE = "pageclose"; static final String PAGE_LOAD = "pageload"; // Can't use just 'error' due to node.js special treatment of error events. + // @see https://nodejs.org/api/events.html#events_error_events static final String WEB_ERROR = "weberror"; static final String BACKGROUND_PAGE = "backgroundpage"; // Deprecated in v1.56, never emitted anymore. static final String SERVICE_WORKER = "serviceworker"; @@ -52,6 +68,10 @@ static final class BrowserContext { static final String REQUEST_FINISHED = "requestfinished"; } + static final class BrowserServer { + static final String CLOSE = "close"; + } + static final class Page { static final String CLOSE = "close"; static final String CRASH = "crash"; @@ -62,6 +82,7 @@ static final class Page { static final String FILE_CHOOSER = "filechooser"; static final String DOM_CONTENT_LOADED = "domcontentloaded"; // Can't use just 'error' due to node.js special treatment of error events. + // @see https://nodejs.org/api/events.html#events_error_events static final String PAGE_ERROR = "pageerror"; static final String REQUEST = "request"; static final String RESPONSE = "response"; @@ -88,6 +109,12 @@ static final class Worker { static final String CONSOLE = "console"; } + static final class ElectronApplication { + static final String CLOSE = "close"; + static final String CONSOLE = "console"; + static final String WINDOW = "window"; + } + // java: events that upstream emits as string literals (cdpSession.ts) or does not have (the Java // frame waits that upstream implements with promises, the json pipe close that the transport observes). static final class CDPSession { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java index 82a1fbfef..f5db22841 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of fileChooser.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.ElementHandle; @@ -27,18 +28,18 @@ class FileChooserImpl implements FileChooser { private final PageImpl page; - private final ElementHandleImpl element; + private final ElementHandleImpl elementHandle; private final boolean isMultiple; - FileChooserImpl(PageImpl page, ElementHandleImpl element, boolean isMultiple) { + FileChooserImpl(PageImpl page, ElementHandleImpl elementHandle, boolean isMultiple) { this.page = page; - this.element = element; + this.elementHandle = elementHandle; this.isMultiple = isMultiple; } @Override public ElementHandle element() { - return element; + return elementHandle; } @Override @@ -51,6 +52,7 @@ public Page page() { return page; } + // java: overloads for the public API; each delegates to ElementHandle.setInputFiles like upstream setFiles. @Override public void setFiles(Path files, SetFilesOptions options) { setFiles(new Path[]{files}, options); @@ -58,7 +60,7 @@ public void setFiles(Path files, SetFilesOptions options) { @Override public void setFiles(Path[] files, SetFilesOptions options) { - element.setInputFiles(files, convertType(options, ElementHandle.SetInputFilesOptions.class)); + elementHandle.setInputFiles(files, convertType(options, ElementHandle.SetInputFilesOptions.class)); } @Override @@ -68,6 +70,6 @@ public void setFiles(FilePayload files, SetFilesOptions options) { @Override public void setFiles(FilePayload[] files, SetFilesOptions options) { - element.setInputFiles(files, convertType(options, ElementHandle.SetInputFilesOptions.class)); + elementHandle.setInputFiles(files, convertType(options, ElementHandle.SetInputFilesOptions.class)); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java new file mode 100644 index 000000000..c457aad92 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of fileUtils.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +class FileUtils { + // Keep in sync with the server. + static final long fileUploadSizeLimit = 50 * 1024 * 1024; + + // java: a failure to create the directory is reported, upstream ignores it. + static void mkdirIfNeeded(Path filePath) { + Path dir = filePath.getParent(); + if (dir != null) { + if (!Files.exists(dir)) { + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new PlaywrightException("Failed to create parent directory: " + dir, e); + } + } + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Protocol.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java similarity index 74% rename from playwright/src/main/java/com/microsoft/playwright/impl/Protocol.java rename to playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java index 7a489ef9d..77f19a2e1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Protocol.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectOptions.java @@ -16,10 +16,13 @@ package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; +import com.microsoft.playwright.impl.protocol.ExpectedTextValue; +import com.microsoft.playwright.impl.protocol.SerializedArgument; import com.microsoft.playwright.options.PseudoElement; + import java.util.List; +// java: the options of Frame._expect, FrameExpectParams of types.ts. class FrameExpectOptions { Object expressionArg; List expectedText; @@ -31,11 +34,3 @@ class FrameExpectOptions { boolean isNot; Double timeout; } - -// Client-side outcome of Frame.expect: the command has no result, a mismatch arrives as an error with FrameExpectErrorDetails. -class FrameExpectResult { - boolean matches; - FrameExpectErrorDetails.FrameExpectErrorDetailsReceived received; - String errorMessage; - List log; -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java similarity index 63% rename from playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java rename to playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java index 05941a86e..8a4d3477d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java @@ -16,14 +16,14 @@ package com.microsoft.playwright.impl; -import com.google.gson.JsonObject; +import com.microsoft.playwright.impl.protocol.FrameExpectErrorDetails; -public class RemoteBrowser extends ChannelOwner { - RemoteBrowser(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } +import java.util.List; - BrowserImpl browser() { - return connection.getExistingObject(initializer.getAsJsonObject("browser").get("guid").getAsString()); - } +// java: ExpectResult of frame.ts; the command has no result, a mismatch arrives as an error with FrameExpectErrorDetails. +class FrameExpectResult { + boolean matches; + FrameExpectErrorDetails.FrameExpectErrorDetailsReceived received; + String errorMessage; + List log; } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index 38b3ac22b..afbeca621 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -14,244 +14,317 @@ * limitations under the License. */ +// Port of frame.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.*; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; -import java.util.function.Consumer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.LocatorUtils.*; +import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*; +import static com.microsoft.playwright.impl.Serialization.deserialize; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Serialization.assertEvaluateOptions; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.Serialization.serializeArgumentWithCallbacks; import static com.microsoft.playwright.impl.Utils.*; -import static com.microsoft.playwright.options.WaitUntilState.*; -import static com.microsoft.playwright.impl.Serialization.*; public class FrameImpl extends ChannelOwner implements Frame { - private String name; - private String url; + final EventEmitter eventEmitter; + Set loadStates; FrameImpl parentFrame; + String url = ""; + String name = ""; + boolean detached; Set childFrames = new LinkedHashSet<>(); - private final Set loadStates = new HashSet<>(); - PageImpl page; - boolean isDetached; - private final WebMCPImpl webmcp = new WebMCPImpl(this); + final WebMCPImpl webmcp; final FrameChannel channel = new FrameChannel(this); + // java: from and fromNullable are not ported, generated results already hold the impl object. + FrameImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - - name = initializer.get("name").getAsString(); - url = initializer.get("url").getAsString(); - if (initializer.has("parentFrame")) { - parentFrame = connection.getExistingObject(initializer.getAsJsonObject("parentFrame").get("guid").getAsString()); + FrameInitializer init = connection.protocolGson().fromJson(initializer, FrameInitializer.class); + eventEmitter = new EventEmitter(); + // java: setMaxListeners(0) is not ported, EventEmitter has no listener limit. + webmcp = new WebMCPImpl(this); + parentFrame = init.parentFrame; + if (parentFrame != null) { parentFrame.childFrames.add(this); } - for (JsonElement item : initializer.get("loadStates").getAsJsonArray()) { - loadStates.add(loadStateFromProtocol(item.getAsString())); - } - } - - private static WaitUntilState loadStateFromProtocol(String value) { - switch (value) { - case "load": return LOAD; - case "domcontentloaded": return DOMCONTENTLOADED; - case "networkidle": return NETWORKIDLE; - case "commit": return COMMIT; - default: throw new PlaywrightException("Unexpected value: " + value); - } + name = init.name; + url = init.url; + loadStates = new LinkedHashSet<>(init.loadStates); } + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. @Override - public ElementHandle querySelector(String selector, QuerySelectorOptions options) { - if (options == null) { - options = new QuerySelectorOptions(); + void handleEvent(String event, JsonObject params) { + if ("loadstate".equals(event)) { + FrameLoadstateEvent loadstateEvent = connection.protocolGson().fromJson(params, FrameLoadstateEvent.class); + if (loadstateEvent.add != null) { + loadStates.add(loadstateEvent.add); + eventEmitter.emit(Events.Frame.LOAD_STATE, loadstateEvent.add); + } + if (loadstateEvent.remove != null) { + loadStates.remove(loadstateEvent.remove); + } + if (parentFrame == null && "load".equals(loadstateEvent.add) && page != null) { + page.emit(Events.Page.LOAD, page); + page.context().emit(Events.BrowserContext.PAGE_LOAD, page); + } + if (parentFrame == null && "domcontentloaded".equals(loadstateEvent.add) && page != null) { + page.emit(Events.Page.DOM_CONTENT_LOADED, page); + } + } else if ("navigated".equals(event)) { + FrameNavigatedEvent navigatedEvent = connection.protocolGson().fromJson(params, FrameNavigatedEvent.class); + url = navigatedEvent.url; + name = navigatedEvent.name; + // Main frame navigation destroys all execution contexts in the page, + // erase the bindings backing the functions passed to evaluate(). + if (parentFrame == null && navigatedEvent.newDocument != null && page != null) { + page.eraseEvaluateCallbacks(); + } + eventEmitter.emit(Events.Frame.NAVIGATED, navigatedEvent); + if (navigatedEvent.error == null && page != null) { + page.emit(Events.Page.FRAME_NAVIGATED, this); + page.context().emit(Events.BrowserContext.FRAME_NAVIGATED, this); + } } - FrameQuerySelectorParams params = toProtocol(options, FrameQuerySelectorParams.class); - params.selector = selector; - return channel.querySelector(params, NO_TIMEOUT).element; } @Override - public List querySelectorAll(String selector) { - FrameQuerySelectorAllParams params = new FrameQuerySelectorAllParams(); - params.selector = selector; - FrameQuerySelectorAllResult result = channel.querySelectorAll(params, NO_TIMEOUT); - if (result.elements == null) { - return null; - } - return new ArrayList(result.elements); + public PageImpl page() { + return page; } - @Override - public List selectOption(String selector, String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(selector, values, options); + double timeout(Double timeout) { + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + return timeoutSettings.timeout(timeout); } - @Override - public List selectOption(String selector, ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{value}; - return selectOption(selector, values, options); + double navigationTimeout(Double timeout) { + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + return timeoutSettings.navigationTimeout(timeout); } @Override - public List selectOption(String selector, String[] values, SelectOptionOptions options) { - return selectOptionImpl(selector, values, options); + public ResponseImpl navigate(String url, NavigateOptions options) { + if (options == null) { + options = new NavigateOptions(); + } + FrameGotoParams params = toProtocol(options, FrameGotoParams.class); + params.url = url; + params.waitUntil = verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); + return channel.goto_(params, navigationTimeout(options.timeout)).response; } - @Override - public List selectOption(String selector, SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{value}; - return selectOption(selector, values, options); + private Waiter setupNavigationWaiter(Double timeout) { + Waiter waiter = new Waiter(page, ""); + if (page.isClosed()) { + waiter.rejectImmediately(page.closeErrorWithReason()); + } + waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); + waiter.rejectOnEvent(page, Events.Page.CRASH, () -> new PlaywrightException("Navigation failed because page crashed!")); + waiter.rejectOnEvent(page, Events.Page.FRAME_DETACHED, () -> new PlaywrightException("Navigating frame was detached!"), frame -> frame == this); + double timeoutMs = page.timeoutSettings.navigationTimeout(timeout); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded."); + return waiter; } - @Override - public Object evalOnSelector(String selector, String pageFunction, Object arg, EvalOnSelectorOptions options) { - return evalOnSelectorImpl(selector, pageFunction, arg, options); - } - - Object evalOnSelectorImpl(String selector, String pageFunction, Object arg, EvalOnSelectorOptions options) { + public ResponseImpl waitForNavigation(WaitForNavigationOptions options, Runnable callback) { if (options == null) { - options = new EvalOnSelectorOptions(); + options = new WaitForNavigationOptions(); } - FrameEvalOnSelectorParams params = toProtocol(options, FrameEvalOnSelectorParams.class); - params.selector = selector; - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evalOnSelector(params, NO_TIMEOUT).value); + // java: the matcher is built once and before the waiter subscribes: a glob is converted by a call to the driver, + // which dispatches the events that arrive meanwhile. + UrlMatcher matcher = UrlMatcher.forOneOf(page != null ? page.context().baseUrl() : null, options.url, connection.localUtils(), false); + return waitForNavigation(matcher, options, callback); } - @Override - public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { - return evalOnSelectorAllImpl(selector, pageFunction, arg); - } + private ResponseImpl waitForNavigation(UrlMatcher matcher, WaitForNavigationOptions options, Runnable callback) { + String waitUntil = verifyLoadState("waitUntil", options.waitUntil == null ? "load" : lifecycleEvent(options.waitUntil)); + Double timeout = options.timeout; + // java: only the setup runs in the "Wait for navigation" zone, so that the calls of the callback are reported on their own. + Waiter waiter = withTitle("Wait for navigation", () -> setupNavigationWaiter(timeout)); - Object evalOnSelectorAllImpl(String selector, String pageFunction, Object arg) { - FrameEvalOnSelectorAllParams params = new FrameEvalOnSelectorAllParams(); - params.selector = selector; - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evalOnSelectorAll(params, NO_TIMEOUT).value); - } + String toUrl = options.url instanceof String ? " to \"" + options.url + "\"" : ""; + waiter.log("waiting for navigation" + toUrl + " until \"" + waitUntil + "\""); - @Override - public ElementHandle addScriptTag(AddScriptTagOptions options){ - return addScriptTagImpl(options); - } + FrameNavigatedEvent navigatedEvent = waiter.waitForEvent(eventEmitter, Events.Frame.NAVIGATED, (FrameNavigatedEvent event) -> { + // Any failed navigation results in a rejection. + if (event.error != null) { + return true; + } + waiter.log(" navigated to \"" + event.url + "\""); + return matcher.test(event.url); + }, callback); + if (navigatedEvent.error != null) { + WaitableResult failure = new WaitableResult<>(); + failure.completeExceptionally(new PlaywrightException(navigatedEvent.error)); + waiter.waitForPromise(failure); + } - ElementHandle addScriptTagImpl(AddScriptTagOptions options) { - if (options == null) { - options = new AddScriptTagOptions(); + if (!loadStates.contains(waitUntil)) { + waiter.waitForPromise(waiter.waitForEvent(eventEmitter, Events.Frame.LOAD_STATE, s -> { + waiter.log(" \"" + s + "\" event fired"); + return s.equals(waitUntil); + })); } - FrameAddScriptTagParams params = toProtocol(options, FrameAddScriptTagParams.class); - if (options.path != null) { - byte[] encoded; + + RequestImpl request = navigatedEvent.newDocument != null ? navigatedEvent.newDocument.request : null; + ResponseImpl response = null; + if (request != null) { + // java: the call pumps the connection until its reply; its outcome goes through the waiter as upstream's promise does. + WaitableResult result = new WaitableResult<>(); try { - encoded = Files.readAllBytes(options.path); - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); + result.complete(request.finalRequest().internalResponse()); + } catch (RuntimeException e) { + result.completeExceptionally(e); } - String content = new String(encoded, StandardCharsets.UTF_8); - content = addSourceUrlToScript(content, options.path); - params.content = content; + response = waiter.waitForPromise(result); } - return channel.addScriptTag(params, NO_TIMEOUT).element; + waiter.dispose(); + return response; } @Override - public ElementHandle addStyleTag(AddStyleTagOptions options){ - return addStyleTagImpl(options); + public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { + waitForLoadState(state == null ? "load" : state.name().toLowerCase(Locale.ROOT), options == null ? null : options.timeout); } - ElementHandle addStyleTagImpl(AddStyleTagOptions options) { - if (options == null) { - options = new AddStyleTagOptions(); - } - FrameAddStyleTagParams params = toProtocol(options, FrameAddStyleTagParams.class); - if (options.path != null) { - byte[] encoded; + // java: the core of waitForLoadState, taking any lifecycle event: LoadState has no COMMIT, which waitForURL may pass. + private void waitForLoadState(String state, Double timeout) { + String verifiedState = verifyLoadState("state", state); + // java: the title carries the state, tests pin it. + withTitle("Wait for load state \"" + verifiedState + "\"", () -> { + Waiter waiter = setupNavigationWaiter(timeout); try { - encoded = Files.readAllBytes(options.path); - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); + if (loadStates.contains(verifiedState)) { + waiter.log(" not waiting, \"" + verifiedState + "\" event already fired"); + waiter.throwIfImmediatelyRejected(); + } else { + waiter.waitForPromise(waiter.waitForEvent(eventEmitter, Events.Frame.LOAD_STATE, s -> { + waiter.log(" \"" + s + "\" event fired"); + return s.equals(verifiedState); + })); + } + } finally { + waiter.dispose(); } - String content = new String(encoded, StandardCharsets.UTF_8); - content += "/*# sourceURL=" + options.path.toString().replace("\n", "") + "*/"; - params.content = content; - } - return channel.addStyleTag(params, NO_TIMEOUT).element; + }); } @Override - public void check(String selector, CheckOptions options){ - if (options == null) { - options = new CheckOptions(); - } - FrameCheckParams params = toProtocol(options, FrameCheckParams.class); - params.selector = selector; - channel.check(params, timeout(options.timeout)); + public void waitForURL(String url, WaitForURLOptions options) { + waitForURL((Object) url, options); } @Override - public List childFrames() { - return new ArrayList<>(childFrames); + public void waitForURL(Pattern url, WaitForURLOptions options) { + waitForURL((Object) url, options); } @Override - public void click(String selector, ClickOptions options) { - clickImpl(selector, options, null); + public void waitForURL(Predicate url, WaitForURLOptions options) { + waitForURL((Object) url, options); } - void clickImpl(String selector, ClickOptions options, Integer steps) { - if (options == null) { - options = new ClickOptions(); - } - FrameClickParams params = toProtocol(options, FrameClickParams.class); - params.selector = selector; - if (steps != null) { - params.steps = steps; + private void waitForURL(Object url, WaitForURLOptions options) { + WaitForURLOptions waitOptions = options == null ? new WaitForURLOptions() : options; + // java: one matcher for the check and the wait, nothing pumps the connection between them. + UrlMatcher matcher = UrlMatcher.forOneOf(page != null ? page.context().baseUrl() : null, url, connection.localUtils(), false); + if (matcher.test(url())) { + waitForLoadState(waitOptions.waitUntil == null ? "load" : lifecycleEvent(waitOptions.waitUntil), waitOptions.timeout); + return; } - channel.click(params, timeout(options.timeout)); + + WaitForNavigationOptions navigationOptions = new WaitForNavigationOptions(); + navigationOptions.url = url; + navigationOptions.waitUntil = waitOptions.waitUntil; + navigationOptions.timeout = waitOptions.timeout; + waitForNavigation(matcher, navigationOptions, null); } @Override - public String content(ContentOptions options) { - if (options == null) { - options = new ContentOptions(); - } - FrameContentParams params = toProtocol(options, FrameContentParams.class); - return channel.content(params, NO_TIMEOUT).value; + public ElementHandleImpl frameElement() { + return channel.frameElement(new FrameFrameElementParams(), NO_TIMEOUT).element; } @Override - public void dblclick(String selector, DblclickOptions options) { - dblclickImpl(selector, options, null); + public JSHandle evaluateHandle(String expression, Object arg) { + return evaluateHandle(expression, arg, null); + } + + // java: the public API has no evaluate options, so the options overload is package-private. assertMaxArguments + // is a JS typing check; isFunction is left out, the expression is a String. + JSHandle evaluateHandle(String expression, Object arg, Serialization.EvaluateOptions options) { + assertEvaluateOptions(options); + SerializedArgument serializedArg = options != null && Boolean.TRUE.equals(options.exposeFunctions) ? serializeArgumentWithCallbacks(this, page, arg) : serializeArgument(arg); + FrameEvaluateExpressionHandleParams params = new FrameEvaluateExpressionHandleParams(); + params.expression = expression; + params.arg = serializedArg; + return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; + } + + @Override + public Object evaluate(String expression, Object arg) { + return evaluate(expression, arg, null); + } + + // java: the public API has no evaluate options, so the options overload is package-private. assertMaxArguments + // is a JS typing check; isFunction is left out, the expression is a String. + Object evaluate(String expression, Object arg, Serialization.EvaluateOptions options) { + assertEvaluateOptions(options); + SerializedArgument serializedArg = options != null && Boolean.TRUE.equals(options.exposeFunctions) ? serializeArgumentWithCallbacks(this, page, arg) : serializeArgument(arg); + FrameEvaluateExpressionParams params = new FrameEvaluateExpressionParams(); + params.expression = expression; + params.arg = serializedArg; + return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); } - void dblclickImpl(String selector, DblclickOptions options, Integer steps) { + // java: assertMaxArguments is a JS typing check; isFunction is left out, the expression is a String. + Object evaluateExposeUtilityScript(String expression, Object arg) { + FrameEvaluateExpressionParams params = new FrameEvaluateExpressionParams(); + params.expression = expression; + params.arg = serializeArgument(arg); + return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); + } + + @Override + public ElementHandleImpl querySelector(String selector, QuerySelectorOptions options) { + FrameQuerySelectorParams params = toProtocol(options, FrameQuerySelectorParams.class); + params.selector = selector; + return channel.querySelector(params, NO_TIMEOUT).element; + } + + @Override + public ElementHandleImpl waitForSelector(String selector, WaitForSelectorOptions options) { if (options == null) { - options = new DblclickOptions(); + options = new WaitForSelectorOptions(); } - FrameDblclickParams params = toProtocol(options, FrameDblclickParams.class); + // java: the visibility and waitFor checks are not ported, WaitForSelectorOptions has no such fields. + FrameWaitForSelectorParams params = toProtocol(options, FrameWaitForSelectorParams.class); params.selector = selector; - if (steps != null) { - params.steps = steps; - } - channel.dblclick(params, timeout(options.timeout)); + return channel.waitForSelector(params, timeout(options.timeout)).element; } @Override @@ -266,101 +339,254 @@ public void dispatchEvent(String selector, String type, Object eventInit, Dispat channel.dispatchEvent(params, timeout(options.timeout)); } + // java: assertMaxArguments is a JS typing check; isFunction is left out, the expression is a String. @Override - public Object evaluate(String expression, Object arg) { - FrameEvaluateExpressionParams params = new FrameEvaluateExpressionParams(); + public Object evalOnSelector(String selector, String expression, Object arg, EvalOnSelectorOptions options) { + FrameEvalOnSelectorParams params = toProtocol(options, FrameEvalOnSelectorParams.class); + params.selector = selector; params.expression = expression; params.arg = serializeArgument(arg); - return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); + return deserialize(channel.evalOnSelector(params, NO_TIMEOUT).value); } + // java: assertMaxArguments is a JS typing check; isFunction is left out, the expression is a String. @Override - public JSHandle evaluateHandle(String pageFunction, Object arg) { - FrameEvaluateExpressionHandleParams params = new FrameEvaluateExpressionHandleParams(); - params.expression = pageFunction; + public Object evalOnSelectorAll(String selector, String expression, Object arg) { + FrameEvalOnSelectorAllParams params = new FrameEvalOnSelectorAllParams(); + params.selector = selector; + params.expression = expression; params.arg = serializeArgument(arg); - return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; + return deserialize(channel.evalOnSelectorAll(params, NO_TIMEOUT).value); } @Override - public void fill(String selector, String value, FillOptions options) { - if (options == null) { - options = new FillOptions(); - } - FrameFillParams params = toProtocol(options, FrameFillParams.class); + public List querySelectorAll(String selector) { + FrameQuerySelectorAllParams params = new FrameQuerySelectorAllParams(); params.selector = selector; - params.value = value; - channel.fill(params, timeout(options.timeout)); + return new ArrayList<>(channel.querySelectorAll(params, NO_TIMEOUT).elements); } - @Override - public void focus(String selector, FocusOptions options) { - if (options == null) { - options = new FocusOptions(); - } - FrameFocusParams params = toProtocol(options, FrameFocusParams.class); + int queryCount(String selector) { + FrameQueryCountParams params = new FrameQueryCountParams(); params.selector = selector; - channel.focus(params, timeout(options.timeout)); + return channel.queryCount(params, NO_TIMEOUT).value; } @Override - public ElementHandle frameElement() { - return channel.frameElement(NO_TIMEOUT).element; + public String content(ContentOptions options) { + FrameContentParams params = toProtocol(options, FrameContentParams.class); + return channel.content(params, NO_TIMEOUT).value; } @Override - public FrameLocator frameLocator(String selector) { - return new FrameLocatorImpl(this, selector == null ? FrameLocatorImpl.ANY_FRAME_SELECTOR : selector); + public void setContent(String html, SetContentOptions options) { + if (options == null) { + options = new SetContentOptions(); + } + FrameSetContentParams params = toProtocol(options, FrameSetContentParams.class); + params.html = html; + params.waitUntil = verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); + channel.setContent(params, navigationTimeout(options.timeout)); } @Override - public String getAttribute(String selector, String name, GetAttributeOptions options) { - return getAttributeImpl(selector, name, options); + public String name() { + return name == null ? "" : name; } @Override - public Locator getByAltText(String text, GetByAltTextOptions options) { - return locator(getByAltTextSelector(text, convertType(options, Locator.GetByAltTextOptions.class))); + public String url() { + return url; } @Override - public Locator getByAltText(Pattern text, GetByAltTextOptions options) { - return locator(getByAltTextSelector(text, convertType(options, Locator.GetByAltTextOptions.class))); + public FrameImpl parentFrame() { + return parentFrame; } @Override - public Locator getByLabel(String text, GetByLabelOptions options) { - return locator(getByLabelSelector(text, convertType(options, Locator.GetByLabelOptions.class))); + public List childFrames() { + return new ArrayList<>(childFrames); } @Override - public Locator getByLabel(Pattern text, GetByLabelOptions options) { - return locator(getByLabelSelector(text, convertType(options, Locator.GetByLabelOptions.class))); + public boolean isDetached() { + return detached; } @Override - public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { - return locator(getByPlaceholderSelector(text, convertType(options, Locator.GetByPlaceholderOptions.class))); + public ElementHandleImpl addScriptTag(AddScriptTagOptions options) { + if (options == null) { + options = new AddScriptTagOptions(); + } + FrameAddScriptTagParams params = toProtocol(options, FrameAddScriptTagParams.class); + if (options.path != null) { + params.content = readFile(options.path); + params.content = ClientHelper.addSourceUrlToScript(params.content, options.path); + } + return channel.addScriptTag(params, NO_TIMEOUT).element; } @Override - public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { - return locator(getByPlaceholderSelector(text, convertType(options, Locator.GetByPlaceholderOptions.class))); + public ElementHandleImpl addStyleTag(AddStyleTagOptions options) { + if (options == null) { + options = new AddStyleTagOptions(); + } + FrameAddStyleTagParams params = toProtocol(options, FrameAddStyleTagParams.class); + if (options.path != null) { + params.content = readFile(options.path); + params.content += "/*# sourceURL=" + options.path.toString().replace("\n", "") + "*/"; + } + return channel.addStyleTag(params, NO_TIMEOUT).element; } @Override - public Locator getByRole(AriaRole role, GetByRoleOptions options) { - return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); + public void click(String selector, ClickOptions options) { + if (options == null) { + options = new ClickOptions(); + } + FrameClickParams params = toProtocol(options, FrameClickParams.class); + params.selector = selector; + channel.click(params, timeout(options.timeout)); } @Override - public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(testId, connection.playwright)); + public void dblclick(String selector, DblclickOptions options) { + if (options == null) { + options = new DblclickOptions(); + } + FrameDblclickParams params = toProtocol(options, FrameDblclickParams.class); + params.selector = selector; + channel.dblclick(params, timeout(options.timeout)); + } + + @Override + public void dragAndDrop(String source, String target, DragAndDropOptions options) { + if (options == null) { + options = new DragAndDropOptions(); + } + FrameDragAndDropParams params = toProtocol(options, FrameDragAndDropParams.class); + params.source = source; + params.target = target; + channel.dragAndDrop(params, timeout(options.timeout)); + } + + // java: the only caller, Locator.drop(), passes strict: true upstream; Locator.DropOptions has no strict field. + void drop(String selector, DropPayload payload, Locator.DropOptions options) { + if (options == null) { + options = new Locator.DropOptions(); + } + FrameDropParams params = toProtocol(options, FrameDropParams.class); + params.selector = selector; + params.strict = true; + if (payload.files != null) { + ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(payload.files, page().context()); + if (converted.localDirectory != null || converted.directoryStream != null) { + throw new PlaywrightException("Dropping a directory is not supported — pass individual files."); + } + if (converted.payloads != null) { + params.payloads = new ArrayList<>(); + for (ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads file : converted.payloads) { + FrameDropParams.FrameDropParamsPayloads item = new FrameDropParams.FrameDropParamsPayloads(); + item.name = file.name; + item.mimeType = file.mimeType; + item.buffer = file.buffer; + params.payloads.add(item); + } + } + params.localPaths = converted.localPaths; + params.streams = converted.streams; + } + if (payload.data != null) { + params.data = new ArrayList<>(); + for (Map.Entry entry : payload.data.entrySet()) { + FrameDropParams.FrameDropParamsData item = new FrameDropParams.FrameDropParamsData(); + item.mimeType = entry.getKey(); + item.value = entry.getValue(); + params.data.add(item); + } + } + channel.drop(params, timeout(options.timeout)); + } + + @Override + public void tap(String selector, TapOptions options) { + if (options == null) { + options = new TapOptions(); + } + FrameTapParams params = toProtocol(options, FrameTapParams.class); + params.selector = selector; + channel.tap(params, timeout(options.timeout)); + } + + @Override + public void fill(String selector, String value, FillOptions options) { + if (options == null) { + options = new FillOptions(); + } + FrameFillParams params = toProtocol(options, FrameFillParams.class); + params.selector = selector; + params.value = value; + channel.fill(params, timeout(options.timeout)); + } + + void highlight(String selector, String style) { + FrameHighlightParams params = new FrameHighlightParams(); + params.selector = selector; + params.style = style; + channel.highlight(params, NO_TIMEOUT); + } + + void hideHighlight(String selector) { + FrameHideHighlightParams params = new FrameHideHighlightParams(); + params.selector = selector; + channel.hideHighlight(params, NO_TIMEOUT); + } + + @Override + public LocatorImpl locator(String selector, LocatorOptions options) { + return new LocatorImpl(this, selector, convertType(options, Locator.LocatorOptions.class)); + } + + // java: testIdAttributeName() of locator.ts is a field of SelectorsImpl of the Playwright instance. + @Override + public Locator getByTestId(String testId) { + return locator(getByTestIdSelector(LocatorImpl.testIdAttributeName(connection.playwright.selectors), testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, connection.playwright)); + return locator(getByTestIdSelector(LocatorImpl.testIdAttributeName(connection.playwright.selectors), testId)); + } + + @Override + public Locator getByAltText(String text, GetByAltTextOptions options) { + return locator(getByAltTextSelector(text, convertType(options, Locator.GetByAltTextOptions.class))); + } + + @Override + public Locator getByAltText(Pattern text, GetByAltTextOptions options) { + return locator(getByAltTextSelector(text, convertType(options, Locator.GetByAltTextOptions.class))); + } + + @Override + public Locator getByLabel(String text, GetByLabelOptions options) { + return locator(getByLabelSelector(text, convertType(options, Locator.GetByLabelOptions.class))); + } + + @Override + public Locator getByLabel(Pattern text, GetByLabelOptions options) { + return locator(getByLabelSelector(text, convertType(options, Locator.GetByLabelOptions.class))); + } + + @Override + public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { + return locator(getByPlaceholderSelector(text, convertType(options, Locator.GetByPlaceholderOptions.class))); + } + + @Override + public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { + return locator(getByPlaceholderSelector(text, convertType(options, Locator.GetByPlaceholderOptions.class))); } @Override @@ -383,236 +609,164 @@ public Locator getByTitle(Pattern text, GetByTitleOptions options) { return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); } - String getAttributeImpl(String selector, String name, GetAttributeOptions options) { - if (options == null) { - options = new GetAttributeOptions(); - } - FrameGetAttributeParams params = toProtocol(options, FrameGetAttributeParams.class); - params.selector = selector; - params.name = name; - FrameGetAttributeResult result = channel.getAttribute(params, timeout(options.timeout)); - return result.value; + @Override + public Locator getByRole(AriaRole role, GetByRoleOptions options) { + return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); } @Override - public ResponseImpl navigate(String url, NavigateOptions options) { - return navigateImpl(url, options); + public FrameLocatorImpl frameLocator(String selector) { + return new FrameLocatorImpl(this, selector == null ? ANY_FRAME_SELECTOR : selector); } - ResponseImpl navigateImpl(String url, NavigateOptions options) { + @Override + public void focus(String selector, FocusOptions options) { if (options == null) { - options = new NavigateOptions(); + options = new FocusOptions(); } - FrameGotoParams params = toProtocol(options, FrameGotoParams.class); - params.url = url; - return channel.goto_(params, navigationTimeout(options.timeout)).response; + FrameFocusParams params = toProtocol(options, FrameFocusParams.class); + params.selector = selector; + channel.focus(params, timeout(options.timeout)); } @Override - public void hover(String selector, HoverOptions options) { - hoverImpl(selector, options); - } - - void hoverImpl(String selector, HoverOptions options) { + public String textContent(String selector, TextContentOptions options) { if (options == null) { - options = new HoverOptions(); + options = new TextContentOptions(); } - FrameHoverParams params = toProtocol(options, FrameHoverParams.class); + FrameTextContentParams params = toProtocol(options, FrameTextContentParams.class); params.selector = selector; - channel.hover(params, timeout(options.timeout)); + return channel.textContent(params, timeout(options.timeout)).value; } @Override - public void dragAndDrop(String source, String target, DragAndDropOptions options) { - dragAndDropImpl(source, target, options, null); - } - - void dragAndDropImpl(String source, String target, DragAndDropOptions options, Integer steps) { + public String innerText(String selector, InnerTextOptions options) { if (options == null) { - options = new DragAndDropOptions(); - } - FrameDragAndDropParams params = toProtocol(options, FrameDragAndDropParams.class); - params.source = source; - params.target = target; - if (steps != null) { - params.steps = steps; + options = new InnerTextOptions(); } - channel.dragAndDrop(params, timeout(options.timeout)); + FrameInnerTextParams params = toProtocol(options, FrameInnerTextParams.class); + params.selector = selector; + return channel.innerText(params, timeout(options.timeout)).value; } @Override public String innerHTML(String selector, InnerHTMLOptions options) { - return innerHTMLImpl(selector, options); - } - - String innerHTMLImpl(String selector, InnerHTMLOptions options) { if (options == null) { options = new InnerHTMLOptions(); } FrameInnerHTMLParams params = toProtocol(options, FrameInnerHTMLParams.class); params.selector = selector; - FrameInnerHTMLResult result = channel.innerHTML(params, timeout(options.timeout)); - return result.value; + return channel.innerHTML(params, timeout(options.timeout)).value; } @Override - public String innerText(String selector, InnerTextOptions options) { - return innerTextImpl(selector, options); - } - - String innerTextImpl(String selector, InnerTextOptions options) { + public String getAttribute(String selector, String name, GetAttributeOptions options) { if (options == null) { - options = new InnerTextOptions(); + options = new GetAttributeOptions(); } - FrameInnerTextParams params = toProtocol(options, FrameInnerTextParams.class); + FrameGetAttributeParams params = toProtocol(options, FrameGetAttributeParams.class); params.selector = selector; - FrameInnerTextResult result = channel.innerText(params, timeout(options.timeout)); - return result.value; + params.name = name; + return channel.getAttribute(params, timeout(options.timeout)).value; } @Override public String inputValue(String selector, InputValueOptions options) { - return inputValueImpl(selector, options); - } - - String inputValueImpl(String selector, InputValueOptions options) { if (options == null) { options = new InputValueOptions(); } FrameInputValueParams params = toProtocol(options, FrameInputValueParams.class); params.selector = selector; - FrameInputValueResult result = channel.inputValue(params, timeout(options.timeout)); - return result.value; + return channel.inputValue(params, timeout(options.timeout)).value; } @Override public boolean isChecked(String selector, IsCheckedOptions options) { - return isCheckedImpl(selector, options); - } - - boolean isCheckedImpl(String selector, IsCheckedOptions options) { if (options == null) { options = new IsCheckedOptions(); } FrameIsCheckedParams params = toProtocol(options, FrameIsCheckedParams.class); params.selector = selector; - FrameIsCheckedResult result = channel.isChecked(params, timeout(options.timeout)); - return result.value; - } - - @Override - public boolean isDetached() { - return isDetached; + return channel.isChecked(params, timeout(options.timeout)).value; } @Override public boolean isDisabled(String selector, IsDisabledOptions options) { - return isDisabledImpl(selector, options); - } - - boolean isDisabledImpl(String selector, IsDisabledOptions options) { if (options == null) { options = new IsDisabledOptions(); } FrameIsDisabledParams params = toProtocol(options, FrameIsDisabledParams.class); params.selector = selector; - FrameIsDisabledResult result = channel.isDisabled(params, timeout(options.timeout)); - return result.value; + return channel.isDisabled(params, timeout(options.timeout)).value; } @Override public boolean isEditable(String selector, IsEditableOptions options) { - return isEditableImpl(selector, options); - } - - boolean isEditableImpl(String selector, IsEditableOptions options) { if (options == null) { options = new IsEditableOptions(); } FrameIsEditableParams params = toProtocol(options, FrameIsEditableParams.class); params.selector = selector; - FrameIsEditableResult result = channel.isEditable(params, timeout(options.timeout)); - return result.value; + return channel.isEditable(params, timeout(options.timeout)).value; } @Override public boolean isEnabled(String selector, IsEnabledOptions options) { - return isEnabledImpl(selector, options); - } - - boolean isEnabledImpl(String selector, IsEnabledOptions options) { if (options == null) { options = new IsEnabledOptions(); } FrameIsEnabledParams params = toProtocol(options, FrameIsEnabledParams.class); params.selector = selector; - FrameIsEnabledResult result = channel.isEnabled(params, timeout(options.timeout)); - return result.value; + return channel.isEnabled(params, timeout(options.timeout)).value; } @Override public boolean isHidden(String selector, IsHiddenOptions options) { - return isHiddenImpl(selector, options); - } - - boolean isHiddenImpl(String selector, IsHiddenOptions options) { - if (options == null) { - options = new IsHiddenOptions(); - } FrameIsHiddenParams params = toProtocol(options, FrameIsHiddenParams.class); params.selector = selector; - FrameIsHiddenResult result = channel.isHidden(params, timeout(options.timeout)); - return result.value; + return channel.isHidden(params, NO_TIMEOUT).value; } @Override public boolean isVisible(String selector, IsVisibleOptions options) { - return isVisibleImpl(selector, options); + FrameIsVisibleParams params = toProtocol(options, FrameIsVisibleParams.class); + params.selector = selector; + return channel.isVisible(params, NO_TIMEOUT).value; } @Override - public Locator locator(String selector, LocatorOptions options) { - return new LocatorImpl(this, selector, convertType(options, Locator.LocatorOptions.class)); - } - - boolean isVisibleImpl(String selector, IsVisibleOptions options) { + public void hover(String selector, HoverOptions options) { if (options == null) { - options = new IsVisibleOptions(); + options = new HoverOptions(); } - FrameIsVisibleParams params = toProtocol(options, FrameIsVisibleParams.class); + FrameHoverParams params = toProtocol(options, FrameHoverParams.class); params.selector = selector; - FrameIsVisibleResult result = channel.isVisible(params, timeout(options.timeout)); - return result.value; + channel.hover(params, timeout(options.timeout)); } @Override - public String name() { - return name; + public List selectOption(String selector, String values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); } @Override - public PageImpl page() { - return page; + public List selectOption(String selector, ElementHandle values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); } @Override - public Frame parentFrame() { - return parentFrame; + public List selectOption(String selector, String[] values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); } @Override - public void press(String selector, String key, PressOptions options) { - pressImpl(selector, key, options); + public List selectOption(String selector, SelectOption values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); } - void pressImpl(String selector, String key, PressOptions options) { - if (options == null) { - options = new PressOptions(); - } - FramePressParams params = toProtocol(options, FramePressParams.class); - params.selector = selector; - params.key = key; - channel.press(params, timeout(options.timeout)); + @Override + public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); } @Override @@ -620,95 +774,31 @@ public List selectOption(String selector, SelectOption[] values, SelectO return selectOptionImpl(selector, values, options); } - List selectOptionImpl(String selector, SelectOption[] values, SelectOptionOptions options) { + private List selectOptionImpl(String selector, Object values, SelectOptionOptions options) { if (options == null) { options = new SelectOptionOptions(); } + ElementHandleSelectOptionParams converted = ElementHandleImpl.convertSelectOptionValues(values); FrameSelectOptionParams params = toProtocol(options, FrameSelectOptionParams.class); params.selector = selector; - if (values != null) { - Utils.assertNoNullItems(values); + params.elements = converted.elements; + if (converted.options != null) { params.options = new ArrayList<>(); - for (SelectOption value : values) { + for (ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions value : converted.options) { FrameSelectOptionParams.FrameSelectOptionParamsOptions option = new FrameSelectOptionParams.FrameSelectOptionParamsOptions(); + option.valueOrLabel = value.valueOrLabel; option.value = value.value; option.label = value.label; option.index = value.index; params.options.add(option); } } - return selectOption(params, options.timeout); - } - - List selectOptionImpl(String selector, String[] values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - FrameSelectOptionParams params = toProtocol(options, FrameSelectOptionParams.class); - params.selector = selector; - if (values != null) { - Utils.assertNoNullItems(values); - params.options = new ArrayList<>(); - for (String value : values) { - FrameSelectOptionParams.FrameSelectOptionParamsOptions option = new FrameSelectOptionParams.FrameSelectOptionParamsOptions(); - option.valueOrLabel = value; - params.options.add(option); - } - } - return selectOption(params, options.timeout); - } - - @Override - public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { - return selectOptionImpl(selector, values, options); - } - - List selectOptionImpl(String selector, ElementHandle[] values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - FrameSelectOptionParams params = toProtocol(options, FrameSelectOptionParams.class); - params.selector = selector; - if (values != null) { - Utils.assertNoNullItems(values); - params.elements = new ArrayList<>(); - for (ElementHandle handle : values) { - params.elements.add((ElementHandleImpl) handle); - } - } - return selectOption(params, options.timeout); - } - - private List selectOption(FrameSelectOptionParams params, Double timeout) { - return channel.selectOption(params, timeout(timeout)).values; - } - - @Override - public void setChecked(String selector, boolean checked, SetCheckedOptions options) { - setCheckedImpl(selector, checked, options); - } - - void setCheckedImpl(String selector, boolean checked, SetCheckedOptions options) { - if (checked) { - check(selector, convertType(options, CheckOptions.class)); - } else { - uncheck(selector, convertType(options, UncheckOptions.class)); - } - } - - @Override - public void setContent(String html, SetContentOptions options) { - if (options == null) { - options = new SetContentOptions(); - } - FrameSetContentParams params = toProtocol(options, FrameSetContentParams.class); - params.html = html; - channel.setContent(params, navigationTimeout(options.timeout)); + return channel.selectOption(params, timeout(options.timeout)).values; } @Override public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { - setInputFiles(selector, new Path[] {files}, options); + setInputFilesImpl(selector, files, options); } @Override @@ -716,26 +806,9 @@ public void setInputFiles(String selector, Path[] files, SetInputFilesOptions op setInputFilesImpl(selector, files, options); } - void setInputFilesImpl(String selector, Path[] files, SetInputFilesOptions options) { - if (options == null) { - options = new SetInputFilesOptions(); - } - FrameSetInputFilesParams params = toProtocol(options, FrameSetInputFilesParams.class); - Utils.UploadParams upload = addFilePathUploadParams(files, page.context()); - if (upload.emptyPayloads) { - params.payloads = new ArrayList<>(); - } - params.localDirectory = upload.localDirectory; - params.directoryStream = upload.directoryStream; - params.localPaths = upload.localPaths; - params.streams = upload.streams; - params.selector = selector; - channel.setInputFiles(params, timeout(options.timeout)); - } - @Override public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { - setInputFiles(selector, new FilePayload[]{files}, options); + setInputFilesImpl(selector, files, options); } @Override @@ -743,58 +816,60 @@ public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOpt setInputFilesImpl(selector, files, options); } - void setInputFilesImpl(String selector, FilePayload[] files, SetInputFilesOptions options) { - checkFilePayloadSize(files); + private void setInputFilesImpl(String selector, Object files, SetInputFilesOptions options) { if (options == null) { options = new SetInputFilesOptions(); } + ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(files, page().context()); FrameSetInputFilesParams params = toProtocol(options, FrameSetInputFilesParams.class); params.selector = selector; - params.payloads = new ArrayList<>(); - for (FilePayload file : files) { - FrameSetInputFilesParams.FrameSetInputFilesParamsPayloads payload = new FrameSetInputFilesParams.FrameSetInputFilesParamsPayloads(); - payload.name = file.name; - payload.mimeType = file.mimeType; - payload.buffer = file.buffer; - params.payloads.add(payload); + if (converted.payloads != null) { + params.payloads = new ArrayList<>(); + for (ElementHandleSetInputFilesParams.ElementHandleSetInputFilesParamsPayloads file : converted.payloads) { + FrameSetInputFilesParams.FrameSetInputFilesParamsPayloads payload = new FrameSetInputFilesParams.FrameSetInputFilesParamsPayloads(); + payload.name = file.name; + payload.mimeType = file.mimeType; + payload.buffer = file.buffer; + params.payloads.add(payload); + } } + params.localDirectory = converted.localDirectory; + params.directoryStream = converted.directoryStream; + params.localPaths = converted.localPaths; + params.streams = converted.streams; channel.setInputFiles(params, timeout(options.timeout)); } @Override - public void tap(String selector, TapOptions options) { + public void type(String selector, String text, TypeOptions options) { if (options == null) { - options = new TapOptions(); + options = new TypeOptions(); } - FrameTapParams params = toProtocol(options, FrameTapParams.class); + FrameTypeParams params = toProtocol(options, FrameTypeParams.class); params.selector = selector; - channel.tap(params, timeout(options.timeout)); + params.text = text; + channel.type(params, timeout(options.timeout)); } @Override - public String textContent(String selector, TextContentOptions options) { + public void press(String selector, String key, PressOptions options) { if (options == null) { - options = new TextContentOptions(); + options = new PressOptions(); } - FrameTextContentParams params = toProtocol(options, FrameTextContentParams.class); + FramePressParams params = toProtocol(options, FramePressParams.class); params.selector = selector; - return channel.textContent(params, timeout(options.timeout)).value; - } - - @Override - public String title() { - return channel.title(NO_TIMEOUT).value; + params.key = key; + channel.press(params, timeout(options.timeout)); } @Override - public void type(String selector, String text, TypeOptions options) { + public void check(String selector, CheckOptions options) { if (options == null) { - options = new TypeOptions(); + options = new CheckOptions(); } - FrameTypeParams params = toProtocol(options, FrameTypeParams.class); + FrameCheckParams params = toProtocol(options, FrameCheckParams.class); params.selector = selector; - params.text = text; - channel.type(params, timeout(options.timeout)); + channel.check(params, timeout(options.timeout)); } @Override @@ -808,145 +883,12 @@ public void uncheck(String selector, UncheckOptions options) { } @Override - public String url() { - return url; - } - - @Override - public JSHandle waitForFunction(String pageFunction, Object arg, WaitForFunctionOptions options) { - if (options == null) { - options = new WaitForFunctionOptions(); - } - FrameWaitForFunctionParams params = toProtocol(options, FrameWaitForFunctionParams.class); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return channel.waitForFunction(params, timeout(options.timeout)).handle; - } - - private Waiter setupNavigationWaiter(Double timeout) { - Waiter waiter = new Waiter(page, ""); - if (page.isClosed()) { - waiter.rejectImmediately(page.closeErrorWithReason()); - } - waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); - waiter.rejectOnEvent(page, Events.Page.CRASH, () -> new PlaywrightException("Navigation failed because page crashed!")); - waiter.rejectOnEvent(page, Events.Page.FRAME_DETACHED, () -> new PlaywrightException("Navigating frame was detached!"), frame -> frame == this); - double timeoutMs = page.timeoutSettings.navigationTimeout(timeout); - waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded."); - return waiter; - } - - @Override - public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) { - if (options == null) { - options = new WaitForNavigationOptions(); - } - UrlMatcher matcher = UrlMatcher.forOneOf(page.context().baseUrl(), options.url, this.connection.localUtils(), false); - return waitForNavigation(matcher, options.url instanceof String ? (String) options.url : null, options.waitUntil, options.timeout, code); - } - - private Response waitForNavigation(UrlMatcher matcher, String url, WaitUntilState waitUntil, Double timeout, Runnable code) { - if (waitUntil == null) { - waitUntil = LOAD; - } - final WaitUntilState expectedState = waitUntil; - // java: the code runs outside of the api zone, so that its calls are not hidden as internal. - Waiter waiter = withTitle("Wait for navigation", () -> setupNavigationWaiter(timeout)); - - String toUrl = url != null ? " to \"" + url + "\"" : ""; - waiter.log("waiting for navigation" + toUrl + " until \"" + loadStateName(waitUntil) + "\""); - - JsonObject navigatedEvent = waiter.waitForEvent(this, Events.Frame.NAVIGATED, event -> { - // Any failed navigation results in a rejection. - if (event.has("error")) { - return true; - } - String eventUrl = event.get("url").getAsString(); - waiter.log(" navigated to \"" + eventUrl + "\""); - return matcher.test(eventUrl); - }, code); - if (navigatedEvent.has("error")) { - WaitableResult failure = new WaitableResult<>(); - failure.completeExceptionally(new PlaywrightException(navigatedEvent.get("error").getAsString())); - waiter.waitForPromise(failure); - } - - if (!loadStates.contains(expectedState)) { - waiter.waitForPromise(waiter.waitForEvent(this, Events.Frame.LOAD_STATE, s -> { - waiter.log(" \"" + loadStateName(s) + "\" event fired"); - return s == expectedState; - })); - } - - RequestImpl request = null; - if (navigatedEvent.has("newDocument")) { - JsonObject jsonReq = navigatedEvent.getAsJsonObject("newDocument").getAsJsonObject("request"); - if (jsonReq != null) { - request = connection.getExistingObject(jsonReq.get("guid").getAsString()); - } - } - Response response = null; - if (request != null) { - WaitableResult result = new WaitableResult<>(); - try { - result.complete(request.finalRequest().response()); - } catch (RuntimeException e) { - result.completeExceptionally(e); - } - response = waiter.waitForPromise(result); - } - waiter.dispose(); - return response; - } - - @Override - public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { - if (state == null) { - state = LoadState.LOAD; - } - waitForLoadState(convertType(state, WaitUntilState.class), options == null ? null : options.timeout); - } - - private void waitForLoadState(WaitUntilState state, Double timeout) { - if (state == null) { - state = LOAD; - } - final WaitUntilState expectedState = state; - withTitle("Wait for load state \"" + loadStateName(state) + "\"", () -> { - Waiter waiter = setupNavigationWaiter(timeout); - try { - if (loadStates.contains(expectedState)) { - waiter.log(" not waiting, \"" + loadStateName(expectedState) + "\" event already fired"); - waiter.throwIfImmediatelyRejected(); - } else { - waiter.waitForPromise(waiter.waitForEvent(this, Events.Frame.LOAD_STATE, s -> { - waiter.log(" \"" + loadStateName(s) + "\" event fired"); - return s == expectedState; - })); - } - } finally { - waiter.dispose(); - } - }); - } - - private static String loadStateName(WaitUntilState state) { - return state.name().toLowerCase(); - } - - @Override - public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { - return waitForSelectorImpl(selector, options, false); - } - - ElementHandle waitForSelectorImpl(String selector, WaitForSelectorOptions options, boolean omitReturnValue) { - if (options == null) { - options = new WaitForSelectorOptions(); + public void setChecked(String selector, boolean checked, SetCheckedOptions options) { + if (checked) { + check(selector, convertType(options, CheckOptions.class)); + } else { + uncheck(selector, convertType(options, UncheckOptions.class)); } - FrameWaitForSelectorParams params = toProtocol(options, FrameWaitForSelectorParams.class); - params.selector = selector; - params.omitReturnValue = omitReturnValue; - return channel.waitForSelector(params, timeout(options.timeout)).element; } @Override @@ -957,132 +899,72 @@ public void waitForTimeout(double timeout) { } @Override - public void waitForURL(String url, WaitForURLOptions options) { - waitForURL(UrlMatcher.forGlob(page.context().baseUrl(), url, this.connection.localUtils(), false), url, options); - } - - @Override - public void waitForURL(Pattern url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), null, options); - } - - @Override - public void waitForURL(Predicate url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), null, options); - } - - private void waitForURL(UrlMatcher matcher, String url, WaitForURLOptions options) { + public JSHandle waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { if (options == null) { - options = new WaitForURLOptions(); - } - if (matcher.test(url())) { - waitForLoadState(options.waitUntil, options.timeout); - return; + options = new WaitForFunctionOptions(); } - waitForNavigation(matcher, url, options.waitUntil, options.timeout, () -> {}); + // java: the options have pollingInterval in place of polling, there is no 'raf' string to check. + FrameWaitForFunctionParams params = toProtocol(options, FrameWaitForFunctionParams.class); + params.expression = expression; + params.arg = serializeArgument(arg); + return channel.waitForFunction(params, timeout(options.timeout)).handle; } - int queryCount(String selector) { - FrameQueryCountParams params = new FrameQueryCountParams(); - params.selector = selector; - return channel.queryCount(params, NO_TIMEOUT).value; + @Override + public String title() { + return channel.title(NO_TIMEOUT).value; } - void dropImpl(String selector, DropPayload payload, com.microsoft.playwright.Locator.DropOptions options) { - if (options == null) { - options = new com.microsoft.playwright.Locator.DropOptions(); - } - FrameDropParams params = toProtocol(options, FrameDropParams.class); - params.selector = selector; - params.strict = true; - if (payload != null) { - if (payload.files != null) { - if (payload.files instanceof Path) { - addDropFilePaths(new Path[] { (Path) payload.files }, params); - } else if (payload.files instanceof Path[]) { - addDropFilePaths((Path[]) payload.files, params); - } else if (payload.files instanceof com.microsoft.playwright.options.FilePayload) { - addDropPayloads(new com.microsoft.playwright.options.FilePayload[] { (com.microsoft.playwright.options.FilePayload) payload.files }, params); - } else if (payload.files instanceof com.microsoft.playwright.options.FilePayload[]) { - addDropPayloads((com.microsoft.playwright.options.FilePayload[]) payload.files, params); - } else { - throw new com.microsoft.playwright.PlaywrightException("Unsupported files type: " + payload.files.getClass()); - } - } - if (payload.data != null) { - params.data = new ArrayList<>(); - for (java.util.Map.Entry entry : payload.data.entrySet()) { - FrameDropParams.FrameDropParamsData e = new FrameDropParams.FrameDropParamsData(); - e.mimeType = entry.getKey(); - e.value = entry.getValue(); - params.data.add(e); - } + // java: the title is a parameter, the options are the seed FrameExpectOptions, the result the seed FrameExpectResult. + FrameExpectResult expect(String expression, FrameExpectOptions options, String title) { + return wrapApiCall(() -> { + FrameExpectParams params = toProtocol(this, options, FrameExpectParams.class); + params.expression = expression; + params.isNot = options.isNot; + // java: expectedValue is serialized by the assertion classes. + FrameExpectResult result = new FrameExpectResult(); + try { + channel.expect(params, options.timeout); + result.matches = !params.isNot; + return result; + } catch (ServerErrorWithDetails e) { + // java: no AbortSignal, so no AbortError branch; only errors with details are expect mismatches. + FrameExpectErrorDetails details = gson().fromJson(e.errorDetails(), FrameExpectErrorDetails.class); + result.matches = params.isNot; + // java: AssertionsBase parses the received value, FrameExpectResult has no timedOut. + result.received = details.received; + result.log = e.log(); + result.errorMessage = details.customErrorMessage != null ? "Error: " + details.customErrorMessage : null; + return result; } - } - channel.drop(params, timeout(options.timeout)); + }, title, false); } - private void addDropFilePaths(Path[] files, FrameDropParams params) { - Utils.UploadParams upload = addFilePathUploadParams(files, page.context()); - if (upload.emptyPayloads) { - params.payloads = new ArrayList<>(); + static String verifyLoadState(String name, String waitUntil) { + if ("networkidle0".equals(waitUntil)) { + waitUntil = "networkidle"; } - params.localPaths = upload.localPaths; - params.streams = upload.streams; - } - - private void addDropPayloads(com.microsoft.playwright.options.FilePayload[] files, FrameDropParams params) { - checkFilePayloadSize(files); - params.payloads = new ArrayList<>(); - for (com.microsoft.playwright.options.FilePayload file : files) { - FrameDropParams.FrameDropParamsPayloads payload = new FrameDropParams.FrameDropParamsPayloads(); - payload.name = file.name; - payload.mimeType = file.mimeType; - payload.buffer = file.buffer; - params.payloads.add(payload); + if (!kLifecycleEvents.contains(waitUntil)) { + throw new PlaywrightException(name + ": expected one of (load|domcontentloaded|networkidle|commit)"); } + return waitUntil; } - void highlightImpl(String selector, String style) { - FrameHighlightParams params = new FrameHighlightParams(); - params.selector = selector; - params.style = style; - channel.highlight(params, NO_TIMEOUT); - } + // java: members with no upstream counterpart: kAnyFrameSelector of isomorphic/selectorParser.ts, kLifecycleEvents + // of types.ts, the enum to lifecycle event conversion, a file reader and the webmcp() accessor of the webmcp field. + static final String ANY_FRAME_SELECTOR = "internal:control=any-frame"; - void hideHighlightImpl(String selector) { - FrameHideHighlightParams params = new FrameHideHighlightParams(); - params.selector = selector; - channel.hideHighlight(params, NO_TIMEOUT); + private static final Set kLifecycleEvents = new LinkedHashSet<>(Arrays.asList("load", "domcontentloaded", "networkidle", "commit")); + + private static String lifecycleEvent(WaitUntilState state) { + return state.name().toLowerCase(Locale.ROOT); } - protected void handleEvent(String event, JsonObject params) { - if ("loadstate".equals(event)) { - JsonElement add = params.get("add"); - if (add != null) { - WaitUntilState state = loadStateFromProtocol(add.getAsString()); - loadStates.add(state); - if (parentFrame == null && page != null) { - if (state == LOAD) { - page.emit(Events.Page.LOAD, page); - page.browserContext.notifyPageLoad(page); - } else if (state == DOMCONTENTLOADED) { - page.emit(Events.Page.DOM_CONTENT_LOADED, page); - } - } - emit(Events.Frame.LOAD_STATE, state); - } - JsonElement remove = params.get("remove"); - if (remove != null) { - loadStates.remove(loadStateFromProtocol(remove.getAsString())); - } - } else if ("navigated".equals(event)) { - url = params.get("url").getAsString(); - name = params.get("name").getAsString(); - if (!params.has("error") && page != null) { - page.frameNavigated(this); - } - emit(Events.Frame.NAVIGATED, params); + private static String readFile(Path path) { + try { + return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new PlaywrightException("Failed to read from file", e); } } @@ -1090,39 +972,4 @@ protected void handleEvent(String event, JsonObject params) { public WebMCP webmcp() { return webmcp; } - - protected double timeout(Double timeout) { - if (page != null) { - return page.timeoutSettings.timeout(timeout); - } - return new TimeoutSettings().timeout(timeout); - } - - protected double navigationTimeout(Double timeout) { - if (page != null) { - return page.timeoutSettings.navigationTimeout(timeout); - } - return new TimeoutSettings().navigationTimeout(timeout); - } - - FrameExpectResult expect(String expression, FrameExpectOptions options, String title) { - return withTitle(title, () -> expect(expression, options)); - } - - FrameExpectResult expect(String expression, FrameExpectOptions options) { - FrameExpectParams params = toProtocol(this, options, FrameExpectParams.class); - params.expression = expression; - FrameExpectResult result = new FrameExpectResult(); - try { - channel.expect(params, options.timeout); - result.matches = !options.isNot; - } catch (ServerErrorWithDetails e) { - FrameExpectErrorDetails details = gson().fromJson(e.errorDetails(), FrameExpectErrorDetails.class); - result.matches = options.isNot; - result.received = details.received; - result.errorMessage = details.customErrorMessage == null ? null : "Error: " + details.customErrorMessage; - result.log = e.log(); - } - return result; - } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java index f5f687d64..5f8f057e8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of locator.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.FrameLocator; @@ -23,13 +24,11 @@ import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.LocatorUtils.*; +import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*; +import static com.microsoft.playwright.impl.LocatorImpl.testIdAttributeName; import static com.microsoft.playwright.impl.Utils.convertType; class FrameLocatorImpl implements FrameLocator { - // Created by page.frameLocator() / frame.frameLocator() without a selector: searches in any frame of the subtree. - static final String ANY_FRAME_SELECTOR = "internal:control=any-frame"; - private final FrameImpl frame; private final String frameSelector; @@ -39,27 +38,31 @@ class FrameLocatorImpl implements FrameLocator { } private String childSelector(String selector) { - if (ANY_FRAME_SELECTOR.equals(frameSelector)) { + if (FrameImpl.ANY_FRAME_SELECTOR.equals(frameSelector)) return frameSelector + " >> " + selector; - } return frameSelector + " >> internal:control=enter-frame >> " + selector; } - private String nthSelector(int nth) { - if (ANY_FRAME_SELECTOR.equals(frameSelector)) { - throw new PlaywrightException("Selecting the nth frame is not allowed on frameLocator()."); - } - return frameSelector + " >> nth=" + nth; + @Override + public Locator locator(String selectorOrLocator, LocatorOptions options) { + return new LocatorImpl(frame, childSelector(selectorOrLocator), convertType(options, Locator.LocatorOptions.class)); } @Override - public FrameLocator first() { - return new FrameLocatorImpl(frame, nthSelector(0)); + public Locator locator(Locator selectorOrLocator, LocatorOptions options) { + if (((LocatorImpl) selectorOrLocator).frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, childSelector(((LocatorImpl) selectorOrLocator).selector), convertType(options, Locator.LocatorOptions.class)); } @Override - public FrameLocatorImpl frameLocator(String selector) { - return new FrameLocatorImpl(frame, childSelector(selector)); + public Locator getByTestId(String testId) { + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); + } + + @Override + public Locator getByTestId(Pattern testId) { + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override @@ -92,21 +95,6 @@ public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { return locator(getByPlaceholderSelector(text, convertType(options, Locator.GetByPlaceholderOptions.class))); } - @Override - public Locator getByRole(AriaRole role, GetByRoleOptions options) { - return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); - } - - @Override - public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); - } - - @Override - public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); - } - @Override public Locator getByText(String text, GetByTextOptions options) { return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); @@ -128,31 +116,38 @@ public Locator getByTitle(Pattern text, GetByTitleOptions options) { } @Override - public FrameLocator last() { - return new FrameLocatorImpl(frame, nthSelector(-1)); + public Locator getByRole(AriaRole role, GetByRoleOptions options) { + return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); } @Override - public Locator locator(String selector, LocatorOptions options) { - return new LocatorImpl(frame, childSelector(selector), convertType(options, Locator.LocatorOptions.class)); + public Locator owner() { + return new LocatorImpl(frame, frameSelector); } @Override - public Locator locator(Locator selectorOrLocator, LocatorOptions options) { - LocatorImpl other = (LocatorImpl) selectorOrLocator; - if (other.frame != frame) { - throw new PlaywrightException("Locators must belong to the same frame."); - } - return locator(other.selector, options); + public FrameLocator frameLocator(String selector) { + return new FrameLocatorImpl(frame, childSelector(selector)); + } + + private String nthSelector(String nth) { + if (FrameImpl.ANY_FRAME_SELECTOR.equals(frameSelector)) + throw new PlaywrightException("Selecting the nth frame is not allowed on frameLocator()."); + return frameSelector + " >> nth=" + nth; } @Override - public FrameLocator nth(int index) { - return new FrameLocatorImpl(frame, nthSelector(index)); + public FrameLocator first() { + return new FrameLocatorImpl(frame, nthSelector("0")); } @Override - public Locator owner() { - return new LocatorImpl(frame, frameSelector, null); + public FrameLocator last() { + return new FrameLocatorImpl(frame, nthSelector("-1")); + } + + @Override + public FrameLocator nth(int index) { + return new FrameLocatorImpl(frame, nthSelector(String.valueOf(index))); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/HARRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/HARRouter.java deleted file mode 100644 index 951117ca2..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/HARRouter.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonObject; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.Request; -import com.microsoft.playwright.Route; -import com.microsoft.playwright.options.HarNotFound; -import com.microsoft.playwright.options.HttpHeader; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static com.microsoft.playwright.impl.LoggingSupport.*; - -public class HARRouter { - private final LocalUtils localUtils; - private final HarNotFound defaultAction; - private final String harId; - - HARRouter(LocalUtils localUtils, Path harFile, HarNotFound defaultAction) { - this.localUtils = localUtils; - this.defaultAction = defaultAction; - - LocalUtilsHarOpenParams params = new LocalUtilsHarOpenParams(); - params.file = harFile.toString(); - LocalUtilsHarOpenResult result = localUtils.channel.harOpen(params, NO_TIMEOUT); - if (result.error != null) { - throw new PlaywrightException(result.error); - } - harId = result.harId; - } - - void handle(Route route) { - Request request = route.request(); - - LocalUtilsHarLookupParams params = new LocalUtilsHarLookupParams(); - params.harId = harId; - params.url = request.url(); - params.method = request.method(); - params.headers = new ArrayList<>(); - for (HttpHeader header : request.headersArray()) { - NameValue nv = new NameValue(); - nv.name = header.name; - nv.value = header.value; - params.headers.add(nv); - } - if (request.postDataBuffer() != null) { - params.postData = request.postDataBuffer(); - } - params.isNavigationRequest = request.isNavigationRequest(); - LocalUtilsHarLookupResult response = localUtils.channel.harLookup(params, NO_TIMEOUT); - - String action = response.action; - if ("redirect".equals(action)) { - String redirectURL = response.redirectURL; - logApiIfEnabled("HAR: " + route.request().url() + " redirected to " + redirectURL); - ((RouteImpl) route).redirectNavigationRequest(redirectURL); - return; - } - - if ("fulfill".equals(action)) { - int status = response.status; - // If the response status is -1, the request was canceled or stalled, so we just stall it here. - // See https://github.com/microsoft/playwright/issues/29311. - // TODO: it'd be better to abort such requests, but then we likely need to respect the timing, - // because the request might have been stalled for a long time until the very end of the - // test when HAR was recorded but we'd abort it immediately. - if (status == -1) { - return; - } - Map headers = mergeSetCookieHeaders(response.headers); - byte[] buffer = response.body; - route.fulfill(new Route.FulfillOptions() - .setStatus(status) - .setHeaders(headers) - .setBodyBytes(buffer)); - return; - } - - if ("error".equals(action)) { - logApiIfEnabled("HAR: " + response.message); - // Report the error, but fall through to the default handler. - } - - if (defaultAction == HarNotFound.FALLBACK) { - route.fallback(); - return; - } - - // By default abort not matching requests. - route.abort(); - } - - private static Map mergeSetCookieHeaders(List headersArray) { - Map result = new java.util.LinkedHashMap<>(); - for (NameValue pair : headersArray) { - String name = pair.name; - String value = pair.value; - if ("set-cookie".equalsIgnoreCase(name)) { - if (!result.containsKey("set-cookie")) { - result.put("set-cookie", value); - } else { - result.put("set-cookie", result.get("set-cookie") + "\n" + value); - } - } else { - result.put(name, value); - } - } - return result; - } - - void dispose() { - LocalUtilsHarCloseParams params = new LocalUtilsHarCloseParams(); - params.harId = harId; - localUtils.sendMessageAsync("harClose", params); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java new file mode 100644 index 000000000..194822126 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of harRouter.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.Request; +import com.microsoft.playwright.Route; +import com.microsoft.playwright.impl.protocol.LocalUtilsHarCloseParams; +import com.microsoft.playwright.impl.protocol.LocalUtilsHarLookupParams; +import com.microsoft.playwright.impl.protocol.LocalUtilsHarLookupResult; +import com.microsoft.playwright.impl.protocol.LocalUtilsHarOpenParams; +import com.microsoft.playwright.impl.protocol.LocalUtilsHarOpenResult; +import com.microsoft.playwright.impl.protocol.NameValue; +import com.microsoft.playwright.options.HarNotFound; +import com.microsoft.playwright.options.HttpHeader; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.LoggingSupport.logApiIfEnabled; + +class HarRouter { + private final LocalUtils localUtils; + private final String harId; + private final HarNotFound notFoundAction; + // java: options.urlMatch, a String or a Pattern; there is no baseURL option. + private final Object urlMatch; + + static HarRouter create(LocalUtils localUtils, String file, HarNotFound notFoundAction, Object urlMatch) { + LocalUtilsHarOpenParams params = new LocalUtilsHarOpenParams(); + params.file = file; + LocalUtilsHarOpenResult result = localUtils.harOpen(params); + if (result.error != null) { + throw new PlaywrightException(result.error); + } + return new HarRouter(localUtils, result.harId, notFoundAction, urlMatch); + } + + // java: the Java API passes the HAR file as a Path. + static HarRouter create(LocalUtils localUtils, Path file, HarNotFound notFoundAction, Object urlMatch) { + return create(localUtils, file.toString(), notFoundAction, urlMatch); + } + + private HarRouter(LocalUtils localUtils, String harId, HarNotFound notFoundAction, Object urlMatch) { + this.localUtils = localUtils; + this.harId = harId; + this.urlMatch = urlMatch; + this.notFoundAction = notFoundAction; + } + + private void handle(Route route) { + Request request = route.request(); + + LocalUtilsHarLookupParams params = new LocalUtilsHarLookupParams(); + params.harId = harId; + params.url = request.url(); + params.method = request.method(); + params.headers = toNameValues(request.headersArray()); + params.postData = request.postDataBuffer(); + params.isNavigationRequest = request.isNavigationRequest(); + LocalUtilsHarLookupResult response = localUtils.harLookup(params); + + if ("redirect".equals(response.action)) { + logApiIfEnabled("HAR: " + route.request().url() + " redirected to " + response.redirectURL); + ((RouteImpl) route).redirectNavigationRequest(response.redirectURL); + return; + } + + if ("fulfill".equals(response.action)) { + // If the response status is -1, the request was canceled or stalled, so we just stall it here. + // See https://github.com/microsoft/playwright/issues/29311. + // TODO: it'd be better to abort such requests, but then we likely need to respect the timing, + // because the request might have been stalled for a long time until the very end of the + // test when HAR was recorded but we'd abort it immediately. + if (response.status == -1) { + return; + } + + // route.fulfill does not support multiple set-cookie headers. We need to merge them into one. + Map transformedHeaders = new LinkedHashMap<>(); + for (NameValue header : response.headers) { + if (!"set-cookie".equals(header.name.toLowerCase())) { + // non-set-cookie header gets set as-is + transformedHeaders.put(header.name, header.value); + } else { + // first set-cookie header gets included as-is + if (!transformedHeaders.containsKey("set-cookie")) { + transformedHeaders.put("set-cookie", header.value); + } else { + // subsequent set-cookie headers get appended to existing header + transformedHeaders.put("set-cookie", transformedHeaders.get("set-cookie") + "\n" + header.value); + } + } + } + + route.fulfill(new Route.FulfillOptions() + .setStatus(response.status) + .setHeaders(transformedHeaders) + .setBodyBytes(response.body)); + return; + } + + if ("error".equals(response.action)) { + logApiIfEnabled("HAR: " + response.message); + } + // Report the error, but fall through to the default handler. + + if (notFoundAction == HarNotFound.ABORT) { + route.abort(); + return; + } + + route.fallback(); + } + + void addContextRoute(BrowserContext context) { + Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; + // java: route() has an overload per URLMatch type. + if (urlMatch instanceof Pattern) { + context.route((Pattern) urlMatch, route -> handle(route)); + } else { + context.route((String) urlMatch, route -> handle(route)); + } + } + + void addPageRoute(Page page) { + Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; + // java: route() has an overload per URLMatch type. + if (urlMatch instanceof Pattern) { + page.route((Pattern) urlMatch, route -> handle(route)); + } else { + page.route((String) urlMatch, route -> handle(route)); + } + } + + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + + void dispose() { + LocalUtilsHarCloseParams params = new LocalUtilsHarCloseParams(); + params.harId = harId; + try { + localUtils.harClose(params); + } catch (PlaywrightException e) { + } + } + + // java: the public HttpHeader list of Request.headersArray() as protocol headers. + private static List toNameValues(List headers) { + List result = new ArrayList<>(); + for (HttpHeader header : headers) { + NameValue nv = new NameValue(); + nv.name = header.name; + nv.value = header.value; + result.add(nv); + } + return result; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java index 67c0a5459..a7634af9c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java @@ -1,12 +1,12 @@ /* * Copyright (c) Microsoft Corporation. - *

+ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - *

+ * * http://www.apache.org/licenses/LICENSE-2.0 - *

+ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -14,73 +14,92 @@ * limitations under the License. */ +// Port of jsHandle.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.ElementHandle; import com.microsoft.playwright.JSHandle; +import com.microsoft.playwright.impl.protocol.*; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; -import static com.microsoft.playwright.impl.Serialization.*; +import static com.microsoft.playwright.impl.Serialization.assertEvaluateOptions; +import static com.microsoft.playwright.impl.Serialization.deserialize; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.Serialization.serializeArgumentWithCallbacks; +// java: the module-level serializeArgument, ExposeFunctionsOptions, EvaluateOptions, serializeArgumentWithCallbacks, +// parseResult and assertEvaluateOptions are in Serialization. public class JSHandleImpl extends ChannelOwner implements JSHandle { private String preview; final JSHandleChannel channel = new JSHandleChannel(this); - public JSHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - this.preview = initializer.get("preview").getAsString(); - } + // java: no from, generated results already hold the JSHandleImpl. - @Override - public ElementHandle asElement() { - return null; + JSHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + this.preview = connection.protocolGson().fromJson(initializer, JSHandleInitializer.class).preview; } + // java: upstream subscribes in the constructor with this._channel.on('previewUpdated', ...). @Override - public void dispose() { - try { - channel.dispose(NO_TIMEOUT); - } catch (TargetClosedError e) { + protected void handleEvent(String event, JsonObject params) { + if ("previewUpdated".equals(event)) { + preview = connection.protocolGson().fromJson(params, JSHandlePreviewUpdatedEvent.class).preview; } } @Override public Object evaluate(String pageFunction, Object arg) { + return evaluate(pageFunction, arg, null); + } + + // java: the public API has no evaluate options, so the options overload is package-private. + Object evaluate(String pageFunction, Object arg, Serialization.EvaluateOptions options) { + assertEvaluateOptions(options); + SerializedArgument serializedArg = options != null && options.exposeFunctions != null && options.exposeFunctions ? serializeArgumentWithCallbacks(this, (PageImpl) parentOfType("Page"), arg) : serializeArgument(arg); JSHandleEvaluateExpressionParams params = new JSHandleEvaluateExpressionParams(); params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializedArg; + JSHandleEvaluateExpressionResult result = channel.evaluateExpression(params, NO_TIMEOUT); + return deserialize(result.value); } @Override public JSHandle evaluateHandle(String pageFunction, Object arg) { - JSHandleEvaluateExpressionHandleParams params = new JSHandleEvaluateExpressionHandleParams(); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; + return evaluateHandle(pageFunction, arg, null); } - @Override - public Map getProperties() { - JSHandleGetPropertyListResult json = channel.getPropertyList(NO_TIMEOUT); - Map result = new HashMap<>(); - for (JSHandleGetPropertyListResult.JSHandleGetPropertyListResultProperties item : json.properties) { - result.put(item.name, item.value); - } - return result; + JSHandle evaluateHandle(String pageFunction, Object arg, Serialization.EvaluateOptions options) { + assertEvaluateOptions(options); + SerializedArgument serializedArg = options != null && options.exposeFunctions != null && options.exposeFunctions ? serializeArgumentWithCallbacks(this, (PageImpl) parentOfType("Page"), arg) : serializeArgument(arg); + JSHandleEvaluateExpressionHandleParams params = new JSHandleEvaluateExpressionHandleParams(); + params.expression = pageFunction; + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializedArg; + JSHandleEvaluateExpressionHandleResult result = channel.evaluateExpressionHandle(params, NO_TIMEOUT); + return result.handle; } @Override public JSHandle getProperty(String propertyName) { JSHandleGetPropertyParams params = new JSHandleGetPropertyParams(); params.name = propertyName; - return channel.getProperty(params, NO_TIMEOUT).handle; + JSHandleGetPropertyResult result = channel.getProperty(params, NO_TIMEOUT); + return result.handle; + } + + @Override + public Map getProperties() { + Map map = new LinkedHashMap<>(); + for (JSHandleGetPropertyListResult.JSHandleGetPropertyListResultProperties property : channel.getPropertyList(NO_TIMEOUT).properties) { + map.put(property.name, property.value); + } + return map; } @Override @@ -89,11 +108,19 @@ public Object jsonValue() { } @Override - void handleEvent(String event, JsonObject parameters) { - if ("previewUpdated".equals(event)) { - preview = parameters.get("preview").getAsString(); + public ElementHandle asElement() { + return null; + } + + // java: no [Symbol.asyncDispose]. + + @Override + public void dispose() { + try { + channel.dispose(NO_TIMEOUT); + } catch (TargetClosedError e) { + return; } - super.handleEvent(event, parameters); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java index a204a45a8..0986fc05a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of jsonPipe.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -27,19 +28,26 @@ import java.util.Queue; import java.util.function.Consumer; -import static com.microsoft.playwright.impl.Serialization.gson; - public class JsonPipe extends ChannelOwner implements Transport { - private final Queue incoming = new LinkedList<>(); - private boolean isClosed; - private String closeReason = "Browser has been closed"; - final JsonPipeChannel channel = new JsonPipeChannel(this); + // java: from is not ported, generated results already hold the impl object. + JsonPipe(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } + JsonPipeChannel channel() { + return channel; + } + + // java: the members below have no counterpart in jsonPipe.ts, they are JsonPipeTransport of connect.ts in the + // order send, onMessage (poll), onClose, close; the pipe is this object and the _owner is not kept, its connect + // is in Connect.connectToEndpoint. + private final Queue incoming = new LinkedList<>(); + private boolean isClosed; + private String closeReason = "Browser has been closed"; + @Override public void send(JsonObject message) { checkIfClosed(); @@ -77,6 +85,10 @@ public void dispose() { }); } + void onClose(Consumer handler) { + on(Events.JsonPipe.CLOSE, handler); + } + @Override public void close() throws IOException { if (!isClosed) { @@ -84,19 +96,6 @@ public void close() throws IOException { } } - String closeReason() { - return closeReason; - } - - void onClose(Consumer handler) { - on(Events.JsonPipe.CLOSE, handler); - } - - void offClose(Consumer handler) { - off(Events.JsonPipe.CLOSE, handler); - } - - @Override protected void handleEvent(String event, JsonObject params) { if ("message".equals(event)) { @@ -113,6 +112,10 @@ protected void handleEvent(String event, JsonObject params) { } } + String closeReason() { + return closeReason; + } + private void checkIfClosed() { if (isClosed) { throw new PlaywrightException(closeReason); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/KeyboardImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/KeyboardImpl.java index f03b2204a..df2442cd6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/KeyboardImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/KeyboardImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of input.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -36,6 +37,13 @@ public void down(String key) { page.channel.keyboardDown(params, NO_TIMEOUT); } + @Override + public void up(String key) { + PageKeyboardUpParams params = new PageKeyboardUpParams(); + params.key = key; + page.channel.keyboardUp(params, NO_TIMEOUT); + } + @Override public void insertText(String text) { PageKeyboardInsertTextParams params = new PageKeyboardInsertTextParams(); @@ -43,32 +51,17 @@ public void insertText(String text) { page.channel.keyboardInsertText(params, NO_TIMEOUT); } - @Override - public void press(String key, PressOptions options) { - pressImpl(key, options); - } - - private void pressImpl(String key, PressOptions options) { - PageKeyboardPressParams params = toProtocol(options, PageKeyboardPressParams.class); - params.key = key; - page.channel.keyboardPress(params, NO_TIMEOUT); - } - @Override public void type(String text, TypeOptions options) { - typeImpl(text, options); - } - - private void typeImpl(String text, TypeOptions options) { PageKeyboardTypeParams params = toProtocol(options, PageKeyboardTypeParams.class); params.text = text; page.channel.keyboardType(params, NO_TIMEOUT); } @Override - public void up(String key) { - PageKeyboardUpParams params = new PageKeyboardUpParams(); + public void press(String key, PressOptions options) { + PageKeyboardPressParams params = toProtocol(options, PageKeyboardPressParams.class); params.key = key; - page.channel.keyboardUp(params, NO_TIMEOUT); + page.channel.keyboardPress(params, NO_TIMEOUT); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java index 47d1e4f46..87be2ac77 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java @@ -14,57 +14,78 @@ * limitations under the License. */ +// Port of localUtils.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import java.nio.file.Path; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.gson; +import com.microsoft.playwright.impl.protocol.LocalUtilsInitializer.LocalUtilsInitializerDeviceDescriptors; +import com.microsoft.playwright.impl.protocol.LocalUtilsInitializer.LocalUtilsInitializerDeviceDescriptors.LocalUtilsInitializerDeviceDescriptorsDescriptor; public class LocalUtils extends ChannelOwner { final LocalUtilsChannel channel = new LocalUtilsChannel(this); + // java: DeviceDescriptor is the generated descriptor type of the initializer. + final Map devices; LocalUtils(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); + LocalUtilsInitializer init = connection.protocolGson().fromJson(initializer, LocalUtilsInitializer.class); + this.devices = new LinkedHashMap<>(); + for (LocalUtilsInitializerDeviceDescriptors device : init.deviceDescriptors) + this.devices.put(device.name, device.descriptor); } - JsonArray deviceDescriptors() { - return initializer.getAsJsonArray("deviceDescriptors"); + void zip(LocalUtilsZipParams params) { + channel.zip(params, NO_TIMEOUT); } - void zip(Path zipFile, List entries, String stacksId, boolean appendMode, boolean includeSources, List additionalSources) { - LocalUtilsZipParams params = new LocalUtilsZipParams(); - params.zipFile = zipFile.toString(); - params.entries = entries; - params.mode = appendMode ? "append" : "write"; - params.stacksId = stacksId; - params.includeSources = includeSources; - if (!additionalSources.isEmpty()) { - params.additionalSources = additionalSources; - } - channel.zip(params, NO_TIMEOUT); + LocalUtilsHarOpenResult harOpen(LocalUtilsHarOpenParams params) { + return channel.harOpen(params, NO_TIMEOUT); + } + + LocalUtilsHarLookupResult harLookup(LocalUtilsHarLookupParams params) { + return channel.harLookup(params, NO_TIMEOUT); + } + + // java: the pending reply, as the only caller does not await it. + WaitableResult harClose(LocalUtilsHarCloseParams params) { + return sendMessageAsync("harClose", params); } - void traceDiscarded(String stacksId) { - LocalUtilsTraceDiscardedParams params = new LocalUtilsTraceDiscardedParams(); - params.stacksId = stacksId; + void harUnzip(LocalUtilsHarUnzipParams params) { + channel.harUnzip(params, NO_TIMEOUT); + } + + LocalUtilsTracingStartedResult tracingStarted(LocalUtilsTracingStartedParams params) { + return channel.tracingStarted(params, NO_TIMEOUT); + } + + void traceDiscarded(LocalUtilsTraceDiscardedParams params) { channel.traceDiscarded(params, NO_TIMEOUT); } - String tracingStarted(String tracesDir, String traceName) { - LocalUtilsTracingStartedParams params = new LocalUtilsTracingStartedParams(); - if (tracesDir != null) { - params.tracesDir = ""; - } - params.traceName = traceName; - return connection.localUtils().channel.tracingStarted(params, NO_TIMEOUT).stacksId; + // java: the pending reply, as the only caller does not await it; it is sent while the connection sends another + // message, so the params stay JSON (the stack is the JsonArray of CallOptions.frames) and the call is internal. + WaitableResult addStackToTracingNoReply(JsonObject params) { + Connection.CallOptions options = new Connection.CallOptions(); + options.internal = true; + return connection.sendMessageToServer(this, "addStackToTracingNoReply", params, options); + } + + // java: the members below have no counterpart in localUtils.ts. + // java: the raw initializer array, which the junit DeviceDescriptor reads. + JsonArray deviceDescriptors() { + return initializer.getAsJsonArray("deviceDescriptors"); } + // java: the Java API matches globs on the driver. public Pattern globToRegex(String glob, String baseURL, boolean webSocketUrl) { LocalUtilsGlobToRegexParams params = new LocalUtilsGlobToRegexParams(); params.glob = glob; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index 5c418c3fa..0bfca68f2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -14,252 +14,179 @@ * limitations under the License. */ +// Port of locator.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.*; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.*; import java.nio.file.Path; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.function.BiFunction; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.LocatorUtils.*; +import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +import static com.microsoft.playwright.impl.isomorphic.LocatorUtils.*; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.escapeForTextSelector; +import static com.microsoft.playwright.impl.isomorphic.Time.monotonicTime; import static com.microsoft.playwright.impl.Utils.convertType; class LocatorImpl implements Locator { final FrameImpl frame; - final String selector; - private String stringRepresentation; + String selector; + String apiName = "Locator"; + + // java: upstream has one constructor with optional LocatorOptions. Locator.LocatorOptions has no + // 'visible', so filter() and visible() use the private constructor that takes FilterOptions. + LocatorImpl(FrameImpl frame, String selector) { + this(frame, selector, (FilterOptions) null); + } LocatorImpl(FrameImpl frame, String selector, LocatorOptions options) { - this(frame, selector, options, null); + this(frame, selector, convertType(options, FilterOptions.class)); } - private LocatorImpl(FrameImpl frame, String selector, LocatorOptions options, Boolean visible) { + private LocatorImpl(FrameImpl frame, String selector, FilterOptions options) { this.frame = frame; - if (options != null) { - if (options.hasText != null) { - selector += " >> internal:has-text=" + escapeForTextSelector(options.hasText, false); - } - if (options.hasNotText != null) { - selector += " >> internal:has-not-text=" + escapeForTextSelector(options.hasNotText, false); - } - if (options.has != null) { - LocatorImpl locator = (LocatorImpl) options.has; - if (locator.frame != frame) - throw new Error("Inner 'has' locator must belong to the same frame."); - selector += " >> internal:has=" + gson().toJson(locator.selector); - } - if (options.hasNot != null) { - LocatorImpl locator = (LocatorImpl) options.hasNot; - if (locator.frame != frame) - throw new Error("Inner 'hasNot' locator must belong to the same frame."); - selector += " >> internal:has-not=" + gson().toJson(locator.selector); - } - } - if (visible != null) { - selector += " >> visible=" + visible; - } this.selector = selector; - } - private R withElement(BiFunction callback, O options, String title) { - return frame.withTitle(title, () -> { - ElementHandleOptions handleOptions = convertType(options, ElementHandleOptions.class); - // TODO: support deadline based timeout - // Double timeout = null; - // if (handleOptions != null) { - // timeout = handleOptions.timeout; - // } - // timeout = frame.page.timeoutSettings.timeout(timeout); - // long deadline = System.nanoTime() + (long) timeout.doubleValue() * 1_000_000; - ElementHandle handle = elementHandle(handleOptions); - try { - return callback.apply(handle, options); - } finally { - if (handle != null) { - handle.dispose(); - } - } - }); - } + if (options != null && options.hasText != null) + this.selector += " >> internal:has-text=" + escapeForTextSelector(options.hasText, false); - @Override - public List all() { - List result = new ArrayList<>(); - int count = this.count(); - for (int i = 0; i < count; i++) { - result.add(nth(i)); + if (options != null && options.hasNotText != null) + this.selector += " >> internal:has-not-text=" + escapeForTextSelector(options.hasNotText, false); + + if (options != null && options.has != null) { + LocatorImpl locator = (LocatorImpl) options.has; + if (locator.frame != frame) + throw new PlaywrightException("Inner \"has\" locator must belong to the same frame."); + this.selector += " >> internal:has=" + gson().toJson(locator.selector); } - return result; - } - @Override - public List allInnerTexts() { - return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.innerText)"); + if (options != null && options.hasNot != null) { + LocatorImpl locator = (LocatorImpl) options.hasNot; + if (locator.frame != frame) + throw new PlaywrightException("Inner \"hasNot\" locator must belong to the same frame."); + this.selector += " >> internal:has-not=" + gson().toJson(locator.selector); + } + + if (options != null && options.visible != null) + this.selector += " >> visible=" + (options.visible ? "true" : "false"); + + // java: no inspect.custom. } - @Override - public List allTextContents() { - return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.textContent || '')"); + R wrapApiCall(Supplier func, String title, boolean internal) { + return frame.wrapApiCall(func, title, internal); } - @Override - public Locator normalize() { - FrameResolveSelectorParams params = new FrameResolveSelectorParams(); + // java: the options are the timeout alone, there is no AbortSignal. + private R withElement(BiFunction task, Double timeoutOption) { + double timeout = frame.timeout(timeoutOption); + double deadline = timeout != 0 ? monotonicTime() + timeout : 0; + + FrameWaitForSelectorParams params = new FrameWaitForSelectorParams(); params.selector = selector; - params.sdkLanguage = "java"; - FrameResolveSelectorResult result = frame.channel.resolveSelector(params, ChannelOwner.NO_TIMEOUT); - LocatorImpl locator = new LocatorImpl(frame, result.resolvedSelector, null); - if (result.locatorCode != null) { - locator.stringRepresentation = result.locatorCode; + params.strict = true; + params.state = "attached"; + FrameWaitForSelectorResult result = frame.channel.waitForSelector(params, timeout); + ElementHandle handle = result.element; + if (handle == null) + throw new PlaywrightException("Could not resolve " + selector + " to DOM Element"); + try { + return task.apply(handle, deadline != 0 ? deadline - monotonicTime() : 0); + } finally { + handle.dispose(); } - return locator; } - @Override - public Locator and(Locator locator) { - LocatorImpl other = (LocatorImpl) locator; - if (other.frame != frame) - throw new Error("Locators must belong to the same frame."); - return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(other.selector), null); + boolean equals(LocatorImpl locator) { + return frame == locator.frame && selector.equals(locator.selector); } + // java: equals(Object) so that Java collections and assertEquals agree with _equals(). @Override - public String ariaSnapshot(AriaSnapshotOptions options) { - if (options == null) { - options = new AriaSnapshotOptions(); - } - FrameAriaSnapshotParams params = Utils.toProtocol(options, FrameAriaSnapshotParams.class); - params.selector = selector; - return frame.channel.ariaSnapshot(params, frame.timeout(options.timeout)).snapshot; + public boolean equals(Object obj) { + if (!(obj instanceof LocatorImpl)) + return false; + return equals((LocatorImpl) obj); } @Override - public void blur(BlurOptions options) { - if (options == null) { - options = new BlurOptions(); - } - FrameBlurParams params = Utils.toProtocol(options, FrameBlurParams.class); - params.selector = selector; - params.strict = true; - frame.channel.blur(params, frame.timeout(options.timeout)); + public Page page() { + return frame.page(); } @Override public BoundingBox boundingBox(BoundingBoxOptions options) { - return withElement((h, o) -> h.boundingBox(), options, "Bounding Box"); + return frame.withTitle("Bounding box", () -> withElement((h, timeout) -> h.boundingBox(), options == null ? null : options.timeout)); } @Override public void check(CheckOptions options) { - if (options == null) { + if (options == null) options = new CheckOptions(); - } frame.check(selector, convertType(options, Frame.CheckOptions.class).setStrict(true)); } - @Override - public void clear(ClearOptions options) { - frame.withTitle("Clear", () -> fill("", convertType(options, FillOptions.class))); - } - + // java: Frame.ClickOptions has no 'steps', so this sends what upstream frame.click() sends. @Override public void click(ClickOptions options) { - if (options == null) { + if (options == null) options = new ClickOptions(); - } - frame.clickImpl(selector, convertType(options, Frame.ClickOptions.class).setStrict(true), options.steps); - } - - @Override - public int count() { - return frame.queryCount(selector); - } - - @Override - public Locator describe(String description) { - return locator(describeSelector(description)); - } - - @Override - public String description() { - // Match internal:describe= at the end of the selector with a JSON string - // Pattern matches: >> internal:describe="..." where ... is a JSON-encoded string - Pattern pattern = Pattern.compile(" >> internal:describe=(\"(?:[^\"\\\\]|\\\\.)*\")$"); - Matcher matcher = pattern.matcher(selector); - - if (matcher.find()) { - String jsonString = matcher.group(1); - try { - // Deserialize the JSON string - return gson().fromJson(jsonString, String.class); - } catch (Exception e) { - // If we can't parse it, return null - return null; - } - } - - return null; + FrameClickParams params = Utils.toProtocol(options, FrameClickParams.class); + params.selector = selector; + params.strict = true; + frame.channel.click(params, frame.timeout(options.timeout)); } + // java: Frame.DblclickOptions has no 'steps', so this sends what upstream frame.dblclick() sends. @Override public void dblclick(DblclickOptions options) { - if (options == null) { + if (options == null) options = new DblclickOptions(); - } - frame.dblclickImpl(selector, convertType(options, Frame.DblclickOptions.class).setStrict(true), options.steps); + FrameDblclickParams params = Utils.toProtocol(options, FrameDblclickParams.class); + params.selector = selector; + params.strict = true; + frame.channel.dblclick(params, frame.timeout(options.timeout)); } @Override public void dispatchEvent(String type, Object eventInit, DispatchEventOptions options) { - if (options == null) { + if (eventInit == null) + eventInit = new LinkedHashMap<>(); + if (options == null) options = new DispatchEventOptions(); - } frame.dispatchEvent(selector, type, eventInit, convertType(options, Frame.DispatchEventOptions.class).setStrict(true)); } @Override public void dragTo(Locator target, DragToOptions options) { - if (options == null) { + if (options == null) options = new DragToOptions(); - } - Frame.DragAndDropOptions frameOptions = convertType(options, Frame.DragAndDropOptions.class); - frameOptions.setStrict(true); - frame.dragAndDropImpl(selector, ((LocatorImpl) target).selector, frameOptions, options.steps); - } - - @Override - public ElementHandle elementHandle(ElementHandleOptions options) { - if (options == null) { - options = new ElementHandleOptions(); - } - Frame.WaitForSelectorOptions frameOptions = convertType(options, Frame.WaitForSelectorOptions.class); - frameOptions.setStrict(true); - frameOptions.setState(WaitForSelectorState.ATTACHED); - return frame.waitForSelector(selector, frameOptions); - } - - @Override - public List elementHandles() { - return frame.querySelectorAll(selector); + frame.dragAndDrop(selector, ((LocatorImpl) target).selector, convertType(options, Frame.DragAndDropOptions.class).setStrict(true)); } @Override - public FrameLocator contentFrame() { - return new FrameLocatorImpl(frame, selector); + public void drop(DropPayload payload, DropOptions options) { + // java: there is no Frame.DropOptions with 'strict', FrameImpl.drop() sets strict: true. + frame.drop(selector, payload, options); } + // java: Locator.EvaluateOptions has no exposeFunctions, so no evaluate options reach h.evaluate(). @Override public Object evaluate(String expression, Object arg, EvaluateOptions options) { - return withElement((h, o) -> h.evaluate(expression, arg), options, "Evaluate"); + return frame.withTitle("Evaluate", () -> withElement((h, timeout) -> h.evaluate(expression, arg), options == null ? null : options.timeout)); } @Override @@ -267,54 +194,70 @@ public Object evaluateAll(String expression, Object arg) { return frame.evalOnSelectorAll(selector, expression, arg); } + // java: Locator.EvaluateHandleOptions has no exposeFunctions, so no evaluate options reach h.evaluateHandle(). @Override public JSHandle evaluateHandle(String expression, Object arg, EvaluateHandleOptions options) { - return withElement((h, o) -> h.evaluateHandle(expression, arg), options, "Evaluate"); + return frame.withTitle("Evaluate", () -> withElement((h, timeout) -> h.evaluateHandle(expression, arg), options == null ? null : options.timeout)); } @Override public void fill(String value, FillOptions options) { - if (options == null) { + if (options == null) options = new FillOptions(); - } frame.fill(selector, value, convertType(options, Frame.FillOptions.class).setStrict(true)); } @Override - public Locator filter(FilterOptions options) { - Boolean visible = (options == null) ? null : options.visible; - return new LocatorImpl(frame, selector, convertType(options, LocatorOptions.class), visible); + public void clear(ClearOptions options) { + frame.withTitle("Clear", () -> fill("", convertType(options, FillOptions.class))); } + // java: _highlight is highlightImpl, highlight() is the public API; the omitted style is null. + void highlightImpl() { + // VS Code extension uses this one, keep it for now. + frame.highlight(selector, null); + } + + // java: HighlightOptions.style is a String, never an object for cssObjectToString(). @Override - public Locator first() { - return new LocatorImpl(frame, selector + " >> nth=0", null); + public AutoCloseable highlight(HighlightOptions options) { + if (options == null) + options = new HighlightOptions(); + String style = options.style; + frame.highlight(selector, style); + return new DisposableStub(this::hideHighlight); } @Override - public Locator visible() { - return new LocatorImpl(frame, selector, null, true); + public void hideHighlight() { + frame.hideHighlight(selector); } @Override - public void focus(FocusOptions options) { - if (options == null) { - options = new FocusOptions(); - } - frame.focus(selector, convertType(options, Frame.FocusOptions.class).setStrict(true)); + public Locator locator(String selectorOrLocator, LocatorOptions options) { + return new LocatorImpl(frame, selector + " >> " + selectorOrLocator, options); } @Override - public FrameLocatorImpl frameLocator(String selector) { - return new FrameLocatorImpl(frame, this.selector + " >> " + selector); + public Locator locator(Locator selectorOrLocator, LocatorOptions options) { + if (((LocatorImpl) selectorOrLocator).frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:chain=" + gson().toJson(((LocatorImpl) selectorOrLocator).selector), options); } @Override - public String getAttribute(String name, GetAttributeOptions options) { - if (options == null) { - options = new GetAttributeOptions(); - } - return frame.getAttribute(selector, name, convertType(options, Frame.GetAttributeOptions.class).setStrict(true)); + public Locator within(Locator locator) { + return locator.locator(this); + } + + @Override + public Locator getByTestId(String testId) { + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); + } + + @Override + public Locator getByTestId(Pattern testId) { + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override @@ -347,337 +290,407 @@ public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { return locator(getByPlaceholderSelector(text, options)); } + @Override + public Locator getByText(String text, GetByTextOptions options) { + return locator(getByTextSelector(text, options)); + } + + @Override + public Locator getByText(Pattern text, GetByTextOptions options) { + return locator(getByTextSelector(text, options)); + } + + @Override + public Locator getByTitle(String text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, options)); + } + + @Override + public Locator getByTitle(Pattern text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, options)); + } + @Override public Locator getByRole(AriaRole role, GetByRoleOptions options) { return locator(getByRoleSelector(role, options)); } @Override - public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + public FrameLocator frameLocator(String selector) { + return new FrameLocatorImpl(frame, this.selector + " >> " + selector); } @Override - public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + public Locator filter(FilterOptions options) { + return new LocatorImpl(frame, selector, options); } @Override - public Locator getByText(String text, GetByTextOptions options) { - return locator(getByTextSelector(text, options)); + public Locator visible() { + return new LocatorImpl(frame, selector, new FilterOptions().setVisible(true)); } @Override - public Locator getByText(Pattern text, GetByTextOptions options) { - return locator(getByTextSelector(text, options)); + public ElementHandle elementHandle(ElementHandleOptions options) { + if (options == null) + options = new ElementHandleOptions(); + Frame.WaitForSelectorOptions frameOptions = convertType(options, Frame.WaitForSelectorOptions.class); + frameOptions.setStrict(true); + frameOptions.setState(WaitForSelectorState.ATTACHED); + return frame.waitForSelector(selector, frameOptions); } @Override - public Locator getByTitle(String text, GetByTitleOptions options) { - return locator(getByTitleSelector(text, options)); + public List elementHandles() { + return frame.querySelectorAll(selector); } @Override - public Locator getByTitle(Pattern text, GetByTitleOptions options) { - return locator(getByTitleSelector(text, options)); + public FrameLocator contentFrame() { + return new FrameLocatorImpl(frame, selector); } @Override - public void drop(DropPayload payload, DropOptions options) { - frame.dropImpl(selector, payload, options); + public Locator describe(String description) { + return new LocatorImpl(frame, selector + " >> internal:describe=" + gson().toJson(description)); } + // java: there is no port of the selector parser; this matches the trailing internal:describe part + // that upstream locatorCustomDescription() reads. @Override - public AutoCloseable highlight(HighlightOptions options) { - String style = options == null ? null : options.style; - frame.highlightImpl(selector, style); - return new DisposableStub(this::hideHighlight); + public String description() { + Matcher matcher = Pattern.compile(" >> internal:describe=(\"(?:[^\"\\\\]|\\\\.)*\")$").matcher(selector); + if (!matcher.find()) + return null; + try { + return gson().fromJson(matcher.group(1), String.class); + } catch (RuntimeException e) { + return null; + } } @Override - public void hideHighlight() { - frame.hideHighlightImpl(selector); + public Locator first() { + return new LocatorImpl(frame, selector + " >> nth=0"); + } + + @Override + public Locator last() { + return new LocatorImpl(frame, selector + " >> nth=-1"); + } + + @Override + public Locator nth(int index) { + return new LocatorImpl(frame, selector + " >> nth=" + index); + } + + @Override + public Locator and(Locator locator) { + if (((LocatorImpl) locator).frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(((LocatorImpl) locator).selector)); + } + + @Override + public Locator or(Locator locator) { + if (((LocatorImpl) locator).frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:or=" + gson().toJson(((LocatorImpl) locator).selector)); + } + + @Override + public void focus(FocusOptions options) { + if (options == null) + options = new FocusOptions(); + frame.focus(selector, convertType(options, Frame.FocusOptions.class).setStrict(true)); + } + + @Override + public void blur(BlurOptions options) { + if (options == null) + options = new BlurOptions(); + FrameBlurParams params = Utils.toProtocol(options, FrameBlurParams.class); + params.selector = selector; + params.strict = true; + frame.channel.blur(params, frame.timeout(options.timeout)); + } + + @Override + public int count() { + return frame.queryCount(selector); + } + + // java: sends sdkLanguage so that toString() prints the Java locator code the server returns. + @Override + public Locator normalize() { + FrameResolveSelectorParams params = new FrameResolveSelectorParams(); + params.selector = selector; + params.sdkLanguage = "java"; + FrameResolveSelectorResult result = frame.channel.resolveSelector(params, NO_TIMEOUT); + LocatorImpl locator = new LocatorImpl(frame, result.resolvedSelector); + locator.stringRepresentation = result.locatorCode; + return locator; + } + + @Override + public String getAttribute(String name, GetAttributeOptions options) { + if (options == null) + options = new GetAttributeOptions(); + return frame.getAttribute(selector, name, convertType(options, Frame.GetAttributeOptions.class).setStrict(true)); } @Override public void hover(HoverOptions options) { - if (options == null) { + if (options == null) options = new HoverOptions(); - } frame.hover(selector, convertType(options, Frame.HoverOptions.class).setStrict(true)); } @Override public String innerHTML(InnerHTMLOptions options) { - if (options == null) { + if (options == null) options = new InnerHTMLOptions(); - } return frame.innerHTML(selector, convertType(options, Frame.InnerHTMLOptions.class).setStrict(true)); } @Override public String innerText(InnerTextOptions options) { - if (options == null) { + if (options == null) options = new InnerTextOptions(); - } return frame.innerText(selector, convertType(options, Frame.InnerTextOptions.class).setStrict(true)); } @Override public String inputValue(InputValueOptions options) { - if (options == null) { + if (options == null) options = new InputValueOptions(); - } return frame.inputValue(selector, convertType(options, Frame.InputValueOptions.class).setStrict(true)); } @Override public boolean isChecked(IsCheckedOptions options) { - if (options == null) { + if (options == null) options = new IsCheckedOptions(); - } return frame.isChecked(selector, convertType(options, Frame.IsCheckedOptions.class).setStrict(true)); } @Override public boolean isDisabled(IsDisabledOptions options) { - if (options == null) { + if (options == null) options = new IsDisabledOptions(); - } return frame.isDisabled(selector, convertType(options, Frame.IsDisabledOptions.class).setStrict(true)); } @Override public boolean isEditable(IsEditableOptions options) { - if (options == null) { + if (options == null) options = new IsEditableOptions(); - } return frame.isEditable(selector, convertType(options, Frame.IsEditableOptions.class).setStrict(true)); } @Override public boolean isEnabled(IsEnabledOptions options) { - if (options == null) { + if (options == null) options = new IsEnabledOptions(); - } return frame.isEnabled(selector, convertType(options, Frame.IsEnabledOptions.class).setStrict(true)); } @Override public boolean isHidden(IsHiddenOptions options) { - if (options == null) { + if (options == null) options = new IsHiddenOptions(); - } return frame.isHidden(selector, convertType(options, Frame.IsHiddenOptions.class).setStrict(true)); } @Override public boolean isVisible(IsVisibleOptions options) { - if (options == null) { + if (options == null) options = new IsVisibleOptions(); - } return frame.isVisible(selector, convertType(options, Frame.IsVisibleOptions.class).setStrict(true)); } - @Override - public Locator last() { - return new LocatorImpl(frame, selector + " >> nth=-1", null); - } - - @Override - public Locator locator(String selector, LocatorOptions options) { - return new LocatorImpl(frame, this.selector + " >> " + selector, options); - } - - @Override - public Locator locator(Locator selectorOrLocator, LocatorOptions options) { - LocatorImpl other = (LocatorImpl) selectorOrLocator; - if (other.frame != frame) { - throw new PlaywrightException("Locators must belong to the same frame."); - } - return new LocatorImpl(frame, this.selector + " >> internal:chain=" + gson().toJson(other.selector), options); - } - - @Override - public Locator nth(int index) { - return new LocatorImpl(frame, selector + " >> nth=" + index, null); - } - - @Override - public Locator or(Locator locator) { - LocatorImpl other = (LocatorImpl) locator; - if (other.frame != frame) - throw new Error("Locators must belong to the same frame."); - return new LocatorImpl(frame, selector + " >> internal:or=" + gson().toJson(other.selector), null); - } - - @Override - public Page page() { - return frame.page(); - } - @Override public void press(String key, PressOptions options) { - if (options == null) { + if (options == null) options = new PressOptions(); - } frame.press(selector, key, convertType(options, Frame.PressOptions.class).setStrict(true)); } @Override - public void pressSequentially(String text, PressSequentiallyOptions options) { - type(text, convertType(options, TypeOptions.class)); + public byte[] screenshot(ScreenshotOptions options) { + ScreenshotOptions screenshotOptions = options == null ? new ScreenshotOptions() : options; + return frame.withTitle("Screenshot", () -> withElement((h, timeout) -> { + ElementHandle.ScreenshotOptions handleOptions = convertType(screenshotOptions, ElementHandle.ScreenshotOptions.class); + handleOptions.timeout = timeout; + return h.screenshot(handleOptions); + }, screenshotOptions.timeout)); } @Override - public byte[] screenshot(ScreenshotOptions options) { - return withElement((h, o) -> h.screenshot(o), convertType(options, ElementHandle.ScreenshotOptions.class), "Screenshot"); + public String ariaSnapshot(AriaSnapshotOptions options) { + if (options == null) + options = new AriaSnapshotOptions(); + FrameAriaSnapshotParams params = Utils.toProtocol(options, FrameAriaSnapshotParams.class); + params.selector = selector; + return frame.channel.ariaSnapshot(params, frame.timeout(options.timeout)).snapshot; + } + + // java: the options are those of ariaSnapshot(), the AriaSnapshotJSON result is a Gson JsonElement. + JsonElement ariaSnapshotJSON(AriaSnapshotOptions options) { + if (options == null) + options = new AriaSnapshotOptions(); + FrameAriaSnapshotJSONParams params = Utils.toProtocol(options, FrameAriaSnapshotJSONParams.class); + params.selector = selector; + FrameAriaSnapshotJSONResult result = frame.channel.ariaSnapshotJSON(params, frame.timeout(options.timeout)); + return result.snapshot; } @Override public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { - withElement((h, o) -> { - h.scrollIntoViewIfNeeded(o); + ScrollIntoViewIfNeededOptions scrollOptions = options == null ? new ScrollIntoViewIfNeededOptions() : options; + frame.withTitle("Scroll into view", () -> withElement((h, timeout) -> { + ElementHandle.ScrollIntoViewIfNeededOptions handleOptions = convertType(scrollOptions, ElementHandle.ScrollIntoViewIfNeededOptions.class); + handleOptions.timeout = timeout; + h.scrollIntoViewIfNeeded(handleOptions); return null; - }, convertType(options, ElementHandle.ScrollIntoViewIfNeededOptions.class), "Scroll into view"); + }, scrollOptions.timeout)); } @Override public List selectOption(String values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public List selectOption(ElementHandle values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public List selectOption(String[] values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public List selectOption(SelectOption values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public List selectOption(ElementHandle[] values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public List selectOption(SelectOption[] values, SelectOptionOptions options) { - if (options == null) { - options = new SelectOptionOptions(); - } - return frame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class).setStrict(true)); + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); } @Override public void selectText(SelectTextOptions options) { - withElement((h, o) -> { - h.selectText(o); + SelectTextOptions selectOptions = options == null ? new SelectTextOptions() : options; + frame.withTitle("Select text", () -> withElement((h, timeout) -> { + ElementHandle.SelectTextOptions handleOptions = convertType(selectOptions, ElementHandle.SelectTextOptions.class); + handleOptions.timeout = timeout; + h.selectText(handleOptions); return null; - }, convertType(options, ElementHandle.SelectTextOptions.class), "Select text"); + }, selectOptions.timeout)); } @Override public void setChecked(boolean checked, SetCheckedOptions options) { - if (options == null) { - options = new SetCheckedOptions(); - } - frame.setChecked(selector, checked, convertType(options, Frame.SetCheckedOptions.class).setStrict(true)); + if (checked) + check(convertType(options, CheckOptions.class)); + else + uncheck(convertType(options, UncheckOptions.class)); } @Override public void setInputFiles(Path files, SetInputFilesOptions options) { - if (options == null) { - options = new SetInputFilesOptions(); - } - frame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class).setStrict(true)); + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); } @Override public void setInputFiles(Path[] files, SetInputFilesOptions options) { - if (options == null) { - options = new SetInputFilesOptions(); - } - frame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class).setStrict(true)); + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); } @Override public void setInputFiles(FilePayload files, SetInputFilesOptions options) { - if (options == null) { - options = new SetInputFilesOptions(); - } - frame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class).setStrict(true)); + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); } @Override public void setInputFiles(FilePayload[] files, SetInputFilesOptions options) { - if (options == null) { - options = new SetInputFilesOptions(); - } - frame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class).setStrict(true)); + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); } @Override public void tap(TapOptions options) { - if (options == null) { + if (options == null) options = new TapOptions(); - } frame.tap(selector, convertType(options, Frame.TapOptions.class).setStrict(true)); } @Override public String textContent(TextContentOptions options) { - if (options == null) { + if (options == null) options = new TextContentOptions(); - } return frame.textContent(selector, convertType(options, Frame.TextContentOptions.class).setStrict(true)); } @Override public void type(String text, TypeOptions options) { - if (options == null) { + if (options == null) options = new TypeOptions(); - } frame.type(selector, text, convertType(options, Frame.TypeOptions.class).setStrict(true)); } + @Override + public void pressSequentially(String text, PressSequentiallyOptions options) { + type(text, convertType(options, TypeOptions.class)); + } + @Override public void uncheck(UncheckOptions options) { - if (options == null) { + if (options == null) options = new UncheckOptions(); - } frame.uncheck(selector, convertType(options, Frame.UncheckOptions.class).setStrict(true)); } + @Override + public List all() { + List result = new ArrayList<>(); + int count = count(); + for (int i = 0; i < count; i++) + result.add(nth(i)); + return result; + } + + @SuppressWarnings("unchecked") + @Override + public List allInnerTexts() { + return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.innerText)"); + } + + @SuppressWarnings("unchecked") + @Override + public List allTextContents() { + return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.textContent || '')"); + } + @Override public void waitFor(WaitForOptions options) { - if (options == null) { + if (options == null) options = new WaitForOptions(); - } - frame.waitForSelectorImpl(selector, convertType(options, Frame.WaitForSelectorOptions.class).setStrict(true), true); + FrameWaitForSelectorParams params = Utils.toProtocol(options, FrameWaitForSelectorParams.class); + params.selector = selector; + params.strict = true; + params.omitReturnValue = true; + frame.channel.waitForSelector(params, frame.timeout(options.timeout)); } + // java: functions are passed as strings, so isFunction is not sent and the server detects it. @Override public void waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { FrameWaitForFunctionParams params = new FrameWaitForFunctionParams(); @@ -688,30 +701,71 @@ public void waitForFunction(String expression, Object arg, WaitForFunctionOption frame.channel.waitForFunction(params, frame.timeout(options == null ? null : options.timeout)); } - @Override - public Locator within(Locator locator) { - return locator.locator(this); + // java: upstream options.title is the separate title parameter, as in FrameImpl.expect. + FrameExpectResult expect(String expression, FrameExpectOptions options, String title) { + options.selector = selector; + return frame.expect(expression, options, title); } + // java: no _inspect, it serves inspect.custom. + + // java: there is no port of the locator generators. The text of the old Java client is kept, + // tests pin it: the server's Java locator code after normalize(), the description, or Locator@. @Override public String toString() { - if (stringRepresentation != null) { + if (stringRepresentation != null) return stringRepresentation; - } String description = description(); - if (description != null) { + if (description != null) return description; - } return "Locator@" + selector; } - @Override - public boolean equals(Object obj) { - if (!(obj instanceof LocatorImpl)) { - return false; + // java: the module-level _testIdAttributeName is SelectorsImpl.testIdAttributeName of the Playwright instance, + // so testIdAttributeName() and setTestIdAttribute() take the selectors. + static String testIdAttributeName(SelectorsImpl selectors) { + return selectors.testIdAttributeName; + } + + static void setTestIdAttribute(SelectorsImpl selectors, String attributeName) { + selectors.testIdAttributeName = attributeName; + } + + // java: a Record is a Map of String or Number values. + static String cssObjectToString(Map style) { + List entries = new ArrayList<>(); + for (Map.Entry entry : style.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + String property; + if (key.startsWith("--")) { + property = key; + } else { + Matcher m = Pattern.compile("[A-Z]").matcher(key); + StringBuffer buffer = new StringBuffer(); + while (m.find()) + m.appendReplacement(buffer, Matcher.quoteReplacement("-" + m.group().toLowerCase())); + m.appendTail(buffer); + property = buffer.toString(); + } + entries.add(property + ": " + value); } - LocatorImpl locator = (LocatorImpl) obj; - return frame.equals(locator.frame) && selector.equals(locator.selector); + return String.join("; ", entries); + } + + // java: helpers and members with no upstream counterpart. + private String stringRepresentation; + + private Frame.SelectOptionOptions frameSelectOptionOptions(SelectOptionOptions options) { + if (options == null) + options = new SelectOptionOptions(); + return convertType(options, Frame.SelectOptionOptions.class).setStrict(true); + } + + private Frame.SetInputFilesOptions frameSetInputFilesOptions(SetInputFilesOptions options) { + if (options == null) + options = new SetInputFilesOptions(); + return convertType(options, Frame.SetInputFilesOptions.class).setStrict(true); } @Override @@ -719,11 +773,6 @@ public int hashCode() { return frame.hashCode() ^ selector.hashCode(); } - FrameExpectResult expect(String expression, FrameExpectOptions options, String title) { - options.selector = selector; - return frame.expect(expression, options, title); - } - JsonObject toProtocol() { JsonObject result = new JsonObject(); result.add("frame", frame.toProtocolRef()); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java deleted file mode 100644 index 8d9c025cd..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.Locator; -import com.microsoft.playwright.options.AriaRole; - -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; - -public class LocatorUtils { - static String getByTextSelector(Object text, Locator.GetByTextOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return "internal:text=" + escapeForTextSelector(text, exact); - } - - static String getByLabelSelector(Object text, Locator.GetByLabelOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return "internal:label=" + escapeForTextSelector(text, exact); - } - - private static String getByAttributeTextSelector(String attrName, Object value, boolean exact) { - return "internal:attr=[" + attrName + "=" + escapeForAttributeSelector(value, exact) + "]"; - } - - static String describeSelector(String description) { - return "internal:describe=" + gson().toJson(description); - } - - // Multiple test id attribute names can be joined with a comma. Attribute names cannot contain commas. - private static String encodeTestIdAttributeName(String testIdAttributeName) { - return testIdAttributeName.contains(",") ? gson().toJson(testIdAttributeName) : testIdAttributeName; - } - - static String getByTestIdSelector(Object testId, PlaywrightImpl playwright) { - String attributeName = encodeTestIdAttributeName(playwright.selectors.testIdAttributeName); - return "internal:testid=[" + attributeName + "=" + escapeForAttributeSelector(testId, true) + "]"; - } - - static String getByAltTextSelector(Object text, Locator.GetByAltTextOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("alt", text, exact); - } - - static String getByTitleSelector(Object text, Locator.GetByTitleOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("title", text, exact); - } - - static String getByPlaceholderSelector(Object text, Locator.GetByPlaceholderOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("placeholder", text, exact); - } - - private static void addAttr(StringBuilder result, String name, String value) { - result.append("[").append(name).append("=").append(value).append("]"); - } - - static String getByRoleSelector(AriaRole role, Locator.GetByRoleOptions options) { - StringBuilder result = new StringBuilder(); - result.append("internal:role=").append(role.name().toLowerCase()); - if (options != null) { - if (options.checked != null) - addAttr(result, "checked", options.checked.toString()); - if (options.disabled != null) - addAttr(result, "disabled", options.disabled.toString()); - if (options.selected != null) - addAttr(result, "selected", options.selected.toString()); - if (options.expanded != null) - addAttr(result, "expanded", options.expanded.toString()); - if (options.includeHidden != null) - addAttr(result, "include-hidden", options.includeHidden.toString()); - if (options.level != null) - addAttr(result, "level", options.level.toString()); - if (options.name != null) { - String name = escapeForAttributeSelector(options.name, options.exact != null && options.exact); - addAttr(result, "name", name); - } - if (options.description != null) { - String description = escapeForAttributeSelector(options.description, options.exact != null && options.exact); - addAttr(result, "description", description); - } - if (options.pressed != null) - addAttr(result, "pressed", options.pressed.toString()); - } - return result.toString(); - } - - private static String escapeRegexForSelector(Pattern re) { - // Even number of backslashes followed by the quote -> insert a backslash. - return toJsRegExp(re).replaceAll("(^|[^\\\\])(\\\\\\\\)*([\"'`])", "$1$2\\\\$3").replaceAll(">>", "\\\\>\\\\>"); - } - - static String escapeForTextSelector(Object value, boolean exact) { - if (value instanceof Pattern) { - return escapeRegexForSelector((Pattern) value); - } - if (value instanceof String) { - return gson().toJson(value) + (exact ? "s" : "i"); - } - throw new IllegalArgumentException("text parameter must be Pattern or String: " + value); - } - - private static String escapeForAttributeSelector(Object value, boolean exact) { - if (value instanceof Pattern) { - return escapeRegexForSelector((Pattern) value); - } - if (value instanceof String) { - // TODO: this should actually be - // cssEscape(value).replace(/\\ /g, ' ') - // However, our attribute selectors do not conform to CSS parsing spec, - // so we escape them differently. - return '"' + ((String) value).replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") + '"' + (exact ? "" : "i"); - } - throw new IllegalArgumentException("Attribute can be String or Pattern, found: " + value); - } - - private static String toJsRegExp(Pattern pattern) { - return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java new file mode 100644 index 000000000..e5055b024 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/manualPromise.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +// java: no ManualPromise class, a WaitableResult stands for it (resolve is complete()). An async race returns the +// race as a Waitable, which race(), safeRace() and raceMultiple() pump the connection of the owner for; disposing +// it is the finally block of _race. +// java: stays in impl, not in impl.isomorphic: it is built on ChannelOwner and the Waitable primitives. +class LongStandingScope { + // java: the owner whose connection a race pumps. + private final ChannelOwner owner; + private PlaywrightException terminateError; + private PlaywrightException closeError; + // java: the frames are a Java stack trace. + private final Map, StackTraceElement[]> terminatePromises = new LinkedHashMap<>(); + private boolean isClosed = false; + + LongStandingScope(ChannelOwner owner) { + this.owner = owner; + } + + void reject(PlaywrightException error) { + isClosed = true; + terminateError = error; + for (WaitableResult p : new ArrayList<>(terminatePromises.keySet())) + p.complete(error); + } + + void close(PlaywrightException error) { + isClosed = true; + closeError = error; + for (Map.Entry, StackTraceElement[]> entry : new ArrayList<>(terminatePromises.entrySet())) + entry.getKey().complete(cloneError(error, entry.getValue())); + } + + boolean isClosed() { + return isClosed; + } + + // java: Promise.race of the s.race(promise) calls is one WaitableRace of their races, s._race([promise], false). + static T raceMultiple(List scopes, Waitable promise) { + List> races = new ArrayList<>(); + for (LongStandingScope s : scopes) + races.add(s.race(Collections.singletonList(promise), false, null)); + try { + return scopes.get(0).owner.runUntil(() -> {}, new WaitableRace<>(races)); + } finally { + for (Waitable race : races) + race.dispose(); + } + } + + // java: the promise | promise[] parameter is an overload. + T race(Waitable promise) { + return race(Collections.singletonList(promise)); + } + + T race(List> promise) { + return await(race(promise, false, null)); + } + + T safeRace(Waitable promise) { + return safeRace(promise, null); + } + + T safeRace(Waitable promise, T defaultValue) { + return await(race(Collections.singletonList(promise), true, defaultValue)); + } + + private Waitable race(List> promises, boolean safe, T defaultValue) { + WaitableResult terminatePromise = new WaitableResult<>(); + StackTraceElement[] frames = new Exception().getStackTrace(); + if (terminateError != null) + terminatePromise.complete(terminateError); + if (closeError != null) + terminatePromise.complete(cloneError(closeError, frames)); + terminatePromises.put(terminatePromise, frames); + List> race = new ArrayList<>(); + // java: the promises go first, a settled promise wins over a closed scope as its reaction runs first upstream. + race.addAll(promises); + race.add(new Waitable() { + @Override + public boolean isDone() { + return terminatePromise.isDone(); + } + + @Override + public T get() { + if (safe) + return defaultValue; + throw terminatePromise.get(); + } + + @Override + public void dispose() { + terminatePromises.remove(terminatePromise); + } + }); + return new WaitableRace<>(race); + } + + // java: no signalToPromise, it serves AbortSignal. + + // java: a new exception of the same type, with the frames of the race as its stack trace. + private static PlaywrightException cloneError(PlaywrightException error, StackTraceElement[] frames) { + PlaywrightException clone = error instanceof TargetClosedError ? new TargetClosedError(error.getMessage()) : new PlaywrightException(error.getMessage()); + clone.setStackTrace(frames); + return clone; + } + + // java: members with no counterpart upstream. + + // java: await of a race; the finally block of _race disposes it. + private T await(Waitable race) { + try { + return owner.runUntil(() -> {}, race); + } finally { + race.dispose(); + } + } + + // java: the terminate promise of a race without promises, raced by PageImpl.createWaitForCloseHelper(). + Waitable terminatePromise(boolean safe) { + return race(new ArrayList<>(), safe, null); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java index f0f06d1b9..5bf7ee8f1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java @@ -14,11 +14,14 @@ * limitations under the License. */ +// Port of input.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.Mouse; +import java.util.function.Supplier; + import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static com.microsoft.playwright.impl.Utils.convertType; import static com.microsoft.playwright.impl.Utils.toProtocol; @@ -30,28 +33,16 @@ class MouseImpl implements Mouse { this.page = page; } - @Override - public void click(double x, double y, ClickOptions options) { - PageMouseClickParams params = toProtocol(options, PageMouseClickParams.class); - params.x = x; - params.y = y; - page.channel.mouseClick(params, NO_TIMEOUT); + R wrapApiCall(Supplier func, String title, boolean internal) { + return page.wrapApiCall(func, title, internal); } @Override - public void dblclick(double x, double y, DblclickOptions options) { - page.withTitle("Double click", () -> dblclickImpl(x, y, options)); - } - - private void dblclickImpl(double x, double y, DblclickOptions options) { - ClickOptions clickOptions; - if (options == null) { - clickOptions = new ClickOptions(); - } else { - clickOptions = convertType(options, ClickOptions.class); - } - clickOptions.clickCount = 2; - click(x, y, clickOptions); + public void move(double x, double y, MoveOptions options) { + PageMouseMoveParams params = toProtocol(options, PageMouseMoveParams.class); + params.x = x; + params.y = y; + page.channel.mouseMove(params, NO_TIMEOUT); } @Override @@ -61,17 +52,34 @@ public void down(DownOptions options) { } @Override - public void move(double x, double y, MoveOptions options) { - PageMouseMoveParams params = toProtocol(options, PageMouseMoveParams.class); + public void up(UpOptions options) { + PageMouseUpParams params = toProtocol(options, PageMouseUpParams.class); + page.channel.mouseUp(params, NO_TIMEOUT); + } + + @Override + public void click(double x, double y, ClickOptions options) { + PageMouseClickParams params = toProtocol(options, PageMouseClickParams.class); params.x = x; params.y = y; - page.channel.mouseMove(params, NO_TIMEOUT); + page.channel.mouseClick(params, NO_TIMEOUT); } @Override - public void up(UpOptions options) { - PageMouseUpParams params = toProtocol(options, PageMouseUpParams.class); - page.channel.mouseUp(params, NO_TIMEOUT); + public void dblclick(double x, double y, DblclickOptions options) { + // java: @apiCall({ title: 'Double click' }) is wrapApiCall with the title. + wrapApiCall(() -> { + ClickOptions clickOptions; + if (options == null) { + // java: options is nullable, upstream defaults it to {}. + clickOptions = new ClickOptions(); + } else { + clickOptions = convertType(options, ClickOptions.class); + } + clickOptions.clickCount = 2; + click(x, y, clickOptions); + return null; + }, "Double click", false); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java index 1c78a8eb5..97e986886 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageAssertionsImpl.java @@ -22,7 +22,7 @@ import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.UrlMatcher.resolveUrl; +import static com.microsoft.playwright.impl.UrlMatcher.constructURLBasedOnBaseURL; import static com.microsoft.playwright.impl.Utils.convertType; public class PageAssertionsImpl extends AssertionsBase implements PageAssertions { @@ -61,7 +61,7 @@ public void hasTitle(Pattern pattern, HasTitleOptions options) { public void hasURL(String url, HasURLOptions options) { ExpectedTextValue expected = new ExpectedTextValue(); if (actualPage.context().baseUrl() != null) { - url = resolveUrl(actualPage.context().baseUrl(), url); + url = constructURLBasedOnBaseURL(actualPage.context().baseUrl().toString(), url); } expected.string = url; expected.ignoreCase = shouldIgnoreCase(options); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index ddee860e2..8f087424d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -14,88 +14,120 @@ * limitations under the License. */ +// Port of page.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.*; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.*; -import java.io.IOException; import java.nio.file.Path; -import java.util.*; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Serialization.parseError; -import static com.microsoft.playwright.impl.Utils.*; -import static com.microsoft.playwright.impl.Errors.isSafeCloseError; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.nio.file.Files.readAllBytes; -import static java.util.Arrays.asList; - +import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; +import static com.microsoft.playwright.impl.ClientHelper.initScriptSourceWithExposedFunctions; +import static com.microsoft.playwright.impl.Serialization.assertEvaluateOptions; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.trimStringWithEllipsis; +import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +import static com.microsoft.playwright.impl.Utils.toProtocol; public class PageImpl extends ChannelOwner implements Page { - final BrowserContextImpl browserContext; + final PageChannel channel = new PageChannel(this); + private final BrowserContextImpl browserContext; + BrowserContextImpl ownedContext; + String apiName = "Page"; + private final FrameImpl mainFrame; - final PageChannel channel; - private final KeyboardImpl keyboard; - private final MouseImpl mouse; - private final TouchscreenImpl touchscreen; - private final ScreencastImpl screencast; - private final WebStorageImpl localStorage; - private final WebStorageImpl sessionStorage; - final Waitable waitableClosedOrCrashed; - private ViewportSize viewport; - private final Router routes = new Router(); - private final WebSocketRouter webSocketRoutes = new WebSocketRouter(); private final Set frames = new LinkedHashSet<>(); - private final Map locatorHandlers = new HashMap<>(); + final Set workers = new LinkedHashSet<>(); + private boolean closed; + final LongStandingScope closedOrCrashedScope = new LongStandingScope(this); + private ViewportSize viewportSize; + List routes = new ArrayList<>(); + List webSocketRoutes = new ArrayList<>(); + + final Coverage coverage; + final KeyboardImpl keyboard; + final MouseImpl mouse; + final APIRequestContextImpl request; + final TouchscreenImpl touchscreen; + final ClockImpl clock; + final ScreencastImpl screencast; + final WebStorageImpl localStorage; + final WebStorageImpl sessionStorage; + final WebMCPImpl webmcp; + + final Map bindings = new LinkedHashMap<>(); + final TimeoutSettings timeoutSettings; + private final VideoImpl video; + final PageImpl opener; + private String closeReason; + boolean closeWasCalled; + private List harRouters = new ArrayList<>(); - private static class LocatorHandler { - private final Locator locator; - private final Consumer handler; - private Integer times; + private final Map locatorHandlers = new LinkedHashMap<>(); + private List evaluateCallbacks = new ArrayList<>(); - LocatorHandler(Locator locator, Consumer handler, Integer times) { - this.locator = locator; - this.handler = handler; - this.times = times; - } + // java: from and fromNullable are not ported, generated results already hold the impl object. - boolean call() { - if (shouldRemove()) { - return true; - } - if (times != null) { - --times; - } - handler.accept(locator); - return shouldRemove(); - } + PageImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + instrumentation.onPage(this); + PageInitializer pageInitializer = connection.protocolGson().fromJson(initializer, PageInitializer.class); + browserContext = (BrowserContextImpl) parent; + timeoutSettings = new TimeoutSettings(browserContext.timeoutSettings); + + keyboard = new KeyboardImpl(this); + mouse = new MouseImpl(this); + request = browserContext.request; + touchscreen = new TouchscreenImpl(this); + clock = browserContext.clock; + localStorage = new WebStorageImpl(this, "local"); + sessionStorage = new WebStorageImpl(this, "session"); - private boolean shouldRemove() { - return times != null && times == 0; + mainFrame = pageInitializer.mainFrame; + mainFrame.page = this; + webmcp = mainFrame.webmcp; + frames.add(mainFrame); + if (pageInitializer.viewportSize != null) { + viewportSize = new ViewportSize(pageInitializer.viewportSize.width, pageInitializer.viewportSize.height); } - } + closed = Boolean.TRUE.equals(pageInitializer.isClosed); + opener = pageInitializer.opener; + video = new VideoImpl(this, pageInitializer.video); + screencast = new ScreencastImpl(this); - final Map bindings = new HashMap<>(); - BrowserContextImpl ownedContext; - private boolean isClosed; - final Set workers = new HashSet<>(); - protected final TimeoutSettings timeoutSettings; - private VideoImpl video; - private final PageImpl opener; - private String closeReason; + coverage = new Coverage(channel); - PageImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - Map mapping = new HashMap<>(); + on(Events.Page.CLOSE, new Consumer() { + @Override + public void accept(Page page) { + off(Events.Page.CLOSE, this); + closedOrCrashedScope.close(closeErrorWithReason()); + } + }); + on(Events.Page.CRASH, new Consumer() { + @Override + public void accept(Page page) { + off(Events.Page.CRASH, this); + closedOrCrashedScope.close(new TargetClosedError()); + } + }); + + Map mapping = new LinkedHashMap<>(); mapping.put(Events.Page.CONSOLE, "console"); mapping.put(Events.Page.DIALOG, "dialog"); mapping.put(Events.Page.DIALOG_CLOSED, "dialogClosed"); @@ -105,438 +137,634 @@ private boolean shouldRemove() { mapping.put(Events.Page.REQUEST_FAILED, "requestFailed"); mapping.put(Events.Page.FILE_CHOOSER, "fileChooser"); setEventToSubscriptionMapping(mapping); - browserContext = (BrowserContextImpl) parent; - mainFrame = connection.getExistingObject(initializer.getAsJsonObject("mainFrame").get("guid").getAsString()); - mainFrame.page = this; - isClosed = initializer.get("isClosed").getAsBoolean(); - if (initializer.has("viewportSize")) { - viewport = gson().fromJson(initializer.get("viewportSize"), ViewportSize.class); + } + + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. + @Override + void handleEvent(String event, JsonObject params) { + switch (event) { + case "bindingCall": { + PageBindingCallEvent e = connection.protocolGson().fromJson(params, PageBindingCallEvent.class); + onBinding(e.binding); + break; + } + case "close": + onClose(); + break; + case "crash": + onCrash(); + break; + case "download": { + PageDownloadEvent e = connection.protocolGson().fromJson(params, PageDownloadEvent.class); + // java: DownloadImpl reads url and suggestedFilename from the event params. + DownloadImpl download = new DownloadImpl(this, e.artifact, params); + emit(Events.Page.DOWNLOAD, download); + browserContext.emit(Events.BrowserContext.DOWNLOAD, download); + break; + } + case "fileChooser": { + PageFileChooserEvent e = connection.protocolGson().fromJson(params, PageFileChooserEvent.class); + emit(Events.Page.FILE_CHOOSER, new FileChooserImpl(this, e.element, Boolean.TRUE.equals(e.isMultiple))); + break; + } + case "frameAttached": { + PageFrameAttachedEvent e = connection.protocolGson().fromJson(params, PageFrameAttachedEvent.class); + onFrameAttached(e.frame); + break; + } + case "frameDetached": { + PageFrameDetachedEvent e = connection.protocolGson().fromJson(params, PageFrameDetachedEvent.class); + onFrameDetached(e.frame); + break; + } + case "locatorHandlerTriggered": { + PageLocatorHandlerTriggeredEvent e = connection.protocolGson().fromJson(params, PageLocatorHandlerTriggeredEvent.class); + onLocatorHandlerTriggered(e.uid); + break; + } + case "route": { + PageRouteEvent e = connection.protocolGson().fromJson(params, PageRouteEvent.class); + onRoute(e.route); + break; + } + case "webSocketRoute": { + PageWebSocketRouteEvent e = connection.protocolGson().fromJson(params, PageWebSocketRouteEvent.class); + onWebSocketRoute(e.webSocketRoute); + break; + } + case "viewportSizeChanged": { + PageViewportSizeChangedEvent e = connection.protocolGson().fromJson(params, PageViewportSizeChangedEvent.class); + viewportSize = e.viewportSize == null ? null : new ViewportSize(e.viewportSize.width, e.viewportSize.height); + break; + } + case "webSocket": { + PageWebSocketEvent e = connection.protocolGson().fromJson(params, PageWebSocketEvent.class); + emit(Events.Page.WEB_SOCKET, e.webSocket); + break; + } + case "worker": { + PageWorkerEvent e = connection.protocolGson().fromJson(params, PageWorkerEvent.class); + onWorker(e.worker); + break; + } + // java: upstream's Screencast subscribes to the page channel itself. + case "screencastFrame": + screencast.handleScreencastFrame(params); + break; + default: + break; } - channel = new PageChannel(this); - keyboard = new KeyboardImpl(this); - mouse = new MouseImpl(this); - touchscreen = new TouchscreenImpl(this); - screencast = new ScreencastImpl(this); - localStorage = new WebStorageImpl(this, "local"); - sessionStorage = new WebStorageImpl(this, "session"); - frames.add(mainFrame); - timeoutSettings = new TimeoutSettings(browserContext.timeoutSettings); - waitableClosedOrCrashed = createWaitForCloseHelper(); - if (initializer.has("opener")) { - opener = connection.getExistingObject(initializer.getAsJsonObject("opener").get("guid").getAsString()); - } else { - opener = null; + } + + private void onFrameAttached(FrameImpl frame) { + frame.page = this; + frames.add(frame); + if (frame.parentFrame != null) { + frame.parentFrame.childFrames.add(frame); } - if (initializer.has("video")) { - String artifactGuid = initializer.getAsJsonObject("video").get("guid").getAsString(); - ArtifactImpl artifact = connection.getExistingObject(artifactGuid); - video = new VideoImpl(this, artifact); - } else { - video = new VideoImpl(this); - } - } - - @Override - protected void handleEvent(String event, JsonObject params) { - if ("worker".equals(event)) { - String guid = params.getAsJsonObject("worker").get("guid").getAsString(); - WorkerImpl worker = connection.getExistingObject(guid); - worker.page = this; - workers.add(worker); - emit(Events.Page.WORKER, worker); - } else if ("webSocket".equals(event)) { - String guid = params.getAsJsonObject("webSocket").get("guid").getAsString(); - WebSocketImpl webSocket = connection.getExistingObject(guid); - emit(Events.Page.WEB_SOCKET, webSocket); - } else if ("download".equals(event)) { - String artifactGuid = params.getAsJsonObject("artifact").get("guid").getAsString(); - ArtifactImpl artifact = connection.getExistingObject(artifactGuid); - DownloadImpl download = new DownloadImpl(this, artifact, params); - emit(Events.Page.DOWNLOAD, download); - browserContext.notifyDownload(download); - } else if ("fileChooser".equals(event)) { - String guid = params.getAsJsonObject("element").get("guid").getAsString(); - ElementHandleImpl elementHandle = connection.getExistingObject(guid); - FileChooser fileChooser = new FileChooserImpl(this, elementHandle, params.get("isMultiple").getAsBoolean()); - emit(Events.Page.FILE_CHOOSER, fileChooser); - } else if ("bindingCall".equals(event)) { - String guid = params.getAsJsonObject("binding").get("guid").getAsString(); - BindingCall bindingCall = connection.getExistingObject(guid); - BindingCallback binding = bindings.get(bindingCall.name()); - if (binding == null) { - binding = browserContext.bindings.get(bindingCall.name()); + emit(Events.Page.FRAME_ATTACHED, frame); + browserContext.emit(Events.BrowserContext.FRAME_ATTACHED, frame); + } + + private void onFrameDetached(FrameImpl frame) { + frames.remove(frame); + frame.detached = true; + if (frame.parentFrame != null) { + frame.parentFrame.childFrames.remove(frame); + } + emit(Events.Page.FRAME_DETACHED, frame); + browserContext.emit(Events.BrowserContext.FRAME_DETACHED, frame); + } + + private void onRoute(RouteImpl route) { + route.context = context(); + List routeHandlers = routes; + for (RouteHandler routeHandler : new ArrayList<>(routeHandlers)) { + // If the page was closed we stall all requests right away. + if (closeWasCalled || browserContext.isClosed()) { + return; } - if (binding != null) { - try { - bindingCall.call(binding); - } catch (RuntimeException e) { - if (!isSafeCloseError(e.getMessage())) { - logWithTimestamp(e.getMessage()); - } - } + if (!routeHandler.matches(route.request().url())) { + continue; } - } else if ("frameAttached".equals(event)) { - String guid = params.getAsJsonObject("frame").get("guid").getAsString(); - FrameImpl frame = connection.getExistingObject(guid); - frames.add(frame); - frame.page = this; - if (frame.parentFrame != null) { - frame.parentFrame.childFrames.add(frame); + int index = routes.indexOf(routeHandler); + if (index == -1) { + continue; } - emit(Events.Page.FRAME_ATTACHED, frame); - browserContext.notifyFrameAttached(frame); - } else if ("frameDetached".equals(event)) { - String guid = params.getAsJsonObject("frame").get("guid").getAsString(); - FrameImpl frame = connection.getExistingObject(guid); - frames.remove(frame); - frame.isDetached = true; - if (frame.parentFrame != null) { - frame.parentFrame.childFrames.remove(frame); + if (routeHandler.willExpire()) { + routes.remove(index); } - emit(Events.Page.FRAME_DETACHED, frame); - browserContext.notifyFrameDetached(frame); - } else if ("locatorHandlerTriggered".equals(event)) { - int uid = params.get("uid").getAsInt(); - onLocatorHandlerTriggered(uid); - } else if ("route".equals(event)) { - RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString()); - route.browserContext = browserContext; - Router.HandleResult handled = routes.handle(route); - if (handled != Router.HandleResult.NoMatchingHandler) { + boolean handled = routeHandler.handle(route); + // unrouteAll() replaces _routes and updates interception after waiting for handlers. + if (routeHandlers == routes && routes.isEmpty()) { try { - updateInterceptionPatterns(); + disableInterception(); } catch (PlaywrightException e) { - // Like the Node.js client, ignore the error when the page or the context was closed meanwhile. - if (!isSafeCloseError(e)) { - throw e; - } } } - if (handled == Router.HandleResult.NoMatchingHandler || handled == Router.HandleResult.Fallback) { - browserContext.handleRoute(route); + if (handled) { + return; } - } else if ("webSocketRoute".equals(event)) { - WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString()); - if (!webSocketRoutes.handle(route)) { - browserContext.handleWebSocketRoute(route); + } + + browserContext.onRoute(route); + } + + private void onWebSocketRoute(WebSocketRouteImpl webSocketRoute) { + WebSocketRouteHandler routeHandler = null; + for (WebSocketRouteHandler route : webSocketRoutes) { + if (route.matches(webSocketRoute.url())) { + routeHandler = route; + break; } - } else if ("crash".equals(event)) { - emit(Events.Page.CRASH, this); - } else if ("close".equals(event)) { - didClose(); - } else if ("screencastFrame".equals(event)) { - screencast.handleScreencastFrame(params); + } + if (routeHandler != null) { + routeHandler.handle(webSocketRoute); + } else { + browserContext.onWebSocketRoute(webSocketRoute); } } - void notifyPopup(PageImpl popup) { - emit(Events.Page.POPUP, popup); + void onBinding(BindingCall bindingCall) { + BindingCallback func = bindings.get(bindingCall.bindingCallInitializer.name); + if (func != null) { + bindingCall.call(func); + return; + } + browserContext.onBinding(bindingCall); } - void didClose() { - isClosed = true; + void onWorker(WorkerImpl worker) { + workers.add(worker); + worker.page = this; + emit(Events.Page.WORKER, worker); + } + + void onClose() { + closed = true; browserContext.pages.remove(this); + disposeHarRouters(); emit(Events.Page.CLOSE, this); - browserContext.notifyPageClose(this); + browserContext.emit(Events.BrowserContext.PAGE_CLOSE, this); } - private String effectiveCloseReason() { - if (closeReason != null) { - return closeReason; + private void onCrash() { + emit(Events.Page.CRASH, this); + } + + @Override + public BrowserContextImpl context() { + return browserContext; + } + + @Override + public PageImpl opener() { + if (opener == null || opener.isClosed()) { + return null; } - return browserContext.effectiveCloseReason(); + return opener; } - TargetClosedError closeErrorWithReason() { - return new TargetClosedError(effectiveCloseReason()); + @Override + public FrameImpl mainFrame() { + return mainFrame; } @Override - public void onClose(Consumer handler) { - on(Events.Page.CLOSE, handler); + public Frame frame(String name) { + return frame(name, null); } @Override - public void offClose(Consumer handler) { - off(Events.Page.CLOSE, handler); + public Frame frameByUrl(String url) { + return frame(null, UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false)); } @Override - public void onConsoleMessage(Consumer handler) { - on(Events.Page.CONSOLE, handler); + public Frame frameByUrl(Pattern url) { + return frame(null, new UrlMatcher(url)); } @Override - public void offConsoleMessage(Consumer handler) { - off(Events.Page.CONSOLE, handler); + public Frame frameByUrl(Predicate url) { + return frame(null, new UrlMatcher(url)); + } + + // java: frameSelector is a name or { name, url }; the Java API has frame(name) and frameByUrl(url). + private Frame frame(String name, UrlMatcher url) { + if ((name == null || name.isEmpty()) && url == null) { + throw new PlaywrightException("Either name or url matcher should be specified"); + } + for (Frame f : frames()) { + if (name != null && !name.isEmpty() ? f.name().equals(name) : url.test(f.url())) { + return f; + } + } + return null; } @Override - public void onCrash(Consumer handler) { - on(Events.Page.CRASH, handler); + public List frames() { + return new ArrayList<>(frames); } @Override - public void offCrash(Consumer handler) { - off(Events.Page.CRASH, handler); + public void setDefaultNavigationTimeout(double timeout) { + timeoutSettings.setDefaultNavigationTimeout(timeout); } @Override - public void onDialog(Consumer

handler) { - on(Events.Page.DIALOG, handler); + public void setDefaultTimeout(double timeout) { + timeoutSettings.setDefaultTimeout(timeout); } @Override - public void offDialog(Consumer handler) { - off(Events.Page.DIALOG, handler); + public VideoImpl video() { + // Note: we are creating Video object lazily, because we do not know + // BrowserContextOptions when constructing the page - it is assigned + // too late during launchPersistentContext. + if (browserContext.options.recordVideo == null) { + return null; + } + return video; } @Override - public void onDialogClosed(Consumer handler) { - on(Events.Page.DIALOG_CLOSED, handler); + public Locator pickLocator() { + PagePickLocatorResult result = channel.pickLocator(NO_TIMEOUT); + return locator(result.selector); } @Override - public void offDialogClosed(Consumer handler) { - off(Events.Page.DIALOG_CLOSED, handler); + public void cancelPickLocator() { + channel.cancelPickLocator(NO_TIMEOUT); } @Override - public void onDOMContentLoaded(Consumer handler) { - on(Events.Page.DOM_CONTENT_LOADED, handler); + public void hideHighlight() { + channel.hideHighlight(NO_TIMEOUT); } @Override - public void offDOMContentLoaded(Consumer handler) { - off(Events.Page.DOM_CONTENT_LOADED, handler); + public ElementHandle querySelector(String selector, QuerySelectorOptions options) { + return mainFrame.querySelector(selector, convertType(options, Frame.QuerySelectorOptions.class)); } @Override - public void onDownload(Consumer handler) { - on(Events.Page.DOWNLOAD, handler); + public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { + return mainFrame.waitForSelector(selector, convertType(options, Frame.WaitForSelectorOptions.class)); } @Override - public void offDownload(Consumer handler) { - off(Events.Page.DOWNLOAD, handler); + public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { + mainFrame.dispatchEvent(selector, type, eventInit, convertType(options, Frame.DispatchEventOptions.class)); } @Override - public void onFileChooser(Consumer handler) { - on(Events.Page.FILE_CHOOSER, handler); + public JSHandle evaluateHandle(String expression, Object arg) { + return evaluateHandle(expression, arg, null); } + // java: the public API has no evaluate options, so the options overload is package-private. assertMaxArguments is + // a JS typing check. + JSHandle evaluateHandle(String expression, Object arg, Serialization.EvaluateOptions options) { + return mainFrame.evaluateHandle(expression, arg, options); + } + + // java: assertMaxArguments is a JS typing check. @Override - public void offFileChooser(Consumer handler) { - off(Events.Page.FILE_CHOOSER, handler); + public Object evalOnSelector(String selector, String expression, Object arg, EvalOnSelectorOptions options) { + return mainFrame.evalOnSelector(selector, expression, arg, convertType(options, Frame.EvalOnSelectorOptions.class)); } + // java: assertMaxArguments is a JS typing check. @Override - public void onFrameAttached(Consumer handler) { - on(Events.Page.FRAME_ATTACHED, handler); + public Object evalOnSelectorAll(String selector, String expression, Object arg) { + return mainFrame.evalOnSelectorAll(selector, expression, arg); } @Override - public void offFrameAttached(Consumer handler) { - off(Events.Page.FRAME_ATTACHED, handler); + public List querySelectorAll(String selector) { + return mainFrame.querySelectorAll(selector); } @Override - public void onFrameDetached(Consumer handler) { - on(Events.Page.FRAME_DETACHED, handler); + public ElementHandle addScriptTag(AddScriptTagOptions options) { + return mainFrame.addScriptTag(convertType(options, Frame.AddScriptTagOptions.class)); } @Override - public void offFrameDetached(Consumer handler) { - off(Events.Page.FRAME_DETACHED, handler); + public ElementHandle addStyleTag(AddStyleTagOptions options) { + return mainFrame.addStyleTag(convertType(options, Frame.AddStyleTagOptions.class)); } @Override - public void onFrameNavigated(Consumer handler) { - on(Events.Page.FRAME_NAVIGATED, handler); + public AutoCloseable exposeFunction(String name, FunctionCallback callback) { + PageExposeBindingParams params = new PageExposeBindingParams(); + params.name = name; + PageExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + BindingCallback binding = (source, args) -> callback.call(args); + bindings.put(name, binding); + return result.disposable; } @Override - public void offFrameNavigated(Consumer handler) { - off(Events.Page.FRAME_NAVIGATED, handler); + public AutoCloseable exposeBinding(String name, BindingCallback callback) { + PageExposeBindingParams params = new PageExposeBindingParams(); + params.name = name; + PageExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + bindings.put(name, callback); + return result.disposable; + } + + // java: the callback Function is a FunctionCallback. + DisposableObject exposeCallbackBinding(String name, FunctionCallback callback) { + bindings.put(name, (source, args) -> callback.call(args)); + PageExposeBindingParams params = new PageExposeBindingParams(); + params.name = name; + params.noGlobal = true; + PageExposeBindingResult result = channel.exposeBinding(params, NO_TIMEOUT); + return result.disposable; + } + + void exposeEvaluateCallback(String name, FunctionCallback callback) { + DisposableObject disposable = exposeCallbackBinding(name, callback); + evaluateCallbacks.add(new ExposedCallback(name, disposable)); + } + + void eraseEvaluateCallbacks() { + for (ExposedCallback callback : evaluateCallbacks) { + bindings.remove(callback.name); + // java: dispose() is not awaited upstream; sendMessageAsync does not pump. + try { + callback.disposable.sendMessageAsync("dispose"); + } catch (PlaywrightException e) { + } + } + evaluateCallbacks = new ArrayList<>(); } @Override - public void onLoad(Consumer handler) { - on(Events.Page.LOAD, handler); + public void setExtraHTTPHeaders(Map headers) { + RawHeaders.validateHeaders(headers); + PageSetExtraHTTPHeadersParams params = new PageSetExtraHTTPHeadersParams(); + params.headers = Headers.headersObjectToArray(headers); + channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @Override - public void offLoad(Consumer handler) { - off(Events.Page.LOAD, handler); + public String url() { + return mainFrame.url(); } @Override - public void onPageError(Consumer handler) { - on(Events.Page.PAGE_ERROR, handler); + public String content(ContentOptions options) { + return mainFrame.content(convertType(options, Frame.ContentOptions.class)); } @Override - public void offPageError(Consumer handler) { - off(Events.Page.PAGE_ERROR, handler); + public void setContent(String html, SetContentOptions options) { + mainFrame.setContent(html, convertType(options, Frame.SetContentOptions.class)); } @Override - public void onPopup(Consumer handler) { - on(Events.Page.POPUP, handler); + public Response navigate(String url, NavigateOptions options) { + return mainFrame.navigate(url, convertType(options, Frame.NavigateOptions.class)); } @Override - public void offPopup(Consumer handler) { - off(Events.Page.POPUP, handler); + public Response reload(ReloadOptions options) { + if (options == null) { + options = new ReloadOptions(); + } + PageReloadParams params = toProtocol(options, PageReloadParams.class); + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); + return channel.reload(params, timeoutSettings.navigationTimeout(options.timeout)).response; } @Override - public void onRequest(Consumer handler) { - on(Events.Page.REQUEST, handler); + public void addLocatorHandler(Locator locator, Consumer handler, AddLocatorHandlerOptions options) { + if (options == null) { + options = new AddLocatorHandlerOptions(); + } + LocatorImpl locatorImpl = (LocatorImpl) locator; + if (locatorImpl.frame != mainFrame) { + throw new PlaywrightException("Locator must belong to the main frame of this page"); + } + if (options.times != null && options.times == 0) { + return; + } + PageRegisterLocatorHandlerParams params = new PageRegisterLocatorHandlerParams(); + params.selector = locatorImpl.selector; + params.noWaitAfter = options.noWaitAfter; + int uid = channel.registerLocatorHandler(params, NO_TIMEOUT).uid; + locatorHandlers.put(uid, new LocatorHandler(locatorImpl, handler, options.times)); + } + + private void onLocatorHandlerTriggered(int uid) { + boolean remove = false; + try { + LocatorHandler handler = locatorHandlers.get(uid); + if (handler != null && !Integer.valueOf(0).equals(handler.times)) { + if (handler.times != null) { + handler.times--; + } + handler.handler.accept(handler.locator); + } + remove = handler != null && Integer.valueOf(0).equals(handler.times); + } finally { + if (remove) { + locatorHandlers.remove(uid); + } + PageResolveLocatorHandlerNoReplyParams params = new PageResolveLocatorHandlerNoReplyParams(); + params.uid = uid; + params.remove = remove; + // java: the call is not awaited upstream; sendMessageAsync does not pump. + try { + sendMessageAsync("resolveLocatorHandlerNoReply", params); + } catch (PlaywrightException e) { + } + } } @Override - public void offRequest(Consumer handler) { - off(Events.Page.REQUEST, handler); + public void removeLocatorHandler(Locator locator) { + for (Map.Entry entry : new ArrayList<>(locatorHandlers.entrySet())) { + if (entry.getValue().locator.equals(locator)) { + locatorHandlers.remove(entry.getKey()); + PageUnregisterLocatorHandlerParams params = new PageUnregisterLocatorHandlerParams(); + params.uid = entry.getKey(); + try { + channel.unregisterLocatorHandler(params, NO_TIMEOUT); + } catch (PlaywrightException e) { + } + } + } } @Override - public void onRequestFailed(Consumer handler) { - on(Events.Page.REQUEST_FAILED, handler); + public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { + mainFrame.waitForLoadState(state, convertType(options, Frame.WaitForLoadStateOptions.class)); } @Override - public void offRequestFailed(Consumer handler) { - off(Events.Page.REQUEST_FAILED, handler); + public Response waitForNavigation(WaitForNavigationOptions options, Runnable callback) { + return mainFrame.waitForNavigation(convertType(options, Frame.WaitForNavigationOptions.class), callback); } @Override - public void onRequestFinished(Consumer handler) { - on(Events.Page.REQUEST_FINISHED, handler); + public void waitForURL(String url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override - public void offRequestFinished(Consumer handler) { - off(Events.Page.REQUEST_FINISHED, handler); + public void waitForURL(Pattern url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override - public void onResponse(Consumer handler) { - on(Events.Page.RESPONSE, handler); + public void waitForURL(Predicate url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override - public void offResponse(Consumer handler) { - off(Events.Page.RESPONSE, handler); + public Request waitForRequest(String urlOrPredicate, WaitForRequestOptions options, Runnable callback) { + return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlOrPredicate, connection.localUtils(), false), null, trimUrl(urlOrPredicate), options, callback); } @Override - public void onWebSocket(Consumer handler) { - on(Events.Page.WEB_SOCKET, handler); + public Request waitForRequest(Pattern urlOrPredicate, WaitForRequestOptions options, Runnable callback) { + return waitForRequest(new UrlMatcher(urlOrPredicate), null, trimUrl(urlOrPredicate), options, callback); } @Override - public void offWebSocket(Consumer handler) { - off(Events.Page.WEB_SOCKET, handler); + public Request waitForRequest(Predicate urlOrPredicate, WaitForRequestOptions options, Runnable callback) { + return waitForRequest(null, urlOrPredicate, null, options, callback); + } + + // java: the url matcher or the predicate of urlOrPredicate, with trimUrl(urlOrPredicate) computed by the overload; + // no signal (AbortSignal). No @apiCall() zone around the waits: the callback runs inside the wait and its calls + // would join that zone. + private Request waitForRequest(UrlMatcher urlMatcher, Predicate urlOrPredicate, String trimmedUrl, WaitForRequestOptions options, Runnable callback) { + if (options == null) { + options = new WaitForRequestOptions(); + } + Double timeout = options.timeout; + Predicate predicate = request -> { + if (urlMatcher != null) { + return urlMatcher.test(request.url()); + } + return urlOrPredicate.test(request); + }; + String logLine = trimmedUrl != null ? "waiting for request " + trimmedUrl : null; + return waitForEvent(Events.Page.REQUEST, predicate, timeout, logLine, callback); } @Override - public void onWorker(Consumer handler) { - on(Events.Page.WORKER, handler); + public Response waitForResponse(String urlOrPredicate, WaitForResponseOptions options, Runnable callback) { + return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlOrPredicate, connection.localUtils(), false), null, trimUrl(urlOrPredicate), options, callback); } @Override - public void offWorker(Consumer handler) { - off(Events.Page.WORKER, handler); + public Response waitForResponse(Pattern urlOrPredicate, WaitForResponseOptions options, Runnable callback) { + return waitForResponse(new UrlMatcher(urlOrPredicate), null, trimUrl(urlOrPredicate), options, callback); } @Override - public ClockImpl clock() { - return browserContext.clock(); + public Response waitForResponse(Predicate urlOrPredicate, WaitForResponseOptions options, Runnable callback) { + return waitForResponse(null, urlOrPredicate, null, options, callback); + } + + private Response waitForResponse(UrlMatcher urlMatcher, Predicate urlOrPredicate, String trimmedUrl, WaitForResponseOptions options, Runnable callback) { + if (options == null) { + options = new WaitForResponseOptions(); + } + Double timeout = options.timeout; + Predicate predicate = response -> { + if (urlMatcher != null) { + return urlMatcher.test(response.url()); + } + return urlOrPredicate.test(response); + }; + String logLine = trimmedUrl != null ? "waiting for response " + trimmedUrl : null; + return waitForEvent(Events.Page.RESPONSE, predicate, timeout, logLine, callback); + } + + // java: waitForEvent(event) is one typed waitForX(options, callback) per event. + private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable callback) { + return waitForEvent(event, predicate, timeout, "waiting for event \"" + event + "\"", callback); } @Override - public Page waitForClose(WaitForCloseOptions options, Runnable code) { + public Page waitForClose(WaitForCloseOptions options, Runnable callback) { if (options == null) { options = new WaitForCloseOptions(); } - return waitForEvent(Events.Page.CLOSE, null, options.timeout, "waiting for event \"close\"", code); + return waitForEvent(Events.Page.CLOSE, null, options.timeout, callback); } @Override - public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { + public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable callback) { if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEvent(Events.Page.CONSOLE, options.predicate, options.timeout, "waiting for event \"console\"", code); + return waitForEvent(Events.Page.CONSOLE, options.predicate, options.timeout, callback); } @Override - public Download waitForDownload(WaitForDownloadOptions options, Runnable code) { + public Download waitForDownload(WaitForDownloadOptions options, Runnable callback) { if (options == null) { options = new WaitForDownloadOptions(); } - return waitForEvent(Events.Page.DOWNLOAD, options.predicate, options.timeout, "waiting for event \"download\"", code); + return waitForEvent(Events.Page.DOWNLOAD, options.predicate, options.timeout, callback); } @Override - public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable code) { - // TODO: enable/disable file chooser interception + public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable callback) { if (options == null) { options = new WaitForFileChooserOptions(); } - return waitForEvent(Events.Page.FILE_CHOOSER, options.predicate, options.timeout, "waiting for event \"filechooser\"", code); + return waitForEvent(Events.Page.FILE_CHOOSER, options.predicate, options.timeout, callback); } @Override - public Page waitForPopup(WaitForPopupOptions options, Runnable code) { + public Page waitForPopup(WaitForPopupOptions options, Runnable callback) { if (options == null) { options = new WaitForPopupOptions(); } - return waitForEvent(Events.Page.POPUP, options.predicate, options.timeout, "waiting for event \"popup\"", code); + return waitForEvent(Events.Page.POPUP, options.predicate, options.timeout, callback); } @Override - public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable code) { + public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Runnable callback) { if (options == null) { - options = new WaitForWebSocketOptions(); + options = new WaitForRequestFinishedOptions(); } - return waitForEvent(Events.Page.WEB_SOCKET, options.predicate, options.timeout, "waiting for event \"websocket\"", code); + return waitForEvent(Events.Page.REQUEST_FINISHED, options.predicate, options.timeout, callback); } @Override - public Worker waitForWorker(WaitForWorkerOptions options, Runnable code) { + public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable callback) { if (options == null) { - options = new WaitForWorkerOptions(); + options = new WaitForWebSocketOptions(); } - return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, "waiting for event \"worker\"", code); + return waitForEvent(Events.Page.WEB_SOCKET, options.predicate, options.timeout, callback); } - private static String trimUrl(Object param) { - if (param instanceof Pattern) { - Pattern pattern = (Pattern) param; - return "/" + trimStringWithEllipsis(pattern.pattern(), 50) + "/" + Utils.toJsRegexFlags(pattern); - } - if (param instanceof String) { - return "\"" + trimStringWithEllipsis((String) param, 50) + "\""; + @Override + public Worker waitForWorker(WaitForWorkerOptions options, Runnable callback) { + if (options == null) { + options = new WaitForWorkerOptions(); } - return null; + return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, callback); } - private static String trimStringWithEllipsis(String input, int cap) { - if (input.length() <= cap) { - return input; - } - int[] chars = input.codePoints().toArray(); - if (chars.length > cap) { - return new String(chars, 0, cap - 1) + "\u2026"; - } - return input; + TargetClosedError closeErrorWithReason() { + return new TargetClosedError(closeReason != null ? closeReason : browserContext.effectiveCloseReason()); } - // _waitForEvent in page.ts - private T waitForEvent(String event, Predicate predicate, Double timeout, String logLine, Runnable code) { + // java: the predicate and timeout are passed separately and the code to run is a Runnable. + private T waitForEvent(String event, Predicate predicate, Double timeout, String logLine, Runnable callback) { double timeoutMs = timeoutSettings.timeout(timeout); Waiter waiter = Waiter.createForEvent(this, event); if (logLine != null) { @@ -549,238 +777,385 @@ private T waitForEvent(String event, Predicate predicate, Double timeout, if (!Events.Page.CLOSE.equals(event)) { waiter.rejectOnEvent(this, Events.Page.CLOSE, () -> closeErrorWithReason()); } - T result = waiter.waitForEvent(this, event, predicate, code); + T result = waiter.waitForEvent(this, event, predicate, callback); waiter.dispose(); return result; } @Override - public void close(CloseOptions options) { + public Response goBack(GoBackOptions options) { if (options == null) { - options = new CloseOptions(); + options = new GoBackOptions(); } - closeReason = options.reason; - try { - if (ownedContext != null) { - ownedContext.close(); - } else if (options.runBeforeUnload != null && options.runBeforeUnload) { - channel.runBeforeUnload(NO_TIMEOUT); - } else { - PageCloseParams params = new PageCloseParams(); - params.reason = options.reason; - channel.close(params, NO_TIMEOUT); - } - } catch (PlaywrightException exception) { - if (isSafeCloseError(exception) && (options.runBeforeUnload == null || !options.runBeforeUnload)) { - return; - } - throw exception; + PageGoBackParams params = toProtocol(options, PageGoBackParams.class); + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); + return channel.goBack(params, timeoutSettings.navigationTimeout(options.timeout)).response; + } + + @Override + public Response goForward(GoForwardOptions options) { + if (options == null) { + options = new GoForwardOptions(); } + PageGoForwardParams params = toProtocol(options, PageGoForwardParams.class); + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); + return channel.goForward(params, timeoutSettings.navigationTimeout(options.timeout)).response; } @Override - public ElementHandle querySelector(String selector, QuerySelectorOptions options) { - return mainFrame.querySelector( - selector, convertType(options, Frame.QuerySelectorOptions.class)); + public void requestGC() { + channel.requestGC(NO_TIMEOUT); } @Override - public List querySelectorAll(String selector) { - return mainFrame.querySelectorAll(selector); + public void emulateMedia(EmulateMediaOptions options) { + // java: an empty Optional is serialized as 'no-override', a null field is left out. + PageEmulateMediaParams params = toProtocol(options, PageEmulateMediaParams.class); + channel.emulateMedia(params, NO_TIMEOUT); } @Override - public List requests() { - PageRequestsResult json = channel.requests(NO_TIMEOUT); - return new ArrayList(json.requests); + public void setViewportSize(int width, int height) { + viewportSize = new ViewportSize(width, height); + PageSetViewportSizeParams params = new PageSetViewportSizeParams(); + params.viewportSize = new PageSetViewportSizeParams.PageSetViewportSizeParamsViewportSize(); + params.viewportSize.width = width; + params.viewportSize.height = height; + channel.setViewportSize(params, NO_TIMEOUT); } @Override - public void addLocatorHandler(Locator locator, Consumer handler, AddLocatorHandlerOptions options) { - LocatorImpl locatorImpl = (LocatorImpl) locator; - if (locatorImpl.frame != mainFrame) { - throw new PlaywrightException("Locator must belong to the main frame of this page"); - } - if (options == null) { - options = new AddLocatorHandlerOptions(); - } - if (options.times != null && options.times == 0) { - return; - } - AddLocatorHandlerOptions finalOptions = options; - PageRegisterLocatorHandlerParams params = new PageRegisterLocatorHandlerParams(); - params.selector = locatorImpl.selector; - if (finalOptions.noWaitAfter != null && finalOptions.noWaitAfter) { - params.noWaitAfter = true; - } - PageRegisterLocatorHandlerResult json = channel.registerLocatorHandler(params, NO_TIMEOUT); - int uid = json.uid; - locatorHandlers.put(uid, new LocatorHandler(locator, handler, finalOptions.times)); + public ViewportSize viewportSize() { + return viewportSize; } @Override - public void removeLocatorHandler(Locator locator) { - for (Map.Entry entry: locatorHandlers.entrySet()) { - if (entry.getValue().locator.equals(locator)) { - locatorHandlers.remove(locator); - PageUnregisterLocatorHandlerParams params = new PageUnregisterLocatorHandlerParams(); - params.uid = entry.getKey(); - try { - channel.unregisterLocatorHandler(params, NO_TIMEOUT); - } catch (PlaywrightException e) { - } - } - } + public Object evaluate(String expression, Object arg) { + return evaluate(expression, arg, null); } - private void onLocatorHandlerTriggered(int uid) { - boolean remove = false; - try { - LocatorHandler handler = locatorHandlers.get(uid); - remove = handler != null && handler.call(); - } finally { - if (remove) { - locatorHandlers.remove(uid); - } - PageResolveLocatorHandlerNoReplyParams params = new PageResolveLocatorHandlerNoReplyParams(); - params.uid = uid; - params.remove = remove; - sendMessageAsync("resolveLocatorHandlerNoReply", params); + // java: the public API has no evaluate options, so the options overload is package-private. assertMaxArguments is + // a JS typing check. + Object evaluate(String expression, Object arg, Serialization.EvaluateOptions options) { + return mainFrame.evaluate(expression, arg, options); + } + + // java: the script is a String or a Path, the Java API has no arg and no options. + @Override + public AutoCloseable addInitScript(String script) { + return addInitScript(script, null, null); + } + + @Override + public AutoCloseable addInitScript(Path script) { + return addInitScript(script, null, null); + } + + // java: the core of the String and Path overloads, package-private. evaluationScript takes no arg: a Java script + // is not a function. + AutoCloseable addInitScript(Object script, Object arg, Serialization.ExposeFunctionsOptions options) { + assertEvaluateOptions(options); + if (options != null && Boolean.TRUE.equals(options.exposeFunctions)) { + return addInitScriptWithExposedFunctions(this, script, arg); } + String source = evaluationScript(script, true); + PageAddInitScriptParams params = new PageAddInitScriptParams(); + params.source = source; + return channel.addInitScript(params, NO_TIMEOUT).disposable; } @Override - public String ariaSnapshot(AriaSnapshotOptions options) { + public AutoCloseable route(String url, Consumer handler, RouteOptions options) { + return route(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false), handler, options); + } + + @Override + public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { + return route(new UrlMatcher(url), handler, options); + } + + @Override + public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { + return route(new UrlMatcher(url), handler, options); + } + + private AutoCloseable route(UrlMatcher url, Consumer handler, RouteOptions options) { + Integer times = options == null ? null : options.times; + return withTitle("Route requests", () -> { + routes.add(0, new RouteHandler(browserContext.options.baseURL, url, handler, times)); + updateInterceptionPatterns(); + return new DisposableStub(() -> unroute(url, handler)); + }); + } + + @Override + public void routeFromHAR(Path har, RouteFromHAROptions options) { if (options == null) { - options = new AriaSnapshotOptions(); + options = new RouteFromHAROptions(); + } + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Route from har is not supported in thin clients"); + } + if (Boolean.TRUE.equals(options.update)) { + browserContext.tracing.recordIntoHAR(har, this, options.url, convertType(options.updateContent, HarContentPolicy.class), options.updateMode, null); + return; } - FrameAriaSnapshotParams params = toProtocol(options, FrameAriaSnapshotParams.class); - return mainFrame.channel.ariaSnapshot(params, mainFrame.timeout(options.timeout)).snapshot; + HarRouter harRouter = HarRouter.create(localUtils, har, options.notFound != null ? options.notFound : HarNotFound.ABORT, options.url); + harRouters.add(harRouter); + harRouter.addPageRoute(this); } @Override - public Object evalOnSelector(String selector, String pageFunction, Object arg, EvalOnSelectorOptions options) { - return mainFrame.evalOnSelectorImpl( - selector, pageFunction, arg, convertType(options, Frame.EvalOnSelectorOptions.class)); + public void routeWebSocket(String url, Consumer handler) { + routeWebSocket(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), true), handler); } @Override - public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { - return mainFrame.evalOnSelectorAllImpl(selector, pageFunction, arg); + public void routeWebSocket(Pattern url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); } @Override - public AutoCloseable addInitScript(String script) { - return addInitScriptImpl(script); + public void routeWebSocket(Predicate url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); } - @Override - public AutoCloseable addInitScript(Path path) { - try { - byte[] bytes = readAllBytes(path); - String script = addSourceUrlToScript(new String(bytes, UTF_8), path); - return addInitScriptImpl(script); - } catch (IOException e) { - throw new PlaywrightException("Failed to read script from file", e); + private void routeWebSocket(UrlMatcher url, Consumer handler) { + withTitle("Route WebSockets", () -> { + webSocketRoutes.add(0, new WebSocketRouteHandler(browserContext.options.baseURL, url, handler)); + updateWebSocketInterceptionPatterns(); + }); + } + + private void disposeHarRouters() { + for (HarRouter router : harRouters) { + router.dispose(); } + harRouters = new ArrayList<>(); } - private AutoCloseable addInitScriptImpl(String script) { - PageAddInitScriptParams params = new PageAddInitScriptParams(); - params.source = script; - return channel.addInitScript(params, NO_TIMEOUT).disposable; + // java: the Java API has no behavior option, unrouteAll() passes none. + @Override + public void unrouteAll() { + withTitle("Unroute requests", () -> { + unrouteInternal(routes, new ArrayList<>(), null); + disposeHarRouters(); + }); } @Override - public ElementHandle addScriptTag(AddScriptTagOptions options) { - return mainFrame.addScriptTagImpl(convertType(options, Frame.AddScriptTagOptions.class)); + public void unroute(String url, Consumer handler) { + unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false), handler); } @Override - public ElementHandle addStyleTag(AddStyleTagOptions options) { - return mainFrame.addStyleTagImpl(convertType(options, Frame.AddStyleTagOptions.class)); + public void unroute(Pattern url, Consumer handler) { + unroute(new UrlMatcher(url), handler); } @Override - public void bringToFront() { - channel.bringToFront(NO_TIMEOUT); + public void unroute(Predicate url, Consumer handler) { + unroute(new UrlMatcher(url), handler); + } + + private void unroute(UrlMatcher url, Consumer handler) { + withTitle("Unroute requests", () -> { + List removed = new ArrayList<>(); + List remaining = new ArrayList<>(); + for (RouteHandler route : routes) { + if (route.url.equals(url) && (handler == null || route.handler == handler)) { + removed.add(route); + } else { + remaining.add(route); + } + } + unrouteInternal(removed, remaining, "default"); + }); } - @Override - public void check(String selector, CheckOptions options) { - mainFrame.check(selector, convertType(options, Frame.CheckOptions.class)); + private void unrouteInternal(List removed, List remaining, String behavior) { + routes = remaining; + if (behavior != null && !"default".equals(behavior)) { + // java: Promise.all over the removed handlers is a loop, each stop() returns when done. + for (RouteHandler routeHandler : removed) { + routeHandler.stop(behavior); + } + } + updateInterceptionPatterns(); } - @Override - public void click(String selector, ClickOptions options) { - mainFrame.clickImpl(selector, convertType(options, Frame.ClickOptions.class), null); + private void disableInterception() { + wrapApiCall(() -> updateInterceptionPatterns(), null, true); } - @Override - public String content(ContentOptions options) { - return mainFrame.content(convertType(options, Frame.ContentOptions.class)); + private void updateInterceptionPatterns() { + PageSetNetworkInterceptionPatternsParams params = new PageSetNetworkInterceptionPatternsParams(); + params.patterns = RouteHandler.prepareInterceptionPatterns(routes); + channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); } - @Override - public BrowserContextImpl context() { - return browserContext; + private void updateWebSocketInterceptionPatterns() { + PageSetWebSocketInterceptionPatternsParams params = new PageSetWebSocketInterceptionPatternsParams(); + params.patterns = WebSocketRouteHandler.prepareInterceptionPatterns(webSocketRoutes); + channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); } @Override - public void dblclick(String selector, DblclickOptions options) { - mainFrame.dblclickImpl(selector, convertType(options, Frame.DblclickOptions.class), null); + public byte[] screenshot(ScreenshotOptions options) { + if (options == null) { + options = new ScreenshotOptions(); + } + List mask = options.mask; + // java: { ...options, mask: undefined } is a shallow copy of the options without the mask, as params. + ScreenshotOptions withoutMask = Utils.clone(options); + withoutMask.mask = null; + PageScreenshotParams copy = toProtocol(withoutMask, PageScreenshotParams.class); + if (copy.type == null) { + copy.type = ElementHandleImpl.determineScreenshotType(options); + } + if (mask != null) { + copy.mask = new ArrayList<>(); + for (Locator locator : mask) { + PageScreenshotParams.PageScreenshotParamsMask item = new PageScreenshotParams.PageScreenshotParamsMask(); + item.frame = ((LocatorImpl) locator).frame; + item.selector = ((LocatorImpl) locator).selector; + copy.mask.add(item); + } + } + PageScreenshotResult result = channel.screenshot(copy, timeoutSettings.timeout(options.timeout)); + if (options.path != null) { + Utils.writeToFile(result.binary, options.path); + } + return result.binary; + } + + // java: no signal (AbortSignal), so no AbortError branch. + ExpectScreenshotResult expectScreenshot(ExpectScreenshotOptions options) { + double timeout = options.timeout; + String title = options.title; + return wrapApiCall(() -> { + List mask = null; + if (options.mask != null) { + mask = new ArrayList<>(); + for (Locator locator : options.mask) { + PageExpectScreenshotParams.PageExpectScreenshotParamsMask item = new PageExpectScreenshotParams.PageExpectScreenshotParamsMask(); + item.frame = ((LocatorImpl) locator).frame; + item.selector = ((LocatorImpl) locator).selector; + mask.add(item); + } + } + PageExpectScreenshotParams.PageExpectScreenshotParamsLocator locator = null; + if (options.locator != null) { + locator = new PageExpectScreenshotParams.PageExpectScreenshotParamsLocator(); + locator.frame = ((LocatorImpl) options.locator).frame; + locator.selector = ((LocatorImpl) options.locator).selector; + } + try { + // java: { ...optionsWithoutTimeout, isNot, locator, mask } copies the protocol fields of the options. + PageExpectScreenshotParams params = new PageExpectScreenshotParams(); + params.expected = options.expected; + params.comparator = options.comparator; + params.maxDiffPixels = options.maxDiffPixels; + params.maxDiffPixelRatio = options.maxDiffPixelRatio; + params.threshold = options.threshold; + params.fullPage = options.fullPage; + params.clip = options.clip; + params.type = options.type; + params.omitBackground = options.omitBackground; + params.caret = options.caret; + params.animations = options.animations; + params.scale = options.scale; + params.maskColor = options.maskColor; + params.style = options.style; + params.isNot = options.isNot; + params.locator = locator; + params.mask = mask; + PageExpectScreenshotResult result = channel.expectScreenshot(params, timeout); + ExpectScreenshotResult expectResult = new ExpectScreenshotResult(); + expectResult.actual = result.actual; + return expectResult; + } catch (ServerErrorWithDetails e) { + // java: a PlaywrightError with details is a ServerErrorWithDetails, other errors pass through. + PageExpectScreenshotErrorDetails details = connection.protocolGson().fromJson(e.errorDetails(), PageExpectScreenshotErrorDetails.class); + if (details.customErrorMessage == null) { + throw e; + } + ExpectScreenshotResult expectResult = new ExpectScreenshotResult(); + expectResult.diff = details.diff; + expectResult.actual = details.actual; + expectResult.previous = details.previous; + expectResult.timedOut = details.timedOut; + expectResult.log = details.log; + expectResult.errorMessage = details.customErrorMessage; + return expectResult; + } + }, title, false); } @Override - public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { - mainFrame.dispatchEvent(selector, type, eventInit, convertType(options, Frame.DispatchEventOptions.class)); + public String title() { + return mainFrame.title(); } @Override - public void emulateMedia(EmulateMediaOptions options) { - emulateMediaImpl(options); + public void bringToFront() { + channel.bringToFront(NO_TIMEOUT); } - private void emulateMediaImpl(EmulateMediaOptions options) { + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + + @Override + public void close(CloseOptions options) { if (options == null) { - options = new EmulateMediaOptions(); + options = new CloseOptions(); + } + boolean runBeforeUnload = Boolean.TRUE.equals(options.runBeforeUnload); + closeReason = options.reason; + if (!runBeforeUnload) { + closeWasCalled = true; + } + try { + if (ownedContext != null) { + ownedContext.close(); + } else if (runBeforeUnload) { + channel.runBeforeUnload(NO_TIMEOUT); + } else { + PageCloseParams params = new PageCloseParams(); + params.reason = options.reason; + channel.close(params, NO_TIMEOUT); + } + } catch (TargetClosedError e) { + if (!runBeforeUnload) { + return; + } + throw e; } - PageEmulateMediaParams params = toProtocol(options, PageEmulateMediaParams.class); - channel.emulateMedia(params, NO_TIMEOUT); } @Override - public Object evaluate(String expression, Object arg) { - return mainFrame.evaluate(expression, arg); + public boolean isClosed() { + return closed; } @Override - public JSHandle evaluateHandle(String pageFunction, Object arg) { - return mainFrame.evaluateHandle(pageFunction, arg); + public void click(String selector, ClickOptions options) { + mainFrame.click(selector, convertType(options, Frame.ClickOptions.class)); } @Override - public AutoCloseable exposeBinding(String name, BindingCallback playwrightBinding) { - return exposeBindingImpl(name, playwrightBinding); + public void dragAndDrop(String source, String target, DragAndDropOptions options) { + mainFrame.dragAndDrop(source, target, convertType(options, Frame.DragAndDropOptions.class)); } - private AutoCloseable exposeBindingImpl(String name, BindingCallback playwrightBinding) { - if (bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered"); - } - if (browserContext.bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered in the browser context"); - } - bindings.put(name, playwrightBinding); - - PageExposeBindingParams params = new PageExposeBindingParams(); - params.name = name; - return channel.exposeBinding(params, NO_TIMEOUT).disposable; + @Override + public void dblclick(String selector, DblclickOptions options) { + mainFrame.dblclick(selector, convertType(options, Frame.DblclickOptions.class)); } @Override - public AutoCloseable exposeFunction(String name, FunctionCallback playwrightFunction) { - return exposeBindingImpl(name, (BindingCallback.Source source, Object... args) -> playwrightFunction.call(args)); + public void tap(String selector, TapOptions options) { + mainFrame.tap(selector, convertType(options, Frame.TapOptions.class)); } @Override @@ -789,87 +1164,87 @@ public void fill(String selector, String value, FillOptions options) { } @Override - public void focus(String selector, FocusOptions options) { - mainFrame.focus(selector, convertType(options, Frame.FocusOptions.class)); + public void clearConsoleMessages() { + channel.clearConsoleMessages(NO_TIMEOUT); } @Override - public Frame frame(String name) { - for (Frame frame : frames) { - if (name.equals(frame.name())) { - return frame; - } + public List consoleMessages(ConsoleMessagesOptions options) { + PageConsoleMessagesParams params = toProtocol(options, PageConsoleMessagesParams.class); + PageConsoleMessagesResult result = channel.consoleMessages(params, NO_TIMEOUT); + List messages = new ArrayList<>(); + for (PageConsoleMessagesResult.PageConsoleMessagesResultMessages message : result.messages) { + messages.add(new ConsoleMessageImpl(this, message)); } - return null; - } - - @Override - public Frame frameByUrl(String glob) { - return frameFor(UrlMatcher.forGlob(browserContext.baseUrl(), glob, this.connection.localUtils(), false)); + return messages; } @Override - public Frame frameByUrl(Pattern pattern) { - return frameFor(new UrlMatcher(pattern)); + public void clearPageErrors() { + channel.clearPageErrors(NO_TIMEOUT); } @Override - public Frame frameByUrl(Predicate predicate) { - return frameFor(new UrlMatcher(predicate)); + public List pageErrors() { + return pageErrors(null); + } + + // java: the Java API returns the errors as strings, not as parsed Error objects; options is its filter, the + // public pageErrors() passes none. + List pageErrors(String filter) { + PagePageErrorsParams params = new PagePageErrorsParams(); + params.filter = filter; + PagePageErrorsResult result = channel.pageErrors(params, NO_TIMEOUT); + List errors = new ArrayList<>(); + for (SerializedError error : result.errors) { + errors.add(Serialization.parseError(connection.protocolGson().toJsonTree(error).getAsJsonObject())); + } + return errors; } @Override - public FrameLocator frameLocator(String selector) { - return mainFrame.frameLocator(selector); - } - - private Frame frameFor(UrlMatcher matcher) { - for (Frame frame : frames) { - if (matcher.test(frame.url())) { - return frame; - } - } - return null; + public Locator locator(String selector, LocatorOptions options) { + return mainFrame().locator(selector, convertType(options, Frame.LocatorOptions.class)); } @Override - public List frames() { - return new ArrayList<>(frames); + public Locator getByTestId(String testId) { + return mainFrame().getByTestId(testId); } @Override - public String getAttribute(String selector, String name, GetAttributeOptions options) { - return mainFrame.getAttributeImpl(selector, name, convertType(options, Frame.GetAttributeOptions.class)); + public Locator getByTestId(Pattern testId) { + return mainFrame().getByTestId(testId); } @Override public Locator getByAltText(String text, GetByAltTextOptions options) { - return mainFrame.getByAltText(text, convertType(options, Frame.GetByAltTextOptions.class)); + return mainFrame().getByAltText(text, convertType(options, Frame.GetByAltTextOptions.class)); } @Override public Locator getByAltText(Pattern text, GetByAltTextOptions options) { - return mainFrame.getByAltText(text, convertType(options, Frame.GetByAltTextOptions.class)); + return mainFrame().getByAltText(text, convertType(options, Frame.GetByAltTextOptions.class)); } @Override public Locator getByLabel(String text, GetByLabelOptions options) { - return mainFrame.getByLabel(text, convertType(options, Frame.GetByLabelOptions.class)); + return mainFrame().getByLabel(text, convertType(options, Frame.GetByLabelOptions.class)); } @Override public Locator getByLabel(Pattern text, GetByLabelOptions options) { - return mainFrame.getByLabel(text, convertType(options, Frame.GetByLabelOptions.class)); + return mainFrame().getByLabel(text, convertType(options, Frame.GetByLabelOptions.class)); } @Override public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { - return mainFrame.getByPlaceholder(text, convertType(options, Frame.GetByPlaceholderOptions.class)); + return mainFrame().getByPlaceholder(text, convertType(options, Frame.GetByPlaceholderOptions.class)); } @Override public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { - return mainFrame.getByPlaceholder(text, convertType(options, Frame.GetByPlaceholderOptions.class)); + return mainFrame().getByPlaceholder(text, convertType(options, Frame.GetByPlaceholderOptions.class)); } @Override @@ -877,705 +1252,637 @@ public Locator getByRef(String ref) { return locator("aria-ref=" + ref); } - @Override - public Locator getByRole(AriaRole role, GetByRoleOptions options) { - return mainFrame.getByRole(role, convertType(options, Frame.GetByRoleOptions.class)); - } - - @Override - public Locator getByTestId(String testId) { - return mainFrame.getByTestId(testId); - } - - @Override - public Locator getByTestId(Pattern testId) { - return mainFrame.getByTestId(testId); - } - @Override public Locator getByText(String text, GetByTextOptions options) { - return mainFrame.getByText(text, convertType(options, Frame.GetByTextOptions.class)); + return mainFrame().getByText(text, convertType(options, Frame.GetByTextOptions.class)); } @Override public Locator getByText(Pattern text, GetByTextOptions options) { - return mainFrame.getByText(text, convertType(options, Frame.GetByTextOptions.class)); + return mainFrame().getByText(text, convertType(options, Frame.GetByTextOptions.class)); } @Override public Locator getByTitle(String text, GetByTitleOptions options) { - return mainFrame.getByTitle(text, convertType(options, Frame.GetByTitleOptions.class)); + return mainFrame().getByTitle(text, convertType(options, Frame.GetByTitleOptions.class)); } @Override public Locator getByTitle(Pattern text, GetByTitleOptions options) { - return mainFrame.getByTitle(text, convertType(options, Frame.GetByTitleOptions.class)); - } - - @Override - public Response goBack(GoBackOptions options) { - return goBackImpl(options); - } - - Response goBackImpl(GoBackOptions options) { - if (options == null) { - options = new GoBackOptions(); - } - PageGoBackParams params = toProtocol(options, PageGoBackParams.class); - return channel.goBack(params, timeoutSettings.navigationTimeout(options.timeout)).response; + return mainFrame().getByTitle(text, convertType(options, Frame.GetByTitleOptions.class)); } @Override - public Response goForward(GoForwardOptions options) { - return goForwardImpl(options); - } - - Response goForwardImpl(GoForwardOptions options) { - if (options == null) { - options = new GoForwardOptions(); - } - PageGoForwardParams params = toProtocol(options, PageGoForwardParams.class); - return channel.goForward(params, timeoutSettings.navigationTimeout(options.timeout)).response; + public Locator getByRole(AriaRole role, GetByRoleOptions options) { + return mainFrame().getByRole(role, convertType(options, Frame.GetByRoleOptions.class)); } @Override - public void requestGC() { - channel.requestGC(NO_TIMEOUT); + public FrameLocator frameLocator(String selector) { + return mainFrame().frameLocator(selector); } @Override - public ResponseImpl navigate(String url, NavigateOptions options) { - return mainFrame.navigateImpl(url, convertType(options, Frame.NavigateOptions.class)); + public void focus(String selector, FocusOptions options) { + mainFrame.focus(selector, convertType(options, Frame.FocusOptions.class)); } @Override - public void hover(String selector, HoverOptions options) { - mainFrame.hoverImpl(selector, convertType(options, Frame.HoverOptions.class)); + public String textContent(String selector, TextContentOptions options) { + return mainFrame.textContent(selector, convertType(options, Frame.TextContentOptions.class)); } @Override - public void dragAndDrop(String source, String target, DragAndDropOptions options) { - if (options == null) { - options = new DragAndDropOptions(); - } - mainFrame.dragAndDropImpl(source, target, convertType(options, Frame.DragAndDropOptions.class), options.steps); + public String innerText(String selector, InnerTextOptions options) { + return mainFrame.innerText(selector, convertType(options, Frame.InnerTextOptions.class)); } @Override public String innerHTML(String selector, InnerHTMLOptions options) { - return mainFrame.innerHTMLImpl(selector, convertType(options, Frame.InnerHTMLOptions.class)); + return mainFrame.innerHTML(selector, convertType(options, Frame.InnerHTMLOptions.class)); } @Override - public String innerText(String selector, InnerTextOptions options) { - return mainFrame.innerTextImpl(selector, convertType(options, Frame.InnerTextOptions.class)); + public String getAttribute(String selector, String name, GetAttributeOptions options) { + return mainFrame.getAttribute(selector, name, convertType(options, Frame.GetAttributeOptions.class)); } @Override public String inputValue(String selector, InputValueOptions options) { - return mainFrame.inputValueImpl(selector, convertType(options, Frame.InputValueOptions.class)); + return mainFrame.inputValue(selector, convertType(options, Frame.InputValueOptions.class)); } @Override public boolean isChecked(String selector, IsCheckedOptions options) { - return mainFrame.isCheckedImpl(selector, convertType(options, Frame.IsCheckedOptions.class)); - } - - @Override - public boolean isClosed() { - return isClosed; + return mainFrame.isChecked(selector, convertType(options, Frame.IsCheckedOptions.class)); } @Override public boolean isDisabled(String selector, IsDisabledOptions options) { - return mainFrame.isDisabledImpl(selector, convertType(options, Frame.IsDisabledOptions.class)); + return mainFrame.isDisabled(selector, convertType(options, Frame.IsDisabledOptions.class)); } @Override public boolean isEditable(String selector, IsEditableOptions options) { - return mainFrame.isEditableImpl(selector, convertType(options, Frame.IsEditableOptions.class)); + return mainFrame.isEditable(selector, convertType(options, Frame.IsEditableOptions.class)); } @Override public boolean isEnabled(String selector, IsEnabledOptions options) { - return mainFrame.isEnabledImpl(selector, convertType(options, Frame.IsEnabledOptions.class)); + return mainFrame.isEnabled(selector, convertType(options, Frame.IsEnabledOptions.class)); } @Override public boolean isHidden(String selector, IsHiddenOptions options) { - return mainFrame.isHiddenImpl(selector, convertType(options, Frame.IsHiddenOptions.class)); + return mainFrame.isHidden(selector, convertType(options, Frame.IsHiddenOptions.class)); } @Override public boolean isVisible(String selector, IsVisibleOptions options) { - return mainFrame.isVisibleImpl(selector, convertType(options, Frame.IsVisibleOptions.class)); + return mainFrame.isVisible(selector, convertType(options, Frame.IsVisibleOptions.class)); } @Override - public Keyboard keyboard() { - return keyboard; + public void hover(String selector, HoverOptions options) { + mainFrame.hover(selector, convertType(options, Frame.HoverOptions.class)); } @Override - public List consoleMessages(ConsoleMessagesOptions options) { - PageConsoleMessagesParams params = toProtocol(options, PageConsoleMessagesParams.class); - PageConsoleMessagesResult json = channel.consoleMessages(params, NO_TIMEOUT); - List result = new ArrayList<>(); - for (PageConsoleMessagesResult.PageConsoleMessagesResultMessages item : json.messages) { - result.add(new ConsoleMessageImpl(this, item)); - } - return result; + public List selectOption(String selector, String values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public void clearConsoleMessages() { - channel.clearConsoleMessages(NO_TIMEOUT); + public List selectOption(String selector, ElementHandle values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public void clearPageErrors() { - channel.clearPageErrors(NO_TIMEOUT); + public List selectOption(String selector, String[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public List pageErrors() { - PagePageErrorsResult json = channel.pageErrors(new PagePageErrorsParams(), NO_TIMEOUT); - List result = new ArrayList<>(); - for (SerializedError item : json.errors) { - String errorStr = ""; - if (item.error != null) { - errorStr = item.error.name + ": " + item.error.message; - if (item.error.stack != null && !item.error.stack.isEmpty()) { - errorStr += "\n" + item.error.stack; - } - } - result.add(errorStr); - } - return result; + public List selectOption(String selector, SelectOption values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public Locator locator(String selector, LocatorOptions options) { - return mainFrame.locator(selector, convertType(options, Frame.LocatorOptions.class)); + public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public Frame mainFrame() { - return mainFrame; + public List selectOption(String selector, SelectOption[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); } @Override - public WebMCP webmcp() { - return mainFrame.webmcp(); + public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); } @Override - public void hideHighlight() { - channel.hideHighlight(NO_TIMEOUT); + public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); } @Override - public Mouse mouse() { - return mouse; + public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); } @Override - public PageImpl opener() { - if (opener == null || opener.isClosed()) { - return null; - } - return opener; + public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); } @Override - public void cancelPickLocator() { - channel.cancelPickLocator(NO_TIMEOUT); + public void type(String selector, String text, TypeOptions options) { + mainFrame.type(selector, text, convertType(options, Frame.TypeOptions.class)); } @Override - public Locator pickLocator() { - PagePickLocatorResult result = channel.pickLocator(NO_TIMEOUT); - return new LocatorImpl(mainFrame, result.selector, null); + public void press(String selector, String key, PressOptions options) { + mainFrame.press(selector, key, convertType(options, Frame.PressOptions.class)); } @Override - public void pause() { - TimeoutSettings settings = browserContext.timeoutSettings; - Double defaultNavigationTimeout = settings.defaultNavigationTimeout(); - Double defaultTimeout = settings.defaultTimeout(); - settings.setDefaultNavigationTimeout(0.0); - settings.setDefaultTimeout(0.0); - try { - runUntil(() -> {}, new WaitableRace<>(asList(context().pause(), (Waitable) waitableClosedOrCrashed))); - } finally { - settings.setDefaultNavigationTimeout(defaultNavigationTimeout); - settings.setDefaultTimeout(defaultTimeout); - } + public void check(String selector, CheckOptions options) { + mainFrame.check(selector, convertType(options, Frame.CheckOptions.class)); } @Override - public byte[] pdf(PdfOptions options) { - return pdfImpl(options); - } - - private byte[] pdfImpl(PdfOptions options) { - if (options == null) { - options = new PdfOptions(); - } - PagePdfParams params = toProtocol(options, PagePdfParams.class); - byte[] buffer = channel.pdf(params, NO_TIMEOUT).pdf; - if (options.path != null) { - Utils.writeToFile(buffer, options.path); - } - return buffer; + public void uncheck(String selector, UncheckOptions options) { + mainFrame.uncheck(selector, convertType(options, Frame.UncheckOptions.class)); } @Override - public void press(String selector, String key, PressOptions options) { - mainFrame.pressImpl(selector, key, convertType(options, Frame.PressOptions.class)); + public void setChecked(String selector, boolean checked, SetCheckedOptions options) { + mainFrame.setChecked(selector, checked, convertType(options, Frame.SetCheckedOptions.class)); } @Override - public Response reload(ReloadOptions options) { - return reloadImpl(options); + public void waitForTimeout(double timeout) { + mainFrame.waitForTimeout(timeout); } @Override - public APIRequestContextImpl request() { - return browserContext.request(); + public JSHandle waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { + return mainFrame.waitForFunction(expression, arg, convertType(options, Frame.WaitForFunctionOptions.class)); } - private Response reloadImpl(ReloadOptions options) { - if (options == null) { - options = new ReloadOptions(); - } - PageReloadParams params = toProtocol(options, PageReloadParams.class); - return channel.reload(params, timeoutSettings.navigationTimeout(options.timeout)).response; + @Override + public List requests() { + PageRequestsResult result = channel.requests(NO_TIMEOUT); + return new ArrayList<>(result.requests); } @Override - public AutoCloseable route(String url, Consumer handler, RouteOptions options) { - route(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + public List workers() { + return new ArrayList<>(workers); } @Override - public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + public void pause() { + pause(false); } - @Override - public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); + // java: _options is its __testHookKeepTestTimeout flag, the public pause() passes false. The inspector.url() + // check is not ported: it detects a Node.js debugger, the Java client has none to detect. + void pause(boolean testHookKeepTestTimeout) { + Double defaultNavigationTimeout = browserContext.timeoutSettings.defaultNavigationTimeout(); + Double defaultTimeout = browserContext.timeoutSettings.defaultTimeout(); + browserContext.setDefaultNavigationTimeout(0); + browserContext.setDefaultTimeout(0); + instrumentation.onWillPause(testHookKeepTestTimeout); + closedOrCrashedScope.safeRace(browserContext.sendMessageAsync("pause")); + // java: the saved defaults may be unset, which the public double setters cannot express. + browserContext.timeoutSettings.setDefaultNavigationTimeout(defaultNavigationTimeout); + browserContext.timeoutSettings.setDefaultTimeout(defaultTimeout); } @Override - public void routeFromHAR(Path har, RouteFromHAROptions options) { + public byte[] pdf(PdfOptions options) { if (options == null) { - options = new RouteFromHAROptions(); + options = new PdfOptions(); } - if (options.update != null && options.update) { - browserContext.recordIntoHar(this, har, convertType(options, BrowserContext.RouteFromHAROptions.class), null); - return; + // java: toProtocol makes a copy of the margin too. + PagePdfParams transportOptions = toProtocol(options, PagePdfParams.class); + // java: width, height and the margins are Strings in the Java API, a number never reaches these checks. + if ((Object) options.width instanceof Number) { + transportOptions.width = options.width + "px"; } - UrlMatcher matcher = UrlMatcher.forOneOf(browserContext.baseUrl(), options.url, this.connection.localUtils(), false); - HARRouter harRouter = new HARRouter(connection.localUtils(), har, options.notFound); - onClose(context -> harRouter.dispose()); - route(matcher, route -> harRouter.handle(route), null); - } - - private void route(UrlMatcher matcher, Consumer handler, RouteOptions options) { - routes.add(matcher, handler, options == null ? null : options.times); - updateInterceptionPatterns(); - } - - @Override - public void routeWebSocket(String url, Consumer handler) { - routeWebSocketImpl(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), true), handler); - } - - @Override - public void routeWebSocket(Pattern pattern, Consumer handler) { - routeWebSocketImpl(new UrlMatcher(pattern), handler); - } - - @Override - public void routeWebSocket(Predicate predicate, Consumer handler) { - routeWebSocketImpl(new UrlMatcher(predicate), handler); - } - - private void routeWebSocketImpl(UrlMatcher matcher, Consumer handler) { - webSocketRoutes.add(matcher, handler); - updateWebSocketInterceptionPatterns(); - } - - @Override - public byte[] screenshot(ScreenshotOptions options) { - return screenshotImpl(options); + if ((Object) options.height instanceof Number) { + transportOptions.height = options.height + "px"; + } + // java: the loop over 'top', 'right', 'bottom' and 'left' is unrolled, Java has no field access by name. + if (options.margin != null && (Object) options.margin.top instanceof Number) { + transportOptions.margin.top = transportOptions.margin.top + "px"; + } + if (options.margin != null && (Object) options.margin.right instanceof Number) { + transportOptions.margin.right = transportOptions.margin.right + "px"; + } + if (options.margin != null && (Object) options.margin.bottom instanceof Number) { + transportOptions.margin.bottom = transportOptions.margin.bottom + "px"; + } + if (options.margin != null && (Object) options.margin.left instanceof Number) { + transportOptions.margin.left = transportOptions.margin.left + "px"; + } + PagePdfResult result = channel.pdf(transportOptions, NO_TIMEOUT); + if (options.path != null) { + Utils.writeToFile(result.pdf, options.path); + } + return result.pdf; } @Override - public List selectOption(String selector, String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(selector, values, options); + public String ariaSnapshot(AriaSnapshotOptions options) { + if (options == null) { + options = new AriaSnapshotOptions(); + } + FrameAriaSnapshotParams params = new FrameAriaSnapshotParams(); + // java: the AriaSnapshotMode enum is sent as its lower-case protocol string. + params.mode = options.mode == null ? null : options.mode.toString().toLowerCase(); + params.depth = options.depth; + params.boxes = options.boxes; + return mainFrame().channel.ariaSnapshot(params, timeoutSettings.timeout(options.timeout)).snapshot; } - @Override - public List selectOption(String selector, ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{ value }; - return selectOption(selector, values, options); + // java: the AriaSnapshotJSON result is parsed JSON, a JsonElement. + JsonElement ariaSnapshotJSON(AriaSnapshotOptions options) { + if (options == null) { + options = new AriaSnapshotOptions(); + } + FrameAriaSnapshotJSONParams params = new FrameAriaSnapshotJSONParams(); + // java: the AriaSnapshotMode enum is sent as its lower-case protocol string. + params.mode = options.mode == null ? null : options.mode.toString().toLowerCase(); + params.depth = options.depth; + params.boxes = options.boxes; + return mainFrame().channel.ariaSnapshotJSON(params, timeoutSettings.timeout(options.timeout)).snapshot; } - @Override - public List selectOption(String selector, String[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + void setDockTile(byte[] image) { + PageSetDockTileParams params = new PageSetDockTileParams(); + params.image = image; + channel.setDockTile(params, NO_TIMEOUT); } - @Override - public List selectOption(String selector, SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{value}; - return selectOption(selector, values, options); - } + // java: class BindingCall is in BindingCall.java. - private byte[] screenshotImpl(ScreenshotOptions options) { - if (options == null) { - options = new ScreenshotOptions(); - } - if (options.type == null && options.path != null) { - options.type = Utils.screenshotTypeForPath(options.path); + private static String trimUrl(Object param) { + if (param instanceof Pattern) { + Pattern pattern = (Pattern) param; + return "/" + trimStringWithEllipsis(pattern.pattern(), 50) + "/" + toJsRegexFlags(pattern); } - PageScreenshotParams params = toProtocol(this, options, PageScreenshotParams.class); - byte[] buffer = channel.screenshot(params, timeoutSettings.timeout(options.timeout)).binary; - if (options.path != null) { - Utils.writeToFile(buffer, options.path); + if (param instanceof String) { + return "\"" + trimStringWithEllipsis((String) param, 50) + "\""; } - return buffer; + return null; } - @Override - public List selectOption(String selector, SelectOption[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + // java: owner is a PageImpl or a BrowserContextImpl, the members it needs are reached through its class. The + // init script function is its source, a String; the callbacks in arg are FunctionCallbacks. + static DisposableStub addInitScriptWithExposedFunctions(ChannelOwner owner, Object script, Object arg) { + if (!(script instanceof String)) { + throw new PlaywrightException("Passing functions requires the init script to be a function"); + } + List callbacks = new ArrayList<>(); + String source = owner.wrapApiCall(() -> { + return initScriptSourceWithExposedFunctions((String) script, arg, (name, callback) -> { + DisposableObject disposable = owner instanceof PageImpl + ? ((PageImpl) owner).exposeCallbackBinding(name, callback) + : ((BrowserContextImpl) owner).exposeCallbackBinding(name, callback); + callbacks.add(new ExposedCallback(name, disposable)); + }); + }, null, true); + DisposableObject initScriptDisposable; + if (owner instanceof PageImpl) { + PageAddInitScriptParams params = new PageAddInitScriptParams(); + params.source = source; + initScriptDisposable = ((PageImpl) owner).channel.addInitScript(params, NO_TIMEOUT).disposable; + } else { + BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); + params.source = source; + initScriptDisposable = ((BrowserContextImpl) owner).channel.addInitScript(params, NO_TIMEOUT).disposable; + } + return new DisposableStub(() -> { + Map bindings = owner instanceof PageImpl ? ((PageImpl) owner).bindings : ((BrowserContextImpl) owner).bindings; + for (ExposedCallback callback : callbacks) { + bindings.remove(callback.name); + // java: dispose() is not awaited upstream; sendMessageAsync does not pump. + try { + callback.disposable.sendMessageAsync("dispose"); + } catch (PlaywrightException e) { + } + } + initScriptDisposable.close(); + }); } - @Override - public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); - } + // java: the value object of _locatorHandlers. + private static class LocatorHandler { + final LocatorImpl locator; + final Consumer handler; + Integer times; - @Override - public void setChecked(String selector, boolean checked, SetCheckedOptions options) { - mainFrame.setCheckedImpl(selector, checked, convertType(options, Frame.SetCheckedOptions.class)); + LocatorHandler(LocatorImpl locator, Consumer handler, Integer times) { + this.locator = locator; + this.handler = handler; + this.times = times; + } } - @Override - public void setContent(String html, SetContentOptions options) { - mainFrame.setContent(html, convertType(options, Frame.SetContentOptions.class)); - } + // java: the { name, disposable } entries of _evaluateCallbacks and of the callbacks of addInitScriptWithExposedFunctions. + static class ExposedCallback { + final String name; + final DisposableObject disposable; - @Override - public void setDefaultNavigationTimeout(double timeout) { - timeoutSettings.setDefaultNavigationTimeout(timeout); + ExposedCallback(String name, DisposableObject disposable) { + this.name = name; + this.disposable = disposable; + } } + // java: ExpectScreenshotOptions of page.ts: the protocol options with Locator objects for locator and mask, the + // timeout and the title; no signal (AbortSignal). + static class ExpectScreenshotOptions { + byte[] expected; + Locator locator; + double timeout; + boolean isNot; + List mask; + String title; + String comparator; + Integer maxDiffPixels; + Double maxDiffPixelRatio; + Double threshold; + Boolean fullPage; + Rect clip; + String type; + Boolean omitBackground; + String caret; + String animations; + String scale; + String maskColor; + String style; + } + + // java: the result type of _expectScreenshot. + static class ExpectScreenshotResult { + byte[] actual; + byte[] previous; + byte[] diff; + String errorMessage; + List log; + Boolean timedOut; + } + + // java: the public API members with no upstream counterpart: accessors of the readonly fields, typed + // listeners, onceDialog, waitForCondition and its waitables. @Override - public void setDefaultTimeout(double timeout) { - timeoutSettings.setDefaultTimeout(timeout); + public ClockImpl clock() { + return clock; } @Override - public void setExtraHTTPHeaders(Map headers) { - PageSetExtraHTTPHeadersParams params = new PageSetExtraHTTPHeadersParams(); - params.headers = new ArrayList<>(); - for (Map.Entry e : headers.entrySet()) { - NameValue header = new NameValue(); - header.name = e.getKey(); - header.value = e.getValue(); - params.headers.add(header); - } - channel.setExtraHTTPHeaders(params, NO_TIMEOUT); + public KeyboardImpl keyboard() { + return keyboard; } @Override - public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { - setInputFiles(selector, new Path[]{files}, options); + public MouseImpl mouse() { + return mouse; } @Override - public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { - mainFrame.setInputFilesImpl(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + public APIRequestContextImpl request() { + return request; } @Override - public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { - setInputFiles(selector, new FilePayload[]{files}, options); + public TouchscreenImpl touchscreen() { + return touchscreen; } @Override - public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { - mainFrame.setInputFilesImpl(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + public Screencast screencast() { + return screencast; } @Override - public void setViewportSize(int width, int height) { - viewport = new ViewportSize(width, height); - PageSetViewportSizeParams params = new PageSetViewportSizeParams(); - params.viewportSize = new PageSetViewportSizeParams.PageSetViewportSizeParamsViewportSize(); - params.viewportSize.width = width; - params.viewportSize.height = height; - channel.setViewportSize(params, NO_TIMEOUT); + public WebStorage localStorage() { + return localStorage; } @Override - public void tap(String selector, TapOptions options) { - mainFrame.tap(selector, convertType(options, Frame.TapOptions.class)); + public WebStorage sessionStorage() { + return sessionStorage; } @Override - public String textContent(String selector, TextContentOptions options) { - return mainFrame.textContent(selector, convertType(options, Frame.TextContentOptions.class)); + public WebMCP webmcp() { + return webmcp; } @Override - public String title() { - return mainFrame.title(); + public void onClose(Consumer handler) { + on(Events.Page.CLOSE, handler); } @Override - public Touchscreen touchscreen() { - return touchscreen; + public void offClose(Consumer handler) { + off(Events.Page.CLOSE, handler); } @Override - public Screencast screencast() { - return screencast; + public void onConsoleMessage(Consumer handler) { + on(Events.Page.CONSOLE, handler); } @Override - public WebStorage localStorage() { - return localStorage; + public void offConsoleMessage(Consumer handler) { + off(Events.Page.CONSOLE, handler); } @Override - public WebStorage sessionStorage() { - return sessionStorage; + public void onCrash(Consumer handler) { + on(Events.Page.CRASH, handler); } @Override - public void type(String selector, String text, TypeOptions options) { - mainFrame.type(selector, text, convertType(options, Frame.TypeOptions.class)); + public void offCrash(Consumer handler) { + off(Events.Page.CRASH, handler); } @Override - public void uncheck(String selector, UncheckOptions options) { - mainFrame.uncheck(selector, convertType(options, Frame.UncheckOptions.class)); + public void onDialog(Consumer handler) { + on(Events.Page.DIALOG, handler); } @Override - public void unrouteAll() { - routes.removeAll(); - updateInterceptionPatterns(); + public void offDialog(Consumer handler) { + off(Events.Page.DIALOG, handler); } @Override - public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), handler); + public void onDialogClosed(Consumer handler) { + on(Events.Page.DIALOG_CLOSED, handler); } @Override - public void unroute(Pattern url, Consumer handler) { - unroute(new UrlMatcher(url), handler); + public void offDialogClosed(Consumer handler) { + off(Events.Page.DIALOG_CLOSED, handler); } @Override - public void unroute(Predicate url, Consumer handler) { - unroute(new UrlMatcher(url), handler); - } - - private void unroute(UrlMatcher matcher, Consumer handler) { - routes.remove(matcher, handler); - updateInterceptionPatterns(); + public void onDOMContentLoaded(Consumer handler) { + on(Events.Page.DOM_CONTENT_LOADED, handler); } - private void updateInterceptionPatterns() { - channel.setNetworkInterceptionPatterns( - connection.protocolGson().fromJson(routes.interceptionPatterns(), PageSetNetworkInterceptionPatternsParams.class), NO_TIMEOUT); + @Override + public void offDOMContentLoaded(Consumer handler) { + off(Events.Page.DOM_CONTENT_LOADED, handler); } - private void updateWebSocketInterceptionPatterns() { - channel.setWebSocketInterceptionPatterns( - connection.protocolGson().fromJson(webSocketRoutes.interceptionPatterns(), PageSetWebSocketInterceptionPatternsParams.class), NO_TIMEOUT); + @Override + public void onDownload(Consumer handler) { + on(Events.Page.DOWNLOAD, handler); } @Override - public String url() { - return mainFrame.url(); + public void offDownload(Consumer handler) { + off(Events.Page.DOWNLOAD, handler); } - @Override - public VideoImpl video() { - if (!browserContext.initializer.getAsJsonObject("options").has("recordVideo")) { - return null; - } - return video; + public void onFileChooser(Consumer handler) { + on(Events.Page.FILE_CHOOSER, handler); } @Override - public ViewportSize viewportSize() { - return viewport; + public void offFileChooser(Consumer handler) { + off(Events.Page.FILE_CHOOSER, handler); } - Waitable createWaitableTimeout(Double timeout) { - return timeoutSettings.createWaitable(timeout); + @Override + public void onFrameAttached(Consumer handler) { + on(Events.Page.FRAME_ATTACHED, handler); } @Override - public JSHandle waitForFunction(String pageFunction, Object arg, WaitForFunctionOptions options) { - return mainFrame.waitForFunction(pageFunction, arg, convertType(options, Frame.WaitForFunctionOptions.class)); + public void offFrameAttached(Consumer handler) { + off(Events.Page.FRAME_ATTACHED, handler); } @Override - public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { - mainFrame.waitForLoadState(state, convertType(options, Frame.WaitForLoadStateOptions.class)); + public void onFrameDetached(Consumer handler) { + on(Events.Page.FRAME_DETACHED, handler); } @Override - public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) { - Frame.WaitForNavigationOptions frameOptions = new Frame.WaitForNavigationOptions(); - if (options != null) { - frameOptions.timeout = options.timeout; - frameOptions.waitUntil = options.waitUntil; - frameOptions.url = options.url; - } - return mainFrame.waitForNavigation(frameOptions, code); + public void offFrameDetached(Consumer handler) { + off(Events.Page.FRAME_DETACHED, handler); } - void frameNavigated(FrameImpl frame) { - emit(Events.Page.FRAME_NAVIGATED, frame); - browserContext.notifyFrameNavigated(frame); + @Override + public void onFrameNavigated(Consumer handler) { + on(Events.Page.FRAME_NAVIGATED, handler); } - Waitable createWaitForCloseHelper() { - return new WaitableRace(asList(new WaitablePageClose(), new WaitablePageCrash())); + @Override + public void offFrameNavigated(Consumer handler) { + off(Events.Page.FRAME_NAVIGATED, handler); } - private class WaitablePageClose extends WaitableEvent { - WaitablePageClose() { - super(PageImpl.this, Events.Page.CLOSE); - } - - @Override - public T get() { - throw closeErrorWithReason(); - } + @Override + public void onLoad(Consumer handler) { + on(Events.Page.LOAD, handler); } - private class WaitablePageCrash extends WaitableEvent { - WaitablePageCrash() { - super(PageImpl.this, Events.Page.CRASH); - } - - @Override - public T get() { - throw new TargetClosedError("Page crashed"); - } + @Override + public void offLoad(Consumer handler) { + off(Events.Page.LOAD, handler); } @Override - public Request waitForRequest(String urlGlob, WaitForRequestOptions options, Runnable code) { - return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, trimUrl(urlGlob), options, code); + public void onPageError(Consumer handler) { + on(Events.Page.PAGE_ERROR, handler); } @Override - public Request waitForRequest(Pattern urlPattern, WaitForRequestOptions options, Runnable code) { - return waitForRequest(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); + public void offPageError(Consumer handler) { + off(Events.Page.PAGE_ERROR, handler); } @Override - public Request waitForRequest(Predicate predicate, WaitForRequestOptions options, Runnable code) { - return waitForRequest(null, predicate, null, options, code); + public void onPopup(Consumer handler) { + on(Events.Page.POPUP, handler); } - private Request waitForRequest(UrlMatcher urlMatcher, Predicate predicate, String trimmedUrl, WaitForRequestOptions options, Runnable code) { - if (options == null) { - options = new WaitForRequestOptions(); - } - Predicate requestPredicate = predicate != null ? predicate : request -> urlMatcher.test(request.url()); - String logLine = trimmedUrl == null ? null : "waiting for request " + trimmedUrl; - return waitForEvent(Events.Page.REQUEST, requestPredicate, options.timeout, logLine, code); + @Override + public void offPopup(Consumer handler) { + off(Events.Page.POPUP, handler); } @Override - public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Runnable code) { - if (options == null) { - options = new WaitForRequestFinishedOptions(); - } - return waitForEvent(Events.Page.REQUEST_FINISHED, options.predicate, options.timeout, "waiting for event \"requestfinished\"", code); + public void onRequest(Consumer handler) { + on(Events.Page.REQUEST, handler); } @Override - public Response waitForResponse(String urlGlob, WaitForResponseOptions options, Runnable code) { - return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, trimUrl(urlGlob), options, code); + public void offRequest(Consumer handler) { + off(Events.Page.REQUEST, handler); } @Override - public Response waitForResponse(Pattern urlPattern, WaitForResponseOptions options, Runnable code) { - return waitForResponse(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); + public void onRequestFailed(Consumer handler) { + on(Events.Page.REQUEST_FAILED, handler); } @Override - public Response waitForResponse(Predicate predicate, WaitForResponseOptions options, Runnable code) { - return waitForResponse(null, predicate, null, options, code); + public void offRequestFailed(Consumer handler) { + off(Events.Page.REQUEST_FAILED, handler); } - private Response waitForResponse(UrlMatcher urlMatcher, Predicate predicate, String trimmedUrl, WaitForResponseOptions options, Runnable code) { - if (options == null) { - options = new WaitForResponseOptions(); - } - Predicate responsePredicate = predicate != null ? predicate : response -> urlMatcher.test(response.url()); - String logLine = trimmedUrl == null ? null : "waiting for response " + trimmedUrl; - return waitForEvent(Events.Page.RESPONSE, responsePredicate, options.timeout, logLine, code); + @Override + public void onRequestFinished(Consumer handler) { + on(Events.Page.REQUEST_FINISHED, handler); } @Override - public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { - return mainFrame.waitForSelector(selector, convertType(options, Frame.WaitForSelectorOptions.class)); + public void offRequestFinished(Consumer handler) { + off(Events.Page.REQUEST_FINISHED, handler); } @Override - public void waitForCondition(BooleanSupplier predicate, WaitForConditionOptions options) { - List> waitables = new ArrayList<>(); - waitables.add(createWaitForCloseHelper()); - waitables.add(createWaitableTimeout(options == null ? null : options.timeout)); - waitables.add(new WaitablePredicate<>(predicate)); - runUntil(() -> {}, new WaitableRace<>(waitables)); + public void onResponse(Consumer handler) { + on(Events.Page.RESPONSE, handler); } @Override - public void waitForTimeout(double timeout) { - mainFrame.waitForTimeout(timeout); + public void offResponse(Consumer handler) { + off(Events.Page.RESPONSE, handler); } @Override - public void waitForURL(String url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + public void onWebSocket(Consumer handler) { + on(Events.Page.WEB_SOCKET, handler); } @Override - public void waitForURL(Pattern url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + public void offWebSocket(Consumer handler) { + off(Events.Page.WEB_SOCKET, handler); } @Override - public void waitForURL(Predicate url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + public void onWorker(Consumer handler) { + on(Events.Page.WORKER, handler); } @Override - public List workers() { - return new ArrayList<>(workers); + public void offWorker(Consumer handler) { + off(Events.Page.WORKER, handler); } @Override @@ -1591,4 +1898,23 @@ public void accept(Dialog dialog) { } }); } + + @Override + public void waitForCondition(BooleanSupplier condition, WaitForConditionOptions options) { + List> waitables = new ArrayList<>(); + // java: the condition goes first, it wins on a page that is already closed. + waitables.add(new WaitablePredicate<>(condition)); + waitables.add(createWaitForCloseHelper()); + waitables.add(createWaitableTimeout(options == null ? null : options.timeout)); + runUntil(() -> {}, new WaitableRace<>(waitables)); + } + + // java: done once the page closed or crashed, then throws the error closedOrCrashedScope was closed with. + Waitable createWaitForCloseHelper() { + return closedOrCrashedScope.terminatePromise(false); + } + + Waitable createWaitableTimeout(Double timeout) { + return timeoutSettings.createWaitable(timeout); + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java index 448d9a2a5..8b11c7a1e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -14,23 +14,98 @@ * limitations under the License. */ +// Port of playwright.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import com.microsoft.playwright.APIRequest; +import com.microsoft.playwright.BrowserType; +import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.Selectors; +import com.microsoft.playwright.TimeoutError; import com.microsoft.playwright.impl.driver.Driver; +import com.microsoft.playwright.impl.protocol.*; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class PlaywrightImpl extends ChannelOwner implements Playwright { + // java: _android and _electron are not ported, android.ts and electron.ts are not ported. + final BrowserTypeImpl chromium; + final BrowserTypeImpl firefox; + final BrowserTypeImpl webkit; + // java: devices is `any` upstream, the Object is the devices of LocalUtils or an empty map. + final Object devices; + SelectorsImpl selectors; + final APIRequestImpl request; + // java: errors maps the name of each error class to the class. + final Map> errors; + + // Instrumentation. + BrowserType.LaunchOptions defaultLaunchOptions; + Double defaultContextTimeout; + Double defaultContextNavigationTimeout; + + final PlaywrightChannel channel = new PlaywrightChannel(this); + + PlaywrightImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + PlaywrightInitializer playwrightInitializer = connection.protocolGson().fromJson(initializer, PlaywrightInitializer.class); + request = new APIRequestImpl(this); + chromium = playwrightInitializer.chromium; + chromium.playwright = this; + firefox = playwrightInitializer.firefox; + firefox.playwright = this; + webkit = playwrightInitializer.webkit; + webkit.playwright = this; + // java: _android and _electron are not created, android.ts and electron.ts are not ported. + LocalUtils localUtils = connection.localUtils(); + devices = localUtils != null && localUtils.devices != null ? localUtils.devices : new LinkedHashMap(); + selectors = new SelectorsImpl(); + errors = new LinkedHashMap<>(); + errors.put("TimeoutError", TimeoutError.class); + } + + // java: from is not ported, generated results already hold the impl object. + + private List browserTypes() { + return Arrays.asList(chromium, firefox, webkit); + } + + BrowserImpl preLaunchedBrowser() { + BrowserImpl browser = connection.protocolGson().fromJson(initializer, PlaywrightInitializer.class).preLaunchedBrowser; + // java: this[browser._name] is a switch over the three browser type fields. + BrowserTypeImpl browserType = "chromium".equals(browser.name) ? chromium : "firefox".equals(browser.name) ? firefox : "webkit".equals(browser.name) ? webkit : null; + browser.connectToBrowserType(browserType, new BrowserType.LaunchOptions(), null); + return browser; + } + + List allContexts() { + List result = new ArrayList<>(); + for (BrowserTypeImpl type : browserTypes()) { + result.addAll(type.contexts); + } + return result; + } + + List allPages() { + List result = new ArrayList<>(); + for (BrowserContextImpl context : allContexts()) { + for (Page page : context.pages()) { + result.add((PageImpl) page); + } + } + return result; + } + + // java: the entry point of the Java client and the getters of the Java API, playwright.ts has no counterpart. private Process driverProcess; public static PlaywrightImpl create(CreateOptions options) { @@ -47,7 +122,7 @@ public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewD Driver.ensureDriverInstalled(env, true); try { ProcessBuilder pb = driver.createProcessBuilder(); - // The driver is installed once per JVM with the env of the first instance, so add the env of this one. + // java: the driver is installed once per JVM with the env of the first instance, so add the env of this one. pb.environment().putAll(env); pb.command().add("run-driver"); pb.redirectError(ProcessBuilder.Redirect.INHERIT); @@ -61,28 +136,6 @@ public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewD } } - private final BrowserTypeImpl chromium; - private final BrowserTypeImpl firefox; - private final BrowserTypeImpl webkit; - private final APIRequestImpl apiRequest; - protected SelectorsImpl selectors; - - final PlaywrightChannel channel = new PlaywrightChannel(this); - - PlaywrightImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - chromium = parent.connection.getExistingObject(initializer.getAsJsonObject("chromium").get("guid").getAsString()); - firefox = parent.connection.getExistingObject(initializer.getAsJsonObject("firefox").get("guid").getAsString()); - webkit = parent.connection.getExistingObject(initializer.getAsJsonObject("webkit").get("guid").getAsString()); - - chromium.playwright = this; - firefox.playwright = this; - webkit.playwright = this; - - selectors = new SelectorsImpl(); - apiRequest = new APIRequestImpl(this); - } - public LocalUtils localUtils() { return connection.localUtils(); } @@ -101,26 +154,26 @@ public BrowserTypeImpl firefox() { return firefox; } - @Override - public APIRequest request() { - return apiRequest; - } - @Override public BrowserTypeImpl webkit() { return webkit; } @Override - public Selectors selectors() { + public SelectorsImpl selectors() { return selectors; } + @Override + public APIRequestImpl request() { + return request; + } + @Override public void close() { try { connection.close(); - // playwright-cli will exit when its stdin is closed, we wait for that. + // java: the driver exits when its stdin is closed, wait for that. boolean didClose = driverProcess.waitFor(30, TimeUnit.SECONDS); if (!didClose) { System.err.println("WARNING: Timed out while waiting for driver process to exit"); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java index cdb3d0f5a..b2bfacb33 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java @@ -14,8 +14,11 @@ * limitations under the License. */ +// Port of network.ts. package com.microsoft.playwright.impl; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.NameValue; import com.microsoft.playwright.options.HttpHeader; import java.util.ArrayList; @@ -24,44 +27,77 @@ import java.util.Map; class RawHeaders { - private final List headersArray; + private final List headersArray; + // java: MultiMap is a map of lists. private final Map> headersMap = new LinkedHashMap<>(); - RawHeaders(List headers) { - headersArray = headers; - for (HttpHeader h: headers) { - String name = h.name.toLowerCase(); + static RawHeaders fromHeadersObjectLossy(Map headers) { + List headersArray = new ArrayList<>(); + for (Map.Entry entry : headers.entrySet()) { + if (entry.getValue() == null) { + continue; + } + NameValue header = new NameValue(); + header.name = entry.getKey(); + header.value = entry.getValue(); + headersArray.add(header); + } + return new RawHeaders(headersArray); + } + + RawHeaders(List headers) { + this.headersArray = headers; + for (NameValue header : headers) { + String name = header.name.toLowerCase(); List values = headersMap.get(name); if (values == null) { values = new ArrayList<>(); headersMap.put(name, values); } - values.add(h.value); + values.add(header.value); } } String get(String name) { List values = getAll(name); - if (values == null) { + if (values == null || values.isEmpty()) { return null; } return String.join("set-cookie".equals(name.toLowerCase()) ? "\n" : ", ", values); } List getAll(String name) { - return headersMap.get(name.toLowerCase()); + List values = headersMap.get(name.toLowerCase()); + return values == null ? new ArrayList<>() : new ArrayList<>(values); } Map headers() { Map result = new LinkedHashMap<>(); - for (String name: headersMap.keySet()) { + for (String name : headersMap.keySet()) { result.put(name, get(name)); } return result; } + // java: a new list of the public HttpHeader type on every call. List headersArray() { - return headersArray; + List result = new ArrayList<>(); + for (NameValue header : headersArray) { + HttpHeader h = new HttpHeader(); + h.name = header.name; + h.value = header.value; + result.add(h); + } + return result; } + // java: a module-level function of network.ts. + static void validateHeaders(Map headers) { + for (Map.Entry entry : headers.entrySet()) { + // java: a null value is a JavaScript null, typeof null is "object". + if (entry.getValue() == null) { + throw new PlaywrightException("Expected value of header \"" + entry.getKey() + "\" to be String, but \"object\" is found."); + } + } + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java index ef97945dc..9e8e4532b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java @@ -14,168 +14,250 @@ * limitations under the License. */ +// Port of network.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.Request; +import com.microsoft.playwright.impl.protocol.NameValue; +import com.microsoft.playwright.impl.protocol.RequestChannel; +import com.microsoft.playwright.impl.protocol.RequestInitializer; +import com.microsoft.playwright.impl.protocol.RequestSizes; import com.microsoft.playwright.options.HttpHeader; import com.microsoft.playwright.options.Sizes; import com.microsoft.playwright.options.Timing; +import java.io.IOException; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Map; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static com.microsoft.playwright.impl.Utils.toHeadersMap; -import static java.util.Arrays.asList; public class RequestImpl extends ChannelOwner implements Request { - private final byte[] postData; - private RequestImpl redirectedFrom; - private RequestImpl redirectedTo; - private final RawHeaders headers; - private RawHeaders rawHeaders; - String failure; - Timing timing; - boolean didFailOrFinish; - ResponseImpl existingResponse; - private FallbackOverrides fallbackOverrides; - private final FrameImpl frame; + // java: toClearCookiesParams is Serialization.toClearCookiesParams, BrowserContextImpl calls it there. + + // java: SerializedFallbackOverrides. + static class SerializedFallbackOverrides { + String url; + String method; + Map headers; + byte[] postDataBuffer; + } + // java: FallbackOverrides, built by RouteImpl from the Route options classes. static class FallbackOverrides { String url; String method; - byte[] postData; Map headers; + Object postData; } + private RequestImpl redirectedFrom; + private RequestImpl redirectedTo; + String failureText; + ResponseImpl response; + private final RawHeaders provisionalHeaders; + // java: the resolved value of _actualHeadersPromise. + private RawHeaders actualHeadersPromise; + final Timing timing; + private final SerializedFallbackOverrides fallbackOverrides = new SerializedFallbackOverrides(); + final RequestChannel channel = new RequestChannel(this); + final RequestInitializer requestInitializer; + + // java: from and fromNullable are not ported, generated results already hold the impl object. RequestImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - - if (initializer.has("frame")) { - frame = connection.getExistingObject(initializer.getAsJsonObject("frame").get("guid").getAsString()); - } else { - frame = null; - } - if (initializer.has("redirectedFrom")) { - redirectedFrom = connection.getExistingObject(initializer.getAsJsonObject("redirectedFrom").get("guid").getAsString()); - redirectedFrom.redirectedTo = this; - } - headers = new RawHeaders(asList(gson().fromJson(initializer.getAsJsonArray("headers"), HttpHeader[].class))); - if (initializer.has("postData")) { - postData = Base64.getDecoder().decode(initializer.get("postData").getAsString()); - } else { - postData = null; + requestInitializer = connection.protocolGson().fromJson(initializer, RequestInitializer.class); + this.redirectedFrom = requestInitializer.redirectedFrom; + if (this.redirectedFrom != null) { + this.redirectedFrom.redirectedTo = this; } + this.provisionalHeaders = new RawHeaders(requestInitializer.headers); + this.timing = new Timing(); + this.timing.startTime = 0; + this.timing.domainLookupStart = -1; + this.timing.domainLookupEnd = -1; + this.timing.connectStart = -1; + this.timing.secureConnectionStart = -1; + this.timing.connectEnd = -1; + this.timing.requestStart = -1; + this.timing.responseStart = -1; + this.timing.responseEnd = -1; } @Override - public ResponseImpl existingResponse() { - return existingResponse; + public String url() { + return fallbackOverrides.url != null && !fallbackOverrides.url.isEmpty() ? fallbackOverrides.url : requestInitializer.url; } @Override - public Map allHeaders() { - return getRawHeaders().headers(); + public String resourceType() { + return requestInitializer.resourceType; } @Override - public String failure() { - return failure; + public String method() { + return fallbackOverrides.method != null && !fallbackOverrides.method.isEmpty() ? fallbackOverrides.method : requestInitializer.method; } - PageImpl safePage() { - return frame == null ? null : frame.page; + @Override + public String postData() { + byte[] buffer = fallbackOverrides.postDataBuffer != null ? fallbackOverrides.postDataBuffer : requestInitializer.postData; + return buffer != null ? new String(buffer, StandardCharsets.UTF_8) : null; } @Override - public FrameImpl frame() { - if (frame == null) { - throw new PlaywrightException("Service Worker requests do not have an associated frame."); + public byte[] postDataBuffer() { + if (fallbackOverrides.postDataBuffer != null) { + return fallbackOverrides.postDataBuffer; } - if (frame.page == null) { - throw new PlaywrightException("Frame for this navigation request is not available, because the request\n" + - "was issued before the frame is created. You can check whether the request\n" + - "is a navigation request by calling isNavigationRequest() method."); + return requestInitializer.postData; + } + + // java: the parsed JSON is a JsonElement and the form entries are a JsonObject of strings. + JsonElement postDataJSON() { + String postData = postData(); + if (postData == null || postData.isEmpty()) { + return null; + } + + String contentType = headers().get("content-type"); + if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) { + JsonObject entries = new JsonObject(); + // java: new URLSearchParams(postData).entries(), parsed here. + String query = postData.startsWith("?") ? postData.substring(1) : postData; + for (String pair : query.split("&")) { + if (pair.isEmpty()) { + continue; + } + int index = pair.indexOf('='); + String k = index == -1 ? pair : pair.substring(0, index); + String v = index == -1 ? "" : pair.substring(index + 1); + entries.addProperty(decodeURLSearchParam(k), decodeURLSearchParam(v)); + } + return entries; + } + + try { + return parseJSON(postData); + } catch (JsonSyntaxException e) { + throw new PlaywrightException("POST data is not a valid JSON object: " + postData); } - return frame; } @Override public Map headers() { - if (fallbackOverrides != null && fallbackOverrides.headers != null) { - return new RawHeaders(Utils.toHeadersList(fallbackOverrides.headers)).headers(); + if (fallbackOverrides.headers != null) { + return RawHeaders.fromHeadersObjectLossy(fallbackOverrides.headers).headers(); + } + return provisionalHeaders.headers(); + } + + RawHeaders actualHeaders() { + if (fallbackOverrides.headers != null) { + return RawHeaders.fromHeadersObjectLossy(fallbackOverrides.headers); + } + + if (actualHeadersPromise == null) { + List headers = channel.rawRequestHeaders(NO_TIMEOUT).headers; + // java: a nested call may have set it while this one waited, the values are the same. + actualHeadersPromise = new RawHeaders(headers); } - return headers.headers(); + return actualHeadersPromise; + } + + @Override + public Map allHeaders() { + return wrapApiCall(() -> actualHeaders().headers(), null, true); } @Override public List headersArray() { - return getRawHeaders().headersArray(); + return wrapApiCall(() -> actualHeaders().headersArray(), null, true); } @Override public String headerValue(String name) { - return getRawHeaders().get(name); + return wrapApiCall(() -> actualHeaders().get(name), null, true); } @Override - public boolean isNavigationRequest() { - return initializer.get("isNavigationRequest").getAsBoolean(); + public ResponseImpl response() { + return channel.response(NO_TIMEOUT).response; + } + + ResponseImpl internalResponse() { + return channel.response(NO_TIMEOUT).response; } @Override - public String method() { - if (fallbackOverrides != null && fallbackOverrides.method != null) { - return fallbackOverrides.method; - } - return initializer.get("method").getAsString(); + public ResponseImpl existingResponse() { + return response; } @Override - public String postData() { - byte[] buffer = postDataBuffer(); - if (buffer == null) { - return null; + public FrameImpl frame() { + if (requestInitializer.frame == null) { + if (serviceWorker() == null) { + throw new PlaywrightException("Assertion error"); + } + throw new PlaywrightException("Service Worker requests do not have an associated frame."); } - return new String(buffer, StandardCharsets.UTF_8); + FrameImpl frame = requestInitializer.frame; + if (frame.page == null) { + throw new PlaywrightException(String.join("\n", + "Frame for this navigation request is not available, because the request", + "was issued before the frame is created. You can check whether the request", + "is a navigation request by calling isNavigationRequest() method.")); + } + return frame; + } + + PageImpl safePage() { + FrameImpl frame = requestInitializer.frame; + return frame != null ? frame.page : null; + } + + // java: not in the Java API, kept for targetClosedScope(). + WorkerImpl serviceWorker() { + return requestInitializer.serviceWorker; } @Override - public byte[] postDataBuffer() { - if (fallbackOverrides != null && fallbackOverrides.postData != null) { - return fallbackOverrides.postData; - } - return postData; + public boolean isNavigationRequest() { + return requestInitializer.isNavigationRequest != null && requestInitializer.isNavigationRequest; } @Override - public Request redirectedFrom() { + public RequestImpl redirectedFrom() { return redirectedFrom; } @Override - public Request redirectedTo() { + public RequestImpl redirectedTo() { return redirectedTo; } + // java: the error text itself, the Java API returns a String. @Override - public String resourceType() { - return initializer.get("resourceType").getAsString(); + public String failure() { + return failureText; } @Override - public ResponseImpl response() { - return channel.response(NO_TIMEOUT).response; + public Timing timing() { + return timing; } @Override @@ -184,52 +266,15 @@ public Sizes sizes() { if (response == null) { throw new PlaywrightException("Unable to fetch sizes for failed request"); } - RequestSizes s = response.channel.sizes(NO_TIMEOUT).sizes; + RequestSizes sizes = response.channel.sizes(NO_TIMEOUT).sizes; Sizes result = new Sizes(); - result.requestBodySize = s.requestBodySize; - result.requestHeadersSize = s.requestHeadersSize; - result.responseBodySize = s.responseBodySize; - result.responseHeadersSize = s.responseHeadersSize; + result.requestBodySize = sizes.requestBodySize; + result.requestHeadersSize = sizes.requestHeadersSize; + result.responseBodySize = sizes.responseBodySize; + result.responseHeadersSize = sizes.responseHeadersSize; return result; } - @Override - public Timing timing() { - return timing; - } - - @Override - public String url() { - if (fallbackOverrides != null && fallbackOverrides.url != null) { - return fallbackOverrides.url; - } - return initializer.get("url").getAsString(); - } - - Request finalRequest() { - return redirectedTo != null ? redirectedTo.finalRequest() : this; - } - - private RawHeaders getRawHeaders() { - if (fallbackOverrides != null && fallbackOverrides.headers != null) { - return new RawHeaders(Utils.toHeadersList(fallbackOverrides.headers)); - } - if (rawHeaders != null) { - return rawHeaders; - } - List headers = new ArrayList<>(); - for (NameValue nv : channel.rawRequestHeaders(NO_TIMEOUT).headers) { - HttpHeader h = new HttpHeader(); - h.name = nv.name; - h.value = nv.value; - headers.add(h); - } - - // The field may have been initialized in a nested call but it is ok. - rawHeaders = new RawHeaders(headers); - return rawHeaders; - } - void setResponseEndTiming(double responseEndTiming) { timing.responseEnd = responseEndTiming; if (timing.responseStart == -1) { @@ -237,25 +282,64 @@ void setResponseEndTiming(double responseEndTiming) { } } + RequestImpl finalRequest() { + return redirectedTo != null ? redirectedTo.finalRequest() : this; + } + void applyFallbackOverrides(FallbackOverrides overrides) { - if (fallbackOverrides == null) { - fallbackOverrides = new FallbackOverrides(); - } - if (overrides.url != null) { + if (overrides.url != null && !overrides.url.isEmpty()) { fallbackOverrides.url = overrides.url; } - if (overrides.method != null) { + if (overrides.method != null && !overrides.method.isEmpty()) { fallbackOverrides.method = overrides.method; } if (overrides.headers != null) { fallbackOverrides.headers = overrides.headers; } - if (overrides.postData != null) { - fallbackOverrides.postData = overrides.postData; + + if (overrides.postData instanceof String) { + fallbackOverrides.postDataBuffer = ((String) overrides.postData).getBytes(StandardCharsets.UTF_8); + } else if (overrides.postData instanceof byte[]) { + fallbackOverrides.postDataBuffer = (byte[]) overrides.postData; + } else if (overrides.postData != null) { + fallbackOverrides.postDataBuffer = gson().toJson(overrides.postData).getBytes(StandardCharsets.UTF_8); } } - FallbackOverrides fallbackOverridesForResume() { + SerializedFallbackOverrides fallbackOverridesForContinue() { return fallbackOverrides; } + + LongStandingScope targetClosedScope() { + WorkerImpl serviceWorker = serviceWorker(); + if (serviceWorker != null) + return serviceWorker.closedScope; + PageImpl page = safePage(); + if (page != null) + return page.closedOrCrashedScope; + return new LongStandingScope(this); + } + + // java: JSON.parse and the decoding of URLSearchParams, which have no Java counterpart. + static JsonElement parseJSON(String text) { + try { + JsonReader reader = new JsonReader(new StringReader(text)); + reader.setLenient(false); + JsonElement result = gson().getAdapter(JsonElement.class).read(reader); + if (reader.peek() != JsonToken.END_DOCUMENT) { + throw new JsonSyntaxException("Unexpected non-whitespace character after JSON"); + } + return result; + } catch (IOException e) { + throw new JsonSyntaxException(e); + } + } + + private static String decodeURLSearchParam(String value) { + try { + return URLDecoder.decode(value, "UTF-8"); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + return value.replace('+', ' '); + } + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java index 559571cdf..158bf93d9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java @@ -14,112 +14,123 @@ * limitations under the License. */ +// Port of network.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.microsoft.playwright.Frame; import com.microsoft.playwright.Response; +import com.microsoft.playwright.impl.protocol.RemoteAddr; +import com.microsoft.playwright.impl.protocol.ResourceTiming; +import com.microsoft.playwright.impl.protocol.ResponseChannel; +import com.microsoft.playwright.impl.protocol.ResponseInitializer; import com.microsoft.playwright.options.HttpHeader; import com.microsoft.playwright.options.SecurityDetails; import com.microsoft.playwright.options.ServerAddr; -import com.microsoft.playwright.options.Timing; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Map; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static java.util.Arrays.asList; - public class ResponseImpl extends ChannelOwner implements Response { - private final RawHeaders headers; - private RawHeaders rawHeaders; - final RequestImpl request; + private final RawHeaders provisionalHeaders; + // java: the resolved value of _actualHeadersPromise. + private RawHeaders actualHeadersPromise; + private final RequestImpl request; + final WaitableResult finishedPromise = new WaitableResult<>(); final ResponseChannel channel = new ResponseChannel(this); + final ResponseInitializer responseInitializer; + + // java: from and fromNullable are not ported, generated results already hold the impl object. ResponseImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - headers = new RawHeaders(asList(gson().fromJson(initializer.getAsJsonArray("headers"), HttpHeader[].class))); - request = connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString()); - request.existingResponse = this; - request.timing = gson().fromJson(initializer.get("timing"), Timing.class); + responseInitializer = connection.protocolGson().fromJson(initializer, ResponseInitializer.class); + this.provisionalHeaders = new RawHeaders(responseInitializer.headers); + this.request = responseInitializer.request; + this.request.response = this; + assignTiming(this.request, responseInitializer.timing); } @Override - public Map allHeaders() { - return getRawHeaders().headers(); + public String url() { + return responseInitializer.url; } @Override - public byte[] body() { - return channel.body(NO_TIMEOUT).binary; + public boolean ok() { + // Status 0 is for file:// URLs + return responseInitializer.status == 0 || (responseInitializer.status >= 200 && responseInitializer.status <= 299); } @Override - public String finished() { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableNever() { - @Override - public boolean isDone() { - return request.didFailOrFinish; - } - @Override - public String get() { - return request.failure(); - } - }); - PageImpl page = request.safePage(); - if (page != null) { - waitables.add(page.createWaitForCloseHelper()); - waitables.add(page.createWaitableTimeout(null)); - } - runUntil(() -> {}, new WaitableRace<>(waitables)); - return request.failure(); + public int status() { + return responseInitializer.status; } @Override - public Frame frame() { - return request().frame(); + public String statusText() { + return responseInitializer.statusText; } @Override public boolean fromServiceWorker() { - return initializer.get("fromServiceWorker").getAsBoolean(); + return responseInitializer.fromServiceWorker != null && responseInitializer.fromServiceWorker; } @Override - public String httpVersion() { - return channel.httpVersion(NO_TIMEOUT).value; + public Map headers() { + return provisionalHeaders.headers(); + } + + RawHeaders actualHeaders() { + if (actualHeadersPromise == null) { + actualHeadersPromise = new RawHeaders(channel.rawResponseHeaders(NO_TIMEOUT).headers); + } + return actualHeadersPromise; } @Override - public Map headers() { - return headers.headers(); + public Map allHeaders() { + return actualHeaders().headers(); } @Override public List headersArray() { - return getRawHeaders().headersArray(); + return actualHeaders().headersArray(); } @Override public String headerValue(String name) { - return getRawHeaders().get(name); + return actualHeaders().get(name); } @Override public List headerValues(String name) { - return getRawHeaders().getAll(name); + return actualHeaders().getAll(name); } @Override - public boolean ok() { - return status() == 0 || (status() >= 200 && status() <= 299); + public String finished() { + return request().targetClosedScope().race(finishedPromise); + } + + @Override + public byte[] body() { + return channel.body(NO_TIMEOUT).binary; + } + + @Override + public String text() { + byte[] content = body(); + return new String(content, StandardCharsets.UTF_8); + } + + // java: the parsed JSON is a JsonElement. + JsonElement json() { + String content = text(); + return RequestImpl.parseJSON(content); } @Override @@ -128,18 +139,8 @@ public RequestImpl request() { } @Override - public SecurityDetails securityDetails() { - com.microsoft.playwright.impl.protocol.SecurityDetails value = channel.securityDetails(NO_TIMEOUT).value; - if (value == null) { - return null; - } - SecurityDetails result = new SecurityDetails(); - result.issuer = value.issuer; - result.protocol = value.protocol; - result.subjectName = value.subjectName; - result.validFrom = value.validFrom; - result.validTo = value.validTo; - return result; + public FrameImpl frame() { + return request.frame(); } @Override @@ -148,6 +149,7 @@ public ServerAddr serverAddr() { if (value == null) { return null; } + // java: the protocol struct is converted to the public options type. ServerAddr result = new ServerAddr(); result.ipAddress = value.ipAddress; result.port = value.port; @@ -155,36 +157,35 @@ public ServerAddr serverAddr() { } @Override - public int status() { - return initializer.get("status").getAsInt(); - } - - @Override - public String statusText() { - return initializer.get("statusText").getAsString(); + public SecurityDetails securityDetails() { + com.microsoft.playwright.impl.protocol.SecurityDetails value = channel.securityDetails(NO_TIMEOUT).value; + if (value == null) { + return null; + } + // java: the protocol struct is converted to the public options type. + SecurityDetails result = new SecurityDetails(); + result.issuer = value.issuer; + result.protocol = value.protocol; + result.subjectName = value.subjectName; + result.validFrom = value.validFrom; + result.validTo = value.validTo; + return result; } @Override - public String text() { - return new String(body(), StandardCharsets.UTF_8); + public String httpVersion() { + return channel.httpVersion(NO_TIMEOUT).value; } - @Override - public String url() { - return initializer.get("url").getAsString(); - } - - private RawHeaders getRawHeaders() { - if (rawHeaders == null) { - List headers = new ArrayList<>(); - for (NameValue nv : channel.rawResponseHeaders(NO_TIMEOUT).headers) { - HttpHeader h = new HttpHeader(); - h.name = nv.name; - h.value = nv.value; - headers.add(h); - } - rawHeaders = new RawHeaders(headers); - } - return rawHeaders; + // java: Object.assign(this._request._timing, this._initializer.timing), field by field. + private static void assignTiming(RequestImpl request, ResourceTiming timing) { + request.timing.startTime = timing.startTime; + request.timing.domainLookupStart = timing.domainLookupStart; + request.timing.domainLookupEnd = timing.domainLookupEnd; + request.timing.connectStart = timing.connectStart; + request.timing.secureConnectionStart = timing.secureConnectionStart; + request.timing.connectEnd = timing.connectEnd; + request.timing.requestStart = timing.requestStart; + request.timing.responseStart = timing.responseStart; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java new file mode 100644 index 000000000..7e0d6e767 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java @@ -0,0 +1,163 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of network.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.Route; +import com.microsoft.playwright.impl.protocol.BrowserContextSetNetworkInterceptionPatternsParams.BrowserContextSetNetworkInterceptionPatternsParamsPatterns; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; + +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +class RouteHandler { + private int handledCount = 0; + private final String baseURL; + private final int times; + final UrlMatcher url; + final Consumer handler; + private boolean ignoreException = false; + private final Set activeInvocations = new LinkedHashSet<>(); + // java: _savedZone is not ported, there are no zones. + + // java: { complete: Promise, route: Route }. + private static class HandlerInvocation { + final WaitableResult complete = new WaitableResult<>(); + final RouteImpl route; + + HandlerInvocation(RouteImpl route) { + this.route = route; + } + } + + // java: UrlMatcher.forGlob() has resolved and validated a glob against the base URL already. A null times + // is Number.MAX_SAFE_INTEGER. + RouteHandler(String baseURL, UrlMatcher url, Consumer handler, Integer times) { + this.baseURL = baseURL; + this.times = times != null ? times : Integer.MAX_VALUE; + this.url = url; + this.handler = handler; + } + + // java: the result is a list of the BrowserContext pattern struct; the Page struct has the same fields + // and serializes the same, so the element type is left to the caller. + @SuppressWarnings("unchecked") + static List prepareInterceptionPatterns(List handlers) { + List patterns = new ArrayList<>(); + boolean all = false; + for (RouteHandler handler : handlers) { + BrowserContextSetNetworkInterceptionPatternsParamsPatterns serialized = serializeURLMatch(handler.url); + if (serialized != null) { + patterns.add(serialized); + } else { + all = true; + } + } + if (all) { + BrowserContextSetNetworkInterceptionPatternsParamsPatterns pattern = new BrowserContextSetNetworkInterceptionPatternsParamsPatterns(); + pattern.glob = "**/*"; + patterns = new ArrayList<>(); + patterns.add(pattern); + } + return (List) (List) patterns; + } + + boolean matches(String requestURL) { + return url.test(requestURL); + } + + // java: no _savedZone.run(), there are no zones. + boolean handle(RouteImpl route) { + return handleImpl(route); + } + + private boolean handleImpl(RouteImpl route) { + HandlerInvocation handlerInvocation = new HandlerInvocation(route); + activeInvocations.add(handlerInvocation); + try { + return handleInternal(route); + } catch (RuntimeException e) { + // If the handler was stopped (without waiting for completion), we ignore all exceptions. + if (ignoreException) { + return false; + } + if (e instanceof TargetClosedError) { + // We are failing in the handler because the target close closed. + // Give user a hint! + // java: exceptions are immutable, a new one carries the rewritten message. + throw new TargetClosedError("\"" + e.getMessage() + "\" while running route callback.\nConsider awaiting `await page.unrouteAll({ behavior: 'ignoreErrors' })`\nbefore the end of the test to ignore remaining routes in flight.", e); + } + throw e; + } finally { + handlerInvocation.complete.complete(null); + activeInvocations.remove(handlerInvocation); + } + } + + void stop(String behavior) { + // When a handler is manually unrouted or its page/context is closed we either + // - wait for the current handler invocations to finish + // - or do not wait, if the user opted out of it, but swallow all exceptions + // that happen after the unroute/close. + if ("ignoreErrors".equals(behavior)) { + ignoreException = true; + } else { + // java: the handlers are synchronous, so every active invocation that did not throw is a caller + // further up this stack and completes only after this call returns; there is nothing to wait for. + } + } + + private boolean handleInternal(RouteImpl route) { + ++handledCount; + WaitableResult handledPromise = route.startHandling(); + // Extract handler into a variable to avoid [RouteHandler.handler] in the stack. + Consumer handler = this.handler; + handler.accept(route); + // java: Promise.all([handledPromise, handler(route, route.request())]) cannot wait for a route the + // handler keeps to handle later: the chain stops here as if the route was handled, and a later + // fallback() continues the request (see RouteImpl.fallback). + if (!handledPromise.isDone()) { + route.handlerReturned = true; + return true; + } + return handledPromise.get(); + } + + boolean willExpire() { + return handledCount + 1 >= times; + } + + // java: serializeURLMatch of isomorphic/urlMatch.ts for a UrlMatcher. + private static BrowserContextSetNetworkInterceptionPatternsParamsPatterns serializeURLMatch(UrlMatcher match) { + BrowserContextSetNetworkInterceptionPatternsParamsPatterns result = new BrowserContextSetNetworkInterceptionPatternsParamsPatterns(); + if (match.glob != null) { + result.glob = match.glob; + return result; + } + if (match.pattern != null) { + result.regexSource = match.pattern.pattern(); + result.regexFlags = toJsRegexFlags(match.pattern); + return result; + } + // Functions cannot be serialized + return null; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java index bb8f64171..5d5556b87 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -1,12 +1,12 @@ /* * Copyright (c) Microsoft Corporation. - *

+ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - *

+ * * http://www.apache.org/licenses/LICENSE-2.0 - *

+ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -14,304 +14,271 @@ * limitations under the License. */ +// Port of network.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.microsoft.playwright.*; import com.microsoft.playwright.APIResponse; -import com.microsoft.playwright.options.RequestOptions; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.Route; +import com.microsoft.playwright.impl.protocol.RouteAbortParams; +import com.microsoft.playwright.impl.protocol.RouteChannel; +import com.microsoft.playwright.impl.protocol.RouteContinueParams; +import com.microsoft.playwright.impl.protocol.RouteFulfillParams; +import com.microsoft.playwright.impl.protocol.RouteInitializer; +import com.microsoft.playwright.impl.protocol.RouteRedirectNavigationRequestParams; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; +import java.nio.file.Path; import java.util.Base64; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; -import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.isomorphic.Headers.headersObjectToArray; +import static com.microsoft.playwright.impl.isomorphic.MimeType.getMimeTypeForPath; public class RouteImpl extends ChannelOwner implements Route { - private final RequestImpl request; - private boolean handled; - BrowserContextImpl browserContext; - boolean fallbackCalled; - boolean shouldResumeIfFallbackIsCalled; + private WaitableResult handlingPromise = null; + BrowserContextImpl context; + boolean didThrow = false; final RouteChannel channel = new RouteChannel(this); + private final RouteInitializer routeInitializer; - public RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - request = connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString()); - } + // java: from is not ported, generated results already hold the impl object. - @Override - public void abort(String errorCode) { - handleRoute(() -> { - RouteAbortParams params = new RouteAbortParams(); - params.errorCode = errorCode; - raceWithTargetClose("abort", params); - }); - } - - boolean isHandled() { - return handled; + RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + routeInitializer = connection.protocolGson().fromJson(initializer, RouteInitializer.class); } @Override - public void resume(ResumeOptions options) { - handleRoute(() -> { - applyOverrides(convertType(options, FallbackOptions.class)); - raceWithTargetClose("continue", continueParams(false)); - }); - } - - // java: upstream awaits _innerContinue(true) and ignores its error; nothing observes the reply here. - void continueAsFallback() { - checkNotHandled(); - handled = true; - sendMessageAsync("continue", continueParams(true)); + public RequestImpl request() { + return routeInitializer.request; } - private void handleRoute(Runnable callback) { - checkNotHandled(); - callback.run(); - handled = true; + // java: takes the pending reply of a message sent with sendMessageAsync. + private void raceWithTargetClose(WaitableResult promise) { + // When page closes or crashes, we catch any potential rejects from this Route. + // Note that page could be missing when routing popup's initial request that + // does not have a Page initialized just yet. + request().targetClosedScope().safeRace(promise); } - // java: pumps the connection until the reply arrives; when the page closes first the call returns - // without an error, as safeRace() of the target closed scope does upstream. - private void raceWithTargetClose(String method, Object params) { - WaitableResult result = sendMessageAsync(method, params); - PageImpl page = request.safePage(); - if (page == null) { - runUntil(() -> {}, result); - return; - } - if (page.isClosed()) { - return; - } - Waitable closed = page.createWaitForCloseHelper(); - runUntil(() -> {}, new WaitableRace<>(Arrays.asList(result, new Waitable() { - @Override - public boolean isDone() { - return closed.isDone(); - } - - @Override - public JsonElement get() { - return null; - } - - @Override - public void dispose() { - closed.dispose(); - } - }))); + WaitableResult startHandling() { + handlingPromise = new WaitableResult<>(); + return handlingPromise; } @Override public void fallback(FallbackOptions options) { - fallbackCalled = true; - if (handled) { - throw new PlaywrightException("Route is already handled!"); + if (options == null) { + options = new FallbackOptions(); } - applyOverrides(options); - if (shouldResumeIfFallbackIsCalled) { - continueAsFallback(); + checkNotHandled(); + request().applyFallbackOverrides(fallbackOverrides(options.url, options.method, options.headers, options.postData)); + reportHandled(false); + // java: nobody waits for a fallback() after the handler returned (see RouteHandler.handleInternal), so the + // request continues as the end of BrowserContext.onRoute() does. + if (handlerReturned) { + try { + innerContinue(true); + } catch (PlaywrightException e) { + } } } @Override - public APIResponse fetch(FetchOptions fetchOptions) { - RequestOptionsImpl options = convertType(fetchOptions, RequestOptionsImpl.class); - if (options == null) { - options = new RequestOptionsImpl(); - } - if (options.method == null) { - options.method = request.method(); - } - if (options.headers == null) { - options.headers = request.headers(); - } - if (fetchOptions != null && fetchOptions.postData != null) { - options.data = fetchOptions.postData; - } else { - options.data = request.postDataBuffer(); - } - if (fetchOptions != null && fetchOptions.timeout != null) { - options.timeout = fetchOptions.timeout; - } - APIRequestContextImpl apiRequest = browserContext.request(); - String url = (fetchOptions == null || fetchOptions.url == null) ? request().url() : fetchOptions.url; - return apiRequest.fetch(url, options); + public void abort(String errorCode) { + handleRoute(() -> { + RouteAbortParams params = new RouteAbortParams(); + params.errorCode = errorCode; + raceWithTargetClose(sendMessageAsync("abort", params)); + }); } - private void applyOverrides(FallbackOptions options) { - if (options == null) { - return; - } - RequestImpl.FallbackOverrides overrides = new RequestImpl.FallbackOverrides(); - overrides.url = options.url; - overrides.method = options.method; - overrides.headers = options.headers; - if (options.postData != null) { - overrides.postData = getPostDataBytes(options.postData); - } - request().applyFallbackOverrides(overrides); + void redirectNavigationRequest(String url) { + handleRoute(() -> { + RouteRedirectNavigationRequestParams params = new RouteRedirectNavigationRequestParams(); + params.url = url; + raceWithTargetClose(sendMessageAsync("redirectNavigationRequest", params)); + }); } - private RouteContinueParams continueParams(boolean isFallback) { - RequestImpl.FallbackOverrides options = request().fallbackOverridesForResume(); - RouteContinueParams params = new RouteContinueParams(); - if (options != null) { - params.url = options.url; - params.method = options.method; - if (options.headers != null) { - params.headers = toNameValues(withoutNullValues(options.headers)); - } - params.postData = options.postData; + @Override + public APIResponse fetch(FetchOptions options) { + if (options == null) { + options = new FetchOptions(); } - params.isFallback = isFallback; - return params; + FetchOptions fetchOptions = options; + return wrapApiCall(() -> { + // java: the FetchOptions fields as RequestOptionsImpl, data is options.postData. + RequestOptionsImpl requestOptions = new RequestOptionsImpl(); + requestOptions.data = fetchOptions.postData; + requestOptions.method = fetchOptions.method; + requestOptions.headers = fetchOptions.headers; + requestOptions.maxRedirects = fetchOptions.maxRedirects; + requestOptions.maxRetries = fetchOptions.maxRetries; + requestOptions.timeout = fetchOptions.timeout; + return ((APIRequestContextImpl) context.request()).innerFetch(fetchOptions.url, request(), requestOptions, null); + }, null, false); } - private static Map withoutNullValues(Map map) { - Map result = new LinkedHashMap<>(); - for (Map.Entry e : map.entrySet()) { - if (e.getValue() != null) { - result.put(e.getKey(), e.getValue()); - } - } - return result; + @Override + public void fulfill(FulfillOptions options) { + fulfill(options, null); } - private static List toNameValues(Map map) { - List result = new ArrayList<>(); - for (Map.Entry e : map.entrySet()) { - if (e.getValue() == null) { - throw new PlaywrightException("Value cannot be null"); - } - NameValue nv = new NameValue(); - nv.name = e.getKey(); - nv.value = e.getValue(); - result.add(nv); - } - return result; + // java: json is the json option of upstream, which FulfillOptions does not have; the value is a JsonElement. + void fulfill(FulfillOptions options, JsonElement json) { + handleRoute(() -> { + innerFulfill(options, json); + }); } - private static byte[] getPostDataBytes(Object postData) { - if (postData instanceof byte[]) { - return (byte[]) postData; - } - if (postData instanceof String) { - return ((String) postData).getBytes(StandardCharsets.UTF_8); + private void handleRoute(Runnable callback) { + checkNotHandled(); + try { + callback.run(); + reportHandled(true); + } catch (RuntimeException e) { + didThrow = true; + throw e; } - throw new PlaywrightException("postData must be either String or byte[], found: " + postData.getClass().getName()); } - @Override - public void fulfill(FulfillOptions options) { - handleRoute(() -> fulfillImpl(options)); - } - - private void fulfillImpl(FulfillOptions options) { + private void innerFulfill(FulfillOptions options, JsonElement json) { if (options == null) { options = new FulfillOptions(); } - - Integer status = options.status; - Map headersOption = options.headers; String fetchResponseUid = null; + Integer statusOption = options.status; + Map headersOption = options.headers; + // java: body is a String (body) or a byte[] (bodyBytes). + Object body = options.body != null ? options.body : options.bodyBytes; + + if (json != null) { + if (body != null) { + throw new PlaywrightException("Can specify either body or json parameters"); + } + body = json.toString(); + } - if (options.response != null) { - if (status == null) { - status = options.response.status(); + if (options.response instanceof APIResponseImpl) { + APIResponseImpl response = (APIResponseImpl) options.response; + if (statusOption == null) { + statusOption = response.status(); } if (headersOption == null) { - headersOption = options.response.headers(); + headersOption = response.headers(); + } + if (body == null && options.path == null) { + if (response.request.connection == this.connection) { + fetchResponseUid = response.fetchUid(); + } else { + body = response.body(); + } } } - if (status == null) { - status = 200; - } - String body = null; + boolean isBase64 = false; int length = 0; if (options.path != null) { - try { - byte[] buffer = Files.readAllBytes(options.path); - body = Base64.getEncoder().encodeToString(buffer); - isBase64 = true; - length = buffer.length; - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file: " + options.path, e); - } - } else if (options.body != null) { - body = options.body; + byte[] buffer = readFile(options.path); + body = Base64.getEncoder().encodeToString(buffer); + isBase64 = true; + length = buffer.length; + } else if (body instanceof String) { isBase64 = false; - length = body.getBytes().length; - } else if (options.bodyBytes != null) { - body = Base64.getEncoder().encodeToString(options.bodyBytes); + length = ((String) body).getBytes(StandardCharsets.UTF_8).length; + } else if (body != null) { + byte[] buffer = (byte[]) body; + length = buffer.length; + body = Base64.getEncoder().encodeToString(buffer); isBase64 = true; - length = options.bodyBytes.length; - } else if (options.response != null) { - APIResponseImpl response = (APIResponseImpl) options.response; - if (response.context.connection == connection) { - fetchResponseUid = response.fetchUid(); - } else { - byte[] bodyBytes = response.body(); - body = Base64.getEncoder().encodeToString(bodyBytes); - isBase64 = true; - length = bodyBytes.length; - } } - Map headers = new LinkedHashMap<>(); if (headersOption != null) { - for (Map.Entry h : headersOption.entrySet()) { - headers.put(h.getKey().toLowerCase(), h.getValue()); + for (Map.Entry header : headersOption.entrySet()) { + headers.put(header.getKey().toLowerCase(), String.valueOf(header.getValue())); } } if (options.contentType != null) { headers.put("content-type", options.contentType); + } else if (json != null && !json.isJsonNull()) { + headers.put("content-type", "application/json"); } else if (options.path != null) { - headers.put("content-type", Utils.mimeType(options.path)); + String mimeType = getMimeTypeForPath(options.path.toString()); + headers.put("content-type", mimeType != null ? mimeType : "application/octet-stream"); } if (length != 0 && !headers.containsKey("content-length")) { - headers.put("content-length", Integer.toString(length)); + headers.put("content-length", String.valueOf(length)); } + RouteFulfillParams params = new RouteFulfillParams(); - params.status = status; - params.headers = toNameValues(headers); + params.status = statusOption != null && statusOption != 0 ? statusOption : 200; + params.headers = headersObjectToArray(headers); + params.body = (String) body; params.isBase64 = isBase64; - params.body = body; params.fetchResponseUid = fetchResponseUid; - raceWithTargetClose("fulfill", params); + raceWithTargetClose(sendMessageAsync("fulfill", params)); } + // java: resume() is continue() of the Node.js API. @Override - public RequestImpl request() { - return request; - } - - void redirectNavigationRequest(String redirectURL) { + public void resume(ResumeOptions options) { + ResumeOptions resumeOptions = options == null ? new ResumeOptions() : options; handleRoute(() -> { - RouteRedirectNavigationRequestParams params = new RouteRedirectNavigationRequestParams(); - params.url = redirectURL; - raceWithTargetClose("redirectNavigationRequest", params); + request().applyFallbackOverrides(fallbackOverrides(resumeOptions.url, resumeOptions.method, resumeOptions.headers, resumeOptions.postData)); + innerContinue(false /* isFallback */); }); } - private void checkNotHandled() { - if (handled) { + void checkNotHandled() { + if (handlingPromise == null) { throw new PlaywrightException("Route is already handled!"); } } + void reportHandled(boolean done) { + WaitableResult chain = handlingPromise; + handlingPromise = null; + chain.complete(done); + } + + void innerContinue(boolean isFallback) { + RequestImpl.SerializedFallbackOverrides options = request().fallbackOverridesForContinue(); + RouteContinueParams params = new RouteContinueParams(); + params.url = options.url; + params.method = options.method; + params.headers = options.headers != null ? headersObjectToArray(options.headers) : null; + params.postData = options.postDataBuffer; + params.isFallback = isFallback; + raceWithTargetClose(sendMessageAsync("continue", params)); + } + + // java: members with no counterpart upstream; handlerReturned is set by RouteHandler when the handler + // returned before it handled the route or fell back. + boolean handlerReturned; + + private static RequestImpl.FallbackOverrides fallbackOverrides(String url, String method, Map headers, Object postData) { + RequestImpl.FallbackOverrides overrides = new RequestImpl.FallbackOverrides(); + overrides.url = url; + overrides.method = method; + overrides.headers = headers; + overrides.postData = postData; + return overrides; + } + + private static byte[] readFile(Path path) { + try { + return Files.readAllBytes(path); + } catch (IOException e) { + throw new PlaywrightException("Failed to read from file: " + path, e); + } + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Router.java b/playwright/src/main/java/com/microsoft/playwright/impl/Router.java deleted file mode 100644 index 71d0a8383..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Router.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.microsoft.playwright.Route; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; - -class Router { - private List routes = new ArrayList<>(); - - private static class RouteInfo { - final UrlMatcher matcher; - final Consumer handler; - Integer times; - - RouteInfo(UrlMatcher matcher, Consumer handler, Integer times) { - this.matcher = matcher; - this.handler = handler; - this.times = times; - } - - void handle(RouteImpl route) { - handler.accept(route); - } - - boolean decrementRemainingCallCount() { - if (times == null) { - return false; - } - --times; - return times <= 0; - } - } - - void add(UrlMatcher matcher, Consumer handler, Integer times) { - routes.add(0, new RouteInfo(matcher, handler, times)); - } - - void remove(UrlMatcher matcher, Consumer handler) { - routes = routes.stream() - .filter(info -> !info.matcher.equals(matcher) || (handler != null && info.handler != handler)) - .collect(Collectors.toList()); - } - - void removeAll() { - routes.clear(); - } - - enum HandleResult { NoMatchingHandler, Handled, Fallback, PendingHandler } - HandleResult handle(RouteImpl route) { - HandleResult result = HandleResult.NoMatchingHandler; - for (RouteInfo info : new ArrayList<>(routes)) { - if (!info.matcher.test(route.request().url())) { - continue; - } - if (!routes.contains(info)) { - continue; - } - if (info.decrementRemainingCallCount()) { - routes.remove(info); - } - route.fallbackCalled = false; - info.handle(route); - if (route.isHandled()) { - return HandleResult.Handled; - } - // Not immediately handled and fallback() was not called => the route - // must be handled asynchronously. - if (!route.fallbackCalled) { - route.shouldResumeIfFallbackIsCalled = true; - return HandleResult.PendingHandler; - } - // Fallback was called, continue to the remaining handlers. - result = HandleResult.Fallback; - } - return result; - } - - JsonObject interceptionPatterns() { - List matchers = routes.stream().map(r -> r.matcher).collect(Collectors.toList()); - return Utils.interceptionPatterns(matchers); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastFrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastFrameImpl.java index e70b5d51a..c067b40dc 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastFrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastFrameImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of the frame object that screencast.ts passes to onFrame (a plain object upstream). package com.microsoft.playwright.impl; import com.microsoft.playwright.ScreencastFrame; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java index 7dd0adba1..5e4d62cb3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of screencast.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -24,10 +25,12 @@ import java.nio.file.Path; import java.util.function.Consumer; +import java.util.function.Supplier; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static com.microsoft.playwright.impl.Utils.toProtocol; +// java: onFrame receives a ScreencastFrame and the frame event arrives through handleScreencastFrame. class ScreencastImpl implements Screencast { private final PageImpl page; private boolean started; @@ -53,50 +56,71 @@ void handleScreencastFrame(JsonObject params) { // The server sends the next frame only after the previous one is acknowledged. PageScreencastFrameAckParams ackParams = new PageScreencastFrameAckParams(); ackParams.frameId = params.get("frameId").getAsInt(); - page.sendMessageAsync("screencastFrameAck", ackParams); + try { + page.sendMessageAsync("screencastFrameAck", ackParams); + } catch (PlaywrightException e) { + } } } + R wrapApiCall(Supplier func, String title, boolean internal) { + return page.wrapApiCall(func, title, internal); + } + @Override public AutoCloseable start(StartOptions options) { + if (options == null) { + options = new StartOptions(); + } if (started) { throw new PlaywrightException("Screencast is already started"); } started = true; + if (options.onFrame != null) { + onFrame = options.onFrame; + } PageScreencastStartParams params = new PageScreencastStartParams(); - if (options != null) { - if (options.onFrame != null) { - onFrame = options.onFrame; - } - if (options.size != null) { - params.size = toProtocol(options.size, PageScreencastStartParams.PageScreencastStartParamsSize.class); - } - params.quality = options.quality; - params.fps = options.fps; - params.sendFrames = options.onFrame != null; - params.record = options.path != null; - savePath = options.path; - } else { - params.sendFrames = false; - params.record = false; + if (options.size != null) { + params.size = toProtocol(options.size, PageScreencastStartParams.PageScreencastStartParamsSize.class); } + params.quality = options.quality; + params.fps = options.fps; + params.sendFrames = options.onFrame != null; + params.record = options.path != null; PageScreencastStartResult result = page.channel.screencastStart(params, NO_TIMEOUT); - if (result != null && result.artifact != null) { + if (result.artifact != null) { artifact = result.artifact; + savePath = options.path; } - return new DisposableStub(this::stop); + return new DisposableStub(() -> stop()); } @Override public void stop() { - started = false; - onFrame = null; - page.channel.screencastStop(NO_TIMEOUT); - if (savePath != null && artifact != null) { - artifact.saveAs(savePath); - } - artifact = null; - savePath = null; + // java: @apiCall() is wrapApiCall without a title. + wrapApiCall(() -> { + started = false; + onFrame = null; + page.channel.screencastStop(NO_TIMEOUT); + if (savePath != null && artifact != null) { + artifact.saveAs(savePath); + } + artifact = null; + savePath = null; + return null; + }, null, false); + } + + @Override + public AutoCloseable showActions(ShowActionsOptions options) { + PageScreencastShowActionsParams params = toProtocol(options, PageScreencastShowActionsParams.class); + page.channel.screencastShowActions(params, NO_TIMEOUT); + return new DisposableStub(() -> page.channel.screencastHideActions(NO_TIMEOUT)); + } + + @Override + public void hideActions() { + page.channel.screencastHideActions(NO_TIMEOUT); } @Override @@ -105,11 +129,11 @@ public AutoCloseable showOverlay(String html, ShowOverlayOptions options) { params.html = html; PageScreencastShowOverlayResult result = page.channel.screencastShowOverlay(params, NO_TIMEOUT); String id = result.id; - return () -> { + return new DisposableStub(() -> { PageScreencastRemoveOverlayParams removeParams = new PageScreencastRemoveOverlayParams(); removeParams.id = id; page.channel.screencastRemoveOverlay(removeParams, NO_TIMEOUT); - }; + }); } @Override @@ -119,13 +143,6 @@ public void showChapter(String title, ShowChapterOptions options) { page.channel.screencastChapter(params, NO_TIMEOUT); } - @Override - public AutoCloseable showActions(ShowActionsOptions options) { - PageScreencastShowActionsParams params = toProtocol(options, PageScreencastShowActionsParams.class); - page.channel.screencastShowActions(params, NO_TIMEOUT); - return new DisposableStub(this::hideActions); - } - @Override public void showOverlays() { PageScreencastSetOverlayVisibleParams params = new PageScreencastSetOverlayVisibleParams(); @@ -133,11 +150,6 @@ public void showOverlays() { page.channel.screencastSetOverlayVisible(params, NO_TIMEOUT); } - @Override - public void hideActions() { - page.channel.screencastHideActions(NO_TIMEOUT); - } - @Override public void hideOverlays() { PageScreencastSetOverlayVisibleParams params = new PageScreencastSetOverlayVisibleParams(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java index cbf8ff602..140c589bd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of selectors.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -21,36 +22,21 @@ import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.Selectors; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static java.nio.charset.StandardCharsets.UTF_8; +import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; +import static com.microsoft.playwright.impl.Serialization.gson; public class SelectorsImpl extends LoggingSupport implements Selectors { - protected final List contextsForSelectors = new ArrayList<>(); protected final List selectorEngines = new ArrayList<>(); - + // java: defaults to data-testid, upstream leaves it undefined until set. String testIdAttributeName = "data-testid"; - - @Override - public void setTestIdAttribute(String attributeName) { - if (attributeName == null) { - throw new PlaywrightException("Test id attribute cannot be null"); - } - testIdAttributeName = attributeName; - for (BrowserContextImpl context : contextsForSelectors) { - try { - BrowserContextSetTestIdAttributeNameParams params = new BrowserContextSetTestIdAttributeNameParams(); - params.testIdAttributeName = attributeName; - context.sendMessageAsync("setTestIdAttributeName", params); - } catch (PlaywrightException e) { - } - } - } + protected final Set contextsForSelectors = new LinkedHashSet<>(); @Override public void register(String name, String script, RegisterOptions options) { @@ -59,23 +45,19 @@ public void register(String name, String script, RegisterOptions options) { @Override public void register(String name, Path path, RegisterOptions options) { - byte[] buffer; - try { - buffer = Files.readAllBytes(path); - } catch (IOException e) { - throw new PlaywrightException("Failed to read selector from file: " + path, e); - } - registerImpl(name, new String(buffer, UTF_8), options); + registerImpl(name, path, options); } - private void registerImpl(String name, String script, RegisterOptions options) { + // java: the core of the String and Path overloads. + private void registerImpl(String name, Object script, RegisterOptions options) { if (selectorEngines.stream().anyMatch(engine -> name.equals(engine.name))) { throw new PlaywrightException("selectors.register: \"" + name + "\" selector engine has been already registered"); } + String source = evaluationScript(script, false); SelectorEngine engine = new SelectorEngine(); engine.name = name; - engine.source = script; + engine.source = source; if (options != null) { engine.contentScript = options.contentScript; } @@ -86,4 +68,31 @@ private void registerImpl(String name, String script, RegisterOptions options) { } selectorEngines.add(engine); } + + @Override + public void setTestIdAttribute(String attributeName) { + if (attributeName == null) { + throw new PlaywrightException("Test id attribute cannot be null"); + } + testIdAttributeName = attributeName; + LocatorImpl.setTestIdAttribute(this, attributeName); + for (BrowserContextImpl context : contextsForSelectors) { + context.options.testIdAttributeName = attributeName; + try { + BrowserContextSetTestIdAttributeNameParams params = new BrowserContextSetTestIdAttributeNameParams(); + params.testIdAttributeName = attributeName; + context.sendMessageAsync("setTestIdAttributeName", params); + } catch (PlaywrightException e) { + } + } + } + + // java: { ...options } of any options type is a JSON round-trip through the same class. + @SuppressWarnings("unchecked") + T withSelectorOptions(T options) { + JsonObject json = gson().toJsonTree(options).getAsJsonObject(); + json.add("selectorEngines", gson().toJsonTree(selectorEngines)); + json.addProperty("testIdAttributeName", testIdAttributeName); + return (T) gson().fromJson(json, options.getClass()); + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java b/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java index c3cfb174b..d2dbdb5c2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Serialization.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of serializers.ts (packages/protocol) and of the module-level functions and types of jsHandle.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -21,7 +22,6 @@ import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; -import com.microsoft.playwright.ElementHandle; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.options.*; import com.microsoft.playwright.options.BrowserChannel; @@ -40,12 +40,483 @@ import java.text.SimpleDateFormat; import java.time.*; import java.util.*; +import java.util.function.Function; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.Utils.createGuid; import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; import static com.microsoft.playwright.impl.Utils.fromJsRegexFlags; class Serialization { + // java: no systemErrorCode and systemErrorMessage, a Java exception has no Node.js system error code. + + static Object parseSerializedValue(SerializedValue value, List handles) { + return innerParseSerializedValue(value, handles, new HashMap<>(), new ArrayList<>()); + } + + private static Object innerParseSerializedValue(SerializedValue value, List handles, Map refs, List accessChain) { + if (value.ref != null) + return refs.get(value.ref); + if (value.n != null) { + // java: an integral number is an Integer, any other number a Double. + if (value.n.doubleValue() == (double) value.n.intValue()) + return value.n.intValue(); + return value.n; + } + if (value.s != null) + return value.s; + if (value.b != null) + return value.b; + if (value.v != null) { + // java: undefined is null. + if (value.v.equals("undefined")) + return null; + if (value.v.equals("null")) + return null; + if (value.v.equals("NaN")) + return Double.NaN; + if (value.v.equals("Infinity")) + return Double.POSITIVE_INFINITY; + if (value.v.equals("-Infinity")) + return Double.NEGATIVE_INFINITY; + if (value.v.equals("-0")) + return -0.0; + } + if (value.d != null) + return Date.from(Instant.parse(value.d)); + if (value.u != null) { + // java: new URL() throws a checked exception. + try { + return new URL(value.u); + } catch (MalformedURLException e) { + throw new PlaywrightException("Unexpected value: " + value.u, e); + } + } + if (value.bi != null) + return new BigInteger(value.bi); + if (value.e != null) { + // java: an Exception has no settable name or stack, its message is the stack (tests pin it). + return new Exception(value.e.s); + } + if (value.r != null) + return Pattern.compile(value.r.p, fromJsRegexFlags(value.r.f)); + if (value.ta != null) { + Class ctor = typedArrayKindToConstructor.get(value.ta.k); + // java: an unknown kind fails here instead of in the constructor call. + if (ctor == null) + throw new PlaywrightException("Unexpected typed array kind: " + value.ta.k); + return fromTypedArrayBytes(ctor, value.ta.b); + } + + if (value.a != null) { + List result = new ArrayList<>(); + refs.put(value.id, result); + for (int i = 0; i < value.a.size(); i++) + result.add(innerParseSerializedValue(value.a.get(i), handles, refs, append(accessChain, i))); + return result; + } + if (value.o != null) { + Map result = new LinkedHashMap<>(); + refs.put(value.id, result); + for (SerializedValue.SerializedValueO o : value.o) + result.put(o.k, innerParseSerializedValue(o.v, handles, refs, append(accessChain, o.k))); + return result; + } + if (value.h != null) { + if (handles == null) + throw new PlaywrightException("Unexpected handle"); + return handles.get(value.h); + } + if (value.fn != null) { + // java: a FunctionCallback stands for a JS function, its toString() is the function name. + String name = value.fn; + FunctionCallback dummy = new FunctionCallback() { + @Override + public Object call(Object... args) { + return null; + } + + @Override + public String toString() { + return name; + } + }; + return dummy; + } + throw new PlaywrightException("Attempting to deserialize unexpected value" + accessChainToDisplayString(accessChain) + ": " + gson().toJson(value)); + } + + // java: HandleOrValue is a class with a flag for 'fallThrough' in handle. + static class HandleOrValue { + Integer h; + String fn; + boolean hasFallThrough; + Object fallThrough; + } + + private static class VisitorInfo { + // java: an IdentityHashMap, keyed by reference like a JavaScript Map. + final Map visited = new IdentityHashMap<>(); + int lastId; + } + + static SerializedValue serializeValue(Object value, Function handleSerializer) { + return innerSerializeValue(value, handleSerializer, new VisitorInfo(), new ArrayList<>()); + } + + static SerializedValue serializePlainValue(Object arg) { + return serializeValue(arg, value -> fallThrough(value)); + } + + private static SerializedValue innerSerializeValue(Object value, Function handleSerializer, VisitorInfo visitorInfo, List accessChain) { + HandleOrValue handle = handleSerializer.apply(value); + if (handle.hasFallThrough) { + value = handle.fallThrough; + } else { + SerializedValue result = new SerializedValue(); + result.h = handle.h; + result.fn = handle.fn; + return result; + } + + SerializedValue result = new SerializedValue(); + // java: there are no symbols; null is undefined (tests pin it), so null never reaches { v: 'null' }. + if (value == null) { + result.v = "undefined"; + return result; + } + if (objectIs(value, Double.NaN)) { + result.v = "NaN"; + return result; + } + if (objectIs(value, Double.POSITIVE_INFINITY)) { + result.v = "Infinity"; + return result; + } + if (objectIs(value, Double.NEGATIVE_INFINITY)) { + result.v = "-Infinity"; + return result; + } + if (objectIs(value, -0.0)) { + result.v = "-0"; + return result; + } + if (value instanceof Boolean) { + result.b = (Boolean) value; + return result; + } + // java: a number is a Byte, Short, Integer, Long, Float or Double. + if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double) { + result.n = ((Number) value).doubleValue(); + return result; + } + if (value instanceof String) { + result.s = (String) value; + return result; + } + // java: a bigint is a BigInteger. + if (value instanceof BigInteger) { + result.bi = value.toString(); + return result; + } + if (isError(value)) { + Throwable error = (Throwable) value; + result.e = new SerializedValue.SerializedValueE(); + // java: the name is the simple class name, the stack is the printed Java stack trace. + result.e.n = error.getClass().getSimpleName(); + result.e.m = error.getMessage(); + StringWriter stack = new StringWriter(); + error.printStackTrace(new PrintWriter(stack)); + result.e.s = stack.toString(); + return result; + } + if (isDate(value)) { + // java: a LocalDateTime is in the default time zone. + Instant instant = value instanceof Date ? ((Date) value).toInstant() : ((LocalDateTime) value).atZone(ZoneId.systemDefault()).toInstant(); + result.d = instant.toString(); + return result; + } + if (isURL(value)) { + result.u = value.toString(); + return result; + } + if (isRegExp(value)) { + result.r = new SerializedValue.SerializedValueR(); + result.r.p = ((Pattern) value).pattern(); + result.r.f = toJsRegexFlags((Pattern) value); + return result; + } + + String typedArrayKind = constructorToTypedArrayKind.get(value.getClass()); + if (typedArrayKind != null) { + result.ta = new SerializedValue.SerializedValueTa(); + result.ta.b = toTypedArrayBytes(value); + result.ta.k = typedArrayKind; + return result; + } + + Integer id = visitorInfo.visited.get(value); + if (id != null) { + result.ref = id; + return result; + } + + // java: an array is a List or an Object[]. + if (value instanceof List || value instanceof Object[]) { + List array = value instanceof List ? (List) value : Arrays.asList((Object[]) value); + List a = new ArrayList<>(); + id = ++visitorInfo.lastId; + visitorInfo.visited.put(value, id); + for (int i = 0; i < array.size(); ++i) + a.add(innerSerializeValue(array.get(i), handleSerializer, visitorInfo, append(accessChain, i))); + result.a = a; + result.id = id; + return result; + } + // java: an object is a Map, its keys are converted to strings; any other Java object is unexpected. + if (value instanceof Map) { + List o = new ArrayList<>(); + id = ++visitorInfo.lastId; + visitorInfo.visited.put(value, id); + for (Map.Entry entry : ((Map) value).entrySet()) { + String name = String.valueOf(entry.getKey()); + SerializedValue.SerializedValueO item = new SerializedValue.SerializedValueO(); + item.k = name; + item.v = innerSerializeValue(entry.getValue(), handleSerializer, visitorInfo, append(accessChain, name)); + o.add(item); + } + result.o = o; + result.id = id; + return result; + } + // Likely only functions can reach here. + throw new PlaywrightException("Attempting to serialize unexpected value" + accessChainToDisplayString(accessChain) + ": " + value); + } + + private static String accessChainToDisplayString(List accessChain) { + StringBuilder chainString = new StringBuilder(); + for (int i = 0; i < accessChain.size(); i++) { + Object accessor = accessChain.get(i); + if (accessor instanceof String) + chainString.append(i != 0 ? "." + accessor : accessor); + else + chainString.append("[").append(accessor).append("]"); + } + + return chainString.length() > 0 ? " at position \"" + chainString + "\"" : ""; + } + + private static boolean isRegExp(Object obj) { + return obj instanceof Pattern; + } + + // java: a date is a Date or a LocalDateTime. + private static boolean isDate(Object obj) { + return obj instanceof Date || obj instanceof LocalDateTime; + } + + private static boolean isURL(Object obj) { + return obj instanceof URL; + } + + // java: an error is a Throwable. + private static boolean isError(Object obj) { + return obj instanceof Throwable; + } + + // java: a typed array is a primitive array, several kinds share one array type. + private static final Map> typedArrayKindToConstructor = new LinkedHashMap<>(); + static { + typedArrayKindToConstructor.put("i8", byte[].class); + typedArrayKindToConstructor.put("ui8", byte[].class); + typedArrayKindToConstructor.put("ui8c", byte[].class); + typedArrayKindToConstructor.put("i16", short[].class); + typedArrayKindToConstructor.put("ui16", short[].class); + typedArrayKindToConstructor.put("i32", int[].class); + typedArrayKindToConstructor.put("ui32", int[].class); + typedArrayKindToConstructor.put("f32", float[].class); + typedArrayKindToConstructor.put("f64", double[].class); + typedArrayKindToConstructor.put("bi64", long[].class); + typedArrayKindToConstructor.put("bui64", long[].class); + } + // java: not the inverse of the map above, a Java array type is sent as the signed kind. + private static final Map, String> constructorToTypedArrayKind = new HashMap<>(); + static { + constructorToTypedArrayKind.put(byte[].class, "i8"); + constructorToTypedArrayKind.put(short[].class, "i16"); + constructorToTypedArrayKind.put(int[].class, "i32"); + constructorToTypedArrayKind.put(float[].class, "f32"); + constructorToTypedArrayKind.put(double[].class, "f64"); + constructorToTypedArrayKind.put(long[].class, "bi64"); + } + + // jsHandle.ts + + // java: the optional registerCallback is an overload. + static SerializedArgument serializeArgument(Object arg) { + return serializeArgument(arg, null); + } + + // This function takes care of converting all JSHandles to their channels, + // so that generic channel serializer converts them to guids. + // java: a FunctionCallback stands for a JS function. + static SerializedArgument serializeArgument(Object arg, Function registerCallback) { + List handles = new ArrayList<>(); + Function pushHandle = channel -> { + handles.add(channel); + return handles.size() - 1; + }; + SerializedValue value = serializeValue(arg, v -> { + // java: a JSHandleImpl is its own channel. + if (v instanceof JSHandleImpl) + return handle(pushHandle.apply((JSHandleImpl) v)); + if (v instanceof FunctionCallback && registerCallback != null) + return fn(registerCallback.apply((FunctionCallback) v)); + return fallThrough(v); + }); + SerializedArgument result = new SerializedArgument(); + result.value = value; + result.handles = handles; + return result; + } + + // java: the ExposeFunctionsOptions type, a null exposeFunctions is undefined. + static class ExposeFunctionsOptions { + Boolean exposeFunctions; + } + + // java: the EvaluateOptions alias of ExposeFunctionsOptions is a subclass. + static class EvaluateOptions extends ExposeFunctionsOptions { + } + + // java: each exposeEvaluateCallback() call returns once the callback is exposed, so there is no Promise.all. + static SerializedArgument serializeArgumentWithCallbacks(ChannelOwner owner, PageImpl page, Object arg) { + return owner.wrapApiCall(() -> { + SerializedArgument serialized = serializeArgument(arg, callback -> { + if (page == null) + throw new PlaywrightException("Passing a function is not supported as an argument here"); + String name = kFunctionBindingPrefix + createGuid(); + page.exposeEvaluateCallback(name, callback); + return name; + }); + return serialized; + }, null, true); + } + + static Object parseResult(SerializedValue value) { + return parseSerializedValue(value, null); + } + + // java: no assertMaxArguments, it checks the JS arguments count. + + // java: options is an Object so that the check keeps its meaning: a null is undefined, a String, Number, Boolean + // or FunctionCallback is not a JS object, a List or a Java array is a JS array. + static void assertEvaluateOptions(Object options) { + if (options != null && (options instanceof String || options instanceof Number || options instanceof Boolean || options instanceof FunctionCallback || options instanceof List || options.getClass().isArray())) + throw new PlaywrightException("Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object."); + } + + // java: helpers of the ported part. + + // java: kFunctionBindingPrefix of isomorphic/utilityScriptSerializers.ts, which has no Java port. + static final String kFunctionBindingPrefix = "__pw_fn_"; + + // java: parseResult cast to the caller's result type, the name other files call. + @SuppressWarnings("unchecked") + static T deserialize(SerializedValue value) { + return (T) parseResult(value); + } + + private static HandleOrValue handle(int h) { + HandleOrValue result = new HandleOrValue(); + result.h = h; + return result; + } + + private static HandleOrValue fn(String fn) { + HandleOrValue result = new HandleOrValue(); + result.fn = fn; + return result; + } + + private static HandleOrValue fallThrough(Object value) { + HandleOrValue result = new HandleOrValue(); + result.hasFallThrough = true; + result.fallThrough = value; + return result; + } + + private static List append(List accessChain, Object accessor) { + List result = new ArrayList<>(accessChain); + result.add(accessor); + return result; + } + + private static boolean objectIs(Object value, double number) { + if (!(value instanceof Double) && !(value instanceof Float)) + return false; + return Double.compare(((Number) value).doubleValue(), number) == 0; + } + + private static Object fromTypedArrayBytes(Class ctor, byte[] bytes) { + ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); + if (ctor == byte[].class) + return bytes; + if (ctor == short[].class) { + short[] result = new short[bytes.length / 2]; + buffer.asShortBuffer().get(result); + return result; + } + if (ctor == int[].class) { + int[] result = new int[bytes.length / 4]; + buffer.asIntBuffer().get(result); + return result; + } + if (ctor == float[].class) { + float[] result = new float[bytes.length / 4]; + buffer.asFloatBuffer().get(result); + return result; + } + if (ctor == double[].class) { + double[] result = new double[bytes.length / 8]; + buffer.asDoubleBuffer().get(result); + return result; + } + long[] result = new long[bytes.length / 8]; + buffer.asLongBuffer().get(result); + return result; + } + + private static byte[] toTypedArrayBytes(Object value) { + if (value instanceof byte[]) + return ((byte[]) value).clone(); + ByteBuffer buffer; + if (value instanceof short[]) { + short[] array = (short[]) value; + buffer = ByteBuffer.allocate(array.length * 2).order(ByteOrder.LITTLE_ENDIAN); + buffer.asShortBuffer().put(array); + } else if (value instanceof int[]) { + int[] array = (int[]) value; + buffer = ByteBuffer.allocate(array.length * 4).order(ByteOrder.LITTLE_ENDIAN); + buffer.asIntBuffer().put(array); + } else if (value instanceof float[]) { + float[] array = (float[]) value; + buffer = ByteBuffer.allocate(array.length * 4).order(ByteOrder.LITTLE_ENDIAN); + buffer.asFloatBuffer().put(array); + } else if (value instanceof double[]) { + double[] array = (double[]) value; + buffer = ByteBuffer.allocate(array.length * 8).order(ByteOrder.LITTLE_ENDIAN); + buffer.asDoubleBuffer().put(array); + } else { + long[] array = (long[]) value; + buffer = ByteBuffer.allocate(array.length * 8).order(ByteOrder.LITTLE_ENDIAN); + buffer.asLongBuffer().put(array); + } + return buffer.array(); + } + + // java: Gson configuration, protocol conversions and error helpers, no counterpart in serializers.ts. + private static final Gson gson = new GsonBuilder().disableHtmlEscaping() .registerTypeAdapter(Date.class, new DateSerializer()) .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer()) @@ -110,249 +581,6 @@ static SerializedError serializeError(Throwable e) { return result; } - private static class ValueSerializer { - // hashCode() of a map containing itself as a key will throw stackoverflow exception, - // so we user wrappers. - private static class HashableValue { - final Object value; - HashableValue(Object value) { - this.value = value; - } - - @Override - public boolean equals(Object o) { - return value == ((HashableValue) o).value; - } - - @Override - public int hashCode() { - return System.identityHashCode(value); - } - } - private final Map valueToId = new HashMap<>(); - private int lastId = 0; - private final List handles = new ArrayList<>(); - private final SerializedValue serializedValue; - - ValueSerializer(Object value) { - serializedValue = serializeValue(value); - } - - SerializedArgument toSerializedArgument() { - SerializedArgument result = new SerializedArgument(); - result.value = serializedValue; - result.handles = new ArrayList<>(handles); - return result; - } - - private SerializedValue serializeValue(Object value) { - SerializedValue result = new SerializedValue(); - if (value instanceof JSHandleImpl) { - result.h = handles.size(); - handles.add((JSHandleImpl) value); - return result; - } - if (value == null) { - result.v = "undefined"; - } else if (value instanceof Double) { - double d = ((Double) value); - if (d == Double.POSITIVE_INFINITY) { - result.v = "Infinity"; - } else if (d == Double.NEGATIVE_INFINITY) { - result.v = "-Infinity"; - } else if (Double.compare(d, -0.0) == 0) { - result.v = "-0"; - } else if (Double.isNaN(d)) { - result.v = "NaN"; - } else { - result.n = d; - } - } else if (value instanceof Boolean) { - result.b = (Boolean) value; - } else if (value instanceof Integer) { - result.n = ((Integer) value).doubleValue(); - } else if (value instanceof String) { - result.s = (String) value; - } else if (value instanceof Date) { - result.d = ((Date)value).toInstant().toString(); - } else if (value instanceof LocalDateTime) { - result.d = ((LocalDateTime)value).atZone(ZoneId.systemDefault()).toInstant().toString(); - } else if (value instanceof URL) { - result.u = ((URL)value).toString(); - } else if (value instanceof BigInteger) { - result.bi = ((BigInteger)value).toString(); - } else if (value instanceof Pattern) { - result.r = new SerializedValue.SerializedValueR(); - result.r.p = ((Pattern)value).pattern(); - result.r.f = toJsRegexFlags(((Pattern)value)); - } else if (value instanceof Exception) { - Exception exception = (Exception) value; - result.e = new SerializedValue.SerializedValueE(); - result.e.m = exception.getMessage(); - result.e.n = exception.getClass().getSimpleName(); - StringWriter sw = new StringWriter(); - exception.printStackTrace(new PrintWriter(sw)); - result.e.s = sw.toString(); - } else { - HashableValue mapKey = new HashableValue(value); - Integer id = valueToId.get(mapKey); - if (id != null) { - result.ref = id; - } else { - result.id = ++lastId; - valueToId.put(mapKey, lastId); - if (value instanceof List) { - List list = new ArrayList<>(); - for (Object o : (List) value) { - list.add(serializeValue(o)); - } - result.a = list; - } else if (value instanceof Map) { - List list = new ArrayList<>(); - @SuppressWarnings("unchecked") - Map map = (Map) value; - for (Map.Entry e : map.entrySet()) { - SerializedValue.SerializedValueO o = new SerializedValue.SerializedValueO(); - o.k = e.getKey(); - o.v = serializeValue(e.getValue()); - list.add(o); - } - result.o = list; - } else if (value instanceof Object[]) { - List list = new ArrayList<>(); - for (Object o : (Object[]) value) { - list.add(serializeValue(o)); - } - result.a = list; - } else { - throw new PlaywrightException("Unsupported type of argument: " + value); - } - } - } - return result; - } - } - - static SerializedArgument serializeArgument(Object arg) { - return new ValueSerializer(arg).toSerializedArgument(); - } - - static T deserialize(SerializedValue value) { - return deserialize(value, new HashMap<>()); - } - - @SuppressWarnings("unchecked") - private static T deserialize(SerializedValue value, Map idToValue) { - if (value.ref != null) { - return (T) idToValue.get(value.ref); - } - if (value.n != null) { - if (value.n.doubleValue() == (double) value.n.intValue()) { - return (T) Integer.valueOf(value.n.intValue()); - } - return (T) Double.valueOf(value.n.doubleValue()); - } - if (value.b != null) - return (T) value.b; - if (value.s != null) - return (T) value.s; - if (value.u != null) { - try { - return (T)(new URL(value.u)); - } catch (MalformedURLException e) { - throw new PlaywrightException("Unexpected value: " + value.u, e); - } - } - if (value.bi != null) { - return (T) new BigInteger(value.bi); - } - if (value.d != null) - return (T)(Date.from(Instant.parse(value.d))); - if (value.r != null) - return (T)(Pattern.compile(value.r.p, fromJsRegexFlags(value.r.f))); - if (value.e != null) { - return (T)new Exception(value.e.s); - } - if (value.ta != null) { - return (T) deserializeTypedArray(value.ta); - } - if (value.v != null) { - switch (value.v) { - case "undefined": - case "null": - return null; - case "Infinity": - return (T) Double.valueOf(Double.POSITIVE_INFINITY); - case "-Infinity": - return (T) Double.valueOf(Double.NEGATIVE_INFINITY); - case "-0": { - return (T) Double.valueOf(-0.0); - } - case "NaN": - return (T) Double.valueOf(Double.NaN); - default: - throw new PlaywrightException("Unexpected value: " + value.v); - } - } - if (value.a != null) { - List list = new ArrayList<>(); - idToValue.put(value.id, list); - for (SerializedValue v : value.a) { - list.add(deserialize(v, idToValue)); - } - return (T) list; - } - if (value.o != null) { - Map map = new LinkedHashMap<>(); - idToValue.put(value.id, map); - for (SerializedValue.SerializedValueO o : value.o) { - map.put(o.k, deserialize(o.v, idToValue)); - } - return (T) map; - } - throw new PlaywrightException("Unexpected result: " + gson().toJson(value)); - } - - private static Object deserializeTypedArray(SerializedValue.SerializedValueTa typedArray) { - ByteBuffer buffer = ByteBuffer.wrap(typedArray.b).order(ByteOrder.LITTLE_ENDIAN); - switch (typedArray.k) { - case "i8": - case "ui8": - case "ui8c": - return typedArray.b; - case "i16": - case "ui16": { - short[] result = new short[typedArray.b.length / 2]; - buffer.asShortBuffer().get(result); - return result; - } - case "i32": - case "ui32": { - int[] result = new int[typedArray.b.length / 4]; - buffer.asIntBuffer().get(result); - return result; - } - case "f32": { - float[] result = new float[typedArray.b.length / 4]; - buffer.asFloatBuffer().get(result); - return result; - } - case "f64": { - double[] result = new double[typedArray.b.length / 8]; - buffer.asDoubleBuffer().get(result); - return result; - } - case "bi64": - case "bui64": { - long[] result = new long[typedArray.b.length / 8]; - buffer.asLongBuffer().get(result); - return result; - } - default: - throw new PlaywrightException("Unexpected typed array kind: " + typedArray.k); - } - } - private static class KeyboardModifiersSerializer implements JsonSerializer> { @Override public JsonArray serialize(List modifiers, Type typeOfSrc, JsonSerializationContext context) { @@ -385,16 +613,6 @@ static JsonArray toProtocol(Map map) { return toNameValueArray(map.entrySet()); } - static void addHarUrlFilter(JsonObject options, Object urlFilter) { - if (urlFilter instanceof String) { - options.addProperty("urlGlob", (String) urlFilter); - } else if (urlFilter instanceof Pattern) { - Pattern pattern = (Pattern) urlFilter; - options.addProperty("urlRegexSource", pattern.pattern()); - options.addProperty("urlRegexFlags", toJsRegexFlags(pattern)); - } - } - static JsonObject toClearCookiesParams(Object name, Object domain, Object path) { JsonObject params = new JsonObject(); setStringOrRegex(params, "name", name); @@ -428,33 +646,6 @@ static JsonArray toNameValueArray(Iterable> colle return array; } - static JsonArray toSelectValueOrLabel(String[] values) { - JsonArray jsonOptions = new JsonArray(); - for (String value : values) { - JsonObject option = new JsonObject(); - option.addProperty("valueOrLabel", value); - jsonOptions.add(option); - } - return jsonOptions; - } - - static Map fromNameValues(JsonArray array) { - Map map = new LinkedHashMap<>(); - for (JsonElement element : array) { - JsonObject pair = element.getAsJsonObject(); - map.put(pair.get("name").getAsString(), pair.get("value").getAsString()); - } - return map; - } - - static List parseStringList(JsonArray array) { - List result = new ArrayList<>(); - for (JsonElement e : array) { - result.add(e.getAsString()); - } - return result; - } - static String parseError(JsonObject object) { SerializedError error = gson().fromJson(object, SerializedError.class); String errorStr = ""; @@ -626,6 +817,4 @@ public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializatio return new JsonPrimitive(dateFormat.format(Date.from(instant))); } } - } - diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java b/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java index 7d2c365bd..42a6cefaf 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of packages/playwright-core/src/client/clientStackTrace.ts +// Port of clientStackTrace.ts. package com.microsoft.playwright.impl; import com.google.gson.JsonArray; @@ -29,8 +29,9 @@ import java.util.stream.Collectors; // java: clientStackTrace.ts exports one function, captureLibraryStackTrace(), which returns the frames -// outside of the library and the api name. The api name is not used here (the tracing titles come from -// wrapApiCall), and the frames are mapped to source files of PLAYWRIGHT_JAVA_SRC; hence a class with state. +// outside of the library and the api name. The api name and its normalizeAPIName are not ported: the Java +// frames name impl classes, not the API, and the titles of wrapApiCall stand in for it (ChannelOwner.wrapApiCall). +// The frames are mapped to source files of PLAYWRIGHT_JAVA_SRC; hence a class with state. class StackTraceCollector { static final String PLAYWRIGHT_JAVA_SRC = "PLAYWRIGHT_JAVA_SRC"; private final List srcDirs; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java b/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java index e6939a88f..e03a86722 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java @@ -14,18 +14,23 @@ * limitations under the License. */ +// Port of stream.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; +import com.microsoft.playwright.PlaywrightException; import java.io.IOException; import java.io.InputStream; +// java: the Readable is an InputStream; _read becomes read(), _destroy becomes close(). public class Stream extends ChannelOwner { private final InputStream stream = new InputStreamImpl(); final StreamChannel channel = new StreamChannel(this); + // java: from is not ported, generated results already hold the impl object. + public Stream(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } @@ -65,7 +70,11 @@ public int read(byte[] b, int off, int len) { @Override public void close() throws IOException { super.close(); - channel.close(NO_TIMEOUT); + // Stream might be destroyed after the connection was closed. + try { + channel.close(NO_TIMEOUT); + } catch (PlaywrightException e) { + } } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java index 06e840a70..ab26e43d8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java @@ -14,14 +14,16 @@ * limitations under the License. */ +// Port of timeoutSettings.ts. package com.microsoft.playwright.impl; -// Port of timeoutSettings.ts. java: no AbortSignal and no PWDEBUG=inspector branch, a timeout is a Double -// and 0 means no deadline. -class TimeoutSettings { - static final int DEFAULT_TIMEOUT = 30_000; - static final int DEFAULT_LAUNCH_TIMEOUT = 180_000; +import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; +import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_TIMEOUT; + +// java: kNoTimeout is ChannelOwner.NO_TIMEOUT. +// java: no AbortSignal, a timeout is a Double and 0 means no deadline. +class TimeoutSettings { private final TimeoutSettings parent; private Double defaultTimeout; private Double defaultNavigationTimeout; @@ -50,6 +52,8 @@ Double defaultTimeout() { return defaultTimeout; } + // java: navigationTimeout, timeout and launchTimeout return the number of _navigationTimeout, _timeout and + // _launchTimeout; the { signal, timeout } object they wrap it in has no signal in Java. double navigationTimeout(Double timeout) { if (timeout != null) { return timeout; @@ -57,36 +61,60 @@ Double defaultTimeout() { if (defaultNavigationTimeout != null) { return defaultNavigationTimeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (defaultTimeout != null) { return defaultTimeout; } if (parent != null) { return parent.navigationTimeout(timeout); } - return DEFAULT_TIMEOUT; + return DEFAULT_PLAYWRIGHT_TIMEOUT; } double timeout(Double timeout) { if (timeout != null) { return timeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (defaultTimeout != null) { return defaultTimeout; } if (parent != null) { return parent.timeout(timeout); } - return DEFAULT_TIMEOUT; + return DEFAULT_PLAYWRIGHT_TIMEOUT; } double launchTimeout(Double timeout) { if (timeout != null) { return timeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (parent != null) { return parent.launchTimeout(timeout); } - return DEFAULT_LAUNCH_TIMEOUT; + return DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; + } + + // java: debugMode() of utils/debug.ts, PWDEBUG of the process environment. + static String debugMode() { + String debugEnv = System.getenv("PWDEBUG"); + if (debugEnv == null) { + debugEnv = ""; + } + if (debugEnv.equals("console")) { + return "console"; + } + if (debugEnv.equals("0") || debugEnv.equals("false")) { + return ""; + } + return !debugEnv.isEmpty() ? "inspector" : ""; } // java: removed once every wait goes through Waiter. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/TouchscreenImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/TouchscreenImpl.java index 71e9c1cc0..50fee64e7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TouchscreenImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TouchscreenImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of input.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java index b9199199b..613e33ae1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -14,315 +14,380 @@ * limitations under the License. */ +// Port of tracing.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.Tracing; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.options.HarContentPolicy; import com.microsoft.playwright.options.HarMode; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Utils.toProtocol; - public class TracingImpl extends ChannelOwner implements Tracing { - private boolean includeSources; - private Path tracesDir; - private boolean isTracing; + private boolean includeSources = false; + private final Set additionalSources = new LinkedHashSet<>(); + private boolean isLive = false; + // java: a Path, as the tracesDir launch option of the Java API. + Path tracesDir; private String stacksId; - private final Set additionalSources = new HashSet<>(); - final Map harRecorders = new HashMap<>(); - - static class HarRecorder { - final Path path; - final HarContentPolicy contentPolicy; - - HarRecorder(Path har, HarContentPolicy policy) { - this.path = har; - this.contentPolicy = policy; - } - } - + private boolean isTracing = false; + private String harId; + private final Map harRecorders = new LinkedHashMap<>(); final TracingChannel channel = new TracingChannel(this); + // java: from is not ported, generated results already hold the impl object. + TracingImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } - void resetStackCounter() { - if (isTracing) { - isTracing = false; - connection.setIsTracing(false); - } - } - - private void stopChunkImpl(Path path) { - resetStackCounter(); - - List capturedAdditionalSources = new ArrayList<>(additionalSources); - additionalSources.clear(); - String stacksId = this.stacksId; - this.stacksId = null; - - try { - saveChunk(path, stacksId, capturedAdditionalSources); - } catch (RuntimeException e) { - // Release the stack session even on failure, otherwise later traces keep appending to it. - if (stacksId != null) { - try { - connection.localUtils().traceDiscarded(stacksId); - } catch (RuntimeException ignored) { - } - } - throw e; - } + @Override + public AutoCloseable start(StartOptions options) { + return start(options, null); } - private void saveChunk(Path path, String stacksId, List capturedAdditionalSources) { - TracingTracingStopChunkParams params = new TracingTracingStopChunkParams(); - // Not interested in artifacts. - if (path == null) { - params.mode = "discard"; - channel.tracingStopChunk(params, NO_TIMEOUT); - if (stacksId != null) { - connection.localUtils().traceDiscarded(stacksId); - } - return; - } - - boolean isLocal = !connection.isRemote(); - if (isLocal) { - params.mode = "entries"; - TracingTracingStopChunkResult result = channel.tracingStopChunk(params, NO_TIMEOUT); - connection.localUtils().zip(path, result.entries, stacksId, false, includeSources, capturedAdditionalSources); - return; - } - - params.mode = "archive"; - TracingTracingStopChunkResult json = channel.tracingStopChunk(params, NO_TIMEOUT); - // The artifact may be missing if the browser closed while stopping tracing. - if (json.artifact == null) { - if (stacksId != null) { - connection.localUtils().traceDiscarded(stacksId); - } - return; - } - ArtifactImpl artifact = json.artifact; - try { - artifact.saveAs(path); - } catch (RuntimeException e) { - // Delete the artifact best-effort, the save error is the one to surface. - try { - artifact.delete(); - } catch (RuntimeException ignored) { - } - throw e; - } - artifact.delete(); - - connection.localUtils().zip(path, new ArrayList<>(), stacksId, true, includeSources, capturedAdditionalSources); + // java: coverage is the _coverage option of upstream, which StartOptions does not have. + AutoCloseable start(StartOptions options, Boolean coverage) { + StartOptions o = options == null ? new StartOptions() : options; + return wrapApiCall(() -> { + includeSources = o.sources != null && o.sources; + isLive = o.live != null && o.live; + TracingTracingStartParams params = new TracingTracingStartParams(); + params.name = o.name; + // java: the snapshots object of upstream is three options, snapshots (dom), ariaSnapshots and screenSnapshots. + params.snapshotDom = o.snapshots; + params.snapshotAria = o.ariaSnapshots; + params.snapshotScreen = o.screenSnapshots; + params.screencast = o.screenshots; + params.coverage = coverage; + params.live = o.live; + channel.tracingStart(params, NO_TIMEOUT); + TracingTracingStartChunkParams chunkParams = new TracingTracingStartChunkParams(); + chunkParams.name = o.name; + chunkParams.title = o.title; + String traceName = channel.tracingStartChunk(chunkParams, NO_TIMEOUT).traceName; + startCollectingStacks(traceName, isLive); + return new DisposableStub(() -> stop()); + }, null, false); } @Override public AutoCloseable startChunk(StartChunkOptions options) { - if (options == null) { - options = new StartChunkOptions(); - } - tracingStartChunk(options.name, options.title); - return new DisposableStub(this::stopChunk); + StartChunkOptions o = options == null ? new StartChunkOptions() : options; + return wrapApiCall(() -> { + TracingTracingStartChunkParams params = new TracingTracingStartChunkParams(); + params.name = o.name; + params.title = o.title; + String traceName = channel.tracingStartChunk(params, NO_TIMEOUT).traceName; + startCollectingStacks(traceName, isLive); + return new DisposableStub(() -> stopChunk()); + }, null, false); } @Override public AutoCloseable group(String name, GroupOptions options) { - groupImpl(name, options); - return new DisposableStub(this::groupEnd); - } - - private void groupImpl(String name, GroupOptions options) { if (options == null) { options = new GroupOptions(); } if (options.location != null) { additionalSources.add(options.location.file); } - TracingTracingGroupParams params = toProtocol(options, TracingTracingGroupParams.class); + TracingTracingGroupParams params = new TracingTracingGroupParams(); params.name = name; + if (options.location != null) { + params.location = new TracingTracingGroupParams.TracingTracingGroupParamsLocation(); + params.location.file = options.location.file; + params.location.line = options.location.line; + params.location.column = options.location.column; + } channel.tracingGroup(params, NO_TIMEOUT); + return new DisposableStub(() -> groupEnd()); } @Override public void groupEnd() { - channel.tracingGroupEnd(NO_TIMEOUT); - } - - private void tracingStartChunk(String name, String title) { - TracingTracingStartChunkParams params = new TracingTracingStartChunkParams(); - params.name = name; - params.title = title; - TracingTracingStartChunkResult result = channel.tracingStartChunk(params, NO_TIMEOUT); - startCollectingStacks(result.traceName); + channel.tracingGroupEnd(new TracingTracingGroupEndParams(), NO_TIMEOUT); } - private void startCollectingStacks(String traceName) { + private void startCollectingStacks(String traceName, boolean live) { if (!isTracing) { isTracing = true; connection.setIsTracing(true); } - stacksId = connection.localUtils().tracingStarted(tracesDir == null ? null : tracesDir.toString(), traceName); + LocalUtilsTracingStartedParams params = new LocalUtilsTracingStartedParams(); + params.tracesDir = tracesDir == null ? null : tracesDir.toString(); + params.traceName = traceName; + params.live = live; + LocalUtils localUtils = connection.localUtils(); + LocalUtilsTracingStartedResult result = localUtils == null ? null : localUtils.tracingStarted(params); + stacksId = result == null ? null : result.stacksId; } @Override - public AutoCloseable start(StartOptions options) { - if (options == null) { - options = new StartOptions(); - } - includeSources = options.sources != null && options.sources; - TracingTracingStartParams params = toProtocol(options, TracingTracingStartParams.class); - params.snapshotDom = options.snapshots; - params.snapshotAria = options.ariaSnapshots; - params.snapshotScreen = options.screenSnapshots; - params.screencast = options.screenshots; - channel.tracingStart(params, NO_TIMEOUT); - tracingStartChunk(options.name, options.title); - return new DisposableStub(this::stop); + public void stopChunk(StopChunkOptions options) { + Path path = options == null ? null : options.path; + wrapApiCall(() -> { + doStopChunk(path); + }, null, false); } @Override public void stop(StopOptions options) { - try { - stopChunkImpl(options == null ? null : options.path); - } finally { - channel.tracingStop(NO_TIMEOUT); - } - } - - @Override - public void stopChunk(StopChunkOptions options) { - stopChunkImpl(options == null ? null : options.path); + Path path = options == null ? null : options.path; + wrapApiCall(() -> { + RuntimeException error = null; + try { + doStopChunk(path); + } catch (RuntimeException e) { + error = e; + } + channel.tracingStop(new TracingTracingStopParams(), NO_TIMEOUT); + if (error != null) { + throw error; + } + }, null, false); } - private String currentHarId; - @Override public AutoCloseable startHar(Path path, StartHarOptions options) { - if (currentHarId != null) { - throw new PlaywrightException("HAR recording has already been started"); - } - if (options == null) { - options = new StartHarOptions(); - } - boolean isZip = isZip(path); - HarContentPolicy contentPolicy = options.content != null - ? options.content - : (isZip ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED); - HarMode mode = options.mode != null ? options.mode : HarMode.FULL; - currentHarId = recordIntoHar(null, path, options.urlFilter, contentPolicy, mode, null); - return new DisposableStub(this::stopHar); + StartHarOptions o = options == null ? new StartHarOptions() : options; + return wrapApiCall(() -> { + if (harId != null) { + throw new PlaywrightException("HAR recording has already been started"); + } + // java: StartHarOptions has no resourcesDir, so there is no check of resourcesDir with a .zip har file. + HarContentPolicy defaultContent = isZip(path) ? HarContentPolicy.ATTACH : HarContentPolicy.EMBED; + harId = recordIntoHAR(path, null, + o.urlFilter, + o.content != null ? o.content : defaultContent, + o.mode != null ? o.mode : HarMode.FULL, + null); + return new DisposableStub(() -> stopHar()); + }, null, false); } @Override public void stopHar() { - if (currentHarId == null) { - throw new PlaywrightException("HAR recording has not been started"); - } - String harId = currentHarId; - currentHarId = null; - exportHar(harId); - } - - static boolean isZip(Path path) { - return path.toString().toLowerCase().endsWith(".zip"); + wrapApiCall(() -> { + String harId = this.harId; + if (harId == null) { + throw new PlaywrightException("HAR recording has not been started"); + } + this.harId = null; + exportHAR(harId); + }, null, false); } - String recordIntoHar(PageImpl page, Path har, Object urlFilter, HarContentPolicy contentPolicy, HarMode mode, Path resourcesDir) { - if (contentPolicy == null) { - contentPolicy = HarContentPolicy.ATTACH; - } - if (mode == null) { - mode = HarMode.MINIMAL; - } - + // java: the options object of upstream is positional, url is a String glob or a Pattern. + String recordIntoHAR(Path har, PageImpl page, Object url, HarContentPolicy updateContent, HarMode updateMode, Path resourcesDir) { + boolean isZip = isZip(har); TracingHarStartParams params = new TracingHarStartParams(); params.page = page; - // The old "zip" key is not part of the protocol anymore (the generated RecordHarOptions has no such field). - RecordHarOptions recordHarArgs = new RecordHarOptions(); - recordHarArgs.content = contentPolicy.name().toLowerCase(); - recordHarArgs.mode = mode.name().toLowerCase(); - if (urlFilter instanceof String) { - recordHarArgs.urlGlob = (String) urlFilter; - } else if (urlFilter instanceof Pattern) { - Pattern pattern = (Pattern) urlFilter; - recordHarArgs.urlRegexSource = pattern.pattern(); - recordHarArgs.urlRegexFlags = Utils.toJsRegexFlags(pattern); - } - if (resourcesDir != null) { - recordHarArgs.resourcesDir = resourcesDir.toString(); - } - if (!isZip(har)) { - recordHarArgs.harPath = har.toString(); - } - - params.options = recordHarArgs; + params.options = new RecordHarOptions(); + params.options.content = (updateContent != null ? updateContent : HarContentPolicy.ATTACH).name().toLowerCase(); + params.options.urlGlob = url instanceof String ? (String) url : null; + params.options.urlRegexSource = url instanceof Pattern ? ((Pattern) url).pattern() : null; + params.options.urlRegexFlags = url instanceof Pattern ? Utils.toJsRegexFlags((Pattern) url) : null; + params.options.mode = (updateMode != null ? updateMode : HarMode.MINIMAL).name().toLowerCase(); + params.options.harPath = isZip ? null : har.toString(); + params.options.resourcesDir = resourcesDir == null ? null : resourcesDir.toString(); String harId = channel.harStart(params, NO_TIMEOUT).harId; - harRecorders.put(harId, new HarRecorder(har, contentPolicy)); + harRecorders.put(harId, new HarRecorder(har, resourcesDir)); return harId; } - void exportHar(String harId) { - HarRecorder harParams = harRecorders.remove(harId); + void exportHAR(String harId) { + HarRecorder harParams = harRecorders.get(harId); if (harParams == null) { return; } + harRecorders.remove(harId); boolean isLocal = !connection.isRemote(); boolean isZip = isZip(harParams.path); - TracingHarExportParams params = new TracingHarExportParams(); - params.harId = harId; if (isLocal) { + TracingHarExportParams params = new TracingHarExportParams(); + params.harId = harId; params.mode = "entries"; - TracingHarExportResult json = channel.harExport(params, NO_TIMEOUT); + List entries = channel.harExport(params, NO_TIMEOUT).entries; if (!isZip) { + // Server wrote HAR and resources to the user's chosen paths. return; } - connection.localUtils().zip(harParams.path, json.entries, null, false, false, java.util.Collections.emptyList()); + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Cannot save zipped HAR in thin clients"); + } + LocalUtilsZipParams zipParams = new LocalUtilsZipParams(); + zipParams.zipFile = harParams.path.toString(); + zipParams.entries = entries; + zipParams.mode = "write"; + zipParams.includeSources = false; + zipParams.additionalSources = new ArrayList<>(); + localUtils.zip(zipParams); return; } + TracingHarExportParams params = new TracingHarExportParams(); + params.harId = harId; params.mode = "archive"; - TracingHarExportResult json = channel.harExport(params, NO_TIMEOUT); - ArtifactImpl artifact = json.artifact; + ArtifactImpl artifact = channel.harExport(params, NO_TIMEOUT).artifact; if (isZip) { artifact.saveAs(harParams.path); artifact.delete(); return; } - String tmpPath = harParams.path + ".tmp"; - artifact.saveAs(Paths.get(tmpPath)); + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Uncompressed har is not supported in thin clients"); + } + artifact.saveAs(Paths.get(harParams.path + ".tmp")); LocalUtilsHarUnzipParams unzipParams = new LocalUtilsHarUnzipParams(); - unzipParams.zipFile = tmpPath; + unzipParams.zipFile = harParams.path + ".tmp"; unzipParams.harFile = harParams.path.toString(); - connection.localUtils().channel.harUnzip(unzipParams, NO_TIMEOUT); + unzipParams.resourcesDir = harParams.resourcesDir == null ? null : harParams.resourcesDir.toString(); + localUtils.harUnzip(unzipParams); artifact.delete(); } void exportAllHars() { - for (String harId : new ArrayList<>(harRecorders.keySet())) { - exportHar(harId); + wrapApiCall(() -> { + for (String harId : new ArrayList<>(harRecorders.keySet())) { + exportHAR(harId); + } + }, null, true); + } + + private void doStopChunk(Path filePath) { + resetStackCounter(); + + List additionalSources = new ArrayList<>(this.additionalSources); + this.additionalSources.clear(); + String stacksId = this.stacksId; + this.stacksId = null; + + try { + saveChunk(filePath, stacksId, additionalSources); + } catch (RuntimeException error) { + // Release the stack session even on failure, otherwise later traces keep appending to it. + if (stacksId != null && connection.localUtils() != null) { + try { + connection.localUtils().traceDiscarded(traceDiscardedParams(stacksId)); + } catch (PlaywrightException e) { + } + } + throw error; + } + } + + private void saveChunk(Path filePath, String stacksId, List additionalSources) { + if (filePath == null) { + // Not interested in artifacts. + TracingTracingStopChunkParams params = new TracingTracingStopChunkParams(); + params.mode = "discard"; + channel.tracingStopChunk(params, NO_TIMEOUT); + if (stacksId != null) { + connection.localUtils().traceDiscarded(traceDiscardedParams(stacksId)); + } + return; + } + + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Cannot save trace in thin clients"); } + + boolean isLocal = !connection.isRemote(); + + if (isLocal) { + TracingTracingStopChunkParams params = new TracingTracingStopChunkParams(); + params.mode = "entries"; + TracingTracingStopChunkResult result = channel.tracingStopChunk(params, NO_TIMEOUT); + LocalUtilsZipParams zipParams = new LocalUtilsZipParams(); + zipParams.zipFile = filePath.toString(); + zipParams.entries = result.entries; + zipParams.mode = "write"; + zipParams.stacksId = stacksId; + zipParams.includeSources = includeSources; + zipParams.additionalSources = additionalSources; + localUtils.zip(zipParams); + return; + } + + TracingTracingStopChunkParams params = new TracingTracingStopChunkParams(); + params.mode = "archive"; + TracingTracingStopChunkResult result = channel.tracingStopChunk(params, NO_TIMEOUT); + + // The artifact may be missing if the browser closed while stopping tracing. + if (result.artifact == null) { + if (stacksId != null) { + localUtils.traceDiscarded(traceDiscardedParams(stacksId)); + } + return; + } + + // Save trace to the final local file. + ArtifactImpl artifact = result.artifact; + try { + artifact.saveAs(filePath); + } catch (RuntimeException error) { + // Delete the artifact best-effort, the save error is the one to surface. + try { + artifact.delete(); + } catch (PlaywrightException e) { + } + throw error; + } + artifact.delete(); + + LocalUtilsZipParams zipParams = new LocalUtilsZipParams(); + zipParams.zipFile = filePath.toString(); + zipParams.entries = new ArrayList<>(); + zipParams.mode = "append"; + zipParams.stacksId = stacksId; + zipParams.includeSources = includeSources; + zipParams.additionalSources = additionalSources; + localUtils.zip(zipParams); + } + + void resetStackCounter() { + if (isTracing) { + isTracing = false; + connection.setIsTracing(false); + } + } + + // java: the value type of harRecorders and the /\.zip$/i test. + static class HarRecorder { + final Path path; + final Path resourcesDir; + + HarRecorder(Path path, Path resourcesDir) { + this.path = path; + this.resourcesDir = resourcesDir; + } + } + + private static boolean isZip(Path path) { + return path.toString().toLowerCase().endsWith(".zip"); } - void setTracesDir(Path tracesDir) { - this.tracesDir = tracesDir; + // java: the { stacksId } params literal. + private static LocalUtilsTraceDiscardedParams traceDiscardedParams(String stacksId) { + LocalUtilsTraceDiscardedParams params = new LocalUtilsTraceDiscardedParams(); + params.stacksId = stacksId; + return params; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java index c19b08a84..65992b6df 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java @@ -14,23 +14,45 @@ * limitations under the License. */ +// Port of isomorphic/urlMatch.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.URLPattern; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiFunction; import java.util.function.Predicate; +import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Utils.fromJsRegexFlags; import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.isString; +// java: an URLMatch value; a glob also holds its resolved regex, so test() does not resolve it again. The reachable +// path has the driver resolve globs (LocalUtils.globToRegex): forGlob(), test() and equals() stand for +// resolveGlobToRegexPattern(), urlMatches() and urlMatchesEqual(), whose ports have no caller. +// java: java.net.URI stands for the WHATWG URL, see newURL(). +// java: stays in impl, not in impl.isomorphic: globs are converted by the driver through LocalUtils. class UrlMatcher { public final String glob; public final Pattern pattern; public final Predicate predicate; + // java: the URLMatch union of a Java Object, a null is undefined. static UrlMatcher forOneOf(URL baseUrl, Object object, LocalUtils localUtils, boolean isWebSocketUrl) { if (object == null) { return new UrlMatcher(null, null, null); @@ -47,27 +69,6 @@ static UrlMatcher forOneOf(URL baseUrl, Object object, LocalUtils localUtils, bo throw new PlaywrightException("Url must be String, Pattern or Predicate, found: " + object.getClass().getTypeName()); } - static String resolveUrl(URL baseUrl, String spec) { - return resolveUrl(baseUrl.toString(), spec); - } - - private static String resolveUrl(String baseUrl, String spec) { - if (baseUrl == null) { - return spec; - } - try { - // Join using URI instead of URL since URL doesn't handle ws(s) protocols. - return new URI(baseUrl).resolve(spec).toString(); - } catch (URISyntaxException e) { - return spec; - } - } - - static UrlMatcher forGlob(URL baseURL, String glob, LocalUtils localUtils, boolean isWebSocketUrl) { - Pattern pattern = localUtils.globToRegex(glob, baseURL != null ? baseURL.toString() : null, isWebSocketUrl); - return new UrlMatcher(glob, pattern, null); - } - UrlMatcher(Pattern pattern) { this(null, pattern, null); } @@ -82,55 +83,473 @@ private UrlMatcher(String glob, Pattern pattern, Predicate predicate) { this.predicate = predicate; } - boolean test(String value) { - if (pattern != null) { - return pattern.matcher(value).find(); + static boolean isHttpUrl(String url) { + return isHttpUrl(url, null); + } + + // java: a null base is undefined. + static boolean isHttpUrl(String url, String base) { + try { + return Arrays.asList("http:", "https:").contains(protocol(newURL(url, base))); + } catch (URISyntaxException | IllegalArgumentException e) { + return false; } - if (predicate != null) { - return predicate.test(value); + } + + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping + private static final Set escapedChars = new LinkedHashSet<>(Arrays.asList('$', '^', '+', '.', '*', '(', ')', '|', '\\', '?', '{', '}', '[', ']')); + + static String globToRegexPattern(String glob) { + List tokens = new ArrayList<>(Collections.singletonList("^")); + boolean inGroup = false; + for (int i = 0; i < glob.length(); ++i) { + char c = glob.charAt(i); + if (c == '\\' && i + 1 < glob.length()) { + char ch = glob.charAt(++i); + tokens.add(escapedChars.contains(ch) ? "\\" + ch : String.valueOf(ch)); + continue; + } + if (c == '*') { + // java: a character out of the string is undefined, here null. + Character charBefore = i > 0 ? glob.charAt(i - 1) : null; + int starCount = 1; + while (i + 1 < glob.length() && glob.charAt(i + 1) == '*') { + starCount++; + i++; + } + if (starCount > 1) { + Character charAfter = i + 1 < glob.length() ? glob.charAt(i + 1) : null; + // Match either /..something../ or /. + if (charAfter != null && charAfter == '/') { + if (charBefore != null && charBefore == '/') + tokens.add("((.+/)|)"); + else + tokens.add("(.*/)"); + ++i; + } else { + tokens.add("(.*)"); + } + } else { + tokens.add("([^/]*)"); + } + continue; + } + + switch (c) { + case '{': + if (inGroup) + throw new PlaywrightException("Invalid glob pattern " + gson().toJson(glob) + ": nested '{' is not supported"); + inGroup = true; + tokens.add("("); + break; + case '}': + if (!inGroup) + throw new PlaywrightException("Invalid glob pattern " + gson().toJson(glob) + ": unmatched '}'"); + inGroup = false; + tokens.add(")"); + break; + case ',': + if (inGroup) { + tokens.add("|"); + break; + } + tokens.add("\\" + c); + break; + default: + tokens.add(escapedChars.contains(c) ? "\\" + c : String.valueOf(c)); + } } - return true; + if (inGroup) + throw new PlaywrightException("Invalid glob pattern " + gson().toJson(glob) + ": unmatched '{'"); + tokens.add("$"); + return String.join("", tokens); + } + + private static boolean isRegExp(Object obj) { + return obj instanceof Pattern; + } + + // java: the JVM has no URLPattern, like a runtime without globalThis.URLPattern. + static boolean isURLPattern(Object v) { + return false; + } + + // java: the protocol URLPattern struct stands for the URLPattern type, it has no test(). + static URLPattern serializeURLPattern(URLPattern v) { + URLPattern result = new URLPattern(); + result.hash = v.hash; + result.hostname = v.hostname; + result.password = v.password; + result.pathname = v.pathname; + result.port = v.port; + result.protocol = v.protocol; + result.search = v.search; + result.username = v.username; + return result; } + // java: the SerializedURLMatch type. + static class SerializedURLMatch { + String glob; + String regexSource; + String regexFlags; + URLPattern urlPattern; + } + + // java: an URLMatch is a String, Pattern or Predicate; a null result is undefined. + static SerializedURLMatch serializeURLMatch(Object match) { + SerializedURLMatch result = new SerializedURLMatch(); + if (isString(match)) { + result.glob = (String) match; + return result; + } + if (isRegExp(match)) { + result.regexSource = ((Pattern) match).pattern(); + result.regexFlags = toJsRegexFlags((Pattern) match); + return result; + } + if (isURLPattern(match)) { + result.urlPattern = serializeURLPattern((URLPattern) match); + return result; + } + // Functions cannot be serialized + return null; + } + + // java: the result is an URLMatch Object. + private static Object deserializeURLPattern(URLPattern v) { + // Client is on Node 24+ and can use URLPattern, Server is not. Let's match all URLs on the server, they'll be filtered again on the client. + // java: the JVM has no URLPattern, so typeof globalThis.URLPattern !== 'function' always holds and there is no + // new globalThis.URLPattern({ ... }, { ignoreCase: true }). + Predicate matchAll = url -> true; + return matchAll; + } + + static Object deserializeURLMatch(SerializedURLMatch match) { + if (match.regexSource != null && !match.regexSource.isEmpty()) + return Pattern.compile(match.regexSource, fromJsRegexFlags(match.regexFlags == null ? "" : match.regexFlags)); + if (match.urlPattern != null) + return deserializeURLPattern(match.urlPattern); + return match.glob; + } + + // java: the Java flags stand for the JS flags; === compares strings by value and functions by identity, as + // Objects.equals() does for a String and a Predicate. + static boolean urlMatchesEqual(Object match1, Object match2) { + if (isRegExp(match1) && isRegExp(match2)) + return ((Pattern) match1).pattern().equals(((Pattern) match2).pattern()) && ((Pattern) match1).flags() == ((Pattern) match2).flags(); + return Objects.equals(match1, match2); + } + + // java: urlMatchesEqual(match1, match2) of two UrlMatcher values, the reachable path. @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UrlMatcher that = (UrlMatcher) o; - if (pattern != null) { - return that.pattern != null && pattern.pattern().equals(that.pattern.pattern()) && pattern.flags() == that.pattern.flags(); + if (isRegExp() && that.isRegExp()) { + return pattern.pattern().equals(that.pattern.pattern()) && pattern.flags() == that.pattern.flags(); } - if (predicate != null) { - return predicate.equals(that.predicate); + // java: match1 === match2 compares strings by value and functions by identity. + if (glob != null || that.glob != null) { + return Objects.equals(glob, that.glob); } - if (glob != null) { - return glob.equals(that.glob); + if (predicate != null || that.predicate != null) { + return predicate == that.predicate; } - return that.pattern == null && that.predicate == null && that.glob == null; + return pattern == null && that.pattern == null; } @Override public int hashCode() { + if (glob != null) { + return glob.hashCode(); + } if (pattern != null) { - return pattern.hashCode(); + return Objects.hash(pattern.pattern(), pattern.flags()); } if (predicate != null) { - return predicate.hashCode(); - } - if (glob != null) { - return glob.hashCode(); + return System.identityHashCode(predicate); } return 0; } + static boolean urlMatches(String baseURL, String urlString, Object match) { + return urlMatches(baseURL, urlString, match, false); + } + + // java: an URLMatch is a String, Pattern or Predicate, a null baseURL or match is undefined. + @SuppressWarnings("unchecked") + static boolean urlMatches(String baseURL, String urlString, Object match, boolean webSocketUrl) { + if (match == null || "".equals(match)) + return true; + if (isString(match)) + match = Pattern.compile(resolveGlobToRegexPattern(baseURL, (String) match, webSocketUrl)); + if (isRegExp(match)) { + // java: no match.lastIndex = 0, a Matcher keeps no state between tests. + return ((Pattern) match).matcher(urlString).find(); + } + URI url = parseURL(urlString); + if (url == null) + return false; + // java: no isURLPattern(match) branch, the JVM has no URLPattern whose test() could be called. + if (!(match instanceof Predicate)) + throw new PlaywrightException("url parameter should be string, RegExp, URLPattern or function"); + // java: a Predicate stands for the function, it takes url.href. + return ((Predicate) match).test(url.toString()); + } + + // java: urlMatches(baseURL, urlString, match), the reachable path; the glob was resolved against the base URL by + // forGlob(), and a predicate takes the URL string, not a parsed URL. + boolean test(String urlString) { + if ((glob == null && pattern == null && predicate == null) || "".equals(glob)) { + return true; + } + if (pattern != null) { + return pattern.matcher(urlString).find(); + } + return predicate.test(urlString); + } + + static String resolveGlobToRegexPattern(String baseURL, String glob) { + return resolveGlobToRegexPattern(baseURL, glob, false); + } + + // java: a null baseURL is undefined. + static String resolveGlobToRegexPattern(String baseURL, String glob, boolean webSocketUrl) { + if (webSocketUrl) + baseURL = toWebSocketBaseUrl(baseURL); + glob = resolveGlobBase(baseURL, glob); + return globToRegexPattern(glob); + } + + // java: resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) and new RegExp(...), the reachable path: the + // driver resolves the glob. + static UrlMatcher forGlob(URL baseURL, String glob, LocalUtils localUtils, boolean isWebSocketUrl) { + Pattern pattern = localUtils.globToRegex(glob, baseURL != null ? baseURL.toString() : null, isWebSocketUrl); + return new UrlMatcher(glob, pattern, null); + } + + private static String toWebSocketBaseUrl(String baseURL) { + // Allow http(s) baseURL to match ws(s) urls. Schemes are case-insensitive, + // same as elsewhere in this file, so 'HTTP://...' should be rewritten too. + if (baseURL != null && Pattern.compile("^https?://", Pattern.CASE_INSENSITIVE).matcher(baseURL).find()) { + Matcher scheme = Pattern.compile("^https?", Pattern.CASE_INSENSITIVE).matcher(baseURL); + scheme.find(); + baseURL = (scheme.group().toLowerCase().equals("https") ? "wss" : "ws") + baseURL.substring(scheme.end()); + } + return baseURL; + } + + private static String resolveGlobBase(String baseURL, String match) { + if (!match.startsWith("*")) { + Map tokenMap = new LinkedHashMap<>(); + BiFunction mapToken = (original, replacement) -> { + if (original.length() == 0) + return ""; + tokenMap.put(replacement, original); + return replacement; + }; + // Escaped `\\?` behaves the same as `?` in our glob patterns. + match = match.replaceAll("\\\\\\\\\\?", "?"); + // Special case about: URLs as they are not relative to baseURL + if (match.startsWith("about:") || match.startsWith("data:") + || match.startsWith("chrome:") || match.startsWith("edge:") + || match.startsWith("file:")) + return match; + // Glob symbols may be escaped in the URL and some of them such as ? affect resolution, + // so we replace them with safe components first. + BiFunction mapPathToken = (token, index) -> { + if (token.equals(".") || token.equals("..") || token.equals("")) + return token; + // Handle special case of http*://, note that the new schema has to be + // a web schema so that slashes are properly inserted after domain. + if (index == 0 && token.endsWith(":")) { + // Replace any pattern with http: + if (token.indexOf('*') != -1 || token.indexOf('{') != -1) + return mapToken.apply(token, "http:"); + // Preserve explicit schema as is as it may affect trailing slashes after domain. + return token; + } + // Components without glob metacharacters are literal, so let them round-trip + // through new URL() to preserve normalization (default ports such as :80/:443, + // percent-encoding, IDN hosts). Only opaque tokens defeat that normalization. + if (!Pattern.compile("[*?{}\\\\]").matcher(token).find()) + return token; + int questionIndex = token.indexOf('?'); + if (questionIndex == -1) + return mapToken.apply(token, "$_" + index + "_$"); + String newPrefix = mapToken.apply(token.substring(0, questionIndex), "$_" + index + "_$"); + String newSuffix = mapToken.apply(token.substring(questionIndex), "?$_" + index + "_$"); + return newPrefix + newSuffix; + }; + String[] pathTokens = match.split("/", -1); + List mappedTokens = new ArrayList<>(); + for (int index = 0; index < pathTokens.length; index++) + mappedTokens.add(mapPathToken.apply(pathTokens[index], index)); + String relativePath = String.join("/", mappedTokens); + ResolvedBaseURL result = resolveBaseURL(baseURL, relativePath); + String resolved = result.resolved; + for (Map.Entry entry : tokenMap.entrySet()) { + String token = entry.getKey(); + String original = entry.getValue(); + boolean normalize = result.caseInsensitivePart != null && result.caseInsensitivePart.contains(token); + String replacement = normalize ? original.toLowerCase() : original; + // '$$', '$&', '$`' and "$'" are special in String.prototype.replace with a string argument. + // Instead, use the function argument form that treats the string argument literally. + // java: indexOf() and substring() replace the first occurrence literally. + int tokenIndex = resolved.indexOf(token); + if (tokenIndex != -1) + resolved = resolved.substring(0, tokenIndex) + replacement + resolved.substring(tokenIndex + token.length()); + } + match = resolved; + } + return match; + } + + // java: a URI that newURL() cannot build is the TypeError of new URL(). + private static URI parseURL(String url) { + try { + return newURL(url, null); + } catch (URISyntaxException | IllegalArgumentException e) { + return null; + } + } + + // java: not resolveBaseURL(baseURL, givenURL).resolved: PageAssertionsImpl depends on URI.resolve() and on + // givenURL coming back unchanged without a base, the behaviour of the Java client. + static String constructURLBasedOnBaseURL(String baseURL, String givenURL) { + if (baseURL == null) { + return givenURL; + } + try { + // Join using URI instead of URL since URL doesn't handle ws(s) protocols. + return new URI(baseURL).resolve(givenURL).toString(); + } catch (URISyntaxException | IllegalArgumentException e) { + return givenURL; + } + } + + // java: the { resolved, caseInsensitivePart } result, a null caseInsensitivePart is undefined. + private static class ResolvedBaseURL { + final String resolved; + final String caseInsensitivePart; + + ResolvedBaseURL(String resolved, String caseInsensitivePart) { + this.resolved = resolved; + this.caseInsensitivePart = caseInsensitivePart; + } + } + + private static ResolvedBaseURL resolveBaseURL(String baseURL, String givenURL) { + try { + URI url = newURL(givenURL, baseURL); + String resolved = url.toString(); + // Schema and domain are case-insensitive. + String caseInsensitivePrefix = origin(url); + return new ResolvedBaseURL(resolved, caseInsensitivePrefix); + } catch (URISyntaxException | IllegalArgumentException e) { + return new ResolvedBaseURL(givenURL, null); + } + } + + // java: members with no counterpart upstream. + + private boolean isRegExp() { + return glob == null && pattern != null; + } + @Override public String toString() { if (glob != null) - return String.format("", glob); + return String.format("", glob); if (pattern != null) return String.format("", pattern.pattern(), toJsRegexFlags(pattern)); if (this.predicate != null) return ""; return ""; } + + // java: new URL(url, base) of the WHATWG URL parser on top of java.net.URI: a null base is undefined, a relative URL + // without a base fails, the scheme and the host are lower-cased, a default port is dropped and the empty path of a + // special scheme becomes '/'. Unlike the WHATWG parser it does not percent-encode, so a URL with a space or a + // character such as '|' fails to parse. + private static URI newURL(String url, String base) throws URISyntaxException { + URI uri; + if (base == null) { + uri = new URI(url); + } else { + URI baseURI = new URI(base); + if (!baseURI.isAbsolute()) + throw new URISyntaxException(base, "Invalid base URL"); + uri = normalizeURL(baseURI).resolve(new URI(url)); + } + if (!uri.isAbsolute()) + throw new URISyntaxException(url, "Invalid URL"); + return normalizeURL(uri.normalize()); + } + + private static URI normalizeURL(URI uri) throws URISyntaxException { + String scheme = uri.getScheme().toLowerCase(); + if (uri.isOpaque()) + return new URI(scheme + ":" + uri.getRawSchemeSpecificPart() + (uri.getRawFragment() != null ? "#" + uri.getRawFragment() : "")); + StringBuilder result = new StringBuilder(scheme).append(':'); + String authority = uri.getRawAuthority(); + if (authority != null) { + result.append("//"); + if (uri.getHost() != null) { + if (uri.getRawUserInfo() != null) + result.append(uri.getRawUserInfo()).append('@'); + result.append(uri.getHost().toLowerCase()); + if (uri.getPort() != -1 && uri.getPort() != defaultPort(scheme)) + result.append(':').append(uri.getPort()); + } else { + result.append(authority); + } + } + String path = uri.getRawPath(); + if ((path == null || path.isEmpty()) && authority != null && defaultPort(scheme) != -1) + path = "/"; + if (path != null) + result.append(path); + if (uri.getRawQuery() != null) + result.append('?').append(uri.getRawQuery()); + if (uri.getRawFragment() != null) + result.append('#').append(uri.getRawFragment()); + return new URI(result.toString()); + } + + // java: the default port of a special scheme with a network host, -1 for any other scheme. + private static int defaultPort(String scheme) { + switch (scheme) { + case "http": + case "ws": + return 80; + case "https": + case "wss": + return 443; + case "ftp": + return 21; + default: + return -1; + } + } + + // java: URL.protocol. + private static String protocol(URI url) { + return url.getScheme() + ":"; + } + + // java: URL.origin; a scheme without a default port has the opaque origin "null". A host that java.net.URI does + // not accept, such as a $_2_$ token, is taken from the authority without its user info. + private static String origin(URI url) { + if (defaultPort(url.getScheme()) == -1 || url.getRawAuthority() == null) + return "null"; + String host; + if (url.getHost() != null) + host = url.getHost() + (url.getPort() != -1 ? ":" + url.getPort() : ""); + else + host = url.getRawAuthority().substring(url.getRawAuthority().lastIndexOf('@') + 1); + return url.getScheme() + "://" + host; + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java index a6dc6a653..9d7056e17 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java @@ -16,38 +16,26 @@ package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.stream.JsonWriter; -import com.google.gson.stream.JsonReader; -import com.google.gson.reflect.TypeToken; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.TypeAdapter; import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.options.ClientCertificate; import com.microsoft.playwright.options.FilePayload; -import com.microsoft.playwright.options.HttpHeader; -import com.microsoft.playwright.options.ScreenshotType; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; -import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; -import java.util.*; +import java.util.Random; import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static java.nio.file.Files.readAllBytes; +// java: helpers with no upstream counterpart. public class Utils { static T convertType(F f, Class t) { if (f == null) { @@ -92,6 +80,13 @@ static T convertType(F f, Class t) { } } + public static T clone(T f) { + if (f == null) { + return f; + } + return convertType(f, (Class) f.getClass()); + } + /** * Copies public API options into a generated protocol params class with the same Gson that serializes them * on the wire. Params that carry channel references (a locator mask holds a frame) must be built with the @@ -146,156 +141,6 @@ public ChannelOwner read(JsonReader in) { } }).create(); - public static T clone(T f) { - if (f == null) { - return f; - } - return convertType(f, (Class) f.getClass()); - } - - static String mimeType(Path path) { - String mimeType; - try { - mimeType = Files.probeContentType(path); - } catch (IOException e) { - throw new PlaywrightException("Failed to determine mime type", e); - } - if (mimeType == null) { - mimeType = "application/octet-stream"; - } - return mimeType; - } - - /** Upload fields shared by the set-input-files and drop params; each call site copies them into its own params class. */ - static class UploadParams { - boolean emptyPayloads; - List localPaths; - List streams; - String localDirectory; - WritableStream directoryStream; - } - - static UploadParams addFilePathUploadParams(Path[] items, BrowserContextImpl context) { - UploadParams upload = new UploadParams(); - List localPaths = new ArrayList<>(); - Path localDirectory = resolvePathsAndDirectoryForInputFiles(items, localPaths); - if (items.length == 0) { - // FIXME: shouldBeAbleToResetSelectedFilesWithEmptyFileList tesst hangs in Chromium if we pass empty paths list. - upload.emptyPayloads = true; - } else if (context.connection.isRemote()) { - if (localDirectory != null) { - localPaths = collectFiles(localDirectory); - } - BrowserContextCreateTempFilesResult result = createTempFiles(context, localDirectory, localPaths); - List streams = copyLocalToTempFiles(localPaths, result.writableStreams); - if (result.rootDir != null) { - upload.directoryStream = result.rootDir; - } else { - upload.streams = streams; - } - } else { - if (!localPaths.isEmpty()) { - upload.localPaths = new ArrayList<>(); - for (Path p : localPaths) { - upload.localPaths.add(p.toAbsolutePath().toString()); - } - } - if (localDirectory != null) { - upload.localDirectory = localDirectory.toString(); - } - } - return upload; - } - - private static Path resolvePathsAndDirectoryForInputFiles(Path[] items, List outLocalPaths) { - Path localDirectory = null; - try { - for (Path item : items) { - if (Files.isDirectory(item)) { - if (localDirectory != null) { - throw new PlaywrightException("Multiple directories are not supported"); - } - localDirectory = item.toRealPath(); - } else { - outLocalPaths.add(item.toRealPath()); - } - } - } catch (IOException e) { - throw new PlaywrightException("Cannot get absolute file path", e); - } - if (!outLocalPaths.isEmpty() && localDirectory != null) { - throw new PlaywrightException("File paths must be all files or a single directory"); - } - return localDirectory; - } - - private static List collectFiles(Path localDirectory) { - try { - return Files.walk(localDirectory).filter(e -> Files.isRegularFile(e)).collect(Collectors.toList()); - } catch (IOException e) { - throw new PlaywrightException("Failed to traverse directory", e); - } - } - - private static List copyLocalToTempFiles(List localPaths, List writableStreams) { - List streams = new ArrayList<>(); - for (int i = 0; i < localPaths.size(); i++) { - WritableStream temp = writableStreams.get(i); - try (OutputStream out = temp.stream()) { - Files.copy(localPaths.get(i), out); - } catch (IOException e) { - throw new PlaywrightException("Failed to copy file to remote server.", e); - } - streams.add(temp); - } - return streams; - } - - private static BrowserContextCreateTempFilesResult createTempFiles(BrowserContextImpl context, Path localDirectory, List localPaths) { - BrowserContextCreateTempFilesParams params = new BrowserContextCreateTempFilesParams(); - if (localDirectory != null) { - params.rootDirName = localDirectory.getFileName().toString(); - } - params.items = new ArrayList<>(); - for (Path path : localPaths) { - long lastModifiedMs; - try { - lastModifiedMs = Files.getLastModifiedTime(path).toMillis(); - } catch (IOException e) { - throw new PlaywrightException("Cannot read file timestamp: " + path, e); - } - Path name; - if (localDirectory == null) { - name = path.getFileName(); - } else { - name = localDirectory.relativize(path); - } - BrowserContextCreateTempFilesParams.BrowserContextCreateTempFilesParamsItems item = new BrowserContextCreateTempFilesParams.BrowserContextCreateTempFilesParamsItems(); - item.name = name.toString(); - item.lastModifiedMs = (double) lastModifiedMs; - params.items.add(item); - } - return context.channel.createTempFiles(params, NO_TIMEOUT); - } - - static void checkFilePayloadSize(FilePayload[] files) { - long totalSize = 0; - for (FilePayload file: files) { - totalSize += file.buffer.length; - } - if (totalSize > 50 * 1024 * 1024) { - throw new PlaywrightException("Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead."); - } - } - - static FilePayload[] toFilePayloads(Path[] files) { - List payloads = new ArrayList<>(); - for (Path file : files) { - payloads.add(toFilePayload(file)); - } - return payloads.toArray(new FilePayload[0]); - } - static FilePayload toFilePayload(Path file) { byte[] buffer; try { @@ -306,36 +151,8 @@ static FilePayload toFilePayload(Path file) { return new FilePayload(file.getFileName().toString(), null, buffer); } - static void mkParentDirs(Path file) { - Path dir = file.getParent(); - if (dir != null) { - if (!Files.exists(dir)) { - try { - Files.createDirectories(dir); - } catch (IOException e) { - throw new PlaywrightException("Failed to create parent directory: " + dir, e); - } - } - } - } - - /** The screenshot type for a path when no type is given, from its extension, like the Node.js client. */ - static ScreenshotType screenshotTypeForPath(Path path) { - String fileName = path.getFileName().toString(); - int extStart = fileName.lastIndexOf('.'); - String extension = extStart == -1 ? "" : fileName.substring(extStart + 1).toLowerCase(); - switch (extension) { - case "png": return ScreenshotType.PNG; - case "jpg": - case "jpeg": return ScreenshotType.JPEG; - case "webp": return ScreenshotType.WEBP; - default: - throw new PlaywrightException("path: unsupported mime type \"" + URLConnection.guessContentTypeFromName(fileName) + "\""); - } - } - static void writeToFile(byte[] buffer, Path path) { - mkParentDirs(path); + FileUtils.mkdirIfNeeded(path); try (FileOutputStream out = new FileOutputStream(path.toFile())) { out.write(buffer); } catch (IOException e) { @@ -344,7 +161,7 @@ static void writeToFile(byte[] buffer, Path path) { } static void writeToFile(InputStream inputStream, Path path) { - mkParentDirs(path); + FileUtils.mkdirIfNeeded(path); try (FileOutputStream out = new FileOutputStream(path.toFile())) { byte[] buf = new byte[1024 * 1024]; int length; @@ -356,46 +173,7 @@ static void writeToFile(InputStream inputStream, Path path) { } } - static String createGuid() { - StringBuffer result = new StringBuffer(); - Random random = new Random(); - for (int i = 0; i < 4; i++) { - result.append(Integer.toHexString(random.nextInt())); - } - return result.toString(); - } - - static Map toHeadersMap(List headers) { - Map map = new LinkedHashMap<>(); - for (HttpHeader header: headers) { - map.put(header.name.toLowerCase(), header.value); - } - return map; - } - - static void assertNoNullItems(Object[] values) { - for (int i = 0; i < values.length; i++) { - if (values[i] == null) { - throw new PlaywrightException("options[" + i + "]: expected object, got null"); - } - } - } - - static List toHeadersList(Map headers) { - List list = new ArrayList<>(); - for (Map.Entry entry: headers.entrySet()) { - if (entry.getValue() == null) { - continue; - } - HttpHeader header = new HttpHeader(); - header.name = entry.getKey(); - header.value = entry.getValue(); - list.add(header); - } - return list; - } - - static String toJsRegexFlags(Pattern pattern) { + public static String toJsRegexFlags(Pattern pattern) { String regexFlags = ""; if ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) { // Case-insensitive search. @@ -429,30 +207,13 @@ static int fromJsRegexFlags(String regexFlags) { return flags; } - static String addSourceUrlToScript(String source, Path path) { - return source + "\n//# sourceURL=" + path.toString().replace("\n", ""); - } - - static JsonObject interceptionPatterns(List matchers) { - JsonArray jsonPatterns = new JsonArray(); - for (UrlMatcher matcher: matchers) { - JsonObject jsonPattern = new JsonObject(); - if (matcher.glob != null) { - jsonPattern.addProperty("glob", matcher.glob); - } else if (matcher.pattern != null) { - jsonPattern.addProperty("regexSource", matcher.pattern.pattern()); - jsonPattern.addProperty("regexFlags", toJsRegexFlags(matcher.pattern)); - } else { - // Match all requests. - jsonPattern.addProperty("glob", "**/*"); - jsonPatterns = new JsonArray(); - jsonPatterns.add(jsonPattern); - break; - } - jsonPatterns.add(jsonPattern); + // java: createGuid of utils/crypto.ts, a Node.js utils file outside the client. + static String createGuid() { + StringBuffer result = new StringBuffer(); + Random random = new Random(); + for (int i = 0; i < 4; i++) { + result.append(Integer.toHexString(random.nextInt())); } - JsonObject result = new JsonObject(); - result.add("patterns", jsonPatterns); - return result; + return result.toString(); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java index 8cee30e23..797afe53a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of video.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; @@ -22,30 +23,19 @@ import java.nio.file.Path; import java.nio.file.Paths; -class VideoImpl implements Video { - private final PageImpl page; - ArtifactImpl artifact; +class VideoImpl extends EventEmitter implements Video { + private ArtifactImpl artifact; + private boolean isRemote = false; - VideoImpl(PageImpl page) { - this.page = page; - } - - VideoImpl(PageImpl page, ArtifactImpl artifact) { - this.page = page; + VideoImpl(Connection connection, ArtifactImpl artifact) { + this.isRemote = connection.isRemote(); this.artifact = artifact; } - @Override - public void delete() { - if (artifact != null) - artifact.delete(); - } - @Override public Path path() { - if (page.connection.isRemote()) { + if (isRemote) throw new PlaywrightException("Path is not available when connecting remotely. Use saveAs() to save a local copy."); - } if (artifact == null) throw new PlaywrightException("Video recording has not been started."); return Paths.get(artifact.initializer.get("absolutePath").getAsString()); @@ -57,4 +47,15 @@ public void saveAs(Path path) { throw new PlaywrightException("Video recording has not been started."); artifact.saveAs(path); } + + @Override + public void delete() { + if (artifact != null) + artifact.delete(); + } + + // java: the constructor PageImpl calls. + VideoImpl(PageImpl page, ArtifactImpl artifact) { + this(page.connection, artifact); + } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java index 88b2ad12b..6fb6fd690 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of waiter.ts. package com.microsoft.playwright.impl; import com.google.gson.JsonObject; @@ -27,7 +28,7 @@ import static com.microsoft.playwright.impl.Utils.createGuid; -// Port of waiter.ts. java: promises are Waitables, the API thread pumps the connection in waitForPromise(), +// java: promises are Waitables, the API thread pumps the connection in waitForPromise(), // there are no zones to save and no AbortSignal. class Waiter { private final List dispose = new ArrayList<>(); @@ -66,23 +67,41 @@ static Waiter createForEvent(ChannelOwner channelOwner, String event) { private void sendWaitInfo(JsonObject info, String title, boolean internal) { // Fire-and-forget: server intentionally never replies, and we never throw to the caller. + ChannelOwner owner = channelOwner; try { - channelOwner.wrapApiCall(() -> { - ApiZone apiZone = channelOwner.connection.apiZone; - if (!apiZone.internal && !apiZone.reported && apiZone.title == null) { - // An outer wrapApiCall may have set its own title (e.g. "Wait for navigation"); - // fall back to ours only when the outer zone left it blank. + owner.wrapApiCall(() -> { + ApiZone apiZone = owner.connection.apiZone; + // java: timeout: 0 is not sent, a null timeout stays absent from the metadata (see Connection.sendMessageToServer). + if (apiZone.internal || apiZone.reported) { + Connection.CallOptions options = new Connection.CallOptions(); + options.internal = true; + owner.connection.sendMessageToServer(owner, "__waitInfo__", info, options); + return; + } + apiZone.reported = true; + // An outer `_wrapApiCall` may have set its own title (e.g. "Wait for navigation"); + // fall back to ours only when the outer zone left it blank. The title is read both by + // `onApiCallBegin` (drives the test runner step title) and by `sendMessageToServer` + // (drives the trace viewer action title), so set it on the zone itself. + if (apiZone.title == null || apiZone.title.isEmpty()) { apiZone.title = title; } - // sendMessageNoReply reports the call when it is the first message of the zone and sends it - // as internal otherwise. - channelOwner.sendMessageNoReply("__waitInfo__", info); + // java: the stack trace is captured by the first reported message, see ChannelOwner.callOptions. + apiZone.frames = owner.connection.captureLibraryStackTrace(); + owner.instrumentation.onApiCallBegin(apiZone, owner.type, "__waitInfo__", info); + Connection.CallOptions options = new Connection.CallOptions(); + options.apiName = apiZone.apiName; + options.title = apiZone.title; + options.frames = apiZone.frames; + options.callId = apiZone.callId; + owner.connection.sendMessageToServer(owner, "__waitInfo__", info, options); }, title, internal); } catch (RuntimeException e) { // Fire-and-forget: never throw to the caller. } } + // java: returns the waitable instead of awaiting waitForPromise; the callback overload at the bottom waits. Waitable waitForEvent(EventEmitter emitter, String event, Predicate predicate) { return new WaitableEvent<>(emitter, event, predicate); } @@ -100,6 +119,7 @@ public T get() { }); } + // java: the AbortSignal branch is not ported, there is no AbortSignal. void rejectOnTimeout(Double timeout, String timeoutMessage) { if (timeout != null && timeout != 0) { rejectOn(new WaitableTimeout(timeout) { @@ -169,6 +189,7 @@ private T waitForPromise(Waitable waitable, Runnable code) { void log(String s) { logs.add(s); + // java: also printed with DEBUG=pw:api, as the Java client always did. LoggingSupport.logApiIfEnabled(s); JsonObject info = new JsonObject(); info.addProperty("waitId", waitId); @@ -182,6 +203,8 @@ private void rejectOn(Waitable failure) { dispose.add(failure::dispose); } + // java: the module functions waitForEvent and waitForTimeout are WaitableEvent and WaitableTimeout. + // java: exceptions are immutable, so a new one of the same class carries the message with the logs. private RuntimeException rewriteErrorMessage(RuntimeException e) { String recording = formatLogRecording(logs); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebErrorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebErrorImpl.java index 95530ac05..ad04660f0 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebErrorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebErrorImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of webError.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.WebError; @@ -21,6 +22,7 @@ public class WebErrorImpl implements WebError { private final PageImpl page; + // java: the error is the message string, upstream keeps an Error. private final String error; private final WebErrorLocation location; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java index 639ca4cee..823a27492 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of webmcp.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java index 546a02537..20b5b92e8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java @@ -1,18 +1,37 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of network.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.WebSocketFrame; -import java.nio.charset.StandardCharsets; import java.util.Base64; +// java: the { payload: string | Buffer } of the WebSocket frame events and the messages of WebSocketRoute. class WebSocketFrameImpl implements WebSocketFrame { - private byte[] bytes; - private String text; + private final byte[] bytes; + private final String text; WebSocketFrameImpl(String payload, boolean isBase64) { if (isBase64) { bytes = Base64.getDecoder().decode(payload); + text = null; } else { + bytes = null; text = payload; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java index 0f5b9df1f..268a3f8b9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java @@ -14,16 +14,19 @@ * limitations under the License. */ +// Port of network.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.WebSocket; import com.microsoft.playwright.WebSocketFrame; +import com.microsoft.playwright.impl.protocol.WebSocketChannel; +import com.microsoft.playwright.impl.protocol.WebSocketFrameReceivedEvent; +import com.microsoft.playwright.impl.protocol.WebSocketFrameSentEvent; +import com.microsoft.playwright.impl.protocol.WebSocketInitializer; +import com.microsoft.playwright.impl.protocol.WebSocketSocketErrorEvent; -import java.util.ArrayList; -import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; @@ -32,12 +35,81 @@ public class WebSocketImpl extends ChannelOwner implements WebSocket { private boolean isClosed; final WebSocketChannel channel = new WebSocketChannel(this); + private final WebSocketInitializer webSocketInitializer; + + // java: from is not ported, generated results already hold the impl object. WebSocketImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); - page = (PageImpl) parent; + webSocketInitializer = connection.protocolGson().fromJson(initializer, WebSocketInitializer.class); + this.isClosed = false; + this.page = (PageImpl) parent; + } + + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. + @Override + void handleEvent(String event, JsonObject params) { + switch (event) { + case "frameSent": { + WebSocketFrameSentEvent e = connection.protocolGson().fromJson(params, WebSocketFrameSentEvent.class); + if (e.opcode == 1) { + emit(Events.WebSocket.FRAME_SENT, new WebSocketFrameImpl(e.data, false)); + } else if (e.opcode == 2) { + emit(Events.WebSocket.FRAME_SENT, new WebSocketFrameImpl(e.data, true)); + } + break; + } + case "frameReceived": { + WebSocketFrameReceivedEvent e = connection.protocolGson().fromJson(params, WebSocketFrameReceivedEvent.class); + if (e.opcode == 1) { + emit(Events.WebSocket.FRAME_RECEIVED, new WebSocketFrameImpl(e.data, false)); + } else if (e.opcode == 2) { + emit(Events.WebSocket.FRAME_RECEIVED, new WebSocketFrameImpl(e.data, true)); + } + break; + } + case "socketError": { + WebSocketSocketErrorEvent e = connection.protocolGson().fromJson(params, WebSocketSocketErrorEvent.class); + emit(Events.WebSocket.ERROR, e.error); + break; + } + case "close": { + isClosed = true; + emit(Events.WebSocket.CLOSE, this); + break; + } + } + } + + @Override + public String url() { + return webSocketInitializer.url; + } + + @Override + public boolean isClosed() { + return isClosed; + } + + // java: the predicate and timeout are passed separately and the code to run is a Runnable; no wrapApiCall + // for @apiCall(), so that the calls of the callback are reported on their own (see WorkerImpl). + private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { + double timeoutMs = page.timeoutSettings.timeout(timeout); + Waiter waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.WebSocket.ERROR.equals(event)) { + waiter.rejectOnEvent(this, Events.WebSocket.ERROR, () -> new PlaywrightException("Socket error")); + } + if (!Events.WebSocket.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.WebSocket.CLOSE, () -> new PlaywrightException("Socket closed")); + } + waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } + // java: typed on/off/waitFor overloads of the generated WebSocket interface. @Override public void onClose(Consumer handler) { on(Events.WebSocket.CLOSE, handler); @@ -79,84 +151,20 @@ public void offSocketError(Consumer handler) { } @Override - public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable code) { + public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable callback) { if (options == null) { options = new WaitForFrameReceivedOptions(); } - return waitForEvent(Events.WebSocket.FRAME_RECEIVED, options.predicate, options.timeout, code); + return waitForEvent(Events.WebSocket.FRAME_RECEIVED, options.predicate, options.timeout, callback); } @Override - public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable code) { + public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable callback) { if (options == null) { options = new WaitForFrameSentOptions(); } - return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, code); + return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, callback); } - @Override - public boolean isClosed() { - return isClosed; - } - - @Override - public String url() { - return initializer.get("url").getAsString(); - } - - // waitForEvent in network.ts - private WebSocketFrame waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { - double timeoutMs = page.timeoutSettings.timeout(timeout); - Waiter waiter = Waiter.createForEvent(this, event); - waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); - if (!Events.WebSocket.ERROR.equals(event)) { - waiter.rejectOnEvent(this, Events.WebSocket.ERROR, () -> new PlaywrightException("Socket error")); - } - if (!Events.WebSocket.CLOSE.equals(event)) { - waiter.rejectOnEvent(this, Events.WebSocket.CLOSE, () -> new PlaywrightException("Socket closed")); - } - waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); - WebSocketFrame result = waiter.waitForEvent(this, event, predicate, code); - waiter.dispose(); - return result; - } - - @Override - void handleEvent(String event, JsonObject parameters) { - switch (event) { - case "frameSent": { - int opCode = parameters.get("opcode").getAsInt(); - if (opCode != 1 && opCode != 2) { - break; - } - WebSocketFrameImpl WebSocketFrame = new WebSocketFrameImpl( - parameters.get("data").getAsString(), opCode == 2); - emit(Events.WebSocket.FRAME_SENT, WebSocketFrame); - break; - } - case "frameReceived": { - int opCode = parameters.get("opcode").getAsInt(); - if (opCode != 1 && opCode != 2) { - break; - } - WebSocketFrameImpl WebSocketFrame = new WebSocketFrameImpl( - parameters.get("data").getAsString(), opCode == 2); - emit(Events.WebSocket.FRAME_RECEIVED, WebSocketFrame); - break; - } - case "socketError": { - String error = parameters.get("error").getAsString(); - emit(Events.WebSocket.ERROR, error); - break; - } - case "close": { - isClosed = true; - emit(Events.WebSocket.CLOSE, this); - break; - } - default: { - throw new PlaywrightException("Unknown event: " + event); - } - } - } + // java: validateHeaders of network.ts is RawHeaders.validateHeaders, BrowserContextImpl and PageImpl call it there. } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java new file mode 100644 index 000000000..e9f561a40 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of network.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.WebSocketRoute; +import com.microsoft.playwright.impl.protocol.BrowserContextSetWebSocketInterceptionPatternsParams.BrowserContextSetWebSocketInterceptionPatternsParamsPatterns; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +class WebSocketRouteHandler { + private final String baseURL; + final UrlMatcher url; + final Consumer handler; + + // java: UrlMatcher.forGlob() has resolved and validated a glob against the base URL already. + WebSocketRouteHandler(String baseURL, UrlMatcher url, Consumer handler) { + this.baseURL = baseURL; + this.url = url; + this.handler = handler; + } + + // java: the result is a list of the BrowserContext pattern struct; the Page struct has the same fields + // and serializes the same, so the element type is left to the caller. + @SuppressWarnings("unchecked") + static List prepareInterceptionPatterns(List handlers) { + List patterns = new ArrayList<>(); + boolean all = false; + for (WebSocketRouteHandler handler : handlers) { + BrowserContextSetWebSocketInterceptionPatternsParamsPatterns serialized = serializeURLMatch(handler.url); + if (serialized != null) { + patterns.add(serialized); + } else { + all = true; + } + } + if (all) { + BrowserContextSetWebSocketInterceptionPatternsParamsPatterns pattern = new BrowserContextSetWebSocketInterceptionPatternsParamsPatterns(); + pattern.glob = "**/*"; + patterns = new ArrayList<>(); + patterns.add(pattern); + } + return (List) (List) patterns; + } + + boolean matches(String wsURL) { + return url.test(wsURL); + } + + void handle(WebSocketRouteImpl webSocketRoute) { + Consumer handler = this.handler; + handler.accept(webSocketRoute); + webSocketRoute.afterHandle(); + } + + // java: serializeURLMatch of isomorphic/urlMatch.ts for a UrlMatcher. + private static BrowserContextSetWebSocketInterceptionPatternsParamsPatterns serializeURLMatch(UrlMatcher match) { + BrowserContextSetWebSocketInterceptionPatternsParamsPatterns result = new BrowserContextSetWebSocketInterceptionPatternsParamsPatterns(); + if (match.glob != null) { + result.glob = match.glob; + return result; + } + if (match.pattern != null) { + result.regexSource = match.pattern.pattern(); + result.regexFlags = toJsRegexFlags(match.pattern); + return result; + } + // Functions cannot be serialized + return null; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java index 1003f0a61..040d42b14 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java @@ -1,11 +1,37 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of network.ts. package com.microsoft.playwright.impl; -import com.microsoft.playwright.impl.protocol.*; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.WebSocketFrame; import com.microsoft.playwright.WebSocketRoute; +import com.microsoft.playwright.impl.protocol.WebSocketRouteChannel; +import com.microsoft.playwright.impl.protocol.WebSocketRouteClosePageEvent; +import com.microsoft.playwright.impl.protocol.WebSocketRouteClosePageParams; +import com.microsoft.playwright.impl.protocol.WebSocketRouteCloseServerEvent; +import com.microsoft.playwright.impl.protocol.WebSocketRouteCloseServerParams; +import com.microsoft.playwright.impl.protocol.WebSocketRouteConnectParams; +import com.microsoft.playwright.impl.protocol.WebSocketRouteInitializer; +import com.microsoft.playwright.impl.protocol.WebSocketRouteMessageFromPageEvent; +import com.microsoft.playwright.impl.protocol.WebSocketRouteMessageFromServerEvent; +import com.microsoft.playwright.impl.protocol.WebSocketRouteSendToPageParams; +import com.microsoft.playwright.impl.protocol.WebSocketRouteSendToServerParams; import java.util.ArrayList; import java.util.Base64; @@ -16,79 +42,160 @@ import static com.microsoft.playwright.impl.Utils.toProtocol; public class WebSocketRouteImpl extends ChannelOwner implements WebSocketRoute { + // java: from is not ported, generated results already hold the impl object. private Consumer onPageMessage; private BiConsumer onPageClose; private Consumer onServerMessage; private BiConsumer onServerClose; - private boolean connected; - private WebSocketRoute server = new WebSocketRoute() { - @Override - public void close(CloseOptions options) { - if (options == null) { - options = new CloseOptions(); + private final WebSocketRoute server; + private boolean connected = false; + + final WebSocketRouteChannel channel = new WebSocketRouteChannel(this); + private final WebSocketRouteInitializer webSocketRouteInitializer; + + WebSocketRouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + webSocketRouteInitializer = connection.protocolGson().fromJson(initializer, WebSocketRouteInitializer.class); + + this.server = new WebSocketRoute() { + @Override + public void onMessage(Consumer handler) { + onServerMessage = handler; } - WebSocketRouteCloseServerParams params = toProtocol(options, WebSocketRouteCloseServerParams.class); - params.wasClean = true; - sendMessageAsync("closeServer", params); - } - @Override - public WebSocketRoute connectToServer() { - throw new PlaywrightException("connectToServer must be called on the page-side WebSocketRoute"); - } + @Override + public void onClose(BiConsumer handler) { + onServerClose = handler; + } - @Override - public void onClose(BiConsumer handler) { - onServerClose = handler; - } + @Override + public WebSocketRoute connectToServer() { + throw new PlaywrightException("connectToServer must be called on the page-side WebSocketRoute"); + } - @Override - public void onMessage(Consumer handler) { - onServerMessage = handler; - } + @Override + public String url() { + return webSocketRouteInitializer.url; + } - @Override - public void send(String message) { - WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); - params.message = message; - params.isBase64 = false; - sendMessageAsync("sendToServer", params); - } + @Override + public List protocols() { + return new ArrayList<>(webSocketRouteInitializer.protocols); + } - @Override - public void send(byte[] message) { - WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); - params.message = Base64.getEncoder().encodeToString(message); - params.isBase64 = true; - sendMessageAsync("sendToServer", params); - } + @Override + public void close(CloseOptions options) { + if (options == null) { + options = new CloseOptions(); + } + WebSocketRouteCloseServerParams params = toProtocol(options, WebSocketRouteCloseServerParams.class); + params.wasClean = true; + try { + channel.closeServer(params, NO_TIMEOUT); + } catch (PlaywrightException e) { + } + } - @Override - public String url() { - return initializer.get("url").getAsString(); - } + // java: send(string | Buffer) is two overloads. + @Override + public void send(String message) { + WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); + params.message = message; + params.isBase64 = false; + sendNoWait("sendToServer", params); + } - @Override - public List protocols() { - return readProtocols(); + @Override + public void send(byte[] message) { + WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); + params.message = Base64.getEncoder().encodeToString(message); + params.isBase64 = true; + sendNoWait("sendToServer", params); + } + + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + }; + } + + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. + @Override + void handleEvent(String event, JsonObject params) { + switch (event) { + case "messageFromPage": { + WebSocketRouteMessageFromPageEvent e = connection.protocolGson().fromJson(params, WebSocketRouteMessageFromPageEvent.class); + if (onPageMessage != null) { + onPageMessage.accept(new WebSocketFrameImpl(e.message, e.isBase64)); + } else if (connected) { + WebSocketRouteSendToServerParams sendParams = new WebSocketRouteSendToServerParams(); + sendParams.message = e.message; + sendParams.isBase64 = e.isBase64; + sendNoWait("sendToServer", sendParams); + } + break; + } + case "messageFromServer": { + WebSocketRouteMessageFromServerEvent e = connection.protocolGson().fromJson(params, WebSocketRouteMessageFromServerEvent.class); + if (onServerMessage != null) { + onServerMessage.accept(new WebSocketFrameImpl(e.message, e.isBase64)); + } else { + WebSocketRouteSendToPageParams sendParams = new WebSocketRouteSendToPageParams(); + sendParams.message = e.message; + sendParams.isBase64 = e.isBase64; + sendNoWait("sendToPage", sendParams); + } + break; + } + case "closePage": { + WebSocketRouteClosePageEvent e = connection.protocolGson().fromJson(params, WebSocketRouteClosePageEvent.class); + if (onPageClose != null) { + onPageClose.accept(e.code, e.reason); + } else { + WebSocketRouteCloseServerParams closeParams = new WebSocketRouteCloseServerParams(); + closeParams.code = e.code; + closeParams.reason = e.reason; + closeParams.wasClean = e.wasClean; + sendNoWait("closeServer", closeParams); + } + break; + } + case "closeServer": { + WebSocketRouteCloseServerEvent e = connection.protocolGson().fromJson(params, WebSocketRouteCloseServerEvent.class); + if (onServerClose != null) { + onServerClose.accept(e.code, e.reason); + } else { + WebSocketRouteClosePageParams closeParams = new WebSocketRouteClosePageParams(); + closeParams.code = e.code; + closeParams.reason = e.reason; + closeParams.wasClean = e.wasClean; + sendNoWait("closePage", closeParams); + } + break; + } } - }; + } - final WebSocketRouteChannel channel = new WebSocketRouteChannel(this); + @Override + public String url() { + return webSocketRouteInitializer.url; + } - WebSocketRouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); + @Override + public List protocols() { + return new ArrayList<>(webSocketRouteInitializer.protocols); } - @Override + @Override public void close(CloseOptions options) { - if (options == null) { - options = new CloseOptions(); - } - WebSocketRouteClosePageParams params = toProtocol(options, WebSocketRouteClosePageParams.class); - params.wasClean = true; - sendMessageAsync("closePage", params); + if (options == null) { + options = new CloseOptions(); + } + WebSocketRouteClosePageParams params = toProtocol(options, WebSocketRouteClosePageParams.class); + params.wasClean = true; + try { + channel.closePage(params, NO_TIMEOUT); + } catch (PlaywrightException e) { + } } @Override @@ -97,26 +204,17 @@ public WebSocketRoute connectToServer() { throw new PlaywrightException("Already connected to the server"); } connected = true; - sendMessageAsync("connect", new WebSocketRouteConnectParams()); + sendNoWait("connect", new WebSocketRouteConnectParams()); return server; } - @Override - public void onClose(BiConsumer handler) { - onPageClose = handler; - } - - @Override - public void onMessage(Consumer handler) { - onPageMessage = handler; - } - + // java: send(string | Buffer) is two overloads. @Override public void send(String message) { WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); params.message = message; params.isBase64 = false; - sendMessageAsync("sendToPage", params); + sendNoWait("sendToPage", params); } @Override @@ -124,92 +222,38 @@ public void send(byte[] message) { WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); params.message = Base64.getEncoder().encodeToString(message); params.isBase64 = true; - sendMessageAsync("sendToPage", params); + sendNoWait("sendToPage", params); } @Override - public String url() { - return initializer.get("url").getAsString(); + public void onMessage(Consumer handler) { + onPageMessage = handler; } @Override - public List protocols() { - return readProtocols(); + public void onClose(BiConsumer handler) { + onPageClose = handler; } - private List readProtocols() { - List result = new ArrayList<>(); - if (!initializer.has("protocols")) { - return result; - } - for (JsonElement element : initializer.getAsJsonArray("protocols")) { - result.add(element.getAsString()); - } - return result; - } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. void afterHandle() { - if (this.connected) { + if (connected) { return; } // Ensure that websocket is "open" and can send messages without an actual server connection. + // If this happens after the page has been closed, ignore the error. try { - sendMessageAsync("ensureOpened", new WebSocketRouteEnsureOpenedParams()); + channel.ensureOpened(NO_TIMEOUT); } catch (PlaywrightException e) { - // If this happens after the page has been closed, ignore the error. } } - @Override - protected void handleEvent(String event, JsonObject params) { - if ("messageFromPage".equals(event)) { - String message = params.get("message").getAsString(); - boolean isBase64 = params.get("isBase64").getAsBoolean(); - if (onPageMessage != null) { - onPageMessage.accept(new WebSocketFrameImpl(message, isBase64)); - } else if (connected) { - WebSocketRouteSendToServerParams messageParams = new WebSocketRouteSendToServerParams(); - messageParams.message = message; - messageParams.isBase64 = isBase64; - sendMessageAsync("sendToServer", messageParams); - } - } else if ("messageFromServer".equals(event)) { - String message = params.get("message").getAsString(); - boolean isBase64 = params.get("isBase64").getAsBoolean(); - if (onServerMessage != null) { - onServerMessage.accept(new WebSocketFrameImpl(message, isBase64)); - } else { - WebSocketRouteSendToPageParams messageParams = new WebSocketRouteSendToPageParams(); - messageParams.message = message; - messageParams.isBase64 = isBase64; - sendMessageAsync("sendToPage", messageParams); - } - } else if ("closePage".equals(event)) { - Integer code = params.has("code") ? params.get("code").getAsInt() : null; - String reason = params.has("reason") ? params.get("reason").getAsString() : null; - boolean wasClean = params.has("wasClean") && params.get("wasClean").getAsBoolean(); - if (onPageClose != null) { - onPageClose.accept(code, reason); - } else { - WebSocketRouteCloseServerParams closeParams = new WebSocketRouteCloseServerParams(); - closeParams.code = code; - closeParams.reason = reason; - closeParams.wasClean = wasClean; - sendMessageAsync("closeServer", closeParams); - } - } else if ("closeServer".equals(event)) { - Integer code = params.has("code") ? params.get("code").getAsInt() : null; - String reason = params.has("reason") ? params.get("reason").getAsString() : null; - boolean wasClean = params.has("wasClean") && params.get("wasClean").getAsBoolean(); - if (onServerClose != null) { - onServerClose.accept(code, reason); - } else { - WebSocketRouteClosePageParams closeParams = new WebSocketRouteClosePageParams(); - closeParams.code = code; - closeParams.reason = reason; - closeParams.wasClean = wasClean; - sendMessageAsync("closePage", closeParams); - } + // java: a channel call that is not awaited, `this._channel.foo(...).catch(() => {})` upstream. + private void sendNoWait(String method, Object params) { + try { + sendMessageAsync(method, params); + } catch (PlaywrightException e) { } } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouter.java deleted file mode 100644 index f43869f99..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouter.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.microsoft.playwright.impl; - -import com.google.gson.JsonObject; -import com.microsoft.playwright.WebSocketRoute; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -public class WebSocketRouter { - private List routes = new ArrayList<>(); - - private static class RouteInfo { - final UrlMatcher matcher; - private final Consumer handler; - - RouteInfo(UrlMatcher matcher, Consumer handler) { - this.matcher = matcher; - this.handler = handler; - } - - void handle(WebSocketRouteImpl route) { - handler.accept(route); - route.afterHandle(); - } - } - - void add(UrlMatcher matcher, Consumer handler) { - routes.add(0, new RouteInfo(matcher, handler)); - } - - boolean handle(WebSocketRouteImpl route) { - for (RouteInfo routeInfo: routes) { - if (routeInfo.matcher.test(route.url())) { - routeInfo.handle(route); - return true; - } - } - return false; - } - - JsonObject interceptionPatterns() { - List matchers = routes.stream().map(r -> r.matcher).collect(Collectors.toList()); - return Utils.interceptionPatterns(matchers); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java index 19461c1f1..fb492b8c9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of webStorage.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java index 2b36e0734..a1641ec99 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of worker.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -34,63 +35,88 @@ import static com.microsoft.playwright.impl.Serialization.*; public class WorkerImpl extends ChannelOwner implements Worker { - PageImpl page; + PageImpl page; // Set for web workers. + BrowserContextImpl context; // Set for service workers. + final LongStandingScope closedScope = new LongStandingScope(this); + private String closeReason; final WorkerChannel channel = new WorkerChannel(this); + // java: fromNullable and from are not ported, generated results already hold the impl object. + WorkerImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); Map mapping = new HashMap<>(); mapping.put(Events.Worker.CONSOLE, "console"); setEventToSubscriptionMapping(mapping); + on(Events.Worker.CLOSE, new Consumer() { + @Override + public void accept(Worker worker) { + off(Events.Worker.CLOSE, this); + closedScope.close(closeErrorWithReason()); + } + }); } + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. @Override - public void onClose(Consumer handler) { - on(Events.Worker.CLOSE, handler); - } - - @Override - public void offClose(Consumer handler) { - off(Events.Worker.CLOSE, handler); + protected void handleEvent(String event, JsonObject params) { + switch (event) { + case "console": { + WorkerConsoleEvent e = connection.protocolGson().fromJson(params, WorkerConsoleEvent.class); + // Note: we only receive console events here for workers from "chromium._connectToWorker". + emit(Events.Worker.CONSOLE, new ConsoleMessageImpl(e, null, this)); + break; + } + case "close": { + if (page != null) { + page.workers.remove(this); + } + if (context != null) { + context.serviceWorkers.remove(this); + } + emit(Events.Worker.CLOSE, this); + break; + } + } } - @Override - public void onConsole(Consumer handler) { - on(Events.Worker.CONSOLE, handler); + TargetClosedError closeErrorWithReason() { + if (closeReason != null) { + return new TargetClosedError(closeReason); + } + if (page != null) { + return page.closeErrorWithReason(); + } + return new TargetClosedError(); } @Override - public void offConsole(Consumer handler) { - off(Events.Worker.CONSOLE, handler); + public String url() { + return initializer.get("url").getAsString(); } + // java: assertMaxArguments is not ported, a JS typing check; isFunction is not sent, the Java pageFunction is a string. @Override - public Worker waitForClose(WaitForCloseOptions options, Runnable code) { - if (options == null) { - options = new WaitForCloseOptions(); - } - return waitForEvent(Events.Worker.CLOSE, null, options.timeout, code); + public Object evaluate(String pageFunction, Object arg) { + WorkerEvaluateExpressionParams params = new WorkerEvaluateExpressionParams(); + params.expression = pageFunction; + params.arg = serializeArgument(arg); + return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); } @Override - public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - if (options == null) { - options = new WaitForConsoleMessageOptions(); - } - return waitForEvent(Events.Worker.CONSOLE, options.predicate, options.timeout, code); - } - - TargetClosedError closeErrorWithReason() { - if (page != null) { - return page.closeErrorWithReason(); - } - return new TargetClosedError(); + public JSHandle evaluateHandle(String pageFunction, Object arg) { + WorkerEvaluateExpressionHandleParams params = new WorkerEvaluateExpressionHandleParams(); + params.expression = pageFunction; + params.arg = serializeArgument(arg); + return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; } - // waitForEvent in worker.ts + // java: the predicate and timeout are passed separately and the code to run is a Runnable; @apiCall() is not + // applied, the Runnable runs inside the wait and its calls would join the api zone. private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { - TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : context != null ? context.timeoutSettings : new TimeoutSettings(); double timeoutMs = timeoutSettings.timeout(timeout); Waiter waiter = Waiter.createForEvent(this, event); waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); @@ -102,34 +128,53 @@ private T waitForEvent(String event, Predicate predicate, Double timeout, return result; } + // java: the { reason } options are the protocol params. + void disconnect(WorkerDisconnectParams options) { + if (options == null) { + options = new WorkerDisconnectParams(); + } + closeReason = options.reason; + try { + channel.disconnect(options, NO_TIMEOUT); + } catch (TargetClosedError e) { + return; + } + } + + // java: typed on/off/waitFor overloads of the generated Worker interface. @Override - public Object evaluate(String pageFunction, Object arg) { - WorkerEvaluateExpressionParams params = new WorkerEvaluateExpressionParams(); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); + public void onClose(Consumer handler) { + on(Events.Worker.CLOSE, handler); } @Override - public JSHandle evaluateHandle(String pageFunction, Object arg) { - WorkerEvaluateExpressionHandleParams params = new WorkerEvaluateExpressionHandleParams(); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; + public void offClose(Consumer handler) { + off(Events.Worker.CLOSE, handler); } @Override - public String url() { - return initializer.get("url").getAsString(); + public void onConsole(Consumer handler) { + on(Events.Worker.CONSOLE, handler); } @Override - protected void handleEvent(String event, JsonObject params) { - if ("close".equals(event)) { - if (page != null) { - page.workers.remove(this); - } - emit(Events.Worker.CLOSE, this); + public void offConsole(Consumer handler) { + off(Events.Worker.CONSOLE, handler); + } + + @Override + public Worker waitForClose(WaitForCloseOptions options, Runnable code) { + if (options == null) { + options = new WaitForCloseOptions(); } + return waitForEvent(Events.Worker.CLOSE, null, options.timeout, code); + } + + @Override + public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { + if (options == null) { + options = new WaitForConsoleMessageOptions(); + } + return waitForEvent(Events.Worker.CONSOLE, options.predicate, options.timeout, code); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java b/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java index de274de73..cca4ab4a2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of writableStream.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -25,9 +26,12 @@ import java.nio.charset.StandardCharsets; import java.util.Arrays; +// java: the Writable is an OutputStream; _write becomes write(), _final becomes close(). public class WritableStream extends ChannelOwner { final WritableStreamChannel channel = new WritableStreamChannel(this); + // java: from is not ported, generated results already hold the impl object. + WritableStream(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java new file mode 100644 index 000000000..dabfabc23 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/headers.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.microsoft.playwright.impl.protocol.NameValue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +// java: HeadersArray is a List of the protocol NameValue, HeadersObject a Map; a null value is undefined. +public final class Headers { + private Headers() { + } + + public static List headersObjectToArray(Map headers) { + return headersObjectToArray(headers, null, null); + } + + public static List headersObjectToArray(Map headers, String separator) { + return headersObjectToArray(headers, separator, null); + } + + // java: split() takes the separator literally and keeps trailing empty strings, as String.prototype.split does; + // String.trim() only removes the ASCII whitespace of JS trim(). + public static List headersObjectToArray(Map headers, String separator, String setCookieSeparator) { + if (setCookieSeparator == null || setCookieSeparator.isEmpty()) + setCookieSeparator = separator; + List result = new ArrayList<>(); + for (Map.Entry entry : headers.entrySet()) { + String name = entry.getKey(); + String values = entry.getValue(); + if (values == null) + continue; + if (separator != null && !separator.isEmpty()) { + String sep = name.toLowerCase().equals("set-cookie") ? setCookieSeparator : separator; + for (String value : values.split(Pattern.quote(sep), -1)) + result.add(nameValue(name, value.trim())); + } else { + result.add(nameValue(name, values)); + } + } + return result; + } + + public static Map headersArrayToObject(List headers, boolean lowerCase) { + Map result = new LinkedHashMap<>(); + for (NameValue header : headers) + result.put(lowerCase ? header.name.toLowerCase() : header.name, header.value); + return result; + } + + public static List splitSetCookieHeader(List headers) { + int index = -1; + for (int i = 0; i < headers.size(); i++) { + if (headers.get(i).name.toLowerCase().equals("set-cookie")) { + index = i; + break; + } + } + if (index == -1) + return headers; + + NameValue header = headers.get(index); + List values = Arrays.asList(header.value.split("\n", -1)); + if (values.size() == 1) + return headers; + List result = new ArrayList<>(headers); + result.remove(index); + List split = new ArrayList<>(); + for (String value : values) + split.add(nameValue(header.name, value)); + result.addAll(index, split); + return result; + } + + // java: helpers with no counterpart upstream. + + // java: the { name, value } object literal. + private static NameValue nameValue(String name, String value) { + NameValue header = new NameValue(); + header.name = name; + header.value = value; + return header; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java new file mode 100644 index 000000000..1b957ea3f --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java @@ -0,0 +1,102 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/locatorUtils.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.options.AriaRole; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static com.microsoft.playwright.impl.isomorphic.StringUtils.escapeForAttributeSelector; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.escapeForTextSelector; +import static com.microsoft.playwright.impl.isomorphic.StringUtils.jsonStringify; + +// java: the ByRoleOptions type is Locator.GetByRoleOptions. +public final class LocatorUtils { + private LocatorUtils() { + } + + // java: each getBy* method has its own options class, so the exact flag is passed instead of the options. + private static String getByAttributeTextSelector(String attrName, Object text, Boolean exact) { + return "internal:attr=[" + attrName + "=" + escapeForAttributeSelector(text, exact != null && exact) + "]"; + } + + // Multiple test id attribute names can be joined with a comma. Attribute names cannot contain commas. + public static List splitTestIdAttributeNames(String testIdAttributeName) { + return new ArrayList<>(Arrays.asList(testIdAttributeName.split(",", -1))); + } + + public static String encodeTestIdAttributeName(String testIdAttributeName) { + return testIdAttributeName.contains(",") ? jsonStringify(testIdAttributeName) : testIdAttributeName; + } + + public static String getByTestIdSelector(String testIdAttributeName, Object testId) { + return "internal:testid=[" + encodeTestIdAttributeName(testIdAttributeName) + "=" + escapeForAttributeSelector(testId, true) + "]"; + } + + public static String getByLabelSelector(Object text, Locator.GetByLabelOptions options) { + return "internal:label=" + escapeForTextSelector(text, options != null && options.exact != null && options.exact); + } + + public static String getByAltTextSelector(Object text, Locator.GetByAltTextOptions options) { + return getByAttributeTextSelector("alt", text, options == null ? null : options.exact); + } + + public static String getByTitleSelector(Object text, Locator.GetByTitleOptions options) { + return getByAttributeTextSelector("title", text, options == null ? null : options.exact); + } + + public static String getByPlaceholderSelector(Object text, Locator.GetByPlaceholderOptions options) { + return getByAttributeTextSelector("placeholder", text, options == null ? null : options.exact); + } + + public static String getByTextSelector(Object text, Locator.GetByTextOptions options) { + return "internal:text=" + escapeForTextSelector(text, options != null && options.exact != null && options.exact); + } + + // java: the role is an AriaRole enum, its lower-cased name is the upstream role string. + public static String getByRoleSelector(AriaRole role, Locator.GetByRoleOptions options) { + if (options == null) + options = new Locator.GetByRoleOptions(); + List props = new ArrayList<>(); + if (options.checked != null) + props.add(new String[] {"checked", String.valueOf(options.checked)}); + if (options.disabled != null) + props.add(new String[] {"disabled", String.valueOf(options.disabled)}); + if (options.selected != null) + props.add(new String[] {"selected", String.valueOf(options.selected)}); + if (options.expanded != null) + props.add(new String[] {"expanded", String.valueOf(options.expanded)}); + if (options.includeHidden != null) + props.add(new String[] {"include-hidden", String.valueOf(options.includeHidden)}); + if (options.level != null) + props.add(new String[] {"level", String.valueOf(options.level)}); + if (options.name != null) + props.add(new String[] {"name", escapeForAttributeSelector(options.name, options.exact != null && options.exact)}); + if (options.description != null) + props.add(new String[] {"description", escapeForAttributeSelector(options.description, options.exact != null && options.exact)}); + if (options.pressed != null) + props.add(new String[] {"pressed", String.valueOf(options.pressed)}); + StringBuilder result = new StringBuilder("internal:role=" + role.name().toLowerCase()); + for (String[] prop : props) + result.append("[").append(prop[0]).append("=").append(prop[1]).append("]"); + return result.toString(); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java new file mode 100644 index 000000000..f87d62b8f --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java @@ -0,0 +1,489 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/mimeType.ts. +package com.microsoft.playwright.impl.isomorphic; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Pattern; + +// java: a match() of a regex anchored with ^ and $ is find(); a Java $ also matches before a final line terminator. +public final class MimeType { + private MimeType() { + } + + public static boolean isJsonMimeType(String mimeType) { + return Pattern.compile("^(application\\/json|application\\/.*?\\+json|text\\/(x-)?json)(;\\s*charset=.*)?$").matcher(mimeType).find(); + } + + public static boolean isXmlMimeType(String mimeType) { + return Pattern.compile("^(application\\/xml|application\\/.*?\\+xml|text\\/xml)(;\\s*charset=.*)?$").matcher(mimeType).find(); + } + + public static boolean isTextualMimeType(String mimeType) { + return Pattern.compile("^(text\\/.*?|application\\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\\/svg(\\+xml)?|application\\/.*?(\\+json|\\+xml))(;\\s*charset=.*)?$").matcher(mimeType).find(); + } + + public static String getMimeTypeForPath(String path) { + int dotIndex = path.lastIndexOf('.'); + if (dotIndex == -1) + return null; + String extension = path.substring(dotIndex + 1).toLowerCase(); + return types.get(extension); + } + + // java: a null contentType is undefined. + public static String getExtensionForMimeType(String contentType) { + String[] parts = (contentType != null ? contentType : "").split(";", -1)[0].split("/", -1); + String subtype = parts.length > 1 ? parts[1].trim().toLowerCase() : ""; + if (subtype.isEmpty()) + return "bin"; + // image/svg+xml → xml, application/ld+json → json + String tail; + if (subtype.contains("+")) { + String[] subtypeParts = subtype.split("\\+", -1); + tail = subtypeParts[subtypeParts.length - 1]; + } else { + tail = subtype; + } + if (tail.equals("plain")) + return "txt"; + if (tail.equals("javascript") || tail.equals("ecmascript")) + return "js"; + if (tail.equals("jpeg")) + return "jpg"; + String result = tail.replaceAll("[^a-z0-9]", ""); + return !result.isEmpty() ? result : "bin"; + } + + private static final Map types = new LinkedHashMap<>(); + static { + types.put("ez", "application/andrew-inset"); + types.put("aw", "application/applixware"); + types.put("atom", "application/atom+xml"); + types.put("atomcat", "application/atomcat+xml"); + types.put("atomdeleted", "application/atomdeleted+xml"); + types.put("atomsvc", "application/atomsvc+xml"); + types.put("dwd", "application/atsc-dwd+xml"); + types.put("held", "application/atsc-held+xml"); + types.put("rsat", "application/atsc-rsat+xml"); + types.put("bdoc", "application/bdoc"); + types.put("xcs", "application/calendar+xml"); + types.put("ccxml", "application/ccxml+xml"); + types.put("cdfx", "application/cdfx+xml"); + types.put("cdmia", "application/cdmi-capability"); + types.put("cdmic", "application/cdmi-container"); + types.put("cdmid", "application/cdmi-domain"); + types.put("cdmio", "application/cdmi-object"); + types.put("cdmiq", "application/cdmi-queue"); + types.put("cu", "application/cu-seeme"); + types.put("mpd", "application/dash+xml"); + types.put("davmount", "application/davmount+xml"); + types.put("dbk", "application/docbook+xml"); + types.put("dssc", "application/dssc+der"); + types.put("xdssc", "application/dssc+xml"); + types.put("ecma", "application/ecmascript"); + types.put("es", "application/ecmascript"); + types.put("emma", "application/emma+xml"); + types.put("emotionml", "application/emotionml+xml"); + types.put("epub", "application/epub+zip"); + types.put("exi", "application/exi"); + types.put("exp", "application/express"); + types.put("fdt", "application/fdt+xml"); + types.put("pfr", "application/font-tdpfr"); + types.put("geojson", "application/geo+json"); + types.put("gml", "application/gml+xml"); + types.put("gpx", "application/gpx+xml"); + types.put("gxf", "application/gxf"); + types.put("gz", "application/gzip"); + types.put("hjson", "application/hjson"); + types.put("stk", "application/hyperstudio"); + types.put("ink", "application/inkml+xml"); + types.put("inkml", "application/inkml+xml"); + types.put("ipfix", "application/ipfix"); + types.put("its", "application/its+xml"); + types.put("ear", "application/java-archive"); + types.put("jar", "application/java-archive"); + types.put("war", "application/java-archive"); + types.put("ser", "application/java-serialized-object"); + types.put("class", "application/java-vm"); + types.put("js", "application/javascript"); + types.put("mjs", "application/javascript"); + types.put("json", "application/json"); + types.put("map", "application/json"); + types.put("json5", "application/json5"); + types.put("jsonml", "application/jsonml+json"); + types.put("jsonld", "application/ld+json"); + types.put("lgr", "application/lgr+xml"); + types.put("lostxml", "application/lost+xml"); + types.put("hqx", "application/mac-binhex40"); + types.put("cpt", "application/mac-compactpro"); + types.put("mads", "application/mads+xml"); + types.put("webmanifest", "application/manifest+json"); + types.put("mrc", "application/marc"); + types.put("mrcx", "application/marcxml+xml"); + types.put("ma", "application/mathematica"); + types.put("mb", "application/mathematica"); + types.put("nb", "application/mathematica"); + types.put("mathml", "application/mathml+xml"); + types.put("mbox", "application/mbox"); + types.put("mscml", "application/mediaservercontrol+xml"); + types.put("metalink", "application/metalink+xml"); + types.put("meta4", "application/metalink4+xml"); + types.put("mets", "application/mets+xml"); + types.put("maei", "application/mmt-aei+xml"); + types.put("musd", "application/mmt-usd+xml"); + types.put("mods", "application/mods+xml"); + types.put("m21", "application/mp21"); + types.put("mp21", "application/mp21"); + types.put("m4p", "application/mp4"); + types.put("mp4s", "application/mp4"); + types.put("doc", "application/msword"); + types.put("dot", "application/msword"); + types.put("mxf", "application/mxf"); + types.put("nq", "application/n-quads"); + types.put("nt", "application/n-triples"); + types.put("cjs", "application/node"); + types.put("bin", "application/octet-stream"); + types.put("bpk", "application/octet-stream"); + types.put("buffer", "application/octet-stream"); + types.put("deb", "application/octet-stream"); + types.put("deploy", "application/octet-stream"); + types.put("dist", "application/octet-stream"); + types.put("distz", "application/octet-stream"); + types.put("dll", "application/octet-stream"); + types.put("dmg", "application/octet-stream"); + types.put("dms", "application/octet-stream"); + types.put("dump", "application/octet-stream"); + types.put("elc", "application/octet-stream"); + types.put("exe", "application/octet-stream"); + types.put("img", "application/octet-stream"); + types.put("iso", "application/octet-stream"); + types.put("lrf", "application/octet-stream"); + types.put("mar", "application/octet-stream"); + types.put("msi", "application/octet-stream"); + types.put("msm", "application/octet-stream"); + types.put("msp", "application/octet-stream"); + types.put("pkg", "application/octet-stream"); + types.put("so", "application/octet-stream"); + types.put("oda", "application/oda"); + types.put("opf", "application/oebps-package+xml"); + types.put("ogx", "application/ogg"); + types.put("omdoc", "application/omdoc+xml"); + types.put("onepkg", "application/onenote"); + types.put("onetmp", "application/onenote"); + types.put("onetoc", "application/onenote"); + types.put("onetoc2", "application/onenote"); + types.put("oxps", "application/oxps"); + types.put("relo", "application/p2p-overlay+xml"); + types.put("xer", "application/patch-ops-error+xml"); + types.put("pdf", "application/pdf"); + types.put("pgp", "application/pgp-encrypted"); + types.put("asc", "application/pgp-signature"); + types.put("sig", "application/pgp-signature"); + types.put("prf", "application/pics-rules"); + types.put("p10", "application/pkcs10"); + types.put("p7c", "application/pkcs7-mime"); + types.put("p7m", "application/pkcs7-mime"); + types.put("p7s", "application/pkcs7-signature"); + types.put("p8", "application/pkcs8"); + types.put("ac", "application/pkix-attr-cert"); + types.put("cer", "application/pkix-cert"); + types.put("crl", "application/pkix-crl"); + types.put("pkipath", "application/pkix-pkipath"); + types.put("pki", "application/pkixcmp"); + types.put("pls", "application/pls+xml"); + types.put("ai", "application/postscript"); + types.put("eps", "application/postscript"); + types.put("ps", "application/postscript"); + types.put("provx", "application/provenance+xml"); + types.put("pskcxml", "application/pskc+xml"); + types.put("raml", "application/raml+yaml"); + types.put("owl", "application/rdf+xml"); + types.put("rdf", "application/rdf+xml"); + types.put("rif", "application/reginfo+xml"); + types.put("rnc", "application/relax-ng-compact-syntax"); + types.put("rl", "application/resource-lists+xml"); + types.put("rld", "application/resource-lists-diff+xml"); + types.put("rs", "application/rls-services+xml"); + types.put("rapd", "application/route-apd+xml"); + types.put("sls", "application/route-s-tsid+xml"); + types.put("rusd", "application/route-usd+xml"); + types.put("gbr", "application/rpki-ghostbusters"); + types.put("mft", "application/rpki-manifest"); + types.put("roa", "application/rpki-roa"); + types.put("rsd", "application/rsd+xml"); + types.put("rss", "application/rss+xml"); + types.put("rtf", "application/rtf"); + types.put("sbml", "application/sbml+xml"); + types.put("scq", "application/scvp-cv-request"); + types.put("scs", "application/scvp-cv-response"); + types.put("spq", "application/scvp-vp-request"); + types.put("spp", "application/scvp-vp-response"); + types.put("sdp", "application/sdp"); + types.put("senmlx", "application/senml+xml"); + types.put("sensmlx", "application/sensml+xml"); + types.put("setpay", "application/set-payment-initiation"); + types.put("setreg", "application/set-registration-initiation"); + types.put("shf", "application/shf+xml"); + types.put("sieve", "application/sieve"); + types.put("siv", "application/sieve"); + types.put("smi", "application/smil+xml"); + types.put("smil", "application/smil+xml"); + types.put("rq", "application/sparql-query"); + types.put("srx", "application/sparql-results+xml"); + types.put("gram", "application/srgs"); + types.put("grxml", "application/srgs+xml"); + types.put("sru", "application/sru+xml"); + types.put("ssdl", "application/ssdl+xml"); + types.put("ssml", "application/ssml+xml"); + types.put("swidtag", "application/swid+xml"); + types.put("tei", "application/tei+xml"); + types.put("teicorpus", "application/tei+xml"); + types.put("tfi", "application/thraud+xml"); + types.put("tsd", "application/timestamped-data"); + types.put("toml", "application/toml"); + types.put("trig", "application/trig"); + types.put("ttml", "application/ttml+xml"); + types.put("ubj", "application/ubjson"); + types.put("rsheet", "application/urc-ressheet+xml"); + types.put("td", "application/urc-targetdesc+xml"); + types.put("vxml", "application/voicexml+xml"); + types.put("wasm", "application/wasm"); + types.put("wgt", "application/widget"); + types.put("hlp", "application/winhlp"); + types.put("wsdl", "application/wsdl+xml"); + types.put("wspolicy", "application/wspolicy+xml"); + types.put("xaml", "application/xaml+xml"); + types.put("xav", "application/xcap-att+xml"); + types.put("xca", "application/xcap-caps+xml"); + types.put("xdf", "application/xcap-diff+xml"); + types.put("xel", "application/xcap-el+xml"); + types.put("xns", "application/xcap-ns+xml"); + types.put("xenc", "application/xenc+xml"); + types.put("xht", "application/xhtml+xml"); + types.put("xhtml", "application/xhtml+xml"); + types.put("xlf", "application/xliff+xml"); + types.put("rng", "application/xml"); + types.put("xml", "application/xml"); + types.put("xsd", "application/xml"); + types.put("xsl", "application/xml"); + types.put("dtd", "application/xml-dtd"); + types.put("xop", "application/xop+xml"); + types.put("xpl", "application/xproc+xml"); + types.put("*xsl", "application/xslt+xml"); + types.put("xslt", "application/xslt+xml"); + types.put("xspf", "application/xspf+xml"); + types.put("mxml", "application/xv+xml"); + types.put("xhvml", "application/xv+xml"); + types.put("xvm", "application/xv+xml"); + types.put("xvml", "application/xv+xml"); + types.put("yang", "application/yang"); + types.put("yin", "application/yin+xml"); + types.put("zip", "application/zip"); + types.put("*3gpp", "audio/3gpp"); + types.put("adp", "audio/adpcm"); + types.put("amr", "audio/amr"); + types.put("au", "audio/basic"); + types.put("snd", "audio/basic"); + types.put("kar", "audio/midi"); + types.put("mid", "audio/midi"); + types.put("midi", "audio/midi"); + types.put("rmi", "audio/midi"); + types.put("mxmf", "audio/mobile-xmf"); + types.put("*mp3", "audio/mp3"); + types.put("m4a", "audio/mp4"); + types.put("mp4a", "audio/mp4"); + types.put("m2a", "audio/mpeg"); + types.put("m3a", "audio/mpeg"); + types.put("mp2", "audio/mpeg"); + types.put("mp2a", "audio/mpeg"); + types.put("mp3", "audio/mpeg"); + types.put("mpga", "audio/mpeg"); + types.put("oga", "audio/ogg"); + types.put("ogg", "audio/ogg"); + types.put("opus", "audio/ogg"); + types.put("spx", "audio/ogg"); + types.put("s3m", "audio/s3m"); + types.put("sil", "audio/silk"); + types.put("wav", "audio/wav"); + types.put("*wav", "audio/wave"); + types.put("weba", "audio/webm"); + types.put("xm", "audio/xm"); + types.put("ttc", "font/collection"); + types.put("otf", "font/otf"); + types.put("ttf", "font/ttf"); + types.put("woff", "font/woff"); + types.put("woff2", "font/woff2"); + types.put("exr", "image/aces"); + types.put("apng", "image/apng"); + types.put("avif", "image/avif"); + types.put("bmp", "image/bmp"); + types.put("cgm", "image/cgm"); + types.put("drle", "image/dicom-rle"); + types.put("emf", "image/emf"); + types.put("fits", "image/fits"); + types.put("g3", "image/g3fax"); + types.put("gif", "image/gif"); + types.put("heic", "image/heic"); + types.put("heics", "image/heic-sequence"); + types.put("heif", "image/heif"); + types.put("heifs", "image/heif-sequence"); + types.put("hej2", "image/hej2k"); + types.put("hsj2", "image/hsj2"); + types.put("ief", "image/ief"); + types.put("jls", "image/jls"); + types.put("jp2", "image/jp2"); + types.put("jpg2", "image/jp2"); + types.put("jpe", "image/jpeg"); + types.put("jpeg", "image/jpeg"); + types.put("jpg", "image/jpeg"); + types.put("jph", "image/jph"); + types.put("jhc", "image/jphc"); + types.put("jpm", "image/jpm"); + types.put("jpf", "image/jpx"); + types.put("jpx", "image/jpx"); + types.put("jxr", "image/jxr"); + types.put("jxra", "image/jxra"); + types.put("jxrs", "image/jxrs"); + types.put("jxs", "image/jxs"); + types.put("jxsc", "image/jxsc"); + types.put("jxsi", "image/jxsi"); + types.put("jxss", "image/jxss"); + types.put("ktx", "image/ktx"); + types.put("ktx2", "image/ktx2"); + types.put("png", "image/png"); + types.put("sgi", "image/sgi"); + types.put("svg", "image/svg+xml"); + types.put("svgz", "image/svg+xml"); + types.put("t38", "image/t38"); + types.put("tif", "image/tiff"); + types.put("tiff", "image/tiff"); + types.put("tfx", "image/tiff-fx"); + types.put("webp", "image/webp"); + types.put("wmf", "image/wmf"); + types.put("disposition-notification", "message/disposition-notification"); + types.put("u8msg", "message/global"); + types.put("u8dsn", "message/global-delivery-status"); + types.put("u8mdn", "message/global-disposition-notification"); + types.put("u8hdr", "message/global-headers"); + types.put("eml", "message/rfc822"); + types.put("mime", "message/rfc822"); + types.put("3mf", "model/3mf"); + types.put("gltf", "model/gltf+json"); + types.put("glb", "model/gltf-binary"); + types.put("iges", "model/iges"); + types.put("igs", "model/iges"); + types.put("mesh", "model/mesh"); + types.put("msh", "model/mesh"); + types.put("silo", "model/mesh"); + types.put("mtl", "model/mtl"); + types.put("obj", "model/obj"); + types.put("stpx", "model/step+xml"); + types.put("stpz", "model/step+zip"); + types.put("stpxz", "model/step-xml+zip"); + types.put("stl", "model/stl"); + types.put("vrml", "model/vrml"); + types.put("wrl", "model/vrml"); + types.put("*x3db", "model/x3d+binary"); + types.put("x3dbz", "model/x3d+binary"); + types.put("x3db", "model/x3d+fastinfoset"); + types.put("*x3dv", "model/x3d+vrml"); + types.put("x3dvz", "model/x3d+vrml"); + types.put("x3d", "model/x3d+xml"); + types.put("x3dz", "model/x3d+xml"); + types.put("x3dv", "model/x3d-vrml"); + types.put("appcache", "text/cache-manifest"); + types.put("manifest", "text/cache-manifest"); + types.put("ics", "text/calendar"); + types.put("ifb", "text/calendar"); + types.put("coffee", "text/coffeescript"); + types.put("litcoffee", "text/coffeescript"); + types.put("css", "text/css"); + types.put("csv", "text/csv"); + types.put("htm", "text/html"); + types.put("html", "text/html"); + types.put("shtml", "text/html"); + types.put("jade", "text/jade"); + types.put("jsx", "text/jsx"); + types.put("less", "text/less"); + types.put("markdown", "text/markdown"); + types.put("md", "text/markdown"); + types.put("mml", "text/mathml"); + types.put("mdx", "text/mdx"); + types.put("n3", "text/n3"); + types.put("conf", "text/plain"); + types.put("def", "text/plain"); + types.put("in", "text/plain"); + types.put("ini", "text/plain"); + types.put("list", "text/plain"); + types.put("log", "text/plain"); + types.put("text", "text/plain"); + types.put("txt", "text/plain"); + types.put("rtx", "text/richtext"); + types.put("*rtf", "text/rtf"); + types.put("sgm", "text/sgml"); + types.put("sgml", "text/sgml"); + types.put("shex", "text/shex"); + types.put("slim", "text/slim"); + types.put("slm", "text/slim"); + types.put("spdx", "text/spdx"); + types.put("styl", "text/stylus"); + types.put("stylus", "text/stylus"); + types.put("tsv", "text/tab-separated-values"); + types.put("man", "text/troff"); + types.put("me", "text/troff"); + types.put("ms", "text/troff"); + types.put("roff", "text/troff"); + types.put("t", "text/troff"); + types.put("tr", "text/troff"); + types.put("ttl", "text/turtle"); + types.put("uri", "text/uri-list"); + types.put("uris", "text/uri-list"); + types.put("urls", "text/uri-list"); + types.put("vcard", "text/vcard"); + types.put("vtt", "text/vtt"); + types.put("*xml", "text/xml"); + types.put("yaml", "text/yaml"); + types.put("yml", "text/yaml"); + types.put("3gp", "video/3gpp"); + types.put("3gpp", "video/3gpp"); + types.put("3g2", "video/3gpp2"); + types.put("h261", "video/h261"); + types.put("h263", "video/h263"); + types.put("h264", "video/h264"); + types.put("m4s", "video/iso.segment"); + types.put("jpgv", "video/jpeg"); + types.put("jpm", "video/jpm"); + types.put("jpgm", "video/jpm"); + types.put("mj2", "video/mj2"); + types.put("mjp2", "video/mj2"); + types.put("ts", "application/typescript"); + types.put("mp4", "video/mp4"); + types.put("mp4v", "video/mp4"); + types.put("mpg4", "video/mp4"); + types.put("m1v", "video/mpeg"); + types.put("m2v", "video/mpeg"); + types.put("mpe", "video/mpeg"); + types.put("mpeg", "video/mpeg"); + types.put("mpg", "video/mpeg"); + types.put("ogv", "video/ogg"); + types.put("mov", "video/quicktime"); + types.put("qt", "video/quicktime"); + types.put("webm", "video/webm"); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java new file mode 100644 index 000000000..cde6ffca1 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java @@ -0,0 +1,346 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/stringUtils.ts. +package com.microsoft.playwright.impl.isomorphic; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.microsoft.playwright.PlaywrightException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +// java: a string | RegExp parameter is an Object holding a String or a Pattern. +public final class StringUtils { + private StringUtils() { + } + + public static String escapeWithQuotes(String text) { + return escapeWithQuotes(text, "'"); + } + + // NOTE: this function should not be used to escape any selectors. + public static String escapeWithQuotes(String text, String ch) { + String stringified = jsonStringify(text); + String escapedText = stringified.substring(1, stringified.length() - 1).replace("\\\"", "\""); + if (ch.equals("'")) + return ch + escapedText.replace("'", "\\'") + ch; + if (ch.equals("\"")) + return ch + escapedText.replace("\"", "\\\"") + ch; + if (ch.equals("`")) + return ch + escapedText.replace("`", "\\`") + ch; + throw new PlaywrightException("Invalid escape char"); + } + + public static String escapeTemplateString(String text) { + return text + .replace("\\", "\\\\") + .replace("`", "\\`") + .replace("${", "\\${"); + } + + // java: a String object is a Java String. + public static boolean isString(Object obj) { + return obj instanceof String; + } + + public static String toTitleCase(String name) { + return name.isEmpty() ? "" : Character.toUpperCase(name.charAt(0)) + name.substring(1); + } + + public static String toSnakeCase(String name) { + // E.g. ignoreHTTPSErrors => ignore_https_errors. + return name.replaceAll("([a-z0-9])([A-Z])", "$1_$2").replaceAll("([A-Z])([A-Z][a-z])", "$1_$2").toLowerCase(); + } + + public static String formatObject(Object value) { + return formatObject(value, " ", "multiline"); + } + + public static String formatObject(Object value, String indent) { + return formatObject(value, indent, "multiline"); + } + + // java: an array is a List or an Object[], an object is a Map with its keys converted to strings; a null value of + // a Map is undefined. String(value) of a number is String.valueOf(), which prints a Double with a fraction. + public static String formatObject(Object value, String indent, String mode) { + if (value == null) + return "null"; + if (value instanceof String) + return escapeWithQuotes((String) value, "'"); + if (value instanceof List || value instanceof Object[]) { + List array = value instanceof List ? (List) value : Arrays.asList((Object[]) value); + List items = new ArrayList<>(); + for (Object o : array) + items.add(formatObject(o)); + return "[" + String.join(", ", items) + "]"; + } + if (value instanceof Map) { + Map object = new LinkedHashMap<>(); + for (Map.Entry entry : ((Map) value).entrySet()) + object.put(String.valueOf(entry.getKey()), entry.getValue()); + List keys = new ArrayList<>(); + for (String key : object.keySet()) { + if (!key.equals("timeout") && object.get(key) != null) + keys.add(key); + } + Collections.sort(keys); + if (keys.isEmpty()) + return "{}"; + List tokens = new ArrayList<>(); + for (String key : keys) + tokens.add(key + ": " + formatObject(object.get(key))); + if (mode.equals("multiline")) { + List lines = new ArrayList<>(); + for (String t : tokens) + lines.add(indent + t); + return "{\n" + String.join(",\n", lines) + "\n}"; + } + return "{ " + String.join(", ", tokens) + " }"; + } + return String.valueOf(value); + } + + public static String formatObjectOrVoid(Object value) { + return formatObjectOrVoid(value, " "); + } + + public static String formatObjectOrVoid(Object value, String indent) { + String result = formatObject(value, indent); + return result.equals("{}") ? "" : result; + } + + public static String quoteCSSAttributeValue(String text) { + return "\"" + text.replaceAll("([\"\\\\])", "\\\\$1") + "\""; + } + + private static Map normalizedWhitespaceCache; + + public static void cacheNormalizedWhitespaces() { + normalizedWhitespaceCache = new HashMap<>(); + } + + // java: JS_WHITESPACE is the \s of a JS RegExp, which trim() also removes. + public static String normalizeWhiteSpace(String text) { + String result = normalizedWhitespaceCache != null ? normalizedWhitespaceCache.get(text) : null; + if (result == null) { + result = text.replaceAll("[​­]", "").replaceAll("^" + JS_WHITESPACE + "+|" + JS_WHITESPACE + "+$", "").replaceAll(JS_WHITESPACE + "+", " "); + if (normalizedWhitespaceCache != null) + normalizedWhitespaceCache.put(text, result); + } + return result; + } + + public static String normalizeEscapedRegexQuotes(String source) { + // This function reverses the effect of escapeRegexForSelector below. + // Odd number of backslashes followed by the quote -> remove unneeded backslash. + return source.replaceAll("(^|[^\\\\])(\\\\\\\\)*\\\\(['\"`])", "$1$2$3"); + } + + // java: toJsRegexFlags() never produces the 'u' or 'v' flag, so there is no unicode early return. + private static String escapeRegexForSelector(Pattern re) { + // Unicode mode does not allow "identity character escapes", so we do not escape and + // hope that it does not contain quotes and/or >> signs. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape + // TODO: rework RE usages in internal selectors away from literal representation to json, e.g. {source,flags}. + // Even number of backslashes followed by the quote -> insert a backslash. + return toJsRegExp(re).replaceAll("(^|[^\\\\])(\\\\\\\\)*([\"'`])", "$1$2\\\\$3").replaceAll(">>", "\\\\>\\\\>"); + } + + public static String escapeForTextSelector(Object text, boolean exact) { + if (!(text instanceof String)) + return escapeRegexForSelector((Pattern) text); + return jsonStringify((String) text) + (exact ? "s" : "i"); + } + + public static String escapeForAttributeSelector(Object value, boolean exact) { + if (!(value instanceof String)) + return escapeRegexForSelector((Pattern) value); + // TODO: this should actually be + // cssEscape(value).replace(/\\ /g, ' ') + // However, our attribute selectors do not conform to CSS parsing spec, + // so we escape them differently. + return "\"" + ((String) value).replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + (exact ? "s" : "i"); + } + + public static String trimString(String input, int cap) { + return trimString(input, cap, ""); + } + + // java: [...input] splits into code points. + public static String trimString(String input, int cap, String suffix) { + if (input.length() <= cap) + return input; + int[] chars = input.codePoints().toArray(); + if (chars.length > cap) + return new String(chars, 0, cap - suffix.length()) + suffix; + return new String(chars, 0, chars.length); + } + + public static String trimStringWithEllipsis(String input, int cap) { + return trimString(input, cap, "…"); + } + + public static String truncateDataUrl(String url) { + // Data URLs can carry megabytes of base64 payload, which is never useful in + // human/AI-facing output. Keep the media type prefix for context, drop the data. + if (!url.startsWith("data:")) + return url; + int comma = url.indexOf(','); + if (comma == -1) + return url; + return url.substring(0, comma + 1) + "…"; + } + + public static String escapeRegExp(String s) { + // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping + // java: $0 is $&. + return s.replaceAll("[.*+?^${}()|\\[\\]\\\\]", "\\\\$0"); // $& means the whole matched string + } + + private static final Map escaped = new LinkedHashMap<>(); + static { + escaped.put("&", "&"); + escaped.put("<", "<"); + escaped.put(">", ">"); + escaped.put("\"", """); + escaped.put("'", "'"); + } + + public static String escapeHTMLAttribute(String s) { + return replaceEach(s, Pattern.compile("[&<>\"']")); + } + + public static String escapeHTML(String s) { + return replaceEach(s, Pattern.compile("[&<]")); + } + + public static String longestCommonSubstring(String s1, String s2) { + int n = s1.length(); + int m = s2.length(); + int maxLen = 0; + int endingIndex = 0; + + // Initialize a 2D array with zeros + int[][] dp = new int[n + 1][m + 1]; + + // Build the dp table + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (s1.charAt(i - 1) == s2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + + if (dp[i][j] > maxLen) { + maxLen = dp[i][j]; + endingIndex = i; + } + } + } + } + + // Extract the longest common substring + return s1.substring(endingIndex - maxLen, endingIndex); + } + + // java: the 'i', 's' and 'm' flags become Pattern flags, the others are dropped. + public static Pattern parseRegex(String regex) { + if (regex.isEmpty() || regex.charAt(0) != '/') + throw new PlaywrightException("Invalid regex, must start with '/': " + regex); + int lastSlash = regex.lastIndexOf('/'); + if (lastSlash <= 0) + throw new PlaywrightException("Invalid regex, must end with '/' followed by optional flags: " + regex); + String source = regex.substring(1, lastSlash); + String flags = regex.substring(lastSlash + 1); + return Pattern.compile(source, fromJsRegexFlags(flags)); + } + + public static String tomlBasicString(String value) { + // JSON.stringify produces a valid TOML basic string: escapes \", \\, \n, \r, \t and uses \\uXXXX for control chars. + return jsonStringify(value); + } + + public static String tomlArray(List values) { + List items = new ArrayList<>(); + for (String value : values) + items.add(tomlBasicString(value)); + return "[" + String.join(", ", items) + "]"; + } + + public static String tomlMultilineBasicString(String value) { + // Triple-quoted basic string: escape backslashes first, then any literal """ sequences. + String escaped = value.replace("\\", "\\\\").replace("\"\"\"", "\\\"\\\"\\\""); + return "\"\"\"\n" + escaped + "\n\"\"\""; + } + + // Semicolons removed from [[\]()#;?] to avoid polynomial backtracking + // when both that group and (?:;...)* can match runs of semicolons. + // \d{1,4} relaxed to \d{0,4} so empty params (e.g. ESC[;H) still match. + // java: the '[' in the first character class is escaped, a Java character class nests an unescaped one. + public static final Pattern ansiRegex = Pattern.compile("([\\u001B\\u009B][\\[\\]()#?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)|(?:(?:\\d{0,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~])))"); + + public static String stripAnsiEscapes(String str) { + return ansiRegex.matcher(str).replaceAll(""); + } + + // java: helpers with no counterpart upstream. + + private static final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); + + // java: JSON.stringify of a string; unlike it, Gson escapes U+2028 and U+2029. + public static String jsonStringify(String value) { + return gson.toJson(value); + } + + // java: String(re) of a JS RegExp. + private static String toJsRegExp(Pattern pattern) { + return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); + } + + // java: the \s character class of a JS RegExp. + private static final String JS_WHITESPACE = "[\\t\\n\\u000B\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]"; + + // java: String.prototype.replace with a global RegExp and a function that looks the match up in escaped. + private static String replaceEach(String s, Pattern pattern) { + Matcher matcher = pattern.matcher(s); + StringBuffer result = new StringBuffer(); + while (matcher.find()) + matcher.appendReplacement(result, Matcher.quoteReplacement(escaped.get(matcher.group()))); + matcher.appendTail(result); + return result.toString(); + } + + // java: Utils.fromJsRegexFlags is not visible from this package. + private static int fromJsRegexFlags(String regexFlags) { + int flags = 0; + if (regexFlags.contains("i")) + flags |= Pattern.CASE_INSENSITIVE; + if (regexFlags.contains("s")) + flags |= Pattern.DOTALL; + if (regexFlags.contains("m")) + flags |= Pattern.MULTILINE; + return flags; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java new file mode 100644 index 000000000..40461559d --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of isomorphic/time.ts. +package com.microsoft.playwright.impl.isomorphic; + +// Hopefully, this file is never used in injected sources, +// because it does not use `builtins.performance`, +// and can break when clock emulation is engaged. + +// java: the time of class loading stands for performance.timeOrigin, System.nanoTime() since then for +// performance.now(). +public final class Time { + private Time() { + } + + private static final long performanceStartNanos = System.nanoTime(); + private static final double performanceTimeOrigin = System.currentTimeMillis(); + + private static double timeOrigin = performanceTimeOrigin; + private static double timeShift = 0; + + public static void setTimeOrigin(double origin) { + timeOrigin = origin; + timeShift = performanceTimeOrigin - origin; + } + + public static double timeOrigin() { + return timeOrigin; + } + + public static double monotonicTime() { + return Math.floor((performanceNow() + timeShift) * 1000) / 1000; + } + + public static final int DEFAULT_PLAYWRIGHT_TIMEOUT = 30_000; + public static final int DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1000; // 3 minutes + + // java: helpers with no counterpart upstream. + + // java: performance.now(), in milliseconds. + private static double performanceNow() { + return (System.nanoTime() - performanceStartNanos) / 1_000_000.0; + } +} diff --git a/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java b/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java index 016d0470e..0ffb550ad 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestGlobalFetch.java @@ -567,7 +567,7 @@ void shouldThrowAnErrorWhenMaxRedirectsIsLessThan0(Playwright playwright, Server PlaywrightException exception = assertThrows(PlaywrightException.class, () -> request.fetch(server.PREFIX + "/a/redirect1", RequestOptions.create().setMethod(method).setMaxRedirects(-1))); - assertTrue(exception.getMessage().contains("'maxRedirects' should be greater than or equal to '0'"), exception.getMessage()); + assertTrue(exception.getMessage().contains("'maxRedirects' must be greater than or equal to '0'"), exception.getMessage()); } request.dispose(); } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestPageSetExtraHttpHeaders.java b/playwright/src/test/java/com/microsoft/playwright/TestPageSetExtraHttpHeaders.java index 36d753741..ac22af42f 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestPageSetExtraHttpHeaders.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestPageSetExtraHttpHeaders.java @@ -73,6 +73,6 @@ void shouldThrowForNonStringHeaderValues(Browser browser) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> { browser.newContext(new Browser.NewContextOptions().setExtraHTTPHeaders(mapOf("foo", null))); }); - assertTrue(e.getMessage().contains("Value cannot be null")); + assertTrue(e.getMessage().contains("Expected value of header \"foo\" to be String, but \"object\" is found.")); } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextSetExtraHttpHeaders.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextSetExtraHttpHeaders.java index d3c4b4ff2..930584b7e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextSetExtraHttpHeaders.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsercontextSetExtraHttpHeaders.java @@ -57,7 +57,6 @@ void shouldOverrideExtraHeadersFromBrowserContext(Browser browser, TestServer se @PlaywrightTest @DisplayName("NE-120 should throw for non-string header values") - @Fixme("java: newContext() with a null header value fails with 'Value cannot be null', the Node.js client checks 'Expected value of header \"foo\" to be String, but \"object\" is found.'") void shouldThrowForNonStringHeaderValues(Browser browser) { Map extraHTTPHeaders = new HashMap<>(); extraHTTPHeaders.put("foo", null); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestGlobalFetch.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestGlobalFetch.java index b2dbb62a7..82d195922 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestGlobalFetch.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestGlobalFetch.java @@ -747,7 +747,6 @@ void shouldNotFollowRedirectsWhenMaxRedirectsIsSetTo0(Playwright playwright, Tes @PlaywrightTest @DisplayName("FE-041 should throw an error when maxRedirects is less than 0") - @Fixme("java: the Java client validates maxRedirects itself and says \"'maxRedirects' should be greater than or equal to '0'\" instead of 'must be'") void shouldThrowAnErrorWhenMaxRedirectsIsLessThan0(Playwright playwright, TestServer server) { server.setRedirect("/a/redirect1", "/b/c/redirect2"); server.setRedirect("/b/c/redirect2", "/simple.json"); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorQuery.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorQuery.java index 83baae87d..de4b730ea 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorQuery.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestLocatorQuery.java @@ -318,7 +318,6 @@ void shouldKeepTheCaptureWhenRemovingACommonFramePrefix(Page page) { @PlaywrightTest @DisplayName("LO-180 should enforce same frame for has/leftOf/rightOf/above/below/near") - @Fixme("java: the message is \"Inner 'has' locator must belong to the same frame.\", with single quotes") void shouldEnforceSameFrameForHasLeftOfRightOfAboveBelowNear(Page page, TestServer server) { page.navigate(server.PREFIX + "/frames/two-frames.html"); Frame child = page.frames().get(1); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java index e7ad35ba5..b89b1262e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageSetInputFiles.java @@ -179,7 +179,6 @@ void shouldUploadAFileAfterPopup(Page page, TestServer server) { @PlaywrightTest @DisplayName("IF-010 should throw an error if the file does not exist") - @Fixme("java: the message is 'Cannot get absolute file path', it has no 'ENOENT: no such file or directory' and no file name") void shouldThrowAnErrorIfTheFileDoesNotExist(Page page, TestServer server) { page.navigate(server.PREFIX + "/input/fileupload.html"); ElementHandle input = page.querySelector("input");