UNPKG

21.7 kBTypeScriptView Raw
1import * as BinaryPack from "peerjs-js-binarypack";
2import { EventEmitter, ValidEventTypes } from "eventemitter3";
3declare class BinaryPackChunker {
4 readonly chunkedMTU = 16300;
5 chunk: (blob: ArrayBuffer) => {
6 __peerData: number;
7 n: number;
8 total: number;
9 data: Uint8Array;
10 }[];
11}
12export interface UtilSupportsObj {
13 /**
14 * The current browser.
15 * This property can be useful in determining whether two peers can connect.
16 *
17 * ```ts
18 * if (util.browser === 'firefox') {
19 * // OK to peer with Firefox peers.
20 * }
21 * ```
22 *
23 * `util.browser` can currently have the values
24 * `'firefox', 'chrome', 'safari', 'edge', 'Not a supported browser.', 'Not a browser.' (unknown WebRTC-compatible agent).
25 */
26 browser: boolean;
27 webRTC: boolean;
28 /**
29 * True if the current browser supports media streams and PeerConnection.
30 */
31 audioVideo: boolean;
32 /**
33 * True if the current browser supports DataChannel and PeerConnection.
34 */
35 data: boolean;
36 binaryBlob: boolean;
37 /**
38 * True if the current browser supports reliable DataChannels.
39 */
40 reliable: boolean;
41}
42export class Util extends BinaryPackChunker {
43 noop(): void;
44 readonly CLOUD_HOST = "0.peerjs.com";
45 readonly CLOUD_PORT = 443;
46 readonly chunkedBrowsers: {
47 Chrome: number;
48 chrome: number;
49 };
50 readonly defaultConfig: {
51 iceServers: ({
52 urls: string;
53 username?: undefined;
54 credential?: undefined;
55 } | {
56 urls: string[];
57 username: string;
58 credential: string;
59 })[];
60 sdpSemantics: string;
61 };
62 readonly browser: string;
63 readonly browserVersion: number;
64 pack: typeof BinaryPack.pack;
65 unpack: typeof BinaryPack.unpack;
66 /**
67 * A hash of WebRTC features mapped to booleans that correspond to whether the feature is supported by the current browser.
68 *
69 * :::caution
70 * Only the properties documented here are guaranteed to be present on `util.supports`
71 * :::
72 */
73 readonly supports: UtilSupportsObj;
74 validateId: (id: string) => boolean;
75 randomToken: () => string;
76 blobToArrayBuffer(blob: Blob, cb: (arg: ArrayBuffer | null) => void): FileReader;
77 binaryStringToArrayBuffer(binary: string): ArrayBuffer | SharedArrayBuffer;
78 isSecure(): boolean;
79}
80/**
81 * Provides a variety of helpful utilities.
82 *
83 * :::caution
84 * Only the utilities documented here are guaranteed to be present on `util`.
85 * Undocumented utilities can be removed without warning.
86 * We don't consider these to be breaking changes.
87 * :::
88 */
89export const util: Util;
90export enum LogLevel {
91 /**
92 * Prints no logs.
93 */
94 Disabled = 0,
95 /**
96 * Prints only errors.
97 */
98 Errors = 1,
99 /**
100 * Prints errors and warnings.
101 */
102 Warnings = 2,
103 /**
104 * Prints all logs.
105 */
106 All = 3
107}
108export enum ConnectionType {
109 Data = "data",
110 Media = "media"
111}
112export enum PeerErrorType {
113 /**
114 * The client's browser does not support some or all WebRTC features that you are trying to use.
115 */
116 BrowserIncompatible = "browser-incompatible",
117 /**
118 * You've already disconnected this peer from the server and can no longer make any new connections on it.
119 */
120 Disconnected = "disconnected",
121 /**
122 * The ID passed into the Peer constructor contains illegal characters.
123 */
124 InvalidID = "invalid-id",
125 /**
126 * The API key passed into the Peer constructor contains illegal characters or is not in the system (cloud server only).
127 */
128 InvalidKey = "invalid-key",
129 /**
130 * Lost or cannot establish a connection to the signalling server.
131 */
132 Network = "network",
133 /**
134 * The peer you're trying to connect to does not exist.
135 */
136 PeerUnavailable = "peer-unavailable",
137 /**
138 * PeerJS is being used securely, but the cloud server does not support SSL. Use a custom PeerServer.
139 */
140 SslUnavailable = "ssl-unavailable",
141 /**
142 * Unable to reach the server.
143 */
144 ServerError = "server-error",
145 /**
146 * An error from the underlying socket.
147 */
148 SocketError = "socket-error",
149 /**
150 * The underlying socket closed unexpectedly.
151 */
152 SocketClosed = "socket-closed",
153 /**
154 * The ID passed into the Peer constructor is already taken.
155 *
156 * :::caution
157 * This error is not fatal if your peer has open peer-to-peer connections.
158 * This can happen if you attempt to {@apilink Peer.reconnect} a peer that has been disconnected from the server,
159 * but its old ID has now been taken.
160 * :::
161 */
162 UnavailableID = "unavailable-id",
163 /**
164 * Native WebRTC errors.
165 */
166 WebRTC = "webrtc"
167}
168export enum BaseConnectionErrorType {
169 NegotiationFailed = "negotiation-failed",
170 ConnectionClosed = "connection-closed"
171}
172export enum DataConnectionErrorType {
173 NotOpenYet = "not-open-yet",
174 MessageToBig = "message-too-big"
175}
176export enum SerializationType {
177 Binary = "binary",
178 BinaryUTF8 = "binary-utf8",
179 JSON = "json",
180 None = "raw"
181}
182export enum SocketEventType {
183 Message = "message",
184 Disconnected = "disconnected",
185 Error = "error",
186 Close = "close"
187}
188export enum ServerMessageType {
189 Heartbeat = "HEARTBEAT",
190 Candidate = "CANDIDATE",
191 Offer = "OFFER",
192 Answer = "ANSWER",
193 Open = "OPEN",// The connection to the server is open.
194 Error = "ERROR",// Server error.
195 IdTaken = "ID-TAKEN",// The selected ID is taken.
196 InvalidKey = "INVALID-KEY",// The given API key cannot be found.
197 Leave = "LEAVE",// Another peer has closed its connection to this peer.
198 Expire = "EXPIRE"
199}
200/**
201 * An abstraction on top of WebSockets to provide fastest
202 * possible connection for peers.
203 */
204declare class Socket extends EventEmitter {
205 constructor(secure: any, host: string, port: number, path: string, key: string, pingInterval?: number);
206 start(id: string, token: string): void;
207 /** Exposed send for DC & Peer. */
208 send(data: any): void;
209 close(): void;
210}
211declare class ServerMessage {
212 type: ServerMessageType;
213 payload: any;
214 src: string;
215}
216interface EventsWithError<ErrorType extends string> {
217 error: (error: PeerError<`${ErrorType}`>) => void;
218}
219declare class EventEmitterWithError<ErrorType extends string, Events extends EventsWithError<ErrorType>> extends EventEmitter<Events, never> {
220 /**
221 * Emits a typed error message.
222 *
223 * @internal
224 */
225 emitError(type: ErrorType, err: string | Error): void;
226}
227/**
228 * A PeerError is emitted whenever an error occurs.
229 * It always has a `.type`, which can be used to identify the error.
230 */
231export class PeerError<T extends string> extends Error {
232 /**
233 * @internal
234 */
235 constructor(type: T, err: Error | string);
236 type: T;
237}
238interface BaseConnectionEvents<ErrorType extends string = BaseConnectionErrorType> extends EventsWithError<ErrorType> {
239 /**
240 * Emitted when either you or the remote peer closes the connection.
241 *
242 * ```ts
243 * connection.on('close', () => { ... });
244 * ```
245 */
246 close: () => void;
247 /**
248 * ```ts
249 * connection.on('error', (error) => { ... });
250 * ```
251 */
252 error: (error: PeerError<`${ErrorType}`>) => void;
253 iceStateChanged: (state: RTCIceConnectionState) => void;
254}
255declare abstract class BaseConnection<SubClassEvents extends ValidEventTypes, ErrorType extends string = never> extends EventEmitterWithError<ErrorType | BaseConnectionErrorType, SubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>> {
256 /**
257 * The ID of the peer on the other end of this connection.
258 */
259 readonly peer: string;
260 provider: Peer;
261 readonly options: any;
262 protected _open: boolean;
263 /**
264 * Any type of metadata associated with the connection,
265 * passed in by whoever initiated the connection.
266 */
267 readonly metadata: any;
268 connectionId: string;
269 peerConnection: RTCPeerConnection;
270 dataChannel: RTCDataChannel;
271 abstract get type(): ConnectionType;
272 /**
273 * The optional label passed in or assigned by PeerJS when the connection was initiated.
274 */
275 label: string;
276 /**
277 * Whether the media connection is active (e.g. your call has been answered).
278 * You can check this if you want to set a maximum wait time for a one-sided call.
279 */
280 get open(): boolean;
281 protected constructor(
282 /**
283 * The ID of the peer on the other end of this connection.
284 */
285 peer: string, provider: Peer, options: any);
286 abstract close(): void;
287 /**
288 * @internal
289 */
290 abstract handleMessage(message: ServerMessage): void;
291 /**
292 * Called by the Negotiator when the DataChannel is ready.
293 * @internal
294 * */
295 abstract _initializeDataChannel(dc: RTCDataChannel): void;
296}
297interface DataConnectionEvents extends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>, BaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {
298 /**
299 * Emitted when data is received from the remote peer.
300 */
301 data: (data: unknown) => void;
302 /**
303 * Emitted when the connection is established and ready-to-use.
304 */
305 open: () => void;
306}
307/**
308 * Wraps a DataChannel between two Peers.
309 */
310export abstract class DataConnection extends BaseConnection<DataConnectionEvents, DataConnectionErrorType> {
311 protected static readonly ID_PREFIX = "dc_";
312 protected static readonly MAX_BUFFERED_AMOUNT: number;
313 abstract readonly serialization: string;
314 readonly reliable: boolean;
315 get type(): ConnectionType;
316 constructor(peerId: string, provider: Peer, options: any);
317 /** Called by the Negotiator when the DataChannel is ready. */
318 _initializeDataChannel(dc: RTCDataChannel): void;
319 /**
320 * Exposed functionality for users.
321 */
322 /** Allows user to close connection. */
323 close(options?: {
324 flush?: boolean;
325 }): void;
326 protected abstract _send(data: any, chunked: boolean): void | Promise<void>;
327 /** Allows user to send data. */
328 send(data: any, chunked?: boolean): void | Promise<void>;
329 handleMessage(message: ServerMessage): Promise<void>;
330}
331export interface AnswerOption {
332 /**
333 * Function which runs before create answer to modify sdp answer message.
334 */
335 sdpTransform?: Function;
336}
337export interface PeerJSOption {
338 key?: string;
339 host?: string;
340 port?: number;
341 path?: string;
342 secure?: boolean;
343 token?: string;
344 config?: RTCConfiguration;
345 debug?: number;
346 referrerPolicy?: ReferrerPolicy;
347}
348export interface PeerConnectOption {
349 /**
350 * A unique label by which you want to identify this data connection.
351 * If left unspecified, a label will be generated at random.
352 *
353 * Can be accessed with {@apilink DataConnection.label}
354 */
355 label?: string;
356 /**
357 * Metadata associated with the connection, passed in by whoever initiated the connection.
358 *
359 * Can be accessed with {@apilink DataConnection.metadata}.
360 * Can be any serializable type.
361 */
362 metadata?: any;
363 serialization?: string;
364 reliable?: boolean;
365}
366export interface CallOption {
367 /**
368 * Metadata associated with the connection, passed in by whoever initiated the connection.
369 *
370 * Can be accessed with {@apilink MediaConnection.metadata}.
371 * Can be any serializable type.
372 */
373 metadata?: any;
374 /**
375 * Function which runs before create offer to modify sdp offer message.
376 */
377 sdpTransform?: Function;
378}
379interface MediaConnectionEvents extends BaseConnectionEvents<never> {
380 /**
381 * Emitted when a connection to the PeerServer is established.
382 *
383 * ```ts
384 * mediaConnection.on('stream', (stream) => { ... });
385 * ```
386 */
387 stream: (stream: MediaStream) => void;
388 /**
389 * Emitted when the auxiliary data channel is established.
390 * After this event, hanging up will close the connection cleanly on the remote peer.
391 * @beta
392 */
393 willCloseOnRemote: () => void;
394}
395/**
396 * Wraps WebRTC's media streams.
397 * To get one, use {@apilink Peer.call} or listen for the {@apilink PeerEvents | `call`} event.
398 */
399export class MediaConnection extends BaseConnection<MediaConnectionEvents> {
400 readonly label: string;
401 /**
402 * For media connections, this is always 'media'.
403 */
404 get type(): ConnectionType;
405 get localStream(): MediaStream;
406 get remoteStream(): MediaStream;
407 constructor(peerId: string, provider: Peer, options: any);
408 /** Called by the Negotiator when the DataChannel is ready. */
409 _initializeDataChannel(dc: RTCDataChannel): void;
410 addStream(remoteStream: any): void;
411 /**
412 * @internal
413 */
414 handleMessage(message: ServerMessage): void;
415 /**
416 * When receiving a {@apilink PeerEvents | `call`} event on a peer, you can call
417 * `answer` on the media connection provided by the callback to accept the call
418 * and optionally send your own media stream.
419
420 *
421 * @param stream A WebRTC media stream.
422 * @param options
423 * @returns
424 */
425 answer(stream?: MediaStream, options?: AnswerOption): void;
426 /**
427 * Exposed functionality for users.
428 */
429 /**
430 * Closes the media connection.
431 */
432 close(): void;
433}
434export abstract class BufferedConnection extends DataConnection {
435 get bufferSize(): number;
436 _initializeDataChannel(dc: RTCDataChannel): void;
437 protected abstract _handleDataMessage(e: MessageEvent): void;
438 protected _bufferedSend(msg: ArrayBuffer): void;
439 close(options?: {
440 flush?: boolean;
441 }): void;
442}
443export class PeerOptions implements PeerJSOption {
444 /**
445 * Prints log messages depending on the debug level passed in.
446 */
447 debug?: LogLevel;
448 /**
449 * Server host. Defaults to `0.peerjs.com`.
450 * Also accepts `'/'` to signify relative hostname.
451 */
452 host?: string;
453 /**
454 * Server port. Defaults to `443`.
455 */
456 port?: number;
457 /**
458 * The path where your self-hosted PeerServer is running. Defaults to `'/'`
459 */
460 path?: string;
461 /**
462 * API key for the PeerServer.
463 * This is not used anymore.
464 * @deprecated
465 */
466 key?: string;
467 token?: string;
468 /**
469 * Configuration hash passed to RTCPeerConnection.
470 * This hash contains any custom ICE/TURN server configuration.
471 *
472 * Defaults to {@apilink util.defaultConfig}
473 */
474 config?: any;
475 /**
476 * Set to true `true` if you're using TLS.
477 * :::danger
478 * If possible *always use TLS*
479 * :::
480 */
481 secure?: boolean;
482 pingInterval?: number;
483 referrerPolicy?: ReferrerPolicy;
484 logFunction?: (logLevel: LogLevel, ...rest: any[]) => void;
485 serializers?: SerializerMapping;
486}
487export interface SerializerMapping {
488 [key: string]: new (peerId: string, provider: Peer, options: any) => DataConnection;
489}
490export interface PeerEvents {
491 /**
492 * Emitted when a connection to the PeerServer is established.
493 *
494 * You may use the peer before this is emitted, but messages to the server will be queued. <code>id</code> is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).<span class='tip'>You should not wait for this event before connecting to other peers if connection speed is important.</span>
495 */
496 open: (id: string) => void;
497 /**
498 * Emitted when a new data connection is established from a remote peer.
499 */
500 connection: (dataConnection: DataConnection) => void;
501 /**
502 * Emitted when a remote peer attempts to call you.
503 */
504 call: (mediaConnection: MediaConnection) => void;
505 /**
506 * Emitted when the peer is destroyed and can no longer accept or create any new connections.
507 */
508 close: () => void;
509 /**
510 * Emitted when the peer is disconnected from the signalling server
511 */
512 disconnected: (currentId: string) => void;
513 /**
514 * Errors on the peer are almost always fatal and will destroy the peer.
515 *
516 * Errors from the underlying socket and PeerConnections are forwarded here.
517 */
518 error: (error: PeerError<`${PeerErrorType}`>) => void;
519}
520/**
521 * A peer who can initiate connections with other peers.
522 */
523export class Peer extends EventEmitterWithError<PeerErrorType, PeerEvents> {
524 protected readonly _serializers: SerializerMapping;
525 /**
526 * The brokering ID of this peer
527 *
528 * If no ID was specified in {@apilink Peer | the constructor},
529 * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.
530 */
531 get id(): string;
532 get options(): PeerOptions;
533 get open(): boolean;
534 /**
535 * @internal
536 */
537 get socket(): Socket;
538 /**
539 * A hash of all connections associated with this peer, keyed by the remote peer's ID.
540 * @deprecated
541 * Return type will change from Object to Map<string,[]>
542 */
543 get connections(): Object;
544 /**
545 * true if this peer and all of its connections can no longer be used.
546 */
547 get destroyed(): boolean;
548 /**
549 * false if there is an active connection to the PeerServer.
550 */
551 get disconnected(): boolean;
552 /**
553 * A peer can connect to other peers and listen for connections.
554 */
555 constructor();
556 /**
557 * A peer can connect to other peers and listen for connections.
558 * @param options for specifying details about PeerServer
559 */
560 constructor(options: PeerOptions);
561 /**
562 * A peer can connect to other peers and listen for connections.
563 * @param id Other peers can connect to this peer using the provided ID.
564 * If no ID is given, one will be generated by the brokering server.
565 * The ID must start and end with an alphanumeric character (lower or upper case character or a digit). In the middle of the ID spaces, dashes (-) and underscores (_) are allowed. Use {@apilink PeerOptions.metadata } to send identifying information.
566 * @param options for specifying details about PeerServer
567 */
568 constructor(id: string, options?: PeerOptions);
569 /**
570 * Retrieve messages from lost message store
571 * @internal
572 */
573 _getMessages(connectionId: string): ServerMessage[];
574 /**
575 * Connects to the remote peer specified by id and returns a data connection.
576 * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).
577 * @param options for specifying details about Peer Connection
578 */
579 connect(peer: string, options?: PeerConnectOption): DataConnection;
580 /**
581 * Calls the remote peer specified by id and returns a media connection.
582 * @param peer The brokering ID of the remote peer (their peer.id).
583 * @param stream The caller's media stream
584 * @param options Metadata associated with the connection, passed in by whoever initiated the connection.
585 */
586 call(peer: string, stream: MediaStream, options?: CallOption): MediaConnection;
587 _removeConnection(connection: DataConnection | MediaConnection): void;
588 /** Retrieve a data/media connection for this peer. */
589 getConnection(peerId: string, connectionId: string): null | DataConnection | MediaConnection;
590 /**
591 * Destroys the Peer: closes all active connections as well as the connection
592 * to the server.
593 *
594 * :::caution
595 * This cannot be undone; the respective peer object will no longer be able
596 * to create or receive any connections, its ID will be forfeited on the server,
597 * and all of its data and media connections will be closed.
598 * :::
599 */
600 destroy(): void;
601 /**
602 * Disconnects the Peer's connection to the PeerServer. Does not close any
603 * active connections.
604 * Warning: The peer can no longer create or accept connections after being
605 * disconnected. It also cannot reconnect to the server.
606 */
607 disconnect(): void;
608 /** Attempts to reconnect with the same ID.
609 *
610 * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.
611 * Destroyed peers cannot be reconnected.
612 * If the connection fails (as an example, if the peer's old ID is now taken),
613 * the peer's existing connections will not close, but any associated errors events will fire.
614 */
615 reconnect(): void;
616 /**
617 * Get a list of available peer IDs. If you're running your own server, you'll
618 * want to set allow_discovery: true in the PeerServer options. If you're using
619 * the cloud server, email team@peerjs.com to get the functionality enabled for
620 * your key.
621 */
622 listAllPeers(cb?: (_: any[]) => void): void;
623}
624export abstract class StreamConnection extends DataConnection {
625 protected writer: WritableStreamDefaultWriter<Uint8Array>;
626 protected _rawReadStream: ReadableStream<ArrayBuffer>;
627 protected constructor(peerId: string, provider: Peer, options: any);
628 _initializeDataChannel(dc: any): void;
629}
630export class Cbor extends StreamConnection {
631 readonly serialization = "Cbor";
632 constructor(peerId: string, provider: Peer, options: any);
633 protected _send(data: any): Promise<void>;
634}
635export class CborPeer extends Peer {
636 _serializers: SerializerMapping;
637}
638export class MsgPackPeer extends Peer {
639 _serializers: SerializerMapping;
640}
641export class MsgPack extends StreamConnection {
642 readonly serialization = "MsgPack";
643 constructor(peerId: string, provider: Peer, options: any);
644 protected _send(data: any): Promise<void>;
645}
646export default Peer;
647
648//# sourceMappingURL=types.d.ts.map