@node-ctypes/python 0.3.1 → 0.4.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.
package/dist/runtime.js CHANGED
@@ -1,3 +1,55 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
1
53
  // Copyright (c) 2026 Damiano Mazzella. MIT License (see LICENSE).
2
54
  import { inspect } from "node:util";
3
55
  import { addressof, byref, memmove, array, EXTERNAL_BUFFERS, c_char_p, c_void_p, c_int, c_ssize_t, c_uint8, threadSafeCallback } from "node-ctypes";
@@ -7,7 +59,7 @@ import { PythonScheduler } from "./scheduler.js";
7
59
  import { PythonPlatform, lineWriter } from "./platform.js";
8
60
  import { PythonConversions } from "./conversions.js";
9
61
  import { PythonBuffers } from "./buffers.js";
10
- import { PythonExecutor } from "./executor.js";
62
+ import { PythonExecutor, nextCompletionToken } from "./executor.js";
11
63
  import { NativeObjects, nativeSlot } from "./objects.js";
12
64
  import { probeInterpreter, loadLibrary } from "./interpreter.js";
13
65
  import { claimHost, releaseHost } from "./host.js";
@@ -36,6 +88,9 @@ function isThenable(value) {
36
88
  const EVENT_DONE = 0;
37
89
  const EVENT_CALL = 1;
38
90
  const EVENT_CANCEL = 2;
91
+ const INT64_MIN = -(1n << 63n);
92
+ const INT64_MAX = (1n << 63n) - 1n;
93
+ const UTF8_SCRATCH_SIZE = 4096;
39
94
  const isIndex = (prop) => /^-?(0|[1-9]\d*)$/.test(prop);
40
95
  // Function.prototype members used by JavaScript code on callables (handler.apply(this, args), fn.bind()).
41
96
  const FUNCTION_MEMBERS = new Set(["apply", "call", "bind", "length", "name"]);
@@ -113,7 +168,15 @@ export class Python {
113
168
  #keep = new WeakMap(); // ArrayBuffer of Python memory → holder that pins it
114
169
  #busy = new Int32Array(1); // 1 while the main thread runs Python code (read by Python threads)
115
170
  #proxies = 0; // live PyObject proxies
116
- #nextToken = 1;
171
+ #lastAwaitToken = 0;
172
+ // Reusable out-slots for non-reentrant C-API reads under the GIL (#fromPy).
173
+ #overflowOut = new c_int();
174
+ #overflowOutRef = byref(this.#overflowOut);
175
+ #sizeOut = new c_ssize_t();
176
+ #sizeOutRef = byref(this.#sizeOut);
177
+ #ptrOut = new c_void_p();
178
+ #ptrOutRef = byref(this.#ptrOut);
179
+ #utf8Scratch = Buffer.allocUnsafe(UTF8_SCRATCH_SIZE);
117
180
  #channel = null; // threadSafeCallback woken by Python threads (see #openChannel)
118
181
  #main;
119
182
  #builtins;
@@ -307,94 +370,105 @@ export class Python {
307
370
  process.once("beforeExit", this.#beforeExitHandler);
308
371
  }
309
372
  #setup(info, streams) {
310
- const api = this.#api;
311
- this.#registry = new FinalizationRegistry((state) => {
312
- if (!state.ptr || this.#finalized || this.#nativeFinalizing || this.#state === "closing")
313
- return;
314
- this.#proxies--;
315
- this.#releasedProxies.push(state.ptr);
316
- state.ptr = null;
317
- this.#scheduleDrain();
318
- });
319
- this.#handler = this.#proxyHandler();
320
- this.#trampoline = nativeSlot(api, (self, args, kw) => this.#withGIL(() => {
321
- const result = this.#callJS(self, args, kw);
322
- const error = api.PyErr_GetRaisedException();
323
- if (error)
324
- this.#trampoline.setNativeError(error);
325
- return result;
326
- }), c_void_p, [c_void_p, c_void_p, c_void_p]);
327
- this.#main = this.#import("__main__");
328
- this.#builtins = this.#import("builtins");
329
- this.#conversions = new PythonConversions(this.#builtins, (name) => this.#import(name));
330
- this.#buffers = new PythonBuffers(this.#builtins, (name) => this.#import(name), (message) => {
331
- api.PyErr_SetString(this.#pointer(this.#builtins.BufferError), message);
332
- throw this.#fetchError();
333
- });
334
- this.#bootstrap = new PythonBootstrap(this.#builtins, (name) => this.#import(name));
335
- const adapters = this.#bootstrap.module;
336
- this.#mainThread = this.#bootstrap.mainThread;
337
- this.#jsProxyType = this.#pointer(this.#bootstrap.objectType);
338
- this.#functionType = this.#typeOf(this.#pointer(this.#bootstrap.wrap));
339
- this.#javascriptCode = this.#pointer(this.#bootstrap.javascriptCode);
340
- this.#scheduler = new PythonScheduler(this.#builtins, (name) => this.#import(name), adapters, addressof(Buffer.from(this.#busy.buffer)), (exception) => {
341
- api.PyErr_SetRaisedException(this.#toPy(exception));
342
- throw this.#fetchError();
343
- }, this.#synchronousCallbacks);
344
- this.#platform = new PythonPlatform(this.#builtins, (name) => this.#import(name), adapters);
345
- const javascript_object = (op, object, ...args) => this.#jsOp(op, object, ...args);
346
- adapters._op = javascript_object;
347
- this.#openChannel();
348
- // The environment of the probed interpreter (virtual environment included).
349
- const sys = this.#import("sys");
350
- sys.modules["_node_ctypes"] = adapters;
351
- let notify;
352
- if (this.#synchronousCallbacks) {
353
- const registration = adapters.register_native_dispatcher(() => this.#nativeObjects?.drain());
354
- notify = BigInt(registration[1]);
355
- registration[Symbol.dispose]();
356
- }
357
- this.#nativeObjects = this.#using(api.PyObject_GetAttrString(this.#pointer(adapters), "_op"), (operation) => new NativeObjects(api, this.#check(this.#jsProxyType), {
358
- withGIL: (fn) => this.#withGIL(fn),
359
- check: (ptr) => this.#check(ptr),
360
- fromPython: (ptr) => this.#fromPy(ptr, false, undefined, true),
361
- toPython: (value) => this.#toPy(value),
362
- operate: (op, self, args, kwargs) => {
363
- const values = args.map((arg) => this.#fromPy(arg, false, undefined, true));
364
- if (kwargs && api.PyDict_Size(kwargs) > 0)
365
- values.push(this.#fromPy(kwargs, true, undefined, true));
366
- return this.#jsOp(op, this.#fromPy(self, false), ...values);
367
- },
368
- raise: (error) => this.#raise(error),
369
- }, {
370
- asyncIterator: this.#pointer(adapters._JsAsyncIterator),
371
- callLater: this.#pointer(adapters._call_later),
372
- operation: this.#check(operation),
373
- wrap: this.#pointer(this.#bootstrap.wrap),
374
- }, notify));
375
- this.#status(api.PyObject_SetAttrString(this.#pointer(adapters), "NativeJsProxy", this.#nativeObjects.type));
376
- sys.path = ["", ...info.path];
377
- sys.executable = info.executable;
378
- sys.argv = [process.argv[1] ?? ""];
379
- // Every Python call acquires the GIL on the Node.js thread: CPU-bound
380
- // Python threads can stall the event loop for several switch intervals.
381
- sys.setswitchinterval(this.#switchInterval / 1000);
382
- // Python reads stdin through a buffer: what it reads is lost for Node.js.
383
- if (!streams.stdin)
384
- sys.stdin = null;
385
- // Python writes to the file descriptors directly, Node.js through a queue
386
- // when they are pipes (macOS) or terminals (Windows): "node" keeps the order.
387
- for (const name of ["stdout", "stderr"]) {
388
- const target = streams[name];
389
- if (target === "inherit")
390
- continue;
391
- if (target === "console") {
392
- const lines = lineWriter(name === "stdout" ? (line) => console.log(line) : (line) => console.error(line));
393
- this.#platform.redirect(name, lines.write, lines.flush);
394
- continue;
373
+ const env_1 = { stack: [], error: void 0, hasError: false };
374
+ try {
375
+ const api = this.#api;
376
+ this.#registry = new FinalizationRegistry((state) => {
377
+ if (!state.ptr || this.#finalized || this.#nativeFinalizing || this.#state === "closing")
378
+ return;
379
+ this.#proxies--;
380
+ this.#releasedProxies.push(state.ptr);
381
+ state.ptr = null;
382
+ this.#scheduleDrain();
383
+ });
384
+ this.#handler = this.#proxyHandler();
385
+ this.#trampoline = nativeSlot(api, (self, args, kw) => this.#withGIL(() => {
386
+ const result = this.#callJS(self, args, kw);
387
+ const error = api.PyErr_GetRaisedException();
388
+ if (error)
389
+ this.#trampoline.setNativeError(error);
390
+ return result;
391
+ }), c_void_p, [c_void_p, c_void_p, c_void_p]);
392
+ this.#main = this.#import("__main__");
393
+ this.#builtins = this.#import("builtins");
394
+ this.#conversions = new PythonConversions(this.#builtins, (name) => this.#import(name));
395
+ this.#buffers = new PythonBuffers(this.#builtins, (name) => this.#import(name), (message) => {
396
+ api.PyErr_SetString(this.#pointer(this.#builtins.BufferError), message);
397
+ throw this.#fetchError();
398
+ });
399
+ this.#bootstrap = new PythonBootstrap(this.#builtins, (name) => this.#import(name));
400
+ const adapters = this.#bootstrap.module;
401
+ this.#mainThread = this.#bootstrap.mainThread;
402
+ this.#jsProxyType = this.#pointer(this.#bootstrap.objectType);
403
+ this.#functionType = this.#typeOf(this.#pointer(this.#bootstrap.wrap));
404
+ this.#javascriptCode = this.#pointer(this.#bootstrap.javascriptCode);
405
+ this.#scheduler = new PythonScheduler(this.#builtins, (name) => this.#import(name), adapters, addressof(Buffer.from(this.#busy.buffer)), (exception) => {
406
+ api.PyErr_SetRaisedException(this.#toPy(exception));
407
+ throw this.#fetchError();
408
+ }, this.#synchronousCallbacks);
409
+ this.#platform = new PythonPlatform(this.#builtins, (name) => this.#import(name), adapters);
410
+ const javascript_object = (op, object, ...args) => this.#jsOp(op, object, ...args);
411
+ adapters._op = javascript_object;
412
+ this.#openChannel();
413
+ // The environment of the probed interpreter (virtual environment included).
414
+ const sys = __addDisposableResource(env_1, this.#import("sys"), false);
415
+ const sysModules = __addDisposableResource(env_1, sys.modules, false);
416
+ sysModules["_node_ctypes"] = adapters;
417
+ let notify;
418
+ if (this.#synchronousCallbacks) {
419
+ const registration = adapters.register_native_dispatcher(() => this.#nativeObjects?.drain());
420
+ notify = BigInt(registration[1]);
421
+ registration[Symbol.dispose]();
395
422
  }
396
- const write = target === "node" ? (text) => void process[name].write(text) : (text) => void target(text);
397
- this.#platform.redirect(name, write);
423
+ this.#nativeObjects = this.#using(api.PyObject_GetAttrString(this.#pointer(adapters), "_op"), (operation) => new NativeObjects(api, this.#check(this.#jsProxyType), {
424
+ withGIL: (fn) => this.#withGIL(fn),
425
+ check: (ptr) => this.#check(ptr),
426
+ fromPython: (ptr) => this.#fromPy(ptr, false, undefined, true),
427
+ toPython: (value) => this.#toPy(value),
428
+ operate: (op, self, args, kwargs) => {
429
+ const values = args.map((arg) => this.#fromPy(arg, false, undefined, true));
430
+ if (kwargs && api.PyDict_Size(kwargs) > 0)
431
+ values.push(this.#fromPy(kwargs, true, undefined, true));
432
+ return this.#jsOp(op, this.#fromPy(self, false), ...values);
433
+ },
434
+ raise: (error) => this.#raise(error),
435
+ }, {
436
+ asyncIterator: this.#pointer(adapters._JsAsyncIterator),
437
+ callLater: this.#pointer(adapters._call_later),
438
+ operation: this.#check(operation),
439
+ wrap: this.#pointer(this.#bootstrap.wrap),
440
+ }, notify));
441
+ this.#status(api.PyObject_SetAttrString(this.#pointer(adapters), "NativeJsProxy", this.#nativeObjects.type));
442
+ sys.path = ["", ...info.path];
443
+ sys.executable = info.executable;
444
+ sys.argv = [process.argv[1] ?? ""];
445
+ // Every Python call acquires the GIL on the Node.js thread: CPU-bound
446
+ // Python threads can stall the event loop for several switch intervals.
447
+ sys.setswitchinterval(this.#switchInterval / 1000);
448
+ // Python reads stdin through a buffer: what it reads is lost for Node.js.
449
+ if (!streams.stdin)
450
+ sys.stdin = null;
451
+ // Python writes to the file descriptors directly, Node.js through a queue
452
+ // when they are pipes (macOS) or terminals (Windows): "node" keeps the order.
453
+ for (const name of ["stdout", "stderr"]) {
454
+ const target = streams[name];
455
+ if (target === "inherit")
456
+ continue;
457
+ if (target === "console") {
458
+ const lines = lineWriter(name === "stdout" ? (line) => console.log(line) : (line) => console.error(line));
459
+ this.#platform.redirect(name, lines.write, lines.flush);
460
+ continue;
461
+ }
462
+ const write = target === "node" ? (text) => void process[name].write(text) : (text) => void target(text);
463
+ this.#platform.redirect(name, write);
464
+ }
465
+ }
466
+ catch (e_1) {
467
+ env_1.error = e_1;
468
+ env_1.hasError = true;
469
+ }
470
+ finally {
471
+ __disposeResources(env_1);
398
472
  }
399
473
  }
400
474
  // ── Public API ────────────────────────────────────────────────────
@@ -448,38 +522,59 @@ export class Python {
448
522
  */
449
523
  module(name, members) {
450
524
  return this.#withGIL(() => {
451
- const types = this.#import("types");
452
- const modules = this.#import("sys").modules;
453
- const module = types.ModuleType(name);
454
- for (const [key, value] of Object.entries(members))
455
- module[key] = value;
456
- modules.__setitem__(name, module);
457
- // Link the module to its parent package, creating the missing ones.
458
- for (let child = module, childName = name; childName.includes(".");) {
459
- const dot = childName.lastIndexOf(".");
460
- const parentName = childName.slice(0, dot);
461
- let parent = modules.get(parentName);
462
- let created = false;
463
- if (parent === null) {
464
- try {
465
- parent = this.#import(parentName); // an existing package (json for json.extra)
466
- }
467
- catch (error) {
468
- const missing = error instanceof PythonError && error.type === "ModuleNotFoundError" ? error.exception.name : null;
469
- if (!(missing === parentName || parentName.startsWith(`${missing}.`)))
470
- throw error;
471
- parent = types.ModuleType(parentName);
472
- parent.__path__ = []; // a package
473
- modules.__setitem__(parentName, parent);
474
- created = true;
525
+ const env_2 = { stack: [], error: void 0, hasError: false };
526
+ try {
527
+ const types = __addDisposableResource(env_2, this.#import("types"), false);
528
+ const sys = __addDisposableResource(env_2, this.#import("sys"), false);
529
+ const modules = __addDisposableResource(env_2, sys.modules, false);
530
+ const module = __addDisposableResource(env_2, types.ModuleType(name), false);
531
+ for (const [key, value] of Object.entries(members))
532
+ module[key] = value;
533
+ modules.__setitem__(name, module);
534
+ // Link the module to its parent package, creating the missing ones.
535
+ const temporaries = [];
536
+ try {
537
+ for (let child = module, childName = name; childName.includes(".");) {
538
+ const dot = childName.lastIndexOf(".");
539
+ const parentName = childName.slice(0, dot);
540
+ let parent = modules.get(parentName);
541
+ let created = false;
542
+ if (parent === null) {
543
+ try {
544
+ parent = this.#import(parentName); // an existing package (json for json.extra)
545
+ }
546
+ catch (error) {
547
+ const missing = error instanceof PythonError && error.type === "ModuleNotFoundError" ? error.exception.name : null;
548
+ if (!(missing === parentName || parentName.startsWith(`${missing}.`)))
549
+ throw error;
550
+ if (error instanceof PythonError)
551
+ error.exception[Symbol.dispose]();
552
+ parent = types.ModuleType(parentName);
553
+ parent.__path__ = []; // a package
554
+ modules.__setitem__(parentName, parent);
555
+ created = true;
556
+ }
557
+ }
558
+ temporaries.push(parent);
559
+ this.#builtins.setattr(parent, childName.slice(dot + 1), child);
560
+ if (!created)
561
+ break;
562
+ [child, childName] = [parent, parentName];
475
563
  }
476
564
  }
477
- this.#builtins.setattr(parent, childName.slice(dot + 1), child);
478
- if (!created)
479
- break;
480
- [child, childName] = [parent, parentName];
565
+ finally {
566
+ for (const temp of temporaries)
567
+ temp[Symbol.dispose]();
568
+ }
569
+ return this.#expose(module);
570
+ }
571
+ catch (e_2) {
572
+ env_2.error = e_2;
573
+ env_2.hasError = true;
574
+ }
575
+ finally {
576
+ __disposeResources(env_2);
481
577
  }
482
- return this.#expose(module);
483
578
  });
484
579
  }
485
580
  /**
@@ -520,8 +615,8 @@ export class Python {
520
615
  try {
521
616
  control?.cancel?.();
522
617
  const state = this.#states.get(owned ? awaitable : control?.awaitable);
523
- if (state?.ptr)
524
- this.#withGIL(() => state.future?.cancel());
618
+ if (state?.ptr && state.future)
619
+ this.#withGIL(() => this.#cancelFuture(state.future));
525
620
  }
526
621
  catch {
527
622
  // Cancellation is best-effort: the promise still rejects with the reason.
@@ -548,64 +643,83 @@ export class Python {
548
643
  * promise, the context manager is exited when it settles.
549
644
  *
550
645
  * @example python.with(python.builtins.open(file), (f) => f.read())
551
- * @param {*} manager - Context manager (PyObject proxy)
646
+ * @param {*} pending - Context manager (PyObject proxy or promise)
552
647
  * @param {Function} body - Called with the value of `__enter__()`
553
648
  * @returns {*} What `body` returns (undefined if the error was suppressed)
554
649
  */
555
- async with(pending, body) {
556
- const manager = await pending;
557
- const [enter, exit] = this.#withGIL(() => {
558
- const type = this.#builtins.type(manager);
559
- return [type.__enter__, type.__exit__];
560
- });
561
- const value = await this.#callAsync(enter, [manager]);
562
- let result;
563
- try {
564
- result = await body(value);
565
- }
566
- catch (error) {
567
- if (await this.#exit(exit, manager, error))
568
- return undefined;
569
- throw error;
570
- }
571
- await this.#callAsync(exit, [manager, null, null, null]);
572
- return result;
650
+ with(pending, body) {
651
+ return this.#withContext(pending, "__enter__", "__exit__", body);
573
652
  }
574
653
  /**
575
654
  * Python's `async with` statement for asynchronous context managers
576
655
  * (`__aenter__` / `__aexit__`), awaited on the asyncio event loop.
577
656
  *
578
- * @param {*} manager - Asynchronous context manager (PyObject proxy)
657
+ * @param {*} pending - Asynchronous context manager (PyObject proxy or promise)
579
658
  * @param {Function} body - Called with the value of `__aenter__()`; may be async
580
659
  * @returns {Promise<*>} What `body` returns (undefined if the error was suppressed)
581
660
  */
582
- async asyncWith(pending, body) {
661
+ asyncWith(pending, body) {
662
+ return this.#withContext(pending, "__aenter__", "__aexit__", body);
663
+ }
664
+ async #withContext(pending, enterName, exitName, body) {
583
665
  const manager = await pending;
584
666
  const [enter, exit] = this.#withGIL(() => {
585
- const type = this.#builtins.type(manager);
586
- return [type.__aenter__, type.__aexit__];
667
+ const env_3 = { stack: [], error: void 0, hasError: false };
668
+ try {
669
+ const type = __addDisposableResource(env_3, this.#builtins.type(manager), false);
670
+ return [type[enterName], type[exitName]];
671
+ }
672
+ catch (e_3) {
673
+ env_3.error = e_3;
674
+ env_3.hasError = true;
675
+ }
676
+ finally {
677
+ __disposeResources(env_3);
678
+ }
587
679
  });
588
- const value = await this.#callAsync(enter, [manager]);
589
- let result;
590
680
  try {
591
- result = await body(value);
681
+ const value = await this.#callAsync(enter, [manager]);
682
+ let result;
683
+ try {
684
+ result = await body(value);
685
+ }
686
+ catch (error) {
687
+ if (await this.#exit(exit, manager, error))
688
+ return undefined;
689
+ throw error;
690
+ }
691
+ const exitResult = await this.#callAsync(exit, [manager, null, null, null]);
692
+ if (this.#states.has(exitResult))
693
+ this.#release(exitResult);
694
+ return result;
592
695
  }
593
- catch (error) {
594
- if (await this.#exit(exit, manager, error))
595
- return undefined;
596
- throw error;
696
+ finally {
697
+ enter[Symbol.dispose]();
698
+ exit[Symbol.dispose]();
597
699
  }
598
- await this.#callAsync(exit, [manager, null, null, null]);
599
- return result;
600
700
  }
601
701
  /** Call `__exit__` / `__aexit__` with the Python version of a JavaScript error. */
602
702
  async #exit(exit, manager, error) {
603
- const args = this.#withGIL(() => {
703
+ const [exc, excType, tb] = this.#withGIL(() => {
604
704
  const exc = this.#wrap(this.#exception(error));
605
- return [manager, this.#builtins.type(exc), exc, exc.__traceback__];
705
+ return [exc, this.#builtins.type(exc), exc.__traceback__];
606
706
  });
607
- const result = await this.#callAsync(exit, args);
608
- return this.#withGIL(() => this.#builtins.bool(result));
707
+ let result;
708
+ try {
709
+ result = await this.#callAsync(exit, [manager, excType, exc, tb]);
710
+ }
711
+ finally {
712
+ tb?.[Symbol.dispose]();
713
+ excType[Symbol.dispose]();
714
+ exc[Symbol.dispose]();
715
+ }
716
+ try {
717
+ return this.#withGIL(() => this.#builtins.bool(result));
718
+ }
719
+ finally {
720
+ if (this.#states.has(result))
721
+ this.#release(result);
722
+ }
609
723
  }
610
724
  #controlled(work) {
611
725
  const control = { aborted: false };
@@ -875,6 +989,34 @@ export class Python {
875
989
  return this.#wrap(state.ptr, true);
876
990
  });
877
991
  }
992
+ /**
993
+ * Transfer ownership of a temporary internal proxy into a public proxy
994
+ * (zero Py_IncRef/Py_DecRef, zero leaked intermediate proxy).
995
+ */
996
+ #takeExposed(value) {
997
+ const state = this.#states.get(value);
998
+ if (!state || state.public)
999
+ return value;
1000
+ const ptr = this.#pointer(value);
1001
+ state.ptr = null;
1002
+ this.#registry.unregister(state);
1003
+ this.#proxies--;
1004
+ return this.#wrap(ptr, true);
1005
+ }
1006
+ #cancelFuture(future) {
1007
+ const env_4 = { stack: [], error: void 0, hasError: false };
1008
+ try {
1009
+ const cancel = __addDisposableResource(env_4, future.cancel, false);
1010
+ cancel();
1011
+ }
1012
+ catch (e_4) {
1013
+ env_4.error = e_4;
1014
+ env_4.hasError = true;
1015
+ }
1016
+ finally {
1017
+ __disposeResources(env_4);
1018
+ }
1019
+ }
878
1020
  // ── Conversions (GIL held) ────────────────────────────────────────
879
1021
  #pointer(proxy) {
880
1022
  const state = this.#states.get(proxy);
@@ -890,10 +1032,6 @@ export class Python {
890
1032
  throw this.#fetchError();
891
1033
  return ptr;
892
1034
  }
893
- #run(source, start, globals) {
894
- const api = this.#api;
895
- return this.#using(this.#check(api.Py_CompileString(source, "<string>", start)), (code) => this.#check(api.PyEval_EvalCode(code, globals, globals)));
896
- }
897
1035
  #import(name) {
898
1036
  return this.#take(this.#api.PyImport_ImportModule(name));
899
1037
  }
@@ -952,30 +1090,34 @@ export class Python {
952
1090
  case T.PyBool_Type:
953
1091
  return ptr === this.#true;
954
1092
  case T.PyLong_Type: {
955
- const overflow = new c_int();
956
- const value = api.PyLong_AsLongLongAndOverflow(ptr, byref(overflow));
957
- if (overflow.value)
1093
+ const value = api.PyLong_AsLongLongAndOverflow(ptr, this.#overflowOutRef);
1094
+ if (this.#overflowOut.value)
958
1095
  return BigInt(this.#take(api.PyObject_Str(ptr)));
959
1096
  return value >= -9007199254740991n && value <= 9007199254740991n ? Number(value) : value;
960
1097
  }
961
1098
  case T.PyFloat_Type:
962
1099
  return api.PyFloat_AsDouble(ptr);
963
1100
  case T.PyUnicode_Type: {
964
- const size = new c_ssize_t();
965
- const data = this.#check(api.PyUnicode_AsUTF8AndSize(ptr, byref(size)));
966
- const utf8 = Buffer.alloc(Number(size.value));
967
- if (utf8.length)
968
- memmove(utf8, data, utf8.length);
1101
+ const data = this.#check(api.PyUnicode_AsUTF8AndSize(ptr, this.#sizeOutRef));
1102
+ const length = Number(this.#sizeOut.value);
1103
+ if (length === 0)
1104
+ return "";
1105
+ if (length <= UTF8_SCRATCH_SIZE) {
1106
+ memmove(this.#utf8Scratch, data, length);
1107
+ return this.#utf8Scratch.toString("utf8", 0, length);
1108
+ }
1109
+ const utf8 = Buffer.allocUnsafe(length);
1110
+ memmove(utf8, data, length);
969
1111
  return utf8.toString("utf8");
970
1112
  }
971
1113
  case T.PyBytes_Type: {
972
- const data = new c_void_p();
973
- const size = new c_ssize_t();
974
- if (api.PyBytes_AsStringAndSize(ptr, byref(data), byref(size)) < 0)
1114
+ if (api.PyBytes_AsStringAndSize(ptr, this.#ptrOutRef, this.#sizeOutRef) < 0)
975
1115
  throw this.#fetchError();
976
- const bytes = Buffer.alloc(Number(size.value));
977
- if (bytes.length)
978
- memmove(bytes, data.value, bytes.length);
1116
+ const length = Number(this.#sizeOut.value);
1117
+ if (length === 0)
1118
+ return Buffer.alloc(0);
1119
+ const bytes = Buffer.allocUnsafe(length);
1120
+ memmove(bytes, this.#ptrOut.value, length);
979
1121
  return bytes;
980
1122
  }
981
1123
  }
@@ -1006,14 +1148,33 @@ export class Python {
1006
1148
  return items;
1007
1149
  }
1008
1150
  case T.PyDict_Type: {
1009
- const entries = [];
1010
1151
  const pos = new c_ssize_t();
1011
1152
  const key = new c_void_p();
1012
1153
  const value = new c_void_p();
1013
- while (api.PyDict_Next(ptr, byref(pos), byref(key), byref(value))) {
1014
- entries.push([this.#fromPy(key.value, true, ancestors, external), this.#fromPy(value.value, true, ancestors, external)]);
1154
+ const posRef = byref(pos);
1155
+ const keyRef = byref(key);
1156
+ const valueRef = byref(value);
1157
+ let record = {};
1158
+ let map = null;
1159
+ while (api.PyDict_Next(ptr, posRef, keyRef, valueRef)) {
1160
+ const k = this.#fromPy(key.value, true, ancestors, external);
1161
+ const v = this.#fromPy(value.value, true, ancestors, external);
1162
+ if (map !== null) {
1163
+ map.set(k, v);
1164
+ }
1165
+ else if (typeof k === "string") {
1166
+ if (k === "__proto__")
1167
+ Object.defineProperty(record, k, { value: v, writable: true, enumerable: true, configurable: true });
1168
+ else
1169
+ record[k] = v;
1170
+ }
1171
+ else {
1172
+ map = new Map(Object.entries(record));
1173
+ record = null;
1174
+ map.set(k, v);
1175
+ }
1015
1176
  }
1016
- return entries.every(([k]) => typeof k === "string") ? Object.fromEntries(entries) : new Map(entries);
1177
+ return map ?? record;
1017
1178
  }
1018
1179
  case T.PySet_Type:
1019
1180
  case T.PyFrozenSet_Type:
@@ -1075,7 +1236,7 @@ export class Python {
1075
1236
  return this.#check(api.PyFloat_FromDouble(value));
1076
1237
  return this.#check(Number.isSafeInteger(value) ? api.PyLong_FromLongLong(value) : api.PyLong_FromDouble(value));
1077
1238
  case "bigint":
1078
- return this.#check(api.PyLong_FromString(value.toString(), null, 10));
1239
+ return this.#check(value >= INT64_MIN && value <= INT64_MAX ? api.PyLong_FromLongLong(value) : api.PyLong_FromString(value.toString(), null, 10));
1079
1240
  case "string": {
1080
1241
  const utf8 = Buffer.from(value, "utf8");
1081
1242
  return this.#check(api.PyUnicode_DecodeUTF8(utf8, utf8.length, null));
@@ -1097,8 +1258,10 @@ export class Python {
1097
1258
  if (fields)
1098
1259
  return this.#takeProxy(this.#conversions.fromTemporal(fields));
1099
1260
  }
1100
- if (value instanceof Uint8Array && !(value instanceof Uint8ClampedArray))
1101
- return this.#check(api.PyBytes_FromStringAndSize(Buffer.from(value.buffer, value.byteOffset, value.byteLength), value.byteLength));
1261
+ if (value instanceof Uint8Array && !(value instanceof Uint8ClampedArray)) {
1262
+ const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value.buffer, value.byteOffset, value.byteLength);
1263
+ return this.#check(api.PyBytes_FromStringAndSize(bytes, bytes.byteLength));
1264
+ }
1102
1265
  if (ArrayBuffer.isView(value) || isArrayBuffer(value))
1103
1266
  return this.#memoryview(value);
1104
1267
  if (typeof value !== "object")
@@ -1193,10 +1356,15 @@ export class Python {
1193
1356
  if (!size)
1194
1357
  return new Type(0);
1195
1358
  if (!EXTERNAL_BUFFERS) {
1196
- // Electron forbids buffers over external memory: a copy.
1197
- const copied = new Type(size / Type.BYTES_PER_ELEMENT);
1198
- memmove(Buffer.from(copied.buffer), address, size);
1199
- return copied;
1359
+ // Electron forbids buffers over external memory: copy and release the buffer lock immediately.
1360
+ try {
1361
+ const copied = new Type(size / Type.BYTES_PER_ELEMENT);
1362
+ memmove(Buffer.from(copied.buffer), address, size);
1363
+ return copied;
1364
+ }
1365
+ finally {
1366
+ holder?.[Symbol.dispose]();
1367
+ }
1200
1368
  }
1201
1369
  const memory = array(c_uint8, size).from_address(address)._buffer; // Python: memoryview((c_ubyte * size).from_address(address))
1202
1370
  this.#keep.set(memory.buffer, holder); // pins the Python buffer while the memory is used
@@ -1447,12 +1615,14 @@ export class Python {
1447
1615
  missingAttribute();
1448
1616
  try {
1449
1617
  const value = this.#conversions.getFallback(target, prop);
1450
- return this.#states.get(target).public ? this.#expose(value) : value;
1618
+ return this.#states.get(target).public ? this.#takeExposed(value) : value;
1451
1619
  }
1452
1620
  catch (error) {
1453
1621
  // Function.prototype members of callables (see FUNCTION_MEMBERS).
1454
- if (FUNCTION_MEMBERS.has(prop) && error instanceof PythonError && error.type === "AttributeError")
1622
+ if (FUNCTION_MEMBERS.has(prop) && error instanceof PythonError && error.type === "AttributeError") {
1623
+ error.exception[Symbol.dispose]();
1455
1624
  return Reflect.get(target, prop);
1625
+ }
1456
1626
  throw error;
1457
1627
  }
1458
1628
  });
@@ -1486,16 +1656,15 @@ export class Python {
1486
1656
  // Object.keys(), Object.entries(), { ...dict }, for...in: the string keys of mappings.
1487
1657
  ownKeys: (target) => this.#withGIL(() => this.#conversions.keys(target)),
1488
1658
  getOwnPropertyDescriptor: (target, prop) => {
1489
- if (typeof prop === "string" && this.#withGIL(() => this.#conversions.isKey(target, prop))) {
1490
- return {
1491
- value: this.#withGIL(() => {
1492
- const value = this.#conversions.item(target, prop);
1493
- return this.#states.get(target).public ? this.#expose(value) : value;
1494
- }),
1495
- writable: true,
1496
- enumerable: true,
1497
- configurable: true,
1498
- };
1659
+ if (typeof prop === "string") {
1660
+ const found = this.#withGIL(() => {
1661
+ if (!this.#conversions.isKey(target, prop))
1662
+ return undefined;
1663
+ const value = this.#conversions.item(target, prop);
1664
+ return { value: this.#states.get(target).public ? this.#takeExposed(value) : value };
1665
+ });
1666
+ if (found)
1667
+ return { value: found.value, writable: true, enumerable: true, configurable: true };
1499
1668
  }
1500
1669
  return Reflect.getOwnPropertyDescriptor(target, prop);
1501
1670
  },
@@ -1545,9 +1714,16 @@ export class Python {
1545
1714
  if (this.#states.has(value) && this.#scheduler.isAwaitable(value)) {
1546
1715
  const awaitable = value;
1547
1716
  control.awaitable = awaitable;
1548
- value = this.#promise(awaitable);
1549
- if (control.aborted)
1550
- this.#states.get(awaitable).future?.cancel();
1717
+ const awaited = this.#promise(awaitable);
1718
+ value = awaited.finally(() => {
1719
+ control.awaitable = undefined;
1720
+ this.#release(awaitable);
1721
+ });
1722
+ if (control.aborted) {
1723
+ const future = this.#states.get(awaitable).future;
1724
+ if (future)
1725
+ this.#cancelFuture(future);
1726
+ }
1551
1727
  }
1552
1728
  return { value };
1553
1729
  }
@@ -1601,8 +1777,8 @@ export class Python {
1601
1777
  }
1602
1778
  }
1603
1779
  finally {
1604
- if (!this.#finalized)
1605
- this.#withGIL(() => api.Py_DecRef(iterator));
1780
+ if (!this.#finalized && !this.#nativeFinalizing)
1781
+ this.#withGIL(() => api.Py_DecRef(iterator), true);
1606
1782
  }
1607
1783
  }
1608
1784
  /** for await over a Python async iterator (async generators, ...). */
@@ -1611,20 +1787,48 @@ export class Python {
1611
1787
  let finished = false;
1612
1788
  try {
1613
1789
  while (true) {
1614
- const [done, value] = await this.#scheduler.next(iterator);
1790
+ const step = this.#withGIL(() => this.#scheduler.next(iterator));
1791
+ let pair;
1792
+ try {
1793
+ pair = (await step);
1794
+ }
1795
+ finally {
1796
+ step[Symbol.dispose]();
1797
+ }
1798
+ let done;
1799
+ let value;
1800
+ try {
1801
+ [done, value] = pair;
1802
+ }
1803
+ finally {
1804
+ if (this.#states.has(pair))
1805
+ pair[Symbol.dispose]();
1806
+ }
1615
1807
  if (done) {
1616
1808
  finished = true;
1617
1809
  return;
1618
1810
  }
1619
- yield this.#withGIL(() => this.#expose(value));
1811
+ yield this.#withGIL(() => this.#takeExposed(value));
1620
1812
  }
1621
1813
  }
1622
1814
  finally {
1623
- // break / return / throw in the loop: close the async generator.
1624
- if (!finished && !this.#finalized) {
1625
- const close = this.#scheduler.closeIterator(iterator);
1626
- if (close !== null)
1627
- await close;
1815
+ try {
1816
+ // break / return / throw in the loop: close the async generator.
1817
+ if (!finished && !this.#finalized) {
1818
+ const close = this.#withGIL(() => this.#scheduler.closeIterator(iterator));
1819
+ if (close !== null) {
1820
+ try {
1821
+ await close;
1822
+ }
1823
+ finally {
1824
+ if (this.#states.has(close))
1825
+ close[Symbol.dispose]();
1826
+ }
1827
+ }
1828
+ }
1829
+ }
1830
+ finally {
1831
+ iterator[Symbol.dispose]();
1628
1832
  }
1629
1833
  }
1630
1834
  }
@@ -1644,12 +1848,13 @@ export class Python {
1644
1848
  #promise(target) {
1645
1849
  const state = this.#states.get(target);
1646
1850
  state.promise ??= new Promise((resolve, reject) => {
1647
- const token = this.#nextToken++;
1851
+ const token = (this.#lastAwaitToken = nextCompletionToken(this.#lastAwaitToken, this.#awaits));
1648
1852
  this.#withGIL(() => {
1649
- this.#awaits.set(token, { resolve, reject, future: null });
1853
+ const entry = { state, public: state.public, resolve, reject, future: null };
1854
+ this.#awaits.set(token, entry);
1650
1855
  this.#channel.ref(); // Node.js waits for Python
1651
1856
  try {
1652
- state.future = this.#awaits.get(token).future = this.#usingProxy(this.#pointer(target), (awaitable) => {
1857
+ state.future = entry.future = this.#usingProxy(this.#pointer(target), (awaitable) => {
1653
1858
  const future = this.#scheduler.submit(awaitable, token);
1654
1859
  return future === awaitable ? this.#wrap(this.#toPy(future)) : future;
1655
1860
  });
@@ -1687,12 +1892,35 @@ export class Python {
1687
1892
  break;
1688
1893
  this.#awaits.delete(token);
1689
1894
  this.#withGIL(() => {
1895
+ const future = entry.future;
1896
+ entry.future = null;
1897
+ if (entry.state.future === future)
1898
+ entry.state.future = undefined;
1899
+ let value;
1690
1900
  try {
1691
- entry.resolve(entry.future.result());
1901
+ const env_5 = { stack: [], error: void 0, hasError: false };
1902
+ try {
1903
+ const resultFn = __addDisposableResource(env_5, future.result, false);
1904
+ value = resultFn();
1905
+ if (entry.public)
1906
+ value = this.#takeExposed(value);
1907
+ }
1908
+ catch (e_5) {
1909
+ env_5.error = e_5;
1910
+ env_5.hasError = true;
1911
+ }
1912
+ finally {
1913
+ __disposeResources(env_5);
1914
+ }
1692
1915
  }
1693
1916
  catch (error) {
1694
1917
  entry.reject(error);
1918
+ return;
1695
1919
  }
1920
+ finally {
1921
+ this.#release(future);
1922
+ }
1923
+ entry.resolve(value);
1696
1924
  });
1697
1925
  this.#unrefChannel();
1698
1926
  break;
@@ -1730,18 +1958,28 @@ export class Python {
1730
1958
  if (request === null)
1731
1959
  return null; // cancelled meanwhile
1732
1960
  try {
1733
- const fid = request[0];
1734
- if (typeof fid !== "bigint" && (typeof fid !== "number" || !Number.isSafeInteger(fid)))
1735
- throw new TypeError("Invalid JavaScript function identifier");
1736
- const args = request[1];
1737
- const kw = request[2];
1738
- const entry = this.#functions.get(BigInt(fid));
1739
- if (!entry)
1740
- throw new Error("JavaScript function has been released");
1741
- const jsArgs = [...args].map((value) => this.#expose(value));
1742
- if (this.#builtins.len(kw) > 0)
1743
- jsArgs.push(this.#fromPy(this.#pointer(kw), true, undefined, true));
1744
- return [entry, jsArgs];
1961
+ const env_6 = { stack: [], error: void 0, hasError: false };
1962
+ try {
1963
+ const fid = request[0];
1964
+ if (typeof fid !== "bigint" && (typeof fid !== "number" || !Number.isSafeInteger(fid)))
1965
+ throw new TypeError("Invalid JavaScript function identifier");
1966
+ const args = __addDisposableResource(env_6, request[1], false);
1967
+ const kw = __addDisposableResource(env_6, request[2], false);
1968
+ const entry = this.#functions.get(BigInt(fid));
1969
+ if (!entry)
1970
+ throw new Error("JavaScript function has been released");
1971
+ const jsArgs = [...args].map((value) => this.#takeExposed(value));
1972
+ if (this.#api.PyDict_Size(this.#pointer(kw)) > 0)
1973
+ jsArgs.push(this.#fromPy(this.#pointer(kw), true, undefined, true));
1974
+ return [entry, jsArgs];
1975
+ }
1976
+ catch (e_6) {
1977
+ env_6.error = e_6;
1978
+ env_6.hasError = true;
1979
+ }
1980
+ finally {
1981
+ __disposeResources(env_6);
1982
+ }
1745
1983
  }
1746
1984
  finally {
1747
1985
  request[Symbol.dispose]();
@@ -1863,9 +2101,7 @@ export class Python {
1863
2101
  const pythonType = errorProperty(error, PY_TYPE);
1864
2102
  if (pythonType) {
1865
2103
  const exc = this.#builtins[String(pythonType)](errorProperty(error, "message"));
1866
- const ptr = this.#pointer(exc);
1867
- api.Py_IncRef(ptr);
1868
- return ptr;
2104
+ return this.#takeProxy(exc);
1869
2105
  }
1870
2106
  // A Python exception that went through JavaScript keeps its type.
1871
2107
  if (error instanceof PythonError && this.#states.get(error.exception)?.ptr) {
@@ -1873,7 +2109,7 @@ export class Python {
1873
2109
  api.Py_IncRef(exc);
1874
2110
  return exc;
1875
2111
  }
1876
- const exc = this.#using(this.#check(api.PyUnicode_DecodeUTF8(...this.#utf8(`JavaScript ${errorProperty(error, "name") ?? "Error"}: ${errorProperty(error, "message") ?? String(error)}`), null)), (message) => {
2112
+ const exc = this.#using(this.#toPy(`JavaScript ${errorProperty(error, "name") ?? "Error"}: ${errorProperty(error, "message") ?? String(error)}`), (message) => {
1877
2113
  const tuple = this.#filled(api.PyTuple_New(1), (t) => {
1878
2114
  api.Py_IncRef(message);
1879
2115
  api.PyTuple_SetItem(t, 0, message);
@@ -1895,10 +2131,6 @@ export class Python {
1895
2131
  throw e;
1896
2132
  }
1897
2133
  }
1898
- #utf8(text) {
1899
- const bytes = Buffer.from(text, "utf8");
1900
- return [bytes, bytes.length];
1901
- }
1902
2134
  /** Current Python exception → PythonError (clears the exception). */
1903
2135
  #fetchError() {
1904
2136
  const api = this.#api;