@4players/odin-common 4.0.2 → 4.0.3

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/mod.mjs CHANGED
@@ -1,1065 +1 @@
1
- // src/mod.ts
2
- import * as zod from "zod";
3
-
4
- // src/schema/serialization.ts
5
- import { z } from "zod";
6
- var ByteArraySchema = z.custom(
7
- (value) => value instanceof Uint8Array
8
- );
9
- var LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
10
- var JsonSchema = z.lazy(
11
- () => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)])
12
- );
13
- var MessagePackRpcSchema = z.union([
14
- // request with method call
15
- z.tuple([z.literal(0), z.number(), z.string(), z.unknown()]),
16
- // response
17
- z.tuple([z.literal(1), z.number(), z.nullable(z.string()), z.unknown()]),
18
- // notification
19
- z.tuple([z.literal(2), z.string(), z.unknown()])
20
- ]);
21
-
22
- // src/schema/token.ts
23
- import { z as z2 } from "zod";
24
- var TokenAudienceSchema = z2.enum(["sfu", "gateway"]);
25
- var TokenSubjectSchema = z2.enum([
26
- "connect",
27
- "roomclose",
28
- "roomupdate",
29
- "roombanclient",
30
- "roomsendmessage"
31
- ]);
32
- var TokenClaimsSchema = z2.object({
33
- uid: z2.string(),
34
- cid: z2.optional(z2.string()),
35
- rid: oneOrMany(z2.string()),
36
- nsp: z2.optional(z2.string()),
37
- adr: z2.optional(z2.string()),
38
- aud: z2.optional(oneOrMany(TokenAudienceSchema)),
39
- sub: z2.optional(oneOrMany(TokenSubjectSchema)),
40
- exp: z2.optional(z2.number()),
41
- nbf: z2.optional(z2.number()),
42
- ups: z2.optional(z2.string()),
43
- tgs: z2.optional(oneOrMany(z2.string())),
44
- tsp: z2.optional(z2.number()),
45
- internal: z2.optional(
46
- z2.object({
47
- server: z2.optional(z2.string())
48
- })
49
- )
50
- });
51
- function oneOrMany(type) {
52
- return z2.union([type, z2.array(type)]);
53
- }
54
-
55
- // src/schema/room.ts
56
- import * as z6 from "zod";
57
-
58
- // src/schema/media.ts
59
- import * as z3 from "zod";
60
- var MediaIdSchema = z3.number();
61
- var MediaAudioPropertiesSchema = z3.object({
62
- kind: z3.optional(z3.literal("audio")),
63
- uid: z3.optional(z3.string()),
64
- customType: z3.optional(z3.string())
65
- });
66
- var MediaVideoPropertiesSchema = z3.object({
67
- kind: z3.optional(z3.literal("video")),
68
- codec: z3.optional(z3.string()),
69
- uid: z3.optional(z3.string()),
70
- customType: z3.optional(z3.string())
71
- });
72
- var MediaPropertiesSchema = z3.union([
73
- MediaAudioPropertiesSchema,
74
- MediaVideoPropertiesSchema
75
- ]);
76
- var MediaSchema = z3.object({
77
- id: MediaIdSchema,
78
- properties: MediaPropertiesSchema,
79
- paused: z3.boolean()
80
- });
81
-
82
- // src/schema/peer.ts
83
- import * as z4 from "zod";
84
- var PeerIdSchema = z4.number();
85
- var PeerPositionSchema = z4.union([
86
- z4.tuple([z4.number(), z4.number(), z4.number()]),
87
- z4.tuple([z4.number(), z4.number()])
88
- ]);
89
- var PeerSchema = z4.object({
90
- id: PeerIdSchema,
91
- user_id: z4.string(),
92
- user_data: ByteArraySchema,
93
- medias: z4.array(MediaSchema)
94
- });
95
- var PeerUpdateSchema = z4.discriminatedUnion("kind", [
96
- z4.object({
97
- kind: z4.literal("UserDataChanged"),
98
- peer_id: PeerIdSchema,
99
- user_data: ByteArraySchema
100
- }),
101
- z4.object({
102
- kind: z4.literal("MediaStarted"),
103
- peer_id: PeerIdSchema,
104
- media: MediaSchema
105
- }),
106
- z4.object({
107
- kind: z4.literal("MediaStopped"),
108
- peer_id: PeerIdSchema,
109
- media_id: MediaIdSchema
110
- })
111
- ]);
112
-
113
- // src/schema/channels.ts
114
- import * as z5 from "zod";
115
- var ChannelSet = class _ChannelSet {
116
- constructor(value = BigInt(0)) {
117
- this.value = value;
118
- }
119
- from(...channels) {
120
- const value = channels.reduce(
121
- (value2, channel) => value2 | channel_mask(channel),
122
- BigInt(0)
123
- );
124
- return new _ChannelSet(value);
125
- }
126
- contains(channel) {
127
- return (this.value & channel_mask(channel)) !== BigInt(0);
128
- }
129
- insert(channel) {
130
- this.value |= channel_mask(channel);
131
- }
132
- remove(channel) {
133
- this.value &= ~channel_mask(channel);
134
- }
135
- [Symbol.iterator]() {
136
- let channel = -1;
137
- const self = new _ChannelSet(this.value);
138
- return {
139
- next() {
140
- while (channel < 63) {
141
- channel += 1;
142
- if (self.contains(channel)) {
143
- return { value: channel, done: false };
144
- }
145
- }
146
- return { value: void 0, done: true };
147
- }
148
- };
149
- }
150
- };
151
- var ChannelSetSchema = z5.bigint().transform((number5) => new ChannelSet(number5));
152
- function channel_mask(channel) {
153
- return BigInt(1) << BigInt(channel);
154
- }
155
-
156
- // src/schema/room.ts
157
- var RoomV1;
158
- ((RoomV12) => {
159
- RoomV12.RoomIdSchema = z6.string();
160
- RoomV12.RoomSchema = z6.object({
161
- id: RoomV12.RoomIdSchema,
162
- customer: z6.string(),
163
- user_data: ByteArraySchema,
164
- peers: z6.array(PeerSchema)
165
- });
166
- RoomV12.RoomUpdateSchema = z6.discriminatedUnion("kind", [
167
- z6.object({
168
- kind: z6.literal("Joined"),
169
- room: RoomV12.RoomSchema,
170
- media_ids: z6.array(MediaIdSchema),
171
- own_peer_id: PeerIdSchema
172
- }),
173
- z6.object({
174
- kind: z6.literal("Left"),
175
- reason: z6.enum(["RoomClosing", "ServerClosing", "PeerKicked"])
176
- }),
177
- z6.object({
178
- kind: z6.literal("UserDataChanged"),
179
- user_data: z6.optional(ByteArraySchema)
180
- }),
181
- z6.object({
182
- kind: z6.literal("PeerJoined"),
183
- peer: PeerSchema
184
- }),
185
- z6.object({
186
- kind: z6.literal("PeerLeft"),
187
- peer_id: PeerIdSchema
188
- })
189
- ]);
190
- RoomV12.RoomUpdatesSchema = z6.object({
191
- updates: z6.array(RoomV12.RoomUpdateSchema)
192
- });
193
- RoomV12.RoomStatusSchema = z6.enum(["Joining", "Joined", "Closed"]);
194
- RoomV12.RoomStatusChangedSchema = z6.object({
195
- status: RoomV12.RoomStatusSchema,
196
- message: z6.optional(z6.string())
197
- });
198
- })(RoomV1 || (RoomV1 = {}));
199
- var RoomV2;
200
- ((RoomV22) => {
201
- RoomV22.ParametersSchema = z6.record(JsonSchema);
202
- RoomV22.PeerProperties = z6.object({
203
- user_data: ByteArraySchema.optional(),
204
- tags: z6.array(z6.string()).optional(),
205
- audio_parameters: RoomV22.ParametersSchema.optional(),
206
- video_parameters: RoomV22.ParametersSchema.optional()
207
- });
208
- RoomV22.PingSchema = z6.object({
209
- Ping: z6.object({ id: z6.number() })
210
- });
211
- RoomV22.ChangeSelfSchema = z6.object({
212
- ChangeSelf: RoomV22.PeerProperties.omit({ tags: true })
213
- });
214
- RoomV22.SetAudioMaskSchema = z6.object({
215
- SetAudioMask: z6.object({
216
- peer_id: z6.number(),
217
- mask: ChannelSetSchema
218
- })
219
- });
220
- RoomV22.SendMessageSchema = z6.object({
221
- SendMessage: z6.object({
222
- peer_ids: z6.number().array().default([]),
223
- message: ByteArraySchema
224
- })
225
- });
226
- RoomV22.CallSchema = RoomV22.PingSchema.or(RoomV22.ChangeSelfSchema).or(RoomV22.SetAudioMaskSchema).or(RoomV22.SendMessageSchema);
227
- RoomV22.PongSchema = z6.object({
228
- Pong: z6.object({ id: z6.number() })
229
- });
230
- RoomV22.JoinedSchema = z6.object({
231
- Joined: z6.object({
232
- own_peer_id: z6.number(),
233
- room_id: z6.string(),
234
- customer: z6.string()
235
- })
236
- });
237
- RoomV22.LeftSchema = z6.object({
238
- Left: z6.object({
239
- reason: z6.enum(["room_closing", "server_closing", "peer_kicked"])
240
- })
241
- });
242
- RoomV22.PeerJoinedSchema = z6.object({
243
- PeerJoined: RoomV22.PeerProperties.extend({
244
- peer_id: z6.number(),
245
- user_id: z6.string()
246
- })
247
- });
248
- RoomV22.PeerLeftSchema = z6.object({
249
- PeerLeft: z6.object({
250
- peer_id: z6.number()
251
- })
252
- });
253
- RoomV22.PeerChangedSchema = z6.object({
254
- PeerChanged: RoomV22.PeerProperties.extend({
255
- peer_id: z6.number()
256
- })
257
- });
258
- RoomV22.NewReconnectTokenSchema = z6.object({
259
- NewReconnectToken: z6.object({
260
- token: z6.string()
261
- })
262
- });
263
- RoomV22.MessageReceivedSchema = z6.object({
264
- MessageReceived: z6.object({
265
- sender_peer_id: z6.number(),
266
- message: ByteArraySchema
267
- })
268
- });
269
- RoomV22.ErrorSchema = z6.object({
270
- Error: z6.object({
271
- message: ByteArraySchema
272
- })
273
- });
274
- RoomV22.EventSchema = RoomV22.PongSchema.or(RoomV22.JoinedSchema).or(RoomV22.LeftSchema).or(RoomV22.PeerJoinedSchema).or(RoomV22.PeerLeftSchema).or(RoomV22.PeerChangedSchema).or(RoomV22.NewReconnectTokenSchema).or(RoomV22.MessageReceivedSchema).or(RoomV22.ErrorSchema);
275
- })(RoomV2 || (RoomV2 = {}));
276
-
277
- // src/schema/message.ts
278
- import { z as z7 } from "zod";
279
- var MessageReceivedSchema = z7.object({
280
- sender_peer_id: PeerIdSchema,
281
- message: ByteArraySchema
282
- });
283
-
284
- // src/schema/webrtc.ts
285
- import * as z8 from "zod";
286
- var WebRtcUpdateSchema = z8.discriminatedUnion("kind", [
287
- z8.object({
288
- kind: z8.literal("Sdp"),
289
- type: z8.enum(["Answer", "Offer"]),
290
- sdp: z8.string(),
291
- media_map: z8.array(z8.tuple([MediaIdSchema, z8.string()]))
292
- }),
293
- z8.object({
294
- kind: z8.literal("Trickle"),
295
- candidate: z8.string(),
296
- spd_mid: z8.optional(z8.string()),
297
- spd_mline_index: z8.optional(z8.number()),
298
- username_fragment: z8.optional(z8.union([z8.string(), z8.null()]))
299
- }),
300
- z8.object({
301
- kind: z8.literal("TrickleFinished")
302
- })
303
- ]);
304
-
305
- // src/rpc/commands.ts
306
- import { z as z9 } from "zod";
307
- var MainCommandsRpc = {
308
- Hello: {
309
- request: z9.object({
310
- stream: z9.literal("main")
311
- }),
312
- response: z9.null()
313
- },
314
- JoinRoom: {
315
- request: z9.object({
316
- token: z9.string(),
317
- room_id: RoomV1.RoomIdSchema,
318
- user_data: ByteArraySchema,
319
- position: PeerPositionSchema
320
- }),
321
- response: z9.object({
322
- peer_id: PeerIdSchema,
323
- stream_id: z9.optional(z9.number()),
324
- token: z9.optional(z9.string())
325
- })
326
- },
327
- WebRtcUpdate: {
328
- request: WebRtcUpdateSchema,
329
- response: z9.null()
330
- },
331
- RequestReconnectToken: {
332
- request: z9.object({ peer_id: z9.optional(PeerIdSchema) }),
333
- response: z9.string()
334
- },
335
- Ping: {
336
- request: z9.object({}),
337
- response: z9.null()
338
- }
339
- };
340
- var RoomCommandsRpc = {
341
- Hello: {
342
- request: z9.object({
343
- stream: z9.literal("room"),
344
- token: z9.string(),
345
- room_id: z9.string(),
346
- user_data: ByteArraySchema,
347
- position: PeerPositionSchema
348
- }),
349
- response: z9.null()
350
- },
351
- UpdatePeer: {
352
- request: z9.object({ user_data: ByteArraySchema }),
353
- response: z9.null()
354
- },
355
- StartMedia: {
356
- request: z9.object({
357
- media_id: MediaIdSchema,
358
- properties: MediaPropertiesSchema
359
- }),
360
- response: z9.null()
361
- },
362
- StopMedia: {
363
- request: z9.object({
364
- media_id: MediaIdSchema
365
- }),
366
- response: z9.null()
367
- },
368
- PauseMedia: {
369
- request: z9.object({
370
- media_id: MediaIdSchema
371
- }),
372
- response: z9.null()
373
- },
374
- ResumeMedia: {
375
- request: z9.object({
376
- media_id: MediaIdSchema
377
- }),
378
- response: z9.null()
379
- },
380
- SetPeerPosition: {
381
- request: z9.object({
382
- position: PeerPositionSchema
383
- }),
384
- response: z9.null()
385
- },
386
- SendMessage: {
387
- request: z9.object({
388
- target_peer_ids: z9.optional(z9.array(PeerIdSchema)),
389
- message: ByteArraySchema
390
- }),
391
- response: z9.null()
392
- }
393
- };
394
-
395
- // src/rpc/notifications.ts
396
- import * as z10 from "zod";
397
- var MainNotificationSchema = z10.object({
398
- name: z10.literal("WebRtcUpdate"),
399
- properties: WebRtcUpdateSchema
400
- });
401
- var MainNotificationsRpc = {
402
- WebRtcUpdate: WebRtcUpdateSchema
403
- };
404
- var RoomNotificationSchema = z10.union([
405
- z10.object({
406
- name: z10.literal("RoomStatusChanged"),
407
- properties: RoomV1.RoomStatusChangedSchema
408
- }),
409
- z10.object({
410
- name: z10.literal("RoomUpdated"),
411
- properties: RoomV1.RoomUpdatesSchema
412
- }),
413
- z10.object({
414
- name: z10.literal("PeerUpdated"),
415
- properties: PeerUpdateSchema
416
- }),
417
- z10.object({
418
- name: z10.literal("MessageReceived"),
419
- properties: MessageReceivedSchema
420
- })
421
- ]);
422
- var RoomNotificationsRpc = {
423
- RoomStatusChanged: RoomV1.RoomStatusChangedSchema,
424
- RoomUpdated: RoomV1.RoomUpdatesSchema,
425
- PeerUpdated: PeerUpdateSchema,
426
- MessageReceived: MessageReceivedSchema
427
- };
428
-
429
- // src/utility/result.ts
430
- function assert(condition, message) {
431
- if (!condition) {
432
- fail(message);
433
- }
434
- }
435
- function fail(message) {
436
- throw new Error(message);
437
- }
438
- function success(value) {
439
- return { type: "Success", value };
440
- }
441
- function failure(reason) {
442
- return { type: "Failure", reason };
443
- }
444
- function unwrap(result) {
445
- if (result.type === "Failure") {
446
- fail(result.reason);
447
- }
448
- return result.value;
449
- }
450
- function unwrapOr(result, fallback) {
451
- return result.type === "Success" ? result.value : fallback;
452
- }
453
-
454
- // src/utility/base64.ts
455
- function fromBase64(base64) {
456
- try {
457
- const binString = atob(base64);
458
- const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
459
- const decoder = new TextDecoder("utf8");
460
- return success(decoder.decode(bytes));
461
- } catch (error2) {
462
- return failure(String(error2));
463
- }
464
- }
465
- function fromBase64Url(base64uri) {
466
- try {
467
- const binString = atob(base64uri.replace(/-/g, "+").replace(/_/g, "/"));
468
- const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
469
- const decoder = new TextDecoder("utf8");
470
- return success(decoder.decode(bytes));
471
- } catch (error2) {
472
- return failure(String(error2));
473
- }
474
- }
475
-
476
- // src/utility/bytearray.ts
477
- function toBytes(value) {
478
- try {
479
- assert(value !== void 0, "undefined cannot be converted to byte array");
480
- assert(value !== null, "null cannot be converted to byte array");
481
- const json = JSON.stringify(value);
482
- const decoder = new TextEncoder();
483
- return success(decoder.encode(json));
484
- } catch (error2) {
485
- return failure(String(error2));
486
- }
487
- }
488
- function fromBytes(bytes) {
489
- try {
490
- assert(bytes.length > 0, "empty byte array cannot be converted to value");
491
- const json = new TextDecoder().decode(bytes);
492
- const text = JSON.parse(json);
493
- return success(text);
494
- } catch (error2) {
495
- return failure(String(error2));
496
- }
497
- }
498
-
499
- // src/utility/codec.ts
500
- var validCodecs = ["VP8", "VP9", "AV1", "H264"];
501
- var VideoCodec = class {
502
- constructor(codec) {
503
- this.codec = codec;
504
- }
505
- channels = 0;
506
- clockRate = 9e4;
507
- isValid() {
508
- return validCodecs.includes(this.codec);
509
- }
510
- isSupported() {
511
- if (typeof RTCRtpReceiver === "undefined" || typeof RTCRtpReceiver.getCapabilities === "undefined") {
512
- return null;
513
- }
514
- const expectedMimeType = unwrapOr(this.getMimeType(), "").toLowerCase();
515
- const expectedFmtpLine = new Set(
516
- unwrapOr(this.getSdpFmtpLine(), "").split(";").map((arg) => arg.trim().toLowerCase())
517
- );
518
- return RTCRtpReceiver.getCapabilities("video")?.codecs?.find((c) => {
519
- const actualMimeType = c.mimeType.toLowerCase();
520
- const actualFmtpLine = new Set(
521
- (c.sdpFmtpLine ?? "").split(";").map((arg) => arg.trim().toLowerCase())
522
- );
523
- if (expectedMimeType !== actualMimeType) return false;
524
- if (expectedFmtpLine.size !== actualFmtpLine.size) return false;
525
- for (const item of expectedFmtpLine) {
526
- if (!actualFmtpLine.has(item)) return false;
527
- }
528
- return true;
529
- }) ?? null;
530
- }
531
- getPayloadType() {
532
- switch (this.codec) {
533
- case "VP8":
534
- return success(96);
535
- case "VP9":
536
- return success(98);
537
- case "AV1":
538
- return success(41);
539
- case "H264":
540
- return success(102);
541
- default:
542
- return failure("invalid video codec");
543
- }
544
- }
545
- getMimeType() {
546
- switch (this.codec) {
547
- case "VP8":
548
- return success("video/VP8");
549
- case "VP9":
550
- return success("video/VP9");
551
- case "AV1":
552
- return success("video/AV1");
553
- case "H264":
554
- return success("video/H264");
555
- default:
556
- return failure("invalid video codec");
557
- }
558
- }
559
- getSdpFmtpLine() {
560
- switch (this.codec) {
561
- case "VP8":
562
- return success("");
563
- case "VP9":
564
- return success(
565
- // using high-bit-depth variant profile
566
- "profile-id=2"
567
- );
568
- case "AV1":
569
- return success(
570
- // using baseline profile (https://aomediacodec.github.io/av1-rtp-spec/#72-sdp-parameters)
571
- "level-idx=5;profile=0;tier=0"
572
- );
573
- case "H264":
574
- return success(
575
- // using baseline profile
576
- "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
577
- );
578
- default:
579
- return failure("invalid video codec");
580
- }
581
- }
582
- };
583
-
584
- // src/utility/iterable.ts
585
- function find(entries, predicate) {
586
- for (const entry of entries) {
587
- if (predicate(entry)) return entry;
588
- }
589
- return void 0;
590
- }
591
-
592
- // src/utility/environment.ts
593
- function isAudioCapable() {
594
- return typeof AudioContext !== "undefined" && typeof Worker !== "undefined";
595
- }
596
- function isSharedArrayBufferCapable() {
597
- return typeof SharedArrayBuffer !== "undefined";
598
- }
599
- function isBlinkBrowser() {
600
- const pattern = /(apple)?webkit\/537\.36/i;
601
- return pattern.test(globalThis.navigator.userAgent);
602
- }
603
- function isElectronBrowser() {
604
- const pattern = /electron/i;
605
- return pattern.test(globalThis.navigator.userAgent);
606
- }
607
- function isFirefoxBrowser() {
608
- const pattern = /firefox|iceweasel|fxios/i;
609
- return pattern.test(globalThis.navigator.userAgent);
610
- }
611
- function isSafariBrowser() {
612
- if (isBlinkBrowser()) return false;
613
- const pattern = /safari|applewebkit/i;
614
- return pattern.test(globalThis.navigator.userAgent);
615
- }
616
-
617
- // src/utility/json.ts
618
- function toRaw(value) {
619
- return JSON.parse(JSON.stringify(value));
620
- }
621
-
622
- // src/utility/selector.ts
623
- var Selector = class _Selector {
624
- constructor(_Generators) {
625
- this._Generators = _Generators;
626
- this._Futures = _Generators.map(_Selector.addIndex);
627
- }
628
- _Futures;
629
- async next() {
630
- const [result, index] = await Promise.race(this._Futures);
631
- this._Futures[index] = _Selector.addIndex(this._Generators[index], index);
632
- return result;
633
- }
634
- static async addIndex(generator, index) {
635
- return [await generator(), index];
636
- }
637
- };
638
-
639
- // src/utility/sleep.ts
640
- function sleep(ms, value) {
641
- if (ms <= 0) {
642
- return Promise.resolve(value);
643
- }
644
- return new Promise((resolve) => setTimeout(() => resolve(value), ms));
645
- }
646
- function abortableSleep(ms, signal) {
647
- if (signal.aborted) {
648
- return Promise.resolve("aborted");
649
- }
650
- return new Promise((resolve) => {
651
- const onAbort = () => resolve("aborted");
652
- signal.addEventListener("abort", onAbort, { once: true });
653
- setTimeout(() => {
654
- signal.removeEventListener("abort", onAbort);
655
- resolve(void 0);
656
- }, ms);
657
- });
658
- }
659
- function nextTick() {
660
- return new Promise((resolve) => setTimeout(resolve, 0));
661
- }
662
-
663
- // src/utility/strand.ts
664
- var Strand = class {
665
- _Tasks = [];
666
- _Running = false;
667
- _Values;
668
- constructor(...values) {
669
- this._Values = values;
670
- }
671
- enqueue(task) {
672
- return new Promise((resolve, reject) => {
673
- const wrapped = async () => {
674
- try {
675
- const result = await task(...this._Values);
676
- resolve(result);
677
- } catch (error2) {
678
- reject(error2);
679
- }
680
- };
681
- this._Tasks.push(wrapped);
682
- if (!this._Running) {
683
- this.execute();
684
- }
685
- });
686
- }
687
- async execute() {
688
- this._Running = true;
689
- while (true) {
690
- const task = this._Tasks.shift();
691
- if (task === void 0) break;
692
- await task();
693
- }
694
- this._Running = false;
695
- }
696
- };
697
-
698
- // src/utility/url.ts
699
- function normalizeUrl(url) {
700
- let normalized = url.trim();
701
- if (url.indexOf("://") === -1) normalized = `https://${normalized}`;
702
- try {
703
- return success(new URL(normalized));
704
- } catch (error2) {
705
- return failure(String(error2));
706
- }
707
- }
708
- function extendUrl(base, path) {
709
- let pathname = base.pathname;
710
- if (pathname.endsWith("/") === false) pathname += "/";
711
- try {
712
- return success(new URL(pathname + path, base));
713
- } catch (error2) {
714
- return failure(String(error2));
715
- }
716
- }
717
-
718
- // src/utility/uuid.ts
719
- var SCHEMA = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
720
- function generateUUID() {
721
- return crypto.randomUUID();
722
- }
723
- function validateUUID(uuid) {
724
- return SCHEMA.test(uuid);
725
- }
726
-
727
- // src/utility/validation.ts
728
- function isProperty(object6, name) {
729
- return name in object6;
730
- }
731
- function isFunction(value) {
732
- return typeof value === "function";
733
- }
734
- function isNull(value) {
735
- return typeof value === "object" && value === null;
736
- }
737
- function isNumber(value) {
738
- return typeof value === "number";
739
- }
740
- function isObject(value) {
741
- return typeof value === "object";
742
- }
743
- function isString(value) {
744
- return typeof value === "string";
745
- }
746
- function isUndefined(value) {
747
- return typeof value === "undefined";
748
- }
749
- function isFailure(result) {
750
- return result.type === "Failure";
751
- }
752
- function isSuccess(result) {
753
- return result.type === "Success";
754
- }
755
-
756
- // src/utility/log.ts
757
- var LogVerbosity = /* @__PURE__ */ ((LogVerbosity2) => {
758
- LogVerbosity2[LogVerbosity2["NONE"] = 0] = "NONE";
759
- LogVerbosity2[LogVerbosity2["ERROR"] = 1] = "ERROR";
760
- LogVerbosity2[LogVerbosity2["WARN"] = 2] = "WARN";
761
- LogVerbosity2[LogVerbosity2["INFO"] = 3] = "INFO";
762
- LogVerbosity2[LogVerbosity2["DEBUG"] = 4] = "DEBUG";
763
- return LogVerbosity2;
764
- })(LogVerbosity || {});
765
- var LogLevels = Object.values(LogVerbosity).filter(
766
- (key) => !isNaN(Number(key))
767
- );
768
- var LogLevelNames = Object.keys(LogVerbosity).filter(
769
- (key) => isNaN(Number(key))
770
- );
771
- var LogSymbols = {
772
- [0 /* NONE */]: "\u26AB",
773
- [1 /* ERROR */]: "\u{1F534}",
774
- [2 /* WARN */]: "\u{1F7E1}",
775
- [3 /* INFO */]: "\u{1F535}",
776
- [4 /* DEBUG */]: "\u{1F7E3}"
777
- };
778
- var LogFunctions = {
779
- [0 /* NONE */]: console.log,
780
- [1 /* ERROR */]: console.error,
781
- [2 /* WARN */]: console.warn,
782
- [3 /* INFO */]: console.info,
783
- [4 /* DEBUG */]: console.debug
784
- };
785
- function getLevelByName(name) {
786
- const level = LogVerbosity[name];
787
- if (level === void 0) {
788
- return failure(
789
- `invalid log level name '${name}'; valid names are: ${LogLevelNames.join(", ")}`
790
- );
791
- }
792
- return success(level);
793
- }
794
- function getLevelName(level) {
795
- const name = LogVerbosity[level];
796
- if (name === void 0) {
797
- return failure(
798
- `invalid log level ${level}; valid levels are: ${LogLevels[0]}-${LogLevels[LogLevels.length - 1]}`
799
- );
800
- }
801
- return success(name);
802
- }
803
- var LOG_DEFAULT_ID = "default";
804
- var LOG_COLLECTION = /* @__PURE__ */ new Map();
805
- function getLogger(name = LOG_DEFAULT_ID) {
806
- let logger = LOG_COLLECTION.get(name);
807
- if (!logger) {
808
- logger = new Logger("WARN", name);
809
- }
810
- return logger;
811
- }
812
- function error(msg, ...args) {
813
- if (msg instanceof Function) {
814
- return getLogger(LOG_DEFAULT_ID).error(msg, ...args);
815
- }
816
- return getLogger(LOG_DEFAULT_ID).error(msg, ...args);
817
- }
818
- function warn(msg, ...args) {
819
- if (msg instanceof Function) {
820
- return getLogger(LOG_DEFAULT_ID).warn(msg, ...args);
821
- }
822
- return getLogger(LOG_DEFAULT_ID).warn(msg, ...args);
823
- }
824
- function info(msg, ...args) {
825
- if (msg instanceof Function) {
826
- return getLogger(LOG_DEFAULT_ID).info(msg, ...args);
827
- }
828
- return getLogger(LOG_DEFAULT_ID).info(msg, ...args);
829
- }
830
- function debug(msg, ...args) {
831
- if (msg instanceof Function) {
832
- return getLogger(LOG_DEFAULT_ID).debug(msg, ...args);
833
- }
834
- return getLogger(LOG_DEFAULT_ID).debug(msg, ...args);
835
- }
836
- var Logger = class {
837
- name;
838
- _Level;
839
- _Handlers;
840
- constructor(level, name, options) {
841
- this.name = name ?? LOG_DEFAULT_ID;
842
- if (isNumber(level)) {
843
- this._Level = unwrap(getLevelByName(unwrap(getLevelName(level))));
844
- } else {
845
- this._Level = unwrap(getLevelByName(level));
846
- }
847
- this._Handlers = options?.handlers || [new LogHandler(level)];
848
- LOG_COLLECTION.set(this.name, this);
849
- }
850
- get level() {
851
- return this._Level;
852
- }
853
- set level(value) {
854
- this.levelName = unwrap(getLevelName(value));
855
- }
856
- get levelName() {
857
- return unwrap(getLevelName(this._Level));
858
- }
859
- set levelName(value) {
860
- this._Level = unwrap(getLevelByName(value));
861
- this._Handlers.forEach((handler) => handler.level = this._Level);
862
- }
863
- get handlers() {
864
- return this._Handlers;
865
- }
866
- addHandler(handler) {
867
- this._Handlers.push(handler);
868
- }
869
- removeHandler(handler) {
870
- const index = this._Handlers.indexOf(handler);
871
- if (index !== -1) this._Handlers.splice(index, 1);
872
- }
873
- log(level, msg, ...args) {
874
- if (this.level < level) {
875
- return msg instanceof Function ? void 0 : msg;
876
- }
877
- let fnResult;
878
- let message;
879
- if (msg instanceof Function) {
880
- fnResult = msg();
881
- message = this.asString(fnResult);
882
- } else {
883
- message = this.asString(msg);
884
- }
885
- this._Handlers.forEach((handler) => {
886
- handler.handle({
887
- date: /* @__PURE__ */ new Date(),
888
- level,
889
- levelName: unwrap(getLevelName(level)),
890
- logger: this.name,
891
- message,
892
- args
893
- });
894
- });
895
- return msg instanceof Function ? fnResult : msg;
896
- }
897
- error(msg, ...args) {
898
- return this.log(1 /* ERROR */, msg, ...args);
899
- }
900
- warn(msg, ...args) {
901
- return this.log(2 /* WARN */, msg, ...args);
902
- }
903
- info(msg, ...args) {
904
- return this.log(3 /* INFO */, msg, ...args);
905
- }
906
- debug(msg, ...args) {
907
- return this.log(4 /* DEBUG */, msg, ...args);
908
- }
909
- asString(data, isProperty2 = false) {
910
- if (typeof data === "string") {
911
- if (isProperty2) return `"${data}"`;
912
- return data;
913
- } else if (data === null || typeof data === "number" || typeof data === "bigint" || typeof data === "boolean" || typeof data === "undefined" || typeof data === "symbol") {
914
- return String(data);
915
- } else if (data instanceof Error) {
916
- return data.stack;
917
- } else if (typeof data === "object") {
918
- return `{${Object.entries(data).map(([k, v]) => `"${k}":${this.asString(v, true)}`).join(",")}}`;
919
- }
920
- return "undefined";
921
- }
922
- };
923
- var DEFAULT_FORMATTER = ({ message }) => message;
924
- var PRETTY_FORMATTER = (record2) => {
925
- const date = `[${record2.date.toISOString()}]`;
926
- const level = `[${record2.levelName}]`;
927
- const logger = record2.logger !== LOG_DEFAULT_ID ? `[${record2.logger}] ` : "";
928
- const symbol = LogSymbols[record2.level];
929
- return `${date} ${symbol} ${level.padEnd(7, " ")} ${logger}${record2.message}`;
930
- };
931
- var LogHandler = class {
932
- _Level;
933
- _FormatterFn;
934
- constructor(level, formatter = DEFAULT_FORMATTER) {
935
- if (isNumber(level)) {
936
- this._Level = unwrap(getLevelByName(unwrap(getLevelName(level))));
937
- } else {
938
- this._Level = unwrap(getLevelByName(level));
939
- }
940
- this._FormatterFn = formatter;
941
- }
942
- get level() {
943
- return this._Level;
944
- }
945
- set level(value) {
946
- this.levelName = unwrap(getLevelName(value));
947
- }
948
- get levelName() {
949
- return unwrap(getLevelName(this._Level));
950
- }
951
- set levelName(value) {
952
- this._Level = unwrap(getLevelByName(value));
953
- }
954
- handle(record2) {
955
- if (this._Level < record2.level) return;
956
- this.log(this._FormatterFn(record2), record2);
957
- }
958
- log(formattedString, record2) {
959
- LogFunctions[record2.level](formattedString, ...record2.args);
960
- }
961
- };
962
-
963
- // src/plugin/api.ts
964
- var MinDBFS = -758.596;
965
- var Backend;
966
- ((Backend2) => {
967
- let Transport;
968
- ((Transport2) => {
969
- Transport2["H3"] = "h3";
970
- Transport2["WebRTC"] = "webrtc";
971
- })(Transport = Backend2.Transport || (Backend2.Transport = {}));
972
- let PeerCipherStatus;
973
- ((PeerCipherStatus2) => {
974
- PeerCipherStatus2[PeerCipherStatus2["InvalidPassword"] = -1] = "InvalidPassword";
975
- PeerCipherStatus2[PeerCipherStatus2["Unknown"] = 0] = "Unknown";
976
- PeerCipherStatus2[PeerCipherStatus2["Unencrypted"] = 1] = "Unencrypted";
977
- PeerCipherStatus2[PeerCipherStatus2["Encrypted"] = 2] = "Encrypted";
978
- })(PeerCipherStatus = Backend2.PeerCipherStatus || (Backend2.PeerCipherStatus = {}));
979
- })(Backend || (Backend = {}));
980
- export {
981
- Backend,
982
- ByteArraySchema,
983
- ChannelSet,
984
- ChannelSetSchema,
985
- DEFAULT_FORMATTER,
986
- JsonSchema,
987
- LogFunctions,
988
- LogHandler,
989
- LogLevelNames,
990
- LogLevels,
991
- LogSymbols,
992
- LogVerbosity,
993
- Logger,
994
- MainCommandsRpc,
995
- MainNotificationSchema,
996
- MainNotificationsRpc,
997
- MediaAudioPropertiesSchema,
998
- MediaIdSchema,
999
- MediaPropertiesSchema,
1000
- MediaSchema,
1001
- MediaVideoPropertiesSchema,
1002
- MessagePackRpcSchema,
1003
- MessageReceivedSchema,
1004
- MinDBFS,
1005
- PRETTY_FORMATTER,
1006
- PeerIdSchema,
1007
- PeerPositionSchema,
1008
- PeerSchema,
1009
- PeerUpdateSchema,
1010
- RoomCommandsRpc,
1011
- RoomNotificationSchema,
1012
- RoomNotificationsRpc,
1013
- RoomV1,
1014
- RoomV2,
1015
- Selector,
1016
- Strand,
1017
- TokenAudienceSchema,
1018
- TokenClaimsSchema,
1019
- TokenSubjectSchema,
1020
- VideoCodec,
1021
- WebRtcUpdateSchema,
1022
- abortableSleep,
1023
- assert,
1024
- debug,
1025
- error,
1026
- extendUrl,
1027
- fail,
1028
- failure,
1029
- find,
1030
- fromBase64,
1031
- fromBase64Url,
1032
- fromBytes,
1033
- generateUUID,
1034
- getLevelByName,
1035
- getLevelName,
1036
- getLogger,
1037
- info,
1038
- isAudioCapable,
1039
- isBlinkBrowser,
1040
- isElectronBrowser,
1041
- isFailure,
1042
- isFirefoxBrowser,
1043
- isFunction,
1044
- isNull,
1045
- isNumber,
1046
- isObject,
1047
- isProperty,
1048
- isSafariBrowser,
1049
- isSharedArrayBufferCapable,
1050
- isString,
1051
- isSuccess,
1052
- isUndefined,
1053
- nextTick,
1054
- normalizeUrl,
1055
- oneOrMany,
1056
- sleep,
1057
- success,
1058
- toBytes,
1059
- toRaw,
1060
- unwrap,
1061
- unwrapOr,
1062
- validateUUID,
1063
- warn,
1064
- zod
1065
- };
1
+ import*as pr from"zod";import{z as l}from"zod";var y=l.custom(t=>t instanceof Uint8Array),se=l.union([l.string(),l.number(),l.boolean(),l.null()]),C=l.lazy(()=>l.union([se,l.array(C),l.record(C)])),Le=l.union([l.tuple([l.literal(0),l.number(),l.string(),l.unknown()]),l.tuple([l.literal(1),l.number(),l.nullable(l.string()),l.unknown()]),l.tuple([l.literal(2),l.string(),l.unknown()])]);import{z as s}from"zod";var ce=s.enum(["sfu","gateway"]),pe=s.enum(["connect","roomclose","roomupdate","roombanclient","roomsendmessage"]),we=s.object({uid:s.string(),cid:s.optional(s.string()),rid:A(s.string()),nsp:s.optional(s.string()),adr:s.optional(s.string()),aud:s.optional(A(ce)),sub:s.optional(A(pe)),exp:s.optional(s.number()),nbf:s.optional(s.number()),ups:s.optional(s.string()),tgs:s.optional(A(s.string())),tsp:s.optional(s.number()),internal:s.optional(s.object({server:s.optional(s.string())}))});function A(t){return s.union([t,s.array(t)])}import*as n from"zod";import*as u from"zod";var T=u.number(),ue=u.object({kind:u.optional(u.literal("audio")),uid:u.optional(u.string()),customType:u.optional(u.string())}),de=u.object({kind:u.optional(u.literal("video")),codec:u.optional(u.string()),uid:u.optional(u.string()),customType:u.optional(u.string())}),N=u.union([ue,de]),U=u.object({id:T,properties:N,paused:u.boolean()});import*as d from"zod";var h=d.number(),j=d.union([d.tuple([d.number(),d.number(),d.number()]),d.tuple([d.number(),d.number()])]),I=d.object({id:h,user_id:d.string(),user_data:y,medias:d.array(U)}),O=d.discriminatedUnion("kind",[d.object({kind:d.literal("UserDataChanged"),peer_id:h,user_data:y}),d.object({kind:d.literal("MediaStarted"),peer_id:h,media:U}),d.object({kind:d.literal("MediaStopped"),peer_id:h,media_id:T})]);import*as $ from"zod";var E=class t{constructor(e=BigInt(0)){this.value=e}from(...e){let r=e.reduce((c,f)=>c|M(f),BigInt(0));return new t(r)}contains(e){return(this.value&M(e))!==BigInt(0)}insert(e){this.value|=M(e)}remove(e){this.value&=~M(e)}[Symbol.iterator](){let e=-1,r=new t(this.value);return{next(){for(;e<63;)if(e+=1,r.contains(e))return{value:e,done:!1};return{value:void 0,done:!0}}}}},q=$.bigint().transform(t=>new E(t));function M(t){return BigInt(1)<<BigInt(t)}var L;(g=>(g.RoomIdSchema=n.string(),g.RoomSchema=n.object({id:g.RoomIdSchema,customer:n.string(),user_data:y,peers:n.array(I)}),g.RoomUpdateSchema=n.discriminatedUnion("kind",[n.object({kind:n.literal("Joined"),room:g.RoomSchema,media_ids:n.array(T),own_peer_id:h}),n.object({kind:n.literal("Left"),reason:n.enum(["RoomClosing","ServerClosing","PeerKicked"])}),n.object({kind:n.literal("UserDataChanged"),user_data:n.optional(y)}),n.object({kind:n.literal("PeerJoined"),peer:I}),n.object({kind:n.literal("PeerLeft"),peer_id:h})]),g.RoomUpdatesSchema=n.object({updates:n.array(g.RoomUpdateSchema)}),g.RoomStatusSchema=n.enum(["Joining","Joined","Closed"]),g.RoomStatusChangedSchema=n.object({status:g.RoomStatusSchema,message:n.optional(n.string())})))(L||={});var le;(i=>(i.ParametersSchema=n.record(C),i.PeerProperties=n.object({user_data:y.optional(),tags:n.array(n.string()).optional(),audio_parameters:i.ParametersSchema.optional(),video_parameters:i.ParametersSchema.optional()}),i.PingSchema=n.object({Ping:n.object({id:n.number()})}),i.ChangeSelfSchema=n.object({ChangeSelf:i.PeerProperties.omit({tags:!0})}),i.SetAudioMaskSchema=n.object({SetAudioMask:n.object({peer_id:n.number(),mask:q})}),i.SendMessageSchema=n.object({SendMessage:n.object({peer_ids:n.number().array().default([]),message:y})}),i.CallSchema=i.PingSchema.or(i.ChangeSelfSchema).or(i.SetAudioMaskSchema).or(i.SendMessageSchema),i.PongSchema=n.object({Pong:n.object({id:n.number()})}),i.JoinedSchema=n.object({Joined:n.object({own_peer_id:n.number(),room_id:n.string(),customer:n.string()})}),i.LeftSchema=n.object({Left:n.object({reason:n.enum(["room_closing","server_closing","peer_kicked"])})}),i.PeerJoinedSchema=n.object({PeerJoined:i.PeerProperties.extend({peer_id:n.number(),user_id:n.string()})}),i.PeerLeftSchema=n.object({PeerLeft:n.object({peer_id:n.number()})}),i.PeerChangedSchema=n.object({PeerChanged:i.PeerProperties.extend({peer_id:n.number()})}),i.NewReconnectTokenSchema=n.object({NewReconnectToken:n.object({token:n.string()})}),i.MessageReceivedSchema=n.object({MessageReceived:n.object({sender_peer_id:n.number(),message:y})}),i.ErrorSchema=n.object({Error:n.object({message:y})}),i.EventSchema=i.PongSchema.or(i.JoinedSchema).or(i.LeftSchema).or(i.PeerJoinedSchema).or(i.PeerLeftSchema).or(i.PeerChangedSchema).or(i.NewReconnectTokenSchema).or(i.MessageReceivedSchema).or(i.ErrorSchema)))(le||={});import{z as me}from"zod";var D=me.object({sender_peer_id:h,message:y});import*as a from"zod";var R=a.discriminatedUnion("kind",[a.object({kind:a.literal("Sdp"),type:a.enum(["Answer","Offer"]),sdp:a.string(),media_map:a.array(a.tuple([T,a.string()]))}),a.object({kind:a.literal("Trickle"),candidate:a.string(),spd_mid:a.optional(a.string()),spd_mline_index:a.optional(a.number()),username_fragment:a.optional(a.union([a.string(),a.null()]))}),a.object({kind:a.literal("TrickleFinished")})]);import{z as o}from"zod";var Ye={Hello:{request:o.object({stream:o.literal("main")}),response:o.null()},JoinRoom:{request:o.object({token:o.string(),room_id:L.RoomIdSchema,user_data:y,position:j}),response:o.object({peer_id:h,stream_id:o.optional(o.number()),token:o.optional(o.string())})},WebRtcUpdate:{request:R,response:o.null()},RequestReconnectToken:{request:o.object({peer_id:o.optional(h)}),response:o.string()},Ping:{request:o.object({}),response:o.null()}},Qe={Hello:{request:o.object({stream:o.literal("room"),token:o.string(),room_id:o.string(),user_data:y,position:j}),response:o.null()},UpdatePeer:{request:o.object({user_data:y}),response:o.null()},StartMedia:{request:o.object({media_id:T,properties:N}),response:o.null()},StopMedia:{request:o.object({media_id:T}),response:o.null()},PauseMedia:{request:o.object({media_id:T}),response:o.null()},ResumeMedia:{request:o.object({media_id:T}),response:o.null()},SetPeerPosition:{request:o.object({position:j}),response:o.null()},SendMessage:{request:o.object({target_peer_ids:o.optional(o.array(h)),message:y}),response:o.null()}};import*as b from"zod";var ot=b.object({name:b.literal("WebRtcUpdate"),properties:R}),it={WebRtcUpdate:R},at=b.union([b.object({name:b.literal("RoomStatusChanged"),properties:L.RoomStatusChangedSchema}),b.object({name:b.literal("RoomUpdated"),properties:L.RoomUpdatesSchema}),b.object({name:b.literal("PeerUpdated"),properties:O}),b.object({name:b.literal("MessageReceived"),properties:D})]),st={RoomStatusChanged:L.RoomStatusChangedSchema,RoomUpdated:L.RoomUpdatesSchema,PeerUpdated:O,MessageReceived:D};function F(t,e){t||W(e)}function W(t){throw new Error(t)}function m(t){return{type:"Success",value:t}}function x(t){return{type:"Failure",reason:t}}function v(t){return t.type==="Failure"&&W(t.reason),t.value}function B(t,e){return t.type==="Success"?t.value:e}function dt(t){try{let e=atob(t),r=Uint8Array.from(e,f=>f.codePointAt(0)),c=new TextDecoder("utf8");return m(c.decode(r))}catch(e){return x(String(e))}}function lt(t){try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=Uint8Array.from(e,f=>f.codePointAt(0)),c=new TextDecoder("utf8");return m(c.decode(r))}catch(e){return x(String(e))}}function gt(t){try{F(t!==void 0,"undefined cannot be converted to byte array"),F(t!==null,"null cannot be converted to byte array");let e=JSON.stringify(t),r=new TextEncoder;return m(r.encode(e))}catch(e){return x(String(e))}}function yt(t){try{F(t.length>0,"empty byte array cannot be converted to value");let e=new TextDecoder().decode(t),r=JSON.parse(e);return m(r)}catch(e){return x(String(e))}}var fe=["VP8","VP9","AV1","H264"],Z=class{constructor(e){this.codec=e}channels=0;clockRate=9e4;isValid(){return fe.includes(this.codec)}isSupported(){if(typeof RTCRtpReceiver>"u"||typeof RTCRtpReceiver.getCapabilities>"u")return null;let e=B(this.getMimeType(),"").toLowerCase(),r=new Set(B(this.getSdpFmtpLine(),"").split(";").map(c=>c.trim().toLowerCase()));return RTCRtpReceiver.getCapabilities("video")?.codecs?.find(c=>{let f=c.mimeType.toLowerCase(),p=new Set((c.sdpFmtpLine??"").split(";").map(g=>g.trim().toLowerCase()));if(e!==f||r.size!==p.size)return!1;for(let g of r)if(!p.has(g))return!1;return!0})??null}getPayloadType(){switch(this.codec){case"VP8":return m(96);case"VP9":return m(98);case"AV1":return m(41);case"H264":return m(102);default:return x("invalid video codec")}}getMimeType(){switch(this.codec){case"VP8":return m("video/VP8");case"VP9":return m("video/VP9");case"AV1":return m("video/AV1");case"H264":return m("video/H264");default:return x("invalid video codec")}}getSdpFmtpLine(){switch(this.codec){case"VP8":return m("");case"VP9":return m("profile-id=2");case"AV1":return m("level-idx=5;profile=0;tier=0");case"H264":return m("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f");default:return x("invalid video codec")}}};function ht(t,e){for(let r of t)if(e(r))return r}function St(){return typeof AudioContext<"u"&&typeof Worker<"u"}function zt(){return typeof SharedArrayBuffer<"u"}function ge(){return/(apple)?webkit\/537\.36/i.test(globalThis.navigator.userAgent)}function Lt(){return/electron/i.test(globalThis.navigator.userAgent)}function kt(){return/firefox|iceweasel|fxios/i.test(globalThis.navigator.userAgent)}function Pt(){return ge()?!1:/safari|applewebkit/i.test(globalThis.navigator.userAgent)}function Rt(t){return JSON.parse(JSON.stringify(t))}var K=class t{constructor(e){this._Generators=e;this._Futures=e.map(t.addIndex)}_Futures;async next(){let[e,r]=await Promise.race(this._Futures);return this._Futures[r]=t.addIndex(this._Generators[r],r),e}static async addIndex(e,r){return[await e(),r]}};function At(t,e){return t<=0?Promise.resolve(e):new Promise(r=>setTimeout(()=>r(e),t))}function jt(t,e){return e.aborted?Promise.resolve("aborted"):new Promise(r=>{let c=()=>r("aborted");e.addEventListener("abort",c,{once:!0}),setTimeout(()=>{e.removeEventListener("abort",c),r(void 0)},t)})}function Mt(){return new Promise(t=>setTimeout(t,0))}var Y=class{_Tasks=[];_Running=!1;_Values;constructor(...e){this._Values=e}enqueue(e){return new Promise((r,c)=>{let f=async()=>{try{let p=await e(...this._Values);r(p)}catch(p){c(p)}};this._Tasks.push(f),this._Running||this.execute()})}async execute(){for(this._Running=!0;;){let e=this._Tasks.shift();if(e===void 0)break;await e()}this._Running=!1}};function It(t){let e=t.trim();t.indexOf("://")===-1&&(e=`https://${e}`);try{return m(new URL(e))}catch(r){return x(String(r))}}function Ot(t,e){let r=t.pathname;r.endsWith("/")===!1&&(r+="/");try{return m(new URL(r+e,t))}catch(c){return x(String(c))}}var ye=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Dt(){return crypto.randomUUID()}function Bt(t){return ye.test(t)}function Jt(t,e){return e in t}function Ht(t){return typeof t=="function"}function Gt(t){return typeof t=="object"&&t===null}function V(t){return typeof t=="number"}function $t(t){return typeof t=="object"}function qt(t){return typeof t=="string"}function Wt(t){return typeof t>"u"}function Zt(t){return t.type==="Failure"}function Kt(t){return t.type==="Success"}var _=(p=>(p[p.NONE=0]="NONE",p[p.ERROR=1]="ERROR",p[p.WARN=2]="WARN",p[p.INFO=3]="INFO",p[p.DEBUG=4]="DEBUG",p))(_||{}),J=Object.values(_).filter(t=>!isNaN(Number(t))),xe=Object.keys(_).filter(t=>isNaN(Number(t))),be={0:"\u26AB",1:"\u{1F534}",2:"\u{1F7E1}",3:"\u{1F535}",4:"\u{1F7E3}"},ve={0:console.log,1:console.error,2:console.warn,3:console.info,4:console.debug};function w(t){let e=_[t];return e===void 0?x(`invalid log level name '${t}'; valid names are: ${xe.join(", ")}`):m(e)}function P(t){let e=_[t];return e===void 0?x(`invalid log level ${t}; valid levels are: ${J[0]}-${J[J.length-1]}`):m(e)}var S="default",Q=new Map;function k(t=S){let e=Q.get(t);return e||(e=new H("WARN",t)),e}function er(t,...e){return t instanceof Function?k(S).error(t,...e):k(S).error(t,...e)}function tr(t,...e){return t instanceof Function?k(S).warn(t,...e):k(S).warn(t,...e)}function rr(t,...e){return t instanceof Function?k(S).info(t,...e):k(S).info(t,...e)}function nr(t,...e){return t instanceof Function?k(S).debug(t,...e):k(S).debug(t,...e)}var H=class{name;_Level;_Handlers;constructor(e,r,c){this.name=r??S,V(e)?this._Level=v(w(v(P(e)))):this._Level=v(w(e)),this._Handlers=c?.handlers||[new G(e)],Q.set(this.name,this)}get level(){return this._Level}set level(e){this.levelName=v(P(e))}get levelName(){return v(P(this._Level))}set levelName(e){this._Level=v(w(e)),this._Handlers.forEach(r=>r.level=this._Level)}get handlers(){return this._Handlers}addHandler(e){this._Handlers.push(e)}removeHandler(e){let r=this._Handlers.indexOf(e);r!==-1&&this._Handlers.splice(r,1)}log(e,r,...c){if(this.level<e)return r instanceof Function?void 0:r;let f,p;return r instanceof Function?(f=r(),p=this.asString(f)):p=this.asString(r),this._Handlers.forEach(g=>{g.handle({date:new Date,level:e,levelName:v(P(e)),logger:this.name,message:p,args:c})}),r instanceof Function?f:r}error(e,...r){return this.log(1,e,...r)}warn(e,...r){return this.log(2,e,...r)}info(e,...r){return this.log(3,e,...r)}debug(e,...r){return this.log(4,e,...r)}asString(e,r=!1){return typeof e=="string"?r?`"${e}"`:e:e===null||typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"||typeof e>"u"||typeof e=="symbol"?String(e):e instanceof Error?e.stack:typeof e=="object"?`{${Object.entries(e).map(([c,f])=>`"${c}":${this.asString(f,!0)}`).join(",")}}`:"undefined"}},he=({message:t})=>t,or=t=>{let e=`[${t.date.toISOString()}]`,r=`[${t.levelName}]`,c=t.logger!==S?`[${t.logger}] `:"",f=be[t.level];return`${e} ${f} ${r.padEnd(7," ")} ${c}${t.message}`},G=class{_Level;_FormatterFn;constructor(e,r=he){V(e)?this._Level=v(w(v(P(e)))):this._Level=v(w(e)),this._FormatterFn=r}get level(){return this._Level}set level(e){this.levelName=v(P(e))}get levelName(){return v(P(this._Level))}set levelName(e){this._Level=v(w(e))}handle(e){this._Level<e.level||this.log(this._FormatterFn(e),e)}log(e,r){ve[r.level](e,...r.args)}};var ar=-758.596,Te;(r=>{let t;(p=>(p.H3="h3",p.WebRTC="webrtc"))(t=r.Transport||={});let e;(z=>(z[z.InvalidPassword=-1]="InvalidPassword",z[z.Unknown=0]="Unknown",z[z.Unencrypted=1]="Unencrypted",z[z.Encrypted=2]="Encrypted"))(e=r.PeerCipherStatus||={})})(Te||={});export{Te as Backend,y as ByteArraySchema,E as ChannelSet,q as ChannelSetSchema,he as DEFAULT_FORMATTER,C as JsonSchema,ve as LogFunctions,G as LogHandler,xe as LogLevelNames,J as LogLevels,be as LogSymbols,_ as LogVerbosity,H as Logger,Ye as MainCommandsRpc,ot as MainNotificationSchema,it as MainNotificationsRpc,ue as MediaAudioPropertiesSchema,T as MediaIdSchema,N as MediaPropertiesSchema,U as MediaSchema,de as MediaVideoPropertiesSchema,Le as MessagePackRpcSchema,D as MessageReceivedSchema,ar as MinDBFS,or as PRETTY_FORMATTER,h as PeerIdSchema,j as PeerPositionSchema,I as PeerSchema,O as PeerUpdateSchema,Qe as RoomCommandsRpc,at as RoomNotificationSchema,st as RoomNotificationsRpc,L as RoomV1,le as RoomV2,K as Selector,Y as Strand,ce as TokenAudienceSchema,we as TokenClaimsSchema,pe as TokenSubjectSchema,Z as VideoCodec,R as WebRtcUpdateSchema,jt as abortableSleep,F as assert,nr as debug,er as error,Ot as extendUrl,W as fail,x as failure,ht as find,dt as fromBase64,lt as fromBase64Url,yt as fromBytes,Dt as generateUUID,w as getLevelByName,P as getLevelName,k as getLogger,rr as info,St as isAudioCapable,ge as isBlinkBrowser,Lt as isElectronBrowser,Zt as isFailure,kt as isFirefoxBrowser,Ht as isFunction,Gt as isNull,V as isNumber,$t as isObject,Jt as isProperty,Pt as isSafariBrowser,zt as isSharedArrayBufferCapable,qt as isString,Kt as isSuccess,Wt as isUndefined,Mt as nextTick,It as normalizeUrl,A as oneOrMany,At as sleep,m as success,gt as toBytes,Rt as toRaw,v as unwrap,B as unwrapOr,Bt as validateUUID,tr as warn,pr as zod};