From e697c42454980af4db54c8c204abc53a01eb2d12 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:13 -0800 Subject: [PATCH 01/30] refactor(artifact): follow artifact.ts --- .../playwright/impl/ArtifactImpl.java | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) 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..a8377b152 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.*; @@ -35,10 +36,36 @@ public ArtifactImpl(ChannelOwner parent, String type, String guid, JsonObject in super(parent, type, guid, initializer); } + public Path pathAfterFinished() { + if (connection.isRemote()) { + // java: the message names the Java API. + 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(); } + // java: upstream readIntoBuffer collects the 'data' chunks of the stream. byte[] readAllBytes() { final int bufLen = 1024 * 1024; byte[] buf = new byte[bufLen]; @@ -60,27 +87,4 @@ public void cancel() { 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); - } } From c855dce5d48bb0bd4699c3e1a29d45ed0477f3f7 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:13 -0800 Subject: [PATCH 02/30] refactor(stream): follow stream.ts --- .../src/main/java/com/microsoft/playwright/impl/Stream.java | 1 + 1 file changed, 1 insertion(+) 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..ed1fdc5c1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of stream.ts. java: the Readable is an InputStream; _read becomes read(), _destroy becomes close(). package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; From bc4983cd91188292a8098434a384167bbc1385e7 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:13 -0800 Subject: [PATCH 03/30] refactor(writable-stream): follow writableStream.ts --- .../main/java/com/microsoft/playwright/impl/WritableStream.java | 1 + 1 file changed, 1 insertion(+) 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..348d0e2ba 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. java: the Writable is an OutputStream; _write becomes write(), _final becomes close(). package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; From 99daa149a98aae674480d163feeb4b9f450ce404 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:13 -0800 Subject: [PATCH 04/30] refactor(download): follow download.ts --- .../playwright/impl/DownloadImpl.java | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) 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..a4bd13003 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. java: url and suggestedFilename are read from the initializer. package com.microsoft.playwright.impl; import com.google.gson.JsonObject; @@ -34,6 +35,11 @@ class DownloadImpl implements Download { this.initializer = initializer; } + @Override + public Page page() { + return page; + } + @Override public String url() { return initializer.get("url").getAsString(); @@ -45,18 +51,13 @@ public String suggestedFilename() { } @Override - public void cancel() { - artifact.cancel(); - } - - @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 +66,17 @@ 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(); } } From da1f66574387569b4eb1a9f73be11954a61c35a2 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:13 -0800 Subject: [PATCH 05/30] refactor(video): follow video.ts --- .../com/microsoft/playwright/impl/VideoImpl.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) 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..f4b768bca 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. java: the video is created before its artifact is known, so the artifact is assigned later. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; @@ -35,15 +36,10 @@ class VideoImpl implements Video { this.artifact = artifact; } - @Override - public void delete() { - if (artifact != null) - artifact.delete(); - } - @Override public Path path() { if (page.connection.isRemote()) { + // java: the message names the Java API. throw new PlaywrightException("Path is not available when connecting remotely. Use saveAs() to save a local copy."); } if (artifact == null) @@ -57,4 +53,10 @@ 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(); + } } From 307a24f3aa933b2a23a842ec9ff87155a1d4b838 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:14 -0800 Subject: [PATCH 06/30] refactor(screencast): follow screencast.ts --- .../playwright/impl/ScreencastFrameImpl.java | 1 + .../playwright/impl/ScreencastImpl.java | 25 ++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) 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..69cf86d5d 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. java: onFrame receives a ScreencastFrame and the frame event arrives through handleScreencastFrame. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -99,6 +100,18 @@ public void stop() { savePath = null; } + @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 hideActions() { + page.channel.screencastHideActions(NO_TIMEOUT); + } + @Override public AutoCloseable showOverlay(String html, ShowOverlayOptions options) { PageScreencastShowOverlayParams params = toProtocol(options, PageScreencastShowOverlayParams.class); @@ -119,13 +132,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 +139,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(); From eb87193f0898acfa7c320ec898090d2059b90afb Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:24:24 -0800 Subject: [PATCH 07/30] refactor(consoleMessage): follow consoleMessage.ts --- .../playwright/impl/ConsoleMessageImpl.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) 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..43b5bbc1a 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.*; @@ -59,19 +60,21 @@ private ConsoleMessageImpl(PageImpl page, WorkerImpl worker, String type, String } @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 +86,12 @@ 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; } } From 51118c6a4e7bd8b654d9a5030e3f276d0cdb1cc6 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:24:24 -0800 Subject: [PATCH 08/30] refactor(dialog): follow dialog.ts --- .../microsoft/playwright/impl/DialogImpl.java | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) 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..55261e3b5 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java @@ -14,12 +14,12 @@ * 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); @@ -35,38 +35,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; + } } } From 950381a224423840d87945f1ef5bd03c7dd320f7 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:24:24 -0800 Subject: [PATCH 09/30] refactor(fileChooser): follow fileChooser.ts --- .../java/com/microsoft/playwright/impl/FileChooserImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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..2d3e353ad 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; @@ -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); From 5d8d70afa0516036b8c2285d22049a6ca58297f0 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:24:24 -0800 Subject: [PATCH 10/30] refactor(webError): follow webError.ts --- .../main/java/com/microsoft/playwright/impl/WebErrorImpl.java | 2 ++ 1 file changed, 2 insertions(+) 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; From 95787e343a9acce0ecd4599e48e2164117f70f7f Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 11/30] refactor(worker): follow worker.ts --- .../microsoft/playwright/impl/WorkerImpl.java | 100 +++++++++--------- 1 file changed, 52 insertions(+), 48 deletions(-) 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..0cfb26a70 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java @@ -33,8 +33,10 @@ import static com.microsoft.playwright.impl.Serialization.*; +// Port of worker.ts. public class WorkerImpl extends ChannelOwner implements Worker { PageImpl page; + // java: no service worker or connectToWorker API, so there is no _context, _closeReason or _disconnect. final WorkerChannel channel = new WorkerChannel(this); @@ -45,50 +47,46 @@ public class WorkerImpl extends ChannelOwner implements Worker { setEventToSubscriptionMapping(mapping); } + // 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) { + if ("close".equals(event)) { + if (page != null) { + page.workers.remove(this); + } + emit(Events.Worker.CLOSE, this); + } } - @Override - public void onConsole(Consumer handler) { - on(Events.Worker.CONSOLE, handler); + TargetClosedError closeErrorWithReason() { + 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(); } @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. private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); double timeoutMs = timeoutSettings.timeout(timeout); @@ -102,34 +100,40 @@ private T waitForEvent(String event, Predicate predicate, Double timeout, return result; } + // 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); } } From 84ce8e0db713aa77eb08c5545708278b56a4fb1b Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 12/30] refactor(cdpSession): follow cdpSession.ts --- .../playwright/impl/CDPSessionImpl.java | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) 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..028020441 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -23,6 +23,7 @@ import java.util.function.Consumer; +// Port of cdpSession.ts. public class CDPSessionImpl extends ChannelOwner implements CDPSession { final CDPSessionChannel channel = new CDPSessionChannel(this); @@ -31,6 +32,7 @@ protected CDPSessionImpl(ChannelOwner parent, String type, String guid, JsonObje 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,18 +49,18 @@ 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); } @Override @@ -68,25 +70,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); } } From 1b0b325eabad714bca09435b1c325aff4894ddf4 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 13/30] refactor(debugger): follow debugger.ts --- .../playwright/impl/DebuggerImpl.java | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) 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..511965b4d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java @@ -28,9 +28,11 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.toProtocol; +// Port of debugger.ts. public class DebuggerImpl extends ChannelOwner implements Debugger { - private final List pausedStateChangedHandlers = new ArrayList<>(); private DebuggerPausedDetails pausedDetails; + // java: handlers of onPausedStateChanged(Runnable); upstream emits Events.Debugger.PausedStateChanged. apiCallsUpdated has no Java API. + private final List pausedStateChangedHandlers = new ArrayList<>(); final DebuggerChannel channel = new DebuggerChannel(this); @@ -38,6 +40,7 @@ public class DebuggerImpl extends ChannelOwner implements Debugger { 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)) { @@ -52,20 +55,7 @@ protected void handleEvent(String event, JsonObject params) { } } - @Override - public void onPausedStateChanged(Runnable handler) { - pausedStateChangedHandlers.add(handler); - } - - @Override - public void offPausedStateChanged(Runnable handler) { - pausedStateChangedHandlers.remove(handler); - } - - @Override - public DebuggerPausedDetails pausedDetails() { - return pausedDetails; - } + // java: _enable has no Java API. @Override public void requestPause() { @@ -88,4 +78,19 @@ public void runTo(Location location) { params.location = toProtocol(location, DebuggerRunToParams.DebuggerRunToParamsLocation.class); channel.runTo(params, NO_TIMEOUT); } + + @Override + public DebuggerPausedDetails pausedDetails() { + return pausedDetails; + } + + @Override + public void onPausedStateChanged(Runnable handler) { + pausedStateChangedHandlers.add(handler); + } + + @Override + public void offPausedStateChanged(Runnable handler) { + pausedStateChangedHandlers.remove(handler); + } } From 3b7e270350981c81b34b6bb78822d890ff6a7690 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 14/30] refactor(clock): follow clock.ts --- .../microsoft/playwright/impl/ClockImpl.java | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) 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..2962f8c54 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java @@ -7,6 +7,7 @@ import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +// Port of clock.ts. class ClockImpl implements Clock { private final BrowserContextImpl browserContext; @@ -14,19 +15,7 @@ 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); - } + // java: parseTime/parseTicks are inlined into the typed overloads (long, String, Date) of the generated Clock interface. @Override public void install(InstallOptions options) { @@ -45,17 +34,17 @@ public void install(InstallOptions options) { } @Override - public void runFor(long ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); + public void fastForward(long ticks) { + BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); params.ticksNumber = (double) ticks; - browserContext.channel.clockRunFor(params, NO_TIMEOUT); + browserContext.channel.clockFastForward(params, NO_TIMEOUT); } @Override - public void runFor(String ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); + public void fastForward(String ticks) { + BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); params.ticksString = ticks; - browserContext.channel.clockRunFor(params, NO_TIMEOUT); + browserContext.channel.clockFastForward(params, NO_TIMEOUT); } @Override @@ -84,6 +73,20 @@ public void resume() { browserContext.channel.clockResume(NO_TIMEOUT); } + @Override + public void runFor(long ticks) { + BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); + params.ticksNumber = (double) ticks; + browserContext.channel.clockRunFor(params, NO_TIMEOUT); + } + + @Override + public void runFor(String ticks) { + BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); + params.ticksString = ticks; + browserContext.channel.clockRunFor(params, NO_TIMEOUT); + } + @Override public void setFixedTime(long time) { BrowserContextClockSetFixedTimeParams params = new BrowserContextClockSetFixedTimeParams(); From d530c68a3858c596962c40d23c28f5829dbab94c Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 15/30] refactor(webStorage): follow webStorage.ts --- .../main/java/com/microsoft/playwright/impl/WebStorageImpl.java | 1 + 1 file changed, 1 insertion(+) 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..e033b3040 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebStorageImpl.java @@ -26,6 +26,7 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static java.util.Arrays.asList; +// Port of webStorage.ts. class WebStorageImpl implements WebStorage { private final PageImpl page; private final String kind; From 4136d39032922f13b9c73cbf2a557193a1d3a29d Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 16/30] refactor(credentials): follow credentials.ts --- .../playwright/impl/CredentialsImpl.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) 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..7e9801e11 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CredentialsImpl.java @@ -27,37 +27,38 @@ import static com.microsoft.playwright.impl.Utils.toProtocol; import static java.util.Arrays.asList; +// Port of credentials.ts. 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); + } } From da05f2d5e7986c3b6b7d2283f3ae81154f1769e4 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:25:04 -0800 Subject: [PATCH 17/30] refactor(webmcp): follow webmcp.ts --- .../src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java | 1 + 1 file changed, 1 insertion(+) 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..fedeadea2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebMCPImpl.java @@ -27,6 +27,7 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; +// Port of webmcp.ts. class WebMCPImpl implements WebMCP { private final FrameImpl frame; From 5aca50f91c49faf1c9d2b782b5bbab16154cdcb8 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:24:24 -0800 Subject: [PATCH 18/30] refactor(input): follow input.ts --- .../playwright/impl/KeyboardImpl.java | 29 ++++------- .../microsoft/playwright/impl/MouseImpl.java | 50 +++++++++---------- .../playwright/impl/TouchscreenImpl.java | 1 + 3 files changed, 37 insertions(+), 43 deletions(-) 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/MouseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java index f0f06d1b9..35955dfa6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of input.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -31,27 +32,11 @@ class MouseImpl implements Mouse { } @Override - public void click(double x, double y, ClickOptions options) { - PageMouseClickParams params = toProtocol(options, PageMouseClickParams.class); + public void move(double x, double y, MoveOptions options) { + PageMouseMoveParams params = toProtocol(options, PageMouseMoveParams.class); params.x = x; params.y = y; - page.channel.mouseClick(params, NO_TIMEOUT); - } - - @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); + page.channel.mouseMove(params, NO_TIMEOUT); } @Override @@ -61,17 +46,32 @@ 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) { + page.withTitle("Double click", () -> { + 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); + }); } @Override 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.*; From 70cbd2c0e073399be051df5e0cff0316effcd764 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:26:16 -0800 Subject: [PATCH 19/30] refactor(localUtils): follow localUtils.ts --- .../com/microsoft/playwright/impl/LocalUtils.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) 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..7c318e264 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java @@ -26,6 +26,7 @@ import static com.microsoft.playwright.impl.Serialization.gson; +// Port of localUtils.ts. public class LocalUtils extends ChannelOwner { final LocalUtilsChannel channel = new LocalUtilsChannel(this); @@ -33,6 +34,7 @@ public class LocalUtils extends ChannelOwner { super(parent, type, guid, initializer); } + // java: devices stay the raw initializer array, DeviceDescriptor is not a Java type. JsonArray deviceDescriptors() { return initializer.getAsJsonArray("deviceDescriptors"); } @@ -50,12 +52,6 @@ void zip(Path zipFile, List entries, String stacksId, boolean appendM channel.zip(params, NO_TIMEOUT); } - void traceDiscarded(String stacksId) { - LocalUtilsTraceDiscardedParams params = new LocalUtilsTraceDiscardedParams(); - params.stacksId = stacksId; - channel.traceDiscarded(params, NO_TIMEOUT); - } - String tracingStarted(String tracesDir, String traceName) { LocalUtilsTracingStartedParams params = new LocalUtilsTracingStartedParams(); if (tracesDir != null) { @@ -65,6 +61,13 @@ String tracingStarted(String tracesDir, String traceName) { return connection.localUtils().channel.tracingStarted(params, NO_TIMEOUT).stacksId; } + void traceDiscarded(String stacksId) { + LocalUtilsTraceDiscardedParams params = new LocalUtilsTraceDiscardedParams(); + params.stacksId = stacksId; + channel.traceDiscarded(params, NO_TIMEOUT); + } + + // java: no counterpart upstream, the Java API matches globs on the driver. public Pattern globToRegex(String glob, String baseURL, boolean webSocketUrl) { LocalUtilsGlobToRegexParams params = new LocalUtilsGlobToRegexParams(); params.glob = glob; From e77c63338031fae0e194b01ae0e3660465a6cd81 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:26:17 -0800 Subject: [PATCH 20/30] refactor(jsonPipe): follow jsonPipe.ts --- .../java/com/microsoft/playwright/impl/JsonPipe.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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..bfae1770e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -29,17 +29,19 @@ import static com.microsoft.playwright.impl.Serialization.gson; +// Port of jsonPipe.ts. 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); JsonPipe(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); } + // java: the members below have no counterpart in jsonPipe.ts, they implement Transport (connect.ts upstream). + private final Queue incoming = new LinkedList<>(); + private boolean isClosed; + private String closeReason = "Browser has been closed"; + @Override public void send(JsonObject message) { checkIfClosed(); @@ -96,7 +98,6 @@ void offClose(Consumer handler) { off(Events.JsonPipe.CLOSE, handler); } - @Override protected void handleEvent(String event, JsonObject params) { if ("message".equals(event)) { From 60e0422fbda6a3d5ff4f5044b3f6cea734a7a48d Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:26:17 -0800 Subject: [PATCH 21/30] refactor(selectors): follow selectors.ts --- .../playwright/impl/SelectorsImpl.java | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) 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..473429690 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java @@ -30,33 +30,19 @@ import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static java.nio.charset.StandardCharsets.UTF_8; +// Port of selectors.ts. 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 List contextsForSelectors = new ArrayList<>(); @Override public void register(String name, String script, RegisterOptions options) { registerImpl(name, script, options); } + // java: evaluationScript with a path, without the sourceURL suffix. @Override public void register(String name, Path path, RegisterOptions options) { byte[] buffer; @@ -86,4 +72,20 @@ 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; + for (BrowserContextImpl context : contextsForSelectors) { + try { + BrowserContextSetTestIdAttributeNameParams params = new BrowserContextSetTestIdAttributeNameParams(); + params.testIdAttributeName = attributeName; + context.sendMessageAsync("setTestIdAttributeName", params); + } catch (PlaywrightException e) { + } + } + } } From 78681d420830ade2a00f415d99dfdcff179421e4 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 18:26:17 -0800 Subject: [PATCH 22/30] refactor(clientHelper): follow clientHelper.ts and fileUtils.ts --- .../playwright/impl/ClientHelper.java | 26 ++++++++++++ .../microsoft/playwright/impl/FileUtils.java | 40 +++++++++++++++++++ .../microsoft/playwright/impl/FrameImpl.java | 2 +- .../microsoft/playwright/impl/PageImpl.java | 2 +- .../com/microsoft/playwright/impl/Utils.java | 21 +--------- 5 files changed, 70 insertions(+), 21 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java 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..20e0cfa83 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java @@ -0,0 +1,26 @@ +/* + * 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 java.nio.file.Path; + +// Port of clientHelper.ts. java: envObjectToArray, evaluationScript and initScriptSourceWithExposedFunctions have no Java caller. +class ClientHelper { + static String addSourceUrlToScript(String source, Path path) { + return source + "\n//# sourceURL=" + path.toString().replace("\n", ""); + } +} 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..f66121fec --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java @@ -0,0 +1,40 @@ +/* + * 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.PlaywrightException; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +// Port of fileUtils.ts. java: fileUploadSizeLimit is inlined in Utils.checkFilePayloadSize. +class FileUtils { + // 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/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index 38b3ac22b..c0c58fc01 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -166,7 +166,7 @@ ElementHandle addScriptTagImpl(AddScriptTagOptions options) { throw new PlaywrightException("Failed to read from file", e); } String content = new String(encoded, StandardCharsets.UTF_8); - content = addSourceUrlToScript(content, options.path); + content = ClientHelper.addSourceUrlToScript(content, options.path); params.content = content; } return channel.addScriptTag(params, NO_TIMEOUT).element; 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..ebf0e7769 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -678,7 +678,7 @@ public AutoCloseable addInitScript(String script) { public AutoCloseable addInitScript(Path path) { try { byte[] bytes = readAllBytes(path); - String script = addSourceUrlToScript(new String(bytes, UTF_8), path); + String script = ClientHelper.addSourceUrlToScript(new String(bytes, UTF_8), path); return addInitScriptImpl(script); } catch (IOException e) { throw new PlaywrightException("Failed to read script from file", e); 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..c5034ff89 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java @@ -306,19 +306,6 @@ 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(); @@ -335,7 +322,7 @@ static ScreenshotType screenshotTypeForPath(Path path) { } 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 +331,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; @@ -429,10 +416,6 @@ 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) { From 05516dec05bde4bfd37fc2566779ef986a33ef0c Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Thu, 19 Nov 2026 18:32:57 -0800 Subject: [PATCH 23/30] chore: drop the notes on the remote path message, it is the upstream one now --- .../main/java/com/microsoft/playwright/impl/ArtifactImpl.java | 1 - .../src/main/java/com/microsoft/playwright/impl/VideoImpl.java | 1 - 2 files changed, 2 deletions(-) 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 a8377b152..44ec7ec50 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java @@ -38,7 +38,6 @@ public ArtifactImpl(ChannelOwner parent, String type, String guid, JsonObject in public Path pathAfterFinished() { if (connection.isRemote()) { - // java: the message names the Java API. 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); 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 f4b768bca..9821a57fe 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java @@ -39,7 +39,6 @@ class VideoImpl implements Video { @Override public Path path() { if (page.connection.isRemote()) { - // java: the message names the Java API. throw new PlaywrightException("Path is not available when connecting remotely. Use saveAs() to save a local copy."); } if (artifact == null) From 1026a1b6cf56bc652cf2eebe440c606bb9ee37ca Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Thu, 19 Nov 2026 18:33:22 -0800 Subject: [PATCH 24/30] chore: remove the classes that are translated anew from the Node.js client --- .../impl/APIRequestContextImpl.java | 321 ---- .../playwright/impl/APIRequestImpl.java | 109 -- .../playwright/impl/APIResponseImpl.java | 189 -- .../playwright/impl/BindingCall.java | 99 - .../playwright/impl/BrowserContextImpl.java | 923 ---------- .../playwright/impl/BrowserImpl.java | 369 ---- .../playwright/impl/BrowserTypeImpl.java | 238 --- .../playwright/impl/ElementHandleImpl.java | 478 ----- .../microsoft/playwright/impl/FrameImpl.java | 1128 ------------ .../playwright/impl/FrameLocatorImpl.java | 158 -- .../microsoft/playwright/impl/HARRouter.java | 137 -- .../playwright/impl/JSHandleImpl.java | 103 -- .../playwright/impl/LocatorImpl.java | 733 -------- .../microsoft/playwright/impl/PageImpl.java | 1594 ----------------- .../playwright/impl/PlaywrightImpl.java | 135 -- .../microsoft/playwright/impl/RawHeaders.java | 67 - .../playwright/impl/RemoteBrowser.java | 29 - .../playwright/impl/RequestImpl.java | 261 --- .../playwright/impl/ResponseImpl.java | 190 -- .../microsoft/playwright/impl/RouteImpl.java | 317 ---- .../com/microsoft/playwright/impl/Router.java | 107 -- .../playwright/impl/TracingImpl.java | 328 ---- .../playwright/impl/WebSocketFrameImpl.java | 29 - .../playwright/impl/WebSocketImpl.java | 162 -- .../playwright/impl/WebSocketRouteImpl.java | 215 --- .../playwright/impl/WebSocketRouter.java | 47 - 26 files changed, 8466 deletions(-) delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/HARRouter.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Router.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouter.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java deleted file mode 100644 index 9d4f42379..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ /dev/null @@ -1,321 +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.*; -import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.APIRequestContext; -import com.microsoft.playwright.APIResponse; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.Request; -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.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; - -public class APIRequestContextImpl extends ChannelOwner implements APIRequestContext { - private final TracingImpl tracing; - private String disposeReason; - - protected TimeoutSettings timeoutSettings = new TimeoutSettings(); - - final APIRequestContextChannel channel = new APIRequestContextChannel(this); - - APIRequestContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - this.tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString()); - } - - @Override - public TracingImpl tracing() { - return tracing; - } - - @Override - public List cookies(String url) { - return cookies(url == null ? new ArrayList<>() : Collections.singletonList(url)); - } - - @Override - public List cookies(List urls) { - APIRequestContextCookiesParams params = new APIRequestContextCookiesParams(); - if (urls == null) { - urls = new ArrayList<>(); - } - params.urls = urls; - APIRequestContextCookiesResult result = channel.cookies(params, NO_TIMEOUT); - Cookie[] cookies = gson().fromJson(gson().toJsonTree(result.cookies), Cookie[].class); - return asList(cookies); - } - - @Override - public void addCookies(List cookies) { - APIRequestContextAddCookiesParams params = new APIRequestContextAddCookiesParams(); - params.cookies = gson().fromJson(gson().toJsonTree(cookies), new TypeToken>() {}.getType()); - channel.addCookies(params, NO_TIMEOUT); - } - - @Override - public void clearCookies(ClearCookiesOptions options) { - if (options == null) { - options = new ClearCookiesOptions(); - } - APIRequestContextClearCookiesParams params = gson().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")); - } - - @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(); - } - - @Override - public APIResponse fetch(String urlOrRequest, RequestOptions options) { - return fetchImpl(urlOrRequest, (RequestOptionsImpl) options); - } - - @Override - public APIResponse fetch(Request request, RequestOptions optionsArg) { - RequestOptionsImpl options = (RequestOptionsImpl) optionsArg; - if (options == null) { - options = new RequestOptionsImpl(); - } - if (options.method == null) { - options.method = request.method(); - } - if (options.headers == null) { - options.headers = request.headers(); - } - if (options.data == null && options.form == null && options.multipart == null) { - options.data = request.postDataBuffer(); - } - return fetch(request.url(), options); - } - - private APIResponse fetchImpl(String url, RequestOptionsImpl options) { - if (disposeReason != null) { - throw new PlaywrightException(disposeReason); - } - if (options == null) { - options = new RequestOptionsImpl(); - } - 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())); - } - params.method = options.method; - if (options.headers != null) { - params.headers = toNameValues(Serialization.toProtocol(options.headers)); - } - - 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 (bytes == null) { - params.jsonData = jsonDataSerializer.toJson(options.data); - } else { - params.postData = bytes; - } - } - if (options.form != null) { - params.formData = toNameValues(toNameValueArray(options.form.fields)); - } - if (options.multipart != null) { - params.multipartData = serializeMultipartData(options.multipart.fields); - } - 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; - } - 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(); - if (options.path != null) { - Utils.writeToFile(Serialization.toPrettyJson(storageState).getBytes(StandardCharsets.UTF_8), options.path); - } - return storageState; - } - - 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; - } - return impl; - } - - private static boolean isJsonParsable(String value) { - if (value.trim().isEmpty()) { - return false; - } - try { - JsonElement result = JsonParser.parseString(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) { - return false; - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java deleted file mode 100644 index 3122ba2bb..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ /dev/null @@ -1,109 +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.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.APIRequest; -import com.microsoft.playwright.PlaywrightException; -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.List; - -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; - - APIRequestImpl(PlaywrightImpl playwright) { - this.playwright = playwright; - } - - @Override - public APIRequestContextImpl newContext(NewContextOptions options) { - if (options == null) { - options = new NewContextOptions(); - } else { - options = Utils.clone(options); - } - 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); - } - } - 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). - Object httpCredentials = options.httpCredentials; - 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()); - } - } - APIRequestContextImpl context = playwright.channel.newRequest(params, NO_TIMEOUT).request; - context.timeoutSettings.setDefaultTimeout(timeout); - 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 deleted file mode 100644 index 48693a031..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java +++ /dev/null @@ -1,189 +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.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.APIResponse; -import com.microsoft.playwright.PlaywrightException; -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.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; - -class APIResponseImpl implements APIResponse { - final APIRequestContextImpl context; - private final com.microsoft.playwright.impl.protocol.APIResponse response; - private final RawHeaders headers; - - 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); - } - - @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; - } - } - - @Override - public void dispose() { - APIRequestContextDisposeAPIResponseParams params = new APIRequestContextDisposeAPIResponseParams(); - params.fetchUid = fetchUid(); - context.channel.disposeAPIResponse(params, NO_TIMEOUT); - } - - @Override - public Map headers() { - return headers.headers(); - } - - @Override - public List headersArray() { - return headers.headersArray(); - } - - @Override - public boolean ok() { - int status = status(); - return status == 0 || (status >= 200 && status <= 299); - } - - @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; - } - - @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; - } - - @Override - public int status() { - return response.status; - } - - @Override - public String statusText() { - return response.statusText; - } - - @Override - public String text() { - return new String(body(), 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; - } - - private static double orZero(Double value) { - return value == null ? 0 : value; - } - - @Override - public String url() { - return response.url; - } - - String fetchUid() { - return response.fetchUid; - } - - List fetchLog() { - APIRequestContextFetchLogParams params = new APIRequestContextFetchLogParams(); - params.fetchUid = fetchUid(); - return context.channel.fetchLog(params, NO_TIMEOUT).log; - } - -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java deleted file mode 100644 index a74c8d91c..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java +++ /dev/null @@ -1,99 +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.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.options.BindingCallback; - -import java.util.ArrayList; -import java.util.List; - -import static com.microsoft.playwright.impl.Serialization.*; - -public class BindingCall extends ChannelOwner { - private static class SourceImpl implements BindingCallback.Source { - private final Frame frame; - - public SourceImpl(Frame frame) { - this.frame = frame; - } - - @Override - public BrowserContext context() { - return page().context(); - } - - @Override - public Page page() { - return frame.page(); - } - - @Override - 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 deleted file mode 100644 index 35225faee..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ /dev/null @@ -1,923 +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.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; -import com.microsoft.playwright.*; -import com.microsoft.playwright.options.*; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.util.*; -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; - -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<>(); - PageImpl ownerPage; - private String closeReason; - - final TimeoutSettings timeoutSettings = new TimeoutSettings(); - - final BrowserContextChannel channel = new BrowserContextChannel(this); - - BrowserContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - Map mapping = new HashMap<>(); - mapping.put(Events.BrowserContext.CONSOLE, "console"); - mapping.put(Events.BrowserContext.DIALOG, "dialog"); - mapping.put(Events.BrowserContext.DIALOG_CLOSED, "dialogClosed"); - mapping.put(Events.BrowserContext.REQUEST, "request"); - mapping.put(Events.BrowserContext.RESPONSE, "response"); - 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) { - } - } - return null; - } - - String effectiveCloseReason() { - if (closeReason != null) { - return closeReason; - } - if (browser != null) { - return browser.closeReason; - } - return null; - } - - @Override - public void onBackgroundPage(Consumer handler) { - } - - @Override - public void offBackgroundPage(Consumer handler) { - } - - @Override - public void onDownload(Consumer handler) { - on(Events.BrowserContext.DOWNLOAD, handler); - } - - @Override - public void offDownload(Consumer handler) { - off(Events.BrowserContext.DOWNLOAD, handler); - } - - void notifyDownload(Download download) { - emit(Events.BrowserContext.DOWNLOAD, download); - } - - @Override - public void onClose(Consumer handler) { - on(Events.BrowserContext.CLOSE, handler); - } - - @Override - public void offClose(Consumer handler) { - off(Events.BrowserContext.CLOSE, handler); - } - - @Override - public void onConsoleMessage(Consumer handler) { - on(Events.BrowserContext.CONSOLE, handler); - } - - @Override - public void offConsoleMessage(Consumer handler) { - off(Events.BrowserContext.CONSOLE, handler); - } - - @Override - public void onDialog(Consumer handler) { - on(Events.BrowserContext.DIALOG, handler); - } - - @Override - public void offDialog(Consumer handler) { - off(Events.BrowserContext.DIALOG, handler); - } - - @Override - public void onDialogClosed(Consumer handler) { - on(Events.BrowserContext.DIALOG_CLOSED, handler); - } - - @Override - public void offDialogClosed(Consumer handler) { - off(Events.BrowserContext.DIALOG_CLOSED, handler); - } - - @Override - public void onPage(Consumer handler) { - on(Events.BrowserContext.PAGE, handler); - } - - @Override - public void offPage(Consumer handler) { - off(Events.BrowserContext.PAGE, handler); - } - - @Override - public void onFrameAttached(Consumer handler) { - on(Events.BrowserContext.FRAME_ATTACHED, handler); - } - - @Override - public void offFrameAttached(Consumer handler) { - off(Events.BrowserContext.FRAME_ATTACHED, handler); - } - - void notifyFrameAttached(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_ATTACHED, frame); - } - - @Override - public void onFrameDetached(Consumer handler) { - on(Events.BrowserContext.FRAME_DETACHED, handler); - } - - @Override - public void offFrameDetached(Consumer handler) { - off(Events.BrowserContext.FRAME_DETACHED, handler); - } - - void notifyFrameDetached(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_DETACHED, frame); - } - - @Override - public void onFrameNavigated(Consumer handler) { - on(Events.BrowserContext.FRAME_NAVIGATED, handler); - } - - @Override - public void offFrameNavigated(Consumer handler) { - off(Events.BrowserContext.FRAME_NAVIGATED, handler); - } - - void notifyFrameNavigated(FrameImpl frame) { - emit(Events.BrowserContext.FRAME_NAVIGATED, frame); - } - - @Override - public void onPageClose(Consumer handler) { - on(Events.BrowserContext.PAGE_CLOSE, handler); - } - - @Override - public void offPageClose(Consumer handler) { - off(Events.BrowserContext.PAGE_CLOSE, handler); - } - - void notifyPageClose(PageImpl page) { - emit(Events.BrowserContext.PAGE_CLOSE, page); - } - - @Override - public void onPageLoad(Consumer handler) { - on(Events.BrowserContext.PAGE_LOAD, handler); - } - - @Override - public void offPageLoad(Consumer handler) { - off(Events.BrowserContext.PAGE_LOAD, handler); - } - - void notifyPageLoad(PageImpl page) { - emit(Events.BrowserContext.PAGE_LOAD, page); - } - - @Override - public void onWebError(Consumer handler) { - on(Events.BrowserContext.WEB_ERROR, handler); - } - - @Override - public void offWebError(Consumer handler) { - off(Events.BrowserContext.WEB_ERROR, handler); - } - - @Override - public void onRequest(Consumer handler) { - on(Events.BrowserContext.REQUEST, handler); - } - - @Override - public void offRequest(Consumer handler) { - off(Events.BrowserContext.REQUEST, handler); - } - - @Override - public void onRequestFailed(Consumer handler) { - on(Events.BrowserContext.REQUEST_FAILED, handler); - } - - @Override - public void offRequestFailed(Consumer handler) { - off(Events.BrowserContext.REQUEST_FAILED, handler); - } - - @Override - public void onRequestFinished(Consumer handler) { - on(Events.BrowserContext.REQUEST_FINISHED, handler); - } - - @Override - public void offRequestFinished(Consumer handler) { - off(Events.BrowserContext.REQUEST_FINISHED, handler); - } - - @Override - public void onResponse(Consumer handler) { - on(Events.BrowserContext.RESPONSE, handler); - } - - @Override - public void offResponse(Consumer handler) { - off(Events.BrowserContext.RESPONSE, handler); - } - - @Override - public ClockImpl clock() { - return clock; - } - - @Override - public Credentials credentials() { - return credentials; - } - - @Override - public Page waitForPage(WaitForPageOptions options, Runnable code) { - if (options == null) { - options = new WaitForPageOptions(); - } - return waitForEvent(Events.BrowserContext.PAGE, options.predicate, options.timeout, code); - } - - // waitForEvent in browserContext.ts - private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { - 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 + "\""); - if (!Events.BrowserContext.CLOSE.equals(event)) { - waiter.rejectOnEvent(this, Events.BrowserContext.CLOSE, () -> new TargetClosedError(effectiveCloseReason())); - } - T result = waiter.waitForEvent(this, event, predicate, code); - waiter.dispose(); - return result; - } - - @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) { - BrowserContextNewCDPSessionParams params = new BrowserContextNewCDPSessionParams(); - params.frame = (FrameImpl) frame; - return channel.newCDPSession(params, NO_TIMEOUT).session; - } - - @Override - public boolean isClosed() { - return closingOrClosed; - } - - @Override - public void close(CloseOptions options) { - 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); - } - runUntil(() -> {}, closePromise); - if (harError != null) { - throw harError; - } - } - - @Override - public List cookies(String url) { - return cookies(url == null ? new ArrayList<>() : Collections.singletonList(url)); - } - - - @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); - } - - @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) { - 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); - } - } - - @Override - public List backgroundPages() { - return Collections.emptyList(); - } - - @Override - public BrowserImpl browser() { - return browser; - } - - @Override - public void clearCookies(ClearCookiesOptions options) { - if (options == null) { - options = new ClearCookiesOptions(); - } - BrowserContextClearCookiesParams params = connection.protocolGson().fromJson(toClearCookiesParams(options.name, options.domain, options.path), BrowserContextClearCookiesParams.class); - channel.clearCookies(params, NO_TIMEOUT); - } - - @Override - public void clearPermissions() { - channel.clearPermissions(NO_TIMEOUT); - } - - @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); - } - - @Override - public AutoCloseable exposeBinding(String name, BindingCallback playwrightBinding) { - return exposeBindingImpl(name, playwrightBinding); - } - - private AutoCloseable exposeBindingImpl(String name, BindingCallback playwrightBinding) { - if (bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered"); - } - for (PageImpl page : pages) { - if (page.bindings.containsKey(name)) { - throw new PlaywrightException("Function \"" + name + "\" has been already registered in one of the pages"); - } - } - 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)); - } - - @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); - } - - @Override - public PageImpl newPage() { - if (ownerPage != null) { - throw new PlaywrightException("Please use browser.newContext()"); - } - return channel.newPage(NO_TIMEOUT).page; - } - - @Override - public List pages() { - return new ArrayList<>(pages); - } - - @Override - public APIRequestContextImpl request() { - return 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)); - } - - @Override - public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); - } - - @Override - public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, 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); - } - - 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(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(); - } - - 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 setDefaultNavigationTimeout(double timeout) { - timeoutSettings.setDefaultNavigationTimeout(timeout); - } - - @Override - public void setDefaultTimeout(double timeout) { - timeoutSettings.setDefaultTimeout(timeout); - } - - @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); - } - - @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); - } - - @Override - public void setOffline(boolean offline) { - BrowserContextSetOfflineParams params = new BrowserContextSetOfflineParams(); - params.offline = offline; - channel.setOffline(params, NO_TIMEOUT); - } - - @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); - } - } - - @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); - - String storageState = json.toString(); - if (options.path != null) { - Utils.writeToFile(Serialization.toPrettyJson(storageState).getBytes(StandardCharsets.UTF_8), options.path); - } - return storageState; - } - - @Override - public DebuggerImpl debugger() { - return debugger; - } - - void setTracesDir(Path tracesDir) { - tracing.setTracesDir(tracesDir); - request.tracing().setTracesDir(tracesDir); - } - - @Override - public TracingImpl tracing() { - return tracing; - } - - @Override - public void unrouteAll() { - routes.removeAll(); - updateInterceptionPatterns(); - } - - @Override - public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(this.baseUrl(), url, this.connection.localUtils(), false), handler); - } - - @Override - public void unroute(Pattern url, Consumer handler) { - unroute(new UrlMatcher(url), handler); - } - - @Override - public void unroute(Predicate url, Consumer handler) { - unroute(new UrlMatcher(url), 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)); - } - - @Override - public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - if (options == null) { - options = new WaitForConsoleMessageOptions(); - } - return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, code); - } - - private class WaitableContextClose extends WaitableEvent { - WaitableContextClose() { - super(BrowserContextImpl.this, Events.BrowserContext.CLOSE); - } - - @Override - public R get() { - throw new TargetClosedError(effectiveCloseReason()); - } - } - - private void unroute(UrlMatcher matcher, Consumer handler) { - routes.remove(matcher, handler); - updateInterceptionPatterns(); - } - - private void updateInterceptionPatterns() { - BrowserContextSetNetworkInterceptionPatternsParams params = connection.protocolGson().fromJson(routes.interceptionPatterns(), BrowserContextSetNetworkInterceptionPatternsParams.class); - channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); - } - - private void updateWebSocketInterceptionPatterns() { - BrowserContextSetWebSocketInterceptionPatternsParams params = connection.protocolGson().fromJson(webSocketRoutes.interceptionPatterns(), BrowserContextSetWebSocketInterceptionPatternsParams.class); - channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); - } - - 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(); - } - } - - void handleWebSocketRoute(WebSocketRouteImpl route) { - if (!webSocketRoutes.handle(route)) { - route.connectToServer(); - } - } - - WaitableResult pause() { - return sendMessageAsync("pause", new BrowserContextPauseParams()); - } - - @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(); - } - } - - void didClose() { - closingOrClosed = true; - if (browser != null) { - browser.contexts.remove(this); - browser.browserType.playwright.selectors.contextsForSelectors.remove(this); - } - tracing.resetStackCounter(); - request.tracing().resetStackCounter(); - emit(Events.BrowserContext.CLOSE, this); - } - - 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"); - } - 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); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java deleted file mode 100644 index 5a0c23e26..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ /dev/null @@ -1,369 +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.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.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.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; - -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; - BrowserTypeImpl browserType; - BrowserType.LaunchOptions launchOptions; - private Path tracePath; - String closeReason; - - final BrowserChannel channel = new BrowserChannel(this); - - BrowserImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } - - @Override - public void onContext(Consumer handler) { - on(Events.Browser.CONTEXT, handler); - } - - @Override - public void offContext(Consumer handler) { - off(Events.Browser.CONTEXT, handler); - } - - @Override - public void onDisconnected(Consumer handler) { - on(Events.Browser.DISCONNECTED, handler); - } - - @Override - public void offDisconnected(Consumer handler) { - off(Events.Browser.DISCONNECTED, handler); - } - - @Override - public BrowserType browserType() { - return browserType; - } - - @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); - } - return; - } - try { - channel.close(new BrowserCloseParams(), NO_TIMEOUT); - } catch (PlaywrightException e) { - if (!isSafeCloseError(e)) { - throw e; - } - } - } - - 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(); - } - didClose(); - } - - @Override - public List contexts() { - return new ArrayList<>(contexts); - } - - @Override - public boolean isConnected() { - return isConnected; - } - - @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); - } - - 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; - } - - @Override - public Page newPage(NewPageOptions options) { - return withTitle("Create Page", () -> newPageImpl(options)); - } - - @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); - } - - @Override - public BindResult bind(String title, BindOptions options) { - BrowserStartServerParams params = toProtocol(options, BrowserStartServerParams.class); - params.title = title; - BrowserStartServerResult result = channel.startServer(params, NO_TIMEOUT); - BindResult bindResult = new BindResult(); - bindResult.endpoint = result.endpoint; - return bindResult; - } - - @Override - public void unbind() { - channel.stopServer(NO_TIMEOUT); - } - - @Override - public byte[] stopTracing() { - ArtifactImpl artifact = channel.stopTracing(NO_TIMEOUT).artifact; - byte[] data = 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; - } - } - return data; - } - - // 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; - } - - static List clientCertificatesToProtocol(List clientCertificates) { - if (clientCertificates == null) { - return null; - } - 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); - } - c.passphrase = cert.passphrase; - result.add(c); - } - 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()); - } - - @Override - public String version() { - return initializer.get("version").getAsString(); - } - - @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; - } - } - - @Override - public CDPSession newBrowserCDPSession() { - return channel.newBrowserCDPSession(NO_TIMEOUT).session; - } - - 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); - } - } - - 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); - } - 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 deleted file mode 100644 index 971834010..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ /dev/null @@ -1,238 +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.Gson; -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 java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -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; - - final BrowserTypeChannel channel = new BrowserTypeChannel(this); - - BrowserTypeImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } - - @Override - public BrowserImpl launch(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; - } - - @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; - } - } - if (!foundBrowserHeader) { - headers.addProperty("x-playwright-browser", name()); - } - params.headers = headers; - - Double timeout = options.timeout; - if (timeout == null) { - timeout = 0.0; - } - - 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); - } - }); - return browser; - } - - @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."); - } - if (options == null) { - options = new ConnectOverCDPOptions(); - } - - 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; - } - - public String executablePath() { - return initializer.get("executablePath").getAsString(); - } - - @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); - } - - 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; - } - } - 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); - } - c.passphrase = cert.passphrase; - params.clientCertificates.add(c); - } - } - 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(); - } - -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java deleted file mode 100644 index 502d160ac..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ /dev/null @@ -1,478 +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.ElementHandle; -import com.microsoft.playwright.Frame; -import com.microsoft.playwright.Locator; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.options.BoundingBox; -import com.microsoft.playwright.options.ElementState; -import com.microsoft.playwright.options.FilePayload; -import com.microsoft.playwright.options.SelectOption; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - -import static com.microsoft.playwright.impl.Serialization.*; -import static com.microsoft.playwright.impl.Utils.*; -import static com.microsoft.playwright.impl.Utils.addFilePathUploadParams; - -public class ElementHandleImpl extends JSHandleImpl implements ElementHandle { - private final FrameImpl frame; - - // Hides JSHandleImpl.channel on purpose: upstream ElementHandle narrows the type of _channel the same way. - final ElementHandleChannel channel = new ElementHandleChannel(this); - - ElementHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - this.frame = (FrameImpl)parent; - } - - @Override - public ElementHandle asElement() { - return this; - } - - @Override - public ElementHandle querySelector(String selector) { - ElementHandleQuerySelectorParams params = new ElementHandleQuerySelectorParams(); - params.selector = selector; - return channel.querySelector(params, NO_TIMEOUT).element; - } - - @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); - } - - @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); - } - - @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); - } - - @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; - } - - @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)); - } - - @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)); - } - - @Override - public Frame contentFrame() { - return channel.contentFrame(NO_TIMEOUT).frame; - } - - @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)); - } - - @Override - public void dispatchEvent(String type, Object eventInit) { - ElementHandleDispatchEventParams params = new ElementHandleDispatchEventParams(); - params.type = type; - params.eventInit = serializeArgument(eventInit); - channel.dispatchEvent(params, NO_TIMEOUT); - } - - @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)); - } - - @Override - public void focus() { - channel.focus(NO_TIMEOUT); - } - - @Override - public String getAttribute(String name) { - ElementHandleGetAttributeParams params = new ElementHandleGetAttributeParams(); - params.name = name; - return channel.getAttribute(params, NO_TIMEOUT).value; - } - - @Override - public void hover(HoverOptions options) { - if (options == null) { - options = new HoverOptions(); - } - ElementHandleHoverParams params = Utils.toProtocol(options, ElementHandleHoverParams.class); - channel.hover(params, frame.timeout(options.timeout)); - } - - @Override - public String innerHTML() { - return channel.innerHTML(NO_TIMEOUT).value; - } - - @Override - public String innerText() { - return channel.innerText(NO_TIMEOUT).value; - } - - @Override - public String inputValue(InputValueOptions options) { - if (options == null) { - options = new InputValueOptions(); - } - ElementHandleInputValueParams params = Utils.toProtocol(options, ElementHandleInputValueParams.class); - return channel.inputValue(params, NO_TIMEOUT).value; - } - - @Override - public boolean isChecked() { - return channel.isChecked(NO_TIMEOUT).value; - } - - @Override - public boolean isDisabled() { - return channel.isDisabled(NO_TIMEOUT).value; - } - - @Override - public boolean isEditable() { - return channel.isEditable(NO_TIMEOUT).value; - } - - @Override - public boolean isEnabled() { - return channel.isEnabled(NO_TIMEOUT).value; - } - - @Override - public boolean isHidden() { - return channel.isHidden(NO_TIMEOUT).value; - } - - @Override - public boolean isVisible() { - return channel.isVisible(NO_TIMEOUT).value; - } - - @Override - public FrameImpl ownerFrame() { - return channel.ownerFrame(NO_TIMEOUT).frame; - } - - @Override - public void press(String key, PressOptions options) { - if (options == null) { - options = new PressOptions(); - } - ElementHandlePressParams params = Utils.toProtocol(options, ElementHandlePressParams.class); - params.key = key; - channel.press(params, frame.timeout(options.timeout)); - } - - @Override - public byte[] screenshot(ScreenshotOptions 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); - } - return buffer; - } - - @Override - public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { - if (options == null) { - options = new ScrollIntoViewIfNeededOptions(); - } - ElementHandleScrollIntoViewIfNeededParams params = Utils.toProtocol(options, ElementHandleScrollIntoViewIfNeededParams.class); - channel.scrollIntoViewIfNeeded(params, frame.timeout(options.timeout)); - } - - @Override - public List selectOption(String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(values, options); - } - - @Override - public List selectOption(ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{ value }; - return selectOption(values, options); - } - - @Override - public List selectOption(String[] values, SelectOptionOptions 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 (String value : values) { - ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); - option.valueOrLabel = value; - params.options.add(option); - } - } - return selectOption(params, options.timeout); - } - - @Override - public List selectOption(SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{ value }; - return selectOption(values, options); - } - - - @Override - public List selectOption(SelectOption[] values, SelectOptionOptions 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); - } - } - return selectOption(params, options.timeout); - } - - @Override - public List selectOption(ElementHandle[] values, SelectOptionOptions 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); - } - } - return selectOption(params, options.timeout); - } - - private List selectOption(ElementHandleSelectOptionParams params, Double timeout) { - return channel.selectOption(params, frame.timeout(timeout)).values; - } - - @Override - public void selectText(SelectTextOptions options) { - if (options == null) { - options = new SelectTextOptions(); - } - ElementHandleSelectTextParams params = Utils.toProtocol(options, ElementHandleSelectTextParams.class); - channel.selectText(params, frame.timeout(options.timeout)); - } - - @Override - public void setChecked(boolean checked, SetCheckedOptions options) { - if (checked) { - check(convertType(options, CheckOptions.class)); - } else { - uncheck(convertType(options, UncheckOptions.class)); - } - } - - @Override - public void setInputFiles(Path files, SetInputFilesOptions options) { - setInputFiles(new Path[]{files}, options); - } - - - @Override - public void setInputFiles(Path[] files, SetInputFilesOptions options) { - FrameImpl frame = ownerFrame(); - if (frame == null) { - throw new Error("Cannot set input files to detached element"); - } - 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<>(); - } - 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(); - } - 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); - } - channel.setInputFiles(params, frame.timeout(options.timeout)); - } - - @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)); - } - - @Override - public String textContent() { - return channel.textContent(NO_TIMEOUT).value; - } - - @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)); - } - - @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)); - } - - @Override - public void waitForElementState(ElementState state, WaitForElementStateOptions options) { - if (options == null) { - options = new WaitForElementStateOptions(); - } - if (state == null) { - throw new IllegalArgumentException("State cannot be null"); - } - ElementHandleWaitForElementStateParams params = Utils.toProtocol(options, ElementHandleWaitForElementStateParams.class); - params.state = state.toString().toLowerCase(); - channel.waitForElementState(params, frame.timeout(options.timeout)); - } - - @Override - public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { - if (options == null) { - options = new WaitForSelectorOptions(); - } - ElementHandleWaitForSelectorParams params = Utils.toProtocol(options, ElementHandleWaitForSelectorParams.class); - params.selector = selector; - return channel.waitForSelector(params, frame.timeout(options.timeout)).element; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java deleted file mode 100644 index c0c58fc01..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ /dev/null @@ -1,1128 +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.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.microsoft.playwright.*; -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.function.Predicate; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.LocatorUtils.*; -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; - FrameImpl parentFrame; - Set childFrames = new LinkedHashSet<>(); - private final Set loadStates = new HashSet<>(); - - PageImpl page; - boolean isDetached; - private final WebMCPImpl webmcp = new WebMCPImpl(this); - - final FrameChannel channel = new FrameChannel(this); - - 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()); - 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); - } - } - - @Override - public ElementHandle querySelector(String selector, QuerySelectorOptions options) { - if (options == null) { - options = new QuerySelectorOptions(); - } - 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); - } - - @Override - public List selectOption(String selector, String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(selector, values, options); - } - - @Override - public List selectOption(String selector, ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{value}; - return selectOption(selector, values, options); - } - - @Override - public List selectOption(String selector, String[] values, SelectOptionOptions options) { - return selectOptionImpl(selector, values, options); - } - - @Override - public List selectOption(String selector, SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{value}; - return selectOption(selector, values, options); - } - - - @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) { - if (options == null) { - options = new EvalOnSelectorOptions(); - } - FrameEvalOnSelectorParams params = toProtocol(options, FrameEvalOnSelectorParams.class); - params.selector = selector; - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evalOnSelector(params, NO_TIMEOUT).value); - } - - @Override - public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { - return evalOnSelectorAllImpl(selector, pageFunction, arg); - } - - 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); - } - - @Override - public ElementHandle addScriptTag(AddScriptTagOptions options){ - return addScriptTagImpl(options); - } - - ElementHandle addScriptTagImpl(AddScriptTagOptions options) { - if (options == null) { - options = new AddScriptTagOptions(); - } - FrameAddScriptTagParams params = toProtocol(options, FrameAddScriptTagParams.class); - if (options.path != null) { - byte[] encoded; - try { - encoded = Files.readAllBytes(options.path); - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); - } - String content = new String(encoded, StandardCharsets.UTF_8); - content = ClientHelper.addSourceUrlToScript(content, options.path); - params.content = content; - } - return channel.addScriptTag(params, NO_TIMEOUT).element; - } - - @Override - public ElementHandle addStyleTag(AddStyleTagOptions options){ - return addStyleTagImpl(options); - } - - ElementHandle addStyleTagImpl(AddStyleTagOptions options) { - if (options == null) { - options = new AddStyleTagOptions(); - } - FrameAddStyleTagParams params = toProtocol(options, FrameAddStyleTagParams.class); - if (options.path != null) { - byte[] encoded; - try { - encoded = Files.readAllBytes(options.path); - } catch (IOException e) { - throw new PlaywrightException("Failed to read from file", e); - } - 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)); - } - - @Override - public List childFrames() { - return new ArrayList<>(childFrames); - } - - @Override - public void click(String selector, ClickOptions options) { - clickImpl(selector, options, null); - } - - 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; - } - channel.click(params, timeout(options.timeout)); - } - - @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; - } - - @Override - public void dblclick(String selector, DblclickOptions options) { - dblclickImpl(selector, options, null); - } - - void dblclickImpl(String selector, DblclickOptions options, Integer steps) { - if (options == null) { - options = new DblclickOptions(); - } - FrameDblclickParams params = toProtocol(options, FrameDblclickParams.class); - params.selector = selector; - if (steps != null) { - params.steps = steps; - } - channel.dblclick(params, timeout(options.timeout)); - } - - @Override - public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { - if (options == null) { - options = new DispatchEventOptions(); - } - FrameDispatchEventParams params = toProtocol(options, FrameDispatchEventParams.class); - params.selector = selector; - params.type = type; - params.eventInit = serializeArgument(eventInit); - channel.dispatchEvent(params, timeout(options.timeout)); - } - - @Override - public Object evaluate(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 JSHandle evaluateHandle(String pageFunction, Object arg) { - FrameEvaluateExpressionHandleParams params = new FrameEvaluateExpressionHandleParams(); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; - } - - @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)); - } - - @Override - public void focus(String selector, FocusOptions options) { - if (options == null) { - options = new FocusOptions(); - } - FrameFocusParams params = toProtocol(options, FrameFocusParams.class); - params.selector = selector; - channel.focus(params, timeout(options.timeout)); - } - - @Override - public ElementHandle frameElement() { - return channel.frameElement(NO_TIMEOUT).element; - } - - @Override - public FrameLocator frameLocator(String selector) { - return new FrameLocatorImpl(this, selector == null ? FrameLocatorImpl.ANY_FRAME_SELECTOR : selector); - } - - @Override - public String getAttribute(String selector, String name, GetAttributeOptions options) { - return getAttributeImpl(selector, name, options); - } - - @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 - 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, connection.playwright)); - } - - @Override - public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, connection.playwright)); - } - - @Override - public Locator getByText(String text, GetByTextOptions options) { - return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); - } - - @Override - public Locator getByText(Pattern text, GetByTextOptions options) { - return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); - } - - @Override - public Locator getByTitle(String text, GetByTitleOptions options) { - return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); - } - - @Override - 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 ResponseImpl navigate(String url, NavigateOptions options) { - return navigateImpl(url, options); - } - - ResponseImpl navigateImpl(String url, NavigateOptions options) { - if (options == null) { - options = new NavigateOptions(); - } - FrameGotoParams params = toProtocol(options, FrameGotoParams.class); - params.url = url; - return channel.goto_(params, navigationTimeout(options.timeout)).response; - } - - @Override - public void hover(String selector, HoverOptions options) { - hoverImpl(selector, options); - } - - void hoverImpl(String selector, HoverOptions options) { - if (options == null) { - options = new HoverOptions(); - } - FrameHoverParams params = toProtocol(options, FrameHoverParams.class); - params.selector = selector; - channel.hover(params, timeout(options.timeout)); - } - - @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) { - if (options == null) { - options = new DragAndDropOptions(); - } - FrameDragAndDropParams params = toProtocol(options, FrameDragAndDropParams.class); - params.source = source; - params.target = target; - if (steps != null) { - params.steps = steps; - } - channel.dragAndDrop(params, timeout(options.timeout)); - } - - @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; - } - - @Override - public String innerText(String selector, InnerTextOptions options) { - return innerTextImpl(selector, options); - } - - String innerTextImpl(String selector, InnerTextOptions options) { - if (options == null) { - options = new InnerTextOptions(); - } - FrameInnerTextParams params = toProtocol(options, FrameInnerTextParams.class); - params.selector = selector; - FrameInnerTextResult result = channel.innerText(params, timeout(options.timeout)); - return result.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; - } - - @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; - } - - @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; - } - - @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; - } - - @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; - } - - @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; - } - - @Override - public boolean isVisible(String selector, IsVisibleOptions options) { - return isVisibleImpl(selector, options); - } - - @Override - public Locator locator(String selector, LocatorOptions options) { - return new LocatorImpl(this, selector, convertType(options, Locator.LocatorOptions.class)); - } - - boolean isVisibleImpl(String selector, IsVisibleOptions options) { - if (options == null) { - options = new IsVisibleOptions(); - } - FrameIsVisibleParams params = toProtocol(options, FrameIsVisibleParams.class); - params.selector = selector; - FrameIsVisibleResult result = channel.isVisible(params, timeout(options.timeout)); - return result.value; - } - - @Override - public String name() { - return name; - } - - @Override - public PageImpl page() { - return page; - } - - @Override - public Frame parentFrame() { - return parentFrame; - } - - @Override - public void press(String selector, String key, PressOptions options) { - pressImpl(selector, key, 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, SelectOption[] values, SelectOptionOptions options) { - return selectOptionImpl(selector, values, options); - } - - List selectOptionImpl(String selector, SelectOption[] 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 (SelectOption value : values) { - FrameSelectOptionParams.FrameSelectOptionParamsOptions option = new FrameSelectOptionParams.FrameSelectOptionParamsOptions(); - 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)); - } - - @Override - public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { - setInputFiles(selector, new Path[] {files}, options); - } - - @Override - public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { - 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); - } - - @Override - public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { - setInputFilesImpl(selector, files, options); - } - - void setInputFilesImpl(String selector, FilePayload[] files, SetInputFilesOptions options) { - checkFilePayloadSize(files); - if (options == null) { - options = new SetInputFilesOptions(); - } - 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); - } - channel.setInputFiles(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 String textContent(String selector, TextContentOptions options) { - if (options == null) { - options = new TextContentOptions(); - } - FrameTextContentParams params = toProtocol(options, FrameTextContentParams.class); - params.selector = selector; - return channel.textContent(params, timeout(options.timeout)).value; - } - - @Override - public String title() { - return channel.title(NO_TIMEOUT).value; - } - - @Override - public void type(String selector, String text, TypeOptions options) { - if (options == null) { - options = new TypeOptions(); - } - FrameTypeParams params = toProtocol(options, FrameTypeParams.class); - params.selector = selector; - params.text = text; - channel.type(params, timeout(options.timeout)); - } - - @Override - public void uncheck(String selector, UncheckOptions options) { - if (options == null) { - options = new UncheckOptions(); - } - FrameUncheckParams params = toProtocol(options, FrameUncheckParams.class); - params.selector = selector; - channel.uncheck(params, timeout(options.timeout)); - } - - @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(); - } - FrameWaitForSelectorParams params = toProtocol(options, FrameWaitForSelectorParams.class); - params.selector = selector; - params.omitReturnValue = omitReturnValue; - return channel.waitForSelector(params, timeout(options.timeout)).element; - } - - @Override - public void waitForTimeout(double timeout) { - FrameWaitForTimeoutParams params = new FrameWaitForTimeoutParams(); - params.waitTimeout = timeout; - channel.waitForTimeout(params, NO_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) { - if (options == null) { - options = new WaitForURLOptions(); - } - if (matcher.test(url())) { - waitForLoadState(options.waitUntil, options.timeout); - return; - } - waitForNavigation(matcher, url, options.waitUntil, options.timeout, () -> {}); - } - - int queryCount(String selector) { - FrameQueryCountParams params = new FrameQueryCountParams(); - params.selector = selector; - return channel.queryCount(params, 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); - } - } - } - channel.drop(params, timeout(options.timeout)); - } - - private void addDropFilePaths(Path[] files, FrameDropParams params) { - Utils.UploadParams upload = addFilePathUploadParams(files, page.context()); - if (upload.emptyPayloads) { - params.payloads = new ArrayList<>(); - } - 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); - } - } - - void highlightImpl(String selector, String style) { - FrameHighlightParams params = new FrameHighlightParams(); - params.selector = selector; - params.style = style; - channel.highlight(params, NO_TIMEOUT); - } - - void hideHighlightImpl(String selector) { - FrameHideHighlightParams params = new FrameHideHighlightParams(); - params.selector = selector; - channel.hideHighlight(params, NO_TIMEOUT); - } - - 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); - } - } - - @Override - 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 deleted file mode 100644 index f5f687d64..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ /dev/null @@ -1,158 +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.FrameLocator; -import com.microsoft.playwright.Locator; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.options.AriaRole; - -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.LocatorUtils.*; -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; - - FrameLocatorImpl(FrameImpl frame, String selector) { - this.frame = frame; - this.frameSelector = selector; - } - - private String childSelector(String selector) { - if (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 FrameLocator first() { - return new FrameLocatorImpl(frame, nthSelector(0)); - } - - @Override - public FrameLocatorImpl frameLocator(String selector) { - return new FrameLocatorImpl(frame, childSelector(selector)); - } - - @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 - 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))); - } - - @Override - public Locator getByText(Pattern text, GetByTextOptions options) { - return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); - } - - @Override - public Locator getByTitle(String text, GetByTitleOptions options) { - return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); - } - - @Override - public Locator getByTitle(Pattern text, GetByTitleOptions options) { - return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); - } - - @Override - public FrameLocator last() { - return new FrameLocatorImpl(frame, nthSelector(-1)); - } - - @Override - public Locator locator(String selector, LocatorOptions options) { - return new LocatorImpl(frame, childSelector(selector), convertType(options, Locator.LocatorOptions.class)); - } - - @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); - } - - @Override - public FrameLocator nth(int index) { - return new FrameLocatorImpl(frame, nthSelector(index)); - } - - @Override - public Locator owner() { - return new LocatorImpl(frame, frameSelector, null); - } -} 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/JSHandleImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java deleted file mode 100644 index 67c0a5459..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java +++ /dev/null @@ -1,103 +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.JsonElement; -import com.google.gson.JsonObject; -import com.microsoft.playwright.ElementHandle; -import com.microsoft.playwright.JSHandle; - -import java.util.HashMap; -import java.util.Map; - -import static com.microsoft.playwright.impl.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(); - } - - @Override - public ElementHandle asElement() { - return null; - } - - @Override - public void dispose() { - try { - channel.dispose(NO_TIMEOUT); - } catch (TargetClosedError e) { - } - } - - @Override - public Object evaluate(String pageFunction, Object arg) { - JSHandleEvaluateExpressionParams params = new JSHandleEvaluateExpressionParams(); - params.expression = pageFunction; - params.arg = serializeArgument(arg); - return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).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; - } - - @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; - } - - @Override - public JSHandle getProperty(String propertyName) { - JSHandleGetPropertyParams params = new JSHandleGetPropertyParams(); - params.name = propertyName; - return channel.getProperty(params, NO_TIMEOUT).handle; - } - - @Override - public Object jsonValue() { - return deserialize(channel.jsonValue(NO_TIMEOUT).value); - } - - @Override - void handleEvent(String event, JsonObject parameters) { - if ("previewUpdated".equals(event)) { - preview = parameters.get("preview").getAsString(); - } - super.handleEvent(event, parameters); - } - - @Override - public String toString() { - return preview; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java deleted file mode 100644 index 5c418c3fa..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ /dev/null @@ -1,733 +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.*; -import com.microsoft.playwright.options.*; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.function.BiFunction; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.microsoft.playwright.impl.LocatorUtils.*; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Serialization.serializeArgument; -import static com.microsoft.playwright.impl.Utils.convertType; - -class LocatorImpl implements Locator { - final FrameImpl frame; - final String selector; - private String stringRepresentation; - - LocatorImpl(FrameImpl frame, String selector, LocatorOptions options) { - this(frame, selector, options, null); - } - - private LocatorImpl(FrameImpl frame, String selector, LocatorOptions options, Boolean visible) { - 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(); - } - } - }); - } - - @Override - public List all() { - List result = new ArrayList<>(); - int count = this.count(); - for (int i = 0; i < count; i++) { - result.add(nth(i)); - } - return result; - } - - @Override - public List allInnerTexts() { - return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.innerText)"); - } - - @Override - public List allTextContents() { - return (List) frame.evalOnSelectorAll(selector, "ee => ee.map(e => e.textContent || '')"); - } - - @Override - public Locator normalize() { - FrameResolveSelectorParams params = new FrameResolveSelectorParams(); - 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; - } - 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); - } - - @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; - } - - @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 BoundingBox boundingBox(BoundingBoxOptions options) { - return withElement((h, o) -> h.boundingBox(), options, "Bounding Box"); - } - - @Override - public void check(CheckOptions options) { - 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))); - } - - @Override - public void click(ClickOptions options) { - 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; - } - - @Override - public void dblclick(DblclickOptions options) { - if (options == null) { - options = new DblclickOptions(); - } - frame.dblclickImpl(selector, convertType(options, Frame.DblclickOptions.class).setStrict(true), options.steps); - } - - @Override - public void dispatchEvent(String type, Object eventInit, DispatchEventOptions options) { - 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) { - 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); - } - - @Override - public FrameLocator contentFrame() { - return new FrameLocatorImpl(frame, selector); - } - - @Override - public Object evaluate(String expression, Object arg, EvaluateOptions options) { - return withElement((h, o) -> h.evaluate(expression, arg), options, "Evaluate"); - } - - @Override - public Object evaluateAll(String expression, Object arg) { - return frame.evalOnSelectorAll(selector, expression, arg); - } - - @Override - public JSHandle evaluateHandle(String expression, Object arg, EvaluateHandleOptions options) { - return withElement((h, o) -> h.evaluateHandle(expression, arg), options, "Evaluate"); - } - - @Override - public void fill(String value, FillOptions options) { - 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); - } - - @Override - public Locator first() { - return new LocatorImpl(frame, selector + " >> nth=0", null); - } - - @Override - public Locator visible() { - return new LocatorImpl(frame, selector, null, true); - } - - @Override - public void focus(FocusOptions options) { - if (options == null) { - options = new FocusOptions(); - } - frame.focus(selector, convertType(options, Frame.FocusOptions.class).setStrict(true)); - } - - @Override - public FrameLocatorImpl frameLocator(String selector) { - return new FrameLocatorImpl(frame, this.selector + " >> " + selector); - } - - @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 Locator getByAltText(String text, GetByAltTextOptions options) { - return locator(getByAltTextSelector(text, options)); - } - - @Override - public Locator getByAltText(Pattern text, GetByAltTextOptions options) { - return locator(getByAltTextSelector(text, options)); - } - - @Override - public Locator getByLabel(String text, GetByLabelOptions options) { - return locator(getByLabelSelector(text, options)); - } - - @Override - public Locator getByLabel(Pattern text, GetByLabelOptions options) { - return locator(getByLabelSelector(text, options)); - } - - @Override - public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { - return locator(getByPlaceholderSelector(text, options)); - } - - @Override - public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { - return locator(getByPlaceholderSelector(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)); - } - - @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, 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 void drop(DropPayload payload, DropOptions options) { - frame.dropImpl(selector, payload, options); - } - - @Override - public AutoCloseable highlight(HighlightOptions options) { - String style = options == null ? null : options.style; - frame.highlightImpl(selector, style); - return new DisposableStub(this::hideHighlight); - } - - @Override - public void hideHighlight() { - frame.hideHighlightImpl(selector); - } - - @Override - public void hover(HoverOptions options) { - 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) { - options = new InnerHTMLOptions(); - } - return frame.innerHTML(selector, convertType(options, Frame.InnerHTMLOptions.class).setStrict(true)); - } - - @Override - public String innerText(InnerTextOptions options) { - 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) { - options = new InputValueOptions(); - } - return frame.inputValue(selector, convertType(options, Frame.InputValueOptions.class).setStrict(true)); - } - - @Override - public boolean isChecked(IsCheckedOptions options) { - 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) { - options = new IsDisabledOptions(); - } - return frame.isDisabled(selector, convertType(options, Frame.IsDisabledOptions.class).setStrict(true)); - } - - @Override - public boolean isEditable(IsEditableOptions options) { - 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) { - options = new IsEnabledOptions(); - } - return frame.isEnabled(selector, convertType(options, Frame.IsEnabledOptions.class).setStrict(true)); - } - - @Override - public boolean isHidden(IsHiddenOptions options) { - 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) { - 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) { - 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)); - } - - @Override - public byte[] screenshot(ScreenshotOptions options) { - return withElement((h, o) -> h.screenshot(o), convertType(options, ElementHandle.ScreenshotOptions.class), "Screenshot"); - } - - @Override - public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { - withElement((h, o) -> { - h.scrollIntoViewIfNeeded(o); - return null; - }, convertType(options, ElementHandle.ScrollIntoViewIfNeededOptions.class), "Scroll into view"); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @Override - public void selectText(SelectTextOptions options) { - withElement((h, o) -> { - h.selectText(o); - return null; - }, convertType(options, ElementHandle.SelectTextOptions.class), "Select text"); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @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)); - } - - @Override - public void tap(TapOptions options) { - 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) { - 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) { - options = new TypeOptions(); - } - frame.type(selector, text, convertType(options, Frame.TypeOptions.class).setStrict(true)); - } - - @Override - public void uncheck(UncheckOptions options) { - if (options == null) { - options = new UncheckOptions(); - } - frame.uncheck(selector, convertType(options, Frame.UncheckOptions.class).setStrict(true)); - } - - @Override - public void waitFor(WaitForOptions options) { - if (options == null) { - options = new WaitForOptions(); - } - frame.waitForSelectorImpl(selector, convertType(options, Frame.WaitForSelectorOptions.class).setStrict(true), true); - } - - @Override - public void waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { - FrameWaitForFunctionParams params = new FrameWaitForFunctionParams(); - params.selector = selector; - params.strict = true; - params.expression = expression; - params.arg = serializeArgument(arg); - frame.channel.waitForFunction(params, frame.timeout(options == null ? null : options.timeout)); - } - - @Override - public Locator within(Locator locator) { - return locator.locator(this); - } - - @Override - public String toString() { - if (stringRepresentation != null) { - return stringRepresentation; - } - String description = description(); - if (description != null) { - return description; - } - return "Locator@" + selector; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof LocatorImpl)) { - return false; - } - LocatorImpl locator = (LocatorImpl) obj; - return frame.equals(locator.frame) && selector.equals(locator.selector); - } - - @Override - 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()); - result.addProperty("selector", selector); - return result; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java deleted file mode 100644 index ebf0e7769..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ /dev/null @@ -1,1594 +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.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.microsoft.playwright.*; -import com.microsoft.playwright.options.*; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.*; -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; - - -public class PageImpl extends ChannelOwner implements Page { - final BrowserContextImpl browserContext; - 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<>(); - - private static class LocatorHandler { - private final Locator locator; - private final Consumer handler; - private Integer times; - - LocatorHandler(Locator locator, Consumer handler, Integer times) { - this.locator = locator; - this.handler = handler; - this.times = times; - } - - boolean call() { - if (shouldRemove()) { - return true; - } - if (times != null) { - --times; - } - handler.accept(locator); - return shouldRemove(); - } - - private boolean shouldRemove() { - return times != null && times == 0; - } - } - - 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; - - PageImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - Map mapping = new HashMap<>(); - mapping.put(Events.Page.CONSOLE, "console"); - mapping.put(Events.Page.DIALOG, "dialog"); - mapping.put(Events.Page.DIALOG_CLOSED, "dialogClosed"); - mapping.put(Events.Page.REQUEST, "request"); - mapping.put(Events.Page.RESPONSE, "response"); - mapping.put(Events.Page.REQUEST_FINISHED, "requestFinished"); - 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); - } - 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; - } - 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()); - } - if (binding != null) { - try { - bindingCall.call(binding); - } catch (RuntimeException e) { - if (!isSafeCloseError(e.getMessage())) { - logWithTimestamp(e.getMessage()); - } - } - } - } 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); - } - 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); - } - 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) { - 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) { - browserContext.handleRoute(route); - } - } else if ("webSocketRoute".equals(event)) { - WebSocketRouteImpl route = connection.getExistingObject(params.getAsJsonObject("webSocketRoute").get("guid").getAsString()); - if (!webSocketRoutes.handle(route)) { - browserContext.handleWebSocketRoute(route); - } - } else if ("crash".equals(event)) { - emit(Events.Page.CRASH, this); - } else if ("close".equals(event)) { - didClose(); - } else if ("screencastFrame".equals(event)) { - screencast.handleScreencastFrame(params); - } - } - - void notifyPopup(PageImpl popup) { - emit(Events.Page.POPUP, popup); - } - - void didClose() { - isClosed = true; - browserContext.pages.remove(this); - emit(Events.Page.CLOSE, this); - browserContext.notifyPageClose(this); - } - - private String effectiveCloseReason() { - if (closeReason != null) { - return closeReason; - } - return browserContext.effectiveCloseReason(); - } - - TargetClosedError closeErrorWithReason() { - return new TargetClosedError(effectiveCloseReason()); - } - - @Override - public void onClose(Consumer handler) { - on(Events.Page.CLOSE, handler); - } - - @Override - public void offClose(Consumer handler) { - off(Events.Page.CLOSE, handler); - } - - @Override - public void onConsoleMessage(Consumer handler) { - on(Events.Page.CONSOLE, handler); - } - - @Override - public void offConsoleMessage(Consumer handler) { - off(Events.Page.CONSOLE, handler); - } - - @Override - public void onCrash(Consumer handler) { - on(Events.Page.CRASH, handler); - } - - @Override - public void offCrash(Consumer handler) { - off(Events.Page.CRASH, handler); - } - - @Override - public void onDialog(Consumer

handler) { - on(Events.Page.DIALOG, handler); - } - - @Override - public void offDialog(Consumer handler) { - off(Events.Page.DIALOG, handler); - } - - @Override - public void onDialogClosed(Consumer handler) { - on(Events.Page.DIALOG_CLOSED, handler); - } - - @Override - public void offDialogClosed(Consumer handler) { - off(Events.Page.DIALOG_CLOSED, handler); - } - - @Override - public void onDOMContentLoaded(Consumer handler) { - on(Events.Page.DOM_CONTENT_LOADED, handler); - } - - @Override - public void offDOMContentLoaded(Consumer handler) { - off(Events.Page.DOM_CONTENT_LOADED, handler); - } - - @Override - public void onDownload(Consumer handler) { - on(Events.Page.DOWNLOAD, handler); - } - - @Override - public void offDownload(Consumer handler) { - off(Events.Page.DOWNLOAD, handler); - } - - @Override - public void onFileChooser(Consumer handler) { - on(Events.Page.FILE_CHOOSER, handler); - } - - @Override - public void offFileChooser(Consumer handler) { - off(Events.Page.FILE_CHOOSER, handler); - } - - @Override - public void onFrameAttached(Consumer handler) { - on(Events.Page.FRAME_ATTACHED, handler); - } - - @Override - public void offFrameAttached(Consumer handler) { - off(Events.Page.FRAME_ATTACHED, handler); - } - - @Override - public void onFrameDetached(Consumer handler) { - on(Events.Page.FRAME_DETACHED, handler); - } - - @Override - public void offFrameDetached(Consumer handler) { - off(Events.Page.FRAME_DETACHED, handler); - } - - @Override - public void onFrameNavigated(Consumer handler) { - on(Events.Page.FRAME_NAVIGATED, handler); - } - - @Override - public void offFrameNavigated(Consumer handler) { - off(Events.Page.FRAME_NAVIGATED, handler); - } - - @Override - public void onLoad(Consumer handler) { - on(Events.Page.LOAD, handler); - } - - @Override - public void offLoad(Consumer handler) { - off(Events.Page.LOAD, handler); - } - - @Override - public void onPageError(Consumer handler) { - on(Events.Page.PAGE_ERROR, handler); - } - - @Override - public void offPageError(Consumer handler) { - off(Events.Page.PAGE_ERROR, handler); - } - - @Override - public void onPopup(Consumer handler) { - on(Events.Page.POPUP, handler); - } - - @Override - public void offPopup(Consumer handler) { - off(Events.Page.POPUP, handler); - } - - @Override - public void onRequest(Consumer handler) { - on(Events.Page.REQUEST, handler); - } - - @Override - public void offRequest(Consumer handler) { - off(Events.Page.REQUEST, handler); - } - - @Override - public void onRequestFailed(Consumer handler) { - on(Events.Page.REQUEST_FAILED, handler); - } - - @Override - public void offRequestFailed(Consumer handler) { - off(Events.Page.REQUEST_FAILED, handler); - } - - @Override - public void onRequestFinished(Consumer handler) { - on(Events.Page.REQUEST_FINISHED, handler); - } - - @Override - public void offRequestFinished(Consumer handler) { - off(Events.Page.REQUEST_FINISHED, handler); - } - - @Override - public void onResponse(Consumer handler) { - on(Events.Page.RESPONSE, handler); - } - - @Override - public void offResponse(Consumer handler) { - off(Events.Page.RESPONSE, handler); - } - - @Override - public void onWebSocket(Consumer handler) { - on(Events.Page.WEB_SOCKET, handler); - } - - @Override - public void offWebSocket(Consumer handler) { - off(Events.Page.WEB_SOCKET, handler); - } - - @Override - public void onWorker(Consumer handler) { - on(Events.Page.WORKER, handler); - } - - @Override - public void offWorker(Consumer handler) { - off(Events.Page.WORKER, handler); - } - - @Override - public ClockImpl clock() { - return browserContext.clock(); - } - - @Override - public Page waitForClose(WaitForCloseOptions options, Runnable code) { - if (options == null) { - options = new WaitForCloseOptions(); - } - return waitForEvent(Events.Page.CLOSE, null, options.timeout, "waiting for event \"close\"", code); - } - - @Override - public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - if (options == null) { - options = new WaitForConsoleMessageOptions(); - } - return waitForEvent(Events.Page.CONSOLE, options.predicate, options.timeout, "waiting for event \"console\"", code); - } - - @Override - public Download waitForDownload(WaitForDownloadOptions options, Runnable code) { - if (options == null) { - options = new WaitForDownloadOptions(); - } - return waitForEvent(Events.Page.DOWNLOAD, options.predicate, options.timeout, "waiting for event \"download\"", code); - } - - @Override - public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable code) { - // TODO: enable/disable file chooser interception - if (options == null) { - options = new WaitForFileChooserOptions(); - } - return waitForEvent(Events.Page.FILE_CHOOSER, options.predicate, options.timeout, "waiting for event \"filechooser\"", code); - } - - @Override - public Page waitForPopup(WaitForPopupOptions options, Runnable code) { - if (options == null) { - options = new WaitForPopupOptions(); - } - return waitForEvent(Events.Page.POPUP, options.predicate, options.timeout, "waiting for event \"popup\"", code); - } - - @Override - public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable code) { - if (options == null) { - options = new WaitForWebSocketOptions(); - } - return waitForEvent(Events.Page.WEB_SOCKET, options.predicate, options.timeout, "waiting for event \"websocket\"", code); - } - - @Override - public Worker waitForWorker(WaitForWorkerOptions options, Runnable code) { - if (options == null) { - options = new WaitForWorkerOptions(); - } - return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, "waiting for event \"worker\"", code); - } - - 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) + "\""; - } - return null; - } - - 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; - } - - // _waitForEvent in page.ts - private T waitForEvent(String event, Predicate predicate, Double timeout, String logLine, Runnable code) { - double timeoutMs = timeoutSettings.timeout(timeout); - Waiter waiter = Waiter.createForEvent(this, event); - if (logLine != null) { - waiter.log(logLine); - } - waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); - if (!Events.Page.CRASH.equals(event)) { - waiter.rejectOnEvent(this, Events.Page.CRASH, () -> new PlaywrightException("Page crashed")); - } - if (!Events.Page.CLOSE.equals(event)) { - waiter.rejectOnEvent(this, Events.Page.CLOSE, () -> closeErrorWithReason()); - } - T result = waiter.waitForEvent(this, event, predicate, code); - waiter.dispose(); - return result; - } - - @Override - public void close(CloseOptions options) { - if (options == null) { - options = new CloseOptions(); - } - 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; - } - } - - @Override - public ElementHandle querySelector(String selector, QuerySelectorOptions options) { - return mainFrame.querySelector( - selector, convertType(options, Frame.QuerySelectorOptions.class)); - } - - @Override - public List querySelectorAll(String selector) { - return mainFrame.querySelectorAll(selector); - } - - @Override - public List requests() { - PageRequestsResult json = channel.requests(NO_TIMEOUT); - return new ArrayList(json.requests); - } - - @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)); - } - - @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) { - } - } - } - } - - 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); - } - } - - @Override - public String ariaSnapshot(AriaSnapshotOptions options) { - if (options == null) { - options = new AriaSnapshotOptions(); - } - FrameAriaSnapshotParams params = toProtocol(options, FrameAriaSnapshotParams.class); - return mainFrame.channel.ariaSnapshot(params, mainFrame.timeout(options.timeout)).snapshot; - } - - @Override - public Object evalOnSelector(String selector, String pageFunction, Object arg, EvalOnSelectorOptions options) { - return mainFrame.evalOnSelectorImpl( - selector, pageFunction, arg, convertType(options, Frame.EvalOnSelectorOptions.class)); - } - - @Override - public Object evalOnSelectorAll(String selector, String pageFunction, Object arg) { - return mainFrame.evalOnSelectorAllImpl(selector, pageFunction, arg); - } - - @Override - public AutoCloseable addInitScript(String script) { - return addInitScriptImpl(script); - } - - @Override - public AutoCloseable addInitScript(Path path) { - try { - byte[] bytes = readAllBytes(path); - String script = ClientHelper.addSourceUrlToScript(new String(bytes, UTF_8), path); - return addInitScriptImpl(script); - } catch (IOException e) { - throw new PlaywrightException("Failed to read script from file", e); - } - } - - private AutoCloseable addInitScriptImpl(String script) { - PageAddInitScriptParams params = new PageAddInitScriptParams(); - params.source = script; - return channel.addInitScript(params, NO_TIMEOUT).disposable; - } - - @Override - public ElementHandle addScriptTag(AddScriptTagOptions options) { - return mainFrame.addScriptTagImpl(convertType(options, Frame.AddScriptTagOptions.class)); - } - - @Override - public ElementHandle addStyleTag(AddStyleTagOptions options) { - return mainFrame.addStyleTagImpl(convertType(options, Frame.AddStyleTagOptions.class)); - } - - @Override - public void bringToFront() { - channel.bringToFront(NO_TIMEOUT); - } - - @Override - public void check(String selector, CheckOptions options) { - mainFrame.check(selector, convertType(options, Frame.CheckOptions.class)); - } - - @Override - public void click(String selector, ClickOptions options) { - mainFrame.clickImpl(selector, convertType(options, Frame.ClickOptions.class), null); - } - - @Override - public String content(ContentOptions options) { - return mainFrame.content(convertType(options, Frame.ContentOptions.class)); - } - - @Override - public BrowserContextImpl context() { - return browserContext; - } - - @Override - public void dblclick(String selector, DblclickOptions options) { - mainFrame.dblclickImpl(selector, convertType(options, Frame.DblclickOptions.class), null); - } - - @Override - public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { - mainFrame.dispatchEvent(selector, type, eventInit, convertType(options, Frame.DispatchEventOptions.class)); - } - - @Override - public void emulateMedia(EmulateMediaOptions options) { - emulateMediaImpl(options); - } - - private void emulateMediaImpl(EmulateMediaOptions options) { - if (options == null) { - options = new EmulateMediaOptions(); - } - PageEmulateMediaParams params = toProtocol(options, PageEmulateMediaParams.class); - channel.emulateMedia(params, NO_TIMEOUT); - } - - @Override - public Object evaluate(String expression, Object arg) { - return mainFrame.evaluate(expression, arg); - } - - @Override - public JSHandle evaluateHandle(String pageFunction, Object arg) { - return mainFrame.evaluateHandle(pageFunction, arg); - } - - @Override - public AutoCloseable exposeBinding(String name, BindingCallback playwrightBinding) { - return exposeBindingImpl(name, playwrightBinding); - } - - 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 AutoCloseable exposeFunction(String name, FunctionCallback playwrightFunction) { - return exposeBindingImpl(name, (BindingCallback.Source source, Object... args) -> playwrightFunction.call(args)); - } - - @Override - public void fill(String selector, String value, FillOptions options) { - mainFrame.fill(selector, value, convertType(options, Frame.FillOptions.class)); - } - - @Override - public void focus(String selector, FocusOptions options) { - mainFrame.focus(selector, convertType(options, Frame.FocusOptions.class)); - } - - @Override - public Frame frame(String name) { - for (Frame frame : frames) { - if (name.equals(frame.name())) { - return frame; - } - } - return null; - } - - @Override - public Frame frameByUrl(String glob) { - return frameFor(UrlMatcher.forGlob(browserContext.baseUrl(), glob, this.connection.localUtils(), false)); - } - - @Override - public Frame frameByUrl(Pattern pattern) { - return frameFor(new UrlMatcher(pattern)); - } - - @Override - public Frame frameByUrl(Predicate predicate) { - return frameFor(new UrlMatcher(predicate)); - } - - @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; - } - - @Override - public List frames() { - return new ArrayList<>(frames); - } - - @Override - public String getAttribute(String selector, String name, GetAttributeOptions options) { - return mainFrame.getAttributeImpl(selector, name, convertType(options, Frame.GetAttributeOptions.class)); - } - - @Override - public Locator getByAltText(String text, GetByAltTextOptions options) { - 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)); - } - - @Override - public Locator getByLabel(String text, GetByLabelOptions options) { - 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)); - } - - @Override - public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { - 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)); - } - - @Override - 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)); - } - - @Override - public Locator getByText(Pattern text, GetByTextOptions options) { - 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)); - } - - @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; - } - - @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; - } - - @Override - public void requestGC() { - channel.requestGC(NO_TIMEOUT); - } - - @Override - public ResponseImpl navigate(String url, NavigateOptions options) { - return mainFrame.navigateImpl(url, convertType(options, Frame.NavigateOptions.class)); - } - - @Override - public void hover(String selector, HoverOptions options) { - mainFrame.hoverImpl(selector, convertType(options, Frame.HoverOptions.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); - } - - @Override - public String innerHTML(String selector, InnerHTMLOptions options) { - return mainFrame.innerHTMLImpl(selector, convertType(options, Frame.InnerHTMLOptions.class)); - } - - @Override - public String innerText(String selector, InnerTextOptions options) { - return mainFrame.innerTextImpl(selector, convertType(options, Frame.InnerTextOptions.class)); - } - - @Override - public String inputValue(String selector, InputValueOptions options) { - return mainFrame.inputValueImpl(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; - } - - @Override - public boolean isDisabled(String selector, IsDisabledOptions options) { - return mainFrame.isDisabledImpl(selector, convertType(options, Frame.IsDisabledOptions.class)); - } - - @Override - public boolean isEditable(String selector, IsEditableOptions options) { - return mainFrame.isEditableImpl(selector, convertType(options, Frame.IsEditableOptions.class)); - } - - @Override - public boolean isEnabled(String selector, IsEnabledOptions options) { - return mainFrame.isEnabledImpl(selector, convertType(options, Frame.IsEnabledOptions.class)); - } - - @Override - public boolean isHidden(String selector, IsHiddenOptions options) { - return mainFrame.isHiddenImpl(selector, convertType(options, Frame.IsHiddenOptions.class)); - } - - @Override - public boolean isVisible(String selector, IsVisibleOptions options) { - return mainFrame.isVisibleImpl(selector, convertType(options, Frame.IsVisibleOptions.class)); - } - - @Override - public Keyboard keyboard() { - return keyboard; - } - - @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; - } - - @Override - public void clearConsoleMessages() { - channel.clearConsoleMessages(NO_TIMEOUT); - } - - @Override - public void clearPageErrors() { - channel.clearPageErrors(NO_TIMEOUT); - } - - @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; - } - - @Override - public Locator locator(String selector, LocatorOptions options) { - return mainFrame.locator(selector, convertType(options, Frame.LocatorOptions.class)); - } - - @Override - public Frame mainFrame() { - return mainFrame; - } - - @Override - public WebMCP webmcp() { - return mainFrame.webmcp(); - } - - @Override - public void hideHighlight() { - channel.hideHighlight(NO_TIMEOUT); - } - - @Override - public Mouse mouse() { - return mouse; - } - - @Override - public PageImpl opener() { - if (opener == null || opener.isClosed()) { - return null; - } - return opener; - } - - @Override - public void cancelPickLocator() { - channel.cancelPickLocator(NO_TIMEOUT); - } - - @Override - public Locator pickLocator() { - PagePickLocatorResult result = channel.pickLocator(NO_TIMEOUT); - return new LocatorImpl(mainFrame, result.selector, null); - } - - @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); - } - } - - @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; - } - - @Override - public void press(String selector, String key, PressOptions options) { - mainFrame.pressImpl(selector, key, convertType(options, Frame.PressOptions.class)); - } - - @Override - public Response reload(ReloadOptions options) { - return reloadImpl(options); - } - - @Override - public APIRequestContextImpl request() { - return browserContext.request(); - } - - 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 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)); - } - - @Override - public AutoCloseable route(Pattern url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); - } - - @Override - public AutoCloseable route(Predicate url, Consumer handler, RouteOptions options) { - route(new UrlMatcher(url), handler, options); - return new DisposableStub(() -> unroute(url, handler)); - } - - @Override - public void routeFromHAR(Path har, RouteFromHAROptions options) { - if (options == null) { - options = new RouteFromHAROptions(); - } - if (options.update != null && options.update) { - browserContext.recordIntoHar(this, har, convertType(options, BrowserContext.RouteFromHAROptions.class), null); - return; - } - 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); - } - - @Override - public List selectOption(String selector, String value, SelectOptionOptions options) { - String[] values = value == null ? null : new String[]{ value }; - return selectOption(selector, values, options); - } - - @Override - public List selectOption(String selector, ElementHandle value, SelectOptionOptions options) { - ElementHandle[] values = value == null ? null : new ElementHandle[]{ value }; - return selectOption(selector, values, options); - } - - @Override - public List selectOption(String selector, String[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); - } - - @Override - public List selectOption(String selector, SelectOption value, SelectOptionOptions options) { - SelectOption[] values = value == null ? null : new SelectOption[]{value}; - return selectOption(selector, values, options); - } - - private byte[] screenshotImpl(ScreenshotOptions options) { - if (options == null) { - options = new ScreenshotOptions(); - } - if (options.type == null && options.path != null) { - options.type = Utils.screenshotTypeForPath(options.path); - } - 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); - } - return buffer; - } - - @Override - public List selectOption(String selector, SelectOption[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); - } - - @Override - public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { - return mainFrame.selectOptionImpl(selector, values, convertType(options, Frame.SelectOptionOptions.class)); - } - - @Override - public void setChecked(String selector, boolean checked, SetCheckedOptions options) { - mainFrame.setCheckedImpl(selector, checked, convertType(options, Frame.SetCheckedOptions.class)); - } - - @Override - public void setContent(String html, SetContentOptions options) { - mainFrame.setContent(html, convertType(options, Frame.SetContentOptions.class)); - } - - @Override - public void setDefaultNavigationTimeout(double timeout) { - timeoutSettings.setDefaultNavigationTimeout(timeout); - } - - @Override - public void setDefaultTimeout(double timeout) { - timeoutSettings.setDefaultTimeout(timeout); - } - - @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); - } - - @Override - public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { - setInputFiles(selector, new Path[]{files}, options); - } - - @Override - public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { - mainFrame.setInputFilesImpl(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); - } - - @Override - public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { - setInputFiles(selector, new FilePayload[]{files}, options); - } - - @Override - public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { - mainFrame.setInputFilesImpl(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); - } - - @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); - } - - @Override - public void tap(String selector, TapOptions options) { - mainFrame.tap(selector, convertType(options, Frame.TapOptions.class)); - } - - @Override - public String textContent(String selector, TextContentOptions options) { - return mainFrame.textContent(selector, convertType(options, Frame.TextContentOptions.class)); - } - - @Override - public String title() { - return mainFrame.title(); - } - - @Override - public Touchscreen touchscreen() { - return touchscreen; - } - - @Override - public Screencast screencast() { - return screencast; - } - - @Override - public WebStorage localStorage() { - return localStorage; - } - - @Override - public WebStorage sessionStorage() { - return sessionStorage; - } - - @Override - public void type(String selector, String text, TypeOptions options) { - mainFrame.type(selector, text, convertType(options, Frame.TypeOptions.class)); - } - - @Override - public void uncheck(String selector, UncheckOptions options) { - mainFrame.uncheck(selector, convertType(options, Frame.UncheckOptions.class)); - } - - @Override - public void unrouteAll() { - routes.removeAll(); - updateInterceptionPatterns(); - } - - @Override - public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), handler); - } - - @Override - public void unroute(Pattern url, Consumer handler) { - unroute(new UrlMatcher(url), 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(); - } - - private void updateInterceptionPatterns() { - channel.setNetworkInterceptionPatterns( - connection.protocolGson().fromJson(routes.interceptionPatterns(), PageSetNetworkInterceptionPatternsParams.class), NO_TIMEOUT); - } - - private void updateWebSocketInterceptionPatterns() { - channel.setWebSocketInterceptionPatterns( - connection.protocolGson().fromJson(webSocketRoutes.interceptionPatterns(), PageSetWebSocketInterceptionPatternsParams.class), NO_TIMEOUT); - } - - @Override - public String url() { - return mainFrame.url(); - } - - - @Override - public VideoImpl video() { - if (!browserContext.initializer.getAsJsonObject("options").has("recordVideo")) { - return null; - } - return video; - } - - @Override - public ViewportSize viewportSize() { - return viewport; - } - - Waitable createWaitableTimeout(Double timeout) { - return timeoutSettings.createWaitable(timeout); - } - - @Override - public JSHandle waitForFunction(String pageFunction, Object arg, WaitForFunctionOptions options) { - return mainFrame.waitForFunction(pageFunction, arg, convertType(options, Frame.WaitForFunctionOptions.class)); - } - - @Override - public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { - mainFrame.waitForLoadState(state, convertType(options, Frame.WaitForLoadStateOptions.class)); - } - - @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); - } - - void frameNavigated(FrameImpl frame) { - emit(Events.Page.FRAME_NAVIGATED, frame); - browserContext.notifyFrameNavigated(frame); - } - - Waitable createWaitForCloseHelper() { - return new WaitableRace(asList(new WaitablePageClose(), new WaitablePageCrash())); - } - - private class WaitablePageClose extends WaitableEvent { - WaitablePageClose() { - super(PageImpl.this, Events.Page.CLOSE); - } - - @Override - public T get() { - throw closeErrorWithReason(); - } - } - - private class WaitablePageCrash extends WaitableEvent { - WaitablePageCrash() { - super(PageImpl.this, Events.Page.CRASH); - } - - @Override - public T get() { - throw new TargetClosedError("Page crashed"); - } - } - - @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); - } - - @Override - public Request waitForRequest(Pattern urlPattern, WaitForRequestOptions options, Runnable code) { - return waitForRequest(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); - } - - @Override - public Request waitForRequest(Predicate predicate, WaitForRequestOptions options, Runnable code) { - return waitForRequest(null, predicate, null, options, code); - } - - 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 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); - } - - @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); - } - - @Override - public Response waitForResponse(Pattern urlPattern, WaitForResponseOptions options, Runnable code) { - return waitForResponse(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); - } - - @Override - public Response waitForResponse(Predicate predicate, WaitForResponseOptions options, Runnable code) { - return waitForResponse(null, predicate, null, options, code); - } - - 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 ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { - return mainFrame.waitForSelector(selector, convertType(options, Frame.WaitForSelectorOptions.class)); - } - - @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)); - } - - @Override - public void waitForTimeout(double timeout) { - mainFrame.waitForTimeout(timeout); - } - - @Override - public void waitForURL(String url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); - } - - @Override - public void waitForURL(Pattern url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); - } - - @Override - public void waitForURL(Predicate url, WaitForURLOptions options) { - mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); - } - - @Override - public List workers() { - return new ArrayList<>(workers); - } - - @Override - public void onceDialog(Consumer handler) { - onDialog(new Consumer() { - @Override - public void accept(Dialog dialog) { - try { - handler.accept(dialog); - } finally { - offDialog(this); - } - } - }); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java deleted file mode 100644 index 448d9a2a5..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ /dev/null @@ -1,135 +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.JsonArray; -import com.google.gson.JsonObject; -import com.microsoft.playwright.APIRequest; -import com.microsoft.playwright.Playwright; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.Selectors; -import com.microsoft.playwright.impl.driver.Driver; - -import java.io.IOException; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -public class PlaywrightImpl extends ChannelOwner implements Playwright { - private Process driverProcess; - - public static PlaywrightImpl create(CreateOptions options) { - return createImpl(options, false); - } - - public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewDriverInstanceForTests) { - Map env = Collections.emptyMap(); - if (options != null && options.env != null) { - env = options.env; - } - Driver driver = forceNewDriverInstanceForTests ? - Driver.createAndInstall(env, true) : - 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. - pb.environment().putAll(env); - pb.command().add("run-driver"); - pb.redirectError(ProcessBuilder.Redirect.INHERIT); - Process p = pb.start(); - Connection connection = new Connection(new PipeTransport(p.getInputStream(), p.getOutputStream()), env); - PlaywrightImpl result = connection.initializePlaywright(); - result.driverProcess = p; - return result; - } catch (IOException e) { - throw new PlaywrightException("Failed to launch driver", e); - } - } - - 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(); - } - - public JsonArray deviceDescriptors() { - return localUtils().deviceDescriptors(); - } - - @Override - public BrowserTypeImpl chromium() { - return chromium; - } - - @Override - public BrowserTypeImpl firefox() { - return firefox; - } - - @Override - public APIRequest request() { - return apiRequest; - } - - @Override - public BrowserTypeImpl webkit() { - return webkit; - } - - @Override - public Selectors selectors() { - return selectors; - } - - @Override - public void close() { - try { - connection.close(); - // playwright-cli will exit when its stdin is closed, we 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"); - } - } catch (IOException e) { - throw new PlaywrightException("Failed to terminate", e); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new PlaywrightException("Operation interrupted", e); - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java deleted file mode 100644 index cdb3d0f5a..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java +++ /dev/null @@ -1,67 +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.options.HttpHeader; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -class RawHeaders { - private final List headersArray; - private final Map> headersMap = new LinkedHashMap<>(); - - RawHeaders(List headers) { - headersArray = headers; - for (HttpHeader h: headers) { - String name = h.name.toLowerCase(); - List values = headersMap.get(name); - if (values == null) { - values = new ArrayList<>(); - headersMap.put(name, values); - } - values.add(h.value); - } - } - - String get(String name) { - List values = getAll(name); - if (values == null) { - return null; - } - return String.join("set-cookie".equals(name.toLowerCase()) ? "\n" : ", ", values); - } - - List getAll(String name) { - return headersMap.get(name.toLowerCase()); - } - - Map headers() { - Map result = new LinkedHashMap<>(); - for (String name: headersMap.keySet()) { - result.put(name, get(name)); - } - return result; - } - - List headersArray() { - return headersArray; - } - -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java b/playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java deleted file mode 100644 index 05941a86e..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RemoteBrowser.java +++ /dev/null @@ -1,29 +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.JsonObject; - -public class RemoteBrowser extends ChannelOwner { - RemoteBrowser(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } - - BrowserImpl browser() { - return connection.getExistingObject(initializer.getAsJsonObject("browser").get("guid").getAsString()); - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java deleted file mode 100644 index ef97945dc..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java +++ /dev/null @@ -1,261 +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.JsonArray; -import com.google.gson.JsonObject; -import com.microsoft.playwright.PlaywrightException; -import com.microsoft.playwright.Request; -import com.microsoft.playwright.options.HttpHeader; -import com.microsoft.playwright.options.Sizes; -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 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; - - static class FallbackOverrides { - String url; - String method; - byte[] postData; - Map headers; - } - - final RequestChannel channel = new RequestChannel(this); - - 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; - } - } - - @Override - public ResponseImpl existingResponse() { - return existingResponse; - } - - @Override - public Map allHeaders() { - return getRawHeaders().headers(); - } - - @Override - public String failure() { - return failure; - } - - PageImpl safePage() { - return frame == null ? null : frame.page; - } - - @Override - public FrameImpl frame() { - if (frame == null) { - throw new PlaywrightException("Service Worker requests do not have an associated frame."); - } - 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 frame; - } - - @Override - public Map headers() { - if (fallbackOverrides != null && fallbackOverrides.headers != null) { - return new RawHeaders(Utils.toHeadersList(fallbackOverrides.headers)).headers(); - } - return headers.headers(); - } - - @Override - public List headersArray() { - return getRawHeaders().headersArray(); - } - - @Override - public String headerValue(String name) { - return getRawHeaders().get(name); - } - - @Override - public boolean isNavigationRequest() { - return initializer.get("isNavigationRequest").getAsBoolean(); - } - - @Override - public String method() { - if (fallbackOverrides != null && fallbackOverrides.method != null) { - return fallbackOverrides.method; - } - return initializer.get("method").getAsString(); - } - - @Override - public String postData() { - byte[] buffer = postDataBuffer(); - if (buffer == null) { - return null; - } - return new String(buffer, StandardCharsets.UTF_8); - } - - @Override - public byte[] postDataBuffer() { - if (fallbackOverrides != null && fallbackOverrides.postData != null) { - return fallbackOverrides.postData; - } - return postData; - } - - @Override - public Request redirectedFrom() { - return redirectedFrom; - } - - @Override - public Request redirectedTo() { - return redirectedTo; - } - - @Override - public String resourceType() { - return initializer.get("resourceType").getAsString(); - } - - @Override - public ResponseImpl response() { - return channel.response(NO_TIMEOUT).response; - } - - @Override - public Sizes sizes() { - ResponseImpl response = response(); - if (response == null) { - throw new PlaywrightException("Unable to fetch sizes for failed request"); - } - RequestSizes s = 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; - 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) { - timing.responseStart = responseEndTiming; - } - } - - void applyFallbackOverrides(FallbackOverrides overrides) { - if (fallbackOverrides == null) { - fallbackOverrides = new FallbackOverrides(); - } - if (overrides.url != null) { - fallbackOverrides.url = overrides.url; - } - if (overrides.method != null) { - fallbackOverrides.method = overrides.method; - } - if (overrides.headers != null) { - fallbackOverrides.headers = overrides.headers; - } - if (overrides.postData != null) { - fallbackOverrides.postData = overrides.postData; - } - } - - FallbackOverrides fallbackOverridesForResume() { - return fallbackOverrides; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java deleted file mode 100644 index 559571cdf..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java +++ /dev/null @@ -1,190 +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.Frame; -import com.microsoft.playwright.Response; -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; - - final ResponseChannel channel = new ResponseChannel(this); - - 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); - } - - @Override - public Map allHeaders() { - return getRawHeaders().headers(); - } - - @Override - public byte[] body() { - return channel.body(NO_TIMEOUT).binary; - } - - @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(); - } - - @Override - public Frame frame() { - return request().frame(); - } - - @Override - public boolean fromServiceWorker() { - return initializer.get("fromServiceWorker").getAsBoolean(); - } - - @Override - public String httpVersion() { - return channel.httpVersion(NO_TIMEOUT).value; - } - - @Override - public Map headers() { - return headers.headers(); - } - - @Override - public List headersArray() { - return getRawHeaders().headersArray(); - } - - @Override - public String headerValue(String name) { - return getRawHeaders().get(name); - } - - @Override - public List headerValues(String name) { - return getRawHeaders().getAll(name); - } - - @Override - public boolean ok() { - return status() == 0 || (status() >= 200 && status() <= 299); - } - - @Override - public RequestImpl request() { - return 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; - } - - @Override - public ServerAddr serverAddr() { - RemoteAddr value = channel.serverAddr(NO_TIMEOUT).value; - if (value == null) { - return null; - } - ServerAddr result = new ServerAddr(); - result.ipAddress = value.ipAddress; - result.port = value.port; - return result; - } - - @Override - public int status() { - return initializer.get("status").getAsInt(); - } - - @Override - public String statusText() { - return initializer.get("statusText").getAsString(); - } - - @Override - public String text() { - return new String(body(), StandardCharsets.UTF_8); - } - - @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; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java deleted file mode 100644 index bb8f64171..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ /dev/null @@ -1,317 +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.JsonElement; -import com.google.gson.JsonObject; -import com.microsoft.playwright.*; -import com.microsoft.playwright.APIResponse; -import com.microsoft.playwright.options.RequestOptions; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static com.microsoft.playwright.impl.Utils.convertType; - -public class RouteImpl extends ChannelOwner implements Route { - private final RequestImpl request; - private boolean handled; - BrowserContextImpl browserContext; - boolean fallbackCalled; - boolean shouldResumeIfFallbackIsCalled; - - final RouteChannel channel = new RouteChannel(this); - - public RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - request = connection.getExistingObject(initializer.getAsJsonObject("request").get("guid").getAsString()); - } - - @Override - public void abort(String errorCode) { - handleRoute(() -> { - RouteAbortParams params = new RouteAbortParams(); - params.errorCode = errorCode; - raceWithTargetClose("abort", params); - }); - } - - boolean isHandled() { - return handled; - } - - @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)); - } - - private void handleRoute(Runnable callback) { - checkNotHandled(); - callback.run(); - handled = true; - } - - // 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(); - } - }))); - } - - @Override - public void fallback(FallbackOptions options) { - fallbackCalled = true; - if (handled) { - throw new PlaywrightException("Route is already handled!"); - } - applyOverrides(options); - if (shouldResumeIfFallbackIsCalled) { - continueAsFallback(); - } - } - - @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); - } - - 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); - } - - 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; - } - params.isFallback = isFallback; - return params; - } - - 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; - } - - 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; - } - - private static byte[] getPostDataBytes(Object postData) { - if (postData instanceof byte[]) { - return (byte[]) postData; - } - if (postData instanceof String) { - return ((String) postData).getBytes(StandardCharsets.UTF_8); - } - 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) { - if (options == null) { - options = new FulfillOptions(); - } - - Integer status = options.status; - Map headersOption = options.headers; - String fetchResponseUid = null; - - if (options.response != null) { - if (status == null) { - status = options.response.status(); - } - if (headersOption == null) { - headersOption = options.response.headers(); - } - } - 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; - isBase64 = false; - length = body.getBytes().length; - } else if (options.bodyBytes != null) { - body = Base64.getEncoder().encodeToString(options.bodyBytes); - 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()); - } - } - if (options.contentType != null) { - headers.put("content-type", options.contentType); - } else if (options.path != null) { - headers.put("content-type", Utils.mimeType(options.path)); - } - if (length != 0 && !headers.containsKey("content-length")) { - headers.put("content-length", Integer.toString(length)); - } - RouteFulfillParams params = new RouteFulfillParams(); - params.status = status; - params.headers = toNameValues(headers); - params.isBase64 = isBase64; - params.body = body; - params.fetchResponseUid = fetchResponseUid; - raceWithTargetClose("fulfill", params); - } - - @Override - public RequestImpl request() { - return request; - } - - void redirectNavigationRequest(String redirectURL) { - handleRoute(() -> { - RouteRedirectNavigationRequestParams params = new RouteRedirectNavigationRequestParams(); - params.url = redirectURL; - raceWithTargetClose("redirectNavigationRequest", params); - }); - } - - private void checkNotHandled() { - if (handled) { - throw new PlaywrightException("Route is already handled!"); - } - } - -} 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/TracingImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java deleted file mode 100644 index b9199199b..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ /dev/null @@ -1,328 +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.Tracing; -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.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 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; - } - } - - - final TracingChannel channel = new TracingChannel(this); - - 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; - } - } - - 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); - } - - @Override - public AutoCloseable startChunk(StartChunkOptions options) { - if (options == null) { - options = new StartChunkOptions(); - } - tracingStartChunk(options.name, options.title); - return new DisposableStub(this::stopChunk); - } - - @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); - params.name = name; - channel.tracingGroup(params, NO_TIMEOUT); - } - - @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); - } - - private void startCollectingStacks(String traceName) { - if (!isTracing) { - isTracing = true; - connection.setIsTracing(true); - } - stacksId = connection.localUtils().tracingStarted(tracesDir == null ? null : tracesDir.toString(), traceName); - } - - @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); - } - - @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); - } - - 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); - } - - @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"); - } - - 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; - } - - 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; - String harId = channel.harStart(params, NO_TIMEOUT).harId; - harRecorders.put(harId, new HarRecorder(har, contentPolicy)); - return harId; - } - - void exportHar(String harId) { - HarRecorder harParams = harRecorders.remove(harId); - if (harParams == null) { - return; - } - boolean isLocal = !connection.isRemote(); - boolean isZip = isZip(harParams.path); - - TracingHarExportParams params = new TracingHarExportParams(); - params.harId = harId; - if (isLocal) { - params.mode = "entries"; - TracingHarExportResult json = channel.harExport(params, NO_TIMEOUT); - if (!isZip) { - return; - } - connection.localUtils().zip(harParams.path, json.entries, null, false, false, java.util.Collections.emptyList()); - return; - } - - params.mode = "archive"; - TracingHarExportResult json = channel.harExport(params, NO_TIMEOUT); - ArtifactImpl artifact = json.artifact; - if (isZip) { - artifact.saveAs(harParams.path); - artifact.delete(); - return; - } - String tmpPath = harParams.path + ".tmp"; - artifact.saveAs(Paths.get(tmpPath)); - LocalUtilsHarUnzipParams unzipParams = new LocalUtilsHarUnzipParams(); - unzipParams.zipFile = tmpPath; - unzipParams.harFile = harParams.path.toString(); - connection.localUtils().channel.harUnzip(unzipParams, NO_TIMEOUT); - artifact.delete(); - } - - void exportAllHars() { - for (String harId : new ArrayList<>(harRecorders.keySet())) { - exportHar(harId); - } - } - - void setTracesDir(Path tracesDir) { - this.tracesDir = tracesDir; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java deleted file mode 100644 index 546a02537..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.WebSocketFrame; - -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -class WebSocketFrameImpl implements WebSocketFrame { - private byte[] bytes; - private String text; - - WebSocketFrameImpl(String payload, boolean isBase64) { - if (isBase64) { - bytes = Base64.getDecoder().decode(payload); - } else { - text = payload; - } - } - - @Override - public byte[] binary() { - return bytes; - } - - @Override - public String text() { - return text; - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java deleted file mode 100644 index 0f5b9df1f..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java +++ /dev/null @@ -1,162 +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.WebSocket; -import com.microsoft.playwright.WebSocketFrame; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Predicate; - -public class WebSocketImpl extends ChannelOwner implements WebSocket { - private final PageImpl page; - private boolean isClosed; - - final WebSocketChannel channel = new WebSocketChannel(this); - - WebSocketImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - page = (PageImpl) parent; - } - - @Override - public void onClose(Consumer handler) { - on(Events.WebSocket.CLOSE, handler); - } - - @Override - public void offClose(Consumer handler) { - off(Events.WebSocket.CLOSE, handler); - } - - @Override - public void onFrameReceived(Consumer handler) { - on(Events.WebSocket.FRAME_RECEIVED, handler); - } - - @Override - public void offFrameReceived(Consumer handler) { - off(Events.WebSocket.FRAME_RECEIVED, handler); - } - - @Override - public void onFrameSent(Consumer handler) { - on(Events.WebSocket.FRAME_SENT, handler); - } - - @Override - public void offFrameSent(Consumer handler) { - off(Events.WebSocket.FRAME_SENT, handler); - } - - @Override - public void onSocketError(Consumer handler) { - on(Events.WebSocket.ERROR, handler); - } - - @Override - public void offSocketError(Consumer handler) { - off(Events.WebSocket.ERROR, handler); - } - - @Override - public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable code) { - if (options == null) { - options = new WaitForFrameReceivedOptions(); - } - return waitForEvent(Events.WebSocket.FRAME_RECEIVED, options.predicate, options.timeout, code); - } - - @Override - public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable code) { - if (options == null) { - options = new WaitForFrameSentOptions(); - } - return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, code); - } - - @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); - } - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java deleted file mode 100644 index 1003f0a61..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java +++ /dev/null @@ -1,215 +0,0 @@ -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 java.util.ArrayList; -import java.util.Base64; -import java.util.List; -import java.util.function.BiConsumer; -import java.util.function.Consumer; - -import static com.microsoft.playwright.impl.Utils.toProtocol; - -public class WebSocketRouteImpl extends ChannelOwner implements WebSocketRoute { - - 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(); - } - 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 onMessage(Consumer handler) { - onServerMessage = handler; - } - - @Override - public void send(String message) { - WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); - params.message = message; - params.isBase64 = false; - sendMessageAsync("sendToServer", params); - } - - @Override - public void send(byte[] message) { - WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); - params.message = Base64.getEncoder().encodeToString(message); - params.isBase64 = true; - sendMessageAsync("sendToServer", params); - } - - @Override - public String url() { - return initializer.get("url").getAsString(); - } - - @Override - public List protocols() { - return readProtocols(); - } - }; - - final WebSocketRouteChannel channel = new WebSocketRouteChannel(this); - - WebSocketRouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { - super(parent, type, guid, initializer); - } - - @Override - public void close(CloseOptions options) { - if (options == null) { - options = new CloseOptions(); - } - WebSocketRouteClosePageParams params = toProtocol(options, WebSocketRouteClosePageParams.class); - params.wasClean = true; - sendMessageAsync("closePage", params); - } - - @Override - public WebSocketRoute connectToServer() { - if (connected) { - throw new PlaywrightException("Already connected to the server"); - } - connected = true; - sendMessageAsync("connect", new WebSocketRouteConnectParams()); - return server; - } - - @Override - public void onClose(BiConsumer handler) { - onPageClose = handler; - } - - @Override - public void onMessage(Consumer handler) { - onPageMessage = handler; - } - - @Override - public void send(String message) { - WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); - params.message = message; - params.isBase64 = false; - sendMessageAsync("sendToPage", params); - } - - @Override - public void send(byte[] message) { - WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); - params.message = Base64.getEncoder().encodeToString(message); - params.isBase64 = true; - sendMessageAsync("sendToPage", params); - } - - @Override - public String url() { - return initializer.get("url").getAsString(); - } - - @Override - public List protocols() { - return readProtocols(); - } - - 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; - } - - void afterHandle() { - if (this.connected) { - return; - } - // Ensure that websocket is "open" and can send messages without an actual server connection. - try { - sendMessageAsync("ensureOpened", new WebSocketRouteEnsureOpenedParams()); - } 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); - } - } - } -} 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); - } -} From 35f85837bddf300808ab5c16e5757815ff549962 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Thu, 19 Nov 2026 18:49:53 -0800 Subject: [PATCH 25/30] chore: translate page, frame, context, locator, network, handles, fetch, tracing and browser classes from the Node.js client --- .../impl/APIRequestContextImpl.java | 376 ++++ .../playwright/impl/APIRequestImpl.java | 81 + .../playwright/impl/APIResponseImpl.java | 187 ++ .../playwright/impl/BindingCall.java | 96 + .../playwright/impl/BrowserContextImpl.java | 1178 +++++++++++ .../playwright/impl/BrowserImpl.java | 260 +++ .../playwright/impl/BrowserTypeImpl.java | 136 ++ .../microsoft/playwright/impl/Connect.java | 132 ++ .../playwright/impl/ElementHandleImpl.java | 606 ++++++ .../microsoft/playwright/impl/FrameImpl.java | 963 +++++++++ .../playwright/impl/FrameLocatorImpl.java | 154 ++ .../microsoft/playwright/impl/HarRouter.java | 206 ++ .../playwright/impl/JSHandleImpl.java | 111 ++ .../playwright/impl/LocatorImpl.java | 727 +++++++ .../microsoft/playwright/impl/PageImpl.java | 1729 +++++++++++++++++ .../playwright/impl/PlaywrightImpl.java | 165 ++ .../microsoft/playwright/impl/RawHeaders.java | 120 ++ .../playwright/impl/RequestImpl.java | 351 ++++ .../playwright/impl/ResponseImpl.java | 204 ++ .../playwright/impl/RouteHandler.java | 176 ++ .../microsoft/playwright/impl/RouteImpl.java | 267 +++ .../playwright/impl/TracingImpl.java | 365 ++++ .../playwright/impl/WebSocketFrameImpl.java | 48 + .../playwright/impl/WebSocketImpl.java | 166 ++ .../impl/WebSocketRouteHandler.java | 96 + .../playwright/impl/WebSocketRouteImpl.java | 253 +++ 26 files changed, 9153 insertions(+) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Connect.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java new file mode 100644 index 000000000..6aaa52f27 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -0,0 +1,376 @@ +/* + * 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 fetch.ts. +package com.microsoft.playwright.impl; + +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.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static com.microsoft.playwright.impl.Errors.isTargetClosedError; +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 { + APIRequestImpl request; + final TracingImpl tracing; + private String closeReason; + TimeoutSettings timeoutSettings; + + final APIRequestContextChannel channel = new APIRequestContextChannel(this); + + APIRequestContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + this.tracing = connection.protocolGson().fromJson(initializer, APIRequestContextInitializer.class).tracing; + this.timeoutSettings = new TimeoutSettings(); + } + + @Override + public void dispose(DisposeOptions options) { + if (options == null) { + options = new DisposeOptions(); + } + closeReason = options.reason; + 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 urls) { + return cookies(urls == null ? Collections.emptyList() : Collections.singletonList(urls)); + } + + @Override + public List cookies(List urls) { + if (urls == null) { + urls = new ArrayList<>(); + } + APIRequestContextCookiesParams params = new APIRequestContextCookiesParams(); + params.urls = urls; + 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(); + // 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); + } + + @Override + public void clearCookies(ClearCookiesOptions options) { + if (options == null) { + options = new ClearCookiesOptions(); + } + // 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, withMethod(options, "DELETE")); + } + + @Override + 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 wrapApiCall(() -> innerFetch(urlOrRequest, null, (RequestOptionsImpl) options), null, false); + } + + @Override + public APIResponse fetch(Request urlOrRequest, RequestOptions options) { + return wrapApiCall(() -> innerFetch(null, urlOrRequest, (RequestOptionsImpl) options), null, false); + } + + // java: upstream takes one object { url, request, ...options }. + APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl options) { + if (options == null) { + options = new RequestOptionsImpl(); + } + if (closeReason != null) { + throw new TargetClosedError(closeReason); + } + if (request == null && url == null) { + throw new PlaywrightException("First argument must be either URL string or Request"); + } + 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"); + } + if (options.maxRedirects != null && options.maxRedirects < 0) { + throw new PlaywrightException("'maxRedirects' must be greater than or equal to '0'"); + } + if (options.maxRetries != null && options.maxRetries < 0) { + throw new PlaywrightException("'maxRetries' must be greater than or equal to '0'"); + } + if (url == null) { + url = request.url(); + } + String method = options.method != null ? options.method : (request != null ? request.method() : null); + // java: RequestOptions has no string or URLSearchParams form of params, so there are no encodedParams. + // 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) { + if (options.data instanceof String) { + String data = (String) options.data; + if (isJsonContentType(headers)) { + jsonData = isJsonParsable(data) ? data : jsonDataSerializer.toJson(data); + } else { + postDataBuffer = data.getBytes(StandardCharsets.UTF_8); + } + } else if (options.data instanceof byte[]) { + postDataBuffer = (byte[]) options.data; + } else { + // java: any other object is serialized with Gson, there is no 'Unexpected data type' case. + 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 (postDataBuffer == null && jsonData == null && formData == null && multipartData == null) { + postDataBuffer = request != null ? request.postDataBuffer() : null; + } + APIRequestContextFetchParams params = new APIRequestContextFetchParams(); + params.url = url; + params.params = objectToArray(options.params); + 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; + params.maxRedirects = options.maxRedirects; + params.maxRetries = options.maxRetries; + APIRequestContextFetchResult result = channel.fetch(params, timeoutSettings.timeout(options.timeout)); + return new APIResponseImpl(this, result.response); + } + + @Override + public String storageState(StorageStateOptions options) { + if (options == null) { + options = new StorageStateOptions(); + } + 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) { + // java: writeToFile creates the parent directories, as mkdirIfNeeded does upstream. + Utils.writeToFile(Serialization.toPrettyJson(state).getBytes(StandardCharsets.UTF_8), options.path); + } + return state; + } + + @Override + public TracingImpl tracing() { + return tracing; + } + + // 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 (value instanceof FilePayload) { + field.file = filePayloadToJson((FilePayload) value); + } else if (value instanceof Path) { + field.file = readStreamToJson((Path) value); + } else { + field.value = String.valueOf(value); + } + return field; + } + + // 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; + } + try { + JsonElement result = JsonParser.parseString(value); + if (result != null && result.isJsonPrimitive()) { + JsonPrimitive primitive = result.getAsJsonPrimitive(); + if (primitive.isString() && value.equals(primitive.getAsString())) { + return false; + } + } + return true; + } catch (JsonSyntaxException e) { + return false; + } + } + + 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 e : map.entrySet()) { + if (e.getValue() != null) { + result.add(nameValue(e.getKey(), String.valueOf(e.getValue()))); + } + } + return result; + } + + // java: helpers, the method override of the get/post/... shortcuts and isomorphic headersObjectToArray. + + // java: upstream overrides the method; an explicit RequestOptions.setMethod wins here, as it always did in Java. + private static RequestOptionsImpl withMethod(RequestOptions options, String method) { + RequestOptionsImpl impl = Utils.clone((RequestOptionsImpl) options); + if (impl == null) { + impl = new RequestOptionsImpl(); + } + if (impl.method == null) { + impl.method = method; + } + return impl; + } + + static List headersObjectToArray(Map headers) { + List result = new ArrayList<>(); + for (Map.Entry e : headers.entrySet()) { + if (e.getValue() == null) { + continue; + } + result.add(nameValue(e.getKey(), e.getValue())); + } + return result; + } + + 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 new file mode 100644 index 000000000..290f61e52 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -0,0 +1,81 @@ +/* + * 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 fetch.ts. +package com.microsoft.playwright.impl; + +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.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; + +class APIRequestImpl implements APIRequest { + private final PlaywrightImpl playwright; + final Set contexts = new LinkedHashSet<>(); + + APIRequestImpl(PlaywrightImpl playwright) { + this.playwright = playwright; + } + + @Override + public APIRequestContextImpl newContext(NewContextOptions options) { + options = options == null ? new NewContextOptions() : Utils.clone(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 { + 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 = storageStateJson == null ? null : + gson().fromJson(storageStateJson, PlaywrightNewRequestParams.PlaywrightNewRequestParamsStorageState.class); + Map extraHTTPHeaders = options.extraHTTPHeaders; + List clientCertificates = options.clientCertificates; + Object httpCredentials = options.httpCredentials; + Double timeout = options.timeout; + // 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; + options.timeout = null; + PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class); + params.extraHTTPHeaders = extraHTTPHeaders != null ? APIRequestContextImpl.headersObjectToArray(extraHTTPHeaders) : null; + params.storageState = storageState; + // java: there are no default launch options with a tracesDir in the Java API. + params.clientCertificates = BrowserContextImpl.toClientCertificatesProtocol(clientCertificates); + params.httpCredentials = BrowserContextImpl.toHttpCredentialsProtocol(httpCredentials); + APIRequestContextImpl context = playwright.channel.newRequest(params, NO_TIMEOUT).request; + contexts.add(context); + context.request = this; + context.timeoutSettings.setDefaultTimeout(timeout); + 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 new file mode 100644 index 000000000..8a8df7222 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java @@ -0,0 +1,187 @@ +/* + * 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 fetch.ts. +package com.microsoft.playwright.impl; + +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.ResourceTiming; +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.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.Errors.isTargetClosedError; + +class APIResponseImpl implements APIResponse { + private final com.microsoft.playwright.impl.protocol.APIResponse initializer; + private final RawHeaders headers; + final APIRequestContextImpl request; + + APIResponseImpl(APIRequestContextImpl context, com.microsoft.playwright.impl.protocol.APIResponse initializer) { + this.request = context; + this.initializer = initializer; + this.headers = new RawHeaders(this.initializer.headers); + } + + R wrapApiCall(Supplier func, String title, boolean internal) { + return request.wrapApiCall(func, title, internal); + } + + @Override + public boolean ok() { + return initializer.status >= 200 && initializer.status <= 299; + } + + @Override + public String url() { + return initializer.url; + } + + @Override + public int status() { + return initializer.status; + } + + @Override + public String statusText() { + return initializer.statusText; + } + + @Override + public Map headers() { + return headers.headers(); + } + + @Override + public List headersArray() { + return headers.headersArray(); + } + + // java: the protocol SecurityDetails and RemoteAddr are converted to the API types. + @Override + public SecurityDetails securityDetails() { + return Utils.convertType(initializer.securityDetails, SecurityDetails.class); + } + + @Override + public ServerAddr serverAddr() { + if (initializer.serverAddr == null) { + return null; + } + ServerAddr result = new ServerAddr(); + result.ipAddress = initializer.serverAddr.ipAddress; + result.port = initializer.serverAddr.port == null ? 0 : initializer.serverAddr.port; + return result; + } + + @Override + 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 byte[] body() { + return wrapApiCall(() -> { + try { + APIRequestContextFetchResponseBodyParams params = new APIRequestContextFetchResponseBodyParams(); + params.fetchUid = fetchUid(); + APIRequestContextFetchResponseBodyResult result = request.channel.fetchResponseBody(params, NO_TIMEOUT); + 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() { + byte[] content = body(); + return new String(content, StandardCharsets.UTF_8); + } + + @Override + public void dispose() { + APIRequestContextDisposeAPIResponseParams params = new APIRequestContextDisposeAPIResponseParams(); + params.fetchUid = fetchUid(); + request.channel.disposeAPIResponse(params, NO_TIMEOUT); + } + + String fetchUid() { + return initializer.fetchUid; + } + + List fetchLog() { + APIRequestContextFetchLogParams params = new APIRequestContextFetchLogParams(); + params.fetchUid = fetchUid(); + return request.channel.fetchLog(params, NO_TIMEOUT).log; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java new file mode 100644 index 000000000..03400d794 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java @@ -0,0 +1,96 @@ +/* + * 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 page.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.Frame; +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; +import java.util.List; + +import static com.microsoft.playwright.impl.Serialization.*; + +public class BindingCall extends ChannelOwner { + final BindingCallChannel channel = new BindingCallChannel(this); + // java: the initializer parsed once, upstream reads this._initializer. + final BindingCallInitializer bindingCallInitializer; + + 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) { + 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; + + Source(BrowserContext context, Page page, Frame frame) { + this.context = context; + this.page = page; + this.frame = frame; + } + + @Override + public BrowserContext context() { + return context; + } + + @Override + public Page page() { + return page; + } + + @Override + public Frame frame() { + return frame; + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java new file mode 100644 index 000000000..f869471d2 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -0,0 +1,1178 @@ +/* + * 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 browserContext.ts. +package com.microsoft.playwright.impl; + +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.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.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +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.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toProtocol; + +public class BrowserContextImpl extends ChannelOwner implements BrowserContext { + // java: an insertion-ordered list, pages() lists the pages in creation order. + final List pages = new ArrayList<>(); + 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 HashMap<>(); + final TimeoutSettings timeoutSettings; + PageImpl ownerPage; + 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; + private List harRouters = new ArrayList<>(); + + final BrowserContextChannel channel = new BrowserContextChannel(this); + + BrowserContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + 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"); + mapping.put(Events.BrowserContext.REQUEST, "request"); + mapping.put(Events.BrowserContext.RESPONSE, "response"); + mapping.put(Events.BrowserContext.REQUEST_FINISHED, "requestFinished"); + mapping.put(Events.BrowserContext.REQUEST_FAILED, "requestFailed"); + setEventToSubscriptionMapping(mapping); + } + + // 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; + // java: no service worker API, so the worker has no _context to set. + 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); + 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; + } + // java: no recorder API, the recorderEvent event is not handled. + } + } + + // java: upstream takes options.recordHar; Java has the flat recordHar* options. + void initializeHarFromOptions(Browser.NewContextOptions recordHar) { + if (recordHar == null || recordHar.recordHarPath == null) { + return; + } + 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); + } + } + + private void onRequest(RequestImpl request, PageImpl page) { + emit(Events.BrowserContext.REQUEST, request); + if (page != null) { + page.emit(Events.Page.REQUEST, request); + } + } + + private void onResponse(ResponseImpl response, PageImpl page) { + emit(Events.BrowserContext.RESPONSE, response); + if (page != null) { + page.emit(Events.Page.RESPONSE, response); + } + } + + private void onRequestFailed(RequestImpl request, Double responseEndTiming, String failureText, PageImpl page) { + request.failureText = failureText; + request.setResponseEndTiming(responseEndTiming); + emit(Events.BrowserContext.REQUEST_FAILED, request); + if (page != null) { + page.emit(Events.Page.REQUEST_FAILED, request); + } + } + + 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.initializer.get("name").getAsString()); + if (func == null) { + return; + } + bindingCall.call(func); + } + + 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 setDefaultNavigationTimeout(double timeout) { + timeoutSettings.setDefaultNavigationTimeout(timeout); + } + + @Override + public void setDefaultTimeout(double timeout) { + timeoutSettings.setDefaultTimeout(timeout); + } + + @Override + public BrowserImpl browser() { + return browser; + } + + @Override + public List pages() { + return new ArrayList<>(pages); + } + + @Override + public boolean isClosed() { + return !"none".equals(closingStatus); + } + + @Override + public PageImpl newPage() { + if (ownerPage != null) { + throw new PlaywrightException("Please use browser.newContext()"); + } + return channel.newPage(new BrowserContextNewPageParams(), NO_TIMEOUT).page; + } + + @Override + public List cookies(String urls) { + return cookies(urls == null ? new ArrayList<>() : Collections.singletonList(urls)); + } + + @Override + 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 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 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 grantPermissions(List permissions, GrantPermissionsOptions options) { + if (options == null) { + options = new GrantPermissionsOptions(); + } + BrowserContextGrantPermissionsParams params = toProtocol(options, BrowserContextGrantPermissionsParams.class); + params.permissions = permissions == null ? new ArrayList<>() : permissions; + channel.grantPermissions(params, NO_TIMEOUT); + } + + @Override + public void clearPermissions() { + channel.clearPermissions(new BrowserContextClearPermissionsParams(), NO_TIMEOUT); + } + + @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 setExtraHTTPHeaders(Map headers) { + BrowserContextSetExtraHTTPHeadersParams params = new BrowserContextSetExtraHTTPHeadersParams(); + params.headers = connection.protocolGson().fromJson(Serialization.toProtocol(headers), new TypeToken>() {}.getType()); + channel.setExtraHTTPHeaders(params, NO_TIMEOUT); + } + + @Override + public void setOffline(boolean offline) { + BrowserContextSetOfflineParams params = new BrowserContextSetOfflineParams(); + params.offline = offline; + channel.setOffline(params, NO_TIMEOUT); + } + + // java: setHTTPCredentials has no Java API. + + @Override + public AutoCloseable addInitScript(String script) { + // java: the exposeFunctions option has no Java API. + BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); + params.source = script; + return channel.addInitScript(params, NO_TIMEOUT).disposable; + } + + @Override + public AutoCloseable addInitScript(Path script) { + // java: evaluationScript of clientHelper.ts for { path }. + String source; + try { + source = new String(Files.readAllBytes(script), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new PlaywrightException("Failed to read script from file", e); + } + return addInitScript(ClientHelper.addSourceUrlToScript(source, script)); + } + + @Override + 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: _exposeCallbackBinding serves the exposeFunctions option of addInitScript, which has no Java API. + + @Override + 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; + } + + @Override + public AutoCloseable route(String url, Consumer handler, RouteOptions options) { + return route(UrlMatcher.forGlob(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); + } + + 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 routeWebSocket(String url, Consumer handler) { + routeWebSocket(UrlMatcher.forGlob(baseUrl(), url, connection.localUtils(), true), handler); + } + + @Override + public void routeWebSocket(Pattern url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); + } + + @Override + public void routeWebSocket(Predicate url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); + } + + private void routeWebSocket(UrlMatcher url, Consumer handler) { + withTitle("Route WebSockets", () -> { + webSocketRoutes.add(0, new WebSocketRouteHandler(options.baseURL, url, handler)); + updateWebSocketInterceptionPatterns(); + }); + } + + @Override + 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); + } + + private void disposeHarRouters() { + for (HarRouter router : harRouters) { + router.dispose(); + } + harRouters = new ArrayList<>(); + } + + @Override + public void unrouteAll() { + withTitle("Unroute requests", () -> { + unrouteInternal(routes, new ArrayList<>()); + disposeHarRouters(); + }); + } + + @Override + public void unroute(String url, Consumer handler) { + unroute(UrlMatcher.forGlob(baseUrl(), url, connection.localUtils(), false), handler); + } + + @Override + public void unroute(Pattern url, Consumer handler) { + unroute(new UrlMatcher(url), handler); + } + + @Override + public void unroute(Predicate url, Consumer handler) { + unroute(new UrlMatcher(url), handler); + } + + 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); + }); + } + + // java: unrouteAll() has no behavior option, so the removed handlers are never stopped. + private void unrouteInternal(List removed, List remaining) { + routes = remaining; + updateInterceptionPatterns(); + } + + 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 browser != null ? browser.closeReason : null; + } + + // 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); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.BrowserContext.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.BrowserContext.CLOSE, () -> new TargetClosedError(effectiveCloseReason())); + } + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; + } + + @Override + 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(); + } + + // java: serviceWorkers() has no Java API. + + @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 page) { + BrowserContextNewCDPSessionParams params = new BrowserContextNewCDPSessionParams(); + params.frame = (FrameImpl) page; + return channel.newCDPSession(params, NO_TIMEOUT).session; + } + + 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); + } + + @Override + public void close(CloseOptions options) { + if (isClosed()) { + return; + } + if (options == null) { + options = new CloseOptions(); + } + closeReason = options.reason; + closingStatus = "closing"; + request.dispose(convertType(options, APIRequestContext.DisposeOptions.class)); + RuntimeException harError = null; + try { + tracing.exportAllHars(); + } catch (RuntimeException e) { + harError = e; + } + BrowserContextCloseParams params = new BrowserContextCloseParams(); + params.reason = options.reason; + channel.close(params, NO_TIMEOUT); + runUntil(() -> {}, closedPromise); + if (harError != null) { + throw harError; + } + } + + // java: showRecorder, startRecording, stopRecording and exposeConsoleApi have no Java API. + + // java: upstream reads a path given as a string and passes an object through; Java options hold a Path. + static JsonElement prepareStorageState(Path storageState) { + String text; + try { + text = 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); + } + try { + return JsonParser.parseString(text); + } catch (JsonParseException e) { + throw new PlaywrightException("Error reading storage state from " + storageState + ":\n" + e.getMessage(), e); + } + } + + // 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 Browser.NewContextOptions(); + } + // 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, and the headers map to name/value pairs. + Browser.NewContextOptions rest = Utils.clone(options); + rest.viewportSize = 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(); + 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. + 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; + } + + // 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()); + } + + private static String toAcceptDownloadsProtocol(Boolean acceptDownloads) { + if (acceptDownloads == null) { + return null; + } + if (acceptDownloads) { + return "accept"; + } + return "deny"; + } + + 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; + } + + // java: the local function of toClientCertificatesProtocol. + private static byte[] bufferizeContent(byte[] value, Path filePath) { + if (value != null) { + return value; + } + if (filePath != null) { + try { + return Files.readAllBytes(filePath); + } catch (IOException e) { + throw new PlaywrightException("Failed to read from file", e); + } + } + 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 ClockImpl clock() { + return clock; + } + + @Override + public Credentials credentials() { + return credentials; + } + + @Override + public DebuggerImpl debugger() { + return debugger; + } + + @Override + public APIRequestContextImpl request() { + return request; + } + + @Override + public TracingImpl tracing() { + return tracing; + } + + URL baseUrl() { + if (options.baseURL != null) { + try { + return new URL(options.baseURL); + } catch (MalformedURLException e) { + } + } + return null; + } + + @Override + public void onBackgroundPage(Consumer handler) { + on(Events.BrowserContext.BACKGROUND_PAGE, handler); + } + + @Override + public void offBackgroundPage(Consumer handler) { + off(Events.BrowserContext.BACKGROUND_PAGE, handler); + } + + @Override + public void onClose(Consumer handler) { + on(Events.BrowserContext.CLOSE, handler); + } + + @Override + public void offClose(Consumer handler) { + off(Events.BrowserContext.CLOSE, handler); + } + + @Override + public void onConsoleMessage(Consumer handler) { + on(Events.BrowserContext.CONSOLE, handler); + } + + @Override + public void offConsoleMessage(Consumer handler) { + off(Events.BrowserContext.CONSOLE, handler); + } + + @Override + public void onDialog(Consumer handler) { + on(Events.BrowserContext.DIALOG, handler); + } + + @Override + public void offDialog(Consumer handler) { + off(Events.BrowserContext.DIALOG, handler); + } + + @Override + public void onDialogClosed(Consumer handler) { + on(Events.BrowserContext.DIALOG_CLOSED, handler); + } + + @Override + public void offDialogClosed(Consumer handler) { + off(Events.BrowserContext.DIALOG_CLOSED, handler); + } + + @Override + public void onDownload(Consumer handler) { + on(Events.BrowserContext.DOWNLOAD, handler); + } + + @Override + public void offDownload(Consumer handler) { + off(Events.BrowserContext.DOWNLOAD, handler); + } + + @Override + public void onFrameAttached(Consumer handler) { + on(Events.BrowserContext.FRAME_ATTACHED, handler); + } + + @Override + public void offFrameAttached(Consumer handler) { + off(Events.BrowserContext.FRAME_ATTACHED, handler); + } + + @Override + public void onFrameDetached(Consumer handler) { + on(Events.BrowserContext.FRAME_DETACHED, handler); + } + + @Override + public void offFrameDetached(Consumer handler) { + off(Events.BrowserContext.FRAME_DETACHED, handler); + } + + @Override + public void onFrameNavigated(Consumer handler) { + on(Events.BrowserContext.FRAME_NAVIGATED, handler); + } + + @Override + public void offFrameNavigated(Consumer handler) { + off(Events.BrowserContext.FRAME_NAVIGATED, handler); + } + + @Override + public void onPage(Consumer handler) { + on(Events.BrowserContext.PAGE, handler); + } + + @Override + public void offPage(Consumer handler) { + off(Events.BrowserContext.PAGE, handler); + } + + @Override + public void onPageClose(Consumer handler) { + on(Events.BrowserContext.PAGE_CLOSE, handler); + } + + @Override + public void offPageClose(Consumer handler) { + off(Events.BrowserContext.PAGE_CLOSE, handler); + } + + @Override + public void onPageLoad(Consumer handler) { + on(Events.BrowserContext.PAGE_LOAD, handler); + } + + @Override + public void offPageLoad(Consumer handler) { + off(Events.BrowserContext.PAGE_LOAD, handler); + } + + @Override + public void onWebError(Consumer handler) { + on(Events.BrowserContext.WEB_ERROR, handler); + } + + @Override + public void offWebError(Consumer handler) { + off(Events.BrowserContext.WEB_ERROR, handler); + } + + @Override + public void onRequest(Consumer handler) { + on(Events.BrowserContext.REQUEST, handler); + } + + @Override + public void offRequest(Consumer handler) { + off(Events.BrowserContext.REQUEST, handler); + } + + @Override + public void onRequestFailed(Consumer handler) { + on(Events.BrowserContext.REQUEST_FAILED, handler); + } + + @Override + public void offRequestFailed(Consumer handler) { + off(Events.BrowserContext.REQUEST_FAILED, handler); + } + + @Override + public void onRequestFinished(Consumer handler) { + on(Events.BrowserContext.REQUEST_FINISHED, handler); + } + + @Override + public void offRequestFinished(Consumer handler) { + off(Events.BrowserContext.REQUEST_FINISHED, handler); + } + + @Override + public void onResponse(Consumer handler) { + on(Events.BrowserContext.RESPONSE, handler); + } + + @Override + public void offResponse(Consumer handler) { + off(Events.BrowserContext.RESPONSE, handler); + } + + @Override + public Page waitForPage(WaitForPageOptions options, Runnable callback) { + if (options == null) { + options = new WaitForPageOptions(); + } + return waitForEvent(Events.BrowserContext.PAGE, options.predicate, options.timeout, callback); + } + + @Override + public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable callback) { + if (options == null) { + options = new WaitForConsoleMessageOptions(); + } + return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, callback); + } + + @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()); + } + }); + 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 new file mode 100644 index 000000000..9f9beb25f --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -0,0 +1,260 @@ +/* + * 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 browser.ts. +package com.microsoft.playwright.impl; + +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.impl.protocol.*; +import com.microsoft.playwright.options.BindResult; + +import java.io.IOException; +import java.nio.file.Path; +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.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 { + final Set contexts = new LinkedHashSet<>(); + private boolean isConnected = true; + // java: no _closedPromise, close() waits until isConnected turns false, which happens when Disconnected is emitted. + boolean shouldCloseConnectionOnClose = false; + BrowserTypeImpl browserType; + private BrowserType.LaunchOptions options = new BrowserType.LaunchOptions(); + final String name; + final String browserName; + private Path path; + String closeReason; + + final BrowserChannel channel = new BrowserChannel(this); + + 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; + } + + @Override + 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 BrowserType browserType() { + return browserType; + } + + @Override + public BrowserContextImpl newContext(NewContextOptions options) { + return innerNewContext(options); + } + + // java: no forReuse parameter, newContextForReuse is not in the Java API. + BrowserContextImpl innerNewContext(NewContextOptions userOptions) { + if (userOptions == null) { + userOptions = new NewContextOptions(); + } + BrowserNewContextParams contextOptions = BrowserContextImpl.prepareBrowserContextParams(userOptions); + // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params. + contextOptions.selectorEngines = new ArrayList<>(browserType.playwright.selectors.selectorEngines); + contextOptions.testIdAttributeName = browserType.playwright.selectors.testIdAttributeName; + BrowserContextImpl context = channel.newContext(contextOptions, NO_TIMEOUT).context; + // java: the HAR options are the recordHar* fields of the options, upstream passes options.recordHar. + context.initializeHarFromOptions(userOptions); + return context; + } + + void connectToBrowserType(BrowserTypeImpl browserType, BrowserType.LaunchOptions browserOptions) { + // 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; + for (BrowserContextImpl context : contexts) { + setupBrowserContext(context); + } + } + + 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); + } + + private void setupBrowserContext(BrowserContextImpl context) { + context.tracing.tracesDir = options.tracesDir; + context.request.tracing.tracesDir = options.tracesDir; + browserType.contexts.add(context); + browserType.playwright.selectors.contextsForSelectors.add(context); + // java: no _defaultContextTimeout and _defaultContextNavigationTimeout, the test runner sets them upstream. + } + + @Override + public List contexts() { + return new ArrayList<>(contexts); + } + + @Override + public String version() { + return initializer.get("version").getAsString(); + } + + @Override + public BindResult bind(String title, BindOptions options) { + BrowserStartServerParams params = toProtocol(options, BrowserStartServerParams.class); + params.title = title; + BrowserStartServerResult result = channel.startServer(params, NO_TIMEOUT); + BindResult bindResult = new BindResult(); + bindResult.endpoint = result.endpoint; + return bindResult; + } + + @Override + 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; + // java: readAllBytes is readIntoBuffer. + byte[] buffer = artifact.readAllBytes(); + artifact.delete(); + if (path != null) { + mkdirIfNeeded(path); + writeToFile(buffer, path); + path = null; + } + return buffer; + } + + @Override + public void close(CloseOptions options) { + if (options == null) { + options = new CloseOptions(); + } + 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(() -> {}, new WaitablePredicate(() -> !isConnected)); + } 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; + } + throw e; + } + } + + void didClose() { + isConnected = false; + emit(Events.Browser.DISCONNECTED, this); + } + + // java: typed listeners of the Java API. + @Override + public void onContext(Consumer handler) { + on(Events.Browser.CONTEXT, handler); + } + + @Override + public void offContext(Consumer handler) { + off(Events.Browser.CONTEXT, handler); + } + + @Override + public void onDisconnected(Consumer handler) { + on(Events.Browser.DISCONNECTED, handler); + } + + @Override + public void offDisconnected(Consumer handler) { + off(Events.Browser.DISCONNECTED, handler); + } + + // 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); + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java new file mode 100644 index 000000000..bcca06a57 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -0,0 +1,136 @@ +/* + * 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 browserType.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.BrowserType; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.impl.protocol.*; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import static com.microsoft.playwright.impl.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toProtocol; + +public class BrowserTypeImpl extends ChannelOwner implements BrowserType { + final Set contexts = new LinkedHashSet<>(); + PlaywrightImpl playwright; + + final BrowserTypeChannel channel = new BrowserTypeChannel(this); + + BrowserTypeImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + } + + @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 launchOptions = options == null ? new LaunchOptions() : options; + return wrapApiCall(() -> { + // java: no userDataDir and port options to reject, and no _defaultLaunchOptions of the test runner. + // 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); + return browser; + }, null, false); + } + + @Override + public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options) { + LaunchPersistentContextOptions persistentOptions = options == null ? new LaunchPersistentContextOptions() : options; + return wrapApiCall(() -> { + // 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); + // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params. + 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()); + } + 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); + BrowserContextImpl context = result.context; + // java: the HAR options are the recordHar* fields of the options, upstream passes options.recordHar. + context.initializeHarFromOptions(contextOptions); + return context; + }, null, false); + } + + @Override + public BrowserImpl connect(String endpoint, ConnectOptions options) { + ConnectOptions params = options == null ? new ConnectOptions() : options; + // java: _connect is inlined, its Java name would be this method's. + return wrapApiCall(() -> { + BrowserImpl browser = Connect.connectToBrowser(playwright, name(), endpoint, params); + browser.connectToBrowserType(this, new LaunchOptions()); + return browser; + }, null, false); + } + + // java: only the endpointURL overload, the Java API has no options object with wsEndpoint and no ConnectOverCDPTransport. + @Override + 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; + BrowserTypeConnectOverCDPResult result = channel.connectOverCDP(params, new TimeoutSettings().timeout(options.timeout)); + return browserFromConnectResult(result); + } + + private BrowserImpl browserFromConnectResult(BrowserTypeConnectOverCDPResult result) { + BrowserImpl browser = result.browser; + browser.connectToBrowserType(this, new LaunchOptions()); + // java: no instrumentation to notify about result.defaultContext. + return browser; + } +} 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..508b611ac --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java @@ -0,0 +1,132 @@ +/* + * 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; + +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; + long deadline = timeout != 0 ? System.nanoTime() + (long) (timeout * 1_000_000) : 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 { + 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. 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); + 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: 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/ElementHandleImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java new file mode 100644 index 000000000..d2dd1534a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -0,0 +1,606 @@ +/* + * 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 elementHandle.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.ElementHandle; +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.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.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 { + FrameImpl frame; + final ElementHandleChannel elementChannel = new ElementHandleChannel(this); + + ElementHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + this.frame = (FrameImpl) parent; + } + + @Override + public ElementHandle asElement() { + return this; + } + + @Override + public FrameImpl ownerFrame() { + return elementChannel.ownerFrame(NO_TIMEOUT).frame; + } + + @Override + public FrameImpl contentFrame() { + return elementChannel.contentFrame(NO_TIMEOUT).frame; + } + + @Override + 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 String inputValue(InputValueOptions options) { + return elementChannel.inputValue(NO_TIMEOUT).value; + } + + @Override + public String textContent() { + return elementChannel.textContent(NO_TIMEOUT).value; + } + + @Override + public String innerText() { + return elementChannel.innerText(NO_TIMEOUT).value; + } + + @Override + public String innerHTML() { + return elementChannel.innerHTML(NO_TIMEOUT).value; + } + + @Override + public boolean isChecked() { + return elementChannel.isChecked(NO_TIMEOUT).value; + } + + @Override + public boolean isDisabled() { + return elementChannel.isDisabled(NO_TIMEOUT).value; + } + + @Override + public boolean isEditable() { + return elementChannel.isEditable(NO_TIMEOUT).value; + } + + @Override + public boolean isEnabled() { + return elementChannel.isEnabled(NO_TIMEOUT).value; + } + + @Override + public boolean isHidden() { + return elementChannel.isHidden(NO_TIMEOUT).value; + } + + @Override + public boolean isVisible() { + return elementChannel.isVisible(NO_TIMEOUT).value; + } + + @Override + public void dispatchEvent(String type, Object eventInit) { + if (eventInit == null) { + eventInit = Collections.emptyMap(); + } + ElementHandleDispatchEventParams params = new ElementHandleDispatchEventParams(); + params.type = type; + params.eventInit = serializeArgument(eventInit); + elementChannel.dispatchEvent(params, NO_TIMEOUT); + } + + @Override + 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 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 void click(ClickOptions options) { + if (options == null) { + options = new ClickOptions(); + } + ElementHandleClickParams params = toProtocol(options, ElementHandleClickParams.class); + elementChannel.click(params, frame.timeout(options.timeout)); + } + + @Override + 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 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 List selectOption(String values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + @Override + public List selectOption(ElementHandle values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + @Override + public List selectOption(String[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + @Override + public List selectOption(SelectOption values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + @Override + public List selectOption(ElementHandle[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + @Override + public List selectOption(SelectOption[] values, SelectOptionOptions options) { + return selectOption((Object) values, options); + } + + private List selectOption(Object values, SelectOptionOptions options) { + if (options == null) { + options = new SelectOptionOptions(); + } + 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 void fill(String value, FillOptions options) { + if (options == null) { + options = new FillOptions(); + } + ElementHandleFillParams params = toProtocol(options, ElementHandleFillParams.class); + params.value = value; + elementChannel.fill(params, frame.timeout(options.timeout)); + } + + @Override + public void selectText(SelectTextOptions options) { + if (options == null) { + options = new SelectTextOptions(); + } + 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 void setInputFiles(Path files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); + } + + @Override + public void setInputFiles(Path[] files, SetInputFilesOptions options) { + setInputFiles((Object) files, options); + } + + @Override + 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 SetInputFilesOptions(); + } + FrameImpl frame = ownerFrame(); + if (frame == null) { + throw new PlaywrightException("Cannot set input files to detached element"); + } + ElementHandleSetInputFilesParams converted = convertInputFiles(files, (BrowserContextImpl) frame.page().context()); + elementChannel.setInputFiles(converted, this.frame.timeout(options.timeout)); + } + + @Override + public void focus() { + elementChannel.focus(NO_TIMEOUT); + } + + @Override + public void type(String text, TypeOptions options) { + if (options == null) { + options = new TypeOptions(); + } + ElementHandleTypeParams params = toProtocol(options, ElementHandleTypeParams.class); + params.text = text; + elementChannel.type(params, frame.timeout(options.timeout)); + } + + @Override + public void press(String key, PressOptions options) { + if (options == null) { + options = new PressOptions(); + } + ElementHandlePressParams params = toProtocol(options, ElementHandlePressParams.class); + params.key = key; + elementChannel.press(params, frame.timeout(options.timeout)); + } + + @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 uncheck(UncheckOptions options) { + if (options == null) { + options = new UncheckOptions(); + } + ElementHandleUncheckParams params = toProtocol(options, ElementHandleUncheckParams.class); + elementChannel.uncheck(params, frame.timeout(options.timeout)); + } + + @Override + public void setChecked(boolean checked, SetCheckedOptions options) { + if (checked) { + check(convertType(options, CheckOptions.class)); + } else { + uncheck(convertType(options, UncheckOptions.class)); + } + } + + @Override + public BoundingBox boundingBox() { + Rect value = elementChannel.boundingBox(NO_TIMEOUT).value; + return value == null ? null : convertType(value, BoundingBox.class); + } + + @Override + public byte[] screenshot(ScreenshotOptions options) { + if (options == null) { + options = new ScreenshotOptions(); + } + // java: toProtocol converts the mask locators to { frame, selector }. + ElementHandleScreenshotParams copy = toProtocol(this, options, ElementHandleScreenshotParams.class); + if (copy.type == null) { + copy.type = determineScreenshotType(options); + } + ElementHandleScreenshotResult result = elementChannel.screenshot(copy, frame.timeout(options.timeout)); + if (options.path != null) { + Utils.writeToFile(result.binary, options.path); + } + return result.binary; + } + + @Override + public ElementHandle querySelector(String selector) { + ElementHandleQuerySelectorParams params = new ElementHandleQuerySelectorParams(); + params.selector = selector; + return elementChannel.querySelector(params, NO_TIMEOUT).element; + } + + @Override + 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 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 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 + public void waitForElementState(ElementState state, WaitForElementStateOptions options) { + if (options == null) { + options = new WaitForElementStateOptions(); + } + // java: the state is an enum that may be null. + if (state == null) { + throw new IllegalArgumentException("State cannot be null"); + } + ElementHandleWaitForElementStateParams params = toProtocol(options, ElementHandleWaitForElementStateParams.class); + params.state = state.toString().toLowerCase(); + elementChannel.waitForElementState(params, frame.timeout(options.timeout)); + } + + @Override + public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { + if (options == null) { + options = new WaitForSelectorOptions(); + } + ElementHandleWaitForSelectorParams params = toProtocol(options, ElementHandleWaitForSelectorParams.class); + params.selector = selector; + 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; + } + Utils.assertNoNullItems(items); + if (items[0] instanceof ElementHandle) { + result.elements = new ArrayList<>(); + for (Object v : items) { + result.elements.add((ElementHandleImpl) v); + } + return result; + } + result.options = new ArrayList<>(); + if (items[0] instanceof String) { + for (Object valueOrLabel : items) { + ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); + option.valueOrLabel = (String) valueOrLabel; + result.options.add(option); + } + return result; + } + 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; + } + + // java: Utils.checkFilePayloadSize is not used, its limit check is > while upstream's is >=. + 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)); + ElementHandleSetInputFilesParams result = new ElementHandleSetInputFilesParams(); + + boolean somePaths = false; + boolean allPaths = true; + for (Object item : items) { + if (item instanceof Path) { + somePaths = true; + } else { + allPaths = false; + } + } + if (somePaths) { + if (!allPaths) { + 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; + 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); + } + BrowserContextCreateTempFilesResult tempFiles = context.wrapApiCall(() -> context.channel.createTempFiles(params, NO_TIMEOUT), null, true); + for (int i = 0; i < filesToStream.size(); i++) { + WritableStream writable = tempFiles.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); + } + } + result.directoryStream = tempFiles.rootDir; + result.streams = localDirectory != null ? null : tempFiles.writableStreams; + return result; + } + 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."); + } + 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); + } + + // java: Utils.screenshotTypeForPath stands for getMimeTypeForPath and throws upstream's error for other mime types. + private static String determineScreenshotType(Path path, ScreenshotType type) { + if (path != null) { + return Utils.screenshotTypeForPath(path).toString().toLowerCase(); + } + return type == null ? null : type.toString().toLowerCase(); + } + + // java: fileUtils.ts fileUploadSizeLimit, fs.promises.stat and fs.promises.readdir with recursive: true. + static final long fileUploadSizeLimit = 50 * 1024 * 1024; + + 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/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java new file mode 100644 index 000000000..3dc82f9ae --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -0,0 +1,963 @@ +/* + * 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 frame.ts. +package com.microsoft.playwright.impl; + +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.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +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.Serialization.deserialize; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.Utils.*; + +public class FrameImpl extends ChannelOwner implements Frame { + final EventEmitter eventEmitter; + Set loadStates; + FrameImpl parentFrame; + String url = ""; + String name = ""; + boolean detached; + Set childFrames = new LinkedHashSet<>(); + PageImpl page; + final WebMCPImpl webmcp; + + final FrameChannel channel = new FrameChannel(this); + + FrameImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + FrameInitializer init = connection.protocolGson().fromJson(initializer, FrameInitializer.class); + eventEmitter = new EventEmitter(); + webmcp = new WebMCPImpl(this); + parentFrame = init.parentFrame; + if (parentFrame != null) { + parentFrame.childFrames.add(this); + } + name = init.name; + url = init.url; + loadStates = new LinkedHashSet<>(); + if (init.loadStates != null) { + loadStates.addAll(init.loadStates); + } + } + + // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. + @Override + 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); + ((BrowserContextImpl) 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; + // java: there are no functions passed to evaluate() (no exposeFunctions option), so no + // _eraseEvaluateCallbacks() on a main frame navigation. + eventEmitter.emit(Events.Frame.NAVIGATED, navigatedEvent); + if (navigatedEvent.error == null && page != null) { + page.emit(Events.Page.FRAME_NAVIGATED, this); + ((BrowserContextImpl) page.context()).emit(Events.BrowserContext.FRAME_NAVIGATED, this); + } + } + } + + @Override + public PageImpl page() { + return page; + } + + double timeout(Double timeout) { + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + return timeoutSettings.timeout(timeout); + } + + double navigationTimeout(Double timeout) { + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + return timeoutSettings.navigationTimeout(timeout); + } + + @Override + 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; + } + + 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 ResponseImpl waitForNavigation(WaitForNavigationOptions options, Runnable callback) { + if (options == null) { + options = new WaitForNavigationOptions(); + } + 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)); + + String toUrl = options.url instanceof String ? " to \"" + options.url + "\"" : ""; + waiter.log("waiting for navigation" + toUrl + " until \"" + waitUntil + "\""); + + // java: the matcher is built once, a glob is converted by a call to the driver that must not run inside the event handler. + UrlMatcher matcher = UrlMatcher.forOneOf(baseURL(), options.url, connection.localUtils(), false); + 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); + } + + if (!loadStates.contains(waitUntil)) { + waiter.waitForPromise(waiter.waitForEvent(eventEmitter, Events.Frame.LOAD_STATE, s -> { + waiter.log(" \"" + s + "\" event fired"); + return s.equals(waitUntil); + })); + } + + 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 { + result.complete(request.finalRequest().internalResponse()); + } catch (RuntimeException e) { + result.completeExceptionally(e); + } + response = waiter.waitForPromise(result); + } + waiter.dispose(); + return response; + } + + @Override + public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { + waitForLoadState(state == null ? "load" : state.name().toLowerCase(Locale.ROOT), options == null ? null : options.timeout); + } + + // 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 { + 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(); + } + }); + } + + @Override + public void waitForURL(String url, WaitForURLOptions options) { + waitForURL((Object) url, options); + } + + @Override + public void waitForURL(Pattern url, WaitForURLOptions options) { + waitForURL((Object) url, options); + } + + @Override + public void waitForURL(Predicate url, WaitForURLOptions options) { + waitForURL((Object) url, options); + } + + private void waitForURL(Object url, WaitForURLOptions options) { + WaitForURLOptions waitOptions = options == null ? new WaitForURLOptions() : options; + if (UrlMatcher.forOneOf(baseURL(), url, connection.localUtils(), false).test(url())) { + waitForLoadState(waitOptions.waitUntil == null ? "load" : lifecycleEvent(waitOptions.waitUntil), waitOptions.timeout); + return; + } + + WaitForNavigationOptions navigationOptions = new WaitForNavigationOptions(); + navigationOptions.url = url; + navigationOptions.waitUntil = waitOptions.waitUntil; + navigationOptions.timeout = waitOptions.timeout; + waitForNavigation(navigationOptions, null); + } + + @Override + public ElementHandleImpl frameElement() { + return channel.frameElement(new FrameFrameElementParams(), NO_TIMEOUT).element; + } + + @Override + public JSHandle evaluateHandle(String expression, Object arg) { + FrameEvaluateExpressionHandleParams params = new FrameEvaluateExpressionHandleParams(); + params.expression = expression; + params.arg = serializeArgument(arg); + return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; + } + + @Override + public Object evaluate(String expression, Object arg) { + FrameEvaluateExpressionParams params = new FrameEvaluateExpressionParams(); + params.expression = expression; + params.arg = serializeArgument(arg); + return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); + } + + 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 WaitForSelectorOptions(); + } + FrameWaitForSelectorParams params = toProtocol(options, FrameWaitForSelectorParams.class); + params.selector = selector; + return channel.waitForSelector(params, timeout(options.timeout)).element; + } + + @Override + public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { + if (options == null) { + options = new DispatchEventOptions(); + } + FrameDispatchEventParams params = toProtocol(options, FrameDispatchEventParams.class); + params.selector = selector; + params.type = type; + params.eventInit = serializeArgument(eventInit); + channel.dispatchEvent(params, timeout(options.timeout)); + } + + @Override + 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.evalOnSelector(params, NO_TIMEOUT).value); + } + + @Override + public Object evalOnSelectorAll(String selector, String expression, Object arg) { + FrameEvalOnSelectorAllParams params = new FrameEvalOnSelectorAllParams(); + params.selector = selector; + params.expression = expression; + params.arg = serializeArgument(arg); + return deserialize(channel.evalOnSelectorAll(params, NO_TIMEOUT).value); + } + + @Override + public List querySelectorAll(String selector) { + FrameQuerySelectorAllParams params = new FrameQuerySelectorAllParams(); + params.selector = selector; + return new ArrayList<>(channel.querySelectorAll(params, NO_TIMEOUT).elements); + } + + int queryCount(String selector) { + FrameQueryCountParams params = new FrameQueryCountParams(); + params.selector = selector; + return channel.queryCount(params, NO_TIMEOUT).value; + } + + @Override + public String content(ContentOptions options) { + FrameContentParams params = toProtocol(options, FrameContentParams.class); + return channel.content(params, NO_TIMEOUT).value; + } + + @Override + 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 name() { + return name == null ? "" : name; + } + + @Override + public String url() { + return url; + } + + @Override + public FrameImpl parentFrame() { + return parentFrame; + } + + @Override + public List childFrames() { + return new ArrayList<>(childFrames); + } + + @Override + public boolean isDetached() { + return detached; + } + + @Override + 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 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 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 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, (BrowserContextImpl) 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)); + } + + @Override + public Locator getByTestId(String testId) { + return locator(getByTestIdSelector(testId, connection.playwright)); + } + + @Override + public Locator getByTestId(Pattern testId) { + return locator(getByTestIdSelector(testId, connection.playwright)); + } + + @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 + public Locator getByText(String text, GetByTextOptions options) { + return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); + } + + @Override + public Locator getByText(Pattern text, GetByTextOptions options) { + return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); + } + + @Override + public Locator getByTitle(String text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); + } + + @Override + public Locator getByTitle(Pattern text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); + } + + @Override + public Locator getByRole(AriaRole role, GetByRoleOptions options) { + return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); + } + + @Override + public FrameLocatorImpl frameLocator(String selector) { + return new FrameLocatorImpl(this, selector == null ? ANY_FRAME_SELECTOR : selector); + } + + @Override + public void focus(String selector, FocusOptions options) { + if (options == null) { + options = new FocusOptions(); + } + FrameFocusParams params = toProtocol(options, FrameFocusParams.class); + params.selector = selector; + channel.focus(params, timeout(options.timeout)); + } + + @Override + public String textContent(String selector, TextContentOptions options) { + if (options == null) { + options = new TextContentOptions(); + } + FrameTextContentParams params = toProtocol(options, FrameTextContentParams.class); + params.selector = selector; + return channel.textContent(params, timeout(options.timeout)).value; + } + + @Override + public String innerText(String selector, InnerTextOptions options) { + if (options == null) { + options = new InnerTextOptions(); + } + 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) { + if (options == null) { + options = new InnerHTMLOptions(); + } + FrameInnerHTMLParams params = toProtocol(options, FrameInnerHTMLParams.class); + params.selector = selector; + return channel.innerHTML(params, timeout(options.timeout)).value; + } + + @Override + public String getAttribute(String selector, String name, GetAttributeOptions options) { + if (options == null) { + options = new GetAttributeOptions(); + } + FrameGetAttributeParams params = toProtocol(options, FrameGetAttributeParams.class); + params.selector = selector; + params.name = name; + return channel.getAttribute(params, timeout(options.timeout)).value; + } + + @Override + public String inputValue(String selector, InputValueOptions options) { + if (options == null) { + options = new InputValueOptions(); + } + FrameInputValueParams params = toProtocol(options, FrameInputValueParams.class); + params.selector = selector; + return channel.inputValue(params, timeout(options.timeout)).value; + } + + @Override + public boolean isChecked(String selector, IsCheckedOptions options) { + if (options == null) { + options = new IsCheckedOptions(); + } + FrameIsCheckedParams params = toProtocol(options, FrameIsCheckedParams.class); + params.selector = selector; + return channel.isChecked(params, timeout(options.timeout)).value; + } + + @Override + public boolean isDisabled(String selector, IsDisabledOptions options) { + if (options == null) { + options = new IsDisabledOptions(); + } + FrameIsDisabledParams params = toProtocol(options, FrameIsDisabledParams.class); + params.selector = selector; + return channel.isDisabled(params, timeout(options.timeout)).value; + } + + @Override + public boolean isEditable(String selector, IsEditableOptions options) { + if (options == null) { + options = new IsEditableOptions(); + } + FrameIsEditableParams params = toProtocol(options, FrameIsEditableParams.class); + params.selector = selector; + return channel.isEditable(params, timeout(options.timeout)).value; + } + + @Override + public boolean isEnabled(String selector, IsEnabledOptions options) { + if (options == null) { + options = new IsEnabledOptions(); + } + FrameIsEnabledParams params = toProtocol(options, FrameIsEnabledParams.class); + params.selector = selector; + return channel.isEnabled(params, timeout(options.timeout)).value; + } + + @Override + public boolean isHidden(String selector, IsHiddenOptions options) { + FrameIsHiddenParams params = toProtocol(options, FrameIsHiddenParams.class); + params.selector = selector; + return channel.isHidden(params, NO_TIMEOUT).value; + } + + @Override + public boolean isVisible(String selector, IsVisibleOptions options) { + FrameIsVisibleParams params = toProtocol(options, FrameIsVisibleParams.class); + params.selector = selector; + return channel.isVisible(params, NO_TIMEOUT).value; + } + + @Override + public void hover(String selector, HoverOptions options) { + if (options == null) { + options = new HoverOptions(); + } + FrameHoverParams params = toProtocol(options, FrameHoverParams.class); + params.selector = selector; + channel.hover(params, timeout(options.timeout)); + } + + @Override + public List selectOption(String selector, String values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); + } + + @Override + public List selectOption(String selector, ElementHandle values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); + } + + @Override + public List selectOption(String selector, String[] values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); + } + + @Override + public List selectOption(String selector, SelectOption values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); + } + + @Override + public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, options); + } + + @Override + public List selectOption(String selector, SelectOption[] values, SelectOptionOptions options) { + return selectOptionImpl(selector, values, 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; + params.elements = converted.elements; + if (converted.options != null) { + params.options = new ArrayList<>(); + 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 channel.selectOption(params, timeout(options.timeout)).values; + } + + @Override + public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { + setInputFilesImpl(selector, files, options); + } + + @Override + public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { + setInputFilesImpl(selector, files, options); + } + + @Override + public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { + setInputFilesImpl(selector, files, options); + } + + @Override + public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { + setInputFilesImpl(selector, files, options); + } + + private void setInputFilesImpl(String selector, Object files, SetInputFilesOptions options) { + if (options == null) { + options = new SetInputFilesOptions(); + } + ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(files, (BrowserContextImpl) page().context()); + FrameSetInputFilesParams params = toProtocol(options, FrameSetInputFilesParams.class); + params.selector = selector; + 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 type(String selector, String text, TypeOptions options) { + if (options == null) { + options = new TypeOptions(); + } + FrameTypeParams params = toProtocol(options, FrameTypeParams.class); + params.selector = selector; + params.text = text; + channel.type(params, timeout(options.timeout)); + } + + @Override + public void press(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 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)); + } + + @Override + public void uncheck(String selector, UncheckOptions options) { + if (options == null) { + options = new UncheckOptions(); + } + FrameUncheckParams params = toProtocol(options, FrameUncheckParams.class); + params.selector = selector; + channel.uncheck(params, timeout(options.timeout)); + } + + @Override + public void setChecked(String selector, boolean checked, SetCheckedOptions options) { + if (checked) { + check(selector, convertType(options, CheckOptions.class)); + } else { + uncheck(selector, convertType(options, UncheckOptions.class)); + } + } + + @Override + public void waitForTimeout(double timeout) { + FrameWaitForTimeoutParams params = new FrameWaitForTimeoutParams(); + params.waitTimeout = timeout; + channel.waitForTimeout(params, NO_TIMEOUT); + } + + @Override + public JSHandle waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { + if (options == null) { + options = new WaitForFunctionOptions(); + } + // 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; + } + + @Override + public String title() { + return channel.title(NO_TIMEOUT).value; + } + + // 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; + } + }, title, false); + } + + static String verifyLoadState(String name, String waitUntil) { + if ("networkidle0".equals(waitUntil)) { + waitUntil = "networkidle"; + } + if (!kLifecycleEvents.contains(waitUntil)) { + throw new PlaywrightException(name + ": expected one of (load|domcontentloaded|networkidle|commit)"); + } + return waitUntil; + } + + private static final Set kLifecycleEvents = new LinkedHashSet<>(Arrays.asList("load", "domcontentloaded", "networkidle", "commit")); + + // java: members with no upstream counterpart: kAnyFrameSelector of isomorphic/selectorParser.ts, the enum form of + // verifyLoadState, conversions for the seed classes, and the webmcp() accessor of upstream's webmcp field. + static final String ANY_FRAME_SELECTOR = "internal:control=any-frame"; + + static WaitUntilState verifyLoadState(String name, WaitUntilState waitUntil) { + return WaitUntilState.valueOf(verifyLoadState(name, lifecycleEvent(waitUntil)).toUpperCase(Locale.ROOT)); + } + + private static String lifecycleEvent(WaitUntilState state) { + return state.name().toLowerCase(Locale.ROOT); + } + + private URL baseURL() { + if (page == null) { + return null; + } + String baseURL = ((BrowserContextImpl) page.context()).options.baseURL; + if (baseURL == null) { + return null; + } + try { + return new URL(baseURL); + } catch (MalformedURLException e) { + return null; + } + } + + 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); + } + } + + @Override + public WebMCP webmcp() { + return webmcp; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java new file mode 100644 index 000000000..c58553a7f --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -0,0 +1,154 @@ +/* + * 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 locator.ts. +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.FrameLocator; +import com.microsoft.playwright.Locator; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.options.AriaRole; + +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.LocatorUtils.*; +import static com.microsoft.playwright.impl.Utils.convertType; + +class FrameLocatorImpl implements FrameLocator { + private final FrameImpl frame; + private final String frameSelector; + + FrameLocatorImpl(FrameImpl frame, String selector) { + this.frame = frame; + this.frameSelector = selector; + } + + private String childSelector(String selector) { + if (FrameImpl.ANY_FRAME_SELECTOR.equals(frameSelector)) + return frameSelector + " >> " + selector; + return frameSelector + " >> internal:control=enter-frame >> " + selector; + } + + @Override + public Locator locator(String selectorOrLocator, LocatorOptions options) { + return new LocatorImpl(frame, childSelector(selectorOrLocator), convertType(options, Locator.LocatorOptions.class)); + } + + @Override + public Locator locator(Locator selectorOrLocator, LocatorOptions options) { + LocatorImpl locator = (LocatorImpl) selectorOrLocator; + if (locator.frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, childSelector(locator.selector), convertType(options, Locator.LocatorOptions.class)); + } + + // java: the test id attribute lives in SelectorsImpl of the Playwright instance, see LocatorUtils.getByTestIdSelector. + @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 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 + public Locator getByText(String text, GetByTextOptions options) { + return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); + } + + @Override + public Locator getByText(Pattern text, GetByTextOptions options) { + return locator(getByTextSelector(text, convertType(options, Locator.GetByTextOptions.class))); + } + + @Override + public Locator getByTitle(String text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); + } + + @Override + public Locator getByTitle(Pattern text, GetByTitleOptions options) { + return locator(getByTitleSelector(text, convertType(options, Locator.GetByTitleOptions.class))); + } + + @Override + public Locator getByRole(AriaRole role, GetByRoleOptions options) { + return locator(getByRoleSelector(role, convertType(options, Locator.GetByRoleOptions.class))); + } + + @Override + public Locator owner() { + return new LocatorImpl(frame, frameSelector); + } + + @Override + 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 first() { + return new FrameLocatorImpl(frame, nthSelector("0")); + } + + @Override + 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 new file mode 100644 index 000000000..8bba5f547 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java @@ -0,0 +1,206 @@ +/* + * 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.function.Predicate; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +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, Pattern, Predicate or UrlMatcher; 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.channel.harOpen(params, NO_TIMEOUT); + 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.channel.harLookup(params, NO_TIMEOUT); + + 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.FALLBACK) { + route.abort(); + return; + } + + route.fallback(); + } + + void addContextRoute(BrowserContext context) { + Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; + if (urlMatch instanceof UrlMatcher) { + urlMatch = fromUrlMatcher((UrlMatcher) urlMatch); + } + if (urlMatch instanceof Pattern) { + context.route((Pattern) urlMatch, route -> handle(route)); + } else if (urlMatch instanceof Predicate) { + context.route(asPredicate(urlMatch), route -> handle(route)); + } else { + context.route((String) urlMatch, route -> handle(route)); + } + } + + void addPageRoute(Page page) { + Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; + if (urlMatch instanceof UrlMatcher) { + urlMatch = fromUrlMatcher((UrlMatcher) urlMatch); + } + if (urlMatch instanceof Pattern) { + page.route((Pattern) urlMatch, route -> handle(route)); + } else if (urlMatch instanceof Predicate) { + page.route(asPredicate(urlMatch), route -> handle(route)); + } else { + page.route((String) urlMatch, route -> handle(route)); + } + } + + void dispose() { + LocalUtilsHarCloseParams params = new LocalUtilsHarCloseParams(); + params.harId = harId; + try { + localUtils.sendMessageAsync("harClose", params); + } catch (PlaywrightException e) { + } + } + + // java: helpers to pass the URLMatch to the String, Pattern and Predicate overloads of route(). + + private static Object fromUrlMatcher(UrlMatcher matcher) { + if (matcher.glob != null) { + return matcher.glob; + } + if (matcher.pattern != null) { + return matcher.pattern; + } + if (matcher.predicate != null) { + return matcher.predicate; + } + return "**/*"; + } + + @SuppressWarnings("unchecked") + private static Predicate asPredicate(Object urlMatch) { + return (Predicate) urlMatch; + } + + 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 new file mode 100644 index 000000000..9b6eda438 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java @@ -0,0 +1,111 @@ +/* + * 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 jsHandle.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.ElementHandle; +import com.microsoft.playwright.JSHandle; +import com.microsoft.playwright.impl.protocol.*; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static com.microsoft.playwright.impl.Serialization.deserialize; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; + +// java: serializeArgument and parseResult are Serialization.serializeArgument and Serialization.deserialize; +// Java has no evaluate options, so EvaluateOptions, serializeArgumentWithCallbacks and the argument assertions are not ported. +public class JSHandleImpl extends ChannelOwner implements JSHandle { + private String preview; + + final JSHandleChannel channel = new JSHandleChannel(this); + + 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 + 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) { + JSHandleEvaluateExpressionParams params = new JSHandleEvaluateExpressionParams(); + params.expression = pageFunction; + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializeArgument(arg); + 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; + // java: functions are passed as strings, so isFunction is not sent and the server detects it. + params.arg = serializeArgument(arg); + JSHandleEvaluateExpressionHandleResult result = channel.evaluateExpressionHandle(params, NO_TIMEOUT); + return result.handle; + } + + @Override + public JSHandle getProperty(String propertyName) { + JSHandleGetPropertyParams params = new JSHandleGetPropertyParams(); + params.name = propertyName; + 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 + public Object jsonValue() { + return deserialize(channel.jsonValue(NO_TIMEOUT).value); + } + + @Override + public ElementHandle asElement() { + return null; + } + + @Override + public void dispose() { + try { + channel.dispose(NO_TIMEOUT); + } catch (TargetClosedError e) { + return; + } + } + + @Override + public String toString() { + return preview; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java new file mode 100644 index 000000000..3560008ff --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -0,0 +1,727 @@ +/* + * 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 locator.ts. +package com.microsoft.playwright.impl; + +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.function.BiFunction; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; +import static com.microsoft.playwright.impl.LocatorUtils.*; +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.Utils.convertType; + +class LocatorImpl implements Locator { + final FrameImpl frame; + final String selector; + + // 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, convertType(options, FilterOptions.class)); + } + + private LocatorImpl(FrameImpl frame, String selector, FilterOptions options) { + this.frame = frame; + + if (options != null && options.hasText != null) + selector += " >> internal:has-text=" + escapeForTextSelector(options.hasText, false); + + if (options != null && options.hasNotText != null) + 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."); + selector += " >> internal:has=" + gson().toJson(locator.selector); + } + + 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."); + selector += " >> internal:has-not=" + gson().toJson(locator.selector); + } + + if (options != null && options.visible != null) + selector += " >> visible=" + (options.visible ? "true" : "false"); + + this.selector = selector; + } + + R wrapApiCall(Supplier func, String title, boolean internal) { + return frame.wrapApiCall(func, title, internal); + } + + 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.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(); + } + } + + // java: upstream _equals(), used by page.ts; equals() so that Java collections and assertEquals agree. + @Override + public boolean equals(Object obj) { + if (!(obj instanceof LocatorImpl)) + return false; + LocatorImpl locator = (LocatorImpl) obj; + return frame == locator.frame && selector.equals(locator.selector); + } + + @Override + public Page page() { + return frame.page(); + } + + @Override + public BoundingBox boundingBox(BoundingBoxOptions options) { + return frame.withTitle("Bounding box", () -> withElement((h, timeout) -> h.boundingBox(), options == null ? null : options.timeout)); + } + + @Override + public void check(CheckOptions options) { + if (options == null) + options = new CheckOptions(); + frame.check(selector, convertType(options, Frame.CheckOptions.class).setStrict(true)); + } + + // java: Frame.ClickOptions has no 'steps', so this sends what upstream frame.click() sends. + @Override + public void click(ClickOptions options) { + if (options == null) + options = new ClickOptions(); + 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) + options = new DblclickOptions(); + 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 (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) + options = new DragToOptions(); + frame.dragAndDrop(selector, ((LocatorImpl) target).selector, convertType(options, Frame.DragAndDropOptions.class).setStrict(true)); + } + + @Override + 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); + } + + @Override + public Object evaluate(String expression, Object arg, EvaluateOptions options) { + return frame.withTitle("Evaluate", () -> withElement((h, timeout) -> h.evaluate(expression, arg), options == null ? null : options.timeout)); + } + + @Override + public Object evaluateAll(String expression, Object arg) { + return frame.evalOnSelectorAll(selector, expression, arg); + } + + @Override + public JSHandle evaluateHandle(String expression, Object arg, EvaluateHandleOptions options) { + 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) + options = new FillOptions(); + frame.fill(selector, value, convertType(options, Frame.FillOptions.class).setStrict(true)); + } + + @Override + public void clear(ClearOptions options) { + frame.withTitle("Clear", () -> fill("", convertType(options, FillOptions.class))); + } + + // java: HighlightOptions.style is a string only, cssObjectToString() is not needed. + @Override + public AutoCloseable highlight(HighlightOptions options) { + if (options == null) + options = new HighlightOptions(); + frame.highlight(selector, options.style); + return new DisposableStub(this::hideHighlight); + } + + @Override + public void hideHighlight() { + frame.hideHighlight(selector); + } + + @Override + public Locator locator(String selectorOrLocator, LocatorOptions options) { + return new LocatorImpl(frame, selector + " >> " + selectorOrLocator, options); + } + + @Override + public Locator locator(Locator selectorOrLocator, LocatorOptions options) { + LocatorImpl locator = (LocatorImpl) selectorOrLocator; + if (locator.frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:chain=" + gson().toJson(locator.selector), options); + } + + @Override + public Locator within(Locator locator) { + return locator.locator(this); + } + + // java: the test id attribute lives in SelectorsImpl of the Playwright instance, see LocatorUtils.getByTestIdSelector. + @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 getByAltText(String text, GetByAltTextOptions options) { + return locator(getByAltTextSelector(text, options)); + } + + @Override + public Locator getByAltText(Pattern text, GetByAltTextOptions options) { + return locator(getByAltTextSelector(text, options)); + } + + @Override + public Locator getByLabel(String text, GetByLabelOptions options) { + return locator(getByLabelSelector(text, options)); + } + + @Override + public Locator getByLabel(Pattern text, GetByLabelOptions options) { + return locator(getByLabelSelector(text, options)); + } + + @Override + public Locator getByPlaceholder(String text, GetByPlaceholderOptions options) { + return locator(getByPlaceholderSelector(text, options)); + } + + @Override + 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 FrameLocator frameLocator(String selector) { + return new FrameLocatorImpl(frame, this.selector + " >> " + selector); + } + + @Override + public Locator filter(FilterOptions options) { + return new LocatorImpl(frame, selector, options); + } + + @Override + public Locator visible() { + return new LocatorImpl(frame, selector, new FilterOptions().setVisible(true)); + } + + @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); + } + + @Override + public FrameLocator contentFrame() { + return new FrameLocatorImpl(frame, selector); + } + + @Override + public Locator describe(String description) { + return new LocatorImpl(frame, selector + " >> " + describeSelector(description)); + } + + // java: there is no port of the selector parser; this matches the trailing internal:describe part + // that upstream locatorCustomDescription() reads. + @Override + 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 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) { + LocatorImpl other = (LocatorImpl) locator; + if (other.frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(other.selector)); + } + + @Override + public Locator or(Locator locator) { + LocatorImpl other = (LocatorImpl) locator; + if (other.frame != frame) + throw new PlaywrightException("Locators must belong to the same frame."); + return new LocatorImpl(frame, selector + " >> internal:or=" + gson().toJson(other.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) + options = new HoverOptions(); + frame.hover(selector, convertType(options, Frame.HoverOptions.class).setStrict(true)); + } + + @Override + public String innerHTML(InnerHTMLOptions options) { + 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) + options = new InnerTextOptions(); + return frame.innerText(selector, convertType(options, Frame.InnerTextOptions.class).setStrict(true)); + } + + @Override + public String inputValue(InputValueOptions options) { + 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) + options = new IsCheckedOptions(); + return frame.isChecked(selector, convertType(options, Frame.IsCheckedOptions.class).setStrict(true)); + } + + @Override + public boolean isDisabled(IsDisabledOptions options) { + 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) + options = new IsEditableOptions(); + return frame.isEditable(selector, convertType(options, Frame.IsEditableOptions.class).setStrict(true)); + } + + @Override + public boolean isEnabled(IsEnabledOptions options) { + 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) + options = new IsHiddenOptions(); + return frame.isHidden(selector, convertType(options, Frame.IsHiddenOptions.class).setStrict(true)); + } + + @Override + public boolean isVisible(IsVisibleOptions options) { + if (options == null) + options = new IsVisibleOptions(); + return frame.isVisible(selector, convertType(options, Frame.IsVisibleOptions.class).setStrict(true)); + } + + @Override + public void press(String key, PressOptions options) { + if (options == null) + options = new PressOptions(); + frame.press(selector, key, convertType(options, Frame.PressOptions.class).setStrict(true)); + } + + @Override + 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 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; + } + + @Override + public void scrollIntoViewIfNeeded(ScrollIntoViewIfNeededOptions options) { + 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; + }, scrollOptions.timeout)); + } + + @Override + public List selectOption(String values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public List selectOption(ElementHandle values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public List selectOption(String[] values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public List selectOption(SelectOption values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public List selectOption(ElementHandle[] values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public List selectOption(SelectOption[] values, SelectOptionOptions options) { + return frame.selectOption(selector, values, frameSelectOptionOptions(options)); + } + + @Override + public void selectText(SelectTextOptions options) { + 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; + }, selectOptions.timeout)); + } + + @Override + public void setChecked(boolean checked, SetCheckedOptions options) { + if (checked) + check(convertType(options, CheckOptions.class)); + else + uncheck(convertType(options, UncheckOptions.class)); + } + + @Override + public void setInputFiles(Path files, SetInputFilesOptions options) { + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); + } + + @Override + public void setInputFiles(Path[] files, SetInputFilesOptions options) { + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); + } + + @Override + public void setInputFiles(FilePayload files, SetInputFilesOptions options) { + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); + } + + @Override + public void setInputFiles(FilePayload[] files, SetInputFilesOptions options) { + frame.setInputFiles(selector, files, frameSetInputFilesOptions(options)); + } + + @Override + public void tap(TapOptions options) { + 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) + 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) + 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) + 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) + options = new WaitForOptions(); + 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(); + params.selector = selector; + params.strict = true; + params.expression = expression; + params.arg = serializeArgument(arg); + frame.channel.waitForFunction(params, frame.timeout(options == null ? null : options.timeout)); + } + + // 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: 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) + return stringRepresentation; + String description = description(); + if (description != null) + return description; + return "Locator@" + selector; + } + + // java: helpers and members with no upstream counterpart. + private String stringRepresentation; + + private static double monotonicTime() { + return System.nanoTime() / 1_000_000.0; + } + + 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 + public int hashCode() { + return frame.hashCode() ^ selector.hashCode(); + } + + JsonObject toProtocol() { + JsonObject result = new JsonObject(); + result.add("frame", frame.toProtocolRef()); + result.addProperty("selector", selector); + return result; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java new file mode 100644 index 000000000..d68d9caae --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -0,0 +1,1729 @@ +/* + * 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 page.ts. +package com.microsoft.playwright.impl; + +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.ArrayList; +import java.util.HashMap; +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.Utils.convertType; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +import static com.microsoft.playwright.impl.Utils.toProtocol; +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.nio.file.Files.readAllBytes; +import static java.util.Arrays.asList; + +public class PageImpl extends ChannelOwner implements Page { + final PageChannel channel = new PageChannel(this); + private final BrowserContextImpl browserContext; + BrowserContextImpl ownedContext; + + private final FrameImpl mainFrame; + private final Set frames = new LinkedHashSet<>(); + final Set workers = new LinkedHashSet<>(); + private boolean closed; + // java: LongStandingScope; the Close and Crash events close it as upstream, createWaitForCloseHelper() races it. + private TargetClosedError closedOrCrashedScope; + private ViewportSize viewportSize; + List routes = new ArrayList<>(); + List webSocketRoutes = new ArrayList<>(); + + 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 HashMap<>(); + final TimeoutSettings timeoutSettings; + private final VideoImpl video; + final PageImpl opener; + private String closeReason; + boolean closeWasCalled; + private List harRouters = new ArrayList<>(); + + private final Map locatorHandlers = new LinkedHashMap<>(); + + PageImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + 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"); + + 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 = pageInitializer.video != null ? new VideoImpl(this, pageInitializer.video) : new VideoImpl(this); + screencast = new ScreencastImpl(this); + + // java: the once(Close) and once(Crash) listeners that close _closedOrCrashedScope are in onClose() and onCrash(). + + Map mapping = new HashMap<>(); + mapping.put(Events.Page.CONSOLE, "console"); + mapping.put(Events.Page.DIALOG, "dialog"); + mapping.put(Events.Page.DIALOG_CLOSED, "dialogClosed"); + mapping.put(Events.Page.REQUEST, "request"); + mapping.put(Events.Page.RESPONSE, "response"); + mapping.put(Events.Page.REQUEST_FINISHED, "requestFinished"); + mapping.put(Events.Page.REQUEST_FAILED, "requestFailed"); + mapping.put(Events.Page.FILE_CHOOSER, "fileChooser"); + setEventToSubscriptionMapping(mapping); + } + + // 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; + } + } + + private void onFrameAttached(FrameImpl frame) { + frame.page = this; + frames.add(frame); + if (frame.parentFrame != null) { + frame.parentFrame.childFrames.add(frame); + } + 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 (!routeHandler.matches(route.request().url())) { + continue; + } + int index = routes.indexOf(routeHandler); + if (index == -1) { + continue; + } + if (routeHandler.willExpire()) { + routes.remove(index); + } + boolean handled = routeHandler.handle(route); + // unrouteAll() replaces _routes and updates interception after waiting for handlers. + if (routeHandlers == routes && routes.isEmpty()) { + try { + disableInterception(); + } catch (PlaywrightException e) { + } + } + if (handled) { + return; + } + } + + browserContext.onRoute(route); + } + + private 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 { + browserContext.onWebSocketRoute(webSocketRoute); + } + } + + void onBinding(BindingCall bindingCall) { + BindingCallback func = bindings.get(bindingCall.initializer.get("name").getAsString()); + if (func != null) { + bindingCall.call(func); + return; + } + browserContext.onBinding(bindingCall); + } + + void onWorker(WorkerImpl worker) { + workers.add(worker); + worker.page = this; + emit(Events.Page.WORKER, worker); + } + + void onClose() { + closed = true; + browserContext.pages.remove(this); + disposeHarRouters(); + // java: this.once(Events.Page.Close, ...) of the constructor. + if (closedOrCrashedScope == null) { + closedOrCrashedScope = closeErrorWithReason(); + } + emit(Events.Page.CLOSE, this); + browserContext.emit(Events.BrowserContext.PAGE_CLOSE, this); + } + + private void onCrash() { + // java: this.once(Events.Page.Crash, ...) of the constructor. + if (closedOrCrashedScope == null) { + closedOrCrashedScope = new TargetClosedError(); + } + emit(Events.Page.CRASH, this); + } + + @Override + public BrowserContextImpl context() { + return browserContext; + } + + @Override + public PageImpl opener() { + if (opener == null || opener.isClosed()) { + return null; + } + return opener; + } + + @Override + public FrameImpl mainFrame() { + return mainFrame; + } + + // java: frame(frameSelector) takes a name or { name, url }; the Java API has frame(name) and frameByUrl(url). + @Override + public Frame frame(String name) { + if (name == null || name.isEmpty()) { + throw new PlaywrightException("Either name or url matcher should be specified"); + } + for (FrameImpl f : frames) { + if (name.equals(f.name())) { + return f; + } + } + return null; + } + + @Override + public Frame frameByUrl(String url) { + return frameByUrl(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false)); + } + + @Override + public Frame frameByUrl(Pattern url) { + return frameByUrl(new UrlMatcher(url)); + } + + @Override + public Frame frameByUrl(Predicate url) { + return frameByUrl(new UrlMatcher(url)); + } + + private Frame frameByUrl(UrlMatcher url) { + for (FrameImpl f : frames) { + if (url.test(f.url())) { + return f; + } + } + return null; + } + + @Override + public List frames() { + return new ArrayList<>(frames); + } + + @Override + public void setDefaultNavigationTimeout(double timeout) { + timeoutSettings.setDefaultNavigationTimeout(timeout); + } + + @Override + public void setDefaultTimeout(double timeout) { + timeoutSettings.setDefaultTimeout(timeout); + } + + @Override + 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 Locator pickLocator() { + PagePickLocatorResult result = channel.pickLocator(NO_TIMEOUT); + return locator(result.selector); + } + + @Override + public void cancelPickLocator() { + channel.cancelPickLocator(NO_TIMEOUT); + } + + @Override + public void hideHighlight() { + channel.hideHighlight(NO_TIMEOUT); + } + + @Override + public ElementHandle querySelector(String selector, QuerySelectorOptions options) { + return mainFrame.querySelector(selector, convertType(options, Frame.QuerySelectorOptions.class)); + } + + @Override + public ElementHandle waitForSelector(String selector, WaitForSelectorOptions options) { + return mainFrame.waitForSelector(selector, convertType(options, Frame.WaitForSelectorOptions.class)); + } + + @Override + public void dispatchEvent(String selector, String type, Object eventInit, DispatchEventOptions options) { + mainFrame.dispatchEvent(selector, type, eventInit, convertType(options, Frame.DispatchEventOptions.class)); + } + + @Override + public JSHandle evaluateHandle(String expression, Object arg) { + return mainFrame.evaluateHandle(expression, arg); + } + + @Override + public Object evalOnSelector(String selector, String expression, Object arg, EvalOnSelectorOptions options) { + return mainFrame.evalOnSelector(selector, expression, arg, convertType(options, Frame.EvalOnSelectorOptions.class)); + } + + @Override + public Object evalOnSelectorAll(String selector, String expression, Object arg) { + return mainFrame.evalOnSelectorAll(selector, expression, arg); + } + + @Override + public List querySelectorAll(String selector) { + return mainFrame.querySelectorAll(selector); + } + + @Override + public ElementHandle addScriptTag(AddScriptTagOptions options) { + return mainFrame.addScriptTag(convertType(options, Frame.AddScriptTagOptions.class)); + } + + @Override + public ElementHandle addStyleTag(AddStyleTagOptions options) { + return mainFrame.addStyleTag(convertType(options, Frame.AddStyleTagOptions.class)); + } + + @Override + 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 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: no exposeFunctions option for evaluate() or addInitScript(), so there is no _exposeCallbackBinding, + // _exposeEvaluateCallback or _eraseEvaluateCallbacks. + + @Override + public void setExtraHTTPHeaders(Map headers) { + // java: validateHeaders checks the JS type of the values, a Java map holds strings. + PageSetExtraHTTPHeadersParams params = new PageSetExtraHTTPHeadersParams(); + params.headers = new ArrayList<>(); + for (Map.Entry e : headers.entrySet()) { + if (e.getValue() == null) { + continue; + } + NameValue header = new NameValue(); + header.name = e.getKey(); + header.value = e.getValue(); + params.headers.add(header); + } + channel.setExtraHTTPHeaders(params, NO_TIMEOUT); + } + + @Override + public String url() { + return mainFrame.url(); + } + + @Override + public String content(ContentOptions options) { + return mainFrame.content(convertType(options, Frame.ContentOptions.class)); + } + + @Override + public void setContent(String html, SetContentOptions options) { + mainFrame.setContent(html, convertType(options, Frame.SetContentOptions.class)); + } + + @Override + public Response navigate(String url, NavigateOptions options) { + return mainFrame.navigate(url, convertType(options, Frame.NavigateOptions.class)); + } + + @Override + public Response reload(ReloadOptions options) { + if (options == null) { + options = new ReloadOptions(); + } + // java: verifyLoadState only validates the string, WaitUntilState is an enum. + PageReloadParams params = toProtocol(options, PageReloadParams.class); + if (params.waitUntil == null) { + params.waitUntil = "load"; + } + return channel.reload(params, timeoutSettings.navigationTimeout(options.timeout)).response; + } + + @Override + 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 removeLocatorHandler(Locator locator) { + for (Map.Entry entry : new ArrayList<>(locatorHandlers.entrySet())) { + if (entry.getValue().locator.equals((LocatorImpl) 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 waitForLoadState(LoadState state, WaitForLoadStateOptions options) { + mainFrame.waitForLoadState(state, convertType(options, Frame.WaitForLoadStateOptions.class)); + } + + @Override + public Response waitForNavigation(WaitForNavigationOptions options, Runnable callback) { + return mainFrame.waitForNavigation(convertType(options, Frame.WaitForNavigationOptions.class), callback); + } + + @Override + public void waitForURL(String url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + } + + @Override + public void waitForURL(Pattern url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + } + + @Override + public void waitForURL(Predicate url, WaitForURLOptions options) { + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); + } + + @Override + 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 Request waitForRequest(Pattern urlOrPredicate, WaitForRequestOptions options, Runnable callback) { + return waitForRequest(new UrlMatcher(urlOrPredicate), null, trimUrl(urlOrPredicate), options, callback); + } + + @Override + 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 @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 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 Response waitForResponse(Pattern urlOrPredicate, WaitForResponseOptions options, Runnable callback) { + return waitForResponse(new UrlMatcher(urlOrPredicate), null, trimUrl(urlOrPredicate), options, callback); + } + + @Override + 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 callback) { + if (options == null) { + options = new WaitForCloseOptions(); + } + return waitForEvent(Events.Page.CLOSE, null, options.timeout, callback); + } + + @Override + public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable callback) { + if (options == null) { + options = new WaitForConsoleMessageOptions(); + } + return waitForEvent(Events.Page.CONSOLE, options.predicate, options.timeout, callback); + } + + @Override + public Download waitForDownload(WaitForDownloadOptions options, Runnable callback) { + if (options == null) { + options = new WaitForDownloadOptions(); + } + return waitForEvent(Events.Page.DOWNLOAD, options.predicate, options.timeout, callback); + } + + @Override + public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable callback) { + if (options == null) { + options = new WaitForFileChooserOptions(); + } + return waitForEvent(Events.Page.FILE_CHOOSER, options.predicate, options.timeout, callback); + } + + @Override + public Page waitForPopup(WaitForPopupOptions options, Runnable callback) { + if (options == null) { + options = new WaitForPopupOptions(); + } + return waitForEvent(Events.Page.POPUP, options.predicate, options.timeout, callback); + } + + @Override + public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Runnable callback) { + if (options == null) { + options = new WaitForRequestFinishedOptions(); + } + return waitForEvent(Events.Page.REQUEST_FINISHED, options.predicate, options.timeout, callback); + } + + @Override + public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable callback) { + if (options == null) { + options = new WaitForWebSocketOptions(); + } + return waitForEvent(Events.Page.WEB_SOCKET, options.predicate, options.timeout, callback); + } + + @Override + public Worker waitForWorker(WaitForWorkerOptions options, Runnable callback) { + if (options == null) { + options = new WaitForWorkerOptions(); + } + return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, callback); + } + + TargetClosedError closeErrorWithReason() { + return new TargetClosedError(closeReason != null ? closeReason : browserContext.effectiveCloseReason()); + } + + // 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) { + waiter.log(logLine); + } + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.Page.CRASH.equals(event)) { + waiter.rejectOnEvent(this, Events.Page.CRASH, () -> new PlaywrightException("Page crashed")); + } + if (!Events.Page.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.Page.CLOSE, () -> closeErrorWithReason()); + } + T result = waiter.waitForEvent(this, event, predicate, callback); + waiter.dispose(); + return result; + } + + @Override + public Response goBack(GoBackOptions options) { + if (options == null) { + options = new GoBackOptions(); + } + PageGoBackParams params = toProtocol(options, PageGoBackParams.class); + if (params.waitUntil == null) { + params.waitUntil = "load"; + } + 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); + if (params.waitUntil == null) { + params.waitUntil = "load"; + } + return channel.goForward(params, timeoutSettings.navigationTimeout(options.timeout)).response; + } + + @Override + public void requestGC() { + channel.requestGC(NO_TIMEOUT); + } + + @Override + 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 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 ViewportSize viewportSize() { + return viewportSize; + } + + @Override + public Object evaluate(String expression, Object arg) { + return mainFrame.evaluate(expression, arg); + } + + // java: the script is a string or a file; there is no function to serialize and no exposeFunctions option. + @Override + public AutoCloseable addInitScript(String script) { + return addInitScriptImpl(script); + } + + @Override + public AutoCloseable addInitScript(Path script) { + String source; + try { + source = ClientHelper.addSourceUrlToScript(new String(readAllBytes(script), UTF_8), script); + } catch (IOException e) { + throw new PlaywrightException("Failed to read script from file", e); + } + return addInitScriptImpl(source); + } + + private AutoCloseable addInitScriptImpl(String source) { + PageAddInitScriptParams params = new PageAddInitScriptParams(); + params.source = source; + return channel.addInitScript(params, NO_TIMEOUT).disposable; + } + + @Override + 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 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; + } + HarRouter harRouter = HarRouter.create(localUtils, har, options.notFound != null ? options.notFound : HarNotFound.ABORT, options.url); + harRouters.add(harRouter); + harRouter.addPageRoute(this); + } + + @Override + public void routeWebSocket(String url, Consumer handler) { + routeWebSocket(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), true), handler); + } + + @Override + public void routeWebSocket(Pattern url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); + } + + @Override + public void routeWebSocket(Predicate url, Consumer handler) { + routeWebSocket(new UrlMatcher(url), handler); + } + + 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<>(); + } + + // java: the Java API has no behavior option, unrouteAll() is behavior 'default'. + @Override + public void unrouteAll() { + withTitle("Unroute requests", () -> { + unrouteInternal(routes, new ArrayList<>()); + disposeHarRouters(); + }); + } + + @Override + public void unroute(String url, Consumer handler) { + unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false), handler); + } + + @Override + public void unroute(Pattern url, Consumer handler) { + unroute(new UrlMatcher(url), handler); + } + + @Override + 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); + }); + } + + // java: no behavior parameter, the 'wait' and 'ignoreErrors' branches that stop the removed handlers are unreachable. + private void unrouteInternal(List removed, List remaining) { + routes = remaining; + updateInterceptionPatterns(); + } + + private void disableInterception() { + wrapApiCall(() -> updateInterceptionPatterns(), null, true); + } + + // java: the patterns go through JSON into the page's own params class. + private void updateInterceptionPatterns() { + JsonObject json = new JsonObject(); + json.add("patterns", gson().toJsonTree(RouteHandler.prepareInterceptionPatterns(routes))); + PageSetNetworkInterceptionPatternsParams params = connection.protocolGson().fromJson(json, PageSetNetworkInterceptionPatternsParams.class); + channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); + } + + private void updateWebSocketInterceptionPatterns() { + JsonObject json = new JsonObject(); + json.add("patterns", gson().toJsonTree(WebSocketRouteHandler.prepareInterceptionPatterns(webSocketRoutes))); + PageSetWebSocketInterceptionPatternsParams params = connection.protocolGson().fromJson(json, PageSetWebSocketInterceptionPatternsParams.class); + channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); + } + + @Override + public byte[] screenshot(ScreenshotOptions options) { + if (options == null) { + options = new ScreenshotOptions(); + } + List mask = options.mask; + ScreenshotOptions copyOptions = Utils.clone(options); + copyOptions.mask = null; + if (copyOptions.type == null && options.path != null) { + // java: determineScreenshotType(options). + copyOptions.type = Utils.screenshotTypeForPath(options.path); + } + PageScreenshotParams copy = toProtocol(copyOptions, PageScreenshotParams.class); + 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; + } + + @Override + public String title() { + return mainFrame.title(); + } + + @Override + public void bringToFront() { + channel.bringToFront(NO_TIMEOUT); + } + + @Override + public void close(CloseOptions options) { + if (options == null) { + 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; + } + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void click(String selector, ClickOptions options) { + mainFrame.click(selector, convertType(options, Frame.ClickOptions.class)); + } + + @Override + public void dragAndDrop(String source, String target, DragAndDropOptions options) { + mainFrame.dragAndDrop(source, target, convertType(options, Frame.DragAndDropOptions.class)); + } + + @Override + public void dblclick(String selector, DblclickOptions options) { + mainFrame.dblclick(selector, convertType(options, Frame.DblclickOptions.class)); + } + + @Override + public void tap(String selector, TapOptions options) { + mainFrame.tap(selector, convertType(options, Frame.TapOptions.class)); + } + + @Override + public void fill(String selector, String value, FillOptions options) { + mainFrame.fill(selector, value, convertType(options, Frame.FillOptions.class)); + } + + @Override + public void clearConsoleMessages() { + channel.clearConsoleMessages(NO_TIMEOUT); + } + + @Override + 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 messages; + } + + @Override + public void clearPageErrors() { + channel.clearPageErrors(NO_TIMEOUT); + } + + // java: the Java API returns the errors as strings, not as parsed Error objects; there is no filter option. + @Override + public List pageErrors() { + PagePageErrorsResult result = channel.pageErrors(new PagePageErrorsParams(), NO_TIMEOUT); + List errors = new ArrayList<>(); + for (SerializedError error : result.errors) { + String errorStr = ""; + if (error.error != null) { + errorStr = error.error.name + ": " + error.error.message; + if (error.error.stack != null && !error.error.stack.isEmpty()) { + errorStr += "\n" + error.error.stack; + } + } + errors.add(errorStr); + } + return errors; + } + + @Override + public Locator locator(String selector, LocatorOptions options) { + return mainFrame().locator(selector, convertType(options, Frame.LocatorOptions.class)); + } + + @Override + public Locator getByTestId(String testId) { + return mainFrame().getByTestId(testId); + } + + @Override + 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)); + } + + @Override + public Locator getByAltText(Pattern text, GetByAltTextOptions options) { + 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)); + } + + @Override + public Locator getByLabel(Pattern text, GetByLabelOptions options) { + 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)); + } + + @Override + public Locator getByPlaceholder(Pattern text, GetByPlaceholderOptions options) { + return mainFrame().getByPlaceholder(text, convertType(options, Frame.GetByPlaceholderOptions.class)); + } + + @Override + public Locator getByRef(String ref) { + return locator("aria-ref=" + ref); + } + + @Override + public Locator getByText(String text, GetByTextOptions options) { + 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)); + } + + @Override + public Locator getByTitle(String text, GetByTitleOptions options) { + 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 Locator getByRole(AriaRole role, GetByRoleOptions options) { + return mainFrame().getByRole(role, convertType(options, Frame.GetByRoleOptions.class)); + } + + @Override + public FrameLocator frameLocator(String selector) { + return mainFrame().frameLocator(selector); + } + + @Override + public void focus(String selector, FocusOptions options) { + mainFrame.focus(selector, convertType(options, Frame.FocusOptions.class)); + } + + @Override + public String textContent(String selector, TextContentOptions options) { + return mainFrame.textContent(selector, convertType(options, Frame.TextContentOptions.class)); + } + + @Override + 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.innerHTML(selector, convertType(options, Frame.InnerHTMLOptions.class)); + } + + @Override + 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.inputValue(selector, convertType(options, Frame.InputValueOptions.class)); + } + + @Override + public boolean isChecked(String selector, IsCheckedOptions options) { + return mainFrame.isChecked(selector, convertType(options, Frame.IsCheckedOptions.class)); + } + + @Override + public boolean isDisabled(String selector, IsDisabledOptions options) { + return mainFrame.isDisabled(selector, convertType(options, Frame.IsDisabledOptions.class)); + } + + @Override + public boolean isEditable(String selector, IsEditableOptions options) { + return mainFrame.isEditable(selector, convertType(options, Frame.IsEditableOptions.class)); + } + + @Override + public boolean isEnabled(String selector, IsEnabledOptions options) { + return mainFrame.isEnabled(selector, convertType(options, Frame.IsEnabledOptions.class)); + } + + @Override + public boolean isHidden(String selector, IsHiddenOptions options) { + return mainFrame.isHidden(selector, convertType(options, Frame.IsHiddenOptions.class)); + } + + @Override + public boolean isVisible(String selector, IsVisibleOptions options) { + return mainFrame.isVisible(selector, convertType(options, Frame.IsVisibleOptions.class)); + } + + @Override + public void hover(String selector, HoverOptions options) { + mainFrame.hover(selector, convertType(options, Frame.HoverOptions.class)); + } + + @Override + public List selectOption(String selector, String values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public List selectOption(String selector, ElementHandle values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public List selectOption(String selector, String[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public List selectOption(String selector, SelectOption values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public List selectOption(String selector, ElementHandle[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public List selectOption(String selector, SelectOption[] values, SelectOptionOptions options) { + return mainFrame.selectOption(selector, values, convertType(options, Frame.SelectOptionOptions.class)); + } + + @Override + public void setInputFiles(String selector, Path files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + } + + @Override + public void setInputFiles(String selector, Path[] files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + } + + @Override + public void setInputFiles(String selector, FilePayload files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + } + + @Override + public void setInputFiles(String selector, FilePayload[] files, SetInputFilesOptions options) { + mainFrame.setInputFiles(selector, files, convertType(options, Frame.SetInputFilesOptions.class)); + } + + @Override + public void type(String selector, String text, TypeOptions options) { + mainFrame.type(selector, text, convertType(options, Frame.TypeOptions.class)); + } + + @Override + public void press(String selector, String key, PressOptions options) { + mainFrame.press(selector, key, convertType(options, Frame.PressOptions.class)); + } + + @Override + public void check(String selector, CheckOptions options) { + mainFrame.check(selector, convertType(options, Frame.CheckOptions.class)); + } + + @Override + public void uncheck(String selector, UncheckOptions options) { + mainFrame.uncheck(selector, convertType(options, Frame.UncheckOptions.class)); + } + + @Override + public void setChecked(String selector, boolean checked, SetCheckedOptions options) { + mainFrame.setChecked(selector, checked, convertType(options, Frame.SetCheckedOptions.class)); + } + + @Override + public void waitForTimeout(double timeout) { + mainFrame.waitForTimeout(timeout); + } + + @Override + public JSHandle waitForFunction(String expression, Object arg, WaitForFunctionOptions options) { + return mainFrame.waitForFunction(expression, arg, convertType(options, Frame.WaitForFunctionOptions.class)); + } + + @Override + public List requests() { + PageRequestsResult result = channel.requests(NO_TIMEOUT); + return new ArrayList<>(result.requests); + } + + @Override + public List workers() { + return new ArrayList<>(workers); + } + + // java: there is no JS debugger to detect and no instrumentation to notify. + @Override + public void pause() { + Double defaultNavigationTimeout = browserContext.timeoutSettings.defaultNavigationTimeout(); + Double defaultTimeout = browserContext.timeoutSettings.defaultTimeout(); + browserContext.setDefaultNavigationTimeout(0); + browserContext.setDefaultTimeout(0); + // java: closedOrCrashedScope.safeRace(promise) is a race of the reply with a close helper that returns null. + WaitableResult pause = browserContext.sendMessageAsync("pause"); + runUntil(() -> {}, new WaitableRace<>(asList(pause, new ClosedOrCrashed<>(true)))); + // java: the saved defaults may be unset, which the public double setters cannot express. + browserContext.timeoutSettings.setDefaultNavigationTimeout(defaultNavigationTimeout); + browserContext.timeoutSettings.setDefaultTimeout(defaultTimeout); + } + + // java: width, height and the margins are strings in the Java API, there is nothing to convert to px. + @Override + public byte[] pdf(PdfOptions options) { + if (options == null) { + options = new PdfOptions(); + } + PagePdfParams transportOptions = toProtocol(options, PagePdfParams.class); + PagePdfResult result = channel.pdf(transportOptions, NO_TIMEOUT); + if (options.path != null) { + Utils.writeToFile(result.pdf, options.path); + } + return result.pdf; + } + + @Override + public String ariaSnapshot(AriaSnapshotOptions options) { + if (options == null) { + options = new AriaSnapshotOptions(); + } + FrameAriaSnapshotParams params = new FrameAriaSnapshotParams(); + 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; + } + + private static String trimUrl(Object param) { + if (param instanceof Pattern) { + Pattern pattern = (Pattern) param; + return "/" + trimStringWithEllipsis(pattern.pattern(), 50) + "/" + toJsRegexFlags(pattern); + } + if (param instanceof String) { + return "\"" + trimStringWithEllipsis((String) param, 50) + "\""; + } + return null; + } + + // java: trimStringWithEllipsis of isomorphic/stringUtils.ts, counting code points like [...input]. + 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) + "…"; + } + return input; + } + + // java: the value object of _locatorHandlers. + private static class LocatorHandler { + final LocatorImpl locator; + final Consumer handler; + Integer times; + + LocatorHandler(LocatorImpl locator, Consumer handler, Integer times) { + this.locator = locator; + this.handler = handler; + this.times = times; + } + } + + // java: the public API members with no upstream counterpart: accessors of the readonly fields, typed + // listeners, onceDialog, waitForCondition, and the close helpers that stand in for _closedOrCrashedScope. + @Override + public ClockImpl clock() { + return clock; + } + + @Override + public KeyboardImpl keyboard() { + return keyboard; + } + + @Override + public MouseImpl mouse() { + return mouse; + } + + @Override + public APIRequestContextImpl request() { + return request; + } + + @Override + public TouchscreenImpl touchscreen() { + return touchscreen; + } + + @Override + public Screencast screencast() { + return screencast; + } + + @Override + public WebStorage localStorage() { + return localStorage; + } + + @Override + public WebStorage sessionStorage() { + return sessionStorage; + } + + @Override + public WebMCP webmcp() { + return webmcp; + } + + @Override + public void onClose(Consumer handler) { + on(Events.Page.CLOSE, handler); + } + + @Override + public void offClose(Consumer handler) { + off(Events.Page.CLOSE, handler); + } + + @Override + public void onConsoleMessage(Consumer handler) { + on(Events.Page.CONSOLE, handler); + } + + @Override + public void offConsoleMessage(Consumer handler) { + off(Events.Page.CONSOLE, handler); + } + + @Override + public void onCrash(Consumer handler) { + on(Events.Page.CRASH, handler); + } + + @Override + public void offCrash(Consumer handler) { + off(Events.Page.CRASH, handler); + } + + @Override + public void onDialog(Consumer handler) { + on(Events.Page.DIALOG, handler); + } + + @Override + public void offDialog(Consumer handler) { + off(Events.Page.DIALOG, handler); + } + + @Override + public void onDialogClosed(Consumer handler) { + on(Events.Page.DIALOG_CLOSED, handler); + } + + @Override + public void offDialogClosed(Consumer handler) { + off(Events.Page.DIALOG_CLOSED, handler); + } + + @Override + public void onDOMContentLoaded(Consumer handler) { + on(Events.Page.DOM_CONTENT_LOADED, handler); + } + + @Override + public void offDOMContentLoaded(Consumer handler) { + off(Events.Page.DOM_CONTENT_LOADED, handler); + } + + @Override + public void onDownload(Consumer handler) { + on(Events.Page.DOWNLOAD, handler); + } + + @Override + public void offDownload(Consumer handler) { + off(Events.Page.DOWNLOAD, handler); + } + + @Override + public void onFileChooser(Consumer handler) { + on(Events.Page.FILE_CHOOSER, handler); + } + + @Override + public void offFileChooser(Consumer handler) { + off(Events.Page.FILE_CHOOSER, handler); + } + + @Override + public void onFrameAttached(Consumer handler) { + on(Events.Page.FRAME_ATTACHED, handler); + } + + @Override + public void offFrameAttached(Consumer handler) { + off(Events.Page.FRAME_ATTACHED, handler); + } + + @Override + public void onFrameDetached(Consumer handler) { + on(Events.Page.FRAME_DETACHED, handler); + } + + @Override + public void offFrameDetached(Consumer handler) { + off(Events.Page.FRAME_DETACHED, handler); + } + + @Override + public void onFrameNavigated(Consumer handler) { + on(Events.Page.FRAME_NAVIGATED, handler); + } + + @Override + public void offFrameNavigated(Consumer handler) { + off(Events.Page.FRAME_NAVIGATED, handler); + } + + @Override + public void onLoad(Consumer handler) { + on(Events.Page.LOAD, handler); + } + + @Override + public void offLoad(Consumer handler) { + off(Events.Page.LOAD, handler); + } + + @Override + public void onPageError(Consumer handler) { + on(Events.Page.PAGE_ERROR, handler); + } + + @Override + public void offPageError(Consumer handler) { + off(Events.Page.PAGE_ERROR, handler); + } + + @Override + public void onPopup(Consumer handler) { + on(Events.Page.POPUP, handler); + } + + @Override + public void offPopup(Consumer handler) { + off(Events.Page.POPUP, handler); + } + + @Override + public void onRequest(Consumer handler) { + on(Events.Page.REQUEST, handler); + } + + @Override + public void offRequest(Consumer handler) { + off(Events.Page.REQUEST, handler); + } + + @Override + public void onRequestFailed(Consumer handler) { + on(Events.Page.REQUEST_FAILED, handler); + } + + @Override + public void offRequestFailed(Consumer handler) { + off(Events.Page.REQUEST_FAILED, handler); + } + + @Override + public void onRequestFinished(Consumer handler) { + on(Events.Page.REQUEST_FINISHED, handler); + } + + @Override + public void offRequestFinished(Consumer handler) { + off(Events.Page.REQUEST_FINISHED, handler); + } + + @Override + public void onResponse(Consumer handler) { + on(Events.Page.RESPONSE, handler); + } + + @Override + public void offResponse(Consumer handler) { + off(Events.Page.RESPONSE, handler); + } + + @Override + public void onWebSocket(Consumer handler) { + on(Events.Page.WEB_SOCKET, handler); + } + + @Override + public void offWebSocket(Consumer handler) { + off(Events.Page.WEB_SOCKET, handler); + } + + @Override + public void onWorker(Consumer handler) { + on(Events.Page.WORKER, handler); + } + + @Override + public void offWorker(Consumer handler) { + off(Events.Page.WORKER, handler); + } + + @Override + public void onceDialog(Consumer handler) { + onDialog(new Consumer() { + @Override + public void accept(Dialog dialog) { + try { + handler.accept(dialog); + } finally { + offDialog(this); + } + } + }); + } + + @Override + public void waitForCondition(BooleanSupplier condition, WaitForConditionOptions options) { + List> waitables = new ArrayList<>(); + waitables.add(createWaitForCloseHelper()); + waitables.add(createWaitableTimeout(options == null ? null : options.timeout)); + waitables.add(new WaitablePredicate<>(condition)); + runUntil(() -> {}, new WaitableRace<>(waitables)); + } + + // A race with _closedOrCrashedScope: done once the page closed or crashed, then throws the error the scope was closed with. + Waitable createWaitForCloseHelper() { + return new ClosedOrCrashed<>(false); + } + + Waitable createWaitableTimeout(Double timeout) { + return timeoutSettings.createWaitable(timeout); + } + + private class ClosedOrCrashed implements Waitable { + private final boolean safe; + + ClosedOrCrashed(boolean safe) { + this.safe = safe; + } + + @Override + public boolean isDone() { + return closedOrCrashedScope != null; + } + + @Override + public T get() { + if (safe) { + return null; + } + throw new TargetClosedError(closedOrCrashedScope.getMessage()); + } + + @Override + public void dispose() { + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java new file mode 100644 index 000000000..e22173411 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -0,0 +1,165 @@ +/* + * 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 playwright.ts. +package com.microsoft.playwright.impl; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.microsoft.playwright.BrowserContext; +import com.microsoft.playwright.Page; +import com.microsoft.playwright.Playwright; +import com.microsoft.playwright.PlaywrightException; +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.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class PlaywrightImpl extends ChannelOwner implements Playwright { + // java: Android and Electron are not ported. + final BrowserTypeImpl chromium; + final BrowserTypeImpl firefox; + final BrowserTypeImpl webkit; + // java: no devices field, deviceDescriptors() reads them from LocalUtils. + SelectorsImpl selectors; + final APIRequestImpl request; + // java: no errors field, TimeoutError is a public class. No _defaultLaunchOptions, _defaultContextTimeout and + // _defaultContextNavigationTimeout, the test runner sets them upstream. + + 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; + selectors = new SelectorsImpl(); + } + + private List browserTypes() { + return Arrays.asList(chromium, firefox, webkit); + } + + // java: no _preLaunchedBrowser, only the test runner calls it upstream. + + List allContexts() { + List result = new ArrayList<>(); + for (BrowserTypeImpl type : browserTypes()) { + result.addAll(type.contexts); + } + return result; + } + + List allPages() { + List result = new ArrayList<>(); + for (BrowserContext context : allContexts()) { + result.addAll(context.pages()); + } + 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) { + return createImpl(options, false); + } + + public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewDriverInstanceForTests) { + Map env = Collections.emptyMap(); + if (options != null && options.env != null) { + env = options.env; + } + Driver driver = forceNewDriverInstanceForTests ? + Driver.createAndInstall(env, true) : + 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. + pb.environment().putAll(env); + pb.command().add("run-driver"); + pb.redirectError(ProcessBuilder.Redirect.INHERIT); + Process p = pb.start(); + Connection connection = new Connection(new PipeTransport(p.getInputStream(), p.getOutputStream()), env); + PlaywrightImpl result = connection.initializePlaywright(); + result.driverProcess = p; + return result; + } catch (IOException e) { + throw new PlaywrightException("Failed to launch driver", e); + } + } + + public LocalUtils localUtils() { + return connection.localUtils(); + } + + public JsonArray deviceDescriptors() { + return localUtils().deviceDescriptors(); + } + + @Override + public BrowserTypeImpl chromium() { + return chromium; + } + + @Override + public BrowserTypeImpl firefox() { + return firefox; + } + + @Override + public APIRequestImpl request() { + return request; + } + + @Override + public BrowserTypeImpl webkit() { + return webkit; + } + + @Override + public SelectorsImpl selectors() { + return selectors; + } + + @Override + public void close() { + try { + connection.close(); + // playwright-cli will exit when its stdin is closed, we 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"); + } + } catch (IOException e) { + throw new PlaywrightException("Failed to terminate", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new PlaywrightException("Operation interrupted", e); + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java new file mode 100644 index 000000000..bf35c9353 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java @@ -0,0 +1,120 @@ +/* + * 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.PlaywrightException; +import com.microsoft.playwright.impl.protocol.NameValue; +import com.microsoft.playwright.options.HttpHeader; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +class RawHeaders { + private final List headersArray; + // java: MultiMap is a map of lists. + private final Map> headersMap = new LinkedHashMap<>(); + + 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(header.value); + } + } + + String get(String name) { + List values = getAll(name); + if (values == null || values.isEmpty()) { + return null; + } + return String.join("set-cookie".equals(name.toLowerCase()) ? "\n" : ", ", values); + } + + List getAll(String name) { + 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()) { + result.put(name, get(name)); + } + return result; + } + + // java: a new list of the public HttpHeader type on every call. + List 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: module-level functions of network.ts and isomorphic/headers.ts used with headers. + static void validateHeaders(Map headers) { + if (headers == null) { + return; + } + 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."); + } + } + } + + static List headersObjectToArray(Map headers) { + List result = 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(); + result.add(header); + } + return result; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java new file mode 100644 index 000000000..3ceb6f539 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java @@ -0,0 +1,351 @@ +/* + * 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.google.gson.JsonObject; +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.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import static com.microsoft.playwright.impl.Serialization.gson; + +public class RequestImpl extends ChannelOwner implements Request { + // 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; + 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; + + RequestImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + 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 != null ? requestInitializer.headers : new ArrayList<>()); + 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 String url() { + return fallbackOverrides.url != null && !fallbackOverrides.url.isEmpty() ? fallbackOverrides.url : requestInitializer.url; + } + + @Override + public String resourceType() { + return requestInitializer.resourceType; + } + + @Override + public String method() { + return fallbackOverrides.method != null && !fallbackOverrides.method.isEmpty() ? fallbackOverrides.method : requestInitializer.method; + } + + @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 byte[] postDataBuffer() { + if (fallbackOverrides.postDataBuffer != null) { + return fallbackOverrides.postDataBuffer; + } + return requestInitializer.postData; + } + + // java: postDataJSON() is not in the Java API. + + @Override + public Map 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 actualHeadersPromise; + } + + @Override + public Map allHeaders() { + return wrapApiCall(() -> actualHeaders().headers(), null, true); + } + + @Override + public List headersArray() { + return wrapApiCall(() -> actualHeaders().headersArray(), null, true); + } + + @Override + public String headerValue(String name) { + return wrapApiCall(() -> actualHeaders().get(name), null, true); + } + + @Override + public ResponseImpl response() { + return channel.response(NO_TIMEOUT).response; + } + + ResponseImpl internalResponse() { + return channel.response(NO_TIMEOUT).response; + } + + @Override + public ResponseImpl existingResponse() { + return response; + } + + @Override + public FrameImpl frame() { + if (requestInitializer.frame == null) { + throw new PlaywrightException("Service Worker requests do not have an associated frame."); + } + 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 boolean isNavigationRequest() { + return requestInitializer.isNavigationRequest != null && requestInitializer.isNavigationRequest; + } + + @Override + public RequestImpl redirectedFrom() { + return redirectedFrom; + } + + @Override + public RequestImpl redirectedTo() { + return redirectedTo; + } + + // java: the error text itself, the Java API returns a String. + @Override + public String failure() { + return failureText; + } + + @Override + public Timing timing() { + return timing; + } + + @Override + public Sizes sizes() { + ResponseImpl response = response(); + if (response == null) { + throw new PlaywrightException("Unable to fetch sizes for failed request"); + } + RequestSizes sizes = response.channel.sizes(NO_TIMEOUT).sizes; + Sizes result = new Sizes(); + result.requestBodySize = sizes.requestBodySize; + result.requestHeadersSize = sizes.requestHeadersSize; + result.responseBodySize = sizes.responseBodySize; + result.responseHeadersSize = sizes.responseHeadersSize; + return result; + } + + void setResponseEndTiming(double responseEndTiming) { + timing.responseEnd = responseEndTiming; + if (timing.responseStart == -1) { + timing.responseStart = responseEndTiming; + } + } + + RequestImpl finalRequest() { + return redirectedTo != null ? redirectedTo.finalRequest() : this; + } + + void applyFallbackOverrides(FallbackOverrides overrides) { + if (overrides.url != null && !overrides.url.isEmpty()) { + fallbackOverrides.url = overrides.url; + } + if (overrides.method != null && !overrides.method.isEmpty()) { + fallbackOverrides.method = overrides.method; + } + if (overrides.headers != null) { + fallbackOverrides.headers = overrides.headers; + } + + 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); + } + } + + SerializedFallbackOverrides fallbackOverridesForContinue() { + return fallbackOverrides; + } + + // java: there is no LongStandingScope; the scope watches the close events of the service worker or the page. + TargetClosedScope targetClosedScope() { + WorkerImpl serviceWorker = serviceWorker(); + if (serviceWorker != null) { + return new TargetClosedScope(this, serviceWorker, Events.Worker.CLOSE, serviceWorker::closeErrorWithReason, null, null); + } + PageImpl page = safePage(); + if (page != null) { + return new TargetClosedScope(this, page, Events.Page.CLOSE, page::closeErrorWithReason, Events.Page.CRASH, TargetClosedError::new); + } + return new TargetClosedScope(this, null, null, null, null, null); + } + + // java: the LongStandingScope of a service worker or a page, built on Waitables. + static class TargetClosedScope { + private final ChannelOwner owner; + private final EventEmitter target; + private final String closeEvent; + private final Supplier closeError; + private final String crashEvent; + private final Supplier crashError; + + TargetClosedScope(ChannelOwner owner, EventEmitter target, String closeEvent, Supplier closeError, + String crashEvent, Supplier crashError) { + this.owner = owner; + this.target = target; + this.closeEvent = closeEvent; + this.closeError = closeError; + this.crashEvent = crashEvent; + this.crashError = crashError; + } + + private boolean isClosed() { + if (target instanceof PageImpl) { + return ((PageImpl) target).isClosed(); + } + return false; + } + + T race(Waitable promise) { + return race(promise, false); + } + + T safeRace(Waitable promise) { + return race(promise, true); + } + + private T race(Waitable promise, boolean safe) { + // java: a settled promise wins over the terminate promise, as its reaction runs first upstream. + if (target == null || promise.isDone()) { + return owner.runUntil(() -> {}, promise); + } + if (isClosed()) { + promise.dispose(); + if (safe) { + return null; + } + throw closeError.get(); + } + List> waitables = new ArrayList<>(); + waitables.add(terminateWaitable(closeEvent, closeError, safe)); + if (crashEvent != null) { + waitables.add(terminateWaitable(crashEvent, crashError, safe)); + } + waitables.add(promise); + return owner.runUntil(() -> {}, new WaitableRace<>(waitables)); + } + + private Waitable terminateWaitable(String event, Supplier error, boolean safe) { + return new WaitableEvent(target, event) { + @Override + public T get() { + if (safe) { + return null; + } + throw error.get(); + } + }; + } + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java new file mode 100644 index 000000000..9454f094c --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java @@ -0,0 +1,204 @@ +/* + * 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.google.gson.JsonObject; +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 java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class ResponseImpl extends ChannelOwner implements Response { + 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; + + ResponseImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + responseInitializer = connection.protocolGson().fromJson(initializer, ResponseInitializer.class); + this.provisionalHeaders = new RawHeaders(responseInitializer.headers != null ? responseInitializer.headers : new ArrayList<>()); + this.request = responseInitializer.request; + this.request.response = this; + assignTiming(this.request, responseInitializer.timing); + } + + @Override + public String url() { + return responseInitializer.url; + } + + @Override + public boolean ok() { + // Status 0 is for file:// URLs + return responseInitializer.status == 0 || (responseInitializer.status >= 200 && responseInitializer.status <= 299); + } + + @Override + public int status() { + return responseInitializer.status; + } + + @Override + public String statusText() { + return responseInitializer.statusText; + } + + @Override + public boolean fromServiceWorker() { + return responseInitializer.fromServiceWorker != null && responseInitializer.fromServiceWorker; + } + + @Override + public Map headers() { + return provisionalHeaders.headers(); + } + + RawHeaders actualHeaders() { + if (actualHeadersPromise == null) { + actualHeadersPromise = new RawHeaders(channel.rawResponseHeaders(NO_TIMEOUT).headers); + } + return actualHeadersPromise; + } + + @Override + public Map allHeaders() { + return actualHeaders().headers(); + } + + @Override + public List headersArray() { + return actualHeaders().headersArray(); + } + + @Override + public String headerValue(String name) { + return actualHeaders().get(name); + } + + @Override + public List headerValues(String name) { + return actualHeaders().getAll(name); + } + + @Override + 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: json() is not in the Java API. + + @Override + public RequestImpl request() { + return request; + } + + @Override + public FrameImpl frame() { + return request.frame(); + } + + @Override + public ServerAddr serverAddr() { + RemoteAddr value = channel.serverAddr(NO_TIMEOUT).value; + 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; + return result; + } + + @Override + 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 httpVersion() { + return channel.httpVersion(NO_TIMEOUT).value; + } + + // java: Object.assign(this._request._timing, this._initializer.timing). + private static void assignTiming(RequestImpl request, ResourceTiming timing) { + if (timing == null) { + return; + } + if (timing.startTime != null) { + request.timing.startTime = timing.startTime; + } + if (timing.domainLookupStart != null) { + request.timing.domainLookupStart = timing.domainLookupStart; + } + if (timing.domainLookupEnd != null) { + request.timing.domainLookupEnd = timing.domainLookupEnd; + } + if (timing.connectStart != null) { + request.timing.connectStart = timing.connectStart; + } + if (timing.secureConnectionStart != null) { + request.timing.secureConnectionStart = timing.secureConnectionStart; + } + if (timing.connectEnd != null) { + request.timing.connectEnd = timing.connectEnd; + } + if (timing.requestStart != null) { + request.timing.requestStart = timing.requestStart; + } + if (timing.responseStart != null) { + 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..c03a0e027 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java @@ -0,0 +1,176 @@ +/* + * 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.net.URL; +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: { complete: Promise, route: Route }. + private static class HandlerInvocation { + final WaitableResult complete = new WaitableResult<>(); + final RouteImpl route; + + HandlerInvocation(RouteImpl route) { + this.route = route; + } + } + + // java: the UrlMatcher has resolved a glob against the base URL and validated it already, baseURL is + // kept for the upstream signature only. 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; + } + + RouteHandler(String baseURL, UrlMatcher url, Consumer handler) { + this(baseURL, url, handler, null); + } + + // java: the base URL of the context as a java.net.URL. + RouteHandler(URL baseURL, UrlMatcher url, Consumer handler, Integer times) { + this(baseURL != null ? baseURL.toString() : null, url, handler, times); + } + + RouteHandler(URL baseURL, UrlMatcher url, Consumer handler) { + this(baseURL, url, handler, null); + } + + // 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: there are no zones to restore. + 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 new file mode 100644 index 000000000..609b90493 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -0,0 +1,267 @@ +/* + * 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.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.microsoft.playwright.APIResponse; +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.nio.file.Path; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; + +import static com.microsoft.playwright.impl.RawHeaders.headersObjectToArray; + +public class RouteImpl extends ChannelOwner implements Route { + private WaitableResult handlingPromise = null; + BrowserContextImpl context; + boolean didThrow = false; + + final RouteChannel channel = new RouteChannel(this); + private final RouteInitializer routeInitializer; + + RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + routeInitializer = connection.protocolGson().fromJson(initializer, RouteInitializer.class); + } + + @Override + public RequestImpl request() { + return routeInitializer.request; + } + + // 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); + } + + WaitableResult startHandling() { + handlingPromise = new WaitableResult<>(); + return handlingPromise; + } + + @Override + public void fallback(FallbackOptions options) { + if (options == null) { + options = new FallbackOptions(); + } + checkNotHandled(); + request().applyFallbackOverrides(fallbackOverrides(options.url, options.method, options.headers, options.postData)); + reportHandled(false); + // java: RouteHandler.handle() returned when the handler did, nobody waits for the outcome of a later + // fallback(), so the request continues to the network as the default handler of the context does. + if (handlerReturned) { + try { + innerContinue(true); + } catch (PlaywrightException e) { + } + } + } + + @Override + public void abort(String errorCode) { + handleRoute(() -> { + RouteAbortParams params = new RouteAbortParams(); + params.errorCode = errorCode; + raceWithTargetClose(sendMessageAsync("abort", params)); + }); + } + + void redirectNavigationRequest(String url) { + handleRoute(() -> { + RouteRedirectNavigationRequestParams params = new RouteRedirectNavigationRequestParams(); + params.url = url; + raceWithTargetClose(sendMessageAsync("redirectNavigationRequest", params)); + }); + } + + @Override + public APIResponse fetch(FetchOptions options) { + if (options == null) { + options = new FetchOptions(); + } + 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, false); + } + + @Override + public void fulfill(FulfillOptions options) { + handleRoute(() -> { + innerFulfill(options); + }); + } + + private void handleRoute(Runnable callback) { + checkNotHandled(); + try { + callback.run(); + reportHandled(true); + } catch (RuntimeException e) { + didThrow = true; + throw e; + } + } + + private void innerFulfill(FulfillOptions options) { + if (options == null) { + options = new FulfillOptions(); + } + String fetchResponseUid = null; + Integer statusOption = options.status; + Map headersOption = options.headers; + // java: body is a String (body) or a byte[] (bodyBytes); there is no json option. + Object body = options.body != null ? options.body : options.bodyBytes; + + if (options.response instanceof APIResponseImpl) { + APIResponseImpl response = (APIResponseImpl) options.response; + if (statusOption == null) { + statusOption = response.status(); + } + if (headersOption == null) { + headersOption = response.headers(); + } + if (body == null && options.path == null) { + if (response.request.connection == this.connection) { + fetchResponseUid = response.fetchUid(); + } else { + body = response.body(); + } + } + } + + boolean isBase64 = false; + int length = 0; + if (options.path != null) { + byte[] buffer = readFile(options.path); + body = Base64.getEncoder().encodeToString(buffer); + isBase64 = true; + length = buffer.length; + } else if (body instanceof String) { + isBase64 = false; + 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; + } + + Map headers = new LinkedHashMap<>(); + if (headersOption != null) { + 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 (options.path != null) { + headers.put("content-type", Utils.mimeType(options.path)); + } + if (length != 0 && !headers.containsKey("content-length")) { + headers.put("content-length", String.valueOf(length)); + } + + RouteFulfillParams params = new RouteFulfillParams(); + params.status = statusOption != null && statusOption != 0 ? statusOption : 200; + params.headers = headersObjectToArray(headers); + params.body = (String) body; + params.isBase64 = isBase64; + params.fetchResponseUid = fetchResponseUid; + raceWithTargetClose(sendMessageAsync("fulfill", params)); + } + + // java: resume() is continue() of the Node.js API. + @Override + public void resume(ResumeOptions options) { + ResumeOptions resumeOptions = options == null ? new ResumeOptions() : options; + handleRoute(() -> { + request().applyFallbackOverrides(fallbackOverrides(resumeOptions.url, resumeOptions.method, resumeOptions.headers, resumeOptions.postData)); + innerContinue(false /* isFallback */); + }); + } + + 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: helpers with no counterpart upstream. + + // java: set by RouteHandler when the handler returned before it fulfilled, continued 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/TracingImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java new file mode 100644 index 000000000..009e0bf9b --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -0,0 +1,365 @@ +/* + * 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 tracing.ts. +package com.microsoft.playwright.impl; + +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.Collections; +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; + +public class TracingImpl extends ChannelOwner implements Tracing { + 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 boolean isTracing = false; + private String harId; + private final Map harRecorders = new LinkedHashMap<>(); + + final TracingChannel channel = new TracingChannel(this); + + TracingImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + } + + @Override + public AutoCloseable start(StartOptions options) { + 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.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) { + 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) { + if (options == null) { + options = new GroupOptions(); + } + if (options.location != null) { + additionalSources.add(options.location.file); + } + 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(new TracingTracingGroupEndParams(), NO_TIMEOUT); + } + + private void startCollectingStacks(String traceName, boolean live) { + if (!isTracing) { + isTracing = true; + connection.setIsTracing(true); + } + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + stacksId = null; + return; + } + // java: LocalUtils.tracingStarted of the seed has no live flag and drops tracesDir, the params go to the channel as upstream passes them. + LocalUtilsTracingStartedParams params = new LocalUtilsTracingStartedParams(); + params.tracesDir = tracesDir == null ? null : tracesDir.toString(); + params.traceName = traceName; + params.live = live; + LocalUtilsTracingStartedResult result = localUtils.channel.tracingStarted(params, NO_TIMEOUT); + stacksId = result == null ? null : result.stacksId; + } + + @Override + public void stopChunk(StopChunkOptions options) { + Path path = options == null ? null : options.path; + wrapApiCall(() -> { + doStopChunk(path); + }, null, false); + } + + @Override + public void stop(StopOptions options) { + 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); + } + + @Override + public AutoCloseable startHar(Path path, StartHarOptions options) { + 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() { + wrapApiCall(() -> { + String harId = this.harId; + if (harId == null) { + throw new PlaywrightException("HAR recording has not been started"); + } + this.harId = null; + exportHAR(harId); + }, null, false); + } + + // 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; + 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, resourcesDir)); + return 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); + + if (isLocal) { + TracingHarExportParams params = new TracingHarExportParams(); + params.harId = harId; + params.mode = "entries"; + List entries = channel.harExport(params, NO_TIMEOUT).entries; + if (!isZip) { + // Server wrote HAR and resources to the user's chosen paths. + return; + } + LocalUtils localUtils = connection.localUtils(); + if (localUtils == null) { + throw new PlaywrightException("Cannot save zipped HAR in thin clients"); + } + localUtils.zip(harParams.path, entries, null, false, false, Collections.emptyList()); + return; + } + + TracingHarExportParams params = new TracingHarExportParams(); + params.harId = harId; + params.mode = "archive"; + ArtifactImpl artifact = channel.harExport(params, NO_TIMEOUT).artifact; + if (isZip) { + artifact.saveAs(harParams.path); + artifact.delete(); + return; + } + 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 = harParams.path + ".tmp"; + unzipParams.harFile = harParams.path.toString(); + unzipParams.resourcesDir = harParams.resourcesDir == null ? null : harParams.resourcesDir.toString(); + // java: the seed LocalUtils has no harUnzip wrapper. + localUtils.channel.harUnzip(unzipParams, NO_TIMEOUT); + artifact.delete(); + } + + void exportAllHars() { + 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(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(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); + localUtils.zip(filePath, result.entries, stacksId, false, includeSources, additionalSources); + 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(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(); + + localUtils.zip(filePath, new ArrayList<>(), stacksId, true, includeSources, additionalSources); + } + + 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"); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java new file mode 100644 index 000000000..20b5b92e8 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketFrameImpl.java @@ -0,0 +1,48 @@ +/* + * 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.util.Base64; + +// java: the { payload: string | Buffer } of the WebSocket frame events and the messages of WebSocketRoute. +class WebSocketFrameImpl implements WebSocketFrame { + 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; + } + } + + @Override + public byte[] binary() { + return bytes; + } + + @Override + public String text() { + return text; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java new file mode 100644 index 000000000..c500b2374 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java @@ -0,0 +1,166 @@ +/* + * 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.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.function.Consumer; +import java.util.function.Predicate; + +public class WebSocketImpl extends ChannelOwner implements WebSocket { + private final PageImpl page; + private boolean isClosed; + + final WebSocketChannel channel = new WebSocketChannel(this); + private final WebSocketInitializer webSocketInitializer; + + WebSocketImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + 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); + } + + @Override + public void offClose(Consumer handler) { + off(Events.WebSocket.CLOSE, handler); + } + + @Override + public void onFrameReceived(Consumer handler) { + on(Events.WebSocket.FRAME_RECEIVED, handler); + } + + @Override + public void offFrameReceived(Consumer handler) { + off(Events.WebSocket.FRAME_RECEIVED, handler); + } + + @Override + public void onFrameSent(Consumer handler) { + on(Events.WebSocket.FRAME_SENT, handler); + } + + @Override + public void offFrameSent(Consumer handler) { + off(Events.WebSocket.FRAME_SENT, handler); + } + + @Override + public void onSocketError(Consumer handler) { + on(Events.WebSocket.ERROR, handler); + } + + @Override + public void offSocketError(Consumer handler) { + off(Events.WebSocket.ERROR, handler); + } + + @Override + public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable callback) { + if (options == null) { + options = new WaitForFrameReceivedOptions(); + } + return waitForEvent(Events.WebSocket.FRAME_RECEIVED, options.predicate, options.timeout, callback); + } + + @Override + public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable callback) { + if (options == null) { + options = new WaitForFrameSentOptions(); + } + return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, callback); + } +} 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..04e9d747d --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java @@ -0,0 +1,96 @@ +/* + * 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.net.URL; +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: the UrlMatcher has resolved a glob against the base URL and validated it already, baseURL is + // kept for the upstream signature only. + WebSocketRouteHandler(String baseURL, UrlMatcher url, Consumer handler) { + this.baseURL = baseURL; + this.url = url; + this.handler = handler; + } + + // java: the base URL of the context as a java.net.URL. + WebSocketRouteHandler(URL baseURL, UrlMatcher url, Consumer handler) { + this(baseURL != null ? baseURL.toString() : null, url, 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 new file mode 100644 index 000000000..4678c54dc --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java @@ -0,0 +1,253 @@ +/* + * 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.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; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +import static com.microsoft.playwright.impl.Utils.toProtocol; + +public class WebSocketRouteImpl extends ChannelOwner implements WebSocketRoute { + private Consumer onPageMessage; + private BiConsumer onPageClose; + private Consumer onServerMessage; + private BiConsumer onServerClose; + 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; + } + + @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 String url() { + return webSocketRouteInitializer.url; + } + + @Override + public List protocols() { + return WebSocketRouteImpl.this.protocols(); + } + + @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) { + } + } + + // 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 void send(byte[] message) { + WebSocketRouteSendToServerParams params = new WebSocketRouteSendToServerParams(); + params.message = Base64.getEncoder().encodeToString(message); + params.isBase64 = true; + sendNoWait("sendToServer", params); + } + }; + } + + // 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; + } + } + } + + @Override + public String url() { + return webSocketRouteInitializer.url; + } + + @Override + public List protocols() { + return webSocketRouteInitializer.protocols != null ? new ArrayList<>(webSocketRouteInitializer.protocols) : new ArrayList<>(); + } + + @Override + public void close(CloseOptions options) { + 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 + public WebSocketRoute connectToServer() { + if (connected) { + throw new PlaywrightException("Already connected to the server"); + } + connected = true; + sendNoWait("connect", new WebSocketRouteConnectParams()); + return server; + } + + // java: send(string | Buffer) is two overloads. + @Override + public void send(String message) { + WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); + params.message = message; + params.isBase64 = false; + sendNoWait("sendToPage", params); + } + + @Override + public void send(byte[] message) { + WebSocketRouteSendToPageParams params = new WebSocketRouteSendToPageParams(); + params.message = Base64.getEncoder().encodeToString(message); + params.isBase64 = true; + sendNoWait("sendToPage", params); + } + + @Override + public void onMessage(Consumer handler) { + onPageMessage = handler; + } + + @Override + public void onClose(BiConsumer handler) { + onPageClose = handler; + } + + void afterHandle() { + 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 { + channel.ensureOpened(NO_TIMEOUT); + } catch (PlaywrightException e) { + } + } + + // 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) { + } + } +} From debac0a9f5e9c762a8ec0cfa49fce544b01eff87 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Thu, 19 Nov 2026 18:54:14 -0800 Subject: [PATCH 26/30] fix: subscribe before pumping in waitForURL, let the condition win in waitForCondition, drop three fixmes --- .../com/microsoft/playwright/impl/FrameImpl.java | 15 +++++++++++---- .../com/microsoft/playwright/impl/PageImpl.java | 3 ++- .../com/microsoft/playwright/TestGlobalFetch.java | 2 +- .../playwright/tests/library/TestGlobalFetch.java | 1 - .../playwright/tests/page/TestLocatorQuery.java | 1 - .../tests/page/TestPageSetInputFiles.java | 1 - 6 files changed, 14 insertions(+), 9 deletions(-) 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 3dc82f9ae..82fd1e072 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -151,6 +151,13 @@ public ResponseImpl waitForNavigation(WaitForNavigationOptions options, Runnable if (options == null) { options = new WaitForNavigationOptions(); } + // 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(baseURL(), options.url, connection.localUtils(), false); + return waitForNavigation(matcher, options, callback); + } + + 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. @@ -159,8 +166,6 @@ public ResponseImpl waitForNavigation(WaitForNavigationOptions options, Runnable String toUrl = options.url instanceof String ? " to \"" + options.url + "\"" : ""; waiter.log("waiting for navigation" + toUrl + " until \"" + waitUntil + "\""); - // java: the matcher is built once, a glob is converted by a call to the driver that must not run inside the event handler. - UrlMatcher matcher = UrlMatcher.forOneOf(baseURL(), options.url, connection.localUtils(), false); FrameNavigatedEvent navigatedEvent = waiter.waitForEvent(eventEmitter, Events.Frame.NAVIGATED, (FrameNavigatedEvent event) -> { // Any failed navigation results in a rejection. if (event.error != null) { @@ -242,7 +247,9 @@ public void waitForURL(Predicate url, WaitForURLOptions options) { private void waitForURL(Object url, WaitForURLOptions options) { WaitForURLOptions waitOptions = options == null ? new WaitForURLOptions() : options; - if (UrlMatcher.forOneOf(baseURL(), url, connection.localUtils(), false).test(url())) { + // java: one matcher for the check and the wait, nothing pumps the connection between them. + UrlMatcher matcher = UrlMatcher.forOneOf(baseURL(), url, connection.localUtils(), false); + if (matcher.test(url())) { waitForLoadState(waitOptions.waitUntil == null ? "load" : lifecycleEvent(waitOptions.waitUntil), waitOptions.timeout); return; } @@ -251,7 +258,7 @@ private void waitForURL(Object url, WaitForURLOptions options) { navigationOptions.url = url; navigationOptions.waitUntil = waitOptions.waitUntil; navigationOptions.timeout = waitOptions.timeout; - waitForNavigation(navigationOptions, null); + waitForNavigation(matcher, navigationOptions, null); } @Override 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 d68d9caae..34b894f48 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -1687,9 +1687,10 @@ 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)); - waitables.add(new WaitablePredicate<>(condition)); runUntil(() -> {}, new WaitableRace<>(waitables)); } 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/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"); From 58c9da6f29758682289a62a538ccbeece8cd756f Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 20 Nov 2026 13:13:27 -0800 Subject: [PATCH 27/30] chore: review the translated classes line by line against the Node.js client --- .../impl/APIRequestContextImpl.java | 28 +--- .../playwright/impl/APIRequestImpl.java | 9 +- .../playwright/impl/APIResponseImpl.java | 11 +- .../playwright/impl/BindingCall.java | 1 + .../playwright/impl/BrowserContextImpl.java | 38 ++--- .../playwright/impl/BrowserImpl.java | 1 + .../playwright/impl/ElementHandleImpl.java | 63 ++++---- .../microsoft/playwright/impl/FrameImpl.java | 47 ++---- .../playwright/impl/FrameLocatorImpl.java | 5 +- .../microsoft/playwright/impl/HarRouter.java | 38 +---- .../microsoft/playwright/impl/JsonPipe.java | 25 ++-- .../playwright/impl/LocatorImpl.java | 32 ++--- .../playwright/impl/LocatorUtils.java | 120 ++++++++-------- .../microsoft/playwright/impl/PageImpl.java | 136 +++++++----------- .../playwright/impl/PlaywrightImpl.java | 10 +- .../microsoft/playwright/impl/RawHeaders.java | 3 - .../playwright/impl/RequestImpl.java | 87 +++++------ .../playwright/impl/ResponseImpl.java | 40 ++---- .../playwright/impl/RouteHandler.java | 18 +-- .../microsoft/playwright/impl/RouteImpl.java | 9 +- .../playwright/impl/TracingImpl.java | 10 +- .../microsoft/playwright/impl/UrlMatcher.java | 105 ++++++++------ .../impl/WebSocketRouteHandler.java | 9 +- .../playwright/impl/WebSocketRouteImpl.java | 4 +- .../TestPageSetExtraHttpHeaders.java | 2 +- ...TestBrowsercontextSetExtraHttpHeaders.java | 1 - 26 files changed, 345 insertions(+), 507 deletions(-) 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 6aaa52f27..89e53e687 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -40,6 +40,7 @@ import java.util.Map; import static com.microsoft.playwright.impl.Errors.isTargetClosedError; +import static com.microsoft.playwright.impl.RawHeaders.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; @@ -262,11 +263,6 @@ public String storageState(StorageStateOptions options) { return state; } - @Override - public TracingImpl tracing() { - return tracing; - } - // java: FormData values are String, Boolean, Integer, Path (upstream's ReadStream) or FilePayload. static FormField toFormField(String name, Object value) { FormField field = new FormField(); @@ -342,31 +338,21 @@ static List objectToArray(Map map) { return result; } - // java: helpers, the method override of the get/post/... shortcuts and isomorphic headersObjectToArray. + // 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; + } - // java: upstream overrides the method; an explicit RequestOptions.setMethod wins here, as it always did in Java. private static RequestOptionsImpl withMethod(RequestOptions options, String method) { RequestOptionsImpl impl = Utils.clone((RequestOptionsImpl) options); if (impl == null) { impl = new RequestOptionsImpl(); } - if (impl.method == null) { - impl.method = method; - } + impl.method = method; return impl; } - static List headersObjectToArray(Map headers) { - List result = new ArrayList<>(); - for (Map.Entry e : headers.entrySet()) { - if (e.getValue() == null) { - continue; - } - result.add(nameValue(e.getKey(), e.getValue())); - } - return result; - } - private static NameValue nameValue(String name, String value) { NameValue nv = new NameValue(); nv.name = name; 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 290f61e52..0a68bbe8b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -58,24 +58,23 @@ public APIRequestContextImpl newContext(NewContextOptions options) { Map extraHTTPHeaders = options.extraHTTPHeaders; List clientCertificates = options.clientCertificates; Object httpCredentials = options.httpCredentials; - Double timeout = options.timeout; // 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; - options.timeout = null; PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class); - params.extraHTTPHeaders = extraHTTPHeaders != null ? APIRequestContextImpl.headersObjectToArray(extraHTTPHeaders) : null; + params.extraHTTPHeaders = extraHTTPHeaders != null ? RawHeaders.headersObjectToArray(extraHTTPHeaders) : null; params.storageState = storageState; - // java: there are no default launch options with a tracesDir in the Java API. + // java: no _defaultLaunchOptions in the Java API, so no tracesDir here and none for context.tracing below. params.clientCertificates = BrowserContextImpl.toClientCertificatesProtocol(clientCertificates); params.httpCredentials = BrowserContextImpl.toHttpCredentialsProtocol(httpCredentials); APIRequestContextImpl context = playwright.channel.newRequest(params, NO_TIMEOUT).request; contexts.add(context); context.request = this; - context.timeoutSettings.setDefaultTimeout(timeout); + // java: no _defaultContextTimeout in the Java API. + context.timeoutSettings.setDefaultTimeout(options.timeout); 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 8a8df7222..18347b9ee 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java @@ -90,13 +90,7 @@ public SecurityDetails securityDetails() { @Override public ServerAddr serverAddr() { - if (initializer.serverAddr == null) { - return null; - } - ServerAddr result = new ServerAddr(); - result.ipAddress = initializer.serverAddr.ipAddress; - result.port = initializer.serverAddr.port == null ? 0 : initializer.serverAddr.port; - return result; + return Utils.convertType(initializer.serverAddr, ServerAddr.class); } @Override @@ -149,6 +143,7 @@ public byte[] body() { 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"); } @@ -168,6 +163,8 @@ public String text() { return new String(content, StandardCharsets.UTF_8); } + // java: json() is not in the Java API. + @Override public void dispose() { APIRequestContextDisposeAPIResponseParams params = new APIRequestContextDisposeAPIResponseParams(); 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 03400d794..74352c290 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java @@ -57,6 +57,7 @@ void call(BindingCallback func) { } 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 { 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 f869471d2..cf6b1a87d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -58,7 +58,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -74,13 +73,12 @@ import static com.microsoft.playwright.impl.Utils.toProtocol; public class BrowserContextImpl extends ChannelOwner implements BrowserContext { - // java: an insertion-ordered list, pages() lists the pages in creation order. - final List pages = new ArrayList<>(); + 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 HashMap<>(); + final Map bindings = new LinkedHashMap<>(); final TimeoutSettings timeoutSettings; PageImpl ownerPage; private final WaitableEvent closedPromise; @@ -172,6 +170,7 @@ void handleEvent(String event, JsonObject params) { } 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); @@ -463,7 +462,7 @@ public void grantPermissions(List permissions, GrantPermissionsOptions o options = new GrantPermissionsOptions(); } BrowserContextGrantPermissionsParams params = toProtocol(options, BrowserContextGrantPermissionsParams.class); - params.permissions = permissions == null ? new ArrayList<>() : permissions; + params.permissions = permissions; channel.grantPermissions(params, NO_TIMEOUT); } @@ -482,8 +481,9 @@ public void setGeolocation(Geolocation geolocation) { @Override public void setExtraHTTPHeaders(Map headers) { + RawHeaders.validateHeaders(headers); BrowserContextSetExtraHTTPHeadersParams params = new BrowserContextSetExtraHTTPHeadersParams(); - params.headers = connection.protocolGson().fromJson(Serialization.toProtocol(headers), new TypeToken>() {}.getType()); + params.headers = RawHeaders.headersObjectToArray(headers); channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @@ -751,12 +751,12 @@ void onClose() { @Override public void close(CloseOptions options) { - if (isClosed()) { - return; - } if (options == null) { options = new CloseOptions(); } + if (isClosed()) { + return; + } closeReason = options.reason; closingStatus = "closing"; request.dispose(convertType(options, APIRequestContext.DisposeOptions.class)); @@ -766,9 +766,7 @@ public void close(CloseOptions options) { } catch (RuntimeException e) { harError = e; } - BrowserContextCloseParams params = new BrowserContextCloseParams(); - params.reason = options.reason; - channel.close(params, NO_TIMEOUT); + channel.close(toProtocol(options, BrowserContextCloseParams.class), NO_TIMEOUT); runUntil(() -> {}, closedPromise); if (harError != null) { throw harError; @@ -779,15 +777,11 @@ public void close(CloseOptions options) { // java: upstream reads a path given as a string and passes an object through; Java options hold a Path. static JsonElement prepareStorageState(Path storageState) { - String text; try { - text = new String(Files.readAllBytes(storageState), StandardCharsets.UTF_8); + 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); - } - try { - return JsonParser.parseString(text); } catch (JsonParseException e) { throw new PlaywrightException("Error reading storage state from " + storageState + ":\n" + e.getMessage(), e); } @@ -798,11 +792,15 @@ static BrowserNewContextParams prepareBrowserContextParams(Browser.NewContextOpt if (options == null) { options = new Browser.NewContextOptions(); } + 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, and the headers map to name/value pairs. + // 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; @@ -824,6 +822,7 @@ static BrowserNewContextParams prepareBrowserContextParams(Browser.NewContextOpt contextParams.viewport.height = options.viewportSize.get().height; } contextParams.noDefaultViewport = options.viewportSize != null && !options.viewportSize.isPresent(); + contextParams.extraHTTPHeaders = options.extraHTTPHeaders != null ? RawHeaders.headersObjectToArray(options.extraHTTPHeaders) : null; if (options.screenSize != null) { contextParams.screen = new BrowserNewContextParams.BrowserNewContextParamsScreen(); contextParams.screen.width = options.screenSize.width; @@ -848,7 +847,8 @@ static BrowserNewContextParams prepareBrowserContextParams(Browser.NewContextOpt } } contextParams.httpCredentials = toHttpCredentialsProtocol(options.httpCredentials); - // java: recordVideo is the flat recordVideoDir, recordVideoSize and recordVideoFps options. + // 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(); 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 9f9beb25f..841436e27 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -99,6 +99,7 @@ BrowserContextImpl innerNewContext(NewContextOptions userOptions) { return context; } + // java: no logger parameter, the Java API has no logger option. void connectToBrowserType(BrowserTypeImpl browserType, BrowserType.LaunchOptions browserOptions) { // Note: when using connect(), `browserType` is different from `this._parent`. // This is why browser type is not wired up in the constructor, 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 d2dd1534a..64fc97662 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -397,10 +397,6 @@ public void waitForElementState(ElementState state, WaitForElementStateOptions o if (options == null) { options = new WaitForElementStateOptions(); } - // java: the state is an enum that may be null. - if (state == null) { - throw new IllegalArgumentException("State cannot be null"); - } ElementHandleWaitForElementStateParams params = toProtocol(options, ElementHandleWaitForElementStateParams.class); params.state = state.toString().toLowerCase(); elementChannel.waitForElementState(params, frame.timeout(options.timeout)); @@ -428,7 +424,11 @@ static ElementHandleSelectOptionParams convertSelectOptionValues(Object values) if (items.length == 0) { return result; } - Utils.assertNoNullItems(items); + 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) { @@ -436,8 +436,8 @@ static ElementHandleSelectOptionParams convertSelectOptionValues(Object values) } return result; } - result.options = new ArrayList<>(); if (items[0] instanceof String) { + result.options = new ArrayList<>(); for (Object valueOrLabel : items) { ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); option.valueOrLabel = (String) valueOrLabel; @@ -445,6 +445,7 @@ static ElementHandleSelectOptionParams convertSelectOptionValues(Object values) } return result; } + result.options = new ArrayList<>(); for (Object v : items) { SelectOption value = (SelectOption) v; ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions option = new ElementHandleSelectOptionParams.ElementHandleSelectOptionParamsOptions(); @@ -456,7 +457,6 @@ static ElementHandleSelectOptionParams convertSelectOptionValues(Object values) return result; } - // java: Utils.checkFilePayloadSize is not used, its limit check is > while upstream's is >=. private static boolean filePayloadExceedsSizeLimit(List payloads) { long size = 0; for (FilePayload item : payloads) { @@ -489,19 +489,9 @@ private static Path resolvePathsAndDirectoryForInputFiles(List items, Li // 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)); - ElementHandleSetInputFilesParams result = new ElementHandleSetInputFilesParams(); - boolean somePaths = false; - boolean allPaths = true; - for (Object item : items) { - if (item instanceof Path) { - somePaths = true; - } else { - allPaths = false; - } - } - if (somePaths) { - if (!allPaths) { + 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"); } @@ -510,19 +500,23 @@ static ElementHandleSetInputFilesParams convertInputFiles(Object files, BrowserC if (context.connection.isRemote()) { List filesToStream = localDirectory != null ? listFilesRecursively(localDirectory) : localPaths; - 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); - } - BrowserContextCreateTempFilesResult tempFiles = context.wrapApiCall(() -> context.channel.createTempFiles(params, NO_TIMEOUT), null, true); + 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 = tempFiles.writableStreams.get(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); @@ -530,10 +524,12 @@ static ElementHandleSetInputFilesParams convertInputFiles(Object files, BrowserC throw new PlaywrightException("Failed to copy file to remote server.", e); } } - result.directoryStream = tempFiles.rootDir; - result.streams = localDirectory != null ? null : tempFiles.writableStreams; + 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) { @@ -551,6 +547,7 @@ static ElementHandleSetInputFilesParams convertInputFiles(Object files, BrowserC 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(); 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 82fd1e072..dcd616034 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -23,8 +23,6 @@ import com.microsoft.playwright.options.*; 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; @@ -68,10 +66,7 @@ public class FrameImpl extends ChannelOwner implements Frame { } name = init.name; url = init.url; - loadStates = new LinkedHashSet<>(); - if (init.loadStates != null) { - loadStates.addAll(init.loadStates); - } + loadStates = new LinkedHashSet<>(init.loadStates); } // java: upstream subscribes in the constructor with this._channel.on(...); the Java channel dispatches events here. @@ -88,7 +83,7 @@ void handleEvent(String event, JsonObject params) { } if (parentFrame == null && "load".equals(loadstateEvent.add) && page != null) { page.emit(Events.Page.LOAD, page); - ((BrowserContextImpl) page.context()).emit(Events.BrowserContext.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); @@ -97,12 +92,11 @@ void handleEvent(String event, JsonObject params) { FrameNavigatedEvent navigatedEvent = connection.protocolGson().fromJson(params, FrameNavigatedEvent.class); url = navigatedEvent.url; name = navigatedEvent.name; - // java: there are no functions passed to evaluate() (no exposeFunctions option), so no - // _eraseEvaluateCallbacks() on a main frame navigation. + // java: no exposeFunctions option of evaluate(), so no _eraseEvaluateCallbacks(). eventEmitter.emit(Events.Frame.NAVIGATED, navigatedEvent); if (navigatedEvent.error == null && page != null) { page.emit(Events.Page.FRAME_NAVIGATED, this); - ((BrowserContextImpl) page.context()).emit(Events.BrowserContext.FRAME_NAVIGATED, this); + page.context().emit(Events.BrowserContext.FRAME_NAVIGATED, this); } } } @@ -153,7 +147,7 @@ public ResponseImpl waitForNavigation(WaitForNavigationOptions options, Runnable } // 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(baseURL(), options.url, connection.localUtils(), false); + UrlMatcher matcher = UrlMatcher.forOneOf(page != null ? page.context().baseUrl() : null, options.url, connection.localUtils(), false); return waitForNavigation(matcher, options, callback); } @@ -248,7 +242,7 @@ public void waitForURL(Predicate url, WaitForURLOptions options) { 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(baseURL(), url, connection.localUtils(), false); + 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; @@ -457,7 +451,7 @@ void drop(String selector, DropPayload payload, Locator.DropOptions options) { params.selector = selector; params.strict = true; if (payload.files != null) { - ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(payload.files, (BrowserContextImpl) page().context()); + 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."); } @@ -796,7 +790,7 @@ private void setInputFilesImpl(String selector, Object files, SetInputFilesOptio if (options == null) { options = new SetInputFilesOptions(); } - ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(files, (BrowserContextImpl) page().context()); + ElementHandleSetInputFilesParams converted = ElementHandleImpl.convertInputFiles(files, page().context()); FrameSetInputFilesParams params = toProtocol(options, FrameSetInputFilesParams.class); params.selector = selector; if (converted.payloads != null) { @@ -926,35 +920,16 @@ static String verifyLoadState(String name, String waitUntil) { return waitUntil; } - private static final Set kLifecycleEvents = new LinkedHashSet<>(Arrays.asList("load", "domcontentloaded", "networkidle", "commit")); - - // java: members with no upstream counterpart: kAnyFrameSelector of isomorphic/selectorParser.ts, the enum form of - // verifyLoadState, conversions for the seed classes, and the webmcp() accessor of upstream's webmcp field. + // 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"; - static WaitUntilState verifyLoadState(String name, WaitUntilState waitUntil) { - return WaitUntilState.valueOf(verifyLoadState(name, lifecycleEvent(waitUntil)).toUpperCase(Locale.ROOT)); - } + 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); } - private URL baseURL() { - if (page == null) { - return null; - } - String baseURL = ((BrowserContextImpl) page.context()).options.baseURL; - if (baseURL == null) { - return null; - } - try { - return new URL(baseURL); - } catch (MalformedURLException e) { - return null; - } - } - private static String readFile(Path path) { try { return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); 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 c58553a7f..c05afa63c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -49,10 +49,9 @@ public Locator locator(String selectorOrLocator, LocatorOptions options) { @Override public Locator locator(Locator selectorOrLocator, LocatorOptions options) { - LocatorImpl locator = (LocatorImpl) selectorOrLocator; - if (locator.frame != frame) + if (((LocatorImpl) selectorOrLocator).frame != frame) throw new PlaywrightException("Locators must belong to the same frame."); - return new LocatorImpl(frame, childSelector(locator.selector), convertType(options, Locator.LocatorOptions.class)); + return new LocatorImpl(frame, childSelector(((LocatorImpl) selectorOrLocator).selector), convertType(options, Locator.LocatorOptions.class)); } // java: the test id attribute lives in SelectorsImpl of the Playwright instance, see LocatorUtils.getByTestIdSelector. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java index 8bba5f547..cb42d0164 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java @@ -36,7 +36,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.function.Predicate; import java.util.regex.Pattern; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; @@ -46,7 +45,7 @@ class HarRouter { private final LocalUtils localUtils; private final String harId; private final HarNotFound notFoundAction; - // java: options.urlMatch, a String, Pattern, Predicate or UrlMatcher; there is no baseURL option. + // 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) { @@ -128,7 +127,7 @@ private void handle(Route route) { } // Report the error, but fall through to the default handler. - if (notFoundAction != HarNotFound.FALLBACK) { + if (notFoundAction == HarNotFound.ABORT) { route.abort(); return; } @@ -138,13 +137,9 @@ private void handle(Route route) { void addContextRoute(BrowserContext context) { Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; - if (urlMatch instanceof UrlMatcher) { - urlMatch = fromUrlMatcher((UrlMatcher) urlMatch); - } + // java: route() has an overload per URLMatch type. if (urlMatch instanceof Pattern) { context.route((Pattern) urlMatch, route -> handle(route)); - } else if (urlMatch instanceof Predicate) { - context.route(asPredicate(urlMatch), route -> handle(route)); } else { context.route((String) urlMatch, route -> handle(route)); } @@ -152,13 +147,9 @@ void addContextRoute(BrowserContext context) { void addPageRoute(Page page) { Object urlMatch = this.urlMatch != null ? this.urlMatch : "**/*"; - if (urlMatch instanceof UrlMatcher) { - urlMatch = fromUrlMatcher((UrlMatcher) urlMatch); - } + // java: route() has an overload per URLMatch type. if (urlMatch instanceof Pattern) { page.route((Pattern) urlMatch, route -> handle(route)); - } else if (urlMatch instanceof Predicate) { - page.route(asPredicate(urlMatch), route -> handle(route)); } else { page.route((String) urlMatch, route -> handle(route)); } @@ -173,26 +164,7 @@ void dispose() { } } - // java: helpers to pass the URLMatch to the String, Pattern and Predicate overloads of route(). - - private static Object fromUrlMatcher(UrlMatcher matcher) { - if (matcher.glob != null) { - return matcher.glob; - } - if (matcher.pattern != null) { - return matcher.pattern; - } - if (matcher.predicate != null) { - return matcher.predicate; - } - return "**/*"; - } - - @SuppressWarnings("unchecked") - private static Predicate asPredicate(Object urlMatch) { - return (Predicate) urlMatch; - } - + // 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) { 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 bfae1770e..805a39501 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -37,7 +37,8 @@ public class JsonPipe extends ChannelOwner implements Transport { super(parent, type, guid, initializer); } - // java: the members below have no counterpart in jsonPipe.ts, they implement Transport (connect.ts upstream). + // java: the members below have no counterpart in jsonPipe.ts, they are JsonPipeTransport of connect.ts in the + // order send, onMessage (poll), onClose, close; its connect is in Connect.connectToEndpoint. private final Queue incoming = new LinkedList<>(); private boolean isClosed; private String closeReason = "Browser has been closed"; @@ -79,17 +80,6 @@ public void dispose() { }); } - @Override - public void close() throws IOException { - if (!isClosed) { - channel.close(NO_TIMEOUT); - } - } - - String closeReason() { - return closeReason; - } - void onClose(Consumer handler) { on(Events.JsonPipe.CLOSE, handler); } @@ -98,6 +88,13 @@ void offClose(Consumer handler) { off(Events.JsonPipe.CLOSE, handler); } + @Override + public void close() throws IOException { + if (!isClosed) { + channel.close(NO_TIMEOUT); + } + } + @Override protected void handleEvent(String event, JsonObject params) { if ("message".equals(event)) { @@ -114,6 +111,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/LocatorImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java index 3560008ff..cf8ead9f9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -39,7 +39,7 @@ class LocatorImpl implements Locator { final FrameImpl frame; - final String selector; + String selector; // java: upstream has one constructor with optional LocatorOptions. Locator.LocatorOptions has no // 'visible', so filter() and visible() use the private constructor that takes FilterOptions. @@ -53,31 +53,30 @@ class LocatorImpl implements Locator { private LocatorImpl(FrameImpl frame, String selector, FilterOptions options) { this.frame = frame; + this.selector = selector; if (options != null && options.hasText != null) - selector += " >> internal:has-text=" + escapeForTextSelector(options.hasText, false); + this.selector += " >> internal:has-text=" + escapeForTextSelector(options.hasText, false); if (options != null && options.hasNotText != null) - selector += " >> internal:has-not-text=" + escapeForTextSelector(options.hasNotText, false); + 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."); - selector += " >> internal:has=" + gson().toJson(locator.selector); + this.selector += " >> internal:has=" + gson().toJson(locator.selector); } 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."); - selector += " >> internal:has-not=" + gson().toJson(locator.selector); + this.selector += " >> internal:has-not=" + gson().toJson(locator.selector); } if (options != null && options.visible != null) - selector += " >> visible=" + (options.visible ? "true" : "false"); - - this.selector = selector; + this.selector += " >> visible=" + (options.visible ? "true" : "false"); } R wrapApiCall(Supplier func, String title, boolean internal) { @@ -221,10 +220,9 @@ public Locator locator(String selectorOrLocator, LocatorOptions options) { @Override public Locator locator(Locator selectorOrLocator, LocatorOptions options) { - LocatorImpl locator = (LocatorImpl) selectorOrLocator; - if (locator.frame != frame) + if (((LocatorImpl) selectorOrLocator).frame != frame) throw new PlaywrightException("Locators must belong to the same frame."); - return new LocatorImpl(frame, selector + " >> internal:chain=" + gson().toJson(locator.selector), options); + return new LocatorImpl(frame, selector + " >> internal:chain=" + gson().toJson(((LocatorImpl) selectorOrLocator).selector), options); } @Override @@ -335,7 +333,7 @@ public FrameLocator contentFrame() { @Override public Locator describe(String description) { - return new LocatorImpl(frame, selector + " >> " + describeSelector(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 @@ -369,18 +367,16 @@ public Locator nth(int index) { @Override public Locator and(Locator locator) { - LocatorImpl other = (LocatorImpl) locator; - if (other.frame != frame) + if (((LocatorImpl) locator).frame != frame) throw new PlaywrightException("Locators must belong to the same frame."); - return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(other.selector)); + return new LocatorImpl(frame, selector + " >> internal:and=" + gson().toJson(((LocatorImpl) locator).selector)); } @Override public Locator or(Locator locator) { - LocatorImpl other = (LocatorImpl) locator; - if (other.frame != frame) + if (((LocatorImpl) locator).frame != frame) throw new PlaywrightException("Locators must belong to the same frame."); - return new LocatorImpl(frame, selector + " >> internal:or=" + gson().toJson(other.selector)); + return new LocatorImpl(frame, selector + " >> internal:or=" + gson().toJson(((LocatorImpl) locator).selector)); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java index 8d9c025cd..3e40477ac 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java @@ -14,113 +14,104 @@ * limitations under the License. */ +// Port of isomorphic/locatorUtils.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.Locator; import com.microsoft.playwright.options.AriaRole; +import java.util.ArrayList; +import java.util.List; 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); +public final class 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. - private static String encodeTestIdAttributeName(String testIdAttributeName) { + static String encodeTestIdAttributeName(String testIdAttributeName) { return testIdAttributeName.contains(",") ? gson().toJson(testIdAttributeName) : testIdAttributeName; } + // java: the test id attribute name lives in SelectorsImpl of the Playwright instance, not in a module variable. static String getByTestIdSelector(Object testId, PlaywrightImpl playwright) { - String attributeName = encodeTestIdAttributeName(playwright.selectors.testIdAttributeName); - return "internal:testid=[" + attributeName + "=" + escapeForAttributeSelector(testId, true) + "]"; + String testIdAttributeName = playwright.selectors.testIdAttributeName; + return "internal:testid=[" + encodeTestIdAttributeName(testIdAttributeName) + "=" + escapeForAttributeSelector(testId, true) + "]"; + } + + static String getByLabelSelector(Object text, Locator.GetByLabelOptions options) { + return "internal:label=" + escapeForTextSelector(text, options != null && options.exact != null && options.exact); } static String getByAltTextSelector(Object text, Locator.GetByAltTextOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("alt", text, exact); + return getByAttributeTextSelector("alt", text, options == null ? null : options.exact); } static String getByTitleSelector(Object text, Locator.GetByTitleOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("title", text, exact); + return getByAttributeTextSelector("title", text, options == null ? null : options.exact); } static String getByPlaceholderSelector(Object text, Locator.GetByPlaceholderOptions options) { - boolean exact = options != null && options.exact != null && options.exact; - return getByAttributeTextSelector("placeholder", text, exact); + return getByAttributeTextSelector("placeholder", text, options == null ? null : options.exact); } - private static void addAttr(StringBuilder result, String name, String value) { - result.append("[").append(name).append("=").append(value).append("]"); + 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. 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()); - } + 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(); } + // java: ports of the isomorphic/stringUtils.ts escapes that the selectors above use. + // java: toJsRegexFlags() never produces the 'u' or 'v' flag, so there is no unicode early return. 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); + static String escapeForTextSelector(Object text, boolean exact) { + if (text instanceof Pattern) + return escapeRegexForSelector((Pattern) text); + if (text instanceof String) + return gson().toJson(text) + (exact ? "s" : "i"); + throw new IllegalArgumentException("text parameter must be Pattern or String: " + text); } + // java: an exact match has no suffix here, upstream appends 's'; kept as the old Java client sent it. private static String escapeForAttributeSelector(Object value, boolean exact) { - if (value instanceof Pattern) { + if (value instanceof Pattern) return escapeRegexForSelector((Pattern) value); - } if (value instanceof String) { // TODO: this should actually be // cssEscape(value).replace(/\\ /g, ' ') @@ -131,6 +122,7 @@ private static String escapeForAttributeSelector(Object value, boolean exact) { throw new IllegalArgumentException("Attribute can be String or Pattern, found: " + value); } + // java: String(re) of a JS RegExp. private static String toJsRegExp(Pattern pattern) { return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); } 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 34b894f48..5fd437fef 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -54,7 +53,7 @@ public class PageImpl extends ChannelOwner implements Page { private final Set frames = new LinkedHashSet<>(); final Set workers = new LinkedHashSet<>(); private boolean closed; - // java: LongStandingScope; the Close and Crash events close it as upstream, createWaitForCloseHelper() races it. + // java: LongStandingScope is the error it was closed with; createWaitForCloseHelper() races it. private TargetClosedError closedOrCrashedScope; private ViewportSize viewportSize; List routes = new ArrayList<>(); @@ -70,7 +69,7 @@ public class PageImpl extends ChannelOwner implements Page { final WebStorageImpl sessionStorage; final WebMCPImpl webmcp; - final Map bindings = new HashMap<>(); + final Map bindings = new LinkedHashMap<>(); final TimeoutSettings timeoutSettings; private final VideoImpl video; final PageImpl opener; @@ -103,12 +102,25 @@ public class PageImpl extends ChannelOwner implements Page { } closed = Boolean.TRUE.equals(pageInitializer.isClosed); opener = pageInitializer.opener; - video = pageInitializer.video != null ? new VideoImpl(this, pageInitializer.video) : new VideoImpl(this); + video = new VideoImpl(this, pageInitializer.video); screencast = new ScreencastImpl(this); - // java: the once(Close) and once(Crash) listeners that close _closedOrCrashedScope are in onClose() and onCrash(). + on(Events.Page.CLOSE, new Consumer() { + @Override + public void accept(Page page) { + off(Events.Page.CLOSE, this); + closedOrCrashedScope = closeErrorWithReason(); + } + }); + on(Events.Page.CRASH, new Consumer() { + @Override + public void accept(Page page) { + off(Events.Page.CRASH, this); + closedOrCrashedScope = new TargetClosedError(); + } + }); - Map mapping = new HashMap<>(); + Map mapping = new LinkedHashMap<>(); mapping.put(Events.Page.CONSOLE, "console"); mapping.put(Events.Page.DIALOG, "dialog"); mapping.put(Events.Page.DIALOG_CLOSED, "dialogClosed"); @@ -267,7 +279,7 @@ private void onWebSocketRoute(WebSocketRouteImpl webSocketRoute) { } void onBinding(BindingCall bindingCall) { - BindingCallback func = bindings.get(bindingCall.initializer.get("name").getAsString()); + BindingCallback func = bindings.get(bindingCall.bindingCallInitializer.name); if (func != null) { bindingCall.call(func); return; @@ -285,19 +297,11 @@ void onClose() { closed = true; browserContext.pages.remove(this); disposeHarRouters(); - // java: this.once(Events.Page.Close, ...) of the constructor. - if (closedOrCrashedScope == null) { - closedOrCrashedScope = closeErrorWithReason(); - } emit(Events.Page.CLOSE, this); browserContext.emit(Events.BrowserContext.PAGE_CLOSE, this); } private void onCrash() { - // java: this.once(Events.Page.Crash, ...) of the constructor. - if (closedOrCrashedScope == null) { - closedOrCrashedScope = new TargetClosedError(); - } emit(Events.Page.CRASH, this); } @@ -319,38 +323,33 @@ public FrameImpl mainFrame() { return mainFrame; } - // java: frame(frameSelector) takes a name or { name, url }; the Java API has frame(name) and frameByUrl(url). @Override public Frame frame(String name) { - if (name == null || name.isEmpty()) { - throw new PlaywrightException("Either name or url matcher should be specified"); - } - for (FrameImpl f : frames) { - if (name.equals(f.name())) { - return f; - } - } - return null; + return frame(name, null); } @Override public Frame frameByUrl(String url) { - return frameByUrl(UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false)); + return frame(null, UrlMatcher.forGlob(browserContext.baseUrl(), url, connection.localUtils(), false)); } @Override public Frame frameByUrl(Pattern url) { - return frameByUrl(new UrlMatcher(url)); + return frame(null, new UrlMatcher(url)); } @Override public Frame frameByUrl(Predicate url) { - return frameByUrl(new UrlMatcher(url)); + return frame(null, new UrlMatcher(url)); } - private Frame frameByUrl(UrlMatcher url) { - for (FrameImpl f : frames) { - if (url.test(f.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; } } @@ -468,18 +467,9 @@ public AutoCloseable exposeBinding(String name, BindingCallback callback) { @Override public void setExtraHTTPHeaders(Map headers) { - // java: validateHeaders checks the JS type of the values, a Java map holds strings. + RawHeaders.validateHeaders(headers); PageSetExtraHTTPHeadersParams params = new PageSetExtraHTTPHeadersParams(); - params.headers = new ArrayList<>(); - for (Map.Entry e : headers.entrySet()) { - if (e.getValue() == null) { - continue; - } - NameValue header = new NameValue(); - header.name = e.getKey(); - header.value = e.getValue(); - params.headers.add(header); - } + params.headers = RawHeaders.headersObjectToArray(headers); channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @@ -508,11 +498,8 @@ public Response reload(ReloadOptions options) { if (options == null) { options = new ReloadOptions(); } - // java: verifyLoadState only validates the string, WaitUntilState is an enum. PageReloadParams params = toProtocol(options, PageReloadParams.class); - if (params.waitUntil == null) { - params.waitUntil = "load"; - } + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); return channel.reload(params, timeoutSettings.navigationTimeout(options.timeout)).response; } @@ -564,7 +551,7 @@ private void onLocatorHandlerTriggered(int uid) { @Override public void removeLocatorHandler(Locator locator) { for (Map.Entry entry : new ArrayList<>(locatorHandlers.entrySet())) { - if (entry.getValue().locator.equals((LocatorImpl) locator)) { + if (entry.getValue().locator.equals(locator)) { locatorHandlers.remove(entry.getKey()); PageUnregisterLocatorHandlerParams params = new PageUnregisterLocatorHandlerParams(); params.uid = entry.getKey(); @@ -761,9 +748,7 @@ public Response goBack(GoBackOptions options) { options = new GoBackOptions(); } PageGoBackParams params = toProtocol(options, PageGoBackParams.class); - if (params.waitUntil == null) { - params.waitUntil = "load"; - } + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); return channel.goBack(params, timeoutSettings.navigationTimeout(options.timeout)).response; } @@ -773,9 +758,7 @@ public Response goForward(GoForwardOptions options) { options = new GoForwardOptions(); } PageGoForwardParams params = toProtocol(options, PageGoForwardParams.class); - if (params.waitUntil == null) { - params.waitUntil = "load"; - } + params.waitUntil = FrameImpl.verifyLoadState("waitUntil", params.waitUntil == null ? "load" : params.waitUntil); return channel.goForward(params, timeoutSettings.navigationTimeout(options.timeout)).response; } @@ -814,24 +797,21 @@ public Object evaluate(String expression, Object arg) { // java: the script is a string or a file; there is no function to serialize and no exposeFunctions option. @Override public AutoCloseable addInitScript(String script) { - return addInitScriptImpl(script); + PageAddInitScriptParams params = new PageAddInitScriptParams(); + params.source = script; + return channel.addInitScript(params, NO_TIMEOUT).disposable; } @Override public AutoCloseable addInitScript(Path script) { + // java: evaluationScript of clientHelper.ts for { path }. String source; try { - source = ClientHelper.addSourceUrlToScript(new String(readAllBytes(script), UTF_8), script); + source = new String(readAllBytes(script), UTF_8); } catch (IOException e) { throw new PlaywrightException("Failed to read script from file", e); } - return addInitScriptImpl(source); - } - - private AutoCloseable addInitScriptImpl(String source) { - PageAddInitScriptParams params = new PageAddInitScriptParams(); - params.source = source; - return channel.addInitScript(params, NO_TIMEOUT).disposable; + return addInitScript(ClientHelper.addSourceUrlToScript(source, script)); } @Override @@ -954,18 +934,15 @@ private void disableInterception() { wrapApiCall(() -> updateInterceptionPatterns(), null, true); } - // java: the patterns go through JSON into the page's own params class. private void updateInterceptionPatterns() { - JsonObject json = new JsonObject(); - json.add("patterns", gson().toJsonTree(RouteHandler.prepareInterceptionPatterns(routes))); - PageSetNetworkInterceptionPatternsParams params = connection.protocolGson().fromJson(json, PageSetNetworkInterceptionPatternsParams.class); + PageSetNetworkInterceptionPatternsParams params = new PageSetNetworkInterceptionPatternsParams(); + params.patterns = RouteHandler.prepareInterceptionPatterns(routes); channel.setNetworkInterceptionPatterns(params, NO_TIMEOUT); } private void updateWebSocketInterceptionPatterns() { - JsonObject json = new JsonObject(); - json.add("patterns", gson().toJsonTree(WebSocketRouteHandler.prepareInterceptionPatterns(webSocketRoutes))); - PageSetWebSocketInterceptionPatternsParams params = connection.protocolGson().fromJson(json, PageSetWebSocketInterceptionPatternsParams.class); + PageSetWebSocketInterceptionPatternsParams params = new PageSetWebSocketInterceptionPatternsParams(); + params.patterns = WebSocketRouteHandler.prepareInterceptionPatterns(webSocketRoutes); channel.setWebSocketInterceptionPatterns(params, NO_TIMEOUT); } @@ -975,13 +952,13 @@ public byte[] screenshot(ScreenshotOptions options) { options = new ScreenshotOptions(); } List mask = options.mask; - ScreenshotOptions copyOptions = Utils.clone(options); - copyOptions.mask = null; - if (copyOptions.type == null && options.path != null) { - // java: determineScreenshotType(options). - copyOptions.type = Utils.screenshotTypeForPath(options.path); + // 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); } - PageScreenshotParams copy = toProtocol(copyOptions, PageScreenshotParams.class); if (mask != null) { copy.mask = new ArrayList<>(); for (Locator locator : mask) { @@ -1093,14 +1070,7 @@ public List pageErrors() { PagePageErrorsResult result = channel.pageErrors(new PagePageErrorsParams(), NO_TIMEOUT); List errors = new ArrayList<>(); for (SerializedError error : result.errors) { - String errorStr = ""; - if (error.error != null) { - errorStr = error.error.name + ": " + error.error.message; - if (error.error.stack != null && !error.error.stack.isEmpty()) { - errorStr += "\n" + error.error.stack; - } - } - errors.add(errorStr); + errors.add(Serialization.parseError(gson().toJsonTree(error).getAsJsonObject())); } return errors; } 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 e22173411..472c14e58 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -131,11 +131,6 @@ public BrowserTypeImpl firefox() { return firefox; } - @Override - public APIRequestImpl request() { - return request; - } - @Override public BrowserTypeImpl webkit() { return webkit; @@ -146,6 +141,11 @@ public SelectorsImpl selectors() { return selectors; } + @Override + public APIRequestImpl request() { + return request; + } + @Override public void close() { try { 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 bf35c9353..fbaf086ba 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java @@ -93,9 +93,6 @@ List headersArray() { // java: module-level functions of network.ts and isomorphic/headers.ts used with headers. static void validateHeaders(Map headers) { - if (headers == null) { - return; - } for (Map.Entry entry : headers.entrySet()) { // java: a null value is a JavaScript null, typeof null is "object". if (entry.getValue() == null) { 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 3ceb6f539..caefde404 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java @@ -73,7 +73,7 @@ static class FallbackOverrides { if (this.redirectedFrom != null) { this.redirectedFrom.redirectedTo = this; } - this.provisionalHeaders = new RawHeaders(requestInitializer.headers != null ? requestInitializer.headers : new ArrayList<>()); + this.provisionalHeaders = new RawHeaders(requestInitializer.headers); this.timing = new Timing(); this.timing.startTime = 0; this.timing.domainLookupStart = -1; @@ -268,43 +268,33 @@ SerializedFallbackOverrides fallbackOverridesForContinue() { return fallbackOverrides; } - // java: there is no LongStandingScope; the scope watches the close events of the service worker or the page. - TargetClosedScope targetClosedScope() { + LongStandingScope targetClosedScope() { WorkerImpl serviceWorker = serviceWorker(); if (serviceWorker != null) { - return new TargetClosedScope(this, serviceWorker, Events.Worker.CLOSE, serviceWorker::closeErrorWithReason, null, null); + // java: WorkerImpl has no _closedScope, the Close event closes it. + return new LongStandingScope(this, () -> new WaitableEvent(serviceWorker, Events.Worker.CLOSE) { + @Override + public Object get() { + throw serviceWorker.closeErrorWithReason(); + } + }); } PageImpl page = safePage(); if (page != null) { - return new TargetClosedScope(this, page, Events.Page.CLOSE, page::closeErrorWithReason, Events.Page.CRASH, TargetClosedError::new); + return new LongStandingScope(this, page::createWaitForCloseHelper); } - return new TargetClosedScope(this, null, null, null, null, null); + return new LongStandingScope(this, null); } - // java: the LongStandingScope of a service worker or a page, built on Waitables. - static class TargetClosedScope { + // java: LongStandingScope of isomorphic/manualPromise.ts, made of the Waitable that is done once the scope + // closed and then throws its error; null is a scope that never closes. + static class LongStandingScope { private final ChannelOwner owner; - private final EventEmitter target; - private final String closeEvent; - private final Supplier closeError; - private final String crashEvent; - private final Supplier crashError; - - TargetClosedScope(ChannelOwner owner, EventEmitter target, String closeEvent, Supplier closeError, - String crashEvent, Supplier crashError) { - this.owner = owner; - this.target = target; - this.closeEvent = closeEvent; - this.closeError = closeError; - this.crashEvent = crashEvent; - this.crashError = crashError; - } + private final Supplier> terminatePromise; - private boolean isClosed() { - if (target instanceof PageImpl) { - return ((PageImpl) target).isClosed(); - } - return false; + LongStandingScope(ChannelOwner owner, Supplier> terminatePromise) { + this.owner = owner; + this.terminatePromise = terminatePromise; } T race(Waitable promise) { @@ -315,37 +305,32 @@ T safeRace(Waitable promise) { return race(promise, true); } + @SuppressWarnings("unchecked") private T race(Waitable promise, boolean safe) { - // java: a settled promise wins over the terminate promise, as its reaction runs first upstream. - if (target == null || promise.isDone()) { + if (terminatePromise == null) { return owner.runUntil(() -> {}, promise); } - if (isClosed()) { - promise.dispose(); - if (safe) { + Waitable terminate = terminatePromise.get(); + List> waitables = new ArrayList<>(); + // java: the promise goes first, a settled promise wins over a closed scope as its reaction runs first upstream. + waitables.add((Waitable) promise); + waitables.add(safe ? new Waitable() { + @Override + public boolean isDone() { + return terminate.isDone(); + } + + @Override + public Object get() { return null; } - throw closeError.get(); - } - List> waitables = new ArrayList<>(); - waitables.add(terminateWaitable(closeEvent, closeError, safe)); - if (crashEvent != null) { - waitables.add(terminateWaitable(crashEvent, crashError, safe)); - } - waitables.add(promise); - return owner.runUntil(() -> {}, new WaitableRace<>(waitables)); - } - private Waitable terminateWaitable(String event, Supplier error, boolean safe) { - return new WaitableEvent(target, event) { @Override - public T get() { - if (safe) { - return null; - } - throw error.get(); + public void dispose() { + terminate.dispose(); } - }; + } : terminate); + return (T) owner.runUntil(() -> {}, new WaitableRace<>(waitables)); } } } 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 9454f094c..b94ab8651 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java @@ -28,7 +28,6 @@ import com.microsoft.playwright.options.ServerAddr; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -45,7 +44,7 @@ public class ResponseImpl extends ChannelOwner implements Response { ResponseImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); responseInitializer = connection.protocolGson().fromJson(initializer, ResponseInitializer.class); - this.provisionalHeaders = new RawHeaders(responseInitializer.headers != null ? responseInitializer.headers : new ArrayList<>()); + this.provisionalHeaders = new RawHeaders(responseInitializer.headers); this.request = responseInitializer.request; this.request.response = this; assignTiming(this.request, responseInitializer.timing); @@ -171,34 +170,15 @@ public String httpVersion() { return channel.httpVersion(NO_TIMEOUT).value; } - // java: Object.assign(this._request._timing, this._initializer.timing). + // java: Object.assign(this._request._timing, this._initializer.timing), field by field. private static void assignTiming(RequestImpl request, ResourceTiming timing) { - if (timing == null) { - return; - } - if (timing.startTime != null) { - request.timing.startTime = timing.startTime; - } - if (timing.domainLookupStart != null) { - request.timing.domainLookupStart = timing.domainLookupStart; - } - if (timing.domainLookupEnd != null) { - request.timing.domainLookupEnd = timing.domainLookupEnd; - } - if (timing.connectStart != null) { - request.timing.connectStart = timing.connectStart; - } - if (timing.secureConnectionStart != null) { - request.timing.secureConnectionStart = timing.secureConnectionStart; - } - if (timing.connectEnd != null) { - request.timing.connectEnd = timing.connectEnd; - } - if (timing.requestStart != null) { - request.timing.requestStart = timing.requestStart; - } - if (timing.responseStart != null) { - request.timing.responseStart = timing.responseStart; - } + 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 index c03a0e027..eb13ab964 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java @@ -20,7 +20,6 @@ import com.microsoft.playwright.Route; import com.microsoft.playwright.impl.protocol.BrowserContextSetNetworkInterceptionPatternsParams.BrowserContextSetNetworkInterceptionPatternsParamsPatterns; -import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -48,8 +47,8 @@ private static class HandlerInvocation { } } - // java: the UrlMatcher has resolved a glob against the base URL and validated it already, baseURL is - // kept for the upstream signature only. A null times is Number.MAX_SAFE_INTEGER. + // 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; @@ -57,19 +56,6 @@ private static class HandlerInvocation { this.handler = handler; } - RouteHandler(String baseURL, UrlMatcher url, Consumer handler) { - this(baseURL, url, handler, null); - } - - // java: the base URL of the context as a java.net.URL. - RouteHandler(URL baseURL, UrlMatcher url, Consumer handler, Integer times) { - this(baseURL != null ? baseURL.toString() : null, url, handler, times); - } - - RouteHandler(URL baseURL, UrlMatcher url, Consumer handler) { - this(baseURL, url, handler, null); - } - // 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") 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 609b90493..3fd5a5774 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -78,8 +78,8 @@ public void fallback(FallbackOptions options) { checkNotHandled(); request().applyFallbackOverrides(fallbackOverrides(options.url, options.method, options.headers, options.postData)); reportHandled(false); - // java: RouteHandler.handle() returned when the handler did, nobody waits for the outcome of a later - // fallback(), so the request continues to the network as the default handler of the context does. + // 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); @@ -243,9 +243,8 @@ void innerContinue(boolean isFallback) { raceWithTargetClose(sendMessageAsync("continue", params)); } - // java: helpers with no counterpart upstream. - - // java: set by RouteHandler when the handler returned before it fulfilled, continued or fell back. + // 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) { 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 009e0bf9b..8f2f9d092 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -119,17 +119,13 @@ private void startCollectingStacks(String traceName, boolean live) { isTracing = true; connection.setIsTracing(true); } - LocalUtils localUtils = connection.localUtils(); - if (localUtils == null) { - stacksId = null; - return; - } - // java: LocalUtils.tracingStarted of the seed has no live flag and drops tracesDir, the params go to the channel as upstream passes them. LocalUtilsTracingStartedParams params = new LocalUtilsTracingStartedParams(); params.tracesDir = tracesDir == null ? null : tracesDir.toString(); params.traceName = traceName; params.live = live; - LocalUtilsTracingStartedResult result = localUtils.channel.tracingStarted(params, NO_TIMEOUT); + LocalUtils localUtils = connection.localUtils(); + // java: LocalUtils.tracingStarted of the seed has no live flag and drops tracesDir, so the channel is called directly. + LocalUtilsTracingStartedResult result = localUtils == null ? null : localUtils.channel.tracingStarted(params, NO_TIMEOUT); stacksId = result == null ? null : result.stacksId; } 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..5c3deca37 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of isomorphic/urlMatch.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; @@ -21,16 +22,19 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.util.Objects; import java.util.function.Predicate; import java.util.regex.Pattern; import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +// java: an URLMatch value; a glob also holds its resolved regex, so test() does not resolve it again. 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 +51,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,51 +65,85 @@ private UrlMatcher(String glob, Pattern pattern, Predicate predicate) { this.predicate = predicate; } - boolean test(String value) { - if (pattern != null) { - return pattern.matcher(value).find(); - } - if (predicate != null) { - return predicate.test(value); - } - return true; - } - + // java: urlMatchesEqual(match1, match2). @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; } + // java: urlMatches(baseURL, urlString, match); 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); + } + + // java: resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) and new RegExp(...); the driver resolves the glob, + // as resolveGlobBase() relies on the WHATWG URL parser. + 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); + } + + // java: constructURLBasedOnBaseURL() for the base URL of a context. + static String resolveUrl(URL baseUrl, String spec) { + return constructURLBasedOnBaseURL(baseUrl.toString(), spec); + } + + private 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: 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) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java index 04e9d747d..e9f561a40 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteHandler.java @@ -20,7 +20,6 @@ import com.microsoft.playwright.WebSocketRoute; import com.microsoft.playwright.impl.protocol.BrowserContextSetWebSocketInterceptionPatternsParams.BrowserContextSetWebSocketInterceptionPatternsParamsPatterns; -import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; @@ -32,19 +31,13 @@ class WebSocketRouteHandler { final UrlMatcher url; final Consumer handler; - // java: the UrlMatcher has resolved a glob against the base URL and validated it already, baseURL is - // kept for the upstream signature only. + // 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 base URL of the context as a java.net.URL. - WebSocketRouteHandler(URL baseURL, UrlMatcher url, Consumer handler) { - this(baseURL != null ? baseURL.toString() : null, url, 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") 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 4678c54dc..9e10aa7d7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java @@ -79,7 +79,7 @@ public String url() { @Override public List protocols() { - return WebSocketRouteImpl.this.protocols(); + return new ArrayList<>(webSocketRouteInitializer.protocols); } @Override @@ -178,7 +178,7 @@ public String url() { @Override public List protocols() { - return webSocketRouteInitializer.protocols != null ? new ArrayList<>(webSocketRouteInitializer.protocols) : new ArrayList<>(); + return new ArrayList<>(webSocketRouteInitializer.protocols); } @Override 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); From 9596990af85c79cfa1bd2dd08353423d76ea3c9b Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 20 Nov 2026 13:45:25 -0800 Subject: [PATCH 28/30] chore: port the helper files of the Node.js client and remove dead code Serialization follows serializers.ts; Headers, StringUtils, MimeType, Time and LongStandingScope follow their isomorphic files; LocalUtils, ClientHelper and FileUtils are completed. --- .../impl/APIRequestContextImpl.java | 2 +- .../playwright/impl/APIRequestImpl.java | 2 +- .../playwright/impl/BrowserContextImpl.java | 29 +- .../playwright/impl/CDPSessionImpl.java | 2 +- .../playwright/impl/ChannelOwner.java | 13 +- .../playwright/impl/ClientHelper.java | 29 +- .../microsoft/playwright/impl/ClockImpl.java | 18 +- .../microsoft/playwright/impl/Connect.java | 4 +- .../microsoft/playwright/impl/Connection.java | 21 +- .../playwright/impl/CredentialsImpl.java | 2 +- .../playwright/impl/DebuggerImpl.java | 2 +- .../playwright/impl/DownloadImpl.java | 3 +- .../playwright/impl/ElementHandleImpl.java | 16 +- .../com/microsoft/playwright/impl/Errors.java | 2 +- .../playwright/impl/EventEmitter.java | 7 +- .../com/microsoft/playwright/impl/Events.java | 3 +- .../microsoft/playwright/impl/FileUtils.java | 5 +- ...{Protocol.java => FrameExpectOptions.java} | 13 +- .../playwright/impl/FrameExpectResult.java | 29 + .../microsoft/playwright/impl/FrameImpl.java | 12 +- .../playwright/impl/FrameLocatorImpl.java | 6 +- .../microsoft/playwright/impl/HarRouter.java | 7 +- .../microsoft/playwright/impl/Headers.java | 47 ++ .../microsoft/playwright/impl/JsonPipe.java | 8 +- .../microsoft/playwright/impl/LocalUtils.java | 56 +- .../playwright/impl/LocatorImpl.java | 12 +- .../playwright/impl/LocatorUtils.java | 42 +- .../playwright/impl/LongStandingScope.java | 86 +++ .../microsoft/playwright/impl/MimeType.java | 453 ++++++++++++ .../playwright/impl/PageAssertionsImpl.java | 4 +- .../microsoft/playwright/impl/PageImpl.java | 84 +-- .../playwright/impl/PlaywrightImpl.java | 31 +- .../microsoft/playwright/impl/RawHeaders.java | 16 +- .../playwright/impl/RequestImpl.java | 68 +- .../microsoft/playwright/impl/RouteImpl.java | 6 +- .../playwright/impl/ScreencastImpl.java | 3 +- .../playwright/impl/SelectorsImpl.java | 21 +- .../playwright/impl/Serialization.java | 686 ++++++++++-------- .../playwright/impl/StackTraceCollector.java | 2 +- .../com/microsoft/playwright/impl/Stream.java | 3 +- .../playwright/impl/StringUtils.java | 70 ++ .../com/microsoft/playwright/impl/Time.java | 32 + .../playwright/impl/TimeoutSettings.java | 15 +- .../playwright/impl/TracingImpl.java | 46 +- .../microsoft/playwright/impl/UrlMatcher.java | 9 +- .../com/microsoft/playwright/impl/Utils.java | 264 +------ .../microsoft/playwright/impl/VideoImpl.java | 3 +- .../com/microsoft/playwright/impl/Waiter.java | 3 +- .../microsoft/playwright/impl/WebMCPImpl.java | 2 +- .../playwright/impl/WebStorageImpl.java | 2 +- .../microsoft/playwright/impl/WorkerImpl.java | 10 +- .../playwright/impl/WritableStream.java | 3 +- 52 files changed, 1405 insertions(+), 909 deletions(-) rename playwright/src/main/java/com/microsoft/playwright/impl/{Protocol.java => FrameExpectOptions.java} (74%) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Headers.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Time.java 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 89e53e687..20376bd20 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -40,7 +40,7 @@ import java.util.Map; import static com.microsoft.playwright.impl.Errors.isTargetClosedError; -import static com.microsoft.playwright.impl.RawHeaders.headersObjectToArray; +import static com.microsoft.playwright.impl.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; 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 0a68bbe8b..c54010644 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -65,7 +65,7 @@ public APIRequestContextImpl newContext(NewContextOptions options) { options.clientCertificates = null; options.httpCredentials = null; PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class); - params.extraHTTPHeaders = extraHTTPHeaders != null ? RawHeaders.headersObjectToArray(extraHTTPHeaders) : null; + params.extraHTTPHeaders = extraHTTPHeaders != null ? Headers.headersObjectToArray(extraHTTPHeaders) : null; params.storageState = storageState; // java: no _defaultLaunchOptions in the Java API, so no tracesDir here and none for context.tracing below. params.clientCertificates = BrowserContextImpl.toClientCertificatesProtocol(clientCertificates); 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 cf6b1a87d..a4d3bc950 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -68,6 +68,7 @@ import java.util.function.Predicate; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.convertType; import static com.microsoft.playwright.impl.Utils.toProtocol; @@ -369,7 +370,7 @@ void onWebSocketRoute(WebSocketRouteImpl webSocketRoute) { } void onBinding(BindingCall bindingCall) { - BindingCallback func = bindings.get(bindingCall.initializer.get("name").getAsString()); + BindingCallback func = bindings.get(bindingCall.bindingCallInitializer.name); if (func == null) { return; } @@ -483,7 +484,7 @@ public void setGeolocation(Geolocation geolocation) { public void setExtraHTTPHeaders(Map headers) { RawHeaders.validateHeaders(headers); BrowserContextSetExtraHTTPHeadersParams params = new BrowserContextSetExtraHTTPHeadersParams(); - params.headers = RawHeaders.headersObjectToArray(headers); + params.headers = Headers.headersObjectToArray(headers); channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @@ -498,22 +499,20 @@ public void setOffline(boolean offline) { @Override public AutoCloseable addInitScript(String script) { - // java: the exposeFunctions option has no Java API. - BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); - params.source = script; - return channel.addInitScript(params, NO_TIMEOUT).disposable; + return addInitScriptImpl(script); } @Override public AutoCloseable addInitScript(Path script) { - // java: evaluationScript of clientHelper.ts for { path }. - String source; - try { - source = new String(Files.readAllBytes(script), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new PlaywrightException("Failed to read script from file", e); - } - return addInitScript(ClientHelper.addSourceUrlToScript(source, script)); + return addInitScriptImpl(script); + } + + // java: the core of the String and Path overloads; the exposeFunctions option and arg have no Java API. + private AutoCloseable addInitScriptImpl(Object script) { + String source = evaluationScript(script, true); + BrowserContextAddInitScriptParams params = new BrowserContextAddInitScriptParams(); + params.source = source; + return channel.addInitScript(params, NO_TIMEOUT).disposable; } @Override @@ -822,7 +821,7 @@ static BrowserNewContextParams prepareBrowserContextParams(Browser.NewContextOpt contextParams.viewport.height = options.viewportSize.get().height; } contextParams.noDefaultViewport = options.viewportSize != null && !options.viewportSize.isPresent(); - contextParams.extraHTTPHeaders = options.extraHTTPHeaders != null ? RawHeaders.headersObjectToArray(options.extraHTTPHeaders) : null; + 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; 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 028020441..ddd208de5 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.*; @@ -23,7 +24,6 @@ import java.util.function.Consumer; -// Port of cdpSession.ts. public class CDPSessionImpl extends ChannelOwner implements CDPSession { final CDPSessionChannel channel = new CDPSessionChannel(this); 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..4846d599a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -14,7 +14,7 @@ * 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.JsonElement; @@ -118,16 +118,7 @@ void adopt(ChannelOwner child) { child.parent = this; } - ChannelOwner parentOfType(String type) { - ChannelOwner parent = this.parent; - while (parent != null) { - if (parent.type.equals(type)) { - return parent; - } - parent = parent.parent; - } - return null; - } + // java: no _parentOfType, the exposeFunctions option it serves has no Java API. void dispose(String reason) { // Clean up from parent and connection. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java index 20e0cfa83..61e0c00db 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java @@ -14,12 +14,39 @@ * limitations under the License. */ +// Port of clientHelper.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; -// Port of clientHelper.ts. java: envObjectToArray, evaluationScript and initScriptSourceWithExposedFunctions have no Java caller. +import static java.nio.charset.StandardCharsets.UTF_8; + +// java: no envObjectToArray, the env map is serialized as a name/value array by Serialization; no +// initScriptSourceWithExposedFunctions, there is no exposeFunctions option. class ClientHelper { + // java: fun is a script String or a file Path; the Java API has no function, { content } or arg. + static String evaluationScript(Object fun, boolean addSourceUrl) { + 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"); + } + static String addSourceUrlToScript(String source, Path path) { return source + "\n//# sourceURL=" + path.toString().replace("\n", ""); } 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 2962f8c54..0c3c90548 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java @@ -1,3 +1,20 @@ +/* + * 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.microsoft.playwright.impl.protocol.*; @@ -7,7 +24,6 @@ import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -// Port of clock.ts. class ClockImpl implements Clock { private final BrowserContextImpl browserContext; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java index 508b611ac..13c9ad35b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java @@ -32,6 +32,8 @@ import java.util.Map; import java.util.function.Consumer; +import static com.microsoft.playwright.impl.Time.monotonicTime; + final class Connect { private Connect() { } @@ -39,7 +41,7 @@ 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; - long deadline = timeout != 0 ? System.nanoTime() + (long) (timeout * 1_000_000) : 0; + double deadline = timeout != 0 ? monotonicTime() + timeout : 0; JsonObject headers = new JsonObject(); if (browserName != null) { headers.addProperty("x-playwright-browser", browserName); 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..fa23a5ea2 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.*; @@ -43,6 +43,7 @@ import java.util.concurrent.TimeUnit; import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Time.monotonicTime; class Root extends ChannelOwner { Root(Connection connection) { @@ -57,15 +58,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 +78,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; } } @@ -216,8 +217,8 @@ 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; } @@ -302,10 +303,8 @@ 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); } return expectsReply ? result : completed(); } 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 7e9801e11..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.*; @@ -27,7 +28,6 @@ import static com.microsoft.playwright.impl.Utils.toProtocol; import static java.util.Arrays.asList; -// Port of credentials.ts. class CredentialsImpl implements Credentials { private final BrowserContextImpl browserContext; 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 511965b4d..11b87b11d 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.*; @@ -28,7 +29,6 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.toProtocol; -// Port of debugger.ts. public class DebuggerImpl extends ChannelOwner implements Debugger { private DebuggerPausedDetails pausedDetails; // java: handlers of onPausedStateChanged(Runnable); upstream emits Events.Debugger.PausedStateChanged. apiCallsUpdated has no Java API. 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 a4bd13003..fac81998c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of download.ts. java: url and suggestedFilename are read from the initializer. +// Port of download.ts. package com.microsoft.playwright.impl; import com.google.gson.JsonObject; @@ -24,6 +24,7 @@ import java.io.InputStream; import java.nio.file.Path; +// java: url and suggestedFilename are read from the initializer. class DownloadImpl implements Download { private final PageImpl page; private final ArtifactImpl 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 64fc97662..236e7c9d4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -42,6 +42,8 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +import static com.microsoft.playwright.impl.FileUtils.fileUploadSizeLimit; +import static com.microsoft.playwright.impl.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; @@ -572,17 +574,21 @@ static String determineScreenshotType(Locator.ScreenshotOptions options) { return determineScreenshotType(options.path, options.type); } - // java: Utils.screenshotTypeForPath stands for getMimeTypeForPath and throws upstream's error for other mime types. private static String determineScreenshotType(Path path, ScreenshotType type) { if (path != null) { - return Utils.screenshotTypeForPath(path).toString().toLowerCase(); + 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: fileUtils.ts fileUploadSizeLimit, fs.promises.stat and fs.promises.readdir with recursive: true. - static final long fileUploadSizeLimit = 50 * 1024 * 1024; - + // java: fs.promises.stat and fs.promises.readdir with recursive: true. private static BasicFileAttributes stat(Path path) { try { return Files.readAttributes(path, BasicFileAttributes.class); 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..24be2a27f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -14,7 +14,7 @@ * 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.*; 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..9dea5fdfb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java @@ -13,7 +13,8 @@ * 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; @@ -72,10 +73,6 @@ void off(String type, Consumer listener) { removeListener(type, listener); } - void removeAllListeners(String type) { - events.remove(type); - } - int listenerCount(String type) { List> list = events.get(type); return list == null ? 0 : list.size(); 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..89dc5d624 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Events.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java @@ -13,7 +13,8 @@ * 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 { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java index f66121fec..c457aad92 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FileUtils.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of fileUtils.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; @@ -22,8 +23,10 @@ import java.nio.file.Files; import java.nio.file.Path; -// Port of fileUtils.ts. java: fileUploadSizeLimit is inlined in Utils.checkFilePayloadSize. 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(); 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/FrameExpectResult.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java new file mode 100644 index 000000000..8a4d3477d --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameExpectResult.java @@ -0,0 +1,29 @@ +/* + * 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.FrameExpectErrorDetails; + +import java.util.List; + +// 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 dcd616034..fe87554e7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -276,13 +276,6 @@ public Object evaluate(String expression, Object arg) { return deserialize(channel.evaluateExpression(params, NO_TIMEOUT).value); } - 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); @@ -519,14 +512,15 @@ 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(testId, connection.playwright)); + return locator(getByTestIdSelector(connection.playwright.selectors.testIdAttributeName, testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, connection.playwright)); + return locator(getByTestIdSelector(connection.playwright.selectors.testIdAttributeName, testId)); } @Override 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 c05afa63c..1e0aa2738 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -54,15 +54,15 @@ public Locator locator(Locator selectorOrLocator, LocatorOptions options) { return new LocatorImpl(frame, childSelector(((LocatorImpl) selectorOrLocator).selector), convertType(options, Locator.LocatorOptions.class)); } - // java: the test id attribute lives in SelectorsImpl of the Playwright instance, see LocatorUtils.getByTestIdSelector. + // java: testIdAttributeName() of locator.ts is a field of SelectorsImpl of the Playwright instance. @Override public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java index cb42d0164..5b837bd32 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java @@ -38,7 +38,6 @@ import java.util.Map; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static com.microsoft.playwright.impl.LoggingSupport.logApiIfEnabled; class HarRouter { @@ -51,7 +50,7 @@ class HarRouter { static HarRouter create(LocalUtils localUtils, String file, HarNotFound notFoundAction, Object urlMatch) { LocalUtilsHarOpenParams params = new LocalUtilsHarOpenParams(); params.file = file; - LocalUtilsHarOpenResult result = localUtils.channel.harOpen(params, NO_TIMEOUT); + LocalUtilsHarOpenResult result = localUtils.harOpen(params); if (result.error != null) { throw new PlaywrightException(result.error); } @@ -80,7 +79,7 @@ private void handle(Route route) { params.headers = toNameValues(request.headersArray()); params.postData = request.postDataBuffer(); params.isNavigationRequest = request.isNavigationRequest(); - LocalUtilsHarLookupResult response = localUtils.channel.harLookup(params, NO_TIMEOUT); + LocalUtilsHarLookupResult response = localUtils.harLookup(params); if ("redirect".equals(response.action)) { logApiIfEnabled("HAR: " + route.request().url() + " redirected to " + response.redirectURL); @@ -159,7 +158,7 @@ void dispose() { LocalUtilsHarCloseParams params = new LocalUtilsHarCloseParams(); params.harId = harId; try { - localUtils.sendMessageAsync("harClose", params); + localUtils.harClose(params); } catch (PlaywrightException e) { } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Headers.java b/playwright/src/main/java/com/microsoft/playwright/impl/Headers.java new file mode 100644 index 000000000..7397cc5b2 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Headers.java @@ -0,0 +1,47 @@ +/* + * 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; + +import com.microsoft.playwright.impl.protocol.NameValue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +// java: headersArrayToObject and splitSetCookieHeader have no caller in the client. +final class Headers { + private Headers() { + } + + // java: the client never passes separator and setCookieSeparator; a null value is undefined. + static List headersObjectToArray(Map headers) { + List result = new ArrayList<>(); + for (Map.Entry entry : headers.entrySet()) { + String name = entry.getKey(); + String values = entry.getValue(); + if (values == null) { + continue; + } + NameValue header = new NameValue(); + header.name = name; + header.value = values; + result.add(header); + } + return result; + } +} 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 805a39501..5c828edd6 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,9 +28,6 @@ import java.util.Queue; import java.util.function.Consumer; -import static com.microsoft.playwright.impl.Serialization.gson; - -// Port of jsonPipe.ts. public class JsonPipe extends ChannelOwner implements Transport { final JsonPipeChannel channel = new JsonPipeChannel(this); @@ -84,10 +82,6 @@ void onClose(Consumer handler) { on(Events.JsonPipe.CLOSE, handler); } - void offClose(Consumer handler) { - off(Events.JsonPipe.CLOSE, handler); - } - @Override public void close() throws IOException { if (!isClosed) { 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 7c318e264..39206917c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java @@ -14,19 +14,16 @@ * 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.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.gson; - -// Port of localUtils.ts. public class LocalUtils extends ChannelOwner { final LocalUtilsChannel channel = new LocalUtilsChannel(this); @@ -39,34 +36,43 @@ JsonArray deviceDescriptors() { return initializer.getAsJsonArray("deviceDescriptors"); } - 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; - } + void zip(LocalUtilsZipParams params) { channel.zip(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; + 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); } + // 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: no counterpart upstream, the Java API matches globs on the driver. public Pattern globToRegex(String glob, String baseURL, boolean webSocketUrl) { LocalUtilsGlobToRegexParams params = new LocalUtilsGlobToRegexParams(); 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 cf8ead9f9..c41230967 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -35,6 +35,8 @@ import static com.microsoft.playwright.impl.LocatorUtils.*; import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; +import static com.microsoft.playwright.impl.StringUtils.escapeForTextSelector; +import static com.microsoft.playwright.impl.Time.monotonicTime; import static com.microsoft.playwright.impl.Utils.convertType; class LocatorImpl implements Locator { @@ -230,15 +232,15 @@ public Locator within(Locator locator) { return locator.locator(this); } - // java: the test id attribute lives in SelectorsImpl of the Playwright instance, see LocatorUtils.getByTestIdSelector. + // java: testIdAttributeName() of locator.ts is a field of SelectorsImpl of the Playwright instance. @Override public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(testId, frame.connection.playwright)); + return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); } @Override @@ -693,10 +695,6 @@ public String toString() { // java: helpers and members with no upstream counterpart. private String stringRepresentation; - private static double monotonicTime() { - return System.nanoTime() / 1_000_000.0; - } - private Frame.SelectOptionOptions frameSelectOptionOptions(SelectOptionOptions options) { if (options == null) options = new SelectOptionOptions(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java index 3e40477ac..e5b0d65cb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java @@ -22,10 +22,10 @@ import java.util.ArrayList; import java.util.List; -import java.util.regex.Pattern; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +import static com.microsoft.playwright.impl.StringUtils.escapeForAttributeSelector; +import static com.microsoft.playwright.impl.StringUtils.escapeForTextSelector; public final class LocatorUtils { // java: each getBy* method has its own options class, so the exact flag is passed instead of the options. @@ -38,9 +38,7 @@ static String encodeTestIdAttributeName(String testIdAttributeName) { return testIdAttributeName.contains(",") ? gson().toJson(testIdAttributeName) : testIdAttributeName; } - // java: the test id attribute name lives in SelectorsImpl of the Playwright instance, not in a module variable. - static String getByTestIdSelector(Object testId, PlaywrightImpl playwright) { - String testIdAttributeName = playwright.selectors.testIdAttributeName; + static String getByTestIdSelector(String testIdAttributeName, Object testId) { return "internal:testid=[" + encodeTestIdAttributeName(testIdAttributeName) + "=" + escapeForAttributeSelector(testId, true) + "]"; } @@ -92,38 +90,4 @@ static String getByRoleSelector(AriaRole role, Locator.GetByRoleOptions options) result.append("[").append(prop[0]).append("=").append(prop[1]).append("]"); return result.toString(); } - - // java: ports of the isomorphic/stringUtils.ts escapes that the selectors above use. - // java: toJsRegexFlags() never produces the 'u' or 'v' flag, so there is no unicode early return. - 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 text, boolean exact) { - if (text instanceof Pattern) - return escapeRegexForSelector((Pattern) text); - if (text instanceof String) - return gson().toJson(text) + (exact ? "s" : "i"); - throw new IllegalArgumentException("text parameter must be Pattern or String: " + text); - } - - // java: an exact match has no suffix here, upstream appends 's'; kept as the old Java client sent it. - 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); - } - - // java: String(re) of a JS RegExp. - 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..12c52f4d0 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java @@ -0,0 +1,86 @@ +/* + * 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.List; + +// java: only the LongStandingScope class, and only the members the client uses (no reject, raceMultiple or the +// safeRace default value). There are no terminate promises to resolve: a race is a Waitable that is done once +// the scope is closed, and the owner pumps the connection while it waits. +class LongStandingScope { + private final ChannelOwner owner; + private PlaywrightException closeError; + private boolean isClosed; + + LongStandingScope(ChannelOwner owner) { + this.owner = owner; + } + + void close(PlaywrightException error) { + isClosed = true; + closeError = error; + } + + T race(Waitable promise) { + return race(promise, false); + } + + T safeRace(Waitable promise) { + return race(promise, true); + } + + private T race(Waitable promise, boolean safe) { + Waitable terminatePromise = terminatePromise(safe); + List> promises = new ArrayList<>(); + // java: the promise goes first, a settled promise wins over a closed scope as its reaction runs first upstream. + promises.add(promise); + promises.add(terminatePromise); + return owner.runUntil(() -> {}, new WaitableRace<>(promises)); + } + + // java: terminatePromise of _race, also raced by PageImpl.createWaitForCloseHelper(); a safe one returns null. + Waitable terminatePromise(boolean safe) { + return new Waitable() { + @Override + public boolean isDone() { + return isClosed; + } + + @Override + public T get() { + if (safe) + return null; + throw cloneError(closeError); + } + + @Override + public void dispose() { + } + }; + } + + // java: a new exception of the same type, so that the stack trace points at the caller of the race. + private static PlaywrightException cloneError(PlaywrightException error) { + if (error instanceof TargetClosedError) + return new TargetClosedError(error.getMessage()); + return new PlaywrightException(error.getMessage()); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java b/playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java new file mode 100644 index 000000000..5cfd74352 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java @@ -0,0 +1,453 @@ +/* + * 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; + +import java.util.LinkedHashMap; +import java.util.Map; + +// java: only getMimeTypeForPath and its table; isJsonMimeType, isXmlMimeType, isTextualMimeType and +// getExtensionForMimeType have no caller in the client. +final class MimeType { + private MimeType() { + } + + 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); + } + + 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/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 5fd437fef..8f3956deb 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -17,13 +17,11 @@ // Port of page.ts. package com.microsoft.playwright.impl; -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.ArrayList; import java.util.LinkedHashMap; @@ -36,13 +34,12 @@ import java.util.function.Predicate; import java.util.regex.Pattern; +import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.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; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.nio.file.Files.readAllBytes; -import static java.util.Arrays.asList; public class PageImpl extends ChannelOwner implements Page { final PageChannel channel = new PageChannel(this); @@ -53,8 +50,7 @@ public class PageImpl extends ChannelOwner implements Page { private final Set frames = new LinkedHashSet<>(); final Set workers = new LinkedHashSet<>(); private boolean closed; - // java: LongStandingScope is the error it was closed with; createWaitForCloseHelper() races it. - private TargetClosedError closedOrCrashedScope; + final LongStandingScope closedOrCrashedScope = new LongStandingScope(this); private ViewportSize viewportSize; List routes = new ArrayList<>(); List webSocketRoutes = new ArrayList<>(); @@ -109,14 +105,14 @@ public class PageImpl extends ChannelOwner implements Page { @Override public void accept(Page page) { off(Events.Page.CLOSE, this); - closedOrCrashedScope = closeErrorWithReason(); + closedOrCrashedScope.close(closeErrorWithReason()); } }); on(Events.Page.CRASH, new Consumer() { @Override public void accept(Page page) { off(Events.Page.CRASH, this); - closedOrCrashedScope = new TargetClosedError(); + closedOrCrashedScope.close(new TargetClosedError()); } }); @@ -469,7 +465,7 @@ public AutoCloseable exposeBinding(String name, BindingCallback callback) { public void setExtraHTTPHeaders(Map headers) { RawHeaders.validateHeaders(headers); PageSetExtraHTTPHeadersParams params = new PageSetExtraHTTPHeadersParams(); - params.headers = RawHeaders.headersObjectToArray(headers); + params.headers = Headers.headersObjectToArray(headers); channel.setExtraHTTPHeaders(params, NO_TIMEOUT); } @@ -797,21 +793,20 @@ public Object evaluate(String expression, Object arg) { // java: the script is a string or a file; there is no function to serialize and no exposeFunctions option. @Override public AutoCloseable addInitScript(String script) { - PageAddInitScriptParams params = new PageAddInitScriptParams(); - params.source = script; - return channel.addInitScript(params, NO_TIMEOUT).disposable; + return addInitScriptImpl(script); } @Override public AutoCloseable addInitScript(Path script) { - // java: evaluationScript of clientHelper.ts for { path }. - String source; - try { - source = new String(readAllBytes(script), UTF_8); - } catch (IOException e) { - throw new PlaywrightException("Failed to read script from file", e); - } - return addInitScript(ClientHelper.addSourceUrlToScript(source, script)); + return addInitScriptImpl(script); + } + + // java: the core of the String and Path overloads; the exposeFunctions option and arg have no Java API. + private AutoCloseable addInitScriptImpl(Object script) { + String source = evaluationScript(script, true); + PageAddInitScriptParams params = new PageAddInitScriptParams(); + params.source = source; + return channel.addInitScript(params, NO_TIMEOUT).disposable; } @Override @@ -1323,9 +1318,7 @@ public void pause() { Double defaultTimeout = browserContext.timeoutSettings.defaultTimeout(); browserContext.setDefaultNavigationTimeout(0); browserContext.setDefaultTimeout(0); - // java: closedOrCrashedScope.safeRace(promise) is a race of the reply with a close helper that returns null. - WaitableResult pause = browserContext.sendMessageAsync("pause"); - runUntil(() -> {}, new WaitableRace<>(asList(pause, new ClosedOrCrashed<>(true)))); + 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); @@ -1368,18 +1361,6 @@ private static String trimUrl(Object param) { return null; } - // java: trimStringWithEllipsis of isomorphic/stringUtils.ts, counting code points like [...input]. - 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) + "…"; - } - return input; - } - // java: the value object of _locatorHandlers. private static class LocatorHandler { final LocatorImpl locator; @@ -1394,7 +1375,7 @@ private static class LocatorHandler { } // java: the public API members with no upstream counterpart: accessors of the readonly fields, typed - // listeners, onceDialog, waitForCondition, and the close helpers that stand in for _closedOrCrashedScope. + // listeners, onceDialog, waitForCondition and its waitables. @Override public ClockImpl clock() { return clock; @@ -1664,37 +1645,12 @@ public void waitForCondition(BooleanSupplier condition, WaitForConditionOptions runUntil(() -> {}, new WaitableRace<>(waitables)); } - // A race with _closedOrCrashedScope: done once the page closed or crashed, then throws the error the scope was closed with. + // java: done once the page closed or crashed, then throws the error closedOrCrashedScope was closed with. Waitable createWaitForCloseHelper() { - return new ClosedOrCrashed<>(false); + return closedOrCrashedScope.terminatePromise(false); } Waitable createWaitableTimeout(Double timeout) { return timeoutSettings.createWaitable(timeout); } - - private class ClosedOrCrashed implements Waitable { - private final boolean safe; - - ClosedOrCrashed(boolean safe) { - this.safe = safe; - } - - @Override - public boolean isDone() { - return closedOrCrashedScope != null; - } - - @Override - public T get() { - if (safe) { - return null; - } - throw new TargetClosedError(closedOrCrashedScope.getMessage()); - } - - @Override - public void dispose() { - } - } } 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 472c14e58..2ec8d89c9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -19,18 +19,13 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import com.microsoft.playwright.BrowserContext; -import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import com.microsoft.playwright.PlaywrightException; 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.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -60,27 +55,7 @@ public class PlaywrightImpl extends ChannelOwner implements Playwright { selectors = new SelectorsImpl(); } - private List browserTypes() { - return Arrays.asList(chromium, firefox, webkit); - } - - // java: no _preLaunchedBrowser, only the test runner calls it upstream. - - List allContexts() { - List result = new ArrayList<>(); - for (BrowserTypeImpl type : browserTypes()) { - result.addAll(type.contexts); - } - return result; - } - - List allPages() { - List result = new ArrayList<>(); - for (BrowserContext context : allContexts()) { - result.addAll(context.pages()); - } - return result; - } + // java: no _browserTypes, _preLaunchedBrowser, _allContexts and _allPages, they serve the test runner upstream. // java: the entry point of the Java client and the getters of the Java API, playwright.ts has no counterpart. private Process driverProcess; @@ -99,7 +74,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); @@ -150,7 +125,7 @@ public APIRequestImpl request() { 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 fbaf086ba..b2bfacb33 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RawHeaders.java @@ -91,7 +91,7 @@ List headersArray() { return result; } - // java: module-level functions of network.ts and isomorphic/headers.ts used with headers. + // 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". @@ -100,18 +100,4 @@ static void validateHeaders(Map headers) { } } } - - static List headersObjectToArray(Map headers) { - List result = 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(); - result.add(header); - } - return result; - } } 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 caefde404..ed7198a4a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java @@ -29,10 +29,8 @@ import com.microsoft.playwright.options.Timing; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.function.Supplier; import static com.microsoft.playwright.impl.Serialization.gson; @@ -270,67 +268,11 @@ SerializedFallbackOverrides fallbackOverridesForContinue() { LongStandingScope targetClosedScope() { WorkerImpl serviceWorker = serviceWorker(); - if (serviceWorker != null) { - // java: WorkerImpl has no _closedScope, the Close event closes it. - return new LongStandingScope(this, () -> new WaitableEvent(serviceWorker, Events.Worker.CLOSE) { - @Override - public Object get() { - throw serviceWorker.closeErrorWithReason(); - } - }); - } + if (serviceWorker != null) + return serviceWorker.closedScope; PageImpl page = safePage(); - if (page != null) { - return new LongStandingScope(this, page::createWaitForCloseHelper); - } - return new LongStandingScope(this, null); - } - - // java: LongStandingScope of isomorphic/manualPromise.ts, made of the Waitable that is done once the scope - // closed and then throws its error; null is a scope that never closes. - static class LongStandingScope { - private final ChannelOwner owner; - private final Supplier> terminatePromise; - - LongStandingScope(ChannelOwner owner, Supplier> terminatePromise) { - this.owner = owner; - this.terminatePromise = terminatePromise; - } - - T race(Waitable promise) { - return race(promise, false); - } - - T safeRace(Waitable promise) { - return race(promise, true); - } - - @SuppressWarnings("unchecked") - private T race(Waitable promise, boolean safe) { - if (terminatePromise == null) { - return owner.runUntil(() -> {}, promise); - } - Waitable terminate = terminatePromise.get(); - List> waitables = new ArrayList<>(); - // java: the promise goes first, a settled promise wins over a closed scope as its reaction runs first upstream. - waitables.add((Waitable) promise); - waitables.add(safe ? new Waitable() { - @Override - public boolean isDone() { - return terminate.isDone(); - } - - @Override - public Object get() { - return null; - } - - @Override - public void dispose() { - terminate.dispose(); - } - } : terminate); - return (T) owner.runUntil(() -> {}, new WaitableRace<>(waitables)); - } + if (page != null) + return page.closedOrCrashedScope; + return new LongStandingScope(this); } } 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 3fd5a5774..e6604c0c7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -37,7 +37,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import static com.microsoft.playwright.impl.RawHeaders.headersObjectToArray; +import static com.microsoft.playwright.impl.Headers.headersObjectToArray; +import static com.microsoft.playwright.impl.MimeType.getMimeTypeForPath; public class RouteImpl extends ChannelOwner implements Route { private WaitableResult handlingPromise = null; @@ -195,7 +196,8 @@ private void innerFulfill(FulfillOptions options) { if (options.contentType != null) { headers.put("content-type", options.contentType); } 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", String.valueOf(length)); 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 69cf86d5d..084851e1b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of screencast.ts. java: onFrame receives a ScreencastFrame and the frame event arrives through handleScreencastFrame. +// Port of screencast.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -29,6 +29,7 @@ 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; 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 473429690..0083a9171 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,16 +22,13 @@ 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.List; 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; -// Port of selectors.ts. public class SelectorsImpl extends LoggingSupport implements Selectors { protected final List selectorEngines = new ArrayList<>(); // java: defaults to data-testid, upstream leaves it undefined until set. @@ -42,26 +40,21 @@ public void register(String name, String script, RegisterOptions options) { registerImpl(name, script, options); } - // java: evaluationScript with a path, without the sourceURL suffix. @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; } 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..41de72588 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 serializeArgument and parseResult 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,414 @@ 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.toJsRegexFlags; import static com.microsoft.playwright.impl.Utils.fromJsRegexFlags; +// java: systemErrorCode and systemErrorMessage read Node.js system errors and are not ported. class Serialization { + 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); + } + // java: Java has no function value, so value.fn is unexpected. + 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; Java has no fn. + static class HandleOrValue { + Integer h; + 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; + 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: Java cannot pass a function, so there is no registerCallback. + static SerializedArgument serializeArgument(Object arg) { + 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)); + return fallThrough(v); + }); + SerializedArgument result = new SerializedArgument(); + result.value = value; + result.handles = handles; + return result; + } + + static Object parseResult(SerializedValue value) { + return parseSerializedValue(value, null); + } + + // java: helpers of the ported part. + + // 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 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 +512,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 +544,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 +577,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 +748,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..ba4b5b307 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; 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 ed1fdc5c1..157b856c4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of stream.ts. java: the Readable is an InputStream; _read becomes read(), _destroy becomes close(). +// Port of stream.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -23,6 +23,7 @@ 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); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java new file mode 100644 index 000000000..22b7a806a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java @@ -0,0 +1,70 @@ +/* + * 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; + +import java.util.regex.Pattern; + +import static com.microsoft.playwright.impl.Serialization.gson; +import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; + +// java: only the functions the client uses; a string | RegExp parameter is an Object holding a String or a Pattern. +final class StringUtils { + private StringUtils() { + } + + // java: toJsRegexFlags() never produces the 'u' or 'v' flag, so there is no unicode early return. + 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 text, boolean exact) { + if (!(text instanceof String)) + return escapeRegexForSelector((Pattern) text); + return gson().toJson(text) + (exact ? "s" : "i"); + } + + 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"); + } + + // java: [...input] splits into code points. + 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); + } + + static String trimStringWithEllipsis(String input, int cap) { + return trimString(input, cap, "…"); + } + + // java: String(re) of a JS RegExp. + private static String toJsRegExp(Pattern pattern) { + return "/" + pattern.pattern() + "/" + toJsRegexFlags(pattern); + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Time.java b/playwright/src/main/java/com/microsoft/playwright/impl/Time.java new file mode 100644 index 000000000..c022a642a --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Time.java @@ -0,0 +1,32 @@ +/* + * 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; + +// java: no setTimeOrigin and timeOrigin, the client does not use them. +final class Time { + private Time() { + } + + // java: System.nanoTime() stands for performance.now(), in milliseconds. + static double monotonicTime() { + return Math.floor(System.nanoTime() / 1000.0) / 1000; + } + + static final int DEFAULT_PLAYWRIGHT_TIMEOUT = 30_000; + static final int DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1000; // 3 minutes +} 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..652561b6e 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,15 @@ * 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 +import static com.microsoft.playwright.impl.Time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; +import static com.microsoft.playwright.impl.Time.DEFAULT_PLAYWRIGHT_TIMEOUT; + +// 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; - private final TimeoutSettings parent; private Double defaultTimeout; private Double defaultNavigationTimeout; @@ -63,7 +64,7 @@ Double defaultTimeout() { if (parent != null) { return parent.navigationTimeout(timeout); } - return DEFAULT_TIMEOUT; + return DEFAULT_PLAYWRIGHT_TIMEOUT; } double timeout(Double timeout) { @@ -76,7 +77,7 @@ Double defaultTimeout() { if (parent != null) { return parent.timeout(timeout); } - return DEFAULT_TIMEOUT; + return DEFAULT_PLAYWRIGHT_TIMEOUT; } double launchTimeout(Double timeout) { @@ -86,7 +87,7 @@ Double defaultTimeout() { if (parent != null) { return parent.launchTimeout(timeout); } - return DEFAULT_LAUNCH_TIMEOUT; + return DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; } // java: removed once every wait goes through Waiter. 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 8f2f9d092..62b544f9f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -27,7 +27,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -124,8 +123,7 @@ private void startCollectingStacks(String traceName, boolean live) { params.traceName = traceName; params.live = live; LocalUtils localUtils = connection.localUtils(); - // java: LocalUtils.tracingStarted of the seed has no live flag and drops tracesDir, so the channel is called directly. - LocalUtilsTracingStartedResult result = localUtils == null ? null : localUtils.channel.tracingStarted(params, NO_TIMEOUT); + LocalUtilsTracingStartedResult result = localUtils == null ? null : localUtils.tracingStarted(params); stacksId = result == null ? null : result.stacksId; } @@ -224,7 +222,13 @@ void exportHAR(String harId) { if (localUtils == null) { throw new PlaywrightException("Cannot save zipped HAR in thin clients"); } - localUtils.zip(harParams.path, entries, null, false, false, Collections.emptyList()); + 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; } @@ -246,8 +250,7 @@ void exportHAR(String harId) { unzipParams.zipFile = harParams.path + ".tmp"; unzipParams.harFile = harParams.path.toString(); unzipParams.resourcesDir = harParams.resourcesDir == null ? null : harParams.resourcesDir.toString(); - // java: the seed LocalUtils has no harUnzip wrapper. - localUtils.channel.harUnzip(unzipParams, NO_TIMEOUT); + localUtils.harUnzip(unzipParams); artifact.delete(); } @@ -273,7 +276,7 @@ private void doStopChunk(Path filePath) { // Release the stack session even on failure, otherwise later traces keep appending to it. if (stacksId != null && connection.localUtils() != null) { try { - connection.localUtils().traceDiscarded(stacksId); + connection.localUtils().traceDiscarded(traceDiscardedParams(stacksId)); } catch (PlaywrightException e) { } } @@ -288,7 +291,7 @@ private void saveChunk(Path filePath, String stacksId, List additionalSo params.mode = "discard"; channel.tracingStopChunk(params, NO_TIMEOUT); if (stacksId != null) { - connection.localUtils().traceDiscarded(stacksId); + connection.localUtils().traceDiscarded(traceDiscardedParams(stacksId)); } return; } @@ -304,7 +307,14 @@ private void saveChunk(Path filePath, String stacksId, List additionalSo TracingTracingStopChunkParams params = new TracingTracingStopChunkParams(); params.mode = "entries"; TracingTracingStopChunkResult result = channel.tracingStopChunk(params, NO_TIMEOUT); - localUtils.zip(filePath, result.entries, stacksId, false, includeSources, additionalSources); + 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; } @@ -315,7 +325,7 @@ private void saveChunk(Path filePath, String stacksId, List additionalSo // The artifact may be missing if the browser closed while stopping tracing. if (result.artifact == null) { if (stacksId != null) { - localUtils.traceDiscarded(stacksId); + localUtils.traceDiscarded(traceDiscardedParams(stacksId)); } return; } @@ -334,7 +344,14 @@ private void saveChunk(Path filePath, String stacksId, List additionalSo } artifact.delete(); - localUtils.zip(filePath, new ArrayList<>(), stacksId, true, includeSources, additionalSources); + 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() { @@ -358,4 +375,11 @@ static class HarRecorder { private static boolean isZip(Path path) { return path.toString().toLowerCase().endsWith(".zip"); } + + // 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 5c3deca37..53f87bd28 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java @@ -28,6 +28,8 @@ import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; +// java: globToRegexPattern, resolveGlobToRegexPattern, resolveGlobBase and the other glob functions are not ported: +// the driver resolves globs (LocalUtils.globToRegex), as they rely on the WHATWG URL parser. // java: an URLMatch value; a glob also holds its resolved regex, so test() does not resolve it again. class UrlMatcher { public final String glob; @@ -117,12 +119,7 @@ static UrlMatcher forGlob(URL baseURL, String glob, LocalUtils localUtils, boole return new UrlMatcher(glob, pattern, null); } - // java: constructURLBasedOnBaseURL() for the base URL of a context. - static String resolveUrl(URL baseUrl, String spec) { - return constructURLBasedOnBaseURL(baseUrl.toString(), spec); - } - - private static String constructURLBasedOnBaseURL(String baseURL, String givenURL) { + static String constructURLBasedOnBaseURL(String baseURL, String givenURL) { if (baseURL == null) { return givenURL; } 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 c5034ff89..8f50448ee 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,21 +151,6 @@ static FilePayload toFilePayload(Path file) { return new FilePayload(file.getFileName().toString(), null, buffer); } - /** 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) { FileUtils.mkdirIfNeeded(path); try (FileOutputStream out = new FileOutputStream(path.toFile())) { @@ -343,45 +173,6 @@ 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) { String regexFlags = ""; if ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) { @@ -416,26 +207,13 @@ static int fromJsRegexFlags(String regexFlags) { return flags; } - 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 9821a57fe..d5224c5e5 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of video.ts. java: the video is created before its artifact is known, so the artifact is assigned later. +// Port of video.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.PlaywrightException; @@ -23,6 +23,7 @@ import java.nio.file.Path; import java.nio.file.Paths; +// java: the video is created before its artifact is known, so the artifact is assigned later. class VideoImpl implements Video { private final PageImpl page; ArtifactImpl 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..bbd6c71bc 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<>(); 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 fedeadea2..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.*; @@ -27,7 +28,6 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.serializeArgument; -// Port of webmcp.ts. class WebMCPImpl implements WebMCP { private final FrameImpl frame; 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 e033b3040..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.*; @@ -26,7 +27,6 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static java.util.Arrays.asList; -// Port of webStorage.ts. class WebStorageImpl implements WebStorage { private final PageImpl page; private final String kind; 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 0cfb26a70..5b7ac6f8e 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.*; @@ -33,10 +34,10 @@ import static com.microsoft.playwright.impl.Serialization.*; -// Port of worker.ts. public class WorkerImpl extends ChannelOwner implements Worker { PageImpl page; // java: no service worker or connectToWorker API, so there is no _context, _closeReason or _disconnect. + final LongStandingScope closedScope = new LongStandingScope(this); final WorkerChannel channel = new WorkerChannel(this); @@ -45,6 +46,13 @@ public class WorkerImpl extends ChannelOwner implements Worker { 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. 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 348d0e2ba..e6963c809 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java @@ -14,7 +14,7 @@ * limitations under the License. */ -// Port of writableStream.ts. java: the Writable is an OutputStream; _write becomes write(), _final becomes close(). +// Port of writableStream.ts. package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; @@ -26,6 +26,7 @@ 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); From 6e6c0e5f849ed9a741ce9c2c25ed9ea023d044b0 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 20 Nov 2026 14:32:09 -0800 Subject: [PATCH 29/30] chore: move the ports of the isomorphic helpers into impl.isomorphic --- .../impl/APIRequestContextImpl.java | 2 +- .../playwright/impl/APIRequestImpl.java | 1 + .../playwright/impl/BrowserContextImpl.java | 1 + .../microsoft/playwright/impl/Connect.java | 2 +- .../microsoft/playwright/impl/Connection.java | 2 +- .../playwright/impl/ElementHandleImpl.java | 2 +- .../microsoft/playwright/impl/FrameImpl.java | 2 +- .../playwright/impl/FrameLocatorImpl.java | 2 +- .../playwright/impl/LocatorImpl.java | 6 ++--- .../playwright/impl/LongStandingScope.java | 1 + .../microsoft/playwright/impl/PageImpl.java | 3 ++- .../microsoft/playwright/impl/RouteImpl.java | 4 +-- .../playwright/impl/TimeoutSettings.java | 4 +-- .../microsoft/playwright/impl/UrlMatcher.java | 1 + .../com/microsoft/playwright/impl/Utils.java | 2 +- .../impl/{ => isomorphic}/Headers.java | 6 ++--- .../impl/{ => isomorphic}/LocatorUtils.java | 26 +++++++++---------- .../impl/{ => isomorphic}/MimeType.java | 6 ++--- .../impl/{ => isomorphic}/StringUtils.java | 24 +++++++++++------ .../impl/{ => isomorphic}/Time.java | 10 +++---- 20 files changed, 60 insertions(+), 47 deletions(-) rename playwright/src/main/java/com/microsoft/playwright/impl/{ => isomorphic}/Headers.java (89%) rename playwright/src/main/java/com/microsoft/playwright/impl/{ => isomorphic}/LocatorUtils.java (76%) rename playwright/src/main/java/com/microsoft/playwright/impl/{ => isomorphic}/MimeType.java (99%) rename playwright/src/main/java/com/microsoft/playwright/impl/{ => isomorphic}/StringUtils.java (77%) rename playwright/src/main/java/com/microsoft/playwright/impl/{ => isomorphic}/Time.java (76%) 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 20376bd20..fe06d0f1b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -40,7 +40,7 @@ import java.util.Map; import static com.microsoft.playwright.impl.Errors.isTargetClosedError; -import static com.microsoft.playwright.impl.Headers.headersObjectToArray; +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; 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 c54010644..c99808c68 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -17,6 +17,7 @@ // Port of fetch.ts. package com.microsoft.playwright.impl; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.microsoft.playwright.APIRequest; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.impl.protocol.PlaywrightNewRequestParams; 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 a4d3bc950..a6fdf1a12 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -17,6 +17,7 @@ // Port of browserContext.ts. package com.microsoft.playwright.impl; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java index 13c9ad35b..8780feaa9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java @@ -32,7 +32,7 @@ import java.util.Map; import java.util.function.Consumer; -import static com.microsoft.playwright.impl.Time.monotonicTime; +import static com.microsoft.playwright.impl.isomorphic.Time.monotonicTime; final class Connect { private Connect() { 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 fa23a5ea2..df57afc4e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -43,7 +43,7 @@ import java.util.concurrent.TimeUnit; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Time.monotonicTime; +import static com.microsoft.playwright.impl.isomorphic.Time.monotonicTime; class Root extends ChannelOwner { Root(Connection connection) { 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 236e7c9d4..025558135 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -43,7 +43,7 @@ import java.util.stream.Stream; import static com.microsoft.playwright.impl.FileUtils.fileUploadSizeLimit; -import static com.microsoft.playwright.impl.MimeType.getMimeTypeForPath; +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; 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 fe87554e7..f73374f6b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -36,7 +36,7 @@ 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.serializeArgument; 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 1e0aa2738..403ec4bb1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -24,7 +24,7 @@ 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.Utils.convertType; class FrameLocatorImpl implements FrameLocator { 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 c41230967..bfa534920 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -32,11 +32,11 @@ import java.util.regex.Pattern; import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; -import static com.microsoft.playwright.impl.LocatorUtils.*; +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.StringUtils.escapeForTextSelector; -import static com.microsoft.playwright.impl.Time.monotonicTime; +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 { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java index 12c52f4d0..2274894d1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java @@ -25,6 +25,7 @@ // java: only the LongStandingScope class, and only the members the client uses (no reject, raceMultiple or the // safeRace default value). There are no terminate promises to resolve: a race is a Waitable that is done once // the scope is closed, and the owner pumps the connection while it waits. +// java: stays in impl, not in impl.isomorphic: it is built on ChannelOwner and the Waitable primitives. class LongStandingScope { private final ChannelOwner owner; private PlaywrightException closeError; 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 8f3956deb..3faaa04d4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -17,6 +17,7 @@ // Port of page.ts. package com.microsoft.playwright.impl; +import com.microsoft.playwright.impl.isomorphic.Headers; import com.google.gson.JsonObject; import com.microsoft.playwright.*; import com.microsoft.playwright.impl.protocol.*; @@ -36,7 +37,7 @@ import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.StringUtils.trimStringWithEllipsis; +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; 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 e6604c0c7..6ad251390 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -37,8 +37,8 @@ import java.util.LinkedHashMap; import java.util.Map; -import static com.microsoft.playwright.impl.Headers.headersObjectToArray; -import static com.microsoft.playwright.impl.MimeType.getMimeTypeForPath; +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 WaitableResult handlingPromise = null; 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 652561b6e..dd13f0f7f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java @@ -17,8 +17,8 @@ // Port of timeoutSettings.ts. package com.microsoft.playwright.impl; -import static com.microsoft.playwright.impl.Time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; -import static com.microsoft.playwright.impl.Time.DEFAULT_PLAYWRIGHT_TIMEOUT; +import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; +import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_TIMEOUT; // java: no AbortSignal and no PWDEBUG=inspector branch, a timeout is a Double // and 0 means no deadline. 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 53f87bd28..9c0aa95a4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java @@ -31,6 +31,7 @@ // java: globToRegexPattern, resolveGlobToRegexPattern, resolveGlobBase and the other glob functions are not ported: // the driver resolves globs (LocalUtils.globToRegex), as they rely on the WHATWG URL parser. // java: an URLMatch value; a glob also holds its resolved regex, so test() does not resolve it again. +// 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; 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 8f50448ee..9d7056e17 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java @@ -173,7 +173,7 @@ static void writeToFile(InputStream inputStream, Path path) { } } - static String toJsRegexFlags(Pattern pattern) { + public static String toJsRegexFlags(Pattern pattern) { String regexFlags = ""; if ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) { // Case-insensitive search. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Headers.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java similarity index 89% rename from playwright/src/main/java/com/microsoft/playwright/impl/Headers.java rename to playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java index 7397cc5b2..a1a8b573f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Headers.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java @@ -15,7 +15,7 @@ */ // Port of isomorphic/headers.ts. -package com.microsoft.playwright.impl; +package com.microsoft.playwright.impl.isomorphic; import com.microsoft.playwright.impl.protocol.NameValue; @@ -24,12 +24,12 @@ import java.util.Map; // java: headersArrayToObject and splitSetCookieHeader have no caller in the client. -final class Headers { +public final class Headers { private Headers() { } // java: the client never passes separator and setCookieSeparator; a null value is undefined. - static List headersObjectToArray(Map headers) { + public static List headersObjectToArray(Map headers) { List result = new ArrayList<>(); for (Map.Entry entry : headers.entrySet()) { String name = entry.getKey(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java similarity index 76% rename from playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java rename to playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java index e5b0d65cb..dacee5519 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java @@ -15,7 +15,7 @@ */ // Port of isomorphic/locatorUtils.ts. -package com.microsoft.playwright.impl; +package com.microsoft.playwright.impl.isomorphic; import com.microsoft.playwright.Locator; import com.microsoft.playwright.options.AriaRole; @@ -23,9 +23,9 @@ import java.util.ArrayList; import java.util.List; -import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.StringUtils.escapeForAttributeSelector; -import static com.microsoft.playwright.impl.StringUtils.escapeForTextSelector; +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; public final class LocatorUtils { // java: each getBy* method has its own options class, so the exact flag is passed instead of the options. @@ -34,36 +34,36 @@ private static String getByAttributeTextSelector(String attrName, Object text, B } // Multiple test id attribute names can be joined with a comma. Attribute names cannot contain commas. - static String encodeTestIdAttributeName(String testIdAttributeName) { - return testIdAttributeName.contains(",") ? gson().toJson(testIdAttributeName) : testIdAttributeName; + public static String encodeTestIdAttributeName(String testIdAttributeName) { + return testIdAttributeName.contains(",") ? jsonStringify(testIdAttributeName) : testIdAttributeName; } - static String getByTestIdSelector(String testIdAttributeName, Object testId) { + public static String getByTestIdSelector(String testIdAttributeName, Object testId) { return "internal:testid=[" + encodeTestIdAttributeName(testIdAttributeName) + "=" + escapeForAttributeSelector(testId, true) + "]"; } - static String getByLabelSelector(Object text, Locator.GetByLabelOptions options) { + public static String getByLabelSelector(Object text, Locator.GetByLabelOptions options) { return "internal:label=" + escapeForTextSelector(text, options != null && options.exact != null && options.exact); } - static String getByAltTextSelector(Object text, Locator.GetByAltTextOptions options) { + public static String getByAltTextSelector(Object text, Locator.GetByAltTextOptions options) { return getByAttributeTextSelector("alt", text, options == null ? null : options.exact); } - static String getByTitleSelector(Object text, Locator.GetByTitleOptions options) { + public static String getByTitleSelector(Object text, Locator.GetByTitleOptions options) { return getByAttributeTextSelector("title", text, options == null ? null : options.exact); } - static String getByPlaceholderSelector(Object text, Locator.GetByPlaceholderOptions options) { + public static String getByPlaceholderSelector(Object text, Locator.GetByPlaceholderOptions options) { return getByAttributeTextSelector("placeholder", text, options == null ? null : options.exact); } - static String getByTextSelector(Object text, Locator.GetByTextOptions options) { + 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. - static String getByRoleSelector(AriaRole role, Locator.GetByRoleOptions options) { + public static String getByRoleSelector(AriaRole role, Locator.GetByRoleOptions options) { if (options == null) options = new Locator.GetByRoleOptions(); List props = new ArrayList<>(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java similarity index 99% rename from playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java rename to playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java index 5cfd74352..2c609832f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MimeType.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java @@ -15,18 +15,18 @@ */ // Port of isomorphic/mimeType.ts. -package com.microsoft.playwright.impl; +package com.microsoft.playwright.impl.isomorphic; import java.util.LinkedHashMap; import java.util.Map; // java: only getMimeTypeForPath and its table; isJsonMimeType, isXmlMimeType, isTextualMimeType and // getExtensionForMimeType have no caller in the client. -final class MimeType { +public final class MimeType { private MimeType() { } - static String getMimeTypeForPath(String path) { + public static String getMimeTypeForPath(String path) { int dotIndex = path.lastIndexOf('.'); if (dotIndex == -1) return null; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java similarity index 77% rename from playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java rename to playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java index 22b7a806a..b5e44b426 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/StringUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java @@ -15,31 +15,39 @@ */ // Port of isomorphic/stringUtils.ts. -package com.microsoft.playwright.impl; +package com.microsoft.playwright.impl.isomorphic; + +import com.google.gson.Gson; import java.util.regex.Pattern; -import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.toJsRegexFlags; // java: only the functions the client uses; a string | RegExp parameter is an Object holding a String or a Pattern. -final class StringUtils { +public final class StringUtils { private StringUtils() { } + private static final Gson gson = new Gson(); + + // java: JSON.stringify of a string. + public static String jsonStringify(String value) { + return gson.toJson(value); + } + // java: toJsRegexFlags() never produces the 'u' or 'v' flag, so there is no unicode early return. 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 text, boolean exact) { + public static String escapeForTextSelector(Object text, boolean exact) { if (!(text instanceof String)) return escapeRegexForSelector((Pattern) text); - return gson().toJson(text) + (exact ? "s" : "i"); + return jsonStringify((String) text) + (exact ? "s" : "i"); } - static String escapeForAttributeSelector(Object value, boolean exact) { + public static String escapeForAttributeSelector(Object value, boolean exact) { if (!(value instanceof String)) return escapeRegexForSelector((Pattern) value); // TODO: this should actually be @@ -50,7 +58,7 @@ static String escapeForAttributeSelector(Object value, boolean exact) { } // java: [...input] splits into code points. - static String trimString(String input, int cap, String suffix) { + public static String trimString(String input, int cap, String suffix) { if (input.length() <= cap) return input; int[] chars = input.codePoints().toArray(); @@ -59,7 +67,7 @@ static String trimString(String input, int cap, String suffix) { return new String(chars, 0, chars.length); } - static String trimStringWithEllipsis(String input, int cap) { + public static String trimStringWithEllipsis(String input, int cap) { return trimString(input, cap, "…"); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Time.java b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java similarity index 76% rename from playwright/src/main/java/com/microsoft/playwright/impl/Time.java rename to playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java index c022a642a..72d5d9e18 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Time.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java @@ -15,18 +15,18 @@ */ // Port of isomorphic/time.ts. -package com.microsoft.playwright.impl; +package com.microsoft.playwright.impl.isomorphic; // java: no setTimeOrigin and timeOrigin, the client does not use them. -final class Time { +public final class Time { private Time() { } // java: System.nanoTime() stands for performance.now(), in milliseconds. - static double monotonicTime() { + public static double monotonicTime() { return Math.floor(System.nanoTime() / 1000.0) / 1000; } - static final int DEFAULT_PLAYWRIGHT_TIMEOUT = 30_000; - static final int DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1000; // 3 minutes + public static final int DEFAULT_PLAYWRIGHT_TIMEOUT = 30_000; + public static final int DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT = 3 * 60 * 1000; // 3 minutes } From c1771ee4b1f86f5704d14a49ff39900cc7aedfd5 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Fri, 20 Nov 2026 16:51:21 -0800 Subject: [PATCH 30/30] chore: port every member of the client files, used or not A member without a Java caller is package-private at its upstream position; what Java cannot express has a note there. Adds ClientInstrumentation and Coverage. --- .../impl/APIRequestContextImpl.java | 84 ++-- .../playwright/impl/APIRequestImpl.java | 9 +- .../playwright/impl/APIResponseImpl.java | 69 ++- .../playwright/impl/ApiCallData.java | 31 ++ .../playwright/impl/ArtifactImpl.java | 11 +- .../playwright/impl/BindingCall.java | 2 + .../playwright/impl/BrowserContextImpl.java | 111 ++++- .../playwright/impl/BrowserImpl.java | 76 +++- .../playwright/impl/BrowserTypeImpl.java | 120 ++++- .../playwright/impl/CDPSessionImpl.java | 3 + .../playwright/impl/ChannelOwner.java | 163 +++++-- .../playwright/impl/ClientHelper.java | 192 +++++++- .../impl/ClientInstrumentation.java | 146 ++++++ .../impl/ClientInstrumentationListener.java | 54 +++ .../microsoft/playwright/impl/ClockImpl.java | 113 +++-- .../microsoft/playwright/impl/Connect.java | 29 +- .../microsoft/playwright/impl/Connection.java | 318 +++++++------ .../playwright/impl/ConsoleMessageImpl.java | 28 +- .../microsoft/playwright/impl/Coverage.java | 55 +++ .../playwright/impl/DebuggerImpl.java | 44 +- .../microsoft/playwright/impl/DialogImpl.java | 2 + .../playwright/impl/DisposableObject.java | 33 +- .../playwright/impl/DisposableStub.java | 17 +- .../playwright/impl/DownloadImpl.java | 18 +- .../playwright/impl/ElementHandleImpl.java | 2 + .../com/microsoft/playwright/impl/Errors.java | 49 +- .../playwright/impl/EventEmitter.java | 268 ++++++++++- .../com/microsoft/playwright/impl/Events.java | 26 ++ .../playwright/impl/FileChooserImpl.java | 12 +- .../microsoft/playwright/impl/FrameImpl.java | 44 +- .../playwright/impl/FrameLocatorImpl.java | 6 +- .../microsoft/playwright/impl/HarRouter.java | 2 + .../playwright/impl/JSHandleImpl.java | 27 +- .../microsoft/playwright/impl/JsonPipe.java | 9 +- .../microsoft/playwright/impl/LocalUtils.java | 24 +- .../playwright/impl/LocatorImpl.java | 77 +++- .../playwright/impl/LongStandingScope.java | 112 +++-- .../microsoft/playwright/impl/MouseImpl.java | 12 +- .../microsoft/playwright/impl/PageImpl.java | 307 ++++++++++++- .../playwright/impl/PlaywrightImpl.java | 58 ++- .../playwright/impl/RequestImpl.java | 69 ++- .../playwright/impl/ResponseImpl.java | 9 +- .../playwright/impl/RouteHandler.java | 3 +- .../microsoft/playwright/impl/RouteImpl.java | 24 +- .../playwright/impl/ScreencastImpl.java | 68 +-- .../playwright/impl/SelectorsImpl.java | 16 +- .../playwright/impl/Serialization.java | 79 +++- .../playwright/impl/StackTraceCollector.java | 5 +- .../com/microsoft/playwright/impl/Stream.java | 9 +- .../playwright/impl/TimeoutSettings.java | 31 +- .../playwright/impl/TracingImpl.java | 8 + .../microsoft/playwright/impl/UrlMatcher.java | 420 +++++++++++++++++- .../microsoft/playwright/impl/VideoImpl.java | 23 +- .../com/microsoft/playwright/impl/Waiter.java | 38 +- .../playwright/impl/WebSocketImpl.java | 4 + .../playwright/impl/WebSocketRouteImpl.java | 6 + .../microsoft/playwright/impl/WorkerImpl.java | 49 +- .../playwright/impl/WritableStream.java | 2 + .../playwright/impl/isomorphic/Headers.java | 71 ++- .../impl/isomorphic/LocatorUtils.java | 9 + .../playwright/impl/isomorphic/MimeType.java | 40 +- .../impl/isomorphic/StringUtils.java | 278 +++++++++++- .../playwright/impl/isomorphic/Time.java | 32 +- 63 files changed, 3504 insertions(+), 552 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ApiCallData.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentation.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ClientInstrumentationListener.java create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Coverage.java 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 fe06d0f1b..d6377c8a4 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestContextImpl.java @@ -53,18 +53,23 @@ public class APIRequestContextImpl extends ChannelOwner implements APIRequestCon 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.protocolGson().fromJson(initializer, APIRequestContextInitializer.class).tracing; this.timeoutSettings = new TimeoutSettings(); } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + @Override public void dispose(DisposeOptions options) { if (options == null) { options = new DisposeOptions(); } closeReason = options.reason; + instrumentation.runBeforeCloseRequestContext(this); tracing.exportAllHars(); try { APIRequestContextDisposeParams params = new APIRequestContextDisposeParams(); @@ -155,16 +160,17 @@ public APIResponse put(String url, RequestOptions options) { // java: the string | Request parameter is two overloads. @Override public APIResponse fetch(String urlOrRequest, RequestOptions options) { - return wrapApiCall(() -> innerFetch(urlOrRequest, null, (RequestOptionsImpl) options), null, false); + return wrapApiCall(() -> innerFetch(urlOrRequest, null, (RequestOptionsImpl) options, null), null, false); } @Override public APIResponse fetch(Request urlOrRequest, RequestOptions options) { - return wrapApiCall(() -> innerFetch(null, urlOrRequest, (RequestOptionsImpl) options), null, false); + return wrapApiCall(() -> innerFetch(null, urlOrRequest, (RequestOptionsImpl) options, null), null, false); } - // java: upstream takes one object { url, request, ...options }. - APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl options) { + // 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(); } @@ -187,7 +193,11 @@ APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl optio url = request.url(); } String method = options.method != null ? options.method : (request != null ? request.method() : null); - // java: RequestOptions has no string or URLSearchParams form of params, so there are no encodedParams. + 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; @@ -198,7 +208,7 @@ APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl optio if (options.data != null) { if (options.data instanceof String) { String data = (String) options.data; - if (isJsonContentType(headers)) { + if (APIResponseImpl.isJsonContentType(headers)) { jsonData = isJsonParsable(data) ? data : jsonDataSerializer.toJson(data); } else { postDataBuffer = data.getBytes(StandardCharsets.UTF_8); @@ -206,7 +216,7 @@ APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl optio } else if (options.data instanceof byte[]) { postDataBuffer = (byte[]) options.data; } else { - // java: any other object is serialized with Gson, there is no 'Unexpected data type' case. + // 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) { @@ -228,9 +238,11 @@ APIResponseImpl innerFetch(String url, Request request, RequestOptionsImpl optio 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 = objectToArray(options.params); + params.params = APIResponseImpl.objectToArray(options.params); + params.encodedParams = encodedParams; params.method = method; params.headers = headers; params.postData = postDataBuffer; @@ -267,12 +279,16 @@ public String storageState(StorageStateOptions options) { static FormField toFormField(String name, Object value) { FormField field = new FormField(); field.name = name; - if (value instanceof FilePayload) { - field.file = filePayloadToJson((FilePayload) value); - } else if (value instanceof Path) { - field.file = readStreamToJson((Path) value); - } else { + 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 field; } @@ -296,47 +312,7 @@ static boolean isJsonParsable(String value) { } } - 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 e : map.entrySet()) { - if (e.getValue() != null) { - result.add(nameValue(e.getKey(), String.valueOf(e.getValue()))); - } - } - return result; - } + // 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 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 c99808c68..004dcc0f7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIRequestImpl.java @@ -45,6 +45,7 @@ class APIRequestImpl implements APIRequest { @Override public APIRequestContextImpl newContext(NewContextOptions 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) { @@ -68,14 +69,16 @@ public APIRequestContextImpl newContext(NewContextOptions options) { PlaywrightNewRequestParams params = Utils.toProtocol(options, PlaywrightNewRequestParams.class); params.extraHTTPHeaders = extraHTTPHeaders != null ? Headers.headersObjectToArray(extraHTTPHeaders) : null; params.storageState = storageState; - // java: no _defaultLaunchOptions in the Java API, so no tracesDir here and none for context.tracing below. + // 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; contexts.add(context); context.request = this; - // java: no _defaultContextTimeout in the Java API. - context.timeoutSettings.setDefaultTimeout(options.timeout); + 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 18347b9ee..bc6f0086b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java @@ -17,19 +17,25 @@ // Port of fetch.ts. package com.microsoft.playwright.impl; +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.List; import java.util.Map; import java.util.function.Supplier; @@ -41,11 +47,14 @@ class APIResponseImpl implements APIResponse { private final com.microsoft.playwright.impl.protocol.APIResponse initializer; private final RawHeaders headers; final APIRequestContextImpl request; + String apiName = "APIResponse"; 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) { @@ -163,7 +172,13 @@ public String text() { return new String(content, StandardCharsets.UTF_8); } - // java: json() is not in the Java API. + // java: the parsed JSON is a JsonElement. + JsonElement json() { + String content = text(); + return RequestImpl.parseJSON(content); + } + + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. @Override public void dispose() { @@ -172,6 +187,8 @@ public void dispose() { request.channel.disposeAPIResponse(params, NO_TIMEOUT); } + // java: _inspect is not ported, Node.js inspection has no Java counterpart. + String fetchUid() { return initializer.fetchUid; } @@ -181,4 +198,54 @@ List fetchLog() { params.fetchUid = fetchUid(); 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 44ec7ec50..a073a73ff 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java @@ -32,6 +32,8 @@ 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); } @@ -64,8 +66,8 @@ public InputStream createReadStream() { return channel.stream(NO_TIMEOUT).stream.stream(); } - // java: upstream readIntoBuffer collects the 'data' chunks of the 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; @@ -86,4 +88,9 @@ public void cancel() { public void delete() { channel.delete(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 74352c290..ee4481027 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BindingCall.java @@ -35,6 +35,8 @@ public class BindingCall extends ChannelOwner { // 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); 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 a6fdf1a12..d57fb9559 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -70,11 +70,24 @@ import java.util.regex.Pattern; 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 { + // 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<>(); @@ -83,6 +96,7 @@ public class BrowserContextImpl extends ChannelOwner implements BrowserContext { final Map bindings = new LinkedHashMap<>(); final TimeoutSettings timeoutSettings; PageImpl ownerPage; + boolean forReuse = false; private final WaitableEvent closedPromise; final BrowserContextInitializer.BrowserContextInitializerOptions options; @@ -96,9 +110,12 @@ public class BrowserContextImpl extends ChannelOwner implements BrowserContext { private String closingStatus = "none"; private String closeReason; 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); BrowserContextInitializer contextInitializer = connection.protocolGson().fromJson(initializer, BrowserContextInitializer.class); @@ -154,7 +171,7 @@ void handleEvent(String event, JsonObject params) { case "serviceWorker": { BrowserContextServiceWorkerEvent e = connection.protocolGson().fromJson(params, BrowserContextServiceWorkerEvent.class); WorkerImpl serviceWorker = e.worker; - // java: no service worker API, so the worker has no _context to set. + serviceWorker.context = this; serviceWorkers.add(serviceWorker); emit(Events.BrowserContext.SERVICE_WORKER, serviceWorker); break; @@ -254,7 +271,23 @@ void handleEvent(String event, JsonObject params) { onResponse(e.response, e.page); break; } - // java: no recorder API, the recorderEvent event is not handled. + 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; + } } } @@ -293,7 +326,7 @@ private void onResponse(ResponseImpl response, PageImpl page) { } private void onRequestFailed(RequestImpl request, Double responseEndTiming, String failureText, PageImpl page) { - request.failureText = failureText; + request.failureText = failureText == null || failureText.isEmpty() ? null : failureText; request.setResponseEndTiming(responseEndTiming); emit(Events.BrowserContext.REQUEST_FAILED, request); if (page != null) { @@ -496,20 +529,29 @@ public void setOffline(boolean offline) { channel.setOffline(params, NO_TIMEOUT); } - // java: setHTTPCredentials has no Java API. + // 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 AutoCloseable addInitScript(String script) { - return addInitScriptImpl(script); + return addInitScript(script, null, null); } @Override public AutoCloseable addInitScript(Path script) { - return addInitScriptImpl(script); + return addInitScript(script, null, null); } - // java: the core of the String and Path overloads; the exposeFunctions option and arg have no Java API. - private AutoCloseable addInitScriptImpl(Object script) { + // 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; @@ -525,7 +567,15 @@ public AutoCloseable exposeBinding(String name, BindingCallback callback) { return result.disposable; } - // java: _exposeCallbackBinding serves the exposeFunctions option of addInitScript, which has no Java API. + // 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 AutoCloseable exposeFunction(String name, FunctionCallback callback) { @@ -607,10 +657,11 @@ private void disposeHarRouters() { harRouters = new ArrayList<>(); } + // java: the Java API has no behavior option, unrouteAll() passes none. @Override public void unrouteAll() { withTitle("Unroute requests", () -> { - unrouteInternal(routes, new ArrayList<>()); + unrouteInternal(routes, new ArrayList<>(), null); disposeHarRouters(); }); } @@ -641,13 +692,18 @@ void unroute(UrlMatcher url, Consumer handler) { remaining.add(route); } } - unrouteInternal(removed, remaining); + unrouteInternal(removed, remaining, "default"); }); } - // java: unrouteAll() has no behavior option, so the removed handlers are never stopped. - private void unrouteInternal(List removed, List remaining) { + 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(); } @@ -720,8 +776,11 @@ public List backgroundPages() { return Collections.emptyList(); } - // java: serviceWorkers() has no Java API. + 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(); @@ -749,6 +808,8 @@ void onClose() { emit(Events.BrowserContext.CLOSE, this); } + // java: Symbol.asyncDispose is not ported. + @Override public void close(CloseOptions options) { if (options == null) { @@ -760,6 +821,7 @@ public void close(CloseOptions options) { closeReason = options.reason; closingStatus = "closing"; request.dispose(convertType(options, APIRequestContext.DisposeOptions.class)); + instrumentation.runBeforeCloseBrowserContext(this); RuntimeException harError = null; try { tracing.exportAllHars(); @@ -773,7 +835,26 @@ public void close(CloseOptions options) { } } - // java: showRecorder, startRecording, stopRecording and exposeConsoleApi have no Java API. + void showRecorder(BrowserContextShowRecorderParams params) { + channel.showRecorder(params, NO_TIMEOUT); + } + + void startRecording(BrowserContextStartRecordingParams params, RecorderEventSink eventSink) { + onRecorderEventSink = eventSink; + channel.startRecording(params, NO_TIMEOUT); + } + + void stopRecording() { + try { + channel.stopRecording(NO_TIMEOUT); + } finally { + onRecorderEventSink = null; + } + } + + void exposeConsoleApi() { + channel.exposeConsoleApi(NO_TIMEOUT); + } // java: upstream reads a path given as a string and passes an object through; Java options hold a Path. static JsonElement prepareStorageState(Path storageState) { 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 841436e27..e7115e833 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -44,7 +44,7 @@ public class BrowserImpl extends ChannelOwner implements Browser { final Set contexts = new LinkedHashSet<>(); private boolean isConnected = true; - // java: no _closedPromise, close() waits until isConnected turns false, which happens when Disconnected is emitted. + private final WaitableResult closedPromise; boolean shouldCloseConnectionOnClose = false; BrowserTypeImpl browserType; private BrowserType.LaunchOptions options = new BrowserType.LaunchOptions(); @@ -55,11 +55,22 @@ public class BrowserImpl extends ChannelOwner implements Browser { 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 @@ -81,31 +92,66 @@ public BrowserType browserType() { @Override public BrowserContextImpl newContext(NewContextOptions options) { - return innerNewContext(options); + return innerNewContext(options, false); + } + + BrowserContextImpl newContextForReuse(NewContextOptions options) { + return innerNewContext(options, true); + } + + void disconnectFromReusedContext(String reason) { + BrowserContextImpl context = null; + for (BrowserContextImpl c : contexts) { + if (c.forReuse) { + context = c; + break; + } + } + if (context == null) { + return; + } + 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); } - // java: no forReuse parameter, newContextForReuse is not in the Java API. - BrowserContextImpl innerNewContext(NewContextOptions userOptions) { + BrowserContextImpl innerNewContext(NewContextOptions userOptions, boolean forReuse) { if (userOptions == null) { userOptions = new NewContextOptions(); } - BrowserNewContextParams contextOptions = BrowserContextImpl.prepareBrowserContextParams(userOptions); - // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params. + // 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; - BrowserContextImpl context = channel.newContext(contextOptions, NO_TIMEOUT).context; + // 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(userOptions); + context.initializeHarFromOptions(options); + instrumentation.runAfterCreateBrowserContext(context); return context; } - // java: no logger parameter, the Java API has no logger option. - void connectToBrowserType(BrowserTypeImpl browserType, BrowserType.LaunchOptions browserOptions) { + // 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); } @@ -123,11 +169,15 @@ private void didCreateContext(BrowserContextImpl 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: no _defaultContextTimeout and _defaultContextNavigationTimeout, the test runner sets them upstream. + // 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 @@ -201,6 +251,8 @@ public byte[] stopTracing() { return buffer; } + // java: Symbol.asyncDispose is not ported. + @Override public void close(CloseOptions options) { if (options == null) { @@ -214,7 +266,7 @@ public void close(CloseOptions options) { } else { channel.close(toProtocol(options, BrowserCloseParams.class), NO_TIMEOUT); } - runUntil(() -> {}, new WaitablePredicate(() -> !isConnected)); + 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)) { 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 bcca06a57..5cb55bcc6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -25,6 +25,7 @@ import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.impl.protocol.*; +import java.lang.reflect.Field; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -35,6 +36,24 @@ import static com.microsoft.playwright.impl.Utils.toProtocol; public class BrowserTypeImpl extends ChannelOwner implements BrowserType { + // 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; @@ -44,6 +63,8 @@ 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"); @@ -60,27 +81,48 @@ public String name() { @Override public BrowserImpl launch(LaunchOptions options) { - LaunchOptions launchOptions = options == null ? new LaunchOptions() : options; + LaunchOptions userOptions = options == null ? new LaunchOptions() : options; return wrapApiCall(() -> { - // java: no userDataDir and port options to reject, and no _defaultLaunchOptions of the test runner. - // ignoreDefaultArgs and ignoreAllDefaultArgs are separate options and env is serialized as a name/value array. + // 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); + browser.connectToBrowserType(this, launchOptions, logger); return browser; }, null, false); } + BrowserServer launchServer(LaunchOptions options) { + if (options == null) { + options = new LaunchOptions(); + } + if (serverLauncher == null) { + throw new PlaywrightException("Launching server is not supported"); + } + options = withDefaults(playwright.defaultLaunchOptions, options, LaunchOptions.class); + return serverLauncher.launchServer(options); + } + @Override public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersistentContextOptions options) { - LaunchPersistentContextOptions persistentOptions = options == null ? new 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); - // java: _withSelectorOptions, the Java options have no selector fields, so they are set on the params. contextParams.selectorEngines = new ArrayList<>(playwright.selectors.selectorEngines); contextParams.testIdAttributeName = playwright.selectors.testIdAttributeName; Gson gson = connection.protocolGson(); @@ -92,26 +134,33 @@ public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersis 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); + 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); } + // 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; - // java: _connect is inlined, its Java name would be this method's. - return wrapApiCall(() -> { - BrowserImpl browser = Connect.connectToBrowser(playwright, name(), endpoint, params); - browser.connectToBrowserType(this, new LaunchOptions()); - return browser; - }, null, false); + return wrapApiCall(() -> connectImpl(endpoint, params), null, false); + } + + // 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. + // 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 BrowserImpl connectOverCDP(String endpointURL, ConnectOverCDPOptions options) { if (options == null) { @@ -129,8 +178,47 @@ public BrowserImpl connectOverCDP(String endpointURL, ConnectOverCDPOptions opti private BrowserImpl browserFromConnectResult(BrowserTypeConnectOverCDPResult result) { BrowserImpl browser = result.browser; - browser.connectToBrowserType(this, new LaunchOptions()); - // java: no instrumentation to notify about result.defaultContext. + browser.connectToBrowserType(this, new LaunchOptions(), null); + if (result.defaultContext != null) { + instrumentation.runAfterCreateBrowserContext(result.defaultContext); + } return browser; } + + // 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; + } + + // 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; + } + 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); + } + } + } catch (IllegalAccessException e) { + throw new PlaywrightException("Internal error", e); + } + 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 ddd208de5..b3591b664 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -28,6 +28,8 @@ 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); } @@ -63,6 +65,7 @@ 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(); 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 4846d599a..a5c944ed9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -17,31 +17,33 @@ // 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 @@ -118,7 +136,16 @@ void adopt(ChannelOwner child) { child.parent = this; } - // java: no _parentOfType, the exposeFunctions option it serves has no Java API. + ChannelOwner parentOfType(String type) { + ChannelOwner parent = this.parent; + while (parent != null) { + if (parent.type.equals(type)) { + return parent; + } + parent = parent.parent; + } + return null; + } void dispose(String reason) { // Clean up from parent and connection. @@ -135,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. @@ -159,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(() -> { @@ -195,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. */ @@ -220,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) { @@ -234,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)); } /** @@ -277,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) { } @@ -289,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 index 61e0c00db..725f6336a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClientHelper.java @@ -17,19 +17,58 @@ // 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; -// java: no envObjectToArray, the env map is serialized as a name/value array by Serialization; no -// initScriptSourceWithExposedFunctions, there is no exposeFunctions option. class ClientHelper { - // java: fun is a script String or a file Path; the Java API has no function, { content } or arg. - static String evaluationScript(Object fun, boolean addSourceUrl) { + 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) { @@ -47,7 +86,152 @@ static String evaluationScript(Object fun, boolean addSourceUrl) { 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 0c3c90548..8d350c62a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ClockImpl.java @@ -17,13 +17,17 @@ // 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; @@ -31,56 +35,47 @@ class ClockImpl implements Clock { this.browserContext = browserContext; } - // java: parseTime/parseTicks are inlined into the typed overloads (long, String, Date) of the generated Clock interface. - @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 fastForward(long ticks) { - BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); - params.ticksNumber = (double) ticks; - browserContext.channel.clockFastForward(params, NO_TIMEOUT); + fastForward((Object) ticks); } @Override public void fastForward(String ticks) { - BrowserContextClockFastForwardParams params = new BrowserContextClockFastForwardParams(); - params.ticksString = 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); } @@ -91,57 +86,83 @@ public void resume() { @Override public void runFor(long ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); - params.ticksNumber = (double) ticks; - browserContext.channel.clockRunFor(params, NO_TIMEOUT); + runFor((Object) ticks); } @Override public void runFor(String ticks) { - BrowserContextClockRunForParams params = new BrowserContextClockRunForParams(); - params.ticksString = 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 index 8780feaa9..e979d43ec 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connect.java @@ -79,6 +79,14 @@ static BrowserImpl connectToBrowser(PlaywrightImpl playwright, String browserNam // 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) { @@ -102,10 +110,10 @@ static BrowserImpl connectToBrowser(PlaywrightImpl playwright, String browserNam // 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. The headers - // of the connect result are not used by the Java Connection. + // 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); + 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()). @@ -119,6 +127,21 @@ static Connection connectToEndpoint(Connection parentConnection, LocalUtilsConne 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); 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 df57afc4e..8783b790d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -37,6 +37,7 @@ 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; @@ -93,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()) @@ -127,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() { @@ -206,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; } @@ -222,27 +257,16 @@ PlaywrightImpl initializePlaywright(double deadline, double 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--; } } @@ -261,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); @@ -296,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(); @@ -306,51 +334,15 @@ WaitableResult sendMessageToServer(ChannelOwner object, String meth // 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; } @@ -361,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; } @@ -384,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; @@ -401,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); } @@ -418,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() { @@ -483,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() { @@ -509,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 43b5bbc1a..cc0aa6a0e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ConsoleMessageImpl.java @@ -36,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, @@ -57,6 +63,7 @@ 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 @@ -94,4 +101,15 @@ public String location() { 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/DebuggerImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java index 11b87b11d..57c592b84 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DebuggerImpl.java @@ -23,19 +23,21 @@ 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 DebuggerPausedDetails pausedDetails; - // java: handlers of onPausedStateChanged(Runnable); upstream emits Events.Debugger.PausedStateChanged. apiCallsUpdated has no Java API. - private final List pausedStateChangedHandlers = new ArrayList<>(); 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); } @@ -43,19 +45,27 @@ public class DebuggerImpl extends ChannelOwner implements Debugger { // 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; } } } - // java: _enable has no Java API. + void enable() { + channel.enable(NO_TIMEOUT); + } @Override public void requestPause() { @@ -84,13 +94,23 @@ 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) { - pausedStateChangedHandlers.add(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) { - pausedStateChangedHandlers.remove(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 55261e3b5..3b4d1ab54 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DialogImpl.java @@ -23,6 +23,8 @@ 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) { 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 fac81998c..56f760e5b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/DownloadImpl.java @@ -24,16 +24,17 @@ import java.io.InputStream; import java.nio.file.Path; -// java: url and suggestedFilename are read from the initializer. 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 @@ -43,12 +44,12 @@ public Page page() { @Override public String url() { - return initializer.get("url").getAsString(); + return url; } @Override public String suggestedFilename() { - return initializer.get("suggestedFilename").getAsString(); + return suggestedFilename; } @Override @@ -80,4 +81,9 @@ public void cancel() { 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 025558135..45a750ab3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ElementHandleImpl.java @@ -53,6 +53,8 @@ public class ElementHandleImpl extends JSHandleImpl implements ElementHandle { FrameImpl frame; final ElementHandleChannel elementChannel = 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; 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 24be2a27f..9b50ebe2b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -21,19 +21,47 @@ 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 9dea5fdfb..3d700b459 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java @@ -20,66 +20,286 @@ 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); } - int listenerCount(String type) { - List> list = events.get(type); - return list == null ? 0 : list.size(); + void removeAllListeners() { + removeAllListeners(null); + } + + void removeAllListeners(String type) { + removeAllListenersImpl(type); + } + + // 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 89dc5d624..37ab4478a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Events.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java @@ -21,6 +21,20 @@ 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"; @@ -44,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"; @@ -53,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"; @@ -63,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"; @@ -89,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 2d3e353ad..f5db22841 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FileChooserImpl.java @@ -28,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 @@ -60,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 @@ -70,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/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index f73374f6b..afbeca621 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -39,7 +39,9 @@ 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.*; public class FrameImpl extends ChannelOwner implements Frame { @@ -55,10 +57,13 @@ public class FrameImpl extends ChannelOwner implements Frame { 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); 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) { @@ -92,7 +97,11 @@ void handleEvent(String event, JsonObject params) { FrameNavigatedEvent navigatedEvent = connection.protocolGson().fromJson(params, FrameNavigatedEvent.class); url = navigatedEvent.url; name = navigatedEvent.name; - // java: no exposeFunctions option of evaluate(), so no _eraseEvaluateCallbacks(). + // 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); @@ -262,14 +271,38 @@ public ElementHandleImpl frameElement() { @Override 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 = serializeArgument(arg); + 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); + } + + // 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); @@ -288,6 +321,7 @@ public ElementHandleImpl waitForSelector(String selector, WaitForSelectorOptions if (options == null) { options = new WaitForSelectorOptions(); } + // java: the visibility and waitFor checks are not ported, WaitForSelectorOptions has no such fields. FrameWaitForSelectorParams params = toProtocol(options, FrameWaitForSelectorParams.class); params.selector = selector; return channel.waitForSelector(params, timeout(options.timeout)).element; @@ -305,6 +339,7 @@ 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 evalOnSelector(String selector, String expression, Object arg, EvalOnSelectorOptions options) { FrameEvalOnSelectorParams params = toProtocol(options, FrameEvalOnSelectorParams.class); @@ -314,6 +349,7 @@ public Object evalOnSelector(String selector, String expression, Object arg, Eva 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 Object evalOnSelectorAll(String selector, String expression, Object arg) { FrameEvalOnSelectorAllParams params = new FrameEvalOnSelectorAllParams(); @@ -515,12 +551,12 @@ public LocatorImpl locator(String selector, LocatorOptions options) { // java: testIdAttributeName() of locator.ts is a field of SelectorsImpl of the Playwright instance. @Override public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(LocatorImpl.testIdAttributeName(connection.playwright.selectors), testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(LocatorImpl.testIdAttributeName(connection.playwright.selectors), testId)); } @Override 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 403ec4bb1..5f8f057e8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameLocatorImpl.java @@ -25,6 +25,7 @@ import java.util.regex.Pattern; 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 { @@ -54,15 +55,14 @@ public Locator locator(Locator selectorOrLocator, LocatorOptions options) { return new LocatorImpl(frame, childSelector(((LocatorImpl) selectorOrLocator).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(frame.connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java index 5b837bd32..194822126 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/HarRouter.java @@ -154,6 +154,8 @@ void addPageRoute(Page page) { } } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + void dispose() { LocalUtilsHarCloseParams params = new LocalUtilsHarCloseParams(); params.harId = harId; 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 9b6eda438..a7634af9c 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JSHandleImpl.java @@ -25,16 +25,20 @@ import java.util.LinkedHashMap; import java.util.Map; +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: serializeArgument and parseResult are Serialization.serializeArgument and Serialization.deserialize; -// Java has no evaluate options, so EvaluateOptions, serializeArgumentWithCallbacks and the argument assertions are not ported. +// 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); + // java: no from, generated results already hold the JSHandleImpl. + JSHandleImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); this.preview = connection.protocolGson().fromJson(initializer, JSHandleInitializer.class).preview; @@ -50,20 +54,33 @@ protected void handleEvent(String event, JsonObject params) { @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; // java: functions are passed as strings, so isFunction is not sent and the server detects it. - params.arg = serializeArgument(arg); + params.arg = serializedArg; JSHandleEvaluateExpressionResult result = channel.evaluateExpression(params, NO_TIMEOUT); return deserialize(result.value); } @Override public JSHandle evaluateHandle(String pageFunction, Object arg) { + return evaluateHandle(pageFunction, arg, null); + } + + 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 = serializeArgument(arg); + params.arg = serializedArg; JSHandleEvaluateExpressionHandleResult result = channel.evaluateExpressionHandle(params, NO_TIMEOUT); return result.handle; } @@ -95,6 +112,8 @@ public ElementHandle asElement() { return null; } + // java: no [Symbol.asyncDispose]. + @Override public void dispose() { try { 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 5c828edd6..0986fc05a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -31,12 +31,19 @@ public class JsonPipe extends ChannelOwner implements Transport { 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; its connect is in Connect.connectToEndpoint. + // 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"; 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 39206917c..87be2ac77 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocalUtils.java @@ -22,18 +22,24 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.util.LinkedHashMap; +import java.util.Map; import java.util.regex.Pattern; +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); - } - - // java: devices stay the raw initializer array, DeviceDescriptor is not a Java type. - JsonArray deviceDescriptors() { - return initializer.getAsJsonArray("deviceDescriptors"); + LocalUtilsInitializer init = connection.protocolGson().fromJson(initializer, LocalUtilsInitializer.class); + this.devices = new LinkedHashMap<>(); + for (LocalUtilsInitializerDeviceDescriptors device : init.deviceDescriptors) + this.devices.put(device.name, device.descriptor); } void zip(LocalUtilsZipParams params) { @@ -73,7 +79,13 @@ WaitableResult addStackToTracingNoReply(JsonObject params) { return connection.sendMessageToServer(this, "addStackToTracingNoReply", params, options); } - // java: no counterpart upstream, the Java API matches globs on the driver. + // 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 bfa534920..0bfca68f2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LocatorImpl.java @@ -17,6 +17,7 @@ // Port of locator.ts. package com.microsoft.playwright.impl; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.*; import com.microsoft.playwright.impl.protocol.*; @@ -26,6 +27,7 @@ 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; @@ -42,6 +44,7 @@ class LocatorImpl implements Locator { final FrameImpl frame; 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. @@ -79,12 +82,15 @@ private LocatorImpl(FrameImpl frame, String selector, FilterOptions options) { if (options != null && options.visible != null) this.selector += " >> visible=" + (options.visible ? "true" : "false"); + + // java: no inspect.custom. } R wrapApiCall(Supplier func, String title, boolean internal) { return frame.wrapApiCall(func, title, internal); } + // 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; @@ -104,13 +110,16 @@ private R withElement(BiFunction task, Double time } } - // java: upstream _equals(), used by page.ts; equals() so that Java collections and assertEquals agree. + 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 boolean equals(Object obj) { if (!(obj instanceof LocatorImpl)) return false; - LocatorImpl locator = (LocatorImpl) obj; - return frame == locator.frame && selector.equals(locator.selector); + return equals((LocatorImpl) obj); } @Override @@ -174,6 +183,7 @@ public void drop(DropPayload payload, DropOptions options) { 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 frame.withTitle("Evaluate", () -> withElement((h, timeout) -> h.evaluate(expression, arg), options == null ? null : options.timeout)); @@ -184,6 +194,7 @@ 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 frame.withTitle("Evaluate", () -> withElement((h, timeout) -> h.evaluateHandle(expression, arg), options == null ? null : options.timeout)); @@ -201,12 +212,19 @@ public void clear(ClearOptions options) { frame.withTitle("Clear", () -> fill("", convertType(options, FillOptions.class))); } - // java: HighlightOptions.style is a string only, cssObjectToString() is not needed. + // 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 AutoCloseable highlight(HighlightOptions options) { if (options == null) options = new HighlightOptions(); - frame.highlight(selector, options.style); + String style = options.style; + frame.highlight(selector, style); return new DisposableStub(this::hideHighlight); } @@ -232,15 +250,14 @@ public Locator within(Locator locator) { return locator.locator(this); } - // java: testIdAttributeName() of locator.ts is a field of SelectorsImpl of the Playwright instance. @Override public Locator getByTestId(String testId) { - return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override public Locator getByTestId(Pattern testId) { - return locator(getByTestIdSelector(frame.connection.playwright.selectors.testIdAttributeName, testId)); + return locator(getByTestIdSelector(testIdAttributeName(frame.connection.playwright.selectors), testId)); } @Override @@ -518,6 +535,16 @@ public String ariaSnapshot(AriaSnapshotOptions options) { 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) { ScrollIntoViewIfNeededOptions scrollOptions = options == null ? new ScrollIntoViewIfNeededOptions() : options; @@ -680,6 +707,8 @@ FrameExpectResult expect(String expression, FrameExpectOptions options, String t 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 @@ -692,6 +721,38 @@ public String toString() { return "Locator@" + selector; } + // 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); + } + return String.join("; ", entries); + } + // java: helpers and members with no upstream counterpart. private String stringRepresentation; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java index 2274894d1..e5055b024 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/LongStandingScope.java @@ -20,68 +20,130 @@ 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: only the LongStandingScope class, and only the members the client uses (no reject, raceMultiple or the -// safeRace default value). There are no terminate promises to resolve: a race is a Waitable that is done once -// the scope is closed, and the owner pumps the connection while it waits. +// 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; - private boolean isClosed; + // 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(promise, false); + return race(Collections.singletonList(promise)); + } + + T race(List> promise) { + return await(race(promise, false, null)); } T safeRace(Waitable promise) { - return race(promise, true); + return safeRace(promise, null); } - private T race(Waitable promise, boolean safe) { - Waitable terminatePromise = terminatePromise(safe); - List> promises = new ArrayList<>(); - // java: the promise goes first, a settled promise wins over a closed scope as its reaction runs first upstream. - promises.add(promise); - promises.add(terminatePromise); - return owner.runUntil(() -> {}, new WaitableRace<>(promises)); + T safeRace(Waitable promise, T defaultValue) { + return await(race(Collections.singletonList(promise), true, defaultValue)); } - // java: terminatePromise of _race, also raced by PageImpl.createWaitForCloseHelper(); a safe one returns null. - Waitable terminatePromise(boolean safe) { - return new Waitable() { + 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 isClosed; + return terminatePromise.isDone(); } @Override public T get() { if (safe) - return null; - throw cloneError(closeError); + 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: a new exception of the same type, so that the stack trace points at the caller of the race. - private static PlaywrightException cloneError(PlaywrightException error) { - if (error instanceof TargetClosedError) - return new TargetClosedError(error.getMessage()); - return new PlaywrightException(error.getMessage()); + // 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 35955dfa6..5bf7ee8f1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/MouseImpl.java @@ -20,6 +20,8 @@ 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; @@ -31,6 +33,10 @@ class MouseImpl implements Mouse { this.page = page; } + R wrapApiCall(Supplier func, String title, boolean internal) { + return page.wrapApiCall(func, title, internal); + } + @Override public void move(double x, double y, MoveOptions options) { PageMouseMoveParams params = toProtocol(options, PageMouseMoveParams.class); @@ -61,7 +67,8 @@ public void click(double x, double y, ClickOptions options) { @Override public void dblclick(double x, double y, DblclickOptions options) { - page.withTitle("Double click", () -> { + // java: @apiCall({ title: 'Double click' }) is wrapApiCall with the title. + wrapApiCall(() -> { ClickOptions clickOptions; if (options == null) { // java: options is nullable, upstream defaults it to {}. @@ -71,7 +78,8 @@ public void dblclick(double x, double y, DblclickOptions options) { } clickOptions.clickCount = 2; click(x, y, clickOptions); - }); + return null; + }, "Double click", false); } @Override 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 3faaa04d4..8f087424d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -18,6 +18,7 @@ package com.microsoft.playwright.impl; 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.*; @@ -36,7 +37,8 @@ import java.util.regex.Pattern; import static com.microsoft.playwright.impl.ClientHelper.evaluationScript; -import static com.microsoft.playwright.impl.Serialization.gson; +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; @@ -46,6 +48,7 @@ public class PageImpl extends ChannelOwner implements Page { final PageChannel channel = new PageChannel(this); private final BrowserContextImpl browserContext; BrowserContextImpl ownedContext; + String apiName = "Page"; private final FrameImpl mainFrame; private final Set frames = new LinkedHashSet<>(); @@ -56,6 +59,7 @@ public class PageImpl extends ChannelOwner implements Page { List routes = new ArrayList<>(); List webSocketRoutes = new ArrayList<>(); + final Coverage coverage; final KeyboardImpl keyboard; final MouseImpl mouse; final APIRequestContextImpl request; @@ -75,9 +79,13 @@ public class PageImpl extends ChannelOwner implements Page { private List harRouters = new ArrayList<>(); private final Map locatorHandlers = new LinkedHashMap<>(); + private List evaluateCallbacks = new ArrayList<>(); + + // java: from and fromNullable are not ported, generated results already hold the impl object. 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); @@ -102,6 +110,8 @@ public class PageImpl extends ChannelOwner implements Page { video = new VideoImpl(this, pageInitializer.video); screencast = new ScreencastImpl(this); + coverage = new Coverage(channel); + on(Events.Page.CLOSE, new Consumer() { @Override public void accept(Page page) { @@ -412,14 +422,22 @@ public void dispatchEvent(String selector, String type, Object eventInit, Dispat @Override public JSHandle evaluateHandle(String expression, Object arg) { - return mainFrame.evaluateHandle(expression, 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 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 Object evalOnSelectorAll(String selector, String expression, Object arg) { return mainFrame.evalOnSelectorAll(selector, expression, arg); @@ -459,8 +477,32 @@ public AutoCloseable exposeBinding(String name, BindingCallback callback) { return result.disposable; } - // java: no exposeFunctions option for evaluate() or addInitScript(), so there is no _exposeCallbackBinding, - // _exposeEvaluateCallback or _eraseEvaluateCallbacks. + // 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 setExtraHTTPHeaders(Map headers) { @@ -600,8 +642,9 @@ public Request waitForRequest(Predicate urlOrPredicate, WaitForRequestO return waitForRequest(null, urlOrPredicate, null, options, callback); } - // java: the url matcher or the predicate of urlOrPredicate, with trimUrl(urlOrPredicate) computed by the overload. - // No @apiCall() zone around the waits: the callback runs inside the wait and its calls would join that zone. + // 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(); @@ -788,22 +831,33 @@ public ViewportSize viewportSize() { @Override public Object evaluate(String expression, Object arg) { - return mainFrame.evaluate(expression, arg); + return evaluate(expression, arg, null); } - // java: the script is a string or a file; there is no function to serialize and no exposeFunctions option. + // 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 addInitScriptImpl(script); + return addInitScript(script, null, null); } @Override public AutoCloseable addInitScript(Path script) { - return addInitScriptImpl(script); + return addInitScript(script, null, null); } - // java: the core of the String and Path overloads; the exposeFunctions option and arg have no Java API. - private AutoCloseable addInitScriptImpl(Object script) { + // 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; @@ -881,11 +935,11 @@ private void disposeHarRouters() { harRouters = new ArrayList<>(); } - // java: the Java API has no behavior option, unrouteAll() is behavior 'default'. + // java: the Java API has no behavior option, unrouteAll() passes none. @Override public void unrouteAll() { withTitle("Unroute requests", () -> { - unrouteInternal(routes, new ArrayList<>()); + unrouteInternal(routes, new ArrayList<>(), null); disposeHarRouters(); }); } @@ -916,13 +970,18 @@ private void unroute(UrlMatcher url, Consumer handler) { remaining.add(route); } } - unrouteInternal(removed, remaining); + unrouteInternal(removed, remaining, "default"); }); } - // java: no behavior parameter, the 'wait' and 'ignoreErrors' branches that stop the removed handlers are unreachable. - private void unrouteInternal(List removed, List remaining) { + 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(); } @@ -971,6 +1030,69 @@ public byte[] screenshot(ScreenshotOptions options) { 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 String title() { return mainFrame.title(); @@ -981,6 +1103,8 @@ public void bringToFront() { channel.bringToFront(NO_TIMEOUT); } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + @Override public void close(CloseOptions options) { if (options == null) { @@ -1060,13 +1184,20 @@ public void clearPageErrors() { channel.clearPageErrors(NO_TIMEOUT); } - // java: the Java API returns the errors as strings, not as parsed Error objects; there is no filter option. @Override public List pageErrors() { - PagePageErrorsResult result = channel.pageErrors(new PagePageErrorsParams(), NO_TIMEOUT); + 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(gson().toJsonTree(error).getAsJsonObject())); + errors.add(Serialization.parseError(connection.protocolGson().toJsonTree(error).getAsJsonObject())); } return errors; } @@ -1312,26 +1443,52 @@ public List workers() { return new ArrayList<>(workers); } - // java: there is no JS debugger to detect and no instrumentation to notify. @Override public void pause() { + pause(false); + } + + // 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); } - // java: width, height and the margins are strings in the Java API, there is nothing to convert to px. @Override public byte[] pdf(PdfOptions options) { if (options == null) { options = new PdfOptions(); } + // 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"; + } + 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); @@ -1345,12 +1502,34 @@ public String ariaSnapshot(AriaSnapshotOptions options) { 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; } + // 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; + } + + void setDockTile(byte[] image) { + PageSetDockTileParams params = new PageSetDockTileParams(); + params.image = image; + channel.setDockTile(params, NO_TIMEOUT); + } + + // java: class BindingCall is in BindingCall.java. + private static String trimUrl(Object param) { if (param instanceof Pattern) { Pattern pattern = (Pattern) param; @@ -1362,6 +1541,45 @@ private static String trimUrl(Object param) { return null; } + // 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(); + }); + } + // java: the value object of _locatorHandlers. private static class LocatorHandler { final LocatorImpl locator; @@ -1375,6 +1593,51 @@ private static class LocatorHandler { } } + // java: the { name, disposable } entries of _evaluateCallbacks and of the callbacks of addInitScriptWithExposedFunctions. + static class ExposedCallback { + final String name; + final DisposableObject disposable; + + 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 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 2ec8d89c9..8b11c7a1e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -19,26 +19,39 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import com.microsoft.playwright.BrowserType; +import com.microsoft.playwright.Page; import com.microsoft.playwright.Playwright; import com.microsoft.playwright.PlaywrightException; +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. + // 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: no devices field, deviceDescriptors() reads them from LocalUtils. + // 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: no errors field, TimeoutError is a public class. No _defaultLaunchOptions, _defaultContextTimeout and - // _defaultContextNavigationTimeout, the test runner sets them upstream. + // 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); @@ -52,10 +65,45 @@ public class PlaywrightImpl extends ChannelOwner implements Playwright { 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; } - // java: no _browserTypes, _preLaunchedBrowser, _allContexts and _allPages, they serve the test runner upstream. + 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; 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 ed7198a4a..9e8e4532b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RequestImpl.java @@ -17,7 +17,11 @@ // Port of network.ts. package com.microsoft.playwright.impl; +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; @@ -28,6 +32,10 @@ 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.List; import java.util.Map; @@ -35,6 +43,8 @@ import static com.microsoft.playwright.impl.Serialization.gson; public class RequestImpl extends ChannelOwner implements Request { + // java: toClearCookiesParams is Serialization.toClearCookiesParams, BrowserContextImpl calls it there. + // java: SerializedFallbackOverrides. static class SerializedFallbackOverrides { String url; @@ -64,6 +74,8 @@ static class FallbackOverrides { 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); requestInitializer = connection.protocolGson().fromJson(initializer, RequestInitializer.class); @@ -113,7 +125,36 @@ public byte[] postDataBuffer() { return requestInitializer.postData; } - // java: postDataJSON() is not in the Java API. + // 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); + } + } @Override public Map headers() { @@ -168,6 +209,9 @@ public ResponseImpl existingResponse() { @Override 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."); } FrameImpl frame = requestInitializer.frame; @@ -275,4 +319,27 @@ LongStandingScope targetClosedScope() { 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 b94ab8651..158bf93d9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ResponseImpl.java @@ -17,6 +17,7 @@ // Port of network.ts. package com.microsoft.playwright.impl; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.microsoft.playwright.Response; import com.microsoft.playwright.impl.protocol.RemoteAddr; @@ -41,6 +42,8 @@ public class ResponseImpl extends ChannelOwner implements Response { 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); responseInitializer = connection.protocolGson().fromJson(initializer, ResponseInitializer.class); @@ -124,7 +127,11 @@ public String text() { return new String(content, StandardCharsets.UTF_8); } - // java: json() is not in the Java API. + // java: the parsed JSON is a JsonElement. + JsonElement json() { + String content = text(); + return RequestImpl.parseJSON(content); + } @Override public RequestImpl request() { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java index eb13ab964..7e0d6e767 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteHandler.java @@ -36,6 +36,7 @@ class RouteHandler { 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 { @@ -83,7 +84,7 @@ boolean matches(String requestURL) { return url.test(requestURL); } - // java: there are no zones to restore. + // java: no _savedZone.run(), there are no zones. boolean handle(RouteImpl route) { return handleImpl(route); } 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 6ad251390..5d5556b87 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/RouteImpl.java @@ -48,6 +48,8 @@ public class RouteImpl extends ChannelOwner implements Route { final RouteChannel channel = new RouteChannel(this); private final RouteInitializer routeInitializer; + // java: from is not ported, generated results already hold the impl object. + RouteImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); routeInitializer = connection.protocolGson().fromJson(initializer, RouteInitializer.class); @@ -121,14 +123,19 @@ public APIResponse fetch(FetchOptions options) { requestOptions.maxRedirects = fetchOptions.maxRedirects; requestOptions.maxRetries = fetchOptions.maxRetries; requestOptions.timeout = fetchOptions.timeout; - return ((APIRequestContextImpl) context.request()).innerFetch(fetchOptions.url, request(), requestOptions); + return ((APIRequestContextImpl) context.request()).innerFetch(fetchOptions.url, request(), requestOptions, null); }, null, false); } @Override public void fulfill(FulfillOptions options) { + fulfill(options, null); + } + + // 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); + innerFulfill(options, json); }); } @@ -143,16 +150,23 @@ private void handleRoute(Runnable callback) { } } - private void innerFulfill(FulfillOptions options) { + private void innerFulfill(FulfillOptions options, JsonElement json) { if (options == null) { options = new FulfillOptions(); } String fetchResponseUid = null; Integer statusOption = options.status; Map headersOption = options.headers; - // java: body is a String (body) or a byte[] (bodyBytes); there is no json option. + // 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 instanceof APIResponseImpl) { APIResponseImpl response = (APIResponseImpl) options.response; if (statusOption == null) { @@ -195,6 +209,8 @@ private void innerFulfill(FulfillOptions options) { } 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) { String mimeType = getMimeTypeForPath(options.path.toString()); headers.put("content-type", mimeType != null ? mimeType : "application/octet-stream"); 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 084851e1b..5e4d62cb3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ScreencastImpl.java @@ -25,6 +25,7 @@ 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; @@ -55,57 +56,66 @@ 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(this::hideActions); + return new DisposableStub(() -> page.channel.screencastHideActions(NO_TIMEOUT)); } @Override @@ -119,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 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 0083a9171..140c589bd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/SelectorsImpl.java @@ -24,16 +24,19 @@ 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 com.microsoft.playwright.impl.ClientHelper.evaluationScript; +import static com.microsoft.playwright.impl.Serialization.gson; public class SelectorsImpl extends LoggingSupport implements Selectors { protected final List selectorEngines = new ArrayList<>(); // java: defaults to data-testid, upstream leaves it undefined until set. String testIdAttributeName = "data-testid"; - protected final List contextsForSelectors = new ArrayList<>(); + protected final Set contextsForSelectors = new LinkedHashSet<>(); @Override public void register(String name, String script, RegisterOptions options) { @@ -72,7 +75,9 @@ public void setTestIdAttribute(String attributeName) { 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; @@ -81,4 +86,13 @@ public void setTestIdAttribute(String attributeName) { } } } + + // 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 41de72588..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,7 +14,7 @@ * limitations under the License. */ -// Port of serializers.ts (packages/protocol) and of serializeArgument and parseResult of jsHandle.ts. +// 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.*; @@ -43,11 +43,13 @@ 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; -// java: systemErrorCode and systemErrorMessage read Node.js system errors and are not ported. 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<>()); } @@ -125,13 +127,29 @@ private static Object innerParseSerializedValue(SerializedValue value, List registerCallback) { List handles = new ArrayList<>(); Function pushHandle = channel -> { handles.add(channel); @@ -344,6 +370,8 @@ static SerializedArgument serializeArgument(Object arg) { // 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(); @@ -352,12 +380,47 @@ static SerializedArgument serializeArgument(Object arg) { 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) { @@ -370,6 +433,12 @@ private static HandleOrValue handle(int 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; 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 ba4b5b307..42a6cefaf 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java @@ -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 157b856c4..e03a86722 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Stream.java @@ -19,6 +19,7 @@ import com.microsoft.playwright.impl.protocol.*; import com.google.gson.JsonObject; +import com.microsoft.playwright.PlaywrightException; import java.io.IOException; import java.io.InputStream; @@ -28,6 +29,8 @@ 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); } @@ -67,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 dd13f0f7f..ab26e43d8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java @@ -20,8 +20,9 @@ import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT; import static com.microsoft.playwright.impl.isomorphic.Time.DEFAULT_PLAYWRIGHT_TIMEOUT; -// java: no AbortSignal and no PWDEBUG=inspector branch, a timeout is a Double -// and 0 means no deadline. +// 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; @@ -51,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; @@ -58,6 +61,9 @@ Double defaultTimeout() { if (defaultNavigationTimeout != null) { return defaultNavigationTimeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (defaultTimeout != null) { return defaultTimeout; } @@ -71,6 +77,9 @@ Double defaultTimeout() { if (timeout != null) { return timeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (defaultTimeout != null) { return defaultTimeout; } @@ -84,12 +93,30 @@ Double defaultTimeout() { if (timeout != null) { return timeout; } + if ("inspector".equals(debugMode())) { + return 0; + } if (parent != null) { return parent.launchTimeout(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. Waitable createWaitable(Double timeout) { if (timeout != null && timeout == 0) { 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 62b544f9f..613e33ae1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -47,12 +47,19 @@ public class TracingImpl extends ChannelOwner implements Tracing { 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); } @Override public AutoCloseable start(StartOptions options) { + return start(options, null); + } + + // 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; @@ -64,6 +71,7 @@ public AutoCloseable start(StartOptions options) { 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(); 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 9c0aa95a4..65992b6df 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/UrlMatcher.java @@ -18,19 +18,34 @@ 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: globToRegexPattern, resolveGlobToRegexPattern, resolveGlobBase and the other glob functions are not ported: -// the driver resolves globs (LocalUtils.globToRegex), as they rely on the WHATWG URL parser. -// java: an URLMatch value; a glob also holds its resolved regex, so test() does not resolve it again. +// 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; @@ -68,7 +83,165 @@ private UrlMatcher(String glob, Pattern pattern, Predicate predicate) { this.predicate = predicate; } - // java: urlMatchesEqual(match1, match2). + 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; + } + } + + // 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)); + } + } + 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; @@ -101,8 +274,33 @@ public int hashCode() { return 0; } - // java: urlMatches(baseURL, urlString, match); the glob was resolved against the base URL by forGlob(), and a - // predicate takes the URL string, not a parsed URL. + 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; @@ -113,13 +311,113 @@ boolean test(String urlString) { return predicate.test(urlString); } - // java: resolveGlobToRegexPattern(baseURL, glob, webSocketUrl) and new RegExp(...); the driver resolves the glob, - // as resolveGlobBase() relies on the WHATWG URL parser. + 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; @@ -132,6 +430,29 @@ static String constructURLBasedOnBaseURL(String baseURL, String 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() { @@ -148,4 +469,87 @@ public String toString() { 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/VideoImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java index d5224c5e5..797afe53a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java @@ -23,25 +23,19 @@ import java.nio.file.Path; import java.nio.file.Paths; -// java: the video is created before its artifact is known, so the artifact is assigned later. -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 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()); @@ -59,4 +53,9 @@ 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 bbd6c71bc..6fb6fd690 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java @@ -67,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); } @@ -101,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) { @@ -170,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); @@ -183,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/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java index c500b2374..268a3f8b9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java @@ -37,6 +37,8 @@ public class WebSocketImpl extends ChannelOwner implements WebSocket { 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); webSocketInitializer = connection.protocolGson().fromJson(initializer, WebSocketInitializer.class); @@ -163,4 +165,6 @@ public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable } return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, callback); } + + // 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/WebSocketRouteImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java index 9e10aa7d7..040d42b14 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketRouteImpl.java @@ -42,6 +42,8 @@ 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; @@ -111,6 +113,8 @@ public void send(byte[] message) { params.isBase64 = true; sendNoWait("sendToServer", params); } + + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. }; } @@ -231,6 +235,8 @@ public void onClose(BiConsumer handler) { onPageClose = handler; } + // java: [Symbol.asyncDispose] is not ported, Java has no async dispose. + void afterHandle() { if (connected) { return; 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 5b7ac6f8e..a1641ec99 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java @@ -35,12 +35,15 @@ import static com.microsoft.playwright.impl.Serialization.*; public class WorkerImpl extends ChannelOwner implements Worker { - PageImpl page; - // java: no service worker or connectToWorker API, so there is no _context, _closeReason or _disconnect. + 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<>(); @@ -58,15 +61,30 @@ public void accept(Worker worker) { // 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 ("close".equals(event)) { - if (page != null) { - page.workers.remove(this); + 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; } - emit(Events.Worker.CLOSE, this); } } TargetClosedError closeErrorWithReason() { + if (closeReason != null) { + return new TargetClosedError(closeReason); + } if (page != null) { return page.closeErrorWithReason(); } @@ -78,6 +96,7 @@ 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 Object evaluate(String pageFunction, Object arg) { WorkerEvaluateExpressionParams params = new WorkerEvaluateExpressionParams(); @@ -94,9 +113,10 @@ public JSHandle evaluateHandle(String pageFunction, Object arg) { return channel.evaluateExpressionHandle(params, NO_TIMEOUT).handle; } - // java: the predicate and timeout are passed separately and the code to run is a Runnable. + // 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 + "\""); @@ -108,6 +128,19 @@ 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 void onClose(Consumer handler) { 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 e6963c809..cca4ab4a2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WritableStream.java @@ -30,6 +30,8 @@ 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 index a1a8b573f..dabfabc23 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Headers.java @@ -20,28 +20,85 @@ 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: headersArrayToObject and splitSetCookieHeader have no caller in the client. +// java: HeadersArray is a List of the protocol NameValue, HeadersObject a Map; a null value is undefined. public final class Headers { private Headers() { } - // java: the client never passes separator and setCookieSeparator; a null value is undefined. 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) { + 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; } - NameValue header = new NameValue(); - header.name = name; - header.value = values; - result.add(header); } + 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 index dacee5519..1b957ea3f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/LocatorUtils.java @@ -21,19 +21,28 @@ 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; } 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 index 2c609832f..f87d62b8f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/MimeType.java @@ -19,13 +19,25 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.regex.Pattern; -// java: only getMimeTypeForPath and its table; isJsonMimeType, isXmlMimeType, isTextualMimeType and -// getExtensionForMimeType have no caller in the client. +// 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) @@ -34,6 +46,30 @@ public static String getMimeTypeForPath(String path) { 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"); 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 index b5e44b426..cde6ffca1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/StringUtils.java @@ -18,25 +18,154 @@ 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: only the functions the client uses; a string | RegExp parameter is an Object holding a String or a Pattern. +// java: a string | RegExp parameter is an Object holding a String or a Pattern. public final class StringUtils { private StringUtils() { } - private static final Gson gson = new Gson(); + public static String escapeWithQuotes(String text) { + return escapeWithQuotes(text, "'"); + } - // java: JSON.stringify of a string. - public static String jsonStringify(String value) { - return gson.toJson(value); + // 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(">>", "\\\\>\\\\>"); } @@ -57,6 +186,10 @@ public static String escapeForAttributeSelector(Object value, boolean exact) { 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) @@ -71,8 +204,143 @@ 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 index 72d5d9e18..40461559d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/isomorphic/Time.java @@ -17,16 +17,42 @@ // Port of isomorphic/time.ts. package com.microsoft.playwright.impl.isomorphic; -// java: no setTimeOrigin and timeOrigin, the client does not use them. +// 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() { } - // java: System.nanoTime() stands for performance.now(), in milliseconds. + 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(System.nanoTime() / 1000.0) / 1000; + 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; + } }