peerjs
Version:
PeerJS client
3 lines (2 loc) • 38.1 kB
JavaScript
function e(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}var t,n,i,r,o,s,a=function(e,t){this.type=e,this.data=t},c=(t=function(e,n){return(t=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)},function(e,n){if("function"!=typeof n&&null!==n)throw TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}),h=function(e){function t(n){var i=e.call(this,n)||this;return Object.setPrototypeOf(i,Object.create(t.prototype)),Object.defineProperty(i,"name",{configurable:!0,enumerable:!1,value:t.name}),i}return c(t,e),t}(Error);function f(e,t,n){var i=Math.floor(n/0x100000000);e.setUint32(t,i),e.setUint32(t+4,n)}function l(e,t){return 0x100000000*e.getInt32(t)+e.getUint32(t+4)}var u={type:-1,encode:function(e){var t,n,i,r;return e instanceof Date?function(e){var t=e.sec,n=e.nsec;if(t>=0&&n>=0&&t<=0x3ffffffff)if(0===n&&t<=0xffffffff){var i=new Uint8Array(4),r=new DataView(i.buffer);return r.setUint32(0,t),i}else{var o=t/0x100000000,i=new Uint8Array(8),r=new DataView(i.buffer);return r.setUint32(0,n<<2|3&o),r.setUint32(4,0|t),i}var i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,n),f(r,4,t),i}((n=Math.floor((t=e.getTime())/1e3),r=Math.floor((i=(t-1e3*n)*1e6)/1e9),{sec:n+r,nsec:i-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:var n=t.getUint32(0),i=0;return{sec:n,nsec:0};case 8:var r=t.getUint32(0),n=(3&r)*0x100000000+t.getUint32(4),i=r>>>2;return{sec:n,nsec:i};case 12:var n=l(t,4),i=t.getUint32(0);return{sec:n,nsec:i};default:throw new h("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},d=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(u)}return e.prototype.register=function(e){var t=e.type,n=e.encode,i=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=i;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=i}},e.prototype.tryToEncode=function(e,t){for(var n=0;n<this.builtInEncoders.length;n++){var i=this.builtInEncoders[n];if(null!=i){var r=i(e,t);if(null!=r){var o=-1-n;return new a(o,r)}}}for(var n=0;n<this.encoders.length;n++){var i=this.encoders[n];if(null!=i){var r=i(e,t);if(null!=r){var o=n;return new a(o,r)}}}return e instanceof a?e:null},e.prototype.decode=function(e,t,n){var i=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return i?i(e,t,n):new a(t,e)},e.defaultCodec=new e,e}(),p="undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function y(e){for(var t=e.length,n=0,i=0;i<t;){var r=e.charCodeAt(i++);if((0xffffff80&r)==0){n++;continue}if((0xfffff800&r)==0)n+=2;else{if(r>=55296&&r<=56319&&i<t){var o=e.charCodeAt(i);(64512&o)==56320&&(++i,r=((1023&r)<<10)+(1023&o)+65536)}(0xffff0000&r)==0?n+=3:n+=4}}return n}var v=p?new TextEncoder:void 0,w=0xffffffff*!p,g=(null==v?void 0:v.encodeInto)?function(e,t,n){v.encodeInto(e,t.subarray(n))}:function(e,t,n){t.set(v.encode(e),n)};function b(e,t,n){for(var i=t,r=i+n,o=[],s="";i<r;){var a=e[i++];if((128&a)==0)o.push(a);else if((224&a)==192){var c=63&e[i++];o.push((31&a)<<6|c)}else if((240&a)==224){var c=63&e[i++],h=63&e[i++];o.push((31&a)<<12|c<<6|h)}else if((248&a)==240){var c=63&e[i++],h=63&e[i++],f=(7&a)<<18|c<<12|h<<6|63&e[i++];f>65535&&(f-=65536,o.push(f>>>10&1023|55296),f=56320|1023&f),o.push(f)}else o.push(a);o.length>=4096&&(s+=String.fromCharCode.apply(String,o),o.length=0)}return o.length>0&&(s+=String.fromCharCode.apply(String,o)),s}var m=p?new TextDecoder:null,U=0xffffffff*!p;function x(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e)}var S=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){var i=this.caches[n-1];e:for(var r=0;r<i.length;r++){for(var o=i[r],s=o.bytes,a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return o.str}return null},e.prototype.store=function(e,t){var n=this.caches[e.length-1],i={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)},e.prototype.decode=function(e,t,n){var i=this.find(e,t,n);if(null!=i)return this.hit++,i;this.miss++;var r=b(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,r),r},e}(),_=function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var c=[o,a];if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&c[0]?i.return:c[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,c[1])).done)return r;switch(i=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return s.label++,{value:c[1],done:!1};case 5:s.label++,i=c[1],c=[0];continue;case 7:c=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===c[0]||2===c[0])){s=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]<r[3])){s.label=c[1];break}if(6===c[0]&&s.label<r[1]){s.label=r[1],r=c;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(c);break}r[2]&&s.ops.pop(),s.trys.pop();continue}c=t.call(e,s)}catch(e){c=[6,e],i=0}finally{n=r=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}},C=function(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(n){t[n]=e[n]&&function(t){return new Promise(function(i,r){var o,s,a;o=i,s=r,a=(t=e[n](t)).done,Promise.resolve(t.value).then(function(e){o({value:e,done:a})},s)})}}},E=function(e){return this instanceof E?(this.v=e,this):new E(e)},I=function(e,t,n){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(e){r[e]&&(i[e]=function(t){return new Promise(function(n,i){o.push([e,t,n,i])>1||a(e,t)})})}function a(e,t){try{var n;(n=r[e](t)).value instanceof E?Promise.resolve(n.value.v).then(c,h):f(o[0][2],n)}catch(e){f(o[0][3],e)}}function c(e){a("next",e)}function h(e){a("throw",e)}function f(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}},T=function(e){var t=typeof e;return"string"===t||"number"===t},k=new DataView(new ArrayBuffer(0)),A=new Uint8Array(k.buffer),L=function(){try{k.getInt8(0)}catch(e){return e.constructor}throw Error("never reached")}(),B=new L("Insufficient data"),D=new S,R=function(){function t(e,t,n,i,r,o,s,a){void 0===e&&(e=d.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=0xffffffff),void 0===i&&(i=0xffffffff),void 0===r&&(r=0xffffffff),void 0===o&&(o=0xffffffff),void 0===s&&(s=0xffffffff),void 0===a&&(a=D),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=i,this.maxArrayLength=r,this.maxMapLength=o,this.maxExtLength=s,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=k,this.bytes=A,this.headByte=-1,this.stack=[]}return t.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},t.prototype.setBuffer=function(e){this.bytes=x(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=x(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},t.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),n=x(e),i=new Uint8Array(t.length+n.length);i.set(t),i.set(n,t.length),this.setBuffer(i)}else this.setBuffer(e)},t.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},t.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},t.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},t.prototype.decodeMulti=function(e){return _(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:if(!this.hasRemaining(1))return[3,3];return[4,this.doDecodeSync()];case 2:return t.sent(),[3,1];case 3:return[2]}})},t.prototype.decodeAsync=function(t){var n,i,r,o,s,a,c,h;return s=this,a=void 0,c=void 0,h=function(){var s,a,c,h,f,l,u;return _(this,function(d){switch(d.label){case 0:s=!1,d.label=1;case 1:d.trys.push([1,6,7,12]),n=C(t),d.label=2;case 2:return[4,n.next()];case 3:if((i=d.sent()).done)return[3,5];if(c=i.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof L))throw e}this.totalPos+=this.pos,d.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return r={error:d.sent()},[3,12];case 7:if(d.trys.push([7,,10,11]),!(i&&!i.done&&(o=n.return)))return[3,9];return[4,o.call(n)];case 8:d.sent(),d.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw h=this,f=h.headByte,l=h.pos,u=h.totalPos,RangeError("Insufficient data in parsing ".concat(e(f)," at ").concat(u," (").concat(l," in the current buffer)"))}})},new(c||(c=Promise))(function(e,t){function n(e){try{r(h.next(e))}catch(e){t(e)}}function i(e){try{r(h.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):((r=t.value)instanceof c?r:new c(function(e){e(r)})).then(n,i)}r((h=h.apply(s,a||[])).next())})},t.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},t.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},t.prototype.decodeMultiAsync=function(e,t){return I(this,arguments,function(){var n,i,r,o,s,a,c,h;return _(this,function(f){switch(f.label){case 0:n=t,i=-1,f.label=1;case 1:f.trys.push([1,13,14,19]),r=C(e),f.label=2;case 2:return[4,E(r.next())];case 3:if((o=f.sent()).done)return[3,12];if(s=o.value,t&&0===i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(i=this.readArraySize(),n=!1,this.complete()),f.label=4;case 4:f.trys.push([4,9,,10]),f.label=5;case 5:return[4,E(this.doDecodeSync())];case 6:return[4,f.sent()];case 7:if(f.sent(),0==--i)return[3,8];return[3,5];case 8:return[3,10];case 9:if(!((a=f.sent())instanceof L))throw a;return[3,10];case 10:this.totalPos+=this.pos,f.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c={error:f.sent()},[3,19];case 14:if(f.trys.push([14,,17,18]),!(o&&!o.done&&(h=r.return)))return[3,16];return[4,E(h.call(r))];case 15:f.sent(),f.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}})})},t.prototype.doDecodeSync=function(){t:for(;;){var t=this.readHeadByte(),n=void 0;if(t>=224)n=t-256;else if(t<192)if(t<128)n=t;else if(t<144){var i=t-128;if(0!==i){this.pushMapState(i),this.complete();continue}n={}}else if(t<160){var i=t-144;if(0!==i){this.pushArrayState(i),this.complete();continue}n=[]}else{var r=t-160;n=this.decodeUtf8String(r,0)}else if(192===t)n=null;else if(194===t)n=!1;else if(195===t)n=!0;else if(202===t)n=this.readF32();else if(203===t)n=this.readF64();else if(204===t)n=this.readU8();else if(205===t)n=this.readU16();else if(206===t)n=this.readU32();else if(207===t)n=this.readU64();else if(208===t)n=this.readI8();else if(209===t)n=this.readI16();else if(210===t)n=this.readI32();else if(211===t)n=this.readI64();else if(217===t){var r=this.lookU8();n=this.decodeUtf8String(r,1)}else if(218===t){var r=this.lookU16();n=this.decodeUtf8String(r,2)}else if(219===t){var r=this.lookU32();n=this.decodeUtf8String(r,4)}else if(220===t){var i=this.readU16();if(0!==i){this.pushArrayState(i),this.complete();continue}n=[]}else if(221===t){var i=this.readU32();if(0!==i){this.pushArrayState(i),this.complete();continue}n=[]}else if(222===t){var i=this.readU16();if(0!==i){this.pushMapState(i),this.complete();continue}n={}}else if(223===t){var i=this.readU32();if(0!==i){this.pushMapState(i),this.complete();continue}n={}}else if(196===t){var i=this.lookU8();n=this.decodeBinary(i,1)}else if(197===t){var i=this.lookU16();n=this.decodeBinary(i,2)}else if(198===t){var i=this.lookU32();n=this.decodeBinary(i,4)}else if(212===t)n=this.decodeExtension(1,0);else if(213===t)n=this.decodeExtension(2,0);else if(214===t)n=this.decodeExtension(4,0);else if(215===t)n=this.decodeExtension(8,0);else if(216===t)n=this.decodeExtension(16,0);else if(199===t){var i=this.lookU8();n=this.decodeExtension(i,1)}else if(200===t){var i=this.lookU16();n=this.decodeExtension(i,2)}else if(201===t){var i=this.lookU32();n=this.decodeExtension(i,4)}else throw new h("Unrecognized type byte: ".concat(e(t)));this.complete();for(var o=this.stack;o.length>0;){var s=o[o.length-1];if(0===s.type)if(s.array[s.position]=n,s.position++,s.position===s.size)o.pop(),n=s.array;else continue t;else if(1===s.type){if(!T(n))throw new h("The type of key must be string or number but "+typeof n);if("__proto__"===n)throw new h("The key __proto__ is not allowed");s.key=n,s.type=2;continue t}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)o.pop(),n=s.map;else{s.key=null,s.type=1;continue t}}return n}},t.prototype.readHeadByte=function(){return -1===this.headByte&&(this.headByte=this.readU8()),this.headByte},t.prototype.complete=function(){this.headByte=-1},t.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:if(t<160)return t-144;throw new h("Unrecognized array type byte: ".concat(e(t)))}},t.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new h("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},t.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new h("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:Array(e),position:0})},t.prototype.decodeUtf8String=function(e,t){if(e>this.maxStrLength)throw new h("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw B;var n,i,r,o,s=this.pos+t;return this.stateIsMapKey()&&(null==(r=this.keyDecoder)?void 0:r.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,s,e):e>U?(n=this.bytes,i=n.subarray(s,s+e),o=m.decode(i)):o=b(this.bytes,s,e),this.pos+=t+e,o},t.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},t.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new h("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw B;var n=this.pos+t,i=this.bytes.subarray(n,n+e);return this.pos+=t+e,i},t.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new h("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),i=this.decodeBinary(e,t+1);return this.extensionCodec.decode(i,n,this.context)},t.prototype.lookU8=function(){return this.view.getUint8(this.pos)},t.prototype.lookU16=function(){return this.view.getUint16(this.pos)},t.prototype.lookU32=function(){return this.view.getUint32(this.pos)},t.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},t.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},t.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},t.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},t.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},t.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},t.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,0x100000000*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},t.prototype.readI64=function(){var e=l(this.view,this.pos);return this.pos+=8,e},t.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},t.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},t}(),O=function(e,t){var n,i,r,o,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){var c=[o,a];if(n)throw TypeError("Generator is already executing.");for(;s;)try{if(n=1,i&&(r=2&c[0]?i.return:c[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,c[1])).done)return r;switch(i=0,r&&(c=[2&c[0],r.value]),c[0]){case 0:case 1:r=c;break;case 4:return s.label++,{value:c[1],done:!1};case 5:s.label++,i=c[1],c=[0];continue;case 7:c=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===c[0]||2===c[0])){s=0;continue}if(3===c[0]&&(!r||c[1]>r[0]&&c[1]<r[3])){s.label=c[1];break}if(6===c[0]&&s.label<r[1]){s.label=r[1],r=c;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(c);break}r[2]&&s.ops.pop(),s.trys.pop();continue}c=t.call(e,s)}catch(e){c=[6,e],i=0}finally{n=r=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}},z=function(e){return this instanceof z?(this.v=e,this):new z(e)},F=function(e,t,n){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var i,r=n.apply(e,t||[]),o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(e){r[e]&&(i[e]=function(t){return new Promise(function(n,i){o.push([e,t,n,i])>1||a(e,t)})})}function a(e,t){try{var n;(n=r[e](t)).value instanceof z?Promise.resolve(n.value.v).then(c,h):f(o[0][2],n)}catch(e){f(o[0][3],e)}}function c(e){a("next",e)}function h(e){a("throw",e)}function f(e,t){e(t),o.shift(),o.length&&a(o[0][0],o[0][1])}},M={},P=function(){function e(e,t,n,i,r,o,s,a){void 0===e&&(e=d.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=100),void 0===i&&(i=2048),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===s&&(s=!1),void 0===a&&(a=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=i,this.sortKeys=r,this.forceFloat32=o,this.ignoreUndefined=s,this.forceIntegerToFloat=a,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)},e.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),n=new Uint8Array(t),i=new DataView(t);n.set(this.bytes),this.view=i,this.bytes=n},e.prototype.encodeNil=function(){this.writeU8(192)},e.prototype.encodeBoolean=function(e){!1===e?this.writeU8(194):this.writeU8(195)},e.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<0x100000000?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-0x80000000?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<0x100000000)this.writeU8(219),this.writeU32(e);else throw Error("Too long string: ".concat(e," bytes in UTF-8"))},e.prototype.encodeString=function(e){if(e.length>w){var t=y(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),g(e,this.bytes,this.pos),this.pos+=t}else{var t=y(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var i=e.length,r=n,o=0;o<i;){var s=e.charCodeAt(o++);if((0xffffff80&s)==0){t[r++]=s;continue}if((0xfffff800&s)==0)t[r++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<i){var a=e.charCodeAt(o);(64512&a)==56320&&(++o,s=((1023&s)<<10)+(1023&a)+65536)}(0xffff0000&s)==0?t[r++]=s>>12&15|224:(t[r++]=s>>18&7|240,t[r++]=s>>12&63|128),t[r++]=s>>6&63|128}t[r++]=63&s|128}}(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if("object"==typeof e)this.encodeMap(e,t);else throw Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)))},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<0x100000000)this.writeU8(198),this.writeU32(t);else throw Error("Too large binary: ".concat(t));var n=x(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<0x100000000)this.writeU8(221),this.writeU32(n);else throw Error("Too large array: ".concat(n));for(var i=0;i<e.length;i++){var r=e[i];this.doEncode(r,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var n=0,i=0;i<t.length;i++)void 0!==e[t[i]]&&n++;return n},e.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<0x100000000)this.writeU8(223),this.writeU32(i);else throw Error("Too large map object: ".concat(i));for(var r=0;r<n.length;r++){var o=n[r],s=e[o];this.ignoreUndefined&&void 0===s||(this.encodeString(o),this.doEncode(s,t+1))}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<0x100000000)this.writeU8(201),this.writeU32(t);else throw Error("Too large extension object: ".concat(t));this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){var t,n;this.ensureBufferSizeToWrite(8),t=this.view,n=this.pos,t.setUint32(n,e/0x100000000),t.setUint32(n+4,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),f(this.view,this.pos,e),this.pos+=8},e}(),W=new class{get logLevel(){return this._logLevel}set logLevel(e){this._logLevel=e}log(...e){this._logLevel>=3&&this._print(3,...e)}warn(...e){this._logLevel>=2&&this._print(2,...e)}error(...e){this._logLevel>=1&&this._print(1,...e)}setLogFunction(e){this._print=e}_print(e,...t){let n=["PeerJS: ",...t];for(let e in n)n[e]instanceof Error&&(n[e]="("+n[e].name+") "+n[e].message);e>=3?console.log(...n):e>=2?console.warn("WARNING",...n):e>=1&&console.error("ERROR",...n)}constructor(){this._logLevel=0}},N=((n={}).Data="data",n.Media="media",n),j=((i={}).BrowserIncompatible="browser-incompatible",i.Disconnected="disconnected",i.InvalidID="invalid-id",i.InvalidKey="invalid-key",i.Network="network",i.PeerUnavailable="peer-unavailable",i.SslUnavailable="ssl-unavailable",i.ServerError="server-error",i.SocketError="socket-error",i.SocketClosed="socket-closed",i.UnavailableID="unavailable-id",i.WebRTC="webrtc",i),$=((r={}).NegotiationFailed="negotiation-failed",r.ConnectionClosed="connection-closed",r),K=((o={}).NotOpenYet="not-open-yet",o.MessageToBig="message-too-big",o),V=((s={}).Heartbeat="HEARTBEAT",s.Candidate="CANDIDATE",s.Offer="OFFER",s.Answer="ANSWER",s.Open="OPEN",s.Error="ERROR",s.IdTaken="ID-TAKEN",s.InvalidKey="INVALID-KEY",s.Leave="LEAVE",s.Expire="EXPIRE",s);class H{constructor(e){this.connection=e}startConnection(e){let t=this._startPeerConnection();if(this.connection.peerConnection=t,this.connection.type===N.Media&&e._stream&&this._addTracksToConnection(e._stream,t),e.originator){let n=this.connection,i={ordered:!!e.reliable},r=t.createDataChannel(n.label,i);n._initializeDataChannel(r),this._makeOffer()}else this.handleSDP("OFFER",e.sdp)}_startPeerConnection(){W.log("Creating RTCPeerConnection.");let e=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(e),e}_setupListeners(e){let t=this.connection.peer,n=this.connection.connectionId,i=this.connection.type,r=this.connection.provider;W.log("Listening for ICE candidates."),e.onicecandidate=e=>{e.candidate&&e.candidate.candidate&&(W.log(`Received ICE candidates for ${t}:`,e.candidate),r.socket.send({type:V.Candidate,payload:{candidate:e.candidate,type:i,connectionId:n},dst:t}))},e.oniceconnectionstatechange=()=>{switch(e.iceConnectionState){case"failed":W.log("iceConnectionState is failed, closing connections to "+t),this.connection.emitError($.NegotiationFailed,"Negotiation of connection to "+t+" failed."),this.connection.close();break;case"closed":W.log("iceConnectionState is closed, closing connections to "+t),this.connection.emitError($.ConnectionClosed,"Connection to "+t+" closed."),this.connection.close();break;case"disconnected":W.log("iceConnectionState changed to disconnected on the connection with "+t);break;case"completed":e.onicecandidate=()=>{}}this.connection.emit("iceStateChanged",e.iceConnectionState)},W.log("Listening for data channel"),e.ondatachannel=e=>{W.log("Received data channel");let i=e.channel;r.getConnection(t,n)._initializeDataChannel(i)},W.log("Listening for remote stream"),e.ontrack=e=>{W.log("Received remote stream");let i=e.streams[0],o=r.getConnection(t,n);o.type===N.Media&&this._addStreamToMediaConnection(i,o)}}cleanup(){W.log("Cleaning up PeerConnection to "+this.connection.peer);let e=this.connection.peerConnection;if(!e)return;this.connection.peerConnection=null,e.onicecandidate=e.oniceconnectionstatechange=e.ondatachannel=e.ontrack=()=>{};let t="closed"!==e.signalingState,n=!1,i=this.connection.dataChannel;i&&(n=!!i.readyState&&"closed"!==i.readyState),(t||n)&&e.close()}async _makeOffer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createOffer(this.connection.options.constraints);W.log("Created offer."),this.connection.options.sdpTransform&&"function"==typeof this.connection.options.sdpTransform&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),W.log("Set localDescription:",n,`for:${this.connection.peer}`);let i={sdp:n,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata};if(this.connection.type===N.Data){let e=this.connection;i={...i,label:e.label,reliable:e.reliable,serialization:e.serialization}}t.socket.send({type:V.Offer,payload:i,dst:this.connection.peer})}catch(e){"OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"!=e&&(t.emitError(j.WebRTC,e),W.log("Failed to setLocalDescription, ",e))}}catch(e){t.emitError(j.WebRTC,e),W.log("Failed to createOffer, ",e)}}async _makeAnswer(){let e=this.connection.peerConnection,t=this.connection.provider;try{let n=await e.createAnswer();W.log("Created answer."),this.connection.options.sdpTransform&&"function"==typeof this.connection.options.sdpTransform&&(n.sdp=this.connection.options.sdpTransform(n.sdp)||n.sdp);try{await e.setLocalDescription(n),W.log("Set localDescription:",n,`for:${this.connection.peer}`),t.socket.send({type:V.Answer,payload:{sdp:n,type:this.connection.type,connectionId:this.connection.connectionId},dst:this.connection.peer})}catch(e){t.emitError(j.WebRTC,e),W.log("Failed to setLocalDescription, ",e)}}catch(e){t.emitError(j.WebRTC,e),W.log("Failed to create answer, ",e)}}async handleSDP(e,t){t=new RTCSessionDescription(t);let n=this.connection.peerConnection,i=this.connection.provider;W.log("Setting remote description",t);try{await n.setRemoteDescription(t),W.log(`Set remoteDescription:${e} for:${this.connection.peer}`),"OFFER"===e&&await this._makeAnswer()}catch(e){i.emitError(j.WebRTC,e),W.log("Failed to setRemoteDescription, ",e)}}async handleCandidate(e){W.log("handleCandidate:",e);try{await this.connection.peerConnection.addIceCandidate(e),W.log(`Added ICE candidate for:${this.connection.peer}`)}catch(e){this.connection.provider.emitError(j.WebRTC,e),W.log("Failed to handleCandidate, ",e)}}_addTracksToConnection(e,t){if(W.log(`add tracks from stream ${e.id} to peer connection`),!t.addTrack)return W.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");e.getTracks().forEach(n=>{t.addTrack(n,e)})}_addStreamToMediaConnection(e,t){W.log(`add stream ${e.id} to media connection ${t.connectionId}`),t.addStream(e)}}var X={},Y=Object.prototype.hasOwnProperty,G="~";function Z(){}function q(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function J(e,t,n,i,r){if("function"!=typeof n)throw TypeError("The listener must be a function");var o=new q(n,i||e,r),s=G?G+t:t;return e._events[s]?e._events[s].fn?e._events[s]=[e._events[s],o]:e._events[s].push(o):(e._events[s]=o,e._eventsCount++),e}function Q(e,t){0==--e._eventsCount?e._events=new Z:delete e._events[t]}function ee(){this._events=new Z,this._eventsCount=0}Object.create&&(Z.prototype=Object.create(null),new Z().__proto__||(G=!1)),ee.prototype.eventNames=function(){var e,t,n=[];if(0===this._eventsCount)return n;for(t in e=this._events)Y.call(e,t)&&n.push(G?t.slice(1):t);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},ee.prototype.listeners=function(e){var t=G?G+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,r=n.length,o=Array(r);i<r;i++)o[i]=n[i].fn;return o},ee.prototype.listenerCount=function(e){var t=G?G+e:e,n=this._events[t];return n?n.fn?1:n.length:0},ee.prototype.emit=function(e,t,n,i,r,o){var s=G?G+e:e;if(!this._events[s])return!1;var a,c,h=this._events[s],f=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),f){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,n),!0;case 4:return h.fn.call(h.context,t,n,i),!0;case 5:return h.fn.call(h.context,t,n,i,r),!0;case 6:return h.fn.call(h.context,t,n,i,r,o),!0}for(c=1,a=Array(f-1);c<f;c++)a[c-1]=arguments[c];h.fn.apply(h.context,a)}else{var l,u=h.length;for(c=0;c<u;c++)switch(h[c].once&&this.removeListener(e,h[c].fn,void 0,!0),f){case 1:h[c].fn.call(h[c].context);break;case 2:h[c].fn.call(h[c].context,t);break;case 3:h[c].fn.call(h[c].context,t,n);break;case 4:h[c].fn.call(h[c].context,t,n,i);break;default:if(!a)for(l=1,a=Array(f-1);l<f;l++)a[l-1]=arguments[l];h[c].fn.apply(h[c].context,a)}}return!0},ee.prototype.on=function(e,t,n){return J(this,e,t,n,!1)},ee.prototype.once=function(e,t,n){return J(this,e,t,n,!0)},ee.prototype.removeListener=function(e,t,n,i){var r=G?G+e:e;if(!this._events[r])return this;if(!t)return Q(this,r),this;var o=this._events[r];if(o.fn)o.fn!==t||i&&!o.once||n&&o.context!==n||Q(this,r);else{for(var s=0,a=[],c=o.length;s<c;s++)(o[s].fn!==t||i&&!o[s].once||n&&o[s].context!==n)&&a.push(o[s]);a.length?this._events[r]=1===a.length?a[0]:a:Q(this,r)}return this},ee.prototype.removeAllListeners=function(e){var t;return e?(t=G?G+e:e,this._events[t]&&Q(this,t)):(this._events=new Z,this._eventsCount=0),this},ee.prototype.off=ee.prototype.removeListener,ee.prototype.addListener=ee.prototype.on,ee.prefixed=G,ee.EventEmitter=ee,X=ee;class et extends X.EventEmitter{emitError(e,t){W.error("Error:",t),this.emit("error",new en(`${e}`,t))}}class en extends Error{constructor(e,t){"string"==typeof t?super(t):(super(),Object.assign(this,t)),this.type=e}}class ei extends et{get open(){return this._open}constructor(e,t,n){super(),this.peer=e,this.provider=t,this.options=n,this._open=!1,this.metadata=n.metadata}}let er=()=>Math.random().toString(36).slice(2);class eo extends ei{static #e=this.ID_PREFIX="dc_";static #t=this.MAX_BUFFERED_AMOUNT=8388608;get type(){return N.Data}constructor(e,t,n){super(e,t,n),this.connectionId=this.options.connectionId||eo.ID_PREFIX+er(),this.label=this.options.label||this.connectionId,this.reliable=!!this.options.reliable,this._negotiator=new H(this),this._negotiator.startConnection(this.options._payload||{originator:!0,reliable:this.reliable})}_initializeDataChannel(e){this.dataChannel=e,this.dataChannel.onopen=()=>{W.log(`DC#${this.connectionId} dc connection success`),this._open=!0,this.emit("open")},this.dataChannel.onmessage=e=>{W.log(`DC#${this.connectionId} dc onmessage:`,e.data)},this.dataChannel.onclose=()=>{W.log(`DC#${this.connectionId} dc closed for:`,this.peer),this.close()}}close(e){if(e?.flush)return void this.send({__peerData:{type:"close"}});this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this.dataChannel=null),this.open&&(this._open=!1,super.emit("close"))}send(e,t=!1){return this.open?this._send(e,t):void this.emitError(K.NotOpenYet,"Connection is not open. You should listen for the `open` event before sending messages.")}async handleMessage(e){let t=e.payload;switch(e.type){case V.Answer:await this._negotiator.handleSDP(e.type,t.sdp);break;case V.Candidate:await this._negotiator.handleCandidate(t.candidate);break;default:W.warn("Unrecognized message type:",e.type,"from peer:",this.peer)}}}class es extends eo{constructor(e,t,n){super(e,t,{...n,reliable:!0}),this._CHUNK_SIZE=32768,this._splitStream=new TransformStream({transform:(e,t)=>{for(let n=0;n<e.length;n+=this._CHUNK_SIZE)t.enqueue(e.subarray(n,n+this._CHUNK_SIZE))}}),this._rawSendStream=new WritableStream({write:async(e,t)=>{let n=new Promise(e=>this.dataChannel.addEventListener("bufferedamountlow",e,{once:!0}));await (this.dataChannel.bufferedAmount<=eo.MAX_BUFFERED_AMOUNT-e.byteLength||n);try{this.dataChannel.send(e)}catch(e){W.error(`DC#:${this.connectionId} Error when sending:`,e),t.error(e),this.close()}}}),this.writer=this._splitStream.writable.getWriter(),this._rawReadStream=new ReadableStream({start:e=>{this.once("open",()=>{this.dataChannel.addEventListener("message",t=>{e.enqueue(t.data)})})}}),this._splitStream.readable.pipeTo(this._rawSendStream)}_initializeDataChannel(e){super._initializeDataChannel(e),this.dataChannel.binaryType="arraybuffer",this.dataChannel.bufferedAmountLowThreshold=eo.MAX_BUFFERED_AMOUNT/2}}class ea extends es{constructor(e,t,n){super(e,t,n),this.serialization="MsgPack",this._encoder=new P,(async()=>{var e,t,n,i;for await(let r of(e=this._rawReadStream,void 0===t&&(t=M),n=null!=(i=e)[Symbol.asyncIterator]?i:function(e){return F(this,arguments,function(){var t,n,i,r;return O(this,function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,z(t.read())];case 3:if(i=(n=o.sent()).done,r=n.value,!i)return[3,5];return[4,z(void 0)];case 4:return[2,o.sent()];case 5:if(null==r)throw Error("Assertion Failure: value must not be null nor undefined");return[4,z(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}(i),new R(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeStream(n))){if(r.__peerData?.type==="close")return void this.close();this.emit("data",r)}})()}_send(e){return this.writer.write(this._encoder.encode(e))}}export{ea as MsgPack};
//# sourceMappingURL=serializer.msgpack.mjs.map