hungerbridge 1.0.dev4__tar.gz → 1.0.dev6__tar.gz

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 (36) hide show
  1. {hungerbridge-1.0.dev4/src/hungerbridge.egg-info → hungerbridge-1.0.dev6}/PKG-INFO +39 -5
  2. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/README.md +38 -4
  3. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/pyproject.toml +1 -1
  4. hungerbridge-1.0.dev6/src/hungerbridge/__init__.py +51 -0
  5. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/auth.py +25 -25
  6. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/bridge.py +4 -4
  7. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/canonical.py +30 -30
  8. hungerbridge-1.0.dev6/src/hungerbridge/client.py +429 -0
  9. hungerbridge-1.0.dev6/src/hungerbridge/exceptions.py +81 -0
  10. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/protocol.py +8 -4
  11. hungerbridge-1.0.dev6/src/hungerbridge/releases.py +184 -0
  12. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/stream.py +101 -60
  13. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/transport.py +20 -20
  14. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/units.py +22 -22
  15. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6/src/hungerbridge.egg-info}/PKG-INFO +39 -5
  16. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge.egg-info/SOURCES.txt +3 -0
  17. hungerbridge-1.0.dev6/tests/test_auth.py +61 -0
  18. hungerbridge-1.0.dev6/tests/test_canonical.py +62 -0
  19. hungerbridge-1.0.dev6/tests/test_client.py +184 -0
  20. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/tests/test_live.py +83 -82
  21. hungerbridge-1.0.dev6/tests/test_releases.py +69 -0
  22. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/tests/test_stream.py +100 -50
  23. hungerbridge-1.0.dev6/tests/test_stream_logs.py +104 -0
  24. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/tests/test_transport.py +43 -43
  25. hungerbridge-1.0.dev4/src/hungerbridge/__init__.py +0 -47
  26. hungerbridge-1.0.dev4/src/hungerbridge/client.py +0 -353
  27. hungerbridge-1.0.dev4/src/hungerbridge/exceptions.py +0 -81
  28. hungerbridge-1.0.dev4/tests/test_auth.py +0 -61
  29. hungerbridge-1.0.dev4/tests/test_canonical.py +0 -62
  30. hungerbridge-1.0.dev4/tests/test_client.py +0 -180
  31. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/LICENSE +0 -0
  32. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/setup.cfg +0 -0
  33. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge/py.typed +0 -0
  34. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge.egg-info/dependency_links.txt +0 -0
  35. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge.egg-info/requires.txt +0 -0
  36. {hungerbridge-1.0.dev4 → hungerbridge-1.0.dev6}/src/hungerbridge.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hungerbridge
3
- Version: 1.0.dev4
3
+ Version: 1.0.dev6
4
4
  Summary: Python client for the HungerBridge Minecraft (Paper/Folia/Fabric) HTTP bridge
5
5
  Author: iFamished
6
6
  License: MIT
@@ -74,10 +74,10 @@ client.log("hello from python", level="BRIDGE", thread="bot")
74
74
  | Method | Endpoint | Returns |
75
75
  |---|---|---|
76
76
  | `isOk()`, `getServerTime()`, `getPing()` | `GET /ping` | bool, epoch ms, RTT ms |
77
- | `getTokenInfo()` | `GET /auth/check` | `token_id`, `policy_id`, `permissions` |
77
+ | `getTokenInfo()` | `GET /auth/check` | `token_id`, `policy_id`, `permissions`, `expiry` |
78
78
  | `getServerMeta()`, `getPlatform()`, `getMinecraftVersion()`, `getBridgeVersion()`, `getBridgePort()`, `getProtocolVersion()` | `GET /server/meta` | |
79
- | `getPlayers('count'\|'list')`, `getMaxPlayers()` | `GET /players/list` | |
80
- | `getTPS('current'\|'1m'\|'5m'\|'15m')` | `GET /world/tps` | float, `-1` if unavailable |
79
+ | `getPlayers('count'\|'list')`, `getMaxPlayers()`, `getPlayerStats()` | `GET /players/list` | |
80
+ | `getTPS('current'\|'1m'\|'5m'\|'15m')`, `getTPSStats()` | `GET /world/tps` | float, `-1` if unavailable |
81
81
  | `getMSPT()` | `GET /world/mspt` | float |
82
82
  | `getWorldTime()`, `getWorldTimeInfo()` | `GET /world/time` | ticks of day (0–23999) / dict |
83
83
  | `getWorldWeather()` | `GET /world/weather` | `clear`/`rain`/`thunder` |
@@ -88,6 +88,7 @@ client.log("hello from python", level="BRIDGE", thread="bot")
88
88
  | `log(message, level='info', thread=None)` | `POST /server/log` | dict |
89
89
  | `stopServer()` | `POST /server/stop` | dict |
90
90
  | `BridgeClient.redeemPickup(url)` / `fromPickup(url)` | `GET /pickup/<id>` | `(token_id, secret)` / client |
91
+ | `streamLogs(history, timeout=, reconnect=, sanitize=)` / `openStream(...)` | `GET /server/stream` | iterator of lines / `Stream` |
91
92
 
92
93
  Constructor options: `max_retries`, `retry_backoff_sec`, `swallow_rate_limit`,
93
94
  `static_delay` (minimum gap between requests), `timeout` (default `(5, 30)` seconds),
@@ -95,19 +96,51 @@ Constructor options: `max_retries`, `retry_backoff_sec`, `swallow_rate_limit`,
95
96
 
96
97
  ### Log streaming (SSE)
97
98
 
99
+ The simplest way is the blocking iterator:
100
+
101
+ ```python
102
+ for line in client.streamLogs(history=50, reconnect=True, sanitize=True):
103
+ if "joined the game" in line:
104
+ print(line)
105
+ ```
106
+
107
+ `streamLogs(history=None, *, timeout=None, reconnect=False, sanitize=False)` replays up to
108
+ `history` recent lines (`True` = the server maximum, `MAX_HISTORY` = 200), then yields live
109
+ lines. It stops when nothing arrives for `timeout` seconds or when the server closes the stream
110
+ (unless `reconnect`), and raises the typed error that ended the connection. `break` disconnects.
111
+
112
+ For callbacks in a background thread use a `Stream`:
113
+
98
114
  ```python
99
115
  def on_history(lines): ...
100
116
  def on_line(line): print(client.stream.sanitize(line))
117
+ def on_close(error): print("stream ended", error)
101
118
 
102
119
  client = BridgeClient(url, token, history_handler=on_history, new_log_handler=on_line)
103
120
  client.stream.connect(history=50, reconnect=True) # background thread
104
121
  ...
105
122
  client.stream.disconnect()
123
+
124
+ other = client.openStream(new_log_handler=on_line, close_handler=on_close) # independent connection
106
125
  ```
107
126
 
108
127
  Without handlers lines are buffered in `getRaw()`, `getSanitized()` and `getTimestamped()`.
109
128
  With `reconnect=True` the stream reconnects with exponential back-off and replays only
110
- the history lines it has not seen yet.
129
+ the history lines it has not seen yet. Permanent errors (401, 403, 404) end the stream instead
130
+ of being retried; `stream.last_error` holds the typed error.
131
+
132
+ ### Release jars
133
+
134
+ ```python
135
+ from hungerbridge import find_release
136
+ from hungerbridge.releases import list_release_assets, loader_for
137
+
138
+ asset = find_release("1.21.11", "paper") # or "latest", loader "PURPUR" -> paper
139
+ print(asset.name, asset.url, asset.directory) # .../plugins
140
+ ```
141
+
142
+ Release assets are named `HungerBridge-<loader>-<minecraft>-<version>.jar`; jars from
143
+ releases before that naming (`<minecraft>-<loader>-<version>.jar`) are recognised too.
111
144
 
112
145
  ### Errors
113
146
 
@@ -136,6 +169,7 @@ if it differs from `hungerbridge.PROTOCOL_VERSION`.
136
169
  | `auth.py` | credentials and HMAC signing |
137
170
  | `canonical.py` | canonical JSON + path normalization (wire format) |
138
171
  | `stream.py` | SSE parser and `Stream` |
172
+ | `releases.py` | release jar discovery on GitHub (`find_release`, `ReleaseAsset`, `loader_for`) |
139
173
  | `exceptions.py`, `units.py`, `protocol.py` | errors, unit conversion, protocol constants |
140
174
  | `bridge.py` | backwards-compatible re-exports of the old single-module API |
141
175
 
@@ -41,10 +41,10 @@ client.log("hello from python", level="BRIDGE", thread="bot")
41
41
  | Method | Endpoint | Returns |
42
42
  |---|---|---|
43
43
  | `isOk()`, `getServerTime()`, `getPing()` | `GET /ping` | bool, epoch ms, RTT ms |
44
- | `getTokenInfo()` | `GET /auth/check` | `token_id`, `policy_id`, `permissions` |
44
+ | `getTokenInfo()` | `GET /auth/check` | `token_id`, `policy_id`, `permissions`, `expiry` |
45
45
  | `getServerMeta()`, `getPlatform()`, `getMinecraftVersion()`, `getBridgeVersion()`, `getBridgePort()`, `getProtocolVersion()` | `GET /server/meta` | |
46
- | `getPlayers('count'\|'list')`, `getMaxPlayers()` | `GET /players/list` | |
47
- | `getTPS('current'\|'1m'\|'5m'\|'15m')` | `GET /world/tps` | float, `-1` if unavailable |
46
+ | `getPlayers('count'\|'list')`, `getMaxPlayers()`, `getPlayerStats()` | `GET /players/list` | |
47
+ | `getTPS('current'\|'1m'\|'5m'\|'15m')`, `getTPSStats()` | `GET /world/tps` | float, `-1` if unavailable |
48
48
  | `getMSPT()` | `GET /world/mspt` | float |
49
49
  | `getWorldTime()`, `getWorldTimeInfo()` | `GET /world/time` | ticks of day (0–23999) / dict |
50
50
  | `getWorldWeather()` | `GET /world/weather` | `clear`/`rain`/`thunder` |
@@ -55,6 +55,7 @@ client.log("hello from python", level="BRIDGE", thread="bot")
55
55
  | `log(message, level='info', thread=None)` | `POST /server/log` | dict |
56
56
  | `stopServer()` | `POST /server/stop` | dict |
57
57
  | `BridgeClient.redeemPickup(url)` / `fromPickup(url)` | `GET /pickup/<id>` | `(token_id, secret)` / client |
58
+ | `streamLogs(history, timeout=, reconnect=, sanitize=)` / `openStream(...)` | `GET /server/stream` | iterator of lines / `Stream` |
58
59
 
59
60
  Constructor options: `max_retries`, `retry_backoff_sec`, `swallow_rate_limit`,
60
61
  `static_delay` (minimum gap between requests), `timeout` (default `(5, 30)` seconds),
@@ -62,19 +63,51 @@ Constructor options: `max_retries`, `retry_backoff_sec`, `swallow_rate_limit`,
62
63
 
63
64
  ### Log streaming (SSE)
64
65
 
66
+ The simplest way is the blocking iterator:
67
+
68
+ ```python
69
+ for line in client.streamLogs(history=50, reconnect=True, sanitize=True):
70
+ if "joined the game" in line:
71
+ print(line)
72
+ ```
73
+
74
+ `streamLogs(history=None, *, timeout=None, reconnect=False, sanitize=False)` replays up to
75
+ `history` recent lines (`True` = the server maximum, `MAX_HISTORY` = 200), then yields live
76
+ lines. It stops when nothing arrives for `timeout` seconds or when the server closes the stream
77
+ (unless `reconnect`), and raises the typed error that ended the connection. `break` disconnects.
78
+
79
+ For callbacks in a background thread use a `Stream`:
80
+
65
81
  ```python
66
82
  def on_history(lines): ...
67
83
  def on_line(line): print(client.stream.sanitize(line))
84
+ def on_close(error): print("stream ended", error)
68
85
 
69
86
  client = BridgeClient(url, token, history_handler=on_history, new_log_handler=on_line)
70
87
  client.stream.connect(history=50, reconnect=True) # background thread
71
88
  ...
72
89
  client.stream.disconnect()
90
+
91
+ other = client.openStream(new_log_handler=on_line, close_handler=on_close) # independent connection
73
92
  ```
74
93
 
75
94
  Without handlers lines are buffered in `getRaw()`, `getSanitized()` and `getTimestamped()`.
76
95
  With `reconnect=True` the stream reconnects with exponential back-off and replays only
77
- the history lines it has not seen yet.
96
+ the history lines it has not seen yet. Permanent errors (401, 403, 404) end the stream instead
97
+ of being retried; `stream.last_error` holds the typed error.
98
+
99
+ ### Release jars
100
+
101
+ ```python
102
+ from hungerbridge import find_release
103
+ from hungerbridge.releases import list_release_assets, loader_for
104
+
105
+ asset = find_release("1.21.11", "paper") # or "latest", loader "PURPUR" -> paper
106
+ print(asset.name, asset.url, asset.directory) # .../plugins
107
+ ```
108
+
109
+ Release assets are named `HungerBridge-<loader>-<minecraft>-<version>.jar`; jars from
110
+ releases before that naming (`<minecraft>-<loader>-<version>.jar`) are recognised too.
78
111
 
79
112
  ### Errors
80
113
 
@@ -103,6 +136,7 @@ if it differs from `hungerbridge.PROTOCOL_VERSION`.
103
136
  | `auth.py` | credentials and HMAC signing |
104
137
  | `canonical.py` | canonical JSON + path normalization (wire format) |
105
138
  | `stream.py` | SSE parser and `Stream` |
139
+ | `releases.py` | release jar discovery on GitHub (`find_release`, `ReleaseAsset`, `loader_for`) |
106
140
  | `exceptions.py`, `units.py`, `protocol.py` | errors, unit conversion, protocol constants |
107
141
  | `bridge.py` | backwards-compatible re-exports of the old single-module API |
108
142
 
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "hungerbridge"
10
- version = "1.0-dev.4"
10
+ version = "1.0-dev.6"
11
11
  description = "Python client for the HungerBridge Minecraft (Paper/Folia/Fabric) HTTP bridge"
12
12
  readme = "README.md"
13
13
  requires-python = ">=3.9"
@@ -0,0 +1,51 @@
1
+ """Python client for the HungerBridge Minecraft HTTP bridge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .auth import Credentials
6
+ from .client import BridgeClient, redeem_pickup
7
+ from .exceptions import (
8
+ HungerBridgeAuthError,
9
+ HungerBridgeConnectionError,
10
+ HungerBridgeError,
11
+ HungerBridgeForbidden,
12
+ HungerBridgeNotFound,
13
+ HungerBridgeRateLimit,
14
+ InvalidModeError,
15
+ )
16
+ from .protocol import MAX_HISTORY, PROTOCOL_VERSION
17
+ from .releases import ReleaseAsset, find_release
18
+ from .stream import Stream
19
+
20
+ try: # installed distribution
21
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
22
+
23
+ try:
24
+ __version__ = _dist_version("hungerbridge")
25
+ except PackageNotFoundError:
26
+ __version__ = "0.0.0"
27
+ except ImportError: # pragma: no cover
28
+ __version__ = "0.0.0"
29
+
30
+ #: Alias kept for the name the original ``__init__`` tried to export.
31
+ HungerBridge = BridgeClient
32
+
33
+ __all__ = [
34
+ "BridgeClient",
35
+ "HungerBridge",
36
+ "Stream",
37
+ "Credentials",
38
+ "redeem_pickup",
39
+ "find_release",
40
+ "ReleaseAsset",
41
+ "PROTOCOL_VERSION",
42
+ "MAX_HISTORY",
43
+ "HungerBridgeError",
44
+ "HungerBridgeRateLimit",
45
+ "HungerBridgeAuthError",
46
+ "HungerBridgeForbidden",
47
+ "HungerBridgeNotFound",
48
+ "HungerBridgeConnectionError",
49
+ "InvalidModeError",
50
+ "__version__",
51
+ ]
@@ -1,4 +1,4 @@
1
- '''HMAC-SHA256 request signing (HungerBridge protocol v1).
1
+ """HMAC-SHA256 request signing (HungerBridge protocol v1).
2
2
 
3
3
  Signature input (``string_to_sign``)::
4
4
 
@@ -6,7 +6,7 @@ Signature input (``string_to_sign``)::
6
6
 
7
7
  The key is the 32-byte per-token secret handed out once by the server's
8
8
  ``/pickup/<id>?passkey=...`` endpoint, encoded as 64 hex characters.
9
- '''
9
+ """
10
10
 
11
11
  from __future__ import annotations
12
12
 
@@ -20,38 +20,38 @@ from typing import Any, Mapping
20
20
  from .canonical import canonical_body, normalize_path
21
21
 
22
22
  __all__ = [
23
- 'HEADER_ID',
24
- 'HEADER_TIMESTAMP',
25
- 'HEADER_NONCE',
26
- 'HEADER_SIGNATURE',
27
- 'Credentials',
28
- 'string_to_sign',
29
- 'sign',
30
- 'build_auth_headers',
23
+ "HEADER_ID",
24
+ "HEADER_TIMESTAMP",
25
+ "HEADER_NONCE",
26
+ "HEADER_SIGNATURE",
27
+ "Credentials",
28
+ "string_to_sign",
29
+ "sign",
30
+ "build_auth_headers",
31
31
  ]
32
32
 
33
- HEADER_ID = 'X-Auth-Id'
34
- HEADER_TIMESTAMP = 'X-Auth-Timestamp'
35
- HEADER_NONCE = 'X-Auth-Nonce'
36
- HEADER_SIGNATURE = 'X-Auth-Signature'
33
+ HEADER_ID = "X-Auth-Id"
34
+ HEADER_TIMESTAMP = "X-Auth-Timestamp"
35
+ HEADER_NONCE = "X-Auth-Nonce"
36
+ HEADER_SIGNATURE = "X-Auth-Signature"
37
37
 
38
38
 
39
39
  @dataclass(frozen=True)
40
40
  class Credentials:
41
- '''A HungerBridge API token (id + hex secret).'''
41
+ """A HungerBridge API token (id + hex secret)."""
42
42
 
43
43
  token_id: str
44
44
  secret: str = field(repr=False)
45
45
 
46
46
  @classmethod
47
- def parse(cls, token_id: str | None, token_secret: str | None = None) -> 'Credentials | None':
48
- '''Build credentials from ``(id, secret)`` or a single ``'id:secret'`` string.
47
+ def parse(cls, token_id: str | None, token_secret: str | None = None) -> "Credentials | None":
48
+ """Build credentials from ``(id, secret)`` or a single ``"id:secret"`` string.
49
49
 
50
50
  Returns ``None`` when no usable credentials were supplied (unauthenticated
51
51
  client; every protected endpoint will answer 401).
52
- '''
53
- if token_id and not token_secret and ':' in token_id:
54
- token_id, _, token_secret = token_id.rpartition(':')
52
+ """
53
+ if token_id and not token_secret and ":" in token_id:
54
+ token_id, _, token_secret = token_id.rpartition(":")
55
55
  if not token_id or not token_secret:
56
56
  return None
57
57
  return cls(token_id=token_id.strip(), secret=token_secret.strip())
@@ -62,15 +62,15 @@ class Credentials:
62
62
  return bytes.fromhex(self.secret)
63
63
  except ValueError:
64
64
  # Historical fallback: non-hex secrets are used as raw UTF-8 bytes.
65
- return self.secret.encode('utf-8')
65
+ return self.secret.encode("utf-8")
66
66
 
67
67
 
68
68
  def string_to_sign(method: str, path: str, timestamp: str, nonce: str, body: str) -> str:
69
- return f'{method.strip().upper()}\n{normalize_path(path)}\n{timestamp}\n{nonce}\n{body}'
69
+ return f"{method.strip().upper()}\n{normalize_path(path)}\n{timestamp}\n{nonce}\n{body}"
70
70
 
71
71
 
72
72
  def sign(key: bytes, message: str) -> str:
73
- return hmac.new(key, message.encode('utf-8'), hashlib.sha256).hexdigest()
73
+ return hmac.new(key, message.encode("utf-8"), hashlib.sha256).hexdigest()
74
74
 
75
75
 
76
76
  def build_auth_headers(
@@ -83,12 +83,12 @@ def build_auth_headers(
83
83
  timestamp: int | str | None = None,
84
84
  nonce: str | None = None,
85
85
  ) -> dict:
86
- '''Return request headers including a fresh signature.
86
+ """Return request headers including a fresh signature.
87
87
 
88
88
  A new nonce and timestamp are generated on every call; never reuse the
89
89
  returned headers for another request (including retries) — the server
90
90
  rejects replayed nonces.
91
- '''
91
+ """
92
92
  headers = dict(base_headers or {})
93
93
  if credentials is None:
94
94
  return headers
@@ -1,4 +1,4 @@
1
- '''Backwards-compatibility module.
1
+ """Backwards-compatibility module.
2
2
 
3
3
  The client used to live entirely in this file. It has been split into:
4
4
 
@@ -11,7 +11,7 @@ The client used to live entirely in this file. It has been split into:
11
11
 
12
12
  Existing imports such as ``from hungerbridge.bridge import BridgeClient``
13
13
  keep working.
14
- '''
14
+ """
15
15
 
16
16
  from __future__ import annotations
17
17
 
@@ -22,9 +22,9 @@ from .exceptions import HungerBridgeError, HungerBridgeRateLimit, InvalidModeErr
22
22
  from .stream import Stream
23
23
  from .units import convert
24
24
 
25
- __all__ = ['BridgeClient', 'Stream', 'HungerBridgeError', 'HungerBridgeRateLimit', 'InvalidModeError', 'convert']
25
+ __all__ = ["BridgeClient", "Stream", "HungerBridgeError", "HungerBridgeRateLimit", "InvalidModeError", "convert"]
26
26
 
27
27
 
28
28
  def _canonicalize_json_body(value):
29
- '''Deprecated private helper kept for compatibility (``None`` → ``''``).'''
29
+ """Deprecated private helper kept for compatibility (``None`` → ``''``)."""
30
30
  return _canonical_body(value)
@@ -1,4 +1,4 @@
1
- '''Canonical request encoding shared with the HungerBridge server.
1
+ """Canonical request encoding shared with the HungerBridge server.
2
2
 
3
3
  Everything in this module is part of the wire protocol: the output must match
4
4
  ``com.hungerbridge.common.security.TokenManager`` (``canonicalizeJson`` and
@@ -8,7 +8,7 @@ Rules (protocol v1):
8
8
 
9
9
  * Objects: keys sorted by UTF-16 code unit order (Java ``TreeMap<String>``),
10
10
  no whitespace, ``key:value`` pairs joined with ``,``.
11
- * Strings: JSON escapes for ``'`` ``\\`` ``\\b`` ``\\f`` ``\\n`` ``\\r`` ``\\t``;
11
+ * Strings: JSON escapes for ``"`` ``\\`` ``\\b`` ``\\f`` ``\\n`` ``\\r`` ``\\t``;
12
12
  every other code unit below U+0020 or above U+007F is written as a
13
13
  lower-case ``\\uXXXX`` escape. Characters outside the BMP are written as a
14
14
  UTF-16 surrogate pair (two escapes), exactly like Java does.
@@ -17,7 +17,7 @@ Rules (protocol v1):
17
17
  NaN and infinities are not valid JSON and are rejected.
18
18
  * Paths: query string and fragment removed, leading ``/`` enforced, trailing
19
19
  ``/`` removed (except for the root path).
20
- '''
20
+ """
21
21
 
22
22
  from __future__ import annotations
23
23
 
@@ -26,7 +26,7 @@ import math
26
26
  from typing import Any
27
27
  from urllib.parse import urlparse
28
28
 
29
- __all__ = ['canonical_json', 'canonical_body', 'normalize_path', 'quote_string']
29
+ __all__ = ["canonical_json", "canonical_body", "normalize_path", "quote_string"]
30
30
 
31
31
  _SIMPLE_ESCAPES = {
32
32
  '"': '\\"',
@@ -40,7 +40,7 @@ _SIMPLE_ESCAPES = {
40
40
 
41
41
 
42
42
  def quote_string(value: str | None) -> str:
43
- '''Quote ``value`` as an ASCII-only JSON string literal (Java-compatible).'''
43
+ """Quote ``value`` as an ASCII-only JSON string literal (Java-compatible)."""
44
44
  if value is None:
45
45
  return '""'
46
46
  out = ['"']
@@ -53,71 +53,71 @@ def quote_string(value: str | None) -> str:
53
53
  if code > 0xFFFF:
54
54
  # Java strings are UTF-16: emit the surrogate pair, not a 5+ digit escape.
55
55
  code -= 0x10000
56
- out.append('\\u%04x\\u%04x' % (0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF)))
56
+ out.append("\\u%04x\\u%04x" % (0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF)))
57
57
  elif code < 0x20 or code > 0x7F:
58
- out.append('\\u%04x' % code)
58
+ out.append("\\u%04x" % code)
59
59
  else:
60
60
  out.append(ch)
61
61
  out.append('"')
62
- return ''.join(out)
62
+ return "".join(out)
63
63
 
64
64
 
65
65
  def _utf16_sort_key(key: str) -> bytes:
66
66
  # Java's TreeMap<String> orders by UTF-16 code units; Python orders by code
67
67
  # points. They differ only when non-BMP characters are compared with
68
68
  # characters in U+E000..U+FFFF. Encoding as UTF-16-BE gives Java's order.
69
- return key.encode('utf-16-be', 'surrogatepass')
69
+ return key.encode("utf-16-be", "surrogatepass")
70
70
 
71
71
 
72
72
  def canonical_json(value: Any) -> str:
73
- '''Return the canonical JSON encoding of ``value``.
73
+ """Return the canonical JSON encoding of ``value``.
74
74
 
75
75
  ``None`` encodes as ``null``. Unknown objects are encoded as their ``str()``
76
76
  (quoted), matching the historical client behavior.
77
- '''
77
+ """
78
78
  if value is None:
79
- return 'null'
79
+ return "null"
80
80
  if isinstance(value, bool):
81
- return 'true' if value else 'false'
81
+ return "true" if value else "false"
82
82
  if isinstance(value, int):
83
83
  return str(int(value))
84
84
  if isinstance(value, float):
85
85
  if not math.isfinite(value):
86
- raise ValueError('NaN and infinite floats cannot be encoded as JSON')
86
+ raise ValueError("NaN and infinite floats cannot be encoded as JSON")
87
87
  return json.dumps(value)
88
88
  if isinstance(value, str):
89
89
  return quote_string(value)
90
90
  if isinstance(value, (list, tuple)):
91
- return '[' + ','.join(canonical_json(v) for v in value) + ']'
91
+ return "[" + ",".join(canonical_json(v) for v in value) + "]"
92
92
  if isinstance(value, dict):
93
93
  items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _utf16_sort_key(kv[0]))
94
- return '{' + ','.join(quote_string(k) + ':' + canonical_json(v) for k, v in items) + '}'
94
+ return "{" + ",".join(quote_string(k) + ":" + canonical_json(v) for k, v in items) + "}"
95
95
  return quote_string(str(value))
96
96
 
97
97
 
98
98
  def canonical_body(payload: Any) -> str:
99
- '''Canonical request body: empty string when there is no payload.'''
99
+ """Canonical request body: empty string when there is no payload."""
100
100
  if payload is None:
101
- return ''
101
+ return ""
102
102
  return canonical_json(payload)
103
103
 
104
104
 
105
105
  def normalize_path(path: str | None) -> str:
106
- '''Normalize a request path exactly like ``TokenManager.normalizePath``.'''
106
+ """Normalize a request path exactly like ``TokenManager.normalizePath``."""
107
107
  if not path:
108
- return '/'
108
+ return "/"
109
109
  normalized = path.strip()
110
110
  if not normalized:
111
- return '/'
112
- if '://' in normalized:
111
+ return "/"
112
+ if "://" in normalized:
113
113
  try:
114
- normalized = urlparse(normalized).path or '/'
114
+ normalized = urlparse(normalized).path or "/"
115
115
  except ValueError:
116
- normalized = normalized.split('://', 1)[1]
117
- normalized = '/' + normalized.split('/', 1)[1] if '/' in normalized else '/'
118
- normalized = normalized.split('?', 1)[0].split('#', 1)[0]
119
- if not normalized.startswith('/'):
120
- normalized = '/' + normalized
121
- while len(normalized) > 1 and normalized.endswith('/'):
116
+ normalized = normalized.split("://", 1)[1]
117
+ normalized = "/" + normalized.split("/", 1)[1] if "/" in normalized else "/"
118
+ normalized = normalized.split("?", 1)[0].split("#", 1)[0]
119
+ if not normalized.startswith("/"):
120
+ normalized = "/" + normalized
121
+ while len(normalized) > 1 and normalized.endswith("/"):
122
122
  normalized = normalized[:-1]
123
- return normalized or '/'
123
+ return normalized or "/"