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.
Files changed (142) hide show
  1. patchright/__init__.py +5 -0
  2. patchright/__main__.py +18 -0
  3. patchright/_impl/__init__.py +0 -0
  4. patchright/_impl/__pyinstaller/__init__.py +20 -0
  5. patchright/_impl/__pyinstaller/hook-playwright.async_api.py +3 -0
  6. patchright/_impl/__pyinstaller/hook-playwright.sync_api.py +3 -0
  7. patchright/_impl/_api_structures.py +343 -0
  8. patchright/_impl/_artifact.py +46 -0
  9. patchright/_impl/_assertions.py +1014 -0
  10. patchright/_impl/_async_base.py +88 -0
  11. patchright/_impl/_browser.py +267 -0
  12. patchright/_impl/_browser_context.py +759 -0
  13. patchright/_impl/_browser_type.py +336 -0
  14. patchright/_impl/_cdp_session.py +25 -0
  15. patchright/_impl/_clock.py +62 -0
  16. patchright/_impl/_connection.py +686 -0
  17. patchright/_impl/_console_message.py +83 -0
  18. patchright/_impl/_credentials.py +38 -0
  19. patchright/_impl/_debugger.py +37 -0
  20. patchright/_impl/_dialog.py +45 -0
  21. patchright/_impl/_disposable.py +71 -0
  22. patchright/_impl/_download.py +49 -0
  23. patchright/_impl/_driver.py +24 -0
  24. patchright/_impl/_element_handle.py +446 -0
  25. patchright/_impl/_errors.py +46 -0
  26. patchright/_impl/_event_context_manager.py +19 -0
  27. patchright/_impl/_fetch.py +592 -0
  28. patchright/_impl/_file_chooser.py +42 -0
  29. patchright/_impl/_form_data.py +19 -0
  30. patchright/_impl/_frame.py +959 -0
  31. patchright/_impl/_glob.py +47 -0
  32. patchright/_impl/_greenlets.py +35 -0
  33. patchright/_impl/_har_router.py +98 -0
  34. patchright/_impl/_helper.py +551 -0
  35. patchright/_impl/_impl_to_api_mapping.py +141 -0
  36. patchright/_impl/_input.py +85 -0
  37. patchright/_impl/_js_handle.py +297 -0
  38. patchright/_impl/_json_pipe.py +55 -0
  39. patchright/_impl/_local_utils.py +73 -0
  40. patchright/_impl/_locator.py +894 -0
  41. patchright/_impl/_map.py +18 -0
  42. patchright/_impl/_network.py +953 -0
  43. patchright/_impl/_object_factory.py +93 -0
  44. patchright/_impl/_page.py +1601 -0
  45. patchright/_impl/_path_utils.py +13 -0
  46. patchright/_impl/_playwright.py +43 -0
  47. patchright/_impl/_screencast.py +149 -0
  48. patchright/_impl/_selectors.py +48 -0
  49. patchright/_impl/_set_input_files_helpers.py +134 -0
  50. patchright/_impl/_str_utils.py +59 -0
  51. patchright/_impl/_stream.py +31 -0
  52. patchright/_impl/_sync_base.py +130 -0
  53. patchright/_impl/_tracing.py +243 -0
  54. patchright/_impl/_transport.py +151 -0
  55. patchright/_impl/_video.py +41 -0
  56. patchright/_impl/_waiter.py +168 -0
  57. patchright/_impl/_web_error.py +33 -0
  58. patchright/_impl/_web_storage.py +41 -0
  59. patchright/_impl/_writable_stream.py +26 -0
  60. patchright/_repo_version.py +1 -0
  61. patchright/async_api/__init__.py +234 -0
  62. patchright/async_api/_context_manager.py +38 -0
  63. patchright/async_api/_generated.py +23396 -0
  64. patchright/driver/README.md +1 -0
  65. patchright/driver/package/README.md +3 -0
  66. patchright/driver/package/ThirdPartyNotices.txt +13 -0
  67. patchright/driver/package/bin/install_media_pack.ps1 +5 -0
  68. patchright/driver/package/bin/install_webkit_wsl.ps1 +33 -0
  69. patchright/driver/package/bin/reinstall_chrome_beta_linux.sh +42 -0
  70. patchright/driver/package/bin/reinstall_chrome_beta_mac.sh +13 -0
  71. patchright/driver/package/bin/reinstall_chrome_beta_win.ps1 +24 -0
  72. patchright/driver/package/bin/reinstall_chrome_stable_linux.sh +42 -0
  73. patchright/driver/package/bin/reinstall_chrome_stable_mac.sh +12 -0
  74. patchright/driver/package/bin/reinstall_chrome_stable_win.ps1 +24 -0
  75. patchright/driver/package/bin/reinstall_msedge_beta_linux.sh +48 -0
  76. patchright/driver/package/bin/reinstall_msedge_beta_mac.sh +11 -0
  77. patchright/driver/package/bin/reinstall_msedge_beta_win.ps1 +23 -0
  78. patchright/driver/package/bin/reinstall_msedge_dev_linux.sh +48 -0
  79. patchright/driver/package/bin/reinstall_msedge_dev_mac.sh +11 -0
  80. patchright/driver/package/bin/reinstall_msedge_dev_win.ps1 +23 -0
  81. patchright/driver/package/bin/reinstall_msedge_stable_linux.sh +48 -0
  82. patchright/driver/package/bin/reinstall_msedge_stable_mac.sh +11 -0
  83. patchright/driver/package/bin/reinstall_msedge_stable_win.ps1 +24 -0
  84. patchright/driver/package/browsers.json +75 -0
  85. patchright/driver/package/cli.js +21 -0
  86. patchright/driver/package/index.js +17 -0
  87. patchright/driver/package/index.mjs +28 -0
  88. patchright/driver/package/lib/bootstrap.js +88 -0
  89. patchright/driver/package/lib/coreBundle.js +77498 -0
  90. patchright/driver/package/lib/entry/cliDaemon.js +5 -0
  91. patchright/driver/package/lib/entry/dashboardApp.js +3 -0
  92. patchright/driver/package/lib/entry/mcp.js +10 -0
  93. patchright/driver/package/lib/entry/oopBrowserDownload.js +3 -0
  94. patchright/driver/package/lib/package.js +50 -0
  95. patchright/driver/package/lib/server/chromium/appIcon.png +0 -0
  96. patchright/driver/package/lib/server/electron/loader.js +107 -0
  97. patchright/driver/package/lib/serverRegistry.js +7347 -0
  98. patchright/driver/package/lib/serverRegistry.js.LICENSE +354 -0
  99. patchright/driver/package/lib/tools/cli-client/channelSessions.js +141 -0
  100. patchright/driver/package/lib/tools/cli-client/cli.js +6 -0
  101. patchright/driver/package/lib/tools/cli-client/help.json +708 -0
  102. patchright/driver/package/lib/tools/cli-client/minimist.js +128 -0
  103. patchright/driver/package/lib/tools/cli-client/output.js +343 -0
  104. patchright/driver/package/lib/tools/cli-client/program.js +404 -0
  105. patchright/driver/package/lib/tools/cli-client/registry.js +176 -0
  106. patchright/driver/package/lib/tools/cli-client/session.js +258 -0
  107. patchright/driver/package/lib/tools/dashboard/appIcon.png +0 -0
  108. patchright/driver/package/lib/tools/skills/playwright-cli/SKILL.md +420 -0
  109. patchright/driver/package/lib/tools/skills/playwright-cli/references/element-attributes.md +23 -0
  110. patchright/driver/package/lib/tools/skills/playwright-cli/references/playwright-tests.md +39 -0
  111. patchright/driver/package/lib/tools/skills/playwright-cli/references/request-mocking.md +87 -0
  112. patchright/driver/package/lib/tools/skills/playwright-cli/references/running-code.md +241 -0
  113. patchright/driver/package/lib/tools/skills/playwright-cli/references/session-management.md +225 -0
  114. patchright/driver/package/lib/tools/skills/playwright-cli/references/storage-state.md +275 -0
  115. patchright/driver/package/lib/tools/skills/playwright-cli/references/test-generation.md +433 -0
  116. patchright/driver/package/lib/tools/skills/playwright-cli/references/tracing.md +139 -0
  117. patchright/driver/package/lib/tools/skills/playwright-cli/references/video-recording.md +143 -0
  118. patchright/driver/package/lib/tools/skills/playwright-component-testing/SKILL.md +143 -0
  119. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/gallery-spec.md +144 -0
  120. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/migration.md +85 -0
  121. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/react.md +67 -0
  122. patchright/driver/package/lib/tools/skills/playwright-component-testing/references/vue.md +75 -0
  123. patchright/driver/package/lib/tools/skills/playwright-trace/SKILL.md +171 -0
  124. patchright/driver/package/lib/tools/utils/extension.js +101 -0
  125. patchright/driver/package/lib/tools/utils/socketConnection.js +108 -0
  126. patchright/driver/package/lib/utilsBundle.js +90764 -0
  127. patchright/driver/package/lib/utilsBundle.js.LICENSE +2179 -0
  128. patchright/driver/package/lib/webp_codec.LICENSE +173 -0
  129. patchright/driver/package/lib/webp_codec.wasm +0 -0
  130. patchright/driver/package/lib/xdg-open +1267 -0
  131. patchright/driver/package/package.json +34 -0
  132. patchright/py.typed +0 -0
  133. patchright/sync_api/__init__.py +234 -0
  134. patchright/sync_api/_context_manager.py +73 -0
  135. patchright/sync_api/_generated.py +23590 -0
  136. pure_patchright-1.62.3.dist-info/LICENSE +201 -0
  137. pure_patchright-1.62.3.dist-info/METADATA +96 -0
  138. pure_patchright-1.62.3.dist-info/RECORD +142 -0
  139. pure_patchright-1.62.3.dist-info/WHEEL +4 -0
  140. pure_patchright-1.62.3.dist-info/entry_points.txt +5 -0
  141. pure_patchright-1.62.3.dist-info/licenses/LICENSE +202 -0
  142. pure_patchright-1.62.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,85 @@
1
+ from patchright._impl._connection import Channel
2
+ from patchright._impl._helper import MouseButton, locals_to_params
3
+
4
+
5
+ class Keyboard:
6
+ def __init__(self, channel: Channel) -> None:
7
+ self._channel = channel
8
+ self._loop = channel._connection._loop
9
+ self._dispatcher_fiber = channel._connection._dispatcher_fiber
10
+
11
+ async def down(self, key: str) -> None:
12
+ await self._channel.send("keyboardDown", None, locals_to_params(locals()))
13
+
14
+ async def up(self, key: str) -> None:
15
+ await self._channel.send("keyboardUp", None, locals_to_params(locals()))
16
+
17
+ async def insert_text(self, text: str) -> None:
18
+ await self._channel.send("keyboardInsertText", None, locals_to_params(locals()))
19
+
20
+ async def type(self, text: str, delay: float = None) -> None:
21
+ await self._channel.send("keyboardType", None, locals_to_params(locals()))
22
+
23
+ async def press(self, key: str, delay: float = None) -> None:
24
+ await self._channel.send("keyboardPress", None, locals_to_params(locals()))
25
+
26
+
27
+ class Mouse:
28
+ def __init__(self, channel: Channel) -> None:
29
+ self._channel = channel
30
+ self._loop = channel._connection._loop
31
+ self._dispatcher_fiber = channel._connection._dispatcher_fiber
32
+
33
+ async def move(self, x: float, y: float, steps: int = None) -> None:
34
+ await self._channel.send("mouseMove", None, locals_to_params(locals()))
35
+
36
+ async def down(self, button: MouseButton = None, clickCount: int = None) -> None:
37
+ await self._channel.send("mouseDown", None, locals_to_params(locals()))
38
+
39
+ async def up(self, button: MouseButton = None, clickCount: int = None) -> None:
40
+ await self._channel.send("mouseUp", None, locals_to_params(locals()))
41
+
42
+ async def _click(
43
+ self,
44
+ x: float,
45
+ y: float,
46
+ delay: float = None,
47
+ button: MouseButton = None,
48
+ clickCount: int = None,
49
+ title: str = None,
50
+ ) -> None:
51
+ await self._channel.send(
52
+ "mouseClick", None, locals_to_params(locals()), title=title
53
+ )
54
+
55
+ async def click(
56
+ self,
57
+ x: float,
58
+ y: float,
59
+ delay: float = None,
60
+ button: MouseButton = None,
61
+ clickCount: int = None,
62
+ ) -> None:
63
+ params = locals()
64
+ del params["self"]
65
+ await self._click(**params)
66
+
67
+ async def dblclick(
68
+ self, x: float, y: float, delay: float = None, button: MouseButton = None
69
+ ) -> None:
70
+ await self._click(
71
+ x, y, delay=delay, button=button, clickCount=2, title="Double click"
72
+ )
73
+
74
+ async def wheel(self, deltaX: float, deltaY: float) -> None:
75
+ await self._channel.send("mouseWheel", None, locals_to_params(locals()))
76
+
77
+
78
+ class Touchscreen:
79
+ def __init__(self, channel: Channel) -> None:
80
+ self._channel = channel
81
+ self._loop = channel._connection._loop
82
+ self._dispatcher_fiber = channel._connection._dispatcher_fiber
83
+
84
+ async def tap(self, x: float, y: float) -> None:
85
+ await self._channel.send("touchscreenTap", None, locals_to_params(locals()))
@@ -0,0 +1,297 @@
1
+ import base64
2
+ import collections.abc
3
+ import datetime
4
+ import math
5
+ import struct
6
+ import traceback
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
9
+ from urllib.parse import ParseResult, urlparse, urlunparse
10
+ from patchright._impl._connection import Channel, ChannelOwner, from_channel
11
+ from patchright._impl._errors import Error, is_target_closed_error
12
+ from patchright._impl._map import Map
13
+
14
+ if TYPE_CHECKING:
15
+ from patchright._impl._element_handle import ElementHandle
16
+ Serializable = Any
17
+
18
+
19
+ class VisitorInfo:
20
+ visited: Map[Any, int]
21
+ last_id: int
22
+
23
+ def __init__(self) -> None:
24
+ self.visited = Map()
25
+ self.last_id = 0
26
+
27
+ def visit(self, obj: Any) -> int:
28
+ assert obj not in self.visited
29
+ self.last_id += 1
30
+ self.visited[obj] = self.last_id
31
+ return self.last_id
32
+
33
+
34
+ class JSHandle(ChannelOwner):
35
+ def __init__(
36
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
37
+ ) -> None:
38
+ super().__init__(parent, type, guid, initializer)
39
+ self._preview = self._initializer["preview"]
40
+ self._channel.on(
41
+ "previewUpdated", lambda params: self._on_preview_updated(params["preview"])
42
+ )
43
+
44
+ def __repr__(self) -> str:
45
+ return f"<JSHandle preview={self._preview}>"
46
+
47
+ def __str__(self) -> str:
48
+ return self._preview
49
+
50
+ def _on_preview_updated(self, preview: str) -> None:
51
+ self._preview = preview
52
+
53
+ async def evaluate(
54
+ self,
55
+ expression: str,
56
+ arg: Serializable = None,
57
+ *,
58
+ isolatedContext: Optional[bool] = True,
59
+ ) -> Any:
60
+ return parse_result(
61
+ await self._channel.send(
62
+ "evaluateExpression",
63
+ None,
64
+ dict(
65
+ expression=expression,
66
+ arg=serialize_argument(arg),
67
+ isolatedContext=isolatedContext,
68
+ ),
69
+ )
70
+ )
71
+
72
+ async def evaluate_handle(
73
+ self,
74
+ expression: str,
75
+ arg: Serializable = None,
76
+ *,
77
+ isolatedContext: Optional[bool] = True,
78
+ ) -> "JSHandle":
79
+ return from_channel(
80
+ await self._channel.send(
81
+ "evaluateExpressionHandle",
82
+ None,
83
+ dict(
84
+ expression=expression,
85
+ arg=serialize_argument(arg),
86
+ isolatedContext=isolatedContext,
87
+ ),
88
+ )
89
+ )
90
+
91
+ async def get_property(self, propertyName: str) -> "JSHandle":
92
+ return from_channel(
93
+ await self._channel.send("getProperty", None, dict(name=propertyName))
94
+ )
95
+
96
+ async def get_properties(self) -> Dict[str, "JSHandle"]:
97
+ return {
98
+ prop["name"]: from_channel(prop["value"])
99
+ for prop in await self._channel.send("getPropertyList", None)
100
+ }
101
+
102
+ def as_element(self) -> Optional["ElementHandle"]:
103
+ return None
104
+
105
+ async def dispose(self) -> None:
106
+ try:
107
+ await self._channel.send("dispose", None)
108
+ except Exception as e:
109
+ if not is_target_closed_error(e):
110
+ raise e
111
+
112
+ async def json_value(self) -> Any:
113
+ return parse_result(await self._channel.send("jsonValue", None))
114
+
115
+
116
+ def serialize_value(
117
+ value: Any, handles: List[Channel], visitor_info: Optional[VisitorInfo] = None
118
+ ) -> Any:
119
+ if visitor_info is None:
120
+ visitor_info = VisitorInfo()
121
+ if isinstance(value, JSHandle):
122
+ h = len(handles)
123
+ handles.append(value._channel)
124
+ return dict(h=h)
125
+ if value is None:
126
+ return dict(v="null")
127
+ if isinstance(value, float):
128
+ if value == float("inf"):
129
+ return dict(v="Infinity")
130
+ if value == float("-inf"):
131
+ return dict(v="-Infinity")
132
+ if value == float("-0"):
133
+ return dict(v="-0")
134
+ if math.isnan(value):
135
+ return dict(v="NaN")
136
+ if isinstance(value, datetime.datetime):
137
+ return {
138
+ "d": datetime.datetime.strftime(
139
+ value.astimezone(datetime.timezone.utc), "%Y-%m-%dT%H:%M:%S.%fZ"
140
+ )
141
+ }
142
+ if isinstance(value, Exception):
143
+ return {
144
+ "e": {
145
+ "m": str(value),
146
+ "n": value.name or ""
147
+ if isinstance(value, Error)
148
+ else value.__class__.__name__,
149
+ "s": value.stack or ""
150
+ if isinstance(value, Error)
151
+ else "".join(
152
+ traceback.format_exception(type(value), value=value, tb=None)
153
+ ),
154
+ }
155
+ }
156
+ if isinstance(value, bool):
157
+ return {"b": value}
158
+ if isinstance(value, (int, float)):
159
+ return {"n": value}
160
+ if isinstance(value, str):
161
+ return {"s": value}
162
+ if isinstance(value, ParseResult):
163
+ return {"u": urlunparse(value)}
164
+ if value in visitor_info.visited:
165
+ return dict(ref=visitor_info.visited[value])
166
+ if isinstance(value, collections.abc.Sequence) and (not isinstance(value, str)):
167
+ id = visitor_info.visit(value)
168
+ a = []
169
+ for e in value:
170
+ a.append(serialize_value(e, handles, visitor_info))
171
+ return dict(a=a, id=id)
172
+ if isinstance(value, dict):
173
+ id = visitor_info.visit(value)
174
+ o = []
175
+ for name in value:
176
+ o.append(
177
+ {"k": name, "v": serialize_value(value[name], handles, visitor_info)}
178
+ )
179
+ return dict(o=o, id=id)
180
+ return dict(v="undefined")
181
+
182
+
183
+ def serialize_argument(arg: Serializable = None) -> Any:
184
+ handles: List[Channel] = []
185
+ value = serialize_value(arg, handles)
186
+ return dict(value=value, handles=handles)
187
+
188
+
189
+ def parse_value(value: Any, refs: Optional[Dict[int, Any]] = None) -> Any:
190
+ if refs is None:
191
+ refs = {}
192
+ if value is None:
193
+ return None
194
+ if isinstance(value, dict):
195
+ if "ref" in value:
196
+ return refs[value["ref"]]
197
+ if "v" in value:
198
+ v = value["v"]
199
+ if v == "Infinity":
200
+ return float("inf")
201
+ if v == "-Infinity":
202
+ return float("-inf")
203
+ if v == "-0":
204
+ return float("-0")
205
+ if v == "NaN":
206
+ return float("nan")
207
+ if v == "undefined":
208
+ return None
209
+ if v == "null":
210
+ return None
211
+ return v
212
+ if "u" in value:
213
+ return urlparse(value["u"])
214
+ if "bi" in value:
215
+ return int(value["bi"])
216
+ if "e" in value:
217
+ error = Error(value["e"]["m"])
218
+ error._name = value["e"]["n"]
219
+ error._stack = value["e"]["s"]
220
+ return error
221
+ if "a" in value:
222
+ a: List = []
223
+ refs[value["id"]] = a
224
+ for e in value["a"]:
225
+ a.append(parse_value(e, refs))
226
+ return a
227
+ if "d" in value:
228
+ return datetime.datetime.strptime(
229
+ value["d"], "%Y-%m-%dT%H:%M:%S.%fZ"
230
+ ).replace(tzinfo=datetime.timezone.utc)
231
+ if "o" in value:
232
+ o: Dict = {}
233
+ refs[value["id"]] = o
234
+ for e in value["o"]:
235
+ o[e["k"]] = parse_value(e["v"], refs)
236
+ return o
237
+ if "n" in value:
238
+ return value["n"]
239
+ if "s" in value:
240
+ return value["s"]
241
+ if "b" in value:
242
+ return value["b"]
243
+ if "ta" in value:
244
+ encoded_bytes = value["ta"]["b"]
245
+ decoded_bytes = base64.b64decode(encoded_bytes)
246
+ array_type = value["ta"]["k"]
247
+ if array_type == "i8":
248
+ word_size = 1
249
+ fmt = "b"
250
+ elif array_type == "ui8" or array_type == "ui8c":
251
+ word_size = 1
252
+ fmt = "B"
253
+ elif array_type == "i16":
254
+ word_size = 2
255
+ fmt = "h"
256
+ elif array_type == "ui16":
257
+ word_size = 2
258
+ fmt = "H"
259
+ elif array_type == "i32":
260
+ word_size = 4
261
+ fmt = "i"
262
+ elif array_type == "ui32":
263
+ word_size = 4
264
+ fmt = "I"
265
+ elif array_type == "f32":
266
+ word_size = 4
267
+ fmt = "f"
268
+ elif array_type == "f64":
269
+ word_size = 8
270
+ fmt = "d"
271
+ elif array_type == "bi64":
272
+ word_size = 8
273
+ fmt = "q"
274
+ elif array_type == "bui64":
275
+ word_size = 8
276
+ fmt = "Q"
277
+ else:
278
+ raise ValueError(f"Unsupported array type: {array_type}")
279
+ byte_len = len(decoded_bytes)
280
+ if byte_len % word_size != 0:
281
+ raise ValueError(
282
+ f"Decoded bytes length {byte_len} is not a multiple of word size {word_size}"
283
+ )
284
+ if byte_len == 0:
285
+ return []
286
+ array_len = byte_len // word_size
287
+ format_string = f"<{array_len}{fmt}"
288
+ return list(struct.unpack(format_string, decoded_bytes))
289
+ return value
290
+
291
+
292
+ def parse_result(result: Any) -> Any:
293
+ return parse_value(result)
294
+
295
+
296
+ def add_source_url_to_script(source: str, path: Union[str, Path]) -> str:
297
+ return source
@@ -0,0 +1,55 @@
1
+ import asyncio
2
+ from typing import Dict, Optional, cast
3
+ from pyee.asyncio import AsyncIOEventEmitter
4
+ from patchright._impl._connection import Channel
5
+ from patchright._impl._errors import TargetClosedError
6
+ from patchright._impl._helper import Error, ParsedMessagePayload
7
+ from patchright._impl._transport import Transport
8
+
9
+
10
+ class JsonPipeTransport(AsyncIOEventEmitter, Transport):
11
+ def __init__(self, loop: asyncio.AbstractEventLoop, pipe_channel: Channel) -> None:
12
+ super().__init__(loop)
13
+ Transport.__init__(self, loop)
14
+ self._stop_requested = False
15
+ self._pipe_channel = pipe_channel
16
+
17
+ def request_stop(self) -> None:
18
+ self._stop_requested = True
19
+ self._pipe_channel.send_no_reply("close", None, {})
20
+
21
+ def dispose(self) -> None:
22
+ self.on_error_future.cancel()
23
+ self._stopped_future.cancel()
24
+
25
+ async def wait_until_stopped(self) -> None:
26
+ await self._stopped_future
27
+
28
+ async def connect(self) -> None:
29
+ self._stopped_future: asyncio.Future = asyncio.Future()
30
+
31
+ def handle_message(message: Dict) -> None:
32
+ if self._stop_requested:
33
+ return
34
+ self.on_message(cast(ParsedMessagePayload, message))
35
+
36
+ def handle_closed(reason: Optional[str]) -> None:
37
+ self.emit("close", reason)
38
+ if reason:
39
+ self.on_error_future.set_exception(TargetClosedError(reason))
40
+ self._stopped_future.set_result(None)
41
+
42
+ self._pipe_channel.on(
43
+ "message", lambda params: handle_message(params["message"])
44
+ )
45
+ self._pipe_channel.on(
46
+ "closed", lambda params: handle_closed(params.get("reason"))
47
+ )
48
+
49
+ async def run(self) -> None:
50
+ await self._stopped_future
51
+
52
+ def send(self, message: Dict) -> None:
53
+ if self._stop_requested:
54
+ raise Error("Playwright connection closed")
55
+ self._pipe_channel.send_no_reply("send", None, {"message": message})
@@ -0,0 +1,73 @@
1
+ import base64
2
+ from typing import Dict, List, Optional, cast
3
+ from patchright._impl._api_structures import HeadersArray
4
+ from patchright._impl._connection import ChannelOwner, StackFrame
5
+ from patchright._impl._helper import HarLookupResult, locals_to_params
6
+
7
+
8
+ class LocalUtils(ChannelOwner):
9
+ def __init__(
10
+ self, parent: ChannelOwner, type: str, guid: str, initializer: Dict
11
+ ) -> None:
12
+ super().__init__(parent, type, guid, initializer)
13
+ self.devices = {
14
+ device["name"]: parse_device_descriptor(device["descriptor"])
15
+ for device in initializer["deviceDescriptors"]
16
+ }
17
+
18
+ async def zip(self, params: Dict) -> None:
19
+ await self._channel.send("zip", None, params)
20
+
21
+ async def har_open(self, file: str) -> None:
22
+ params = locals_to_params(locals())
23
+ await self._channel.send("harOpen", None, params)
24
+
25
+ async def har_lookup(
26
+ self,
27
+ harId: str,
28
+ url: str,
29
+ method: str,
30
+ headers: HeadersArray,
31
+ isNavigationRequest: bool,
32
+ postData: Optional[bytes] = None,
33
+ ) -> HarLookupResult:
34
+ params = locals_to_params(locals())
35
+ if "postData" in params:
36
+ params["postData"] = base64.b64encode(params["postData"]).decode()
37
+ return cast(
38
+ HarLookupResult,
39
+ await self._channel.send_return_as_dict("harLookup", None, params),
40
+ )
41
+
42
+ async def har_close(self, harId: str) -> None:
43
+ params = locals_to_params(locals())
44
+ await self._channel.send("harClose", None, params)
45
+
46
+ async def har_unzip(self, zipFile: str, harFile: str) -> None:
47
+ params = locals_to_params(locals())
48
+ await self._channel.send("harUnzip", None, params)
49
+
50
+ async def tracing_started(
51
+ self, tracesDir: Optional[str], traceName: str, live: bool = False
52
+ ) -> str:
53
+ params = locals_to_params(locals())
54
+ return await self._channel.send("tracingStarted", None, params)
55
+
56
+ async def trace_discarded(self, stacks_id: str) -> None:
57
+ return await self._channel.send("traceDiscarded", None, {"stacksId": stacks_id})
58
+
59
+ def add_stack_to_tracing_no_reply(self, id: int, frames: List[StackFrame]) -> None:
60
+ self._channel.send_no_reply(
61
+ "addStackToTracingNoReply", None, {"callData": {"stack": frames, "id": id}}
62
+ )
63
+
64
+
65
+ def parse_device_descriptor(dict: Dict) -> Dict:
66
+ return {
67
+ "user_agent": dict["userAgent"],
68
+ "viewport": dict["viewport"],
69
+ "device_scale_factor": dict["deviceScaleFactor"],
70
+ "is_mobile": dict["isMobile"],
71
+ "has_touch": dict["hasTouch"],
72
+ "default_browser_type": dict["defaultBrowserType"],
73
+ }