onecli-sdk 0.1.0__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.
onecli/_url.py ADDED
@@ -0,0 +1,264 @@
1
+ """The parts of an http(s) URL, read the way a browser or Node reads them.
2
+
3
+ Node's SDK checks addresses with the WHATWG URL parser. This module reads the
4
+ same hosts the same way for the forms that matter here: host names are put in
5
+ lower case, IPv4 addresses written as numbers in other bases become the
6
+ dotted form, IPv6 addresses take their short form, and a port is 0 to 65535.
7
+
8
+ Where it cannot read a URL exactly as WHATWG does, it refuses it instead of
9
+ guessing: spaces, tabs or backslashes anywhere, ``https:`` without ``//``, a
10
+ percent sign in a host, and a host with letters outside ASCII (write its
11
+ ``xn--`` form). WHATWG repairs or converts these.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ipaddress
17
+ import re
18
+ from dataclasses import dataclass
19
+
20
+ __all__ = ["HttpUrl", "parse_http_url", "scheme_of"]
21
+
22
+ _SCHEME_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]*):")
23
+ _DEFAULT_PORTS = {"http": 80, "https": 443}
24
+ # Code points WHATWG never allows in a host name.
25
+ _FORBIDDEN_HOST = re.compile(r"[\x00-\x20#%/:<>?@\[\\\]^|\x7f]")
26
+ _DIGITS = re.compile(r"[0-9]+")
27
+ _HEX = re.compile(r"[0-9A-Fa-f]*")
28
+ _OCTAL = re.compile(r"[0-7]+")
29
+ _IPV4_PARTS = 4
30
+ _IPV4_PART_MAX = 255
31
+ _PORT_MAX = 65535
32
+ _IPV6_GROUPS = 8
33
+ # Path segments WHATWG reads as `.` and `..`, with a dot written as %2e too.
34
+ _SINGLE_DOT = frozenset({".", "%2e"})
35
+ _DOUBLE_DOT = frozenset({"..", ".%2e", "%2e.", "%2e%2e"})
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class HttpUrl:
40
+ """An http or https URL, read.
41
+
42
+ ``raw`` is the text as given. ``host`` is as WHATWG writes it: an IPv6
43
+ address keeps its brackets. ``port`` is None when the URL names none, or
44
+ names the scheme's own. ``path`` has its ``.`` and ``..`` segments resolved,
45
+ as WHATWG's ``pathname``. ``has_userinfo``, ``has_query`` and
46
+ ``has_fragment`` are true when a user or password, a query or a fragment
47
+ is there and not empty (WHATWG's ``username``, ``search`` and ``hash``).
48
+ """
49
+
50
+ raw: str
51
+ scheme: str
52
+ host: str
53
+ port: int | None
54
+ path: str
55
+ has_userinfo: bool
56
+ has_query: bool
57
+ has_fragment: bool
58
+
59
+ @property
60
+ def authority(self) -> str:
61
+ """The host and a port that is not the scheme's own (Node's ``url.host``)."""
62
+ return self.host if self.port is None else f"{self.host}:{self.port}"
63
+
64
+ @property
65
+ def origin(self) -> str:
66
+ """The scheme, the host and a port that is not the scheme's own."""
67
+ return f"{self.scheme}://{self.authority}"
68
+
69
+ @property
70
+ def bare_host(self) -> str:
71
+ """The host with no IPv6 brackets."""
72
+ return self.host[1:-1] if self.host.startswith("[") else self.host
73
+
74
+
75
+ def scheme_of(raw: str) -> str | None:
76
+ """The scheme in lower case, or None when the text does not start with one."""
77
+ match = _SCHEME_RE.match(raw)
78
+ return match.group(1).lower() if match else None
79
+
80
+
81
+ def _ipv4_number(part: str) -> int | None:
82
+ if part[:2] in {"0x", "0X"}:
83
+ digits = part[2:]
84
+ # WHATWG reads a bare 0x as 0.
85
+ return int(digits or "0", 16) if _HEX.fullmatch(digits) else None
86
+ if len(part) > 1 and part[0] == "0":
87
+ return int(part[1:], 8) if _OCTAL.fullmatch(part[1:]) else None
88
+ return int(part) if _DIGITS.fullmatch(part) else None
89
+
90
+
91
+ def _ends_in_number(host: str) -> bool:
92
+ parts = host.split(".")
93
+ if parts[-1] == "" and len(parts) > 1:
94
+ parts.pop()
95
+ last = parts[-1]
96
+ if last and _DIGITS.fullmatch(last):
97
+ return True
98
+ return last[:2] in {"0x", "0X"} and _HEX.fullmatch(last[2:]) is not None
99
+
100
+
101
+ def _ipv4(host: str) -> str | None:
102
+ """The dotted form of an IPv4 host, or None when it is not a valid one."""
103
+ parts = host.split(".")
104
+ if parts[-1] == "" and len(parts) > 1:
105
+ parts.pop()
106
+ if len(parts) > _IPV4_PARTS or "" in parts:
107
+ return None
108
+ numbers = [_ipv4_number(p) for p in parts]
109
+ if any(n is None for n in numbers):
110
+ return None
111
+ values = [n for n in numbers if n is not None]
112
+ if any(n > _IPV4_PART_MAX for n in values[:-1]):
113
+ return None
114
+ if values[-1] >= 256 ** (5 - len(values)):
115
+ return None
116
+ address = values[-1]
117
+ for i, n in enumerate(values[:-1]):
118
+ address += n * 256 ** (3 - i)
119
+ return str(ipaddress.IPv4Address(address))
120
+
121
+
122
+ def _ipv6(inside: str) -> str | None:
123
+ """The WHATWG form of an IPv6 address, or None when it is not a valid one."""
124
+ if "%" in inside: # A zone id, which Python reads and WHATWG refuses.
125
+ return None
126
+ try:
127
+ packed = ipaddress.IPv6Address(inside).packed
128
+ except ValueError:
129
+ return None
130
+ groups = [int.from_bytes(packed[i : i + 2], "big") for i in range(0, 16, 2)]
131
+ # The longest run of two or more zero groups is written as "::"; the first one on a tie.
132
+ best_start, best_len, start = -1, 1, -1
133
+ for i in range(_IPV6_GROUPS + 1):
134
+ if i < _IPV6_GROUPS and groups[i] == 0:
135
+ start = i if start == -1 else start
136
+ continue
137
+ if start != -1 and i - start > best_len:
138
+ best_start, best_len = start, i - start
139
+ start = -1
140
+ if best_start == -1:
141
+ return ":".join(f"{g:x}" for g in groups)
142
+ head = ":".join(f"{g:x}" for g in groups[:best_start])
143
+ tail = ":".join(f"{g:x}" for g in groups[best_start + best_len :])
144
+ return f"{head}::{tail}"
145
+
146
+
147
+ def _domain(host: str) -> str | None:
148
+ # Python's IDNA rules are older than WHATWG's and give another host for a
149
+ # few letters (faß.de), so a host outside ASCII is refused, not converted.
150
+ if not host.isascii():
151
+ return None
152
+ ascii_host = host.lower()
153
+ for label in ascii_host.split("."):
154
+ if label.startswith("xn--") and not _valid_xn_label(label):
155
+ return None
156
+ if _FORBIDDEN_HOST.search(ascii_host):
157
+ return None
158
+ if _ends_in_number(ascii_host):
159
+ return _ipv4(ascii_host)
160
+ return ascii_host
161
+
162
+
163
+ def _valid_xn_label(label: str) -> bool:
164
+ """Whether an ``xn--`` label decodes to a name with letters outside ASCII.
165
+
166
+ WHATWG also checks which letters, with rules Python does not ship, so it
167
+ refuses some labels taken here. It takes none that are refused here.
168
+ """
169
+ try:
170
+ name = label[4:].encode("ascii").decode("punycode")
171
+ except UnicodeError:
172
+ return False
173
+ return not name.isascii()
174
+
175
+
176
+ def _host(raw_host: str) -> str | None:
177
+ if raw_host.startswith("["):
178
+ if not raw_host.endswith("]"):
179
+ return None
180
+ short = _ipv6(raw_host[1:-1])
181
+ return None if short is None else f"[{short}]"
182
+ if raw_host == "":
183
+ return None
184
+ return _domain(raw_host)
185
+
186
+
187
+ def _split_authority(authority: str) -> tuple[bool, str, str | None]:
188
+ """Whether a user is named, the host, and the port text (None when there is no colon)."""
189
+ userinfo, at, hostport = authority.rpartition("@")
190
+ named_user = bool(at) and userinfo not in {"", ":"}
191
+ if hostport.startswith("["):
192
+ close = hostport.find("]")
193
+ if close == -1:
194
+ return named_user, hostport, None
195
+ host, rest = hostport[: close + 1], hostport[close + 1 :]
196
+ if rest == "":
197
+ return named_user, host, None
198
+ if not rest.startswith(":"):
199
+ return named_user, "", None
200
+ return named_user, host, rest[1:]
201
+ host, colon, port = hostport.partition(":")
202
+ return named_user, host, port if colon else None
203
+
204
+
205
+ def _resolve_dots(raw_path: str) -> str:
206
+ """The path with its dot segments resolved, as WHATWG's path state does for http(s)."""
207
+ if raw_path == "":
208
+ return "/"
209
+ segments = raw_path[1:].split("/")
210
+ kept: list[str] = []
211
+ for index, segment in enumerate(segments):
212
+ last = index == len(segments) - 1
213
+ lowered = segment.lower()
214
+ if lowered in _DOUBLE_DOT:
215
+ if kept:
216
+ kept.pop()
217
+ if last:
218
+ kept.append("")
219
+ elif lowered in _SINGLE_DOT:
220
+ if last:
221
+ kept.append("")
222
+ else:
223
+ kept.append(segment)
224
+ return "/" + "/".join(kept)
225
+
226
+
227
+ def parse_http_url(raw: str) -> HttpUrl | None:
228
+ """Read an http or https URL. None when it is not a valid one."""
229
+ scheme = scheme_of(raw)
230
+ if scheme not in _DEFAULT_PORTS:
231
+ return None
232
+ rest = raw[len(scheme) + 1 :]
233
+ if not rest.startswith("//") or re.search(r"[\x00-\x20\x7f\\]", raw):
234
+ return None
235
+ rest = rest[2:]
236
+ end = len(rest)
237
+ for mark in "/?#":
238
+ at = rest.find(mark)
239
+ if at != -1:
240
+ end = min(end, at)
241
+ authority, tail = rest[:end], rest[end:]
242
+ named_user, raw_host, port_text = _split_authority(authority)
243
+ host = _host(raw_host)
244
+ if host is None:
245
+ return None
246
+ port: int | None = None
247
+ if port_text:
248
+ if not _DIGITS.fullmatch(port_text) or int(port_text) > _PORT_MAX:
249
+ return None
250
+ port = int(port_text)
251
+ if port == _DEFAULT_PORTS[scheme]:
252
+ port = None
253
+ before_hash, _, fragment = tail.partition("#")
254
+ raw_path, _, query = before_hash.partition("?")
255
+ return HttpUrl(
256
+ raw=raw,
257
+ scheme=scheme,
258
+ host=host,
259
+ port=port,
260
+ path=_resolve_dots(raw_path),
261
+ has_userinfo=named_user,
262
+ has_query=query != "",
263
+ has_fragment=fragment != "",
264
+ )
onecli/_version.py ADDED
@@ -0,0 +1,19 @@
1
+ """This package's version, from its installed metadata."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from typing import Final
7
+
8
+ __all__ = ["SDK_VERSION"]
9
+
10
+
11
+ def _installed_version() -> str:
12
+ try:
13
+ return version("onecli-sdk")
14
+ except PackageNotFoundError: # pragma: no cover - a source tree that is not installed
15
+ return "0.0.0-dev"
16
+
17
+
18
+ SDK_VERSION: Final = _installed_version()
19
+ """This package's version."""