weida-http 0.0.0-stage → 0.1.0-alpha.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/native.js ADDED
@@ -0,0 +1,12 @@
1
+ // The Node-API addon (src/addon.c) of this platform, from
2
+ // prebuilds/<platform>-<arch>/ (build.sh writes it there), loaded the one
3
+ // way Node, Bun and Deno all accept from an ES module, and the library it
4
+ // opened before anything else ran: libweida_full of weida-native-full when
5
+ // that is installed at this version, else the libweida_http beside the addon
6
+ // (lib/shared/load.js).
7
+ import { loadAddon } from "./shared/load.js";
8
+
9
+ const { native, libraryPath } = loadAddon(import.meta.url, "weida_http");
10
+
11
+ export { libraryPath };
12
+ export default native;
@@ -0,0 +1,208 @@
1
+ // The argument conversions of a package's API: refused where they are
2
+ // written, naming the argument (TypeError for a value of the wrong kind,
3
+ // RangeError for one the protocol or the C types cannot hold), and the
4
+ // builders of C option handles.
5
+ //
6
+ // One source in crates/js/shared/lib, copied into each package's lib/shared/
7
+ // (crates/js/shared/README.md); `../native.js` is the package's own addon.
8
+ // Namespace imports, so the module still loads on a runtime that lacks one
9
+ // of the exports; the conversions that need it check at use.
10
+ import * as nodeCrypto from "node:crypto";
11
+ import * as os from "node:os";
12
+
13
+ import native from "../native.js";
14
+
15
+ const encoder = new TextEncoder();
16
+
17
+ export function describe(value) {
18
+ return value === null ? "null" : typeof value === "string" ? "a string" : typeof value;
19
+ }
20
+
21
+ export function text(name, value) {
22
+ if (typeof value !== "string") {
23
+ throw new TypeError(`${name} is a string, not ${describe(value)}`);
24
+ }
25
+ if (value.includes("\0")) {
26
+ throw new RangeError(`${name} holds a null byte`);
27
+ }
28
+ return value;
29
+ }
30
+
31
+ export function optionalText(name, value) {
32
+ return value == null ? null : text(name, value);
33
+ }
34
+
35
+ /** Bytes as a Uint8Array: a Uint8Array (a Buffer is one) as it is, so a
36
+ * payload read back is the array the caller gave, another ArrayBuffer view
37
+ * or an ArrayBuffer viewed without a copy. A string is refused: a payload is
38
+ * opaque bytes, and which encoding a text takes is the caller's choice. */
39
+ export function bytes(name, value) {
40
+ if (value instanceof Uint8Array) {
41
+ return value;
42
+ }
43
+ if (value instanceof ArrayBuffer) {
44
+ return new Uint8Array(value);
45
+ }
46
+ if (ArrayBuffer.isView(value)) {
47
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
48
+ }
49
+ throw new TypeError(`${name} is bytes (a Uint8Array), not ${describe(value)}`);
50
+ }
51
+
52
+ export function optionalBytes(name, value) {
53
+ return value == null ? null : bytes(name, value);
54
+ }
55
+
56
+ export function isBytes(value) {
57
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value);
58
+ }
59
+
60
+ /** A duration in milliseconds as the C ABI takes it: rounded, not
61
+ * truncated. */
62
+ export function millis(name, value) {
63
+ if (typeof value !== "number") {
64
+ throw new TypeError(`${name} is a number of milliseconds, not ${describe(value)}`);
65
+ }
66
+ if (!Number.isFinite(value) || value < 0) {
67
+ throw new RangeError(`${name} must be a finite, non-negative number of milliseconds`);
68
+ }
69
+ const ms = Math.round(value);
70
+ if (ms > Number.MAX_SAFE_INTEGER) {
71
+ throw new RangeError(`${name} is too large`);
72
+ }
73
+ return ms;
74
+ }
75
+
76
+ /** `millis`, with null as the C ABI's none (-1, R7). */
77
+ export function optionalMillis(name, value) {
78
+ return value == null ? -1 : millis(name, value);
79
+ }
80
+
81
+ /** A duration checked as `millis` checks it and kept as the caller wrote
82
+ * it; null for none. */
83
+ export function duration(name, value) {
84
+ if (value == null) {
85
+ return null;
86
+ }
87
+ millis(name, value);
88
+ return value;
89
+ }
90
+
91
+ /** An integer within a C type's range: a number, or a BigInt where the
92
+ * type is wider than a safe integer. */
93
+ export function integer(name, value, max, min = 0) {
94
+ if (typeof value === "bigint") {
95
+ if (value < BigInt(min) || value > BigInt(max)) {
96
+ throw new RangeError(`${name} is ${min} to ${max}, not ${value}`);
97
+ }
98
+ return value;
99
+ }
100
+ if (typeof value !== "number" || !Number.isInteger(value)) {
101
+ throw new TypeError(`${name} is an integer, not ${describe(value)}`);
102
+ }
103
+ if (value < min || value > max) {
104
+ throw new RangeError(`${name} is ${min} to ${max}, not ${value}`);
105
+ }
106
+ if (value > Number.MAX_SAFE_INTEGER) {
107
+ throw new RangeError(`${name} is past Number.MAX_SAFE_INTEGER: pass a BigInt`);
108
+ }
109
+ return value;
110
+ }
111
+
112
+ export function optionalInteger(name, value, max, min = 0) {
113
+ return value == null ? null : integer(name, value, max, min);
114
+ }
115
+
116
+ /** The options object of a constructor or call, its keys checked. */
117
+ export function optionsOf(value, known, what) {
118
+ if (value == null) {
119
+ return {};
120
+ }
121
+ if (typeof value !== "object") {
122
+ throw new TypeError(`the options of ${what} are an object`);
123
+ }
124
+ for (const key of Object.keys(value)) {
125
+ if (!known.includes(key)) {
126
+ throw new TypeError(`unknown ${what} option: ${key}`);
127
+ }
128
+ }
129
+ return value;
130
+ }
131
+
132
+ /** Whether `value` is an instance of `node:crypto`'s export `name`. */
133
+ export function isCrypto(value, name) {
134
+ const Class = nodeCrypto[name];
135
+ return typeof Class === "function" && value instanceof Class;
136
+ }
137
+
138
+ /** A C builder handle of `value` for the length of `use`. */
139
+ export function withBuilt(build, value, use) {
140
+ const handle = build(value);
141
+ try {
142
+ return use(handle);
143
+ } finally {
144
+ native.drop(handle);
145
+ }
146
+ }
147
+
148
+ /** Runs `settings(handle)`, dropping the handle when a setter fails. */
149
+ export function configured(handle, settings) {
150
+ try {
151
+ settings(handle);
152
+ } catch (error) {
153
+ native.drop(handle);
154
+ throw error;
155
+ }
156
+ return handle;
157
+ }
158
+
159
+ export function isAnchor(value) {
160
+ return (
161
+ value instanceof Uint8Array ||
162
+ typeof value === "string" ||
163
+ value instanceof URL ||
164
+ isCrypto(value, "X509Certificate")
165
+ );
166
+ }
167
+
168
+ /** A certificate chain as PEM bytes: bytes, an X509Certificate or an array
169
+ * of them. */
170
+ export function certPem(cert) {
171
+ if (isCrypto(cert, "X509Certificate")) {
172
+ return encoder.encode(cert.toString());
173
+ }
174
+ if (Array.isArray(cert) && cert.length > 0 && cert.every((c) => isCrypto(c, "X509Certificate"))) {
175
+ return encoder.encode(cert.map((c) => c.toString()).join("\n"));
176
+ }
177
+ if (cert instanceof Uint8Array) {
178
+ return cert;
179
+ }
180
+ throw new TypeError("identity.cert is PEM bytes, an X509Certificate or an array of them");
181
+ }
182
+
183
+ /** A private key as PEM bytes: bytes or a private KeyObject (as PKCS#8). */
184
+ export function keyPem(key) {
185
+ if (isCrypto(key, "KeyObject")) {
186
+ if (key.type !== "private") {
187
+ throw new TypeError("identity.key is a private KeyObject");
188
+ }
189
+ return encoder.encode(key.export({ type: "pkcs8", format: "pem" }));
190
+ }
191
+ if (key instanceof Uint8Array) {
192
+ return key;
193
+ }
194
+ throw new TypeError("identity.key is PEM bytes or a private KeyObject");
195
+ }
196
+
197
+ /** The default number of worker threads: one per core. */
198
+ export function defaultThreads() {
199
+ const n = globalThis.navigator?.hardwareConcurrency;
200
+ if (Number.isInteger(n) && n > 0) {
201
+ return n;
202
+ }
203
+ try {
204
+ return os.availableParallelism?.() ?? os.cpus().length ?? 1;
205
+ } catch {
206
+ return 1;
207
+ }
208
+ }
@@ -0,0 +1,28 @@
1
+ // The base of every weida package's error class (docs/c/README.md R9). A
2
+ // package derives its own class from it, adding the fields of its library's
3
+ // thread-local record, and registers that class with its addon
4
+ // (`native.setErrorClass`), which creates it with the message and sets
5
+ // `code`, `errno` and the record's fields from the call that failed.
6
+ //
7
+ // One source in crates/js/shared/lib, copied into each package's lib/shared/
8
+ // (crates/js/shared/README.md); `../native.js` is the package's own addon.
9
+ import native from "../native.js";
10
+
11
+ export class WeidaError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "WeidaError";
15
+ /** The R9 constant name, e.g. "WEIDA_EUNTRUSTED". */
16
+ this.code = null;
17
+ /** The positive status code. */
18
+ this.errno = null;
19
+ }
20
+ }
21
+
22
+ /** ECLOSED, one of the C ABI's own codes, the same in every library. */
23
+ const ECLOSED = 103;
24
+
25
+ /** The error a dropped, spent or consumed object fails with. */
26
+ export function closed() {
27
+ return native.error(ECLOSED);
28
+ }
@@ -0,0 +1,55 @@
1
+ // The base of a package's handle classes, one class per C ABI handle: the
2
+ // handle in the HANDLE slot, the pending waits in WAITS (wait.js), `drop()`
3
+ // and `Symbol.dispose`.
4
+ //
5
+ // One source in crates/js/shared/lib, copied into each package's lib/shared/
6
+ // (crates/js/shared/README.md); `../native.js` is the package's own addon.
7
+ import native from "../native.js";
8
+ import { WAITS, cancelWaits } from "./wait.js";
9
+
10
+ /** The slot of a handle object that holds its native handle. */
11
+ export const HANDLE = Symbol("weida.handle");
12
+ const dispose = Symbol.dispose ?? Symbol.for("Symbol.dispose");
13
+
14
+ /** The native handle of `value`, which must be a `Class`. */
15
+ export function handleOf(value, Class) {
16
+ if (!(value instanceof Class)) {
17
+ throw new TypeError(`expected a ${Class.name}`);
18
+ }
19
+ return value[HANDLE];
20
+ }
21
+
22
+ /** Makes `object` the owner of `handle`. */
23
+ export function init(object, handle) {
24
+ object[HANDLE] = handle;
25
+ object[WAITS] = new Set();
26
+ return object;
27
+ }
28
+
29
+ /** An object of a class without a public constructor, around `handle`. */
30
+ export function adopt(Class, handle) {
31
+ return init(Object.create(Class.prototype), handle);
32
+ }
33
+
34
+ /** The handle of `object` for a consuming call (R6), its waits ended. */
35
+ export function consume(object) {
36
+ cancelWaits(object);
37
+ return object[HANDLE];
38
+ }
39
+
40
+ /** The TypeError of a class without a public constructor. */
41
+ export function noConstructor(name, how) {
42
+ throw new TypeError(`${name} has no public constructor; ${how} makes one`);
43
+ }
44
+
45
+ export class Handle {
46
+ /** Releases the handle now, ending its pending waits with ECLOSED. */
47
+ drop() {
48
+ cancelWaits(this);
49
+ native.drop(this[HANDLE]);
50
+ }
51
+
52
+ [dispose]() {
53
+ this.drop();
54
+ }
55
+ }
@@ -0,0 +1,74 @@
1
+ // Which native library a package opens, and its addon over it
2
+ // (plans/protocol-libraries/README.md section 1, "the loader rule"): the
3
+ // libweida_full of `weida-native-full` when that package resolves from this
4
+ // one at exactly the version the addon was built for, else the library the
5
+ // package bundles beside its addon. A weida-native-full of another version
6
+ // is ignored, not an error; the addon's `load` refuses a library that reports
7
+ // another version than its own, naming both.
8
+ //
9
+ // One source in crates/js/shared/lib, copied into each package's lib/shared/
10
+ // (crates/js/shared/README.md). It imports nothing from the package; each
11
+ // package's lib/native.js calls `loadAddon` before anything else runs.
12
+ import { existsSync } from "node:fs";
13
+ import { createRequire } from "node:module";
14
+ import { join } from "node:path";
15
+ import process from "node:process";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ /** The prebuilds/ directory of this platform: Node's platform-arch. */
19
+ export const target = `${process.platform}-${process.arch}`;
20
+
21
+ /** The file of the native library `stem` (cargo's lib name: weida,
22
+ * weida_<p>, weida_full) on `platform`. */
23
+ export function libraryFile(stem, platform = process.platform) {
24
+ if (platform === "win32") {
25
+ return `${stem}.dll`;
26
+ }
27
+ if (platform === "darwin") {
28
+ return `lib${stem}.dylib`;
29
+ }
30
+ return `lib${stem}.so`;
31
+ }
32
+
33
+ /**
34
+ * The library file to open: `weida-native-full`'s `libraryPath()` when
35
+ * `require` (the package's own, so resolution starts at the package) finds
36
+ * weida-native-full at exactly `version`, else `own`.
37
+ */
38
+ export function choose(require, version, own) {
39
+ let manifest;
40
+ try {
41
+ manifest = require("weida-native-full/package.json");
42
+ } catch (error) {
43
+ if (error?.code === "MODULE_NOT_FOUND") {
44
+ return own;
45
+ }
46
+ throw error;
47
+ }
48
+ if (manifest.version !== version) {
49
+ return own;
50
+ }
51
+ return require("weida-native-full").libraryPath();
52
+ }
53
+
54
+ /**
55
+ * Loads the addon `<stem>.node` of this platform from the package's
56
+ * prebuilds/ (beside lib/, where `base`, the URL of the package's
57
+ * lib/native.js, sits) and has it open the library `choose` names: its own
58
+ * `lib<stem>` beside it, or libweida_full. Returns the addon and the path of
59
+ * the library it opened.
60
+ */
61
+ export function loadAddon(base, stem) {
62
+ const require = createRequire(base);
63
+ const dir = fileURLToPath(new URL(`../prebuilds/${target}/`, base));
64
+ const addon = join(dir, `${stem}.node`);
65
+ if (!existsSync(addon)) {
66
+ throw new Error(
67
+ `${stem}: no addon for ${target}: ${addon} does not exist; the package carries linux-x64, linux-arm64, darwin-arm64 and win32-x64, and build.sh (build.ps1 on Windows) builds one from source`,
68
+ );
69
+ }
70
+ const native = require(addon);
71
+ const libraryPath = choose(require, native.VERSION, join(dir, libraryFile(stem)));
72
+ native.load(libraryPath);
73
+ return { native, libraryPath };
74
+ }
@@ -0,0 +1,90 @@
1
+ // Waiting on a weida library from the JS thread (docs/c/README.md R3, R4,
2
+ // R11): every native call tries with timeout 0; on AGAIN the handle's
3
+ // descriptor is watched once through the addon's waiter thread and the call
4
+ // is tried again when it turns readable. R11 allows one stale AGAIN, which
5
+ // simply watches again.
6
+ //
7
+ // One source in crates/js/shared/lib, copied into each package's lib/shared/
8
+ // (crates/js/shared/README.md); `../native.js` is the package's own addon.
9
+ import native from "../native.js";
10
+ import { closed } from "./errors.js";
11
+
12
+ /** The pending watches of a handle object: a Set of entries. */
13
+ export const WAITS = Symbol("weida.waits");
14
+
15
+ function watch(owner, fd, signal, weak) {
16
+ return new Promise((resolve, reject) => {
17
+ const entry = {};
18
+ const settle = () => {
19
+ owner[WAITS].delete(entry);
20
+ signal?.removeEventListener("abort", entry.abort);
21
+ };
22
+ entry.cancel = (reason) => {
23
+ native.unwatch(entry.id);
24
+ settle();
25
+ reject(reason);
26
+ };
27
+ entry.abort = () => entry.cancel(signal.reason);
28
+ entry.id = native.watch(
29
+ fd,
30
+ () => {
31
+ settle();
32
+ resolve();
33
+ },
34
+ weak === true,
35
+ );
36
+ owner[WAITS].add(entry);
37
+ signal?.addEventListener("abort", entry.abort, { once: true });
38
+ });
39
+ }
40
+
41
+ /**
42
+ * Runs `attempt()` until it returns something other than AGAIN, watching
43
+ * the descriptor `fdOf()` names in between. `fdOf()` is asked once, the
44
+ * first time the call has to wait: a handle's descriptor does not change,
45
+ * and where asking a library for it raises it, asking on every round would
46
+ * wake every watch at once and spin. `owner` is the object whose `drop()`
47
+ * ends the wait; aborting `signal` ends it with `signal.reason`. A `weak`
48
+ * wait does not keep the process alive.
49
+ */
50
+ export async function call(owner, attempt, fdOf, signal, weak = false) {
51
+ signal?.throwIfAborted();
52
+ let rc = attempt();
53
+ let fd;
54
+ while (rc === native.AGAIN) {
55
+ fd ??= fdOf();
56
+ await watch(owner, fd, signal, weak);
57
+ rc = attempt();
58
+ }
59
+ return rc;
60
+ }
61
+
62
+ /**
63
+ * Awaits the op `start()` returns (R3b) and drops it on every path, which
64
+ * cancels the operation when it did not finish (an abort, or `owner`
65
+ * dropped).
66
+ */
67
+ export async function op(owner, start, waitOf, fdOf, signal) {
68
+ signal?.throwIfAborted();
69
+ const handle = start();
70
+ try {
71
+ return await call(owner, () => waitOf(handle), () => fdOf(handle), signal);
72
+ } finally {
73
+ native.drop(handle);
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Ends every pending wait of `owner` with ECLOSED, before its handle is
79
+ * dropped or consumed, so no descriptor is watched once it is closed.
80
+ */
81
+ export function cancelWaits(owner) {
82
+ const pending = owner[WAITS];
83
+ if (pending.size === 0) {
84
+ return;
85
+ }
86
+ const error = closed();
87
+ for (const entry of [...pending]) {
88
+ entry.cancel(error);
89
+ }
90
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "weida-http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.19",
4
+ "description": "HTTP/1.1, HTTP/2 and HTTP/3 for Node, Bun and Deno, a client and a server: a Node-API addon over libweida_http",
5
+ "license": "MIT OR Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/tuco86/weida.git",
9
+ "directory": "crates/js/weida-http"
10
+ },
11
+ "homepage": "https://weida.doodleshnookie.net",
12
+ "keywords": [
13
+ "http",
14
+ "http2",
15
+ "http3",
16
+ "quic",
17
+ "client",
18
+ "server",
19
+ "async"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./lib/index.d.ts",
25
+ "default": "./lib/index.js"
26
+ }
27
+ },
28
+ "types": "./lib/index.d.ts",
29
+ "files": [
30
+ "lib",
31
+ "prebuilds"
32
+ ],
33
+ "publishConfig": {
34
+ "registry": "https://registry.npmjs.org/"
35
+ },
36
+ "engines": {
37
+ "node": ">=20"
38
+ },
39
+ "peerDependencies": {
40
+ "weida-native-full": "0.1.0-alpha.19"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "weida-native-full": {
44
+ "optional": true
45
+ }
46
+ }
47
+ }