tywrap 0.5.0 → 0.6.0

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 (169) hide show
  1. package/dist/cli.js +8 -6
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config/index.d.ts.map +1 -1
  4. package/dist/config/index.js +236 -147
  5. package/dist/config/index.js.map +1 -1
  6. package/dist/core/annotation-parser.d.ts.map +1 -1
  7. package/dist/core/annotation-parser.js +93 -83
  8. package/dist/core/annotation-parser.js.map +1 -1
  9. package/dist/core/discovery.d.ts.map +1 -1
  10. package/dist/core/discovery.js +26 -0
  11. package/dist/core/discovery.js.map +1 -1
  12. package/dist/core/emit-call.d.ts +58 -0
  13. package/dist/core/emit-call.d.ts.map +1 -0
  14. package/dist/core/emit-call.js +103 -0
  15. package/dist/core/emit-call.js.map +1 -0
  16. package/dist/core/generator.d.ts +2 -0
  17. package/dist/core/generator.d.ts.map +1 -1
  18. package/dist/core/generator.js +54 -211
  19. package/dist/core/generator.js.map +1 -1
  20. package/dist/core/mapper.d.ts.map +1 -1
  21. package/dist/core/mapper.js +118 -104
  22. package/dist/core/mapper.js.map +1 -1
  23. package/dist/index.d.ts +6 -25
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +9 -31
  26. package/dist/index.js.map +1 -1
  27. package/dist/runtime/bounded-context.d.ts +2 -2
  28. package/dist/runtime/bounded-context.js +2 -2
  29. package/dist/runtime/{safe-codec.d.ts → bridge-codec.d.ts} +11 -11
  30. package/dist/runtime/bridge-codec.d.ts.map +1 -0
  31. package/dist/runtime/{safe-codec.js → bridge-codec.js} +26 -26
  32. package/dist/runtime/bridge-codec.js.map +1 -0
  33. package/dist/runtime/{http-io.d.ts → http-transport.d.ts} +6 -6
  34. package/dist/runtime/http-transport.d.ts.map +1 -0
  35. package/dist/runtime/{http-io.js → http-transport.js} +3 -3
  36. package/dist/runtime/http-transport.js.map +1 -0
  37. package/dist/runtime/http.d.ts +3 -3
  38. package/dist/runtime/http.d.ts.map +1 -1
  39. package/dist/runtime/http.js +4 -4
  40. package/dist/runtime/http.js.map +1 -1
  41. package/dist/runtime/index.d.ts +9 -1
  42. package/dist/runtime/index.d.ts.map +1 -1
  43. package/dist/runtime/index.js +9 -1
  44. package/dist/runtime/index.js.map +1 -1
  45. package/dist/runtime/node.d.ts +6 -6
  46. package/dist/runtime/node.d.ts.map +1 -1
  47. package/dist/runtime/node.js +7 -7
  48. package/dist/runtime/node.js.map +1 -1
  49. package/dist/runtime/pooled-transport.d.ts +11 -11
  50. package/dist/runtime/pooled-transport.d.ts.map +1 -1
  51. package/dist/runtime/pooled-transport.js +10 -10
  52. package/dist/runtime/pooled-transport.js.map +1 -1
  53. package/dist/runtime/pyodide-bootstrap-core.generated.d.ts.map +1 -1
  54. package/dist/runtime/pyodide-bootstrap-core.generated.js +1 -1
  55. package/dist/runtime/pyodide-bootstrap-core.generated.js.map +1 -1
  56. package/dist/runtime/{pyodide-io.d.ts → pyodide-transport.d.ts} +8 -8
  57. package/dist/runtime/pyodide-transport.d.ts.map +1 -0
  58. package/dist/runtime/{pyodide-io.js → pyodide-transport.js} +5 -5
  59. package/dist/runtime/pyodide-transport.js.map +1 -0
  60. package/dist/runtime/pyodide.d.ts +3 -3
  61. package/dist/runtime/pyodide.d.ts.map +1 -1
  62. package/dist/runtime/pyodide.js +5 -5
  63. package/dist/runtime/pyodide.js.map +1 -1
  64. package/dist/runtime/rpc-client.d.ts +5 -5
  65. package/dist/runtime/rpc-client.d.ts.map +1 -1
  66. package/dist/runtime/rpc-client.js +6 -7
  67. package/dist/runtime/rpc-client.js.map +1 -1
  68. package/dist/runtime/{process-io.d.ts → subprocess-transport.d.ts} +9 -9
  69. package/dist/runtime/subprocess-transport.d.ts.map +1 -0
  70. package/dist/runtime/{process-io.js → subprocess-transport.js} +6 -6
  71. package/dist/runtime/subprocess-transport.js.map +1 -0
  72. package/dist/runtime/{worker-pool.d.ts → transport-pool.d.ts} +15 -15
  73. package/dist/runtime/transport-pool.d.ts.map +1 -0
  74. package/dist/runtime/{worker-pool.js → transport-pool.js} +6 -6
  75. package/dist/runtime/transport-pool.js.map +1 -0
  76. package/dist/runtime/transport.d.ts +14 -8
  77. package/dist/runtime/transport.d.ts.map +1 -1
  78. package/dist/runtime/transport.js +10 -4
  79. package/dist/runtime/transport.js.map +1 -1
  80. package/dist/types/index.d.ts +10 -1
  81. package/dist/types/index.d.ts.map +1 -1
  82. package/dist/tywrap.d.ts.map +1 -1
  83. package/dist/tywrap.js +1 -3
  84. package/dist/tywrap.js.map +1 -1
  85. package/dist/utils/cache.d.ts +2 -2
  86. package/dist/utils/cache.d.ts.map +1 -1
  87. package/dist/utils/cache.js +2 -2
  88. package/dist/utils/cache.js.map +1 -1
  89. package/dist/utils/codec.d.ts +1 -1
  90. package/dist/utils/codec.d.ts.map +1 -1
  91. package/dist/utils/codec.js +181 -182
  92. package/dist/utils/codec.js.map +1 -1
  93. package/dist/version.d.ts +12 -0
  94. package/dist/version.d.ts.map +1 -0
  95. package/dist/version.js +12 -0
  96. package/dist/version.js.map +1 -0
  97. package/package.json +3 -5
  98. package/runtime/__pycache__/safe_codec.cpython-311.pyc +0 -0
  99. package/runtime/__pycache__/tywrap_bridge_core.cpython-311.pyc +0 -0
  100. package/runtime/python_bridge.py +54 -6
  101. package/runtime/safe_codec.py +8 -8
  102. package/runtime/tywrap_bridge_core.py +159 -23
  103. package/src/cli.ts +8 -12
  104. package/src/config/index.ts +271 -165
  105. package/src/core/annotation-parser.ts +112 -105
  106. package/src/core/discovery.ts +32 -0
  107. package/src/core/emit-call.ts +171 -0
  108. package/src/core/generator.ts +67 -263
  109. package/src/core/mapper.ts +125 -110
  110. package/src/index.ts +11 -68
  111. package/src/runtime/bounded-context.ts +2 -2
  112. package/src/runtime/{safe-codec.ts → bridge-codec.ts} +27 -27
  113. package/src/runtime/{http-io.ts → http-transport.ts} +5 -5
  114. package/src/runtime/http.ts +5 -5
  115. package/src/runtime/index.ts +23 -1
  116. package/src/runtime/node.ts +15 -15
  117. package/src/runtime/pooled-transport.ts +15 -15
  118. package/src/runtime/pyodide-bootstrap-core.generated.ts +1 -1
  119. package/src/runtime/{pyodide-io.ts → pyodide-transport.ts} +7 -7
  120. package/src/runtime/pyodide.ts +6 -6
  121. package/src/runtime/rpc-client.ts +12 -8
  122. package/src/runtime/{process-io.ts → subprocess-transport.ts} +8 -8
  123. package/src/runtime/{worker-pool.ts → transport-pool.ts} +26 -26
  124. package/src/runtime/transport.ts +15 -8
  125. package/src/types/index.ts +10 -1
  126. package/src/tywrap.ts +1 -3
  127. package/src/utils/cache.ts +2 -2
  128. package/src/utils/codec.ts +217 -196
  129. package/src/version.ts +12 -0
  130. package/dist/core/analyzer.d.ts +0 -64
  131. package/dist/core/analyzer.d.ts.map +0 -1
  132. package/dist/core/analyzer.js +0 -710
  133. package/dist/core/analyzer.js.map +0 -1
  134. package/dist/runtime/http-io.d.ts.map +0 -1
  135. package/dist/runtime/http-io.js.map +0 -1
  136. package/dist/runtime/optimized-node.d.ts +0 -23
  137. package/dist/runtime/optimized-node.d.ts.map +0 -1
  138. package/dist/runtime/optimized-node.js +0 -23
  139. package/dist/runtime/optimized-node.js.map +0 -1
  140. package/dist/runtime/process-io.d.ts.map +0 -1
  141. package/dist/runtime/process-io.js.map +0 -1
  142. package/dist/runtime/protocol.d.ts +0 -3
  143. package/dist/runtime/protocol.d.ts.map +0 -1
  144. package/dist/runtime/protocol.js +0 -3
  145. package/dist/runtime/protocol.js.map +0 -1
  146. package/dist/runtime/pyodide-io.d.ts.map +0 -1
  147. package/dist/runtime/pyodide-io.js.map +0 -1
  148. package/dist/runtime/safe-codec.d.ts.map +0 -1
  149. package/dist/runtime/safe-codec.js.map +0 -1
  150. package/dist/runtime/worker-pool.d.ts.map +0 -1
  151. package/dist/runtime/worker-pool.js.map +0 -1
  152. package/dist/utils/bundle-optimizer.d.ts +0 -182
  153. package/dist/utils/bundle-optimizer.d.ts.map +0 -1
  154. package/dist/utils/bundle-optimizer.js +0 -680
  155. package/dist/utils/bundle-optimizer.js.map +0 -1
  156. package/dist/utils/memory-profiler.d.ts +0 -123
  157. package/dist/utils/memory-profiler.d.ts.map +0 -1
  158. package/dist/utils/memory-profiler.js +0 -426
  159. package/dist/utils/memory-profiler.js.map +0 -1
  160. package/dist/utils/parallel-processor.d.ts +0 -146
  161. package/dist/utils/parallel-processor.d.ts.map +0 -1
  162. package/dist/utils/parallel-processor.js +0 -707
  163. package/dist/utils/parallel-processor.js.map +0 -1
  164. package/src/core/analyzer.ts +0 -824
  165. package/src/runtime/optimized-node.ts +0 -25
  166. package/src/runtime/protocol.ts +0 -2
  167. package/src/utils/bundle-optimizer.ts +0 -876
  168. package/src/utils/memory-profiler.ts +0 -582
  169. package/src/utils/parallel-processor.ts +0 -955
@@ -9,4 +9,4 @@
9
9
  * Regenerate with: node scripts/generate-pyodide-bootstrap.mjs
10
10
  */
11
11
 
12
- export const PYODIDE_BRIDGE_CORE_SOURCE: string = "\"\"\"\nShared tywrap bridge core: protocol dispatch + value (de)serialization.\n\nThis module is the SINGLE source of truth for the \"tywrap/1\" server-side\nprotocol. It is imported by:\n\n - runtime/python_bridge.py (the Node/Bun/Deno subprocess server and the HTTP\n server), which owns I/O concerns: the stdin/stdout JSONL loop, env-var size\n guards, the real OS pid, bridge='python-subprocess', and the final SafeCodec\n encode wrapper.\n\n - the in-WASM Pyodide server (src/runtime/pyodide-io.ts). Pyodide cannot read\n this file from disk, so it is shipped as a build-time-generated TypeScript\n string constant (src/runtime/pyodide-bootstrap-core.generated.ts) produced by\n scripts/generate-pyodide-bootstrap.mjs and exec'd into a module registered in\n sys.modules. A conformance drift guard (test/runtime_conformance.test.ts)\n asserts the generated constant stays byte-identical to this file.\n\nCROSS-LANGUAGE CONTRACT (Python <-> the TypeScript decoder in src/utils/codec.ts\nand the request encoder in src/runtime/safe-codec.ts):\n\n * Every value-type \"marker\" envelope carries {'__tywrap__': <type>,\n 'codecVersion': 1, 'encoding': ...}. The 6 markers are: ndarray, dataframe,\n series, scipy.sparse, torch.tensor, sklearn.estimator.\n * bytes round-trip both ways via base64 envelopes (see _deserialize_bytes_*\n and the bytes branch of default_encoder).\n * NaN/Infinity are rejected (the JS client cannot parse the non-standard tokens\n that allow_nan=True would emit).\n\nPURITY: This module depends only on the standard library plus LAZY optional\nimports (numpy/pandas/scipy/torch/sklearn/pyarrow are each imported inside the\nfunction that needs them). It performs no stdin/stdout I/O and reads no env vars,\nso it runs unchanged under CPython-in-WASM (Pyodide).\n\nforce_json_markers: a *parameter* threaded through every serializer (including\nthe nested torch.tensor -> ndarray call). When True, ndarray/dataframe/series are\nforced down their JSON path regardless of pyarrow availability. Pyodide passes\nTrue (Arrow is unavailable in WASM); the subprocess server passes the boolean\nderived from TYWRAP_CODEC_FALLBACK=json so that \"Node in json-fallback mode\" and\n\"Pyodide\" produce byte-identical marker envelopes.\n\"\"\"\n\nimport base64\nimport datetime as dt\nimport decimal\nimport importlib\nimport importlib.util\nimport json\nimport math\nimport traceback\nimport uuid\nfrom pathlib import Path, PurePath\n\n# Protocol constants. These MUST match src/runtime/protocol.ts (PROTOCOL_ID,\n# TYWRAP_PROTOCOL_VERSION) and the codec version baked into marker envelopes.\nPROTOCOL = 'tywrap/1'\nPROTOCOL_VERSION = 1\nCODEC_VERSION = 1\n\n\nclass ProtocolError(Exception):\n \"\"\"Raised for malformed requests (bad protocol/id/method/params).\"\"\"\n\n\nclass InstanceHandleError(ValueError):\n \"\"\"Raised when an instance handle is unknown or no longer valid.\"\"\"\n\n\nclass CodecError(Exception):\n \"\"\"Raised when value encoding fails (e.g. NaN/Infinity not allowed).\"\"\"\n\n\n# =============================================================================\n# REQUEST-SIDE DESERIALIZATION (bytes envelopes -> Python bytes)\n# =============================================================================\n\n_NO_DESERIALIZE = object()\n_ERR_BYTES_MISSING_B64 = 'Invalid bytes envelope: missing b64'\n_ERR_BYTES_MISSING_DATA = 'Invalid bytes envelope: missing data'\n_ERR_BYTES_INVALID_BASE64 = 'Invalid bytes envelope: invalid base64'\n\n\ndef _deserialize_bytes_envelope(value):\n \"\"\"\n Decode base64-encoded bytes envelopes from JS into Python bytes.\n\n Supported shapes:\n - { \"__tywrap_bytes__\": true, \"b64\": \"...\" } (JS SafeCodec.encodeRequest)\n - { \"__type__\": \"bytes\", \"encoding\": \"base64\", \"data\": \"...\" } (legacy/compat)\n\n Why: TS SafeCodec encodes Uint8Array/ArrayBuffer as base64 objects, but\n Python handlers expect real bytes/bytearray to preserve behavior (e.g., len()).\n \"\"\"\n if not isinstance(value, dict):\n return _NO_DESERIALIZE\n\n if value.get('__tywrap_bytes__') is True:\n b64 = value.get('b64')\n if not isinstance(b64, str):\n raise ProtocolError(_ERR_BYTES_MISSING_B64)\n try:\n return base64.b64decode(b64, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n if value.get('__type__') == 'bytes' and value.get('encoding') == 'base64':\n data = value.get('data')\n if not isinstance(data, str):\n raise ProtocolError(_ERR_BYTES_MISSING_DATA)\n try:\n return base64.b64decode(data, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n return _NO_DESERIALIZE\n\n\ndef deserialize(value):\n \"\"\"\n Recursively deserialize request values into Python-native types.\n\n Why: requests are JSON-only; we need a small set of explicit decoders\n (currently bytes) to restore Python semantics at the boundary.\n \"\"\"\n decoded = _deserialize_bytes_envelope(value)\n if decoded is not _NO_DESERIALIZE:\n return decoded\n\n if isinstance(value, list):\n return [deserialize(item) for item in value]\n if isinstance(value, dict):\n # Preserve dict shape while decoding nested values.\n return {k: deserialize(v) for k, v in value.items()}\n return value\n\n\n# =============================================================================\n# CAPABILITY DETECTION (lazy, best-effort)\n# =============================================================================\n\ndef arrow_available():\n \"\"\"Return True when pyarrow can be imported.\"\"\"\n try:\n import pyarrow # noqa: F401\n except (ImportError, OSError):\n return False\n return True\n\n\ndef module_available(module_name):\n \"\"\"\n Lightweight feature detection for optional codec dependencies via find_spec.\n\n Why: exposes availability in bridge metadata without importing heavy modules.\n \"\"\"\n try:\n return importlib.util.find_spec(module_name) is not None\n except (ImportError, AttributeError, TypeError, ValueError):\n return False\n\n\ndef is_numpy_array(obj):\n try:\n import numpy as np # noqa: F401\n except Exception:\n return False\n return isinstance(obj, np.ndarray)\n\n\ndef is_pandas_dataframe(obj):\n try:\n import pandas as pd # noqa: F401\n except Exception:\n return False\n return isinstance(obj, pd.DataFrame)\n\n\ndef is_pandas_series(obj):\n try:\n import pandas as pd # noqa: F401\n except Exception:\n return False\n return isinstance(obj, pd.Series)\n\n\ndef is_scipy_sparse(obj):\n try:\n import scipy.sparse as sp # noqa: F401\n except Exception:\n return False\n try:\n return sp.issparse(obj)\n except Exception:\n return False\n\n\ndef is_torch_tensor(obj):\n try:\n import torch # noqa: F401\n except Exception:\n return False\n try:\n return torch.is_tensor(obj)\n except Exception:\n return False\n\n\ndef is_sklearn_estimator(obj):\n try:\n from sklearn.base import BaseEstimator # noqa: F401\n except Exception:\n return False\n return isinstance(obj, BaseEstimator)\n\n\n# =============================================================================\n# MARKER SERIALIZERS (6 __tywrap__ value types)\n# =============================================================================\n#\n# Each serializer accepts force_json_markers. When True, the Arrow path is never\n# taken (used by Pyodide and by the subprocess server in TYWRAP_CODEC_FALLBACK=json\n# mode). The JSON fallback envelopes are byte-identical across both callers, which\n# is what the conformance suite asserts.\n\ndef serialize_ndarray(obj, *, force_json_markers):\n \"\"\"\n Encode a NumPy ndarray. Arrow IPC (compact, lossless) by default; JSON when\n force_json_markers is set or pyarrow is unavailable in fallback mode.\n\n Note: pa.array() only handles 1D arrays; multi-dimensional arrays are\n flattened with shape metadata for JS-side reconstruction. See\n https://github.com/apache/arrow-js/issues/115\n \"\"\"\n if force_json_markers:\n return serialize_ndarray_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for ndarray; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n original_shape = list(obj.shape) if hasattr(obj, 'shape') else None\n flat = obj.flatten() if hasattr(obj, 'ndim') and obj.ndim > 1 else obj\n arr = pa.array(flat)\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'shape': original_shape,\n 'dtype': str(obj.dtype) if hasattr(obj, 'dtype') else None,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for ndarray') from exc\n\n\ndef serialize_ndarray_json(obj):\n \"\"\"JSON fallback for ndarray (larger payloads, potential dtype loss).\"\"\"\n try:\n data = obj.tolist()\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for ndarray') from exc\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'shape': getattr(obj, 'shape', None),\n }\n\n\ndef serialize_dataframe(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas DataFrame. Feather/Arrow-IPC (uncompressed, so apache-arrow\n in JS can read it) by default; JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_dataframe_json(obj)\n try:\n import pyarrow as pa # type: ignore\n import pyarrow.feather as feather # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.DataFrame; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n table = pa.Table.from_pandas(obj) # type: ignore\n sink = pa.BufferOutputStream()\n feather.write_feather(table, sink, compression='uncompressed')\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.DataFrame') from exc\n\n\ndef serialize_dataframe_json(obj):\n \"\"\"JSON fallback for DataFrame: records orientation.\"\"\"\n try:\n data = obj.to_dict(orient='records')\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.DataFrame') from exc\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n }\n\n\ndef serialize_series(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas Series as a single-column Arrow Table stream (the JS decoder\n contract is \"table-like\"); JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_series_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.Series; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n arr = pa.Array.from_pandas(obj) # type: ignore\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'name': getattr(obj, 'name', None),\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.Series') from exc\n\n\ndef serialize_series_json(obj):\n \"\"\"JSON fallback for Series (potentially lossy dtype/NA representation).\"\"\"\n try:\n data = obj.to_list() # type: ignore\n except Exception:\n try:\n data = obj.to_dict() # type: ignore\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.Series') from exc\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'name': getattr(obj, 'name', None),\n }\n\n\ndef serialize_sparse_matrix(obj):\n \"\"\"\n Serialize scipy sparse matrices into structured JSON envelopes (json-only;\n there is no Arrow path). Preserves sparsity; rejects unsupported formats and\n complex dtypes explicitly.\n \"\"\"\n try:\n fmt = obj.getformat()\n except Exception as exc:\n raise RuntimeError('Failed to inspect scipy sparse matrix format') from exc\n\n if fmt not in ('csr', 'csc', 'coo'):\n raise RuntimeError(f'Unsupported scipy sparse format: {fmt}')\n\n dtype = None\n try:\n dtype = str(obj.dtype)\n except Exception:\n dtype = None\n if getattr(obj.dtype, 'kind', None) == 'c':\n raise RuntimeError('Complex sparse matrices are not supported by JSON codec')\n\n if fmt in ('csr', 'csc'):\n data = obj.data.tolist()\n indices = obj.indices.tolist()\n indptr = obj.indptr.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'indices': indices,\n 'indptr': indptr,\n 'dtype': dtype,\n }\n\n # coo\n data = obj.data.tolist()\n row = obj.row.tolist()\n col = obj.col.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'row': row,\n 'col': col,\n 'dtype': dtype,\n }\n\n\ndef serialize_torch_tensor(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Serialize torch.Tensor values via the nested ndarray envelope. CPU-only by\n default; device/copy behavior is explicit. force_json_markers is threaded\n into the nested ndarray serialization so Pyodide gets a JSON ndarray value.\n \"\"\"\n tensor = obj.detach()\n if getattr(tensor, 'device', None) is not None and tensor.device.type != 'cpu':\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is on a non-CPU device; set TYWRAP_TORCH_ALLOW_COPY=1 to allow CPU transfer'\n )\n tensor = tensor.to('cpu')\n if hasattr(tensor, 'is_contiguous') and not tensor.is_contiguous():\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is not contiguous; set TYWRAP_TORCH_ALLOW_COPY=1 to allow contiguous copy'\n )\n tensor = tensor.contiguous()\n try:\n arr = tensor.numpy()\n except Exception as exc:\n raise RuntimeError('Failed to convert torch.Tensor to numpy') from exc\n\n return {\n '__tywrap__': 'torch.tensor',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'ndarray',\n 'value': serialize_ndarray(arr, force_json_markers=force_json_markers),\n 'shape': list(tensor.shape),\n 'dtype': str(tensor.dtype),\n 'device': str(tensor.device),\n }\n\n\ndef serialize_sklearn_estimator(obj):\n \"\"\"Serialize sklearn estimators as metadata only (json-only); no pickling.\"\"\"\n try:\n import sklearn # noqa: F401\n except Exception as exc:\n raise RuntimeError('scikit-learn is not available') from exc\n\n params = obj.get_params(deep=False)\n try:\n json.dumps(params)\n except Exception as exc:\n raise RuntimeError(\n 'scikit-learn estimator params are not JSON-serializable; avoid returning estimators or sanitize params'\n ) from exc\n\n return {\n '__tywrap__': 'sklearn.estimator',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'className': obj.__class__.__name__,\n 'module': obj.__class__.__module__,\n 'version': getattr(sklearn, '__version__', None),\n 'params': params,\n }\n\n\n_NO_PYDANTIC = object()\n\n\ndef serialize_pydantic(obj):\n \"\"\"\n Serialize Pydantic v2 models via model_dump(by_alias=True, mode='json')\n without importing Pydantic. Returns _NO_PYDANTIC when obj is not a model.\n \"\"\"\n model_dump = getattr(obj, 'model_dump', None)\n if not callable(model_dump):\n return _NO_PYDANTIC\n try:\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n # Older Pydantic versions may not support `mode=...`.\n return model_dump(by_alias=True)\n except Exception as exc:\n raise RuntimeError(f'model_dump failed: {exc}') from exc\n\n\ndef serialize_stdlib(obj):\n \"\"\"Coerce common stdlib scalar types to JSON-safe forms; None otherwise.\"\"\"\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n return None\n\n\ndef serialize(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Top-level result serializer. Dispatch order is significant: numpy ndarray ->\n dataframe -> series -> scipy.sparse -> torch -> sklearn -> Pydantic -> stdlib\n -> passthrough. The remaining SafeCodec value behaviors (numpy/pandas scalars,\n bytes, sets, complex rejection, NaN/Infinity) are applied later during JSON\n encoding by default_encoder.\n \"\"\"\n if is_numpy_array(obj):\n return serialize_ndarray(obj, force_json_markers=force_json_markers)\n if is_pandas_dataframe(obj):\n return serialize_dataframe(obj, force_json_markers=force_json_markers)\n if is_pandas_series(obj):\n return serialize_series(obj, force_json_markers=force_json_markers)\n if is_scipy_sparse(obj):\n return serialize_sparse_matrix(obj)\n if is_torch_tensor(obj):\n return serialize_torch_tensor(\n obj, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n if is_sklearn_estimator(obj):\n return serialize_sklearn_estimator(obj)\n pydantic_value = serialize_pydantic(obj)\n if pydantic_value is not _NO_PYDANTIC:\n return pydantic_value\n stdlib_value = serialize_stdlib(obj)\n if stdlib_value is not None:\n return stdlib_value\n return obj\n\n\n# =============================================================================\n# JSON ENCODE: SafeCodec-equivalent value handling (NaN reject, scalars, bytes)\n# =============================================================================\n#\n# This mirrors SafeCodec._default_encoder (runtime/safe_codec.py) for the VALUE\n# behaviors that are part of the wire contract. The subprocess server still uses\n# the real SafeCodec for its final encode (it also enforces size limits); this\n# core encoder exists so the Pyodide server gets identical value handling without\n# depending on safe_codec.py. The conformance suite asserts these behaviors match.\n\ndef _is_nan_or_inf(value):\n if not isinstance(value, (int, float)):\n return False\n try:\n return math.isnan(value) or math.isinf(value)\n except (TypeError, ValueError):\n return False\n\n\ndef _is_numpy_scalar(obj):\n try:\n import numpy as np\n except ImportError:\n return False\n return isinstance(obj, (np.generic, np.ndarray)) and obj.ndim == 0\n\n\ndef _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(obj, (pd.Timestamp, pd.Timedelta, type(pd.NaT)))\n\n\ndef make_default_encoder(*, allow_nan):\n \"\"\"\n Build a json.dumps default= encoder matching SafeCodec's value handling.\n\n Raises CodecError for NaN/Infinity extracted from numpy scalars (json.dumps\n itself rejects top-level/nested NaN/Infinity floats when allow_nan=False).\n \"\"\"\n\n def default_encoder(obj):\n # numpy/pandas scalars first (need .item() extraction).\n if _is_numpy_scalar(obj):\n extracted = obj.item()\n if not allow_nan and _is_nan_or_inf(extracted):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON')\n return extracted\n\n if _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n pass\n else:\n if obj is pd.NaT or (hasattr(pd, 'isna') and pd.isna(obj)):\n return None\n if isinstance(obj, pd.Timestamp):\n return obj.isoformat()\n if isinstance(obj, pd.Timedelta):\n return obj.total_seconds()\n\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n\n if isinstance(obj, (bytes, bytearray)):\n return {\n '__type__': 'bytes',\n 'encoding': 'base64',\n 'data': base64.b64encode(obj).decode('ascii'),\n }\n\n model_dump = getattr(obj, 'model_dump', None)\n if callable(model_dump):\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n return model_dump(by_alias=True)\n\n if isinstance(obj, (set, frozenset)):\n return list(obj)\n\n if isinstance(obj, complex):\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n return default_encoder\n\n\ndef encode_value(value, *, allow_nan):\n \"\"\"\n JSON-encode a fully-serialized response value, applying the SafeCodec-equivalent\n default encoder and rejecting NaN/Infinity when allow_nan is False.\n\n Raises CodecError (wrapping the json.dumps ValueError) on NaN/Infinity, matching\n SafeCodec's \"Cannot serialize NaN...\" wording so error parity holds.\n \"\"\"\n try:\n return json.dumps(value, default=make_default_encoder(allow_nan=allow_nan), allow_nan=allow_nan)\n except ValueError as exc:\n error_msg = str(exc).lower()\n # json.dumps(allow_nan=False) rejects NaN/Infinity with a ValueError whose\n # wording is Python-version dependent: 3.12+ appends the offending value\n # (\"...not JSON compliant: nan\"), but 3.10/3.11 emit only the canonical\n # \"Out of range float values are not JSON compliant\". Match that phrase too\n # so the typed error message is stable across versions.\n if (\n 'nan' in error_msg\n or 'infinity' in error_msg\n or 'inf' in error_msg\n or 'out of range float' in error_msg\n ):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON') from exc\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n except TypeError as exc:\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n\n\n# =============================================================================\n# REQUEST VALIDATION + HANDLERS + DISPATCH\n# =============================================================================\n\ndef require_protocol(msg):\n if not isinstance(msg, dict):\n raise ProtocolError('Invalid request payload')\n proto = msg.get('protocol')\n if proto != PROTOCOL:\n raise ProtocolError(f'Invalid protocol: {proto}')\n mid = msg.get('id')\n if not isinstance(mid, int):\n raise ProtocolError(f'Invalid request id: {mid}')\n return mid\n\n\ndef require_str(params, key):\n value = params.get(key)\n if not isinstance(value, str) or not value:\n raise ProtocolError(f'Missing {key}')\n return value\n\n\ndef coerce_list(value, key):\n if value is None:\n return []\n if not isinstance(value, list):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef coerce_dict(value, key):\n if value is None:\n return {}\n if not isinstance(value, dict):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef handle_call(params, *, force_json_markers, torch_allow_copy):\n module_name = require_str(params, 'module')\n function_name = require_str(params, 'functionName')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n mod = importlib.import_module(module_name)\n func = getattr(mod, function_name)\n res = func(*args, **kwargs)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef handle_instantiate(params, instances):\n module_name = require_str(params, 'module')\n class_name = require_str(params, 'className')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n mod = importlib.import_module(module_name)\n cls = getattr(mod, class_name)\n obj = cls(*args, **kwargs)\n handle_id = str(id(obj))\n instances[handle_id] = obj\n return handle_id\n\n\ndef handle_call_method(params, instances, *, force_json_markers, torch_allow_copy):\n handle_id = require_str(params, 'handle')\n method_name = require_str(params, 'methodName')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n if handle_id not in instances:\n raise InstanceHandleError(f'Unknown instance handle: {handle_id}')\n obj = instances[handle_id]\n func = getattr(obj, method_name)\n res = func(*args, **kwargs)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef handle_dispose_instance(params, instances):\n handle_id = require_str(params, 'handle')\n if handle_id not in instances:\n return False\n del instances[handle_id]\n return True\n\n\ndef build_meta(instances, *, bridge, pid, python_version, codec_fallback, arrow_available_override=None):\n \"\"\"\n Build the bridge metadata payload.\n\n Field order here is part of the wire contract (the JS validator and the\n documented BridgeInfo shape). Callers supply the backend-specific identity:\n the subprocess server passes bridge='python-subprocess' and a real pid; the\n Pyodide server passes bridge='pyodide' and pid=None.\n\n arrow_available_override: when not None, report this value for arrowAvailable\n instead of probing pyarrow. The Pyodide server forces markers to JSON\n unconditionally, so it advertises arrowAvailable=False regardless of whether\n pyarrow happens to be importable in the WASM environment.\n \"\"\"\n arrow = arrow_available() if arrow_available_override is None else arrow_available_override\n return {\n 'protocol': PROTOCOL,\n 'protocolVersion': PROTOCOL_VERSION,\n 'bridge': bridge,\n 'pythonVersion': python_version,\n 'pid': pid,\n 'codecFallback': codec_fallback,\n 'arrowAvailable': arrow,\n 'scipyAvailable': module_available('scipy'),\n 'torchAvailable': module_available('torch'),\n 'sklearnAvailable': module_available('sklearn'),\n 'instances': len(instances),\n }\n\n\ndef dispatch_request(\n msg,\n instances,\n *,\n bridge,\n pid,\n force_json_markers,\n allow_nan=False,\n python_version=None,\n torch_allow_copy=False,\n arrow_available_override=None,\n):\n \"\"\"\n Validate and route a request, returning the fully-serialized response dict\n ({'id', 'protocol', 'result'}). Raises ProtocolError for malformed requests\n and propagates handler exceptions to the caller, which is responsible for\n building the error envelope (so it controls traceback inclusion).\n\n allow_nan is accepted for signature symmetry; NaN rejection happens during\n the final encode_value() call, which the caller performs.\n \"\"\"\n mid = require_protocol(msg)\n method = msg.get('method')\n if not isinstance(method, str):\n raise ProtocolError('Missing method')\n params = coerce_dict(msg.get('params'), 'params')\n if method == 'call':\n result = handle_call(\n params, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n elif method == 'instantiate':\n result = handle_instantiate(params, instances)\n elif method == 'call_method':\n result = handle_call_method(\n params, instances, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n elif method == 'dispose_instance':\n result = handle_dispose_instance(params, instances)\n elif method == 'meta':\n if python_version is None:\n import sys\n python_version = sys.version.split()[0]\n codec_fallback = 'json' if force_json_markers else 'none'\n result = build_meta(\n instances,\n bridge=bridge,\n pid=pid,\n python_version=python_version,\n codec_fallback=codec_fallback,\n arrow_available_override=arrow_available_override,\n )\n else:\n raise ProtocolError(f'Unknown method: {method}')\n return {'id': mid, 'protocol': PROTOCOL, 'result': result}\n\n\ndef build_error_payload(mid, exc, *, include_traceback):\n \"\"\"\n Build a protocol error response. Protocol/validation errors omit traceback;\n handler errors include it. Field order matches the reference server.\n \"\"\"\n error = {'type': type(exc).__name__, 'message': str(exc)}\n if include_traceback:\n error['traceback'] = traceback.format_exc()\n return {\n 'id': mid if mid is not None else -1,\n 'protocol': PROTOCOL,\n 'error': error,\n }\n";
12
+ export const PYODIDE_BRIDGE_CORE_SOURCE: string = "\"\"\"\nShared tywrap bridge core: protocol dispatch + value (de)serialization.\n\nThis module is the SINGLE source of truth for the \"tywrap/1\" server-side\nprotocol. It is imported by:\n\n - runtime/python_bridge.py (the Node/Bun/Deno subprocess server and the HTTP\n server), which owns I/O concerns: the stdin/stdout JSONL loop, env-var size\n guards, the real OS pid, bridge='python-subprocess', and the final BridgeCodec\n encode wrapper.\n\n - the in-WASM Pyodide server (src/runtime/pyodide-transport.ts). Pyodide cannot read\n this file from disk, so it is shipped as a build-time-generated TypeScript\n string constant (src/runtime/pyodide-bootstrap-core.generated.ts) produced by\n scripts/generate-pyodide-bootstrap.mjs and exec'd into a module registered in\n sys.modules. A conformance drift guard (test/runtime_conformance.test.ts)\n asserts the generated constant stays byte-identical to this file.\n\nCROSS-LANGUAGE CONTRACT (Python <-> the TypeScript decoder in src/utils/codec.ts\nand the request encoder in src/runtime/bridge-codec.ts):\n\n * Every value-type \"marker\" envelope carries {'__tywrap__': <type>,\n 'codecVersion': 1, 'encoding': ...}. The 6 markers are: ndarray, dataframe,\n series, scipy.sparse, torch.tensor, sklearn.estimator.\n * bytes round-trip both ways via base64 envelopes (see _deserialize_bytes_*\n and the bytes branch of default_encoder).\n * NaN/Infinity are rejected (the JS client cannot parse the non-standard tokens\n that allow_nan=True would emit).\n\nPURITY: This module depends only on the standard library plus LAZY optional\nimports (numpy/pandas/scipy/torch/sklearn/pyarrow are each imported inside the\nfunction that needs them). It performs no stdin/stdout I/O and reads no env vars,\nso it runs unchanged under CPython-in-WASM (Pyodide).\n\nforce_json_markers: a *parameter* threaded through every serializer (including\nthe nested torch.tensor -> ndarray call). When True, ndarray/dataframe/series are\nforced down their JSON path regardless of pyarrow availability. Pyodide passes\nTrue (Arrow is unavailable in WASM); the subprocess server passes the boolean\nderived from TYWRAP_CODEC_FALLBACK=json so that \"Node in json-fallback mode\" and\n\"Pyodide\" produce byte-identical marker envelopes.\n\"\"\"\n\nimport base64\nimport datetime as dt\nimport decimal\nimport importlib\nimport importlib.util\nimport json\nimport math\nimport traceback\nimport uuid\nfrom pathlib import Path, PurePath\n\n# Protocol constants. These MUST match src/runtime/protocol.ts (PROTOCOL_ID,\n# TYWRAP_PROTOCOL_VERSION) and the codec version baked into marker envelopes.\nPROTOCOL = 'tywrap/1'\nPROTOCOL_VERSION = 1\nCODEC_VERSION = 1\n\n\nclass ProtocolError(Exception):\n \"\"\"Raised for malformed requests (bad protocol/id/method/params).\"\"\"\n\n\nclass InstanceHandleError(ValueError):\n \"\"\"Raised when an instance handle is unknown or no longer valid.\"\"\"\n\n\nclass ImportNotAllowedError(PermissionError):\n \"\"\"Raised when a requested module import is not on the active allowlist.\"\"\"\n\n def __init__(self, module_name):\n super().__init__(\n f'Import of module {module_name!r} is not permitted by the tywrap bridge '\n 'allowlist; add it to TYWRAP_ALLOWED_MODULES (subprocess) or the '\n 'allowed_modules parameter to enable it'\n )\n\n\nclass AttributeNotAllowedError(PermissionError):\n \"\"\"Raised when access to a private/dunder attribute is denied by policy.\"\"\"\n\n def __init__(self, attr_name):\n super().__init__(\n f'Access to attribute {attr_name!r} is not permitted by the tywrap bridge: '\n 'underscore-prefixed (private/dunder) attributes are blocked to prevent '\n 'sandbox-escape via attributes like __globals__/__subclasses__/__builtins__; '\n 'set TYWRAP_ALLOW_PRIVATE_ATTRS=1 (subprocess) or pass allow_private_attrs=True '\n 'to override'\n )\n\n\n# =============================================================================\n# IMPORT / ATTRIBUTE ALLOWLIST (trust boundary enforcement)\n# =============================================================================\n#\n# The bridge dispatches call/instantiate/call_method by importing the requested\n# module and getattr-ing the requested function/class/method. That is an\n# arbitrary import+getattr+call surface, so two complementary guards live here.\n# Both are PURE (no env reads) so the rules behave identically under the\n# subprocess server and the in-WASM Pyodide server; the subprocess server derives\n# the parameters from env vars (TYWRAP_ALLOWED_MODULES / TYWRAP_ALLOW_PRIVATE_ATTRS)\n# and threads them in, exactly like force_json_markers / torch_allow_copy.\n#\n# 1. MODULE ALLOWLIST (opt-in, default = allow all):\n# allowed_modules=None means \"no restriction\" so existing configurations keep\n# working unchanged. When a caller supplies a set, only those modules (plus the\n# stdlib the bridge itself needs to serialize results, see _BRIDGE_REQUIRED_MODULES)\n# may be imported; submodules of an allowed module are permitted (e.g. allowing\n# 'scipy' also allows 'scipy.sparse'). A non-allowlisted import fails LOUDLY with\n# ImportNotAllowedError rather than silently importing.\n#\n# 2. PRIVATE-ATTRIBUTE BLOCK (default ON):\n# getattr of any name starting with '_' (single-underscore private OR dunder) is\n# rejected. This blocks the classic escape chain (obj.__class__.__subclasses__()\n# /__globals__/__builtins__/__import__) without depending on the module allowlist.\n# tywrap-generated wrappers never reference underscore-prefixed names (the IR\n# analyzer skips them), so this does not regress generated code. Set\n# allow_private_attrs=True to restore unrestricted getattr for trusted callers.\n\n# Stdlib modules the bridge's own serialization/handlers may need to import even\n# when a caller-supplied allowlist is active. Optional codec deps (numpy, pandas,\n# scipy, torch, sklearn, pyarrow) are intentionally NOT here: if a caller restricts\n# modules, they must opt those in explicitly. These names cover only what the\n# bridge core itself imports.\n_BRIDGE_REQUIRED_MODULES = frozenset(\n {\n 'base64',\n 'datetime',\n 'decimal',\n 'importlib',\n 'json',\n 'math',\n 'sys',\n 'traceback',\n 'uuid',\n 'pathlib',\n }\n)\n\n\ndef _top_level_package(module_name):\n \"\"\"Return the top-level package of a dotted module name ('a.b.c' -> 'a').\"\"\"\n return module_name.split('.', 1)[0]\n\n\ndef _is_module_allowed(module_name, allowed_modules):\n \"\"\"\n Return True when module_name may be imported under the active policy.\n\n allowed_modules=None disables enforcement (allow all). Otherwise a module is\n allowed when it (or its top-level package) is explicitly listed, or it is one\n of the stdlib modules the bridge itself requires.\n \"\"\"\n if allowed_modules is None:\n return True\n if module_name in allowed_modules or module_name in _BRIDGE_REQUIRED_MODULES:\n return True\n top = _top_level_package(module_name)\n return top in allowed_modules or top in _BRIDGE_REQUIRED_MODULES\n\n\ndef import_allowed_module(module_name, allowed_modules):\n \"\"\"\n Import module_name only if permitted by the allowlist, else raise loudly.\n\n This is the single chokepoint every handler routes module imports through.\n \"\"\"\n if not _is_module_allowed(module_name, allowed_modules):\n raise ImportNotAllowedError(module_name)\n return importlib.import_module(module_name)\n\n\ndef get_allowed_attr(obj, attr_name, *, allow_private_attrs):\n \"\"\"\n getattr(obj, attr_name) with the private/dunder block applied.\n\n Rejects any underscore-prefixed name unless allow_private_attrs is True. This\n is the single chokepoint every handler routes attribute access through.\n \"\"\"\n if not allow_private_attrs and attr_name.startswith('_'):\n raise AttributeNotAllowedError(attr_name)\n return getattr(obj, attr_name)\n\n\nclass CodecError(Exception):\n \"\"\"Raised when value encoding fails (e.g. NaN/Infinity not allowed).\"\"\"\n\n\n# =============================================================================\n# REQUEST-SIDE DESERIALIZATION (bytes envelopes -> Python bytes)\n# =============================================================================\n\n_NO_DESERIALIZE = object()\n_ERR_BYTES_MISSING_B64 = 'Invalid bytes envelope: missing b64'\n_ERR_BYTES_MISSING_DATA = 'Invalid bytes envelope: missing data'\n_ERR_BYTES_INVALID_BASE64 = 'Invalid bytes envelope: invalid base64'\n\n\ndef _deserialize_bytes_envelope(value):\n \"\"\"\n Decode base64-encoded bytes envelopes from JS into Python bytes.\n\n Supported shapes:\n - { \"__tywrap_bytes__\": true, \"b64\": \"...\" } (JS BridgeCodec.encodeRequest)\n - { \"__type__\": \"bytes\", \"encoding\": \"base64\", \"data\": \"...\" } (legacy/compat)\n\n Why: TS BridgeCodec encodes Uint8Array/ArrayBuffer as base64 objects, but\n Python handlers expect real bytes/bytearray to preserve behavior (e.g., len()).\n \"\"\"\n if not isinstance(value, dict):\n return _NO_DESERIALIZE\n\n if value.get('__tywrap_bytes__') is True:\n b64 = value.get('b64')\n if not isinstance(b64, str):\n raise ProtocolError(_ERR_BYTES_MISSING_B64)\n try:\n return base64.b64decode(b64, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n if value.get('__type__') == 'bytes' and value.get('encoding') == 'base64':\n data = value.get('data')\n if not isinstance(data, str):\n raise ProtocolError(_ERR_BYTES_MISSING_DATA)\n try:\n return base64.b64decode(data, validate=True)\n except Exception as exc:\n raise ProtocolError(_ERR_BYTES_INVALID_BASE64) from exc\n\n return _NO_DESERIALIZE\n\n\ndef deserialize(value):\n \"\"\"\n Recursively deserialize request values into Python-native types.\n\n Why: requests are JSON-only; we need a small set of explicit decoders\n (currently bytes) to restore Python semantics at the boundary.\n \"\"\"\n decoded = _deserialize_bytes_envelope(value)\n if decoded is not _NO_DESERIALIZE:\n return decoded\n\n if isinstance(value, list):\n return [deserialize(item) for item in value]\n if isinstance(value, dict):\n # Preserve dict shape while decoding nested values.\n return {k: deserialize(v) for k, v in value.items()}\n return value\n\n\n# =============================================================================\n# CAPABILITY DETECTION (lazy, best-effort)\n# =============================================================================\n\ndef arrow_available():\n \"\"\"Return True when pyarrow can be imported.\"\"\"\n try:\n import pyarrow # noqa: F401\n except (ImportError, OSError):\n return False\n return True\n\n\ndef module_available(module_name):\n \"\"\"\n Lightweight feature detection for optional codec dependencies via find_spec.\n\n Why: exposes availability in bridge metadata without importing heavy modules.\n \"\"\"\n try:\n return importlib.util.find_spec(module_name) is not None\n except (ImportError, AttributeError, TypeError, ValueError):\n return False\n\n\ndef is_numpy_array(obj):\n try:\n import numpy as np # noqa: F401\n except Exception:\n return False\n return isinstance(obj, np.ndarray)\n\n\ndef is_pandas_dataframe(obj):\n try:\n import pandas as pd # noqa: F401\n except Exception:\n return False\n return isinstance(obj, pd.DataFrame)\n\n\ndef is_pandas_series(obj):\n try:\n import pandas as pd # noqa: F401\n except Exception:\n return False\n return isinstance(obj, pd.Series)\n\n\ndef is_scipy_sparse(obj):\n try:\n import scipy.sparse as sp # noqa: F401\n except Exception:\n return False\n try:\n return sp.issparse(obj)\n except Exception:\n return False\n\n\ndef is_torch_tensor(obj):\n try:\n import torch # noqa: F401\n except Exception:\n return False\n try:\n return torch.is_tensor(obj)\n except Exception:\n return False\n\n\ndef is_sklearn_estimator(obj):\n try:\n from sklearn.base import BaseEstimator # noqa: F401\n except Exception:\n return False\n return isinstance(obj, BaseEstimator)\n\n\n# =============================================================================\n# MARKER SERIALIZERS (6 __tywrap__ value types)\n# =============================================================================\n#\n# Each serializer accepts force_json_markers. When True, the Arrow path is never\n# taken (used by Pyodide and by the subprocess server in TYWRAP_CODEC_FALLBACK=json\n# mode). The JSON fallback envelopes are byte-identical across both callers, which\n# is what the conformance suite asserts.\n\ndef serialize_ndarray(obj, *, force_json_markers):\n \"\"\"\n Encode a NumPy ndarray. Arrow IPC (compact, lossless) by default; JSON when\n force_json_markers is set or pyarrow is unavailable in fallback mode.\n\n Note: pa.array() only handles 1D arrays; multi-dimensional arrays are\n flattened with shape metadata for JS-side reconstruction. See\n https://github.com/apache/arrow-js/issues/115\n \"\"\"\n if force_json_markers:\n return serialize_ndarray_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for ndarray; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n original_shape = list(obj.shape) if hasattr(obj, 'shape') else None\n flat = obj.flatten() if hasattr(obj, 'ndim') and obj.ndim > 1 else obj\n arr = pa.array(flat)\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'shape': original_shape,\n 'dtype': str(obj.dtype) if hasattr(obj, 'dtype') else None,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for ndarray') from exc\n\n\ndef serialize_ndarray_json(obj):\n \"\"\"JSON fallback for ndarray (larger payloads, potential dtype loss).\"\"\"\n try:\n data = obj.tolist()\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for ndarray') from exc\n return {\n '__tywrap__': 'ndarray',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'shape': getattr(obj, 'shape', None),\n }\n\n\ndef serialize_dataframe(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas DataFrame. Feather/Arrow-IPC (uncompressed, so apache-arrow\n in JS can read it) by default; JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_dataframe_json(obj)\n try:\n import pyarrow as pa # type: ignore\n import pyarrow.feather as feather # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.DataFrame; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n table = pa.Table.from_pandas(obj) # type: ignore\n sink = pa.BufferOutputStream()\n feather.write_feather(table, sink, compression='uncompressed')\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.DataFrame') from exc\n\n\ndef serialize_dataframe_json(obj):\n \"\"\"JSON fallback for DataFrame: records orientation.\"\"\"\n try:\n data = obj.to_dict(orient='records')\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.DataFrame') from exc\n return {\n '__tywrap__': 'dataframe',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n }\n\n\ndef serialize_series(obj, *, force_json_markers):\n \"\"\"\n Encode a pandas Series as a single-column Arrow Table stream (the JS decoder\n contract is \"table-like\"); JSON when force_json_markers is set.\n \"\"\"\n if force_json_markers:\n return serialize_series_json(obj)\n try:\n import pyarrow as pa # type: ignore\n except Exception as exc:\n raise RuntimeError(\n 'Arrow encoding unavailable for pandas.Series; install pyarrow or set TYWRAP_CODEC_FALLBACK=json to enable JSON fallback'\n ) from exc\n try:\n arr = pa.Array.from_pandas(obj) # type: ignore\n table = pa.Table.from_arrays([arr], names=['value'])\n sink = pa.BufferOutputStream()\n with pa.ipc.new_stream(sink, table.schema) as writer:\n writer.write_table(table)\n buf = sink.getvalue()\n b64 = base64.b64encode(buf.to_pybytes()).decode('ascii')\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'arrow',\n 'b64': b64,\n 'name': getattr(obj, 'name', None),\n }\n except Exception as exc:\n raise RuntimeError('Arrow encoding failed for pandas.Series') from exc\n\n\ndef serialize_series_json(obj):\n \"\"\"JSON fallback for Series (potentially lossy dtype/NA representation).\"\"\"\n try:\n data = obj.to_list() # type: ignore\n except Exception:\n try:\n data = obj.to_dict() # type: ignore\n except Exception as exc:\n raise RuntimeError('JSON fallback failed for pandas.Series') from exc\n return {\n '__tywrap__': 'series',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'data': data,\n 'name': getattr(obj, 'name', None),\n }\n\n\ndef serialize_sparse_matrix(obj):\n \"\"\"\n Serialize scipy sparse matrices into structured JSON envelopes (json-only;\n there is no Arrow path). Preserves sparsity; rejects unsupported formats and\n complex dtypes explicitly.\n \"\"\"\n try:\n fmt = obj.getformat()\n except Exception as exc:\n raise RuntimeError('Failed to inspect scipy sparse matrix format') from exc\n\n if fmt not in ('csr', 'csc', 'coo'):\n raise RuntimeError(f'Unsupported scipy sparse format: {fmt}')\n\n dtype = None\n try:\n dtype = str(obj.dtype)\n except Exception:\n dtype = None\n if getattr(obj.dtype, 'kind', None) == 'c':\n raise RuntimeError('Complex sparse matrices are not supported by JSON codec')\n\n if fmt in ('csr', 'csc'):\n data = obj.data.tolist()\n indices = obj.indices.tolist()\n indptr = obj.indptr.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'indices': indices,\n 'indptr': indptr,\n 'dtype': dtype,\n }\n\n # coo\n data = obj.data.tolist()\n row = obj.row.tolist()\n col = obj.col.tolist()\n return {\n '__tywrap__': 'scipy.sparse',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'format': fmt,\n 'shape': list(obj.shape),\n 'data': data,\n 'row': row,\n 'col': col,\n 'dtype': dtype,\n }\n\n\ndef serialize_torch_tensor(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Serialize torch.Tensor values via the nested ndarray envelope. CPU-only by\n default; device/copy behavior is explicit. force_json_markers is threaded\n into the nested ndarray serialization so Pyodide gets a JSON ndarray value.\n \"\"\"\n tensor = obj.detach()\n if getattr(tensor, 'device', None) is not None and tensor.device.type != 'cpu':\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is on a non-CPU device; set TYWRAP_TORCH_ALLOW_COPY=1 to allow CPU transfer'\n )\n tensor = tensor.to('cpu')\n if hasattr(tensor, 'is_contiguous') and not tensor.is_contiguous():\n if not torch_allow_copy:\n raise RuntimeError(\n 'Torch tensor is not contiguous; set TYWRAP_TORCH_ALLOW_COPY=1 to allow contiguous copy'\n )\n tensor = tensor.contiguous()\n try:\n arr = tensor.numpy()\n except Exception as exc:\n raise RuntimeError('Failed to convert torch.Tensor to numpy') from exc\n\n return {\n '__tywrap__': 'torch.tensor',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'ndarray',\n 'value': serialize_ndarray(arr, force_json_markers=force_json_markers),\n 'shape': list(tensor.shape),\n 'dtype': str(tensor.dtype),\n 'device': str(tensor.device),\n }\n\n\ndef serialize_sklearn_estimator(obj):\n \"\"\"Serialize sklearn estimators as metadata only (json-only); no pickling.\"\"\"\n try:\n import sklearn # noqa: F401\n except Exception as exc:\n raise RuntimeError('scikit-learn is not available') from exc\n\n params = obj.get_params(deep=False)\n try:\n json.dumps(params)\n except Exception as exc:\n raise RuntimeError(\n 'scikit-learn estimator params are not JSON-serializable; avoid returning estimators or sanitize params'\n ) from exc\n\n return {\n '__tywrap__': 'sklearn.estimator',\n 'codecVersion': CODEC_VERSION,\n 'encoding': 'json',\n 'className': obj.__class__.__name__,\n 'module': obj.__class__.__module__,\n 'version': getattr(sklearn, '__version__', None),\n 'params': params,\n }\n\n\n_NO_PYDANTIC = object()\n\n\ndef serialize_pydantic(obj):\n \"\"\"\n Serialize Pydantic v2 models via model_dump(by_alias=True, mode='json')\n without importing Pydantic. Returns _NO_PYDANTIC when obj is not a model.\n \"\"\"\n model_dump = getattr(obj, 'model_dump', None)\n if not callable(model_dump):\n return _NO_PYDANTIC\n try:\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n # Older Pydantic versions may not support `mode=...`.\n return model_dump(by_alias=True)\n except Exception as exc:\n raise RuntimeError(f'model_dump failed: {exc}') from exc\n\n\ndef serialize_stdlib(obj):\n \"\"\"Coerce common stdlib scalar types to JSON-safe forms; None otherwise.\"\"\"\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n return None\n\n\ndef serialize(obj, *, force_json_markers, torch_allow_copy=False):\n \"\"\"\n Top-level result serializer. Dispatch order is significant: numpy ndarray ->\n dataframe -> series -> scipy.sparse -> torch -> sklearn -> Pydantic -> stdlib\n -> passthrough. The remaining BridgeCodec value behaviors (numpy/pandas scalars,\n bytes, sets, complex rejection, NaN/Infinity) are applied later during JSON\n encoding by default_encoder.\n \"\"\"\n if is_numpy_array(obj):\n return serialize_ndarray(obj, force_json_markers=force_json_markers)\n if is_pandas_dataframe(obj):\n return serialize_dataframe(obj, force_json_markers=force_json_markers)\n if is_pandas_series(obj):\n return serialize_series(obj, force_json_markers=force_json_markers)\n if is_scipy_sparse(obj):\n return serialize_sparse_matrix(obj)\n if is_torch_tensor(obj):\n return serialize_torch_tensor(\n obj, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy\n )\n if is_sklearn_estimator(obj):\n return serialize_sklearn_estimator(obj)\n pydantic_value = serialize_pydantic(obj)\n if pydantic_value is not _NO_PYDANTIC:\n return pydantic_value\n stdlib_value = serialize_stdlib(obj)\n if stdlib_value is not None:\n return stdlib_value\n return obj\n\n\n# =============================================================================\n# JSON ENCODE: BridgeCodec-equivalent value handling (NaN reject, scalars, bytes)\n# =============================================================================\n#\n# This mirrors BridgeCodec._default_encoder (runtime/safe_codec.py) for the VALUE\n# behaviors that are part of the wire contract. The subprocess server still uses\n# the real BridgeCodec for its final encode (it also enforces size limits); this\n# core encoder exists so the Pyodide server gets identical value handling without\n# depending on safe_codec.py. The conformance suite asserts these behaviors match.\n\ndef _is_nan_or_inf(value):\n if not isinstance(value, (int, float)):\n return False\n try:\n return math.isnan(value) or math.isinf(value)\n except (TypeError, ValueError):\n return False\n\n\ndef _is_numpy_scalar(obj):\n try:\n import numpy as np\n except ImportError:\n return False\n return isinstance(obj, (np.generic, np.ndarray)) and obj.ndim == 0\n\n\ndef _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n return False\n return isinstance(obj, (pd.Timestamp, pd.Timedelta, type(pd.NaT)))\n\n\ndef make_default_encoder(*, allow_nan):\n \"\"\"\n Build a json.dumps default= encoder matching BridgeCodec's value handling.\n\n Raises CodecError for NaN/Infinity extracted from numpy scalars (json.dumps\n itself rejects top-level/nested NaN/Infinity floats when allow_nan=False).\n \"\"\"\n\n def default_encoder(obj):\n # numpy/pandas scalars first (need .item() extraction).\n if _is_numpy_scalar(obj):\n extracted = obj.item()\n if not allow_nan and _is_nan_or_inf(extracted):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON')\n return extracted\n\n if _is_pandas_scalar(obj):\n try:\n import pandas as pd\n except ImportError:\n pass\n else:\n if obj is pd.NaT or (hasattr(pd, 'isna') and pd.isna(obj)):\n return None\n if isinstance(obj, pd.Timestamp):\n return obj.isoformat()\n if isinstance(obj, pd.Timedelta):\n return obj.total_seconds()\n\n if isinstance(obj, dt.datetime):\n return obj.isoformat()\n if isinstance(obj, dt.date):\n return obj.isoformat()\n if isinstance(obj, dt.time):\n return obj.isoformat()\n if isinstance(obj, dt.timedelta):\n return obj.total_seconds()\n if isinstance(obj, decimal.Decimal):\n return str(obj)\n if isinstance(obj, uuid.UUID):\n return str(obj)\n if isinstance(obj, (Path, PurePath)):\n return str(obj)\n\n if isinstance(obj, (bytes, bytearray)):\n return {\n '__type__': 'bytes',\n 'encoding': 'base64',\n 'data': base64.b64encode(obj).decode('ascii'),\n }\n\n model_dump = getattr(obj, 'model_dump', None)\n if callable(model_dump):\n try:\n return model_dump(by_alias=True, mode='json')\n except TypeError:\n return model_dump(by_alias=True)\n\n if isinstance(obj, (set, frozenset)):\n return list(obj)\n\n if isinstance(obj, complex):\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')\n\n return default_encoder\n\n\ndef encode_value(value, *, allow_nan):\n \"\"\"\n JSON-encode a fully-serialized response value, applying the BridgeCodec-equivalent\n default encoder and rejecting NaN/Infinity when allow_nan is False.\n\n Raises CodecError (wrapping the json.dumps ValueError) on NaN/Infinity, matching\n BridgeCodec's \"Cannot serialize NaN...\" wording so error parity holds.\n \"\"\"\n try:\n return json.dumps(value, default=make_default_encoder(allow_nan=allow_nan), allow_nan=allow_nan)\n except ValueError as exc:\n error_msg = str(exc).lower()\n # json.dumps(allow_nan=False) rejects NaN/Infinity with a ValueError whose\n # wording is Python-version dependent: 3.12+ appends the offending value\n # (\"...not JSON compliant: nan\"), but 3.10/3.11 emit only the canonical\n # \"Out of range float values are not JSON compliant\". Match that phrase too\n # so the typed error message is stable across versions.\n if (\n 'nan' in error_msg\n or 'infinity' in error_msg\n or 'inf' in error_msg\n or 'out of range float' in error_msg\n ):\n raise CodecError('Cannot serialize NaN - NaN/Infinity not allowed in JSON') from exc\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n except TypeError as exc:\n raise CodecError(f'JSON encoding failed: {exc}') from exc\n\n\n# =============================================================================\n# REQUEST VALIDATION + HANDLERS + DISPATCH\n# =============================================================================\n\ndef require_protocol(msg):\n if not isinstance(msg, dict):\n raise ProtocolError('Invalid request payload')\n proto = msg.get('protocol')\n if proto != PROTOCOL:\n raise ProtocolError(f'Invalid protocol: {proto}')\n mid = msg.get('id')\n if not isinstance(mid, int):\n raise ProtocolError(f'Invalid request id: {mid}')\n return mid\n\n\ndef require_str(params, key):\n value = params.get(key)\n if not isinstance(value, str) or not value:\n raise ProtocolError(f'Missing {key}')\n return value\n\n\ndef coerce_list(value, key):\n if value is None:\n return []\n if not isinstance(value, list):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef coerce_dict(value, key):\n if value is None:\n return {}\n if not isinstance(value, dict):\n raise ProtocolError(f'Invalid {key}')\n return value\n\n\ndef handle_call(params, *, force_json_markers, torch_allow_copy, allowed_modules, allow_private_attrs):\n module_name = require_str(params, 'module')\n function_name = require_str(params, 'functionName')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n mod = import_allowed_module(module_name, allowed_modules)\n func = get_allowed_attr(mod, function_name, allow_private_attrs=allow_private_attrs)\n res = func(*args, **kwargs)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef handle_instantiate(params, instances, *, allowed_modules, allow_private_attrs):\n module_name = require_str(params, 'module')\n class_name = require_str(params, 'className')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n mod = import_allowed_module(module_name, allowed_modules)\n cls = get_allowed_attr(mod, class_name, allow_private_attrs=allow_private_attrs)\n obj = cls(*args, **kwargs)\n handle_id = str(id(obj))\n instances[handle_id] = obj\n return handle_id\n\n\ndef handle_call_method(params, instances, *, force_json_markers, torch_allow_copy, allow_private_attrs):\n handle_id = require_str(params, 'handle')\n method_name = require_str(params, 'methodName')\n args = deserialize(coerce_list(params.get('args'), 'args'))\n kwargs = deserialize(coerce_dict(params.get('kwargs'), 'kwargs'))\n if handle_id not in instances:\n raise InstanceHandleError(f'Unknown instance handle: {handle_id}')\n obj = instances[handle_id]\n func = get_allowed_attr(obj, method_name, allow_private_attrs=allow_private_attrs)\n res = func(*args, **kwargs)\n return serialize(res, force_json_markers=force_json_markers, torch_allow_copy=torch_allow_copy)\n\n\ndef handle_dispose_instance(params, instances):\n handle_id = require_str(params, 'handle')\n if handle_id not in instances:\n return False\n del instances[handle_id]\n return True\n\n\ndef build_meta(instances, *, bridge, pid, python_version, codec_fallback, arrow_available_override=None):\n \"\"\"\n Build the bridge metadata payload.\n\n Field order here is part of the wire contract (the JS validator and the\n documented BridgeInfo shape). Callers supply the backend-specific identity:\n the subprocess server passes bridge='python-subprocess' and a real pid; the\n Pyodide server passes bridge='pyodide' and pid=None.\n\n arrow_available_override: when not None, report this value for arrowAvailable\n instead of probing pyarrow. The Pyodide server forces markers to JSON\n unconditionally, so it advertises arrowAvailable=False regardless of whether\n pyarrow happens to be importable in the WASM environment.\n \"\"\"\n arrow = arrow_available() if arrow_available_override is None else arrow_available_override\n return {\n 'protocol': PROTOCOL,\n 'protocolVersion': PROTOCOL_VERSION,\n 'bridge': bridge,\n 'pythonVersion': python_version,\n 'pid': pid,\n 'codecFallback': codec_fallback,\n 'arrowAvailable': arrow,\n 'scipyAvailable': module_available('scipy'),\n 'torchAvailable': module_available('torch'),\n 'sklearnAvailable': module_available('sklearn'),\n 'instances': len(instances),\n }\n\n\ndef dispatch_request(\n msg,\n instances,\n *,\n bridge,\n pid,\n force_json_markers,\n allow_nan=False,\n python_version=None,\n torch_allow_copy=False,\n arrow_available_override=None,\n allowed_modules=None,\n allow_private_attrs=False,\n):\n \"\"\"\n Validate and route a request, returning the fully-serialized response dict\n ({'id', 'protocol', 'result'}). Raises ProtocolError for malformed requests\n and propagates handler exceptions to the caller, which is responsible for\n building the error envelope (so it controls traceback inclusion).\n\n allow_nan is accepted for signature symmetry; NaN rejection happens during\n the final encode_value() call, which the caller performs.\n\n allowed_modules: None (default) disables the import allowlist so existing\n behavior is preserved. Supplying a set restricts call/instantiate imports to\n those modules (plus the stdlib the bridge itself needs) and raises\n ImportNotAllowedError otherwise. allow_private_attrs=False (default) blocks\n getattr of underscore-prefixed names; True restores unrestricted access. See\n the IMPORT / ATTRIBUTE ALLOWLIST section above for the full trust model.\n \"\"\"\n mid = require_protocol(msg)\n method = msg.get('method')\n if not isinstance(method, str):\n raise ProtocolError('Missing method')\n params = coerce_dict(msg.get('params'), 'params')\n if method == 'call':\n result = handle_call(\n params,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n allowed_modules=allowed_modules,\n allow_private_attrs=allow_private_attrs,\n )\n elif method == 'instantiate':\n result = handle_instantiate(\n params, instances, allowed_modules=allowed_modules, allow_private_attrs=allow_private_attrs\n )\n elif method == 'call_method':\n result = handle_call_method(\n params,\n instances,\n force_json_markers=force_json_markers,\n torch_allow_copy=torch_allow_copy,\n allow_private_attrs=allow_private_attrs,\n )\n elif method == 'dispose_instance':\n result = handle_dispose_instance(params, instances)\n elif method == 'meta':\n if python_version is None:\n import sys\n python_version = sys.version.split()[0]\n codec_fallback = 'json' if force_json_markers else 'none'\n result = build_meta(\n instances,\n bridge=bridge,\n pid=pid,\n python_version=python_version,\n codec_fallback=codec_fallback,\n arrow_available_override=arrow_available_override,\n )\n else:\n raise ProtocolError(f'Unknown method: {method}')\n return {'id': mid, 'protocol': PROTOCOL, 'result': result}\n\n\ndef build_error_payload(mid, exc, *, include_traceback):\n \"\"\"\n Build a protocol error response. Protocol/validation errors omit traceback;\n handler errors include it. Field order matches the reference server.\n \"\"\"\n error = {'type': type(exc).__name__, 'message': str(exc)}\n if include_traceback:\n error['traceback'] = traceback.format_exc()\n return {\n 'id': mid if mid is not None else -1,\n 'protocol': PROTOCOL,\n 'error': error,\n }\n";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * PyodideIO Transport - In-memory Pyodide communication for browser environments.
2
+ * PyodideTransport - In-memory Pyodide communication for browser environments.
3
3
  *
4
4
  * This transport implements the Transport interface for direct in-memory
5
5
  * communication with Pyodide (Python compiled to WebAssembly). It is designed
@@ -29,9 +29,9 @@ import {
29
29
  // =============================================================================
30
30
 
31
31
  /**
32
- * Options for configuring the PyodideIO transport.
32
+ * Options for configuring the PyodideTransport.
33
33
  */
34
- export interface PyodideIOOptions {
34
+ export interface PyodideTransportOptions {
35
35
  /** URL for Pyodide CDN. Default: official CDN */
36
36
  indexURL?: string;
37
37
  /** Python packages to load during initialization */
@@ -176,7 +176,7 @@ def __tywrap_dispatch(message_json):
176
176
  *
177
177
  * @example
178
178
  * ```typescript
179
- * const transport = new PyodideIO({ packages: ['numpy'] });
179
+ * const transport = new PyodideTransport({ packages: ['numpy'] });
180
180
  * await transport.init();
181
181
  *
182
182
  * const response = await transport.send(
@@ -192,17 +192,17 @@ def __tywrap_dispatch(message_json):
192
192
  * await transport.dispose();
193
193
  * ```
194
194
  */
195
- export class PyodideIO extends DisposableBase implements Transport {
195
+ export class PyodideTransport extends DisposableBase implements Transport {
196
196
  private readonly indexURL: string;
197
197
  private readonly packages: readonly string[];
198
198
  private py?: PyodideInstance;
199
199
 
200
200
  /**
201
- * Create a new PyodideIO transport.
201
+ * Create a new PyodideTransport.
202
202
  *
203
203
  * @param options - Configuration options
204
204
  */
205
- constructor(options: PyodideIOOptions = {}) {
205
+ constructor(options: PyodideTransportOptions = {}) {
206
206
  super();
207
207
  this.indexURL = options.indexURL ?? DEFAULT_INDEX_URL;
208
208
  this.packages = Object.freeze([...(options.packages ?? [])]);
@@ -2,7 +2,7 @@
2
2
  * Pyodide runtime bridge.
3
3
  *
4
4
  * PyodideBridge is a thin facade: it extends DisposableBase (lifecycle) and
5
- * implements PythonRuntime by HOLDING an RpcClient over a PyodideIO transport
5
+ * implements PythonRuntime by HOLDING an RpcClient over a PyodideTransport
6
6
  * for in-memory Python execution in browser environments via WebAssembly.
7
7
  *
8
8
  * @see https://github.com/bbopen/tywrap/issues/149
@@ -12,8 +12,8 @@ import type { PythonRuntime, BridgeInfo } from '../types/index.js';
12
12
 
13
13
  import { DisposableBase } from './bounded-context.js';
14
14
  import { RpcClient, type GetBridgeInfoOptions } from './rpc-client.js';
15
- import { PyodideIO } from './pyodide-io.js';
16
- import type { CodecOptions } from './safe-codec.js';
15
+ import { PyodideTransport } from './pyodide-transport.js';
16
+ import type { CodecOptions } from './bridge-codec.js';
17
17
 
18
18
  // =============================================================================
19
19
  // OPTIONS
@@ -51,7 +51,7 @@ export interface PyodideBridgeOptions {
51
51
  * - Zero network overhead (in-memory execution)
52
52
  * - Automatic Pyodide loading from CDN or module
53
53
  * - Python package loading support
54
- * - Full SafeCodec validation (NaN/Infinity rejection, key validation)
54
+ * - Full BridgeCodec validation (NaN/Infinity rejection, key validation)
55
55
  * - Proper proxy cleanup to prevent memory leaks
56
56
  *
57
57
  * @example
@@ -78,7 +78,7 @@ export class PyodideBridge extends DisposableBase implements PythonRuntime {
78
78
  constructor(options: PyodideBridgeOptions = {}) {
79
79
  super();
80
80
 
81
- const transport = new PyodideIO({
81
+ const transport = new PyodideTransport({
82
82
  indexURL: options.indexURL,
83
83
  packages: options.packages,
84
84
  });
@@ -110,7 +110,7 @@ export class PyodideBridge extends DisposableBase implements PythonRuntime {
110
110
  }
111
111
 
112
112
  // ===========================================================================
113
- // RPC METHODS (delegate to the held RpcClient; never PyodideIO directly)
113
+ // RPC METHODS (delegate to the held RpcClient; never PyodideTransport directly)
114
114
  // ===========================================================================
115
115
 
116
116
  async call<T = unknown>(
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * RpcClient - the single correlated-RPC client for JS<->Python communication.
3
3
  *
4
- * It HOLDS a Transport and a codec (SafeCodec) and is, in turn, HELD by the
4
+ * It HOLDS a Transport and a codec (BridgeCodec) and is, in turn, HELD by the
5
5
  * bridge facades (NodeBridge/HttpBridge/PyodideBridge) via composition — it is
6
6
  * NOT a base class bridges extend. It owns the one place where the wire frame
7
7
  * is built and correlated: id generation, {id, protocol} stamping, codec
@@ -22,9 +22,13 @@ import type { BridgeInfo } from '../types/index.js';
22
22
 
23
23
  import { DisposableBase, type ExecuteOptions } from './bounded-context.js';
24
24
  import { BridgeProtocolError } from './errors.js';
25
- import { SafeCodec, type CodecOptions } from './safe-codec.js';
26
- import { TYWRAP_PROTOCOL_VERSION } from './protocol.js';
27
- import { PROTOCOL_ID, type Transport, type ProtocolMessage } from './transport.js';
25
+ import { BridgeCodec, type CodecOptions } from './bridge-codec.js';
26
+ import {
27
+ PROTOCOL_ID,
28
+ TYWRAP_PROTOCOL_VERSION,
29
+ type Transport,
30
+ type ProtocolMessage,
31
+ } from './transport.js';
28
32
 
29
33
  // =============================================================================
30
34
  // TYPES
@@ -180,7 +184,7 @@ function validateBridgeInfoPayload(value: unknown): BridgeInfo {
180
184
  // =============================================================================
181
185
 
182
186
  /**
183
- * RpcClient holds a SafeCodec + Transport and composes DisposableBase for
187
+ * RpcClient holds a BridgeCodec + Transport and composes DisposableBase for
184
188
  * lifecycle/bounded-execution. It is the one correlated-RPC client; bridge
185
189
  * facades HOLD an instance and delegate their PythonRuntime methods to it.
186
190
  *
@@ -190,7 +194,7 @@ function validateBridgeInfoPayload(value: unknown): BridgeInfo {
190
194
  * private readonly rpc: RpcClient;
191
195
  * constructor(options: NodeBridgeOptions) {
192
196
  * super();
193
- * const transport = new ProcessIO(options);
197
+ * const transport = new SubprocessTransport(options);
194
198
  * this.rpc = new RpcClient({ transport, defaultTimeoutMs: options.timeout });
195
199
  * this.trackResource(this.rpc);
196
200
  * }
@@ -200,7 +204,7 @@ function validateBridgeInfoPayload(value: unknown): BridgeInfo {
200
204
  */
201
205
  export class RpcClient extends DisposableBase {
202
206
  /** Codec instance for validation and serialization */
203
- readonly codec: SafeCodec;
207
+ readonly codec: BridgeCodec;
204
208
 
205
209
  /** Transport instance for message passing */
206
210
  readonly transport: Transport;
@@ -221,7 +225,7 @@ export class RpcClient extends DisposableBase {
221
225
  */
222
226
  constructor(options: RpcClientOptions) {
223
227
  super();
224
- this.codec = new SafeCodec(options.codec);
228
+ this.codec = new BridgeCodec(options.codec);
225
229
  this.transport = options.transport;
226
230
  this.defaultTimeoutMs = options.defaultTimeoutMs ?? 30000;
227
231
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * ProcessIO Transport - Subprocess-based Python communication for Node.js.
2
+ * SubprocessTransport - Subprocess-based Python communication for Node.js.
3
3
  *
4
4
  * This transport implements the Transport interface for spawning and communicating
5
5
  * with a Python subprocess via stdio streams. It provides:
@@ -46,9 +46,9 @@ const CONTROL_CHARS_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F\u0080-\u
46
46
  // =============================================================================
47
47
 
48
48
  /**
49
- * Options for ProcessIO transport.
49
+ * Options for the SubprocessTransport.
50
50
  */
51
- export interface ProcessIOOptions {
51
+ export interface SubprocessTransportOptions {
52
52
  /** Python executable path. Default: 'python3' */
53
53
  pythonPath?: string;
54
54
 
@@ -135,14 +135,14 @@ function extractMessageId(json: string): number | null {
135
135
  /**
136
136
  * Transport implementation for subprocess-based Python communication.
137
137
  *
138
- * ProcessIO spawns a Python child process and communicates via stdio:
138
+ * SubprocessTransport spawns a Python child process and communicates via stdio:
139
139
  * - Requests are written to stdin as JSON lines
140
140
  * - Responses are read from stdout as JSON lines
141
141
  * - Stderr is captured for diagnostics
142
142
  *
143
143
  * @example
144
144
  * ```typescript
145
- * const transport = new ProcessIO({
145
+ * const transport = new SubprocessTransport({
146
146
  * bridgeScript: '/path/to/bridge.py',
147
147
  * pythonPath: 'python3',
148
148
  * });
@@ -157,7 +157,7 @@ function extractMessageId(json: string): number | null {
157
157
  * await transport.dispose();
158
158
  * ```
159
159
  */
160
- export class ProcessIO extends DisposableBase implements Transport {
160
+ export class SubprocessTransport extends DisposableBase implements Transport {
161
161
  // Configuration
162
162
  private readonly pythonPath: string;
163
163
  private readonly bridgeScript: string;
@@ -189,11 +189,11 @@ export class ProcessIO extends DisposableBase implements Transport {
189
189
  private draining = false;
190
190
 
191
191
  /**
192
- * Create a new ProcessIO transport.
192
+ * Create a new SubprocessTransport.
193
193
  *
194
194
  * @param options - Transport configuration options
195
195
  */
196
- constructor(options: ProcessIOOptions) {
196
+ constructor(options: SubprocessTransportOptions) {
197
197
  super();
198
198
 
199
199
  this.pythonPath = options.pythonPath ?? 'python3';
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WorkerPool - Manages multiple Transport instances for concurrent request handling.
2
+ * TransportPool - Manages multiple Transport instances for concurrent request handling.
3
3
  *
4
4
  * Provides semaphore-based concurrency control with configurable limits per worker
5
5
  * and a wait queue for callers when all workers are at capacity.
@@ -16,9 +16,9 @@ import type { Transport } from './transport.js';
16
16
  // =============================================================================
17
17
 
18
18
  /**
19
- * Configuration options for the WorkerPool.
19
+ * Configuration options for the TransportPool.
20
20
  */
21
- export interface WorkerPoolOptions {
21
+ export interface TransportPoolOptions {
22
22
  /** Factory function to create transports */
23
23
  createTransport: () => Transport;
24
24
 
@@ -38,20 +38,20 @@ export interface WorkerPoolOptions {
38
38
  * Callback invoked after each worker is created and initialized.
39
39
  * Use this for per-worker warmup (e.g., importing modules, running setup).
40
40
  */
41
- onWorkerReady?: (worker: PooledWorker) => Promise<void>;
41
+ onWorkerReady?: (worker: TransportLease) => Promise<void>;
42
42
 
43
43
  /**
44
44
  * Optional callback used only for background replacement workers after a
45
45
  * fatal timeout/crash. This lets callers publish a replacement only after it
46
46
  * is proven ready, without charging hidden work to normal request startup.
47
47
  */
48
- onReplacementWorkerReady?: (worker: PooledWorker) => Promise<void>;
48
+ onReplacementWorkerReady?: (worker: TransportLease) => Promise<void>;
49
49
  }
50
50
 
51
51
  /**
52
52
  * A pooled worker with its transport and current in-flight request count.
53
53
  */
54
- export interface PooledWorker {
54
+ export interface TransportLease {
55
55
  /** The underlying transport instance */
56
56
  transport: Transport;
57
57
 
@@ -64,7 +64,7 @@ export interface PooledWorker {
64
64
  */
65
65
  interface QueuedWaiter {
66
66
  /** Resolve function to fulfill the promise with a worker */
67
- resolve: (worker: PooledWorker) => void;
67
+ resolve: (worker: TransportLease) => void;
68
68
 
69
69
  /** Reject function to reject the promise with an error */
70
70
  reject: (error: Error) => void;
@@ -88,8 +88,8 @@ interface QueuedWaiter {
88
88
  *
89
89
  * @example
90
90
  * ```typescript
91
- * const pool = new WorkerPool({
92
- * createTransport: () => new ProcessIO({ pythonPath: 'python3' }),
91
+ * const pool = new TransportPool({
92
+ * createTransport: () => new SubprocessTransport({ pythonPath: 'python3' }),
93
93
  * maxWorkers: 4,
94
94
  * maxConcurrentPerWorker: 2,
95
95
  * queueTimeoutMs: 5000,
@@ -105,25 +105,25 @@ interface QueuedWaiter {
105
105
  * await pool.dispose();
106
106
  * ```
107
107
  */
108
- export class WorkerPool extends DisposableBase {
108
+ export class TransportPool extends DisposableBase {
109
109
  private readonly options: Omit<
110
- Required<WorkerPoolOptions>,
110
+ Required<TransportPoolOptions>,
111
111
  'onWorkerReady' | 'onReplacementWorkerReady'
112
112
  > & {
113
- onWorkerReady?: (worker: PooledWorker) => Promise<void>;
114
- onReplacementWorkerReady?: (worker: PooledWorker) => Promise<void>;
113
+ onWorkerReady?: (worker: TransportLease) => Promise<void>;
114
+ onReplacementWorkerReady?: (worker: TransportLease) => Promise<void>;
115
115
  };
116
- private readonly workers: PooledWorker[] = [];
116
+ private readonly workers: TransportLease[] = [];
117
117
  private readonly waitQueue: QueuedWaiter[] = [];
118
118
  /** Tracks workers being created to prevent race condition in acquire() */
119
119
  private pendingCreations = 0;
120
120
 
121
121
  /**
122
- * Create a new WorkerPool.
122
+ * Create a new TransportPool.
123
123
  *
124
124
  * @param options - Pool configuration options
125
125
  */
126
- constructor(options: WorkerPoolOptions) {
126
+ constructor(options: TransportPoolOptions) {
127
127
  super();
128
128
 
129
129
  // Validate required options
@@ -216,7 +216,7 @@ export class WorkerPool extends DisposableBase {
216
216
  * @throws BridgeTimeoutError if queue timeout expires
217
217
  * @throws BridgeExecutionError if pool is disposed while waiting
218
218
  */
219
- async acquire(): Promise<PooledWorker> {
219
+ async acquire(): Promise<TransportLease> {
220
220
  // Check for disposed state
221
221
  if (this.isDisposed || this.state === 'disposing') {
222
222
  throw new BridgeExecutionError('Pool has been disposed');
@@ -261,7 +261,7 @@ export class WorkerPool extends DisposableBase {
261
261
  *
262
262
  * @param worker - The worker to release
263
263
  */
264
- release(worker: PooledWorker): void {
264
+ release(worker: TransportLease): void {
265
265
  // Validate the worker belongs to this pool
266
266
  if (!this.workers.includes(worker)) {
267
267
  return;
@@ -288,7 +288,7 @@ export class WorkerPool extends DisposableBase {
288
288
  * });
289
289
  * ```
290
290
  */
291
- async withWorker<T>(fn: (worker: PooledWorker) => Promise<T>): Promise<T> {
291
+ async withWorker<T>(fn: (worker: TransportLease) => Promise<T>): Promise<T> {
292
292
  const worker = await this.acquire();
293
293
  let workerRemoved = false;
294
294
 
@@ -341,7 +341,7 @@ export class WorkerPool extends DisposableBase {
341
341
  * This is called when a worker is detected as dead (crashed, pipe error, etc.).
342
342
  * The worker's transport is disposed in the background.
343
343
  */
344
- private removeWorker(worker: PooledWorker): void {
344
+ private removeWorker(worker: TransportLease): void {
345
345
  const index = this.workers.indexOf(worker);
346
346
  if (index !== -1) {
347
347
  this.workers.splice(index, 1);
@@ -387,7 +387,7 @@ export class WorkerPool extends DisposableBase {
387
387
  /**
388
388
  * Find an available worker with capacity for another request.
389
389
  */
390
- private findAvailableWorker(): PooledWorker | undefined {
390
+ private findAvailableWorker(): TransportLease | undefined {
391
391
  return this.workers.find(w => w.inFlightCount < this.options.maxConcurrentPerWorker);
392
392
  }
393
393
 
@@ -452,7 +452,7 @@ export class WorkerPool extends DisposableBase {
452
452
  this.publishAvailableWorker(worker);
453
453
  }
454
454
 
455
- private publishAvailableWorker(worker: PooledWorker): void {
455
+ private publishAvailableWorker(worker: TransportLease): void {
456
456
  while (
457
457
  this.waitQueue.length > 0 &&
458
458
  worker.inFlightCount < this.options.maxConcurrentPerWorker
@@ -473,13 +473,13 @@ export class WorkerPool extends DisposableBase {
473
473
  * If onWorkerReady is configured, calls it after the transport is initialized.
474
474
  * This is useful for per-worker warmup (importing modules, running setup).
475
475
  */
476
- private async createWorker(onWorkerReady = this.options.onWorkerReady): Promise<PooledWorker> {
476
+ private async createWorker(onWorkerReady = this.options.onWorkerReady): Promise<TransportLease> {
477
477
  const transport = this.options.createTransport();
478
478
 
479
479
  // Initialize the transport
480
480
  await transport.init();
481
481
 
482
- const worker: PooledWorker = {
482
+ const worker: TransportLease = {
483
483
  transport,
484
484
  inFlightCount: 0,
485
485
  };
@@ -512,8 +512,8 @@ export class WorkerPool extends DisposableBase {
512
512
  /**
513
513
  * Wait in queue for a worker to become available.
514
514
  */
515
- private waitForWorker(): Promise<PooledWorker> {
516
- return new Promise<PooledWorker>((resolve, reject) => {
515
+ private waitForWorker(): Promise<TransportLease> {
516
+ return new Promise<TransportLease>((resolve, reject) => {
517
517
  const timer = setTimeout(() => {
518
518
  // Remove this waiter from the queue
519
519
  const index = this.waitQueue.findIndex(w => w.timer === timer);
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * Provides an abstract I/O channel for all bridge communications across
5
5
  * the JS-Python boundary. Concrete implementations handle different runtimes:
6
- * - ProcessIO: Child process with stdio streams (Node.js)
7
- * - HttpIO: HTTP POST requests (remote Python server)
8
- * - PyodideIO: In-memory Pyodide calls (browser/WASM)
6
+ * - SubprocessTransport: Child process with stdio streams (Node.js)
7
+ * - HttpTransport: HTTP POST requests (remote Python server)
8
+ * - PyodideTransport: In-memory Pyodide calls (browser/WASM)
9
9
  *
10
10
  * @see https://github.com/bbopen/tywrap/issues/149
11
11
  */
@@ -16,9 +16,16 @@ import type { Disposable } from './disposable.js';
16
16
  // PROTOCOL CONSTANTS
17
17
  // =============================================================================
18
18
 
19
- /** Protocol identifier for tywrap communication */
19
+ /** Protocol identifier for tywrap communication. Single source of truth for the version. */
20
20
  export const PROTOCOL_ID = 'tywrap/1';
21
21
 
22
+ /**
23
+ * Numeric protocol version negotiated with the Python bridge. Derived from the
24
+ * trailing number of {@link PROTOCOL_ID} so the two cannot drift — bump
25
+ * PROTOCOL_ID alone and this follows.
26
+ */
27
+ export const TYWRAP_PROTOCOL_VERSION = Number.parseInt(PROTOCOL_ID.split('/')[1] ?? '', 10);
28
+
22
29
  // =============================================================================
23
30
  // PROTOCOL TYPES
24
31
  // =============================================================================
@@ -112,13 +119,13 @@ export interface ProtocolResponse {
112
119
  * 4. Call `dispose()` to release resources
113
120
  *
114
121
  * Implementations:
115
- * - ProcessIO: Spawns a Python child process, communicates via stdio
116
- * - HttpIO: Sends HTTP POST requests to a Python server
117
- * - PyodideIO: Calls Pyodide directly in-memory (WASM)
122
+ * - SubprocessTransport: Spawns a Python child process, communicates via stdio
123
+ * - HttpTransport: Sends HTTP POST requests to a Python server
124
+ * - PyodideTransport: Calls Pyodide directly in-memory (WASM)
118
125
  *
119
126
  * @example
120
127
  * ```typescript
121
- * const transport = new ProcessIO({ pythonPath: 'python3' });
128
+ * const transport = new SubprocessTransport({ pythonPath: 'python3' });
122
129
  * await transport.init();
123
130
  *
124
131
  * const response = await transport.send(