@eserstack/webtransport 0.0.0-bootstrap.0 โ†’ 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023-present Eser Ozvataf and other contributors.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,120 @@
1
+ # ๐Ÿš‡ [@eserstack/webtransport](./)
2
+
3
+ > **Note:** JSR is frozen at 4.5.x. From 5.0.0, `@eserstack/webtransport` is
4
+ > published on npm under the same name (`pnpm add @eserstack/webtransport`); the
5
+ > JSR versions stay available but get no updates.
6
+
7
+ > **eserstack Tool** ยท [eser/stack on GitHub](https://github.com/eser/stack) ยท
8
+ > **Install:** `pnpm add @eserstack/webtransport`
9
+
10
+ `@eserstack/webtransport` wraps the `WebTransport` API in a client for
11
+ bidirectional streams, unidirectional streams and datagrams over HTTP/3. It
12
+ follows the factory pattern of `@eserstack/httpclient`: you create a client with
13
+ a `baseUrl`, then connect to paths under it. It adds certificate pinning for
14
+ self-signed servers and a dial timeout. Use `@eserstack/httpclient` for REST
15
+ requests and this package for long-lived streams.
16
+
17
+ The client needs a runtime that provides a global `WebTransport`, such as a
18
+ current browser.
19
+
20
+ ## Quick Start
21
+
22
+ Connect to a server, open a bidirectional stream and write one line to it:
23
+
24
+ ```typescript
25
+ import * as webtransport from "@eserstack/webtransport";
26
+
27
+ const client = webtransport.createWebTransportClient({
28
+ baseUrl: "https://localhost:4433",
29
+ });
30
+
31
+ const session = await client.connect("/your_endpoint_path");
32
+ const stream = await session.openBidirectionalStream();
33
+
34
+ const writer = stream.writable.getWriter();
35
+ await writer.write(new TextEncoder().encode("hello\n"));
36
+ writer.releaseLock();
37
+
38
+ session.close();
39
+ ```
40
+
41
+ ## Client
42
+
43
+ ### `createWebTransportClient(config?)`
44
+
45
+ Returns a `WebTransportClient`. Every option is optional:
46
+
47
+ | Option | Type | Description |
48
+ | --------------- | --------------- | --------------------------------------------------------------------------------------------- |
49
+ | `baseUrl` | `string` | Prefix for paths passed to `connect`; a full `https://` or `http://` URL is used as given |
50
+ | `certHashes` | `ArrayBuffer[]` | SHA-256 hashes of the server certificate, passed to WebTransport as `serverCertificateHashes` |
51
+ | `dialTimeout` | `number` | Milliseconds to wait for the session to be ready; `0` or unset waits with no limit |
52
+ | `_newTransport` | `function` | Replaces `new WebTransport(url, options)`, for tests that run without a server |
53
+
54
+ `certHashes` lets a browser accept a self-signed certificate without trusting it
55
+ in the operating system. Pass the hash the server publishes:
56
+
57
+ ```typescript
58
+ import * as webtransport from "@eserstack/webtransport";
59
+
60
+ const hex = "your_sha256_fingerprint_hex";
61
+ const hash = new Uint8Array(
62
+ hex.match(/../g)!.map((pair) => Number.parseInt(pair, 16)),
63
+ ).buffer;
64
+
65
+ const client = webtransport.createWebTransportClient({
66
+ baseUrl: "https://localhost:4433",
67
+ certHashes: [hash],
68
+ dialTimeout: 5000,
69
+ });
70
+ ```
71
+
72
+ ### `client.connect(urlOrPath, headers?)`
73
+
74
+ Opens a session and resolves once it is ready. It rejects when the handshake
75
+ fails, or when `dialTimeout` passes first; in that case it closes the pending
76
+ session and the error says how long it waited. The `headers` argument is
77
+ accepted for API symmetry and not sent: the browser `WebTransport` API has no
78
+ way to set request headers, so pass values such as tokens in the query string.
79
+
80
+ ## Session
81
+
82
+ `connect` resolves to a `WebTransportSession`:
83
+
84
+ | Member | Description |
85
+ | ----------------------------- | ---------------------------------------------------------------------- |
86
+ | `openBidirectionalStream()` | Opens a stream you can read from and write to |
87
+ | `acceptBidirectionalStream()` | Waits for the next stream the server opens; rejects once closed |
88
+ | `openUnidirectionalStream()` | Opens a send-only stream |
89
+ | `datagrams` | `{ readable, writable }` for unreliable, unordered messages |
90
+ | `ready` / `closed` | Promises from the underlying `WebTransport` object |
91
+ | `close(closeInfo?)` | Closes the session, optionally with a close code and reason |
92
+ | `inner` | The native `WebTransport` object, for APIs this wrapper does not cover |
93
+
94
+ Read the server's replies from a stream with its `readable` side:
95
+
96
+ ```typescript
97
+ import * as webtransport from "@eserstack/webtransport";
98
+
99
+ const client = webtransport.createWebTransportClient({
100
+ baseUrl: "https://localhost:4433",
101
+ });
102
+ const session = await client.connect("/your_endpoint_path");
103
+ const stream = await session.openBidirectionalStream();
104
+
105
+ const reader = stream.readable.pipeThrough(new TextDecoderStream()).getReader();
106
+ const { value } = await reader.read();
107
+ console.log(value);
108
+
109
+ session.close();
110
+ ```
111
+
112
+ ## ๐Ÿ”— Links
113
+
114
+ - [eser/stack on GitHub](https://github.com/eser/stack)
115
+ - [`@eserstack/httpclient`](../httpclient/): the HTTP client this package
116
+ mirrors, for REST requests
117
+ - [`@eserstack/noskills-client`](../noskills-client/README.md): attaches to
118
+ `noskills-server` sessions over this client
119
+ - [WebTransport on MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebTransport):
120
+ the browser API underneath
@@ -0,0 +1,26 @@
1
+ /**
2
+ * WebTransport client implementation for browser environments.
3
+ *
4
+ * Browser: uses globalThis.WebTransport directly. Chrome 97+, Edge 97+,
5
+ * Safari 18.2+, Firefox 114+ (experimental). h3 ALPN is negotiated
6
+ * automatically by the browser โ€” no client-side configuration needed.
7
+ *
8
+ * Node: Node 22+ has experimental WebTransport via --experimental-fetch.
9
+ * Long-term path: extend the ajan bridge HTTP-client FFI
10
+ * surface with protocol:"h3" so the TS bridge gets HTTP/3 natively.
11
+ *
12
+ * @module
13
+ */
14
+ import type { WebTransportClient as IWebTransportClient, WebTransportConfig } from "./types.ts";
15
+ /**
16
+ * Creates a WebTransport client. Parallel to createHttpClient from
17
+ * @eserstack/httpclient โ€” same factory pattern, same config shape.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const client = createWebTransportClient({ baseUrl: "https://localhost:4433" });
22
+ * const session = await client.connect("/attach/my-project/session-id");
23
+ * const stream = await session.openBidirectionalStream();
24
+ * ```
25
+ */
26
+ export declare function createWebTransportClient(config?: WebTransportConfig): IWebTransportClient;
package/dist/client.js ADDED
@@ -0,0 +1,116 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ class WebTransportSessionImpl {
3
+ inner;
4
+ constructor(wt) {
5
+ this.inner = wt;
6
+ }
7
+ get ready() {
8
+ return this.inner.ready;
9
+ }
10
+ get closed() {
11
+ return this.inner.closed;
12
+ }
13
+ get datagrams() {
14
+ return this.inner.datagrams;
15
+ }
16
+ openBidirectionalStream() {
17
+ return this.inner.createBidirectionalStream();
18
+ }
19
+ acceptBidirectionalStream() {
20
+ const reader = this.inner.incomingBidirectionalStreams.getReader();
21
+ return reader.read().then(({ value, done }) => {
22
+ reader.releaseLock();
23
+ if (done || value === undefined) {
24
+ return Promise.reject(new Error("WebTransport session closed"));
25
+ }
26
+ return value;
27
+ });
28
+ }
29
+ openUnidirectionalStream() {
30
+ return this.inner.createUnidirectionalStream();
31
+ }
32
+ close(closeInfo) {
33
+ this.inner.close(closeInfo);
34
+ }
35
+ }
36
+ class WebTransportClientImpl {
37
+ #config;
38
+ constructor(config) {
39
+ this.#config = config;
40
+ }
41
+ async connect(urlOrPath, _headers) {
42
+ const url = this.#resolveUrl(urlOrPath);
43
+ const options = this.#buildOptions();
44
+ const newTransport = this.#config._newTransport;
45
+ const wt = newTransport !== undefined
46
+ ? newTransport(url, options)
47
+ : new globalThis.WebTransport(url, options);
48
+ await this.#waitUntilReady(wt);
49
+ return new WebTransportSessionImpl(wt);
50
+ }
51
+ async #waitUntilReady(wt) {
52
+ const timeout = this.#config.dialTimeout ?? 0;
53
+ if (timeout <= 0) {
54
+ await wt.ready;
55
+ return;
56
+ }
57
+ let timer;
58
+ const timedOut = new Promise((resolve) => {
59
+ timer = setTimeout(() => resolve("timeout"), timeout);
60
+ });
61
+ try {
62
+ const outcome = await Promise.race([
63
+ wt.ready.then(() => "ready"),
64
+ timedOut,
65
+ ]);
66
+ if (outcome === "timeout") {
67
+ // Abandon the attempt so a late handshake does not leave an open
68
+ // session nobody holds.
69
+ wt.close();
70
+ // The URL is left out: it can carry the session token as a query
71
+ // parameter.
72
+ throw new Error(`WebTransport dial timed out after ${timeout} ms; check that the server is reachable, or raise dialTimeout`);
73
+ }
74
+ }
75
+ finally {
76
+ clearTimeout(timer);
77
+ }
78
+ }
79
+ #resolveUrl(urlOrPath) {
80
+ const baseUrl = this.#config.baseUrl;
81
+ if (baseUrl === undefined ||
82
+ baseUrl === "" ||
83
+ urlOrPath.startsWith("https://") ||
84
+ urlOrPath.startsWith("http://")) {
85
+ return urlOrPath;
86
+ }
87
+ const base = baseUrl.replace(/\/$/, "");
88
+ const path = urlOrPath.startsWith("/") ? urlOrPath : `/${urlOrPath}`;
89
+ return `${base}${path}`;
90
+ }
91
+ #buildOptions() {
92
+ const opts = {};
93
+ const certHashes = this.#config.certHashes;
94
+ if (certHashes !== undefined && certHashes.length > 0) {
95
+ opts.serverCertificateHashes = certHashes.map((hash) => ({
96
+ algorithm: "sha-256",
97
+ value: hash,
98
+ }));
99
+ }
100
+ return opts;
101
+ }
102
+ }
103
+ /**
104
+ * Creates a WebTransport client. Parallel to createHttpClient from
105
+ * @eserstack/httpclient โ€” same factory pattern, same config shape.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * const client = createWebTransportClient({ baseUrl: "https://localhost:4433" });
110
+ * const session = await client.connect("/attach/my-project/session-id");
111
+ * const stream = await session.openBidirectionalStream();
112
+ * ```
113
+ */
114
+ export function createWebTransportClient(config = {}) {
115
+ return new WebTransportClientImpl(config);
116
+ }
package/dist/mod.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @eserstack/webtransport โ€” WebTransport client for browser and Node.
3
+ *
4
+ * Parallel to @eserstack/httpclient: same factory pattern, same config shape,
5
+ * same options naming. Use createWebTransportClient for bidi streams and
6
+ * datagrams; use createHttpClient for REST requests.
7
+ *
8
+ * @module
9
+ */
10
+ export { createWebTransportClient } from "./client.ts";
11
+ export type { WebTransportClient, WebTransportConfig, WebTransportSession, } from "./types.ts";
package/dist/mod.js ADDED
@@ -0,0 +1,11 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * @eserstack/webtransport โ€” WebTransport client for browser and Node.
4
+ *
5
+ * Parallel to @eserstack/httpclient: same factory pattern, same config shape,
6
+ * same options naming. Use createWebTransportClient for bidi streams and
7
+ * datagrams; use createHttpClient for REST requests.
8
+ *
9
+ * @module
10
+ */
11
+ export { createWebTransportClient } from "./client.js";
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Public type definitions for @eserstack/webtransport.
3
+ *
4
+ * Config shape is intentionally parallel to @eserstack/httpclient.HttpClientConfig
5
+ * so contributors switching contexts need no relearning.
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Configuration for createWebTransportClient.
11
+ *
12
+ * @property baseUrl - Base URL for connections (e.g. "https://localhost:4433").
13
+ * @property certHashes - SHA-256 DER fingerprints for certificate pinning.
14
+ * Passed as serverCertificateHashes to the browser WebTransport API.
15
+ * Use for self-signed development certs when mkcert is unavailable.
16
+ * @property dialTimeout - Abort connection attempt after this many milliseconds. 0 = no cap.
17
+ * @property _newTransport - Escape hatch for testing: inject a custom WebTransport factory.
18
+ */
19
+ export interface WebTransportConfig {
20
+ baseUrl?: string;
21
+ certHashes?: ArrayBuffer[];
22
+ dialTimeout?: number;
23
+ /** Inject a custom WebTransport factory for testing without a live server. */
24
+ _newTransport?: (url: string, options?: WebTransportOptions) => WebTransport;
25
+ }
26
+ /**
27
+ * A connected WebTransport session.
28
+ * Methods mirror the browser WebTransport API but are wrapped for
29
+ * ergonomics and testability.
30
+ */
31
+ export interface WebTransportSession {
32
+ /** Open a new bidirectional stream. */
33
+ openBidirectionalStream(): Promise<WebTransportBidirectionalStream>;
34
+ /** Accept an incoming bidirectional stream from the server. */
35
+ acceptBidirectionalStream(): Promise<WebTransportBidirectionalStream>;
36
+ /** Open a new unidirectional (send-only) stream. */
37
+ openUnidirectionalStream(): Promise<WritableStream<Uint8Array>>;
38
+ /** Datagrams โ€” unreliable, lossy. Use only for presence / typing signals. */
39
+ datagrams: {
40
+ readonly readable: ReadableStream<Uint8Array>;
41
+ readonly writable: WritableStream<Uint8Array>;
42
+ };
43
+ /** Resolved when the session is ready to use. */
44
+ readonly ready: Promise<void>;
45
+ /** Resolved when the session is closed (cleanly or with error). */
46
+ readonly closed: Promise<WebTransportCloseInfo>;
47
+ /** Close the session. */
48
+ close(closeInfo?: WebTransportCloseInfo): void;
49
+ /** Underlying native WebTransport object (escape hatch). */
50
+ readonly inner: WebTransport;
51
+ }
52
+ /**
53
+ * Top-level client returned by createWebTransportClient.
54
+ * Use connect() to open a session; keep the client alive to share
55
+ * the underlying QUIC connection across sessions (future optimisation).
56
+ */
57
+ export interface WebTransportClient {
58
+ connect(url: string): Promise<WebTransportSession>;
59
+ connect(url: string, headers?: Record<string, string>): Promise<WebTransportSession>;
60
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ export {};
package/package.json CHANGED
@@ -1 +1,35 @@
1
- {"name":"@eserstack/webtransport","version":"0.0.0-bootstrap.0","license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/eser/stack.git"}}
1
+ {
2
+ "name": "@eserstack/webtransport",
3
+ "version": "5.0.0",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/eser/stack",
8
+ "directory": "pkg/@eserstack/webtransport"
9
+ },
10
+ "files": [
11
+ "dist/**/*.js",
12
+ "dist/**/*.d.ts",
13
+ "dist/**/*.json"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/mod.d.ts",
18
+ "import": "./dist/mod.js"
19
+ },
20
+ "./client": {
21
+ "types": "./dist/client.d.ts",
22
+ "import": "./dist/client.js"
23
+ },
24
+ "./types": {
25
+ "types": "./dist/types.d.ts",
26
+ "import": "./dist/types.js"
27
+ }
28
+ },
29
+ "devDependencies": {
30
+ "@eserstack/test-kit": "5.0.0"
31
+ },
32
+ "scripts": {
33
+ "build": "node ../../../etc/scripts/build-library.ts"
34
+ }
35
+ }