sandboxedjs 0.1.32 → 0.1.33

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.
package/dist/index.js CHANGED
@@ -17907,20 +17907,570 @@ def _install():
17907
17907
 
17908
17908
  _install()
17909
17909
  `;
17910
+ var PROCESS_PY = `
17911
+ import io, os, shlex, subprocess, sys
17912
+ import _sbx_host as _host
17913
+ from pyodide.ffi import can_run_sync, run_sync
17914
+
17915
+ _PIPE = subprocess.PIPE
17916
+ _DEVNULL = subprocess.DEVNULL
17917
+ _STDOUT = subprocess.STDOUT
17918
+
17919
+
17920
+ def _argv_for(args, shell):
17921
+ if shell:
17922
+ line = args if isinstance(args, str) else " ".join(str(a) for a in args)
17923
+ return ["sh", "-c", line]
17924
+ if isinstance(args, (str, bytes)):
17925
+ return shlex.split(args if isinstance(args, str) else args.decode())
17926
+ return [str(a) for a in args]
17927
+
17928
+
17929
+ def _require_blocking(what):
17930
+ if not can_run_sync():
17931
+ raise OSError(
17932
+ "cannot " + what + " on this host: WebAssembly stack switching "
17933
+ "(JSPI) is unavailable."
17934
+ )
17935
+
17936
+
17937
+ def _to_bytes_result(value):
17938
+ if value is None:
17939
+ return b""
17940
+ to_bytes = getattr(value, "to_bytes", None)
17941
+ return to_bytes() if to_bytes is not None else bytes(value.to_py())
17942
+
17943
+
17944
+ class _ChildReader(io.RawIOBase):
17945
+ """One of a running child's output streams.
17946
+
17947
+ Reads suspend only for as long as the child takes to produce the next
17948
+ bytes, so \`for line in p.stdout\` follows a child that is still running
17949
+ instead of waiting for it to exit.
17950
+ """
17951
+
17952
+ def __init__(self, child_id, which):
17953
+ self._id = child_id
17954
+ self._which = which
17955
+
17956
+ def readable(self):
17957
+ return True
17958
+
17959
+ def readinto(self, target):
17960
+ want = len(target)
17961
+ if want == 0:
17962
+ return 0
17963
+ _require_blocking("read from a child process")
17964
+ data = _to_bytes_result(run_sync(_host.proc_read(self._id, self._which, want)))
17965
+ target[: len(data)] = data
17966
+ return len(data)
17967
+
17968
+
17969
+ class _ChildWriter(io.RawIOBase):
17970
+ """A running child's standard input."""
17971
+
17972
+ def __init__(self, child_id):
17973
+ self._id = child_id
17974
+
17975
+ def writable(self):
17976
+ return True
17977
+
17978
+ def write(self, data):
17979
+ if isinstance(data, str):
17980
+ text = data
17981
+ else:
17982
+ text = bytes(data).decode("utf-8", "replace")
17983
+ _host.proc_write(self._id, text)
17984
+ return len(data)
17985
+
17986
+ def close(self):
17987
+ if not self.closed:
17988
+ _host.proc_close_stdin(self._id)
17989
+ super().close()
17990
+
17991
+
17992
+ class SbxPopen:
17993
+ """A child process, run through the container's kernel.
17994
+
17995
+ The child is a real, live process: it starts when \`Popen\` is constructed
17996
+ and runs on the host's event loop while Python carries on. The parent only
17997
+ suspends when it actually reads, waits, or communicates \u2014 which is what
17998
+ makes streaming from a long-running child work rather than deadlocking on
17999
+ a single interpreter stack.
18000
+ """
18001
+
18002
+ def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None,
18003
+ stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None,
18004
+ env=None, universal_newlines=None, startupinfo=None, creationflags=0,
18005
+ restore_signals=True, start_new_session=False, pass_fds=(), *,
18006
+ text=None, encoding=None, errors=None, **kwargs):
18007
+ self.args = args
18008
+ self.returncode = None
18009
+ self._text = bool(text or encoding or errors or universal_newlines)
18010
+ self._encoding = encoding or "utf-8"
18011
+ self._errors = errors or "replace"
18012
+ self._merge_err = stderr == _STDOUT
18013
+ self._closed = False
18014
+
18015
+ argv = _argv_for(args, shell)
18016
+ env_map = None if env is None else {str(k): str(v) for k, v in dict(env).items()}
18017
+ self._id = _host.proc_start(
18018
+ argv, None if cwd is None else str(cwd), env_map, self._merge_err
18019
+ )
18020
+ self.pid = int(_host.proc_pid(self._id))
18021
+
18022
+ self.stdin = self._wrap_writer() if stdin == _PIPE else None
18023
+ self.stdout = self._wrap_reader(1) if stdout == _PIPE else None
18024
+ # When merged there is only one stream, and it is stream 1.
18025
+ self.stderr = self._wrap_reader(2) if stderr == _PIPE and not self._merge_err else None
18026
+
18027
+ # Output nobody captured belongs on the parent's own streams, or a
18028
+ # program's diagnostics would vanish rather than being seen.
18029
+ self._drain_out = stdout is None
18030
+ self._drain_err = stderr is None and not self._merge_err
18031
+
18032
+ def _wrap_reader(self, which):
18033
+ raw = io.BufferedReader(_ChildReader(self._id, which))
18034
+ if self._text:
18035
+ return io.TextIOWrapper(raw, encoding=self._encoding, errors=self._errors)
18036
+ return raw
18037
+
18038
+ def _wrap_writer(self):
18039
+ raw = io.BufferedWriter(_ChildWriter(self._id))
18040
+ if self._text:
18041
+ return io.TextIOWrapper(raw, encoding=self._encoding, errors=self._errors)
18042
+ return raw
18043
+
18044
+ def _read_all(self, which):
18045
+ _require_blocking("read from a child process")
18046
+ parts = []
18047
+ while True:
18048
+ chunk = _to_bytes_result(run_sync(_host.proc_read(self._id, which, 65536)))
18049
+ if not chunk:
18050
+ break
18051
+ parts.append(chunk)
18052
+ return b"".join(parts)
18053
+
18054
+ def _decode(self, raw):
18055
+ return raw.decode(self._encoding, self._errors) if self._text else raw
18056
+
18057
+ def communicate(self, input=None, timeout=None):
18058
+ if input is not None and self.stdin is not None:
18059
+ if isinstance(input, bytes):
18060
+ input = input.decode(self._encoding, "replace")
18061
+ self.stdin.write(input)
18062
+ if self.stdin is not None:
18063
+ try:
18064
+ self.stdin.close()
18065
+ except Exception:
18066
+ pass
18067
+
18068
+ out = self.stdout.read() if self.stdout is not None else None
18069
+ err = self.stderr.read() if self.stderr is not None else None
18070
+ self.wait()
18071
+ self._flush_uncaptured()
18072
+ return out, err
18073
+
18074
+ def _flush_uncaptured(self):
18075
+ if self._drain_out:
18076
+ text = self._decode_raw(self._read_all(1))
18077
+ if text:
18078
+ sys.stdout.write(text)
18079
+ if self._drain_err:
18080
+ text = self._decode_raw(self._read_all(2))
18081
+ if text:
18082
+ sys.stderr.write(text)
18083
+ self._drain_out = False
18084
+ self._drain_err = False
18085
+
18086
+ def _decode_raw(self, raw):
18087
+ return raw.decode(self._encoding, "replace")
18088
+
18089
+ def poll(self):
18090
+ code = _host.proc_poll(self._id)
18091
+ if code is not None:
18092
+ self.returncode = int(code)
18093
+ return self.returncode
18094
+
18095
+ def wait(self, timeout=None):
18096
+ _require_blocking("wait for a child process")
18097
+ self.returncode = int(run_sync(_host.proc_wait(self._id)))
18098
+ return self.returncode
18099
+
18100
+ def kill(self):
18101
+ self.send_signal("SIGKILL")
18102
+
18103
+ def terminate(self):
18104
+ self.send_signal("SIGTERM")
18105
+
18106
+ def send_signal(self, sig):
18107
+ _host.proc_kill(self._id, sig if isinstance(sig, str) else "SIGTERM")
18108
+
18109
+ def __del__(self):
18110
+ try:
18111
+ _host.proc_release(self._id)
18112
+ except Exception:
18113
+ pass
18114
+
18115
+ def __enter__(self):
18116
+ return self
18117
+
18118
+ def __exit__(self, *exc):
18119
+ if self.stdin is not None:
18120
+ try:
18121
+ self.stdin.close()
18122
+ except Exception:
18123
+ pass
18124
+ self.wait()
18125
+ self._flush_uncaptured()
18126
+ for stream in (self.stdout, self.stderr):
18127
+ if stream is not None:
18128
+ try:
18129
+ stream.close()
18130
+ except Exception:
18131
+ pass
18132
+ # The host holds the process and its pipes until it is told the child
18133
+ # is finished with; a loop spawning children would otherwise keep every
18134
+ # one of them alive. Safe here only because the child has been waited
18135
+ # for and everything anyone wanted has been read.
18136
+ _host.proc_release(self._id)
18137
+ return False
18138
+
18139
+
18140
+ def _system(command):
18141
+ with SbxPopen(command, shell=True) as child:
18142
+ pass
18143
+ # os.system returns a wait status, not an exit code.
18144
+ return (child.returncode or 0) << 8
18145
+
18146
+
18147
+ def _popen(command, mode="r", buffering=-1):
18148
+ if "w" in mode:
18149
+ raise OSError("os.popen with mode 'w' is not supported in this container")
18150
+ child = SbxPopen(command, shell=True, stdout=_PIPE, text=True)
18151
+ stream = child.stdout
18152
+ inner = stream.close
18153
+
18154
+ def close():
18155
+ inner()
18156
+ code = child.wait()
18157
+ return None if code == 0 else code << 8
18158
+
18159
+ stream.close = close
18160
+ return stream
18161
+
18162
+
18163
+ def _install_processes():
18164
+ subprocess.Popen = SbxPopen
18165
+ os.system = _system
18166
+ os.popen = _popen
18167
+
18168
+
18169
+ _install_processes()
18170
+ `;
18171
+ var NETWORK_PY = `
18172
+ import builtins, email.message, io, sys, urllib.error, urllib.request, urllib.response
18173
+ import _sbx_host as _host
18174
+ from pyodide.ffi import can_run_sync, run_sync
18175
+
18176
+
18177
+ def _fetch(request):
18178
+ if not can_run_sync():
18179
+ raise urllib.error.URLError(
18180
+ "cannot make a request on this host: WebAssembly stack switching "
18181
+ "(JSPI) is unavailable."
18182
+ )
18183
+ body = request.data
18184
+ if isinstance(body, str):
18185
+ body = body.encode()
18186
+ try:
18187
+ result = run_sync(
18188
+ _host.http(
18189
+ request.full_url,
18190
+ request.get_method(),
18191
+ [[k, v] for k, v in request.header_items()],
18192
+ body,
18193
+ )
18194
+ )
18195
+ except Exception as error:
18196
+ raise urllib.error.URLError(str(error)) from None
18197
+
18198
+ headers = email.message.Message()
18199
+ for pair in result.headers.to_py():
18200
+ headers[str(pair[0])] = str(pair[1])
18201
+ payload = result.body.to_bytes()
18202
+ response = urllib.response.addinfourl(
18203
+ io.BytesIO(payload), headers, str(result.url), int(result.status)
18204
+ )
18205
+ response.msg = str(result.statusText)
18206
+ return response
18207
+
18208
+
18209
+ class _SbxHTTPHandler(urllib.request.HTTPHandler):
18210
+ """Both schemes, from one handler.
18211
+
18212
+ Pyodide builds urllib without \`ssl\`, so \`HTTPSHandler\` does not exist to
18213
+ subclass \u2014 and https is the scheme most callers actually want. Serving
18214
+ both from a subclass of the one handler that does exist keeps
18215
+ \`build_opener\` treating this as a replacement rather than stacking it
18216
+ alongside the original.
18217
+ """
18218
+
18219
+ def http_open(self, request):
18220
+ return _fetch(request)
18221
+
18222
+ def https_open(self, request):
18223
+ return _fetch(request)
18224
+
18225
+ https_request = urllib.request.HTTPHandler.do_request_
18226
+
18227
+
18228
+ def _raw_fetch(url, method, headers, body):
18229
+ """One request, through the container's network path."""
18230
+ if not can_run_sync():
18231
+ raise urllib.error.URLError(
18232
+ "cannot make a request on this host: WebAssembly stack switching "
18233
+ "(JSPI) is unavailable."
18234
+ )
18235
+ if isinstance(body, str):
18236
+ body = body.encode()
18237
+ result = run_sync(
18238
+ _host.http(url, method, [[str(k), str(v)] for k, v in dict(headers).items()], body)
18239
+ )
18240
+ return {
18241
+ "status": int(result.status),
18242
+ "reason": str(result.statusText),
18243
+ "headers": [(str(p[0]), str(p[1])) for p in result.headers.to_py()],
18244
+ "body": result.body.to_bytes(),
18245
+ "url": str(result.url),
18246
+ }
18247
+
18248
+
18249
+ # \u2500\u2500 Routing third-party HTTP stacks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18250
+ #
18251
+ # A library that brings its own transport does not go through urllib, and in
18252
+ # Pyodide several of them reach JavaScript's fetch directly \u2014 which leaves the
18253
+ # container's network policy behind entirely. They cannot all be patched at
18254
+ # boot either, because pip installs them later.
18255
+ #
18256
+ # So: adapters are registered by module name and applied the moment that module
18257
+ # is first imported, whenever that happens. Supporting another stack is a small
18258
+ # function registered here, not a change to the machinery.
18259
+
18260
+ _ADAPTERS = {}
18261
+
18262
+
18263
+ def _register_adapter(name):
18264
+ def decorate(fn):
18265
+ _ADAPTERS[name] = fn
18266
+ return fn
18267
+
18268
+ return decorate
18269
+
18270
+
18271
+ def _apply_adapter(name):
18272
+ fn = _ADAPTERS.pop(name, None)
18273
+ if fn is None:
18274
+ return
18275
+ try:
18276
+ fn()
18277
+ except Exception:
18278
+ # A stack we cannot adapt must not stop the import that triggered it.
18279
+ pass
18280
+
18281
+
18282
+ def _install_import_hook():
18283
+ real_import = builtins.__import__
18284
+
18285
+ def hooked(name, globals=None, locals=None, fromlist=(), level=0):
18286
+ module = real_import(name, globals, locals, fromlist, level)
18287
+ root = name.split(".")[0] if level == 0 else None
18288
+ if root in _ADAPTERS:
18289
+ _apply_adapter(root)
18290
+ return module
18291
+
18292
+ builtins.__import__ = hooked
18293
+
18294
+
18295
+ @_register_adapter("requests")
18296
+ def _adapt_requests():
18297
+ """Replace the transport, not the API.
18298
+
18299
+ \`HTTPAdapter.send\` is the single seam every requests call passes through,
18300
+ below sessions, redirects, cookies and retries and above the urllib3
18301
+ transport that would otherwise reach the network on its own. Replacing it
18302
+ leaves everything callers actually use intact.
18303
+ """
18304
+ import requests
18305
+ from requests.adapters import HTTPAdapter
18306
+ from requests.structures import CaseInsensitiveDict
18307
+
18308
+ native_send = HTTPAdapter.send
18309
+
18310
+ def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
18311
+ if not can_run_sync():
18312
+ # Without stack switching this transport cannot run at all. Falling
18313
+ # back to the library's own is better than breaking requests on
18314
+ # such a host \u2014 but the container's network policy is not the part
18315
+ # that degrades, so a forbidden host is still refused.
18316
+ if not _host.policy_allows(request.url):
18317
+ raise requests.exceptions.ConnectionError(
18318
+ "outbound network access is disabled for this container "
18319
+ "(enable with network: { allowOutbound: true })"
18320
+ )
18321
+ return native_send(self, request, stream, timeout, verify, cert, proxies)
18322
+ try:
18323
+ result = _raw_fetch(request.url, request.method, request.headers, request.body)
18324
+ except Exception as error:
18325
+ raise requests.exceptions.ConnectionError(str(error)) from None
18326
+ response = requests.Response()
18327
+ response.status_code = result["status"]
18328
+ response.reason = result["reason"]
18329
+ response.headers = CaseInsensitiveDict(result["headers"])
18330
+ response.url = result["url"]
18331
+ response.request = request
18332
+ response.raw = io.BytesIO(result["body"])
18333
+ response.encoding = requests.utils.get_encoding_from_headers(response.headers)
18334
+ return response
18335
+
18336
+ HTTPAdapter.send = send
18337
+
18338
+
18339
+ def _install_network():
18340
+ urllib.request.HTTPHandler = _SbxHTTPHandler
18341
+ urllib.request.HTTPSHandler = _SbxHTTPHandler
18342
+ urllib.request.install_opener(urllib.request.build_opener(_SbxHTTPHandler))
18343
+ _install_import_hook()
18344
+ for already_imported in [n for n in _ADAPTERS if n in sys.modules]:
18345
+ _apply_adapter(already_imported)
18346
+
18347
+
18348
+ _install_network()
18349
+ `;
18350
+ async function httpForPython(slot, url, method, headers, body) {
18351
+ const current = slot.current;
18352
+ if (!current) throw new Error("no program is bound");
18353
+ const result = await performRequest(current.ctx, new URL(url), {
18354
+ method,
18355
+ headers: Object.fromEntries(headers),
18356
+ ...body ? { body } : {}
18357
+ });
18358
+ return {
18359
+ status: result.status,
18360
+ statusText: result.statusText,
18361
+ headers: Object.entries(result.headers),
18362
+ body: result.body,
18363
+ url: result.url
18364
+ };
18365
+ }
18366
+ async function resuming(py, slot, work) {
18367
+ const parent = slot.current;
18368
+ try {
18369
+ return await work();
18370
+ } finally {
18371
+ if (parent && slot.current !== parent) bindProgram(py, parent);
18372
+ }
18373
+ }
17910
18374
  function installSyscallBridge(py) {
17911
- const slot = py.__sbxStdin ??= { active: null };
18375
+ const slot = py.__sbxSlot ??= { current: null };
18376
+ const children = /* @__PURE__ */ new Map();
18377
+ let lastChildId = 0;
17912
18378
  py.registerJsModule("_sbx_host", {
17913
18379
  /* Not `?.` and `??`: `buffered` returns undefined to mean "you will have
17914
18380
  * to wait", and a nullish default would quietly turn that into end-of-file —
17915
18381
  * which is exactly the silent EOF this bridge exists to remove. */
17916
- buffered: (size) => slot.active ? slot.active.buffered(size) : EMPTY,
17917
- read: (size) => slot.active ? slot.active.read(size) : Promise.resolve(EMPTY),
17918
- isatty: () => slot.active?.isatty() ?? false
18382
+ buffered: (size) => slot.current ? slot.current.stdin.buffered(size) : EMPTY,
18383
+ read: (size) => slot.current ? slot.current.stdin.read(size) : Promise.resolve(EMPTY),
18384
+ isatty: () => slot.current?.stdin.isatty() ?? false,
18385
+ proc_start: (argv, cwd, env2, merge) => {
18386
+ const current = slot.current;
18387
+ if (!current) throw new Error("no program is bound");
18388
+ const { ctx } = current;
18389
+ const stdin = new Pipe();
18390
+ stdin.interactive = true;
18391
+ const stdout = new Pipe();
18392
+ const stderr = merge ? stdout : new Pipe();
18393
+ const proc = ctx.kernel.spawn(argv, {
18394
+ cwd: cwd ?? ctx.cwd,
18395
+ env: env2 ?? ctx.env,
18396
+ cred: ctx.cred,
18397
+ stdin,
18398
+ stdout,
18399
+ stderr
18400
+ });
18401
+ void proc.wait().then(() => {
18402
+ stdout.end();
18403
+ if (stderr !== stdout) stderr.end();
18404
+ });
18405
+ const id = ++lastChildId;
18406
+ children.set(id, { proc, stdin, stdout, stderr });
18407
+ return id;
18408
+ },
18409
+ proc_read: (id, which2, size) => {
18410
+ const child = children.get(id);
18411
+ if (!child) return Promise.resolve(EMPTY);
18412
+ const pipe = which2 === 2 ? child.stderr : child.stdout;
18413
+ return resuming(py, slot, async () => await pipe.read(size) ?? EMPTY);
18414
+ },
18415
+ proc_write: (id, text2) => {
18416
+ children.get(id)?.stdin.write(text2);
18417
+ },
18418
+ proc_close_stdin: (id) => {
18419
+ children.get(id)?.stdin.end();
18420
+ },
18421
+ /* Non-blocking on purpose: `poll()` must be able to say "still running". */
18422
+ proc_poll: (id) => children.get(id)?.proc.exitCode ?? void 0,
18423
+ proc_pid: (id) => children.get(id)?.proc.pid ?? 0,
18424
+ proc_wait: (id) => {
18425
+ const child = children.get(id);
18426
+ if (!child) return Promise.resolve(0);
18427
+ return resuming(py, slot, () => child.proc.wait());
18428
+ },
18429
+ proc_kill: (id, signal) => {
18430
+ const child = children.get(id);
18431
+ if (!child) return;
18432
+ const current = slot.current;
18433
+ current?.ctx.kernel.procs.signal(child.proc.pid, signal);
18434
+ },
18435
+ proc_release: (id) => {
18436
+ children.delete(id);
18437
+ },
18438
+ http: (url, method, headers, body) => resuming(py, slot, () => httpForPython(slot, url, method, headers, body)),
18439
+ /* So Python can enforce the container's policy even on a host where it
18440
+ * cannot route the request itself. */
18441
+ policy_allows: (url) => {
18442
+ const current = slot.current;
18443
+ if (!current) return false;
18444
+ const net = current.ctx.kernel.net;
18445
+ try {
18446
+ return net.isLocal(new URL(url).hostname) || net.outboundAllowed(url);
18447
+ } catch {
18448
+ return false;
18449
+ }
18450
+ }
17919
18451
  });
17920
18452
  py.runPython(BRIDGE_PY);
18453
+ py.runPython(PROCESS_PY);
18454
+ py.runPython(NETWORK_PY);
17921
18455
  }
17922
- function bindStdin(py, host2) {
17923
- py.__sbxStdin.active = host2;
18456
+ function bindProgram(py, binding) {
18457
+ py.__sbxSlot.current = binding;
18458
+ const { ctx, stdin } = binding;
18459
+ const decoder8 = new TextDecoder();
18460
+ py.setStdout({
18461
+ write: (buffer) => (ctx.write(decoder8.decode(buffer)), buffer.length)
18462
+ });
18463
+ py.setStderr({
18464
+ write: (buffer) => (ctx.stderr.write(decoder8.decode(buffer)), buffer.length)
18465
+ });
18466
+ py.setStdin({
18467
+ read: (buffer) => {
18468
+ const ready = stdin.buffered(buffer.length);
18469
+ if (!ready || ready.length === 0) return 0;
18470
+ buffer.set(ready);
18471
+ return ready.length;
18472
+ }
18473
+ });
17924
18474
  }
17925
18475
 
17926
18476
  // src/runtime/cpython.ts
@@ -18111,30 +18661,9 @@ async function runCPythonProgram(ctx, source, argv, scriptDir = null) {
18111
18661
  });
18112
18662
  } catch {
18113
18663
  }
18114
- const decoder8 = new TextDecoder();
18115
- py.setStdout({
18116
- write: (buffer) => {
18117
- ctx.write(decoder8.decode(buffer));
18118
- return buffer.length;
18119
- }
18120
- });
18121
- py.setStderr({
18122
- write: (buffer) => {
18123
- ctx.stderr.write(decoder8.decode(buffer));
18124
- return buffer.length;
18125
- }
18126
- });
18127
18664
  const stdinHost = createStdinHost(ctx);
18128
18665
  await stdinHost.prime();
18129
- bindStdin(py, stdinHost);
18130
- py.setStdin({
18131
- read: (buffer) => {
18132
- const ready = stdinHost.buffered(buffer.length);
18133
- if (!ready || ready.length === 0) return 0;
18134
- buffer.set(ready);
18135
- return ready.length;
18136
- }
18137
- });
18666
+ bindProgram(py, { ctx, stdin: stdinHost });
18138
18667
  try {
18139
18668
  bootstrap(py, ctx, argv, scriptDir);
18140
18669
  } catch (error) {
@@ -18173,9 +18702,7 @@ async function runCPythonRepl(ctx) {
18173
18702
  }
18174
18703
  mountContainerDirs(py, ctx);
18175
18704
  bootstrap(py, ctx, [""], null);
18176
- const decoder8 = new TextDecoder();
18177
- py.setStdout({ write: (data) => (ctx.write(decoder8.decode(data)), data.length) });
18178
- py.setStderr({ write: (data) => (ctx.stderr.write(decoder8.decode(data)), data.length) });
18705
+ bindProgram(py, { ctx, stdin: createStdinHost(ctx) });
18179
18706
  ctx.line(`Python ${String(py.runPython("import sys; sys.version.split()[0]"))} (Pyodide)`);
18180
18707
  ctx.line('Type "help()" for more information.');
18181
18708
  let source = "";
@@ -18235,6 +18762,13 @@ var micropip = defineCommand({
18235
18762
  ctx.stderr.write("pip: no packages specified\n");
18236
18763
  return 1;
18237
18764
  }
18765
+ const index = "https://pypi.org";
18766
+ if (!ctx.kernel.net.outboundAllowed(index)) {
18767
+ ctx.stderr.write(
18768
+ "pip: outbound network access is disabled for this container (enable with network: { allowOutbound: true })\n"
18769
+ );
18770
+ return 1;
18771
+ }
18238
18772
  let py;
18239
18773
  try {
18240
18774
  py = await interpreterFor(ctx);