@js-toolkit/web-utils 1.47.0 → 1.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{__rest}from"tslib";import isEmptyObject from"@jstoolkit/utils/isEmptyObject";export function isEventTargetLike(t){return void 0!==t.addEventListener&&void 0!==t.removeEventListener}export function isDomEventTarget(t){return isEventTargetLike(t)&&void 0!==t.dispatchEvent}export function isEventEmitterLike(t){return!isEventTargetLike(t)&&!isDomEventTarget(t)&&void 0!==t.on&&void 0!==t.once&&void 0!==t.off}let passiveSupported=!1;export function isPassiveSupported(){return passiveSupported}try{const t={get passive(){return passiveSupported=!0,!1}};window.addEventListener("__testpassive__",null,t)}catch(e){}export function normalizeOptions(t){if(t&&"object"==typeof t){let e=t;if("passive"in t&&!passiveSupported){const{passive:i}=t;e=__rest(t,["passive"])}return isEmptyObject(e)?void 0:e}return t}
1
+ import{__rest}from"tslib";import isEmptyObject from"@js-toolkit/utils/isEmptyObject";export function isEventTargetLike(t){return void 0!==t.addEventListener&&void 0!==t.removeEventListener}export function isDomEventTarget(t){return isEventTargetLike(t)&&void 0!==t.dispatchEvent}export function isEventEmitterLike(t){return!isEventTargetLike(t)&&!isDomEventTarget(t)&&void 0!==t.on&&void 0!==t.once&&void 0!==t.off}let passiveSupported=!1;export function isPassiveSupported(){return passiveSupported}try{const t={get passive(){return passiveSupported=!0,!1}};window.addEventListener("__testpassive__",null,t)}catch(e){}export function normalizeOptions(t){if(t&&"object"==typeof t){let e=t;if("passive"in t&&!passiveSupported){const{passive:i}=t;e=__rest(t,["passive"])}return isEmptyObject(e)?void 0:e}return t}
package/fullscreen.js CHANGED
@@ -1 +1 @@
1
- import es5ErrorCompat from"@jstoolkit/utils/es5ErrorCompat";export class FullscreenUnavailableError extends Error{constructor(){super("Fullscreen is not available"),es5ErrorCompat(this,FullscreenUnavailableError)}}export var fullscreen;!function(e){e.names=[{requestFullscreenName:"requestFullscreen",exitFullscreenName:"exitFullscreen",fullscreenElementName:"fullscreenElement",fullscreenEnabledName:"fullscreenEnabled",changeEventName:"fullscreenchange",errorEventName:"fullscreenerror"},{requestFullscreenName:"webkitRequestFullscreen",exitFullscreenName:"webkitExitFullscreen",fullscreenElementName:"webkitFullscreenElement",fullscreenEnabledName:"webkitFullscreenEnabled",changeEventName:"webkitfullscreenchange",errorEventName:"webkitfullscreenerror"},{requestFullscreenName:"webkitRequestFullScreen",exitFullscreenName:"webkitCancelFullScreen",fullscreenElementName:"webkitCurrentFullScreenElement",fullscreenEnabledName:"webkitCancelFullScreen",changeEventName:"webkitfullscreenchange",errorEventName:"webkitfullscreenerror"},{requestFullscreenName:"mozRequestFullScreen",exitFullscreenName:"mozCancelFullScreen",fullscreenElementName:"mozFullScreenElement",fullscreenEnabledName:"mozFullScreenEnabled",changeEventName:"mozfullscreenchange",errorEventName:"mozfullscreenerror"},{requestFullscreenName:"msRequestFullscreen",exitFullscreenName:"msExitFullscreen",fullscreenElementName:"msFullscreenElement",fullscreenEnabledName:"msFullscreenEnabled",changeEventName:"MSFullscreenChange",errorEventName:"MSFullscreenError"}].find((({exitFullscreenName:e})=>e in document));const n={change:null===e.names||void 0===e.names?void 0:e.names.changeEventName,error:null===e.names||void 0===e.names?void 0:e.names.errorEventName};function r(){if(!e.names)throw new e.UnavailableError;return Boolean(document[e.names.fullscreenElementName])}function l(e,r,l){const a=n[e];a&&document.addEventListener(a,r,l)}function a(e,r,l){const a=n[e];a&&document.removeEventListener(a,r,l)}function t(n,r){return new Promise(((t,s)=>{if(!e.names)throw new e.UnavailableError;const c=()=>{a("change",c),a("error",u),t()},u=e=>{a("change",c),a("error",u),s(e)};l("change",c),l("error",u);const o=n[e.names.requestFullscreenName](r);o instanceof Promise&&o.then(c,u)}))}function s(){return new Promise(((n,t)=>{if(!e.names)throw new e.UnavailableError;if(!r)return void n();const s=()=>{a("change",s),a("error",c),n()},c=e=>{a("change",s),a("error",c),t(e)};l("change",s),l("error",c);const u=document[e.names.exitFullscreenName]();u instanceof Promise&&u.then(s,c)}))}e.UnavailableError=FullscreenUnavailableError,e.isSupported=function(){return!!e.names},e.isEnabled=function(){return!!e.names&&Boolean(document[e.names.fullscreenEnabledName])},e.isFullscreen=r,e.getElement=function(){if(!e.names)throw new e.UnavailableError;return document[e.names.fullscreenElementName]},e.on=l,e.off=a,e.request=t,e.exit=s,e.toggle=function(e){return Promise.resolve().then((()=>r()?s():t(e)))},e.onChange=function(e){l("change",e)},e.onError=function(e){l("error",e)}}(fullscreen||(fullscreen={}));export default fullscreen;
1
+ import es5ErrorCompat from"@js-toolkit/utils/es5ErrorCompat";export class FullscreenUnavailableError extends Error{constructor(){super("Fullscreen is not available"),es5ErrorCompat(this,FullscreenUnavailableError)}}export var fullscreen;!function(e){e.names=[{requestFullscreenName:"requestFullscreen",exitFullscreenName:"exitFullscreen",fullscreenElementName:"fullscreenElement",fullscreenEnabledName:"fullscreenEnabled",changeEventName:"fullscreenchange",errorEventName:"fullscreenerror"},{requestFullscreenName:"webkitRequestFullscreen",exitFullscreenName:"webkitExitFullscreen",fullscreenElementName:"webkitFullscreenElement",fullscreenEnabledName:"webkitFullscreenEnabled",changeEventName:"webkitfullscreenchange",errorEventName:"webkitfullscreenerror"},{requestFullscreenName:"webkitRequestFullScreen",exitFullscreenName:"webkitCancelFullScreen",fullscreenElementName:"webkitCurrentFullScreenElement",fullscreenEnabledName:"webkitCancelFullScreen",changeEventName:"webkitfullscreenchange",errorEventName:"webkitfullscreenerror"},{requestFullscreenName:"mozRequestFullScreen",exitFullscreenName:"mozCancelFullScreen",fullscreenElementName:"mozFullScreenElement",fullscreenEnabledName:"mozFullScreenEnabled",changeEventName:"mozfullscreenchange",errorEventName:"mozfullscreenerror"},{requestFullscreenName:"msRequestFullscreen",exitFullscreenName:"msExitFullscreen",fullscreenElementName:"msFullscreenElement",fullscreenEnabledName:"msFullscreenEnabled",changeEventName:"MSFullscreenChange",errorEventName:"MSFullscreenError"}].find((({exitFullscreenName:e})=>e in document));const n={change:null===e.names||void 0===e.names?void 0:e.names.changeEventName,error:null===e.names||void 0===e.names?void 0:e.names.errorEventName};function r(){if(!e.names)throw new e.UnavailableError;return Boolean(document[e.names.fullscreenElementName])}function l(e,r,l){const a=n[e];a&&document.addEventListener(a,r,l)}function a(e,r,l){const a=n[e];a&&document.removeEventListener(a,r,l)}function t(n,r){return new Promise(((t,s)=>{if(!e.names)throw new e.UnavailableError;const c=()=>{a("change",c),a("error",u),t()},u=e=>{a("change",c),a("error",u),s(e)};l("change",c),l("error",u);const o=n[e.names.requestFullscreenName](r);o instanceof Promise&&o.then(c,u)}))}function s(){return new Promise(((n,t)=>{if(!e.names)throw new e.UnavailableError;if(!r)return void n();const s=()=>{a("change",s),a("error",c),n()},c=e=>{a("change",s),a("error",c),t(e)};l("change",s),l("error",c);const u=document[e.names.exitFullscreenName]();u instanceof Promise&&u.then(s,c)}))}e.UnavailableError=FullscreenUnavailableError,e.isSupported=function(){return!!e.names},e.isEnabled=function(){return!!e.names&&Boolean(document[e.names.fullscreenEnabledName])},e.isFullscreen=r,e.getElement=function(){if(!e.names)throw new e.UnavailableError;return document[e.names.fullscreenElementName]},e.on=l,e.off=a,e.request=t,e.exit=s,e.toggle=function(e){return Promise.resolve().then((()=>r()?s():t(e)))},e.onChange=function(e){l("change",e)},e.onError=function(e){l("error",e)}}(fullscreen||(fullscreen={}));export default fullscreen;
package/getAspectRatio.js CHANGED
@@ -1 +1 @@
1
- import farey from"@jstoolkit/utils/farey";export function getAspectRatio(t,e){const o=t/e,[r,i]=farey(o,50);return{width:r,height:i,ratio:o}}export default getAspectRatio;
1
+ import farey from"@js-toolkit/utils/farey";export function getAspectRatio(t,e){const o=t/e,[r,i]=farey(o,50);return{width:r,height:i,ratio:o}}export default getAspectRatio;
@@ -1,4 +1,4 @@
1
- import { type Awaiter } from '@jstoolkit/utils/getAwaiter';
1
+ import { type Awaiter } from '@js-toolkit/utils/getAwaiter';
2
2
  import { type EmitterTarget, type GetEventType } from './EventEmitterListener.utils';
3
3
  export type EventAwaiter = Awaiter<void>;
4
4
  export declare function getEventAwaiter<T extends EmitterTarget, E extends GetEventType<T>>(target: T, resolveEvent: E | E[], rejectEvent?: E | E[],
@@ -1 +1 @@
1
- import{getAwaiter}from"@jstoolkit/utils/getAwaiter";import{EventEmitterListener}from"./EventEmitterListener";import{isEventEmitterLike}from"./EventEmitterListener.utils";export function getEventAwaiter(t,e,r,i){const o=getAwaiter({lazy:!0}),n=Array.isArray(e)?e:[e],s=Array.isArray(r)?r:[r],E=isEventEmitterLike(t)?t:new EventEmitterListener(t),a=()=>{n.forEach((t=>E.off(t,m))),s.forEach((t=>E.off(t,m)))},c=o.resolve;o.resolve=(...t)=>{a(),c(...t)};const f=o.reject;o.reject=(...t)=>{f(...t),a()};const m=()=>{o.resolve()},v=t=>{const e=i?i(t):t;null!=e&&o.reject(e)};return n.forEach((t=>E.on(t,m))),s.forEach((t=>E.on(t,v))),o}
1
+ import{getAwaiter}from"@js-toolkit/utils/getAwaiter";import{EventEmitterListener}from"./EventEmitterListener";import{isEventEmitterLike}from"./EventEmitterListener.utils";export function getEventAwaiter(t,e,r,i){const o=getAwaiter({lazy:!0}),n=Array.isArray(e)?e:[e],s=Array.isArray(r)?r:[r],E=isEventEmitterLike(t)?t:new EventEmitterListener(t),a=()=>{n.forEach((t=>E.off(t,m))),s.forEach((t=>E.off(t,m)))},c=o.resolve;o.resolve=(...t)=>{a(),c(...t)};const f=o.reject;o.reject=(...t)=>{f(...t),a()};const m=()=>{o.resolve()},v=t=>{const e=i?i(t):t;null!=e&&o.reject(e)};return n.forEach((t=>E.on(t,m))),s.forEach((t=>E.on(t,v))),o}
@@ -1 +1 @@
1
- import{toInt}from"@jstoolkit/utils/toInt";export function getSecondsCounter({onChange:t}={}){const e=new Set;let n=t,o=!1;return{getTotal:()=>e.size,push(t){if(o)throw new Error("SecondsCounter was destroyed.");const r="number"==typeof t?t:"currentTime"in t?t.currentTime:t.data.currentTime;if(null==t)return;const s=toInt(r);s>0&&!e.has(s)&&(e.add(s),n&&n({value:s,total:e.size}))},get onChange(){return n},set onChange(t){n=t},reset(){e.clear()},destroy(){o=!0,n=void 0,this.reset()}}}export default getSecondsCounter;
1
+ import{toInt}from"@js-toolkit/utils/toInt";export function getSecondsCounter({onChange:t}={}){const e=new Set;let n=t,o=!1;return{getTotal:()=>e.size,push(t){if(o)throw new Error("SecondsCounter was destroyed.");const r="number"==typeof t?t:"currentTime"in t?t.currentTime:t.data.currentTime;if(null==t)return;const s=toInt(r);s>0&&!e.has(s)&&(e.add(s),n&&n({value:s,total:e.size}))},get onChange(){return n},set onChange(t){n=t},reset(){e.clear()},destroy(){o=!0,n=void 0,this.reset()}}}export default getSecondsCounter;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@js-toolkit/web-utils",
3
- "version": "1.47.0",
3
+ "version": "1.47.1",
4
4
  "description": "Web utils",
5
5
  "author": "VZH",
6
6
  "license": "MIT",
@@ -21,11 +21,11 @@
21
21
  },
22
22
  "devDependencies": {
23
23
  "@js-toolkit/configs": "^3.87.5",
24
- "@js-toolkit/utils": "^1.49.1",
24
+ "@js-toolkit/utils": "^1.49.2",
25
25
  "@types/ua-parser-js": "^0.7.36",
26
26
  "@types/uuid": "^9.0.2",
27
- "@typescript-eslint/eslint-plugin": "^6.3.0",
28
- "@typescript-eslint/parser": "^6.3.0",
27
+ "@typescript-eslint/eslint-plugin": "^6.4.0",
28
+ "@typescript-eslint/parser": "^6.4.0",
29
29
  "copyfiles": "^2.4.1",
30
30
  "eslint": "^8.47.0",
31
31
  "eslint-config-airbnb-base": "^15.0.0",
package/takeSnapshot.js CHANGED
@@ -1 +1 @@
1
- import{hasIn}from"@jstoolkit/utils/hasIn";export function get2dContextError(){return new Error("Failed to get canvas 2d context.")}const getDefaultWidth=t=>t instanceof HTMLVideoElement?t.videoWidth:hasIn(t,"displayWidth")?t.displayWidth:t.width instanceof SVGAnimatedLength?t.width.animVal.value:t.width,getDefaultHeight=t=>t instanceof HTMLVideoElement?t.videoHeight:hasIn(t,"displayHeight")?t.displayHeight:t.height instanceof SVGAnimatedLength?t.height.animVal.value:t.height;export function takeSnapshot(t,{width:e=getDefaultWidth(t),height:i=getDefaultHeight(t),type:n="image/jpeg",quality:a=1}={}){const o=document.createElement("canvas");o.width=e,o.height=i;const h=o.getContext("2d");if(!h)throw get2dContextError();return h.drawImage(t,0,0),o.toDataURL(n,a)}export function takeSnapshotAsync(t,{width:e=getDefaultWidth(t),height:i=getDefaultHeight(t),type:n="image/jpeg",quality:a=1}={}){return new Promise(((o,h)=>{const d=document.createElement("canvas");d.width=e,d.height=i;const g=d.getContext("2d");if(!g)throw get2dContextError();g.drawImage(t,0,0),d.toBlob((t=>{null==t?h(new Error("Unable get blob")):o(t)}),n,a)}))}
1
+ import{hasIn}from"@js-toolkit/utils/hasIn";export function get2dContextError(){return new Error("Failed to get canvas 2d context.")}const getDefaultWidth=t=>t instanceof HTMLVideoElement?t.videoWidth:hasIn(t,"displayWidth")?t.displayWidth:t.width instanceof SVGAnimatedLength?t.width.animVal.value:t.width,getDefaultHeight=t=>t instanceof HTMLVideoElement?t.videoHeight:hasIn(t,"displayHeight")?t.displayHeight:t.height instanceof SVGAnimatedLength?t.height.animVal.value:t.height;export function takeSnapshot(t,{width:e=getDefaultWidth(t),height:i=getDefaultHeight(t),type:n="image/jpeg",quality:a=1}={}){const o=document.createElement("canvas");o.width=e,o.height=i;const h=o.getContext("2d");if(!h)throw get2dContextError();return h.drawImage(t,0,0),o.toDataURL(n,a)}export function takeSnapshotAsync(t,{width:e=getDefaultWidth(t),height:i=getDefaultHeight(t),type:n="image/jpeg",quality:a=1}={}){return new Promise(((o,h)=>{const d=document.createElement("canvas");d.width=e,d.height=i;const g=d.getContext("2d");if(!g)throw get2dContextError();g.drawImage(t,0,0),d.toBlob((t=>{null==t?h(new Error("Unable get blob")):o(t)}),n,a)}))}
package/types/refs.d.ts CHANGED
@@ -1 +1 @@
1
- import '@jstoolkit/utils/types';
1
+ import '@js-toolkit/utils/types';
package/types/refs.js CHANGED
@@ -1 +1 @@
1
- import"@jstoolkit/utils/types";
1
+ import"@js-toolkit/utils/types";
@@ -1,4 +1,4 @@
1
- import DataEventEmitter, { type DataEventListener, type DataEventMap } from '@jstoolkit/utils/DataEventEmitter';
1
+ import DataEventEmitter, { type DataEventListener, type DataEventMap } from '@js-toolkit/utils/DataEventEmitter';
2
2
  import * as sdpUtils from './sdputils';
3
3
  export declare class PeerConnection extends DataEventEmitter<PeerConnection.EventMap, PeerConnection> {
4
4
  readonly options: PeerConnection.Options;
@@ -1 +1 @@
1
- import{__awaiter}from"tslib";import DataEventEmitter,{}from"@jstoolkit/utils/DataEventEmitter";import getErrorMessage from"@jstoolkit/utils/getErrorMessage";import{hasIn}from"@jstoolkit/utils/hasIn";import*as sdpUtils from"./sdputils";export class PeerConnection extends DataEventEmitter{get Events(){return PeerConnection.Events}constructor(e={}){var t;super(),this.options=e,this.logger=null!==(t=e.logger)&&void 0!==t?t:console,this.pc=this.createPC()}clear(){this.pc.onsignalingstatechange=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onnegotiationneeded=null,this.pc.onicecandidate=null,this.pc.onicecandidateerror=null}createPC(){const e=new RTCPeerConnection(this.options.rtc);return e.onsignalingstatechange=()=>{this.logger.debug(`Signaling state changed to: ${e.signalingState}`),"closed"===e.signalingState&&(this.emit(this.Events.Closed),this.clear())},hasIn(RTCPeerConnection.prototype,"onconnectionstatechange")?e.onconnectionstatechange=()=>{this.logger.debug(`Connection state changed to: ${e.connectionState}`),"connected"===e.connectionState?this.emit(this.Events.Connected):"disconnected"===e.connectionState&&this.emit(this.Events.Disconnected)}:e.oniceconnectionstatechange=()=>{this.logger.debug(`ICE connection state changed to: ${e.iceConnectionState}`),"connected"===e.iceConnectionState?this.emit(this.Events.Connected):"disconnected"===e.iceConnectionState&&this.emit(this.Events.Disconnected)},e.ontrack=({streams:e,track:t})=>{if(this.logger.debug("Remote stream received.",e.length,t.kind),0===e.length)return;const[n]=e;n.onremovetrack=()=>{this.logger.debug("onremovetrack"),this.emit(this.Events.RemoteStreamChanged,n)},n.onaddtrack=()=>{this.logger.debug("onaddtrack"),this.emit(this.Events.RemoteStreamChanged,n)},this.emit(this.Events.RemoteStreamChanged,n)},e.onnegotiationneeded=()=>{const{iceConnectionState:t}=e;"connected"!==t&&"completed"!==t||(this.logger.debug("Reinitializing connection..."),this.emit(this.Events.ReinitializingConnectionRequired))},e.onicecandidate=({candidate:e})=>{e?sdpUtils.isValidIceCandidate(e)&&this.emit(this.Events.LocalIceCandidate,e):this.emit(this.Events.EndOfIceCandidates)},e.onicecandidateerror=e=>{if(e instanceof RTCPeerConnectionIceErrorEvent){const{errorCode:t,errorText:n,hostCandidate:i,url:o}=e;this.logger.warn(`ICE candidate error: errorCode=${t}, errorText=${n}, hostCandidate=${i}, url=${o}`)}else this.logger.warn(`ICE candidate error: ${getErrorMessage(e)}`)},e}setLocalDescription(e,t){return __awaiter(this,void 0,void 0,(function*(){const n=sdpUtils.prepareLocalDescription(t,this.options.codecs);return yield e.setLocalDescription(n),n}))}setRemoteDescription(e,t){return __awaiter(this,void 0,void 0,(function*(){const n=sdpUtils.prepareRemoteDescription(t,this.options.codecs);return yield e.setRemoteDescription(n),n}))}isConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}isClosed(){return"closed"===this.pc.signalingState}addIceCandidate(e){return this.pc.addIceCandidate(e)}attachStream(e){const t=this.pc.getSenders(),n=t.length?e.getTracks().filter((e=>!t.find((({track:t})=>!!t&&t.id===e.id)))):e.getTracks();n.length?(n.forEach((t=>this.pc.addTrack(t,e))),this.logger.debug(`Attached ${n.length} track(s) to a peer connection.`)):this.logger.debug("No tracks to attach to a peer connection.")}reattachStream(e){const t=this.pc.iceConnectionState;if("new"!==t&&"connected"!==t&&"completed"!==t)return;const n=e?e.getTracks():[];this.pc.getSenders().forEach((e=>{const{track:t}=e;!t||"ended"!==t.readyState&&n.find((e=>e.id===t.id))||(this.pc.removeTrack(e),this.logger.debug(`'${t&&t.kind}' track is removed from a peer connection.`))})),e&&this.attachStream(e)}createOffer(){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.pc.createOffer(this.options.offerOptions);return this.setLocalDescription(this.pc,e)}))}createAnswer(e){return __awaiter(this,void 0,void 0,(function*(){yield this.setRemoteDescription(this.pc,e);const t=yield this.pc.createAnswer(this.options.offerOptions);return this.setLocalDescription(this.pc,t)}))}applyAnswer(e){return this.setRemoteDescription(this.pc,e)}reconnect(){this.close(),this.pc=this.createPC()}close(){this.pc.close(),this.pc.onsignalingstatechange&&(this.emit(this.Events.Closed),this.clear())}destroy(){this.close(),this.removeAllListeners()}}!function(e){let t;!function(e){e.LocalIceCandidate="LocalIceCandidate",e.EndOfIceCandidates="EndOfIceCandidates",e.Connected="Connected",e.Disconnected="Disconnected",e.RemoteStreamChanged="RemoteStreamChanged",e.ReinitializingConnectionRequired="ReinitializingConnectionRequired",e.Closed="Closed"}(t=e.Events||(e.Events={}))}(PeerConnection||(PeerConnection={}));
1
+ import{__awaiter}from"tslib";import DataEventEmitter,{}from"@js-toolkit/utils/DataEventEmitter";import getErrorMessage from"@js-toolkit/utils/getErrorMessage";import{hasIn}from"@js-toolkit/utils/hasIn";import*as sdpUtils from"./sdputils";export class PeerConnection extends DataEventEmitter{get Events(){return PeerConnection.Events}constructor(e={}){var t;super(),this.options=e,this.logger=null!==(t=e.logger)&&void 0!==t?t:console,this.pc=this.createPC()}clear(){this.pc.onsignalingstatechange=null,this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onnegotiationneeded=null,this.pc.onicecandidate=null,this.pc.onicecandidateerror=null}createPC(){const e=new RTCPeerConnection(this.options.rtc);return e.onsignalingstatechange=()=>{this.logger.debug(`Signaling state changed to: ${e.signalingState}`),"closed"===e.signalingState&&(this.emit(this.Events.Closed),this.clear())},hasIn(RTCPeerConnection.prototype,"onconnectionstatechange")?e.onconnectionstatechange=()=>{this.logger.debug(`Connection state changed to: ${e.connectionState}`),"connected"===e.connectionState?this.emit(this.Events.Connected):"disconnected"===e.connectionState&&this.emit(this.Events.Disconnected)}:e.oniceconnectionstatechange=()=>{this.logger.debug(`ICE connection state changed to: ${e.iceConnectionState}`),"connected"===e.iceConnectionState?this.emit(this.Events.Connected):"disconnected"===e.iceConnectionState&&this.emit(this.Events.Disconnected)},e.ontrack=({streams:e,track:t})=>{if(this.logger.debug("Remote stream received.",e.length,t.kind),0===e.length)return;const[n]=e;n.onremovetrack=()=>{this.logger.debug("onremovetrack"),this.emit(this.Events.RemoteStreamChanged,n)},n.onaddtrack=()=>{this.logger.debug("onaddtrack"),this.emit(this.Events.RemoteStreamChanged,n)},this.emit(this.Events.RemoteStreamChanged,n)},e.onnegotiationneeded=()=>{const{iceConnectionState:t}=e;"connected"!==t&&"completed"!==t||(this.logger.debug("Reinitializing connection..."),this.emit(this.Events.ReinitializingConnectionRequired))},e.onicecandidate=({candidate:e})=>{e?sdpUtils.isValidIceCandidate(e)&&this.emit(this.Events.LocalIceCandidate,e):this.emit(this.Events.EndOfIceCandidates)},e.onicecandidateerror=e=>{if(e instanceof RTCPeerConnectionIceErrorEvent){const{errorCode:t,errorText:n,hostCandidate:i,url:o}=e;this.logger.warn(`ICE candidate error: errorCode=${t}, errorText=${n}, hostCandidate=${i}, url=${o}`)}else this.logger.warn(`ICE candidate error: ${getErrorMessage(e)}`)},e}setLocalDescription(e,t){return __awaiter(this,void 0,void 0,(function*(){const n=sdpUtils.prepareLocalDescription(t,this.options.codecs);return yield e.setLocalDescription(n),n}))}setRemoteDescription(e,t){return __awaiter(this,void 0,void 0,(function*(){const n=sdpUtils.prepareRemoteDescription(t,this.options.codecs);return yield e.setRemoteDescription(n),n}))}isConnected(){return"connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState}isClosed(){return"closed"===this.pc.signalingState}addIceCandidate(e){return this.pc.addIceCandidate(e)}attachStream(e){const t=this.pc.getSenders(),n=t.length?e.getTracks().filter((e=>!t.find((({track:t})=>!!t&&t.id===e.id)))):e.getTracks();n.length?(n.forEach((t=>this.pc.addTrack(t,e))),this.logger.debug(`Attached ${n.length} track(s) to a peer connection.`)):this.logger.debug("No tracks to attach to a peer connection.")}reattachStream(e){const t=this.pc.iceConnectionState;if("new"!==t&&"connected"!==t&&"completed"!==t)return;const n=e?e.getTracks():[];this.pc.getSenders().forEach((e=>{const{track:t}=e;!t||"ended"!==t.readyState&&n.find((e=>e.id===t.id))||(this.pc.removeTrack(e),this.logger.debug(`'${t&&t.kind}' track is removed from a peer connection.`))})),e&&this.attachStream(e)}createOffer(){return __awaiter(this,void 0,void 0,(function*(){const e=yield this.pc.createOffer(this.options.offerOptions);return this.setLocalDescription(this.pc,e)}))}createAnswer(e){return __awaiter(this,void 0,void 0,(function*(){yield this.setRemoteDescription(this.pc,e);const t=yield this.pc.createAnswer(this.options.offerOptions);return this.setLocalDescription(this.pc,t)}))}applyAnswer(e){return this.setRemoteDescription(this.pc,e)}reconnect(){this.close(),this.pc=this.createPC()}close(){this.pc.close(),this.pc.onsignalingstatechange&&(this.emit(this.Events.Closed),this.clear())}destroy(){this.close(),this.removeAllListeners()}}!function(e){let t;!function(e){e.LocalIceCandidate="LocalIceCandidate",e.EndOfIceCandidates="EndOfIceCandidates",e.Connected="Connected",e.Disconnected="Disconnected",e.RemoteStreamChanged="RemoteStreamChanged",e.ReinitializingConnectionRequired="ReinitializingConnectionRequired",e.Closed="Closed"}(t=e.Events||(e.Events={}))}(PeerConnection||(PeerConnection={}));
@@ -1,5 +1,5 @@
1
1
  import ReconnectingWebSocket, { type ErrorEvent, type Message, type Options as BaseOptions, type UrlProvider } from 'reconnecting-websocket';
2
- import DataEventEmitter, { type DataEventListener, type DataEventMap } from '@jstoolkit/utils/DataEventEmitter';
2
+ import DataEventEmitter, { type DataEventListener, type DataEventMap } from '@js-toolkit/utils/DataEventEmitter';
3
3
  export declare class WSController<TData = unknown> extends DataEventEmitter<WSController.EventMap<TData>, WSController<TData>> {
4
4
  get Events(): typeof WSController.Events;
5
5
  readonly logger: NonNullable<WSController.Options['logger']>;
@@ -1 +1 @@
1
- import{__rest}from"tslib";import ReconnectingWebSocket,{}from"reconnecting-websocket";import DataEventEmitter,{}from"@jstoolkit/utils/DataEventEmitter";import delayed from"@jstoolkit/utils/delayed";import{EventEmitterListener}from"../EventEmitterListener";function getNotConnectedError(){return new Error("The object is not connected yet.")}export class WSController extends DataEventEmitter{get Events(){return WSController.Events}constructor(e,t){super();const n=null!=t?t:{},{logger:s,protocols:o,binaryType:i,idleTimeout:r,halfOpenDetection:c,startClosed:l}=n,a=__rest(n,["logger","protocols","binaryType","idleTimeout","halfOpenDetection","startClosed"]);this.logger=null!=s?s:console,this.ws=new ReconnectingWebSocket(e,o,Object.assign(Object.assign({},a),{startClosed:!0})),null!=i&&(this.ws.binaryType=i),this.listener=new EventEmitterListener(this.ws),r&&r>0&&(this.reconnectOnIdle=delayed((()=>{this.logger.info(`WS connection reconnecting after ${r}ms due to inactivity.`),this.ws.reconnect()}),r)),this.halfOpen=(()=>{if(!c)return;const{pingTimeout:e=12e3,outMessage:t=(()=>JSON.stringify({type:"pong"})),inMessageFilter:n=(e=>e&&"object"==typeof e&&"ping"===e.type)}=c,s=delayed((()=>{this.logger.info(`WS connection reconnecting after ${e}ms due to the probability of a half-open connection.`),this.ws.reconnect()}),e),o=()=>{s(),this.ws.send("function"!=typeof t||t instanceof Blob?t:t())};return{heartbeat:o,cancel:()=>s.cancel(),onMessage:({data:e})=>{n(e)?o():s()}}})(),this.listener.on("open",(()=>{var e;this.reconnectOnIdle&&this.reconnectOnIdle(),null===(e=this.halfOpen)||void 0===e||e.heartbeat(),this.emit(this.Events.Connected)})).on("close",(({code:e})=>{var n,s;null===(n=this.reconnectOnIdle)||void 0===n||n.cancel(),null===(s=this.halfOpen)||void 0===s||s.cancel(),null!=(null==t?void 0:t.maxRetries)&&this.ws.readyState===this.ws.CLOSED&&this.ws.retryCount===t.maxRetries&&this.close(e,`Failed to connect after ${t.maxRetries} attempts.`)})).on("message",(e=>{var t;this.reconnectOnIdle&&this.reconnectOnIdle(),null===(t=this.halfOpen)||void 0===t||t.onMessage(e),this.emit(this.Events.Message,e)})).on("error",(({error:e,message:t})=>{this.emit(this.Events.Error,{error:e,message:t})})),this.halfOpen&&(this.isConnected()||this.ws.readyState===this.ws.CONNECTING)&&this.halfOpen.heartbeat(),l||this.connect()}isConnected(){return this.ws.readyState===this.ws.OPEN}getUrl(){return this.ws.url}connect(){this.ws.reconnect()}send(e){if(!this.ws)throw getNotConnectedError();this.ws.send(e)}close(e,t){const n=!!this.ws;try{this.reconnectOnIdle&&this.reconnectOnIdle.cancel(),this.halfOpen&&this.halfOpen.cancel(),this.ws.close(e,t)}catch(e){this.logger.warn(e)}n&&this.emit(this.Events.Closed,t?{reason:t}:void 0)}destroy(){this.close(),this.listener.removeAllListeners(),this.removeAllListeners()}}!function(e){let t;!function(e){e.Connected="Connected",e.Message="Message",e.Error="Error",e.Closed="Closed"}(t=e.Events||(e.Events={}))}(WSController||(WSController={}));
1
+ import{__rest}from"tslib";import ReconnectingWebSocket,{}from"reconnecting-websocket";import DataEventEmitter,{}from"@js-toolkit/utils/DataEventEmitter";import delayed from"@js-toolkit/utils/delayed";import{EventEmitterListener}from"../EventEmitterListener";function getNotConnectedError(){return new Error("The object is not connected yet.")}export class WSController extends DataEventEmitter{get Events(){return WSController.Events}constructor(e,t){super();const n=null!=t?t:{},{logger:s,protocols:o,binaryType:i,idleTimeout:r,halfOpenDetection:c,startClosed:l}=n,a=__rest(n,["logger","protocols","binaryType","idleTimeout","halfOpenDetection","startClosed"]);this.logger=null!=s?s:console,this.ws=new ReconnectingWebSocket(e,o,Object.assign(Object.assign({},a),{startClosed:!0})),null!=i&&(this.ws.binaryType=i),this.listener=new EventEmitterListener(this.ws),r&&r>0&&(this.reconnectOnIdle=delayed((()=>{this.logger.info(`WS connection reconnecting after ${r}ms due to inactivity.`),this.ws.reconnect()}),r)),this.halfOpen=(()=>{if(!c)return;const{pingTimeout:e=12e3,outMessage:t=(()=>JSON.stringify({type:"pong"})),inMessageFilter:n=(e=>e&&"object"==typeof e&&"ping"===e.type)}=c,s=delayed((()=>{this.logger.info(`WS connection reconnecting after ${e}ms due to the probability of a half-open connection.`),this.ws.reconnect()}),e),o=()=>{s(),this.ws.send("function"!=typeof t||t instanceof Blob?t:t())};return{heartbeat:o,cancel:()=>s.cancel(),onMessage:({data:e})=>{n(e)?o():s()}}})(),this.listener.on("open",(()=>{var e;this.reconnectOnIdle&&this.reconnectOnIdle(),null===(e=this.halfOpen)||void 0===e||e.heartbeat(),this.emit(this.Events.Connected)})).on("close",(({code:e})=>{var n,s;null===(n=this.reconnectOnIdle)||void 0===n||n.cancel(),null===(s=this.halfOpen)||void 0===s||s.cancel(),null!=(null==t?void 0:t.maxRetries)&&this.ws.readyState===this.ws.CLOSED&&this.ws.retryCount===t.maxRetries&&this.close(e,`Failed to connect after ${t.maxRetries} attempts.`)})).on("message",(e=>{var t;this.reconnectOnIdle&&this.reconnectOnIdle(),null===(t=this.halfOpen)||void 0===t||t.onMessage(e),this.emit(this.Events.Message,e)})).on("error",(({error:e,message:t})=>{this.emit(this.Events.Error,{error:e,message:t})})),this.halfOpen&&(this.isConnected()||this.ws.readyState===this.ws.CONNECTING)&&this.halfOpen.heartbeat(),l||this.connect()}isConnected(){return this.ws.readyState===this.ws.OPEN}getUrl(){return this.ws.url}connect(){this.ws.reconnect()}send(e){if(!this.ws)throw getNotConnectedError();this.ws.send(e)}close(e,t){const n=!!this.ws;try{this.reconnectOnIdle&&this.reconnectOnIdle.cancel(),this.halfOpen&&this.halfOpen.cancel(),this.ws.close(e,t)}catch(e){this.logger.warn(e)}n&&this.emit(this.Events.Closed,t?{reason:t}:void 0)}destroy(){this.close(),this.listener.removeAllListeners(),this.removeAllListeners()}}!function(e){let t;!function(e){e.Connected="Connected",e.Message="Message",e.Error="Error",e.Closed="Closed"}(t=e.Events||(e.Events={}))}(WSController||(WSController={}));