UNPKG

@wioex/stream-sdk

Version:

WebSocket streaming SDK for real-time WioEX market data

1 lines • 56.4 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).WioexStreamJQuery=t()}(this,function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function s(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function r(e,t,s,r,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new n(s,r||e,o),h=i?i+t:t;return e._events[h]?e._events[h].fn?e._events[h]=[e._events[h],a]:e._events[h].push(a):(e._events[h]=a,e._eventsCount++),e}function o(e,t){0===--e._eventsCount?e._events=new s:delete e._events[t]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),a.prototype.eventNames=function(){var e,s,n=[];if(0===this._eventsCount)return n;for(s in e=this._events)t.call(e,s)&&n.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},a.prototype.listeners=function(e){var t=i?i+e:e,s=this._events[t];if(!s)return[];if(s.fn)return[s.fn];for(var n=0,r=s.length,o=new Array(r);n<r;n++)o[n]=s[n].fn;return o},a.prototype.listenerCount=function(e){var t=i?i+e:e,s=this._events[t];return s?s.fn?1:s.length:0},a.prototype.emit=function(e,t,s,n,r,o){var a=i?i+e:e;if(!this._events[a])return!1;var h,c,d=this._events[a],l=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,s),!0;case 4:return d.fn.call(d.context,t,s,n),!0;case 5:return d.fn.call(d.context,t,s,n,r),!0;case 6:return d.fn.call(d.context,t,s,n,r,o),!0}for(c=1,h=new Array(l-1);c<l;c++)h[c-1]=arguments[c];d.fn.apply(d.context,h)}else{var u,f=d.length;for(c=0;c<f;c++)switch(d[c].once&&this.removeListener(e,d[c].fn,void 0,!0),l){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,t);break;case 3:d[c].fn.call(d[c].context,t,s);break;case 4:d[c].fn.call(d[c].context,t,s,n);break;default:if(!h)for(u=1,h=new Array(l-1);u<l;u++)h[u-1]=arguments[u];d[c].fn.apply(d[c].context,h)}}return!0},a.prototype.on=function(e,t,i){return r(this,e,t,i,!1)},a.prototype.once=function(e,t,i){return r(this,e,t,i,!0)},a.prototype.removeListener=function(e,t,s,n){var r=i?i+e:e;if(!this._events[r])return this;if(!t)return o(this,r),this;var a=this._events[r];if(a.fn)a.fn!==t||n&&!a.once||s&&a.context!==s||o(this,r);else{for(var h=0,c=[],d=a.length;h<d;h++)(a[h].fn!==t||n&&!a[h].once||s&&a[h].context!==s)&&c.push(a[h]);c.length?this._events[r]=1===c.length?c[0]:c:o(this,r)}return this},a.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&o(this,t)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,e.exports=a}(t);var i=e(t.exports);const s=new TextEncoder;function n(e,t,i){e.length>50?function(e,t,i){s.encodeInto(e,t.subarray(i))}(e,t,i):function(e,t,i){const s=e.length;let n=i,r=0;for(;r<s;){let i=e.charCodeAt(r++);if(4294967168&i){if(4294965248&i){if(i>=55296&&i<=56319&&r<s){const t=e.charCodeAt(r);56320==(64512&t)&&(++r,i=((1023&i)<<10)+(1023&t)+65536)}4294901760&i?(t[n++]=i>>18&7|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128):(t[n++]=i>>12&15|224,t[n++]=i>>6&63|128)}else t[n++]=i>>6&31|192;t[n++]=63&i|128}else t[n++]=i}}(e,t,i)}function r(e,t,i){let s=t;const n=s+i,r=[];let o="";for(;s<n;){const t=e[s++];if(128&t)if(192==(224&t)){const i=63&e[s++];r.push((31&t)<<6|i)}else if(224==(240&t)){const i=63&e[s++],n=63&e[s++];r.push((31&t)<<12|i<<6|n)}else if(240==(248&t)){let i=(7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++];i>65535&&(i-=65536,r.push(i>>>10&1023|55296),i=56320|1023&i),r.push(i)}else r.push(t);else r.push(t);r.length>=4096&&(o+=String.fromCharCode(...r),r.length=0)}return r.length>0&&(o+=String.fromCharCode(...r)),o}const o=new TextDecoder;function a(e,t,i){return i>200?function(e,t,i){const s=e.subarray(t,t+i);return o.decode(s)}(e,t,i):r(e,t,i)}class h{constructor(e,t){this.type=e,this.data=t}}class c extends Error{constructor(e){super(e);const t=Object.create(c.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:c.name})}}const d=4294967295;function l(e,t,i){const s=Math.floor(i/4294967296),n=i;e.setUint32(t,s),e.setUint32(t+4,n)}function u(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const f={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183){if(0===t&&e<=4294967295){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const i=e/4294967296,s=4294967295&e,n=new Uint8Array(8),r=new DataView(n.buffer);return r.setUint32(0,t<<2|3&i),r.setUint32(4,s),n}}{const i=new Uint8Array(12),s=new DataView(i.buffer);return s.setUint32(0,t),l(s,4,e),i}}(function(e){const t=e.getTime(),i=Math.floor(t/1e3),s=1e6*(t-1e3*i),n=Math.floor(s/1e9);return{sec:i+n,nsec:s-1e9*n}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:u(t,4),nsec:t.getUint32(0)};default:throw new c(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class g{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(f)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(null!=s){const n=s(e,t);if(null!=n){return new h(-1-i,n)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(null!=s){const n=s(e,t);if(null!=n){return new h(i,n)}}}return e instanceof h?e:null}decode(e,t,i){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,i):new h(t,e)}}function p(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}g.defaultCodec=new g;class y{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??g.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new y({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),s=new DataView(t);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(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>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(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<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let i=0,s=0;for(;s<t;){let n=e.charCodeAt(s++);if(4294967168&n)if(4294965248&n){if(n>=55296&&n<=56319&&s<t){const t=e.charCodeAt(s);56320==(64512&t)&&(++s,n=((1023&n)<<10)+(1023&t)+65536)}i+=4294901760&n?4:3}else i+=2;else i++}return i}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),n(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(null!=i)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const 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<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const i=p(e);this.writeU8a(i)}encodeArray(e,t){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error(`Too large array: ${i}`);this.writeU8(221),this.writeU32(i)}for(const i of e)this.doEncode(i,t+1)}countWithoutUndefined(e,t){let i=0;for(const s of t)void 0!==e[s]&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large map object: ${s}`);this.writeU8(223),this.writeU32(s)}for(const s of i){const i=e[s];this.ignoreUndefined&&void 0===i||(this.encodeString(s),this.doEncode(i,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),i=t.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);return this.writeU8(201),this.writeU32(i),this.writeI8(e.type),void this.writeU8a(t)}const 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<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,i){const s=i/4294967296,n=i;e.setUint32(t,s),e.setUint32(t+4,n)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),l(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function w(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const m="array",b="map_key",S="map_value",k=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new c("The type of key must be string or number but "+typeof e)};class E{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=m,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=b,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===m){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===b||e.type===S){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const x=new DataView(new ArrayBuffer(0)),v=new Uint8Array(x.buffer);try{x.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const T=new RangeError("Insufficient data"),U=new class{constructor(e=16,t=16){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const s=this.caches[i-1];e:for(const n of s){const s=n.bytes;for(let n=0;n<i;n++)if(s[n]!==e[t+n])continue e;return n.str}return null}store(e,t){const i=this.caches[e.length-1],s={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,t,i){const s=this.find(e,t,i);if(null!=s)return this.hit++,s;this.miss++;const n=r(e,t,i),o=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(o,n),n}};class A{constructor(e){this.totalPos=0,this.pos=0,this.view=x,this.bytes=v,this.headByte=-1,this.stack=new E,this.entered=!1,this.extensionCodec=e?.extensionCodec??g.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??d,this.maxBinLength=e?.maxBinLength??d,this.maxArrayLength=e?.maxArrayLength??d,this.maxMapLength=e?.maxMapLength??d,this.maxExtLength=e?.maxExtLength??d,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:U,this.mapKeyConverter=e?.mapKeyConverter??k}clone(){return new A({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=p(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),i=p(e),s=new Uint8Array(t.length+i.length);s.set(t),s.set(i,t.length),this.setBuffer(s)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();return void(yield*t.decodeMulti(e))}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,i=!1;for await(const s of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{t=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:s,pos:n,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${w(s)} at ${r} (${n} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const i=this.clone();return void(yield*i.decodeMultiAsync(e,t))}try{this.entered=!0;let i=t,s=-1;for await(const n of e){if(t&&0===s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--s;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const i=e-128;if(0!==i){this.pushMapState(i),this.complete();continue e}t={}}else if(e<160){const i=e-144;if(0!==i){this.pushArrayState(i),this.complete();continue e}t=[]}else{const i=e-160;t=this.decodeString(i,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new c(`Unrecognized type byte: ${w(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const i=this.stack;for(;i.length>0;){const e=i.top();if(e.type===m){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,i.release(e)}else{if(e.type===b){if("__proto__"===t)throw new c("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=S;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=b;continue e}t=e.map,i.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new c(`Unrecognized array type byte: ${w(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new c(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new c(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new c(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw T;const i=this.pos+t;let s;return s=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,i,e):a(this.bytes,i,e),this.pos+=t+e,s}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===b}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new c(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw T;const i=this.pos+t,s=this.bytes.subarray(i,i+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new c(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,i=this.pos,4294967296*t.getUint32(i)+t.getUint32(i+4));var t,i;return this.pos+=8,e}readI64(){const e=u(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}var B,R;!function(e){e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.REGISTERED="registered",e.RECONNECTING="reconnecting",e.FAILED="failed"}(B||(B={}));class I{constructor(e=!1,t="WioEX"){this.enabled=e,this.prefix=t}setEnabled(e){this.enabled=e}getTimestamp(){return(new Date).toISOString().substring(11,23)}formatPrefix(){return`[${this.prefix} ${this.getTimestamp()}]`}log(e,t){this.enabled&&(void 0!==t?console.log(this.formatPrefix(),e,t):console.log(this.formatPrefix(),e))}warn(e,t){this.enabled&&(void 0!==t?console.warn(this.formatPrefix(),e,t):console.warn(this.formatPrefix(),e))}error(e,t){this.enabled&&(void 0!==t?console.error(this.formatPrefix(),e,t):console.error(this.formatPrefix(),e))}info(e,t){this.log(e,t)}debug(e,t){this.log(e,t)}}class C{constructor(e={},t,i=!1){this.sendBatch=t,this.queue=[],this.flushTimer=null,this.errorFingerprints=new Map,this.cleanupTimer=null,this.logger=new I(i,"WioEX:ErrorQueue"),this.config={maxBatchSize:e.maxBatchSize??10,flushInterval:e.flushInterval??5e3,deduplication:e.deduplication??!0,deduplicationWindow:e.deduplicationWindow??6e4,maxQueueSize:e.maxQueueSize??100},this.config.deduplication&&this.startCleanupTimer()}async add(e){this.config.deduplication&&this.isDuplicate(e)||(this.queue.length>=this.config.maxQueueSize&&await this.flush(),this.queue.push(e),this.config.deduplication&&this.updateFingerprint(e),this.queue.length>=this.config.maxBatchSize?await this.flush():this.scheduleFlush())}async flush(){if(this.cancelScheduledFlush(),0===this.queue.length)return;const e=this.queue.splice(0,this.queue.length);try{await this.sendBatch(e)}catch(e){this.logger.warn("Failed to send error batch:",e)}}destroy(){this.cancelScheduledFlush(),this.stopCleanupTimer(),this.queue=[],this.errorFingerprints.clear()}size(){return this.queue.length}isDuplicate(e){const t=this.getFingerprint(e),i=this.errorFingerprints.get(t);if(void 0===i)return!1;return Date.now()-i.lastSeen<this.config.deduplicationWindow}updateFingerprint(e){const t=this.getFingerprint(e);this.errorFingerprints.set(t,{type:e.error.type,message:e.error.message,lastSeen:Date.now()})}getFingerprint(e){const t=e.error.message.substring(0,100);return`${e.error.type}:${t}`}scheduleFlush(){null===this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flush()},this.config.flushInterval))}cancelScheduledFlush(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null)}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanupOldFingerprints()},6e4)}stopCleanupTimer(){null!==this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}cleanupOldFingerprints(){const e=Date.now()-this.config.deduplicationWindow;for(const[t,i]of this.errorFingerprints.entries())i.lastSeen<e&&this.errorFingerprints.delete(t)}}class D{constructor(e){this.sdkVersion="1.5.0",this.apiKeyHash=null,this.config=e,this.errorReportingUrl=e.errorReportingUrl??"https://api.wioex.com/v1/sdk/errors";const t=e.debug??this.isDebugMode();this.logger=new I(t,"WioEX:ErrorReporter"),this.errorQueue=new C(e.errorQueue??{},this.sendErrorBatch.bind(this),t)}async report(e,t={}){const i=this.config.errorReportingLevel??"detailed";if("none"!==i)try{const s=this.buildErrorPayload(e,t,i);await this.errorQueue.add(s)}catch(e){this.logger.warn("Failed to queue error for reporting:",e)}}async flush(){await this.errorQueue.flush()}destroy(){this.errorQueue.destroy()}buildErrorPayload(e,t,i){const s={sdk_version:this.sdkVersion,sdk_type:"stream",category:"stream",runtime:this.getRuntime(),api_key_id:this.getApiKeyIdentification(),reporting_level:i,error:{type:""!==e.name?e.name:"Error",message:e.message},timestamp:Date.now()};return"standard"!==i&&"detailed"!==i||void 0!==e.stack&&(s.error.stack=this.sanitizeStackTrace(e.stack,i)),"code"in e&&"string"==typeof e.code&&(s.error.code=e.code),"standard"!==i&&"detailed"!==i||(s.context=this.sanitizeContext(t,i)),s}sanitizeStackTrace(e,t){return"minimal"===t?e.split("\n")[0]??e:"standard"===t?e.split("\n").slice(0,5).map(e=>this.sanitizePath(e)).join("\n"):e.split("\n").map(e=>this.sanitizePath(e)).join("\n")}sanitizePath(e){return e.replace(/file:\/\/\/[^\s)]+\//g,"").replace(/[A-Z]:\\[^\s)]+\\/gi,"").replace(/\/(?:home|Users|var)\/[^\s)]+\//g,"")}sanitizeContext(e,t){const i={};if(void 0!==e.connectionState&&(i.connectionState=e.connectionState),void 0!==e.subscribedStocks&&(i.subscribedStocks=e.subscribedStocks),("standard"===t||"detailed"===t)&&((this.config.includeMessageData??"detailed"===t)&&(void 0!==e.lastMessage&&"string"==typeof e.lastMessage&&(i.lastMessage=this.truncateString(e.lastMessage,500)),void 0!==e.triggerMessage&&(i.triggerMessage=this.sanitizeMessageData(e.triggerMessage,t))),this.config.includeConnectionData??"detailed"===t))for(const[s,n]of Object.entries(e))"connectionState"!==s&&"subscribedStocks"!==s&&"lastMessage"!==s&&"triggerMessage"!==s&&(i[s]=this.sanitizeValue(n,t));return i}sanitizeMessageData(e,t){if(null==e)return e;if("string"==typeof e)return"detailed"===t?e:this.truncateString(e,200);if("object"==typeof e)try{const i=JSON.stringify(e);return"detailed"===t?i:this.truncateString(i,200)}catch{return"[Object]"}return String(e)}sanitizeValue(e,t){return null==e?e:"string"==typeof e?"detailed"===t?e:this.truncateString(e,100):"number"==typeof e||"boolean"==typeof e?e:Array.isArray(e)?"detailed"===t?e:e.slice(0,5):"object"==typeof e?"detailed"===t?e:"[Object]":String(e)}truncateString(e,t){return e.length<=t?e:e.substring(0,t)+"..."}getApiKeyIdentification(){return null!==this.apiKeyHash?this.apiKeyHash:this.config.apiKey?(this.apiKeyHash=this.syncHashApiKey(this.config.apiKey),this.apiKeyHash):this.config.token?(this.apiKeyHash=this.syncHashApiKey(this.config.token),this.apiKeyHash):(this.apiKeyHash="unknown",this.apiKeyHash)}syncHashApiKey(e){let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return Math.abs(t).toString(16).padStart(16,"0").substring(0,16)}getRuntime(){if("undefined"!=typeof window){return`Browser/${window.navigator.userAgent.split(" ").pop()??"Unknown"}`}return void 0!==process?.versions?.node?`Node.js/${process.versions.node}`:"Unknown"}async sendErrorBatch(e){0!==e.length&&await Promise.allSettled(e.map(async e=>{if("undefined"!=typeof fetch){const t=await fetch(this.errorReportingUrl,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`WioEX-Stream-SDK/${this.sdkVersion}`},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`)}else await this.sendWithHttps(e)}))}async sendWithHttps(e){const t=await import("https"),{URL:i}=await import("url"),s=new i(this.errorReportingUrl),n=JSON.stringify(e);return new Promise((e,i)=>{const r=t.request({hostname:s.hostname,port:""!==s.port?s.port:443,path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n),"User-Agent":`WioEX-Stream-SDK/${this.sdkVersion}`}},t=>{void 0!==t.statusCode&&t.statusCode>=400?i(new Error(`HTTP ${t.statusCode}: ${t.statusMessage??"Error"}`)):e()});r.on("error",i),r.write(n),r.end()})}isDebugMode(){return void 0!==process?.env?.DEBUG&&("wioex:*"===process.env.DEBUG||"wioex:errors"===process.env.DEBUG)}}class F{constructor(e,t={}){this.throttleTimer=null,this.rafId=null,this.lastEvent=null,this.eventBatch=[],this.emitFn=e,this.config={throttleInterval:t.throttleInterval??16,enableBatching:t.enableBatching??!1,maxBatchSize:t.maxBatchSize??10}}emit(e){0!==this.config.throttleInterval?this.config.enableBatching?this.addToBatch(e):(this.lastEvent=e,this.scheduleEmit()):this.emitFn(e)}flush(){this.cancelScheduled(),this.config.enableBatching?this.flushBatch():null!==this.lastEvent&&(this.emitFn(this.lastEvent),this.lastEvent=null)}destroy(){this.flush(),this.cancelScheduled(),this.eventBatch=[],this.lastEvent=null}addToBatch(e){this.eventBatch.push(e),this.eventBatch.length>=this.config.maxBatchSize?this.flushBatch():this.scheduleEmit()}flushBatch(){if(0===this.eventBatch.length)return;const e=this.eventBatch.splice(0,this.eventBatch.length);this.emitFn(e)}scheduleEmit(){null===this.throttleTimer&&null===this.rafId&&("undefined"!=typeof requestAnimationFrame?this.rafId=requestAnimationFrame(()=>{this.rafId=null,this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.config.enableBatching?this.flushBatch():null!==this.lastEvent&&(this.emitFn(this.lastEvent),this.lastEvent=null)},this.config.throttleInterval)}):this.throttleTimer=setTimeout(()=>{this.throttleTimer=null,this.config.enableBatching?this.flushBatch():null!==this.lastEvent&&(this.emitFn(this.lastEvent),this.lastEvent=null)},this.config.throttleInterval))}cancelScheduled(){null!==this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),null!==this.rafId&&"undefined"!=typeof cancelAnimationFrame&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}class L{static reportFirstUsage(){this.sendTelemetry()}static async sendTelemetry(){try{if(this.isTelemetryDisabled())return;if(this.hasReported())return;const e=this.buildPayload();await this.sendWithTimeout(e,5e3),this.markAsReported()}catch{}}static isTelemetryDisabled(){return"undefined"!=typeof process&&"1"===process.env?.[this.DISABLE_ENV]||"undefined"!=typeof window&&"1"===window.WIOEX_TELEMETRY_DISABLED}static hasReported(){if(this.isBrowser())try{return"1"===localStorage.getItem(this.STORAGE_KEY)}catch{return!1}else try{const e=require("fs"),t=require("os"),i=require("path").join(t.homedir(),".wioex",this.STORAGE_KEY);return e.existsSync(i)}catch{return!1}}static markAsReported(){if(this.isBrowser())try{localStorage.setItem(this.STORAGE_KEY,"1")}catch{}else try{const e=require("fs"),t=require("os"),i=require("path"),s=i.join(t.homedir(),".wioex"),n=i.join(s,this.STORAGE_KEY);e.existsSync(s)||e.mkdirSync(s,{recursive:!0}),e.writeFileSync(n,"1","utf-8")}catch{}}static buildPayload(){return{sdk_version:this.SDK_VERSION,sdk_type:"stream",runtime:this.getRuntime(),os:this.getOS(),first_install:!0,timestamp:Date.now(),anonymous_id:this.getAnonymousId()}}static getRuntime(){if("undefined"!=typeof window&&"undefined"!=typeof navigator){const e=navigator.userAgent;return e.includes("Chrome")?"Browser/Chrome":e.includes("Firefox")?"Browser/Firefox":e.includes("Safari")?"Browser/Safari":e.includes("Edge")?"Browser/Edge":"Browser/Unknown"}return"undefined"!=typeof process&&process.versions?.node?`Node.js/${process.versions.node}`:"Unknown"}static getOS(){if("undefined"!=typeof window&&"undefined"!=typeof navigator){const e=navigator.userAgent;return e.includes("Windows")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}if("undefined"!=typeof process&&process.platform){const e=process.platform;return"win32"===e?"Windows":"darwin"===e?"macOS":"linux"===e?"Linux":e}return"Unknown"}static getAnonymousId(){const e=`${this.getRuntime()}-${this.getOS()}-${Date.now()}`;let t=0;for(let i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t&=t}return Math.abs(t).toString(16).padStart(16,"0").substring(0,16)}static isBrowser(){return"undefined"!=typeof window&&void 0!==window.document}static async sendWithTimeout(e,t){const i="undefined"!=typeof AbortController?new AbortController:void 0,s=setTimeout(()=>{i?.abort()},t);try{if("undefined"!=typeof fetch){const t={method:"POST",headers:{"Content-Type":"application/json","User-Agent":`WioEX-Stream-SDK/${this.SDK_VERSION}`},body:JSON.stringify(e)};i&&(t.signal=i.signal);if(!(await fetch(this.TELEMETRY_URL,t)).ok)return}else await this.sendWithHttps(e)}finally{clearTimeout(s)}}static async sendWithHttps(e){const t=await import("https"),{URL:i}=await import("url");return new Promise(s=>{const n=new i(this.TELEMETRY_URL),r=JSON.stringify(e),o=t.request({hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r),"User-Agent":`WioEX-Stream-SDK/${this.SDK_VERSION}`},timeout:5e3},e=>{e.on("data",()=>{}),e.on("end",()=>{s()})});o.on("error",()=>{s()}),o.on("timeout",()=>{o.destroy(),s()}),o.write(r),o.end()})}}L.TELEMETRY_URL="https://api.wioex.com/v1/sdk/usage",L.DISABLE_ENV="WIOEX_TELEMETRY_DISABLED",L.SDK_VERSION="1.7.0",L.STORAGE_KEY="wioex_sdk_telemetry_reported";class M extends i{constructor(e){super(),this.ws=null,this.state=B.DISCONNECTED,this.subscribedStocks=new Set,this.reconnectAttempts=0,this.reconnectTimer=null,this.tokenExpiresAt=null,this.tokenRefreshTimer=null,this.isRefreshingToken=!1,this.isReconnecting=!1,this.lastReceivedMessage=null,this.tickerThrottler=null,this.signalSubscriptions=new Set;if("undefined"!=typeof window&&e.apiKey)throw new Error('šŸ”’ SECURITY ERROR: apiKey cannot be used in browser!\n\nAPI keys MUST stay on your backend server.\n\nāœ… CORRECT - Use tokenEndpoint:\n const client = new WioexStream({\n tokenEndpoint: "/api/stream/token"\n });\n\nāŒ WRONG - Never use apiKey in browser:\n const client = new WioexStream({\n apiKey: "xxx" // ← Visible in DevTools!\n });\n\nBackend examples: examples/backend-token-proxy.{php,js,py,go,java}\nDocs: https://github.com/wioex/stream-sdk#browser-security');if(!e.token&&!e.apiKey&&!e.tokenEndpoint)throw new Error("Either token, tokenEndpoint, or apiKey is required.");if(void 0!==e.token&&""===e.token.trim())throw new Error("Token cannot be empty or whitespace");const t=e.maxSymbols??50;if(t<1||t>50)throw new Error("maxSymbols must be between 1 and 50");this.config={apiKey:e.apiKey,token:e.token,tokenExpiresAt:e.tokenExpiresAt,tokenEndpoint:e.tokenEndpoint,tokenFetchHeaders:e.tokenFetchHeaders,tokenFetchRetry:e.tokenFetchRetry??{maxAttempts:3,delay:1e3,backoff:"exponential"},onTokenExpiring:e.onTokenExpiring,autoRefreshToken:e.autoRefreshToken??void 0!==e.onTokenExpiring,refreshBeforeExpiry:e.refreshBeforeExpiry??36e5,lazyConnect:e.lazyConnect??!0,debug:e.debug??!1,maxSymbols:t,autoReconnect:e.autoReconnect??!0,reconnectDelay:e.reconnectDelay??3e3,maxReconnectAttempts:e.maxReconnectAttempts??0,streamUrl:e.streamUrl??`wss://stream.wioex.com/rs/i/${this.generateRandomId(8)}/websocket`,errorReportingLevel:e.errorReportingLevel??"detailed",errorReportingUrl:e.errorReportingUrl,includeMessageData:e.includeMessageData,includeConnectionData:e.includeConnectionData,enableStats:e.performance?.enableStats??!0,useBinaryProtocol:e.performance?.useBinaryProtocol??!1},e.tokenExpiresAt&&(this.tokenExpiresAt=e.tokenExpiresAt),this.stats={connectedAt:null,reconnectAttempts:0,messagesReceived:0,messagesSent:0,tickersReceived:0,subscribedStocks:[],state:this.state};const i={};void 0!==e.performance?.errorBatchSize&&(i.maxBatchSize=e.performance.errorBatchSize),void 0!==e.performance?.errorBatchInterval&&(i.flushInterval=e.performance.errorBatchInterval),void 0!==e.performance?.errorDeduplication&&(i.deduplication=e.performance.errorDeduplication);const s={};void 0!==this.config.apiKey&&(s.apiKey=this.config.apiKey),void 0!==this.config.token&&(s.token=this.config.token),void 0!==this.config.errorReportingLevel&&(s.errorReportingLevel=this.config.errorReportingLevel),void 0!==this.config.errorReportingUrl&&(s.errorReportingUrl=this.config.errorReportingUrl),void 0!==this.config.includeMessageData&&(s.includeMessageData=this.config.includeMessageData),void 0!==this.config.includeConnectionData&&(s.includeConnectionData=this.config.includeConnectionData),Object.keys(i).length>0&&(s.errorQueue=i),s.debug=this.config.debug,this.errorReporter=new D(s),this.logger=new I(this.config.debug);const n=e.performance?.tickerThrottle??16;n>0&&(this.tickerThrottler=new F(e=>{Array.isArray(e)?e.forEach(e=>super.emit("ticker",e)):super.emit("ticker",e)},{throttleInterval:n,enableBatching:e.performance?.batchTickers??!1,maxBatchSize:e.performance?.tickerBatchSize??10})),this.config.autoRefreshToken&&this.tokenExpiresAt&&this.scheduleTokenRefresh(),L.reportFirstUsage()}log(e,t){this.logger.log(e,t)}async connect(){if(this.state!==B.CONNECTED&&this.state!==B.CONNECTING){if(this.log("Connecting to WioEX stream...",{streamUrl:this.config.streamUrl}),!this.config.token)if(this.config.tokenEndpoint){this.log("No token provided, fetching from endpoint");try{await this.fetchTokenFromEndpoint()}catch(e){const t=e instanceof Error?e:new Error(String(e));return void this.handleError(t)}}else{if(!this.config.apiKey)return void this.handleError(new Error("Token is required but not available.\nPlease provide either apiKey or token in config."));this.log("No token provided, fetching from WioEX API with apiKey");try{await this.fetchTokenFromApiKey()}catch(e){const t=e instanceof Error?e:new Error(String(e));return void this.handleError(t)}}this.setState(B.CONNECTING);try{const e=this.getWebSocketImplementation();this.ws=new e(this.config.streamUrl),this.ws.binaryType="arraybuffer",this.ws.onopen=this.handleOpen.bind(this),this.ws.onmessage=this.handleMessage.bind(this),this.ws.onerror=this.handleError.bind(this),this.ws.onclose=this.handleClose.bind(this)}catch(e){this.handleError(e instanceof Error?e:new Error(String(e)))}}else this.log("Already connected or connecting, skipping connect()")}disconnect(){this.config.autoReconnect=!1,this.clearTimers(),this.tickerThrottler?.flush(),this.errorReporter.flush(),null!==this.ws&&(this.ws.close(1e3,"Client disconnected"),this.ws=null),this.setState(B.DISCONNECTED)}subscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one stock symbol is required");if(this.subscribedStocks.size+t.filter(e=>!this.subscribedStocks.has(e)).length>this.config.maxSymbols)throw new Error(`Cannot subscribe to more than ${this.config.maxSymbols} symbols. Current: ${this.subscribedStocks.size}`);if(t.forEach(e=>this.subscribedStocks.add(e.toUpperCase())),this.config.lazyConnect&&this.state===B.DISCONNECTED)return this.log("Lazy connect triggered by subscribe()",{stocks:t}),void this.connect();this.state===B.REGISTERED&&this.sendMessage({action:"subscribe",stocks:[...this.subscribedStocks]})}unsubscribe(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one stock symbol is required");t.forEach(e=>this.subscribedStocks.delete(e.toUpperCase())),this.state===B.REGISTERED&&this.sendMessage({action:"unsubscribe",stocks:t.map(e=>e.toUpperCase())})}subscribeSignals(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one symbol is required");this.log("Subscribing to signals",{symbols:t}),t.forEach(e=>this.signalSubscriptions.add(e.toUpperCase())),this.state===B.REGISTERED?this.sendMessage({action:"subscribe-signals",symbols:[...this.signalSubscriptions]}):this.log("Not connected, signal subscription will be sent after registration")}unsubscribeSignals(e){const t=Array.isArray(e)?e:[e];if(0===t.length)throw new Error("At least one symbol is required");this.log("Unsubscribing from signals",{symbols:t}),t.forEach(e=>this.signalSubscriptions.delete(e.toUpperCase())),this.state===B.REGISTERED&&this.sendMessage({action:"unsubscribe-signals",symbols:t.map(e=>e.toUpperCase())})}getSignalSubscriptions(){return Array.from(this.signalSubscriptions)}getState(){return this.state}getSubscribedStocks(){return[...this.subscribedStocks]}getStats(){return{...this.stats,subscribedStocks:this.getSubscribedStocks(),state:this.state}}isConnected(){return this.state===B.CONNECTED||this.state===B.REGISTERED}handleOpen(){this.setState(B.CONNECTED),this.config.enableStats&&(this.stats.connectedAt=Date.now(),this.stats.reconnectAttempts=0),this.reconnectAttempts=0,this.emit("connected"),this.config.token?this.sendMessage({action:"register",token:this.config.token}):this.handleError(new Error("Token is not available for registration"))}handleMessage(e){this.config.enableStats&&this.stats.messagesReceived++;const t=e.data;this.lastReceivedMessage="string"==typeof t?t:"[Binary Data]";try{let e;if(t instanceof ArrayBuffer||t instanceof Uint8Array)i=t instanceof ArrayBuffer?new Uint8Array(t):t,e=new A(s).decode(i);else{if("string"!=typeof t)throw new Error("Unsupported message format");e=JSON.parse(t)}if("object"!=typeof e||null===e)throw new Error("Invalid message format");const n=e;if("type"in n&&"ticker"===n.type)return void this.handleTicker(e);if("type"in n&&"registered"===n.type)return void this.handleRegistration(e);if("type"in n&&("subscribed"===n.type||"unsubscribed"===n.type))return void this.handleSubscription(e);if("type"in n&&"signal"===n.type)return void this.handleSignal(e);if("type"in n&&"signal-triggered"===n.type)return void this.handleSignalTriggered(e);if("type"in n&&"signalSubscribed"===n.type)return void this.handleSignalSubscription(e);if("type"in n&&"signalUnsubscribed"===n.type)return void this.handleSignalUnsubscription(e);if("status"in n&&"error"===n.status){const t=new Error("string"==typeof n.message?n.message:"Unknown error");return this.reportError(t,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],triggerMessage:e}),void this.emit("error",t)}}catch(e){const t=e instanceof Error?e.message:String(e),i=new Error(`Failed to parse message: ${t}`);this.reportError(i,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],lastMessage:this.lastReceivedMessage??void 0}),this.emit("error",i)}var i,s}handleError(e){const t=e instanceof Error?e:new Error("WebSocket error");this.reportError(t,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks]}),this.emit("error",t)}handleClose(e){this.clearTimers();const t=this.isConnected();this.setState(B.DISCONNECTED),this.emit("disconnected",e.code,e.reason),this.config.autoReconnect&&t&&this.attemptReconnect()}handleRegistration(e){if("success"===e.status)this.setState(B.REGISTERED),this.emit("registered",e),this.subscribedStocks.size>0&&this.sendMessage({action:"subscribe",stocks:[...this.subscribedStocks]}),this.signalSubscriptions.size>0&&this.sendMessage({action:"subscribe-signals",symbols:[...this.signalSubscriptions]});else{const t=new Error(`Registration failed: ${e.message}`);this.reportError(t,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],triggerMessage:e}),this.emit("error",t),this.disconnect()}}handleSubscription(e){if("success"===e.status)"subscribed"===e.type&&void 0!==e.stocks?this.emit("subscribed",e.stocks):"unsubscribed"===e.type&&void 0!==e.stocks&&this.emit("unsubscribed",e.stocks);else{const t=new Error(`Subscription failed: ${e.message}`);this.reportError(t,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],triggerMessage:e}),this.emit("error",t)}}handleTicker(e){this.config.enableStats&&this.stats.tickersReceived++;const t=e.data;null!==this.tickerThrottler?this.tickerThrottler.emit(t):this.emit("ticker",t)}handleSignal(e){this.log("Signal received",{symbol:e.data.symbol,type:e.data.signalType}),this.emit("signal",e.data)}handleSignalTriggered(e){this.log("Signal triggered",{symbol:e.data.symbol,triggerType:e.data.triggerType}),this.emit("signalTriggered",e.data)}handleSignalSubscription(e){if("success"===e.status)this.log("Signal subscription successful",{symbols:e.symbols}),this.emit("signalSubscribed",e.symbols||[]);else{const t=new Error(`Signal subscription failed: ${e.message}`);this.log("Signal subscription error",{message:e.message}),this.reportError(t,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],triggerMessage:e}),this.emit("signalError",t)}}handleSignalUnsubscription(e){if("success"===e.status)this.log("Signal unsubscription successful"),this.emit("signalUnsubscribed",[]);else{const t=new Error(`Signal unsubscription failed: ${e.message}`);this.log("Signal unsubscription error",{message:e.message}),this.emit("signalError",t)}}sendMessage(e){if(null===this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");if(this.config.useBinaryProtocol){const s=(t=e,new y(i).encodeSharedRef(t));this.ws.send(s)}else this.ws.send(JSON.stringify(e));var t,i;this.config.enableStats&&this.stats.messagesSent++}attemptReconnect(){if(!this.isReconnecting){if(this.config.maxReconnectAttempts>0&&this.reconnectAttempts>=this.config.maxReconnectAttempts){this.setState(B.FAILED);const e=new Error("Max reconnection attempts reached");return this.reportError(e,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks],reconnectAttempts:this.reconnectAttempts}),void this.emit("error",e)}this.isReconnecting=!0,this.reconnectAttempts++,this.config.enableStats&&this.stats.reconnectAttempts++,this.setState(B.RECONNECTING),this.emit("reconnecting",this.reconnectAttempts),this.reconnectTimer=setTimeout(()=>{this.isReconnecting=!1,this.connect()},this.config.reconnectDelay)}}clearTimers(){null!==this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.isReconnecting=!1),this.cancelTokenRefresh()}setState(e){const t=this.state;this.state=e,this.config.enableStats&&(this.stats.state=e),t!==e&&this.emit("stateChange",e)}getWebSocketImplementation(){if("undefined"!=typeof WebSocket)return WebSocket;try{return require("ws").WebSocket}catch(e){throw new Error('WebSocket implementation not found. Please install "ws" package for Node.js')}}updateToken(e,t){if(!e||""===e.trim())throw new Error("Token cannot be empty");this.config.token=e,this.tokenExpiresAt=t,this.cancelTokenRefresh(),this.config.autoRefreshToken&&this.scheduleTokenRefresh(),this.emit("tokenRefreshed",{token:e,expiresAt:t})}scheduleTokenRefresh(){if(!this.tokenExpiresAt||!this.config.onTokenExpiring)return;this.cancelTokenRefresh();const e=Date.now(),t=1e3*this.tokenExpiresAt-this.config.refreshBeforeExpiry,i=Math.max(0,t-e);this.tokenRefreshTimer=setTimeout(()=>{this.handleTokenRefresh()},i)}async handleTokenRefresh(){if(!this.isRefreshingToken&&this.config.onTokenExpiring){if(!this.config.token){const e=new Error("Token is not available for refresh");return this.emit("tokenRefreshFailed",e),void this.reportError(e,{connectionState:this.state,subscribedStocks:[...this.subscribedStocks]})}this.isRefreshingToken=!0;try{this.emit("tokenExpiring",{currentToken:this.config.token,ex