pure-patchright 1.62.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- patchright/__init__.py +5 -0
- patchright/__main__.py +18 -0
- patchright/_impl/__init__.py +0 -0
- patchright/_impl/__pyinstaller/__init__.py +20 -0
- patchright/_impl/__pyinstaller/hook-playwright.async_api.py +3 -0
- patchright/_impl/__pyinstaller/hook-playwright.sync_api.py +3 -0
- patchright/_impl/_api_structures.py +343 -0
- patchright/_impl/_artifact.py +46 -0
- patchright/_impl/_assertions.py +1014 -0
- patchright/_impl/_async_base.py +88 -0
- patchright/_impl/_browser.py +267 -0
- patchright/_impl/_browser_context.py +759 -0
- patchright/_impl/_browser_type.py +336 -0
- patchright/_impl/_cdp_session.py +25 -0
- patchright/_impl/_clock.py +62 -0
- patchright/_impl/_connection.py +686 -0
- patchright/_impl/_console_message.py +83 -0
- patchright/_impl/_credentials.py +38 -0
- patchright/_impl/_debugger.py +37 -0
- patchright/_impl/_dialog.py +45 -0
- patchright/_impl/_disposable.py +71 -0
- patchright/_impl/_download.py +49 -0
- patchright/_impl/_driver.py +24 -0
- patchright/_impl/_element_handle.py +446 -0
- patchright/_impl/_errors.py +46 -0
- patchright/_impl/_event_context_manager.py +19 -0
- patchright/_impl/_fetch.py +592 -0
- patchright/_impl/_file_chooser.py +42 -0
- patchright/_impl/_form_data.py +19 -0
- patchright/_impl/_frame.py +959 -0
- patchright/_impl/_glob.py +47 -0
- patchright/_impl/_greenlets.py +35 -0
- patchright/_impl/_har_router.py +98 -0
- patchright/_impl/_helper.py +551 -0
- patchright/_impl/_impl_to_api_mapping.py +141 -0
- patchright/_impl/_input.py +85 -0
- patchright/_impl/_js_handle.py +297 -0
- patchright/_impl/_json_pipe.py +55 -0
- patchright/_impl/_local_utils.py +73 -0
- patchright/_impl/_locator.py +894 -0
- patchright/_impl/_map.py +18 -0
- patchright/_impl/_network.py +953 -0
- patchright/_impl/_object_factory.py +93 -0
- patchright/_impl/_page.py +1601 -0
- patchright/_impl/_path_utils.py +13 -0
- patchright/_impl/_playwright.py +43 -0
- patchright/_impl/_screencast.py +149 -0
- patchright/_impl/_selectors.py +48 -0
- patchright/_impl/_set_input_files_helpers.py +134 -0
- patchright/_impl/_str_utils.py +59 -0
- patchright/_impl/_stream.py +31 -0
- patchright/_impl/_sync_base.py +130 -0
- patchright/_impl/_tracing.py +243 -0
- patchright/_impl/_transport.py +151 -0
- patchright/_impl/_video.py +41 -0
- patchright/_impl/_waiter.py +168 -0
- patchright/_impl/_web_error.py +33 -0
- patchright/_impl/_web_storage.py +41 -0
- patchright/_impl/_writable_stream.py +26 -0
- patchright/_repo_version.py +1 -0
- patchright/async_api/__init__.py +234 -0
- patchright/async_api/_context_manager.py +38 -0
- patchright/async_api/_generated.py +23396 -0
- patchright/driver/README.md +1 -0
- patchright/driver/package/README.md +3 -0
- patchright/driver/package/ThirdPartyNotices.txt +13 -0
- patchright/driver/package/bin/install_media_pack.ps1 +5 -0
- patchright/driver/package/bin/install_webkit_wsl.ps1 +33 -0
- patchright/driver/package/bin/reinstall_chrome_beta_linux.sh +42 -0
- patchright/driver/package/bin/reinstall_chrome_beta_mac.sh +13 -0
- patchright/driver/package/bin/reinstall_chrome_beta_win.ps1 +24 -0
- patchright/driver/package/bin/reinstall_chrome_stable_linux.sh +42 -0
- patchright/driver/package/bin/reinstall_chrome_stable_mac.sh +12 -0
- patchright/driver/package/bin/reinstall_chrome_stable_win.ps1 +24 -0
- patchright/driver/package/bin/reinstall_msedge_beta_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_beta_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_beta_win.ps1 +23 -0
- patchright/driver/package/bin/reinstall_msedge_dev_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_dev_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_dev_win.ps1 +23 -0
- patchright/driver/package/bin/reinstall_msedge_stable_linux.sh +48 -0
- patchright/driver/package/bin/reinstall_msedge_stable_mac.sh +11 -0
- patchright/driver/package/bin/reinstall_msedge_stable_win.ps1 +24 -0
- patchright/driver/package/browsers.json +75 -0
- patchright/driver/package/cli.js +21 -0
- patchright/driver/package/index.js +17 -0
- patchright/driver/package/index.mjs +28 -0
- patchright/driver/package/lib/bootstrap.js +88 -0
- patchright/driver/package/lib/coreBundle.js +77498 -0
- patchright/driver/package/lib/entry/cliDaemon.js +5 -0
- patchright/driver/package/lib/entry/dashboardApp.js +3 -0
- patchright/driver/package/lib/entry/mcp.js +10 -0
- patchright/driver/package/lib/entry/oopBrowserDownload.js +3 -0
- patchright/driver/package/lib/package.js +50 -0
- patchright/driver/package/lib/server/chromium/appIcon.png +0 -0
- patchright/driver/package/lib/server/electron/loader.js +107 -0
- patchright/driver/package/lib/serverRegistry.js +7347 -0
- patchright/driver/package/lib/serverRegistry.js.LICENSE +354 -0
- patchright/driver/package/lib/tools/cli-client/channelSessions.js +141 -0
- patchright/driver/package/lib/tools/cli-client/cli.js +6 -0
- patchright/driver/package/lib/tools/cli-client/help.json +708 -0
- patchright/driver/package/lib/tools/cli-client/minimist.js +128 -0
- patchright/driver/package/lib/tools/cli-client/output.js +343 -0
- patchright/driver/package/lib/tools/cli-client/program.js +404 -0
- patchright/driver/package/lib/tools/cli-client/registry.js +176 -0
- patchright/driver/package/lib/tools/cli-client/session.js +258 -0
- patchright/driver/package/lib/tools/dashboard/appIcon.png +0 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/SKILL.md +420 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/running-code.md +241 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/session-management.md +225 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
- patchright/driver/package/lib/tools/skills/playwright-cli/references/video-recording.md +143 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/SKILL.md +143 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/migration.md +85 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/react.md +67 -0
- patchright/driver/package/lib/tools/skills/playwright-component-testing/references/vue.md +75 -0
- patchright/driver/package/lib/tools/skills/playwright-trace/SKILL.md +171 -0
- patchright/driver/package/lib/tools/utils/extension.js +101 -0
- patchright/driver/package/lib/tools/utils/socketConnection.js +108 -0
- patchright/driver/package/lib/utilsBundle.js +90764 -0
- patchright/driver/package/lib/utilsBundle.js.LICENSE +2179 -0
- patchright/driver/package/lib/webp_codec.LICENSE +173 -0
- patchright/driver/package/lib/webp_codec.wasm +0 -0
- patchright/driver/package/lib/xdg-open +1267 -0
- patchright/driver/package/package.json +34 -0
- patchright/py.typed +0 -0
- patchright/sync_api/__init__.py +234 -0
- patchright/sync_api/_context_manager.py +73 -0
- patchright/sync_api/_generated.py +23590 -0
- pure_patchright-1.62.3.dist-info/LICENSE +201 -0
- pure_patchright-1.62.3.dist-info/METADATA +96 -0
- pure_patchright-1.62.3.dist-info/RECORD +142 -0
- pure_patchright-1.62.3.dist-info/WHEEL +4 -0
- pure_patchright-1.62.3.dist-info/entry_points.txt +5 -0
- pure_patchright-1.62.3.dist-info/licenses/LICENSE +202 -0
- pure_patchright-1.62.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from types import FrameType
|
|
4
|
+
from typing import cast
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def get_file_dirname() -> Path:
|
|
8
|
+
"""Returns the callee (`__file__`) directory name"""
|
|
9
|
+
frame = cast(FrameType, inspect.currentframe()).f_back
|
|
10
|
+
module = inspect.getmodule(frame)
|
|
11
|
+
assert module
|
|
12
|
+
assert module.__file__
|
|
13
|
+
return Path(module.__file__).parent.absolute()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from typing import Dict
|
|
2
|
+
from patchright._impl._browser_type import BrowserType
|
|
3
|
+
from patchright._impl._connection import ChannelOwner, from_channel
|
|
4
|
+
from patchright._impl._fetch import APIRequest
|
|
5
|
+
from patchright._impl._selectors import Selectors
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Playwright(ChannelOwner):
|
|
9
|
+
devices: Dict
|
|
10
|
+
selectors: Selectors
|
|
11
|
+
chromium: BrowserType
|
|
12
|
+
firefox: BrowserType
|
|
13
|
+
webkit: BrowserType
|
|
14
|
+
request: APIRequest
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
|
|
18
|
+
) -> None:
|
|
19
|
+
super().__init__(parent, type, guid, initializer)
|
|
20
|
+
self.request = APIRequest(self)
|
|
21
|
+
self.chromium = from_channel(initializer["chromium"])
|
|
22
|
+
self.chromium._playwright = self
|
|
23
|
+
self.firefox = from_channel(initializer["firefox"])
|
|
24
|
+
self.firefox._playwright = self
|
|
25
|
+
self.webkit = from_channel(initializer["webkit"])
|
|
26
|
+
self.webkit._playwright = self
|
|
27
|
+
self.selectors = Selectors(self._loop, self._dispatcher_fiber)
|
|
28
|
+
self.devices = self._connection.local_utils.devices
|
|
29
|
+
|
|
30
|
+
def __getitem__(self, value: str) -> "BrowserType":
|
|
31
|
+
if value == "chromium":
|
|
32
|
+
return self.chromium
|
|
33
|
+
elif value == "firefox":
|
|
34
|
+
return self.firefox
|
|
35
|
+
elif value == "webkit":
|
|
36
|
+
return self.webkit
|
|
37
|
+
raise ValueError("Invalid browser " + value)
|
|
38
|
+
|
|
39
|
+
def _set_selectors(self, selectors: Selectors) -> None:
|
|
40
|
+
self.selectors = selectors
|
|
41
|
+
|
|
42
|
+
async def stop(self) -> None:
|
|
43
|
+
pass
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union
|
|
4
|
+
from patchright._impl._api_structures import ScreencastFrame, ScreencastSize
|
|
5
|
+
from patchright._impl._artifact import Artifact
|
|
6
|
+
from patchright._impl._connection import from_nullable_channel
|
|
7
|
+
from patchright._impl._disposable import DisposableStub
|
|
8
|
+
from patchright._impl._errors import Error
|
|
9
|
+
from patchright._impl._helper import locals_to_params
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from patchright._impl._page import Page
|
|
13
|
+
ScreencastFrameCallback = Callable[[ScreencastFrame], Any]
|
|
14
|
+
ScreencastPosition = Literal[
|
|
15
|
+
"bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"
|
|
16
|
+
]
|
|
17
|
+
ScreencastCursor = Literal["none", "pointer"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Screencast:
|
|
21
|
+
def __init__(self, page: "Page") -> None:
|
|
22
|
+
self._page = page
|
|
23
|
+
self._loop = page._loop
|
|
24
|
+
self._dispatcher_fiber = page._dispatcher_fiber
|
|
25
|
+
self._started = False
|
|
26
|
+
self._save_path: Optional[Union[str, Path]] = None
|
|
27
|
+
self._on_frame: Optional[ScreencastFrameCallback] = None
|
|
28
|
+
self._artifact: Optional[Artifact] = None
|
|
29
|
+
page._channel.on("screencastFrame", self._dispatch_frame)
|
|
30
|
+
|
|
31
|
+
def _ack_frame(self, frame_id: int) -> None:
|
|
32
|
+
try:
|
|
33
|
+
self._page._channel.send_no_reply(
|
|
34
|
+
"screencastFrameAck", None, {"frameId": frame_id}
|
|
35
|
+
)
|
|
36
|
+
except (Error, OSError):
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
async def _await_callback_and_ack(self, result: Any, frame_id: int) -> None:
|
|
40
|
+
try:
|
|
41
|
+
await result
|
|
42
|
+
finally:
|
|
43
|
+
self._ack_frame(frame_id)
|
|
44
|
+
|
|
45
|
+
def _dispatch_frame(self, params: dict) -> Any:
|
|
46
|
+
result = None
|
|
47
|
+
task = None
|
|
48
|
+
try:
|
|
49
|
+
if not self._on_frame:
|
|
50
|
+
return
|
|
51
|
+
data = params["data"]
|
|
52
|
+
if isinstance(data, str):
|
|
53
|
+
data = base64.b64decode(data)
|
|
54
|
+
result = self._on_frame(
|
|
55
|
+
{
|
|
56
|
+
"data": data,
|
|
57
|
+
"timestamp": params.get("timestamp", 0),
|
|
58
|
+
"viewportWidth": params["viewportWidth"],
|
|
59
|
+
"viewportHeight": params["viewportHeight"],
|
|
60
|
+
}
|
|
61
|
+
)
|
|
62
|
+
finally:
|
|
63
|
+
if hasattr(result, "__await__"):
|
|
64
|
+
task = self._loop.create_task(
|
|
65
|
+
self._await_callback_and_ack(result, params["frameId"])
|
|
66
|
+
)
|
|
67
|
+
else:
|
|
68
|
+
self._ack_frame(params["frameId"])
|
|
69
|
+
return task
|
|
70
|
+
|
|
71
|
+
async def start(
|
|
72
|
+
self,
|
|
73
|
+
onFrame: ScreencastFrameCallback = None,
|
|
74
|
+
path: Union[str, Path] = None,
|
|
75
|
+
quality: int = None,
|
|
76
|
+
size: ScreencastSize = None,
|
|
77
|
+
) -> DisposableStub:
|
|
78
|
+
if self._started:
|
|
79
|
+
raise Error("Screencast is already started")
|
|
80
|
+
self._started = True
|
|
81
|
+
self._on_frame = onFrame
|
|
82
|
+
result = await self._page._channel.send_return_as_dict(
|
|
83
|
+
"screencastStart",
|
|
84
|
+
None,
|
|
85
|
+
{
|
|
86
|
+
"size": size,
|
|
87
|
+
"quality": quality,
|
|
88
|
+
"sendFrames": bool(onFrame),
|
|
89
|
+
"record": bool(path),
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
artifact_channel = (result or {}).get("artifact")
|
|
93
|
+
if artifact_channel:
|
|
94
|
+
self._artifact = from_nullable_channel(artifact_channel)
|
|
95
|
+
self._save_path = path
|
|
96
|
+
return DisposableStub(lambda: self.stop(), self._page)
|
|
97
|
+
|
|
98
|
+
async def stop(self) -> None:
|
|
99
|
+
self._started = False
|
|
100
|
+
self._on_frame = None
|
|
101
|
+
await self._page._channel.send("screencastStop", None)
|
|
102
|
+
if self._save_path and self._artifact:
|
|
103
|
+
await self._artifact.save_as(self._save_path)
|
|
104
|
+
self._artifact = None
|
|
105
|
+
self._save_path = None
|
|
106
|
+
|
|
107
|
+
async def show_actions(
|
|
108
|
+
self,
|
|
109
|
+
duration: float = None,
|
|
110
|
+
position: ScreencastPosition = None,
|
|
111
|
+
fontSize: int = None,
|
|
112
|
+
cursor: ScreencastCursor = None,
|
|
113
|
+
) -> DisposableStub:
|
|
114
|
+
await self._page._channel.send(
|
|
115
|
+
"screencastShowActions", None, locals_to_params(locals())
|
|
116
|
+
)
|
|
117
|
+
return DisposableStub(lambda: self.hide_actions(), self._page)
|
|
118
|
+
|
|
119
|
+
async def hide_actions(self) -> None:
|
|
120
|
+
await self._page._channel.send("screencastHideActions", None)
|
|
121
|
+
|
|
122
|
+
async def show_overlay(self, html: str, duration: float = None) -> DisposableStub:
|
|
123
|
+
result = await self._page._channel.send_return_as_dict(
|
|
124
|
+
"screencastShowOverlay", None, locals_to_params(locals())
|
|
125
|
+
)
|
|
126
|
+
overlay_id = (result or {}).get("id")
|
|
127
|
+
return DisposableStub(
|
|
128
|
+
lambda: self._page._channel.send(
|
|
129
|
+
"screencastRemoveOverlay", None, {"id": overlay_id}
|
|
130
|
+
),
|
|
131
|
+
self._page,
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
async def show_chapter(
|
|
135
|
+
self, title: str, description: str = None, duration: float = None
|
|
136
|
+
) -> None:
|
|
137
|
+
await self._page._channel.send(
|
|
138
|
+
"screencastChapter", None, locals_to_params(locals())
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
async def show_overlays(self) -> None:
|
|
142
|
+
await self._page._channel.send(
|
|
143
|
+
"screencastSetOverlayVisible", None, {"visible": True}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
async def hide_overlays(self) -> None:
|
|
147
|
+
await self._page._channel.send(
|
|
148
|
+
"screencastSetOverlayVisible", None, {"visible": False}
|
|
149
|
+
)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Dict, List, Optional, Set, Union
|
|
4
|
+
from patchright._impl._browser_context import BrowserContext
|
|
5
|
+
from patchright._impl._errors import Error
|
|
6
|
+
from patchright._impl._helper import async_readfile
|
|
7
|
+
from patchright._impl._locator import set_test_id_attribute_name
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Selectors:
|
|
11
|
+
def __init__(self, loop: asyncio.AbstractEventLoop, dispatcher_fiber: Any) -> None:
|
|
12
|
+
self._loop = loop
|
|
13
|
+
self._contexts_for_selectors: Set[BrowserContext] = set()
|
|
14
|
+
self._selector_engines: List[Dict] = []
|
|
15
|
+
self._dispatcher_fiber = dispatcher_fiber
|
|
16
|
+
self._test_id_attribute_name: Optional[str] = None
|
|
17
|
+
|
|
18
|
+
async def register(
|
|
19
|
+
self,
|
|
20
|
+
name: str,
|
|
21
|
+
script: str = None,
|
|
22
|
+
path: Union[str, Path] = None,
|
|
23
|
+
contentScript: bool = None,
|
|
24
|
+
) -> None:
|
|
25
|
+
if any((engine for engine in self._selector_engines if engine["name"] == name)):
|
|
26
|
+
raise Error(
|
|
27
|
+
f'Selectors.register: "{name}" selector engine has been already registered'
|
|
28
|
+
)
|
|
29
|
+
if not script and (not path):
|
|
30
|
+
raise Error("Either source or path should be specified")
|
|
31
|
+
if path:
|
|
32
|
+
script = (await async_readfile(path)).decode()
|
|
33
|
+
engine: Dict[str, Any] = dict(name=name, source=script)
|
|
34
|
+
if contentScript:
|
|
35
|
+
engine["contentScript"] = contentScript
|
|
36
|
+
for context in self._contexts_for_selectors:
|
|
37
|
+
await context._channel.send(
|
|
38
|
+
"registerSelectorEngine", None, {"selectorEngine": engine}
|
|
39
|
+
)
|
|
40
|
+
self._selector_engines.append(engine)
|
|
41
|
+
|
|
42
|
+
def set_test_id_attribute(self, attributeName: str) -> None:
|
|
43
|
+
set_test_id_attribute_name(attributeName)
|
|
44
|
+
self._test_id_attribute_name = attributeName
|
|
45
|
+
for context in self._contexts_for_selectors:
|
|
46
|
+
context._channel.send_no_reply(
|
|
47
|
+
"setTestIdAttributeName", None, {"testIdAttributeName": attributeName}
|
|
48
|
+
)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import collections.abc
|
|
3
|
+
import os
|
|
4
|
+
import stat
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import (
|
|
7
|
+
TYPE_CHECKING,
|
|
8
|
+
Dict,
|
|
9
|
+
List,
|
|
10
|
+
Optional,
|
|
11
|
+
Sequence,
|
|
12
|
+
Tuple,
|
|
13
|
+
TypedDict,
|
|
14
|
+
Union,
|
|
15
|
+
cast,
|
|
16
|
+
)
|
|
17
|
+
from patchright._impl._connection import Channel, from_channel
|
|
18
|
+
from patchright._impl._helper import Error
|
|
19
|
+
from patchright._impl._writable_stream import WritableStream
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from patchright._impl._browser_context import BrowserContext
|
|
23
|
+
from patchright._impl._api_structures import FilePayload
|
|
24
|
+
|
|
25
|
+
SIZE_LIMIT_IN_BYTES = 50 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class InputFilesList(TypedDict, total=False):
|
|
29
|
+
streams: Optional[List[Channel]]
|
|
30
|
+
directoryStream: Optional[Channel]
|
|
31
|
+
localDirectory: Optional[str]
|
|
32
|
+
localPaths: Optional[List[str]]
|
|
33
|
+
payloads: Optional[List[Dict[str, Union[str, bytes]]]]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _list_files(directory: str) -> List[str]:
|
|
37
|
+
files = []
|
|
38
|
+
for root, _, filenames in os.walk(directory):
|
|
39
|
+
for filename in filenames:
|
|
40
|
+
files.append(os.path.join(root, filename))
|
|
41
|
+
return files
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def convert_input_files(
|
|
45
|
+
files: Union[
|
|
46
|
+
str, Path, FilePayload, Sequence[Union[str, Path]], Sequence[FilePayload]
|
|
47
|
+
],
|
|
48
|
+
context: "BrowserContext",
|
|
49
|
+
) -> InputFilesList:
|
|
50
|
+
items = (
|
|
51
|
+
files
|
|
52
|
+
if isinstance(files, collections.abc.Sequence) and (not isinstance(files, str))
|
|
53
|
+
else [files]
|
|
54
|
+
)
|
|
55
|
+
if any([isinstance(item, (str, Path)) for item in items]):
|
|
56
|
+
if not all([isinstance(item, (str, Path)) for item in items]):
|
|
57
|
+
raise Error("File paths cannot be mixed with buffers")
|
|
58
|
+
local_paths, local_directory = resolve_paths_and_directory_for_input_files(
|
|
59
|
+
cast(Sequence[Union[str, Path]], items)
|
|
60
|
+
)
|
|
61
|
+
if context._channel._connection.is_remote:
|
|
62
|
+
files_to_stream = cast(
|
|
63
|
+
List[str],
|
|
64
|
+
_list_files(local_directory) if local_directory else local_paths,
|
|
65
|
+
)
|
|
66
|
+
streams = []
|
|
67
|
+
result = await context._connection.wrap_api_call(
|
|
68
|
+
lambda: context._channel.send_return_as_dict(
|
|
69
|
+
"createTempFiles",
|
|
70
|
+
None,
|
|
71
|
+
{
|
|
72
|
+
"rootDirName": os.path.basename(local_directory)
|
|
73
|
+
if local_directory
|
|
74
|
+
else None,
|
|
75
|
+
"items": list(
|
|
76
|
+
map(
|
|
77
|
+
lambda file: dict(
|
|
78
|
+
name=os.path.relpath(file, local_directory)
|
|
79
|
+
if local_directory
|
|
80
|
+
else os.path.basename(file),
|
|
81
|
+
lastModifiedMs=int(os.path.getmtime(file) * 1000),
|
|
82
|
+
),
|
|
83
|
+
files_to_stream,
|
|
84
|
+
)
|
|
85
|
+
),
|
|
86
|
+
},
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
for i, file in enumerate(result["writableStreams"]):
|
|
90
|
+
stream: WritableStream = from_channel(file)
|
|
91
|
+
await stream.copy(files_to_stream[i])
|
|
92
|
+
streams.append(stream._channel)
|
|
93
|
+
return InputFilesList(
|
|
94
|
+
streams=None if local_directory else streams,
|
|
95
|
+
directoryStream=result.get("rootDir"),
|
|
96
|
+
)
|
|
97
|
+
return InputFilesList(localPaths=local_paths, localDirectory=local_directory)
|
|
98
|
+
file_payload_exceeds_size_limit = (
|
|
99
|
+
sum([len(f.get("buffer", "")) for f in items if not isinstance(f, (str, Path))])
|
|
100
|
+
> SIZE_LIMIT_IN_BYTES
|
|
101
|
+
)
|
|
102
|
+
if file_payload_exceeds_size_limit:
|
|
103
|
+
raise Error(
|
|
104
|
+
"Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead."
|
|
105
|
+
)
|
|
106
|
+
return InputFilesList(
|
|
107
|
+
payloads=[
|
|
108
|
+
{
|
|
109
|
+
"name": item["name"],
|
|
110
|
+
"mimeType": item["mimeType"],
|
|
111
|
+
"buffer": base64.b64encode(item["buffer"]).decode(),
|
|
112
|
+
}
|
|
113
|
+
for item in cast(List[FilePayload], items)
|
|
114
|
+
]
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def resolve_paths_and_directory_for_input_files(
|
|
119
|
+
items: Sequence[Union[str, Path]],
|
|
120
|
+
) -> Tuple[Optional[List[str]], Optional[str]]:
|
|
121
|
+
local_paths: Optional[List[str]] = None
|
|
122
|
+
local_directory: Optional[str] = None
|
|
123
|
+
for item in items:
|
|
124
|
+
item_stat = os.stat(item)
|
|
125
|
+
if stat.S_ISDIR(item_stat.st_mode):
|
|
126
|
+
if local_directory:
|
|
127
|
+
raise Error("Multiple directories are not supported")
|
|
128
|
+
local_directory = str(Path(item).resolve())
|
|
129
|
+
else:
|
|
130
|
+
local_paths = local_paths or []
|
|
131
|
+
local_paths.append(str(Path(item).resolve()))
|
|
132
|
+
if local_paths and local_directory:
|
|
133
|
+
raise Error("File paths must be all files or a single directory")
|
|
134
|
+
return (local_paths, local_directory)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
from typing import Pattern, Union
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def escape_regex_flags(pattern: Pattern) -> str:
|
|
7
|
+
flags = ""
|
|
8
|
+
if pattern.flags != 0:
|
|
9
|
+
flags = ""
|
|
10
|
+
if pattern.flags & int(re.IGNORECASE) != 0:
|
|
11
|
+
flags += "i"
|
|
12
|
+
if pattern.flags & int(re.DOTALL) != 0:
|
|
13
|
+
flags += "s"
|
|
14
|
+
if pattern.flags & int(re.MULTILINE) != 0:
|
|
15
|
+
flags += "m"
|
|
16
|
+
assert (
|
|
17
|
+
pattern.flags
|
|
18
|
+
& ~(int(re.MULTILINE) | int(re.IGNORECASE) | int(re.DOTALL) | int(re.UNICODE))
|
|
19
|
+
== 0
|
|
20
|
+
), (
|
|
21
|
+
"Unexpected re.Pattern flag, only MULTILINE, IGNORECASE and DOTALL are supported."
|
|
22
|
+
)
|
|
23
|
+
return flags
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def escape_for_regex(text: str) -> str:
|
|
27
|
+
return re.sub("[.*+?^>${}()|[\\]\\\\]", "\\$&", text)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def escape_regex_for_selector(text: Pattern) -> str:
|
|
31
|
+
return (
|
|
32
|
+
"/"
|
|
33
|
+
+ re.sub(
|
|
34
|
+
"(^|[^\\\\])(\\\\\\\\)*([\"\\'`])", "\\1\\2\\\\\\3", text.pattern
|
|
35
|
+
).replace(">>", "\\>\\>")
|
|
36
|
+
+ "/"
|
|
37
|
+
+ escape_regex_flags(text)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def escape_for_text_selector(
|
|
42
|
+
text: Union[str, Pattern[str]], exact: bool = None, case_sensitive: bool = None
|
|
43
|
+
) -> str:
|
|
44
|
+
if isinstance(text, Pattern):
|
|
45
|
+
return escape_regex_for_selector(text)
|
|
46
|
+
return json.dumps(text) + ("s" if exact else "i")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def escape_for_attribute_selector(
|
|
50
|
+
value: Union[str, Pattern], exact: bool = None
|
|
51
|
+
) -> str:
|
|
52
|
+
if isinstance(value, Pattern):
|
|
53
|
+
return escape_regex_for_selector(value)
|
|
54
|
+
return (
|
|
55
|
+
'"'
|
|
56
|
+
+ value.replace("\\", "\\\\").replace('"', '\\"')
|
|
57
|
+
+ '"'
|
|
58
|
+
+ ("s" if exact else "i")
|
|
59
|
+
)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Dict, Union
|
|
4
|
+
from patchright._impl._connection import ChannelOwner
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Stream(ChannelOwner):
|
|
8
|
+
def __init__(
|
|
9
|
+
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
|
|
10
|
+
) -> None:
|
|
11
|
+
super().__init__(parent, type, guid, initializer)
|
|
12
|
+
|
|
13
|
+
async def save_as(self, path: Union[str, Path]) -> None:
|
|
14
|
+
file = await self._loop.run_in_executor(None, lambda: open(path, "wb"))
|
|
15
|
+
while True:
|
|
16
|
+
binary = await self._channel.send("read", None, {"size": 1024 * 1024})
|
|
17
|
+
if not binary:
|
|
18
|
+
break
|
|
19
|
+
await self._loop.run_in_executor(
|
|
20
|
+
None, lambda: file.write(base64.b64decode(binary))
|
|
21
|
+
)
|
|
22
|
+
await self._loop.run_in_executor(None, lambda: file.close())
|
|
23
|
+
|
|
24
|
+
async def read_all(self) -> bytes:
|
|
25
|
+
binary = b""
|
|
26
|
+
while True:
|
|
27
|
+
chunk = await self._channel.send("read", None, {"size": 1024 * 1024})
|
|
28
|
+
if not chunk:
|
|
29
|
+
break
|
|
30
|
+
binary += base64.b64decode(chunk)
|
|
31
|
+
return binary
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import traceback
|
|
3
|
+
from contextlib import AbstractContextManager
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import (
|
|
6
|
+
Any,
|
|
7
|
+
Callable,
|
|
8
|
+
Coroutine,
|
|
9
|
+
Generator,
|
|
10
|
+
Generic,
|
|
11
|
+
Optional,
|
|
12
|
+
Type,
|
|
13
|
+
TypeVar,
|
|
14
|
+
Union,
|
|
15
|
+
cast,
|
|
16
|
+
)
|
|
17
|
+
import greenlet
|
|
18
|
+
from patchright._impl._connection import _capture_stack_trace
|
|
19
|
+
from patchright._impl._helper import Error
|
|
20
|
+
from patchright._impl._impl_to_api_mapping import ImplToApiMapping, ImplWrapper
|
|
21
|
+
|
|
22
|
+
mapping = ImplToApiMapping()
|
|
23
|
+
T = TypeVar("T")
|
|
24
|
+
Self = TypeVar("Self", bound="SyncContextManager")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class EventInfo(Generic[T]):
|
|
28
|
+
def __init__(self, sync_base: "SyncBase", future: "asyncio.Future[T]") -> None:
|
|
29
|
+
self._sync_base = sync_base
|
|
30
|
+
self._future = future
|
|
31
|
+
g_self = greenlet.getcurrent()
|
|
32
|
+
self._future.add_done_callback(lambda _: g_self.switch())
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def value(self) -> T:
|
|
36
|
+
while not self._future.done():
|
|
37
|
+
self._sync_base._dispatcher_fiber.switch()
|
|
38
|
+
asyncio._set_running_loop(self._sync_base._loop)
|
|
39
|
+
exception = self._future.exception()
|
|
40
|
+
if exception:
|
|
41
|
+
raise exception
|
|
42
|
+
return cast(T, mapping.from_maybe_impl(self._future.result()))
|
|
43
|
+
|
|
44
|
+
def _cancel(self) -> None:
|
|
45
|
+
self._future.cancel()
|
|
46
|
+
|
|
47
|
+
def is_done(self) -> bool:
|
|
48
|
+
return self._future.done()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class EventContextManager(Generic[T], AbstractContextManager):
|
|
52
|
+
def __init__(self, sync_base: "SyncBase", future: "asyncio.Future[T]") -> None:
|
|
53
|
+
self._event = EventInfo[T](sync_base, future)
|
|
54
|
+
|
|
55
|
+
def __enter__(self) -> EventInfo[T]:
|
|
56
|
+
return self._event
|
|
57
|
+
|
|
58
|
+
def __exit__(
|
|
59
|
+
self,
|
|
60
|
+
exc_type: Optional[Type[BaseException]],
|
|
61
|
+
exc_val: Optional[BaseException],
|
|
62
|
+
exc_tb: Optional[TracebackType],
|
|
63
|
+
) -> None:
|
|
64
|
+
if exc_val:
|
|
65
|
+
self._event._cancel()
|
|
66
|
+
else:
|
|
67
|
+
self._event.value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SyncBase(ImplWrapper):
|
|
71
|
+
def __init__(self, impl_obj: Any) -> None:
|
|
72
|
+
super().__init__(impl_obj)
|
|
73
|
+
self._loop: asyncio.AbstractEventLoop = impl_obj._loop
|
|
74
|
+
self._dispatcher_fiber = impl_obj._dispatcher_fiber
|
|
75
|
+
|
|
76
|
+
def __str__(self) -> str:
|
|
77
|
+
return self._impl_obj.__str__()
|
|
78
|
+
|
|
79
|
+
def _sync(
|
|
80
|
+
self, coro: Union[Coroutine[Any, Any, Any], Generator[Any, Any, Any]]
|
|
81
|
+
) -> Any:
|
|
82
|
+
__tracebackhide__ = True
|
|
83
|
+
if self._loop.is_closed():
|
|
84
|
+
coro.close()
|
|
85
|
+
raise Error("Event loop is closed! Is Playwright already stopped?")
|
|
86
|
+
g_self = greenlet.getcurrent()
|
|
87
|
+
task: asyncio.tasks.Task[Any] = self._loop.create_task(coro)
|
|
88
|
+
setattr(task, "__pw_stack__", _capture_stack_trace())
|
|
89
|
+
setattr(task, "__pw_stack_trace__", traceback.extract_stack(limit=10))
|
|
90
|
+
task.add_done_callback(lambda _: g_self.switch())
|
|
91
|
+
while not task.done():
|
|
92
|
+
self._dispatcher_fiber.switch()
|
|
93
|
+
asyncio._set_running_loop(self._loop)
|
|
94
|
+
return task.result()
|
|
95
|
+
|
|
96
|
+
def _wrap_handler(
|
|
97
|
+
self, handler: Union[Callable[..., Any], Any]
|
|
98
|
+
) -> Callable[..., None]:
|
|
99
|
+
if callable(handler):
|
|
100
|
+
return mapping.wrap_handler(handler)
|
|
101
|
+
return handler
|
|
102
|
+
|
|
103
|
+
def on(self, event: Any, f: Any) -> None:
|
|
104
|
+
"""Registers the function ``f`` to the event name ``event``."""
|
|
105
|
+
self._impl_obj.on(event, self._wrap_handler(f))
|
|
106
|
+
|
|
107
|
+
def once(self, event: Any, f: Any) -> None:
|
|
108
|
+
"""The same as ``self.on``, except that the listener is automatically
|
|
109
|
+
removed after being called.
|
|
110
|
+
"""
|
|
111
|
+
self._impl_obj.once(event, self._wrap_handler(f))
|
|
112
|
+
|
|
113
|
+
def remove_listener(self, event: Any, f: Any) -> None:
|
|
114
|
+
"""Removes the function ``f`` from ``event``."""
|
|
115
|
+
self._impl_obj.remove_listener(event, self._wrap_handler(f))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class SyncContextManager(SyncBase):
|
|
119
|
+
def __enter__(self: Self) -> Self:
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
def __exit__(
|
|
123
|
+
self,
|
|
124
|
+
exc_type: Optional[Type[BaseException]],
|
|
125
|
+
exc_val: Optional[BaseException],
|
|
126
|
+
_traceback: Optional[TracebackType],
|
|
127
|
+
) -> None:
|
|
128
|
+
self.close()
|
|
129
|
+
|
|
130
|
+
def close(self) -> None: ...
|