echidnae-fetch 0.2.1__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.
@@ -0,0 +1,16 @@
1
+ """JavaScript-style fetch, response objects and promises for Python."""
2
+
3
+ from .fetch import FetchError, Headers, Request, Response, fetch
4
+ from .jsonobject import JSONObject, JSONValue
5
+ from .promise import Promise
6
+
7
+ __all__ = [
8
+ "FetchError",
9
+ "Headers",
10
+ "JSONObject",
11
+ "JSONValue",
12
+ "Promise",
13
+ "Request",
14
+ "Response",
15
+ "fetch",
16
+ ]
@@ -0,0 +1,441 @@
1
+ """A standard-library implementation of the core echidnae.javascript Fetch API for Python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gzip
6
+ import json
7
+ import math
8
+ import re
9
+ import zlib
10
+ from collections.abc import Iterable, Iterator, Mapping, MutableMapping
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from http.client import HTTPException
13
+ from threading import Lock
14
+ from typing import Literal
15
+ from urllib.error import HTTPError, URLError
16
+ from urllib.parse import quote, urljoin, urlsplit, urlunsplit
17
+ from urllib.request import HTTPRedirectHandler, Request as URLRequest, build_opener
18
+
19
+ from .jsonobject import JSONObject, JSONValue
20
+ from .promise import Promise
21
+
22
+ type BodyInit = str | bytes | bytearray | memoryview | None
23
+ type HeadersInit = Mapping[str, str] | Iterable[tuple[str, str]]
24
+ type Redirect = Literal["follow", "error", "manual"]
25
+
26
+ _TOKEN = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+\Z")
27
+ _OPTIONS = frozenset({"method", "headers", "body", "redirect", "timeout"})
28
+ _REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
29
+ _NULL_BODY_STATUSES = frozenset({204, 205, 304})
30
+ _network = ThreadPoolExecutor(max_workers=8, thread_name_prefix="fetch")
31
+
32
+
33
+ class FetchError(TypeError):
34
+ """A network failure, distinct from an HTTP error status on a Response."""
35
+
36
+
37
+ class Headers(MutableMapping[str, str]):
38
+ """Case-insensitive headers with ``get``, ``set``, ``append`` and ``delete``."""
39
+
40
+ def __init__(self, values: HeadersInit | None = None) -> None:
41
+ self._values: dict[str, str] = {}
42
+ self._immutable = False
43
+ if values is not None:
44
+ pairs = values.items() if isinstance(values, Mapping) else values
45
+ for name, value in pairs:
46
+ self.append(name, value)
47
+
48
+ @staticmethod
49
+ def _name(name: str) -> str:
50
+ if not isinstance(name, str) or not _TOKEN.fullmatch(name):
51
+ raise TypeError("Header names must be valid HTTP tokens")
52
+ return name.lower()
53
+
54
+ @staticmethod
55
+ def _value(value: str) -> str:
56
+ if not isinstance(value, str):
57
+ raise TypeError("Header values must be strings")
58
+ if any(character in value for character in "\r\n\0"):
59
+ raise TypeError("Header values cannot contain a newline or null byte")
60
+ try:
61
+ value.encode("latin-1")
62
+ except UnicodeEncodeError as error:
63
+ raise TypeError("Header values must be representable as HTTP bytes") from error
64
+ return value.strip(" \t")
65
+
66
+ def _check_mutable(self) -> None:
67
+ if self._immutable:
68
+ raise TypeError("Headers on a fetched response are immutable")
69
+
70
+ def __getitem__(self, name: str) -> str:
71
+ return self._values[self._name(name)]
72
+
73
+ def __setitem__(self, name: str, value: str) -> None:
74
+ self._check_mutable()
75
+ self._values[self._name(name)] = self._value(value)
76
+
77
+ def __delitem__(self, name: str) -> None:
78
+ self._check_mutable()
79
+ del self._values[self._name(name)]
80
+
81
+ def __iter__(self) -> Iterator[str]:
82
+ return iter(sorted(self._values))
83
+
84
+ def __len__(self) -> int:
85
+ return len(self._values)
86
+
87
+ def set(self, name: str, value: str) -> None:
88
+ self[name] = value
89
+
90
+ def append(self, name: str, value: str) -> None:
91
+ self._check_mutable()
92
+ name, value = self._name(name), self._value(value)
93
+ if name in self._values:
94
+ value = f"{self._values[name]}, {value}"
95
+ self._values[name] = value
96
+
97
+ def delete(self, name: str) -> None:
98
+ self._check_mutable()
99
+ self._values.pop(self._name(name), None)
100
+
101
+ def has(self, name: str) -> bool:
102
+ return self._name(name) in self._values
103
+
104
+ def entries(self) -> Iterator[tuple[str, str]]:
105
+ return iter(self.items())
106
+
107
+
108
+ def _body_bytes(body: BodyInit, headers: Headers) -> bytes | None:
109
+ if body is None:
110
+ return None
111
+ if isinstance(body, str):
112
+ if not headers.has("content-type"):
113
+ headers.set("content-type", "text/plain;charset=UTF-8")
114
+ return body.encode("utf-8")
115
+ if isinstance(body, (bytes, bytearray, memoryview)):
116
+ return bytes(body)
117
+ raise TypeError("body must be text or bytes; use json.dumps() for a JSON request")
118
+
119
+
120
+ def _parse_json(data: bytes) -> JSONValue:
121
+ def invalid_constant(value: str):
122
+ raise json.JSONDecodeError(f"Invalid JSON constant: {value}", value, 0)
123
+
124
+ return json.loads(
125
+ data.decode("utf-8-sig", errors="replace"),
126
+ object_hook=JSONObject,
127
+ parse_constant=invalid_constant,
128
+ )
129
+
130
+
131
+ class _Body:
132
+ def _initialize_body(self, data: bytes | None) -> None:
133
+ self._body: Promise[bytes] | None = None if data is None else Promise.resolve(data)
134
+ self._body_used = False
135
+ self._body_lock = Lock()
136
+
137
+ @property
138
+ def bodyUsed(self) -> bool:
139
+ with self._body_lock:
140
+ return self._body_used
141
+
142
+ def _mark_body_used(self) -> None:
143
+ with self._body_lock:
144
+ if self._body_used:
145
+ raise TypeError("Body has already been consumed; clone it before reading")
146
+ if self._body is not None:
147
+ self._body_used = True
148
+
149
+ def _consume(self, transform) -> Promise:
150
+ try:
151
+ self._mark_body_used()
152
+ except TypeError as error:
153
+ return Promise.reject(error)
154
+ body = self._body if self._body is not None else Promise.resolve(b"")
155
+ return body.then(transform)
156
+
157
+ def json(self) -> Promise[JSONValue]:
158
+ """Consume and parse JSON; objects, including nested objects, are JSONObject."""
159
+ return self._consume(_parse_json)
160
+
161
+ def text(self) -> Promise[str]:
162
+ """Consume UTF-8 text, replacing invalid byte sequences like echidnae.javascript does."""
163
+ return self._consume(lambda data: data.decode("utf-8-sig", errors="replace"))
164
+
165
+ def bytes(self) -> Promise[bytes]:
166
+ """Consume the body as Python bytes."""
167
+ return self._consume(lambda data: data)
168
+
169
+ def arrayBuffer(self) -> Promise[bytes]:
170
+ """Python's immutable bytes represent echidnae.javascript's ArrayBuffer result."""
171
+ return self.bytes()
172
+
173
+
174
+ def _url(value: str) -> str:
175
+ if not isinstance(value, str):
176
+ raise TypeError("resource must be an absolute HTTP(S) URL or a Request")
177
+ try:
178
+ parts = urlsplit(value)
179
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
180
+ raise ValueError("Missing HTTP(S) scheme or hostname")
181
+ if parts.username is not None or parts.password is not None:
182
+ raise ValueError("Credentials in URLs are unsupported")
183
+ hostname = parts.hostname.encode("idna").decode("ascii")
184
+ if ":" in hostname:
185
+ hostname = f"[{hostname}]"
186
+ authority = hostname if parts.port is None else f"{hostname}:{parts.port}"
187
+ path = quote(parts.path or "/", safe="/%:@!$&'()*+,;=-._~")
188
+ query = quote(parts.query, safe="/%?:@!$&'()*+,;=-._~")
189
+ return urlunsplit((parts.scheme, authority, path, query, ""))
190
+ except (ValueError, UnicodeError) as error:
191
+ raise TypeError("resource must be a valid absolute HTTP(S) URL without credentials") from error
192
+
193
+
194
+ def _options(options: Mapping[str, object] | None, keywords: dict) -> dict:
195
+ if options is not None and not isinstance(options, Mapping):
196
+ raise TypeError("options must be a mapping")
197
+ values = dict(options or {})
198
+ values.update(keywords)
199
+ unsupported = values.keys() - _OPTIONS
200
+ if unsupported:
201
+ raise TypeError(f"Unsupported fetch options: {', '.join(sorted(map(str, unsupported)))}")
202
+ return values
203
+
204
+
205
+ class Request(_Body):
206
+ """A URL plus request options. Options override an existing Request's settings."""
207
+
208
+ def __init__(
209
+ self,
210
+ resource: str | Request,
211
+ options: Mapping[str, object] | None = None,
212
+ **keywords: object,
213
+ ) -> None:
214
+ values = _options(options, keywords)
215
+ original = resource if isinstance(resource, Request) else None
216
+ if original is not None and original.bodyUsed:
217
+ raise TypeError("Cannot copy a Request whose body has been consumed")
218
+ self._url = original.url if original is not None else _url(resource)
219
+ method = values.get("method", original.method if original is not None else "GET")
220
+ if not isinstance(method, str) or not _TOKEN.fullmatch(method):
221
+ raise TypeError("method must be a valid HTTP token")
222
+ if method.upper() in {"CONNECT", "TRACE", "TRACK"}:
223
+ raise TypeError("CONNECT, TRACE and TRACK are forbidden fetch methods")
224
+ if method.upper() in {"DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"}:
225
+ method = method.upper()
226
+ self._method = method
227
+ self._headers = Headers(values.get("headers", original.headers if original else None))
228
+ body = values.get("body", original._data if original is not None else None)
229
+ self._data = _body_bytes(body, self.headers)
230
+ if method in {"GET", "HEAD"} and self._data is not None:
231
+ raise TypeError("GET and HEAD requests cannot have a body")
232
+ self._redirect = values.get("redirect", original.redirect if original else "follow")
233
+ if self._redirect not in {"follow", "error", "manual"}:
234
+ raise TypeError("redirect must be 'follow', 'error' or 'manual'")
235
+ timeout = values.get("timeout", original.timeout if original else None)
236
+ if timeout is not None:
237
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
238
+ raise TypeError("timeout must be a positive, finite number of seconds or None")
239
+ if not math.isfinite(timeout) or timeout <= 0:
240
+ raise TypeError("timeout must be a positive, finite number of seconds or None")
241
+ self._timeout = timeout
242
+ self._initialize_body(self._data)
243
+
244
+ @property
245
+ def url(self) -> str:
246
+ return self._url
247
+
248
+ @property
249
+ def method(self) -> str:
250
+ return self._method
251
+
252
+ @property
253
+ def headers(self) -> Headers:
254
+ return self._headers
255
+
256
+ @property
257
+ def redirect(self) -> Redirect:
258
+ return self._redirect
259
+
260
+ @property
261
+ def timeout(self) -> float | None:
262
+ return self._timeout
263
+
264
+ def clone(self) -> Request:
265
+ """Copy a request before its body has been sent or read."""
266
+ return Request(self)
267
+
268
+
269
+ class Response(_Body):
270
+ """HTTP metadata and one-use, promise-returning body readers."""
271
+
272
+ def __init__(
273
+ self,
274
+ body: BodyInit = None,
275
+ *,
276
+ status: int = 200,
277
+ statusText: str = "",
278
+ headers: HeadersInit | None = None,
279
+ ) -> None:
280
+ if isinstance(status, bool) or not isinstance(status, int) or not 200 <= status <= 599:
281
+ raise ValueError("Response status must be an integer between 200 and 599")
282
+ if not isinstance(statusText, str) or any(char in statusText for char in "\r\n"):
283
+ raise TypeError("statusText must be a string without newlines")
284
+ self._status, self._status_text = status, statusText
285
+ self._headers = Headers(headers)
286
+ data = _body_bytes(body, self.headers)
287
+ if status in _NULL_BODY_STATUSES and data is not None:
288
+ raise TypeError("Responses with status 204, 205 or 304 cannot have a body")
289
+ self._url, self._redirected, self._type = "", False, "default"
290
+ self._initialize_body(data)
291
+
292
+ @property
293
+ def ok(self) -> bool:
294
+ return 200 <= self.status <= 299
295
+
296
+ @property
297
+ def status(self) -> int:
298
+ return self._status
299
+
300
+ @property
301
+ def statusText(self) -> str:
302
+ return self._status_text
303
+
304
+ @property
305
+ def headers(self) -> Headers:
306
+ return self._headers
307
+
308
+ @property
309
+ def url(self) -> str:
310
+ return self._url
311
+
312
+ @property
313
+ def redirected(self) -> bool:
314
+ return self._redirected
315
+
316
+ @property
317
+ def type(self) -> str:
318
+ return self._type
319
+
320
+ def clone(self) -> Response:
321
+ """Share the buffered bytes with a new, independently consumable Response."""
322
+ with self._body_lock:
323
+ if self._body_used:
324
+ raise TypeError("Cannot clone a Response whose body has been consumed")
325
+ cloned = Response(headers=self.headers)
326
+ cloned._status, cloned._status_text = self.status, self.statusText
327
+ cloned._url, cloned._redirected, cloned._type = self.url, self.redirected, self.type
328
+ cloned._body = self._body
329
+ cloned.headers._immutable = self.headers._immutable
330
+ return cloned
331
+
332
+
333
+ class _NoRedirect(HTTPRedirectHandler):
334
+ # Let HTTPErrorProcessor expose the response, without urllib interpreting
335
+ # Location first. _send applies the Fetch redirect rules itself.
336
+ def http_error_302(self, request, stream, code, message, headers):
337
+ return None
338
+
339
+ http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
340
+
341
+
342
+ def _origin(url: str) -> tuple[str, str, int]:
343
+ parts = urlsplit(url)
344
+ return parts.scheme, parts.hostname, parts.port or (443 if parts.scheme == "https" else 80)
345
+
346
+
347
+ def _read_body(stream) -> bytes:
348
+ try:
349
+ with stream:
350
+ data = stream.read()
351
+ encodings = stream.headers.get("Content-Encoding", "").lower().split(",")
352
+ for encoding in reversed(encodings):
353
+ encoding = encoding.strip()
354
+ if encoding == "gzip":
355
+ data = gzip.decompress(data)
356
+ elif encoding == "deflate":
357
+ data = zlib.decompress(data)
358
+ elif encoding not in {"", "identity"}:
359
+ raise FetchError("Unsupported response content encoding")
360
+ return data
361
+ except (OSError, EOFError, HTTPException, zlib.error) as error:
362
+ raise FetchError("Reading the response body failed") from error
363
+
364
+
365
+ def _send(request: Request) -> Response:
366
+ opener = build_opener(_NoRedirect())
367
+ url, method, data = request.url, request.method, request._data
368
+ headers = Headers(request.headers)
369
+ redirects = 0
370
+ while True:
371
+ outgoing = URLRequest(url, data=data, headers=dict(headers), method=method)
372
+ try:
373
+ stream = opener.open(outgoing, timeout=request.timeout)
374
+ except HTTPError as response:
375
+ # urllib treats HTTP errors as exceptions; fetch resolves them normally.
376
+ stream = response
377
+ except (URLError, OSError, HTTPException) as error:
378
+ raise FetchError("Network request failed") from error
379
+ status = stream.code
380
+ location = stream.headers.get("Location")
381
+ if status in _REDIRECT_STATUSES and location is not None and request.redirect != "manual":
382
+ stream.close()
383
+ if request.redirect == "error":
384
+ raise FetchError("Redirect encountered with redirect='error'")
385
+ if redirects >= 20:
386
+ raise FetchError("Too many redirects")
387
+ try:
388
+ next_url = _url(urljoin(url, location))
389
+ except (TypeError, ValueError) as error:
390
+ raise FetchError("Invalid redirect URL") from error
391
+ if _origin(url) != _origin(next_url):
392
+ for name in ("authorization", "proxy-authorization", "cookie", "host"):
393
+ headers.delete(name)
394
+ if (status in {301, 302} and method == "POST") or (
395
+ status == 303 and method not in {"GET", "HEAD"}
396
+ ):
397
+ method, data = "GET", None
398
+ for name in (
399
+ "content-encoding", "content-language", "content-location",
400
+ "content-type", "content-length",
401
+ ):
402
+ headers.delete(name)
403
+ url = next_url
404
+ redirects += 1
405
+ continue
406
+ response = Response(headers=stream.headers.items())
407
+ response._status, response._status_text = status, str(stream.reason or "")
408
+ response._url, response._redirected, response._type = url, redirects > 0, "basic"
409
+ response.headers._immutable = True
410
+ if method == "HEAD" or status in _NULL_BODY_STATUSES:
411
+ stream.close()
412
+ else:
413
+ response._body = Promise._from_future(_network.submit(_read_body, stream))
414
+ return response
415
+
416
+
417
+ def fetch(
418
+ resource: str | Request,
419
+ options: Mapping[str, object] | None = None,
420
+ **keywords: object,
421
+ ) -> Promise[Response]:
422
+ """Start an HTTP(S) request and return a Promise resolving to its Response.
423
+
424
+ ``resource`` is an absolute URL or Request. ``options`` accepts ``method``
425
+ (default GET), ``headers``, ``body``, ``redirect`` (default follow), and
426
+ ``timeout`` (seconds, default None). The same options may be passed as Python
427
+ keyword arguments; keywords override the options mapping.
428
+
429
+ HTTP 4xx/5xx responses fulfill the Promise; inspect ``response.ok`` or
430
+ ``response.status``. Invalid requests and network errors reject it. The
431
+ Promise fulfills when headers arrive; body readers wait for the body bytes.
432
+ Browser-only options and streaming bodies are outside this implementation.
433
+ """
434
+ try:
435
+ request = Request(resource, options, **keywords)
436
+ if isinstance(resource, Request):
437
+ resource._mark_body_used()
438
+ request._mark_body_used()
439
+ except (TypeError, ValueError) as error:
440
+ return Promise.reject(error)
441
+ return Promise._from_future(_network.submit(_send, request))
@@ -0,0 +1,30 @@
1
+ """JSON objects with both dictionary lookup and JavaScript-style attribute access."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class JSONObject(dict[str, "JSONValue"]):
7
+ """A JSON object: ``obj['name']`` and ``obj.name`` access the same value.
8
+
9
+ Parsed nested objects also use this class. Keys that overlap dictionary
10
+ methods, such as ``items`` or ``get``, should be accessed with brackets.
11
+ Arrays stay lists and JSON primitives retain their normal Python types.
12
+ """
13
+
14
+ def __getattr__(self, name: str) -> JSONValue:
15
+ try:
16
+ return self[name]
17
+ except KeyError as error:
18
+ raise AttributeError(name) from error
19
+
20
+ def __setattr__(self, name: str, value: JSONValue) -> None:
21
+ self[name] = value
22
+
23
+ def __delattr__(self, name: str) -> None:
24
+ try:
25
+ del self[name]
26
+ except KeyError as error:
27
+ raise AttributeError(name) from error
28
+
29
+
30
+ type JSONValue = JSONObject | list[JSONValue] | str | int | float | bool | None
@@ -0,0 +1,195 @@
1
+ """Awaitable promises with JavaScript-style chaining, using only the standard library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Callable, Iterable
7
+ from concurrent.futures import Future, ThreadPoolExecutor
8
+ from threading import Lock
9
+ from typing import Generic, TypeVar
10
+
11
+ T = TypeVar("T")
12
+ U = TypeVar("U")
13
+
14
+ # Keep user callbacks off the network workers and execute them in registration order.
15
+ _callbacks = ThreadPoolExecutor(max_workers=1, thread_name_prefix="promise")
16
+
17
+
18
+ class Promise(Generic[T]):
19
+ """A value that will be fulfilled or rejected once.
20
+
21
+ An executor, when supplied, runs immediately with ``resolve`` and ``reject``
22
+ callbacks. Handlers run on a separate callback thread. A handler may return a
23
+ value or another Promise; returning a Promise adopts its eventual outcome.
24
+ ``await promise`` is nonblocking; ``promise.result()`` is a blocking Python
25
+ convenience for scripts without an asyncio event loop.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ executor: Callable[[Callable[[T], None], Callable[[BaseException], None]], None],
31
+ ) -> None:
32
+ self._initialize()
33
+ try:
34
+ executor(self._resolve, self._reject)
35
+ except BaseException as error:
36
+ self._reject(error)
37
+
38
+ def _initialize(self) -> None:
39
+ self._future: Future[T] = Future()
40
+ self._lock = Lock()
41
+ self._claimed = False
42
+
43
+ @classmethod
44
+ def _pending(cls) -> Promise:
45
+ promise = cls.__new__(cls)
46
+ promise._initialize()
47
+ return promise
48
+
49
+ @classmethod
50
+ def _from_future(cls, future: Future[T]) -> Promise[T]:
51
+ promise = cls._pending()
52
+ promise._resolve(future)
53
+ return promise
54
+
55
+ def _claim(self) -> bool:
56
+ with self._lock:
57
+ if self._claimed:
58
+ return False
59
+ self._claimed = True
60
+ return True
61
+
62
+ def _resolve(self, value) -> None:
63
+ if not self._claim():
64
+ return
65
+ if value is self:
66
+ self._future.set_exception(TypeError("A Promise cannot resolve to itself"))
67
+ elif isinstance(value, (Promise, Future)):
68
+ future = value._future if isinstance(value, Promise) else value
69
+ future.add_done_callback(self._adopt)
70
+ else:
71
+ self._future.set_result(value)
72
+
73
+ def _adopt(self, future: Future) -> None:
74
+ try:
75
+ value = future.result()
76
+ except BaseException as error:
77
+ self._future.set_exception(error)
78
+ else:
79
+ self._future.set_result(value)
80
+
81
+ def _reject(self, error: BaseException) -> None:
82
+ if self._claim():
83
+ if not isinstance(error, BaseException):
84
+ error = Exception(error)
85
+ self._future.set_exception(error)
86
+
87
+ @classmethod
88
+ def resolve(cls, value: T | Promise[T]) -> Promise[T]:
89
+ """Return an existing Promise, or a fulfilled Promise containing a value."""
90
+ if isinstance(value, cls):
91
+ return value
92
+ promise = cls._pending()
93
+ promise._resolve(value)
94
+ return promise
95
+
96
+ @classmethod
97
+ def reject(cls, error: BaseException) -> Promise:
98
+ """Return a rejected Promise. Python exceptions represent rejection reasons."""
99
+ promise = cls._pending()
100
+ promise._reject(error)
101
+ return promise
102
+
103
+ def then(
104
+ self,
105
+ on_fulfilled: Callable[[T], U | Promise[U]] | None = None,
106
+ on_rejected: Callable[[BaseException], U | Promise[U]] | None = None,
107
+ ) -> Promise[U]:
108
+ """Chain a handler, forwarding an outcome when its handler is omitted."""
109
+ following = self._pending()
110
+
111
+ def run(future: Future[T]) -> None:
112
+ try:
113
+ try:
114
+ value = future.result()
115
+ except BaseException as error:
116
+ if not callable(on_rejected):
117
+ following._reject(error)
118
+ return
119
+ outcome = on_rejected(error)
120
+ else:
121
+ outcome = on_fulfilled(value) if callable(on_fulfilled) else value
122
+ following._resolve(outcome)
123
+ except BaseException as error:
124
+ following._reject(error)
125
+
126
+ self._future.add_done_callback(lambda future: _callbacks.submit(run, future))
127
+ return following
128
+
129
+ def catch(self, on_rejected: Callable[[BaseException], U | Promise[U]]) -> Promise[U]:
130
+ """Handle rejection, equivalent to ``then(None, on_rejected)``."""
131
+ return self.then(None, on_rejected)
132
+
133
+ def finally_(self, on_finally: Callable[[], object]) -> Promise[T]:
134
+ """Run cleanup and preserve the outcome unless cleanup itself fails.
135
+
136
+ Python reserves the word ``finally``, so its method is named ``finally_``.
137
+ A returned Promise is awaited before the original outcome is forwarded.
138
+ """
139
+ if not callable(on_finally):
140
+ return self.then()
141
+
142
+ def fulfilled(value):
143
+ return Promise.resolve(on_finally()).then(lambda _: value)
144
+
145
+ def rejected(error):
146
+ return Promise.resolve(on_finally()).then(lambda _: Promise.reject(error))
147
+
148
+ return self.then(fulfilled, rejected)
149
+
150
+ @classmethod
151
+ def all(cls, values: Iterable[T | Promise[T]]) -> Promise[list[T]]:
152
+ """Fulfill with input-ordered results, or reject on the first failure."""
153
+ combined = cls._pending()
154
+ try:
155
+ promises = [cls.resolve(value) for value in values]
156
+ except BaseException as error:
157
+ combined._reject(error)
158
+ return combined
159
+ results = [None] * len(promises)
160
+ remaining = len(promises)
161
+ lock = Lock()
162
+ if not remaining:
163
+ combined._resolve([])
164
+ return combined
165
+
166
+ def complete(index, value):
167
+ nonlocal remaining
168
+ with lock:
169
+ results[index] = value
170
+ remaining -= 1
171
+ if remaining == 0:
172
+ combined._resolve(results)
173
+
174
+ for index, promise in enumerate(promises):
175
+ promise.then(lambda value, index=index: complete(index, value), combined._reject)
176
+ return combined
177
+
178
+ @classmethod
179
+ def race(cls, values: Iterable[T | Promise[T]]) -> Promise[T]:
180
+ """Adopt the first outcome; an empty iterable leaves the Promise pending."""
181
+ raced = cls._pending()
182
+ try:
183
+ for value in values:
184
+ cls.resolve(value).then(raced._resolve, raced._reject)
185
+ except BaseException as error:
186
+ raced._reject(error)
187
+ return raced
188
+
189
+ def result(self, timeout: float | None = None) -> T:
190
+ """Wait for the outcome. The timeout limits waiting, not the HTTP request."""
191
+ return self._future.result(timeout)
192
+
193
+ def __await__(self):
194
+ # Cancelling one waiter must not cancel a Promise shared by other callers.
195
+ return asyncio.shield(asyncio.wrap_future(self._future)).__await__()
@@ -0,0 +1,243 @@
1
+ Metadata-Version: 2.4
2
+ Name: echidnae-fetch
3
+ Version: 0.2.1
4
+ Summary: JavaScript-style Fetch and Promise APIs for Python
5
+ Author: ellainng
6
+ Author-email: ellainng <299958882+ellainng@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.md
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Programming Language :: Python :: 3.14
11
+ Requires-Python: >=3.14
12
+ Project-URL: Repository, https://github.com/wispsy/echidnae
13
+ Project-URL: Issues, https://github.com/wispsy/echidnae/issues
14
+ Description-Content-Type: text/markdown
15
+
16
+ # echidnae-fetch
17
+
18
+ A Python 3.14 implementation of the core JavaScript Fetch API, built with the
19
+ standard library. There are no runtime dependencies. The HTTP transport uses
20
+ `urllib.request`; requests run on background threads so `await` does not block
21
+ the asyncio event loop.
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ python -m pip install echidnae-fetch
27
+ ```
28
+
29
+ The Python import is `from echidnae.fetch import fetch`.
30
+
31
+ ## GET and JSON
32
+
33
+ Replace the example URL with an HTTP(S) endpoint that returns JSON:
34
+
35
+ ```python
36
+ import asyncio
37
+
38
+ from echidnae.fetch import JSONObject, fetch
39
+
40
+
41
+ async def main() -> None:
42
+ response = await fetch("https://example.com/api/profile") # method defaults to GET
43
+ if not response.ok:
44
+ raise RuntimeError(f"HTTP {response.status}: {response.statusText}")
45
+
46
+ data = await response.json()
47
+ if isinstance(data, JSONObject):
48
+ print(data["name"])
49
+ print(data.name) # attribute access works too
50
+
51
+
52
+ asyncio.run(main())
53
+ ```
54
+
55
+ Like JavaScript, `fetch()` returns a `Promise[Response]`. `response.json()`
56
+ returns another promise, which resolves to parsed data. JSON objects become
57
+ dictionary-compatible `JSONObject` instances, including objects nested inside
58
+ objects or arrays. JSON arrays become lists, and strings, numbers, booleans and
59
+ `null` become Python strings, numbers, booleans and `None`.
60
+
61
+ Attribute access is a Python convenience. Use brackets for keys with spaces or
62
+ keys matching dictionary methods, such as `data["items"]` or `data["get"]`.
63
+ You can serialize a `JSONObject` with the standard `json.dumps()` function.
64
+
65
+ ## Parameters
66
+
67
+ ```python
68
+ fetch(resource, options=None, **keywords) -> Promise[Response]
69
+ ```
70
+
71
+ `resource` is an absolute `http://` or `https://` URL, or a `Request` instance.
72
+ There is no document base URL for relative URLs. URL credentials are rejected.
73
+ `options` is an optional mapping. You may also use Python keyword arguments;
74
+ keywords override matching settings in the mapping.
75
+
76
+ | Option | Accepted value | Default |
77
+ | --- | --- | --- |
78
+ | `method` | HTTP method string, such as `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` or `OPTIONS` | `GET` |
79
+ | `headers` | Mapping of string names to string values, iterable of `(name, value)` pairs, or `Headers` | Empty |
80
+ | `body` | `str`, `bytes`, `bytearray`, `memoryview`, or `None` | `None` |
81
+ | `redirect` | `"follow"`, `"error"`, or `"manual"` | `"follow"` |
82
+ | `timeout` | Positive, finite seconds, or `None`; limits individual socket operations | `None` |
83
+
84
+ `timeout` is a Python extension, not a JavaScript Fetch option. When `resource`
85
+ is a `Request`, omitted options inherit that request's settings. `GET` and
86
+ `HEAD` cannot include a body, even an empty one. `CONNECT`, `TRACE` and `TRACK`
87
+ are rejected. A string body receives `Content-Type: text/plain;charset=UTF-8`
88
+ unless you supply a content type; byte bodies receive no automatic content type.
89
+
90
+ For a JSON request, serialize explicitly, as you would with JavaScript's
91
+ `JSON.stringify()`:
92
+
93
+ ```python
94
+ import json
95
+
96
+ response = await fetch(
97
+ "https://example.com/api/profile",
98
+ {
99
+ "method": "POST",
100
+ "headers": {"Content-Type": "application/json"},
101
+ "body": json.dumps({"name": "Ada"}),
102
+ },
103
+ )
104
+ ```
105
+
106
+ The equivalent keyword form is
107
+ `await fetch(url, method="POST", headers=headers, body=json.dumps(data))`.
108
+
109
+ ## Response
110
+
111
+ The fetch promise resolves when the server's response headers are available.
112
+ The body is read and buffered separately; its promise may still be pending or
113
+ may reject if the connection fails after the headers arrive.
114
+
115
+ | Property | Meaning |
116
+ | --- | --- |
117
+ | `ok` | `True` when `200 <= status <= 299` |
118
+ | `status` | HTTP status code |
119
+ | `statusText` | HTTP reason phrase, such as `"OK"` |
120
+ | `headers` | Case-insensitive `Headers` collection; fetched response headers are immutable |
121
+ | `url` | Final URL after redirects, without its fragment |
122
+ | `redirected` | Whether at least one redirect was followed |
123
+ | `type` | `"basic"` for fetched HTTP responses; `"default"` for constructed responses |
124
+ | `bodyUsed` | Whether this request or response body has been consumed |
125
+
126
+ | Method | Promise result |
127
+ | --- | --- |
128
+ | `json()` | `JSONObject`, list, or JSON primitive, depending on the document |
129
+ | `text()` | UTF-8 string; invalid sequences are replaced and an initial BOM is removed |
130
+ | `bytes()` | Python `bytes` |
131
+ | `arrayBuffer()` | Python `bytes`, representing the JavaScript binary result |
132
+
133
+ Body readers consume a body once. Calling another reader rejects with
134
+ `TypeError`, including after JSON parsing fails. Clone **before** reading if
135
+ you need more than one representation:
136
+
137
+ ```python
138
+ response = await fetch(url)
139
+ copy = response.clone()
140
+ data = await response.json()
141
+ text = await copy.text()
142
+ ```
143
+
144
+ `HEAD` responses and statuses `204`, `205`, and `304` have a null body. Their
145
+ text/binary readers return empty values without setting `bodyUsed`; `json()`
146
+ rejects because an empty body is not JSON.
147
+
148
+ HTTP `404` and `500` fulfill with a response whose `ok` is `False`. Invalid
149
+ requests reject with `TypeError`; network failures reject with `FetchError`, a
150
+ `TypeError` subclass. Invalid JSON rejects its reader with `json.JSONDecodeError`.
151
+ Check the HTTP status yourself when your application treats it as an error.
152
+
153
+ You can construct a response locally with
154
+ `Response('{"name":"Ada"}', status=200, headers={"Content-Type": "application/json"})`.
155
+
156
+ ## Promises
157
+
158
+ Promises support `await`, `.then(on_fulfilled, on_rejected=None)`, `.catch()` and
159
+ `.finally_()`. Python reserves `finally`, so the method has a trailing underscore.
160
+ Handlers return a value or another `Promise`; returned promises are adopted,
161
+ and exceptions raised by handlers reject the next promise.
162
+
163
+ ```python
164
+ from echidnae.fetch import fetch
165
+
166
+
167
+ def read_json(response):
168
+ if not response.ok:
169
+ raise RuntimeError(f"HTTP {response.status}")
170
+ return response.json()
171
+
172
+
173
+ completed = (
174
+ fetch("https://example.com/api/profile")
175
+ .then(read_json)
176
+ .then(lambda data: print(data.name))
177
+ .catch(lambda error: print(f"Request failed: {error}"))
178
+ .finally_(lambda: print("Finished"))
179
+ )
180
+ completed.result() # blocking convenience for a synchronous script
181
+ ```
182
+
183
+ `Promise(executor)` immediately calls `executor(resolve, reject)` and accepts
184
+ only the first resolution or rejection. Rejection reasons use Python exceptions.
185
+ `Promise.resolve(value)`, `Promise.reject(error)`, `Promise.all(iterable)` and
186
+ `Promise.race(iterable)` are also available. `all()` preserves input order and
187
+ rejects on the first failure. `race()` adopts the first settled outcome.
188
+
189
+ Use `await` inside asynchronous code. `.result(timeout=...)` blocks its calling
190
+ thread and only limits how long that caller waits; it does not stop the request.
191
+ Cancelling an asyncio waiter also leaves the shared promise running. Handlers
192
+ execute serially on a background callback thread; Python does not reproduce
193
+ JavaScript's event-loop microtask scheduling. Handlers should return promises
194
+ instead of blocking on `.result()` or returning raw Python coroutines.
195
+
196
+ ## Headers and Request
197
+
198
+ `Headers` provides `.get()`, `.set()`, `.append()`, `.delete()`, `.has()`,
199
+ `.entries()`, `.keys()` and `.values()`, plus normal mapping access.
200
+ Names are case-insensitive, duplicate values are combined with `", "`, and
201
+ invalid HTTP names or values are rejected. Missing `.get()` lookups return
202
+ `None`.
203
+
204
+ `Request(url, options=None, **keywords)` supports the same options as `fetch()`
205
+ and exposes `url`, `method`, `headers`, `redirect`, `timeout`, `bodyUsed`, and
206
+ the same body readers. A request with a body is consumed when fetched; call
207
+ `.clone()` beforehand to reuse it. Requests without bodies may be reused.
208
+
209
+ ## Compatibility scope
210
+
211
+ This implements core HTTP(S) fetch behavior in Python, rather than a complete
212
+ browser environment. Bodies are buffered in memory; `ReadableStream`, `Blob`,
213
+ `FormData`, and `URLSearchParams` objects are not provided. `gzip` and `deflate`
214
+ response encodings are decoded with the standard library.
215
+ Other response content encodings reject the body reader with `FetchError`.
216
+
217
+ Browser policies and options such as `mode`, `credentials`, `cache`, `referrer`,
218
+ `referrerPolicy`, `integrity`, `keepalive`, `signal`, `priority`, and `duplex`
219
+ are not implemented; unsupported options are rejected explicitly. There is no
220
+ cookie jar, browser cache, origin policy, or abort controller. Proxy environment
221
+ settings follow `urllib.request` defaults.
222
+
223
+ Redirects follow Fetch's method/body rules, with a limit of 20. Cross-origin
224
+ redirects remove authorization and cookie headers. `redirect="error"` rejects;
225
+ `redirect="manual"` exposes the actual redirect status, headers and body,
226
+ instead of a browser's filtered `opaqueredirect` response.
227
+
228
+ References: [Fetch Standard](https://fetch.spec.whatwg.org/),
229
+ [ECMAScript Promise specification](https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-objects),
230
+ and [Python urllib.request](https://docs.python.org/3/library/urllib.request.html).
231
+
232
+ ## Verification
233
+
234
+ ```sh
235
+ uv run python -m unittest discover -s tests -v
236
+ ```
237
+
238
+ The tests use only the standard library and local loopback HTTP servers. To run
239
+ without installing the package or its build backend:
240
+
241
+ ```sh
242
+ PYTHONPATH=src python3 -m unittest discover -s tests -v
243
+ ```
@@ -0,0 +1,8 @@
1
+ echidnae/fetch/__init__.py,sha256=1AasnFV_FTC85Q2UVchns8w_OOVYC6K4lua8_1fkHfE,355
2
+ echidnae/fetch/fetch.py,sha256=2uUhg9fPt3cVigTnRef-di_dgx8W6aWWCBkuqsH_gcA,17437
3
+ echidnae/fetch/jsonobject.py,sha256=763HWJxMJpfBQLVhP2f0-87vaZPdPzquRcdn6eDFjrE,1006
4
+ echidnae/fetch/promise.py,sha256=K9s_sgpsFkkcf2PMJaOemgfh66yoy1Y-viYsJwKPh-I,7006
5
+ echidnae_fetch-0.2.1.dist-info/licenses/LICENSE.md,sha256=dJjxPlUliHO6iuJiKxsIn0HSnRRb-dp_8lpVtAunRj8,1063
6
+ echidnae_fetch-0.2.1.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
7
+ echidnae_fetch-0.2.1.dist-info/METADATA,sha256=pojtxW2k0lhhZtLrMadG72RPETZoRB3DHfTn55XZHtg,9757
8
+ echidnae_fetch-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.19
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wispsy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.