coffeejson 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.
coffeejson/codec.py ADDED
@@ -0,0 +1,442 @@
1
+ """The share-URL and file bindings: decode, envelope check and encode.
2
+
3
+ A decode reads the transport framing and the envelope and stops; it never reads
4
+ inside a collection. A payload can decode cleanly and still be schema-invalid —
5
+ saying so is :func:`coffeejson.validate`'s job, and importing never depends on
6
+ it (https://coffeejson.org/docs/integration-guide#consuming--the-import-checklist).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import json
13
+ import math
14
+ import re
15
+ import unicodedata
16
+ import zlib
17
+ from typing import IO, Any, Final, Literal, NoReturn, get_args
18
+ from urllib.parse import parse_qsl
19
+
20
+ from .version import SUPPORTED_MAJOR
21
+
22
+ MAX_PAYLOAD_BYTES: Final = 8192
23
+ """The cap on the JSON document a share payload carries, as sent or inflated
24
+ (https://coffeejson.org/docs/transport#encoding)."""
25
+
26
+ DecodeErrorKind = Literal[
27
+ "no_payload",
28
+ "malformed_base64",
29
+ "unrecognized_encoding",
30
+ "damaged_compression",
31
+ "too_large",
32
+ "not_utf8",
33
+ "not_json",
34
+ "not_a_document",
35
+ "unsupported_version",
36
+ "empty_document",
37
+ "not_a_url",
38
+ "not_http",
39
+ ]
40
+
41
+ DECODE_ERROR_KINDS: Final[tuple[DecodeErrorKind, ...]] = get_args(DecodeErrorKind)
42
+ """Why a payload did not become a document, in decode order — the twelve names
43
+ https://coffeejson.org/docs/integration-guide tabulates and every reference
44
+ implementation reports."""
45
+
46
+
47
+ class DecodeError(ValueError):
48
+ """A decode failure, named by one of :data:`DECODE_ERROR_KINDS`."""
49
+
50
+ kind: DecodeErrorKind
51
+ detail: str | None
52
+
53
+ def __init__(self, kind: DecodeErrorKind, detail: str | None = None) -> None:
54
+ super().__init__(kind if detail is None else f"{kind}: {detail}")
55
+ self.kind = kind
56
+ self.detail = detail
57
+
58
+
59
+ def _fail(kind: DecodeErrorKind, detail: str | None = None) -> NoReturn:
60
+ raise DecodeError(kind, detail)
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Decode
65
+ # ---------------------------------------------------------------------------
66
+
67
+ _ASCII_WHITESPACE = "\t\n\f\r "
68
+ _BASE64_BODY = re.compile(r"[A-Za-z0-9+/]*")
69
+ _VERSION = re.compile(r"(0|[1-9][0-9]*)\.[0-9]+")
70
+ _UTF8_BOM = b"\xef\xbb\xbf"
71
+ _BOM = chr(0xFEFF) # U+FEFF, the byte-order mark as text
72
+
73
+
74
+ def _base64_bytes(raw: str) -> bytes | None:
75
+ """Base64 in either alphabet to bytes: remove ASCII whitespace and trailing
76
+ ``=``, translate ``-_`` to ``+/``, re-pad to a multiple of four, then decode as the WHATWG
77
+ forgiving-base64 algorithm does (https://coffeejson.org/docs/transport#encoding).
78
+ ``None`` when the text is not Base64."""
79
+ text = "".join(ch for ch in raw if ch not in _ASCII_WHITESPACE).rstrip("=")
80
+ text = text.replace("-", "+").replace("_", "/")
81
+ if len(text) % 4 == 1 or not _BASE64_BODY.fullmatch(text):
82
+ return None
83
+ return base64.b64decode(text + "=" * (-len(text) % 4))
84
+
85
+
86
+ def _inflate_bounded(data: bytes) -> bytes:
87
+ """Inflate a zlib stream, refusing to produce more than the cap.
88
+
89
+ The output is bounded while inflating, never measured afterwards: a kilobyte
90
+ of payload can carry megabytes (https://coffeejson.org/docs/transport#encoding).
91
+ """
92
+ inflater = zlib.decompressobj()
93
+ try:
94
+ out = inflater.decompress(data, MAX_PAYLOAD_BYTES + 1)
95
+ except zlib.error as e:
96
+ _fail("damaged_compression", str(e))
97
+ if len(out) > MAX_PAYLOAD_BYTES:
98
+ _fail("too_large", f"inflates past {MAX_PAYLOAD_BYTES} bytes")
99
+ # A stream cut short, or bytes after its checksum, did not survive the wire.
100
+ if not inflater.eof:
101
+ _fail("damaged_compression", "truncated stream")
102
+ if inflater.unused_data:
103
+ _fail("damaged_compression", "bytes after the checksum")
104
+ return out
105
+
106
+
107
+ def _payload_body(data: bytes) -> bytes:
108
+ """Dispatch on the first decoded byte, once, and commit
109
+ (https://coffeejson.org/docs/transport#compression).
110
+
111
+ A plain payload begins ``{``. A zlib stream carries CM 8 in the low nibble
112
+ and passes zlib's own header check with no preset dictionary; ``0x7B``
113
+ cannot. Testing for ``0x78`` exactly would reject a legal smaller window.
114
+ """
115
+ if not data:
116
+ _fail("unrecognized_encoding")
117
+ b0 = data[0]
118
+ if b0 == 0x7B:
119
+ if len(data) > MAX_PAYLOAD_BYTES:
120
+ _fail("too_large", f"{len(data)} bytes")
121
+ return data
122
+ is_zlib = (
123
+ len(data) >= 2 and b0 & 0x0F == 8 and ((b0 << 8) | data[1]) % 31 == 0 and not data[1] & 0x20
124
+ )
125
+ if not is_zlib:
126
+ _fail("unrecognized_encoding", f"first byte 0x{b0:02X}")
127
+ return _inflate_bounded(data)
128
+
129
+
130
+ def _reject_constant(name: str) -> NoReturn:
131
+ raise ValueError(f"{name} is not JSON")
132
+
133
+
134
+ def _parse_int(digits: str) -> int | float:
135
+ # An integer past Python's digit limit reads as a double, as it does in
136
+ # every ECMAScript JSON parser, rather than failing the parse.
137
+ try:
138
+ return int(digits)
139
+ except ValueError:
140
+ return float(digits)
141
+
142
+
143
+ def _parse_json(text: str) -> Any:
144
+ """Parse JSON and only JSON: ``NaN`` and ``Infinity`` are not JSON."""
145
+ try:
146
+ return json.loads(text, parse_constant=_reject_constant, parse_int=_parse_int)
147
+ except RecursionError:
148
+ _fail("not_json", "nested too deeply")
149
+ except ValueError as e:
150
+ _fail("not_json", str(e))
151
+
152
+
153
+ def _utf8_text(data: bytes) -> str:
154
+ try:
155
+ return data.decode("utf-8")
156
+ except UnicodeDecodeError as e:
157
+ _fail("not_utf8", str(e))
158
+
159
+
160
+ def check_envelope(value: object) -> dict[str, Any]:
161
+ """The envelope check on already-parsed JSON — an HTTP body, an uploaded
162
+ file, a paste. Same rules and same failure names as a decoded share link.
163
+
164
+ Accepts a JSON object carrying a ``coffeejson`` version of the major this
165
+ build reads and at least one non-empty ``beans`` or ``recipes``, and returns
166
+ it unchanged. Nothing past that is read.
167
+ """
168
+ if not isinstance(value, dict):
169
+ _fail("not_a_document")
170
+ version = value.get("coffeejson")
171
+ if not isinstance(version, str):
172
+ _fail("not_a_document")
173
+ # MAJOR.MINOR, no patch component and no leading zero on the major — the
174
+ # wire grammar. A spelling outside it names no major to gate on.
175
+ m = _VERSION.fullmatch(version)
176
+ if m is None or m.group(1) != SUPPORTED_MAJOR:
177
+ _fail("unsupported_version", version)
178
+ # Absent and empty are one claim, and a tastings-only document is the same
179
+ # rejection. After the version gate on purpose: this build cannot judge a
180
+ # newer major's envelope.
181
+ if not (_carries(value, "beans") or _carries(value, "recipes")):
182
+ _fail("empty_document")
183
+ return value
184
+
185
+
186
+ def _carries(doc: dict[str, Any], key: str) -> bool:
187
+ item = doc.get(key)
188
+ return isinstance(item, list) and len(item) > 0
189
+
190
+
191
+ def decode_payload(raw: str) -> dict[str, Any]:
192
+ """Decode the ``d`` value of a share URL: ``base64url(JSON)`` or
193
+ ``base64url(zlib(JSON))`` (https://coffeejson.org/docs/transport#encoding)."""
194
+ if not raw:
195
+ _fail("no_payload")
196
+ data = _base64_bytes(raw)
197
+ if data is None:
198
+ _fail("malformed_base64")
199
+ text = _utf8_text(_payload_body(data))
200
+ # A UTF-8 decoder discards a leading byte-order mark, as `TextDecoder` does.
201
+ if text.startswith(_BOM):
202
+ text = text[1:]
203
+ return check_envelope(_parse_json(text))
204
+
205
+
206
+ def decode_document_text(text: str) -> dict[str, Any]:
207
+ """Read a document from the text of a file, discarding one leading
208
+ byte-order mark, which the File binding tells a consumer to tolerate
209
+ (https://coffeejson.org/docs/transport#file)."""
210
+ if text.startswith(_BOM):
211
+ text = text[1:]
212
+ return check_envelope(_parse_json(text))
213
+
214
+
215
+ def decode_document_bytes(data: bytes) -> dict[str, Any]:
216
+ """Read a document from the bytes of a file: strict UTF-8, one leading
217
+ UTF-8 byte-order mark discarded."""
218
+ if data.startswith(_UTF8_BOM):
219
+ data = data[len(_UTF8_BOM) :]
220
+ return check_envelope(_parse_json(_utf8_text(data)))
221
+
222
+
223
+ # The scheme grammar of RFC 3986 § 3.1, as the WHATWG URL parser reads it after
224
+ # trimming C0 controls and spaces and dropping tabs and newlines.
225
+ _SCHEME = re.compile(r"([A-Za-z][A-Za-z0-9+.\-]*):(.*)", re.DOTALL)
226
+ _C0_OR_SPACE = "".join(chr(c) for c in range(0x21))
227
+ _FORBIDDEN_HOST = re.compile(r"[\x00-\x20\x7f#/:<>?@\[\\\]^|]")
228
+
229
+
230
+ def _share_url_query(text: str) -> str | None:
231
+ """The query of a scanned http(s) URL, or ``None`` when it has none.
232
+
233
+ The checks run before anything is read: text that is not a URL is the
234
+ ordinary case for a scanner, and a ``javascript:`` or ``data:`` URL must be
235
+ refused for its scheme before its payload is touched
236
+ (https://coffeejson.org/docs/transport#accepting-links-from-any-host).
237
+ """
238
+ s = text.strip(_C0_OR_SPACE)
239
+ s = s.replace("\t", "").replace("\n", "").replace("\r", "")
240
+ m = _SCHEME.fullmatch(s)
241
+ if m is None:
242
+ _fail("not_a_url")
243
+ scheme = m.group(1).lower()
244
+ if scheme not in ("http", "https"):
245
+ _fail("not_http", f"{scheme}:")
246
+ # http(s) always has an authority; a backslash reads as a slash there.
247
+ rest = m.group(2).lstrip("/\\")
248
+ authority = re.split(r"[/\\?#]", rest, maxsplit=1)[0]
249
+ if not _valid_host_port(authority.rpartition("@")[2]):
250
+ _fail("not_a_url", "no valid host")
251
+ before_fragment = rest.split("#", 1)[0]
252
+ return before_fragment.split("?", 1)[1] if "?" in before_fragment else None
253
+
254
+
255
+ def _valid_host_port(hostport: str) -> bool:
256
+ if hostport.startswith("["): # an IPv6 literal
257
+ end = hostport.find("]")
258
+ tail = hostport[end + 1 :]
259
+ if end < 2 or (tail and not tail.startswith(":")):
260
+ return False
261
+ port = tail[1:]
262
+ else:
263
+ host, _, port = hostport.partition(":")
264
+ if not host or _FORBIDDEN_HOST.search(host):
265
+ return False
266
+ # Not `int(port)`: a port of thousands of digits raises instead of failing.
267
+ digits = port.lstrip("0")
268
+ return port == "" or (
269
+ port.isascii() and port.isdigit() and len(digits) <= 5 and int(digits or "0") <= 65535
270
+ )
271
+
272
+
273
+ def decode_scanned(text: str) -> dict[str, Any]:
274
+ """A scanned string in, a document or a :class:`DecodeError` out — the whole
275
+ share-link binding in one call.
276
+
277
+ Accepts a link from any host, because a share link is self-contained. The
278
+ payload is the first ``d`` query item; the fragment is never read.
279
+ """
280
+ query = _share_url_query(text)
281
+ if query is None:
282
+ _fail("no_payload")
283
+ for name, value in parse_qsl(query, keep_blank_values=True):
284
+ if name == "d":
285
+ return decode_payload(value)
286
+ _fail("no_payload")
287
+
288
+
289
+ # ---------------------------------------------------------------------------
290
+ # Encode
291
+ # ---------------------------------------------------------------------------
292
+
293
+ # The linking members, by collection. Association is a byte-exact match, so a
294
+ # producer MUST emit these in NFC or the same visible id in two normalization
295
+ # forms silently fails to link
296
+ # (https://coffeejson.org/docs/spec/02-envelope#association-explicit-reference).
297
+ # Human text is the producer's own and is left unchanged.
298
+ _LINKING_KEYS: Final = {
299
+ "beans": ("id",),
300
+ "recipes": ("id", "bean_ref"),
301
+ "tastings": ("id", "recipe_ref", "bean_ref"),
302
+ }
303
+
304
+ _LONE_SURROGATE = re.compile("[\ud800-\udfff]")
305
+ _NESTED_TOO_DEEPLY = "the document is nested too deeply to encode"
306
+
307
+
308
+ def _wire_value(value: Any) -> Any:
309
+ """A copy fit for the wire: absence is the null, so a ``None`` member is
310
+ dropped at every depth, and an integral float is written as an integer, as
311
+ every ECMAScript producer writes it."""
312
+ if isinstance(value, dict):
313
+ return {k: _wire_value(v) for k, v in value.items() if v is not None}
314
+ if isinstance(value, (list, tuple)):
315
+ return [_wire_value(v) for v in value]
316
+ if isinstance(value, float) and value.is_integer() and abs(value) < 1e21:
317
+ return int(value)
318
+ return value
319
+
320
+
321
+ def _wire_copy(doc: Any) -> Any:
322
+ """Works on a copy, so encoding a document never rewrites the caller's."""
323
+ out = _wire_value(doc)
324
+ if isinstance(out, dict):
325
+ for collection, keys in _LINKING_KEYS.items():
326
+ members = out.get(collection)
327
+ if not isinstance(members, list):
328
+ continue
329
+ for member in members:
330
+ if not isinstance(member, dict):
331
+ continue
332
+ for key in keys:
333
+ if isinstance(member.get(key), str):
334
+ member[key] = unicodedata.normalize("NFC", member[key])
335
+ return out
336
+
337
+
338
+ def _escape_lone_surrogates(text: str) -> str:
339
+ # ECMAScript's JSON.stringify writes a lone surrogate as an escape, which
340
+ # keeps the output encodable as UTF-8.
341
+ return _LONE_SURROGATE.sub(lambda m: f"\\u{ord(m.group()):04x}", text)
342
+
343
+
344
+ def _js_number(n: float) -> str:
345
+ """A float as ECMAScript's ``Number.prototype.toString`` spells it, so the
346
+ same document makes the same payload in every implementation."""
347
+ if not math.isfinite(n):
348
+ raise ValueError(f"{n!r} is not a JSON number")
349
+ if n == 0:
350
+ return "0"
351
+ sign = "-" if n < 0 else ""
352
+ # Not `repr`: a float subclass, such as numpy's, can print something else.
353
+ mantissa, _, exp = float.__repr__(float.__abs__(n)).partition("e")
354
+ whole, _, frac = mantissa.partition(".")
355
+ digits = (whole + frac).lstrip("0")
356
+ significant = digits.rstrip("0")
357
+ k = len(significant)
358
+ point = int(exp or 0) - len(frac) + (len(digits) - k) + k
359
+ if k <= point <= 21:
360
+ body = significant + "0" * (point - k)
361
+ elif 0 < point <= 21:
362
+ body = f"{significant[:point]}.{significant[point:]}"
363
+ elif -6 < point <= 0:
364
+ body = "0." + "0" * -point + significant
365
+ else:
366
+ e = point - 1
367
+ head = significant if k == 1 else f"{significant[0]}.{significant[1:]}"
368
+ body = f"{head}e{'+' if e >= 0 else '-'}{abs(e)}"
369
+ return sign + body
370
+
371
+
372
+ def _compact_json(value: Any) -> str:
373
+ """Compact JSON spelled as ECMAScript's ``JSON.stringify`` spells it."""
374
+ if value is None:
375
+ return "null"
376
+ if value is True:
377
+ return "true"
378
+ if value is False:
379
+ return "false"
380
+ if isinstance(value, int):
381
+ return int.__repr__(value)
382
+ if isinstance(value, float):
383
+ return _js_number(value)
384
+ if isinstance(value, str):
385
+ return json.dumps(value, ensure_ascii=False)
386
+ if isinstance(value, list):
387
+ return "[" + ",".join(_compact_json(v) for v in value) + "]"
388
+ if isinstance(value, dict):
389
+ members = []
390
+ for k, v in value.items():
391
+ if not isinstance(k, str):
392
+ raise TypeError(f"object keys must be strings, not {type(k).__name__}")
393
+ members.append(f"{json.dumps(k, ensure_ascii=False)}:{_compact_json(v)}")
394
+ return "{" + ",".join(members) + "}"
395
+ raise TypeError(f"{type(value).__name__} is not JSON serializable")
396
+
397
+
398
+ def encode_payload(doc: Any, *, compress: bool = False) -> str:
399
+ """The ``d`` value of a share URL: base64url, unpadded, of the compact UTF-8
400
+ JSON — zlib-compressed first when ``compress`` is true.
401
+
402
+ Raises :class:`ValueError` when the JSON exceeds :data:`MAX_PAYLOAD_BYTES`,
403
+ a link every conformant consumer rejects, or when the document is nested too
404
+ deeply to encode.
405
+ """
406
+ try:
407
+ text = _compact_json(_wire_copy(doc))
408
+ except RecursionError:
409
+ raise ValueError(_NESTED_TOO_DEEPLY) from None
410
+ data = _escape_lone_surrogates(text).encode("utf-8")
411
+ if len(data) > MAX_PAYLOAD_BYTES:
412
+ raise ValueError(
413
+ f"the document is {len(data)} bytes of JSON; a share payload carries "
414
+ f"at most {MAX_PAYLOAD_BYTES}"
415
+ )
416
+ if compress:
417
+ data = zlib.compress(data, 9)
418
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
419
+
420
+
421
+ def share_url(doc: Any, host: str = "coffeejson.org", *, compress: bool = True) -> str:
422
+ """A self-contained share link, ``https://<host>/r?d=<payload>``
423
+ (https://coffeejson.org/docs/transport#share-url). Compressed by default,
424
+ as the binding recommends."""
425
+ return f"https://{host}/r?d={encode_payload(doc, compress=compress)}"
426
+
427
+
428
+ def dumps(doc: Any, *, indent: int | None = 2) -> str:
429
+ """The File binding's text: JSON with ``None`` members dropped and the
430
+ linking members in NFC. Pass ``indent=None`` for compact output."""
431
+ try:
432
+ text = json.dumps(_wire_copy(doc), ensure_ascii=False, indent=indent, allow_nan=False)
433
+ except RecursionError:
434
+ raise ValueError(_NESTED_TOO_DEEPLY) from None
435
+ text = _escape_lone_surrogates(text)
436
+ return text + "\n" if indent is not None else text
437
+
438
+
439
+ def dump(doc: Any, fp: IO[bytes], *, indent: int | None = 2) -> None:
440
+ """Write :func:`dumps` to a binary file as UTF-8 with no byte-order mark
441
+ (https://coffeejson.org/docs/transport#file)."""
442
+ fp.write(dumps(doc, indent=indent).encode("utf-8"))