vercel-workflow 0.9.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.
@@ -0,0 +1,347 @@
1
+ """Parse devalue JSON wire format back into Python values."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import json
7
+ from collections.abc import Callable
8
+ from datetime import datetime
9
+ from typing import Any
10
+
11
+ from .constants import (
12
+ HOLE,
13
+ MAX_SPARSE_ARRAY_LENGTH,
14
+ NAN,
15
+ NEGATIVE_INFINITY,
16
+ NEGATIVE_ZERO,
17
+ POSITIVE_INFINITY,
18
+ SPARSE,
19
+ UNDEFINED,
20
+ )
21
+ from .utils import (
22
+ Hole,
23
+ JsBigInt,
24
+ JsRegExp,
25
+ Undefined,
26
+ is_valid_array_index,
27
+ is_valid_array_len,
28
+ )
29
+
30
+
31
+ def parse(serialized: str, revivers: dict[str, Callable] | None = None) -> Any:
32
+ """Deserialize a string produced by ``devalue.stringify`` (JS or Python).
33
+
34
+ *revivers* is an optional dict mapping custom type tags to functions
35
+ that receive the hydrated inner value and return the final object.
36
+ """
37
+ return unflatten(json.loads(serialized), revivers)
38
+
39
+
40
+ def unflatten(parsed: Any, revivers: dict[str, Callable] | None = None) -> Any:
41
+ """Hydrate an already-JSON-parsed value produced by ``devalue.stringify``.
42
+
43
+ Accepts either a negative integer (for special top-level values such as
44
+ ``undefined`` or ``NaN``) or a list (the flattened representation).
45
+
46
+ Input is untrusted: an index that does not address a slot hydrates to
47
+ ``Undefined`` (as it does in JS), and a sparse array declaring more than
48
+ ``MAX_SPARSE_ARRAY_LENGTH`` slots is rejected rather than allocated.
49
+ """
50
+ if isinstance(parsed, (int, float)) and not isinstance(parsed, bool):
51
+ return _hydrate_toplevel(parsed)
52
+
53
+ if not isinstance(parsed, list) or len(parsed) == 0:
54
+ raise ValueError("Invalid input")
55
+
56
+ values: list[Any] = parsed
57
+ hydrated: dict[int, Any] = {}
58
+ hydrating: set[int] | None = None
59
+
60
+ def hydrate(index: Any, standalone: bool = False) -> Any:
61
+ nonlocal hydrating
62
+
63
+ # Special sentinel constants
64
+ if index == UNDEFINED:
65
+ return Undefined
66
+ if index == NAN:
67
+ return float("nan")
68
+ if index == POSITIVE_INFINITY:
69
+ return float("inf")
70
+ if index == NEGATIVE_INFINITY:
71
+ return float("-inf")
72
+ if index == NEGATIVE_ZERO:
73
+ return -0.0
74
+
75
+ if standalone or not isinstance(index, (int, float)) or isinstance(index, bool):
76
+ raise ValueError("Invalid input")
77
+
78
+ # A float index addresses no slot; JS reads `undefined` from the gap
79
+ # rather than truncating towards one. Checked before the cache
80
+ # because such an index resolves to `Undefined` either way.
81
+ if not isinstance(index, int):
82
+ return Undefined
83
+
84
+ if index in hydrated:
85
+ return hydrated[index]
86
+
87
+ # JS reads out-of-range indexes off the end of the array and gets
88
+ # `undefined`. Python would wrap a negative index around to a real
89
+ # element (silently returning the wrong value) or raise IndexError.
90
+ if index < 0 or index >= len(values):
91
+ hydrated[index] = Undefined
92
+ return Undefined
93
+
94
+ value = values[index]
95
+
96
+ # --- scalar (not a dict or list) → store directly ---
97
+ if not isinstance(value, (dict, list)):
98
+ hydrated[index] = value
99
+ # --- list-encoded values ---
100
+ elif isinstance(value, list):
101
+ if len(value) > 0 and isinstance(value[0], str):
102
+ _hydrate_typed(index, value, hydrate, hydrated, values, revivers, hydrating)
103
+ # hydrating might have been mutated – re-read from the closure
104
+ elif len(value) > 0 and value[0] == SPARSE:
105
+ _hydrate_sparse(index, value, hydrate, hydrated)
106
+ else:
107
+ _hydrate_dense(index, value, hydrate, hydrated)
108
+ # --- plain dict ---
109
+ else:
110
+ obj: dict[str, Any] = {}
111
+ hydrated[index] = obj
112
+ for key in value:
113
+ if key == "__proto__":
114
+ raise ValueError("Cannot parse an object with a `__proto__` property")
115
+ obj[key] = hydrate(value[key])
116
+
117
+ return hydrated[index]
118
+
119
+ # ---------- typed value dispatcher ----------
120
+
121
+ def _hydrate_typed(
122
+ index: int,
123
+ value: list,
124
+ hydrate: Callable,
125
+ hydrated: dict,
126
+ values: list,
127
+ revivers: dict | None,
128
+ outer_hydrating: set | None,
129
+ ) -> None:
130
+ nonlocal hydrating
131
+ type_name: str = value[0]
132
+
133
+ # --- custom reviver? ---
134
+ reviver = revivers.get(type_name) if revivers else None
135
+ if reviver is not None:
136
+ i = value[1]
137
+ if not isinstance(i, (int, float)) or isinstance(i, bool):
138
+ values.append(value[1])
139
+ i = len(values) - 1
140
+
141
+ # If the payload is already hydrated, its recursion has already
142
+ # terminated (e.g. a self-referential object cached itself before
143
+ # following its own back-reference), so revive it directly.
144
+ # Falling through to the `hydrating` guard here would wrongly
145
+ # reject a valid cycle. An actually infinite payload (e.g.
146
+ # `[["Custom", 0]]`) is never cached, so it still hits the guard.
147
+ if i in hydrated:
148
+ hydrated[index] = reviver(hydrated[i])
149
+ return
150
+
151
+ if hydrating is None:
152
+ hydrating = set()
153
+
154
+ if i in hydrating:
155
+ raise ValueError("Invalid circular reference")
156
+
157
+ hydrating.add(i)
158
+ hydrated[index] = reviver(hydrate(i))
159
+ hydrating.discard(i)
160
+ return
161
+
162
+ # --- built-in types ---
163
+ if type_name == "Date":
164
+ date_str = value[1]
165
+ if not date_str:
166
+ hydrated[index] = None
167
+ else:
168
+ hydrated[index] = _parse_iso_date(date_str)
169
+
170
+ elif type_name == "Set":
171
+ s: set[Any] = set()
172
+ hydrated[index] = s
173
+ for i in range(1, len(value)):
174
+ s.add(hydrate(value[i]))
175
+
176
+ elif type_name == "Map":
177
+ d: dict[Any, Any] = {}
178
+ hydrated[index] = d
179
+ for i in range(1, len(value), 2):
180
+ k = hydrate(value[i])
181
+ v = hydrate(value[i + 1])
182
+ d[k] = v
183
+
184
+ elif type_name == "RegExp":
185
+ pattern = value[1]
186
+ flags_str = value[2] if len(value) > 2 else ""
187
+ hydrated[index] = JsRegExp(pattern, flags_str)
188
+
189
+ elif type_name == "Object":
190
+ wrapped_index = value[1]
191
+ # A boxed special value carries a negative sentinel here (`-3` for
192
+ # NaN, `-6` for -0, …), and JS reads an out-of-range index as
193
+ # `undefined` rather than wrapping around to a real element.
194
+ wrapped_raw = (
195
+ values[wrapped_index]
196
+ if isinstance(wrapped_index, int) and 0 <= wrapped_index < len(values)
197
+ else None
198
+ )
199
+ if isinstance(wrapped_raw, (dict, list)) and not (
200
+ isinstance(wrapped_raw, list)
201
+ and len(wrapped_raw) > 0
202
+ and wrapped_raw[0] == "BigInt"
203
+ ):
204
+ raise ValueError("Invalid input")
205
+ hydrated[index] = hydrate(wrapped_index)
206
+
207
+ elif type_name == "BigInt":
208
+ hydrated[index] = JsBigInt(value[1])
209
+
210
+ elif type_name == "null":
211
+ obj: dict[str, Any] = {}
212
+ hydrated[index] = obj
213
+ for i in range(1, len(value), 2):
214
+ k = value[i]
215
+ if k == "__proto__":
216
+ raise ValueError("Cannot parse an object with a `__proto__` property")
217
+ obj[k] = hydrate(value[i + 1])
218
+
219
+ elif type_name == "ArrayBuffer":
220
+ b64 = value[1]
221
+ if not isinstance(b64, str):
222
+ raise ValueError("Invalid ArrayBuffer encoding")
223
+ # A bare buffer, `bytearray`; a view over one is `bytes` below.
224
+ hydrated[index] = bytearray(base64.b64decode(b64))
225
+
226
+ elif type_name in _TYPED_ARRAY_TYPES:
227
+ ref_idx = value[1]
228
+ ref_val = (
229
+ values[ref_idx] if isinstance(ref_idx, int) and 0 <= ref_idx < len(values) else None
230
+ )
231
+ if not (isinstance(ref_val, list) and len(ref_val) > 0 and ref_val[0] == "ArrayBuffer"):
232
+ raise ValueError("Invalid data")
233
+ buf = hydrate(value[1])
234
+ # Always a copy, so that writing through the `bytearray` the buffer
235
+ # parsed to cannot reach a view over it.
236
+ if len(value) > 2:
237
+ byte_offset = value[2]
238
+ elem_count = value[3]
239
+ if type_name == "DataView":
240
+ hydrated[index] = bytes(buf[byte_offset : byte_offset + elem_count])
241
+ else:
242
+ bpe = _BYTES_PER_ELEMENT.get(type_name, 1)
243
+ hydrated[index] = bytes(buf[byte_offset : byte_offset + elem_count * bpe])
244
+ else:
245
+ hydrated[index] = bytes(buf)
246
+
247
+ elif type_name == "URL":
248
+ hydrated[index] = value[1]
249
+
250
+ elif type_name == "URLSearchParams":
251
+ hydrated[index] = value[1]
252
+
253
+ elif type_name.startswith("Temporal."):
254
+ hydrated[index] = value[1]
255
+
256
+ else:
257
+ raise ValueError(f"Unknown type {type_name}")
258
+
259
+ return hydrate(0)
260
+
261
+
262
+ # ---------------------------------------------------------------------------
263
+ # Internal helpers
264
+ # ---------------------------------------------------------------------------
265
+
266
+ _BYTES_PER_ELEMENT: dict[str, int] = {
267
+ "Int8Array": 1,
268
+ "Uint8Array": 1,
269
+ "Uint8ClampedArray": 1,
270
+ "Int16Array": 2,
271
+ "Uint16Array": 2,
272
+ "Float16Array": 2,
273
+ "Int32Array": 4,
274
+ "Uint32Array": 4,
275
+ "Float32Array": 4,
276
+ "Float64Array": 8,
277
+ "BigInt64Array": 8,
278
+ "BigUint64Array": 8,
279
+ }
280
+
281
+ _TYPED_ARRAY_TYPES: set[str] = set(_BYTES_PER_ELEMENT) | {"DataView"}
282
+
283
+
284
+ def _hydrate_toplevel(n: int | float) -> Any:
285
+ """Return the Python equivalent for a top-level special constant."""
286
+ if n == UNDEFINED:
287
+ return Undefined
288
+ if n == NAN:
289
+ return float("nan")
290
+ if n == POSITIVE_INFINITY:
291
+ return float("inf")
292
+ if n == NEGATIVE_INFINITY:
293
+ return float("-inf")
294
+ if n == NEGATIVE_ZERO:
295
+ return -0.0
296
+ raise ValueError("Invalid input")
297
+
298
+
299
+ def _hydrate_sparse(
300
+ index: int,
301
+ value: list,
302
+ hydrate: Callable,
303
+ hydrated: dict,
304
+ ) -> None:
305
+ """Hydrate a sparse-array encoding ``[SPARSE, length, idx, val, …]``."""
306
+ length = value[1]
307
+ if not is_valid_array_len(length):
308
+ raise ValueError("Invalid input")
309
+
310
+ if length > MAX_SPARSE_ARRAY_LENGTH:
311
+ # `length` comes from the input rather than being bounded by it, so
312
+ # honouring it would let a few bytes of payload allocate arbitrary
313
+ # memory. See MAX_SPARSE_ARRAY_LENGTH for why Python cannot do what
314
+ # JS does here.
315
+ raise ValueError(
316
+ f"Sparse array length {length} exceeds the maximum of {MAX_SPARSE_ARRAY_LENGTH}"
317
+ )
318
+
319
+ array: list[Any] = [Hole] * length
320
+ hydrated[index] = array
321
+ for i in range(2, len(value), 2):
322
+ idx = value[i]
323
+ if not is_valid_array_index(idx) or idx >= length:
324
+ raise ValueError("Invalid input")
325
+ array[idx] = hydrate(value[i + 1])
326
+
327
+
328
+ def _hydrate_dense(
329
+ index: int,
330
+ value: list,
331
+ hydrate: Callable,
332
+ hydrated: dict,
333
+ ) -> None:
334
+ """Hydrate a dense array (may contain ``HOLE`` sentinels)."""
335
+ array: list[Any] = [Hole] * len(value)
336
+ hydrated[index] = array
337
+ for i, n in enumerate(value):
338
+ if n == HOLE:
339
+ continue # leave as Hole
340
+ array[i] = hydrate(n)
341
+
342
+
343
+ def _parse_iso_date(s: str) -> datetime:
344
+ """Parse a JS ``Date.toISOString()`` string into a Python datetime."""
345
+ if s.endswith("Z"):
346
+ s = s[:-1] + "+00:00"
347
+ return datetime.fromisoformat(s)
@@ -0,0 +1,290 @@
1
+ """Serialize Python values into the devalue JSON wire format."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import math
7
+ import re as re_module
8
+ from collections.abc import Callable
9
+ from datetime import datetime, timezone
10
+ from typing import Any
11
+
12
+ from .constants import (
13
+ HOLE,
14
+ MAX_SAFE_INTEGER,
15
+ NAN,
16
+ NEGATIVE_INFINITY,
17
+ NEGATIVE_ZERO,
18
+ POSITIVE_INFINITY,
19
+ UNDEFINED,
20
+ )
21
+ from .utils import (
22
+ DevalueError,
23
+ Hole,
24
+ JsBigInt,
25
+ JsRegExp,
26
+ Undefined,
27
+ py_flags_to_js,
28
+ stringify_key,
29
+ stringify_string,
30
+ )
31
+
32
+
33
+ def stringify(value: Any, reducers: dict[str, Callable] | None = None) -> str:
34
+ """Serialize *value* into a JSON string compatible with JS ``devalue.parse``.
35
+
36
+ Supports: ``None``, ``bool``, ``int``, ``float`` (including NaN / ±Inf /
37
+ −0), ``str``, ``list``, ``tuple``, ``dict`` (string keys only), ``set``,
38
+ ``frozenset``, ``datetime``, ``re.Pattern``, ``bytes`` (as a
39
+ ``Uint8Array``), ``bytearray`` and ``memoryview`` (as an ``ArrayBuffer``),
40
+ and the ``Undefined`` sentinel.
41
+
42
+ Cyclic and repeated references are handled automatically. Integers
43
+ outside the JS safe range are emitted as ``["BigInt", …]``, since a bare
44
+ JSON number would not survive the trip through a JS ``number``.
45
+
46
+ *reducers* is an optional dict mapping type tags to functions. Each
47
+ function receives a value and should return a replacement value for the
48
+ values it handles, or a falsy one to decline. Truthiness follows JS, not
49
+ Python: ``{}``, ``[]`` and ``set()`` claim the value, while ``NaN`` and
50
+ ``-0.0`` decline.
51
+ """
52
+ stringified: dict[int, str] = {}
53
+ # Maps a key from `_make_key` to `(index, value)`. JS keys its index Map
54
+ # by the value itself, which gives objects reference identity and keeps
55
+ # them alive. A dict cannot do that — it would merge distinct-but-equal
56
+ # objects and reject unhashable ones — so object keys use `id()` instead,
57
+ # and each entry holds the value so that its address cannot be recycled
58
+ # while the key is live.
59
+ indexes: dict[Any, tuple[int, Any]] = {}
60
+ custom: list[tuple[str, Callable]] = []
61
+ if reducers:
62
+ for key in reducers:
63
+ custom.append((key, reducers[key]))
64
+ keys: list[str] = []
65
+ p = 0
66
+
67
+ def _make_key(thing: Any) -> Any:
68
+ """Build a dict key that distinguishes ``bool`` from ``int``."""
69
+ if isinstance(thing, bool):
70
+ return ("b", thing)
71
+ if thing is None:
72
+ return ("n",)
73
+ if thing is Undefined:
74
+ return ("u",)
75
+ if isinstance(thing, JsBigInt):
76
+ return ("bigint", int(thing))
77
+ if isinstance(thing, int):
78
+ return ("i", thing)
79
+ if isinstance(thing, float):
80
+ return ("f", thing)
81
+ if isinstance(thing, str):
82
+ return ("s", thing)
83
+ return ("o", id(thing))
84
+
85
+ def flatten(thing: Any, index: int | None = None) -> int:
86
+ nonlocal p
87
+
88
+ # --- special values → negative sentinel constants ---
89
+ if thing is Undefined:
90
+ return UNDEFINED
91
+ if thing is Hole:
92
+ # Only an array slot can be a hole; the array branch handles it.
93
+ raise DevalueError("Cannot stringify a hole outside an array", keys, thing, value)
94
+ if isinstance(thing, float):
95
+ if math.isnan(thing):
96
+ return NAN
97
+ if thing == float("inf"):
98
+ return POSITIVE_INFINITY
99
+ if thing == float("-inf"):
100
+ return NEGATIVE_INFINITY
101
+ if thing == 0.0 and math.copysign(1.0, thing) < 0:
102
+ return NEGATIVE_ZERO
103
+
104
+ # --- already indexed → reuse ---
105
+ key = _make_key(thing)
106
+ entry = indexes.get(key)
107
+ if entry is not None:
108
+ return entry[0]
109
+
110
+ # --- assign a fresh index ---
111
+ if index is None:
112
+ index = p
113
+ p += 1
114
+ indexes[key] = (index, thing)
115
+
116
+ # --- custom reducers ---
117
+ for reducer_key, fn in custom:
118
+ reduced = fn(thing)
119
+ if _is_js_truthy(reduced):
120
+ stringified[index] = f'["{reducer_key}",{flatten(reduced)}]'
121
+ return index
122
+
123
+ # --- callable (functions, lambdas) ---
124
+ if callable(thing) and not isinstance(thing, type):
125
+ raise DevalueError("Cannot stringify a function", keys, thing, value)
126
+
127
+ # --- primitives ---
128
+ if thing is None or isinstance(thing, (bool, int, float, str)):
129
+ stringified[index] = _stringify_primitive(thing)
130
+ return index
131
+
132
+ # --- list / tuple → Array ---
133
+ if isinstance(thing, (list, tuple)):
134
+ parts = ["["]
135
+ for i, item in enumerate(thing):
136
+ if i > 0:
137
+ parts.append(",")
138
+ if item is Hole:
139
+ parts.append(str(HOLE))
140
+ continue
141
+ keys.append(f"[{i}]")
142
+ parts.append(str(flatten(item)))
143
+ keys.pop()
144
+ parts.append("]")
145
+ stringified[index] = "".join(parts)
146
+ return index
147
+
148
+ # --- dict → Object ---
149
+ if isinstance(thing, dict):
150
+ for k in thing:
151
+ if not isinstance(k, str):
152
+ raise DevalueError(
153
+ "Cannot stringify objects with non-string keys",
154
+ keys,
155
+ thing,
156
+ value,
157
+ )
158
+ if k == "__proto__":
159
+ raise DevalueError(
160
+ "Cannot stringify objects with __proto__ keys",
161
+ keys,
162
+ thing,
163
+ value,
164
+ )
165
+ parts = ["{"]
166
+ started = False
167
+ for k, v in thing.items():
168
+ if started:
169
+ parts.append(",")
170
+ started = True
171
+ keys.append(stringify_key(k))
172
+ parts.append(f"{stringify_string(k)}:{flatten(v)}")
173
+ keys.pop()
174
+ parts.append("}")
175
+ stringified[index] = "".join(parts)
176
+ return index
177
+
178
+ # --- set / frozenset → Set ---
179
+ if isinstance(thing, (set, frozenset)):
180
+ parts = ['["Set"']
181
+ for item in thing:
182
+ parts.append(f",{flatten(item)}")
183
+ parts.append("]")
184
+ stringified[index] = "".join(parts)
185
+ return index
186
+
187
+ # --- datetime → Date ---
188
+ if isinstance(thing, datetime):
189
+ if thing.tzinfo is not None:
190
+ utc_dt = thing.astimezone(timezone.utc)
191
+ else:
192
+ utc_dt = thing
193
+ ms = utc_dt.microsecond // 1000
194
+ iso = utc_dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{ms:03d}Z"
195
+ stringified[index] = f'["Date","{iso}"]'
196
+ return index
197
+
198
+ # --- JsRegExp / re.Pattern → RegExp ---
199
+ if isinstance(thing, (JsRegExp, re_module.Pattern)):
200
+ if isinstance(thing, JsRegExp):
201
+ source, flags_str = thing.source, thing.flags
202
+ else:
203
+ # Best effort: a Python pattern is not a JS one, so this can
204
+ # produce a source the far side refuses to compile.
205
+ source = thing.pattern
206
+ flags_str = py_flags_to_js(thing.flags)
207
+ if flags_str:
208
+ stringified[index] = f'["RegExp",{stringify_string(source)},"{flags_str}"]'
209
+ else:
210
+ stringified[index] = f'["RegExp",{stringify_string(source)}]'
211
+ return index
212
+
213
+ # --- bytearray / memoryview → ArrayBuffer ---
214
+ if isinstance(thing, (bytearray, memoryview)):
215
+ b64 = base64.b64encode(bytes(thing)).decode("ascii")
216
+ stringified[index] = f'["ArrayBuffer","{b64}"]'
217
+ return index
218
+
219
+ # --- bytes → Uint8Array over its own ArrayBuffer ---
220
+ # `bytes` gets the view rather than the bare buffer because that is what
221
+ # the far side wants: a `Uint8Array` can be piped straight into a
222
+ # `Response`, an `ArrayBuffer` cannot.
223
+ if isinstance(thing, bytes):
224
+ b64 = base64.b64encode(thing).decode("ascii")
225
+ # Allocated here rather than through `flatten`, which would need a
226
+ # temporary object to key on and would offer it to the reducers.
227
+ buffer_index = p
228
+ p += 1
229
+ stringified[buffer_index] = f'["ArrayBuffer","{b64}"]'
230
+ # No offset or length: upstream emits those only for a view narrower
231
+ # than its buffer, and this one never is.
232
+ stringified[index] = f'["Uint8Array",{buffer_index}]'
233
+ return index
234
+
235
+ raise DevalueError("Cannot stringify arbitrary non-POJOs", keys, thing, value)
236
+
237
+ idx = flatten(value)
238
+
239
+ # Special value (encoded as a negative number with no array wrapper)
240
+ if idx < 0:
241
+ return str(idx)
242
+
243
+ parts = [stringified[i] for i in range(p)]
244
+ return "[" + ",".join(parts) + "]"
245
+
246
+
247
+ # ---------------------------------------------------------------------------
248
+ # Helpers
249
+ # ---------------------------------------------------------------------------
250
+
251
+
252
+ def _is_js_truthy(thing: Any) -> bool:
253
+ """Mirror JS truthiness, which decides whether a reducer claimed a value.
254
+
255
+ Differs from Python's in both directions: empty containers are truthy in
256
+ JS, while ``NaN`` and ``-0.0`` are falsy.
257
+ """
258
+ if thing is None or thing is Undefined or thing is False:
259
+ return False
260
+ if isinstance(thing, str):
261
+ return thing != ""
262
+ if isinstance(thing, bool):
263
+ return thing
264
+ if isinstance(thing, (int, float)):
265
+ return not (thing == 0 or (isinstance(thing, float) and math.isnan(thing)))
266
+ return True
267
+
268
+
269
+ def _stringify_primitive(thing: Any) -> str:
270
+ """Return the JSON-compatible representation of a Python primitive."""
271
+ if isinstance(thing, str):
272
+ return stringify_string(thing)
273
+ if thing is None:
274
+ return "null"
275
+ # bool MUST be checked before int (bool is a subclass of int)
276
+ if isinstance(thing, bool):
277
+ return "true" if thing else "false"
278
+ if isinstance(thing, JsBigInt):
279
+ return f'["BigInt","{int(thing)}"]'
280
+ if isinstance(thing, int):
281
+ # A JS `number` cannot hold these exactly, so emitting a bare JSON
282
+ # number would silently round-trip as a different value. Any integer
283
+ # this large is a `bigint` on the JS side anyway.
284
+ if not -MAX_SAFE_INTEGER <= thing <= MAX_SAFE_INTEGER:
285
+ return f'["BigInt","{thing}"]'
286
+ return str(thing)
287
+ if isinstance(thing, float):
288
+ # NaN / Inf / -Inf / -0 are handled before reaching here
289
+ return repr(thing)
290
+ return str(thing) # pragma: no cover