@huddle01/web-core
Advanced tools
Comparing version 1.0.0-alpha.14 to 1.0.0-alpha.15
@@ -14,3 +14,3 @@ type Events = Record<string, unknown[]>; | ||
} | ||
export { EnhancedEventEmitter }; | ||
//# sourceMappingURL=EnhancedEventEmitter.d.ts.map |
@@ -1,455 +0,8 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
import { | ||
EnhancedEventEmitter | ||
} from "../chunk-NZZLDVRO.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
EnhancedEventEmitter | ||
}; | ||
//# sourceMappingURL=EnhancedEventEmitter.js.map | ||
//# sourceMappingURL=EnhancedEventEmitter.js.map |
@@ -1,4 +0,4 @@ | ||
export type TEnhancedMapKeyOptions = string | number; | ||
export declare const defaultCompareFn: (a: TEnhancedMapKeyOptions, b: TEnhancedMapKeyOptions) => boolean; | ||
export declare class EnhancedMap<T> { | ||
type TEnhancedMapKeyOptions = string | number; | ||
declare const defaultCompareFn: (a: TEnhancedMapKeyOptions, b: TEnhancedMapKeyOptions) => boolean; | ||
declare class EnhancedMap<T> { | ||
private map; | ||
@@ -16,2 +16,3 @@ private compareFn; | ||
} | ||
//# sourceMappingURL=EnhancedMap.d.ts.map | ||
export { EnhancedMap, TEnhancedMapKeyOptions, defaultCompareFn }; |
@@ -1,46 +0,6 @@ | ||
// src/common-js/EnhancedMap.ts | ||
var defaultCompareFn = (a, b) => { | ||
if (a < b) { | ||
return false; | ||
} | ||
if (a > b) { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
var EnhancedMap = class { | ||
map; | ||
compareFn; | ||
getKey = (a, b) => { | ||
const key = this.compareFn(a, b) ? `${a}_${b}` : `${b}_${a}`; | ||
return key; | ||
}; | ||
get size() { | ||
return this.map.size; | ||
} | ||
get = (a, b) => { | ||
const key = this.getKey(a, b); | ||
const value = this.map.get(key); | ||
return value; | ||
}; | ||
set = (a, b, value) => { | ||
const key = this.getKey(a, b); | ||
this.map.set(key, value); | ||
return value; | ||
}; | ||
delete = (a, b) => { | ||
const key = this.getKey(a, b); | ||
return this.map.delete(key); | ||
}; | ||
clear = () => { | ||
this.map.clear(); | ||
}; | ||
constructor(data) { | ||
this.map = /* @__PURE__ */ new Map(); | ||
if (data.compareFn) | ||
this.compareFn = data.compareFn; | ||
else | ||
this.compareFn = defaultCompareFn; | ||
} | ||
}; | ||
import { | ||
EnhancedMap, | ||
defaultCompareFn | ||
} from "../chunk-7PO7E25R.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
@@ -50,2 +10,2 @@ EnhancedMap, | ||
}; | ||
//# sourceMappingURL=EnhancedMap.js.map | ||
//# sourceMappingURL=EnhancedMap.js.map |
@@ -1,4 +0,4 @@ | ||
export type TEnhancedSetKeyOptions = string | number; | ||
export declare const defaultCompareFn: (a: TEnhancedSetKeyOptions, b: TEnhancedSetKeyOptions) => boolean; | ||
export declare class EnhancedSet { | ||
type TEnhancedSetKeyOptions = string | number; | ||
declare const defaultCompareFn: (a: TEnhancedSetKeyOptions, b: TEnhancedSetKeyOptions) => boolean; | ||
declare class EnhancedSet { | ||
private set; | ||
@@ -16,2 +16,3 @@ private compareFn; | ||
} | ||
//# sourceMappingURL=EnhancedSet.d.ts.map | ||
export { EnhancedSet, TEnhancedSetKeyOptions, defaultCompareFn }; |
@@ -0,1 +1,3 @@ | ||
import "../chunk-UXIASGQL.js"; | ||
// src/common-js/EnhancedSet.ts | ||
@@ -50,2 +52,2 @@ var defaultCompareFn = (a, b) => { | ||
}; | ||
//# sourceMappingURL=EnhancedSet.js.map | ||
//# sourceMappingURL=EnhancedSet.js.map |
@@ -42,3 +42,3 @@ declare const defaultMediaConstraints: { | ||
}; | ||
export default defaultMediaConstraints; | ||
//# sourceMappingURL=deviceConstraints.d.ts.map | ||
export { defaultMediaConstraints as default }; |
@@ -1,45 +0,9 @@ | ||
// src/constants/rtpConstants.ts | ||
var VIDEO_CONSTRAINTS = { | ||
qvga: { width: { ideal: 320 }, height: { ideal: 240 } }, | ||
vga: { width: { ideal: 640 }, height: { ideal: 480 } }, | ||
hd: { width: { ideal: 1280 }, height: { ideal: 720 } }, | ||
fHd: { width: { ideal: 1920 }, height: { ideal: 1080 } }, | ||
qHd: { width: { ideal: 4096 }, height: { ideal: 2160 } } | ||
}; | ||
// src/constants/deviceConstraints.ts | ||
var videoDefaultConstraints = { | ||
video: { | ||
...VIDEO_CONSTRAINTS.hd | ||
} | ||
}; | ||
var audioConstraints = { | ||
audio: { | ||
echoCancellation: true, | ||
noiseSuppression: true | ||
} | ||
}; | ||
var shareConstraints = { | ||
video: { | ||
displaySurface: "monitor", | ||
logicalSurface: true, | ||
cursor: true, | ||
width: { ideal: 1920, max: 1920 }, | ||
height: { ideal: 1080, max: 1080 }, | ||
frameRate: { ideal: 25, max: 30 } | ||
}, | ||
audio: { | ||
echoCancellation: true, | ||
noiseSuppression: true | ||
} | ||
}; | ||
var defaultMediaConstraints = { | ||
cam: videoDefaultConstraints, | ||
mic: audioConstraints, | ||
screen: shareConstraints | ||
}; | ||
var deviceConstraints_default = defaultMediaConstraints; | ||
import { | ||
deviceConstraints_default | ||
} from "../chunk-ECJWSCEU.js"; | ||
import "../chunk-UBA4U2PP.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
deviceConstraints_default as default | ||
}; | ||
//# sourceMappingURL=deviceConstraints.js.map | ||
//# sourceMappingURL=deviceConstraints.js.map |
@@ -1,3 +0,4 @@ | ||
import type { RtpEncodingParameters } from "mediasoup-client/lib/types"; | ||
export declare const VIDEO_CONSTRAINTS: { | ||
import { RtpEncodingParameters } from 'mediasoup-client/lib/types'; | ||
declare const VIDEO_CONSTRAINTS: { | ||
qvga: { | ||
@@ -44,3 +45,3 @@ width: { | ||
}; | ||
export declare const PC_PROPRIETARY_CONSTRAINTS: { | ||
declare const PC_PROPRIETARY_CONSTRAINTS: { | ||
optional: { | ||
@@ -50,8 +51,8 @@ googDscp: boolean; | ||
}; | ||
export declare const WEBCAM_SIMULCAST_ENCODINGS: RtpEncodingParameters[]; | ||
export declare const SCREEN_SHARING_SVC_ENCODINGS: { | ||
declare const WEBCAM_SIMULCAST_ENCODINGS: RtpEncodingParameters[]; | ||
declare const SCREEN_SHARING_SVC_ENCODINGS: { | ||
scalabilityMode: string; | ||
dtx: boolean; | ||
}[]; | ||
export declare const encodingViaMediaType: { | ||
declare const encodingViaMediaType: { | ||
video: RtpEncodingParameters[]; | ||
@@ -66,3 +67,3 @@ "screen-video": { | ||
}; | ||
export declare const codecOptionsViaKind: { | ||
declare const codecOptionsViaKind: { | ||
audio: { | ||
@@ -77,5 +78,6 @@ opusStereo: boolean; | ||
}; | ||
export declare const WEBCAM_KSVC_ENCODINGS: { | ||
declare const WEBCAM_KSVC_ENCODINGS: { | ||
scalabilityMode: string; | ||
}[]; | ||
//# sourceMappingURL=rtpConstants.d.ts.map | ||
export { PC_PROPRIETARY_CONSTRAINTS, SCREEN_SHARING_SVC_ENCODINGS, VIDEO_CONSTRAINTS, WEBCAM_KSVC_ENCODINGS, WEBCAM_SIMULCAST_ENCODINGS, codecOptionsViaKind, encodingViaMediaType }; |
@@ -1,51 +0,11 @@ | ||
// src/constants/rtpConstants.ts | ||
var VIDEO_CONSTRAINTS = { | ||
qvga: { width: { ideal: 320 }, height: { ideal: 240 } }, | ||
vga: { width: { ideal: 640 }, height: { ideal: 480 } }, | ||
hd: { width: { ideal: 1280 }, height: { ideal: 720 } }, | ||
fHd: { width: { ideal: 1920 }, height: { ideal: 1080 } }, | ||
qHd: { width: { ideal: 4096 }, height: { ideal: 2160 } } | ||
}; | ||
var PC_PROPRIETARY_CONSTRAINTS = { | ||
optional: [{ googDscp: true }] | ||
}; | ||
var WEBCAM_SIMULCAST_ENCODINGS = [ | ||
{ | ||
scaleResolutionDownBy: 4, | ||
maxBitrate: 3e5, | ||
// 300kbps | ||
rid: "r0", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 15 | ||
}, | ||
{ | ||
scaleResolutionDownBy: 2, | ||
maxBitrate: 6e5, | ||
// 600kbps | ||
rid: "r1", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 30 | ||
}, | ||
{ | ||
scaleResolutionDownBy: 1, | ||
maxBitrate: 9e6, | ||
// 900kbps | ||
rid: "r2", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 30 | ||
} | ||
]; | ||
var SCREEN_SHARING_SVC_ENCODINGS = [ | ||
{ scalabilityMode: "S3T3", dtx: true } | ||
]; | ||
var encodingViaMediaType = { | ||
video: WEBCAM_SIMULCAST_ENCODINGS, | ||
"screen-video": SCREEN_SHARING_SVC_ENCODINGS, | ||
audio: [{ maxBitrate: 128e3 }] | ||
}; | ||
var codecOptionsViaKind = { | ||
audio: { opusStereo: true, opusFec: true, opusDtx: true }, | ||
video: { videoGoogleStartBitrate: 1e3 } | ||
}; | ||
var WEBCAM_KSVC_ENCODINGS = [{ scalabilityMode: "S3T3_KEY" }]; | ||
import { | ||
PC_PROPRIETARY_CONSTRAINTS, | ||
SCREEN_SHARING_SVC_ENCODINGS, | ||
VIDEO_CONSTRAINTS, | ||
WEBCAM_KSVC_ENCODINGS, | ||
WEBCAM_SIMULCAST_ENCODINGS, | ||
codecOptionsViaKind, | ||
encodingViaMediaType | ||
} from "../chunk-UBA4U2PP.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
@@ -60,2 +20,2 @@ PC_PROPRIETARY_CONSTRAINTS, | ||
}; | ||
//# sourceMappingURL=rtpConstants.js.map | ||
//# sourceMappingURL=rtpConstants.js.map |
@@ -1,4 +0,7 @@ | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
import type { Consumer as mediasoupConsumer } from "mediasoup-client/lib/types"; | ||
export type ConsumerEvents = { | ||
import * as mediasoup_client_lib_types from 'mediasoup-client/lib/types'; | ||
import { Consumer as Consumer$1 } from 'mediasoup-client/lib/types'; | ||
import * as mediasoup_client_lib_RtpParameters from 'mediasoup-client/lib/RtpParameters'; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
type ConsumerEvents = { | ||
closed: []; | ||
@@ -53,3 +56,3 @@ }; | ||
*/ | ||
setMediaSoupConsumer(consumer: mediasoupConsumer): void; | ||
setMediaSoupConsumer(consumer: Consumer$1): void; | ||
/** | ||
@@ -81,3 +84,3 @@ * Getter for the mediasoupConsumer id, which is also the id of the Consumer for the RemotePeer. it is only available when the Consumer is consuming a media. | ||
*/ | ||
get kind(): import("mediasoup-client/lib/RtpParameters").MediaKind | undefined; | ||
get kind(): mediasoup_client_lib_RtpParameters.MediaKind | undefined; | ||
/** | ||
@@ -92,3 +95,3 @@ * If the Consumer is paused, it is only available when the Consumer is consuming a media. | ||
*/ | ||
get appData(): import("mediasoup-client/lib/types").AppData | undefined; | ||
get appData(): mediasoup_client_lib_types.AppData | undefined; | ||
/** | ||
@@ -127,3 +130,3 @@ * State of a Consumer is defined by the following: | ||
} | ||
export default Consumer; | ||
//# sourceMappingURL=Consumer.d.ts.map | ||
export { ConsumerEvents, Consumer as default }; |
@@ -1,766 +0,10 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger2, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger2; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger2 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger2, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/Consumer.ts | ||
var logger = mainLogger.createSubLogger("Consumer"); | ||
var Consumer = class _Consumer extends EnhancedEventEmitter { | ||
/** | ||
* ProducerId of the Consumer, this is the id of the Media Entity which is responsible for producing the media in the room. | ||
*/ | ||
producerId; | ||
/** | ||
* PeerId of the Producer, this is the peerId of the Peer which is responsible for producing the media in the room. | ||
*/ | ||
producerPeerId; | ||
/** | ||
* Label of the Consumer, this is the label of the Media Entity which is responsible for producing the media in the room. | ||
*/ | ||
label; | ||
/** | ||
* Flag to check if the Consumer is consuming a media, if `true` then the Consumer is consuming a media. | ||
* | ||
* @default false | ||
*/ | ||
__consuming = false; | ||
/** | ||
* Flag to check if the Consumer is consuming a media, if `true` then the Consumer is consuming a media. | ||
* | ||
* @default false | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get consuming() { | ||
return this.__consuming; | ||
} | ||
/** | ||
* mediasoupConsumer instance, this is the instance of the mediasoupConsumer which is responsible for consuming the media in the room. | ||
* @remarks This is a private property and should not be accessed directly. | ||
* | ||
* Every Consumer is created without a mediasoupConsumer, when the peer starts to consume the media, the mediasoupConsumer is set. | ||
*/ | ||
#mediasoupConsumer = null; | ||
/** | ||
* Getter for the id for the mediaSoupConsumer, which is also the id of the Consumer for the RemotePeer. | ||
*/ | ||
get id() { | ||
return this.#mediasoupConsumer?.id; | ||
} | ||
/** | ||
* | ||
* @param consumer Sets the mediasoupConsumer for the Consumer | ||
*/ | ||
setMediaSoupConsumer(consumer) { | ||
if (this.consuming) { | ||
throw new Error("Consumer is already consuming"); | ||
} | ||
if (this.#mediasoupConsumer) { | ||
throw new Error("Consumer already has a mediasoupConsumer"); | ||
} | ||
this.#mediasoupConsumer = consumer; | ||
this.__consuming = true; | ||
} | ||
/** | ||
* Getter for the mediasoupConsumer id, which is also the id of the Consumer for the RemotePeer. it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get consumerId() { | ||
return this.#mediasoupConsumer?.id; | ||
} | ||
/** | ||
* Get the Track of the Consumer, it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get track() { | ||
return this.#mediasoupConsumer?.track; | ||
} | ||
/** | ||
* Get the kind of the Consumer, it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get kind() { | ||
return this.#mediasoupConsumer?.kind; | ||
} | ||
/** | ||
* If the Consumer is paused, it is only available when the Consumer is consuming a media. | ||
* | ||
* if paused the user is not consuming any media for the given producerId. | ||
*/ | ||
get paused() { | ||
return this.#mediasoupConsumer?.paused; | ||
} | ||
/** | ||
* AppData of the Consumer, it is only available when the Consumer is consuming a media. | ||
*/ | ||
get appData() { | ||
return this.#mediasoupConsumer?.appData; | ||
} | ||
/** | ||
* State of a Consumer is defined by the following: | ||
* - `playable` - The Consumer is ready to play the media. | ||
* - `unavailable` - The Consumer is not available to play the media. This can happen when the Consumer is closed or paused. | ||
* - `paused` - The Consumer is paused and is not playing the media. | ||
* - `available` - The Consumer is available to play the media. Peer can consume the media by using `localPeer.consume({ peerId, label: "video", appData: {} });` after which the state will change to `playable`. | ||
*/ | ||
get state() { | ||
if (this?.consuming) | ||
return "playable"; | ||
if (this?.paused) | ||
return "paused"; | ||
return "available"; | ||
} | ||
/** | ||
* Get the stats of the Consumer, it is only available when the Consumer is consuming a media. | ||
* It generates the stats for the Consumer using the `getStats` method of the mediasoupConsumer. | ||
* @returns - RTCStatsReport | null | ||
*/ | ||
getStats = async () => { | ||
const stats = await this.#mediasoupConsumer?.getStats(); | ||
return stats; | ||
}; | ||
/** | ||
* Resume the consumer, if the state of the consumer is `paused`. | ||
*/ | ||
resume = () => { | ||
this.#mediasoupConsumer?.resume(); | ||
}; | ||
/** | ||
* Removes all the eventListeners attached to the Consumer. | ||
*/ | ||
removeListeners = () => { | ||
this.removeAllListeners(); | ||
}; | ||
/** | ||
* Creates a Consumer instance. This is a static method and should be called using `Consumer.create({ producerPeerId, producerId, label })`. | ||
*/ | ||
static create = (data) => { | ||
try { | ||
const consumer = new _Consumer(data); | ||
return consumer; | ||
} catch (error) { | ||
logger.error(error); | ||
throw new Error("\u274C Error creating Consumer"); | ||
} | ||
}; | ||
close = () => { | ||
try { | ||
this.#mediasoupConsumer?.close(); | ||
this.__consuming = false; | ||
this.emit("closed"); | ||
this.removeAllListeners(); | ||
} catch (error) { | ||
logger.error("\u274C Error Closing Consumer"); | ||
logger.error({ | ||
consumerId: this.consumerId, | ||
producerId: this.producerId | ||
}); | ||
} | ||
}; | ||
constructor(data) { | ||
super(); | ||
this.producerPeerId = data.producerPeerId; | ||
this.producerId = data.producerId; | ||
this.label = data.label; | ||
} | ||
}; | ||
var Consumer_default = Consumer; | ||
import { | ||
Consumer_default | ||
} from "./chunk-N24AG534.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
Consumer_default as default | ||
}; | ||
//# sourceMappingURL=Consumer.js.map | ||
//# sourceMappingURL=Consumer.js.map |
@@ -1,4 +0,5 @@ | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
export type IStreamPermissions = "granted" | "denied" | "prompt"; | ||
export type IStreamPermissionsError = { | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
type StreamPermissions = "granted" | "denied" | "prompt"; | ||
type StreamPermissionsError = { | ||
blocked?: { | ||
@@ -12,43 +13,39 @@ byDeviceMissing?: boolean; | ||
}; | ||
export type TFetchStreamResponse = Promise<{ | ||
type FetchStreamResponse = Promise<{ | ||
deviceId: string | null; | ||
stream: MediaStream | null; | ||
track: MediaStreamTrack | null; | ||
error?: IStreamPermissionsError; | ||
error?: StreamPermissionsError; | ||
}>; | ||
export type TFetchScreenResponse = Promise<Omit<Awaited<TFetchStreamResponse>, "track" | "deviceId">>; | ||
export type TCustomMediaKind = "cam" | "mic" | "screen"; | ||
export type TCustomMediaDevice = "mic" | "cam" | "speaker"; | ||
export type IStreamAdded = { | ||
type FetchScreenResponse = Promise<Omit<Awaited<FetchStreamResponse>, "track" | "deviceId">>; | ||
type CustomMediaKind = "cam" | "mic" | "screen"; | ||
type CustomMediaDevice = "mic" | "cam" | "speaker"; | ||
type StreamAdded = { | ||
stream: MediaStream; | ||
track: MediaStreamTrack; | ||
mediaKind: TCustomMediaKind; | ||
mediaKind: CustomMediaKind; | ||
}; | ||
export type DeviceHandlerEvents = { | ||
type DeviceHandlerEvents = { | ||
"device-change": []; | ||
"stream-fetched": [ | ||
data: { | ||
mediaKind: TCustomMediaKind; | ||
stream: MediaStream; | ||
} | ||
]; | ||
"stream-fetched": [data: { | ||
mediaKind: CustomMediaKind; | ||
stream: MediaStream; | ||
}]; | ||
"stream-stopped": [data: { | ||
mediaKind: TCustomMediaKind; | ||
mediaKind: CustomMediaKind; | ||
}]; | ||
"screen-fetched": [ | ||
data: { | ||
mediaKind: TCustomMediaKind; | ||
stream: MediaStream; | ||
} | ||
]; | ||
"screen-fetched": [data: { | ||
mediaKind: CustomMediaKind; | ||
stream: MediaStream; | ||
}]; | ||
"screen-stopped": [data: { | ||
mediaKind: TCustomMediaKind; | ||
mediaKind: CustomMediaKind; | ||
}]; | ||
"permission-granted": [data: { | ||
deviceKind: TCustomMediaDevice; | ||
deviceKind: CustomMediaDevice; | ||
}]; | ||
"permission-denied": [ | ||
data: { | ||
deviceKind: TCustomMediaDevice; | ||
error: IStreamPermissionsError; | ||
deviceKind: CustomMediaDevice; | ||
error: StreamPermissionsError; | ||
} | ||
@@ -58,3 +55,3 @@ ]; | ||
data: { | ||
deviceKind: TCustomMediaDevice; | ||
deviceKind: CustomMediaDevice; | ||
deviceId: string | null; | ||
@@ -97,6 +94,6 @@ } | ||
*/ | ||
get devices(): Map<TCustomMediaDevice, [] | MediaDeviceInfo[]>; | ||
get preferredDevices(): Map<TCustomMediaDevice, string | null>; | ||
get devices(): Map<CustomMediaDevice, [] | MediaDeviceInfo[]>; | ||
get preferredDevices(): Map<CustomMediaDevice, string | null>; | ||
getStreamOfPreferredDevice(data: { | ||
kind: Exclude<TCustomMediaDevice, "speaker">; | ||
kind: Exclude<CustomMediaDevice, "speaker">; | ||
}): MediaStream | null; | ||
@@ -114,3 +111,3 @@ getStreamOfScreen(): MediaStream | null; | ||
*/ | ||
getMediaDevices: (filterByDeviceKind?: TCustomMediaDevice) => Promise<MediaDeviceInfo[]>; | ||
getMediaDevices: (filterByDeviceKind?: CustomMediaDevice) => Promise<MediaDeviceInfo[]>; | ||
/** | ||
@@ -124,3 +121,3 @@ * Get the device from the given groupId | ||
*/ | ||
getDeviceFromGroupId: (groupId: string, mediaDeviceKind: TCustomMediaDevice) => MediaDeviceInfo | null; | ||
getDeviceFromGroupId: (groupId: string, mediaDeviceKind: CustomMediaDevice) => MediaDeviceInfo | null; | ||
/** | ||
@@ -137,8 +134,8 @@ * Get the device from the given facing type of device | ||
*/ | ||
getDeviceFromFacingMode: (facing: "environment" | "user" | undefined, mediaDeviceKind: TCustomMediaDevice) => MediaDeviceInfo | null; | ||
getDeviceFromFacingMode: (facing: "environment" | "user" | undefined, mediaDeviceKind: CustomMediaDevice) => MediaDeviceInfo | null; | ||
setPreferredDevice: (data: { | ||
deviceId: string; | ||
deviceKind: TCustomMediaDevice; | ||
deviceKind: CustomMediaDevice; | ||
}) => void; | ||
fetchScreen: () => Promise<TFetchScreenResponse>; | ||
fetchScreen: () => Promise<FetchScreenResponse>; | ||
/** | ||
@@ -153,4 +150,4 @@ * Fetch the stream from the device for the given media kind, if no preferred device is found it will throw an error. | ||
fetchStream: (data: { | ||
mediaDeviceKind: Exclude<TCustomMediaDevice, "speaker">; | ||
}) => Promise<TFetchStreamResponse>; | ||
mediaDeviceKind: Exclude<CustomMediaDevice, "speaker">; | ||
}) => Promise<FetchStreamResponse>; | ||
/** | ||
@@ -183,10 +180,10 @@ * Fetch the stream from the device for the React Native Based Application | ||
* @param data `{ type: 'cam' | 'mic' | 'speaker' }` ( `IMediaDeviceType` ) | ||
* @returns { hasPermission: boolean, error?: IStreamPermissionsError } | ||
* @returns { hasPermission: boolean, error?: StreamPermissionsError } | ||
* @example await checkPermission({ type: 'cam' }) | ||
*/ | ||
checkPermission: (data: { | ||
mediaDeviceKind: TCustomMediaDevice; | ||
mediaDeviceKind: CustomMediaDevice; | ||
}) => Promise<{ | ||
hasPermission: boolean; | ||
error?: IStreamPermissionsError | undefined; | ||
error?: StreamPermissionsError | undefined; | ||
}>; | ||
@@ -196,13 +193,13 @@ /** | ||
* @param data { type: 'video' | 'audio' } | ||
* @throws error { IStreamPermissionsError } | ||
* @throws error { StreamPermissionsError } | ||
* @example await getMediaPermission({ type: 'video' }) | ||
*/ | ||
getMediaPermission: (data: { | ||
mediaDeviceKind: TCustomMediaDevice; | ||
mediaDeviceKind: CustomMediaDevice; | ||
}) => Promise<{ | ||
permission: "granted" | "denied"; | ||
error?: IStreamPermissionsError; | ||
error?: StreamPermissionsError; | ||
}>; | ||
stopStream: (data: { | ||
mediaDeviceKind: Exclude<TCustomMediaDevice, "speaker">; | ||
mediaDeviceKind: Exclude<CustomMediaDevice, "speaker">; | ||
}) => void; | ||
@@ -216,3 +213,3 @@ stopScreen: () => void; | ||
} | ||
export default DeviceHandler; | ||
//# sourceMappingURL=DeviceHandler.d.ts.map | ||
export { CustomMediaDevice, CustomMediaKind, DeviceHandlerEvents, FetchScreenResponse, FetchStreamResponse, StreamAdded, StreamPermissions, StreamPermissionsError, DeviceHandler as default }; |
@@ -1,1152 +0,12 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/constants/rtpConstants.ts | ||
var VIDEO_CONSTRAINTS = { | ||
qvga: { width: { ideal: 320 }, height: { ideal: 240 } }, | ||
vga: { width: { ideal: 640 }, height: { ideal: 480 } }, | ||
hd: { width: { ideal: 1280 }, height: { ideal: 720 } }, | ||
fHd: { width: { ideal: 1920 }, height: { ideal: 1080 } }, | ||
qHd: { width: { ideal: 4096 }, height: { ideal: 2160 } } | ||
}; | ||
// src/constants/deviceConstraints.ts | ||
var videoDefaultConstraints = { | ||
video: { | ||
...VIDEO_CONSTRAINTS.hd | ||
} | ||
}; | ||
var audioConstraints = { | ||
audio: { | ||
echoCancellation: true, | ||
noiseSuppression: true | ||
} | ||
}; | ||
var shareConstraints = { | ||
video: { | ||
displaySurface: "monitor", | ||
logicalSurface: true, | ||
cursor: true, | ||
width: { ideal: 1920, max: 1920 }, | ||
height: { ideal: 1080, max: 1080 }, | ||
frameRate: { ideal: 25, max: 30 } | ||
}, | ||
audio: { | ||
echoCancellation: true, | ||
noiseSuppression: true | ||
} | ||
}; | ||
var defaultMediaConstraints = { | ||
cam: videoDefaultConstraints, | ||
mic: audioConstraints, | ||
screen: shareConstraints | ||
}; | ||
var deviceConstraints_default = defaultMediaConstraints; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger2, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger2; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger2 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger2, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/DeviceHandler.ts | ||
var logger = mainLogger.createSubLogger("DeviceHandler"); | ||
var userMediaConstraints = { | ||
cam: { | ||
video: true | ||
}, | ||
mic: { | ||
audio: true | ||
}, | ||
speaker: { | ||
audio: true | ||
} | ||
}; | ||
var SystemKindToCustomMediaKind = { | ||
audioinput: "mic", | ||
audiooutput: "speaker", | ||
videoinput: "cam" | ||
}; | ||
var CustomMediaKindToSystemKind = { | ||
cam: "videoinput", | ||
mic: "audioinput", | ||
speaker: "videoinput" | ||
}; | ||
var DeviceHandler = class extends EnhancedEventEmitter { | ||
/** | ||
* Map of streams currently running which is managed by the Huddle01 SDK | ||
* It can also be extended to store multiple streams from the same device | ||
* | ||
* Having an array also stands as a safety check for multiple streams from the same device, | ||
* and closing all of them. | ||
* | ||
* @example | ||
* { | ||
* "deviceId": [MediaStream] | ||
* } | ||
*/ | ||
SCREEN_DEFAULT_DEVICE = "monitor"; | ||
__activeStreams = /* @__PURE__ */ new Map(); | ||
/** | ||
* User Selected Devices, If no device is selected, it will use the default device of the system | ||
* | ||
* is preffered device is null, it will use the default device of the system | ||
* | ||
* `NOTE: User has the ability to select a preferred device for each media kind` | ||
*/ | ||
__preferredDevices = /* @__PURE__ */ new Map([ | ||
["cam", null], | ||
["mic", null], | ||
["speaker", null] | ||
]); | ||
/** | ||
* Map the media devices currently present in the system | ||
*/ | ||
__mediaDevicesInfo = /* @__PURE__ */ new Map([ | ||
["cam", []], | ||
["mic", []], | ||
["speaker", []] | ||
]); | ||
/** | ||
* Get all the devices which are currently available in the system | ||
*/ | ||
get devices() { | ||
return this.__mediaDevicesInfo; | ||
} | ||
get preferredDevices() { | ||
return this.__preferredDevices; | ||
} | ||
getStreamOfPreferredDevice(data) { | ||
const { kind } = data; | ||
const deviceId = this.__preferredDevices.get(kind); | ||
if (!deviceId) { | ||
return null; | ||
} | ||
const stream = this.__activeStreams.get(deviceId); | ||
if (!stream) { | ||
return null; | ||
} | ||
return stream[0]; | ||
} | ||
getStreamOfScreen() { | ||
const stream = this.__activeStreams.get(this.SCREEN_DEFAULT_DEVICE); | ||
if (!stream) { | ||
return null; | ||
} | ||
return stream[0]; | ||
} | ||
/** | ||
* Get all the devices which are currently available in the system, also updates the `__mediaDevicesInfo` record | ||
* | ||
* Can also query for a specific device kind `audioinput` | `videoinput` | `audiooutput` | ||
* | ||
* @param deviceKind `cam` | `mic` | `speaker` | `undefined` | ||
* @returns - MediaDeviceInfo[] | null | ||
* | ||
* `NOTE`: Ask for MediaDevice Permission to get the right result for that device else it will return `null` | ||
*/ | ||
getMediaDevices = async (filterByDeviceKind) => { | ||
const stream = await navigator.mediaDevices.getUserMedia( | ||
userMediaConstraints[filterByDeviceKind ?? "mic"] | ||
); | ||
const devices = await navigator.mediaDevices.enumerateDevices(); | ||
stream.getTracks().forEach((track) => track.stop()); | ||
const mediaDevices = devices.filter((device) => { | ||
if (device.deviceId === "default") { | ||
return false; | ||
} | ||
if (filterByDeviceKind) { | ||
const systemDeviceKind = CustomMediaKindToSystemKind[filterByDeviceKind]; | ||
return device.kind === systemDeviceKind; | ||
} | ||
return true; | ||
}); | ||
return mediaDevices; | ||
}; | ||
/** | ||
* Get the device from the given groupId | ||
* @param groupId - groupId for the device | ||
* @param mediaDeviceKind - mediaDeviceKind for the device { 'audioinput' | 'videoinput' } | ||
* @returns - MediaDeviceInfo | null | ||
* | ||
* `NOTE`: Ask for MediaDevice Permission to get the right result for that device else it will return `null` | ||
*/ | ||
getDeviceFromGroupId = (groupId, mediaDeviceKind) => { | ||
const allDevices = this.__mediaDevicesInfo.get(mediaDeviceKind); | ||
if (allDevices) { | ||
const d = allDevices.find((device) => device.groupId === groupId); | ||
if (d) | ||
return d; | ||
} | ||
logger.info({ allDevices, m: this.__mediaDevicesInfo }); | ||
return null; | ||
}; | ||
/** | ||
* Get the device from the given facing type of device | ||
* | ||
* This function is used for only RN | ||
* | ||
* @param facing - facing of the device { 'environment' | 'user' | 'undefined' } | ||
* @param mediaDeviceKind - mediaDeviceKind for the device { 'audioinput' | 'videoinput' } | ||
* @returns - MediaDeviceInfo | null | ||
* | ||
* `NOTE`: Ask for MediaDevice Permission to get the right result for that device else it will return `null` | ||
*/ | ||
getDeviceFromFacingMode = (facing, mediaDeviceKind) => { | ||
const allDevices = this.__mediaDevicesInfo.get(mediaDeviceKind); | ||
if (allDevices) { | ||
const d = allDevices.find((device) => device.facing === facing); | ||
if (d) | ||
return d; | ||
} | ||
return null; | ||
}; | ||
setPreferredDevice = (data) => { | ||
const { deviceId, deviceKind } = data; | ||
this.__preferredDevices.set(deviceKind, deviceId); | ||
this.emit("preferred-device-change", { | ||
deviceId, | ||
deviceKind | ||
}); | ||
}; | ||
fetchScreen = async () => { | ||
const constraints = deviceConstraints_default.screen; | ||
try { | ||
const stream = await navigator.mediaDevices.getDisplayMedia(constraints); | ||
if (this.__activeStreams.has(this.SCREEN_DEFAULT_DEVICE)) { | ||
logger.warn( | ||
`Stream already exists for the given deviceId: ${this.SCREEN_DEFAULT_DEVICE}`, | ||
this.__activeStreams | ||
); | ||
stream.getTracks().forEach((track) => track.stop()); | ||
} else { | ||
this.__activeStreams.set(this.SCREEN_DEFAULT_DEVICE, [stream]); | ||
} | ||
this.emit("screen-fetched", { | ||
mediaKind: "screen", | ||
stream | ||
}); | ||
return { stream }; | ||
} catch (err) { | ||
logger.error(err); | ||
let error = { | ||
message: "Unknown Error", | ||
errorStack: err | ||
}; | ||
if (err instanceof DOMException) { | ||
error = { | ||
blocked: { | ||
byDeviceMissing: err.name === "NotFoundError", | ||
byDeviceInUse: err.name === "OverconstrainedError", | ||
byPermissions: err.name === "NotAllowedError" | ||
}, | ||
message: err.message | ||
}; | ||
} | ||
return { | ||
stream: null, | ||
error | ||
}; | ||
} | ||
}; | ||
/** | ||
* Fetch the stream from the device for the given media kind, if no preferred device is found it will throw an error. | ||
* by default the preferred device is the system default device | ||
* | ||
* `NOTE: If Preffered device is not found, it will use the system default device, if no default device is found it will throw an error` | ||
* `Set the preferred device using setPreferredDevice()` | ||
* | ||
*/ | ||
fetchStream = async (data) => { | ||
const preferredDeviceId = this.__preferredDevices.get(data.mediaDeviceKind); | ||
const { hasPermission } = await this.checkPermission({ | ||
mediaDeviceKind: data.mediaDeviceKind | ||
}); | ||
if (!hasPermission) { | ||
const perms = await this.getMediaPermission({ | ||
mediaDeviceKind: data.mediaDeviceKind | ||
}); | ||
if (perms.permission === "denied") { | ||
return { | ||
stream: null, | ||
track: null, | ||
deviceId: null, | ||
error: perms.error | ||
}; | ||
} | ||
} | ||
try { | ||
let fetchStreamFunc; | ||
if (typeof navigator === "object" && navigator.product === "ReactNative") { | ||
fetchStreamFunc = this.__fetchStreamFromDeviceForRN; | ||
} else { | ||
fetchStreamFunc = this.__fetchStreamFromDeviceForWeb; | ||
} | ||
const { stream, deviceId } = await fetchStreamFunc({ | ||
deviceId: preferredDeviceId ?? void 0, | ||
mediaKind: data.mediaDeviceKind === "mic" ? "mic" : "cam" | ||
}); | ||
const track = data.mediaDeviceKind === "mic" ? stream.getAudioTracks()[0] : stream.getVideoTracks()[0]; | ||
if (this.__activeStreams.has(deviceId)) { | ||
logger.warn( | ||
`Stream already exists for the given deviceId: ${deviceId}`, | ||
this.__activeStreams | ||
); | ||
stream.getTracks().forEach((track2) => track2.stop()); | ||
} else { | ||
logger.info( | ||
`\u{1F4F9} Adding a new Stream, mediaDeviceKind: ${data.mediaDeviceKind}, deviceId: ${deviceId}`, | ||
this.__activeStreams | ||
); | ||
if (!this.__preferredDevices.get(data.mediaDeviceKind)) { | ||
this.__preferredDevices.set(data.mediaDeviceKind, deviceId); | ||
} | ||
this.__activeStreams.set(deviceId, [stream]); | ||
} | ||
this.emit("stream-fetched", { | ||
mediaKind: data.mediaDeviceKind === "mic" ? "mic" : "cam", | ||
stream | ||
}); | ||
return { | ||
stream, | ||
track, | ||
deviceId | ||
}; | ||
} catch (err) { | ||
logger.error(err); | ||
let error = { | ||
message: "Unknown Error", | ||
errorStack: err | ||
}; | ||
if (err instanceof DOMException) { | ||
error = { | ||
blocked: { | ||
byDeviceMissing: err.name === "NotFoundError", | ||
byDeviceInUse: err.name === "OverconstrainedError", | ||
byPermissions: err.name === "NotAllowedError" | ||
}, | ||
message: err.message | ||
}; | ||
} | ||
return { | ||
stream: null, | ||
track: null, | ||
deviceId: null, | ||
error | ||
}; | ||
} | ||
}; | ||
/** | ||
* Fetch the stream from the device for the React Native Based Application | ||
* | ||
* `This stream is not managed by the Huddle01 SDK, i.e. it will not be closed by the SDK | ||
* the user has to close it manually by calling {stream.getTracks().forEach(track => track.stop())}` | ||
* | ||
* NOTE: `using stopTrackOnClose = true` while producing will stop the track when producing is stopped | ||
* | ||
* @param data - { deviceId: "front" | "back" | "audio" | string; kind: "audioinput" | "videoinput" } | ||
* @returns - { stream: MediaStream, deviceId: string } | ||
*/ | ||
__fetchStreamFromDeviceForRN = async (data) => { | ||
const constraints = deviceConstraints_default[data.mediaKind]; | ||
let facingMode; | ||
if (data.mediaKind === "cam") { | ||
facingMode = data.deviceId === "front" ? "user" : "environment"; | ||
constraints.video = Object.assign({}, constraints.video, { | ||
facingMode | ||
}); | ||
} | ||
if (data.mediaKind === "mic") { | ||
constraints.audio = Object.assign({}, constraints.audio, { | ||
deviceId: data.deviceId | ||
}); | ||
} | ||
const stream = await navigator.mediaDevices.getUserMedia(constraints); | ||
const streamDeviceId = this.getDeviceFromFacingMode( | ||
facingMode, | ||
data.mediaKind === "mic" ? "mic" : "cam" | ||
)?.deviceId; | ||
if (!streamDeviceId) { | ||
stream.getTracks().forEach((track) => track.stop()); | ||
throw new Error( | ||
"\u274C No DeviceId found for this stream, this is a bug in the SDK, please report it to the developers" | ||
); | ||
} | ||
return { | ||
stream, | ||
deviceId: streamDeviceId | ||
}; | ||
}; | ||
/** | ||
* Fetch the stream from the device for the web | ||
* | ||
* `This stream is not managed by the Huddle01 SDK, i.e. it will not be closed by the SDK | ||
* the user has to close it manually by calling {stream.getTracks().forEach(track => track.stop())}` | ||
* | ||
* NOTE: `using stopTrackOnClose = true` while producing will stop the track when producing is stopped | ||
* | ||
* @param data - { deviceId: string; kind: 'audio' | 'video' } | ||
* @returns - { stream: MediaStream, deviceId: string } | ||
*/ | ||
__fetchStreamFromDeviceForWeb = async (data) => { | ||
const constraints = deviceConstraints_default[data.mediaKind]; | ||
if (data.mediaKind === "cam" && data.deviceId) { | ||
constraints.video = Object.assign({}, constraints.video, { | ||
deviceId: data.deviceId | ||
}); | ||
} | ||
if (data.mediaKind === "mic" && data.deviceId) { | ||
constraints.audio = Object.assign({}, constraints.video, { | ||
deviceId: { | ||
exact: data.deviceId | ||
} | ||
}); | ||
} | ||
const stream = await navigator.mediaDevices.getUserMedia(constraints); | ||
let streamDeviceId = stream.getTracks()[0].getSettings().deviceId; | ||
const groupId = stream.getTracks()[0].getSettings().groupId; | ||
if (streamDeviceId === "default" && groupId) { | ||
streamDeviceId = this.getDeviceFromGroupId( | ||
groupId, | ||
data.mediaKind === "mic" ? "mic" : "cam" | ||
)?.deviceId; | ||
} | ||
if (!streamDeviceId) { | ||
stream.getTracks().forEach((track) => track.stop()); | ||
throw new Error( | ||
"\u274C No DeviceId found for this stream, this is a bug in the browser, please report it to the developers" | ||
); | ||
} | ||
return { | ||
stream, | ||
deviceId: streamDeviceId | ||
}; | ||
}; | ||
/** | ||
* @description Check the permission for the given type | ||
* @param data `{ type: 'cam' | 'mic' | 'speaker' }` ( `IMediaDeviceType` ) | ||
* @returns { hasPermission: boolean, error?: IStreamPermissionsError } | ||
* @example await checkPermission({ type: 'cam' }) | ||
*/ | ||
checkPermission = async (data) => { | ||
let hasPermission = false; | ||
const { mediaDeviceKind } = data; | ||
try { | ||
const devices = await navigator.mediaDevices.enumerateDevices(); | ||
devices.forEach((device) => { | ||
const systemDeviceKind = CustomMediaKindToSystemKind[mediaDeviceKind]; | ||
if (device.kind === systemDeviceKind && device.deviceId !== "") { | ||
hasPermission = true; | ||
return; | ||
} | ||
}); | ||
if (!hasPermission) { | ||
return { | ||
hasPermission, | ||
error: { | ||
blocked: { | ||
byPermissions: true | ||
}, | ||
message: "Permission not granted" | ||
} | ||
}; | ||
} | ||
if (navigator.mediaDevices.ondevicechange === null) { | ||
navigator.mediaDevices.ondevicechange = async () => { | ||
await this.__setMediaDeviceInfo(); | ||
this.emit("device-change"); | ||
}; | ||
} | ||
await this.__setMediaDeviceInfo(); | ||
return { hasPermission }; | ||
} catch (error) { | ||
return { | ||
hasPermission, | ||
error: { | ||
blocked: { | ||
byPermissions: true | ||
}, | ||
message: "Permission not granted" | ||
} | ||
}; | ||
} | ||
}; | ||
/** | ||
* @description Get the media permission for the given type | ||
* @param data { type: 'video' | 'audio' } | ||
* @throws error { IStreamPermissionsError } | ||
* @example await getMediaPermission({ type: 'video' }) | ||
*/ | ||
getMediaPermission = async (data) => { | ||
const { mediaDeviceKind } = data; | ||
try { | ||
const object = { | ||
video: mediaDeviceKind === "cam", | ||
audio: mediaDeviceKind === "mic" | ||
}; | ||
await navigator.mediaDevices.getUserMedia(object).then((stream) => { | ||
stream.getTracks().forEach((track) => track.stop()); | ||
}); | ||
await this.__setMediaDeviceInfo(); | ||
this.emit("permission-granted", { deviceKind: mediaDeviceKind }); | ||
return { | ||
permission: "granted" | ||
}; | ||
} catch (err) { | ||
let error = { | ||
message: "Unknown Error", | ||
errorStack: err | ||
}; | ||
if (err instanceof DOMException) { | ||
error = { | ||
blocked: { | ||
byDeviceMissing: err.name === "NotFoundError", | ||
byDeviceInUse: err.name === "OverconstrainedError", | ||
byPermissions: err.name === "NotAllowedError" | ||
}, | ||
message: err.message | ||
}; | ||
} | ||
this.emit("permission-denied", { deviceKind: mediaDeviceKind, error }); | ||
return { | ||
permission: "denied", | ||
error | ||
}; | ||
} | ||
}; | ||
stopStream = (data) => { | ||
const prefferedStream = this.getStreamOfPreferredDevice({ | ||
kind: data.mediaDeviceKind | ||
}); | ||
if (prefferedStream) { | ||
prefferedStream.getTracks().forEach((track) => track.stop()); | ||
} | ||
const deviceId = this.__preferredDevices.get(data.mediaDeviceKind); | ||
if (deviceId) { | ||
this.__activeStreams.delete(deviceId); | ||
} | ||
this.emit("stream-stopped", { | ||
mediaKind: data.mediaDeviceKind | ||
}); | ||
}; | ||
stopScreen = () => { | ||
const prefferedStream = this.getStreamOfScreen(); | ||
if (prefferedStream) { | ||
prefferedStream.getTracks().forEach((track) => track.stop()); | ||
this.__activeStreams.delete(this.SCREEN_DEFAULT_DEVICE); | ||
} | ||
this.emit("screen-stopped", { | ||
mediaKind: "screen" | ||
}); | ||
}; | ||
destroy = () => { | ||
const streams = this.__activeStreams; | ||
streams.forEach((stream) => { | ||
stream.forEach((s) => { | ||
s.getTracks().forEach((track) => track.stop()); | ||
}); | ||
}); | ||
this.__preferredDevices.clear(); | ||
this.__mediaDevicesInfo.clear(); | ||
this.__activeStreams.clear(); | ||
logger.info("\u2705 Destroyed StreamHandler"); | ||
}; | ||
/** | ||
* Set the Media devices info based on the latest devices available in the system | ||
*/ | ||
__setMediaDeviceInfo = async () => { | ||
const allDevices = await this.getMediaDevices(); | ||
this.__mediaDevicesInfo.clear(); | ||
allDevices.map((device) => { | ||
const customDeviceKind = SystemKindToCustomMediaKind[device.kind]; | ||
const prevDevices = this.__mediaDevicesInfo.get(customDeviceKind); | ||
if (prevDevices) { | ||
const newDevices = /* @__PURE__ */ new Set([...prevDevices, device]); | ||
this.__mediaDevicesInfo.set(customDeviceKind, [...newDevices]); | ||
} else { | ||
this.__mediaDevicesInfo.set(customDeviceKind, [device]); | ||
} | ||
}); | ||
}; | ||
}; | ||
var DeviceHandler_default = DeviceHandler; | ||
import { | ||
DeviceHandler_default | ||
} from "./chunk-MFQPKMZ4.js"; | ||
import "./chunk-ECJWSCEU.js"; | ||
import "./chunk-UBA4U2PP.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
DeviceHandler_default as default | ||
}; | ||
//# sourceMappingURL=DeviceHandler.js.map | ||
//# sourceMappingURL=DeviceHandler.js.map |
@@ -1,7 +0,9 @@ | ||
import { MediaKind } from "mediasoup-client/lib/RtpParameters"; | ||
export declare const getMediaStreamKind: (stream: MediaStream) => MediaKind; | ||
export declare const getMediaTrack: (data: { | ||
import { MediaKind } from 'mediasoup-client/lib/RtpParameters'; | ||
declare const getMediaStreamKind: (stream: MediaStream) => MediaKind; | ||
declare const getMediaTrack: (data: { | ||
stream: MediaStream; | ||
kind: MediaKind; | ||
}) => MediaStreamTrack; | ||
//# sourceMappingURL=index.d.ts.map | ||
export { getMediaStreamKind, getMediaTrack }; |
@@ -1,29 +0,6 @@ | ||
// src/helpers/index.ts | ||
var getMediaStreamKind = (stream) => { | ||
let kind = null; | ||
const tracks = stream.getTracks(); | ||
for (const track of tracks) { | ||
if (track.kind === "audio") { | ||
kind = "audio"; | ||
break; | ||
} else if (track.kind === "video") { | ||
kind = "video"; | ||
break; | ||
} | ||
} | ||
if (!kind) { | ||
throw new Error("Stream Kind Not Found"); | ||
} | ||
return kind; | ||
}; | ||
var getMediaTrack = (data) => { | ||
const { stream, kind } = data; | ||
const tracks = stream.getTracks(); | ||
for (const track of tracks) { | ||
if (track.kind === kind) { | ||
return track; | ||
} | ||
} | ||
throw new Error("Track Not Found"); | ||
}; | ||
import { | ||
getMediaStreamKind, | ||
getMediaTrack | ||
} from "../chunk-OZOR2RLF.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
@@ -33,2 +10,2 @@ getMediaStreamKind, | ||
}; | ||
//# sourceMappingURL=index.js.map | ||
//# sourceMappingURL=index.js.map |
@@ -1,4 +0,21 @@ | ||
import LocalPeer from "./LocalPeer"; | ||
import Socket from "./Socket"; | ||
import Room from "./Room"; | ||
import LocalPeer from './LocalPeer.js'; | ||
import Socket from './Socket.js'; | ||
import Room from './Room.js'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client'; | ||
import 'types/dist/common.types'; | ||
import 'types/dist/socket.types'; | ||
import './DeviceHandler.js'; | ||
import './common-js/EnhancedEventEmitter.js'; | ||
import './Transport.js'; | ||
import 'types/dist'; | ||
import './Consumer.js'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
import 'types/dist/mq/response.types'; | ||
import './common-js/EnhancedMap.js'; | ||
import 'types/dist/clientToSushiEvents.types'; | ||
import 'types/dist/sushiToClientEvents.types'; | ||
import './types/common.types.js'; | ||
import './RemotePeer.js'; | ||
declare class HuddleClient { | ||
@@ -52,3 +69,3 @@ /** | ||
} | ||
export default HuddleClient; | ||
//# sourceMappingURL=HuddleClient.d.ts.map | ||
export { HuddleClient as default }; |
@@ -1,6 +0,21 @@ | ||
import HuddleClient from "./HuddleClient"; | ||
import RemotePeer from "./RemotePeer"; | ||
export { RemotePeer }; | ||
export * from "./validators"; | ||
export { HuddleClient }; | ||
//# sourceMappingURL=index.d.ts.map | ||
export { default as HuddleClient } from './HuddleClient.js'; | ||
export { default as Room } from './Room.js'; | ||
export { default as RemotePeer } from './RemotePeer.js'; | ||
export { default as LocalPeer } from './LocalPeer.js'; | ||
export { default as Consumer } from './Consumer.js'; | ||
export { default as Permissions } from './Permissions.js'; | ||
export { default as DeviceHandler } from './DeviceHandler.js'; | ||
export { default as Socket } from './Socket.js'; | ||
export { default as Transport } from './Transport.js'; | ||
import './common-js/EnhancedEventEmitter.js'; | ||
import './types/common.types.js'; | ||
import 'types/dist/common.types'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client'; | ||
import 'types/dist/socket.types'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
import 'types/dist/clientToSushiEvents.types'; | ||
import 'types/dist/sushiToClientEvents.types'; | ||
import 'types/dist'; | ||
import 'types/dist/mq/response.types'; | ||
import './common-js/EnhancedMap.js'; |
@@ -1,11 +0,20 @@ | ||
import type { Producer, AppData } from "mediasoup-client/lib/types"; | ||
import { Device } from "mediasoup-client"; | ||
import type { TDataMessage } from "types/dist/common.types"; | ||
import type { ESocketCloseCode } from "types/dist/socket.types"; | ||
import DeviceHandler from "./DeviceHandler"; | ||
import Transport from "./Transport"; | ||
import Consumer from "./Consumer"; | ||
import Socket from "./Socket"; | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
export type LocalPeerEvents = { | ||
import { Producer, AppData } from 'mediasoup-client/lib/types'; | ||
import { Device } from 'mediasoup-client'; | ||
import { TDataMessage } from 'types/dist/common.types'; | ||
import { ESocketCloseCode } from 'types/dist/socket.types'; | ||
import DeviceHandler from './DeviceHandler.js'; | ||
import Transport from './Transport.js'; | ||
import Consumer from './Consumer.js'; | ||
import Socket from './Socket.js'; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import 'types/dist'; | ||
import 'types/dist/mq/response.types'; | ||
import './common-js/EnhancedMap.js'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
import 'types/dist/clientToSushiEvents.types'; | ||
import 'types/dist/sushiToClientEvents.types'; | ||
import './types/common.types.js'; | ||
import './RemotePeer.js'; | ||
type LocalPeerEvents = { | ||
"stream-playabale": [data: { | ||
@@ -355,3 +364,3 @@ label: string; | ||
} | ||
export default LocalPeer; | ||
//# sourceMappingURL=LocalPeer.d.ts.map | ||
export { LocalPeerEvents, LocalPeer as default }; |
@@ -1,3 +0,3 @@ | ||
export type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "silent"; | ||
export interface Logger { | ||
type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "silent"; | ||
interface Logger { | ||
trace(...args: any[]): void; | ||
@@ -9,3 +9,3 @@ debug(...args: any[]): void; | ||
} | ||
export interface WrappedLogger extends Logger { | ||
interface WrappedLogger extends Logger { | ||
init(): void; | ||
@@ -15,9 +15,10 @@ level: LogLevel | undefined; | ||
} | ||
export type LoggerFactory = () => Logger; | ||
export declare const createLogger: (moduleName: string, logLevel?: LogLevel) => WrappedLogger; | ||
export declare const setLogLevel: (level: LogLevel) => void; | ||
export declare const setLoggerFactory: (loggerFactory: LoggerFactory) => void; | ||
export declare const mainLogger: { | ||
type LoggerFactory = () => Logger; | ||
declare const createLogger: (moduleName: string, logLevel?: LogLevel) => WrappedLogger; | ||
declare const setLogLevel: (level: LogLevel) => void; | ||
declare const setLoggerFactory: (loggerFactory: LoggerFactory) => void; | ||
declare const mainLogger: { | ||
createSubLogger: (moduleName: string) => WrappedLogger; | ||
}; | ||
//# sourceMappingURL=logger.d.ts.map | ||
export { LogLevel, Logger, LoggerFactory, WrappedLogger, createLogger, mainLogger, setLogLevel, setLoggerFactory }; |
@@ -1,145 +0,8 @@ | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var setLogLevel = (level) => { | ||
defaultLevel = level; | ||
for (const [moduleName] of Array.from(loggers.entries())) { | ||
loggers.set(moduleName, createLogger(moduleName, level)); | ||
} | ||
}; | ||
var setLoggerFactory = (loggerFactory) => { | ||
actualLoggerFactory = loggerFactory; | ||
for (const [moduleName, logger] of Array.from(loggers.entries())) { | ||
loggers.set(moduleName, createLogger(moduleName, logger.level)); | ||
} | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
import { | ||
createLogger, | ||
mainLogger, | ||
setLogLevel, | ||
setLoggerFactory | ||
} from "./chunk-YOQRRMW7.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
@@ -151,2 +14,2 @@ createLogger, | ||
}; | ||
//# sourceMappingURL=logger.js.map | ||
//# sourceMappingURL=logger.js.map |
@@ -1,3 +0,4 @@ | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
import { TPermissions } from "types/dist/common.types"; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import { TPermissions } from 'types/dist/common.types'; | ||
type PermissionEvents = { | ||
@@ -60,6 +61,6 @@ updated: [data: { | ||
} | ||
export declare const checkPermissions: (permission: Partial<TPermissions>) => { | ||
declare const checkPermissions: (permission: Partial<TPermissions>) => { | ||
validate: <T extends unknown[], R>(fn: (...args: T) => R) => (...args: T) => R; | ||
}; | ||
export default Permissions; | ||
//# sourceMappingURL=Permissions.d.ts.map | ||
export { PermissionEvents, checkPermissions, Permissions as default }; |
@@ -1,700 +0,8 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger2, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger2; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger2 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger2, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/Permissions.ts | ||
var logger = mainLogger.createSubLogger("Permissions"); | ||
var Permissions = class _Permissions extends EnhancedEventEmitter { | ||
/** | ||
* Get the Singleton Instance of the Permissions Class. | ||
*/ | ||
static __instance; | ||
/** | ||
* Admin Access of the Room. | ||
*/ | ||
__admin = false; | ||
/** | ||
* Can Consume Media Stream of the Room from RemotePeers; | ||
*/ | ||
__canConsume = false; | ||
/** | ||
* Can Produce Media Stream to the Room | ||
*/ | ||
__canProduce = true; | ||
/** | ||
* Allowed Sources to Produce Media Stream to the Room | ||
*/ | ||
__canProduceSources = ["cam", "mic", "screen"]; | ||
/** | ||
* Can Send Data to the Room, e.g. Chat Messages, update of avatar, name etc. to the room | ||
*/ | ||
__canSendData = false; | ||
/** | ||
* Can Receive Data from the Room, e.g. Chat Messages, update of avatar, name etc. from other Remote Peers. | ||
*/ | ||
__canRecvData = false; | ||
/** | ||
* Can Update Metadata of the Room, e.g. DisplayName, Avatar, etc. | ||
*/ | ||
__canUpdateMetadata = false; | ||
/** | ||
* Get the Access Control List ( acl ) of the Local Peer in the Room. | ||
*/ | ||
get acl() { | ||
return { | ||
admin: this.__admin, | ||
canConsume: this.__canConsume, | ||
canProduce: this.__canProduce, | ||
canProduceSources: this.__canProduceSources, | ||
canSendData: this.__canSendData, | ||
canRecvData: this.__canRecvData, | ||
canUpdateMetadata: this.__canUpdateMetadata | ||
}; | ||
} | ||
/** | ||
* Update the Permissions of the Local Peer in the Room. This will emit an event `updated` with the updated permissions. | ||
* | ||
* `NOTE: If the Peer is not an admin, then the permissions will not be updated on the server` | ||
*/ | ||
updatePermissions(permissions) { | ||
logger.info("\u{1F514} Updating Permissions", permissions); | ||
this.__admin = permissions.admin ?? this.__admin; | ||
this.__canConsume = permissions.canConsume ?? this.__canConsume; | ||
this.__canProduce = permissions.canProduce ?? this.__canProduce; | ||
this.__canProduceSources = permissions.canProduceSources ?? this.__canProduceSources; | ||
this.__canSendData = permissions.canSendData ?? this.__canSendData; | ||
this.__canRecvData = permissions.canRecvData ?? this.__canRecvData; | ||
this.__canUpdateMetadata = permissions.canUpdateMetadata ?? this.__canUpdateMetadata; | ||
this.emit("updated", { | ||
permissions: this.acl | ||
}); | ||
} | ||
static createInstance() { | ||
if (_Permissions.__instance) | ||
return _Permissions.__instance; | ||
_Permissions.__instance = new _Permissions(); | ||
return _Permissions.__instance; | ||
} | ||
static getInstance() { | ||
if (!_Permissions.__instance) { | ||
throw new Error("Permissions Instance not created yet."); | ||
} | ||
return _Permissions.__instance; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
}; | ||
var checkPermissions = (permission) => { | ||
return { | ||
validate: (fn) => { | ||
return (...args) => { | ||
const permissions = Permissions.getInstance().acl; | ||
if (permission.admin && !permissions.admin) { | ||
throw new Error("Admin Access Required."); | ||
} | ||
if (permission.canConsume && !permissions.canConsume) { | ||
throw new Error("Can Consume Access Required."); | ||
} | ||
if (permission.canProduce && !permissions.canProduce) { | ||
throw new Error("Can Produce Access Required."); | ||
} | ||
if (permission.canProduceSources && !permission.canProduceSources.every( | ||
(source) => permissions.canProduceSources.includes(source) | ||
)) { | ||
throw new Error("Can Produce Sources Access Required."); | ||
} | ||
if (permission.canSendData && !permissions.canSendData) { | ||
throw new Error("Can Send Data Access Required."); | ||
} | ||
if (permission.canRecvData && !permissions.canRecvData) { | ||
throw new Error("Can Recv Data Access Required."); | ||
} | ||
return fn(...args); | ||
}; | ||
} | ||
}; | ||
}; | ||
var Permissions_default = Permissions; | ||
import { | ||
Permissions_default, | ||
checkPermissions | ||
} from "./chunk-WLSB47W7.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
@@ -704,2 +12,2 @@ checkPermissions, | ||
}; | ||
//# sourceMappingURL=Permissions.js.map | ||
//# sourceMappingURL=Permissions.js.map |
@@ -1,4 +0,7 @@ | ||
import Consumer from "./Consumer"; | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
type TRemotePeerEvents = { | ||
import Consumer from './Consumer.js'; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
type RemotePeerEvents = { | ||
"stream-available": [ | ||
@@ -35,3 +38,3 @@ data: { | ||
}; | ||
declare class RemotePeer extends EnhancedEventEmitter<TRemotePeerEvents> { | ||
declare class RemotePeer extends EnhancedEventEmitter<RemotePeerEvents> { | ||
/** | ||
@@ -116,3 +119,3 @@ * peerId of the remote peer, this is unique for each peer | ||
} | ||
export default RemotePeer; | ||
//# sourceMappingURL=RemotePeer.d.ts.map | ||
export { RemotePeerEvents, RemotePeer as default }; |
@@ -1,6 +0,10 @@ | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
import RemotePeer from "./RemotePeer"; | ||
import { TNewPeerJoined } from "./types"; | ||
import { TRoomInfo, TNewRoomControls, TPermissions } from "types/dist/common.types"; | ||
export type IRoomEvents = { | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import RemotePeer from './RemotePeer.js'; | ||
import { NewPeerJoined } from './types/common.types.js'; | ||
import { TNewRoomControls, TRoomInfo, TPermissions } from 'types/dist/common.types'; | ||
import './Consumer.js'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
type RoomEvents = { | ||
"room-joined": []; | ||
@@ -16,3 +20,3 @@ "room-joined-failed": [ | ||
"room-connecting": []; | ||
"new-peer-joined": [data: TNewPeerJoined]; | ||
"new-peer-joined": [data: NewPeerJoined]; | ||
"lobby-peers-updated": [peerIds: string[]]; | ||
@@ -22,7 +26,4 @@ "peer-left": [peerId: string]; | ||
}; | ||
export type RoomStates = "idle" | "connecting" | "connected" | "failed" | "left" | "closed"; | ||
export type IRoomInitData = { | ||
roomId: string; | ||
}; | ||
declare class Room extends EnhancedEventEmitter<IRoomEvents> { | ||
type RoomStates = "idle" | "connecting" | "connected" | "failed" | "left" | "closed"; | ||
declare class Room extends EnhancedEventEmitter<RoomEvents> { | ||
/** | ||
@@ -114,3 +115,2 @@ * Room Instance, Singleton class | ||
* | ||
* @param data { IRoomInitData - { roomId: string }} | ||
* @returns - Room Instance | ||
@@ -184,3 +184,3 @@ */ | ||
} | ||
export default Room; | ||
//# sourceMappingURL=Room.d.ts.map | ||
export { RoomEvents, RoomStates, Room as default }; |
1416
dist/Room.js
@@ -1,1408 +0,14 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// ../types/dist/socket.types.js | ||
var require_socket_types = __commonJS({ | ||
"../types/dist/socket.types.js"(exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SocketCloseReason = exports.ESocketCloseCode = void 0; | ||
var ESocketCloseCode2; | ||
(function(ESocketCloseCode3) { | ||
ESocketCloseCode3[ESocketCloseCode3["ABNORMAL_CLOSURE"] = 1006] = "ABNORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["NORMAL_CLOSURE"] = 1e3] = "NORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["BROWSER_TAB_CLOSE"] = 1001] = "BROWSER_TAB_CLOSE"; | ||
ESocketCloseCode3[ESocketCloseCode3["GOING_AWAY"] = 4001] = "GOING_AWAY"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_EXPIRED"] = 4002] = "CONNECTION_EXPIRED"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_ERROR"] = 4006] = "CONNECTION_ERROR"; | ||
ESocketCloseCode3[ESocketCloseCode3["ROOM_CLOSED"] = 4007] = "ROOM_CLOSED"; | ||
})(ESocketCloseCode2 || (exports.ESocketCloseCode = ESocketCloseCode2 = {})); | ||
exports.SocketCloseReason = { | ||
[ESocketCloseCode2.ROOM_CLOSED]: "ROOM_CLOSED", | ||
[ESocketCloseCode2.ABNORMAL_CLOSURE]: "ABNORMAL_CLOSURE", | ||
[ESocketCloseCode2.NORMAL_CLOSURE]: "NORMAL_CLOSURE", | ||
[ESocketCloseCode2.BROWSER_TAB_CLOSE]: "BROWSER_TAB_CLOSE", | ||
[ESocketCloseCode2.GOING_AWAY]: "GOING_AWAY", | ||
[ESocketCloseCode2.CONNECTION_ERROR]: "CONNECTION_ERROR", | ||
[ESocketCloseCode2.CONNECTION_EXPIRED]: "CONNECTION_EXPIRED" | ||
}; | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger4, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger4; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger4 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger4, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/Socket.ts | ||
var import_socket = __toESM(require_socket_types(), 1); | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
// src/Socket.ts | ||
var logger = mainLogger.createSubLogger("Socket.ts"); | ||
var Socket = class _Socket extends EnhancedEventEmitter { | ||
/** | ||
* Socket Instance, Singleton class | ||
*/ | ||
static __instance; | ||
__retryCount = 0; | ||
/** | ||
* Current connection state of the socket connection | ||
*/ | ||
__connectionState = "uninitialized"; | ||
/** | ||
* Underlying WebSocket connection, until we dont call Socket.connect(); this will be null | ||
*/ | ||
__ws = null; | ||
/** | ||
* Map of all the subscribed events/topics for the socket connection | ||
*/ | ||
__subscribedMap = /* @__PURE__ */ new Map(); | ||
/** | ||
* Region of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
__region = null; | ||
/** | ||
* Endpoint of the socket server, this is fetched from the API server | ||
*/ | ||
__ENDPOINT = null; | ||
isLocalDev = false; | ||
/** | ||
* Token of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
token = null; | ||
/** | ||
* Returns the underlying WebSocket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
get ws() { | ||
if (!this.__ws) { | ||
throw new Error("\u{1F534} Socket Not Initialised"); | ||
} | ||
return this.__ws; | ||
} | ||
/** | ||
* Getter for the region of the current socket connection | ||
*/ | ||
get region() { | ||
return this.__region; | ||
} | ||
/** | ||
* Returns the current connection state of the socket connection | ||
*/ | ||
get connectionState() { | ||
return this.__connectionState; | ||
} | ||
/** | ||
* Returns true if the socket connection is connected | ||
*/ | ||
get connected() { | ||
return this.ws.OPEN === 1 && this.connectionState === "connected"; | ||
} | ||
/** | ||
* Returns true if the socket connection is connecting | ||
*/ | ||
get connecting() { | ||
return this.ws.CONNECTING === 0 && this.connectionState === "connecting"; | ||
} | ||
/** | ||
* Returns true if the socket connection is closed | ||
*/ | ||
get closed() { | ||
return this.ws.CLOSED === 3 || this.ws.CLOSING === 2; | ||
} | ||
/** | ||
* Sets the current connection state of the socket connection | ||
*/ | ||
set connectionState(state) { | ||
logger.info(`Connection state changed to ${state}`); | ||
if (this.__connectionState !== state) { | ||
this.emit(state); | ||
} | ||
this.__connectionState = state; | ||
} | ||
/** | ||
* Update the token for this socket | ||
* @throws `Error` if the token is already set | ||
*/ | ||
setToken(token) { | ||
if (this.token) { | ||
throw new Error("\u{1F534} Token Already Set"); | ||
} | ||
this.token = token; | ||
this.emit("token-updated", token); | ||
} | ||
/** | ||
* Set a new region for the socket connection | ||
*/ | ||
setRegion(region) { | ||
this.__region = region; | ||
this.emit("region-updated", region); | ||
} | ||
/** | ||
* Initializes the socket Manager and returns the instance of the socket connection if already initialized | ||
* you need to call connect method to connect to the server | ||
* @param data | ||
* @returns | ||
*/ | ||
static init() { | ||
if (!this.__instance) { | ||
this.__instance = new _Socket(); | ||
} | ||
return this.__instance; | ||
} | ||
/** | ||
* Returns the instance of the socket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
static getInstance() { | ||
if (!_Socket.__instance) { | ||
throw new Error( | ||
"\u{1F534} Socket Instance Not Initialised, You are trying to do something which is not possible" | ||
); | ||
} | ||
return _Socket.__instance; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
/** | ||
* | ||
*/ | ||
__getRegion = async () => { | ||
const resp = await fetch( | ||
"https://shinigami.huddle01.com/api/get-geolocation" | ||
); | ||
const data = await resp?.json(); | ||
const geolocationdata = GeolocationSchema.safeParse(data); | ||
if (!geolocationdata.success) { | ||
throw new Error("\u{1F534} Error While Finding the Region to connect to"); | ||
} | ||
const region = geolocationdata.data.globalRegion; | ||
return region; | ||
}; | ||
enableLocalDev = () => { | ||
this.isLocalDev = true; | ||
}; | ||
/** | ||
* Connect to the socket server using the token | ||
* @param data - `{ token: string }` | ||
*/ | ||
connect = async (data) => { | ||
if (!this.token) { | ||
this.setToken(data.token); | ||
} | ||
if (this.connectionState === "connected") { | ||
logger.error("\u{1F534} Socket Already Connected"); | ||
return _Socket.__instance; | ||
} | ||
if (this.connectionState === "connecting") { | ||
logger.error("\u{1F534} Socket Connecting"); | ||
return _Socket.__instance; | ||
} | ||
if (this.__ws) { | ||
logger.error("\u{1F534} Socket Already Initialized"); | ||
return _Socket.__instance; | ||
} | ||
logger.info("\u{1F50C} Connecting to the socket server"); | ||
if (this.connectionState === "closed") { | ||
logger.info( | ||
"\u{1F50C} Socket connection was closed, creating a new socket connection" | ||
); | ||
this.emit("reconnecting"); | ||
} | ||
if (!this.__region) { | ||
const region = await this.__getRegion(); | ||
this.__region = region; | ||
} | ||
const url = await this.__getConfigUrl(data.token, this.__region); | ||
this.__ws = new WebSocket(url); | ||
this.__ws.onerror = (ev) => { | ||
logger.error(ev); | ||
}; | ||
this.connectionState = "connecting"; | ||
this.__ws.addEventListener("message", this.__handleIncomingMessage); | ||
this.__registerSocketEvents(this.ws); | ||
this.__ws.onclose = async (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
if (this.__retryCount < 5) { | ||
if (ev.code === import_socket.ESocketCloseCode.ABNORMAL_CLOSURE) { | ||
const delay = 2 ** this.__retryCount * 1e3; | ||
setTimeout(async () => { | ||
if (this.token) { | ||
await this.connect({ token: this.token }); | ||
this.emit("reconnected"); | ||
this.__retryCount = 0; | ||
} | ||
}, delay); | ||
this.__retryCount++; | ||
} | ||
} | ||
}; | ||
const socketConnectionPromise = new Promise((resolve, reject) => { | ||
const handleSuccess = () => { | ||
logger.info("\u2705 Socket Connection Established"); | ||
handleRemoveListeners(); | ||
resolve(); | ||
}; | ||
const handleError = () => { | ||
logger.error("\u{1F534} Error While Connecting to the Socket"); | ||
handleRemoveListeners(); | ||
reject(new Error("\u274C Socket Connection Failed")); | ||
}; | ||
const handleRemoveListeners = () => { | ||
this.off("connected", handleSuccess); | ||
this.off("failed", handleError); | ||
this.off("closed", handleError); | ||
}; | ||
this.once("connected", handleSuccess); | ||
this.once("failed", handleError); | ||
this.once("closed", handleError); | ||
}); | ||
await socketConnectionPromise; | ||
return _Socket.__instance; | ||
}; | ||
/** | ||
* Closes the underlying socket connection, and clears all the event listeners and subscriptions to events as well as | ||
* any other information related to the connection. | ||
* @param code `{ ESocketCloseCode }` | ||
*/ | ||
close = (code) => { | ||
this.ws.removeEventListener("message", this.__handleIncomingMessage); | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F50C} Closing the connection, ${code} ${reason}`); | ||
if (code >= 3e3 && code <= 4999 || code === 1e3) { | ||
this.ws.close(code, reason); | ||
} else { | ||
this.ws.close(); | ||
} | ||
this.__unregisterSocketEvents(this.ws); | ||
this.__subscribedMap.clear(); | ||
this.__ws = null; | ||
this.connectionState = "closed"; | ||
logger.info("\u{1F50C} Socket Connection closed"); | ||
}; | ||
/** | ||
* Publish a message to the server using the socket connection based on some events/topics | ||
*/ | ||
publish = (event, data) => { | ||
const payload = JSON.stringify({ | ||
event, | ||
data: data || {} | ||
}); | ||
this.ws.send(payload); | ||
}; | ||
/** | ||
* Subscribe to a specific event/topic from the server | ||
*/ | ||
subscribe = (event, fn) => { | ||
if (this.__subscribedMap.has(event)) { | ||
logger.warn("\u26A0\uFE0F Overriding existing event handler"); | ||
} | ||
this.__subscribedMap.set(event, fn); | ||
}; | ||
/** | ||
* Get the config url for the socket connection based on the token and region | ||
* @param token Local Peer specific meeting token | ||
* @param region Local Peer specific region | ||
* @returns | ||
*/ | ||
async __getConfigUrl(token, region) { | ||
if (this.__ENDPOINT) { | ||
return this.__ENDPOINT; | ||
} | ||
const apiServerUrl = this.isLocalDev ? "http://localhost:8000/api/v1" : "https://apira.huddle01.com/api/v1"; | ||
const res = await fetch(`${apiServerUrl}/getSushiUrl`, { | ||
method: "GET", | ||
headers: { | ||
"Content-Type": "application/json", | ||
authorization: `Bearer ${token}` | ||
} | ||
}); | ||
if (!res.ok) { | ||
throw new Error("\u{1F534} Error While Fetching the Url"); | ||
} | ||
const { url } = await res.json(); | ||
this.__ENDPOINT = url.replace("https://", "wss://").replace("http://", "ws://"); | ||
const wssAddress = `${this.__ENDPOINT}/ws`; | ||
const wsAddress = `${wssAddress}?${[ | ||
`token=${token}`, | ||
`version=${2}`, | ||
`region=${region}` | ||
].join("&")}`; | ||
this.__ENDPOINT = wsAddress; | ||
return wsAddress; | ||
} | ||
/** | ||
* !Important | ||
* Handle the incoming message from the server based on the events recieved from the server and call the subscribed event handler | ||
*/ | ||
__handleIncomingMessage = (event) => { | ||
const { event: eventName, data } = JSON.parse(event.data); | ||
logger.info("\u{1F4E8} Incoming message event name: ", eventName); | ||
const fn = this.__subscribedMap.get(eventName); | ||
if (fn) { | ||
fn(data); | ||
} | ||
}; | ||
__handleSocketError = (ev) => { | ||
logger.error("Socket connection error", ev); | ||
this.connectionState = "failed"; | ||
}; | ||
/** | ||
* @description Handle the socket close event which is sent by the server | ||
* @param ev CloseEvent | ||
*/ | ||
__handleSocketClose = (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
const code = ev.code; | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F534} { Server }: Closing the connection, ${code} ${reason}`); | ||
this.connectionState = "closed"; | ||
this.close(code); | ||
}; | ||
/** | ||
* @description Handle the socket open event which is sent after the connection is established with the server | ||
* @param ev Event | ||
*/ | ||
__handleSocketOpen = (ev) => { | ||
logger.info("Socket Connection Open", ev); | ||
this.connectionState = "connected"; | ||
}; | ||
/** | ||
* @description Register the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__registerSocketEvents = (ws) => { | ||
ws.addEventListener("error", this.__handleSocketError); | ||
ws.addEventListener("close", this.__handleSocketClose); | ||
ws.addEventListener("open", this.__handleSocketOpen); | ||
}; | ||
/** | ||
* @description Unregister the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__unregisterSocketEvents = (ws) => { | ||
ws.removeEventListener("error", this.__handleSocketError); | ||
ws.removeEventListener("close", this.__handleSocketClose); | ||
ws.removeEventListener("open", this.__handleSocketOpen); | ||
}; | ||
}; | ||
var Socket_default = Socket; | ||
// src/Permissions.ts | ||
var logger2 = mainLogger.createSubLogger("Permissions"); | ||
var Permissions = class _Permissions extends EnhancedEventEmitter { | ||
/** | ||
* Get the Singleton Instance of the Permissions Class. | ||
*/ | ||
static __instance; | ||
/** | ||
* Admin Access of the Room. | ||
*/ | ||
__admin = false; | ||
/** | ||
* Can Consume Media Stream of the Room from RemotePeers; | ||
*/ | ||
__canConsume = false; | ||
/** | ||
* Can Produce Media Stream to the Room | ||
*/ | ||
__canProduce = true; | ||
/** | ||
* Allowed Sources to Produce Media Stream to the Room | ||
*/ | ||
__canProduceSources = ["cam", "mic", "screen"]; | ||
/** | ||
* Can Send Data to the Room, e.g. Chat Messages, update of avatar, name etc. to the room | ||
*/ | ||
__canSendData = false; | ||
/** | ||
* Can Receive Data from the Room, e.g. Chat Messages, update of avatar, name etc. from other Remote Peers. | ||
*/ | ||
__canRecvData = false; | ||
/** | ||
* Can Update Metadata of the Room, e.g. DisplayName, Avatar, etc. | ||
*/ | ||
__canUpdateMetadata = false; | ||
/** | ||
* Get the Access Control List ( acl ) of the Local Peer in the Room. | ||
*/ | ||
get acl() { | ||
return { | ||
admin: this.__admin, | ||
canConsume: this.__canConsume, | ||
canProduce: this.__canProduce, | ||
canProduceSources: this.__canProduceSources, | ||
canSendData: this.__canSendData, | ||
canRecvData: this.__canRecvData, | ||
canUpdateMetadata: this.__canUpdateMetadata | ||
}; | ||
} | ||
/** | ||
* Update the Permissions of the Local Peer in the Room. This will emit an event `updated` with the updated permissions. | ||
* | ||
* `NOTE: If the Peer is not an admin, then the permissions will not be updated on the server` | ||
*/ | ||
updatePermissions(permissions) { | ||
logger2.info("\u{1F514} Updating Permissions", permissions); | ||
this.__admin = permissions.admin ?? this.__admin; | ||
this.__canConsume = permissions.canConsume ?? this.__canConsume; | ||
this.__canProduce = permissions.canProduce ?? this.__canProduce; | ||
this.__canProduceSources = permissions.canProduceSources ?? this.__canProduceSources; | ||
this.__canSendData = permissions.canSendData ?? this.__canSendData; | ||
this.__canRecvData = permissions.canRecvData ?? this.__canRecvData; | ||
this.__canUpdateMetadata = permissions.canUpdateMetadata ?? this.__canUpdateMetadata; | ||
this.emit("updated", { | ||
permissions: this.acl | ||
}); | ||
} | ||
static createInstance() { | ||
if (_Permissions.__instance) | ||
return _Permissions.__instance; | ||
_Permissions.__instance = new _Permissions(); | ||
return _Permissions.__instance; | ||
} | ||
static getInstance() { | ||
if (!_Permissions.__instance) { | ||
throw new Error("Permissions Instance not created yet."); | ||
} | ||
return _Permissions.__instance; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
}; | ||
var checkPermissions = (permission) => { | ||
return { | ||
validate: (fn) => { | ||
return (...args) => { | ||
const permissions = Permissions.getInstance().acl; | ||
if (permission.admin && !permissions.admin) { | ||
throw new Error("Admin Access Required."); | ||
} | ||
if (permission.canConsume && !permissions.canConsume) { | ||
throw new Error("Can Consume Access Required."); | ||
} | ||
if (permission.canProduce && !permissions.canProduce) { | ||
throw new Error("Can Produce Access Required."); | ||
} | ||
if (permission.canProduceSources && !permission.canProduceSources.every( | ||
(source) => permissions.canProduceSources.includes(source) | ||
)) { | ||
throw new Error("Can Produce Sources Access Required."); | ||
} | ||
if (permission.canSendData && !permissions.canSendData) { | ||
throw new Error("Can Send Data Access Required."); | ||
} | ||
if (permission.canRecvData && !permissions.canRecvData) { | ||
throw new Error("Can Recv Data Access Required."); | ||
} | ||
return fn(...args); | ||
}; | ||
} | ||
}; | ||
}; | ||
// src/Room.ts | ||
var logger3 = mainLogger.createSubLogger("Room.ts"); | ||
var Room = class _Room extends EnhancedEventEmitter { | ||
/** | ||
* Room Instance, Singleton class | ||
*/ | ||
static __instance; | ||
/** | ||
* Socket Instance, Singleton class | ||
*/ | ||
__socket = Socket_default.getInstance(); | ||
/** | ||
* Returns the instance of the socket connection | ||
*/ | ||
get socket() { | ||
return this.__socket; | ||
} | ||
/** | ||
* Room Id of the current room | ||
*/ | ||
__roomId = null; | ||
/** | ||
* Lobby PeerIds | ||
*/ | ||
__lobbyPeerIds = /* @__PURE__ */ new Set(); | ||
/** | ||
* Removed Lobby PeerId from the lobby | ||
* @param peerId - PeerId of the peer who joined the room | ||
*/ | ||
removeLobbyPeer = (peerId) => { | ||
this.__lobbyPeerIds.delete(peerId); | ||
this.emit("lobby-peers-updated", this.lobbyPeerIds); | ||
}; | ||
/** | ||
* Room Config Object | ||
* - `allowProduce`: Allow non-admin Peers in the Room to produce Media Streams | ||
* - `allowConsume`: Allow non-admin Peers in the Room to consume Media Streams | ||
* - `allowSendData`: Allow non-admin Peers in the Room to send data message | ||
* - `roomLocked`: If the room is locked | ||
*/ | ||
__config = { | ||
roomLocked: false, | ||
allowProduce: true, | ||
allowProduceSources: ["cam", "mic", "screen"], | ||
allowConsume: true, | ||
allowSendData: true | ||
}; | ||
/** | ||
* Auto consume flag, if set to true, Peers Joining the Room will automatically consume the media streams of the remote peers | ||
* | ||
* @default true | ||
* | ||
* @remarks - This flag is used by the `useRoom` hook to automatically consume the media streams of the remote peers, | ||
* - if set to false, the user will have to manually consume the media streams of the remote peers | ||
* using the `consume` method of the `LocalPeer` instance `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
autoConsume = true; | ||
/** | ||
* State of the Room | ||
*/ | ||
__state = "idle"; | ||
/** | ||
* Set the state of the room | ||
*/ | ||
set state(newState) { | ||
if (this.state !== newState) { | ||
this.__state = newState; | ||
} | ||
} | ||
/** | ||
* State of the room | ||
*/ | ||
get state() { | ||
return this.__state; | ||
} | ||
/** | ||
* Get the Lobby Peers in the form of Set | ||
* @retruns - Set of Lobby PeerIds | ||
*/ | ||
get lobbyPeerSet() { | ||
return this.__lobbyPeerIds; | ||
} | ||
set lobbyPeerSet(peerIds) { | ||
this.__lobbyPeerIds = peerIds; | ||
this.emit("lobby-peers-updated", this.lobbyPeerIds); | ||
} | ||
/** | ||
* Get lobby peers in the form of array | ||
* @returns - Array of Lobby PeerIds | ||
*/ | ||
get lobbyPeerIds() { | ||
return Array.from(this.__lobbyPeerIds); | ||
} | ||
/** | ||
* Set lobby peers in the form of array | ||
*/ | ||
set lobbyPeerIds(peerIds) { | ||
peerIds.map((peerId) => this.__lobbyPeerIds.add(peerId)); | ||
this.emit("lobby-peers-updated", peerIds); | ||
} | ||
/** | ||
* Room Config Object | ||
* - `allowProduce`: Allow non-admin Peers in the Room to produce Media Streams | ||
* - `allowConsume`: Allow non-admin Peers in the Room to consume Media Streams | ||
* - `allowSendData`: Allow non-admin Peers in the Room to send data message | ||
* - `roomLocked`: If the room is locked | ||
*/ | ||
get config() { | ||
return this.__config; | ||
} | ||
set config(config) { | ||
this.__config = config; | ||
} | ||
/** | ||
* Remote Peers Map, Stores all the remote peers | ||
*/ | ||
remotePeers = /* @__PURE__ */ new Map(); | ||
/** | ||
* Returns the Room Instance, if the instance is not initialized, it will initialize the instance and return it | ||
* | ||
* @param data { IRoomInitData - { roomId: string }} | ||
* @returns - Room Instance | ||
*/ | ||
static init() { | ||
if (_Room.__instance) { | ||
return _Room.__instance; | ||
} | ||
_Room.__instance = new _Room(); | ||
return _Room.__instance; | ||
} | ||
/** | ||
* Get the Room Instance if its not initialized it will throw an error | ||
* @returns - Room Instance | ||
* @throws { Error } If the Room Instance is not initialized | ||
*/ | ||
static getInstance = () => { | ||
if (!_Room.__instance) { | ||
throw new Error("\u274C Room Instance Not Initialized"); | ||
} | ||
return _Room.__instance; | ||
}; | ||
/** | ||
* RoomId of the currently joined room. | ||
*/ | ||
get roomId() { | ||
if (!this.__roomId) { | ||
logger3.warn( | ||
"RoomId is not set, Call connect() method before you can access the roomId" | ||
); | ||
return null; | ||
} | ||
return this.__roomId; | ||
} | ||
set roomId(roomId) { | ||
if (this.__roomId) { | ||
logger3.warn( | ||
"RoomId is already set, Ignoring the new roomId, end this room and create a new room" | ||
); | ||
return; | ||
} | ||
this.__roomId = roomId; | ||
} | ||
/** | ||
* Returns the PeerIds of the remote peers | ||
*/ | ||
get peerIds() { | ||
return Array.from(this.remotePeers.keys()); | ||
} | ||
/** | ||
* @description Update room control booleans - roomLocked, allowProduce, allowConsume, allowSendData | ||
* @param data: TNewRoomControls | ||
*/ | ||
updateRoomControls = checkPermissions({ | ||
admin: true | ||
}).validate((data) => { | ||
logger3.info("\u{1F514} Updating Room Controls", data); | ||
this.config[data.type] = data.value; | ||
this.emit("room-controls-updated", { ...data }); | ||
this.socket.publish("updateRoomControls", data); | ||
}); | ||
/** | ||
* Update the Permissions of the Remote Peer in the Room, this will emit an event `updated` with the updated permissions. | ||
*/ | ||
updatePeerPermission = checkPermissions({ | ||
admin: true | ||
}).validate((data) => { | ||
logger3.info("\u{1F514} Updating Peer Permission", data); | ||
this.socket.publish("updatePeerPermission", { | ||
peerId: data.peerId, | ||
permission: data.permission | ||
}); | ||
}); | ||
/** | ||
* Returns the Remote Peer with the given peerId is present in the room. Returns null if the peer is not present in the room. | ||
* | ||
* @param peerId - PeerId of the remote peer | ||
* @returns - RemotePeer Instance | ||
* @return - null if the peer is not present in the room | ||
*/ | ||
remotePeerExists = (peerId) => { | ||
const peer = this.remotePeers.get(peerId); | ||
if (!peer) { | ||
return null; | ||
} | ||
return peer; | ||
}; | ||
/** | ||
* Returns the Remote Peer if present in room. | ||
* @param peerId - PeerId of the remote peer | ||
* @returns - RemotePeer Instance | ||
* @throws { Error } If the Remote Peer is not found | ||
*/ | ||
getRemotePeerById(peerId) { | ||
const peer = this.remotePeers.get(peerId); | ||
if (!peer) { | ||
throw new Error(`Remote Peer Not Found, peerId: ${peerId}`); | ||
} | ||
return peer; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
/** | ||
* Connects to the room and returns the instance of the room | ||
* @throws { Error } If the socket connection is not connected, or if the socket connection is connecting | ||
*/ | ||
connect = () => { | ||
if (!this.socket.connected) { | ||
throw new Error("Socket is Not Connected"); | ||
} | ||
if (this.socket.connecting) { | ||
throw new Error("Socket is Connecting, Wait for it to be connected"); | ||
} | ||
if (!this.roomId) { | ||
throw new Error("Room Id is required to connect to the room"); | ||
} | ||
this.socket.publish("connectRoom", { roomId: this.roomId }); | ||
this.__state = "connecting"; | ||
this.emit("room-connecting"); | ||
return _Room.__instance; | ||
}; | ||
/** | ||
* Admit a Peer to the room who is in the lobby | ||
*/ | ||
admitPeer = checkPermissions({ admin: true }).validate( | ||
(peerId) => { | ||
try { | ||
this.removeLobbyPeer(peerId); | ||
this.socket.publish("acceptLobbyPeer", { peerId }); | ||
} catch (error) { | ||
logger3.error("\u{1F534} Error admitting peer", error); | ||
} | ||
} | ||
); | ||
/** | ||
* Denies the peer from joining the room, who is in the lobby | ||
*/ | ||
denyPeer = checkPermissions({ admin: true }).validate( | ||
(peerId) => { | ||
try { | ||
this.removeLobbyPeer(peerId); | ||
this.socket.publish("denyLobbyPeer", { peerId }); | ||
} catch (error) { | ||
logger3.error("\u{1F534} Error denying peer", error); | ||
} | ||
} | ||
); | ||
/** | ||
* Closes the room for the current user and every other user | ||
*/ | ||
close = checkPermissions({ | ||
admin: true | ||
}).validate(() => { | ||
logger3.info("\u{1F534} Closing the room"); | ||
this.__roomId = null; | ||
this.remotePeers.clear(); | ||
this.state = "closed"; | ||
this.emit("room-closed"); | ||
}); | ||
/** | ||
* Leaves the room for the current user, room will keep on running for the remote users | ||
*/ | ||
leave = () => { | ||
logger3.info("\u{1F534} Leaving the room"); | ||
this.__roomId = null; | ||
this.remotePeers.clear(); | ||
this.state = "left"; | ||
this.emit("room-left"); | ||
}; | ||
}; | ||
var Room_default = Room; | ||
import { | ||
Room_default | ||
} from "./chunk-4VF3VETZ.js"; | ||
import "./chunk-WLSB47W7.js"; | ||
import "./chunk-PHWUOEBN.js"; | ||
import "./chunk-PYD4CES4.js"; | ||
import "./chunk-OYKTKRTB.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
Room_default as default | ||
}; | ||
//# sourceMappingURL=Room.js.map | ||
//# sourceMappingURL=Room.js.map |
@@ -1,7 +0,12 @@ | ||
import { ClientToSushiEvents } from "types/dist/clientToSushiEvents.types"; | ||
import { SushiToClientEvents } from "types/dist/sushiToClientEvents.types"; | ||
import { ESocketCloseCode } from "types/dist/socket.types"; | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
import { ConnectionState } from "./types"; | ||
export type ISocketEvents = { | ||
import { ClientToSushiEvents } from 'types/dist/clientToSushiEvents.types'; | ||
import { SushiToClientEvents } from 'types/dist/sushiToClientEvents.types'; | ||
import { ESocketCloseCode } from 'types/dist/socket.types'; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import { ConnectionState } from './types/common.types.js'; | ||
import './RemotePeer.js'; | ||
import './Consumer.js'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
type SocketEvents = { | ||
uninitialized: []; | ||
@@ -17,3 +22,3 @@ connecting: []; | ||
}; | ||
export type TMessagePayload<T = SushiToClientEvents> = { | ||
type MessagePayload<T = SushiToClientEvents> = { | ||
event: keyof T; | ||
@@ -25,3 +30,3 @@ data: Parameters<SushiToClientEvents[keyof SushiToClientEvents]>[0]; | ||
*/ | ||
declare class Socket<T = SushiToClientEvents> extends EnhancedEventEmitter<ISocketEvents> { | ||
declare class Socket<T = SushiToClientEvents> extends EnhancedEventEmitter<SocketEvents> { | ||
/** | ||
@@ -168,3 +173,3 @@ * Socket Instance, Singleton class | ||
} | ||
export default Socket; | ||
//# sourceMappingURL=Socket.d.ts.map | ||
export { MessagePayload, SocketEvents, Socket as default }; |
1008
dist/Socket.js
@@ -1,1002 +0,12 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../types/dist/socket.types.js | ||
var require_socket_types = __commonJS({ | ||
"../types/dist/socket.types.js"(exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SocketCloseReason = exports.ESocketCloseCode = void 0; | ||
var ESocketCloseCode2; | ||
(function(ESocketCloseCode3) { | ||
ESocketCloseCode3[ESocketCloseCode3["ABNORMAL_CLOSURE"] = 1006] = "ABNORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["NORMAL_CLOSURE"] = 1e3] = "NORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["BROWSER_TAB_CLOSE"] = 1001] = "BROWSER_TAB_CLOSE"; | ||
ESocketCloseCode3[ESocketCloseCode3["GOING_AWAY"] = 4001] = "GOING_AWAY"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_EXPIRED"] = 4002] = "CONNECTION_EXPIRED"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_ERROR"] = 4006] = "CONNECTION_ERROR"; | ||
ESocketCloseCode3[ESocketCloseCode3["ROOM_CLOSED"] = 4007] = "ROOM_CLOSED"; | ||
})(ESocketCloseCode2 || (exports.ESocketCloseCode = ESocketCloseCode2 = {})); | ||
exports.SocketCloseReason = { | ||
[ESocketCloseCode2.ROOM_CLOSED]: "ROOM_CLOSED", | ||
[ESocketCloseCode2.ABNORMAL_CLOSURE]: "ABNORMAL_CLOSURE", | ||
[ESocketCloseCode2.NORMAL_CLOSURE]: "NORMAL_CLOSURE", | ||
[ESocketCloseCode2.BROWSER_TAB_CLOSE]: "BROWSER_TAB_CLOSE", | ||
[ESocketCloseCode2.GOING_AWAY]: "GOING_AWAY", | ||
[ESocketCloseCode2.CONNECTION_ERROR]: "CONNECTION_ERROR", | ||
[ESocketCloseCode2.CONNECTION_EXPIRED]: "CONNECTION_EXPIRED" | ||
}; | ||
} | ||
}); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger2, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger2; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger2.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger2 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger2, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/Socket.ts | ||
var import_socket = __toESM(require_socket_types(), 1); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
// src/Socket.ts | ||
var logger = mainLogger.createSubLogger("Socket.ts"); | ||
var Socket = class _Socket extends EnhancedEventEmitter { | ||
/** | ||
* Socket Instance, Singleton class | ||
*/ | ||
static __instance; | ||
__retryCount = 0; | ||
/** | ||
* Current connection state of the socket connection | ||
*/ | ||
__connectionState = "uninitialized"; | ||
/** | ||
* Underlying WebSocket connection, until we dont call Socket.connect(); this will be null | ||
*/ | ||
__ws = null; | ||
/** | ||
* Map of all the subscribed events/topics for the socket connection | ||
*/ | ||
__subscribedMap = /* @__PURE__ */ new Map(); | ||
/** | ||
* Region of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
__region = null; | ||
/** | ||
* Endpoint of the socket server, this is fetched from the API server | ||
*/ | ||
__ENDPOINT = null; | ||
isLocalDev = false; | ||
/** | ||
* Token of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
token = null; | ||
/** | ||
* Returns the underlying WebSocket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
get ws() { | ||
if (!this.__ws) { | ||
throw new Error("\u{1F534} Socket Not Initialised"); | ||
} | ||
return this.__ws; | ||
} | ||
/** | ||
* Getter for the region of the current socket connection | ||
*/ | ||
get region() { | ||
return this.__region; | ||
} | ||
/** | ||
* Returns the current connection state of the socket connection | ||
*/ | ||
get connectionState() { | ||
return this.__connectionState; | ||
} | ||
/** | ||
* Returns true if the socket connection is connected | ||
*/ | ||
get connected() { | ||
return this.ws.OPEN === 1 && this.connectionState === "connected"; | ||
} | ||
/** | ||
* Returns true if the socket connection is connecting | ||
*/ | ||
get connecting() { | ||
return this.ws.CONNECTING === 0 && this.connectionState === "connecting"; | ||
} | ||
/** | ||
* Returns true if the socket connection is closed | ||
*/ | ||
get closed() { | ||
return this.ws.CLOSED === 3 || this.ws.CLOSING === 2; | ||
} | ||
/** | ||
* Sets the current connection state of the socket connection | ||
*/ | ||
set connectionState(state) { | ||
logger.info(`Connection state changed to ${state}`); | ||
if (this.__connectionState !== state) { | ||
this.emit(state); | ||
} | ||
this.__connectionState = state; | ||
} | ||
/** | ||
* Update the token for this socket | ||
* @throws `Error` if the token is already set | ||
*/ | ||
setToken(token) { | ||
if (this.token) { | ||
throw new Error("\u{1F534} Token Already Set"); | ||
} | ||
this.token = token; | ||
this.emit("token-updated", token); | ||
} | ||
/** | ||
* Set a new region for the socket connection | ||
*/ | ||
setRegion(region) { | ||
this.__region = region; | ||
this.emit("region-updated", region); | ||
} | ||
/** | ||
* Initializes the socket Manager and returns the instance of the socket connection if already initialized | ||
* you need to call connect method to connect to the server | ||
* @param data | ||
* @returns | ||
*/ | ||
static init() { | ||
if (!this.__instance) { | ||
this.__instance = new _Socket(); | ||
} | ||
return this.__instance; | ||
} | ||
/** | ||
* Returns the instance of the socket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
static getInstance() { | ||
if (!_Socket.__instance) { | ||
throw new Error( | ||
"\u{1F534} Socket Instance Not Initialised, You are trying to do something which is not possible" | ||
); | ||
} | ||
return _Socket.__instance; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
/** | ||
* | ||
*/ | ||
__getRegion = async () => { | ||
const resp = await fetch( | ||
"https://shinigami.huddle01.com/api/get-geolocation" | ||
); | ||
const data = await resp?.json(); | ||
const geolocationdata = GeolocationSchema.safeParse(data); | ||
if (!geolocationdata.success) { | ||
throw new Error("\u{1F534} Error While Finding the Region to connect to"); | ||
} | ||
const region = geolocationdata.data.globalRegion; | ||
return region; | ||
}; | ||
enableLocalDev = () => { | ||
this.isLocalDev = true; | ||
}; | ||
/** | ||
* Connect to the socket server using the token | ||
* @param data - `{ token: string }` | ||
*/ | ||
connect = async (data) => { | ||
if (!this.token) { | ||
this.setToken(data.token); | ||
} | ||
if (this.connectionState === "connected") { | ||
logger.error("\u{1F534} Socket Already Connected"); | ||
return _Socket.__instance; | ||
} | ||
if (this.connectionState === "connecting") { | ||
logger.error("\u{1F534} Socket Connecting"); | ||
return _Socket.__instance; | ||
} | ||
if (this.__ws) { | ||
logger.error("\u{1F534} Socket Already Initialized"); | ||
return _Socket.__instance; | ||
} | ||
logger.info("\u{1F50C} Connecting to the socket server"); | ||
if (this.connectionState === "closed") { | ||
logger.info( | ||
"\u{1F50C} Socket connection was closed, creating a new socket connection" | ||
); | ||
this.emit("reconnecting"); | ||
} | ||
if (!this.__region) { | ||
const region = await this.__getRegion(); | ||
this.__region = region; | ||
} | ||
const url = await this.__getConfigUrl(data.token, this.__region); | ||
this.__ws = new WebSocket(url); | ||
this.__ws.onerror = (ev) => { | ||
logger.error(ev); | ||
}; | ||
this.connectionState = "connecting"; | ||
this.__ws.addEventListener("message", this.__handleIncomingMessage); | ||
this.__registerSocketEvents(this.ws); | ||
this.__ws.onclose = async (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
if (this.__retryCount < 5) { | ||
if (ev.code === import_socket.ESocketCloseCode.ABNORMAL_CLOSURE) { | ||
const delay = 2 ** this.__retryCount * 1e3; | ||
setTimeout(async () => { | ||
if (this.token) { | ||
await this.connect({ token: this.token }); | ||
this.emit("reconnected"); | ||
this.__retryCount = 0; | ||
} | ||
}, delay); | ||
this.__retryCount++; | ||
} | ||
} | ||
}; | ||
const socketConnectionPromise = new Promise((resolve, reject) => { | ||
const handleSuccess = () => { | ||
logger.info("\u2705 Socket Connection Established"); | ||
handleRemoveListeners(); | ||
resolve(); | ||
}; | ||
const handleError = () => { | ||
logger.error("\u{1F534} Error While Connecting to the Socket"); | ||
handleRemoveListeners(); | ||
reject(new Error("\u274C Socket Connection Failed")); | ||
}; | ||
const handleRemoveListeners = () => { | ||
this.off("connected", handleSuccess); | ||
this.off("failed", handleError); | ||
this.off("closed", handleError); | ||
}; | ||
this.once("connected", handleSuccess); | ||
this.once("failed", handleError); | ||
this.once("closed", handleError); | ||
}); | ||
await socketConnectionPromise; | ||
return _Socket.__instance; | ||
}; | ||
/** | ||
* Closes the underlying socket connection, and clears all the event listeners and subscriptions to events as well as | ||
* any other information related to the connection. | ||
* @param code `{ ESocketCloseCode }` | ||
*/ | ||
close = (code) => { | ||
this.ws.removeEventListener("message", this.__handleIncomingMessage); | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F50C} Closing the connection, ${code} ${reason}`); | ||
if (code >= 3e3 && code <= 4999 || code === 1e3) { | ||
this.ws.close(code, reason); | ||
} else { | ||
this.ws.close(); | ||
} | ||
this.__unregisterSocketEvents(this.ws); | ||
this.__subscribedMap.clear(); | ||
this.__ws = null; | ||
this.connectionState = "closed"; | ||
logger.info("\u{1F50C} Socket Connection closed"); | ||
}; | ||
/** | ||
* Publish a message to the server using the socket connection based on some events/topics | ||
*/ | ||
publish = (event, data) => { | ||
const payload = JSON.stringify({ | ||
event, | ||
data: data || {} | ||
}); | ||
this.ws.send(payload); | ||
}; | ||
/** | ||
* Subscribe to a specific event/topic from the server | ||
*/ | ||
subscribe = (event, fn) => { | ||
if (this.__subscribedMap.has(event)) { | ||
logger.warn("\u26A0\uFE0F Overriding existing event handler"); | ||
} | ||
this.__subscribedMap.set(event, fn); | ||
}; | ||
/** | ||
* Get the config url for the socket connection based on the token and region | ||
* @param token Local Peer specific meeting token | ||
* @param region Local Peer specific region | ||
* @returns | ||
*/ | ||
async __getConfigUrl(token, region) { | ||
if (this.__ENDPOINT) { | ||
return this.__ENDPOINT; | ||
} | ||
const apiServerUrl = this.isLocalDev ? "http://localhost:8000/api/v1" : "https://apira.huddle01.com/api/v1"; | ||
const res = await fetch(`${apiServerUrl}/getSushiUrl`, { | ||
method: "GET", | ||
headers: { | ||
"Content-Type": "application/json", | ||
authorization: `Bearer ${token}` | ||
} | ||
}); | ||
if (!res.ok) { | ||
throw new Error("\u{1F534} Error While Fetching the Url"); | ||
} | ||
const { url } = await res.json(); | ||
this.__ENDPOINT = url.replace("https://", "wss://").replace("http://", "ws://"); | ||
const wssAddress = `${this.__ENDPOINT}/ws`; | ||
const wsAddress = `${wssAddress}?${[ | ||
`token=${token}`, | ||
`version=${2}`, | ||
`region=${region}` | ||
].join("&")}`; | ||
this.__ENDPOINT = wsAddress; | ||
return wsAddress; | ||
} | ||
/** | ||
* !Important | ||
* Handle the incoming message from the server based on the events recieved from the server and call the subscribed event handler | ||
*/ | ||
__handleIncomingMessage = (event) => { | ||
const { event: eventName, data } = JSON.parse(event.data); | ||
logger.info("\u{1F4E8} Incoming message event name: ", eventName); | ||
const fn = this.__subscribedMap.get(eventName); | ||
if (fn) { | ||
fn(data); | ||
} | ||
}; | ||
__handleSocketError = (ev) => { | ||
logger.error("Socket connection error", ev); | ||
this.connectionState = "failed"; | ||
}; | ||
/** | ||
* @description Handle the socket close event which is sent by the server | ||
* @param ev CloseEvent | ||
*/ | ||
__handleSocketClose = (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
const code = ev.code; | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F534} { Server }: Closing the connection, ${code} ${reason}`); | ||
this.connectionState = "closed"; | ||
this.close(code); | ||
}; | ||
/** | ||
* @description Handle the socket open event which is sent after the connection is established with the server | ||
* @param ev Event | ||
*/ | ||
__handleSocketOpen = (ev) => { | ||
logger.info("Socket Connection Open", ev); | ||
this.connectionState = "connected"; | ||
}; | ||
/** | ||
* @description Register the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__registerSocketEvents = (ws) => { | ||
ws.addEventListener("error", this.__handleSocketError); | ||
ws.addEventListener("close", this.__handleSocketClose); | ||
ws.addEventListener("open", this.__handleSocketOpen); | ||
}; | ||
/** | ||
* @description Unregister the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__unregisterSocketEvents = (ws) => { | ||
ws.removeEventListener("error", this.__handleSocketError); | ||
ws.removeEventListener("close", this.__handleSocketClose); | ||
ws.removeEventListener("open", this.__handleSocketOpen); | ||
}; | ||
}; | ||
var Socket_default = Socket; | ||
import { | ||
Socket_default | ||
} from "./chunk-PHWUOEBN.js"; | ||
import "./chunk-PYD4CES4.js"; | ||
import "./chunk-OYKTKRTB.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
Socket_default as default | ||
}; | ||
//# sourceMappingURL=Socket.js.map | ||
//# sourceMappingURL=Socket.js.map |
@@ -1,11 +0,18 @@ | ||
import * as mediasoup from "mediasoup-client"; | ||
import { EnhancedEventEmitter } from "./common-js/EnhancedEventEmitter"; | ||
import { TSDPInfo } from "types/dist/common.types"; | ||
import { TTransportType } from "types/dist"; | ||
import type { AppData, Producer } from "mediasoup-client/lib/types"; | ||
import Socket from "./Socket"; | ||
import Consumer from "./Consumer"; | ||
import { TConsumeResponseData } from "types/dist/mq/response.types"; | ||
import { EnhancedMap } from "./common-js/EnhancedMap"; | ||
export type TransportEvents = { | ||
import * as mediasoup from 'mediasoup-client'; | ||
import { EnhancedEventEmitter } from './common-js/EnhancedEventEmitter.js'; | ||
import { TSDPInfo } from 'types/dist/common.types'; | ||
import { TTransportType } from 'types/dist'; | ||
import { Producer, AppData } from 'mediasoup-client/lib/types'; | ||
import Socket from './Socket.js'; | ||
import Consumer from './Consumer.js'; | ||
import { TConsumeResponseData } from 'types/dist/mq/response.types'; | ||
import { EnhancedMap } from './common-js/EnhancedMap.js'; | ||
import 'types/dist/clientToSushiEvents.types'; | ||
import 'types/dist/sushiToClientEvents.types'; | ||
import 'types/dist/socket.types'; | ||
import './types/common.types.js'; | ||
import './RemotePeer.js'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
type TransportEvents = { | ||
connectTransportResponse: []; | ||
@@ -133,3 +140,3 @@ }; | ||
} | ||
export default Transport; | ||
//# sourceMappingURL=Transport.d.ts.map | ||
export { TransportEvents, Transport as default }; |
@@ -1,1684 +0,17 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// ../types/dist/socket.types.js | ||
var require_socket_types = __commonJS({ | ||
"../types/dist/socket.types.js"(exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SocketCloseReason = exports.ESocketCloseCode = void 0; | ||
var ESocketCloseCode2; | ||
(function(ESocketCloseCode3) { | ||
ESocketCloseCode3[ESocketCloseCode3["ABNORMAL_CLOSURE"] = 1006] = "ABNORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["NORMAL_CLOSURE"] = 1e3] = "NORMAL_CLOSURE"; | ||
ESocketCloseCode3[ESocketCloseCode3["BROWSER_TAB_CLOSE"] = 1001] = "BROWSER_TAB_CLOSE"; | ||
ESocketCloseCode3[ESocketCloseCode3["GOING_AWAY"] = 4001] = "GOING_AWAY"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_EXPIRED"] = 4002] = "CONNECTION_EXPIRED"; | ||
ESocketCloseCode3[ESocketCloseCode3["CONNECTION_ERROR"] = 4006] = "CONNECTION_ERROR"; | ||
ESocketCloseCode3[ESocketCloseCode3["ROOM_CLOSED"] = 4007] = "ROOM_CLOSED"; | ||
})(ESocketCloseCode2 || (exports.ESocketCloseCode = ESocketCloseCode2 = {})); | ||
exports.SocketCloseReason = { | ||
[ESocketCloseCode2.ROOM_CLOSED]: "ROOM_CLOSED", | ||
[ESocketCloseCode2.ABNORMAL_CLOSURE]: "ABNORMAL_CLOSURE", | ||
[ESocketCloseCode2.NORMAL_CLOSURE]: "NORMAL_CLOSURE", | ||
[ESocketCloseCode2.BROWSER_TAB_CLOSE]: "BROWSER_TAB_CLOSE", | ||
[ESocketCloseCode2.GOING_AWAY]: "GOING_AWAY", | ||
[ESocketCloseCode2.CONNECTION_ERROR]: "CONNECTION_ERROR", | ||
[ESocketCloseCode2.CONNECTION_EXPIRED]: "CONNECTION_EXPIRED" | ||
}; | ||
} | ||
}); | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
var EnhancedEventEmitter = class { | ||
emitter; | ||
constructor() { | ||
this.emitter = new import_events.EventEmitter(); | ||
this.emitter.setMaxListeners(Infinity); | ||
} | ||
on(eventName, listener) { | ||
this.emitter.on( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: need to override the type because default it's any[ and we cannot assign E[K] to any[] | ||
listener | ||
); | ||
return this; | ||
} | ||
off(eventName, listener) { | ||
this.emitter.off( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
listenerCount(eventName) { | ||
return this.emitter.listenerCount(eventName); | ||
} | ||
listeners(eventName) { | ||
return this.emitter.listeners(eventName); | ||
} | ||
emit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
safeEmit(eventName, ...args) { | ||
return this.emitter.emit(eventName, ...args); | ||
} | ||
once(eventName, listener) { | ||
this.emitter.once( | ||
eventName, | ||
// biome-ignore lint/suspicious/noExplicitAny: <explanation> | ||
listener | ||
); | ||
return this; | ||
} | ||
removeAllListeners(eventName) { | ||
if (eventName) { | ||
this.emitter.removeAllListeners(eventName); | ||
} else { | ||
this.emitter.removeAllListeners(); | ||
} | ||
return this; | ||
} | ||
}; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger4, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger4; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger4.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger4 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger4, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/Socket.ts | ||
var import_socket = __toESM(require_socket_types(), 1); | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
// src/Socket.ts | ||
var logger = mainLogger.createSubLogger("Socket.ts"); | ||
var Socket = class _Socket extends EnhancedEventEmitter { | ||
/** | ||
* Socket Instance, Singleton class | ||
*/ | ||
static __instance; | ||
__retryCount = 0; | ||
/** | ||
* Current connection state of the socket connection | ||
*/ | ||
__connectionState = "uninitialized"; | ||
/** | ||
* Underlying WebSocket connection, until we dont call Socket.connect(); this will be null | ||
*/ | ||
__ws = null; | ||
/** | ||
* Map of all the subscribed events/topics for the socket connection | ||
*/ | ||
__subscribedMap = /* @__PURE__ */ new Map(); | ||
/** | ||
* Region of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
__region = null; | ||
/** | ||
* Endpoint of the socket server, this is fetched from the API server | ||
*/ | ||
__ENDPOINT = null; | ||
isLocalDev = false; | ||
/** | ||
* Token of the current socket connection, specific to the Local Peer who joined the meeting | ||
*/ | ||
token = null; | ||
/** | ||
* Returns the underlying WebSocket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
get ws() { | ||
if (!this.__ws) { | ||
throw new Error("\u{1F534} Socket Not Initialised"); | ||
} | ||
return this.__ws; | ||
} | ||
/** | ||
* Getter for the region of the current socket connection | ||
*/ | ||
get region() { | ||
return this.__region; | ||
} | ||
/** | ||
* Returns the current connection state of the socket connection | ||
*/ | ||
get connectionState() { | ||
return this.__connectionState; | ||
} | ||
/** | ||
* Returns true if the socket connection is connected | ||
*/ | ||
get connected() { | ||
return this.ws.OPEN === 1 && this.connectionState === "connected"; | ||
} | ||
/** | ||
* Returns true if the socket connection is connecting | ||
*/ | ||
get connecting() { | ||
return this.ws.CONNECTING === 0 && this.connectionState === "connecting"; | ||
} | ||
/** | ||
* Returns true if the socket connection is closed | ||
*/ | ||
get closed() { | ||
return this.ws.CLOSED === 3 || this.ws.CLOSING === 2; | ||
} | ||
/** | ||
* Sets the current connection state of the socket connection | ||
*/ | ||
set connectionState(state) { | ||
logger.info(`Connection state changed to ${state}`); | ||
if (this.__connectionState !== state) { | ||
this.emit(state); | ||
} | ||
this.__connectionState = state; | ||
} | ||
/** | ||
* Update the token for this socket | ||
* @throws `Error` if the token is already set | ||
*/ | ||
setToken(token) { | ||
if (this.token) { | ||
throw new Error("\u{1F534} Token Already Set"); | ||
} | ||
this.token = token; | ||
this.emit("token-updated", token); | ||
} | ||
/** | ||
* Set a new region for the socket connection | ||
*/ | ||
setRegion(region) { | ||
this.__region = region; | ||
this.emit("region-updated", region); | ||
} | ||
/** | ||
* Initializes the socket Manager and returns the instance of the socket connection if already initialized | ||
* you need to call connect method to connect to the server | ||
* @param data | ||
* @returns | ||
*/ | ||
static init() { | ||
if (!this.__instance) { | ||
this.__instance = new _Socket(); | ||
} | ||
return this.__instance; | ||
} | ||
/** | ||
* Returns the instance of the socket connection, throws an error if the connection is not initialized | ||
* @throws `Error` if the connection is not initialized | ||
*/ | ||
static getInstance() { | ||
if (!_Socket.__instance) { | ||
throw new Error( | ||
"\u{1F534} Socket Instance Not Initialised, You are trying to do something which is not possible" | ||
); | ||
} | ||
return _Socket.__instance; | ||
} | ||
constructor() { | ||
super(); | ||
} | ||
/** | ||
* | ||
*/ | ||
__getRegion = async () => { | ||
const resp = await fetch( | ||
"https://shinigami.huddle01.com/api/get-geolocation" | ||
); | ||
const data = await resp?.json(); | ||
const geolocationdata = GeolocationSchema.safeParse(data); | ||
if (!geolocationdata.success) { | ||
throw new Error("\u{1F534} Error While Finding the Region to connect to"); | ||
} | ||
const region = geolocationdata.data.globalRegion; | ||
return region; | ||
}; | ||
enableLocalDev = () => { | ||
this.isLocalDev = true; | ||
}; | ||
/** | ||
* Connect to the socket server using the token | ||
* @param data - `{ token: string }` | ||
*/ | ||
connect = async (data) => { | ||
if (!this.token) { | ||
this.setToken(data.token); | ||
} | ||
if (this.connectionState === "connected") { | ||
logger.error("\u{1F534} Socket Already Connected"); | ||
return _Socket.__instance; | ||
} | ||
if (this.connectionState === "connecting") { | ||
logger.error("\u{1F534} Socket Connecting"); | ||
return _Socket.__instance; | ||
} | ||
if (this.__ws) { | ||
logger.error("\u{1F534} Socket Already Initialized"); | ||
return _Socket.__instance; | ||
} | ||
logger.info("\u{1F50C} Connecting to the socket server"); | ||
if (this.connectionState === "closed") { | ||
logger.info( | ||
"\u{1F50C} Socket connection was closed, creating a new socket connection" | ||
); | ||
this.emit("reconnecting"); | ||
} | ||
if (!this.__region) { | ||
const region = await this.__getRegion(); | ||
this.__region = region; | ||
} | ||
const url = await this.__getConfigUrl(data.token, this.__region); | ||
this.__ws = new WebSocket(url); | ||
this.__ws.onerror = (ev) => { | ||
logger.error(ev); | ||
}; | ||
this.connectionState = "connecting"; | ||
this.__ws.addEventListener("message", this.__handleIncomingMessage); | ||
this.__registerSocketEvents(this.ws); | ||
this.__ws.onclose = async (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
if (this.__retryCount < 5) { | ||
if (ev.code === import_socket.ESocketCloseCode.ABNORMAL_CLOSURE) { | ||
const delay = 2 ** this.__retryCount * 1e3; | ||
setTimeout(async () => { | ||
if (this.token) { | ||
await this.connect({ token: this.token }); | ||
this.emit("reconnected"); | ||
this.__retryCount = 0; | ||
} | ||
}, delay); | ||
this.__retryCount++; | ||
} | ||
} | ||
}; | ||
const socketConnectionPromise = new Promise((resolve, reject) => { | ||
const handleSuccess = () => { | ||
logger.info("\u2705 Socket Connection Established"); | ||
handleRemoveListeners(); | ||
resolve(); | ||
}; | ||
const handleError = () => { | ||
logger.error("\u{1F534} Error While Connecting to the Socket"); | ||
handleRemoveListeners(); | ||
reject(new Error("\u274C Socket Connection Failed")); | ||
}; | ||
const handleRemoveListeners = () => { | ||
this.off("connected", handleSuccess); | ||
this.off("failed", handleError); | ||
this.off("closed", handleError); | ||
}; | ||
this.once("connected", handleSuccess); | ||
this.once("failed", handleError); | ||
this.once("closed", handleError); | ||
}); | ||
await socketConnectionPromise; | ||
return _Socket.__instance; | ||
}; | ||
/** | ||
* Closes the underlying socket connection, and clears all the event listeners and subscriptions to events as well as | ||
* any other information related to the connection. | ||
* @param code `{ ESocketCloseCode }` | ||
*/ | ||
close = (code) => { | ||
this.ws.removeEventListener("message", this.__handleIncomingMessage); | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F50C} Closing the connection, ${code} ${reason}`); | ||
if (code >= 3e3 && code <= 4999 || code === 1e3) { | ||
this.ws.close(code, reason); | ||
} else { | ||
this.ws.close(); | ||
} | ||
this.__unregisterSocketEvents(this.ws); | ||
this.__subscribedMap.clear(); | ||
this.__ws = null; | ||
this.connectionState = "closed"; | ||
logger.info("\u{1F50C} Socket Connection closed"); | ||
}; | ||
/** | ||
* Publish a message to the server using the socket connection based on some events/topics | ||
*/ | ||
publish = (event, data) => { | ||
const payload = JSON.stringify({ | ||
event, | ||
data: data || {} | ||
}); | ||
this.ws.send(payload); | ||
}; | ||
/** | ||
* Subscribe to a specific event/topic from the server | ||
*/ | ||
subscribe = (event, fn) => { | ||
if (this.__subscribedMap.has(event)) { | ||
logger.warn("\u26A0\uFE0F Overriding existing event handler"); | ||
} | ||
this.__subscribedMap.set(event, fn); | ||
}; | ||
/** | ||
* Get the config url for the socket connection based on the token and region | ||
* @param token Local Peer specific meeting token | ||
* @param region Local Peer specific region | ||
* @returns | ||
*/ | ||
async __getConfigUrl(token, region) { | ||
if (this.__ENDPOINT) { | ||
return this.__ENDPOINT; | ||
} | ||
const apiServerUrl = this.isLocalDev ? "http://localhost:8000/api/v1" : "https://apira.huddle01.com/api/v1"; | ||
const res = await fetch(`${apiServerUrl}/getSushiUrl`, { | ||
method: "GET", | ||
headers: { | ||
"Content-Type": "application/json", | ||
authorization: `Bearer ${token}` | ||
} | ||
}); | ||
if (!res.ok) { | ||
throw new Error("\u{1F534} Error While Fetching the Url"); | ||
} | ||
const { url } = await res.json(); | ||
this.__ENDPOINT = url.replace("https://", "wss://").replace("http://", "ws://"); | ||
const wssAddress = `${this.__ENDPOINT}/ws`; | ||
const wsAddress = `${wssAddress}?${[ | ||
`token=${token}`, | ||
`version=${2}`, | ||
`region=${region}` | ||
].join("&")}`; | ||
this.__ENDPOINT = wsAddress; | ||
return wsAddress; | ||
} | ||
/** | ||
* !Important | ||
* Handle the incoming message from the server based on the events recieved from the server and call the subscribed event handler | ||
*/ | ||
__handleIncomingMessage = (event) => { | ||
const { event: eventName, data } = JSON.parse(event.data); | ||
logger.info("\u{1F4E8} Incoming message event name: ", eventName); | ||
const fn = this.__subscribedMap.get(eventName); | ||
if (fn) { | ||
fn(data); | ||
} | ||
}; | ||
__handleSocketError = (ev) => { | ||
logger.error("Socket connection error", ev); | ||
this.connectionState = "failed"; | ||
}; | ||
/** | ||
* @description Handle the socket close event which is sent by the server | ||
* @param ev CloseEvent | ||
*/ | ||
__handleSocketClose = (ev) => { | ||
logger.info("Socket connection closed", ev); | ||
const code = ev.code; | ||
const reason = import_socket.SocketCloseReason[code]; | ||
logger.info(`\u{1F534} { Server }: Closing the connection, ${code} ${reason}`); | ||
this.connectionState = "closed"; | ||
this.close(code); | ||
}; | ||
/** | ||
* @description Handle the socket open event which is sent after the connection is established with the server | ||
* @param ev Event | ||
*/ | ||
__handleSocketOpen = (ev) => { | ||
logger.info("Socket Connection Open", ev); | ||
this.connectionState = "connected"; | ||
}; | ||
/** | ||
* @description Register the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__registerSocketEvents = (ws) => { | ||
ws.addEventListener("error", this.__handleSocketError); | ||
ws.addEventListener("close", this.__handleSocketClose); | ||
ws.addEventListener("open", this.__handleSocketOpen); | ||
}; | ||
/** | ||
* @description Unregister the socket events | ||
* @param ws WebSocket | ||
*/ | ||
__unregisterSocketEvents = (ws) => { | ||
ws.removeEventListener("error", this.__handleSocketError); | ||
ws.removeEventListener("close", this.__handleSocketClose); | ||
ws.removeEventListener("open", this.__handleSocketOpen); | ||
}; | ||
}; | ||
var Socket_default = Socket; | ||
// src/Consumer.ts | ||
var logger2 = mainLogger.createSubLogger("Consumer"); | ||
var Consumer = class _Consumer extends EnhancedEventEmitter { | ||
/** | ||
* ProducerId of the Consumer, this is the id of the Media Entity which is responsible for producing the media in the room. | ||
*/ | ||
producerId; | ||
/** | ||
* PeerId of the Producer, this is the peerId of the Peer which is responsible for producing the media in the room. | ||
*/ | ||
producerPeerId; | ||
/** | ||
* Label of the Consumer, this is the label of the Media Entity which is responsible for producing the media in the room. | ||
*/ | ||
label; | ||
/** | ||
* Flag to check if the Consumer is consuming a media, if `true` then the Consumer is consuming a media. | ||
* | ||
* @default false | ||
*/ | ||
__consuming = false; | ||
/** | ||
* Flag to check if the Consumer is consuming a media, if `true` then the Consumer is consuming a media. | ||
* | ||
* @default false | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get consuming() { | ||
return this.__consuming; | ||
} | ||
/** | ||
* mediasoupConsumer instance, this is the instance of the mediasoupConsumer which is responsible for consuming the media in the room. | ||
* @remarks This is a private property and should not be accessed directly. | ||
* | ||
* Every Consumer is created without a mediasoupConsumer, when the peer starts to consume the media, the mediasoupConsumer is set. | ||
*/ | ||
#mediasoupConsumer = null; | ||
/** | ||
* Getter for the id for the mediaSoupConsumer, which is also the id of the Consumer for the RemotePeer. | ||
*/ | ||
get id() { | ||
return this.#mediasoupConsumer?.id; | ||
} | ||
/** | ||
* | ||
* @param consumer Sets the mediasoupConsumer for the Consumer | ||
*/ | ||
setMediaSoupConsumer(consumer) { | ||
if (this.consuming) { | ||
throw new Error("Consumer is already consuming"); | ||
} | ||
if (this.#mediasoupConsumer) { | ||
throw new Error("Consumer already has a mediasoupConsumer"); | ||
} | ||
this.#mediasoupConsumer = consumer; | ||
this.__consuming = true; | ||
} | ||
/** | ||
* Getter for the mediasoupConsumer id, which is also the id of the Consumer for the RemotePeer. it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get consumerId() { | ||
return this.#mediasoupConsumer?.id; | ||
} | ||
/** | ||
* Get the Track of the Consumer, it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get track() { | ||
return this.#mediasoupConsumer?.track; | ||
} | ||
/** | ||
* Get the kind of the Consumer, it is only available when the Consumer is consuming a media. | ||
* | ||
* @remarks | ||
* There are two ways a Peer can Consume any media produced in the room. | ||
* - Automatically consume the media streams of the remote peers by setting the `autoConsume` flag to `true` in the `Room`. | ||
* - Using the `consume` function inside the `LocalPeer` instance. `localPeer.consume({ peerId, label: "video", appData: {} });` | ||
*/ | ||
get kind() { | ||
return this.#mediasoupConsumer?.kind; | ||
} | ||
/** | ||
* If the Consumer is paused, it is only available when the Consumer is consuming a media. | ||
* | ||
* if paused the user is not consuming any media for the given producerId. | ||
*/ | ||
get paused() { | ||
return this.#mediasoupConsumer?.paused; | ||
} | ||
/** | ||
* AppData of the Consumer, it is only available when the Consumer is consuming a media. | ||
*/ | ||
get appData() { | ||
return this.#mediasoupConsumer?.appData; | ||
} | ||
/** | ||
* State of a Consumer is defined by the following: | ||
* - `playable` - The Consumer is ready to play the media. | ||
* - `unavailable` - The Consumer is not available to play the media. This can happen when the Consumer is closed or paused. | ||
* - `paused` - The Consumer is paused and is not playing the media. | ||
* - `available` - The Consumer is available to play the media. Peer can consume the media by using `localPeer.consume({ peerId, label: "video", appData: {} });` after which the state will change to `playable`. | ||
*/ | ||
get state() { | ||
if (this?.consuming) | ||
return "playable"; | ||
if (this?.paused) | ||
return "paused"; | ||
return "available"; | ||
} | ||
/** | ||
* Get the stats of the Consumer, it is only available when the Consumer is consuming a media. | ||
* It generates the stats for the Consumer using the `getStats` method of the mediasoupConsumer. | ||
* @returns - RTCStatsReport | null | ||
*/ | ||
getStats = async () => { | ||
const stats = await this.#mediasoupConsumer?.getStats(); | ||
return stats; | ||
}; | ||
/** | ||
* Resume the consumer, if the state of the consumer is `paused`. | ||
*/ | ||
resume = () => { | ||
this.#mediasoupConsumer?.resume(); | ||
}; | ||
/** | ||
* Removes all the eventListeners attached to the Consumer. | ||
*/ | ||
removeListeners = () => { | ||
this.removeAllListeners(); | ||
}; | ||
/** | ||
* Creates a Consumer instance. This is a static method and should be called using `Consumer.create({ producerPeerId, producerId, label })`. | ||
*/ | ||
static create = (data) => { | ||
try { | ||
const consumer = new _Consumer(data); | ||
return consumer; | ||
} catch (error) { | ||
logger2.error(error); | ||
throw new Error("\u274C Error creating Consumer"); | ||
} | ||
}; | ||
close = () => { | ||
try { | ||
this.#mediasoupConsumer?.close(); | ||
this.__consuming = false; | ||
this.emit("closed"); | ||
this.removeAllListeners(); | ||
} catch (error) { | ||
logger2.error("\u274C Error Closing Consumer"); | ||
logger2.error({ | ||
consumerId: this.consumerId, | ||
producerId: this.producerId | ||
}); | ||
} | ||
}; | ||
constructor(data) { | ||
super(); | ||
this.producerPeerId = data.producerPeerId; | ||
this.producerId = data.producerId; | ||
this.label = data.label; | ||
} | ||
}; | ||
var Consumer_default = Consumer; | ||
// src/helpers/index.ts | ||
var getMediaStreamKind = (stream) => { | ||
let kind = null; | ||
const tracks = stream.getTracks(); | ||
for (const track of tracks) { | ||
if (track.kind === "audio") { | ||
kind = "audio"; | ||
break; | ||
} else if (track.kind === "video") { | ||
kind = "video"; | ||
break; | ||
} | ||
} | ||
if (!kind) { | ||
throw new Error("Stream Kind Not Found"); | ||
} | ||
return kind; | ||
}; | ||
var getMediaTrack = (data) => { | ||
const { stream, kind } = data; | ||
const tracks = stream.getTracks(); | ||
for (const track of tracks) { | ||
if (track.kind === kind) { | ||
return track; | ||
} | ||
} | ||
throw new Error("Track Not Found"); | ||
}; | ||
// src/constants/rtpConstants.ts | ||
var WEBCAM_SIMULCAST_ENCODINGS = [ | ||
{ | ||
scaleResolutionDownBy: 4, | ||
maxBitrate: 3e5, | ||
// 300kbps | ||
rid: "r0", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 15 | ||
}, | ||
{ | ||
scaleResolutionDownBy: 2, | ||
maxBitrate: 6e5, | ||
// 600kbps | ||
rid: "r1", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 30 | ||
}, | ||
{ | ||
scaleResolutionDownBy: 1, | ||
maxBitrate: 9e6, | ||
// 900kbps | ||
rid: "r2", | ||
scalabilityMode: "S1T3", | ||
maxFramerate: 30 | ||
} | ||
]; | ||
var SCREEN_SHARING_SVC_ENCODINGS = [ | ||
{ scalabilityMode: "S3T3", dtx: true } | ||
]; | ||
var encodingViaMediaType = { | ||
video: WEBCAM_SIMULCAST_ENCODINGS, | ||
"screen-video": SCREEN_SHARING_SVC_ENCODINGS, | ||
audio: [{ maxBitrate: 128e3 }] | ||
}; | ||
var codecOptionsViaKind = { | ||
audio: { opusStereo: true, opusFec: true, opusDtx: true }, | ||
video: { videoGoogleStartBitrate: 1e3 } | ||
}; | ||
// src/common-js/EnhancedMap.ts | ||
var defaultCompareFn = (a, b) => { | ||
if (a < b) { | ||
return false; | ||
} | ||
if (a > b) { | ||
return true; | ||
} | ||
return false; | ||
}; | ||
var EnhancedMap = class { | ||
map; | ||
compareFn; | ||
getKey = (a, b) => { | ||
const key = this.compareFn(a, b) ? `${a}_${b}` : `${b}_${a}`; | ||
return key; | ||
}; | ||
get size() { | ||
return this.map.size; | ||
} | ||
get = (a, b) => { | ||
const key = this.getKey(a, b); | ||
const value = this.map.get(key); | ||
return value; | ||
}; | ||
set = (a, b, value) => { | ||
const key = this.getKey(a, b); | ||
this.map.set(key, value); | ||
return value; | ||
}; | ||
delete = (a, b) => { | ||
const key = this.getKey(a, b); | ||
return this.map.delete(key); | ||
}; | ||
clear = () => { | ||
this.map.clear(); | ||
}; | ||
constructor(data) { | ||
this.map = /* @__PURE__ */ new Map(); | ||
if (data.compareFn) | ||
this.compareFn = data.compareFn; | ||
else | ||
this.compareFn = defaultCompareFn; | ||
} | ||
}; | ||
// src/Transport.ts | ||
var logger3 = mainLogger.createSubLogger("Transport"); | ||
var Transport = class _Transport extends EnhancedEventEmitter { | ||
/** | ||
* Peer Id, which handles the peer id. | ||
*/ | ||
peerId; | ||
/** | ||
* MediaSoup Device Instance, which handles the browsers or mobile device init. | ||
*/ | ||
__device; | ||
/** | ||
* MediaSoup Transport Instance, which handles the media transport. | ||
*/ | ||
__mediasoupTransport; | ||
/** | ||
* Socket Instance, which handles the socket connection. | ||
*/ | ||
__socket; | ||
/** | ||
* Map of Producers, which handles the producers. ( Sending out Media Streams ) | ||
* | ||
* `Mapped with {producerId => Producer}` | ||
*/ | ||
__producers = /* @__PURE__ */ new Map(); | ||
/** | ||
* Map of Consumers, which handles the consumers. ( Receiving Media Streams ) | ||
* | ||
* `Mapped with {label:RemotePeerId => Consumer}` | ||
*/ | ||
__consumers = new EnhancedMap({}); | ||
/** | ||
* Map of Identifiers to Producer Ids, which handles the mapping of identifiers to producer ids. | ||
* | ||
* `identifiers` are the unique identifiers for the stream, which is used to identify the stream. | ||
*/ | ||
labelToProducerId = /* @__PURE__ */ new Map(); | ||
/** | ||
* Transport Type, which handles the transport type. ( `send | recv` ) | ||
*/ | ||
transportType; | ||
/** | ||
* Pending Producer Tasks, which handles the pending producer tasks. | ||
* callback function is necessary to be called when the producer is created | ||
* on the server as well as on the client side. | ||
*/ | ||
__pendingProducerTasks = /* @__PURE__ */ new Map(); | ||
/** | ||
* Debounce to handle concurrent request to restart Ice. Waits for some time before sending | ||
* more requests to restart ice. | ||
*/ | ||
__iceRestartDebounce = false; | ||
/** | ||
* Connection State, which handles the connection state. | ||
* | ||
* - `connected` - Transport is connected. | ||
* - `disconnected` - Transport is disconnected. | ||
* - `failed` - Transport connection failed. | ||
* - `reconnecting` - Transport is reconnecting. | ||
* - `connecting` - Transport is connecting. | ||
*/ | ||
connectionState = "disconnected"; | ||
get device() { | ||
return this.__device; | ||
} | ||
get mediasoupTransport() { | ||
return this.__mediasoupTransport; | ||
} | ||
get producers() { | ||
return this.__producers; | ||
} | ||
get consumers() { | ||
return this.__consumers; | ||
} | ||
getProducerById(producerId) { | ||
const producer = this.__producers.get(producerId); | ||
if (!producer) | ||
throw new Error("Transport Not Initialized"); | ||
return producer; | ||
} | ||
removeProducerById(producerId) { | ||
logger3.info(`\u{1F514} Removing Producer, id: ${producerId}`); | ||
return this.__producers.delete(producerId); | ||
} | ||
/** | ||
* Get the consumer by label and peerId | ||
* @param data | ||
* @returns Consumer | null; Returns null if consumer is not found | ||
*/ | ||
getConsumer = (data) => { | ||
const consumer = this.__consumers.get(data.label, data.peerId); | ||
if (!consumer) | ||
return null; | ||
return consumer; | ||
}; | ||
get transport() { | ||
const transport = this.__mediasoupTransport; | ||
if (!transport) | ||
throw new Error("Transport Not Initialized"); | ||
return transport; | ||
} | ||
addPendingProducerTask = (data) => { | ||
const key = `${data.peerId}-${data.label}`; | ||
logger3.info("\u{1F514} Adding Pending Producer Task, key", key); | ||
if (this.__pendingProducerTasks.has(key)) { | ||
logger3.debug("\u{1F534} Producer Creation is Pending for key: ", key); | ||
return; | ||
} | ||
this.__pendingProducerTasks.set(key, data.callback); | ||
}; | ||
resolvePendingProducerTask = (data) => { | ||
const key = `${data.peerId}-${data.label}`; | ||
logger3.info("\u{1F514} Resolving Pending Producer Task, key", key); | ||
const callback = this.__pendingProducerTasks.get(key); | ||
if (!callback) { | ||
logger3.error("\u{1F534} Producer Creation is not Pending for key: ", key); | ||
return; | ||
} | ||
callback({ id: data.id }); | ||
this.__pendingProducerTasks.delete(key); | ||
}; | ||
static create = (data) => { | ||
try { | ||
logger3.info( | ||
`\u{1F514} Creating Client Side Transport, type: ${data.transportType}` | ||
); | ||
const { transportType, device } = data; | ||
const payload = { | ||
id: data.sdpInfo.id, | ||
iceParameters: data.sdpInfo.iceParameters, | ||
iceCandidates: data.sdpInfo.iceCandidates, | ||
iceServers: data.iceServers, | ||
dtlsParameters: data.sdpInfo.dtlsParameters, | ||
sctpParameters: data.sdpInfo.sctpParameters, | ||
proprietaryConstraints: {}, | ||
appData: {} | ||
}; | ||
const mediasoupTransport = transportType === "send" ? device.createSendTransport(payload) : device.createRecvTransport(payload); | ||
const transport = new _Transport({ | ||
peerId: data.peerId, | ||
device: data.device, | ||
transportType: data.transportType, | ||
mediasoupTransport | ||
}); | ||
return transport; | ||
} catch (error) { | ||
logger3.error(`\u274C Transport.create(), type: ${data.transportType}`); | ||
logger3.error(error); | ||
throw error; | ||
} | ||
}; | ||
constructor(data) { | ||
super(); | ||
this.__socket = Socket_default.getInstance(); | ||
this.__device = data.device; | ||
this.transportType = data.transportType; | ||
this.__mediasoupTransport = data.mediasoupTransport; | ||
this.__mediasoupTransport.on("connectionstatechange", (state) => { | ||
this.__connectionStateChangeHandler(state); | ||
}); | ||
this.peerId = data.peerId; | ||
this.__listenTransportConnect(); | ||
this.__listenTransportProduce(); | ||
logger3.info(`\u2705 ${data.transportType} Transport Initialized`); | ||
} | ||
__listenTransportConnect = () => { | ||
this.__mediasoupTransport.on( | ||
"connect", | ||
({ dtlsParameters }, callback, errback) => { | ||
logger3.info("\u{1F514} Transport Connect Event Called"); | ||
try { | ||
this.once("connectTransportResponse", () => { | ||
callback(); | ||
}); | ||
this.__socket.publish("connectTransport", { | ||
dtlsParameters, | ||
transportType: this.transportType | ||
}); | ||
} catch (error) { | ||
logger3.error("\u274C Error Transport Connect Event"); | ||
logger3.error(error); | ||
errback(error); | ||
} | ||
} | ||
); | ||
}; | ||
__listenTransportProduce = () => { | ||
this.__mediasoupTransport.on( | ||
"produce", | ||
async ({ kind, rtpParameters, appData }, callback, errback) => { | ||
logger3.info(`\u{1F514} ${this.transportType} Produce Event Called`); | ||
try { | ||
const label = appData?.label; | ||
if (!label) | ||
throw new Error("\u{1F534} Stream Identifier Not Found"); | ||
this.__socket.publish("produce", { | ||
createProducerData: { | ||
rtpParameters, | ||
kind, | ||
label, | ||
appData, | ||
paused: false | ||
} | ||
}); | ||
this.addPendingProducerTask({ | ||
peerId: this.peerId, | ||
label, | ||
callback | ||
}); | ||
} catch (error) { | ||
logger3.error("\u274C Error Transport Produce Event"); | ||
logger3.error(error); | ||
errback(error); | ||
} | ||
} | ||
); | ||
}; | ||
produce = async (data) => { | ||
const kind = getMediaStreamKind(data.stream); | ||
const track = getMediaTrack({ stream: data.stream, kind }); | ||
logger3.info(`\u{1F514} Produce Called for kind: ${kind}, label: ${data.label}`); | ||
try { | ||
if (!this.__device.loaded) { | ||
throw new Error("Device Not Loaded"); | ||
} | ||
if (!this.__device.rtpCapabilities.codecs) { | ||
throw new Error("No Codecs Found"); | ||
} | ||
if (!this.__device.canProduce(kind)) { | ||
throw new Error(`Device Cannot produce ${kind}`); | ||
} | ||
if (this.transportType !== "send") { | ||
throw new Error(`Cannot produce on ${this.transportType} transport`); | ||
} | ||
const codecs = this.__device.rtpCapabilities?.codecs; | ||
if (!codecs) { | ||
throw new Error("\u274C Device RTP Capabilities not found"); | ||
} | ||
const codecViaMediaType = { | ||
video: codecs.find( | ||
(codec) => codec.mimeType.toLowerCase() === "video/vp8" | ||
), | ||
"screen-video": codecs.find( | ||
(codec) => codec.mimeType.toLowerCase() === "video/vp8" | ||
), | ||
audio: void 0 | ||
}; | ||
const mediaType = data.label === "screen-video" ? "screen-video" : kind; | ||
const mediasoupProducer = await this.__mediasoupTransport.produce({ | ||
track, | ||
encodings: encodingViaMediaType[mediaType], | ||
codecOptions: codecOptionsViaKind[kind], | ||
codec: codecViaMediaType[mediaType], | ||
stopTracks: data.stopTrackOnClose, | ||
zeroRtpOnPause: true, | ||
disableTrackOnPause: true, | ||
appData: { | ||
...data.appData, | ||
producerPeerId: this.peerId | ||
} | ||
}); | ||
this.__producers.set(mediasoupProducer.id, mediasoupProducer); | ||
this.labelToProducerId.set(data.label, mediasoupProducer.id); | ||
return mediasoupProducer; | ||
} catch (error) { | ||
logger3.error("\u274C Error Transport Produce Event"); | ||
logger3.error(error); | ||
throw error; | ||
} | ||
}; | ||
consume = async (data) => { | ||
const { label, producerPeerId, kind } = data; | ||
logger3.info( | ||
`\u{1F514} Consume Called for ${kind} from remote peer ${producerPeerId}` | ||
); | ||
try { | ||
if (this.transportType !== "recv") { | ||
throw new Error(`Cannot consume on ${this.transportType} transport`); | ||
} | ||
const consumer = Consumer_default.create({ | ||
producerId: data.producerId, | ||
producerPeerId, | ||
label | ||
}); | ||
if (!this.__device.loaded) { | ||
throw new Error("Device Not Loaded"); | ||
} | ||
if (!this.__device.rtpCapabilities.codecs) { | ||
throw new Error("No Codecs Found"); | ||
} | ||
const mediaSoupConsumer = await this.__mediasoupTransport.consume({ | ||
id: data.consumerId, | ||
rtpParameters: data.rtpParameters, | ||
kind: data.kind, | ||
producerId: data.producerId, | ||
appData: data.appData | ||
}); | ||
mediaSoupConsumer.on("transportclose", () => { | ||
this.closeConsumer({ label, peerId: producerPeerId }); | ||
}); | ||
mediaSoupConsumer.on("trackended", () => { | ||
this.closeConsumer({ label, peerId: producerPeerId }); | ||
}); | ||
this.__consumers.set(consumer.label, consumer.producerPeerId, consumer); | ||
consumer.setMediaSoupConsumer(mediaSoupConsumer); | ||
return { consumer, mediaSoupConsumer }; | ||
} catch (error) { | ||
logger3.error(error); | ||
throw new Error("\u274C Error calling consume()"); | ||
} | ||
}; | ||
closeConsumer = (data) => { | ||
try { | ||
const consumer = this.getConsumer(data); | ||
if (!consumer) { | ||
throw new Error( | ||
`\u274C Consumer not found label: ${data.label}, peerId: ${data.peerId}` | ||
); | ||
} | ||
consumer.close(); | ||
this.__consumers.delete(data.label, data.peerId); | ||
consumer.emit("closed"); | ||
consumer.removeListeners(); | ||
} catch (error) { | ||
logger3.error("\u274C Error closing consumer"); | ||
logger3.error(error); | ||
} | ||
}; | ||
close = async (data) => { | ||
try { | ||
if (data.retries <= 0) { | ||
logger3.error("\u274C Error closing transport, max retries exceeded"); | ||
return; | ||
} | ||
logger3.info(`\u{1F514} Closing ${this.transportType} transport`); | ||
this.__mediasoupTransport.close(); | ||
logger3.info(`\u2705 ${this.transportType} transport closed`); | ||
} catch (error) { | ||
logger3.error("\u274C Error closing transport"); | ||
logger3.error(error); | ||
logger3.error("Retrying..."); | ||
this.close({ retries: data.retries - 1 }); | ||
} | ||
}; | ||
__connectionStateChangeHandler = (state) => { | ||
try { | ||
logger3.debug( | ||
`\u{1F514} ${this.transportType} Transport Connection State Changed, state: ${state}` | ||
); | ||
const transportType = this.transportType; | ||
const handler = { | ||
connected: () => { | ||
logger3.debug(`\u{1F514} ${this.transportType} Transport Connected`); | ||
}, | ||
disconnected: () => { | ||
if (this.__iceRestartDebounce) | ||
return; | ||
this.__iceRestartDebounce = true; | ||
this.__socket.publish("restartTransportIce", { | ||
transportId: this.__mediasoupTransport.id, | ||
transportType | ||
}); | ||
setTimeout(() => { | ||
this.__iceRestartDebounce = false; | ||
}, 3e3); | ||
logger3.debug(`\u{1F514} ${transportType} Transport Disconnected`); | ||
}, | ||
failed: () => { | ||
logger3.debug(`\u{1F514} ${transportType} Transport Failed`); | ||
}, | ||
connecting: () => { | ||
logger3.debug(`\u{1F514} ${transportType} Transport Connecting`); | ||
}, | ||
closed: () => { | ||
logger3.debug(`\u{1F514} ${transportType} Transport closed`); | ||
}, | ||
new: () => { | ||
logger3.debug(`\u{1F514} ${transportType} Transport new`); | ||
} | ||
}; | ||
handler[state](); | ||
} catch (err) { | ||
logger3.error("\u274C Error in connectionStateChangeHandler"); | ||
logger3.error(err); | ||
} | ||
}; | ||
}; | ||
var Transport_default = Transport; | ||
import { | ||
Transport_default | ||
} from "./chunk-HPL2MDFQ.js"; | ||
import "./chunk-7PO7E25R.js"; | ||
import "./chunk-OZOR2RLF.js"; | ||
import "./chunk-N24AG534.js"; | ||
import "./chunk-UBA4U2PP.js"; | ||
import "./chunk-PHWUOEBN.js"; | ||
import "./chunk-PYD4CES4.js"; | ||
import "./chunk-OYKTKRTB.js"; | ||
import "./chunk-YOQRRMW7.js"; | ||
import "./chunk-NZZLDVRO.js"; | ||
import "./chunk-UXIASGQL.js"; | ||
export { | ||
Transport_default as default | ||
}; | ||
//# sourceMappingURL=Transport.js.map | ||
//# sourceMappingURL=Transport.js.map |
@@ -1,14 +0,12 @@ | ||
import RemotePeer from "../RemotePeer"; | ||
export type TPromiseResponse<T = string> = { | ||
success: boolean; | ||
data?: T; | ||
error?: { | ||
message: string; | ||
code?: number; | ||
}; | ||
}; | ||
export type ConnectionState = "uninitialized" | "connecting" | "connected" | "failed" | "closed"; | ||
export type TNewPeerJoined = { | ||
import RemotePeer from '../RemotePeer.js'; | ||
import '../Consumer.js'; | ||
import 'mediasoup-client/lib/types'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
import '../common-js/EnhancedEventEmitter.js'; | ||
type ConnectionState = "uninitialized" | "connecting" | "connected" | "failed" | "closed"; | ||
type NewPeerJoined = { | ||
peer: RemotePeer; | ||
}; | ||
//# sourceMappingURL=common.types.d.ts.map | ||
export { ConnectionState, NewPeerJoined }; |
@@ -1,1 +0,1 @@ | ||
//# sourceMappingURL=common.types.js.map | ||
//# sourceMappingURL=common.types.js.map |
@@ -1,6 +0,22 @@ | ||
import { Producer } from "mediasoup-client/lib/types"; | ||
export type { Producer }; | ||
export * from "../HuddleClient"; | ||
export * from "./common.types"; | ||
export * from "./socket.types"; | ||
//# sourceMappingURL=index.d.ts.map | ||
export { Producer } from 'mediasoup-client/lib/types'; | ||
export { ConnectionState, NewPeerJoined } from './common.types.js'; | ||
export { SocketConnectionParameter } from './socket.types.js'; | ||
export { ConsumerEvents } from '../Consumer.js'; | ||
export { CustomMediaDevice, CustomMediaKind, DeviceHandlerEvents, FetchScreenResponse, FetchStreamResponse, StreamAdded, StreamPermissions, StreamPermissionsError } from '../DeviceHandler.js'; | ||
export { LocalPeerEvents } from '../LocalPeer.js'; | ||
export { PermissionEvents } from '../Permissions.js'; | ||
export { RemotePeerEvents } from '../RemotePeer.js'; | ||
export { RoomEvents, RoomStates } from '../Room.js'; | ||
export { MessagePayload, SocketEvents } from '../Socket.js'; | ||
export { TransportEvents } from '../Transport.js'; | ||
import 'zod'; | ||
import 'mediasoup-client/lib/RtpParameters'; | ||
import '../common-js/EnhancedEventEmitter.js'; | ||
import 'mediasoup-client'; | ||
import 'types/dist/common.types'; | ||
import 'types/dist/socket.types'; | ||
import 'types/dist/clientToSushiEvents.types'; | ||
import 'types/dist/sushiToClientEvents.types'; | ||
import 'types/dist'; | ||
import 'types/dist/mq/response.types'; | ||
import '../common-js/EnhancedMap.js'; |
@@ -1,650 +0,1 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __commonJS = (cb, mod) => function __require() { | ||
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
// ../../node_modules/events/events.js | ||
var require_events = __commonJS({ | ||
"../../node_modules/events/events.js"(exports, module) { | ||
"use strict"; | ||
var R = typeof Reflect === "object" ? Reflect : null; | ||
var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { | ||
return Function.prototype.apply.call(target, receiver, args); | ||
}; | ||
var ReflectOwnKeys; | ||
if (R && typeof R.ownKeys === "function") { | ||
ReflectOwnKeys = R.ownKeys; | ||
} else if (Object.getOwnPropertySymbols) { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); | ||
}; | ||
} else { | ||
ReflectOwnKeys = function ReflectOwnKeys2(target) { | ||
return Object.getOwnPropertyNames(target); | ||
}; | ||
} | ||
function ProcessEmitWarning(warning) { | ||
if (console && console.warn) | ||
console.warn(warning); | ||
} | ||
var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { | ||
return value !== value; | ||
}; | ||
function EventEmitter2() { | ||
EventEmitter2.init.call(this); | ||
} | ||
module.exports = EventEmitter2; | ||
module.exports.once = once; | ||
EventEmitter2.EventEmitter = EventEmitter2; | ||
EventEmitter2.prototype._events = void 0; | ||
EventEmitter2.prototype._eventsCount = 0; | ||
EventEmitter2.prototype._maxListeners = void 0; | ||
var defaultMaxListeners = 10; | ||
function checkListener(listener) { | ||
if (typeof listener !== "function") { | ||
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); | ||
} | ||
} | ||
Object.defineProperty(EventEmitter2, "defaultMaxListeners", { | ||
enumerable: true, | ||
get: function() { | ||
return defaultMaxListeners; | ||
}, | ||
set: function(arg) { | ||
if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { | ||
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); | ||
} | ||
defaultMaxListeners = arg; | ||
} | ||
}); | ||
EventEmitter2.init = function() { | ||
if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} | ||
this._maxListeners = this._maxListeners || void 0; | ||
}; | ||
EventEmitter2.prototype.setMaxListeners = function setMaxListeners(n) { | ||
if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { | ||
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); | ||
} | ||
this._maxListeners = n; | ||
return this; | ||
}; | ||
function _getMaxListeners(that) { | ||
if (that._maxListeners === void 0) | ||
return EventEmitter2.defaultMaxListeners; | ||
return that._maxListeners; | ||
} | ||
EventEmitter2.prototype.getMaxListeners = function getMaxListeners() { | ||
return _getMaxListeners(this); | ||
}; | ||
EventEmitter2.prototype.emit = function emit(type) { | ||
var args = []; | ||
for (var i = 1; i < arguments.length; i++) | ||
args.push(arguments[i]); | ||
var doError = type === "error"; | ||
var events = this._events; | ||
if (events !== void 0) | ||
doError = doError && events.error === void 0; | ||
else if (!doError) | ||
return false; | ||
if (doError) { | ||
var er; | ||
if (args.length > 0) | ||
er = args[0]; | ||
if (er instanceof Error) { | ||
throw er; | ||
} | ||
var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); | ||
err.context = er; | ||
throw err; | ||
} | ||
var handler = events[type]; | ||
if (handler === void 0) | ||
return false; | ||
if (typeof handler === "function") { | ||
ReflectApply(handler, this, args); | ||
} else { | ||
var len = handler.length; | ||
var listeners = arrayClone(handler, len); | ||
for (var i = 0; i < len; ++i) | ||
ReflectApply(listeners[i], this, args); | ||
} | ||
return true; | ||
}; | ||
function _addListener(target, type, listener, prepend) { | ||
var m; | ||
var events; | ||
var existing; | ||
checkListener(listener); | ||
events = target._events; | ||
if (events === void 0) { | ||
events = target._events = /* @__PURE__ */ Object.create(null); | ||
target._eventsCount = 0; | ||
} else { | ||
if (events.newListener !== void 0) { | ||
target.emit( | ||
"newListener", | ||
type, | ||
listener.listener ? listener.listener : listener | ||
); | ||
events = target._events; | ||
} | ||
existing = events[type]; | ||
} | ||
if (existing === void 0) { | ||
existing = events[type] = listener; | ||
++target._eventsCount; | ||
} else { | ||
if (typeof existing === "function") { | ||
existing = events[type] = prepend ? [listener, existing] : [existing, listener]; | ||
} else if (prepend) { | ||
existing.unshift(listener); | ||
} else { | ||
existing.push(listener); | ||
} | ||
m = _getMaxListeners(target); | ||
if (m > 0 && existing.length > m && !existing.warned) { | ||
existing.warned = true; | ||
var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); | ||
w.name = "MaxListenersExceededWarning"; | ||
w.emitter = target; | ||
w.type = type; | ||
w.count = existing.length; | ||
ProcessEmitWarning(w); | ||
} | ||
} | ||
return target; | ||
} | ||
EventEmitter2.prototype.addListener = function addListener(type, listener) { | ||
return _addListener(this, type, listener, false); | ||
}; | ||
EventEmitter2.prototype.on = EventEmitter2.prototype.addListener; | ||
EventEmitter2.prototype.prependListener = function prependListener(type, listener) { | ||
return _addListener(this, type, listener, true); | ||
}; | ||
function onceWrapper() { | ||
if (!this.fired) { | ||
this.target.removeListener(this.type, this.wrapFn); | ||
this.fired = true; | ||
if (arguments.length === 0) | ||
return this.listener.call(this.target); | ||
return this.listener.apply(this.target, arguments); | ||
} | ||
} | ||
function _onceWrap(target, type, listener) { | ||
var state = { fired: false, wrapFn: void 0, target, type, listener }; | ||
var wrapped = onceWrapper.bind(state); | ||
wrapped.listener = listener; | ||
state.wrapFn = wrapped; | ||
return wrapped; | ||
} | ||
EventEmitter2.prototype.once = function once2(type, listener) { | ||
checkListener(listener); | ||
this.on(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.prependOnceListener = function prependOnceListener(type, listener) { | ||
checkListener(listener); | ||
this.prependListener(type, _onceWrap(this, type, listener)); | ||
return this; | ||
}; | ||
EventEmitter2.prototype.removeListener = function removeListener(type, listener) { | ||
var list, events, position, i, originalListener; | ||
checkListener(listener); | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
list = events[type]; | ||
if (list === void 0) | ||
return this; | ||
if (list === listener || list.listener === listener) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else { | ||
delete events[type]; | ||
if (events.removeListener) | ||
this.emit("removeListener", type, list.listener || listener); | ||
} | ||
} else if (typeof list !== "function") { | ||
position = -1; | ||
for (i = list.length - 1; i >= 0; i--) { | ||
if (list[i] === listener || list[i].listener === listener) { | ||
originalListener = list[i].listener; | ||
position = i; | ||
break; | ||
} | ||
} | ||
if (position < 0) | ||
return this; | ||
if (position === 0) | ||
list.shift(); | ||
else { | ||
spliceOne(list, position); | ||
} | ||
if (list.length === 1) | ||
events[type] = list[0]; | ||
if (events.removeListener !== void 0) | ||
this.emit("removeListener", type, originalListener || listener); | ||
} | ||
return this; | ||
}; | ||
EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; | ||
EventEmitter2.prototype.removeAllListeners = function removeAllListeners(type) { | ||
var listeners, events, i; | ||
events = this._events; | ||
if (events === void 0) | ||
return this; | ||
if (events.removeListener === void 0) { | ||
if (arguments.length === 0) { | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
} else if (events[type] !== void 0) { | ||
if (--this._eventsCount === 0) | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
else | ||
delete events[type]; | ||
} | ||
return this; | ||
} | ||
if (arguments.length === 0) { | ||
var keys = Object.keys(events); | ||
var key; | ||
for (i = 0; i < keys.length; ++i) { | ||
key = keys[i]; | ||
if (key === "removeListener") | ||
continue; | ||
this.removeAllListeners(key); | ||
} | ||
this.removeAllListeners("removeListener"); | ||
this._events = /* @__PURE__ */ Object.create(null); | ||
this._eventsCount = 0; | ||
return this; | ||
} | ||
listeners = events[type]; | ||
if (typeof listeners === "function") { | ||
this.removeListener(type, listeners); | ||
} else if (listeners !== void 0) { | ||
for (i = listeners.length - 1; i >= 0; i--) { | ||
this.removeListener(type, listeners[i]); | ||
} | ||
} | ||
return this; | ||
}; | ||
function _listeners(target, type, unwrap) { | ||
var events = target._events; | ||
if (events === void 0) | ||
return []; | ||
var evlistener = events[type]; | ||
if (evlistener === void 0) | ||
return []; | ||
if (typeof evlistener === "function") | ||
return unwrap ? [evlistener.listener || evlistener] : [evlistener]; | ||
return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); | ||
} | ||
EventEmitter2.prototype.listeners = function listeners(type) { | ||
return _listeners(this, type, true); | ||
}; | ||
EventEmitter2.prototype.rawListeners = function rawListeners(type) { | ||
return _listeners(this, type, false); | ||
}; | ||
EventEmitter2.listenerCount = function(emitter, type) { | ||
if (typeof emitter.listenerCount === "function") { | ||
return emitter.listenerCount(type); | ||
} else { | ||
return listenerCount.call(emitter, type); | ||
} | ||
}; | ||
EventEmitter2.prototype.listenerCount = listenerCount; | ||
function listenerCount(type) { | ||
var events = this._events; | ||
if (events !== void 0) { | ||
var evlistener = events[type]; | ||
if (typeof evlistener === "function") { | ||
return 1; | ||
} else if (evlistener !== void 0) { | ||
return evlistener.length; | ||
} | ||
} | ||
return 0; | ||
} | ||
EventEmitter2.prototype.eventNames = function eventNames() { | ||
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; | ||
}; | ||
function arrayClone(arr, n) { | ||
var copy = new Array(n); | ||
for (var i = 0; i < n; ++i) | ||
copy[i] = arr[i]; | ||
return copy; | ||
} | ||
function spliceOne(list, index) { | ||
for (; index + 1 < list.length; index++) | ||
list[index] = list[index + 1]; | ||
list.pop(); | ||
} | ||
function unwrapListeners(arr) { | ||
var ret = new Array(arr.length); | ||
for (var i = 0; i < ret.length; ++i) { | ||
ret[i] = arr[i].listener || arr[i]; | ||
} | ||
return ret; | ||
} | ||
function once(emitter, name) { | ||
return new Promise(function(resolve, reject) { | ||
function errorListener(err) { | ||
emitter.removeListener(name, resolver); | ||
reject(err); | ||
} | ||
function resolver() { | ||
if (typeof emitter.removeListener === "function") { | ||
emitter.removeListener("error", errorListener); | ||
} | ||
resolve([].slice.call(arguments)); | ||
} | ||
; | ||
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); | ||
if (name !== "error") { | ||
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); | ||
} | ||
}); | ||
} | ||
function addErrorHandlerIfEventEmitter(emitter, handler, flags) { | ||
if (typeof emitter.on === "function") { | ||
eventTargetAgnosticAddListener(emitter, "error", handler, flags); | ||
} | ||
} | ||
function eventTargetAgnosticAddListener(emitter, name, listener, flags) { | ||
if (typeof emitter.on === "function") { | ||
if (flags.once) { | ||
emitter.once(name, listener); | ||
} else { | ||
emitter.on(name, listener); | ||
} | ||
} else if (typeof emitter.addEventListener === "function") { | ||
emitter.addEventListener(name, function wrapListener(arg) { | ||
if (flags.once) { | ||
emitter.removeEventListener(name, wrapListener); | ||
} | ||
listener(arg); | ||
}); | ||
} else { | ||
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); | ||
} | ||
} | ||
} | ||
}); | ||
// ../types/dist/socket.types.js | ||
var require_socket_types = __commonJS({ | ||
"../types/dist/socket.types.js"(exports) { | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SocketCloseReason = exports.ESocketCloseCode = void 0; | ||
var ESocketCloseCode3; | ||
(function(ESocketCloseCode4) { | ||
ESocketCloseCode4[ESocketCloseCode4["ABNORMAL_CLOSURE"] = 1006] = "ABNORMAL_CLOSURE"; | ||
ESocketCloseCode4[ESocketCloseCode4["NORMAL_CLOSURE"] = 1e3] = "NORMAL_CLOSURE"; | ||
ESocketCloseCode4[ESocketCloseCode4["BROWSER_TAB_CLOSE"] = 1001] = "BROWSER_TAB_CLOSE"; | ||
ESocketCloseCode4[ESocketCloseCode4["GOING_AWAY"] = 4001] = "GOING_AWAY"; | ||
ESocketCloseCode4[ESocketCloseCode4["CONNECTION_EXPIRED"] = 4002] = "CONNECTION_EXPIRED"; | ||
ESocketCloseCode4[ESocketCloseCode4["CONNECTION_ERROR"] = 4006] = "CONNECTION_ERROR"; | ||
ESocketCloseCode4[ESocketCloseCode4["ROOM_CLOSED"] = 4007] = "ROOM_CLOSED"; | ||
})(ESocketCloseCode3 || (exports.ESocketCloseCode = ESocketCloseCode3 = {})); | ||
exports.SocketCloseReason = { | ||
[ESocketCloseCode3.ROOM_CLOSED]: "ROOM_CLOSED", | ||
[ESocketCloseCode3.ABNORMAL_CLOSURE]: "ABNORMAL_CLOSURE", | ||
[ESocketCloseCode3.NORMAL_CLOSURE]: "NORMAL_CLOSURE", | ||
[ESocketCloseCode3.BROWSER_TAB_CLOSE]: "BROWSER_TAB_CLOSE", | ||
[ESocketCloseCode3.GOING_AWAY]: "GOING_AWAY", | ||
[ESocketCloseCode3.CONNECTION_ERROR]: "CONNECTION_ERROR", | ||
[ESocketCloseCode3.CONNECTION_EXPIRED]: "CONNECTION_EXPIRED" | ||
}; | ||
} | ||
}); | ||
// src/LocalPeer.ts | ||
import { detectDevice, Device } from "mediasoup-client"; | ||
// src/common-js/EnhancedEventEmitter.ts | ||
var import_events = __toESM(require_events(), 1); | ||
// src/constants/rtpConstants.ts | ||
var VIDEO_CONSTRAINTS = { | ||
qvga: { width: { ideal: 320 }, height: { ideal: 240 } }, | ||
vga: { width: { ideal: 640 }, height: { ideal: 480 } }, | ||
hd: { width: { ideal: 1280 }, height: { ideal: 720 } }, | ||
fHd: { width: { ideal: 1920 }, height: { ideal: 1080 } }, | ||
qHd: { width: { ideal: 4096 }, height: { ideal: 2160 } } | ||
}; | ||
// src/constants/deviceConstraints.ts | ||
var videoDefaultConstraints = { | ||
video: { | ||
...VIDEO_CONSTRAINTS.hd | ||
} | ||
}; | ||
// src/logger.ts | ||
var COLORS = { | ||
black: "\x1B[30m", | ||
red: "\x1B[31m", | ||
green: "\x1B[32m", | ||
yellow: "\x1B[33m", | ||
blue: "\x1B[34m", | ||
magenta: "\x1B[35m", | ||
cyan: "\x1B[36m", | ||
white: "\x1B[37m", | ||
default: "\x1B[39m" | ||
}; | ||
var defaultLevel = "debug"; | ||
var created = Date.now(); | ||
function createDefaultLoggerFactory() { | ||
return () => { | ||
const trace = (...args) => { | ||
console.trace(...args); | ||
}; | ||
const debug = (...args) => { | ||
console.debug(...args); | ||
}; | ||
const info = (...args) => { | ||
console.info(...args); | ||
}; | ||
const warn = (...args) => { | ||
console.warn(...args); | ||
}; | ||
const error = (...args) => { | ||
console.error(...args); | ||
}; | ||
return { | ||
trace, | ||
debug, | ||
info, | ||
warn, | ||
error | ||
}; | ||
}; | ||
} | ||
var wrapLogger = (logger10, moduleName, logLevel) => { | ||
let isTrace = false; | ||
let isDebug = false; | ||
let isInfo = false; | ||
let isWarning = false; | ||
let isError = false; | ||
let _level = logLevel; | ||
let _logger = logger10; | ||
const tracePrefix = `${COLORS.magenta}[TRACE]${COLORS.default} ${moduleName}`; | ||
const debugPrefix = `${COLORS.cyan}[DEBUG]${COLORS.default} ${moduleName}`; | ||
const infoPrefix = `${COLORS.green}[INFO]${COLORS.default} ${moduleName}`; | ||
const warnPrefix = `${COLORS.yellow}[WARN]${COLORS.default} ${moduleName}`; | ||
const errorPrefix = `${COLORS.red}[ERROR]${COLORS.default} ${moduleName}`; | ||
const result = new class { | ||
init() { | ||
isTrace = ["trace"].includes(_level ?? defaultLevel); | ||
isDebug = ["trace", "debug"].includes(_level ?? defaultLevel); | ||
isInfo = ["trace", "debug", "info"].includes(_level ?? defaultLevel); | ||
isWarning = ["trace", "debug", "info", "warn"].includes( | ||
_level ?? defaultLevel | ||
); | ||
isError = ["trace", "debug", "info", "warn", "error"].includes( | ||
_level ?? defaultLevel | ||
); | ||
} | ||
get logger() { | ||
return _logger; | ||
} | ||
set logger(value) { | ||
_logger = value; | ||
} | ||
get level() { | ||
return _level; | ||
} | ||
set level(value) { | ||
_level = value; | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
trace(...args) { | ||
if (isTrace) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger10.trace(tracePrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
debug(...args) { | ||
if (isDebug) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger10.debug(debugPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
info(...args) { | ||
if (isInfo) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger10.info(infoPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
warn(...args) { | ||
if (isWarning) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger10.warn(warnPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
// biome-ignore lint/suspicious/noExplicitAny: need any | ||
error(...args) { | ||
if (isError) { | ||
const elapsedInMs = `${COLORS.magenta}+${Date.now() - created}ms${COLORS.default}`; | ||
logger10.error(errorPrefix, ...args, elapsedInMs); | ||
} | ||
} | ||
}(); | ||
return result; | ||
}; | ||
var actualLoggerFactory = createDefaultLoggerFactory(); | ||
var loggers = /* @__PURE__ */ new Map(); | ||
var createLogger = (moduleName, logLevel) => { | ||
let wrappedLogger = loggers.get(moduleName); | ||
if (!wrappedLogger) { | ||
const logger10 = actualLoggerFactory(); | ||
wrappedLogger = wrapLogger(logger10, moduleName, logLevel ?? defaultLevel); | ||
loggers.set(moduleName, wrappedLogger); | ||
} else { | ||
wrappedLogger.level = logLevel ?? defaultLevel; | ||
} | ||
wrappedLogger.init(); | ||
return wrappedLogger; | ||
}; | ||
var mainLogger = { | ||
createSubLogger: (moduleName) => createLogger(`nezuko:${moduleName}`) | ||
}; | ||
// src/DeviceHandler.ts | ||
var logger = mainLogger.createSubLogger("DeviceHandler"); | ||
// src/Socket.ts | ||
var import_socket = __toESM(require_socket_types(), 1); | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
// src/Socket.ts | ||
var logger2 = mainLogger.createSubLogger("Socket.ts"); | ||
// src/Permissions.ts | ||
var logger3 = mainLogger.createSubLogger("Permissions"); | ||
// src/Room.ts | ||
var logger4 = mainLogger.createSubLogger("Room.ts"); | ||
// src/RemotePeer.ts | ||
var logger5 = mainLogger.createSubLogger("RemotePeer"); | ||
// src/Consumer.ts | ||
var logger6 = mainLogger.createSubLogger("Consumer"); | ||
// src/Transport.ts | ||
var logger7 = mainLogger.createSubLogger("Transport"); | ||
// src/LocalPeer.ts | ||
var logger8 = mainLogger.createSubLogger("LocalPeer"); | ||
// src/HuddleClient.ts | ||
var import_socket2 = __toESM(require_socket_types(), 1); | ||
var logger9 = mainLogger.createSubLogger("NezukoClient"); | ||
// src/types/socket.types.ts | ||
import { z as z2 } from "zod"; | ||
var SocketConnectionParameterSchema = z2.object({}).merge(ConnectionParameterSchema); | ||
export { | ||
SocketConnectionParameterSchema | ||
}; | ||
//# sourceMappingURL=index.js.map | ||
//# sourceMappingURL=index.js.map |
@@ -1,3 +0,4 @@ | ||
import { z } from "zod"; | ||
export declare const SocketConnectionParameterSchema: z.ZodObject<{ | ||
import { z } from 'zod'; | ||
declare const SocketConnectionParameterSchema: z.ZodObject<{ | ||
roomId: z.ZodString; | ||
@@ -12,3 +13,4 @@ token: z.ZodString; | ||
}>; | ||
export type ISocketConnectionParameter = z.infer<typeof SocketConnectionParameterSchema>; | ||
//# sourceMappingURL=socket.types.d.ts.map | ||
type SocketConnectionParameter = z.infer<typeof SocketConnectionParameterSchema>; | ||
export { SocketConnectionParameter, SocketConnectionParameterSchema }; |
@@ -0,40 +1,13 @@ | ||
import "../chunk-PYD4CES4.js"; | ||
import { | ||
ConnectionParameterSchema | ||
} from "../chunk-OYKTKRTB.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
// src/types/socket.types.ts | ||
import { z as z2 } from "zod"; | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
// src/types/socket.types.ts | ||
var SocketConnectionParameterSchema = z2.object({}).merge(ConnectionParameterSchema); | ||
var SocketConnectionParameterSchema = z.object({}).merge(ConnectionParameterSchema); | ||
export { | ||
SocketConnectionParameterSchema | ||
}; | ||
//# sourceMappingURL=socket.types.js.map | ||
//# sourceMappingURL=socket.types.js.map |
@@ -1,3 +0,4 @@ | ||
import { z } from "zod"; | ||
export declare const ConnectionParameterSchema: z.ZodObject<{ | ||
import { z } from 'zod'; | ||
declare const ConnectionParameterSchema: z.ZodObject<{ | ||
roomId: z.ZodString; | ||
@@ -12,3 +13,3 @@ token: z.ZodString; | ||
}>; | ||
export declare const GeolocationSchema: z.ZodObject<{ | ||
declare const GeolocationSchema: z.ZodObject<{ | ||
country: z.ZodString; | ||
@@ -35,3 +36,4 @@ latitude: z.ZodString; | ||
}>; | ||
export type IConnectionParameter = z.infer<typeof ConnectionParameterSchema>; | ||
//# sourceMappingURL=common.validators.d.ts.map | ||
type IConnectionParameter = z.infer<typeof ConnectionParameterSchema>; | ||
export { ConnectionParameterSchema, GeolocationSchema, IConnectionParameter }; |
@@ -1,31 +0,6 @@ | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
import { | ||
ConnectionParameterSchema, | ||
GeolocationSchema | ||
} from "../chunk-OYKTKRTB.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
@@ -35,2 +10,2 @@ ConnectionParameterSchema, | ||
}; | ||
//# sourceMappingURL=common.validators.js.map | ||
//# sourceMappingURL=common.validators.js.map |
@@ -1,2 +0,2 @@ | ||
export * from "./common.validators"; | ||
//# sourceMappingURL=index.d.ts.map | ||
export { ConnectionParameterSchema, GeolocationSchema, IConnectionParameter } from './common.validators.js'; | ||
import 'zod'; |
@@ -1,31 +0,7 @@ | ||
// src/validators/common.validators.ts | ||
import { z } from "zod"; | ||
var ConnectionParameterSchema = z.object({ | ||
roomId: z.string({ | ||
required_error: "Room id must provided" | ||
}), | ||
token: z.string({ | ||
required_error: "Token must provided" | ||
}) | ||
}); | ||
var GeolocationSchema = z.object({ | ||
country: z.string({ | ||
required_error: "Country must provided" | ||
}), | ||
latitude: z.string({ | ||
required_error: "Latitude must provided" | ||
}), | ||
longitude: z.string({ | ||
required_error: "Longitude must provided" | ||
}), | ||
region: z.string({ | ||
required_error: "Region must provided" | ||
}), | ||
globalRegion: z.string({ | ||
required_error: "Global region must provided" | ||
}), | ||
ip: z.string({ | ||
required_error: "IP must provided" | ||
}) | ||
}); | ||
import "../chunk-PYD4CES4.js"; | ||
import { | ||
ConnectionParameterSchema, | ||
GeolocationSchema | ||
} from "../chunk-OYKTKRTB.js"; | ||
import "../chunk-UXIASGQL.js"; | ||
export { | ||
@@ -35,2 +11,2 @@ ConnectionParameterSchema, | ||
}; | ||
//# sourceMappingURL=index.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@huddle01/web-core", | ||
"version": "1.0.0-alpha.14", | ||
"version": "1.0.0-alpha.15", | ||
"description": "", | ||
@@ -8,6 +8,9 @@ "type": "module", | ||
"types": "dist/index.d.ts", | ||
"files": ["dist", "types.d.ts"], | ||
"files": [ | ||
"dist", | ||
"types.d.ts" | ||
], | ||
"scripts": { | ||
"build": "rm -rf dist & node --no-warnings ./bundler.mjs & yarn gen-types", | ||
"gen-types": "tsc --skipLibCheck --emitDeclarationOnly --declaration --declarationMap", | ||
"build": "rm -rf dist && tsup", | ||
"watch": "tsup -w", | ||
"pub": "npm publish --access public --tag alpha" | ||
@@ -25,10 +28,2 @@ }, | ||
}, | ||
"tsup": { | ||
"entry": ["src/**/*.ts"], | ||
"sourcemap": true, | ||
"dts": true, | ||
"splitting": true, | ||
"clean": true, | ||
"format": ["esm"] | ||
}, | ||
"keywords": [], | ||
@@ -35,0 +30,0 @@ "author": "", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
102
3
463772
6498