diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f228e1e..59c692f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,19 @@ on: push: pull_request: workflow_dispatch: + inputs: + quickjs_build_ref: + description: "quickjs-build tag, branch or commit (default: its latest release)" + type: string + required: false + default: "" + # Called by release.yml, which passes the quickjs-build release it packages. + workflow_call: + inputs: + quickjs_build_ref: + type: string + required: false + default: "" permissions: contents: read @@ -13,10 +26,6 @@ concurrency: cancel-in-progress: true env: - # quickjs-build is built from source as a sibling directory (the default of - # QJSNAPI_QUICKJS_DIR and of the toolchain path in CMakePresets.json). - # The branch with QuickJS 2026-06-04; switch to a tag once it is released. - QUICKJS_BUILD_REF: feat/quickjs-2026-06-04 # Same major version as the local parity runs (Node.js 22.23). NODE_VERSION: "22" # UBSan findings fail the test (-fno-sanitize-recover is set by CMake too). @@ -26,6 +35,34 @@ env: TSAN_OPTIONS: halt_on_error=1:second_deadlock_stack=1 jobs: + # ---------------------------------------------------------------------------- + # quickjs-build is built from source as a sibling directory (the default of + # QJSNAPI_QUICKJS_DIR and of the toolchain path in CMakePresets.json): its + # latest release, or the ref given as input. CMake checks that its QuickJS + # headers are the ones in include/. + # ---------------------------------------------------------------------------- + quickjs-build: + name: quickjs-build ref + runs-on: ubuntu-24.04 + outputs: + ref: ${{ steps.ref.outputs.ref }} + steps: + - id: ref + env: + GH_TOKEN: ${{ github.token }} + INPUT_REF: ${{ inputs.quickjs_build_ref }} + run: | + ref=$INPUT_REF + if [ -z "$ref" ]; then + ref=$(gh release view --repo napi-bindings/quickjs-build --json tagName --jq .tagName) + fi + if [ -z "$ref" ]; then + echo "::error::cannot determine the latest quickjs-build release" + exit 1 + fi + echo "quickjs-build: $ref" + echo "ref=$ref" >> "$GITHUB_OUTPUT" + # ---------------------------------------------------------------------------- # Linux and macOS: native builds with the system compiler. The Debug builds # keep QuickJS's assertion that JS_FreeRuntime finds no live object, so every @@ -36,6 +73,7 @@ jobs: # ---------------------------------------------------------------------------- unix: name: ${{ matrix.name }} + needs: quickjs-build runs-on: ${{ matrix.os }} strategy: fail-fast: false @@ -75,7 +113,7 @@ jobs: - uses: actions/checkout@v7 with: repository: napi-bindings/quickjs-build - ref: ${{ env.QUICKJS_BUILD_REF }} + ref: ${{ needs.quickjs-build.outputs.ref }} path: quickjs-build - uses: actions/setup-python@v7 with: @@ -115,6 +153,7 @@ jobs: # ---------------------------------------------------------------------------- windows: name: ${{ matrix.name }} + needs: quickjs-build runs-on: windows-latest strategy: fail-fast: false @@ -135,7 +174,7 @@ jobs: - uses: actions/checkout@v7 with: repository: napi-bindings/quickjs-build - ref: ${{ env.QUICKJS_BUILD_REF }} + ref: ${{ needs.quickjs-build.outputs.ref }} path: quickjs-build - uses: actions/setup-python@v7 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3aae38c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,307 @@ +name: Release + +# Builds the binary packages of a release and attaches them to it. +# +# Every package is a zip archive, quickjs-napi--.zip: +# bin/ quickjs-napi (+ qjsnapi.dll on Windows) +# include/ Node-API headers, qjsnapi.h, quickjs.h, quickjs-libc.h, uv.h +# lib/ libqjsnapi.a, libqjs.a, libuv.a, the shared library, +# import libraries (Windows), cmake/qjsnapi (find_package) +# share/doc/quickjs-napi/ licenses, BUILDINFO.txt +# See doc/building.md#release-packages. +# +# Order: the full CI suite and the package builds run in parallel; every +# package is then used as a user would (test/package/smoke.sh) on a machine +# or emulator of its platform; the release gets its assets only when all of +# that passed. workflow_dispatch runs everything but the upload. + +on: + release: + types: [published] + workflow_dispatch: + inputs: + quickjs_build_ref: + description: "quickjs-build tag, branch or commit (default: its latest release)" + type: string + required: false + default: "" + +permissions: + contents: read + +jobs: + # ---------------------------------------------------------------------------- + # The version (checked against the release tag) and the quickjs-build + # release to build with. + # ---------------------------------------------------------------------------- + prepare: + name: Prepare + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.version.outputs.version }} + quickjs_build_ref: ${{ steps.quickjs-build.outputs.ref }} + steps: + - uses: actions/checkout@v7 + - id: version + env: + EVENT: ${{ github.event_name }} + TAG: ${{ github.event.release.tag_name }} + run: | + version=$(sed -n 's/^project(quickjs-napi VERSION \([0-9][0-9.]*\).*/\1/p' CMakeLists.txt) + if [ -z "$version" ]; then + echo "::error file=CMakeLists.txt::project(quickjs-napi VERSION x.y.z) not found" + exit 1 + fi + if [ "$EVENT" = release ] && [ "${TAG#v}" != "$version" ]; then + echo "::error::the tag $TAG does not match the project version $version (CMakeLists.txt)" + exit 1 + fi + echo "version: $version" + echo "version=$version" >> "$GITHUB_OUTPUT" + - id: quickjs-build + env: + GH_TOKEN: ${{ github.token }} + INPUT_REF: ${{ inputs.quickjs_build_ref }} + run: | + ref=$INPUT_REF + if [ -z "$ref" ]; then + ref=$(gh release view --repo napi-bindings/quickjs-build --json tagName --jq .tagName) + fi + if [ -z "$ref" ]; then + echo "::error::cannot determine the latest quickjs-build release" + exit 1 + fi + echo "quickjs-build: $ref" + echo "ref=$ref" >> "$GITHUB_OUTPUT" + + # ---------------------------------------------------------------------------- + # The whole test suite, on the same quickjs-build. + # ---------------------------------------------------------------------------- + ci: + name: CI + needs: prepare + uses: ./.github/workflows/ci.yml + with: + quickjs_build_ref: ${{ needs.prepare.outputs.quickjs_build_ref }} + + # ---------------------------------------------------------------------------- + # One package per platform. Linux, Windows and FreeBSD are cross-compiled + # with `zig cc` from Linux, with the zig targets of quickjs-build (glibc + # 2.17, MinGW-w64 UCRT); macOS is built natively with the Xcode SDK. + # ---------------------------------------------------------------------------- + build: + name: build ${{ matrix.platform }} + needs: prepare + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - { platform: linux-x86_64, os: ubuntu-24.04, zig: x86_64-linux-gnu.2.17 } + - { platform: linux-x86, os: ubuntu-24.04, zig: x86-linux-gnu.2.17 } + - { platform: linux-arm64, os: ubuntu-24.04, zig: aarch64-linux-gnu.2.17 } + - { platform: linux-armv7, os: ubuntu-24.04, zig: arm-linux-gnueabihf.2.17 } + - { platform: linux-riscv64, os: ubuntu-24.04, zig: riscv64-linux-gnu.2.27 } + - { platform: linux-x86_64-musl, os: ubuntu-24.04, zig: x86_64-linux-musl } + - { platform: linux-arm64-musl, os: ubuntu-24.04, zig: aarch64-linux-musl } + - { platform: windows-x86_64, os: ubuntu-24.04, zig: x86_64-windows-gnu } + - { platform: windows-x86, os: ubuntu-24.04, zig: x86-windows-gnu } + - { platform: windows-arm64, os: ubuntu-24.04, zig: aarch64-windows-gnu } + - { platform: freebsd-x86_64, os: ubuntu-24.04, zig: x86_64-freebsd } + - { platform: macos-arm64, os: macos-latest, arch: arm64 } + - { platform: macos-x86_64, os: macos-15-intel, arch: x86_64 } + env: + PACKAGE: quickjs-napi-${{ needs.prepare.outputs.version }}-${{ matrix.platform }} + steps: + - uses: actions/checkout@v7 + with: + path: quickjs-napi + - uses: actions/checkout@v7 + with: + repository: napi-bindings/quickjs-build + ref: ${{ needs.prepare.outputs.quickjs_build_ref }} + path: quickjs-build + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + - name: Install Ninja + run: python -m pip install ninja + - name: Install zig + if: matrix.zig + run: | + python -m pip install "ziglang==$(cat quickjs-build/.zigversion)" + mkdir -p "$RUNNER_TEMP/bin" + printf '#!/bin/sh\nexec "%s" -m ziglang "$@"\n' "$(command -v python)" > "$RUNNER_TEMP/bin/zig" + chmod +x "$RUNNER_TEMP/bin/zig" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + - name: Configure + env: + ZIG_TARGET: ${{ matrix.zig }} + ARCH: ${{ matrix.arch }} + QUICKJS_BUILD_REF: ${{ needs.prepare.outputs.quickjs_build_ref }} + run: | + set -- -S quickjs-napi -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DQJSNAPI_BUILD_TESTS=OFF \ + "-DQJSNAPI_QUICKJS_BUILD_REF=$QUICKJS_BUILD_REF" \ + "-DCMAKE_INSTALL_PREFIX=$PWD/stage/$PACKAGE" -DCMAKE_INSTALL_LIBDIR=lib + if [ -n "$ZIG_TARGET" ]; then + zig version + set -- "$@" "-DCMAKE_TOOLCHAIN_FILE=$PWD/quickjs-build/toolchains/zig.cmake" \ + "-DZIG_TARGET=$ZIG_TARGET" + else + # Same minimum as the quickjs-build archives. + set -- "$@" "-DCMAKE_OSX_ARCHITECTURES=$ARCH" -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 + fi + cmake "$@" + - name: Build + run: cmake --build build + - name: Package + run: | + cmake --install build + mkdir dist + (cd stage && zip -qr -9 "../dist/$PACKAGE.zip" "$PACKAGE") + unzip -l "dist/$PACKAGE.zip" + - uses: actions/upload-artifact@v7 + with: + name: package-${{ matrix.platform }} + path: dist/${{ env.PACKAGE }}.zip + if-no-files-found: error + + # ---------------------------------------------------------------------------- + # Each package used as a user would (test/package/smoke.sh): find_package, + # the embedding test linked with the static archives and with the shared + # library, a script and addons built with the package headers only. + # cc: the system compiler (else zig, for the package's target) + # run: command prefix for the binaries (qemu-user), "skip" = build only + # container: run inside this Docker image (musl: Alpine) + # ---------------------------------------------------------------------------- + smoke: + name: smoke ${{ matrix.platform }} + needs: [prepare, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - { platform: linux-x86_64, os: ubuntu-24.04, cc: gcc } + - { platform: linux-x86, os: ubuntu-24.04, zig: x86-linux-gnu.2.17, packages: libc6-i386 } + - { platform: linux-arm64, os: ubuntu-24.04-arm, cc: gcc } + - platform: linux-armv7 + os: ubuntu-24.04 + zig: arm-linux-gnueabihf.2.17 + packages: qemu-user libc6-armhf-cross + run: qemu-arm -L /usr/arm-linux-gnueabihf + - platform: linux-riscv64 + os: ubuntu-24.04 + zig: riscv64-linux-gnu.2.27 + packages: qemu-user libc6-riscv64-cross + run: qemu-riscv64 -L /usr/riscv64-linux-gnu + - { platform: linux-x86_64-musl, os: ubuntu-24.04, container: "alpine:3.22" } + - { platform: linux-arm64-musl, os: ubuntu-24.04-arm, container: "alpine:3.22" } + - { platform: windows-x86_64, os: windows-latest, zig: x86_64-windows-gnu } + - { platform: windows-x86, os: windows-latest, zig: x86-windows-gnu } + - { platform: windows-arm64, os: windows-11-arm, zig: aarch64-windows-gnu } + - { platform: macos-arm64, os: macos-latest, cc: cc } + - { platform: macos-x86_64, os: macos-15-intel, cc: cc } + # No hosted FreeBSD runner: compiled and linked only. + - { platform: freebsd-x86_64, os: ubuntu-24.04, zig: x86_64-freebsd, run: skip } + defaults: + run: + shell: bash + env: + PACKAGE: quickjs-napi-${{ needs.prepare.outputs.version }}-${{ matrix.platform }} + steps: + - uses: actions/checkout@v7 + with: + path: quickjs-napi + - uses: actions/checkout@v7 + if: matrix.zig + with: + repository: napi-bindings/quickjs-build + ref: ${{ needs.prepare.outputs.quickjs_build_ref }} + path: quickjs-build + - uses: actions/download-artifact@v8 + with: + name: package-${{ matrix.platform }} + path: dist + - name: Unpack + run: | + mkdir pkg + cd pkg + if command -v unzip >/dev/null 2>&1; then + unzip -q "../dist/$PACKAGE.zip" + else + cmake -E tar xf "../dist/$PACKAGE.zip" + fi + - uses: actions/setup-python@v7 + if: ${{ !matrix.container }} + with: + python-version: "3.x" + - name: Install Ninja + if: ${{ !matrix.container }} + run: python -m pip install ninja + - name: Install zig + if: matrix.zig + run: | + python -m pip install "ziglang==$(cat quickjs-build/.zigversion)" + if [ "$RUNNER_OS" = Windows ]; then + python -c "import os, ziglang; print(os.path.dirname(ziglang.__file__))" >> "$GITHUB_PATH" + else + mkdir -p "$RUNNER_TEMP/bin" + printf '#!/bin/sh\nexec "%s" -m ziglang "$@"\n' "$(command -v python)" > "$RUNNER_TEMP/bin/zig" + chmod +x "$RUNNER_TEMP/bin/zig" + echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH" + fi + - name: Install the runtime + if: matrix.packages + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends ${{ matrix.packages }} + - name: Smoke test + if: ${{ !matrix.container }} + env: + CC: ${{ matrix.cc }} + ZIG_TARGET: ${{ matrix.zig }} + RUN: ${{ matrix.run }} + BUILD_DIR: ${{ github.workspace }}/package-smoke + run: | + set -- + if [ -n "$ZIG_TARGET" ]; then + toolchain=$PWD/quickjs-build/toolchains/zig.cmake + if [ "$RUNNER_OS" = Windows ]; then toolchain=$(cygpath -m "$toolchain"); fi + set -- "-DCMAKE_TOOLCHAIN_FILE=$toolchain" "-DZIG_TARGET=$ZIG_TARGET" + fi + sh quickjs-napi/test/package/smoke.sh "pkg/$PACKAGE" "$@" + - name: Smoke test (${{ matrix.container }}) + if: matrix.container + env: + IMAGE: ${{ matrix.container }} + run: | + docker run --rm -v "$PWD:/w" -w /w -e PACKAGE "$IMAGE" sh -c ' + apk add --no-cache build-base cmake samurai >/dev/null && + BUILD_DIR=/w/package-smoke sh quickjs-napi/test/package/smoke.sh "pkg/$PACKAGE"' + + # ---------------------------------------------------------------------------- + # Attach the packages and their checksums to the release. + # ---------------------------------------------------------------------------- + publish: + name: Upload release assets + if: github.event_name == 'release' + needs: [prepare, ci, build, smoke] + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + pattern: package-* + path: dist + merge-multiple: true + - name: Checksums + working-directory: dist + run: sha256sum quickjs-napi-*.zip | tee SHA256SUMS + - name: Upload + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.release.tag_name }} + run: gh release upload "$TAG" dist/quickjs-napi-*.zip dist/SHA256SUMS --repo "$GITHUB_REPOSITORY" --clobber diff --git a/CMakeLists.txt b/CMakeLists.txt index 67934d8..0c6c510 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,7 @@ cmake_minimum_required(VERSION 3.24) -project(quickjs-napi LANGUAGES C) +# The release workflow checks that the tag of a release matches this version. +project(quickjs-napi VERSION 0.0.1 LANGUAGES C) # ------------------------------------------------------------------------------ # Options @@ -12,6 +13,19 @@ option(QJSNAPI_TSAN option(QJSNAPI_BUILD_TESTS "Build the test addons and the test suite" ON) option(QJSNAPI_NODE_ADDON_API_TESTS "Build and run the node-addon-api test suite (C++, 8 bindings)" ON) +option(QJSNAPI_BUILD_SHARED + "Also build libqjsnapi as a shared library, QuickJS and libuv included" + ON) +# Recorded in BUILDINFO.txt of the installed tree (set by the release workflow). +set(QJSNAPI_QUICKJS_BUILD_REF + "" + CACHE STRING "Tag or commit of quickjs-build, for BUILDINFO.txt") + +# The shared library contains QuickJS and libuv: every object must be +# position-independent, theirs included. +if(QJSNAPI_BUILD_SHARED) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) +endif() set(QJSNAPI_QUICKJS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../quickjs-build" @@ -68,10 +82,11 @@ include(FetchContent) set(LIBUV_BUILD_SHARED OFF CACHE BOOL "" FORCE) set(LIBUV_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(LIBUV_BUILD_BENCH OFF CACHE BOOL "" FORCE) +set(QJSNAPI_LIBUV_TAG v1.51.0) FetchContent_Declare( libuv GIT_REPOSITORY https://github.com/libuv/libuv.git - GIT_TAG v1.51.0 + GIT_TAG ${QJSNAPI_LIBUV_TAG} GIT_SHALLOW TRUE) if(POLICY CMP0169) cmake_policy(SET CMP0169 OLD) # FetchContent_Populate, for EXCLUDE_FROM_ALL @@ -243,6 +258,201 @@ if(WIN32 AND NOT MSVC) # static libgcc / libwinpthread, as for the quickjs-build tools target_link_options(quickjs-napi PRIVATE -static) endif() +# zig links musl executables statically by default, and a static musl +# executable cannot dlopen(): it could not load any addon. -dynamic links +# against the system's musl (/lib/ld-musl-.so.1, as on Alpine). +if(DEFINED ZIG_TARGET AND ZIG_TARGET MATCHES "-musl") + target_link_options(quickjs-napi PRIVATE -dynamic) +endif() + +# ------------------------------------------------------------------------------ +# Shared library: libqjsnapi.so / libqjsnapi.dylib / qjsnapi.dll +# ------------------------------------------------------------------------------ +# The same sources as the static library, linked with all of QuickJS and libuv +# (whole archive). An embedder must create its JSRuntime and JSContext with +# the QuickJS inside it: two copies of QuickJS in one process do not share +# their class IDs and atoms. So the library exports, besides napi_*, uv_* and +# qjsnapi_*, the QuickJS API (JS_*): +# - Linux/BSD/macOS: QuickJS is compiled with default visibility, libuv and +# our functions mark their API visible (UV_EXTERN, NAPI_EXTERN, +# QJSNAPI_EXTERN); everything else of ours is hidden. +# - Windows: napi_*, uv_* and qjsnapi_* carry __declspec(dllexport); +# QuickJS has no export annotation, so a .def file lists the JS_*, __JS_* +# and js_* symbols defined by libqjs.a, read from its symbol index +# (cmake/gen_def.cmake). +# zig's linker ignores --export-all-symbols. +if(QJSNAPI_BUILD_SHARED) + set(_qjsnapi_def) + if(WIN32) + set(_qjsnapi_def "${QJSNAPI_GENERATED_DIR}/qjsnapi_quickjs.def") + set(_qjsnapi_strip OFF) + if(CMAKE_SIZEOF_VOID_P EQUAL 4) + set(_qjsnapi_strip ON) # x86: C names are decorated with "_" + endif() + add_custom_command( + OUTPUT "${_qjsnapi_def}" + COMMAND "${CMAKE_COMMAND}" "-DLIB=$" + "-DSTRIP_UNDERSCORE=${_qjsnapi_strip}" + "-DOUTPUT=${_qjsnapi_def}" + # __JS_*: called by the inline functions of quickjs.h + "-DREGEX=^(__)?(JS|js)_[A-Za-z0-9_]+$" -P + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/gen_def.cmake" + DEPENDS "$" cmake/gen_def.cmake + COMMENT "Listing the QuickJS API exported by qjsnapi.dll" + VERBATIM) + endif() + add_library(qjsnapi_shared SHARED ${QJSNAPI_SOURCES} + "${QJSNAPI_GENERATED_DIR}/buffer_js.h" + ${_qjsnapi_def}) + set_target_properties( + qjsnapi_shared + PROPERTIES OUTPUT_NAME qjsnapi + C_STANDARD 17 + C_STANDARD_REQUIRED ON + C_VISIBILITY_PRESET hidden) + target_compile_definitions(qjsnapi_shared PRIVATE NAPI_VERSION=10) + target_include_directories( + qjsnapi_shared PUBLIC include PRIVATE src "${QJSNAPI_GENERATED_DIR}") + target_link_libraries( + qjsnapi_shared PRIVATE "$" + ${CMAKE_DL_LIBS}) + if(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(qjsnapi_shared PRIVATE -Wall -Wextra + -Wno-unused-parameter + -Wmissing-prototypes) + endif() + if(WIN32 AND NOT MSVC) + # qjsnapi.dll and libqjsnapi.dll.a, next to the static libqjsnapi.a + set_target_properties(qjsnapi_shared PROPERTIES PREFIX "") + endif() +endif() + +# ------------------------------------------------------------------------------ +# Installation (the layout of the release packages, see doc/building.md) +# ------------------------------------------------------------------------------ +# bin/ quickjs-napi, qjsnapi.dll (Windows) +# include/ the Node-API headers, qjsnapi.h, quickjs.h, quickjs-libc.h, uv.h +# lib/ libqjsnapi.a, libqjs.a, libuv.a: three archives, so that an +# embedder can link its own compatible QuickJS or libuv instead; +# the shared library; the import libraries (Windows) +# lib/cmake/qjsnapi/ find_package(qjsnapi) +# share/doc/quickjs-napi/ licenses and BUILDINFO.txt +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) +option(QJSNAPI_INSTALL_HOST "Install the quickjs-napi executable" ON) + +if(QJSNAPI_INSTALL_HOST) + # ARCHIVE: libquickjs-napi.dll.a on Windows, the import library that + # addons built with MinGW link against (the test addons do the same). + install(TARGETS quickjs-napi RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) +endif() +install(TARGETS qjsnapi ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) +if(QJSNAPI_BUILD_SHARED) + install(TARGETS qjsnapi_shared RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) +endif() +install(FILES "$" DESTINATION ${CMAKE_INSTALL_LIBDIR} + RENAME libqjs.a) +install(FILES "$" DESTINATION ${CMAKE_INSTALL_LIBDIR} + RENAME libuv.a) + +install( + FILES include/js_native_api.h + include/js_native_api_types.h + include/node_api.h + include/node_api_types.h + include/qjsnapi.h + include/quickjs.h + include/quickjs-libc.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) +# uv.h is part of the addon API (node-gyp puts it on the include path too). +install(DIRECTORY "${libuv_SOURCE_DIR}/include/" + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + +# Licenses: ours, QuickJS (MIT), quickjs-build (Apache-2.0), libuv (MIT and +# the licenses of the code it includes). +install(FILES LICENSE DESTINATION ${CMAKE_INSTALL_DOCDIR}) +set(_qjsnapi_licenses "${libuv_SOURCE_DIR}/LICENSE" libuv.txt + "${libuv_SOURCE_DIR}/LICENSE-extra" libuv-extra.txt) +if(EXISTS "${QJSNAPI_QUICKJS_DIR}/LICENSE.quickjs") + list(APPEND _qjsnapi_licenses "${QJSNAPI_QUICKJS_DIR}/LICENSE.quickjs" + QuickJS.txt "${QJSNAPI_QUICKJS_DIR}/LICENSE" quickjs-build.txt) +endif() +while(_qjsnapi_licenses) + list(POP_FRONT _qjsnapi_licenses _src _name) + install(FILES "${_src}" DESTINATION ${CMAKE_INSTALL_DOCDIR}/licenses + RENAME ${_name}) +endwhile() + +# What the package was built from. +if(DEFINED ZIG_TARGET) + set(_qjsnapi_target "${ZIG_TARGET}") +else() + set(_qjsnapi_target "${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") +endif() +set(_qjsnapi_quickjs "prebuilt ${QJSNAPI_QUICKJS_LIBRARY}") +if(EXISTS "${QJSNAPI_QUICKJS_DIR}/VERSION") + file(STRINGS "${QJSNAPI_QUICKJS_DIR}/VERSION" _qjsnapi_quickjs LIMIT_COUNT 1) +endif() +if(QJSNAPI_QUICKJS_BUILD_REF) + string(APPEND _qjsnapi_quickjs " (quickjs-build ${QJSNAPI_QUICKJS_BUILD_REF})") +endif() +file( + WRITE "${CMAKE_CURRENT_BINARY_DIR}/BUILDINFO.txt" + "quickjs-napi ${PROJECT_VERSION}\n" + "Node-API: 10 (Node.js 22 behaviour)\n" + "Target: ${_qjsnapi_target}\n" + "Compiler: ${CMAKE_C_COMPILER_ID} ${CMAKE_C_COMPILER_VERSION}\n" + "Build type: ${CMAKE_BUILD_TYPE}\n" + "QuickJS: ${_qjsnapi_quickjs}\n" + "libuv: ${QJSNAPI_LIBUV_TAG}\n") +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/BUILDINFO.txt" + DESTINATION ${CMAKE_INSTALL_DOCDIR}) + +# find_package(qjsnapi): the system libraries of each archive, as linked here. +function(qjsnapi_plain_link_libraries target out) + get_target_property(_libs ${target} INTERFACE_LINK_LIBRARIES) + set(_plain) + foreach(_lib IN LISTS _libs) + if(_lib MATCHES "^\\$$") + set(_lib "${CMAKE_MATCH_1}") + endif() + if(_lib AND NOT _lib MATCHES "\\$<") + list(APPEND _plain "${_lib}") + endif() + endforeach() + set(${out} "${_plain}" PARENT_SCOPE) +endfunction() +qjsnapi_plain_link_libraries(qjs QJSNAPI_PKG_QJS_LIBS) +qjsnapi_plain_link_libraries(uv_a QJSNAPI_PKG_UV_LIBS) +set(QJSNAPI_PKG_CORE_LIBS "${CMAKE_DL_LIBS}") +set(QJSNAPI_PKG_HOST ${QJSNAPI_INSTALL_HOST}) +set(QJSNAPI_PKG_SHARED ${QJSNAPI_BUILD_SHARED}) +if(WIN32) + set(QJSNAPI_PKG_SHARED_FILE "${CMAKE_INSTALL_BINDIR}/qjsnapi.dll") + set(QJSNAPI_PKG_SHARED_IMPLIB "${CMAKE_INSTALL_LIBDIR}/libqjsnapi.dll.a") + set(QJSNAPI_PKG_HOST_IMPLIB "${CMAKE_INSTALL_LIBDIR}/libquickjs-napi.dll.a") +elseif(APPLE) + set(QJSNAPI_PKG_SHARED_FILE "${CMAKE_INSTALL_LIBDIR}/libqjsnapi.dylib") +else() + set(QJSNAPI_PKG_SHARED_FILE "${CMAKE_INSTALL_LIBDIR}/libqjsnapi.so") +endif() +set(QJSNAPI_PKG_HOST_FILE + "${CMAKE_INSTALL_BINDIR}/quickjs-napi${CMAKE_EXECUTABLE_SUFFIX}") +set(QJSNAPI_CMAKE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/qjsnapi") +configure_package_config_file( + cmake/qjsnapiConfig.cmake.in + "${CMAKE_CURRENT_BINARY_DIR}/qjsnapiConfig.cmake" + INSTALL_DESTINATION ${QJSNAPI_CMAKE_DIR} + PATH_VARS CMAKE_INSTALL_INCLUDEDIR CMAKE_INSTALL_LIBDIR CMAKE_INSTALL_BINDIR) +write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/qjsnapiConfigVersion.cmake" + COMPATIBILITY SameMinorVersion) +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/qjsnapiConfig.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/qjsnapiConfigVersion.cmake" + DESTINATION ${QJSNAPI_CMAKE_DIR}) # ------------------------------------------------------------------------------ # Tests diff --git a/README.md b/README.md index 6fded0e..b8aa2ab 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ Details: [building](doc/building.md), [the executable](doc/host.md). | ↳ [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 | +| [Building](doc/building.md) | prerequisites, presets, options, Windows (zig, MSYS2), build outputs, installing, release packages, 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 | @@ -105,6 +105,7 @@ Test-suite specific notes: [test/node/README.md](test/node/README.md) | `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/package` | checks an installed / released package (`smoke.sh`, used by the release workflow) | | `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 | diff --git a/cmake/gen_def.cmake b/cmake/gen_def.cmake new file mode 100644 index 0000000..fac33ca --- /dev/null +++ b/cmake/gen_def.cmake @@ -0,0 +1,93 @@ +# Writes a module-definition (.def) file that exports the functions of a +# static archive whose names match REGEX. Used for qjsnapi.dll: QuickJS has +# no __declspec(dllexport) annotations, and the linker of zig ignores +# --export-all-symbols. +# +# cmake -DLIB=libqjs.a -DOUTPUT=out.def -DREGEX=^JS_ [-DSTRIP_UNDERSCORE=ON] +# -P gen_def.cmake +# +# STRIP_UNDERSCORE: for 32-bit x86, where the symbol names carry a leading +# "_" that the .def file must not. +# +# The names come from the archive's symbol index (its first member, "/"), +# which lists only the external symbols the archive defines: static +# functions and undefined references, which would make the link fail, are +# not in it. Layout of that member (System V / GNU, also written by llvm-ar +# for COFF): a 32-bit big-endian count, the member offsets, then the names, +# NUL-terminated. + +foreach(_var LIB OUTPUT REGEX) + if(NOT DEFINED ${_var}) + message(FATAL_ERROR "gen_def.cmake: -D${_var}=... is required") + endif() +endforeach() + +file(READ "${LIB}" _magic LIMIT 8) +if(NOT _magic STREQUAL "!\n") + message(FATAL_ERROR "${LIB} is not an ar archive") +endif() +# Member header: name[16] date[12] uid[6] gid[6] mode[8] size[10] fmag[2] +file(READ "${LIB}" _header OFFSET 8 LIMIT 60) +string(SUBSTRING "${_header}" 0 16 _name) +string(STRIP "${_name}" _name) +if(NOT _name STREQUAL "/") + message(FATAL_ERROR "${LIB} has no symbol index (run ranlib on it)") +endif() +string(SUBSTRING "${_header}" 48 10 _size) +string(STRIP "${_size}" _size) + +# Read the member as hex: CMake strings cannot hold NUL bytes. +file(READ "${LIB}" _hex OFFSET 68 LIMIT ${_size} HEX) +string(SUBSTRING "${_hex}" 0 8 _count_hex) +math(EXPR _count "0x${_count_hex}") +math(EXPR _names_start "(1 + ${_count}) * 8") # hex digits: count + offsets +string(SUBSTRING "${_hex}" ${_names_start} -1 _names_hex) + +# Byte -> character table for the printable ASCII range. +foreach(_code RANGE 33 126) + math(EXPR _byte "${_code}" OUTPUT_FORMAT HEXADECIMAL) + string(SUBSTRING "${_byte}" 2 -1 _byte) + string(LENGTH "${_byte}" _len) + if(_len EQUAL 1) + set(_byte "0${_byte}") + endif() + string(ASCII ${_code} _char) + set("_chr_${_byte}" "${_char}") +endforeach() + +set(_exports) +set(_current "") +set(_seen 0) +string(REGEX MATCHALL ".." _bytes "${_names_hex}") +foreach(_b IN LISTS _bytes) + if(_b STREQUAL "00") + # 32-bit x86 decorates C names with "_"; a .def file lists them without. + # (Not REGEX REPLACE "^_": it would strip every leading underscore.) + if(STRIP_UNDERSCORE AND _current MATCHES "^_") + string(SUBSTRING "${_current}" 1 -1 _current) + endif() + if(_current MATCHES "${REGEX}") + list(APPEND _exports "${_current}") + endif() + set(_current "") + math(EXPR _seen "${_seen} + 1") + if(_seen EQUAL _count) + break() + endif() + elseif(DEFINED "_chr_${_b}") + string(APPEND _current "${_chr_${_b}}") + else() + message(FATAL_ERROR "unexpected byte 0x${_b} in a symbol name of ${LIB}") + endif() +endforeach() +list(REMOVE_DUPLICATES _exports) +list(SORT _exports) +list(LENGTH _exports _count) +if(_count EQUAL 0) + message(FATAL_ERROR "no symbol of ${LIB} matches ${REGEX}") +endif() + +list(JOIN _exports "\n " _body) +file(WRITE "${OUTPUT}.tmp" "EXPORTS\n ${_body}\n") +file(COPY_FILE "${OUTPUT}.tmp" "${OUTPUT}" ONLY_IF_DIFFERENT) +file(REMOVE "${OUTPUT}.tmp") diff --git a/cmake/qjsnapiConfig.cmake.in b/cmake/qjsnapiConfig.cmake.in new file mode 100644 index 0000000..d0683d5 --- /dev/null +++ b/cmake/qjsnapiConfig.cmake.in @@ -0,0 +1,111 @@ +# CMake package of quickjs-napi @PROJECT_VERSION@ (Node-API on QuickJS). +# +# find_package(qjsnapi CONFIG REQUIRED) +# +# Imported targets: +# qjsnapi::static libqjsnapi.a with the bundled QuickJS and libuv +# qjsnapi::core libqjsnapi.a alone, for an embedder that links its +# own QuickJS and libuv: they must be ABI-compatible +# with the bundled quickjs.h and uv.h (see +# BUILDINFO.txt for the versions) +# qjsnapi::quickjs the bundled libqjs.a +# qjsnapi::uv the bundled libuv.a +# qjsnapi::shared the shared library, QuickJS and libuv inside +# qjsnapi::addon usage requirements of a .node addon +# qjsnapi::quickjs-napi the executable +# qjsnapi::shared and qjsnapi::quickjs-napi exist only when the package has +# them (QJSNAPI_HAS_SHARED, QJSNAPI_HAS_HOST). + +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) + +set(_qjsnapi_qjs_libs "@QJSNAPI_PKG_QJS_LIBS@") +set(_qjsnapi_uv_libs "@QJSNAPI_PKG_UV_LIBS@") +if("Threads::Threads" IN_LIST _qjsnapi_qjs_libs + OR "Threads::Threads" IN_LIST _qjsnapi_uv_libs) + find_dependency(Threads) +endif() + +set_and_check(_qjsnapi_include "@PACKAGE_CMAKE_INSTALL_INCLUDEDIR@") +set_and_check(_qjsnapi_lib "@PACKAGE_CMAKE_INSTALL_LIBDIR@") + +if(NOT TARGET qjsnapi::core) + add_library(qjsnapi::core STATIC IMPORTED) + set_target_properties( + qjsnapi::core + PROPERTIES IMPORTED_LOCATION "${_qjsnapi_lib}/libqjsnapi.a" + INTERFACE_INCLUDE_DIRECTORIES "${_qjsnapi_include}" + INTERFACE_LINK_LIBRARIES "@QJSNAPI_PKG_CORE_LIBS@") + + add_library(qjsnapi::quickjs STATIC IMPORTED) + set_target_properties( + qjsnapi::quickjs + PROPERTIES IMPORTED_LOCATION "${_qjsnapi_lib}/libqjs.a" + INTERFACE_INCLUDE_DIRECTORIES "${_qjsnapi_include}" + INTERFACE_LINK_LIBRARIES "${_qjsnapi_qjs_libs}") + + add_library(qjsnapi::uv STATIC IMPORTED) + set_target_properties( + qjsnapi::uv + PROPERTIES IMPORTED_LOCATION "${_qjsnapi_lib}/libuv.a" + INTERFACE_INCLUDE_DIRECTORIES "${_qjsnapi_include}" + INTERFACE_LINK_LIBRARIES "${_qjsnapi_uv_libs}") + + add_library(qjsnapi::static INTERFACE IMPORTED) + set_target_properties( + qjsnapi::static + PROPERTIES INTERFACE_LINK_LIBRARIES + "qjsnapi::core;qjsnapi::quickjs;qjsnapi::uv") + + set(QJSNAPI_HAS_SHARED @QJSNAPI_PKG_SHARED@) + if(QJSNAPI_HAS_SHARED) + add_library(qjsnapi::shared SHARED IMPORTED) + set_target_properties( + qjsnapi::shared + PROPERTIES IMPORTED_LOCATION + "${PACKAGE_PREFIX_DIR}/@QJSNAPI_PKG_SHARED_FILE@" + INTERFACE_INCLUDE_DIRECTORIES "${_qjsnapi_include}") + if(WIN32) + set_target_properties( + qjsnapi::shared + PROPERTIES IMPORTED_IMPLIB + "${PACKAGE_PREFIX_DIR}/@QJSNAPI_PKG_SHARED_IMPLIB@") + endif() + endif() + + set(QJSNAPI_HAS_HOST @QJSNAPI_PKG_HOST@) + if(QJSNAPI_HAS_HOST) + add_executable(qjsnapi::quickjs-napi IMPORTED) + set_target_properties( + qjsnapi::quickjs-napi + PROPERTIES IMPORTED_LOCATION + "${PACKAGE_PREFIX_DIR}/@QJSNAPI_PKG_HOST_FILE@") + endif() + + # An addon is built like node-gyp builds it: Node-API headers only, the + # napi_* and uv_* symbols are resolved from the process that loads it. + add_library(qjsnapi::addon INTERFACE IMPORTED) + set_target_properties( + qjsnapi::addon + PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${_qjsnapi_include}" + INTERFACE_COMPILE_DEFINITIONS BUILDING_NODE_EXTENSION) + if(WIN32 AND QJSNAPI_HAS_HOST) + # Imports from quickjs-napi.exe, through its import library. + set_target_properties( + qjsnapi::addon + PROPERTIES INTERFACE_LINK_LIBRARIES + "${PACKAGE_PREFIX_DIR}/@QJSNAPI_PKG_HOST_IMPLIB@") + elseif(APPLE) + set_target_properties( + qjsnapi::addon PROPERTIES INTERFACE_LINK_OPTIONS + "LINKER:-undefined,dynamic_lookup") + endif() +endif() + +unset(_qjsnapi_qjs_libs) +unset(_qjsnapi_uv_libs) +unset(_qjsnapi_include) +unset(_qjsnapi_lib) + +check_required_components(qjsnapi) diff --git a/doc/building.md b/doc/building.md index 4d14c00..3bcc731 100644 --- a/doc/building.md +++ b/doc/building.md @@ -9,13 +9,15 @@ configure time. - [Options](#options) - [Windows](#windows) - [What the build produces](#what-the-build-produces) +- [Installing](#installing) +- [Release packages](#release-packages) - [Continuous integration](#continuous-integration) ## Prerequisites | Requirement | Notes | |---|---| -| `quickjs-build` checked out **next to** this repository | `../quickjs-build`, branch `feat/quickjs-2026-06-04`; or point `QJSNAPI_QUICKJS_DIR` at it | +| `quickjs-build` checked out **next to** this repository | `../quickjs-build`, its latest release (7.0.0: QuickJS 2026-06-04); or point `QJSNAPI_QUICKJS_DIR` at it | | CMake and Ninja | | | A C17 compiler | gcc or clang on Linux/macOS; zig (`zig cc`) or MSYS2 MinGW on Windows. MSVC is not supported (QuickJS does not build with it) | | A C++17 compiler | only for the C++ test addons and the node-addon-api suite | @@ -72,6 +74,9 @@ assertions. | `QJSNAPI_TSAN` | `OFF` | ThreadSanitizer for everything (exclusive with `QJSNAPI_SANITIZE`) | | `QJSNAPI_BUILD_TESTS` | `ON` | test addons and the CTest suite | | `QJSNAPI_NODE_ADDON_API_TESTS` | `ON` | the node-addon-api suite (8 C++ bindings, about 2 minutes of build) | +| `QJSNAPI_BUILD_SHARED` | `ON` | also build the shared library (QuickJS and libuv inside); turns on position-independent code for everything | +| `QJSNAPI_INSTALL_HOST` | `ON` | install the `quickjs-napi` executable | +| `QJSNAPI_QUICKJS_BUILD_REF` | empty | the quickjs-build tag recorded in `BUILDINFO.txt` (set by the release workflow) | ## Windows @@ -114,6 +119,7 @@ resolves the `napi_*` imports from the running executable. | Target | What it is | |---|---| | `qjsnapi` | static library: the Node-API implementation and `qjsnapi.h` | +| `qjsnapi_shared` | shared library `libqjsnapi.so` / `libqjsnapi.dylib` / `qjsnapi.dll`: the same sources plus all of QuickJS and libuv ([embedding.md](embedding.md#from-a-release-package)) | | `quickjs-napi` | the executable ([host.md](host.md)); exports every `napi_*` and `uv_*` symbol | | `test_embed` | the C embedding test | | test addons | `test/addons`, the Node.js conformance addons, the 8 node-addon-api bindings | @@ -127,9 +133,83 @@ How the executable exports its symbols on each platform (whole archive, `--export-dynamic`, `__declspec(dllexport)`, `-undefined dynamic_lookup` for addons on macOS) is described in [embedding.md](embedding.md#linking). +On Windows, QuickJS has no export annotations: `cmake/gen_def.cmake` reads +the symbol index of `libqjs.a` and writes a `.def` file listing its +`JS_*`, `__JS_*` and `js_*` symbols for `qjsnapi.dll` (the zig linker +ignores `--export-all-symbols`). + +## Installing + +```sh +cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DQJSNAPI_BUILD_TESTS=OFF -DCMAKE_INSTALL_PREFIX=/opt/quickjs-napi +cmake --build build +cmake --install build +``` + +| Path | Content | +|---|---| +| `bin/` | `quickjs-napi`; `qjsnapi.dll` on Windows | +| `include/` | `node_api.h`, `node_api_types.h`, `js_native_api.h`, `js_native_api_types.h`, `qjsnapi.h`, `quickjs.h`, `quickjs-libc.h`, `uv.h`, `uv/*.h` | +| `lib/` | `libqjsnapi.a`, `libqjs.a`, `libuv.a` (three separate archives); `libqjsnapi.so` / `.dylib`; on Windows the import libraries `libqjsnapi.dll.a` (the DLL) and `libquickjs-napi.dll.a` (the executable, for MinGW addons) | +| `lib/cmake/qjsnapi/` | `find_package(qjsnapi)`, targets in [embedding.md](embedding.md#from-a-release-package) | +| `share/doc/quickjs-napi/` | `LICENSE`, `licenses/` (QuickJS, quickjs-build, libuv), `BUILDINFO.txt` (version, target, compiler, QuickJS and libuv versions) | + +`test/package/smoke.sh ` checks an installed tree: it builds +`test/package` with `find_package`, runs the embedding test linked with the +static archives and with the shared library, a script, and the addons of +`test/js/test_hello.js` built with the installed headers only. + +## Release packages + +`.github/workflows/release.yml` runs when a GitHub release is **published** +(or by hand, `workflow_dispatch`, which does everything but the upload): + +1. **prepare**: reads `project(quickjs-napi VERSION x.y.z)` from + `CMakeLists.txt` and fails if the release tag (`x.y.z` or `vx.y.z`) + differs; picks the latest release of quickjs-build (or the + `quickjs_build_ref` input). +2. **ci**: the whole CI suite (`ci.yml`) on that quickjs-build. +3. **build**: one package per platform, Release, tests off, installed and + zipped as `quickjs-napi--.zip` (the layout of + [Installing](#installing)). +4. **smoke**: `test/package/smoke.sh` on each package, on a machine or + emulator of its platform. +5. **publish**: only if everything above passed, uploads the zip files and + `SHA256SUMS` to the release. + +| Package | Built with | Smoke test | +|---|---|---| +| `linux-x86_64` | zig, glibc 2.17 | ubuntu, gcc | +| `linux-x86` | zig, glibc 2.17 | ubuntu (32-bit), zig | +| `linux-arm64` | zig, glibc 2.17 | ubuntu arm64, gcc | +| `linux-armv7` | zig, glibc 2.17 | qemu-user | +| `linux-riscv64` | zig, glibc 2.27 | qemu-user | +| `linux-x86_64-musl`, `linux-arm64-musl` | zig, musl | Alpine container, gcc | +| `windows-x86_64`, `windows-x86` | zig, MinGW-w64 UCRT | windows-latest, zig | +| `windows-arm64` | zig, MinGW-w64 UCRT | windows-11-arm, zig | +| `macos-arm64`, `macos-x86_64` | Apple clang, macOS 11+ | native runners | +| `freebsd-x86_64` | zig | compiled and linked only (no hosted FreeBSD runner) | + +**musl.** zig links musl executables statically by default, and a static +musl executable cannot `dlopen()` addons. The executable is therefore linked +**dynamically** against the system musl (`/lib/ld-musl-.so.1`, as on +Alpine); the libraries are the same as for the other platforms. If a musl +smoke test fails because of the executable, set `-DQJSNAPI_INSTALL_HOST=OFF` +for that package in `release.yml`: it then holds the headers and libraries +only (`find_package` reports `QJSNAPI_HAS_HOST` false), for embedders. + +**Not packaged:** WebAssembly (no `dlopen`, and libuv does not support WASI), +builds with MSVC (QuickJS does not compile with it; MSVC addons still load in +`quickjs-napi.exe`), Android and iOS. + +To release: bump `VERSION` in `CMakeLists.txt`, merge, then publish a +release whose tag is that version. + ## Continuous integration -`.github/workflows/ci.yml` runs on every push and pull request: +`.github/workflows/ci.yml` runs on every push and pull request, and from the +release workflow (`workflow_call`). It builds against the latest +quickjs-build release, or the `quickjs_build_ref` input: | Job | Preset | Compiler | |---|---|---| diff --git a/doc/embedding.md b/doc/embedding.md index 2a6e9b1..98dbde9 100644 --- a/doc/embedding.md +++ b/doc/embedding.md @@ -367,3 +367,48 @@ Node-API function is exported. Link with `uv_a` (libuv) and the QuickJS library the headers in `include/` were taken from. + +### From a release package + +The [release packages](building.md#release-packages) install a CMake +package: + +```cmake +find_package(qjsnapi CONFIG REQUIRED) # CMAKE_PREFIX_PATH= +target_link_libraries(my_app PRIVATE qjsnapi::static) # or qjsnapi::shared +``` + +| Target | What it is | +|---|---| +| `qjsnapi::static` | `libqjsnapi.a` + the bundled `libqjs.a` and `libuv.a`, with their system libraries | +| `qjsnapi::core` | `libqjsnapi.a` alone, to link **your own** QuickJS and libuv | +| `qjsnapi::quickjs`, `qjsnapi::uv` | the bundled `libqjs.a` and `libuv.a` | +| `qjsnapi::shared` | the shared library (`libqjsnapi.so`, `libqjsnapi.dylib`, `qjsnapi.dll`) | +| `qjsnapi::addon` | usage requirements of a `.node` addon for the `quickjs-napi` executable | +| `qjsnapi::quickjs-napi` | the executable | + +`test/package/CMakeLists.txt` uses each of them; it is what the release +workflow runs on every package. + +**Static: three archives.** QuickJS and libuv are separate archives so that +an embedder can replace them (`qjsnapi::core` plus its own libraries). The +replacements must be ABI-compatible with the headers of the package: the same +QuickJS release (`quickjs.h` defines the layout of `JSValue`) and a libuv 1.x +not older than the bundled one (`BUILDINFO.txt` has both versions). The rules +of the table above still apply: to load addons, the executable must link +`libqjsnapi.a` and libuv as whole archives and export their symbols. + +**Shared.** The shared library contains QuickJS and libuv and exports +`napi_*`, `uv_*`, `qjsnapi_*` and the QuickJS API (`JS_*`, `js_*`). Create the +`JSRuntime` and `JSContext` with the QuickJS **of the library**: do not link +another QuickJS in the same process (two copies do not share class IDs and +atoms, and values cannot cross between them). Limits: + +- **Windows:** node-gyp addons import Node-API from `node.exe`, and their + delay-load hook redirects that to the *executable* of the process, not to + `qjsnapi.dll`: they cannot load in a program that uses the DLL. Use the + static archives (exporting the symbols from the executable, as above), or + `quickjs-napi.exe`. Addons linked against `libqjsnapi.dll.a` instead load + normally. +- **Linux, BSD, macOS:** addons find the symbols in the shared library, which + is loaded globally with the executable; nothing else is needed. diff --git a/include/qjsnapi.h b/include/qjsnapi.h index b9b02c3..90b7952 100644 --- a/include/qjsnapi.h +++ b/include/qjsnapi.h @@ -32,6 +32,19 @@ #include "quickjs.h" #include "node_api_types.h" +/* Visibility of the embedding API, as NAPI_EXTERN in js_native_api.h: the + * library is compiled with hidden visibility, and the shared library + * (libqjsnapi.so / .dylib / qjsnapi.dll) exports these functions through this + * annotation. Calls through the import library of qjsnapi.dll need no + * __declspec(dllimport). */ +#ifndef QJSNAPI_EXTERN +#if defined(_WIN32) +#define QJSNAPI_EXTERN __declspec(dllexport) +#else +#define QJSNAPI_EXTERN __attribute__((visibility("default"))) +#endif +#endif + #ifdef __cplusplus extern "C" { #endif @@ -42,17 +55,21 @@ struct uv_loop_s; /* Creates the Node-API host for `ctx` and stores it as the context opaque * pointer, with a libuv loop of its own (closed by qjsnapi_host_destroy). * Returns NULL on failure (a JS exception may be pending). */ +QJSNAPI_EXTERN qjsnapi_host *qjsnapi_host_create(JSContext *ctx); /* Same, on the embedder's loop, which must outlive the host. The loop runs * on the thread that owns `ctx`. */ +QJSNAPI_EXTERN qjsnapi_host *qjsnapi_host_create_with_loop(JSContext *ctx, struct uv_loop_s *loop); /* The loop napi_get_uv_event_loop returns. */ +QJSNAPI_EXTERN struct uv_loop_s *qjsnapi_host_get_loop(qjsnapi_host *host); /* Returns the host attached to `ctx`, or NULL. */ +QJSNAPI_EXTERN qjsnapi_host *qjsnapi_host_from_context(JSContext *ctx); /* Tears down every env, as Node.js does at exit, with JavaScript disabled: @@ -62,6 +79,7 @@ qjsnapi_host *qjsnapi_host_from_context(JSContext *ctx); * references and instance data are finalized, the module cache is released * and the host is detached from the context. The embedder closes its own * handles on the loop first. Must be called before JS_FreeContext(). */ +QJSNAPI_EXTERN void qjsnapi_host_destroy(qjsnapi_host *host); /* Loads a `.node` shared library and runs its Node-API initializer. @@ -70,11 +88,13 @@ void qjsnapi_host_destroy(qjsnapi_host *host); * context. As with Node.js's process.dlopen, every call runs the addon's * initializer again with a new env and returns new exports (caching is the * module loader's job). */ +QJSNAPI_EXTERN int qjsnapi_load_addon(qjsnapi_host *host, const char *path, 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 semantics (0 selects the default, 8). */ +QJSNAPI_EXTERN int qjsnapi_init_static_addon(qjsnapi_host *host, const char *name, napi_addon_register_func init, int32_t module_api_version, JSValue *exports); @@ -82,14 +102,17 @@ int qjsnapi_init_static_addon(qjsnapi_host *host, const char *name, /* The minimal Node.js Buffer constructor used by napi_create_buffer* * (Buffer.from, alloc, toString, ...). The library does not install it as a * global: the embedder decides where it is visible. Returns a new reference. */ +QJSNAPI_EXTERN JSValue qjsnapi_host_get_buffer(qjsnapi_host *host); /* What napi_get_node_version reports: the Node.js release whose Node-API * behaviour is reproduced, with release name "quickjs-napi". A host that * provides `process` should report the same (process.version). */ +QJSNAPI_EXTERN const napi_node_version *qjsnapi_node_version(void); /* Highest Node-API version supported by this build. */ +QJSNAPI_EXTERN uint32_t qjsnapi_napi_version(void); /* ---- Finalizers ----------------------------------------------------------- @@ -103,6 +126,7 @@ uint32_t qjsnapi_napi_version(void); * JavaScript disabled (napi_cannot_run_js). */ /* Runs the queued finalizers of every env. Returns how many ran. */ +QJSNAPI_EXTERN size_t qjsnapi_host_run_finalizers(qjsnapi_host *host); /* ---- Weak references ------------------------------------------------------ @@ -117,9 +141,11 @@ size_t qjsnapi_host_run_finalizers(qjsnapi_host *host); * when the host is destroyed, and when the embedder calls this function. An * embedder clears it at the end of each macrotask it runs itself, and before * an explicit garbage collection (global.gc()). */ +QJSNAPI_EXTERN void qjsnapi_host_clear_kept_objects(qjsnapi_host *host); /* Non-zero when finalizers are queued: the event loop must not exit yet. */ +QJSNAPI_EXTERN int qjsnapi_host_has_pending_finalizers(qjsnapi_host *host); /* Called with an exception that no JavaScript frame can catch: thrown by a @@ -128,6 +154,7 @@ int qjsnapi_host_has_pending_finalizers(qjsnapi_host *host); * printed on stderr and dropped. */ typedef void (*qjsnapi_uncaught_fn)(qjsnapi_host *host, JSContext *ctx, JSValue exception, void *opaque); +QJSNAPI_EXTERN void qjsnapi_host_set_uncaught_handler(qjsnapi_host *host, qjsnapi_uncaught_fn fn, void *opaque); @@ -139,6 +166,7 @@ void qjsnapi_host_set_uncaught_handler(qjsnapi_host *host, * exceptions to the uncaught handler. */ typedef void (*qjsnapi_checkpoint_fn)(qjsnapi_host *host, JSContext *ctx, void *opaque); +QJSNAPI_EXTERN void qjsnapi_host_set_checkpoint(qjsnapi_host *host, qjsnapi_checkpoint_fn fn, void *opaque); @@ -146,6 +174,7 @@ void qjsnapi_host_set_checkpoint(qjsnapi_host *host, qjsnapi_checkpoint_fn fn, * 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. */ +QJSNAPI_EXTERN void qjsnapi_host_set_force_uncaught_exceptions_policy(qjsnapi_host *host, int force); diff --git a/test/package/CMakeLists.txt b/test/package/CMakeLists.txt new file mode 100644 index 0000000..c308352 --- /dev/null +++ b/test/package/CMakeLists.txt @@ -0,0 +1,49 @@ +# Uses an installed quickjs-napi package the way a user would: through +# find_package(qjsnapi), with nothing from this source tree but test sources. +# Run by test/package/smoke.sh (and by the release workflow on every package). +# +# cmake -S test/package -B build-pkg -DCMAKE_PREFIX_PATH= +cmake_minimum_required(VERSION 3.24) +project(qjsnapi_package_test LANGUAGES C) + +find_package(qjsnapi CONFIG REQUIRED) + +set(_root "${CMAKE_CURRENT_SOURCE_DIR}/../..") + +# The embedding test against the three static archives. +add_executable(embed_static "${_root}/test/unit/test_embed.c") +target_link_libraries(embed_static PRIVATE qjsnapi::static) +target_compile_definitions(embed_static PRIVATE NAPI_VERSION=10) + +# The same test against the shared library, QuickJS included. +if(QJSNAPI_HAS_SHARED) + add_executable(embed_shared "${_root}/test/unit/test_embed.c") + target_link_libraries(embed_shared PRIVATE qjsnapi::shared) + target_compile_definitions(embed_shared PRIVATE NAPI_VERSION=10) + if(WIN32) + # Windows has no rpath: the DLL must be next to the executable. + add_custom_command( + TARGET embed_shared POST_BUILD + COMMAND "${CMAKE_COMMAND}" -E copy_if_different + "$" "$" + VERBATIM) + endif() +endif() + +# The addons of test/js/test_hello.js, built with the package headers only +# and loaded by the executable of the package. +if(QJSNAPI_HAS_HOST) + foreach(_addon hello/hello loader/legacy loader/fnexport loader/future) + get_filename_component(_name "${_addon}" NAME) + add_library(${_name} MODULE "${_root}/test/addons/${_addon}.c") + set_target_properties( + ${_name} + PROPERTIES PREFIX "" + SUFFIX ".node" + C_VISIBILITY_PRESET hidden + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/addons") + target_compile_definitions(${_name} PRIVATE NAPI_VERSION=10) + target_link_libraries(${_name} PRIVATE qjsnapi::addon) + endforeach() +endif() diff --git a/test/package/smoke.sh b/test/package/smoke.sh new file mode 100644 index 0000000..1e60184 --- /dev/null +++ b/test/package/smoke.sh @@ -0,0 +1,69 @@ +#!/bin/sh +# Checks an installed (or unzipped) quickjs-napi package. +# +# test/package/smoke.sh [extra cmake configure arguments] +# +# Builds test/package with the package (find_package(qjsnapi)), then runs: +# - the embedding test linked with the static archives and, if present, +# with the shared library; +# - if the package has the executable: a script, and an addon built with +# the package headers only (test/js/test_hello.js). +# +# Environment: +# BUILD_DIR build tree (default: ./package-smoke) +# RUN command prefix for the target's binaries, e.g. an emulator +# ("qemu-arm -L /usr/arm-linux-gnueabihf"); "skip" builds only +# CC C compiler, as usual (or a toolchain file in the arguments) +set -eu + +if [ $# -lt 1 ]; then + echo "usage: $0 [cmake arguments]" >&2 + exit 2 +fi +pkg=$(CDPATH= cd -- "$1" && pwd) +shift +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH= cd -- "$here/../.." && pwd) +build=${BUILD_DIR:-$PWD/package-smoke} + +# Paths handed to the target's binaries: native form on Windows (MSYS bash). +native() { + if command -v cygpath >/dev/null 2>&1; then cygpath -m "$1"; else echo "$1"; fi +} + +run() { + echo "+ ${RUN:-} $*" + # RUN is a command prefix: word splitting is intended. + # shellcheck disable=SC2086 + ${RUN:-} "$@" +} + +if [ -f "$pkg/share/doc/quickjs-napi/BUILDINFO.txt" ]; then + cat "$pkg/share/doc/quickjs-napi/BUILDINFO.txt" +fi + +cmake -S "$here" -B "$build" -G Ninja -DCMAKE_BUILD_TYPE=Release \ + "-DCMAKE_PREFIX_PATH=$(native "$pkg")" "$@" +cmake --build "$build" + +if [ "${RUN:-}" = skip ]; then + echo "built only (RUN=skip)" + exit 0 +fi + +run "$build/embed_static" +if [ -f "$build/embed_shared" ] || [ -f "$build/embed_shared.exe" ]; then + run "$build/embed_shared" +fi + +host="$pkg/bin/quickjs-napi" +if [ -f "$host" ] || [ -f "$host.exe" ]; then + run "$host" -e " + const b = require('buffer').Buffer.from('aGk=', 'base64'); + if (b.toString() !== 'hi') throw new Error('Buffer: ' + b.toString()); + console.log('script ok');" + run "$host" "$(native "$root/test/js/test_hello.js")" "$(native "$build/addons")" +else + echo "no executable in the package: addon test skipped" +fi +echo "package ok"