diff --git a/.cto-toolkit/learning/patterns.jsonl b/.cto-toolkit/learning/patterns.jsonl index cef2d69..95e3487 100644 --- a/.cto-toolkit/learning/patterns.jsonl +++ b/.cto-toolkit/learning/patterns.jsonl @@ -34,3 +34,12 @@ "security_relevant": false, "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" } +{ + "session_id": "1794975437-433", + "timestamp": "2026-11-18T04:17:17Z", + "files_modified": 209, + "languages": "javascript,python", + "tests_touched": false, + "security_relevant": true, + "project_root": "/c/Users/nicol/Desktop/QUICKJS-NAPI/quickjs-napi" +} diff --git a/.gitignore b/.gitignore index ac11d75..1d21bc6 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,17 @@ dkms.conf # VSCode .vscode + +# Claude files +CLAUDE.md +.claude + +# Local tooling +AGENTS.md +.agents + +# Ignore .githuman +.githuman + +# Ignore cto toolkit files +.cto-toolkit/ \ No newline at end of file diff --git a/README.md b/README.md index 7865e0f..6fded0e 100644 --- a/README.md +++ b/README.md @@ -2,289 +2,83 @@ [![CI](https://github.com/napi-bindings/quickjs-napi/actions/workflows/ci.yml/badge.svg?branch=napi)](https://github.com/napi-bindings/quickjs-napi/actions/workflows/ci.yml) -Node-API implementation for QuickJS (2026-06-04, from `../quickjs-build`). -Addons built for Node.js (node-gyp, node-addon-api, napi-rs) are loaded -unchanged: they resolve `napi_*` from the `quickjs-napi` executable. +Node-API implementation for [QuickJS](https://bellard.org/quickjs/) +(2026-06-04, from `../quickjs-build`). Addons built for Node.js (node-gyp, +node-addon-api, napi-rs) are loaded **unchanged**: they resolve `napi_*` from +the `quickjs-napi` executable, exactly as they do from `node`. -Status: milestone **M6** in progress (M1 values, strings, objects, properties, -functions, classes, errors; M2 references, externals, wrapping, finalizers, -type tags, instance data, `napi_run_script`; M3 ArrayBuffer, TypedArray, -DataView, BigInt, Date, Promise; M4 the synchronous `node_api.h`: Buffer, -async context, `napi_make_callback`, callback scopes, -`napi_fatal_exception`; M5 the libuv event loop: async work, thread-safe -functions, async cleanup hooks, `napi_get_uv_event_loop`; M6 real-world -conformance). All 155 Node-API functions are implemented and pass 30 tests -of the Node.js `js-native-api` suite, 19 of its `node-api` suite (see -`test/node/README.md`) and 78 of the 83 test modules of the node-addon-api -8.9.2 suite (the others need `worker_threads`, `npm` or test the npm -package itself), in its four binding variants (C++ exceptions, no exceptions, -`Maybe`, custom namespace; see `test/node-addon-api/harness/README.md`). -`NAPI_EXPERIMENTAL` APIs are not provided. See `PIANO-IMPLEMENTAZIONE.md` -in the project for the plan. - -## Lifetime model - -- `napi_ref` follows `v8impl::Reference`: strong while its count is > 0; at - count 0 an object, function or local symbol is held through a JS `WeakRef` - (QuickJS reports the target dead as soon as its refcount drops to zero), - other values are released. -- V8 keeps the target of a weak handle until a garbage collection; QuickJS - frees an object when its refcount drops to zero, so an object created by - a native call and only referenced weakly would die when the call returns - (node-addon-api relies on the V8 behaviour: `Napi::Weak(Object::New(env))` - used later in the same synchronous code). When a reference becomes weak its - target is therefore also put on a list of *kept objects*, like the - `[[KeptAlive]]` list of ECMAScript WeakRefs, cleared at the end of every - macrotask (the library's checkpoint), by `gc()` and at teardown; - embedders call `qjsnapi_host_clear_kept_objects` at the end of their own - macrotasks. -- `napi_define_class`: as with V8's prototype template, a later instance - property with the same key replaces an earlier one, whatever its - attributes (static properties are defined like `napi_define_properties`, - where such a redefinition fails, in Node.js too). -- QuickJS has no weak callback in its C API. Each target of a reference, a - wrap or a type tag gets a *holder* object in a `WeakMap` keyed by the - target; QuickJS drops the entry of a dead key during `JS_RunGC`, and the - holder's class finalizer plays the role of V8's weak callback. Wrapping - therefore works on any object (frozen objects, proxies, functions) without - adding properties. -- Finalizers never run inside the GC: as in Node.js they are queued and run - from the event loop (`qjsnapi_host_run_finalizers`), or at teardown with - JavaScript disabled (`napi_cannot_run_js`). `global.gc()` runs two GC - passes, because QuickJS collects cycles after dropping weak entries. - -## Binary data, BigInt, Date, Promise - -- Builtin classes are recognised by class ID, found at startup by probing - one instance of each (QuickJS does not export its class enum). DataView - and TypedArray accessors, `Date.prototype.getTime` and the constructors - are captured before any user code runs, so monkey-patching the globals - does not affect Node-API. -- Semantics follow Node.js 22.23 / V8, checked against Node.js by - `test/js/test_binary.js`: `napi_get_arraybuffer_info` and - `napi_create_typedarray` accept a SharedArrayBuffer; an empty or detached - buffer has `data == NULL`; `napi_is_detached_arraybuffer` is V8's - `WasDetached()`; an external ArrayBuffer over `NULL` is detached; a - detached or out-of-bounds view reports length 0; length-tracking views of - resizable buffers report their current length; alignment, length and - DataView range errors throw the same `RangeError`s with the same codes. -- External ArrayBuffers use the memory in place; the finalizer is queued - when the buffer is collected, as Node.js defers it. -- `napi_*_bigint_words` go through a hexadecimal string (O(n)); 0n has no - words and sign 0. -- Deviations: `napi_float16_array` is supported (QuickJS has - `Float16Array`; Node.js 22 returns `napi_invalid_arg`); a BigInt is - limited to 2^20 bits (16384 words; V8: 2^30 bits), beyond which - `napi_create_bigint_words` throws `RangeError: Maximum BigInt size - exceeded`, as V8 does past its own limit; for an out-of-bounds, - non-detached view of a resizable buffer the byte offset is reported as 0 - (V8 reports the stored offset), since QuickJS does not expose it. - -## Buffer and the synchronous node_api.h - -- Buffers are instances of a minimal Node.js `Buffer` (`src/buffer.js`, - embedded in the library): a `Uint8Array` subclass with `Buffer.from`, - `alloc`, `allocUnsafe`, `isBuffer`, `byteLength`, `concat`, `compare` and - `toString`/`write`/`equals`/`copy`/`fill`/`slice`/`toJSON`/`indexOf` for - utf8, utf16le, latin1, ascii, hex, base64 and base64url. The library - installs no global; `qjsnapi_host_get_buffer()` gives the class to the - embedder. `napi_create_buffer` returns zero-filled memory (Node.js: - uninitialized). As in Node.js 22, `napi_is_buffer` and - `napi_get_buffer_info` accept any ArrayBufferView; external buffers use - the memory in place and their finalizer is queued after collection. -- No async_hooks: an async context only records that it exists. What - remains of Node's callback scopes is the microtask checkpoint when the - outermost scope closes with no JavaScript below the native code; from a - Node-API callback called by JavaScript (the usual case) nothing runs - early, as in Node.js. `napi_fatal_exception` reaches - `process.on('uncaughtException')` synchronously. -- `napi_get_node_version` reports 22.23.4, the Node.js release whose - behaviour is reproduced, with release name `quickjs-napi` - (`qjsnapi_node_version()`; the executable's `process.version` matches). -- Every `qjsnapi_load_addon` runs the addon's initializer again with a new - env, like `process.dlopen` (re-`require` after deleting the cache entry - gives new exports); a legacy `napi_module` registered by the first - `dlopen` is reused. File URLs (`node_api_get_module_file_name`) are - encoded like Node's `url.pathToFileURL`. -- Deviation: `node_api_create_buffer_from_arraybuffer` with an - out-of-range offset + length returns `napi_pending_exception`; Node.js - returns `napi_ok` with the RangeError pending and no result. - -## Event loop, async work, thread-safe functions - -- The host runs on a libuv loop (v1.51.0, built statically and linked - into the executable, whose `uv_*` symbols are exported like `napi_*`, so - addons that use libuv directly load too). `qjsnapi_host_create` owns a - loop; `qjsnapi_host_create_with_loop` uses the embedder's. - `napi_get_uv_event_loop` returns it. -- Finalizers queued by the GC run from a `uv_check` handle of the library - (an idle handle keeps the loop alive while some are queued), each followed - by a checkpoint: microtasks by default, or the embedder's - (`qjsnapi_host_set_checkpoint`). -- Async work runs `execute` on libuv's thread pool (`UV_THREADPOOL_SIZE` - applies) and `complete` on the loop thread. `napi_cancel_async_work` maps - to `uv_cancel`. A work item deleted while queued is freed after its - completion (Node.js: undefined behaviour). -- Thread-safe functions are a port of Node's `ThreadSafeFunction`: mutex, - bounded queue with a condition variable, `uv_async_t` dispatch of at most - 1000 calls per iteration, `napi_tsfn_abort`, ref/unref of the handle, and - closing at env teardown (an internal cleanup hook) with `call_js_cb(env = - NULL)` for the items still queued. -- An exception thrown by `complete`, `call_js_cb` or a finalizer goes to - `process.on('uncaughtException')`. For thread-safe functions of an addon - built with `NAPI_VERSION` < 10 it is dropped with a DEP0168 warning, as in - Node.js, unless `--force-node-api-uncaught-exceptions-policy` is given - (`qjsnapi_host_set_force_uncaught_exceptions_policy`). -- Teardown (`qjsnapi_host_destroy`) mirrors Node's: cleanup hooks newest - first (env and async ones, thread-safe functions closed there), queued - work cancelled, the loop run until every in-flight work item, closing - thread-safe function and async cleanup hook is done, then the reference - finalizers with JavaScript disabled. Async work items and user references - the addon never deleted are freed with the env (Node.js leaks them). -- `process.exit()` and a fatal exception end the executable like Node.js - (`DefaultProcessExitHandlerInternal`): the `exit` event is emitted, the - thread pool is shut down, and the process exits without tearing the - environment down (no cleanup hook or finalizer runs, work in flight is not - waited for). A normal end of the script tears everything down as above. -- `napi_fatal_error` prints `FATAL ERROR: ` and aborts - (`_exit(134)` on Windows, as Node.js). +```sh +quickjs-napi -e "console.log(require('./build/Release/addon.node').hello())" +``` -## Build +## Status + +Milestone **M6** in progress (real-world conformance). Done: M1 values, +strings, objects, properties, functions, classes, errors; M2 references, +externals, wrapping, finalizers, type tags, instance data, `napi_run_script`; +M3 ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise; M4 the +synchronous `node_api.h` (Buffer, async context, `napi_make_callback`, +callback scopes, `napi_fatal_exception`); M5 the libuv event loop (async +work, thread-safe functions, async cleanup hooks, +`napi_get_uv_event_loop`). See `PIANO-IMPLEMENTAZIONE.md` in the project for +the plan. + +- All **155 Node-API functions** (version 10) are implemented. +- They pass 30 tests of the Node.js `js-native-api` suite, 19 of its + `node-api` suite, and 78 of the 83 test modules of the **node-addon-api + 8.9.2** suite in its four binding variants (the others need + `worker_threads`, `npm` or test the npm package itself). +- Behaviour follows **Node.js 22.23.4**; the few differences are listed in + [compatibility.md](doc/compatibility.md). `NAPI_EXPERIMENTAL` APIs are not + provided. + +## Quick start `quickjs-build` must be checked out next to this repository -(`../quickjs-build`, branch `feat/quickjs-2026-06-04`). The presets in -`CMakePresets.json` are the reference configurations, used by CI too; each -builds in `build/`: - -| Preset | | -|---|---| -| `unix-debug` | Linux/macOS, Debug (QuickJS leak assertion at `JS_FreeRuntime`) | -| `unix-release` | Linux/macOS, Release | -| `unix-asan` | Linux/macOS, Debug + ASan/UBSan, QuickJS included | -| `unix-tsan` | Linux/macOS, Debug + ThreadSanitizer, QuickJS and libuv included | -| `windows-zig-debug`, `windows-zig-release` | Windows x64 with `zig cc` (see below) | +(`../quickjs-build`, branch `feat/quickjs-2026-06-04`). ```sh -cmake --preset unix-debug +cmake --preset unix-debug # windows-zig-debug on Windows cmake --build --preset unix-debug ctest --preset unix-debug ``` -With Clang (`zig cc` included), Debug builds compile the QuickJS library -itself with `-O1`: at `-O0` its interpreter loop needs ~64 KiB of C stack per -JS call and QuickJS's 1 MiB stack limit would stop at ~16 nested calls. Our -own code keeps the Debug flags, and QuickJS keeps its assertions. - -Without presets: - -```sh -cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -cmake --build build -ctest --test-dir build --output-on-failure -``` - -CI (`.github/workflows/ci.yml`) runs gcc Debug/Release, clang, gcc with -ASan/UBSan, gcc with ThreadSanitizer and macOS arm64 with the `unix-*` -presets, and Windows x64 with the `windows-zig-*` presets; the Linux and -macOS jobs without sanitizers also run the `node_parity_*` tests under -Node.js 22. - -libuv is fetched at configure time (`FetchContent`, tag v1.51.0). To build -offline, pass `-DFETCHCONTENT_SOURCE_DIR_LIBUV=`. - -Options: - -| Option | Default | | -|---|---|---| -| `QJSNAPI_QUICKJS_DIR` | `../quickjs-build` | QuickJS sources, built as a subproject | -| `QJSNAPI_QUICKJS_LIBRARY` | empty | prebuilt `libqjs.a` when the sources are not available | -| `QJSNAPI_SANITIZE` | OFF | ASan + UBSan for everything, QuickJS included | -| `QJSNAPI_TSAN` | OFF | ThreadSanitizer for everything (exclusive with `QJSNAPI_SANITIZE`) | -| `QJSNAPI_BUILD_TESTS` | ON | test addons and CTest suite | -| `QJSNAPI_NODE_ADDON_API_TESTS` | ON | the node-addon-api suite (8 C++ bindings, about 2 minutes of build) | - -`include/quickjs.h` and `include/quickjs-libc.h` must be identical to the -ones in `quickjs-build`: configuration fails otherwise (JSValue ABI). - -### Windows - -QuickJS does not support Microsoft Visual C++: the Visual Studio generators -(and clang-cl) are rejected at configure time. Use a MinGW-w64 toolchain with -Ninja, as quickjs-build does: - -- **zig** (version in `../quickjs-build/.zigversion`, e.g. `winget install zig.zig`; - `zig` must be in `PATH`, or set the `ZIG` environment variable). Use the - presets in `CMakePresets.json`, which pass the toolchain file: - - ```sh - cmake --preset windows-zig-debug - cmake --build --preset windows-zig-debug - ctest --preset windows-zig-debug - ``` - - In VS Code (CMake Tools) select the configure preset *Windows x64 - zig - - Debug*. Do not use a "zig" compiler **kit**: a kit sets `CMAKE_AR=zig;ar` - without the toolchain file, and Ninja then runs the literal command `zig;ar` - (`error: unknown command: ;ar`). The presets build in `build/`; if - `build/` still holds a tree configured with a kit or a Visual Studio - generator (`build/CMakeCache.txt`), delete it once before the first configure. - -- **MSYS2**: from a UCRT64 shell (`pacman -S mingw-w64-ucrt-x86_64-{gcc,cmake,ninja}`), - the generic commands above. - -Addons compiled with MSVC by node-gyp still load in the MinGW-built -`quickjs-napi.exe`: Node-API is a plain C ABI, and node-gyp's delay-load hook -resolves the `napi_*` imports from the running executable. - -## Usage - ```sh quickjs-napi [options] script.js [args...] quickjs-napi [options] -e [args...] ``` -Options: `-e`/`--eval ` (run the code instead of a script, -`process.argv` is `[execPath, args...]`), `-r`/`--require ` -(loaded before the script, repeatable), -`--force-node-api-uncaught-exceptions-policy[=true|false]` and -`--no-force-node-api-uncaught-exceptions-policy` (see above), `--expose-gc` -(accepted and ignored: `gc()` is always defined). An unknown option exits -with code 9, as Node.js. `NODE_OPTIONS` is read first, with the same -options separated by spaces; the options only Node.js knows are ignored -there (the variable is shared with Node.js). - -The script runs as a CommonJS module (`host/bootstrap.js`): `require` -loads `.js`, `.json` and `.node` files with Node.js resolution rules -(relative paths, directories with `package.json` "main" or `index.*`, -`node_modules`). Globals: a subset of `process` (`argv`, `platform`, -`exitCode`, `exit`, `on`/`emit` for `exit`, `uncaughtException` and -`unhandledRejection`, `nextTick`, `cwd`), `global`, `gc()`, timers -(`setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask`; builtin -modules `timers` and `timers/promises`), `Buffer` (also `require('buffer')`), -minimal builtin modules `util` (`promisify`, `types`), `url` -(`pathToFileURL`, `fileURLToPath`) and `vm` (`runInNewContext`, a new realm -of the same runtime), `child_process` (`spawnSync` and `spawn` without a -shell; stdio `pipe`, `inherit` or `ignore`, an asynchronous child's stdin is -never a pipe), `events` (a minimal `EventEmitter`), `process.env` (the real -environment), `process.version`, and the quickjs-libc helpers -(`console.log`, `print`, `scriptArgs`). As in Node.js, an exception no -frame catches (a timer, a microtask, a Node-API finalizer) goes to -`process.on('uncaughtException')` or ends the process with exit code 1, and -an unhandled promise rejection is treated the same way. ES modules and -package `exports` maps are not supported yet. +Details: [building](doc/building.md), [the executable](doc/host.md). -Embedding: see `include/qjsnapi.h` -(`qjsnapi_host_create`, `qjsnapi_host_create_with_loop`, -`qjsnapi_host_get_loop`, `qjsnapi_load_addon`, `qjsnapi_init_static_addon`, -`qjsnapi_host_get_buffer`, `qjsnapi_node_version`, `qjsnapi_host_destroy`). -The embedder runs the host's libuv loop (`uv_run`), which also runs the -queued finalizers; it installs `qjsnapi_host_set_uncaught_handler` for -exceptions thrown by native callbacks and may install -`qjsnapi_host_set_checkpoint` to drain microtasks, rejections and its own -timers after each one, and calls `qjsnapi_host_clear_kept_objects` at the -end of each macrotask it runs itself and before an explicit GC. +## Documentation -## Layout +| Document | Contents | +|---|---| +| [Architecture](doc/architecture.md) | goals, components, host and env, handle-scope arena, function calls, error model, object lifetime on a reference-counting engine, event loop, addon loading, teardown, design decisions; with diagrams | +| [Embedding API](doc/embedding.md) | `qjsnapi.h`: embedding the library in a QuickJS application, every `qjsnapi_*` function, embedder responsibilities, symbol export | +| [Node-API reference](doc/node-api/README.md) | conventions (statuses, pending exceptions, threads), writing an addon, and an index of all 155 functions | +| ↳ [Environment](doc/node-api/environment.md) | last error, versions, module file name, cleanup hooks, `napi_fatal_error`, legacy registration | +| ↳ [Values](doc/node-api/values.md) | singletons, numbers, booleans, `typeof`, coercion, arrays, strict equality | +| ↳ [Strings](doc/node-api/strings.md) | latin1 / UTF-8 / UTF-16 strings, external strings, property keys, symbols | +| ↳ [Objects](doc/node-api/objects.md) | properties by key, name and index, `napi_define_properties`, key enumeration, prototype, freeze/seal, `instanceof` | +| ↳ [Functions](doc/node-api/functions.md) | native functions, `napi_get_cb_info`, calls, `new.target`, classes, `napi_run_script` | +| ↳ [Errors](doc/node-api/errors.md) | error objects, throwing, pending exceptions | +| ↳ [Handle scopes](doc/node-api/scopes.md) | handle and escapable scopes | +| ↳ [Lifetime](doc/node-api/lifetime.md) | references, wrapping, finalizers, externals, type tags, instance data, external memory | +| ↳ [Binary data](doc/node-api/binary-data.md) | ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise | +| ↳ [Node.js-specific](doc/node-api/node-specific.md) | Buffer, async context, `napi_make_callback`, callback scopes, `napi_fatal_exception` | +| ↳ [Asynchronous APIs](doc/node-api/async.md) | async work, thread-safe functions, `napi_get_uv_event_loop` | +| [The executable](doc/host.md) | command line, `NODE_OPTIONS`, CommonJS modules, globals, builtin modules, `child_process`, event loop, exit | +| [Building](doc/building.md) | prerequisites, presets, options, Windows (zig, MSYS2), build outputs, CI | +| [Testing](doc/testing.md) | test suites, Node.js parity, sanitizers, tools, development workflows | +| [Compatibility](doc/compatibility.md) | every known difference from Node.js 22 | + +Test-suite specific notes: [test/node/README.md](test/node/README.md) +(Node.js conformance tests) and +[test/node-addon-api/harness/README.md](test/node-addon-api/harness/README.md) +(node-addon-api suite). + +## Repository layout | Path | | |---|---| @@ -305,15 +99,14 @@ end of each macrotask it runs itself and before an explicit GC. | `src/tsfn.c` | thread-safe functions | | `src/loader.c` | `.node` loading: `napi_register_module_v1`, API version, legacy `napi_module_register` | | `src/stubs_generated.c` | generated by `tools/gen_stubs.py`, do not edit (empty now: every function is implemented) | -| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: options, libuv event loop (timers, immediates, `beforeExit`), CommonJS loader, `process` (embedded at build time by `cmake/embed.cmake`), `buffer`, `util`, `url`, `vm`, `child_process`, `events` | +| `host/main.c`, `host/bootstrap.js` | the `quickjs-napi` executable: options, event loop, CommonJS loader, `process` and builtin modules (`bootstrap.js` embedded at build time by `cmake/embed.cmake`) | | `host/spawn.c` | child processes (`spawnSync` on a private loop, `spawn` on the main one) | | `test/addons`, `test/js` | our test addons; the JS tests also run under Node.js as reference | -| `test/node` | Node.js conformance tests (vendored, see its README) | -| `test/node-addon-api` | node-addon-api headers and test suite (vendored by `tools/sync_node_addon_api.py`); `harness/` is ours (see its README) | -| `cmake/node_addon_api_tests.cmake` | builds the 8 node-addon-api test bindings, one CTest per test module | +| `test/node` | Node.js conformance tests (vendored) | +| `test/node-addon-api` | node-addon-api headers and test suite (vendored by `tools/sync_node_addon_api.py`); `harness/` is ours | | `test/unit` | C embedding test (teardown order, scopes, error state, finalizer queue) | | `test/lsan.supp` | LeakSanitizer suppressions for leaks the Node.js and node-addon-api tests make by design | +| `cmake/node_addon_api_tests.cmake` | builds the 8 node-addon-api test bindings, one CTest per test module | | `cmake/expect_abort.cmake` | runs a Node.js test that must abort (`napi_fatal_error`) and checks its output | - -After implementing a function, run `python3 tools/gen_stubs.py` to drop its -stub; the `stubs_up_to_date` test fails otherwise. +| `tools/` | stub generation, export check, test vendoring ([testing.md](doc/testing.md#tools)) | +| `doc/` | this documentation | diff --git a/doc/architecture.md b/doc/architecture.md new file mode 100644 index 0000000..a2275d3 --- /dev/null +++ b/doc/architecture.md @@ -0,0 +1,559 @@ +# Architecture + +This document explains how quickjs-napi is built and why. It is meant for +contributors and for embedders who need to understand what happens behind the +Node-API calls. The API itself is described in the +[Node-API reference](node-api/README.md) and the +[embedding guide](embedding.md). + +- [Goals and constraints](#goals-and-constraints) +- [Components](#components) +- [Host and env](#host-and-env) +- [Values and handle scopes](#values-and-handle-scopes) +- [Calling native functions](#calling-native-functions) +- [Errors and exceptions](#errors-and-exceptions) +- [Object lifetime](#object-lifetime) +- [The event loop](#the-event-loop) +- [Loading addons](#loading-addons) +- [Teardown](#teardown) +- [Captured builtins](#captured-builtins) +- [Design decisions](#design-decisions) + +## Goals and constraints + +quickjs-napi implements Node-API (version 10) on top of the +[QuickJS](https://bellard.org/quickjs/) engine, so that addons compiled for +Node.js load **unchanged**. Everything in the design follows from that goal: + +1. **Binary compatibility.** An addon built by node-gyp, node-addon-api or + napi-rs does not link against any quickjs-napi library: it resolves the + `napi_*` (and `uv_*`) symbols from the running process, exactly as it does + from `node`. The executable must therefore export the whole Node-API and + libuv. +2. **Observable Node.js semantics.** The reference is Node.js **22.23.4** + (`src/js_native_api_v8.cc`, `src/node_api.cc`). Status codes, pending + exceptions, property order, error messages and finalizer timing follow it. + Each difference is a documented deviation (see + [compatibility.md](compatibility.md)). +3. **QuickJS as it is.** The engine is used through its public C API + (`quickjs.h`); it is not patched. When QuickJS lacks something V8 has (weak + callbacks, `new.target` in C functions, a class ID enum, DataView + accessors), the library builds it from what QuickJS has. + +The main difference between the two engines is the memory model: **V8 uses a +tracing GC**, so an object stays alive until a collection finds it unreachable. +**QuickJS uses reference counting** plus a cycle collector, so an object is +freed as soon as its last reference goes away. Much of the lifetime machinery +below exists to make reference counting look like a tracing GC to addons. + +## Components + +```mermaid +flowchart TB + subgraph process["quickjs-napi process"] + direction TB + script["user script
(CommonJS)"] + boot["host/bootstrap.js
require, process, timers,
Buffer, child_process, ..."] + main["host/main.c + host/spawn.c
CLI, event loop phases,
natives for bootstrap.js"] + lib["libqjsnapi (src/*.c)
Node-API 10 + qjsnapi.h"] + qjs["QuickJS
(libqjs, quickjs-libc)"] + uv["libuv 1.51
(static, uv_a)"] + script --> boot --> main + main --> lib + lib --> qjs + lib --> uv + main --> qjs + main --> uv + end + addon["addon.node
(node-gyp / node-addon-api / napi-rs)"] + addon -. "napi_* resolved
from the executable" .-> lib + addon -. "uv_*" .-> uv +``` + +| Component | Role | +|---|---| +| `src/` (library `qjsnapi`) | The Node-API implementation and the embedding API `include/qjsnapi.h`. It does not depend on the executable and can be embedded in any QuickJS application. | +| `host/` (executable `quickjs-napi`) | A small Node.js-like runtime around the library: command line, CommonJS loader, `process`, timers, the event loop. It runs addons and the test suites. See [host.md](host.md). | +| QuickJS | Built as a subproject from `../quickjs-build`. `include/quickjs.h` must match it exactly (the `JSValue` ABI); configuration fails otherwise. | +| libuv | Fetched at configure time (v1.51.0), built statically and exported by the executable, because addons call `uv_*` directly. | + +The library is linked into the executable as a **whole archive** +(`QJSNAPI_WHOLE_ARCHIVE` in `CMakeLists.txt`), so that the objects of +functions the host itself never calls are kept and exported too. The +`exports_complete` test (`tools/check_exports.py`) checks that all 155 +functions are exported. + +### Source layout of the library + +| File | Responsibility | Node-API functions | +|---|---|---| +| `env.c` | host and env lifecycle, last error, cleanup hooks, versions, fatal errors | 9 | +| `scope.c` | handle-scope arena | 5 | +| `value.c` | singletons, numbers, booleans, `typeof`, coercion, arrays, strict equality | 24 | +| `string.c` | strings (latin1, UTF-8, UTF-16), property keys, symbols | 13 | +| `object.c` | properties, descriptors, key enumeration, prototype, freeze/seal, `instanceof` | 19 | +| `function.c` | functions, calls, `new.target`, classes, `napi_run_script` | 7 | +| `error.c` | error objects and exceptions | 12 | +| `lifetime.c` | references, externals, wrap, finalizers, type tags, instance data | 16 | +| `builtins.c` | ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise | 25 | +| `buffer.c`, `buffer.js` | Node.js `Buffer` | 6 | +| `node_api.c` | async context, `napi_make_callback`, callback scopes, `napi_fatal_exception` | 6 | +| `async.c` | async work on the libuv thread pool | 4 | +| `tsfn.c` | thread-safe functions | 7 | +| `loop.c` | libuv loop ownership, finalizer handles, `napi_get_uv_event_loop` | 1 | +| `loader.c` | `.node` loading, legacy `napi_module_register` | 1 | +| `stubs_generated.c` | generated stubs for unimplemented functions (empty: everything is implemented) | 0 | + +Shared types and helpers live in `src/qjsnapi_internal.h`. Internal functions +carry the `qn_` prefix and are hidden (`QN_INTERNAL`, ELF visibility +`hidden`), so the only exported symbols are the Node-API and `qjsnapi_*` +ones. + +## Host and env + +Node.js has one *environment* per thread and one `napi_env` per loaded addon. +quickjs-napi keeps the same split: + +```mermaid +classDiagram + direction LR + class JSRuntime + class JSContext { + opaque points to the host + } + class qjsnapi_host { + uv_loop_t* loop + qn_list envs + qn_list modules + JSValue holders (WeakMap) + captured builtins + JSValue* kept + uncaught / checkpoint callbacks + } + class napi_env__ { + int32 module_api_version + bool can_call_into_js + last_error + qn_arena arena + cleanup_hooks + reflist / finalizing_reflist + pending_finalizers + works, deferreds, async_contexts + } + class qn_module_record { + path + dlopen handle + legacy napi_module + } + JSRuntime "1" o-- "1..*" JSContext + JSContext "1" -- "1" qjsnapi_host + qjsnapi_host "1" *-- "*" napi_env__ : one per addon load + qjsnapi_host "1" *-- "*" qn_module_record + qn_module_record --> napi_env__ +``` + +- **`qjsnapi_host`** (one per `JSContext`, stored as the context opaque) owns + everything that is shared: the libuv loop, the captured builtins, the + `WeakMap` of lifetime holders, the list of envs and loaded modules, the + *kept objects* list, and the embedder's callbacks (uncaught exception + handler, checkpoint). +- **`napi_env__`** (one per addon initialization) owns what Node.js keeps per + module: the **module API version** (which changes some behaviours, e.g. + `napi_cannot_run_js` instead of `napi_pending_exception` during teardown), + the last error, the handle-scope arena, cleanup hooks, references, the + finalizer queue, and the async objects not yet released. + +Loading the same addon twice creates two envs, like `process.dlopen` in +Node.js: the initializer runs again and returns new exports. + +## Values and handle scopes + +A `napi_value` is an opaque pointer. In quickjs-napi it **points to a +`JSValue` slot** in an arena owned by the env. Each slot owns exactly one +QuickJS reference (`JS_DupValue` when the slot is filled, `JS_FreeValue` when +its scope closes). This is the reference-counting equivalent of a V8 local +handle. + +```mermaid +flowchart LR + subgraph arena["env arena: chunks of 256 JSValue slots, never moved"] + direction LR + c1["chunk 1
slots 0..255"] --- c2["chunk 2
slots 0..255"] --- c3["chunk 3
..."] + end + root["root scope
mark: chunk 1, slot 0"] -.-> c1 + s1["implicit scope of a call
mark: chunk 1, slot 17"] -.-> c1 + s2["napi_open_handle_scope
mark: chunk 2, slot 40"] -.-> c2 + top["top: next free slot"] -.-> c3 +``` + +- Slots are allocated by bumping `arena.top`. Chunks are linked, never + reallocated, so a `napi_value` stays valid until its scope closes. +- A scope records the arena position (`qn_mark`) when it opens. Closing it + frees, in LIFO order, every slot allocated since then and resets `top`. + Closing a scope is O(number of values created in it), with no per-handle + bookkeeping. +- **Escapable scopes** reserve one slot in the parent *before* recording their + own mark. `napi_escape_handle` stores a duplicated reference into that slot, + so the value survives the inner scope. Escaping twice returns + `napi_escape_called_twice`. +- Every native entry point (a function call, a finalizer, module init, a loop + callback) runs inside an **implicit scope**, so addons that never open scopes + do not leak. Closing a scope that is not the innermost one returns + `napi_handle_scope_mismatch`. +- Scope records are recycled through a free list, so opening a scope does not + allocate in the steady state. + +## Calling native functions + +`JS_NewCFunctionData` is not enough for Node-API: its trampoline does not expose +`new.target`, which `napi_get_new_target` and `napi_define_class` need. Native +functions are therefore objects of a dedicated QuickJS class with a `call` +hook. QuickJS passes `JS_CALL_FLAG_CONSTRUCTOR` and, for construct calls, +`new.target` as `this_val`. + +```mermaid +sequenceDiagram + participant JS as JavaScript + participant T as qn_function_call (trampoline) + participant S as handle-scope arena + participant CB as addon callback + JS->>T: f(a, b) or new F(a, b) + alt construct call + T->>T: receiver = object with new.target.prototype + else plain call + T->>T: receiver = this + end + T->>S: open implicit scope + T->>T: clear last error, native_depth++ + T->>CB: cb(env, &callback_info) + CB->>S: napi_create_* (new slots) + CB-->>T: napi_value result (or NULL) + T->>T: native_depth-- + alt exception pending + T-->>JS: JS_EXCEPTION (the exception propagates) + else + T->>T: duplicate the result out of the scope + end + T->>S: close the scope (frees every slot of the call) + T-->>JS: result, or the receiver when a construct call
returned a non-object +``` + +- `napi_callback_info` points to a stack record (`this`, `new.target`, + `argc`, `argv`, `data`): there is no allocation per call. +- The per-function record (`qn_function`: env, callback, data) is owned by the + function object and freed by its class finalizer. It holds no `JSValue`, so + the class needs no `gc_mark` hook. +- `host->native_depth` counts the native frames on the stack. It is `0` only + when no JavaScript is below the running native code, which is how callback + scopes decide whether to run a microtask checkpoint. +- A function whose env is shutting down throws an `InternalError` instead of + calling into the addon. + +`napi_define_class` creates such a function and defines the instance +properties on its `prototype` and the static ones on the constructor. As with +V8's prototype templates, a later instance property with the same key replaces +an earlier one regardless of its attributes. + +## Errors and exceptions + +Node-API reports errors in two ways, and quickjs-napi keeps both exactly like +Node.js: + +1. **Status codes.** Every function returns a `napi_status` and records it as + the env's *last error* (`napi_get_last_error_info`). The checks are the + macros of `qjsnapi_internal.h`, named after their Node.js equivalents: + `CHECK_ENV`, `CHECK_ARG`, `RETURN_STATUS_IF_FALSE`, `NAPI_PREAMBLE`, + `CHECK_JS`, `GET_RETURN_STATUS`. +2. **JavaScript exceptions.** QuickJS keeps the pending exception on the + runtime. A JavaScript failure leaves it pending, exactly like V8, and the + function returns `napi_pending_exception`. + +```mermaid +flowchart TD + A["API that may run JavaScript"] --> P{"NAPI_PREAMBLE"} + P -- "env is NULL" --> E1["napi_invalid_arg"] + P -- "an exception is already pending" --> E2["napi_pending_exception"] + P -- "env is tearing down" --> E3["napi_cannot_run_js (module API >= 10)
napi_pending_exception (older modules)"] + P -- ok --> B["clear the last error, run the QuickJS call"] + B -- "JavaScript threw" --> E4["napi_pending_exception
(the exception stays pending)"] + B -- "other failure" --> E5["specific status
(napi_*_expected, napi_generic_failure, ...)"] + B -- ok --> OK["napi_ok"] +``` + +When a native callback returns with an exception pending, the trampoline +returns `JS_EXCEPTION`, so the exception propagates to the JavaScript caller. +When there is no JavaScript caller (a finalizer, an async work completion, a +thread-safe function call), the exception goes to the host's **uncaught +handler** (`qjsnapi_host_set_uncaught_handler`), which the executable maps to +`process.on('uncaughtException')`. + +## Object lifetime + +This is where the two engines differ most. The +[lifetime reference](node-api/lifetime.md) describes the API; this section +explains the mechanism. + +### References + +`napi_ref` (`struct napi_ref__`) mirrors `v8impl::Reference`: + +```mermaid +stateDiagram-v2 + [*] --> Strong: create with count > 0 + [*] --> Weak: create with count 0
(object, function, local symbol) + [*] --> Empty: create with count 0
(any other value) + Strong --> Weak: unref reaches 0, weakable target + Strong --> Empty: unref reaches 0, other value + Weak --> Strong: ref, target still alive + Weak --> Empty: target collected (holder finalizer) + Strong --> [*]: napi_delete_reference + Weak --> [*]: napi_delete_reference + Empty --> [*]: napi_delete_reference +``` + +- **Strong** (count > 0): the reference owns a `JSValue`. +- **Weak** (count 0; object, function or non-registered symbol): it holds a + JavaScript `WeakRef`. QuickJS reports a `WeakRef` target dead as soon as its + refcount drops to zero, so `napi_get_reference_value` returns `NULL` exactly + when the value is gone. The target is also on the *kept-objects* list until + the next clear (see below). +- **Empty** (count 0, any other value): the value is released for good, like a + reset V8 persistent. +- Registered symbols (`Symbol.for`) cannot be held weakly by QuickJS. They are + never collected anyway, so they stay strong (`keep_strong`), which is what + Node.js observably does. + +### Kept objects + +V8 keeps the target of a weak handle alive until the next GC. node-addon-api +relies on this: `Napi::Weak(Object::New(env))` is used later in the same +synchronous code. Under reference counting such an object would die when the +call's scope closes. So when a reference becomes weak, its target is also put +on a **kept-objects list**, like the `[[KeptAlive]]` list of ECMAScript +`WeakRef`s. The list is cleared: + +- at the end of every macrotask (the library's checkpoint, after each callback + from the event loop); +- by `gc()` in the executable; +- by the embedder, with `qjsnapi_host_clear_kept_objects`; +- at teardown. + +### Weak callbacks through holders + +V8 notifies a weak persistent when its target is collected; QuickJS has no +such hook in its C API. quickjs-napi gets the notification through a +**holder**: + +```mermaid +sequenceDiagram + participant A as addon + participant L as lifetime.c + participant W as host.holders (WeakMap) + participant H as NapiHolder object + participant G as QuickJS GC + participant Q as env.pending_finalizers + participant U as event loop (uv_check) + A->>L: napi_wrap / napi_create_reference / napi_type_tag_object + L->>W: get(target), or set(target, new holder) + L->>H: register the reference, wrap or tag + Note over G: the target becomes unreachable + G->>W: JS_RunGC drops the entry of the dead key + W->>H: the holder is freed + H->>L: class finalizer: notify every registered reference + L->>Q: no finalizer: reset now
with a finalizer: queue it + U->>Q: qjsnapi_host_run_finalizers + Q->>A: finalize_cb(env, data, hint) in its own scope +``` + +- Each target of a reference, wrap or type tag gets **one holder**, an object + of the internal `NapiHolder` class stored in `host->holders`, a `WeakMap` + keyed by the target. +- QuickJS drops the entries of dead keys during `JS_RunGC`. The holder is + freed, and its class finalizer plays the role of V8's weak callback. +- The holder also stores the `napi_wrap` reference and the type tag, so + **wrapping and tagging work on any object** (frozen objects, proxies, + functions) without adding properties to it. +- QuickJS drops weak entries *before* collecting cycles, so a target that died + in a cycle is only seen dead by a second pass: `gc()` runs `JS_RunGC` twice. + +### Finalizers are deferred + +Finalizers **never run inside the GC**. As in Node.js, they are queued on the +env (`pending_finalizers`) and run later from the event loop, where +JavaScript may run (`qjsnapi_host_run_finalizers`), each in its own handle +scope and followed by a checkpoint. Finalizers still queued at teardown run +then, with JavaScript disabled (`napi_cannot_run_js`). + +External values (`napi_create_external`), external ArrayBuffers and external +Buffers use the same queue: their finalizer runs after the object is +collected, never synchronously. + +## The event loop + +The host is bound to a **libuv loop**: `qjsnapi_host_create` creates its own, +`qjsnapi_host_create_with_loop` uses the embedder's. The library only adds +handles to the loop; **the embedder runs it** (`uv_run`). + +```mermaid +flowchart LR + subgraph iteration["one libuv iteration"] + direction LR + T["timers"] --> P["pending"] --> I["idle / prepare"] --> PO["poll (I/O)"] --> C["check"] --> CL["close callbacks"] + end + W["async work completion
(uv_queue_work after_work)"] -.-> PO + TS["thread-safe function dispatch
(uv_async_t)"] -.-> PO + FI["finalizer_idle (uv_idle_t)
active while finalizers are queued,
so poll does not block"] -.-> I + FC["finalizer_check (uv_check_t, unreferenced)
runs the queued finalizers"] -.-> C +``` + +| Handle | Owner | Purpose | +|---|---|---| +| `finalizer_check` (`uv_check_t`, unreferenced) | `loop.c` | runs the queued finalizers at the end of each iteration, then a checkpoint | +| `finalizer_idle` (`uv_idle_t`) | `loop.c` | active only while finalizers are queued: keeps the loop alive and stops the poll phase from blocking (Node.js uses a referenced `SetImmediate`) | +| `uv_work_t` per queued work item | `async.c` | `execute` on the thread pool, `complete` on the loop thread | +| `uv_async_t` per thread-safe function | `tsfn.c` | wakes the loop thread to dispatch queued calls (referenced unless `napi_unref_threadsafe_function`) | + +Every callback from the loop into native code goes through a **callback +frame** (`qn_callback_enter` / `qn_callback_leave`): a handle scope, a callback +scope, and on exit an exception check (reported as uncaught) and, for the +outermost scope, a **checkpoint**. The default checkpoint runs the pending +promise jobs (`JS_ExecutePendingJob`); the embedder can replace it +(`qjsnapi_host_set_checkpoint`) to drain its own queues too, which is what the +executable does for `process.nextTick` and unhandled rejections. + +### Async work + +```mermaid +sequenceDiagram + participant A as addon (loop thread) + participant L as libuv loop + participant P as thread pool + A->>A: napi_create_async_work(execute, complete, data) + A->>L: napi_queue_async_work (uv_queue_work), active_works++ + L->>P: execute(env, data), no JavaScript allowed + P-->>L: done + L->>A: after_work: active_works--, then complete(env, napi_ok, data)
inside a callback frame + A->>A: napi_delete_async_work (usually from complete) + Note over A,L: napi_cancel_async_work before execute starts:
complete(env, napi_cancelled, data) +``` + +The item is uncounted *before* `complete` runs, so `complete` may queue the +same item again. + +### Thread-safe functions + +A port of Node 22's `v8impl::ThreadSafeFunction` on libuv primitives: a mutex, +a queue (bounded when `max_queue_size > 0`, with a condition variable for +blocked producers), a `uv_async_t` that wakes the loop thread, and at most +1000 calls dispatched per wake-up so that other handles are not starved. + +```mermaid +stateDiagram-v2 + [*] --> Open: napi_create_threadsafe_function
(thread_count = initial_thread_count) + Open --> Open: call queues an item, acquire increments,
release decrements thread_count + Open --> Closing: thread_count reaches 0 and the queue is empty + Open --> Closing: release with napi_tsfn_abort + Open --> Closing: env teardown (internal cleanup hook) + Closing --> Finalized: uv_close callback runs thread_finalize_cb,
then call_js_cb(env = NULL) for each queued item + Finalized --> [*] +``` + +While closing, producers get `napi_closing`. + +## Loading addons + +```mermaid +sequenceDiagram + participant R as require / embedder + participant L as qjsnapi_load_addon + participant D as dlopen / LoadLibrary + participant M as addon + R->>L: path + L->>D: open the absolute path (the handle is never closed) + D->>M: static constructors run + M-->>L: napi_module_register(mod), legacy addons only + L->>M: dlsym napi_register_module_v1 + L->>M: dlsym node_api_module_get_api_version_v1 (optional) + L->>L: version: missing = 8, below 8 raised to 8,
above 10 = ERR_DLOPEN_FAILED + L->>L: new env, implicit scope, exports = {} + L->>M: init(env, exports) + M-->>L: exports, or a replacement value + L-->>R: new reference to the exports +``` + +1. `node_api_module_get_api_version_v1` (optional, default 8) gives the module + API version. A version above 10 is refused with `ERR_DLOPEN_FAILED`; one + below 8 is raised to 8, as in Node.js. +2. `napi_register_module_v1` is the symbol-based entry point (what + `NAPI_MODULE` and `NAPI_MODULE_INIT` produce). +3. Otherwise, a `napi_module` registered by `napi_module_register()` from a + static constructor **during** `dlopen` (legacy addons). The constructor only + runs on the first `dlopen` of a file, so the record is remembered and reused + by later loads. + +If the initializer returns a value other than `exports`, that value replaces +the exports, as Node.js assigns it to `module.exports`. + +Library handles are **never closed**: finalizers and cleanup hooks may point +into addon code until the very end of the process. + +Static addons, linked into the embedder, use `qjsnapi_init_static_addon`, +which runs the initializer once and caches its exports by name. + +## Teardown + +`qjsnapi_host_destroy` mirrors Node's `Environment::RunCleanup` and +`node_napi_env__::DeleteMe`: + +```mermaid +flowchart TD + S["qjsnapi_host_destroy"] --> A["1. every env, newest first:
can_call_into_js = false, then cleanup hooks LIFO
(user hooks, async hooks start, thread-safe functions start closing)"] + A --> B["2. queued async work cancelled"] + B --> C["3. uv_run(UV_RUN_ONCE) until in-flight work,
closing thread-safe functions and
started async cleanup hooks are done"] + C --> D["4. every env, newest first: queued finalizers,
then references with a finalizer (instance data included),
then plain references"] + D --> E["5. module cache released (exports objects)"] + E --> F["6. every env arena released (all napi_value slots)"] + F --> G["7. library loop handles closed (the loop too when owned),
captured builtins released, host detached from the context"] + G --> H["embedder: JS_FreeContext, JS_FreeRuntime"] +``` + +- References with a finalizer are finalized before plain ones, because their + finalizers may delete plain references. +- Async work items and user references the addon never deleted are freed with + the env. Node.js leaks them; here nothing can reach them after teardown, and + freeing them keeps the QuickJS leak assertion (`JS_FreeRuntime` in Debug + builds) meaningful. +- In the executable, `process.exit()` and fatal exceptions **skip** this + teardown, as Node.js does: no cleanup hook or finalizer runs. + +## Captured builtins + +Some APIs have no QuickJS C equivalent and are implemented by calling a +JavaScript builtin: `WeakRef`, `WeakMap.prototype.get/set`, `Object.freeze`, +`Object.seal`, `Symbol`, `Symbol.for`, the `DataView` and `%TypedArray%` +getters, `Date.prototype.getTime`, and BigInt conversion to and from +hexadecimal. These are captured **when the host is created, before any user +script runs**, and stored on the host. Monkey-patching the globals later +therefore cannot change what Node-API reports, which matches V8, where these +operations do not go through JavaScript. + +QuickJS does not export its class ID enum. The class IDs of `ArrayBuffer`, +`SharedArrayBuffer`, `DataView`, `Date` and the 12 typed arrays are found by +**probing one instance of each** at startup (`host->cid_*`); type checks then +compare class IDs. + +## Design decisions + +| Decision | Alternative | Why | +|---|---|---| +| Addons resolve `napi_*` from the executable | ship a `libnode`-like shared library | It is how addons are built for Node.js. Prebuilt binaries work unchanged, including MSVC builds on Windows (node-gyp's delay-load hook redirects the `node.exe` imports to the running process). | +| `napi_value` = pointer to an arena slot that owns one reference | box every value in a malloc'ed handle; or cast the `JSValue` itself | A `JSValue` is larger than a pointer on every target (a 16-byte struct on 64-bit, a NaN-boxed 64-bit value on 32-bit). The arena gives stable addresses, O(1) allocation, and scope release without per-handle bookkeeping. | +| Weak callbacks through a `WeakMap` of holders | patch QuickJS to add weak callbacks; add hidden properties to the target | Uses only the public API; works on frozen objects, proxies and functions; the engine stays unpatched. | +| Kept-objects list for weak targets | pure reference-counting semantics | Without it, objects referenced only weakly die when the creating call returns, which breaks node-addon-api (`Napi::Weak`). The list reproduces V8's "alive until the next GC" the same way ECMAScript `WeakRef` does. | +| Finalizers queued and run from the loop | run them in the QuickJS class finalizer | Node.js does the same; a QuickJS class finalizer runs inside the GC, where calling into the engine is unsafe. | +| Dedicated function class with a `call` hook | `JS_NewCFunctionData` | Only the `call` hook receives `new.target`, needed by `napi_get_new_target` and `napi_define_class`. | +| Builtins captured at startup | look them up on `globalThis` at each call | Immune to monkey-patching, like V8; no lookup per call. | +| libuv as the event loop | a custom loop | Addons call `napi_get_uv_event_loop` and `uv_*` directly; the semantics of async work and thread-safe functions are defined in libuv terms. | +| Library and executable are separate | a single executable | The library can be embedded in any QuickJS application ([embedding.md](embedding.md)); the executable is one embedder among others. | +| Free what the addon leaked at teardown | leak like Node.js | Debug builds of QuickJS assert that every object is released at `JS_FreeRuntime`, which turns any leak in the library into a test failure. | +| Node.js 22 as the behavioural reference, checked by running the same JS tests under Node.js | follow the Node-API documentation only | The documentation leaves many details open (property order, error codes, edge cases); the Node.js implementation and its test suites are the contract addons actually depend on. | diff --git a/doc/compatibility.md b/doc/compatibility.md new file mode 100644 index 0000000..0f51aee --- /dev/null +++ b/doc/compatibility.md @@ -0,0 +1,72 @@ +# Compatibility with Node.js + +quickjs-napi reproduces the Node-API behaviour of **Node.js 22.23.4**: same +statuses, same pending exceptions, same error codes and messages, same +finalizer ordering. This page lists every known difference, so that addon +authors know what to expect. Each item links to the function reference. + +- [Deviations in the API](#deviations-in-the-api) +- [Differences that come from QuickJS](#differences-that-come-from-quickjs) +- [Behaviour that is defined here but not in Node.js](#behaviour-that-is-defined-here-but-not-in-nodejs) +- [Not provided](#not-provided) +- [The executable](#the-executable) + +## Deviations in the API + +| Function | Node.js 22 | quickjs-napi | Reference | +|---|---|---|---| +| `napi_define_class` | prototype methods have a V8 *signature*: calling one on a foreign object throws `TypeError: Illegal invocation` | the callback runs; it must validate `this` (e.g. with `napi_unwrap`) | [functions.md](node-api/functions.md#napi_define_class) | +| `napi_is_array` | `false` for every Proxy | `true` for a Proxy whose target is an array (as `Array.isArray`); `false` for a revoked Proxy | [values.md](node-api/values.md#napi_is_array) | +| `napi_create_buffer` | memory uninitialized | memory zero-filled | [node-specific.md](node-api/node-specific.md#napi_create_buffer) | +| `node_api_create_buffer_from_arraybuffer`, range out of bounds | `napi_ok` with the `RangeError` pending | `napi_pending_exception` with the same `RangeError` pending | [node-specific.md](node-api/node-specific.md#node_api_create_buffer_from_arraybuffer) | +| `napi_create_typedarray` / `napi_get_typedarray_info` with `napi_float16_array` | `napi_invalid_arg` | supported (QuickJS has `Float16Array`) | [binary-data.md](node-api/binary-data.md#typedarray) | +| `napi_get_typedarray_info`, out-of-bounds non-detached view of a resizable buffer | reports the stored byte offset | reports byte offset 0 (QuickJS does not expose it) | [binary-data.md](node-api/binary-data.md#napi_get_typedarray_info) | +| `napi_get_threadsafe_function_context` with `NULL` arguments | aborts | `napi_invalid_arg` | [async.md](node-api/async.md#napi_get_threadsafe_function_context) | +| `napi_module_register` outside of an addon load | registers a module | prints a warning and does nothing (use `qjsnapi_init_static_addon`) | [environment.md](node-api/environment.md#napi_module_register) | + +## Differences that come from QuickJS + +| Area | Effect | +|---|---| +| **Finalizer timing** | QuickJS frees an object as soon as its last reference goes away (cycles at `JS_RunGC`). Finalizers therefore usually run **earlier** than in Node.js, at the next loop iteration instead of at some later major GC. Code that assumes an object stays alive while only weakly referenced still works within the same macrotask (the kept-objects list), but not across macrotasks. See [architecture.md](architecture.md#object-lifetime). | +| **BigInt size** | at most 2^20 bits (16384 words; V8: 2^30). `napi_create_bigint_words` beyond that throws `RangeError: Maximum BigInt size exceeded`, as V8 does past its own limit. | +| **BigInt words** | `napi_*_bigint_words` convert through a hexadecimal string: O(n), slower than V8's direct access for very large values. | +| **External strings** | `node_api_create_external_string_*` always copy and run the finalizer immediately (`*copied = true`). Node.js does the same when V8 uses the pointer-compression sandbox, so addons handle it already. | +| **Property keys** | `node_api_create_property_key_*` create ordinary strings: QuickJS atomizes keys itself. Not observable. | +| **External memory** | `napi_adjust_external_memory` keeps the counter but does not influence garbage collection: QuickJS has no such heuristic. | +| **Basic finalizers** | all finalizers run outside the GC, so calling any Node-API function from a `node_api_basic_finalize` never triggers Node's fatal "Finalizer is calling a function that may affect GC state" error. | +| **Async context** | there is no `async_hooks`: `napi_async_init`, `napi_make_callback` and callback scopes work, but no async resource is tracked (`AsyncLocalStorage` and async stack traces do not follow native callbacks). | + +## Behaviour that is defined here but not in Node.js + +These cases are undefined behaviour or leaks in Node.js; quickjs-napi chose a +safe behaviour: + +| Case | quickjs-napi | +|---|---| +| `napi_delete_async_work` on a queued item | the item is freed after its `complete` has run | +| async work items and user references never deleted | freed with the env at teardown (Node.js leaks them) | +| a user `napi_ref` whose finalizer ran but that the addon never deleted | freed at teardown | +| a handle scope left open by a function called from JavaScript | closed with the call's implicit scope (warning in Debug builds) | + +## Not provided + +- `NAPI_EXPERIMENTAL` APIs: the bundled headers stop at version 10 and + declare no experimental function (`node_api_post_finalizer`, ...); an addon + that needs one fails to load because the symbol is missing. +- `napi_would_deadlock` is never returned (Node.js 22 does not return it + either); a blocking call of a full thread-safe function from the loop + thread deadlocks. + +## The executable + +The `quickjs-napi` executable is not Node.js; it provides what addon packages +and their tests need ([host.md](host.md)). In particular: + +- `process.version` is `v22.23.4` (the reproduced Node-API behaviour) but + `process.versions.node` is not set; +- CommonJS only: no ES modules, no `package.json` `"exports"` maps; +- no `worker_threads`, `async_hooks`, `domain`, `fs`, `net`, `http`, + `crypto`; +- `child_process` without a shell, and an asynchronous child's stdin is never + a pipe. diff --git a/doc/embedding.md b/doc/embedding.md new file mode 100644 index 0000000..2a6e9b1 --- /dev/null +++ b/doc/embedding.md @@ -0,0 +1,369 @@ +# Embedding API (`qjsnapi.h`) + +The library `qjsnapi` can be embedded in any application that uses QuickJS. +`include/qjsnapi.h` is its whole public interface besides Node-API itself. +The `quickjs-napi` executable ([host.md](host.md)) is one such embedder, and +`test/unit/test_embed.c` is a complete, tested example. + +- [Lifecycle at a glance](#lifecycle-at-a-glance) +- [Minimal embedder](#minimal-embedder) +- [Function reference](#function-reference) +- [Embedder responsibilities](#embedder-responsibilities) +- [Linking](#linking) + +## Lifecycle at a glance + +```mermaid +sequenceDiagram + participant E as embedder + participant Q as QuickJS + participant H as qjsnapi host + participant U as libuv loop + E->>Q: JS_NewRuntime, JS_NewContext + E->>H: qjsnapi_host_create(ctx) (or _with_loop) + E->>H: set_uncaught_handler, set_checkpoint (optional) + E->>H: qjsnapi_load_addon / qjsnapi_init_static_addon + H-->>E: exports + E->>Q: run scripts that use the exports + E->>U: uv_run(qjsnapi_host_get_loop(host), UV_RUN_DEFAULT) + U->>H: async work, thread-safe functions, finalizers + E->>Q: JS_FreeValue(exports) + E->>H: qjsnapi_host_destroy (cleanup hooks, drain, finalizers) + E->>Q: JS_FreeContext, JS_FreeRuntime +``` + +The rules are: + +- **One host per `JSContext`.** The host is stored as the context opaque + (`JS_SetContextOpaque`), so the embedder must not use that slot for anything + else. `qjsnapi_host_from_context` gets it back. +- **One thread.** The context and the loop run on the same thread. Other + threads only reach the host through thread-safe functions and async work. +- **Destroy before `JS_FreeContext`.** `qjsnapi_host_destroy` still needs the + context to finalize references. + +## Minimal embedder + +```c +#include +#include + +#include "qjsnapi.h" +#include "quickjs.h" + +static void on_uncaught(qjsnapi_host *host, JSContext *ctx, JSValue exc, + void *opaque) { + (void)host; + (void)opaque; + const char *s = JS_ToCString(ctx, exc); + fprintf(stderr, "uncaught: %s\n", s ? s : "?"); + JS_FreeCString(ctx, s); + JS_FreeValue(ctx, exc); /* the handler owns the exception */ +} + +int main(void) { + JSRuntime *rt = JS_NewRuntime(); + JSContext *ctx = JS_NewContext(rt); + qjsnapi_host *host = qjsnapi_host_create(ctx); + if (!host) return 1; + qjsnapi_host_set_uncaught_handler(host, on_uncaught, NULL); + + JSValue exports; + if (qjsnapi_load_addon(host, "./build/Release/addon.node", &exports) < 0) { + JSValue exc = JS_GetException(ctx); /* the load error is pending */ + on_uncaught(host, ctx, exc, NULL); + } else { + JSValue global = JS_GetGlobalObject(ctx); + JS_SetPropertyStr(ctx, global, "addon", exports); /* takes ownership */ + JS_FreeValue(ctx, global); + + JSValue r = JS_Eval(ctx, "addon.hello()", 13, "
", + JS_EVAL_TYPE_GLOBAL); + if (JS_IsException(r)) on_uncaught(host, ctx, JS_GetException(ctx), NULL); + JS_FreeValue(ctx, r); + } + + /* Async work, thread-safe functions and finalizers run from the loop. */ + uv_run(qjsnapi_host_get_loop(host), UV_RUN_DEFAULT); + + qjsnapi_host_destroy(host); + JS_FreeContext(ctx); + JS_FreeRuntime(rt); + return 0; +} +``` + +An addon linked into the application instead of loaded from a file: + +```c +static napi_value Init(napi_env env, napi_value exports) { + /* ... napi_define_properties(env, exports, ...) ... */ + return exports; +} + +JSValue exports; +if (qjsnapi_init_static_addon(host, "my-static-addon", Init, + 10 /* module API version */, &exports) < 0) { + /* exception pending on ctx */ +} +``` + +## Function reference + +### Host lifecycle + +#### `qjsnapi_host_create` + +```c +qjsnapi_host *qjsnapi_host_create(JSContext *ctx); +``` + +Creates the Node-API host for `ctx`, with a **libuv loop of its own** that +`qjsnapi_host_destroy` closes. It captures the builtins Node-API needs, +evaluates the embedded `Buffer` class, probes the builtin class IDs and +registers the library's loop handles. Must be called before any user script +runs (see [captured builtins](architecture.md#captured-builtins)). +Returns `NULL` on failure; a JavaScript exception may then be pending. + +#### `qjsnapi_host_create_with_loop` + +```c +qjsnapi_host *qjsnapi_host_create_with_loop(JSContext *ctx, + struct uv_loop_s *loop); +``` + +Same, on the embedder's loop. The loop must outlive the host and run on the +thread that owns `ctx`. The host adds its handles to it and removes them in +`qjsnapi_host_destroy`, but does not close the loop. + +#### `qjsnapi_host_get_loop` + +```c +struct uv_loop_s *qjsnapi_host_get_loop(qjsnapi_host *host); +``` + +The loop of the host: the one `napi_get_uv_event_loop` returns to addons and +the one the embedder must run. + +#### `qjsnapi_host_from_context` + +```c +qjsnapi_host *qjsnapi_host_from_context(JSContext *ctx); +``` + +The host attached to `ctx`, or `NULL`. Useful in native functions of the +embedder that only receive a `JSContext`. + +#### `qjsnapi_host_destroy` + +```c +void qjsnapi_host_destroy(qjsnapi_host *host); +``` + +Tears down every env as Node.js does at exit, with JavaScript disabled: + +1. cleanup hooks, newest first (thread-safe functions start closing, async + cleanup hooks start); +2. queued async work cancelled; +3. the loop runs until in-flight work, thread-safe functions and async cleanup + hooks are done; +4. references and instance data finalized; +5. the module cache released and the host detached from the context. + +The embedder closes its own handles on the loop first. Must be called before +`JS_FreeContext()`. The full order is described in +[architecture.md](architecture.md#teardown). + +### Loading addons + +#### `qjsnapi_load_addon` + +```c +int qjsnapi_load_addon(qjsnapi_host *host, const char *path, JSValue *exports); +``` + +Loads a `.node` shared library and runs its Node-API initializer. + +- Returns `0` and stores a **new reference** to the exports in `*exports`; the + caller frees it. +- Returns `-1` with a JavaScript exception pending on the context. Its `code` + property is `MODULE_NOT_FOUND` (the path cannot be resolved) or + `ERR_DLOPEN_FAILED` (the library cannot be opened, does not register a + module, or needs a Node-API version above 10). A legacy module registered + without an init function fails with `Module has no declared entry point.` + and no code, as in Node.js. An exception thrown by the initializer is left + pending as it is. +- Like `process.dlopen`, **every call runs the initializer again** with a new + env and returns new exports. Caching by path is the module loader's job. +- Fails while the host is being destroyed. + +The entry point is resolved as described in +[architecture.md](architecture.md#loading-addons). + +#### `qjsnapi_init_static_addon` + +```c +int qjsnapi_init_static_addon(qjsnapi_host *host, const char *name, + napi_addon_register_func init, + int32_t module_api_version, JSValue *exports); +``` + +Runs the initializer of an addon **linked statically** into the embedder, as +if it had been loaded from `name`. `module_api_version` follows the +`node_api_module_get_api_version_v1` rules: `0` selects the default (8), a +value above 10 fails. Unlike `qjsnapi_load_addon`, the exports are **cached by +name**: a second call with the same name returns a new reference to the same +exports object without running `init` again. `node_api_get_module_file_name` +reports `name` for such an addon. + +### Buffer and versions + +#### `qjsnapi_host_get_buffer` + +```c +JSValue qjsnapi_host_get_buffer(qjsnapi_host *host); +``` + +The minimal Node.js `Buffer` constructor used by `napi_create_buffer*` +(`Buffer.from`, `alloc`, `toString`, ...; see +[buffers](node-api/node-specific.md#buffers)). The library **does not install it +as a global**: the embedder decides where it is visible (the executable sets +`globalThis.Buffer` and `require('buffer')`). Returns a new reference. + +#### `qjsnapi_node_version` + +```c +const napi_node_version *qjsnapi_node_version(void); +``` + +What `napi_get_node_version` reports: `22.23.4`, the Node.js release whose +Node-API behaviour is reproduced, with release name `"quickjs-napi"`. A host +that provides `process` should report the same in `process.version`. + +#### `qjsnapi_napi_version` + +```c +uint32_t qjsnapi_napi_version(void); +``` + +The highest Node-API version supported by this build (`10`), the value of +`napi_get_version`. + +### Finalizers and weak references + +#### `qjsnapi_host_run_finalizers` + +```c +size_t qjsnapi_host_run_finalizers(qjsnapi_host *host); +``` + +Runs the queued finalizers of every env (objects collected by the GC that +have a `napi_wrap`, `napi_add_finalizer`, external value, external +ArrayBuffer or external Buffer finalizer) and returns how many ran. The +library's `uv_check` handle already calls it once per loop iteration, so an +embedder that runs the host's loop does not need to; an embedder with its own +scheduling calls it outside of any JavaScript call. Finalizers still queued at +`qjsnapi_host_destroy` run then, with JavaScript disabled. + +#### `qjsnapi_host_has_pending_finalizers` + +```c +int qjsnapi_host_has_pending_finalizers(qjsnapi_host *host); +``` + +Non-zero while finalizers are queued: an event loop that decides itself when +to stop must not exit yet. + +#### `qjsnapi_host_clear_kept_objects` + +```c +void qjsnapi_host_clear_kept_objects(qjsnapi_host *host); +``` + +Releases the *kept objects*: the targets of references that became weak, +held strongly until now to reproduce V8's "alive until the next GC" (see +[architecture.md](architecture.md#kept-objects)). The library clears the list +at each of its own checkpoints. The embedder calls it **at the end of each +macrotask it runs itself** (a timer, an I/O callback) and **before an +explicit garbage collection** (`JS_RunGC`), otherwise weakly referenced +objects are collected later than expected. + +### Callbacks of the embedder + +#### `qjsnapi_host_set_uncaught_handler` + +```c +typedef void (*qjsnapi_uncaught_fn)(qjsnapi_host *host, JSContext *ctx, + JSValue exception, void *opaque); +void qjsnapi_host_set_uncaught_handler(qjsnapi_host *host, + qjsnapi_uncaught_fn fn, void *opaque); +``` + +Called with an exception that no JavaScript frame can catch: thrown by a +finalizer, an async work `complete` callback, a thread-safe function's +`call_js_cb`, a promise job run by the default checkpoint, or passed to +`napi_fatal_exception`. Node.js emits `process.on('uncaughtException')` or +exits. **The handler takes ownership of `exception`.** Without a handler, and +always during `qjsnapi_host_destroy`, the exception is printed on stderr +(`quickjs-napi: uncaught exception in a Node-API callback: ...`) and dropped. + +#### `qjsnapi_host_set_checkpoint` + +```c +typedef void (*qjsnapi_checkpoint_fn)(qjsnapi_host *host, JSContext *ctx, + void *opaque); +void qjsnapi_host_set_checkpoint(qjsnapi_host *host, qjsnapi_checkpoint_fn fn, + void *opaque); +``` + +Called after native code entered from the loop (async work completion, +thread-safe function calls, finalizers) and when the outermost callback scope +closes with no JavaScript below it: where Node.js runs its tick and microtask +queues and reports unhandled rejections. The default runs the pending promise +jobs (`JS_ExecutePendingJob`) and reports their exceptions to the uncaught +handler. An embedder with a `process.nextTick` queue or rejection tracking +installs its own (the executable does: `host_checkpoint` in `host/main.c`). + +#### `qjsnapi_host_set_force_uncaught_exceptions_policy` + +```c +void qjsnapi_host_set_force_uncaught_exceptions_policy(qjsnapi_host *host, + int force); +``` + +Node's `--force-node-api-uncaught-exceptions-policy` (default off). When off, +an exception thrown by a thread-safe function callback of an addon built for +Node-API < 10 becomes a `DEP0168` deprecation warning instead of an uncaught +exception. When on, it is always an uncaught exception. + +## Embedder responsibilities + +| Responsibility | How | +|---|---| +| Run the loop | `uv_run(qjsnapi_host_get_loop(host), ...)`; it runs async work completions, thread-safe function calls and queued finalizers. | +| Report uncaught exceptions | `qjsnapi_host_set_uncaught_handler`. | +| Drain the embedder's own queues | `qjsnapi_host_set_checkpoint` (microtasks, `nextTick`, unhandled rejections). | +| End macrotasks | `qjsnapi_host_clear_kept_objects` after each macrotask it runs itself, and before `JS_RunGC`. | +| Expose `Buffer` | `qjsnapi_host_get_buffer`, if scripts should see it. | +| Cache modules | `qjsnapi_load_addon` never caches; `require` does. | +| Tear down in order | close the embedder's handles, `qjsnapi_host_destroy`, then `JS_FreeContext`, `JS_FreeRuntime`. | +| Export the symbols | addons resolve `napi_*` and `uv_*` from the process (see below). | + +## Linking + +Addons do not link against the library: they find `napi_*` and `uv_*` in the +process. The executable that embeds the library must therefore **export** +them: + +| Platform | What is needed | +|---|---| +| Linux, BSD | link the library as a whole archive and export dynamic symbols (`--export-dynamic`, CMake `ENABLE_EXPORTS`). | +| macOS | whole archive (`-force_load`); addons are linked with `-undefined dynamic_lookup`. | +| Windows (MinGW) | whole archive; the definitions carry `__declspec(dllexport)` (`NAPI_EXTERN`; libuv is built with `BUILDING_UV_SHARED`). node-gyp addons import from `node.exe` and are redirected to the running process by node-gyp's delay-load hook. | + +`CMakeLists.txt` does all of this for the `quickjs-napi` target; an embedder +can copy that setup. `tools/check_exports.py ` verifies that every +Node-API function is exported. + +Link with `uv_a` (libuv) and the QuickJS library the headers in `include/` +were taken from. diff --git a/doc/host.md b/doc/host.md new file mode 100644 index 0000000..c18172a --- /dev/null +++ b/doc/host.md @@ -0,0 +1,191 @@ +# The `quickjs-napi` executable + +`quickjs-napi` is a small Node.js-like runtime built on the library. It runs +CommonJS scripts, loads `.node` addons with `require`, and provides the subset +of Node.js that addon packages and their tests need. It is also the reference +embedder of the library ([embedding.md](embedding.md)). + +Sources: `host/main.c` (command line, event loop, natives), +`host/bootstrap.js` (module loader, `process`, builtin modules; embedded in +the executable at build time by `cmake/embed.cmake`) and `host/spawn.c` +(child processes). + +- [Command line](#command-line) +- [Modules](#modules) +- [Globals](#globals) +- [Builtin modules](#builtin-modules) +- [Event loop](#event-loop) +- [Errors and exit](#errors-and-exit) +- [Not supported](#not-supported) + +## Command line + +```sh +quickjs-napi [options] script.js [args...] +quickjs-napi [options] -e [args...] +``` + +| Option | Effect | +|---|---| +| `-e`, `--eval ` | run `code` instead of a script; `process.argv` is `[execPath, args...]` | +| `-r`, `--require ` | load the module before the script; repeatable | +| `--force-node-api-uncaught-exceptions-policy[=true\|false]` | report exceptions from thread-safe function callbacks of Node-API < 10 addons as uncaught instead of a `DEP0168` warning (see [async.md](node-api/async.md#exceptions-in-call_js_cb)) | +| `--no-force-node-api-uncaught-exceptions-policy` | the default | +| `--expose-gc` | accepted and ignored: `gc()` is always defined | + +- `NODE_OPTIONS` is read first, with the same options separated by spaces. + Options only Node.js knows are **ignored** there, because the variable is + shared with Node.js (a test that sets `NODE_OPTIONS=--max-old-space-size=…` + for its children still works). +- On the command line an unknown option exits with code **9**, as in Node.js. +- Without a script or `-e`, the usage is printed and the exit code is 2. + +Examples: + +```sh +quickjs-napi app.js --verbose +quickjs-napi -e "console.log(require('./build/Release/addon.node').hello())" +quickjs-napi -r ./setup.js test.js +NODE_OPTIONS="--require ./setup.js" quickjs-napi test.js +``` + +## Modules + +The script runs as a **CommonJS module**: `require`, `module`, `exports`, +`__filename` and `__dirname` are defined as in Node.js. + +`require(id)` resolves like Node.js for what addon packages use: + +1. builtin modules (`require('buffer')`, ...); +2. relative (`./`, `../`) and absolute paths, trying the exact name, then + the extensions `.js`, `.json`, `.node`; +3. directories: `package.json` `"main"`, then `index.js`, `index.json`, + `index.node`; +4. `node_modules` directories, from the requiring module's directory up to the + root. + +| Extension | Loaded as | +|---|---| +| `.js` | CommonJS module, wrapped in a function like Node.js | +| `.json` | parsed JSON | +| `.node` | Node-API addon through [`qjsnapi_load_addon`](embedding.md#qjsnapi_load_addon) | + +Modules are cached by resolved path (`require.cache`); deleting a cache entry +and requiring the addon again runs its initializer again with a new env, like +`process.dlopen`. + +`module.registerBuiltin(name, exports)` is a quickjs-napi extension that lets +a script provide a builtin module (the test harnesses use it to provide +`assert`). + +## Globals + +| Global | Notes | +|---|---| +| `process` | `argv`, `env` (the real environment, passed to children), `platform`, `execPath`, `version` (`v22.23.4`, the Node.js release whose Node-API behaviour is reproduced), `release.name` (`quickjs-napi`), `versions.quickjs`, `versions.napi`, `exitCode`, `exit()`, `cwd()`, `nextTick()`, `on`/`once`/`off`/`addListener`/`removeListener`/`listeners`/`emit` for `exit`, `beforeExit`, `uncaughtException` and `unhandledRejection` | +| `global` | `globalThis` | +| `gc()` | runs the QuickJS GC twice (cycles are collected after weak entries are dropped) and clears the kept objects | +| `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `setImmediate`, `clearImmediate`, `queueMicrotask` | timers return objects with `ref()`, `unref()`, `hasRef()` | +| `Buffer` | the library's minimal Buffer ([node-specific.md](node-api/node-specific.md#buffers)) | +| `console` | `log` from quickjs-libc, plus `error`, `warn`, `info` | +| `print`, `scriptArgs` | quickjs-libc helpers | + +`process.versions.node` is deliberately **not** set, so that packages do not +take quickjs-napi for Node.js itself. + +## Builtin modules + +Minimal subsets, providing what addon packages and the test suites use: + +| Module | Provides | +|---|---| +| `module` | `builtinModules`, `createRequire`, `registerBuiltin` | +| `timers` | the timer functions | +| `timers/promises` | `setTimeout`, `setImmediate` returning promises | +| `buffer` | `Buffer`, `kMaxLength` | +| `util` | `promisify`, `types` (`isArrayBuffer`, `isSharedArrayBuffer`, `isAnyArrayBuffer`, `isArrayBufferView`, `isTypedArray`, `isDataView`, `isDate`, `isPromise`, `isRegExp`, `isNativeError`, ...) | +| `url` | `pathToFileURL`, `fileURLToPath` | +| `vm` | `runInNewContext(code)`: evaluates in a new realm of the same runtime | +| `child_process` | `spawnSync` and `spawn` (below) | +| `events` | a minimal `EventEmitter` | + +### `child_process` + +Children are started directly, **without a shell**, with libuv's `uv_spawn` +(`host/spawn.c`): + +- `spawnSync(file, args, options)` runs the child on a private libuv loop + until it exits and its pipes are drained. Options: `env`, `cwd`, `stdio` + (`'pipe'`, `'inherit'`, `'ignore'`), `input`, `encoding`, `timeout` (the + child is killed with `killSignal`, `SIGTERM` by default, and `error.code` is + `ETIMEDOUT`). The result has `pid`, `status`, `signal`, `stdout`, `stderr`, + `output` and `error` (`ENOENT` when the program does not exist). +- `spawn(file, args, options)` runs the child on the main loop and returns a + `ChildProcess`-like emitter: `stdout`/`stderr` streams with `data` events + and `setEncoding`, then `exit` and `close` events, `kill(signal)`, and an + `error` event when it cannot start. An asynchronous child's stdin is never a + pipe: it reads end-of-file. + +Every child of the test suites is the same executable (`process.execPath`), so +the tests that spawn processes run on every platform. + +## Event loop + +The executable runs the host's libuv loop (`uv_run`) until nothing referenced +is left, then emits `beforeExit` (whose listeners may schedule more work, in +which case the loop runs again), then `exit`. + +```mermaid +flowchart LR + T["timers phase
g_timer: due JS timers,
one at a time"] --> P["poll (I/O)
async work completions,
thread-safe functions,
child processes"] + P --> C["check phase
g_check: immediates queued before it started
library: queued finalizers"] + C --> T + CB["after every callback:
checkpoint"] -.-> T + CB -.-> P + CB -.-> C +``` + +| Handle | Purpose | +|---|---| +| `g_timer` (`uv_timer_t`) | armed by `bootstrap.js` for the earliest JavaScript timer; referenced only while a referenced timer exists | +| `g_check` (`uv_check_t`, unreferenced) | runs the immediates queued before the check phase began, one at a time | +| `g_idle` (`uv_idle_t`) | active while immediates are queued (referenced only for referenced ones), so the poll phase does not block | +| library handles | queued finalizers, async work, thread-safe functions ([architecture.md](architecture.md#the-event-loop)) | + +After **every** callback (a timer, an immediate, an I/O event, a Node-API +callback from the loop) a **checkpoint** runs: the promise jobs and +`process.nextTick` callbacks, then the unhandled rejections, repeated until +both are empty. The same function is installed as the library's checkpoint +(`qjsnapi_host_set_checkpoint`), so Node-API callbacks behave like Node.js +macrotasks. + +## Errors and exit + +- An exception that no frame catches (thrown by a timer, a microtask, a + Node-API finalizer or callback) goes to `process.on('uncaughtException')` + listeners; without listeners the error is printed and the process exits + with code **1**. +- An unhandled promise rejection goes to `process.on('unhandledRejection')`; + without listeners it is treated as an uncaught exception (Node.js default + `--unhandled-rejections=throw`). +- At the normal end of the script, `beforeExit` and `exit` are emitted and the + host is **destroyed**: cleanup hooks, then finalizers + ([architecture.md](architecture.md#teardown)). The exit code is + `process.exitCode` (0 by default). +- `process.exit(code)` and fatal exceptions end the process **immediately**, + like Node.js: `exit` is emitted, the thread pool is shut down, and no + cleanup hook or finalizer runs, nor is in-flight work waited for. +- `napi_fatal_error` prints `FATAL ERROR: ` and aborts + (`_exit(134)` on Windows). +- On Windows, stdout and stderr are in binary mode: `\n` is written as is, + as Node.js does, so a parent reading the pipe sees the same bytes on every + platform. + +## Not supported + +- ES modules (`import`, `.mjs`), `package.json` `"exports"` maps and + conditional exports; +- `worker_threads`, `async_hooks` (and therefore `AsyncLocalStorage`), + `domain`; +- most of the Node.js standard library (`fs`, `net`, `http`, `crypto`, ...): + only the modules listed above exist. diff --git a/doc/node-api/README.md b/doc/node-api/README.md new file mode 100644 index 0000000..dc4ad94 --- /dev/null +++ b/doc/node-api/README.md @@ -0,0 +1,325 @@ +# Node-API reference + +quickjs-napi implements all **155 functions** of Node-API version 10 +(`include/js_native_api.h` and `include/node_api.h`, the headers of Node.js +22). This reference documents what each function does **in quickjs-napi**: +its contract, the statuses it returns, and where its behaviour depends on the +QuickJS implementation. The upstream +[Node-API documentation](https://nodejs.org/docs/latest-v22.x/api/n-api.html) +remains the normative text; differences from Node.js are collected in +[compatibility.md](../compatibility.md). + +- [Conventions](#conventions) +- [Writing an addon](#writing-an-addon) +- [Function index](#function-index) + +| Area | File | Functions | +|---|---|---| +| Environment, versions, cleanup hooks, module registration | [environment.md](environment.md) | 10 | +| Primitives, numbers, booleans, coercion, arrays | [values.md](values.md) | 24 | +| Strings, property keys, symbols | [strings.md](strings.md) | 13 | +| Objects and properties | [objects.md](objects.md) | 19 | +| Functions, calls, classes, scripts | [functions.md](functions.md) | 7 | +| Errors and exceptions | [errors.md](errors.md) | 12 | +| Handle scopes | [scopes.md](scopes.md) | 5 | +| References, externals, wrap, finalizers, type tags, instance data | [lifetime.md](lifetime.md) | 16 | +| ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise | [binary-data.md](binary-data.md) | 25 | +| Buffer, async context, `napi_make_callback`, callback scopes | [node-specific.md](node-specific.md) | 12 | +| Async work, thread-safe functions, the event loop | [async.md](async.md) | 12 | + +## Conventions + +### Status codes and the last error + +Every function returns a `napi_status`. `napi_ok` means success; anything else +is a failure and is also recorded as the env's last error, which +`napi_get_last_error_info` returns with a message: + +| Status | Message | Typical cause | +|---|---|---| +| `napi_ok` | | success | +| `napi_invalid_arg` | Invalid argument | a `NULL` pointer argument, an out-of-range enum, a value of the wrong kind where no specific status exists | +| `napi_object_expected` | An object was expected | the receiver is `null`/`undefined` (a `TypeError` is then pending), or not an object | +| `napi_string_expected` | A string was expected | | +| `napi_name_expected` | A string or symbol was expected | property keys, symbol descriptions | +| `napi_function_expected` | A function was expected | | +| `napi_number_expected` | A number was expected | getters never coerce | +| `napi_boolean_expected` | A boolean was expected | | +| `napi_array_expected` | An array was expected | | +| `napi_generic_failure` | Unknown failure | out of memory, or a failed engine operation without a JS exception | +| `napi_pending_exception` | An exception is pending | JavaScript threw during the call, or an exception was already pending | +| `napi_cancelled` | The async work item was cancelled | passed to `complete` | +| `napi_escape_called_twice` | napi_escape_handle already called on scope | | +| `napi_handle_scope_mismatch` | Invalid handle scope usage | closing a scope that is not the innermost one | +| `napi_callback_scope_mismatch` | Invalid callback scope usage | | +| `napi_queue_full` | Thread-safe function queue is full | non-blocking call on a full queue | +| `napi_closing` | Thread-safe function handle is closing | | +| `napi_bigint_expected` | A bigint was expected | | +| `napi_date_expected` | A date was expected | | +| `napi_arraybuffer_expected` | An arraybuffer was expected | | +| `napi_detachable_arraybuffer_expected` | A detachable arraybuffer was expected | | +| `napi_would_deadlock` | Main thread would deadlock | never returned (as in Node.js 22) | +| `napi_no_external_buffers_allowed` | External buffers are not allowed | never returned: external buffers are always allowed | +| `napi_cannot_run_js` | Cannot run JavaScript | the env is tearing down (modules built for Node-API ≥ 10) | + +### Functions that run JavaScript + +Some functions may call into JavaScript (getters, setters, `valueOf`, +proxies, user callbacks). These **refuse to start** when an exception is +already pending (`napi_pending_exception`) or when the env can no longer run +JavaScript (`napi_cannot_run_js`, or `napi_pending_exception` for modules +built for Node-API < 10). They are marked **JS** in the +[function index](#function-index). The other functions only touch C +bookkeeping or create values, and work even with an exception pending: this +is what lets an addon build an error message while an exception is pending. + +When JavaScript throws during a call, the function returns +`napi_pending_exception` and **the exception stays pending**, exactly as in +Node.js. Returning from the native callback then propagates it to the +JavaScript caller. Use `napi_is_exception_pending` and +`napi_get_and_clear_last_exception` to handle it in C. + +### Basic env + +Functions whose first parameter is `node_api_basic_env` (cleanup hooks, +instance data, `napi_delete_reference`, `napi_adjust_external_memory`, +`napi_get_uv_event_loop`, ...) may be called from a *basic finalizer* +(`node_api_basic_finalize`). In quickjs-napi every finalizer, basic or not, +runs **outside the garbage collector** (from the event loop or at teardown), +so calling other functions from a basic finalizer never causes the fatal +error Node.js raises; the distinction is kept for source compatibility. + +### Values and threads + +- A `napi_value` is valid until the handle scope it was created in is closed. + Values created in a native callback are released when the callback returns, + unless they are returned, escaped, or kept in a `napi_ref`. +- Every function except the thread-safe function ones + (`napi_call_threadsafe_function`, `napi_acquire_threadsafe_function`, + `napi_release_threadsafe_function`, + `napi_get_threadsafe_function_context`) must be called on the thread that + runs the event loop. `execute` callbacks of async work run on the thread + pool and must not call Node-API functions that take an env. + +## Writing an addon + +Addons are written exactly as for Node.js. A minimal C addon: + +```c +#include + +#define NAPI_CALL(env, call) \ + do { \ + if ((call) != napi_ok) { \ + const napi_extended_error_info *info; \ + bool pending; \ + napi_get_last_error_info((env), &info); \ + napi_is_exception_pending((env), &pending); \ + if (!pending) \ + napi_throw_error((env), NULL, info->error_message \ + ? info->error_message \ + : "Node-API call failed"); \ + return NULL; \ + } \ + } while (0) + +static napi_value Add(napi_env env, napi_callback_info info) { + size_t argc = 2; + napi_value argv[2]; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + double a, b; + NAPI_CALL(env, napi_get_value_double(env, argv[0], &a)); + NAPI_CALL(env, napi_get_value_double(env, argv[1], &b)); + napi_value sum; + NAPI_CALL(env, napi_create_double(env, a + b, &sum)); + return sum; +} + +NAPI_MODULE_INIT(/* napi_env env, napi_value exports */) { + napi_property_descriptor desc = {"add", NULL, Add, NULL, NULL, NULL, + napi_default, NULL}; + NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); + return exports; +} +``` + +Build it with node-gyp, cmake-js or any toolchain that produces a Node.js +addon, then: + +```sh +quickjs-napi -e "console.log(require('./build/Release/addon.node').add(2, 3))" +``` + +The same binary loads in Node.js. node-addon-api (C++) and napi-rs (Rust) +addons work the same way; the node-addon-api 8.9.2 test suite runs in CI +([testing.md](../testing.md)). + +The module API version is chosen by the addon at build time (`NAPI_VERSION`, +exported through `node_api_module_get_api_version_v1`). It is 8 when the +addon does not declare one, and changes a few behaviours: which values +`napi_create_reference` accepts, the status of +[functions that run JavaScript](#functions-that-run-javascript) during +teardown, and the [thread-safe function exception policy](async.md#exceptions-in-call_js_cb). + +## Function index + +**JS**: the function may run JavaScript and refuses to start with an exception +pending (see [above](#functions-that-run-javascript)). + +| Function | | Reference | +|---|---|---| +| `napi_acquire_threadsafe_function` | | [async.md](async.md#napi_acquire_threadsafe_function) | +| `napi_add_async_cleanup_hook` | | [environment.md](environment.md#napi_add_async_cleanup_hook) | +| `napi_add_env_cleanup_hook` | | [environment.md](environment.md#napi_add_env_cleanup_hook) | +| `napi_add_finalizer` | | [lifetime.md](lifetime.md#napi_add_finalizer) | +| `napi_adjust_external_memory` | | [lifetime.md](lifetime.md#napi_adjust_external_memory) | +| `napi_async_destroy` | | [node-specific.md](node-specific.md#napi_async_destroy) | +| `napi_async_init` | | [node-specific.md](node-specific.md#napi_async_init) | +| `napi_call_function` | JS | [functions.md](functions.md#napi_call_function) | +| `napi_call_threadsafe_function` | | [async.md](async.md#napi_call_threadsafe_function) | +| `napi_cancel_async_work` | | [async.md](async.md#napi_cancel_async_work) | +| `napi_check_object_type_tag` | JS | [lifetime.md](lifetime.md#napi_check_object_type_tag) | +| `napi_close_callback_scope` | | [node-specific.md](node-specific.md#napi_close_callback_scope) | +| `napi_close_escapable_handle_scope` | | [scopes.md](scopes.md#napi_close_escapable_handle_scope) | +| `napi_close_handle_scope` | | [scopes.md](scopes.md#napi_close_handle_scope) | +| `napi_coerce_to_bool` | JS | [values.md](values.md#napi_coerce_to_bool) | +| `napi_coerce_to_number` | JS | [values.md](values.md#napi_coerce_to_number) | +| `napi_coerce_to_object` | JS | [values.md](values.md#napi_coerce_to_object) | +| `napi_coerce_to_string` | JS | [values.md](values.md#napi_coerce_to_string) | +| `napi_create_array` | | [values.md](values.md#napi_create_array) | +| `napi_create_array_with_length` | | [values.md](values.md#napi_create_array_with_length) | +| `napi_create_arraybuffer` | JS | [binary-data.md](binary-data.md#napi_create_arraybuffer) | +| `napi_create_async_work` | | [async.md](async.md#napi_create_async_work) | +| `napi_create_bigint_int64` | | [binary-data.md](binary-data.md#napi_create_bigint_int64) | +| `napi_create_bigint_uint64` | | [binary-data.md](binary-data.md#napi_create_bigint_uint64) | +| `napi_create_bigint_words` | JS | [binary-data.md](binary-data.md#napi_create_bigint_words) | +| `napi_create_buffer` | JS | [node-specific.md](node-specific.md#napi_create_buffer) | +| `napi_create_buffer_copy` | JS | [node-specific.md](node-specific.md#napi_create_buffer_copy) | +| `napi_create_dataview` | JS | [binary-data.md](binary-data.md#napi_create_dataview) | +| `napi_create_date` | JS | [binary-data.md](binary-data.md#napi_create_date) | +| `napi_create_double` | | [values.md](values.md#napi_create_double) | +| `napi_create_error` | | [errors.md](errors.md#napi_create_error) | +| `napi_create_external` | JS | [lifetime.md](lifetime.md#napi_create_external) | +| `napi_create_external_arraybuffer` | JS | [binary-data.md](binary-data.md#napi_create_external_arraybuffer) | +| `napi_create_external_buffer` | JS | [node-specific.md](node-specific.md#napi_create_external_buffer) | +| `napi_create_function` | JS | [functions.md](functions.md#napi_create_function) | +| `napi_create_int32` | | [values.md](values.md#napi_create_int32) | +| `napi_create_int64` | | [values.md](values.md#napi_create_int64) | +| `napi_create_object` | | [values.md](values.md#napi_create_object) | +| `napi_create_promise` | JS | [binary-data.md](binary-data.md#napi_create_promise) | +| `napi_create_range_error` | | [errors.md](errors.md#napi_create_range_error) | +| `napi_create_reference` | | [lifetime.md](lifetime.md#napi_create_reference) | +| `napi_create_string_latin1` | | [strings.md](strings.md#napi_create_string_latin1) | +| `napi_create_string_utf16` | | [strings.md](strings.md#napi_create_string_utf16) | +| `napi_create_string_utf8` | | [strings.md](strings.md#napi_create_string_utf8) | +| `napi_create_symbol` | | [strings.md](strings.md#napi_create_symbol) | +| `napi_create_threadsafe_function` | | [async.md](async.md#napi_create_threadsafe_function) | +| `napi_create_type_error` | | [errors.md](errors.md#napi_create_type_error) | +| `napi_create_typedarray` | JS | [binary-data.md](binary-data.md#napi_create_typedarray) | +| `napi_create_uint32` | | [values.md](values.md#napi_create_uint32) | +| `napi_define_class` | JS | [functions.md](functions.md#napi_define_class) | +| `napi_define_properties` | JS | [objects.md](objects.md#napi_define_properties) | +| `napi_delete_async_work` | | [async.md](async.md#napi_delete_async_work) | +| `napi_delete_element` | JS | [objects.md](objects.md#napi_delete_element) | +| `napi_delete_property` | JS | [objects.md](objects.md#napi_delete_property) | +| `napi_delete_reference` | | [lifetime.md](lifetime.md#napi_delete_reference) | +| `napi_detach_arraybuffer` | | [binary-data.md](binary-data.md#napi_detach_arraybuffer) | +| `napi_escape_handle` | | [scopes.md](scopes.md#napi_escape_handle) | +| `napi_fatal_error` | | [environment.md](environment.md#napi_fatal_error) | +| `napi_fatal_exception` | JS | [node-specific.md](node-specific.md#napi_fatal_exception) | +| `napi_get_all_property_names` | JS | [objects.md](objects.md#napi_get_all_property_names) | +| `napi_get_and_clear_last_exception` | | [errors.md](errors.md#napi_get_and_clear_last_exception) | +| `napi_get_array_length` | JS | [values.md](values.md#napi_get_array_length) | +| `napi_get_arraybuffer_info` | | [binary-data.md](binary-data.md#napi_get_arraybuffer_info) | +| `napi_get_boolean` | | [values.md](values.md#napi_get_boolean) | +| `napi_get_buffer_info` | | [node-specific.md](node-specific.md#napi_get_buffer_info) | +| `napi_get_cb_info` | | [functions.md](functions.md#napi_get_cb_info) | +| `napi_get_dataview_info` | | [binary-data.md](binary-data.md#napi_get_dataview_info) | +| `napi_get_date_value` | JS | [binary-data.md](binary-data.md#napi_get_date_value) | +| `napi_get_element` | JS | [objects.md](objects.md#napi_get_element) | +| `napi_get_global` | | [values.md](values.md#napi_get_global) | +| `napi_get_instance_data` | | [lifetime.md](lifetime.md#napi_get_instance_data) | +| `napi_get_last_error_info` | | [environment.md](environment.md#napi_get_last_error_info) | +| `napi_get_named_property` | JS | [objects.md](objects.md#napi_get_named_property) | +| `napi_get_new_target` | | [functions.md](functions.md#napi_get_new_target) | +| `napi_get_node_version` | | [environment.md](environment.md#napi_get_node_version) | +| `napi_get_null` | | [values.md](values.md#napi_get_null) | +| `napi_get_property` | JS | [objects.md](objects.md#napi_get_property) | +| `napi_get_property_names` | JS | [objects.md](objects.md#napi_get_property_names) | +| `napi_get_prototype` | JS | [objects.md](objects.md#napi_get_prototype) | +| `napi_get_reference_value` | | [lifetime.md](lifetime.md#napi_get_reference_value) | +| `napi_get_threadsafe_function_context` | | [async.md](async.md#napi_get_threadsafe_function_context) | +| `napi_get_typedarray_info` | | [binary-data.md](binary-data.md#napi_get_typedarray_info) | +| `napi_get_undefined` | | [values.md](values.md#napi_get_undefined) | +| `napi_get_uv_event_loop` | | [async.md](async.md#napi_get_uv_event_loop) | +| `napi_get_value_bigint_int64` | | [binary-data.md](binary-data.md#napi_get_value_bigint_int64) | +| `napi_get_value_bigint_uint64` | | [binary-data.md](binary-data.md#napi_get_value_bigint_uint64) | +| `napi_get_value_bigint_words` | | [binary-data.md](binary-data.md#napi_get_value_bigint_words) | +| `napi_get_value_bool` | | [values.md](values.md#napi_get_value_bool) | +| `napi_get_value_double` | | [values.md](values.md#napi_get_value_double) | +| `napi_get_value_external` | | [lifetime.md](lifetime.md#napi_get_value_external) | +| `napi_get_value_int32` | | [values.md](values.md#napi_get_value_int32) | +| `napi_get_value_int64` | | [values.md](values.md#napi_get_value_int64) | +| `napi_get_value_string_latin1` | | [strings.md](strings.md#napi_get_value_string_latin1) | +| `napi_get_value_string_utf16` | | [strings.md](strings.md#napi_get_value_string_utf16) | +| `napi_get_value_string_utf8` | | [strings.md](strings.md#napi_get_value_string_utf8) | +| `napi_get_value_uint32` | | [values.md](values.md#napi_get_value_uint32) | +| `napi_get_version` | | [environment.md](environment.md#napi_get_version) | +| `napi_has_element` | JS | [objects.md](objects.md#napi_has_element) | +| `napi_has_named_property` | JS | [objects.md](objects.md#napi_has_named_property) | +| `napi_has_own_property` | JS | [objects.md](objects.md#napi_has_own_property) | +| `napi_has_property` | JS | [objects.md](objects.md#napi_has_property) | +| `napi_instanceof` | JS | [objects.md](objects.md#napi_instanceof) | +| `napi_is_array` | | [values.md](values.md#napi_is_array) | +| `napi_is_arraybuffer` | | [binary-data.md](binary-data.md#napi_is_arraybuffer) | +| `napi_is_buffer` | | [node-specific.md](node-specific.md#napi_is_buffer) | +| `napi_is_dataview` | | [binary-data.md](binary-data.md#napi_is_dataview) | +| `napi_is_date` | | [binary-data.md](binary-data.md#napi_is_date) | +| `napi_is_detached_arraybuffer` | | [binary-data.md](binary-data.md#napi_is_detached_arraybuffer) | +| `napi_is_error` | | [errors.md](errors.md#napi_is_error) | +| `napi_is_exception_pending` | | [errors.md](errors.md#napi_is_exception_pending) | +| `napi_is_promise` | | [binary-data.md](binary-data.md#napi_is_promise) | +| `napi_is_typedarray` | | [binary-data.md](binary-data.md#napi_is_typedarray) | +| `napi_make_callback` | JS | [node-specific.md](node-specific.md#napi_make_callback) | +| `napi_module_register` | | [environment.md](environment.md#napi_module_register) | +| `napi_new_instance` | JS | [functions.md](functions.md#napi_new_instance) | +| `napi_object_freeze` | JS | [objects.md](objects.md#napi_object_freeze) | +| `napi_object_seal` | JS | [objects.md](objects.md#napi_object_seal) | +| `napi_open_callback_scope` | | [node-specific.md](node-specific.md#napi_open_callback_scope) | +| `napi_open_escapable_handle_scope` | | [scopes.md](scopes.md#napi_open_escapable_handle_scope) | +| `napi_open_handle_scope` | | [scopes.md](scopes.md#napi_open_handle_scope) | +| `napi_queue_async_work` | | [async.md](async.md#napi_queue_async_work) | +| `napi_ref_threadsafe_function` | | [async.md](async.md#napi_ref_threadsafe_function) | +| `napi_reference_ref` | | [lifetime.md](lifetime.md#napi_reference_ref) | +| `napi_reference_unref` | | [lifetime.md](lifetime.md#napi_reference_unref) | +| `napi_reject_deferred` | JS | [binary-data.md](binary-data.md#napi_reject_deferred) | +| `napi_release_threadsafe_function` | | [async.md](async.md#napi_release_threadsafe_function) | +| `napi_remove_async_cleanup_hook` | | [environment.md](environment.md#napi_remove_async_cleanup_hook) | +| `napi_remove_env_cleanup_hook` | | [environment.md](environment.md#napi_remove_env_cleanup_hook) | +| `napi_remove_wrap` | JS | [lifetime.md](lifetime.md#napi_remove_wrap) | +| `napi_resolve_deferred` | JS | [binary-data.md](binary-data.md#napi_resolve_deferred) | +| `napi_run_script` | JS | [functions.md](functions.md#napi_run_script) | +| `napi_set_element` | JS | [objects.md](objects.md#napi_set_element) | +| `napi_set_instance_data` | | [lifetime.md](lifetime.md#napi_set_instance_data) | +| `napi_set_named_property` | JS | [objects.md](objects.md#napi_set_named_property) | +| `napi_set_property` | JS | [objects.md](objects.md#napi_set_property) | +| `napi_strict_equals` | JS | [values.md](values.md#napi_strict_equals) | +| `napi_throw` | JS | [errors.md](errors.md#napi_throw) | +| `napi_throw_error` | JS | [errors.md](errors.md#napi_throw_error) | +| `napi_throw_range_error` | JS | [errors.md](errors.md#napi_throw_range_error) | +| `napi_throw_type_error` | JS | [errors.md](errors.md#napi_throw_type_error) | +| `napi_type_tag_object` | JS | [lifetime.md](lifetime.md#napi_type_tag_object) | +| `napi_typeof` | | [values.md](values.md#napi_typeof) | +| `napi_unref_threadsafe_function` | | [async.md](async.md#napi_unref_threadsafe_function) | +| `napi_unwrap` | JS | [lifetime.md](lifetime.md#napi_unwrap) | +| `napi_wrap` | JS | [lifetime.md](lifetime.md#napi_wrap) | +| `node_api_create_buffer_from_arraybuffer` | JS | [node-specific.md](node-specific.md#node_api_create_buffer_from_arraybuffer) | +| `node_api_create_external_string_latin1` | | [strings.md](strings.md#node_api_create_external_string_latin1) | +| `node_api_create_external_string_utf16` | | [strings.md](strings.md#node_api_create_external_string_utf16) | +| `node_api_create_property_key_latin1` | | [strings.md](strings.md#node_api_create_property_key_latin1) | +| `node_api_create_property_key_utf16` | | [strings.md](strings.md#node_api_create_property_key_utf16) | +| `node_api_create_property_key_utf8` | | [strings.md](strings.md#node_api_create_property_key_utf8) | +| `node_api_create_syntax_error` | | [errors.md](errors.md#node_api_create_syntax_error) | +| `node_api_get_module_file_name` | | [environment.md](environment.md#node_api_get_module_file_name) | +| `node_api_symbol_for` | | [strings.md](strings.md#node_api_symbol_for) | +| `node_api_throw_syntax_error` | JS | [errors.md](errors.md#node_api_throw_syntax_error) | diff --git a/doc/node-api/async.md b/doc/node-api/async.md new file mode 100644 index 0000000..b1a0e17 --- /dev/null +++ b/doc/node-api/async.md @@ -0,0 +1,286 @@ +# Async work, thread-safe functions and the event loop + +[Node-API reference](README.md) › Asynchronous APIs + +Implemented in `src/async.c`, `src/tsfn.c` and `src/loop.c`, on libuv 1.51. +How these objects sit on the loop, and how teardown waits for them, is +described in [architecture.md](../architecture.md#the-event-loop). + +| Group | Functions | +|---|---| +| Async work | [`napi_create_async_work`](#napi_create_async_work), [`napi_queue_async_work`](#napi_queue_async_work), [`napi_cancel_async_work`](#napi_cancel_async_work), [`napi_delete_async_work`](#napi_delete_async_work) | +| Thread-safe functions | [`napi_create_threadsafe_function`](#napi_create_threadsafe_function), [`napi_call_threadsafe_function`](#napi_call_threadsafe_function), [`napi_acquire_threadsafe_function`](#napi_acquire_threadsafe_function), [`napi_release_threadsafe_function`](#napi_release_threadsafe_function), [`napi_get_threadsafe_function_context`](#napi_get_threadsafe_function_context), [`napi_ref_threadsafe_function`](#napi_ref_threadsafe_function), [`napi_unref_threadsafe_function`](#napi_unref_threadsafe_function) | +| Event loop | [`napi_get_uv_event_loop`](#napi_get_uv_event_loop) | + +## Threads + +| Code | Runs on | +|---|---| +| `execute` of async work | a libuv thread-pool thread (`UV_THREADPOOL_SIZE` threads, 4 by default). Must not call Node-API functions that take an env. | +| `complete` of async work | the loop thread | +| `napi_call_threadsafe_function`, `napi_acquire_threadsafe_function`, `napi_release_threadsafe_function`, `napi_get_threadsafe_function_context` | any thread | +| `call_js_cb`, `thread_finalize_cb` of a thread-safe function | the loop thread | +| everything else | the loop thread | + +Every callback the loop thread runs (`complete`, `call_js_cb`, +`thread_finalize_cb`) gets a handle scope and a callback scope; on return, +a pending exception is reported as uncaught and the checkpoint runs +(microtasks, `process.nextTick` in the executable). + +--- + +## Async work + +Runs a C function on the thread pool, then a completion on the loop thread. + +```c +typedef struct { napi_async_work work; napi_deferred deferred; double input, output; } job; + +static void Execute(napi_env env, void *data) { /* thread pool */ + job *j = data; + j->output = expensive(j->input); /* no Node-API here */ +} + +static void Complete(napi_env env, napi_status status, void *data) { /* loop */ + job *j = data; + napi_value v; + if (status == napi_ok) { + napi_create_double(env, j->output, &v); + napi_resolve_deferred(env, j->deferred, v); + } else { /* napi_cancelled */ + napi_get_undefined(env, &v); + napi_reject_deferred(env, j->deferred, v); + } + napi_delete_async_work(env, j->work); + free(j); +} + +static napi_value Compute(napi_env env, napi_callback_info info) { + job *j = calloc(1, sizeof *j); + napi_value name, promise; + /* ... read the input into j->input ... */ + napi_create_string_utf8(env, "compute", NAPI_AUTO_LENGTH, &name); + napi_create_promise(env, &j->deferred, &promise); + napi_create_async_work(env, NULL, name, Execute, Complete, j, &j->work); + napi_queue_async_work(env, j->work); + return promise; +} +``` + +### `napi_create_async_work` + +```c +napi_status napi_create_async_work(napi_env env, napi_value async_resource, + napi_value async_resource_name, + napi_async_execute_callback execute, + napi_async_complete_callback complete, + void *data, napi_async_work *result); +``` + +Creates a work item; nothing runs until it is queued. `execute` is required, +`complete` is optional. `async_resource` (optional; `null`/`undefined` give +`napi_object_expected`) and `async_resource_name` (required; a symbol gives +`napi_string_expected`) are only validated: there is no `async_hooks`. + +The item belongs to the addon until `napi_delete_async_work`. Items never +deleted are freed at teardown. + +### `napi_queue_async_work` + +```c +napi_status napi_queue_async_work(node_api_basic_env env, + napi_async_work work); +``` + +Queues the item (`uv_queue_work`): `execute(env, data)` runs on a pool thread, +then `complete(env, status, data)` on the loop thread with `napi_ok`. The +queued item keeps the loop alive. + +- Queuing an item that is already queued, or queuing while the host is being + destroyed, returns `napi_generic_failure`. +- The item can be queued again once `complete` has started, including from + `complete` itself. + +### `napi_cancel_async_work` + +```c +napi_status napi_cancel_async_work(node_api_basic_env env, + napi_async_work work); +``` + +Cancels a queued item whose `execute` has not started (`uv_cancel`). +`complete` then still runs, with status `napi_cancelled`. When `execute` is +already running or done, cancellation fails with `napi_generic_failure`. + +### `napi_delete_async_work` + +```c +napi_status napi_delete_async_work(napi_env env, napi_async_work work); +``` + +Frees the item. Usually called from `complete`. Deleting an item that is +still queued is undefined behaviour in Node.js; here the item is only marked, +and freed after its `complete` has run. + +At teardown, queued items are cancelled, in-flight ones are waited for, and +their `complete` runs with JavaScript disabled, so the addon can still free +its data. + +## Thread-safe functions + +A thread-safe function lets any thread schedule a call to JavaScript on the +loop thread. It is a port of Node 22's implementation: a queue protected by a +mutex, a `uv_async_t` to wake the loop thread, and up to 1000 calls dispatched +per wake-up. Its life cycle is shown in +[architecture.md](../architecture.md#thread-safe-functions). + +```c +static void CallJs(napi_env env, napi_value js_cb, void *context, void *data) { + int *value = data; + if (env != NULL) { /* NULL when the function is being finalized */ + napi_value undefined, arg; + napi_get_undefined(env, &undefined); + napi_create_int32(env, *value, &arg); + napi_call_function(env, undefined, js_cb, 1, &arg, NULL); + } + free(value); +} + +/* loop thread */ +napi_create_threadsafe_function(env, js_callback, NULL, name, 0 /* unbounded */, + 1 /* this thread */, NULL, NULL, NULL, CallJs, + &tsfn); +/* worker thread */ +int *v = malloc(sizeof *v); *v = 42; +napi_call_threadsafe_function(tsfn, v, napi_tsfn_blocking); +napi_release_threadsafe_function(tsfn, napi_tsfn_release); +``` + +### `napi_create_threadsafe_function` + +```c +napi_status napi_create_threadsafe_function( + napi_env env, napi_value func, napi_value async_resource, + napi_value async_resource_name, size_t max_queue_size, + size_t initial_thread_count, void *thread_finalize_data, + napi_finalize thread_finalize_cb, void *context, + napi_threadsafe_function_call_js call_js_cb, + napi_threadsafe_function *result); +``` + +| Parameter | Meaning | +|---|---| +| `func` | JavaScript function passed to `call_js_cb` (kept with a strong reference); optional when `call_js_cb` is given, otherwise it must be a function (`napi_invalid_arg`) | +| `async_resource`, `async_resource_name` | validated only (no `async_hooks`); the name is required | +| `max_queue_size` | 0 for an unbounded queue; otherwise producers block (or get `napi_queue_full`) when it is full | +| `initial_thread_count` | number of threads using the function, at least 1 (`napi_invalid_arg` otherwise) | +| `thread_finalize_data`, `thread_finalize_cb` | `thread_finalize_cb(env, thread_finalize_data, context)` runs on the loop thread when the function is finalized | +| `context` | any pointer, passed to `call_js_cb` and `thread_finalize_cb` | +| `call_js_cb` | `call_js_cb(env, func, context, data)` for each queued item; without it, `func` is called with no arguments and `this = undefined` | + +The function starts **referenced**: it keeps the loop alive until it is +finalized or unreferenced. It registers an internal cleanup hook, so it is +closed at teardown. + +### `napi_call_threadsafe_function` + +```c +napi_status napi_call_threadsafe_function( + napi_threadsafe_function func, void *data, + napi_threadsafe_function_call_mode is_blocking); +``` + +Queues `data` for a call of `call_js_cb` on the loop thread. Callable from any +thread. + +| Result | When | +|---|---| +| `napi_ok` | queued | +| `napi_queue_full` | bounded queue full and `napi_tsfn_nonblocking` | +| (blocks) | bounded queue full and `napi_tsfn_blocking`: waits for room. Do not do this on the loop thread: it would deadlock (`napi_would_deadlock` is not returned, as in Node.js 22) | +| `napi_closing` | the function is closing (aborted, or finalized at teardown); this call also releases the caller's thread count, so the caller must not call `napi_release_threadsafe_function` afterwards | +| `napi_invalid_arg` | `func` is `NULL`, or it is closing and no thread holds it any more | + +### `napi_acquire_threadsafe_function` + +```c +napi_status napi_acquire_threadsafe_function(napi_threadsafe_function func); +``` + +Increments the thread count, before handing the function to another thread. +`napi_closing` if it is already closing. + +### `napi_release_threadsafe_function` + +```c +napi_status napi_release_threadsafe_function( + napi_threadsafe_function func, + napi_threadsafe_function_release_mode mode); +``` + +Decrements the thread count. When it reaches 0 the function closes once its +queue is drained. With `napi_tsfn_abort` it closes **now**: blocked producers +wake up, further calls get `napi_closing`, and items still queued are handed +to `call_js_cb` with `env == NULL` (and `func == NULL`) so that their data can +be freed. `napi_invalid_arg` when the count is already 0. + +### `napi_get_threadsafe_function_context` + +```c +napi_status napi_get_threadsafe_function_context(napi_threadsafe_function func, + void **result); +``` + +Stores the `context` given at creation. Callable from any thread. +`napi_invalid_arg` for `NULL` arguments (Node.js aborts). + +### `napi_ref_threadsafe_function` + +```c +napi_status napi_ref_threadsafe_function(node_api_basic_env env, + napi_threadsafe_function func); +``` + +Makes the function keep the loop alive again (`uv_ref` on its async handle). +Loop thread only. + +### `napi_unref_threadsafe_function` + +```c +napi_status napi_unref_threadsafe_function(node_api_basic_env env, + napi_threadsafe_function func); +``` + +Lets the loop exit while the function is still open (`uv_unref`): useful for a +background producer that should not keep the process running. Loop thread +only. + +### Exceptions in `call_js_cb` + +An exception left pending by `call_js_cb` (or `thread_finalize_cb`) has no +JavaScript caller. For modules built for **Node-API ≥ 10** it is reported as +uncaught (`process.on('uncaughtException')`). For older modules it is +dropped with a one-time `DEP0168` deprecation warning on stderr, as in +Node.js, unless the host forces the policy +(`--force-node-api-uncaught-exceptions-policy`, or +[`qjsnapi_host_set_force_uncaught_exceptions_policy`](../embedding.md#qjsnapi_host_set_force_uncaught_exceptions_policy)). + +Exceptions from async work `complete` callbacks and from finalizers are always +reported as uncaught. + +## Event loop + +### `napi_get_uv_event_loop` + +```c +napi_status napi_get_uv_event_loop(node_api_basic_env env, + struct uv_loop_s **loop); +``` + +Stores the libuv loop of the host: the one the embedder runs and the +executable runs until nothing referenced is left. Addons may add their own +handles to it (timers, sockets, `uv_async_t`); they must close them before +teardown ends, typically from an +[async cleanup hook](environment.md#napi_add_async_cleanup_hook). The +executable exports every `uv_*` function, so addons built with node-gyp's +`uv.h` link against it like against `node`. diff --git a/doc/node-api/binary-data.md b/doc/node-api/binary-data.md new file mode 100644 index 0000000..9c00201 --- /dev/null +++ b/doc/node-api/binary-data.md @@ -0,0 +1,387 @@ +# ArrayBuffer, TypedArray, DataView, BigInt, Date, Promise + +[Node-API reference](README.md) › Binary data and builtins + +Implemented in `src/builtins.c`. Semantics follow Node.js 22.23 / V8 and are +checked against Node.js by `test/js/test_binary.js`. + +| Group | Functions | +|---|---| +| ArrayBuffer | [`napi_create_arraybuffer`](#napi_create_arraybuffer), [`napi_create_external_arraybuffer`](#napi_create_external_arraybuffer), [`napi_is_arraybuffer`](#napi_is_arraybuffer), [`napi_get_arraybuffer_info`](#napi_get_arraybuffer_info), [`napi_detach_arraybuffer`](#napi_detach_arraybuffer), [`napi_is_detached_arraybuffer`](#napi_is_detached_arraybuffer) | +| TypedArray | [`napi_create_typedarray`](#napi_create_typedarray), [`napi_is_typedarray`](#napi_is_typedarray), [`napi_get_typedarray_info`](#napi_get_typedarray_info) | +| DataView | [`napi_create_dataview`](#napi_create_dataview), [`napi_is_dataview`](#napi_is_dataview), [`napi_get_dataview_info`](#napi_get_dataview_info) | +| BigInt | [`napi_create_bigint_int64`](#napi_create_bigint_int64), [`napi_create_bigint_uint64`](#napi_create_bigint_uint64), [`napi_create_bigint_words`](#napi_create_bigint_words), [`napi_get_value_bigint_int64`](#napi_get_value_bigint_int64), [`napi_get_value_bigint_uint64`](#napi_get_value_bigint_uint64), [`napi_get_value_bigint_words`](#napi_get_value_bigint_words) | +| Date | [`napi_create_date`](#napi_create_date), [`napi_is_date`](#napi_is_date), [`napi_get_date_value`](#napi_get_date_value) | +| Promise | [`napi_create_promise`](#napi_create_promise), [`napi_resolve_deferred`](#napi_resolve_deferred), [`napi_reject_deferred`](#napi_reject_deferred), [`napi_is_promise`](#napi_is_promise) | + +## Implementation notes + +- **Type checks use class IDs.** QuickJS does not export its class ID enum, so + the IDs of `ArrayBuffer`, `SharedArrayBuffer`, `DataView`, `Date` and the + typed arrays are found at startup by probing one instance of each. A check + such as `napi_is_date` is therefore exact: an object whose prototype is + `Date.prototype` is not a Date, and a Date from another realm is one. +- **Accessors are captured.** The `DataView` and `%TypedArray%` getters, + `Date.prototype.getTime` and the `ArrayBuffer` / `DataView` constructors are + captured before any user code runs: patching the globals has no effect. +- **Pointers into buffers stay valid while the buffer is alive and not + detached.** QuickJS never moves ArrayBuffer memory, but resizing a + resizable ArrayBuffer may reallocate it: read `data` again after JavaScript + ran. + +```mermaid +flowchart LR + AB["ArrayBuffer
(or SharedArrayBuffer)"] --> TA["TypedArray
type, byte_offset, length"] + AB --> DV["DataView
byte_offset, byte_length"] + AB --> BUF["Buffer
(Uint8Array subclass,
see node-specific.md)"] + TA -. "data = buffer data + byte_offset" .-> AB +``` + +--- + +## ArrayBuffer + +### `napi_create_arraybuffer` + +```c +napi_status napi_create_arraybuffer(napi_env env, size_t byte_length, + void **data, napi_value *result); +``` + +Creates a **zero-filled** ArrayBuffer of `byte_length` bytes (through the +`ArrayBuffer` constructor, so QuickJS's size limits apply: too large a size +throws a `RangeError`, `napi_pending_exception`). `data` (optional) receives +a pointer to the contents, `NULL` for a zero-length buffer. + +### `napi_create_external_arraybuffer` + +```c +napi_status napi_create_external_arraybuffer( + napi_env env, void *external_data, size_t byte_length, + node_api_basic_finalize finalize_cb, void *finalize_hint, + napi_value *result); +``` + +Creates an ArrayBuffer over memory owned by the addon. The memory is **used in +place**, never copied nor freed by QuickJS. When the ArrayBuffer is collected, +`finalize_cb(env, external_data, finalize_hint)` runs (queued, from the +event loop, as in Node.js), and the addon frees the memory there. + +`external_data == NULL` creates a buffer that reads as **detached** (V8 has +no backing store for `NULL` data). + +### `napi_is_arraybuffer` + +```c +napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool *result); +``` + +`true` for an `ArrayBuffer` (detached ones included). `false` for a +`SharedArrayBuffer`, as in V8. + +### `napi_get_arraybuffer_info` + +```c +napi_status napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, + void **data, size_t *byte_length); +``` + +Stores the contents pointer and size; both outputs are optional. Accepts an +`ArrayBuffer` or, like Node.js 22.23, a `SharedArrayBuffer` +(`napi_invalid_arg` for anything else). An empty or detached buffer has +`data == NULL` and length 0. For a resizable buffer the current length is +reported. + +### `napi_detach_arraybuffer` + +```c +napi_status napi_detach_arraybuffer(napi_env env, napi_value arraybuffer); +``` + +Detaches an ArrayBuffer, as `structuredClone(ab, {transfer: [ab]})` would: +its length becomes 0 and every view on it reads as empty. +`napi_arraybuffer_expected` for anything other than an `ArrayBuffer` (every +non-shared QuickJS ArrayBuffer is detachable). Detaching an external buffer +does not run its finalizer early; the finalizer still runs when the object is +collected. + +### `napi_is_detached_arraybuffer` + +```c +napi_status napi_is_detached_arraybuffer(napi_env env, napi_value value, + bool *result); +``` + +`true` when `value` is an `ArrayBuffer` that has been detached, like V8's +`WasDetached()`; `false` for any other value. + +## TypedArray + +Supported types (`napi_typedarray_type`): `napi_int8_array`, +`napi_uint8_array`, `napi_uint8_clamped_array`, `napi_int16_array`, +`napi_uint16_array`, `napi_int32_array`, `napi_uint32_array`, +`napi_float32_array`, `napi_float64_array`, `napi_bigint64_array`, +`napi_biguint64_array` and `napi_float16_array`. + +`napi_float16_array` is supported because QuickJS has `Float16Array`; +Node.js 22 returns `napi_invalid_arg` for it. + +### `napi_create_typedarray` + +```c +napi_status napi_create_typedarray(napi_env env, napi_typedarray_type type, + size_t length, napi_value arraybuffer, + size_t byte_offset, napi_value *result); +``` + +Creates a typed array of `length` elements over `arraybuffer` (an +`ArrayBuffer` or a `SharedArrayBuffer`), starting at `byte_offset`. Errors are +the same `RangeError`s as in Node.js, thrown with the function returning +`napi_generic_failure` and the exception pending: + +| Condition | Code | Message | +|---|---|---| +| `byte_offset` not a multiple of the element size | `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` | `start offset of Int32Array should be a multiple of 4` | +| `byte_offset + length * size` beyond the buffer | `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` | `Invalid typed array length` | + +An unknown `type` or a non-buffer `arraybuffer` gives `napi_invalid_arg`. + +### `napi_is_typedarray` + +```c +napi_status napi_is_typedarray(napi_env env, napi_value value, bool *result); +``` + +`true` for an instance of any of the 12 typed array types, Buffers included. +`false` for a DataView. + +### `napi_get_typedarray_info` + +```c +napi_status napi_get_typedarray_info(napi_env env, napi_value typedarray, + napi_typedarray_type *type, + size_t *length, void **data, + napi_value *arraybuffer, + size_t *byte_offset); +``` + +Stores, for every non-`NULL` output: the element type, the length **in +elements**, a pointer to the first element (buffer data + offset), the +underlying ArrayBuffer and the byte offset. `napi_invalid_arg` when +`typedarray` is not a typed array. + +- A view whose buffer is detached, or that is out of bounds after its + resizable buffer shrank, reports length 0. +- A length-tracking view (created without a length on a resizable buffer) + reports its current length. +- For an out-of-bounds, non-detached view the byte offset is reported as 0; + V8 reports the stored offset, which QuickJS does not expose. + +## DataView + +### `napi_create_dataview` + +```c +napi_status napi_create_dataview(napi_env env, size_t length, + napi_value arraybuffer, size_t byte_offset, + napi_value *result); +``` + +Creates a DataView of `length` bytes over an `ArrayBuffer`, starting at +`byte_offset` (`napi_invalid_arg` for anything other than an ArrayBuffer). +When the range exceeds the buffer, throws a `RangeError` with code +`ERR_NAPI_INVALID_DATAVIEW_ARGS` ("byte_offset + byte_length should be less +than or equal to the size in bytes of the array passed in") and returns +`napi_pending_exception`, as in Node.js. + +### `napi_is_dataview` + +```c +napi_status napi_is_dataview(napi_env env, napi_value value, bool *result); +``` + +`true` for a DataView. + +### `napi_get_dataview_info` + +```c +napi_status napi_get_dataview_info(napi_env env, napi_value dataview, + size_t *bytelength, void **data, + napi_value *arraybuffer, + size_t *byte_offset); +``` + +Stores, for every non-`NULL` output: the length in bytes, a pointer to the +first byte, the underlying ArrayBuffer and the byte offset. On a detached +buffer, length and offset are 0, as V8 reports. `napi_invalid_arg` when +`dataview` is not a DataView. + +## BigInt + +QuickJS limits a BigInt to **2^20 bits** (16384 64-bit words); V8 allows 2^30. + +### `napi_create_bigint_int64` + +```c +napi_status napi_create_bigint_int64(napi_env env, int64_t value, + napi_value *result); +``` + +Creates a BigInt from a signed 64-bit integer. + +### `napi_create_bigint_uint64` + +```c +napi_status napi_create_bigint_uint64(napi_env env, uint64_t value, + napi_value *result); +``` + +Creates a BigInt from an unsigned 64-bit integer. + +### `napi_create_bigint_words` + +```c +napi_status napi_create_bigint_words(napi_env env, int sign_bit, + size_t word_count, const uint64_t *words, + napi_value *result); +``` + +Creates a BigInt from its magnitude as little-endian 64-bit words (`words[0]` +is the least significant) and a sign (`sign_bit != 0` for negative). Zero +words, or words that are all zero, give `0n` whatever the sign. + +- `word_count > INT_MAX`: `napi_invalid_arg`. +- `word_count` above 16384: `RangeError: Maximum BigInt size exceeded`, with + `napi_pending_exception`, checked before `words` is read (V8 throws the + same error past its own limit). +- The conversion goes through a hexadecimal string: O(n) in the number of + words. + +### `napi_get_value_bigint_int64` + +```c +napi_status napi_get_value_bigint_int64(napi_env env, napi_value value, + int64_t *result, bool *lossless); +``` + +Stores the BigInt modulo 2^64 as a signed integer (two's complement), and +`*lossless = true` when that is exactly the value. Both outputs are required. +`napi_bigint_expected` when `value` is not a BigInt. + +### `napi_get_value_bigint_uint64` + +```c +napi_status napi_get_value_bigint_uint64(napi_env env, napi_value value, + uint64_t *result, bool *lossless); +``` + +Same, as an unsigned integer (`-1n` gives `UINT64_MAX`, not lossless). + +### `napi_get_value_bigint_words` + +```c +napi_status napi_get_value_bigint_words(napi_env env, napi_value value, + int *sign_bit, size_t *word_count, + uint64_t *words); +``` + +Reads a BigInt as sign and magnitude words, like V8's +`BigInt::ToWordsArray`: + +- **Count only:** with `sign_bit` and `words` both `NULL`, stores in + `*word_count` the number of words the value needs. +- **Read:** `*word_count` is the capacity of `words` on input. The low words + that fit are written; on output `*word_count` is the number of words the + value needs (which may be more than were written). `*sign_bit` is 1 for a + negative value. +- `0n` has no words and sign 0. + +```c +size_t n; +napi_get_value_bigint_words(env, value, NULL, &n, NULL); +uint64_t *w = malloc(n * sizeof *w); +int sign; +napi_get_value_bigint_words(env, value, &sign, &n, w); +``` + +## Date + +### `napi_create_date` + +```c +napi_status napi_create_date(napi_env env, double time, napi_value *result); +``` + +Creates a Date from milliseconds since the epoch. `TimeClip` applies: values +beyond ±8.64e15 or non-finite give an invalid date (`NaN` time), as in V8. + +### `napi_is_date` + +```c +napi_status napi_is_date(napi_env env, napi_value value, bool *is_date); +``` + +`true` for a Date object. + +### `napi_get_date_value` + +```c +napi_status napi_get_date_value(napi_env env, napi_value value, + double *result); +``` + +Stores the time value in milliseconds (`NaN` for an invalid date), using the +`Date.prototype.getTime` captured at startup. `napi_date_expected` when +`value` is not a Date. + +## Promise + +A `napi_deferred` is the pair of resolving functions of a new promise. It is +**released by the first resolve or reject**; deferreds never concluded are +freed at teardown. + +```c +napi_deferred deferred; +napi_value promise; +napi_create_promise(env, &deferred, &promise); +/* return `promise` to JavaScript; later, e.g. in an async work complete: */ +napi_resolve_deferred(env, deferred, value); +``` + +### `napi_create_promise` + +```c +napi_status napi_create_promise(napi_env env, napi_deferred *deferred, + napi_value *promise); +``` + +Creates a pending promise and its deferred. Both outputs are required. + +### `napi_resolve_deferred` + +```c +napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, + napi_value resolution); +``` + +Resolves the promise with `resolution` (a thenable is followed, as with the +`resolve` function of `new Promise`) and frees the deferred. Reactions run at +the next microtask checkpoint, not synchronously. + +### `napi_reject_deferred` + +```c +napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, + napi_value rejection); +``` + +Rejects the promise with `rejection` and frees the deferred. A rejection +nobody handles is reported by the host as an unhandled rejection. + +### `napi_is_promise` + +```c +napi_status napi_is_promise(napi_env env, napi_value value, bool *is_promise); +``` + +`true` for a native Promise object (not for other thenables). diff --git a/doc/node-api/environment.md b/doc/node-api/environment.md new file mode 100644 index 0000000..24579f6 --- /dev/null +++ b/doc/node-api/environment.md @@ -0,0 +1,180 @@ +# Environment, versions and cleanup hooks + +[Node-API reference](README.md) › Environment + +Implemented in `src/env.c` and `src/loader.c`. + +| Function | Purpose | +|---|---| +| [`napi_get_last_error_info`](#napi_get_last_error_info) | details of the last failed call | +| [`napi_get_version`](#napi_get_version) | highest supported Node-API version | +| [`napi_get_node_version`](#napi_get_node_version) | the Node.js version that is emulated | +| [`node_api_get_module_file_name`](#node_api_get_module_file_name) | URL of the addon file | +| [`napi_add_env_cleanup_hook`](#napi_add_env_cleanup_hook) | run a function at teardown | +| [`napi_remove_env_cleanup_hook`](#napi_remove_env_cleanup_hook) | unregister it | +| [`napi_add_async_cleanup_hook`](#napi_add_async_cleanup_hook) | asynchronous teardown step | +| [`napi_remove_async_cleanup_hook`](#napi_remove_async_cleanup_hook) | unregister it, or signal it is done | +| [`napi_fatal_error`](#napi_fatal_error) | abort the process | +| [`napi_module_register`](#napi_module_register) | legacy module registration | + +--- + +### `napi_get_last_error_info` + +```c +napi_status napi_get_last_error_info(node_api_basic_env env, + const napi_extended_error_info **result); +``` + +Returns a pointer to the env's last-error record: `error_code` is the status of +the last Node-API call that failed (or `napi_ok`), `error_message` a static +English message (see the [status table](README.md#status-codes-and-the-last-error)). +`engine_error_code` and `engine_reserved` are always `0` / `NULL`. + +- The record belongs to the env and is overwritten by the next call: copy what + you need before calling another function. +- This function never changes the last error itself, so it can be called + repeatedly. It always returns `napi_ok` (or `napi_invalid_arg` for a `NULL` + argument). +- Each native callback starts with a clear last error, as in Node.js. + +### `napi_get_version` + +```c +napi_status napi_get_version(node_api_basic_env env, uint32_t *result); +``` + +Stores `10`, the highest Node-API version this build supports (the same value +as `qjsnapi_napi_version()`). Experimental APIs (`NAPI_EXPERIMENTAL`) are not +provided. + +### `napi_get_node_version` + +```c +napi_status napi_get_node_version(node_api_basic_env env, + const napi_node_version **version); +``` + +Stores a pointer to a static record `{ major: 22, minor: 23, patch: 4, +release: "quickjs-napi" }`: the Node.js release whose Node-API behaviour is +reproduced. Addons that check for a minimum Node.js version therefore see +22.23.4. The executable's `process.version` reports the same. + +### `node_api_get_module_file_name` + +```c +napi_status node_api_get_module_file_name(node_api_basic_env env, + const char **result); +``` + +Stores the absolute `file://` URL of the addon this env belongs to, encoded +like Node's `url.pathToFileURL` (percent-encoding, Windows drive letters as +`file:///C:/...`). The string lives as long as the env. For a static addon +(`qjsnapi_init_static_addon`) it is the name given by the embedder. + +### `napi_add_env_cleanup_hook` + +```c +napi_status napi_add_env_cleanup_hook(node_api_basic_env env, + napi_cleanup_hook fun, void *arg); +``` + +Registers `fun(arg)` to run when the env is torn down +(`qjsnapi_host_destroy`, or the normal end of the executable). Hooks run in +**reverse order of registration** (LIFO), interleaved with the async cleanup +hooks and the library's own hooks (thread-safe functions), with JavaScript +already disabled. + +- Registering the same `(fun, arg)` pair twice is a **fatal error**, as in + Node.js (where it is a `CHECK` failure). +- Hooks do **not** run when the executable ends with `process.exit()` or a + fatal exception, as in Node.js. + +### `napi_remove_env_cleanup_hook` + +```c +napi_status napi_remove_env_cleanup_hook(node_api_basic_env env, + napi_cleanup_hook fun, void *arg); +``` + +Unregisters the hook registered with the same `(fun, arg)`. Removing a pair +that is not registered does nothing and returns `napi_ok`. + +### `napi_add_async_cleanup_hook` + +```c +napi_status napi_add_async_cleanup_hook( + node_api_basic_env env, napi_async_cleanup_hook hook, void *arg, + napi_async_cleanup_hook_handle *remove_handle); +``` + +Registers a cleanup step that may take time, such as closing a libuv handle. +At teardown `hook(handle, arg)` is called in LIFO order with the other hooks; +the teardown then **keeps running the event loop** until the addon calls +`napi_remove_async_cleanup_hook(handle)`, typically from a `uv_close` +callback. + +`remove_handle` may be `NULL` when the hook is never removed early; the hook +then receives the handle as its first argument. + +```c +static void on_close(uv_handle_t *h) { + napi_remove_async_cleanup_hook(((my_state *)h->data)->cleanup_handle); +} +static void cleanup(napi_async_cleanup_hook_handle handle, void *arg) { + my_state *s = arg; + s->cleanup_handle = handle; + uv_close((uv_handle_t *)&s->timer, on_close); +} +/* in init: */ +napi_add_async_cleanup_hook(env, cleanup, state, NULL); +``` + +### `napi_remove_async_cleanup_hook` + +```c +napi_status napi_remove_async_cleanup_hook( + napi_async_cleanup_hook_handle remove_handle); +``` + +Has two meanings, as in Node.js: + +- **before teardown**, it unregisters the hook, which will not run; +- **after the hook started**, it signals that the asynchronous cleanup is + complete, so the teardown can stop waiting for it. + +The handle is freed in both cases and must not be used again. Returns +`napi_invalid_arg` for `NULL`. + +### `napi_fatal_error` + +```c +NAPI_NO_RETURN void napi_fatal_error(const char *location, size_t location_len, + const char *message, size_t message_len); +``` + +Prints `FATAL ERROR: ` on stderr and ends the process +immediately: `abort()` on Linux and macOS, `_exit(134)` on Windows (like +Node.js, which avoids the Windows Error Reporting dialog). No cleanup runs. +Both lengths accept `NAPI_AUTO_LENGTH`; `location` and `message` may be +`NULL`. + +### `napi_module_register` + +```c +void napi_module_register(napi_module *mod); +``` + +Legacy registration used by addons built with the old `NAPI_MODULE` macro +from a static constructor. When called **while `qjsnapi_load_addon` is opening +a library**, the module is attached to that load and its `nm_register_func` +becomes the initializer (only when the library does not export +`napi_register_module_v1`, which takes precedence). The record is remembered, +so loading the same file again reuses it even though the constructor does not +run a second time. + +Called outside of a load (for instance by an addon linked into the +executable), it prints a warning and does nothing: use +[`qjsnapi_init_static_addon`](../embedding.md#qjsnapi_init_static_addon) +instead. A legacy module with no `nm_register_func` fails to load with +`Module has no declared entry point.` diff --git a/doc/node-api/errors.md b/doc/node-api/errors.md new file mode 100644 index 0000000..50ea283 --- /dev/null +++ b/doc/node-api/errors.md @@ -0,0 +1,173 @@ +# Errors and exceptions + +[Node-API reference](README.md) › Errors + +Implemented in `src/error.c`. The model (status codes plus a pending +JavaScript exception) is described in +[architecture.md](../architecture.md#errors-and-exceptions). + +| Group | Functions | +|---|---| +| Create an error object | [`napi_create_error`](#napi_create_error), [`napi_create_type_error`](#napi_create_type_error), [`napi_create_range_error`](#napi_create_range_error), [`node_api_create_syntax_error`](#node_api_create_syntax_error) | +| Throw | [`napi_throw`](#napi_throw), [`napi_throw_error`](#napi_throw_error), [`napi_throw_type_error`](#napi_throw_type_error), [`napi_throw_range_error`](#napi_throw_range_error), [`node_api_throw_syntax_error`](#node_api_throw_syntax_error) | +| Inspect | [`napi_is_error`](#napi_is_error), [`napi_is_exception_pending`](#napi_is_exception_pending), [`napi_get_and_clear_last_exception`](#napi_get_and_clear_last_exception) | + +## Pending exceptions + +QuickJS keeps at most **one pending exception** on the runtime, and +quickjs-napi uses it directly: + +- a failed call into JavaScript leaves the exception pending and returns + `napi_pending_exception`; +- `napi_throw*` make an exception pending and return `napi_ok`; +- while an exception is pending, [functions that run JavaScript](README.md#functions-that-run-javascript) + refuse to start, but value creation and the functions on this page still + work; +- when the native callback returns, a pending exception propagates to the + JavaScript caller. With no JavaScript caller (finalizers, async work, + thread-safe functions) it is reported as uncaught. + +A typical error path: + +```c +napi_value result; +napi_status s = napi_call_function(env, recv, fn, 0, NULL, &result); +if (s == napi_pending_exception) { + napi_value exc; + napi_get_and_clear_last_exception(env, &exc); /* handle it here ... */ + /* ... or simply return NULL and let it propagate */ +} +``` + +## Error objects + +The four error constructors (`Error`, `TypeError`, `RangeError`, +`SyntaxError`) are captured when the host is created, so replacing +`globalThis.Error` later does not change what these functions create. Like +Node.js, they create `new Ctor(message)` and, when a code is given, set an +own enumerable `code` property after construction. + +--- + +## Create an error object + +These functions only create the object; nothing is thrown. They work while an +exception is pending. + +### `napi_create_error` + +```c +napi_status napi_create_error(napi_env env, napi_value code, napi_value msg, + napi_value *result); +``` + +Creates `new Error(msg)`. `msg` must be a string; `code` is optional (`NULL`) +or a string, set as `error.code`. Either one not being a string gives +`napi_string_expected`. + +### `napi_create_type_error` + +```c +napi_status napi_create_type_error(napi_env env, napi_value code, + napi_value msg, napi_value *result); +``` + +Same with `TypeError`. + +### `napi_create_range_error` + +```c +napi_status napi_create_range_error(napi_env env, napi_value code, + napi_value msg, napi_value *result); +``` + +Same with `RangeError`. + +### `node_api_create_syntax_error` + +```c +napi_status node_api_create_syntax_error(napi_env env, napi_value code, + napi_value msg, napi_value *result); +``` + +Same with `SyntaxError`. + +## Throw + +### `napi_throw` + +```c +napi_status napi_throw(napi_env env, napi_value error); +``` + +Throws `error`, which may be any value (not only an Error object). Returns +`napi_ok`; the exception is now pending. + +### `napi_throw_error` + +```c +napi_status napi_throw_error(napi_env env, const char *code, const char *msg); +``` + +Creates and throws `new Error(msg)` with an optional `code` (`NULL` for none). +`msg` is a NUL-terminated UTF-8 string and is required. + +### `napi_throw_type_error` + +```c +napi_status napi_throw_type_error(napi_env env, const char *code, + const char *msg); +``` + +Same with `TypeError`. + +### `napi_throw_range_error` + +```c +napi_status napi_throw_range_error(napi_env env, const char *code, + const char *msg); +``` + +Same with `RangeError`. + +### `node_api_throw_syntax_error` + +```c +napi_status node_api_throw_syntax_error(napi_env env, const char *code, + const char *msg); +``` + +Same with `SyntaxError`. + +All `napi_throw*` functions refuse to start (`napi_pending_exception`) when an +exception is already pending: an exception never silently replaces another. + +## Inspect + +### `napi_is_error` + +```c +napi_status napi_is_error(napi_env env, napi_value value, bool *result); +``` + +`true` when `value` is an Error object: an object created by a builtin error +constructor or a subclass of one (QuickJS `JS_IsError`). An ordinary object +whose prototype chain contains `Error.prototype` is not an Error. + +### `napi_is_exception_pending` + +```c +napi_status napi_is_exception_pending(napi_env env, bool *result); +``` + +`true` when an exception is pending on the context. + +### `napi_get_and_clear_last_exception` + +```c +napi_status napi_get_and_clear_last_exception(napi_env env, + napi_value *result); +``` + +Takes the pending exception: stores it in `result` and clears it, so +JavaScript can run again. When no exception is pending, stores `undefined`. diff --git a/doc/node-api/functions.md b/doc/node-api/functions.md new file mode 100644 index 0000000..8b00299 --- /dev/null +++ b/doc/node-api/functions.md @@ -0,0 +1,201 @@ +# Functions, classes and scripts + +[Node-API reference](README.md) › Functions + +Implemented in `src/function.c`. How a call reaches the addon is described in +[architecture.md](../architecture.md#calling-native-functions). + +| Function | Purpose | +|---|---| +| [`napi_create_function`](#napi_create_function) | wrap a C callback in a JavaScript function | +| [`napi_get_cb_info`](#napi_get_cb_info) | arguments, `this` and data of the current call | +| [`napi_get_new_target`](#napi_get_new_target) | `new.target` of the current call | +| [`napi_call_function`](#napi_call_function) | call a JavaScript function | +| [`napi_new_instance`](#napi_new_instance) | `new Constructor(...)` | +| [`napi_define_class`](#napi_define_class) | constructor with prototype and static members | +| [`napi_run_script`](#napi_run_script) | evaluate a string of JavaScript | + +## The callback + +```c +typedef napi_value (*napi_callback)(napi_env env, napi_callback_info info); +``` + +A native function receives the env and an opaque `info`, valid only during +the call. It returns the result, or `NULL` for `undefined`. If it leaves an +exception pending (`napi_throw*`, or a failed call into JavaScript), the +returned value is ignored and the exception propagates to the caller. + +Every call runs in its own handle scope: values created during the call are +released when it returns, except the returned one. The last error is cleared +before the callback runs. + +--- + +### `napi_create_function` + +```c +napi_status napi_create_function(napi_env env, const char *utf8name, + size_t length, napi_callback cb, void *data, + napi_value *result); +``` + +Creates a JavaScript function that calls `cb`. `data` is handed back by +`napi_get_cb_info`. + +- `utf8name` (optional; `NULL` gives `""`) becomes the `name` property; + `length` is its length in bytes or `NAPI_AUTO_LENGTH`. +- Like a V8 function created by `Function::New`: own properties `length` (0) + and `name`, both non-writable, non-enumerable and configurable, in that + order; and an own `prototype` object whose `constructor` points back to the + function, so the function can also be called with `new`. +- The function holds `data` as a plain pointer. To free it when the function is + collected, attach a finalizer with + [`napi_add_finalizer`](lifetime.md#napi_add_finalizer). + +### `napi_get_cb_info` + +```c +napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, + size_t *argc, napi_value *argv, + napi_value *this_arg, void **data); +``` + +Reads the current call. Every output is optional: + +- `argc` is in/out: on input the capacity of `argv`, on output the **actual** + number of arguments, which may be larger than the capacity. +- `argv` receives `min(capacity, actual)` arguments; the remaining slots up to + the capacity are filled with `undefined`. `argc` is required when `argv` is + given. +- `this_arg` receives the receiver. In a construct call this is the new object + created from `new.target.prototype`. +- `data` receives the pointer given to `napi_create_function`, + `napi_define_class` or the property descriptor. + +```c +size_t argc = 3; +napi_value argv[3]; +napi_value self; +napi_get_cb_info(env, info, &argc, argv, &self, NULL); +/* argc may now be 0..N; argv[argc..2] are undefined */ +``` + +### `napi_get_new_target` + +```c +napi_status napi_get_new_target(napi_env env, napi_callback_info cbinfo, + napi_value *result); +``` + +Stores `new.target`: the constructor `new` was applied to (a subclass when +called through `super()`), or `NULL` when the function was called without +`new`. This is how a constructor detects a plain call. + +### `napi_call_function` + +```c +napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, + size_t argc, const napi_value *argv, + napi_value *result); +``` + +Calls `func` with `this = recv` and `argc` arguments. `recv` is required (use +`napi_get_undefined` or `napi_get_global`). `result` is optional. + +- `func` not a function: `napi_invalid_arg`, as in Node.js. +- The function throws: `napi_pending_exception`, exception pending. +- Up to 8 arguments are passed without allocation. + +### `napi_new_instance` + +```c +napi_status napi_new_instance(napi_env env, napi_value constructor, + size_t argc, const napi_value *argv, + napi_value *result); +``` + +`new constructor(...argv)`. `napi_invalid_arg` when `constructor` is not a +function; `napi_pending_exception` when it is not a constructor (an arrow +function, a method) or throws. + +### `napi_define_class` + +```c +napi_status napi_define_class(napi_env env, const char *utf8name, + size_t length, napi_callback constructor, + void *data, size_t property_count, + const napi_property_descriptor *properties, + napi_value *result); +``` + +Creates a constructor function named `utf8name` (required) that calls +`constructor`, then defines the properties: + +- descriptors **without** `napi_static` go on `prototype` (instance methods, + accessors and values); +- descriptors **with** `napi_static` go on the constructor itself. + +Descriptors follow [`napi_define_properties`](objects.md#napi_define_properties). +As with V8's prototype templates, when two instance descriptors have the same +key **the later one wins**, whatever the attributes of the earlier one +(node-addon-api relies on it). Static descriptors are defined one by one, so +redefining a non-configurable static property fails, as in Node.js. + +The usual pattern pairs the class with [`napi_wrap`](lifetime.md#napi_wrap): + +```c +static napi_value Counter_New(napi_env env, napi_callback_info info) { + napi_value self, target; + napi_get_new_target(env, info, &target); + if (target == NULL) { + napi_throw_type_error(env, NULL, "Counter must be called with new"); + return NULL; + } + napi_get_cb_info(env, info, NULL, NULL, &self, NULL); + int64_t *count = calloc(1, sizeof *count); + napi_wrap(env, self, count, free_counter, NULL, NULL); + return self; +} + +static napi_value Counter_Increment(napi_env env, napi_callback_info info) { + napi_value self, result; + int64_t *count; + napi_get_cb_info(env, info, NULL, NULL, &self, NULL); + if (napi_unwrap(env, self, (void **)&count) != napi_ok) { + napi_throw_type_error(env, NULL, "not a Counter"); + return NULL; + } + napi_create_int64(env, ++*count, &result); + return result; +} + +napi_property_descriptor props[] = { + {"increment", NULL, Counter_Increment, NULL, NULL, NULL, napi_default_method, NULL}, +}; +napi_value cls; +napi_define_class(env, "Counter", NAPI_AUTO_LENGTH, Counter_New, NULL, 1, + props, &cls); +``` + +**Difference from Node.js:** V8 attaches a *signature* to prototype methods, +so calling one on an object that was not created by the class throws +`TypeError: Illegal invocation` before the callback runs. In quickjs-napi the +callback runs and must validate `this` itself, as `Counter_Increment` does +above (`napi_unwrap` fails on objects that are not wrapped). See +[compatibility.md](../compatibility.md). + +### `napi_run_script` + +```c +napi_status napi_run_script(napi_env env, napi_value script, + napi_value *result); +``` + +Compiles and runs `script` (a string) as a classic global script in the +current context, like `v8::Script::Compile` + `Run`, and stores its +completion value. The file name in stack traces is ``. + +- `script` not a string: `napi_string_expected`. +- A syntax error or an exception thrown by the script: `napi_generic_failure`, + **with the exception pending**, as in Node.js. diff --git a/doc/node-api/lifetime.md b/doc/node-api/lifetime.md new file mode 100644 index 0000000..b1bdb27 --- /dev/null +++ b/doc/node-api/lifetime.md @@ -0,0 +1,294 @@ +# References, externals, wrapping and finalizers + +[Node-API reference](README.md) › Lifetime + +Implemented in `src/lifetime.c`. This is where QuickJS (reference counting) +and V8 (tracing GC) differ most; the mechanism that bridges them, holders in +a `WeakMap` and the kept-objects list, is described in +[architecture.md](../architecture.md#object-lifetime). + +| Group | Functions | +|---|---| +| References | [`napi_create_reference`](#napi_create_reference), [`napi_delete_reference`](#napi_delete_reference), [`napi_reference_ref`](#napi_reference_ref), [`napi_reference_unref`](#napi_reference_unref), [`napi_get_reference_value`](#napi_get_reference_value) | +| Wrapping | [`napi_wrap`](#napi_wrap), [`napi_unwrap`](#napi_unwrap), [`napi_remove_wrap`](#napi_remove_wrap) | +| Finalizers | [`napi_add_finalizer`](#napi_add_finalizer) | +| Externals | [`napi_create_external`](#napi_create_external), [`napi_get_value_external`](#napi_get_value_external) | +| Type tags | [`napi_type_tag_object`](#napi_type_tag_object), [`napi_check_object_type_tag`](#napi_check_object_type_tag) | +| Instance data | [`napi_set_instance_data`](#napi_set_instance_data), [`napi_get_instance_data`](#napi_get_instance_data) | +| Memory accounting | [`napi_adjust_external_memory`](#napi_adjust_external_memory) | + +## When finalizers run + +Every finalizer in this file (`napi_wrap`, `napi_add_finalizer`, +`napi_create_external`, instance data) runs **after** its object is +collected, never synchronously and never inside the garbage collector: + +```mermaid +flowchart LR + A["object unreachable"] --> B["QuickJS frees it
(refcount 0, or JS_RunGC for cycles)"] + B --> C["holder finalizer:
finalizer queued on the env"] + C --> D["next loop iteration (uv_check):
finalize_cb(env, data, hint)
in its own handle scope"] + C --> E["or qjsnapi_host_destroy:
finalize_cb with JavaScript disabled"] +``` + +- A finalizer may call any Node-API function; JavaScript can run unless the + env is tearing down (`napi_cannot_run_js`, or `napi_pending_exception` for + modules built for Node-API < 10). +- An exception left pending by a finalizer is reported as uncaught. +- Finalizers of objects still alive at teardown run during + `qjsnapi_host_destroy`: those with a finalizer first, newest first, then + plain references. +- In the executable, `process.exit()` skips them, as in Node.js. + +Because QuickJS frees objects as soon as their last reference goes away, +finalizers usually run **earlier** than in Node.js (at the next loop +iteration instead of the next major GC). Objects in reference cycles are +collected by the cycle collector (`JS_RunGC`, or `gc()` in the executable). + +--- + +## References + +A `napi_ref` keeps a value reachable across calls. It has a count: above 0 +the reference is **strong**; at 0 it is **weak** for objects, functions and +non-registered symbols (the value can be collected, and the reference then +reads as empty), and released for any other value. + +### `napi_create_reference` + +```c +napi_status napi_create_reference(napi_env env, napi_value value, + uint32_t initial_refcount, napi_ref *result); +``` + +Creates a reference with the given count. + +- Modules built for **Node-API ≥ 10** may reference any value. Older modules + may only reference objects, functions and symbols (`napi_invalid_arg` + otherwise), as in Node.js. +- With `initial_refcount == 0` and an object target, the reference is weak + from the start, but the object is kept alive until the end of the current + macrotask (*kept objects*), as V8 keeps it until the next GC. +- A reference to a registered symbol (`Symbol.for`) is always strong; such + symbols are never collected anyway. + +The addon owns the reference and must delete it with +`napi_delete_reference`. References never deleted are freed at teardown. + +### `napi_delete_reference` + +```c +napi_status napi_delete_reference(node_api_basic_env env, napi_ref ref); +``` + +Deletes the reference and releases its value (if still held). Must be called +exactly once per reference created by `napi_create_reference`, and by +`napi_wrap` / `napi_add_finalizer` when they returned one (see there). Can be +called from a finalizer. + +### `napi_reference_ref` + +```c +napi_status napi_reference_ref(napi_env env, napi_ref ref, uint32_t *result); +``` + +Increments the count and stores the new value in `result` (optional). Going +from 0 to 1 makes a weak reference strong again, if its target is still +alive. + +### `napi_reference_unref` + +```c +napi_status napi_reference_unref(napi_env env, napi_ref ref, + uint32_t *result); +``` + +Decrements the count and stores the new value in `result` (optional). +Reaching 0 makes the reference weak (or empty for primitives). +`napi_generic_failure` when the count is already 0. + +### `napi_get_reference_value` + +```c +napi_status napi_get_reference_value(napi_env env, napi_ref ref, + napi_value *result); +``` + +Stores the referenced value, or `NULL` when a weak reference's target has +been collected (or a primitive was released at count 0). Always check for +`NULL` when the count may be 0. + +## Wrapping + +Wrapping attaches a native pointer to a JavaScript object, typically the +`this` of a class constructor (see the +[`napi_define_class` example](functions.md#napi_define_class)). The pointer is +stored in the object's *holder*, not in a property, so **any object** can be +wrapped: frozen objects, proxies and functions included, and wrapping is +invisible to JavaScript. + +### `napi_wrap` + +```c +napi_status napi_wrap(napi_env env, napi_value js_object, void *native_object, + node_api_basic_finalize finalize_cb, + void *finalize_hint, napi_ref *result); +``` + +Associates `native_object` with `js_object` (which must be an object: +`napi_invalid_arg` otherwise). When the object is collected, +`finalize_cb(env, native_object, finalize_hint)` runs. + +- Wrapping an object that is already wrapped returns `napi_invalid_arg`. +- `result` (optional) receives a weak reference (count 0) to the object. That + reference is **owned by the addon**: delete it from the finalizer, so + `finalize_cb` is then required. Without `result`, the library owns the + internal reference. + +### `napi_unwrap` + +```c +napi_status napi_unwrap(napi_env env, napi_value js_object, void **result); +``` + +Stores the pointer given to `napi_wrap`. `napi_invalid_arg` when `js_object` +is not an object or is not wrapped: methods use this to validate `this`. + +### `napi_remove_wrap` + +```c +napi_status napi_remove_wrap(napi_env env, napi_value js_object, + void **result); +``` + +Removes the wrap and stores the pointer in `result` (optional). **The +finalizer will not run**: the addon now owns the native object. If `napi_wrap` +returned a reference, the addon must still delete it. The object can then be +wrapped again. + +## Finalizers + +### `napi_add_finalizer` + +```c +napi_status napi_add_finalizer(napi_env env, napi_value js_object, + void *finalize_data, + node_api_basic_finalize finalize_cb, + void *finalize_hint, napi_ref *result); +``` + +Runs `finalize_cb(env, finalize_data, finalize_hint)` when `js_object` (an +object or a function) is collected. Unlike `napi_wrap`, an object may have +any number of finalizers, and nothing can be retrieved from it. `finalize_cb` +is required. `result` (optional) receives a weak reference owned by the addon, +to be deleted with `napi_delete_reference`; without it the library deletes the +reference after the finalizer runs. + +A common use: free the `data` of a function created with +`napi_create_function`. + +## Externals + +### `napi_create_external` + +```c +napi_status napi_create_external(napi_env env, void *data, + node_api_basic_finalize finalize_cb, + void *finalize_hint, napi_value *result); +``` + +Creates a JavaScript value that carries a native pointer, like a +`v8::External`. JavaScript sees an object with a `null` prototype that is not +extensible (`typeof` is `'object'`); [`napi_typeof`](values.md#napi_typeof) +reports `napi_external`. When it is collected, +`finalize_cb(env, data, finalize_hint)` runs (if given). + +### `napi_get_value_external` + +```c +napi_status napi_get_value_external(napi_env env, napi_value value, + void **result); +``` + +Stores the pointer of an external. `napi_invalid_arg` for any other value. + +## Type tags + +A type tag is a 128-bit value (`napi_type_tag {uint64_t lower, upper}`) +attached to an object, so that an addon can check that an object it receives +really is one of its own before unwrapping it: + +```c +static const napi_type_tag kDatabaseTag = {0x1edf75a38336451d, 0xa5ed9ce2e4c00c38}; +/* when creating */ +napi_type_tag_object(env, obj, &kDatabaseTag); +/* when receiving */ +bool ok; +napi_check_object_type_tag(env, arg, &kDatabaseTag, &ok); +``` + +Like wraps, tags live in the object's holder (or inside the external), not in +a property. + +### `napi_type_tag_object` + +```c +napi_status napi_type_tag_object(napi_env env, napi_value value, + const napi_type_tag *type_tag); +``` + +Tags an object or an external. An object can be tagged only once: +`napi_invalid_arg` if it already has a tag. `null` and `undefined` give +`napi_object_expected`. + +### `napi_check_object_type_tag` + +```c +napi_status napi_check_object_type_tag(napi_env env, napi_value value, + const napi_type_tag *type_tag, + bool *result); +``` + +`true` when `value` carries exactly `type_tag`; `false` when it has another +tag or none. + +## Instance data + +Per-env data, the replacement for global variables in addons that can be +loaded several times (each load has its own env). + +### `napi_set_instance_data` + +```c +napi_status napi_set_instance_data(node_api_basic_env env, void *data, + napi_finalize finalize_cb, + void *finalize_hint); +``` + +Stores `data` on the env. `finalize_cb(env, data, finalize_hint)` (optional) +runs at teardown. Setting new data **replaces** the previous data without +finalizing it, as in Node.js. + +### `napi_get_instance_data` + +```c +napi_status napi_get_instance_data(node_api_basic_env env, void **data); +``` + +Stores the data set by `napi_set_instance_data`, or `NULL`. + +## Memory accounting + +### `napi_adjust_external_memory` + +```c +napi_status napi_adjust_external_memory(node_api_basic_env env, + int64_t change_in_bytes, + int64_t *adjusted_value); +``` + +Adds `change_in_bytes` (may be negative) to a per-host counter of native +memory kept alive by JavaScript objects, and stores the new total. V8 uses +this counter to schedule garbage collections; QuickJS has no such notion, so +the counter is only bookkeeping. It never goes below 0 and saturates at +`INT64_MAX`. diff --git a/doc/node-api/node-specific.md b/doc/node-api/node-specific.md new file mode 100644 index 0000000..0ac1056 --- /dev/null +++ b/doc/node-api/node-specific.md @@ -0,0 +1,212 @@ +# Buffers, async context and callback scopes + +[Node-API reference](README.md) › Node.js-specific APIs + +The synchronous part of `node_api.h`. Implemented in `src/buffer.c` (with the +`Buffer` class of `src/buffer.js`) and `src/node_api.c`. + +| Group | Functions | +|---|---| +| Buffers | [`napi_create_buffer`](#napi_create_buffer), [`napi_create_buffer_copy`](#napi_create_buffer_copy), [`napi_create_external_buffer`](#napi_create_external_buffer), [`node_api_create_buffer_from_arraybuffer`](#node_api_create_buffer_from_arraybuffer), [`napi_is_buffer`](#napi_is_buffer), [`napi_get_buffer_info`](#napi_get_buffer_info) | +| Async context | [`napi_async_init`](#napi_async_init), [`napi_async_destroy`](#napi_async_destroy), [`napi_make_callback`](#napi_make_callback) | +| Callback scopes | [`napi_open_callback_scope`](#napi_open_callback_scope), [`napi_close_callback_scope`](#napi_close_callback_scope) | +| Uncaught exceptions | [`napi_fatal_exception`](#napi_fatal_exception) | + +--- + +## Buffers + +Buffers are instances of a **minimal Node.js `Buffer`** embedded in the +library (`src/buffer.js`). As in Node.js, a buffer is a `FastBuffer`, a +`Uint8Array` subclass whose prototype is `Buffer.prototype`, so typed-array +APIs work on it too. The class provides: + +| | | +|---|---| +| Static | `Buffer.from`, `alloc`, `allocUnsafe`, `allocUnsafeSlow`, `isBuffer`, `isEncoding`, `byteLength`, `concat`, `compare`, `poolSize` | +| Prototype | `toString`, `toLocaleString`, `write`, `equals`, `compare`, `copy`, `fill`, `slice`, `subarray`, `toJSON`, `indexOf`, `includes` | +| Encodings | `utf8`, `utf16le` (`ucs2`), `latin1` (`binary`), `ascii`, `hex`, `base64`, `base64url` | + +The library installs no global. The embedder gets the class with +[`qjsnapi_host_get_buffer`](../embedding.md#qjsnapi_host_get_buffer); the +`quickjs-napi` executable exposes it as `globalThis.Buffer` and +`require('buffer').Buffer`. + +### `napi_create_buffer` + +```c +napi_status napi_create_buffer(napi_env env, size_t length, void **data, + napi_value *result); +``` + +Creates a Buffer of `length` bytes and stores a pointer to its contents in +`data` (optional; `NULL` when `length` is 0). The memory is **zero-filled**; +Node.js leaves it uninitialized, so addons cannot rely on either. + +### `napi_create_buffer_copy` + +```c +napi_status napi_create_buffer_copy(napi_env env, size_t length, + const void *data, void **result_data, + napi_value *result); +``` + +Creates a Buffer holding a copy of `length` bytes from `data`, and stores a +pointer to the new contents in `result_data` (optional). + +### `napi_create_external_buffer` + +```c +napi_status napi_create_external_buffer(napi_env env, size_t length, + void *data, + node_api_basic_finalize finalize_cb, + void *finalize_hint, + napi_value *result); +``` + +Creates a Buffer over memory owned by the addon, **used in place**. When the +underlying ArrayBuffer is collected, `finalize_cb(env, data, finalize_hint)` +runs (queued, from the event loop, as Node.js defers it). External buffers are +always allowed: `napi_no_external_buffers_allowed` is never returned. + +### `node_api_create_buffer_from_arraybuffer` + +```c +napi_status node_api_create_buffer_from_arraybuffer(napi_env env, + napi_value arraybuffer, + size_t byte_offset, + size_t byte_length, + napi_value *result); +``` + +Creates a Buffer that **shares** the memory of an `ArrayBuffer` (no copy), +over `byte_length` bytes from `byte_offset`. `napi_invalid_arg` when +`arraybuffer` is not an `ArrayBuffer`. When the range does not fit, throws a +`RangeError` with code `ERR_OUT_OF_RANGE` ("The byte offset + length is out of +range") and returns `napi_pending_exception`; `*result` is not set. Node.js +returns `napi_ok` in that case, with the same exception pending. + +### `napi_is_buffer` + +```c +napi_status napi_is_buffer(napi_env env, napi_value value, bool *result); +``` + +`true` for a Buffer and, as in Node.js 22 (`node::Buffer::HasInstance`), for +**any ArrayBufferView**: every typed array and DataView. + +### `napi_get_buffer_info` + +```c +napi_status napi_get_buffer_info(napi_env env, napi_value value, void **data, + size_t *length); +``` + +Stores the contents pointer and the length in bytes of a Buffer or any other +ArrayBufferView (both outputs optional). `napi_invalid_arg` for anything else. + +## Async context + +Node.js associates native callbacks with `async_hooks` resources, so that +`AsyncLocalStorage` and async stack traces follow them. **quickjs-napi has no +`async_hooks`**: an async context only records that it exists, and the +resource and its name are validated but not used. The functions are provided +so that addons using them load and behave correctly. + +### `napi_async_init` + +```c +napi_status napi_async_init(napi_env env, napi_value async_resource, + napi_value async_resource_name, + napi_async_context *result); +``` + +Creates an async context. `async_resource` is optional; `null` or `undefined` +give `napi_object_expected` (without a pending exception, as in Node.js). +`async_resource_name` is required. Contexts never destroyed are freed at +teardown. + +### `napi_async_destroy` + +```c +napi_status napi_async_destroy(napi_env env, napi_async_context async_context); +``` + +Frees an async context. + +### `napi_make_callback` + +```c +napi_status napi_make_callback(napi_env env, napi_async_context async_context, + napi_value recv, napi_value func, size_t argc, + const napi_value *argv, napi_value *result); +``` + +Calls `func` with `this = recv` the way Node.js calls JavaScript from native +code that was not itself called by JavaScript (an I/O completion, a timer of +the addon). Compared to `napi_call_function`: + +- the call runs inside a **callback scope**: when it is the outermost one and + no JavaScript is on the stack, the host's checkpoint (microtasks, + `process.nextTick`) runs after `func` returns, as Node's + `InternalCallbackScope` does; +- `recv` is converted with `ToObject` (`null` / `undefined` give + `napi_object_expected` with a `TypeError` pending); +- `func` must be a function (`napi_function_expected`); +- `async_context` may be `NULL`; at most 65535 arguments. + +`result` is optional. + +## Callback scopes + +### `napi_open_callback_scope` + +```c +napi_status napi_open_callback_scope(napi_env env, napi_value resource_object, + napi_async_context context, + napi_callback_scope *result); +``` + +Opens a callback scope, for native code that calls into JavaScript several +times (with `napi_call_function`) and wants a single checkpoint at the end. +`context` is required; `resource_object` is ignored, as in Node.js. + +### `napi_close_callback_scope` + +```c +napi_status napi_close_callback_scope(napi_env env, + napi_callback_scope scope); +``` + +Closes the scope. When it is the outermost callback scope of the host, no +JavaScript is below the current native code, and no exception is pending, +the checkpoint runs here. `napi_callback_scope_mismatch` when no callback +scope is open. + +```mermaid +flowchart TD + A["napi_close_callback_scope / end of napi_make_callback"] --> B{"outermost callback scope?"} + B -- no --> Z["nothing more"] + B -- yes --> C{"JavaScript below the native code?
(native_depth > 0)"} + C -- yes --> Z + C -- no --> D{"exception pending or env tearing down?"} + D -- yes --> Z + D -- no --> E["checkpoint: pending promise jobs
(or the embedder's checkpoint),
then kept objects cleared"] +``` + +Inside a Node-API callback called by JavaScript (the usual case) the caller's +own frame is still on the stack, so nothing runs early, exactly as in Node.js. + +## Uncaught exceptions + +### `napi_fatal_exception` + +```c +napi_status napi_fatal_exception(napi_env env, napi_value err); +``` + +Reports `err` as an uncaught exception **synchronously**: the host's uncaught +handler runs before the function returns. In the executable that means +`process.on('uncaughtException')` listeners, or printing the error and +exiting with code 1 when there are none. Despite its name, the process does +not necessarily end. diff --git a/doc/node-api/objects.md b/doc/node-api/objects.md new file mode 100644 index 0000000..6c4e9ac --- /dev/null +++ b/doc/node-api/objects.md @@ -0,0 +1,285 @@ +# Objects and properties + +[Node-API reference](README.md) › Objects + +Implemented in `src/object.c`. All functions here may run JavaScript +(getters, setters, proxy traps, `Symbol.hasInstance`) and refuse to start +with an exception pending. + +| Group | Functions | +|---|---| +| By key (`napi_value`) | [`napi_set_property`](#napi_set_property), [`napi_get_property`](#napi_get_property), [`napi_has_property`](#napi_has_property), [`napi_has_own_property`](#napi_has_own_property), [`napi_delete_property`](#napi_delete_property) | +| By name (C string) | [`napi_set_named_property`](#napi_set_named_property), [`napi_get_named_property`](#napi_get_named_property), [`napi_has_named_property`](#napi_has_named_property) | +| By index | [`napi_set_element`](#napi_set_element), [`napi_get_element`](#napi_get_element), [`napi_has_element`](#napi_has_element), [`napi_delete_element`](#napi_delete_element) | +| Definition | [`napi_define_properties`](#napi_define_properties) | +| Enumeration | [`napi_get_property_names`](#napi_get_property_names), [`napi_get_all_property_names`](#napi_get_all_property_names) | +| Prototype and integrity | [`napi_get_prototype`](#napi_get_prototype), [`napi_object_freeze`](#napi_object_freeze), [`napi_object_seal`](#napi_object_seal), [`napi_instanceof`](#napi_instanceof) | + +## Common rules + +These follow Node.js (`src/js_native_api_v8.cc`): + +- **The receiver goes through `ToObject`.** Primitives are wrapped (so + `napi_get_named_property(env, a_string, "length", ...)` works), while `null` + and `undefined` throw a `TypeError` and return `napi_object_expected` with + the exception pending. +- **Keys go through `ToPropertyKey`.** A `napi_value` key may be any value: a + number becomes its string form, an object is converted with `toString` / + `Symbol.toPrimitive`, which may run user code. Only `napi_has_own_property` + and `napi_define_properties` require a string or symbol + (`napi_name_expected`). +- **Setting is a sloppy-mode `[[Set]]`.** Assigning to a read-only property or + to a frozen object **fails silently** and returns `napi_ok`, like + `v8::Object::Set`. Setters and proxy `set` traps run. +- **Deleting is a sloppy-mode `delete`.** A non-configurable property is not + deleted, and `*result` is `false`; the call still returns `napi_ok`. + +--- + +## By key + +### `napi_set_property` + +```c +napi_status napi_set_property(napi_env env, napi_value object, napi_value key, + napi_value value); +``` + +`object[key] = value`. + +### `napi_get_property` + +```c +napi_status napi_get_property(napi_env env, napi_value object, napi_value key, + napi_value *result); +``` + +Stores `object[key]` (getters and the prototype chain included; `undefined` +when absent). + +### `napi_has_property` + +```c +napi_status napi_has_property(napi_env env, napi_value object, napi_value key, + bool *result); +``` + +`key in object`: own or inherited. + +### `napi_has_own_property` + +```c +napi_status napi_has_own_property(napi_env env, napi_value object, + napi_value key, bool *result); +``` + +`Object.prototype.hasOwnProperty.call(object, key)`. The key must be a string +or a symbol; anything else returns `napi_name_expected` (no conversion). + +### `napi_delete_property` + +```c +napi_status napi_delete_property(napi_env env, napi_value object, + napi_value key, bool *result); +``` + +`delete object[key]`. `*result` (optional, may be `NULL`) is `true` when the +property is gone afterwards (including when it never existed) and `false` +when it is non-configurable. + +## By name + +The name is a NUL-terminated UTF-8 string. These are shortcuts for the keyed +functions with a string key. + +### `napi_set_named_property` + +```c +napi_status napi_set_named_property(napi_env env, napi_value object, + const char *utf8name, napi_value value); +``` + +`object[utf8name] = value`. + +### `napi_get_named_property` + +```c +napi_status napi_get_named_property(napi_env env, napi_value object, + const char *utf8name, napi_value *result); +``` + +Stores `object[utf8name]`. + +### `napi_has_named_property` + +```c +napi_status napi_has_named_property(napi_env env, napi_value object, + const char *utf8name, bool *result); +``` + +`utf8name in object`. + +## By index + +`index` is an array index (`0` to `2^32 - 2` are array indices; larger values +are ordinary integer-like keys). + +### `napi_set_element` + +```c +napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, + napi_value value); +``` + +`object[index] = value`. On an array, extends `length` when needed. + +### `napi_get_element` + +```c +napi_status napi_get_element(napi_env env, napi_value object, uint32_t index, + napi_value *result); +``` + +Stores `object[index]` (`undefined` for holes and missing elements). + +### `napi_has_element` + +```c +napi_status napi_has_element(napi_env env, napi_value object, uint32_t index, + bool *result); +``` + +`index in object` (`false` for holes). + +### `napi_delete_element` + +```c +napi_status napi_delete_element(napi_env env, napi_value object, + uint32_t index, bool *result); +``` + +`delete object[index]`; `*result` as for `napi_delete_property`. + +## Definition + +### `napi_define_properties` + +```c +napi_status napi_define_properties(napi_env env, napi_value object, + size_t property_count, + const napi_property_descriptor *properties); +``` + +Defines each descriptor with `Object.defineProperty` semantics (a **complete** +descriptor: attributes not set are `false`). + +```c +typedef struct { + const char *utf8name; /* key as UTF-8, or NULL to use `name` */ + napi_value name; /* string or symbol key */ + napi_callback method; /* data property holding a new function */ + napi_callback getter; /* accessor property */ + napi_callback setter; + napi_value value; /* data property holding this value */ + napi_property_attributes attributes; + void *data; /* passed to method / getter / setter */ +} napi_property_descriptor; +``` + +| Descriptor | Defines | +|---|---| +| `getter` and/or `setter` | an accessor property; a missing half is `undefined`; `napi_writable` is ignored | +| `method` | a data property whose value is a new function (named after nothing, `length` 0) calling `method` with `data` | +| `value` (or nothing) | a data property holding `value` (or `undefined`) | + +Attributes: `napi_writable`, `napi_enumerable`, `napi_configurable`, and the +combinations `napi_default` (none), `napi_default_method` (writable + +configurable, like class methods) and `napi_default_jsproperty` (all three, +like an assignment). `napi_static` is only meaningful for +[`napi_define_class`](functions.md#napi_define_class). + +Definitions are applied in order and stop at the first failure: + +- a key that is neither `utf8name` nor a string/symbol `name` returns + `napi_name_expected`; +- a definition the object refuses (redefining a non-configurable property, + adding to a non-extensible object) returns `napi_invalid_arg` for data and + accessor properties and `napi_generic_failure` for methods, as in Node.js. + +## Enumeration + +### `napi_get_property_names` + +```c +napi_status napi_get_property_names(napi_env env, napi_value object, + napi_value *result); +``` + +Stores an array with the **enumerable string keys** of `object` and of its +prototype chain, array indices converted to strings: the keys a `for...in` +loop visits. Equivalent to `napi_get_all_property_names(env, object, +napi_key_include_prototypes, napi_key_enumerable | napi_key_skip_symbols, +napi_key_numbers_to_strings, result)`. + +### `napi_get_all_property_names` + +```c +napi_status napi_get_all_property_names(napi_env env, napi_value object, + napi_key_collection_mode key_mode, + napi_key_filter key_filter, + napi_key_conversion key_conversion, + napi_value *result); +``` + +Stores an array of keys, like V8's `Object::GetPropertyNames`: + +| Parameter | Values | +|---|---| +| `key_mode` | `napi_key_own_only`, or `napi_key_include_prototypes` (keys of the prototype chain that are not shadowed by an earlier object) | +| `key_filter` | bit mask: `napi_key_all_properties` (0), `napi_key_writable`, `napi_key_enumerable`, `napi_key_configurable` (keep only keys with these attributes), `napi_key_skip_strings`, `napi_key_skip_symbols` | +| `key_conversion` | `napi_key_keep_numbers` (array indices as Numbers) or `napi_key_numbers_to_strings` | + +Keys are in `OwnPropertyKeys` order for each object (integer indices +ascending, then strings in creation order, then symbols). An unknown +`key_mode` or `key_conversion` returns `napi_invalid_arg`. Proxy traps +(`ownKeys`, `getOwnPropertyDescriptor`) run. + +## Prototype and integrity + +### `napi_get_prototype` + +```c +napi_status napi_get_prototype(napi_env env, napi_value object, + napi_value *result); +``` + +`Object.getPrototypeOf(object)` (`null` at the end of the chain; the proxy +`getPrototypeOf` trap runs). + +### `napi_object_freeze` + +```c +napi_status napi_object_freeze(napi_env env, napi_value object); +``` + +`Object.freeze(object)`, through the builtin captured at startup. + +### `napi_object_seal` + +```c +napi_status napi_object_seal(napi_env env, napi_value object); +``` + +`Object.seal(object)`, through the builtin captured at startup. + +### `napi_instanceof` + +```c +napi_status napi_instanceof(napi_env env, napi_value object, + napi_value constructor, bool *result); +``` + +`object instanceof constructor`, `Symbol.hasInstance` included. When +`constructor` is not a function, a `TypeError` with code +`ERR_NAPI_CONS_FUNCTION` ("Constructor must be a function") is thrown and the +function returns `napi_function_expected`, as in Node.js. diff --git a/doc/node-api/scopes.md b/doc/node-api/scopes.md new file mode 100644 index 0000000..8be918b --- /dev/null +++ b/doc/node-api/scopes.md @@ -0,0 +1,137 @@ +# Handle scopes + +[Node-API reference](README.md) › Handle scopes + +Implemented in `src/scope.c`. The arena behind them is described in +[architecture.md](../architecture.md#values-and-handle-scopes). + +| Function | Purpose | +|---|---| +| [`napi_open_handle_scope`](#napi_open_handle_scope) | start a scope for temporary values | +| [`napi_close_handle_scope`](#napi_close_handle_scope) | release every value created since it opened | +| [`napi_open_escapable_handle_scope`](#napi_open_escapable_handle_scope) | same, with room for one value that survives | +| [`napi_close_escapable_handle_scope`](#napi_close_escapable_handle_scope) | close it | +| [`napi_escape_handle`](#napi_escape_handle) | promote one value to the parent scope | + +## When to use them + +Every `napi_value` keeps its JavaScript value alive until the scope it was +created in is closed. Each native entry point (a function call, module init, a +finalizer, a loop callback) already runs in an implicit scope, closed when it +returns. Explicit scopes are needed only when one call creates **many +temporary values**, typically in a loop: + +```c +for (uint32_t i = 0; i < n; i++) { + napi_handle_scope scope; + napi_open_handle_scope(env, &scope); + napi_value item; + napi_get_element(env, array, i, &item); /* released at close */ + /* ... */ + napi_close_handle_scope(env, scope); +} +``` + +Without the inner scope, a loop over a million elements keeps a million +values alive until the callback returns. + +```mermaid +flowchart TB + subgraph call["implicit scope of the native call"] + a["arg values"] + subgraph esc["escapable scope"] + t1["temporary"] + t2["temporary"] + r["result"] + end + slot["slot reserved in the parent
when the escapable scope opened"] + end + r -- "napi_escape_handle" --> slot +``` + +Rules: + +- Scopes are **strictly nested**: close them in reverse order of opening. + Closing a scope that is not the innermost one returns + `napi_handle_scope_mismatch` and closes nothing. +- A `napi_value` from a closed scope must not be used. +- Close every scope you open before returning. A scope left open by a + function called from JavaScript is closed automatically with the call's + implicit scope (Debug builds print a warning). A scope left open by a + callback entered from the event loop (async work `complete`, a thread-safe + function's `call_js_cb`) or by a finalizer is a **fatal error** ("a callback + left a handle scope open", "a finalizer left a handle scope open"), as in + Node.js. +- Opening a scope does not allocate in the steady state: scope records are + recycled. + +--- + +### `napi_open_handle_scope` + +```c +napi_status napi_open_handle_scope(napi_env env, napi_handle_scope *result); +``` + +Opens a scope nested in the current one. Values created afterwards belong to +it. + +### `napi_close_handle_scope` + +```c +napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); +``` + +Closes `scope`, releasing every value created since it was opened. + +- `napi_handle_scope_mismatch`: no user scope is open, or `scope` is not the + innermost one. +- `napi_invalid_arg`: `scope` is not a handle scope (for example an escapable + scope, which needs `napi_close_escapable_handle_scope`). + +### `napi_open_escapable_handle_scope` + +```c +napi_status napi_open_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope *result); +``` + +Opens a scope from which one value can be escaped. A slot is reserved in the +**parent** scope before the new scope starts, so the escaped value belongs to +the parent. + +### `napi_close_escapable_handle_scope` + +```c +napi_status napi_close_escapable_handle_scope( + napi_env env, napi_escapable_handle_scope scope); +``` + +Closes an escapable scope, with the same rules as `napi_close_handle_scope`. + +### `napi_escape_handle` + +```c +napi_status napi_escape_handle(napi_env env, napi_escapable_handle_scope scope, + napi_value escapee, napi_value *result); +``` + +Copies `escapee` into the slot reserved in the parent scope and stores in +`result` a `napi_value` that stays valid after `scope` is closed. Allowed once +per scope: a second call returns `napi_escape_called_twice`. + +```c +static napi_value make_point(napi_env env, double x, double y) { + napi_escapable_handle_scope scope; + napi_open_escapable_handle_scope(env, &scope); + napi_value obj, vx, vy, escaped; + napi_create_object(env, &obj); + napi_create_double(env, x, &vx); + napi_create_double(env, y, &vy); + napi_set_named_property(env, obj, "x", vx); + napi_set_named_property(env, obj, "y", vy); + napi_escape_handle(env, scope, obj, &escaped); + napi_close_escapable_handle_scope(env, scope); /* vx, vy released */ + return escaped; +} +``` diff --git a/doc/node-api/strings.md b/doc/node-api/strings.md new file mode 100644 index 0000000..ddfad1e --- /dev/null +++ b/doc/node-api/strings.md @@ -0,0 +1,233 @@ +# Strings, property keys and symbols + +[Node-API reference](README.md) › Strings + +Implemented in `src/string.c`. + +| Group | Functions | +|---|---| +| Creation | [`napi_create_string_latin1`](#napi_create_string_latin1), [`napi_create_string_utf8`](#napi_create_string_utf8), [`napi_create_string_utf16`](#napi_create_string_utf16) | +| External strings | [`node_api_create_external_string_latin1`](#node_api_create_external_string_latin1), [`node_api_create_external_string_utf16`](#node_api_create_external_string_utf16) | +| Property keys | [`node_api_create_property_key_latin1`](#node_api_create_property_key_latin1), [`node_api_create_property_key_utf8`](#node_api_create_property_key_utf8), [`node_api_create_property_key_utf16`](#node_api_create_property_key_utf16) | +| Extraction | [`napi_get_value_string_latin1`](#napi_get_value_string_latin1), [`napi_get_value_string_utf8`](#napi_get_value_string_utf8), [`napi_get_value_string_utf16`](#napi_get_value_string_utf16) | +| Symbols | [`napi_create_symbol`](#napi_create_symbol), [`node_api_symbol_for`](#node_api_symbol_for) | + +## How strings are converted + +JavaScript strings are sequences of UTF-16 code units. QuickJS has no public +UTF-16 API, but its UTF-8 entry points are lossless at the code-unit level, +and quickjs-napi relies on that: + +```mermaid +flowchart LR + U16["UTF-16 buffer
(may contain lone surrogates)"] -- "pairs: 4-byte sequences
lone surrogates: 3-byte sequences" --> W["WTF-8"] + W -- JS_NewStringLen --> S["QuickJS string"] + L1["latin1 buffer"] -- "each byte = one code point" --> U8["UTF-8"] -- JS_NewStringLen --> S + S -- "JS_ToCStringLen2(cesu8 = 1):
one sequence per code unit" --> C["CESU-8"] + C -- "decode unit by unit" --> O16["UTF-16 / latin1 output"] + S -- "JS_ToCStringLen2(cesu8 = 0)" --> W2["WTF-8"] -- "lone surrogates -> U+FFFD" --> O8["UTF-8 output"] +``` + +- **Creation** is exact: a UTF-16 buffer with lone surrogates round-trips + unchanged. +- **Extraction** follows V8 as used by Node.js: lengths are counted in code + units for latin1 and UTF-16 and in bytes for UTF-8; UTF-8 output never ends + with a partial character and replaces lone surrogates with U+FFFD; latin1 + output keeps the low byte of each code unit (V8 `WriteOneByte`). + +### Length arguments + +Creation functions take a `length` in code units (bytes for latin1 and +UTF-8, `char16_t` for UTF-16) or `NAPI_AUTO_LENGTH` for a NUL-terminated +string. `str` may be `NULL` only when `length` is `0`. A length above +`INT32_MAX` (other than `NAPI_AUTO_LENGTH`) returns `napi_invalid_arg`. + +### Buffer arguments + +The three `napi_get_value_string_*` functions share one protocol: + +| `buf` | `bufsize` | Effect | +|---|---|---| +| `NULL` | ignored | `*result` = full length (code units, or UTF-8 bytes), without the terminator. `result` is then required. | +| not `NULL` | `0` | nothing is written; `*result` = `0` | +| not `NULL` | `n > 0` | at most `n - 1` units are copied, then a NUL terminator; `*result` (optional) = units copied | + +The usual pattern is two calls: + +```c +size_t len; +napi_get_value_string_utf8(env, value, NULL, 0, &len); +char *s = malloc(len + 1); +napi_get_value_string_utf8(env, value, s, len + 1, &len); +``` + +All extraction functions return `napi_string_expected` when `value` is not a +string primitive (`String` objects are not converted). + +--- + +## Creation + +### `napi_create_string_latin1` + +```c +napi_status napi_create_string_latin1(napi_env env, const char *str, + size_t length, napi_value *result); +``` + +Creates a string from ISO-8859-1 bytes: each byte becomes the code point of +the same value (0x00 to 0xFF). + +### `napi_create_string_utf8` + +```c +napi_status napi_create_string_utf8(napi_env env, const char *str, + size_t length, napi_value *result); +``` + +Creates a string from UTF-8 bytes. + +### `napi_create_string_utf16` + +```c +napi_status napi_create_string_utf16(napi_env env, const char16_t *str, + size_t length, napi_value *result); +``` + +Creates a string from UTF-16 code units, lone surrogates included. With +`NAPI_AUTO_LENGTH` the buffer ends at the first `0` unit. + +## External strings + +V8 can create a string that points to memory owned by the addon. QuickJS +cannot: its strings always own their content. + +### `node_api_create_external_string_latin1` + +```c +napi_status node_api_create_external_string_latin1( + napi_env env, char *str, size_t length, + node_api_basic_finalize finalize_callback, void *finalize_hint, + napi_value *result, bool *copied); +``` + +Creates a string from latin1 bytes. The content is **always copied**: +`*copied` is set to `true` (when `copied` is not `NULL`) and +`finalize_callback(env, str, finalize_hint)` runs **before the function +returns**, so the addon may free `str` right away. This is exactly what +Node.js does when V8 is built with the pointer-compression sandbox, so addons +already handle it. + +### `node_api_create_external_string_utf16` + +```c +napi_status node_api_create_external_string_utf16( + napi_env env, char16_t *str, size_t length, + node_api_basic_finalize finalize_callback, void *finalize_hint, + napi_value *result, bool *copied); +``` + +Same, from UTF-16 code units. + +## Property keys + +V8 internalizes these strings so that property lookups with them are faster. +QuickJS turns any string used as a property key into an *atom*, so these +functions create **ordinary strings**; using them as keys is as fast as with +any other string. + +### `node_api_create_property_key_latin1` + +```c +napi_status node_api_create_property_key_latin1(napi_env env, const char *str, + size_t length, + napi_value *result); +``` + +Same as `napi_create_string_latin1`. + +### `node_api_create_property_key_utf8` + +```c +napi_status node_api_create_property_key_utf8(napi_env env, const char *str, + size_t length, + napi_value *result); +``` + +Same as `napi_create_string_utf8`. + +### `node_api_create_property_key_utf16` + +```c +napi_status node_api_create_property_key_utf16(napi_env env, + const char16_t *str, + size_t length, + napi_value *result); +``` + +Same as `napi_create_string_utf16`. + +## Extraction + +### `napi_get_value_string_latin1` + +```c +napi_status napi_get_value_string_latin1(napi_env env, napi_value value, + char *buf, size_t bufsize, + size_t *result); +``` + +Copies the string as one byte per UTF-16 code unit, keeping the **low byte** +of each unit (characters above U+00FF are therefore mangled, as in Node.js). +Lengths are in code units. + +### `napi_get_value_string_utf8` + +```c +napi_status napi_get_value_string_utf8(napi_env env, napi_value value, + char *buf, size_t bufsize, + size_t *result); +``` + +Copies the string as UTF-8. Lengths are in bytes. A character is never split: +if the next character does not fit in the remaining space, copying stops +before it. Lone surrogates become U+FFFD (`EF BF BD`). + +### `napi_get_value_string_utf16` + +```c +napi_status napi_get_value_string_utf16(napi_env env, napi_value value, + char16_t *buf, size_t bufsize, + size_t *result); +``` + +Copies the UTF-16 code units exactly (lone surrogates included). Lengths are +in code units; a buffer that is too short may end between the two halves of +a surrogate pair. + +## Symbols + +### `napi_create_symbol` + +```c +napi_status napi_create_symbol(napi_env env, napi_value description, + napi_value *result); +``` + +Creates a new unique symbol, like `Symbol(description)`. `description` may be +`NULL` (no description) or a string; anything else gives +`napi_string_expected`. Uses the `Symbol` function captured at startup. + +### `node_api_symbol_for` + +```c +napi_status node_api_symbol_for(napi_env env, const char *utf8description, + size_t length, napi_value *result); +``` + +`Symbol.for(description)`: returns the symbol registered under that key in +the global symbol registry, creating it if needed. The description is UTF-8 +with the usual length rules. + +Registered symbols are never collected; a `napi_ref` to one always stays +strong (see [lifetime.md](lifetime.md#napi_create_reference)). diff --git a/doc/node-api/values.md b/doc/node-api/values.md new file mode 100644 index 0000000..f5ca040 --- /dev/null +++ b/doc/node-api/values.md @@ -0,0 +1,271 @@ +# Values + +[Node-API reference](README.md) › Values + +Implemented in `src/value.c`. Semantics follow `src/js_native_api_v8.cc` of +Node.js: **getters never coerce** (a value of the wrong type gives +`napi_*_expected`), while the `napi_coerce_*` functions apply the ECMAScript +conversions and may run JavaScript. + +| Group | Functions | +|---|---| +| Singletons | [`napi_get_undefined`](#napi_get_undefined), [`napi_get_null`](#napi_get_null), [`napi_get_global`](#napi_get_global), [`napi_get_boolean`](#napi_get_boolean) | +| Creation | [`napi_create_object`](#napi_create_object), [`napi_create_array`](#napi_create_array), [`napi_create_array_with_length`](#napi_create_array_with_length), [`napi_create_double`](#napi_create_double), [`napi_create_int32`](#napi_create_int32), [`napi_create_uint32`](#napi_create_uint32), [`napi_create_int64`](#napi_create_int64) | +| Type and getters | [`napi_typeof`](#napi_typeof), [`napi_get_value_double`](#napi_get_value_double), [`napi_get_value_int32`](#napi_get_value_int32), [`napi_get_value_uint32`](#napi_get_value_uint32), [`napi_get_value_int64`](#napi_get_value_int64), [`napi_get_value_bool`](#napi_get_value_bool) | +| Coercion | [`napi_coerce_to_bool`](#napi_coerce_to_bool), [`napi_coerce_to_number`](#napi_coerce_to_number), [`napi_coerce_to_object`](#napi_coerce_to_object), [`napi_coerce_to_string`](#napi_coerce_to_string) | +| Arrays and comparison | [`napi_is_array`](#napi_is_array), [`napi_get_array_length`](#napi_get_array_length), [`napi_strict_equals`](#napi_strict_equals) | + +All the creation and getter functions work while an exception is pending. + +--- + +## Singletons + +### `napi_get_undefined` + +```c +napi_status napi_get_undefined(napi_env env, napi_value *result); +``` + +Stores `undefined`. + +### `napi_get_null` + +```c +napi_status napi_get_null(napi_env env, napi_value *result); +``` + +Stores `null`. + +### `napi_get_global` + +```c +napi_status napi_get_global(napi_env env, napi_value *result); +``` + +Stores the global object of the context (`globalThis`). + +### `napi_get_boolean` + +```c +napi_status napi_get_boolean(napi_env env, bool value, napi_value *result); +``` + +Stores `true` or `false`. + +## Creation + +### `napi_create_object` + +```c +napi_status napi_create_object(napi_env env, napi_value *result); +``` + +Creates an empty ordinary object (`{}`) whose prototype is +`Object.prototype`. + +### `napi_create_array` + +```c +napi_status napi_create_array(napi_env env, napi_value *result); +``` + +Creates an empty array (`[]`). + +### `napi_create_array_with_length` + +```c +napi_status napi_create_array_with_length(napi_env env, size_t length, + napi_value *result); +``` + +Creates an array whose `length` is `length`, with no elements (holes), like +`new Array(length)`. As with V8's `Array::New(int)`, a length above +`INT32_MAX` gives an empty array instead of failing. + +### `napi_create_double` + +```c +napi_status napi_create_double(napi_env env, double value, napi_value *result); +``` + +Creates a Number from a double (including `NaN`, `±Infinity`, `-0`). + +### `napi_create_int32` + +```c +napi_status napi_create_int32(napi_env env, int32_t value, napi_value *result); +``` + +Creates a Number from a signed 32-bit integer. + +### `napi_create_uint32` + +```c +napi_status napi_create_uint32(napi_env env, uint32_t value, + napi_value *result); +``` + +Creates a Number from an unsigned 32-bit integer. + +### `napi_create_int64` + +```c +napi_status napi_create_int64(napi_env env, int64_t value, napi_value *result); +``` + +Creates a **Number** (not a BigInt) from a signed 64-bit integer. Values +beyond ±2^53 lose precision, as in V8. Use +[`napi_create_bigint_int64`](binary-data.md#napi_create_bigint_int64) for exact +64-bit values. + +## Type and getters + +### `napi_typeof` + +```c +napi_status napi_typeof(napi_env env, napi_value value, + napi_valuetype *result); +``` + +Stores the type of `value`, like the `typeof` operator except that: + +- `null` is `napi_null` (not `napi_object`); +- values created by [`napi_create_external`](lifetime.md#napi_create_external) + are `napi_external` (JavaScript sees `typeof` `'object'`). + +Possible results: `napi_undefined`, `napi_null`, `napi_boolean`, +`napi_number`, `napi_bigint`, `napi_string`, `napi_symbol`, `napi_object`, +`napi_function`, `napi_external`. + +### `napi_get_value_double` + +```c +napi_status napi_get_value_double(napi_env env, napi_value value, + double *result); +``` + +Stores the value of a Number. `napi_number_expected` for anything else +(strings, BigInts and `Number` objects included). + +### `napi_get_value_int32` + +```c +napi_status napi_get_value_int32(napi_env env, napi_value value, + int32_t *result); +``` + +Stores the ECMAScript `ToInt32` of a Number: truncation towards zero, then +modulo 2^32 into the signed range. `NaN` and `±Infinity` give `0`. +`napi_number_expected` when `value` is not a Number. + +### `napi_get_value_uint32` + +```c +napi_status napi_get_value_uint32(napi_env env, napi_value value, + uint32_t *result); +``` + +Stores the ECMAScript `ToUint32` of a Number (same bit pattern as +`ToInt32`; `-1` gives `4294967295`). `NaN` and `±Infinity` give `0`. + +### `napi_get_value_int64` + +```c +napi_status napi_get_value_int64(napi_env env, napi_value value, + int64_t *result); +``` + +Stores the integer value of a Number, like V8's `Value::IntegerValue`: +truncation towards zero, **saturating** at `INT64_MIN` / `INT64_MAX` outside +the 64-bit range. `NaN` and `±Infinity` give `0`, as in Node.js. + +### `napi_get_value_bool` + +```c +napi_status napi_get_value_bool(napi_env env, napi_value value, bool *result); +``` + +Stores the value of a Boolean primitive. `napi_boolean_expected` for anything +else (truthy values are not converted: use `napi_coerce_to_bool`). + +## Coercion + +These follow the ECMAScript abstract operations and may call user code +(`valueOf`, `toString`, `Symbol.toPrimitive`, proxies). If it throws, the +exception stays pending. + +### `napi_coerce_to_bool` + +```c +napi_status napi_coerce_to_bool(napi_env env, napi_value value, + napi_value *result); +``` + +`ToBoolean(value)`. Never runs user code, but is still refused while an +exception is pending, as in Node.js. + +### `napi_coerce_to_number` + +```c +napi_status napi_coerce_to_number(napi_env env, napi_value value, + napi_value *result); +``` + +`ToNumber(value)`. A Number is returned as is. Symbols and BigInts throw a +`TypeError`; the function then returns `napi_number_expected` with the +exception pending. + +### `napi_coerce_to_object` + +```c +napi_status napi_coerce_to_object(napi_env env, napi_value value, + napi_value *result); +``` + +`ToObject(value)`: objects are returned as is, primitives are wrapped (`Number`, +`String`, `Boolean`, `Symbol`, `BigInt` objects), `null` and `undefined` throw +a `TypeError` and return `napi_object_expected`. + +### `napi_coerce_to_string` + +```c +napi_status napi_coerce_to_string(napi_env env, napi_value value, + napi_value *result); +``` + +`ToString(value)`. Symbols throw a `TypeError` (`napi_string_expected`, with +the exception pending). + +## Arrays and comparison + +### `napi_is_array` + +```c +napi_status napi_is_array(napi_env env, napi_value value, bool *result); +``` + +`Array.isArray(value)`. It never throws: a revoked Proxy reports `false`. +A Proxy whose target is an array reports `true`, like `Array.isArray`; V8's +`IsArray` reports `false` for every Proxy (see +[compatibility.md](../compatibility.md)). + +### `napi_get_array_length` + +```c +napi_status napi_get_array_length(napi_env env, napi_value value, + uint32_t *result); +``` + +Stores the `length` of an array. `napi_array_expected` when `value` is not an +array (typed arrays included). + +### `napi_strict_equals` + +```c +napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, + bool *result); +``` + +`lhs === rhs` (`NaN !== NaN`, `+0 === -0`, objects by identity, strings and +BigInts by value). diff --git a/doc/testing.md b/doc/testing.md new file mode 100644 index 0000000..f90957c --- /dev/null +++ b/doc/testing.md @@ -0,0 +1,108 @@ +# Testing + +quickjs-napi is tested against the behaviour of Node.js itself: most tests +are Node.js's own Node-API tests and the node-addon-api test suite, and our +own JavaScript tests also run under Node.js as a reference. CTest runs about +170 tests per configuration. + +```sh +ctest --preset unix-debug # everything +ctest --preset unix-debug -R '^naa/' # the node-addon-api suite +ctest --test-dir build/unix-debug -R js_host --output-on-failure +``` + +- [Test suites](#test-suites) +- [Consistency checks](#consistency-checks) +- [Sanitizers and leak checks](#sanitizers-and-leak-checks) +- [Tools](#tools) +- [Workflows](#workflows) + +## Test suites + +| Suite | CTest names | Source | What it covers | +|---|---|---|---| +| Our JS tests | `js_hello`, `js_values`, `js_binary`, `js_node_api`, `js_host` | `test/js`, addons in `test/addons` | values, binary data, `node_api.h`, the executable's host features (child processes, `-e`, `-r`, `NODE_OPTIONS`) | +| Node.js parity | `node_parity_*` | the same `test/js` scripts | runs those tests under Node.js 22 with the same addon binaries: the expectations are checked against the reference implementation | +| Node.js conformance | `node/js-native-api/...`, `node/node-api/...` | `test/node` (Node.js v22.23.4) | 30 tests of `js-native-api` and 19 of `node-api`; see [test/node/README.md](../test/node/README.md) | +| node-addon-api | `naa/` | `test/node-addon-api` (8.9.2) | 78 of the 83 test modules, each in the four binding variants (C++ exceptions, no exceptions, `Maybe`, custom namespace); see [the harness README](../test/node-addon-api/harness/README.md) | +| Embedding | `unit_embed` | `test/unit/test_embed.c` | what a JS test cannot observe: teardown order, handle-scope misuse, the error state, the finalizer queue of the embedding API | +| Fatal errors | `node/node-api/test_fatal/...` | `cmake/expect_abort.cmake` | runs a test that must abort (`napi_fatal_error`) and checks its output | + +The test addons are built **exactly like node-gyp addons**: they do not link +against the library and resolve `napi_*` from the executable. The same +binaries load in Node.js, which is what makes the parity tests possible. + +Tests not run, with the reason: + +- node-addon-api modules that need `worker_threads`, `npm`, or test the npm + package itself (5 of 83); +- Node.js tests that need `async_hooks` or `domain` (`test_async_context`, + `test_make_callback_recurse`) or `worker_threads` (`test_worker_*`). + +## Consistency checks + +| Test | Checks | +|---|---| +| `stubs_up_to_date` | `src/stubs_generated.c` matches the set of functions implemented (`tools/gen_stubs.py --check`) | +| `exports_complete` | the executable exports every Node-API function (`tools/check_exports.py`) | + +## Sanitizers and leak checks + +- **Debug builds** use a Debug QuickJS, whose `JS_FreeRuntime` asserts that + every object was released. Any `JSValue` leaked by the library aborts the + test. This is why the library frees, at teardown, what addons never deleted. +- **`unix-asan`** runs everything under AddressSanitizer, UndefinedBehavior + Sanitizer and LeakSanitizer, QuickJS included. `test/lsan.supp` suppresses + the leaks that Node.js and node-addon-api tests make **by design** (each + entry says why). +- **`unix-tsan`** runs everything under ThreadSanitizer, QuickJS and libuv + included: async work and thread-safe functions are exercised from several + threads. CI reduces ASLR entropy for it. + +## Tools + +| Tool | Purpose | +|---|---| +| `tools/gen_stubs.py` | regenerates `src/stubs_generated.c`: a stub (returning `napi_generic_failure` with a descriptive last-error message) for every function of the headers that no `src/*.c` defines. `--check` only verifies. | +| `tools/check_exports.py ` | verifies that the executable exports every Node-API function (`nm` or `objdump`) | +| `tools/napi_decls.py` | parses the declarations of `js_native_api.h` and `node_api.h`; shared by the two tools above so that they agree on the function set | +| `tools/sync_node_tests.py ` | vendors Node.js's `test/js-native-api` and `test/node-api` tests into `test/node`, applies the declared patches and generates `tests.cmake` from each `binding.gyp` (the build needs neither Python nor node-gyp) | +| `tools/sync_node_addon_api.py ` | vendors the node-addon-api headers and test suite into `test/node-addon-api`, applies the declared patches and generates `tests.cmake` | + +The vendored test directories are **generated**: do not edit them by hand. +Every change goes through the sync scripts, whose `PATCHES` / `SKIP_*` tables +give the reason for each difference from upstream. + +## Workflows + +### Implementing or changing a Node-API function + +1. Implement it in the `src/` file of its area, following the Node.js source + (`src/js_native_api_v8.cc`, `src/node_api.cc`) for statuses and edge + cases. Use the macros of `qjsnapi_internal.h` (`NAPI_PREAMBLE`, + `CHECK_ARG`, `CHECK_JS`, ...) so the error behaviour matches. +2. Run `python3 tools/gen_stubs.py` to drop its stub; `stubs_up_to_date` fails + otherwise. +3. Enable the matching Node.js test in `tools/sync_node_tests.py` (`TESTS`) and + re-run it, or add a case to a `test/js` script and its addon. +4. Run the suite in Debug (leak assertion) and under `unix-asan`. +5. Update the reference page in [doc/node-api](node-api/README.md) and, for a + deviation, [compatibility.md](compatibility.md). + +### Adding a JS test + +Write it so that it runs **unchanged under both runtimes** (see +`test/js/test_hello.js`): it receives the addon directory as an argument and +throws on the first failed expectation. Register it in `CMakeLists.txt` +next to the other `js_*` tests; the `node_parity_*` variant is added the same +way. + +### Updating the vendored suites + +```sh +git clone --depth 1 --branch v22.23.4 --filter=blob:none --sparse https://github.com/nodejs/node +git -C node sparse-checkout set --no-cone /test/js-native-api/ /test/node-api/ /test/common/gc.js /test/common/tick.js /LICENSE +python3 tools/sync_node_tests.py node + +python3 tools/sync_node_addon_api.py +```