8000 Let code that calls init() run on Node.js, so that the types match the build loaded at run time by dominion525 · Pull Request #179 · dominion525/jetdb · GitHub
[go: up one dir, main page]

Skip to content
Merged
< 8000 div class="d-flex flex-items-center flex-wrap" style="gap: 4px 16px;" data-pjax="#repo-content-pjax-container" data-turbo-frame="repo-content-turbo-frame">
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/jetdb-wasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ document.querySelector("input[type=file]").addEventListener("change", async (eve
});
```

In Node.js, and in a bundle built for the server, the module is ready when it is imported, and has no default export to call:
In Node.js, and in a bundle built for the server, the module is ready when it is imported, so there is no need to call `init()`. It is there and does nothing, so code that calls it, such as code shared with the browser, runs as well:

```js
import { readFileSync } from "node:fs";
Expand Down Expand Up @@ -54,7 +54,7 @@ db.free();

Values come as JavaScript values: numbers, bigints, booleans, strings (for text and dates, and for money, decimals and other values that a number would round), `Uint8Array` for binary data, and arrays for attachments and multiple values. A method that fails throws an `Error` named `JetdbError`, whose `code` tells what went wrong, such as `PASSWORD_REQUIRED` or `TABLE_NOT_FOUND`.

The package includes TypeScript types. See [the JavaScript API](https://github.com/dominion525/jetdb/blob/main/docs/wasm.md) for each method and its options.
The package includes TypeScript types, which need TypeScript 5.2 or later. See [the JavaScript API](https://github.com/dominion525/jetdb/blob/main/docs/wasm.md) for each method and its options.

## Limitations

Expand Down
10 changes: 8 additions & 2 deletions crates/jetdb-wasm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@
"exports": {
".": {
"node": {
"types": "./node/jetdb_wasm.d.ts",
"default": "./node/jetdb_wasm.js"
"import": {
"types": "./node/jetdb_wasm.d.mts",
"default": "./node/jetdb_wasm.mjs"
},
"default": {
"types": "./node/jetdb_wasm.d.ts",
"default": "./node/jetdb_wasm.js"
}
},
"default": {
"types": "./web/jetdb_wasm.d.ts",
Expand Down
10 changes: 9 additions & 1 deletion crates/jetdb-wasm/tests/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import { runInNewContext } from "node:vm";

import { Database as NodeDatabase } from "jetdb-wasm";
import init, { Database as NodeDatabase, initSync } from "jetdb-wasm";

const testdata = process.argv[2];
const read = (file) => readFileSync(join(testdata, file));
Expand Down Expand Up @@ -576,6 +576,14 @@ function checkPassword(Database, build) {
assert.deepEqual(Database.open(encrypted, "Test123").tables(), ["Table1"], build);
}

// The Node.js build is ready when it is imported, and its init and initSync,
// which initialize the web build, do nothing. A require gives the same build.
assert.equal(await init(), undefined);
assert.equal(initSync(), undefined);
const required = createRequire(import.meta.url)("jetdb-wasm");
assert.equal(required.Database, NodeDatabase);
assert.equal(await required.default(), undefined);
assert.equal(required.initSync(), undefined);
check(NodeDatabase, "node");

const packageDir = dirname(dirname(createRequire(import.meta.url).resolve("jetdb-wasm")));
Expand Down
10 changes: 9 additions & 1 deletion crates/jetdb-wasm/tests/types/check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
// under @ts-expect-error must fail to type-check, and tsc reports it when it
// does not.

import {
import init, {
Database,
initSync,
type Column,
type ColumnType,
type Index,
Expand Down Expand Up @@ -44,6 +45,13 @@ import {

declare const bytes: Uint8Array;

// Both builds have init and initSync, so code that initializes the web build
// type-checks with the types of either.
export async function load(): Promise<void> {
await init();
initSync({ module: bytes });
}

const db = Database.open(bytes);
Database.open(bytes, "password");
Database.open(bytes, undefined);
Expand Down
13 changes: 13 additions & 0 deletions crates/jetdb-wasm/tests/types/require.cts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Checks the types of the Node.js build as a CommonJS module imports it, with
// require rather than import. Only type-checked, with tsconfig.node.json; see
// check.ts.

import init, { Database, initSync } from "jetdb-wasm";

declare const bytes: Uint8Array;

export async function open(): Promise<Database> {
await init();
initSync({ module: bytes });
return Database.open(bytes);
}
2 changes: 1 addition & 1 deletion crates/jetdb-wasm/tests/types/tsconfig.node.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
"strict": true,
"noEmit": true
},
"files": ["check.ts"]
"files": ["check.ts", "require.cts"]
}
4 changes: 2 additions & 2 deletions docs/wasm.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[English](wasm.md)

jetdb-wasm は、jetdb を WebAssembly にしたもので、Microsoft Access のデータベース(.mdb / .accdb)をブラウザと Node.js で読みます。この文書では、その `Database` クラスを説明します。パッケージには TypeScript の型定義が入っていて、メソッドが返すオブジェクトの各フィールドは、型定義の説明文に書かれています。
jetdb-wasm は、jetdb を WebAssembly にしたもので、Microsoft Access のデータベース(.mdb / .accdb)をブラウザと Node.js で読みます。この文書では、その `Database` クラスを説明します。パッケージには TypeScript の型定義が入っていて、メソッドが返すオブジェクトの各フィールドは、型定義の説明文に書かれています。型定義には TypeScript 5.2 以降が必要です。

## モジュールの読み込み

Expand All @@ -16,7 +16,7 @@ import init, { Database } from "jetdb-wasm";
await init();
```

CommonJS のビルドでは、読み込んだときに Wasm のファイルが読まれるので、`Database` はそのまま使えます。Node.js と、サーバーサイドレンダリング(SSR)のようにバンドラーがサーバー向けにビルドするものが、このビルドを使います。このビルドには、呼ぶための既定のエクスポートがありません。
CommonJS のビルドでは、読み込んだときに Wasm のファイルが読まれるので、`Database` はそのまま使えます。Node.js と、サーバーサイドレンダリング(SSR)のようにバンドラーがサーバー向けにビルドするものが、このビルドを使います。このビルドでは既定のエクスポートを呼ぶ必要はありません。既定のエクスポートと `initSync` はあって、何もしないので、ブラウザと共有するコードのように、これらを呼ぶコードもそのまま動きます。

```js
import { Database } from "jetdb-wasm";
Expand Down
4 changes: 2 additions & 2 deletions docs/wasm.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[日本語版 (Japanese)](wasm.ja.md)

jetdb-wasm is jetdb built as WebAssembly, for reading Microsoft Access databases (.mdb / .accdb) in the browser and Node.js. This document describes its `Database` class. The package includes TypeScript types, whose comments describe each field of the objects the methods return.
jetdb-wasm is jetdb built as WebAssembly, for reading Microsoft Access databases (.mdb / .accdb) in the browser and Node.js. This document describes its `Database` class. The package includes TypeScript types, whose comments describe each field of the objects the methods return. The types need TypeScript 5.2 or later.

## Loading the Module

Expand All @@ -16,7 +16,7 @@ import init, { Database } from "jetdb-wasm";
await init();
```

Node.js, and a bundle built for the server, such as for server-side rendering, get the CommonJS build. It loads its Wasm file when it is imported, so `Database` is ready to use, and it has no default export to call:
Node.js, and a bundle built for the server, such as for server-side rendering, get the CommonJS build. It loads its Wasm file when it is imported, so `Database` is ready to use without calling the default export. The default export and `initSync` are there and do nothing, so code that calls them, such as code shared with the browser, runs as well:

```js
import { Database } from "jetdb-wasm";
Expand Down
37 changes: 37 additions & 0 deletions scripts/build-wasm-package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,42 @@ wasm-bindgen --target nodejs --out-dir "$OUT_DIR/node" "$wasm"
# The web build is an ES module; node/ stays CommonJS.
echo '{ "type": "module" }' >"$OUT_DIR/web/package.json"

# The web build is initialized with its default export, init, or with
# initSync. The Node.js build loads its Wasm when it is required, so it gets
# an init and an initSync that do nothing: the two builds then have the same
# shape, and code that calls init runs on both. __esModule tells TypeScript
# and bundlers that the default export is exports.default. Node.js gives
# module.exports as the default export of CommonJS to an ES module, so ES
# modules import the Node.js build through jetdb_wasm.mjs, which gives init
# as its default export. Its types do not use those of the browser, which a
# project for Node.js may not have.
cat >>"$OUT_DIR/node/jetdb_wasm.js" <<'EOF'

exports.default = async function init() {};
exports.initSync = function initSync() {};
Object.defineProperty(exports, "__esModule", { value: true });
EOF
cat >"$OUT_DIR/node/jetdb_wasm.mjs" <<'EOF'
import jetdb from "./jetdb_wasm.js";

export * from "./jetdb_wasm.js";
export default jetdb.default;
EOF
cat >>"$OUT_DIR/node/jetdb_wasm.d.ts" <<'EOF'

/**
* Does nothing: the Node.js build loads its Wasm when it is imported. The web
* build is initialized with it, so code that calls it runs on both.
*/
export function initSync(module?: unknown): void;

/**
* Does nothing: the Node.js build loads its Wasm when it is imported. The web
* build is initialized with it, so code that calls it runs on both.
*/
export default function init(module_or_path?: unknown): Promise<void>;
EOF

# The generated types declare [Symbol.dispose](), which the TypeScript
# libraries before esnext lack. Referencing that library from the types lets
# projects with an older target use them without changing their settings
Expand All @@ -62,6 +98,7 @@ for build in web node; do
{ echo '/// <reference lib="esnext.disposable" />'; cat "$types"; } >"$types.tmp"
mv "$types.tmp" "$types"
done
cp "$OUT_DIR/node/jetdb_wasm.d.ts" "$OUT_DIR/node/jetdb_wasm.d.mts"

jq --arg version "$crate_version" '.version = $version' "$CRATE_DIR/package.json" \
>"$OUT_DIR/package.json"
Expand Down
5 changes: 4 additions & 1 deletion scripts/test-wasm-package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ fi
echo "readme ok"

# tsc finds jetdb-wasm in $work/node_modules, one directory up. The node config
# resolves the node condition of the exports, the bundler config the default.
# resolves the node condition of the exports, for an import (check.ts) and for
# a require (require.cts), and the bundler config the default. The node10
# resolution, which reads the top-level "types", the web types, as the bundler
# config does, is not in TypeScript 7.
cp -R "$CRATE_DIR/tests/types" "$work/types"
(cd "$work/types" && npm ci --silent --no-audit --no-fund)
for config in tsconfig.node.json tsconfig.bundler.json; do
Expand Down
Loading
0