@jsprismarine/native-network 0.0.0 → 0.21.0-unstable-20261112021648
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/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +93 -0
- package/dist/NativeNetwork.d.ts +109 -0
- package/dist/NativeNetwork.d.ts.map +1 -0
- package/dist/NativeNetwork.js +188 -0
- package/dist/NativeNetwork.js.map +1 -0
- package/dist/PeerConnection.d.ts +143 -0
- package/dist/PeerConnection.d.ts.map +1 -0
- package/dist/PeerConnection.js +269 -0
- package/dist/PeerConnection.js.map +1 -0
- package/dist/SharedPort.d.ts +79 -0
- package/dist/SharedPort.d.ts.map +1 -0
- package/dist/SharedPort.js +88 -0
- package/dist/SharedPort.js.map +1 -0
- package/dist/classify.d.ts +20 -0
- package/dist/classify.d.ts.map +1 -0
- package/dist/classify.js +20 -0
- package/dist/classify.js.map +1 -0
- package/dist/embed.d.ts +20 -0
- package/dist/embed.d.ts.map +1 -0
- package/dist/embed.js +57 -0
- package/dist/embed.js.map +1 -0
- package/dist/ffi.d.ts +50 -0
- package/dist/ffi.d.ts.map +1 -0
- package/dist/ffi.js +138 -0
- package/dist/ffi.js.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/install.d.ts +46 -0
- package/dist/install.d.ts.map +1 -0
- package/dist/install.js +80 -0
- package/dist/install.js.map +1 -0
- package/dist/isRecord.d.ts +3 -0
- package/dist/isRecord.d.ts.map +1 -0
- package/dist/isRecord.js +6 -0
- package/dist/isRecord.js.map +1 -0
- package/dist/library.d.ts +44 -0
- package/dist/library.d.ts.map +1 -0
- package/dist/library.js +82 -0
- package/dist/library.js.map +1 -0
- package/dist/manifest.d.ts +44 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +50 -0
- package/dist/manifest.js.map +1 -0
- package/dist/native/manifest.json.js +87 -0
- package/dist/native/manifest.json.js.map +1 -0
- package/dist/nativeHash.d.ts +16 -0
- package/dist/nativeHash.d.ts.map +1 -0
- package/dist/nativeHash.js +43 -0
- package/dist/nativeHash.js.map +1 -0
- package/dist/platform.d.ts +35 -0
- package/dist/platform.d.ts.map +1 -0
- package/dist/platform.js +54 -0
- package/dist/platform.js.map +1 -0
- package/dist/testing/loopback-main.d.ts +2 -0
- package/dist/testing/loopback-main.d.ts.map +1 -0
- package/dist/testing/loopback-main.js +21 -0
- package/dist/testing/loopback-main.js.map +1 -0
- package/dist/testing/loopback.d.ts +23 -0
- package/dist/testing/loopback.d.ts.map +1 -0
- package/dist/testing/loopback.js +63 -0
- package/dist/testing/loopback.js.map +1 -0
- package/dist/testing/shared-port-main.d.ts +2 -0
- package/dist/testing/shared-port-main.d.ts.map +1 -0
- package/dist/testing/shared-port-main.js +55 -0
- package/dist/testing/shared-port-main.js.map +1 -0
- package/native/manifest.json +79 -0
- package/package.json +63 -6
- package/scripts/postinstall.mjs +54 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# @jsprismarine/native-network
|
|
2
|
+
|
|
3
|
+
## 0.21.0-unstable-20261112021648
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#2987](https://github.com/JSPrismarine/JSPrismarine/pull/2987) [`f64fee1`](https://github.com/JSPrismarine/JSPrismarine/commit/f64fee173c2ceec52534f2d3f1632ca6ae298797) Thanks [@filiphsps](https://github.com/filiphsps)! - A NetherNet connection that closes delivers everything sent before it. The native peer connection is deleted only once libdatachannel reports it closed, after its graceful SCTP shutdown, and a connection whose unreliable channel or peer connection goes down first waits for the reliable channel's own close, which comes after its last message. The server no longer waits before it closes a kicked player's connection.
|
|
8
|
+
|
|
9
|
+
- [#2987](https://github.com/JSPrismarine/JSPrismarine/pull/2987) [`6a29967`](https://github.com/JSPrismarine/JSPrismarine/commit/6a29967baa7fe9bc44acad762e651a4964af037b) Thanks [@filiphsps](https://github.com/filiphsps)! - The native networking library stays loaded for the life of the process, so a worker thread that loaded it can exit while libdatachannel's threads keep running, where the process used to crash on exit.
|
|
10
|
+
|
|
11
|
+
- [#2987](https://github.com/JSPrismarine/JSPrismarine/pull/2987) [`4cd0308`](https://github.com/JSPrismarine/JSPrismarine/commit/4cd0308e0a6f2733e21dc239107323bd79b0d70a) Thanks [@filiphsps](https://github.com/filiphsps)! - `@jsprismarine/native-network` downloads the build of its library for the machine it is installed on, from a GitHub release, in its install script, checks the file's SHA-256 against its manifest, and stores it in the package. Loading checks the file again and downloads nothing; without a build it fails with how to let npm, pnpm or Bun run the install script. `JSP_NATIVE_NETWORK_LIBRARY` names another file to load, checked the same way.
|
|
12
|
+
|
|
13
|
+
The single executables carry their platform's library and write it to their cache directory on the first start.
|
|
14
|
+
|
|
15
|
+
- [#2987](https://github.com/JSPrismarine/JSPrismarine/pull/2987) [`7ad176f`](https://github.com/JSPrismarine/JSPrismarine/commit/7ad176f908b8c7946773fa9fa2a942f6ac3cbd45) Thanks [@filiphsps](https://github.com/filiphsps)! - Add `@jsprismarine/native-network`, JSPrismarine's networking in native code: WebRTC peer connections and data channels on libdatachannel with Mbed TLS, bound through `node:ffi` and `bun:ffi`, and `SharedPort`, a UDP port that RakNet and NetherNet share, sorted by each datagram's bytes before libjuice's lookup. This release builds from source only; prebuilt libraries follow.
|
|
16
|
+
|
|
17
|
+
`SharedByteRing` in `@jsprismarine/raknet` now has eight control slots, with a wake flag (`claimWake` and `clearWake`), and needs a power-of-two capacity, so native code can read and write the same rings. A ring made with any other capacity is refused.
|
|
18
|
+
|
|
19
|
+
- [#2987](https://github.com/JSPrismarine/JSPrismarine/pull/2987) [`763c07d`](https://github.com/JSPrismarine/JSPrismarine/commit/763c07d5467a638658db0187110d2615160fdd19) Thanks [@filiphsps](https://github.com/filiphsps)! - RakNet and NetherNet can share one UDP port. When `server-udp-ports` covers `port` or `server-portv6` and both transports are on, the native networking library owns the port, sorts each datagram by its bytes, and hands RakNet its datagrams through shared-memory rings, in socket mode and with the RakNet worker.
|
|
20
|
+
|
|
21
|
+
With RakNet off, the server port is opened the same way when NetherNet's UDP is on it, so a taken port stops the start, and query, when `query-port` is the server port, answers through it instead of binding a socket that would keep NetherNet's peers off the port.
|
|
22
|
+
|
|
23
|
+
`@jsprismarine/raknet` adds `DatagramSource`, with `UdpDatagramSource` and `RingDatagramSource`, and `ServerSocket` and `WorkerServerSocket` take one as a new last constructor argument. `@jsprismarine/native-network`'s `SharedPort.attach` takes the rings to fill instead of allocating them.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JSPrismarine Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# @jsprismarine/native-network
|
|
2
|
+
|
|
3
|
+
[](https://discord.gg/kZZCDyCBbW)
|
|
4
|
+
[](https://www.npmjs.com/package/@jsprismarine/native-network)
|
|
5
|
+
|
|
6
|
+
JSPrismarine's networking in native code. It holds one library, built from pinned sources, and the
|
|
7
|
+
TypeScript that binds it:
|
|
8
|
+
|
|
9
|
+
- `PeerConnection` and `DataChannel`, WebRTC on
|
|
10
|
+
[libdatachannel](https://github.com/paullouisageneau/libdatachannel) with Mbed TLS, built without
|
|
11
|
+
media or WebSocket support. `@jsprismarine/nethernet` runs NetherNet on them.
|
|
12
|
+
- `SharedPort`, a UDP port that RakNet and NetherNet share. libjuice, libdatachannel's ICE library,
|
|
13
|
+
owns the socket, and the library sorts each datagram by its bytes before libjuice looks it up:
|
|
14
|
+
RakNet's datagrams go to RakNet through shared-memory rings, and WebRTC's stay in native code.
|
|
15
|
+
[ADR 0008](../../docs/adr/0008-shared-udp-port-in-native-code.md) has the design.
|
|
16
|
+
|
|
17
|
+
## How it is called
|
|
18
|
+
|
|
19
|
+
The library has a flat C interface, `native/include/jsp_native_network.h`. Node.js binds it with
|
|
20
|
+
`node:ffi` and Bun with `bun:ffi`. Every call is synchronous, and native code never calls into
|
|
21
|
+
JavaScript:
|
|
22
|
+
|
|
23
|
+
- libdatachannel's threads queue their events in native memory. When the queue stops being empty,
|
|
24
|
+
the library sends one byte to a UDP socket on `127.0.0.1` that `NativeNetwork` listens on, and
|
|
25
|
+
the socket's handler reads every queued event. A burst of events costs one wake.
|
|
26
|
+
- RakNet's datagrams on a shared port cross through two rings in a `SharedArrayBuffer`, in the
|
|
27
|
+
layout of `SharedByteRing` in `@jsprismarine/raknet`. Each side wakes the other with one byte to
|
|
28
|
+
a loopback socket, and only when the other side was idle. A RakNet worker thread can own the
|
|
29
|
+
rings without loading this package.
|
|
30
|
+
|
|
31
|
+
## Installing it
|
|
32
|
+
|
|
33
|
+
The package carries no library. Its install script downloads the one build for the machine it is
|
|
34
|
+
installed on from the GitHub release `native/manifest.json` names, checks the file's SHA-256
|
|
35
|
+
against the manifest, and stores it in the package's `prebuilds/` directory. Loading the library
|
|
36
|
+
downloads nothing, and checks the file against the same digest.
|
|
37
|
+
|
|
38
|
+
Package managers that hold install scripts back need to be told to run this one:
|
|
39
|
+
|
|
40
|
+
- npm runs it unless install scripts are turned off.
|
|
41
|
+
- pnpm runs it after `pnpm approve-builds`, or with
|
|
42
|
+
`allowBuilds: { '@jsprismarine/native-network': true }` in `pnpm-workspace.yaml`.
|
|
43
|
+
- Bun runs it once `"@jsprismarine/native-network"` is in the project's `trustedDependencies`.
|
|
44
|
+
|
|
45
|
+
Without the build, loading fails with a message that says which of these applies.
|
|
46
|
+
|
|
47
|
+
| Variable | Effect |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `JSP_NATIVE_NETWORK_LIBRARY` | Loads this file instead of the installed build. It is checked against the manifest too. |
|
|
50
|
+
| `JSP_NATIVE_NETWORK_SKIP_DOWNLOAD=1` | The install script downloads nothing. |
|
|
51
|
+
| `JSP_NATIVE_NETWORK_BASE_URL` | Downloads from another host, or reads from a directory, instead of the release. |
|
|
52
|
+
|
|
53
|
+
Builds exist for macOS on Apple Silicon, Windows on x64, and Linux on x64 and arm64
|
|
54
|
+
against glibc 2.36 or newer and against musl. Each depends only on what every machine of its
|
|
55
|
+
platform has. The C++ runtime and TLS are linked in.
|
|
56
|
+
|
|
57
|
+
A single executable built by `pnpm run package`, or by the release's Bun compile, carries its
|
|
58
|
+
platform's build. On its first start it writes the library to its cache directory under the
|
|
59
|
+
file's digest, and loads it from there.
|
|
60
|
+
|
|
61
|
+
## Building it
|
|
62
|
+
|
|
63
|
+
`pnpm --filter @jsprismarine/native-network run build:native` builds the library for this machine
|
|
64
|
+
into `prebuilds/<platform>/`. It needs CMake 3.20 or newer, a C and C++ compiler, `tar` and `git`.
|
|
65
|
+
`CMAKE` names a CMake that is not on the path. The script downloads every source in
|
|
66
|
+
`native/sources.json` into `node_modules/.cache/jsprismarine/native-network`, checks its SHA-256,
|
|
67
|
+
applies `native/patches/libjuice-mux-hooks.patch`, and runs CMake.
|
|
68
|
+
|
|
69
|
+
`--tls openssl` builds against OpenSSL instead, for comparison; it also needs Perl and make.
|
|
70
|
+
|
|
71
|
+
The build writes a `build.json` beside the library, and the loader accepts a library whose
|
|
72
|
+
digest matches it, so a checkout runs its own build. A checkout's `pnpm install` downloads the
|
|
73
|
+
published build only while the native sources still match the manifest's `build` hash.
|
|
74
|
+
|
|
75
|
+
## Publishing builds
|
|
76
|
+
|
|
77
|
+
The Native network workflow builds every platform on each change and checks each build's
|
|
78
|
+
dependencies. It tests the Linux x64 build under Node.js, and installs the packed package with
|
|
79
|
+
npm. Run by hand with `publish`, it attaches the builds to a release named
|
|
80
|
+
`native-network-build-<hash>` for the native sources' hash, and commits the manifest that points
|
|
81
|
+
at them. The release workflow refuses to publish the package while the manifest does not match
|
|
82
|
+
the sources.
|
|
83
|
+
|
|
84
|
+
## The libjuice patch
|
|
85
|
+
|
|
86
|
+
The patch adds two functions to libjuice's mux mode, and nothing else:
|
|
87
|
+
|
|
88
|
+
- `juice_mux_set_hooks`, which binds a mux port and keeps it open with no peer on it, with a filter
|
|
89
|
+
that sees each datagram before the address lookup and a callback for each datagram no peer
|
|
90
|
+
claims.
|
|
91
|
+
- `juice_mux_sendto`, which sends a datagram from a mux port's socket.
|
|
92
|
+
|
|
93
|
+
The classifier itself lives in this library, so the patch stays generic.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { NativeSymbols } from './ffi';
|
|
2
|
+
/** The interface version this binding speaks; it must equal the library's `JSP_ABI_VERSION`. */
|
|
3
|
+
export declare const ABI_VERSION = 1;
|
|
4
|
+
/** Event kinds, as `native/include/jsp_native_network.h` numbers them. */
|
|
5
|
+
export declare const NativeEvent: {
|
|
6
|
+
readonly description: 1;
|
|
7
|
+
readonly candidate: 2;
|
|
8
|
+
readonly state: 3;
|
|
9
|
+
readonly gathering: 4;
|
|
10
|
+
readonly dataChannel: 5;
|
|
11
|
+
readonly open: 6;
|
|
12
|
+
readonly closed: 7;
|
|
13
|
+
readonly error: 8;
|
|
14
|
+
readonly message: 9;
|
|
15
|
+
readonly bufferedLow: 10;
|
|
16
|
+
readonly iceState: 11;
|
|
17
|
+
readonly log: 12;
|
|
18
|
+
};
|
|
19
|
+
/** One event read from the native queue. */
|
|
20
|
+
export interface NativeEventRecord {
|
|
21
|
+
readonly kind: number;
|
|
22
|
+
/** The peer connection or data channel the event is about. */
|
|
23
|
+
readonly id: number;
|
|
24
|
+
readonly value: number;
|
|
25
|
+
/** A copy of the payload; it stays valid after the next read. */
|
|
26
|
+
readonly payload: Buffer;
|
|
27
|
+
}
|
|
28
|
+
/** What receives the events of one peer connection or data channel. */
|
|
29
|
+
export type NativeEventHandler = (event: NativeEventRecord) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Encodes a string for the C interface, NUL-terminated.
|
|
32
|
+
* @param text - The string.
|
|
33
|
+
* @returns Its UTF-8 bytes and a trailing NUL.
|
|
34
|
+
*/
|
|
35
|
+
export declare const cString: (text: string) => Buffer;
|
|
36
|
+
/**
|
|
37
|
+
* The native library, loaded once per thread, and that thread's event queue.
|
|
38
|
+
*
|
|
39
|
+
* The library is mapped once per process, and each thread that loads it opens a queue of its
|
|
40
|
+
* own, so a worker's peer connections report to the worker. libdatachannel's threads queue
|
|
41
|
+
* events in native memory and send one datagram to a loopback socket here when the queue stops
|
|
42
|
+
* being empty. The socket's handler drains the queue and
|
|
43
|
+
* dispatches each event to the handler registered for its id, so every event reaches JavaScript
|
|
44
|
+
* on the event loop, in order, with no call from a foreign thread.
|
|
45
|
+
*/
|
|
46
|
+
export declare class NativeNetwork {
|
|
47
|
+
private readonly library;
|
|
48
|
+
private readonly wakeSocket;
|
|
49
|
+
/** The handle of this thread's event queue, which peer connections are created on. */
|
|
50
|
+
readonly queue: number;
|
|
51
|
+
private static instance;
|
|
52
|
+
/** Wake datagrams received; a burst of events costs one. */
|
|
53
|
+
wakes: number;
|
|
54
|
+
private readonly handlers;
|
|
55
|
+
private readBuffer;
|
|
56
|
+
private logHandler;
|
|
57
|
+
/** Things that keep the process alive while they are open, such as a connection being made. */
|
|
58
|
+
private holds;
|
|
59
|
+
private constructor();
|
|
60
|
+
/**
|
|
61
|
+
* Loads the library and opens this thread's event queue, the first time it is called on a thread.
|
|
62
|
+
* @param options - The library file and log level; the defaults find the installed build.
|
|
63
|
+
* @returns The loaded library.
|
|
64
|
+
* @throws {NativeLibraryError} When the library cannot be found, loaded, or speaks another interface.
|
|
65
|
+
*/
|
|
66
|
+
static load(options?: {
|
|
67
|
+
path?: string;
|
|
68
|
+
logLevel?: number;
|
|
69
|
+
}): Promise<NativeNetwork>;
|
|
70
|
+
/** The loaded library, or undefined before {@link NativeNetwork.load}. */
|
|
71
|
+
static loaded(): NativeNetwork | undefined;
|
|
72
|
+
/** The bound C interface. */
|
|
73
|
+
get symbols(): NativeSymbols;
|
|
74
|
+
/**
|
|
75
|
+
* The address of shared memory, for an interface call that takes a pointer.
|
|
76
|
+
* @param memory - The memory; it must outlive every native use of the pointer.
|
|
77
|
+
* @returns The pointer.
|
|
78
|
+
*/
|
|
79
|
+
pointerOf(memory: SharedArrayBuffer): bigint | number;
|
|
80
|
+
/**
|
|
81
|
+
* Sends the events of one id to a handler, until {@link NativeNetwork.unwatch}.
|
|
82
|
+
* @param id - The peer connection or data channel.
|
|
83
|
+
* @param handler - Receives its events in order.
|
|
84
|
+
*/
|
|
85
|
+
watch(id: number, handler: NativeEventHandler): void;
|
|
86
|
+
/**
|
|
87
|
+
* Stops sending an id's events anywhere.
|
|
88
|
+
* @param id - The peer connection or data channel.
|
|
89
|
+
*/
|
|
90
|
+
unwatch(id: number): void;
|
|
91
|
+
/**
|
|
92
|
+
* Receives libdatachannel's log lines, when the library was loaded with a log level.
|
|
93
|
+
* @param handler - Receives each line and its level.
|
|
94
|
+
*/
|
|
95
|
+
onLog(handler: (level: number, line: string) => void): void;
|
|
96
|
+
/** Keeps the process alive until the matching {@link NativeNetwork.release}. */
|
|
97
|
+
hold(): void;
|
|
98
|
+
/** Lets the process exit once nothing holds it. */
|
|
99
|
+
release(): void;
|
|
100
|
+
/** Reads every queued event and dispatches it; a read that finds the queue empty rearms the wake. */
|
|
101
|
+
drain(): void;
|
|
102
|
+
/**
|
|
103
|
+
* Closes this thread's peer connections and its event queue. The library stays mapped, and
|
|
104
|
+
* another thread's connections and the shared ports are not touched.
|
|
105
|
+
*/
|
|
106
|
+
close(): void;
|
|
107
|
+
private dispatch;
|
|
108
|
+
}
|
|
109
|
+
//# sourceMappingURL=NativeNetwork.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeNetwork.d.ts","sources":["../src/NativeNetwork.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAgB,aAAa,EAAE,MAAM,OAAO,CAAC;AAGzD,gGAAgG;AAChG,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,0EAA0E;AAC1E,eAAO,MAAM,WAAW;aACpB,WAAW,EAAE,CAAC;aACd,SAAS,EAAE,CAAC;aACZ,KAAK,EAAE,CAAC;aACR,SAAS,EAAE,CAAC;aACZ,WAAW,EAAE,CAAC;aACd,IAAI,EAAE,CAAC;aACP,MAAM,EAAE,CAAC;aACT,KAAK,EAAE,CAAC;aACR,OAAO,EAAE,CAAC;aACV,WAAW,EAAE,EAAE;aACf,QAAQ,EAAE,EAAE;aACZ,GAAG,EAAE,EAAE;CACD,CAAC;AAEX,4CAA4C;AAC5C,MAAM,WAAW,iBAAiB;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,iEAAiE;IACjE,QAAQ,CAAC,OAAO,E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AI,CAEjE;IAED,gFAAgF;IACzE,IAAI,IAAI,IAAI,CAElB;IAED,mDAAmD;IAC5C,OAAO,IAAI,IAAI,CAErB;IAED,qGAAqG;IAC9F,KAAK,IAAI,IAAI,CAqBnB;IAED;;;OAGG;IACI,KAAK,IAAI,IAAI,CAKnB;IAED,OAAO,CAAC,QAAQ;CAOnB"}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { bindLibrary } from "./ffi.js";
|
|
2
|
+
import { NativeLibraryError, locateLibrary } from "./library.js";
|
|
3
|
+
import dgram from "node:dgram";
|
|
4
|
+
// src/NativeNetwork.ts
|
|
5
|
+
/** The interface version this binding speaks; it must equal the library's `JSP_ABI_VERSION`. */
|
|
6
|
+
var ABI_VERSION = 1;
|
|
7
|
+
/** Event kinds, as `native/include/jsp_native_network.h` numbers them. */
|
|
8
|
+
var NativeEvent = {
|
|
9
|
+
description: 1,
|
|
10
|
+
candidate: 2,
|
|
11
|
+
state: 3,
|
|
12
|
+
gathering: 4,
|
|
13
|
+
dataChannel: 5,
|
|
14
|
+
open: 6,
|
|
15
|
+
closed: 7,
|
|
16
|
+
error: 8,
|
|
17
|
+
message: 9,
|
|
18
|
+
bufferedLow: 10,
|
|
19
|
+
iceState: 11,
|
|
20
|
+
log: 12
|
|
21
|
+
};
|
|
22
|
+
var EVENT_HEADER_BYTES = 16;
|
|
23
|
+
var INITIAL_READ_BYTES = 262144;
|
|
24
|
+
/**
|
|
25
|
+
* Encodes a string for the C interface, NUL-terminated.
|
|
26
|
+
* @param text - The string.
|
|
27
|
+
* @returns Its UTF-8 bytes and a trailing NUL.
|
|
28
|
+
*/
|
|
29
|
+
var cString = (text) => Buffer.from(`${text}\0`, "utf8");
|
|
30
|
+
/**
|
|
31
|
+
* The native library, loaded once per thread, and that thread's event queue.
|
|
32
|
+
*
|
|
33
|
+
* The library is mapped once per process, and each thread that loads it opens a queue of its
|
|
34
|
+
* own, so a worker's peer connections report to the worker. libdatachannel's threads queue
|
|
35
|
+
* events in native memory and send one datagram to a loopback socket here when the queue stops
|
|
36
|
+
* being empty. The socket's handler drains the queue and
|
|
37
|
+
* dispatches each event to the handler registered for its id, so every event reaches JavaScript
|
|
38
|
+
* on the event loop, in order, with no call from a foreign thread.
|
|
39
|
+
*/
|
|
40
|
+
var NativeNetwork = class NativeNetwork {
|
|
41
|
+
library;
|
|
42
|
+
wakeSocket;
|
|
43
|
+
queue;
|
|
44
|
+
static instance;
|
|
45
|
+
/** Wake datagrams received; a burst of events costs one. */
|
|
46
|
+
wakes = 0;
|
|
47
|
+
handlers = /* @__PURE__ */ new Map();
|
|
48
|
+
readBuffer = Buffer.allocUnsafe(INITIAL_READ_BYTES);
|
|
49
|
+
logHandler;
|
|
50
|
+
/** Things that keep the process alive while they are open, such as a connection being made. */
|
|
51
|
+
holds = 0;
|
|
52
|
+
constructor(library, wakeSocket, queue) {
|
|
53
|
+
this.library = library;
|
|
54
|
+
this.wakeSocket = wakeSocket;
|
|
55
|
+
this.queue = queue;
|
|
56
|
+
wakeSocket.on("message", () => {
|
|
57
|
+
this.wakes++;
|
|
58
|
+
this.drain();
|
|
59
|
+
});
|
|
60
|
+
wakeSocket.unref();
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Loads the library and opens this thread's event queue, the first time it is called on a thread.
|
|
64
|
+
* @param options - The library file and log level; the defaults find the installed build.
|
|
65
|
+
* @returns The loaded library.
|
|
66
|
+
* @throws {NativeLibraryError} When the library cannot be found, loaded, or speaks another interface.
|
|
67
|
+
*/
|
|
68
|
+
static async load(options = {}) {
|
|
69
|
+
if (NativeNetwork.instance !== void 0) return NativeNetwork.instance;
|
|
70
|
+
const path = options.path ?? locateLibrary();
|
|
71
|
+
let library;
|
|
72
|
+
try {
|
|
73
|
+
library = bindLibrary(path);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
throw new NativeLibraryError(`The native networking library at ${path} does not load on ${process.platform}-${process.arch}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
76
|
+
}
|
|
77
|
+
const version = library.symbols.jsp_abi_version();
|
|
78
|
+
if (version !== 1) {
|
|
79
|
+
library.close();
|
|
80
|
+
throw new NativeLibraryError(`The native networking library at ${path} speaks interface ${version}; this package needs 1`);
|
|
81
|
+
}
|
|
82
|
+
const socket = dgram.createSocket("udp4");
|
|
83
|
+
await new Promise((resolve, reject) => {
|
|
84
|
+
socket.once("error", reject);
|
|
85
|
+
socket.bind(0, "127.0.0.1", () => {
|
|
86
|
+
socket.off("error", reject);
|
|
87
|
+
resolve();
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
const opened = library.symbols.jsp_events_open(socket.address().port, options.logLevel ?? 0);
|
|
91
|
+
if (opened < 0) {
|
|
92
|
+
socket.close();
|
|
93
|
+
library.close();
|
|
94
|
+
throw new NativeLibraryError(`The native networking library could not open its event queue (${opened})`);
|
|
95
|
+
}
|
|
96
|
+
NativeNetwork.instance = new NativeNetwork(library, socket, opened);
|
|
97
|
+
return NativeNetwork.instance;
|
|
98
|
+
}
|
|
99
|
+
/** The loaded library, or undefined before {@link NativeNetwork.load}. */
|
|
100
|
+
static loaded() {
|
|
101
|
+
return NativeNetwork.instance;
|
|
102
|
+
}
|
|
103
|
+
/** The bound C interface. */
|
|
104
|
+
get symbols() {
|
|
105
|
+
return this.library.symbols;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The address of shared memory, for an interface call that takes a pointer.
|
|
109
|
+
* @param memory - The memory; it must outlive every native use of the pointer.
|
|
110
|
+
* @returns The pointer.
|
|
111
|
+
*/
|
|
112
|
+
pointerOf(memory) {
|
|
113
|
+
return this.library.pointerOf(memory);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Sends the events of one id to a handler, until {@link NativeNetwork.unwatch}.
|
|
117
|
+
* @param id - The peer connection or data channel.
|
|
118
|
+
* @param handler - Receives its events in order.
|
|
119
|
+
*/
|
|
120
|
+
watch(id, handler) {
|
|
121
|
+
this.handlers.set(id, handler);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Stops sending an id's events anywhere.
|
|
125
|
+
* @param id - The peer connection or data channel.
|
|
126
|
+
*/
|
|
127
|
+
unwatch(id) {
|
|
128
|
+
this.handlers.delete(id);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Receives libdatachannel's log lines, when the library was loaded with a log level.
|
|
132
|
+
* @param handler - Receives each line and its level.
|
|
133
|
+
*/
|
|
134
|
+
onLog(handler) {
|
|
135
|
+
this.logHandler = handler;
|
|
136
|
+
}
|
|
137
|
+
/** Keeps the process alive until the matching {@link NativeNetwork.release}. */
|
|
138
|
+
hold() {
|
|
139
|
+
if (this.holds++ === 0) this.wakeSocket.ref();
|
|
140
|
+
}
|
|
141
|
+
/** Lets the process exit once nothing holds it. */
|
|
142
|
+
release() {
|
|
143
|
+
if (this.holds > 0 && --this.holds === 0) this.wakeSocket.unref();
|
|
144
|
+
}
|
|
145
|
+
/** Reads every queued event and dispatches it; a read that finds the queue empty rearms the wake. */
|
|
146
|
+
drain() {
|
|
147
|
+
for (;;) {
|
|
148
|
+
const written = this.symbols.jsp_events_read(this.queue, this.readBuffer, this.readBuffer.byteLength);
|
|
149
|
+
if (written === 0) return;
|
|
150
|
+
if (written < 0) {
|
|
151
|
+
this.readBuffer = Buffer.allocUnsafe(Math.max(-written, this.readBuffer.byteLength * 2));
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
let offset = 0;
|
|
155
|
+
while (offset < written) {
|
|
156
|
+
const length = this.readBuffer.readUInt32LE(offset);
|
|
157
|
+
const event = {
|
|
158
|
+
kind: this.readBuffer[offset + 4],
|
|
159
|
+
id: this.readBuffer.readInt32LE(offset + 8),
|
|
160
|
+
value: this.readBuffer.readInt32LE(offset + 12),
|
|
161
|
+
payload: Buffer.from(this.readBuffer.subarray(offset + EVENT_HEADER_BYTES, offset + length))
|
|
162
|
+
};
|
|
163
|
+
offset += length;
|
|
164
|
+
this.dispatch(event);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Closes this thread's peer connections and its event queue. The library stays mapped, and
|
|
170
|
+
* another thread's connections and the shared ports are not touched.
|
|
171
|
+
*/
|
|
172
|
+
close() {
|
|
173
|
+
this.symbols.jsp_events_close(this.queue);
|
|
174
|
+
this.handlers.clear();
|
|
175
|
+
this.wakeSocket.close();
|
|
176
|
+
NativeNetwork.instance = void 0;
|
|
177
|
+
}
|
|
178
|
+
dispatch(event) {
|
|
179
|
+
if (event.kind === NativeEvent.log) {
|
|
180
|
+
this.logHandler?.(event.value, event.payload.toString("utf8"));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
this.handlers.get(event.id)?.(event);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
export { ABI_VERSION, NativeEvent, NativeNetwork, cString };
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=NativeNetwork.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeNetwork.js","names":[],"sources":["../src/NativeNetwork.ts"],"sourcesContent":["import dgram from 'node:dgram';\n\nimport { bindLibrary } from './ffi';\nimport type { BoundLibrary, NativeSymbols } from './ffi';\nimport { NativeLibraryError, locateLibrary } from './library';\n\n/** The interface version this binding speaks; it must equal the library's `JSP_ABI_VERSION`. */\nexport const ABI_VERSION = 1;\n\n/** Event kinds, as `native/include/jsp_native_network.h` numbers them. */\nexport const NativeEvent = {\n description: 1,\n candidate: 2,\n state: 3,\n gathering: 4,\n dataChannel: 5,\n open: 6,\n closed: 7,\n error: 8,\n message: 9,\n bufferedLow: 10,\n iceState: 11,\n log: 12\n} as const;\n\n/** One event read from the native queue. */\nexport interface NativeEventRecord {\n readonly kind: number;\n /** The peer connection or data channel the event is about. */\n readonly id: number;\n readonly value: number;\n /** A copy of the payload; it stays valid after the next read. */\n readonly payload: Buffer;\n}\n\n/** What receives the events of one peer connection or data channel. */\nexport type NativeEventHandler = (event: NativeEventRecord) => void;\n\nconst EVENT_HEADER_BYTES = 16;\nconst INITIAL_READ_BYTES = 256 * 1024;\n\n/**\n * Encodes a string for the C interface, NUL-terminated.\n * @param text - The string.\n * @returns Its UTF-8 bytes and a trailing NUL.\n */\nexport const cString = (text: string): Buffer => Buffer.from(`${text}\\0`, 'utf8');\n\n/**\n * The native library, loaded once per thread, and that thread's event queue.\n *\n * The library is mapped once per process, and each thread that loads it opens a queue of its\n * own, so a worker's peer connections report to the worker. libdatachannel's threads queue\n * events in native memory and send one datagram to a loopback socket here when the queue stops\n * being empty. The socket's handler drains the queue and\n * dispatches each event to the handler registered for its id, so every event reaches JavaScript\n * on the event loop, in order, with no call from a foreign thread.\n */\nexport class NativeNetwork {\n private static instance: NativeNetwork | undefined;\n\n /** Wake datagrams received; a burst of events costs one. */\n public wakes = 0;\n\n private readonly handlers = new Map<number, NativeEventHandler>();\n private readBuffer = Buffer.allocUnsafe(INITIAL_READ_BYTES);\n private logHandler: ((level: number, line: string) => void) | undefined;\n /** Things that keep the process alive while they are open, such as a connection being made. */\n private holds = 0;\n\n private constructor(\n private readonly library: BoundLibrary,\n private readonly wakeSocket: dgram.Socket,\n /** The handle of this thread's event queue, which peer connections are created on. */\n public readonly queue: number\n ) {\n wakeSocket.on('message', () => {\n this.wakes++;\n this.drain();\n });\n wakeSocket.unref();\n }\n\n /**\n * Loads the library and opens this thread's event queue, the first time it is called on a thread.\n * @param options - The library file and log level; the defaults find the installed build.\n * @returns The loaded library.\n * @throws {NativeLibraryError} When the library cannot be found, loaded, or speaks another interface.\n */\n public static async load(options: { path?: string; logLevel?: number } = {}): Promise<NativeNetwork> {\n if (NativeNetwork.instance !== undefined) return NativeNetwork.instance;\n const path = options.path ?? locateLibrary();\n let library: BoundLibrary;\n try {\n library = bindLibrary(path);\n } catch (error: unknown) {\n throw new NativeLibraryError(\n `The native networking library at ${path} does not load on ${process.platform}-${process.arch}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error }\n );\n }\n const version = library.symbols.jsp_abi_version();\n if (version !== ABI_VERSION) {\n library.close();\n throw new NativeLibraryError(\n `The native networking library at ${path} speaks interface ${version}; this package needs ${ABI_VERSION}`\n );\n }\n\n const socket = dgram.createSocket('udp4');\n await new Promise<void>((resolve, reject) => {\n socket.once('error', reject);\n socket.bind(0, '127.0.0.1', () => {\n socket.off('error', reject);\n resolve();\n });\n });\n const opened = library.symbols.jsp_events_open(socket.address().port, options.logLevel ?? 0);\n if (opened < 0) {\n socket.close();\n library.close();\n throw new NativeLibraryError(`The native networking library could not open its event queue (${opened})`);\n }\n NativeNetwork.instance = new NativeNetwork(library, socket, opened);\n return NativeNetwork.instance;\n }\n\n /** The loaded library, or undefined before {@link NativeNetwork.load}. */\n public static loaded(): NativeNetwork | undefined {\n return NativeNetwork.instance;\n }\n\n /** The bound C interface. */\n public get symbols(): NativeSymbols {\n return this.library.symbols;\n }\n\n /**\n * The address of shared memory, for an interface call that takes a pointer.\n * @param memory - The memory; it must outlive every native use of the pointer.\n * @returns The pointer.\n */\n public pointerOf(memory: SharedArrayBuffer): bigint | number {\n return this.library.pointerOf(memory);\n }\n\n /**\n * Sends the events of one id to a handler, until {@link NativeNetwork.unwatch}.\n * @param id - The peer connection or data channel.\n * @param handler - Receives its events in order.\n */\n public watch(id: number, handler: NativeEventHandler): void {\n this.handlers.set(id, handler);\n }\n\n /**\n * Stops sending an id's events anywhere.\n * @param id - The peer connection or data channel.\n */\n public unwatch(id: number): void {\n this.handlers.delete(id);\n }\n\n /**\n * Receives libdatachannel's log lines, when the library was loaded with a log level.\n * @param handler - Receives each line and its level.\n */\n public onLog(handler: (level: number, line: string) => void): void {\n this.logHandler = handler;\n }\n\n /** Keeps the process alive until the matching {@link NativeNetwork.release}. */\n public hold(): void {\n if (this.holds++ === 0) this.wakeSocket.ref();\n }\n\n /** Lets the process exit once nothing holds it. */\n public release(): void {\n if (this.holds > 0 && --this.holds === 0) this.wakeSocket.unref();\n }\n\n /** Reads every queued event and dispatches it; a read that finds the queue empty rearms the wake. */\n public drain(): void {\n for (;;) {\n const written = this.symbols.jsp_events_read(this.queue, this.readBuffer, this.readBuffer.byteLength);\n if (written === 0) return;\n if (written < 0) {\n this.readBuffer = Buffer.allocUnsafe(Math.max(-written, this.readBuffer.byteLength * 2));\n continue;\n }\n let offset = 0;\n while (offset < written) {\n const length = this.readBuffer.readUInt32LE(offset);\n const event: NativeEventRecord = {\n kind: this.readBuffer[offset + 4]!,\n id: this.readBuffer.readInt32LE(offset + 8),\n value: this.readBuffer.readInt32LE(offset + 12),\n payload: Buffer.from(this.readBuffer.subarray(offset + EVENT_HEADER_BYTES, offset + length))\n };\n offset += length;\n this.dispatch(event);\n }\n }\n }\n\n /**\n * Closes this thread's peer connections and its event queue. The library stays mapped, and\n * another thread's connections and the shared ports are not touched.\n */\n public close(): void {\n this.symbols.jsp_events_close(this.queue);\n this.handlers.clear();\n this.wakeSocket.close();\n NativeNetwork.instance = undefined;\n }\n\n private dispatch(event: NativeEventRecord): void {\n if (event.kind === NativeEvent.log) {\n this.logHandler?.(event.value, event.payload.toString('utf8'));\n return;\n }\n this.handlers.get(event.id)?.(event);\n }\n}\n"],"mappings":";;;;;AAOA,IAAa,cAAc;;AAG3B,IAAa,cAAc;CACvB,aAAa;CACb,WAAW;CACX,OAAO;CACP,WAAW;CACX,aAAa;CACb,MAAM;CACN,QAAQ;CACR,OAAO;CACP,SAAS;CACT,aAAa;CACb,UAAU;CACV,KAAK;AACT;AAeA,IAAM,qBAAqB;AAC3B,IAAM,qBAAqB;;;;;;AAO3B,IAAa,WAAW,SAAyB,OAAO,KAAK,GAAG,KAAK,KAAK,MAAM;;;;;;;;;;;AAYhF,IAAa,gBAAb,MAAa,cAAc;CAaF;CACA;CAED;CAfpB,OAAe;;CAGf,QAAe;CAEf,2BAA4B,IAAI,IAAgC;CAChE,aAAqB,OAAO,YAAY,kBAAkB;CAC1D;;CAEA,QAAgB;CAEhB,YACI,SACA,YAEA,OACF;EA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K,aAAa,MAAM,OAAO,MAAM,QAAQ,SAAS,MAAM,CAAC;GAC7D;EACJ;EACA,KAAK,SAAS,IAAI,MAAM,EAAE,CAAC,GAAG,KAAK;CACvC;AACJ"}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import type { NativeNetwork } from './NativeNetwork';
|
|
3
|
+
/** libdatachannel's `rtcState`, a peer connection's state. */
|
|
4
|
+
export type PeerConnectionState = 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed';
|
|
5
|
+
/** libdatachannel's `rtcGatheringState`. */
|
|
6
|
+
export type GatheringState = 'new' | 'in-progress' | 'complete';
|
|
7
|
+
/** libdatachannel's `rtcIceState`. */
|
|
8
|
+
export type IceConnectionState = 'new' | 'checking' | 'connected' | 'completed' | 'failed' | 'disconnected' | 'closed';
|
|
9
|
+
/** How a peer connection binds and which ports it may use. */
|
|
10
|
+
export interface PeerConnectionOptions {
|
|
11
|
+
/** The local address libjuice binds; every interface when absent. */
|
|
12
|
+
readonly bindAddress?: string;
|
|
13
|
+
/** STUN or TURN servers, as libdatachannel's URLs. */
|
|
14
|
+
readonly iceServers?: readonly string[];
|
|
15
|
+
/** The lowest local UDP port; with `portRangeEnd`, 0 or absent lets the system choose. */
|
|
16
|
+
readonly portRangeBegin?: number;
|
|
17
|
+
readonly portRangeEnd?: number;
|
|
18
|
+
/** Serves every peer connection on a port from one socket, libjuice's mux mode. */
|
|
19
|
+
readonly enableIceUdpMux?: boolean;
|
|
20
|
+
/** The largest message the remote side may send; libdatachannel's default when absent. */
|
|
21
|
+
readonly maxMessageSize?: number;
|
|
22
|
+
}
|
|
23
|
+
/** Which way a data channel delivers. */
|
|
24
|
+
export interface DataChannelOptions {
|
|
25
|
+
/** Delivers in any order. */
|
|
26
|
+
readonly unordered?: boolean;
|
|
27
|
+
/** Gives up on a message after this many retransmissions; reliable when absent. */
|
|
28
|
+
readonly maxRetransmits?: number;
|
|
29
|
+
}
|
|
30
|
+
/** A selected pair's two candidates, as SDP candidate lines without the `a=` prefix. */
|
|
31
|
+
export interface SelectedCandidatePair {
|
|
32
|
+
readonly local: string;
|
|
33
|
+
readonly remote: string;
|
|
34
|
+
}
|
|
35
|
+
/** A local candidate, as a W3C `RTCIceCandidateInit` carries it. */
|
|
36
|
+
export interface LocalCandidate {
|
|
37
|
+
readonly candidate: string;
|
|
38
|
+
readonly sdpMid: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A data channel on a native peer connection.
|
|
42
|
+
*
|
|
43
|
+
* Events: `open`, `close`, `error` (Error), `message` (Buffer, binary flag), `bufferedamountlow`.
|
|
44
|
+
*/
|
|
45
|
+
export declare class DataChannel extends EventEmitter {
|
|
46
|
+
private readonly network;
|
|
47
|
+
readonly id: number;
|
|
48
|
+
readonly label: string;
|
|
49
|
+
private state;
|
|
50
|
+
/**
|
|
51
|
+
* @param network - The loaded library.
|
|
52
|
+
* @param id - libdatachannel's id for the channel.
|
|
53
|
+
* @param label - The channel's label.
|
|
54
|
+
* @param open - Whether it is open already, as an incoming channel often is.
|
|
55
|
+
*/
|
|
56
|
+
constructor(network: NativeNetwork, id: number, label: string, open: boolean);
|
|
57
|
+
/** `connecting`, `open`, `closing` or `closed`, as the W3C `readyState`. */
|
|
58
|
+
get readyState(): 'connecting' | 'open' | 'closing' | 'closed';
|
|
59
|
+
/** Bytes queued in libdatachannel and not yet handed to SCTP. */
|
|
60
|
+
get bufferedAmount(): number;
|
|
61
|
+
/**
|
|
62
|
+
* Fires `bufferedamountlow` once the buffered amount falls to this many bytes.
|
|
63
|
+
* @param amount - The threshold.
|
|
64
|
+
*/
|
|
65
|
+
setBufferedAmountLowThreshold(amount: number): void;
|
|
66
|
+
/**
|
|
67
|
+
* Sends one message.
|
|
68
|
+
* @param data - The message's bytes.
|
|
69
|
+
* @returns Whether libdatachannel took it; false on a channel that is not open.
|
|
70
|
+
*/
|
|
71
|
+
send(data: Uint8Array): boolean;
|
|
72
|
+
/** Closes the channel; `close` follows, once the stream is reset. */
|
|
73
|
+
close(): void;
|
|
74
|
+
private handle;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A peer connection in the native library.
|
|
78
|
+
*
|
|
79
|
+
* Events: `description` ({ type, sdp }), `candidate` (LocalCandidate), `gatheringstatechange`,
|
|
80
|
+
* `connectionstatechange`, `iceconnectionstatechange`, `datachannel` (DataChannel).
|
|
81
|
+
* libdatachannel negotiates by itself: a remote offer produces the answer, and the first data
|
|
82
|
+
* channel on a new connection produces the offer.
|
|
83
|
+
*/
|
|
84
|
+
export declare class PeerConnection extends EventEmitter {
|
|
85
|
+
private readonly network;
|
|
86
|
+
connectionState: PeerConnectionState;
|
|
87
|
+
iceGatheringState: GatheringState;
|
|
88
|
+
iceConnectionState: IceConnectionState;
|
|
89
|
+
/** The last local description libdatachannel made. */
|
|
90
|
+
localDescription: {
|
|
91
|
+
type: 'offer' | 'answer';
|
|
92
|
+
sdp: string;
|
|
93
|
+
} | undefined;
|
|
94
|
+
readonly id: number;
|
|
95
|
+
private readonly channels;
|
|
96
|
+
private deleted;
|
|
97
|
+
private closing;
|
|
98
|
+
/**
|
|
99
|
+
* @param network - The loaded library.
|
|
100
|
+
* @param options - Binding and ports.
|
|
101
|
+
* @throws {Error} When libdatachannel refuses the configuration.
|
|
102
|
+
*/
|
|
103
|
+
constructor(network: NativeNetwork, options?: PeerConnectionOptions);
|
|
104
|
+
/**
|
|
105
|
+
* Applies the remote side's description. An offer makes libdatachannel answer.
|
|
106
|
+
* @param description - The description and its type.
|
|
107
|
+
*/
|
|
108
|
+
setRemoteDescription(description: {
|
|
109
|
+
type: 'offer' | 'answer';
|
|
110
|
+
sdp: string;
|
|
111
|
+
}): void;
|
|
112
|
+
/**
|
|
113
|
+
* Adds a remote candidate.
|
|
114
|
+
* @param candidate - The candidate line, with or without `a=`.
|
|
115
|
+
* @param sdpMid - Its media id; `0` when absent, as a NetherNet offer has one section.
|
|
116
|
+
*/
|
|
117
|
+
addRemoteCandidate(candidate: string, sdpMid?: string): void;
|
|
118
|
+
/**
|
|
119
|
+
* Creates a data channel; on a new connection, that makes libdatachannel produce the offer.
|
|
120
|
+
* @param label - The channel's label.
|
|
121
|
+
* @param options - Ordering and retransmissions.
|
|
122
|
+
* @returns The channel.
|
|
123
|
+
*/
|
|
124
|
+
createDataChannel(label: string, options?: DataChannelOptions): DataChannel;
|
|
125
|
+
/**
|
|
126
|
+
* The current local description as libdatachannel holds it, with every candidate gathered so
|
|
127
|
+
* far; read it after `gatheringstatechange` reaches `complete` to send one with all of them.
|
|
128
|
+
* @returns The SDP, or undefined before there is one.
|
|
129
|
+
*/
|
|
130
|
+
currentLocalSdp(): string | undefined;
|
|
131
|
+
/** The candidate pair ICE selected, once connected. */
|
|
132
|
+
selectedCandidatePair(): SelectedCandidatePair | undefined;
|
|
133
|
+
/**
|
|
134
|
+
* Closes the connection and its channels. libdatachannel shuts SCTP down gracefully, so what
|
|
135
|
+
* was sent before still arrives; the native objects are freed once it reports `closed`, and
|
|
136
|
+
* deleting them sooner would cut that shutdown short.
|
|
137
|
+
*/
|
|
138
|
+
close(): void;
|
|
139
|
+
private track;
|
|
140
|
+
private free;
|
|
141
|
+
private handle;
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=PeerConnection.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PeerConnection.d.ts","sources":["../src/PeerConnection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG3C,OAAO,KAAK,EAAqB,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAExE,8DAA8D;AAC9D,MAAM,MAAM,mBAAmB,GAAG,KAAK,GAAG,YAAY,GAAG,WAAW,GAAG,cAAc,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC5G,4CAA4C;AAC5C,MAAM,MAAM,cAAc,GAAG,KAAK,GAAG,aAAa,GAAG,UAAU,C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