diff --git a/.gitignore b/.gitignore index 2815ae6..12ce418 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,15 @@ -*.egg-info -.mypy_cache __pycache__ -venv +/build +/dist +/docs/_build +/.venv +/*.egg-info +/.ipynb_checkpoints +/.mypy_cache +/.pytest_cache +/.vscode +/.tool-versions +/test_* +/*.log +.idea +.DS_Store \ No newline at end of file diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..70a3958 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,10 @@ +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details +version: 2 + +sphinx: + configuration: docs/conf.py + +python: + version: 3.7 + install: + - requirements: docs/requirements.txt diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..69b90ef --- /dev/null +++ b/.travis.yml @@ -0,0 +1,18 @@ +language: python +dist: xenial + +git: + depth: 1 + +matrix: + include: + - python: 3.7 + +before_install: + - pip install poetry + +install: + - poetry install + +script: + - poetry run make diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f8a5884 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2018 Hyperion Gray +Copyright (c) 2022 Heraldo Lucena + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..dde37e5 --- /dev/null +++ b/Makefile @@ -0,0 +1,27 @@ +# The targets in this makefile should be executed inside Poetry, i.e. `poetry run make +# docs`. + +.PHONY: docs + +default: mypy-generate test-generate generate test-import mypy-cdp test-cdp + +docs: + $(MAKE) -C docs html + +generate: + python cdpgen/generate.py + +mypy-cdp: + mypy cdp/ + +mypy-generate: + mypy cdpgen/ + +test-cdp: + pytest test/ + +test-generate: + pytest cdpgen/ + +test-import: + python -c 'import cdp; print(cdp.accessibility)' diff --git a/README.md b/README.md index 63c5cad..8343608 100644 --- a/README.md +++ b/README.md @@ -1,359 +1,160 @@ -# Chrome Devtools Protocol (CDP) for Python +# Python CDP +#### Currently supports CDP [r1429850][2]. -_Status: this library is very alpha. Do not use it! It is not on PyPI yet but -when we get a little more stable it will be published there._ +Python CDP Generator (shortened to PyCDP) is a library that provides +Python wrappers for the types, commands, and events specified in the [Chrome +DevTools Protocol][1]. -## Overview +The Chrome DevTools Protocol provides for remote control of a web browser by +sending JSON messages over a WebSocket. That JSON format is described by a +machine-readable specification. This specification is used to automatically +generate the classes and methods found in this library. -This repository contains Python type wrappers for the Chrome DevTools Protocol -(CDP), which is a JSON RPC protocol used for driving Chrome in headless browsing -mode. This code is all generated from the CDP specification, which is itself a -set of JSON documents that define the protocols base types, events, and -commands. - -**This library does not perform any I/O!** This library generates Pythonic -wrappers for all of the items defined in the protocol. These wrappers make it -easy to generate the JSON messages that are sent to the browser and parse the -responses. The benefits of using this library versus writing JSON directly are: - -* Writing in Python is less tedious: there are fewer braces and quotes to worry - about balancing than in JSON. -* Python will help avoid typos: it knows what types are defined and will raise - `AttributeError` if you make a typo. -* It can also help your IDE to autocomplete type names, commands, arguments, - etc. - -Most developers should use a higher level library that wraps this library and -handles the protocol I/O. You should only use this library if you want to write -such a wrapper library yourself. - -## Basic Types - -CDP has several primitive types such as `string`, `integer`, and `object`. For -basic types like `string` and `integer`, this library generates a trivial -wrapper around the type. For example, CDP has the following basic type: - -``` -{ - "types": [ - { - "id": "ScriptIdentifier", - "description": "Unique script identifier.", - "type": "string" - }, - ... - ] -} -``` - -This CDP type corresponds to the following Python code: - -```python -class ScriptIdentifier(str): - ''' - Unique script identifier. - ''' - @classmethod - def from_json(cls, json): - return cls(json) - - def __repr__(self): - return 'ScriptIdentifier({})'.format(str.__repr__(self)) +## Installation +You can install this library as a dependency on your project with: ``` - -The type extends a built-in type (`str`) and adds a `repr()` that is helpful -when debugging or logging. It also creates a `from_json()` method that is -used for generating instances of the type from JSON representations. Although -this method is trivial for these basic types, more complex types also implement -the same interface for converting JSON into Python instances. - -CDP uses the `enum` type to describe collections of related string constants. -Here is an example of a CDP enum: - -```json -{ - "id": "ClientNavigationReason", - "experimental": true, - "type": "string", - "enum": [ - "formSubmissionGet", - "formSubmissionPost", - "httpHeaderRefresh", - "scriptInitiated", - "metaTagRefresh", - "pageBlockInterstitial", - "reload" - ] -} +pip install git+https://github.com/HMaker/python-cdp.git@latest ``` +Change the git tag `@latest` if you need another version. To install for development, clone this +repository, install [Poetry][5] package manager and run `poetry install` to install dependencies. -This gets converted into a Python enumeration: - +## Usage +If all you want is automate Chrome right now, PyCDP includes a low-level client for asyncio and twisted: ```python -class ClientNavigationReason(enum.Enum): - FORM_SUBMISSION_GET = "formSubmissionGet" - FORM_SUBMISSION_POST = "formSubmissionPost" - HTTP_HEADER_REFRESH = "httpHeaderRefresh" - SCRIPT_INITIATED = "scriptInitiated" - META_TAG_REFRESH = "metaTagRefresh" - PAGE_BLOCK_INTERSTITIAL = "pageBlockInterstitial" - RELOAD = "reload" - - def to_json(self) -> str: - return self.value -``` - -The generated class inherits from `Enum` so that its members have the expected -type, e.g. `ClientNavigationReason` instead of `str`. Each member is upper snake -case. The class implements the same `to_json()` interface as the other types. - -CDP uses the `object` type to describe more complicated data types. Here's an -example: - -``` -{ - "types": [ - { - "id": "FrameTree", - "description": "Information about the Frame hierarchy.", - "type": "object", - "properties": [ - { - "name": "frame", - "description": "Frame information for this tree item.", - "$ref": "Frame" - }, - { - "name": "childFrames", - "description": "Child frames.", - "optional": true, - "type": "array", - "items": { - "$ref": "FrameTree" - } - } - ] - }, - ... - ] -} -``` - -This corresponds to the following Python code: - -```python3 -@dataclass -class FrameTree: - ''' - Information about the Frame hierarchy. - ''' - #: Frame information for this tree item. - frame: Frame - - #: Child frames. - child_frames: typing.List['FrameTree'] - - @classmethod - def from_json(cls, json): - return cls( - frame=Frame.from_json(json.get('frame')), - child_frames=[FrameTree.from_json(i) for i in json.get('childFrames')], - ) -``` - -The generated Python code is a dataclass, complete with docstring, type -annotations, and a non-trivial `from_json()` method. Notice that protocol -fields like `child_frames` are snake-cased: it is automatically converted to -camel-case when generating JSON and vice-versa. - -## Commands - -The CDP commands are the trickiest part of this library, because each "command" -is really a remote procedure call over a network socket! Here's an example of a -CDP command specification from the `Target` domain: - -``` -{ - "commands": [ - { - "name": "getTargetInfo", - "description": "Returns information about a target.", - "experimental": true, - "parameters": [ - { - "name": "targetId", - "optional": true, - "$ref": "TargetID" - } - ], - "returns": [ - { - "name": "targetInfo", - "$ref": "TargetInfo" - } - ] - }, - ... - ] -} -``` - -This leads to the following generated Python code: - -```python3 - def get_target_info(target_id: TargetID) -> typing.Generator[dict,dict,TargetInfo]: - ''' - Returns information about a target. - - :param target_id: - :returns: - ''' - - cmd_dict = { - 'method': 'Target.getTargetInfo', - 'params': { - 'targetId': target_id, - } - } - response = yield cmd_dict - return TargetInfo.from_json(response['targetInfo']) -``` - -First, notice that all commands in the `Target` domain are generated as -functions inside of the module `cdp.target.commands` on a class called `Target`. -Therefore, a fully-qualified CDP command command like `Target.getTargetInfo` -translates to a Python function called `cdp.target.commands.get_target_info`. - -Second, notice that the command has the proper type annotations and docstring -derived from the CDP metadata. Depending on your IDE, this should help with -autocompletion. - -Third—and this is the tricky bit—we have a single function that can both -generate a CDP JSON command and also parse the response without doing any actual -I/O in between! In order to accommodate this goal, each command is actually a -_generator function_. To run a command, you should do the following: - -1. Invoke the function to obtain a generator `gen`. -2. Get the request by calling `request = gen.send(None)`. -3. Send the request to Chrome using whatever I/O framework you want and wait for - the response. (Notice that commands are multiplexed on a single WebSocket, so - you will also need to do some bookkeeping to track which responses correspond - to which requests. That logic is outside the scope of this explanation.) -4. Send the response back to the generator by calling `gen.send(response)`. -5. The generator will raise `StopIteration`. You should catch this exception, - and the command's result is stored in the exception's `value` field. - -Here's some sample code. This code sets the command ID to zero every time. As -mentioned above, you'll need to generate unique command IDs if you want to send -multiple commands concurrently. - +import asyncio +from pycdp import cdp +from pycdp.browser import ChromeLauncher +from pycdp.asyncio import connect_cdp + +async def main(): + chrome = ChromeLauncher( + binary='/usr/bin/google-chrome', # linux path + args=['--remote-debugging-port=9222', '--incognito'] + ) + # ChromeLauncher.launch() is blocking, run it on a background thread + await asyncio.get_running_loop().run_in_executor(None, chrome.launch) + conn = await connect_cdp('http://localhost:9222') + target_id = await conn.execute(cdp.target.create_target('about:blank')) + target_session = await conn.connect_session(target_id) + await target_session.execute(cdp.page.enable()) + # you may use "async for target_session.listen()" to listen multiple events, here we listen just a single event. + with target_session.safe_wait_for(cdp.page.DomContentEventFired) as navigation: + await target_session.execute(cdp.page.navigate('https://chromedevtools.github.io/devtools-protocol/')) + await navigation + dom = await target_session.execute(cdp.dom.get_document()) + node = await target_session.execute(cdp.dom.query_selector(dom.node_id, 'p')) + js_node = await target_session.execute(cdp.dom.resolve_node(node)) + print((await target_session.execute(cdp.runtime.call_function_on('function() {return this.innerText;}', js_node.object_id, return_by_value=True)))[0].value) + await target_session.execute(cdp.page.close()) + await conn.close() + await asyncio.get_running_loop().run_in_executor(None, chrome.kill) + +asyncio.run(main()) +``` +the twisted client requires [twisted][6] and [autobahn][7] packages: ```python -from cdp import Target, TargetID - -def run_command(cmd): - # Run the generator once to get a request. - request_dict = cmd.send(None) - request_dict['id'] = 0 - request_str = json.dumps(request_dict) - # vvv Use whatever I/O framework you want. vvv - mysock.send(request_str) - response_str = mysock.recv() - # ^^^ Use whatever I/O framework you want. ^^^ - response_dict = json.loads(response_str) - try: - cmd.send(response_dict) - raise Exception('Should not reach this line!') - except StopIteration as exit: - response = exit.value - return response - -target_id = TargetID('F86FCB9B3890EB413FAC5DD9DD150E6F') -target_info = run_command(Target.get_target_info(target_info)) -print(target_info) -``` - -The script above prints something like this: - -``` -TargetInfo(target_id=TargetID('F86FCB9B3890EB413FAC5DD9DD150E6F'), type_='page', -title='New Tab', url='chrome://newtab/', attached=False, opener_id=TargetID('None'), -browser_context_id=BrowserContextID('B26C01EBDA29AC04BE3966B4E50F3F49')) -``` - -## Events - -While each command elicits a single response, the CDP protocol provides _events_ -as a mechanism for the browser to send information to the client that is not -necessarily tied to a single command/response pair. Here's an example of a CDP -event definition: - -```json -{ - "name": "attachedToTarget", - "description": "Issued when attached to target because of auto-attach or `attachToTarget` command.", - "experimental": true, - "parameters": [ - { - "name": "sessionId", - "description": "Identifier assigned to the session used to send/receive messages.", - "$ref": "SessionID" - }, - { - "name": "targetInfo", - "$ref": "TargetInfo" - }, - { - "name": "waitingForDebugger", - "type": "boolean" - } - ] -} -``` - -This gets translated into the following Python code: - +from twisted.python.log import err +from twisted.internet import reactor, defer, threads +from pycdp import cdp +from pycdp.browser import ChromeLauncher +from pycdp.twisted import connect_cdp + +async def main(): + chrome = ChromeLauncher( + binary='C:\Program Files\Google\Chrome\Application\chrome.exe', # windows path + args=['--remote-debugging-port=9222', '--incognito'] + ) + await threads.deferToThread(chrome.launch) + conn = await connect_cdp('http://localhost:9222', reactor) + target_id = await conn.execute(cdp.target.create_target('about:blank')) + target_session = await conn.connect_session(target_id) + await target_session.execute(cdp.page.enable()) + await target_session.execute(cdp.page.navigate('https://chromedevtools.github.io/devtools-protocol/')) + async with target_session.wait_for(cdp.page.DomContentEventFired): + dom = await target_session.execute(cdp.dom.get_document()) + node = await target_session.execute(cdp.dom.query_selector(dom.node_id, 'p')) + js_node = await target_session.execute(cdp.dom.resolve_node(node)) + print((await target_session.execute(cdp.runtime.call_function_on('function() {return this.innerText;}', js_node.object_id, return_by_value=True)))[0].value) + await target_session.execute(cdp.page.close()) + await conn.close() + await threads.deferToThread(chrome.kill) + +def main_error(failure): + err(failure) + reactor.stop() + +d = defer.ensureDeferred(main()) +d.addErrback(main_error) +d.addCallback(lambda *args: reactor.stop()) +reactor.run() +``` + +You also can use just the built-in CDP type wrappers with `import pycdp.cdp` on your own client implementation. If you want to try a different CDP version you can build new type wrappers with `cdpgen` command: +``` +usage: cdpgen + +Generate Python types for the Chrome Devtools Protocol (CDP) specification. + +optional arguments: + -h, --help show this help message and exit + --browser-protocol BROWSER_PROTOCOL + JSON file for the browser protocol + --js-protocol JS_PROTOCOL + JSON file for the javascript protocol + --output OUTPUT output path for the generated Python modules + +JSON files for the CDP spec can be found at https://github.com/ChromeDevTools/devtools-protocol/tree/master/json +``` +Example: +```sh +cdpgen --browser-protocol browser_protocol.json --js-protocol js_protocol.json --output /tmp/cdp +``` +You can then include the `/tmp/cdp` package in your project and import it like the builtin CDP types. + +### Updating built-in CDP wrappers +The `update-cdp.sh` script generates the builtin CDP wrappers, the `pycdp.cdp` package, by automatically fetching CDP protocol specifications from the [ChromeDevTools][8] repostitory. + +**To generate types for the latest version:** +```shell +./update-cdp.sh +``` +**To generate types for a specific version, you must provide full commit hash:** +```shell +./update-cdp.sh 4dd6c67776f43f75bc9b19f09618c151621c6ed9 +``` +P.S. Don't forget to make it executable by running `chmod +x update-cdp.sh` + +## Implementation of a CDP client +The `pycdp.cdp` package follows same structure of CDP domains, each domain is a Python module and each command a function in that module. + +Each function is a generator with a single yield which is a Python dict, on the CDP wire format, +containing the message that should be sent to the browser, on resumption the generator receives the message from browser: ```python -@dataclass -class AttachedToTarget: - ''' - Issued when attached to target because of auto-attach or `attachToTarget` command. - ''' - #: Issued when attached to target because of auto-attach or `attachToTarget` command. - session_id: SessionID - - #: Issued when attached to target because of auto-attach or `attachToTarget` command. - target_info: TargetInfo - - #: Issued when attached to target because of auto-attach or `attachToTarget` command. - waiting_for_debugger: bool - - @classmethod - def from_json(cls, json: dict) -> 'AttachedToTarget': - return cls( - session_id=SessionID.from_json(response['sessionId']), - target_info=TargetInfo.from_json(response['targetInfo']), - waiting_for_debugger=bool(response['waitingForDebugger']), - ) -``` - -The generated code consists of a dataclass the contains the event's attributes. -The dataclass also contains a `from_json()` class method (similar to the -`from_json()` class method that each type has) to construct an instance of the -object from a JSON dictionary. The library also has a convenience function -`cdp.parse_json_event(json: dict)` that will take a JSON dictionary, look up the -corresponding event class, instantiate it with the parameters contained in -the JSON dictionary, and return the instance. - -## Build - -The protocol specifications and a build tool are stored in the `build` -directory. Before running the build tool, install the build requirements in -requirements.txt. - -Run the build tool as follows: - -``` -$ python build/generate.py -``` - -This will write all of the generated files into the `cdp` package directory. +import cdp + +# Get all CDP targets +command = cdp.target.get_targets() # this is a generator +raw_cdp_request = next(command) # receive the yield +raw_cdp_response = send_cdp_request(raw_cdp_request) # you implement send_cdp_request, raw_cdp_request is the JSON object that should be sent to browser +try: + command.send(raw_cdp_response) # send the response to the generator where raw_cdp_response is the JSON object received from browser, it will raise StopIteration + raise RuntimeError("the generator didnt exit!") # this shouldnt happen +except StopIteration as result: + response = result.value # the parsed response to Target.get_targets() command +print(response) +``` +For implementation details check out the [docs][3]. + +
+
+PyCDP is licensed under the MIT License. +
+ +[1]: https://chromedevtools.github.io/devtools-protocol/ +[2]: https://github.com/ChromeDevTools/devtools-protocol/tree/e1bdcc8cda9709838002a1516058ec8b266cbe88 +[3]: docs/getting_started.rst +[4]: https://github.com/hyperiongray/trio-chrome-devtools-protocol +[5]: https://python-poetry.org/docs/ +[6]: https://pypi.org/project/Twisted/ +[7]: https://pypi.org/project/autobahn/ +[8]: https://github.com/ChromeDevTools/devtools-protocol diff --git a/build/generate.py b/build/generate.py deleted file mode 100644 index 09a8385..0000000 --- a/build/generate.py +++ /dev/null @@ -1,752 +0,0 @@ -import json -import logging -import operator -import os -from pathlib import Path -import typing - -import inflection - - -log_level = getattr(logging, os.environ.get('LOG_LEVEL', 'info').upper()) -logging.basicConfig(level=log_level) -logger = logging.getLogger('generate') - -init_header = '''\'\'\' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. -\'\'\' -''' - -module_header = '''\'\'\' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: {} -Experimental: {} -\'\'\' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -''' - - -def clear_dirs(package_path): - ''' Remove generated code. ''' - def rmdir(path): - for subpath in path.iterdir(): - if subpath.is_file(): - subpath.unlink() - elif subpath.is_dir(): - rmdir(subpath) - path.rmdir() - - try: - (package_path / '__init__.py').unlink() - except FileNotFoundError: - pass - - for subpath in package_path.iterdir(): - if subpath.is_dir(): - rmdir(subpath) - - -def parse(json_path, output_path): - ''' - Parse JSON protocol description and generate module files. - - :param Path json_path: path to a JSON CDP schema - :param Path output_path: a directory path to create the modules in - :returns: a list of 2-tuples containing (module name, list of exported - symbols) - ''' - with json_path.open() as json_file: - schema = json.load(json_file) - version = schema['version'] - assert (version['major'], version['minor']) == ('1', '3') - modules = list() - for domain in schema['domains']: - modules.append( - generate_domain_module(domain, output_path)) - return modules - - -def generate_domain_module(domain, output_path): - ''' - Generate a Python module for a given CDP domain. - - :param dict domain: domain schema - :param Path output_path: a directory path to create the module in - :returns: module name and a list of exported names - ''' - name = domain['domain'] - module_name = inflection.underscore(name) - logger.info('Generating module: %s → %s.py', name, module_name) - experimental = domain.get('experimental', False) - - # The dependencies listed in the JSON don't match the actual dependencies - # encountered when building the types. So we ignore the declared - # dependencies and compute it ourself. - type_dependencies = set() - domain_types = domain.get('types', list()) - for type_ in domain_types: - for prop in type_.get('properties', list()): - dependency = get_dependency(prop) - if dependency: - type_dependencies.add(dependency) - if type_dependencies: - logger.debug('Computed type_dependencies: %s', ','.join( - type_dependencies)) - - event_dependencies = set() - domain_events = domain.get('events', list()) - for event in domain_events: - for param in event.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - event_dependencies.add(dependency) - if event_dependencies: - logger.debug('Computed event_dependencies: %s', ','.join( - event_dependencies)) - - command_dependencies = set() - domain_commands = domain.get('commands', list()) - for command in domain_commands: - for param in command.get('parameters', list()): - dependency = get_dependency(param) - if dependency: - command_dependencies.add(dependency) - for return_ in command.get('returns', list()): - dependency = get_dependency(return_) - if dependency: - command_dependencies.add(dependency) - if command_dependencies: - logger.debug('Computed command_dependencies: %s', ','.join( - command_dependencies)) - - # Generate code for this module. - module_path = output_path / module_name - module_path.mkdir(parents=True, exist_ok=True) - init_path = module_path / '__init__.py' - with init_path.open('w'): - # Zero out this file - pass - - types_path = module_path / 'types.py' - with types_path.open('w') as types_file: - types_file.write(module_header.format(module_name, experimental)) - for dependency in sorted(type_dependencies): - types_file.write(import_dependency(dependency)) - if type_dependencies: - types_file.write('\n') - type_exports, type_code = generate_types(domain_types) - types_file.write(type_code) - - events_path = module_path / 'events.py' - with events_path.open('w') as events_file: - events_file.write(module_header.format(module_name, experimental)) - events_file.write('from .types import *\n') - for dependency in sorted(event_dependencies): - events_file.write(import_dependency(dependency)) - if event_dependencies: - events_file.write('\n') - event_exports, event_code = generate_events(name, domain_events) - events_file.write(event_code) - - commands_path = module_path / 'commands.py' - with commands_path.open('w') as commands_file: - commands_file.write(module_header.format(module_name, experimental)) - commands_file.write('from .types import *\n') - for dependency in sorted(command_dependencies): - commands_file.write(import_dependency(dependency)) - if command_dependencies: - commands_file.write('\n') - command_exports, command_code = generate_commands(name, domain_commands) - commands_file.write(command_code) - - return module_name, type_exports, event_exports, command_exports - - -def get_dependency(cdp_meta): - if 'type' in cdp_meta and cdp_meta['type'] != 'array': - return None - - if 'items' in cdp_meta and 'type' in cdp_meta['items']: - return None - - if '$ref' in cdp_meta: - type_ = cdp_meta['$ref'] - elif 'items' in cdp_meta and '$ref' in cdp_meta['items']: - type_ = cdp_meta['items']['$ref'] - else: - raise Exception('Cannot get dependency: {!r}'.format(cdp_meta)) - - try: - dependency, _ = type_.split('.') - return dependency - except ValueError: - # Not a dependency on another module. - return None - - -def import_dependency(dependency): - module_name = inflection.underscore(dependency) - return 'from ..{} import types as {}\n'.format(module_name, module_name) - - -def generate_types(types): - ''' - Generate type definitions as Python code. - - :param list types: a list of CDP type definitions - :returns: a tuple (list of types, code as string) - ''' - code = '\n' - exports = list() - classes = list() - emitted_types = set() - for type_ in types: - cdp_type = type_['type'] - type_name = type_['id'] - exports.append(type_name) - description = type_.get('description') - logger.debug('Generating type %s: %s', type_name, cdp_type) - if 'enum' in type_: - code += generate_enum_type(type_) - emitted_types.add(type_name) - elif cdp_type == 'object': - classes.append(generate_class_type(type_)) - else: - code += generate_basic_type(type_) - emitted_types.add(type_name) - - # The classes have dependencies on each other, so we have to emit them in - # a specific order. If we can't resolve these dependencies after a certain - # number of iterations, it suggests a cyclical dependency that this code - # cannot handle. - tries_remaining = 1000 - while classes: - class_ = classes.pop(0) - if not class_['children']: - code += class_['code'] - emitted_types.add(class_['name']) - continue - if all(child in emitted_types for child in class_['children']): - code += class_['code'] - emitted_types.add(class_['name']) - continue - classes.append(class_) - tries_remaining -= 1 - if not tries_remaining: - logger.error('Class resolution failed. Emitted these types: %s', - emitted_types) - logger.error('Class resolution failed. Cannot emit these types: %s', - json.dumps(classes, indent=2)) - raise Exception('Failed to resolve class dependencies.' - ' See output above.') - - return exports, code - - -def inline_doc(description, indent=0): - ''' - Generate an inline doc, e.g. ``#: This type is a ...`` - - :param str description: - :returns: a string - ''' - if not description: - return '' - - i = ' ' * indent - lines = ['{}#: {}\n'.format(i, l) for l in description.split('\n')] - return ''.join(lines) - - -def docstring(description, indent=4): - ''' - Generate a docstring from a description. - - :param str description: - :param int indent: the number of spaces to indent the docstring - ''' - if not description: - return '' - - i = ' ' * indent - start_stop = "{}'''".format(i) - lines = [start_stop] - for line in description.split('\n'): - lines.append('{}{}'.format(i, line)) - lines.append(start_stop) - return '\n'.join(lines) + '\n' - - -def generate_enum_type(type_): - ''' - Generate an "enum" type. - - Enums are handled by making a python class that contains only class members. - Each class member is upper snaked case, e.g. ``MyTypeClass.MY_ENUM_VALUE`` - and is assigned a string value from the CDP metadata. - - :param dict type_: CDP type metadata - ''' - code = '' - if type_['type'] != 'string': - raise Exception('Unexpected enum type: {!r}'.format(type_)) - code += 'class {}(enum.Enum):\n'.format(type_['id']) - description = type_.get('description') - code += docstring(description) - for enum_member in type_['enum']: - snake_case = inflection.underscore(enum_member).upper() - code += ' {} = "{}"\n'.format(snake_case, enum_member) - code += '\n' - code += ' def to_json(self) -> str:\n' - code += ' return self.value\n' - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: str) -> '{}':\n".format(type_['id']) - code += ' return cls(json)\n' - code += '\n\n' - return code - - -def get_python_type(cdp_meta): - ''' - Generate a name for the Python type that corresponds to the the given CDP - type. - - :param dict cdp_meta: CDP metadata for a type or property - :returns: Python type as a string - ''' - if 'type' in cdp_meta: - cdp_type = cdp_meta['type'] - if cdp_type == 'array': - py_type = 'typing.List' - try: - cdp_nested_type = get_python_type(cdp_meta['items']) - if '.' in cdp_nested_type: - domain, subtype = cdp_nested_type.split('.') - cdp_nested_type = '{}.{}'.format( - inflection.underscore(domain), subtype) - py_type += "['{}']".format(cdp_nested_type) - except KeyError: - # No nested type: ignore. - pass - else: - py_type = { - 'any': 'typing.Any', - 'boolean': 'bool', - 'integer': 'int', - 'object': 'dict', - 'number': 'float', - 'string': 'str', - }[cdp_type] - return py_type - - if '$ref' in cdp_meta: - prop_type = cdp_meta['$ref'] - if '.' in prop_type: - # If the type lives in another module, then we need to - # snake_case the module name and it should *not* be added to the - # list of child classes that is used for dependency resolution. - other_module, other_type = prop_type.split('.') - prop_type = '{}.{}'.format(inflection.underscore(other_module), - other_type) - return prop_type - - raise Exception('Cannot get python type from CDP metadata: {!r}'.format( - cdp_meta)) - - -def is_builtin_type(python_type): - return python_type in ('bool', 'int', 'dict', 'float', 'str') - - -def generate_class_type(type_): - ''' - Generate a class type. - - Top-level types that are defined as a CDP ``object`` are turned into Python - dataclasses. - - :param dict type_: CDP type metadata - ''' - description = type_.get('description') - type_name = type_['id'] - children = set() - class_code = '@dataclass\n' - class_code += 'class {}:\n'.format(type_name) - class_code += docstring(description) - from_json = list() - properties = list() - to_json = list() - for prop in type_.get('properties', []): - prop_name = prop['name'] - optional = prop.get('optional', False) - snake_name = inflection.underscore(prop_name) - prop_code = '' - prop_description = prop.get('description') - if prop_description: - prop_code += inline_doc(prop_description, indent=4) - prop_type = get_python_type(prop) - prop_decl = prop_type - if prop_type == type_name: - # If a type refers to itself, e.g. StackTrace has a member - # called ``parent`` that is itself a StackTrace, then the type - # name must be quoted or else Python will not be able to compile - # the module. - prop_decl = "'{}'".format(prop_decl) - elif '$ref' in prop and '.' not in prop_type: - # If the type lives in this module and is not a type that refers - # to itself, then add it to the set of children so that - # inter-class dependencies can be resolved later on. - children.add(prop_type) - if optional: - prop_decl = 'typing.Optional[{}] = None'.format(prop_decl) - prop_code += ' {}: {}\n\n'.format(snake_name, prop_decl) - properties.append((prop_code, optional)) - getter = "json['{}']".format(prop_name) - if 'type' in prop: - if prop['type'] != 'array': - from_json.append((snake_name, "{}".format(getter), prop_name, - optional)) - to_json.append((snake_name, prop_name, optional, - 'self.{}'.format(snake_name))) - elif '$ref' in prop['items']: - subtype = get_python_type(prop['items']) - from_json.append((snake_name, "[{}.from_json(i) for i in {}]".format( - subtype, getter), prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - '[i.to_json() for i in self.{}]'.format(snake_name))) - elif 'type' in prop['items']: - subtype = get_python_type(prop['items']) - from_json.append((snake_name, "[i for i in {}]".format(getter), - prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - '[i for i in self.{}]'.format(snake_name))) - else: - from_json.append((snake_name, "{}.from_json({})".format( - prop_type, getter), prop_name, optional)) - to_json.append((snake_name, prop_name, optional, - 'self.{}.to_json()'.format(snake_name))) - # Sort properties so that optional properties come after required - # properties, otherwise the dataclass will raise an error. - properties.sort(key=operator.itemgetter(1)) - for prop_code, _ in properties: - class_code += prop_code - class_code += ' def to_json(self) -> T_JSON_DICT:\n' - class_code += ' json: T_JSON_DICT = {\n' - for snake_name, prop_name, optional, code in to_json: - if optional: - continue - class_code += " '{}': {},\n".format(prop_name, code) - class_code += ' }\n' - for snake_name, prop_name, optional, code in to_json: - if not optional: - continue - class_code += " if self.{} is not None:\n".format(snake_name) - class_code += " json['{}'] = {}\n".format(prop_name, code) - class_code += ' return json\n' - class_code += '\n' - class_code += ' @classmethod\n' - class_code += " def from_json(cls, json: T_JSON_DICT) -> '{}':\n".format(type_name) - for snake_name, code, prop_name, optional in from_json: - if not optional: - continue - class_code += " {} = {} if '{}' in json else None\n".format( - snake_name, code, prop_name) - class_code += ' return cls(\n' - for snake_name, code, prop_name, optional in from_json: - if optional: - class_code += " {}={},\n".format(snake_name, snake_name) - else: - class_code += " {}={},\n".format(snake_name, code) - class_code += ' )\n' - class_code += '\n' - - return { - 'name': type_name, - 'code': class_code, - # Don't emit children that live in a different module. We assume that - # modules do not have cyclical dependencies on each other. - 'children': [c for c in children if '.' not in c], - } - - -def generate_basic_type(type_): - ''' - Generate one of the "basic" types, i.e. type aliases for Python built-ins. - - :param dict type_: CDP type metadata - ''' - code = '' - cdp_type = type_['id'] - py_type = get_python_type(type_) - description = type_.get('description') - code += 'class {}({}):\n'.format(cdp_type, py_type) - code += docstring(description) - code += ' def to_json(self) -> {}:\n'.format(py_type) - code += ' return self\n' - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: {}) -> '{}':\n".format( - py_type, cdp_type) - code += ' return cls(json)\n' - code += '\n' - code += ' def __repr__(self):\n' - code += " return '{}({{}})'.format({}.__repr__(self))\n".format( - cdp_type, py_type) - code += '\n\n' - return code - - -def generate_events(domain, events): - exports = list() - code = '\n' - for event in events: - event_name = inflection.camelize(event['name'], - uppercase_first_letter=True) - parameters = event.get('parameters', list()) - code += '\n@dataclass\n' - code += 'class {}:\n'.format(event_name) - description = event.get('description') - code += docstring(description) - from_json = list() - for parameter in parameters: - name = parameter['name'] - snake_name = inflection.underscore(name) - param_description = parameter.get('description') - code += inline_doc(description, indent=4) - if 'type' in parameter: - param_decl = get_python_type(parameter) - elif '$ref' in parameter: - param_decl = parameter['$ref'] - if '.' in param_decl: - # If the type lives in another module, then we need to - # snake_case the module name and it should *not* be - # added to the list of child classes that is used for - # dependency resolution. - other_module, other_type = param_decl.split('.') - param_decl = '{}.{}'.format( - inflection.underscore(other_module), other_type) - else: - raise Exception('Cannot determing event parameter type:' - ' {!r}'.format(parameter)) - optional = parameter.get('optional', False) - if optional: - param_decl = 'typing.Optional[{}] = None'.format(param_decl) - code += ' {}: {}\n\n'.format(snake_name, param_decl) - from_json.append((name, snake_name, optional, make_return_code(parameter))) - code += ' # These fields are used for internal purposes and are not part of CDP\n' - code += " _domain = '{}'\n".format(domain) - code += " _method = '{}'\n".format(event['name']) - code += '\n' - code += ' @classmethod\n' - code += " def from_json(cls, json: dict) -> '{}':\n".format(event_name) - for name, snake_name, optional, snippet in from_json: - if not optional: - continue - code += " {} = {} if '{}' in json else None\n".format( - snake_name, snippet, name) - code += ' return cls(\n' - for name, snake_name, optional, snippet in from_json: - if optional: - code += ' {}={},\n'.format(snake_name, snake_name) - else: - code += ' {}={},\n'.format(snake_name, snippet) - code += ' )\n\n' - exports.append(event_name) - return exports, code - - -def generate_commands(domain_name, commands): - ''' - Generate command definitions as Python code. - - :param str domain_name: the CDP domain name - :param list commands: a list of CDP command definitions - :returns: a tuple (list of exported types, code as string) - ''' - code = '\n\n' - for command in commands: - command_name = command['name'] - method_name = inflection.underscore(command_name) - description = command.get('description', '') - arg_list = list() - to_json = list() - params = command.get('parameters', list()) - if params: - description += '\n' - for param in params: - param_name = param['name'] - snake_name = inflection.underscore(param_name) - param_type = get_python_type(param) - param_decl = param_type - if param.get('optional', False): - param_decl = 'typing.Optional[{}] = None'.format(param_decl) - arg_list.append('{}: {}'.format(snake_name, param_decl)) - description += '\n:param {}: {}'.format(snake_name, - param.get('description', '')) - if 'type' in param: - if param['type'] != 'array': - json_code = '{}'.format(snake_name) - elif '$ref' in param['items']: - subtype = get_python_type(param['items']) - json_code = '[i.to_json() for i in {}]'.format(snake_name) - elif 'type' in param['items']: - subtype = get_python_type(param['items']) - json_code = '[i for i in {}]'.format(snake_name) - else: - json_code = '{}.to_json()'.format(snake_name) - # convert = '' if is_builtin_type(param_type) else '.to_json()' - to_json.append((param_name, snake_name, json_code, - param.get('optional', False))) - returns = command.get('returns', list()) - if len(returns) == 0: - return_type = 'None' - elif len(returns) == 1: - return_type = get_python_type(returns[0]) - description += '\n:returns: {}'.format( - returns[0].get('description', '')) - else: - return_type = 'dict' - description += '\n:returns: a dict with the following keys:' - for return_ in returns: - optstr = '(Optional) ' if return_.get('optional', False) else '' - description += '\n * {}: {}{}'.format(return_['name'], - optstr, return_.get('description', '')) - code += 'def {}('.format(method_name) - if arg_list: - code += '\n' - for arg in arg_list: - code += ' {},\n'.format(arg) - code += ' ' - code += ') -> typing.Generator[T_JSON_DICT,T_JSON_DICT,{}]:\n'.format(return_type) - code += docstring(description, indent=4) - if to_json: - code += ' params: T_JSON_DICT = {\n' - for param_name, snake_name, json_code, optional in to_json: - if optional: - continue - code += " '{}': {},\n".format(param_name, json_code) - code += ' }\n' - for param_name, snake_name, json_code, optional in to_json: - if not optional: - continue - code += ' if {} is not None:\n'.format(snake_name) - code += " params['{}'] = {}\n".format(param_name, - json_code) - code += ' cmd_dict: T_JSON_DICT = {\n' - code += " 'method': '{}.{}',\n".format(domain_name, - command_name) - if to_json: - code += " 'params': params,\n" - code += ' }\n' - code += ' json = yield cmd_dict\n' - if len(returns) == 1: - return_ = returns[0] - return_type = get_python_type(return_) - code += ' return {}\n'.format(make_return_code(return_)) - elif len(returns) > 1: - # we should be able to refactor the first part of this if block to have something - # reusable, then we call that new thing inside of a loop in this elif block - # the only difference here is printing key names and dict syntax - code += ' result: T_JSON_DICT = {\n' - # code += ' return {\n' - for return_ in returns: - if return_.get('optional', False): - continue - return_type = get_python_type(return_) - code += " '{}': {},\n".format(return_['name'], - make_return_code(return_)) - code += ' }\n' - for return_ in returns: - if not return_.get('optional', False): - continue - code += " if '{}' in json:\n".format(return_['name']) - code += " result['{}'] = {}\n".format(return_['name'], - make_return_code(return_)) - code += ' return result\n' - code += '\n\n' - return [domain_name], code - - -def make_return_code(return_): - ''' - Make a snippet of code that retuns a value inside of a ``from_json()`` - method. - - :param dict return_: the CDP metadata for the item to return - :returns: a string - ''' - return_name = return_['name'] - return_type = get_python_type(return_) - if 'typing.List' in return_type: - subtype = get_python_type(return_['items']) - if subtype.startswith('typing.Any'): - code = "[i for i in json['{}']]".format(return_name) - elif 'type' in return_['items'] or is_builtin_type(subtype): - code = "[{}(i) for i in json['{}']]".format(subtype, return_name) - else: - code = "[{}.from_json(i) for i in json['{}']]".format(subtype, return_name) - elif is_builtin_type(return_type): - code = "{}(json['{}'])".format(return_type, return_name) - elif return_type.startswith('typing.Any'): - code = "json['{}']".format(return_name) - else: - code = "{}.from_json(json['{}'])".format(return_type, return_name) - return code - - -def generate_init(init_path, modules): - ''' - Generate an ``__init__.py`` that exports the specified modules. - - :param Path init_path: a file path to create the init file in - :param list[tuple] modules: a list of modules each represented as tuples - of (name, list_of_exported_symbols) - ''' - modules = [module[0] for module in modules] - modules.sort() - with init_path.open('w') as init_file: - init_file.write(init_header) - for submodule in ('types', 'events', 'commands'): - for module in modules: - init_file.write('import cdp.{}.{}\n'.format(module, submodule)) - init_file.write('\n') - init_file.write('import cdp.util\n') - - -def main(): - ''' Main entry point. ''' - here = Path(__file__).parent.resolve() - json_paths = [ - here / 'browser_protocol.json', - here / 'js_protocol.json', - ] - output_path = here.parent / 'cdp' - clear_dirs(output_path) - - modules = list() - for json_path in json_paths: - logger.info('Parsing JSON file %s', json_path) - modules.extend(parse(json_path, output_path)) - - init_path = output_path / '__init__.py' - generate_init(init_path, modules) - - py_typed_path = output_path / 'py.typed' - py_typed_path.touch() - - -if __name__ == '__main__': - main() diff --git a/cdp/__init__.py b/cdp/__init__.py deleted file mode 100644 index ab6ea54..0000000 --- a/cdp/__init__.py +++ /dev/null @@ -1,142 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. -''' -import cdp.accessibility.types -import cdp.animation.types -import cdp.application_cache.types -import cdp.audits.types -import cdp.background_service.types -import cdp.browser.types -import cdp.cache_storage.types -import cdp.cast.types -import cdp.console.types -import cdp.css.types -import cdp.database.types -import cdp.debugger.types -import cdp.device_orientation.types -import cdp.dom.types -import cdp.dom_debugger.types -import cdp.dom_snapshot.types -import cdp.dom_storage.types -import cdp.emulation.types -import cdp.fetch.types -import cdp.headless_experimental.types -import cdp.heap_profiler.types -import cdp.indexed_db.types -import cdp.input.types -import cdp.inspector.types -import cdp.io.types -import cdp.layer_tree.types -import cdp.log.types -import cdp.memory.types -import cdp.network.types -import cdp.overlay.types -import cdp.page.types -import cdp.performance.types -import cdp.profiler.types -import cdp.runtime.types -import cdp.schema.types -import cdp.security.types -import cdp.service_worker.types -import cdp.storage.types -import cdp.system_info.types -import cdp.target.types -import cdp.tethering.types -import cdp.tracing.types -import cdp.web_audio.types -import cdp.web_authn.types - -import cdp.accessibility.events -import cdp.animation.events -import cdp.application_cache.events -import cdp.audits.events -import cdp.background_service.events -import cdp.browser.events -import cdp.cache_storage.events -import cdp.cast.events -import cdp.console.events -import cdp.css.events -import cdp.database.events -import cdp.debugger.events -import cdp.device_orientation.events -import cdp.dom.events -import cdp.dom_debugger.events -import cdp.dom_snapshot.events -import cdp.dom_storage.events -import cdp.emulation.events -import cdp.fetch.events -import cdp.headless_experimental.events -import cdp.heap_profiler.events -import cdp.indexed_db.events -import cdp.input.events -import cdp.inspector.events -import cdp.io.events -import cdp.layer_tree.events -import cdp.log.events -import cdp.memory.events -import cdp.network.events -import cdp.overlay.events -import cdp.page.events -import cdp.performance.events -import cdp.profiler.events -import cdp.runtime.events -import cdp.schema.events -import cdp.security.events -import cdp.service_worker.events -import cdp.storage.events -import cdp.system_info.events -import cdp.target.events -import cdp.tethering.events -import cdp.tracing.events -import cdp.web_audio.events -import cdp.web_authn.events - -import cdp.accessibility.commands -import cdp.animation.commands -import cdp.application_cache.commands -import cdp.audits.commands -import cdp.background_service.commands -import cdp.browser.commands -import cdp.cache_storage.commands -import cdp.cast.commands -import cdp.console.commands -import cdp.css.commands -import cdp.database.commands -import cdp.debugger.commands -import cdp.device_orientation.commands -import cdp.dom.commands -import cdp.dom_debugger.commands -import cdp.dom_snapshot.commands -import cdp.dom_storage.commands -import cdp.emulation.commands -import cdp.fetch.commands -import cdp.headless_experimental.commands -import cdp.heap_profiler.commands -import cdp.indexed_db.commands -import cdp.input.commands -import cdp.inspector.commands -import cdp.io.commands -import cdp.layer_tree.commands -import cdp.log.commands -import cdp.memory.commands -import cdp.network.commands -import cdp.overlay.commands -import cdp.page.commands -import cdp.performance.commands -import cdp.profiler.commands -import cdp.runtime.commands -import cdp.schema.commands -import cdp.security.commands -import cdp.service_worker.commands -import cdp.storage.commands -import cdp.system_info.commands -import cdp.target.commands -import cdp.tethering.commands -import cdp.tracing.commands -import cdp.web_audio.commands -import cdp.web_authn.commands - -import cdp.util diff --git a/cdp/accessibility/commands.py b/cdp/accessibility/commands.py deleted file mode 100644 index 49ce42d..0000000 --- a/cdp/accessibility/commands.py +++ /dev/null @@ -1,88 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from .types import * -from ..dom import types as dom -from ..runtime import types as runtime - - - -def disable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: - ''' - Disables the accessibility domain. - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.disable', - } - json = yield cmd_dict - - -def enable() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,None]: - ''' - Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. - This turns on accessibility for the page, which can impact performance until accessibility is disabled. - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.enable', - } - json = yield cmd_dict - - -def get_partial_ax_tree( - node_id: typing.Optional[dom.NodeId] = None, - backend_node_id: typing.Optional[dom.BackendNodeId] = None, - object_id: typing.Optional[runtime.RemoteObjectId] = None, - fetch_relatives: typing.Optional[bool] = None, - ) -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List['AXNode']]: - ''' - Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. - - :param node_id: Identifier of the node to get the partial accessibility tree for. - :param backend_node_id: Identifier of the backend node to get the partial accessibility tree for. - :param object_id: JavaScript object id of the node wrapper to get the partial accessibility tree for. - :param fetch_relatives: Whether to fetch this nodes ancestors, siblings and children. Defaults to true. - :returns: The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and - children, if requested. - ''' - params: T_JSON_DICT = { - } - if node_id is not None: - params['nodeId'] = node_id.to_json() - if backend_node_id is not None: - params['backendNodeId'] = backend_node_id.to_json() - if object_id is not None: - params['objectId'] = object_id.to_json() - if fetch_relatives is not None: - params['fetchRelatives'] = fetch_relatives - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.getPartialAXTree', - 'params': params, - } - json = yield cmd_dict - return [AXNode.from_json(i) for i in json['nodes']] - - -def get_full_ax_tree() -> typing.Generator[T_JSON_DICT,T_JSON_DICT,typing.List['AXNode']]: - ''' - Fetches the entire accessibility tree - :returns: - ''' - cmd_dict: T_JSON_DICT = { - 'method': 'Accessibility.getFullAXTree', - } - json = yield cmd_dict - return [AXNode.from_json(i) for i in json['nodes']] - - diff --git a/cdp/accessibility/events.py b/cdp/accessibility/events.py deleted file mode 100644 index ceb8207..0000000 --- a/cdp/accessibility/events.py +++ /dev/null @@ -1,17 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from .types import * - diff --git a/cdp/accessibility/types.py b/cdp/accessibility/types.py deleted file mode 100644 index eece334..0000000 --- a/cdp/accessibility/types.py +++ /dev/null @@ -1,411 +0,0 @@ -''' -DO NOT EDIT THIS FILE - -This file is generated from the CDP definitions. If you need to make changes, -edit the generator and regenerate all of the modules. - -Domain: accessibility -Experimental: True -''' - -from cdp.util import T_JSON_DICT -from dataclasses import dataclass -import enum -import typing - -from ..dom import types as dom - - -class AXNodeId(str): - ''' - Unique accessibility node identifier. - ''' - def to_json(self) -> str: - return self - - @classmethod - def from_json(cls, json: str) -> 'AXNodeId': - return cls(json) - - def __repr__(self): - return 'AXNodeId({})'.format(str.__repr__(self)) - - -class AXValueType(enum.Enum): - ''' - Enum of possible property types. - ''' - BOOLEAN = "boolean" - TRISTATE = "tristate" - BOOLEAN_OR_UNDEFINED = "booleanOrUndefined" - IDREF = "idref" - IDREF_LIST = "idrefList" - INTEGER = "integer" - NODE = "node" - NODE_LIST = "nodeList" - NUMBER = "number" - STRING = "string" - COMPUTED_STRING = "computedString" - TOKEN = "token" - TOKEN_LIST = "tokenList" - DOM_RELATION = "domRelation" - ROLE = "role" - INTERNAL_ROLE = "internalRole" - VALUE_UNDEFINED = "valueUndefined" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueType': - return cls(json) - - -class AXValueSourceType(enum.Enum): - ''' - Enum of possible property sources. - ''' - ATTRIBUTE = "attribute" - IMPLICIT = "implicit" - STYLE = "style" - CONTENTS = "contents" - PLACEHOLDER = "placeholder" - RELATED_ELEMENT = "relatedElement" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueSourceType': - return cls(json) - - -class AXValueNativeSourceType(enum.Enum): - ''' - Enum of possible native property sources (as a subtype of a particular AXValueSourceType). - ''' - FIGCAPTION = "figcaption" - LABEL = "label" - LABELFOR = "labelfor" - LABELWRAPPED = "labelwrapped" - LEGEND = "legend" - TABLECAPTION = "tablecaption" - TITLE = "title" - OTHER = "other" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXValueNativeSourceType': - return cls(json) - - -class AXPropertyName(enum.Enum): - ''' - Values of AXProperty name: - - from 'busy' to 'roledescription': states which apply to every AX node - - from 'live' to 'root': attributes which apply to nodes in live regions - - from 'autocomplete' to 'valuetext': attributes which apply to widgets - - from 'checked' to 'selected': states which apply to widgets - - from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling. - ''' - BUSY = "busy" - DISABLED = "disabled" - EDITABLE = "editable" - FOCUSABLE = "focusable" - FOCUSED = "focused" - HIDDEN = "hidden" - HIDDEN_ROOT = "hiddenRoot" - INVALID = "invalid" - KEYSHORTCUTS = "keyshortcuts" - SETTABLE = "settable" - ROLEDESCRIPTION = "roledescription" - LIVE = "live" - ATOMIC = "atomic" - RELEVANT = "relevant" - ROOT = "root" - AUTOCOMPLETE = "autocomplete" - HAS_POPUP = "hasPopup" - LEVEL = "level" - MULTISELECTABLE = "multiselectable" - ORIENTATION = "orientation" - MULTILINE = "multiline" - READONLY = "readonly" - REQUIRED = "required" - VALUEMIN = "valuemin" - VALUEMAX = "valuemax" - VALUETEXT = "valuetext" - CHECKED = "checked" - EXPANDED = "expanded" - MODAL = "modal" - PRESSED = "pressed" - SELECTED = "selected" - ACTIVEDESCENDANT = "activedescendant" - CONTROLS = "controls" - DESCRIBEDBY = "describedby" - DETAILS = "details" - ERRORMESSAGE = "errormessage" - FLOWTO = "flowto" - LABELLEDBY = "labelledby" - OWNS = "owns" - - def to_json(self) -> str: - return self.value - - @classmethod - def from_json(cls, json: str) -> 'AXPropertyName': - return cls(json) - - -@dataclass -class AXRelatedNode: - #: The BackendNodeId of the related DOM node. - backend_dom_node_id: dom.BackendNodeId - - #: The IDRef value provided, if any. - idref: typing.Optional[str] = None - - #: The text alternative of this node in the current context. - text: typing.Optional[str] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'backendDOMNodeId': self.backend_dom_node_id.to_json(), - } - if self.idref is not None: - json['idref'] = self.idref - if self.text is not None: - json['text'] = self.text - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXRelatedNode': - idref = json['idref'] if 'idref' in json else None - text = json['text'] if 'text' in json else None - return cls( - backend_dom_node_id=dom.BackendNodeId.from_json(json['backendDOMNodeId']), - idref=idref, - text=text, - ) - -@dataclass -class AXValue: - ''' - A single computed AX property. - ''' - #: The type of this value. - type: AXValueType - - #: The computed value of this property. - value: typing.Optional[typing.Any] = None - - #: One or more related nodes, if applicable. - related_nodes: typing.Optional[typing.List['AXRelatedNode']] = None - - #: The sources which contributed to the computation of this property. - sources: typing.Optional[typing.List['AXValueSource']] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'type': self.type.to_json(), - } - if self.value is not None: - json['value'] = self.value - if self.related_nodes is not None: - json['relatedNodes'] = [i.to_json() for i in self.related_nodes] - if self.sources is not None: - json['sources'] = [i.to_json() for i in self.sources] - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXValue': - value = json['value'] if 'value' in json else None - related_nodes = [AXRelatedNode.from_json(i) for i in json['relatedNodes']] if 'relatedNodes' in json else None - sources = [AXValueSource.from_json(i) for i in json['sources']] if 'sources' in json else None - return cls( - type=AXValueType.from_json(json['type']), - value=value, - related_nodes=related_nodes, - sources=sources, - ) - -@dataclass -class AXNode: - ''' - A node in the accessibility tree. - ''' - #: Unique identifier for this node. - node_id: AXNodeId - - #: Whether this node is ignored for accessibility - ignored: bool - - #: Collection of reasons why this node is hidden. - ignored_reasons: typing.Optional[typing.List['AXProperty']] = None - - #: This `Node`'s role, whether explicit or implicit. - role: typing.Optional[AXValue] = None - - #: The accessible name for this `Node`. - name: typing.Optional[AXValue] = None - - #: The accessible description for this `Node`. - description: typing.Optional[AXValue] = None - - #: The value for this `Node`. - value: typing.Optional[AXValue] = None - - #: All other properties - properties: typing.Optional[typing.List['AXProperty']] = None - - #: IDs for each of this node's child nodes. - child_ids: typing.Optional[typing.List['AXNodeId']] = None - - #: The backend ID for the associated DOM node, if any. - backend_dom_node_id: typing.Optional[dom.BackendNodeId] = None - - def to_json(self) -> T_JSON_DICT: - json: T_JSON_DICT = { - 'nodeId': self.node_id.to_json(), - 'ignored': self.ignored, - } - if self.ignored_reasons is not None: - json['ignoredReasons'] = [i.to_json() for i in self.ignored_reasons] - if self.role is not None: - json['role'] = self.role.to_json() - if self.name is not None: - json['name'] = self.name.to_json() - if self.description is not None: - json['description'] = self.description.to_json() - if self.value is not None: - json['value'] = self.value.to_json() - if self.properties is not None: - json['properties'] = [i.to_json() for i in self.properties] - if self.child_ids is not None: - json['childIds'] = [i.to_json() for i in self.child_ids] - if self.backend_dom_node_id is not None: - json['backendDOMNodeId'] = self.backend_dom_node_id.to_json() - return json - - @classmethod - def from_json(cls, json: T_JSON_DICT) -> 'AXNode': - ignored_reasons = [AXProperty.from_json(i) for i in json['ignoredReasons']] if 'ignoredReasons' in json else None - role = AXValue.from_json(json['role']) if 'role' in json else None - name = AXValue.from_json(json['name']) if 'name' in json else None - description = AXValue.from_json(json['description']) if 'description' in json else None - value = AXValue.from_json(json['value']) if 'value' in json else None - properties = [AXProperty.from_json(i) for i in json['properties']] if 'properties' in json else None - child_ids = [AXNodeId.from_json(i) for i in json['childIds']] if 'childIds' in json else None - backend_dom_node_id = dom.BackendNodeId.from_json(json['backendDOMNodeId']) if 'backendDOMNodeId' in json else None - return cls( - node_id=AXNodeId.from_json(json['nodeId']), - ignored=json['ignored'], - ignored_reasons=ignored_reasons, - role=role, - name=name, - description=description, - value=value, - properties=properties, - child_ids=child_ids, - backend_dom_node_id=backend_dom_node_id, - ) - -@dataclass -class AXValueSource: - ''' - A single source for a computed AX property. - ''' - #: What type of source this is. - type: AXValueSourceType - - #: The value of this property source. - value: typing.Optional[AXValue] = None - - #: The name of the relevant attribute, if any. - attribute: typing.Optional[str] = None - - #: The value of the relevant attribute, if any. - attribute_value: typing.Optional[AXValue] = None - - #: Whether this source is superseded by a higher priority source. - superseded: typing.Optional[bool] = None - - #: The native markup source for this value, e.g. a