@tbisoftware/phone 2.0.9 → 2.0.11

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
- {"version":3,"file":"PhoneManager.d.ts","sourceRoot":"","sources":["../../src/core/PhoneManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAM7F,MAAM,WAAW,kBAAkB;IAC/B,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IAChD,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAC;IAC/C,kBAAkB,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;IACxD,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,QAAQ,KAAK,IAAI,CAAC;IACvF,gBAAgB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9C,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;CAC3D;AAED,MAAM,WAAW,iBAAiB;IAC9B,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,gBAAgB,CAAC;CACtC;AAED,MAAM,WAAW,mBAAmB;IAChC,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAoID;;;GAGG;AACH,qBAAa,YAAY;IAqBjB,OAAO,CAAC,MAAM;IApBlB,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,cAAc,CAAa;IACnC,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,gBAAgB,CAA+C;IACvE,OAAO,CAAC,sBAAsB,CAAyC;IAEvE,OAAO,CAAC,MAAM,CAOZ;IAEF,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,OAAO,CAAgC;IAC/C,OAAO,CAAC,QAAQ,CAAkB;gBAGtB,MAAM,EAAE,WAAW,EAC3B,MAAM,GAAE,kBAAuB,EAC/B,OAAO,GAAE,mBAAwB;IA8CrC;;OAEG;IACH,IAAI,KAAK,IAAI,QAAQ,CAAC,iBAAiB,CAAC,CAEvC;IAED;;OAEG;IACH,IAAI,EAAE,IAAI,KAAK,CAAC,EAAE,GAAG,IAAI,CAExB;IAED;;OAEG;IACH,UAAU,IAAI,IAAI;IAuClB;;OAEG;IACH,OAAO,IAAI,IAAI;IAmBf;;OAEG;IACH,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAInC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IA2E/B;;OAEG;IACH,OAAO,IAAI,IAAI;IAOf;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAuDzB;;OAEG;IACH,YAAY,IAAI,IAAI;IAOpB;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,IAAI;IAQpD,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,WAAW;IAanB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,YAAY;IAcpB,OAAO,CAAC,kBAAkB;IAW1B,OAAO,CAAC,iBAAiB;CAO5B;AAED,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"PhoneManager.d.ts","sourceRoot":"","sources":["../../src/core/PhoneManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAM7F,MAAM,WAAW,kBAAkB;IAC/B,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAC5B,oBAAoB,CAAC,EAAE,CAAC,KAAK,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC;IAChD,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAC;IAC/C,kBAAkB,CAAC,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;IACxD,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACvC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,QAAQ,KAAK,IAAI,CAAC;IACvF,gBAAgB,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IAC9C,eAAe,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,IAAI,CAAC;CAC3D;AAED,MAAM,WAAW,iBAAiB;IAC9B,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,gBAAgB,EAAE,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,gBAAgB,CAAC;CACtC;AAED,MAAM,WAAW,mBAAmB;IAChC,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAoID;;;GAGG;AACH,qBAAa,YAAY;IAqBjB,OAAO,CAAC,MAAM;IApBlB,OAAO,CAAC,UAAU,CAA2B;IAC7C,OAAO,CAAC,cAAc,CAAa;IACnC,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,gBAAgB,CAA+C;IACvE,OAAO,CAAC,sBAAsB,CAAyC;IAEvE,OAAO,CAAC,MAAM,CAOZ;IAEF,OAAO,CAAC,MAAM,CAA0B;IACxC,OAAO,CAAC,OAAO,CAAgC;IAC/C,OAAO,CAAC,QAAQ,CAAkB;gBAGtB,MAAM,EAAE,WAAW,EAC3B,MAAM,GAAE,kBAAuB,EAC/B,OAAO,GAAE,mBAAwB;IA8CrC;;OAEG;IACH,IAAI,KAAK,IAAI,QAAQ,CAAC,iBAAiB,CAAC,CAEvC;IAED;;OAEG;IACH,IAAI,EAAE,IAAI,KAAK,CAAC,EAAE,GAAG,IAAI,CAExB;IAED;;OAEG;IACH,UAAU,IAAI,IAAI;IA4ClB;;OAEG;IACH,OAAO,IAAI,IAAI;IAmBf;;OAEG;IACH,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAInC;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IA2E/B;;OAEG;IACH,OAAO,IAAI,IAAI;IAOf;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAuDzB;;OAEG;IACH,YAAY,IAAI,IAAI;IAOpB;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,IAAI;IAQpD,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,WAAW;IAanB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,YAAY;IAcpB,OAAO,CAAC,kBAAkB;IAW1B,OAAO,CAAC,iBAAiB;CAO5B;AAED,eAAe,YAAY,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../index-1EBiLrV_.cjs");exports.PhoneManager=e.PhoneManager;exports.cn=e.cn;exports.defaultLabels=e.defaultLabels;exports.formatDuration=e.formatDuration;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("../index-BofRGPCe.cjs");exports.PhoneManager=e.PhoneManager;exports.cn=e.cn;exports.defaultLabels=e.defaultLabels;exports.formatDuration=e.formatDuration;
@@ -1,4 +1,4 @@
1
- import { P as o, c as r, d as s, f } from "../index-8z_LWKp3.js";
1
+ import { P as o, c as r, d as s, f } from "../index-BP63oarb.js";
2
2
  export {
3
3
  o as PhoneManager,
4
4
  r as cn,
@@ -8093,7 +8093,7 @@ class Oi {
8093
8093
  initialize() {
8094
8094
  this.uaInstance = Kn(this.config), this.uaInstance.ua.isRegistered() ? this.updateState({ isReady: !0, connectionStatus: "connected" }) : this.uaInstance.ua.isConnected() && this.updateState({ connectionStatus: "connected" }), this.uaInstance.listeners.add(this.listener), this.uaInstance.isStarted || (this.uaInstance.ua.start(), this.uaInstance.isStarted = !0), this.loadHistory(), this.startCallEventListener = (y) => {
8095
8095
  const _ = y.detail.number;
8096
- this._state.status === "disconnected" && (!this.uaInstance || !this._state.isReady ? this.initializeAndCall(_) : this.startCall(_));
8096
+ this._state.status === "disconnected" && (this.uaInstance?.ua.isRegistered() && !this._state.isReady && this.updateState({ isReady: !0, connectionStatus: "connected" }), !this.uaInstance || !this._state.isReady ? this.initializeAndCall(_) : this.startCall(_));
8097
8097
  }, window.addEventListener("StartCallEvent", this.startCallEventListener);
8098
8098
  }
8099
8099
  /**
@@ -65,4 +65,4 @@ ${h}
65
65
  `,T+=`Call-ID: ${l.call_id}\r
66
66
  `,T+=`CSeq: ${l.cseq} ${l.method}\r
67
67
  `,T+=`\r
68
- `,c.send(T)}return cs}var ft={},Bn;function oi(){if(Bn)return ft;Bn=1;const O=ue(),y=ie(),i=ge(),_=ye(),E=el(),t=Re();ft.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:y.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,register_from_tag_trail:"",registrar_server:null,sockets:null,connection_recovery_max_interval:y.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:y.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${O.createRandomToken(12)}.invalid`};const h={mandatory:{sockets(d){const l=[];if(E.isSocket(d))l.push({socket:d});else if(Array.isArray(d)&&d.length)for(const g of d)Object.prototype.hasOwnProperty.call(g,"socket")&&E.isSocket(g.socket)?l.push(g):E.isSocket(g)&&l.push({socket:g});else return;return l},uri(d){/^sip:/i.test(d)||(d=`${y.SIP}:${d}`);const l=_.parse(d);if(l)return l.user?l:void 0}},optional:{authorization_user(d){if(i.parse(`"${d}"`,"quoted_string")!==-1)return d},authorization_jwt(d){if(typeof d=="string")return d},user_agent(d){if(typeof d=="string")return d},connection_recovery_max_interval(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},connection_recovery_min_interval(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},contact_uri(d){if(typeof d=="string"){const l=i.parse(d,"SIP_URI");if(l!==-1)return l}},display_name(d){return d},instance_id(d){if(/^uuid:/i.test(d)&&(d=d.substr(5)),i.parse(d,"uuid")!==-1)return d},no_answer_timeout(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},session_timers(d){if(typeof d=="boolean")return d},session_timers_refresh_method(d){if(typeof d=="string"&&(d=d.toUpperCase(),d===y.INVITE||d===y.UPDATE))return d},session_timers_force_refresher(d){if(typeof d=="boolean")return d},password(d){return String(d)},realm(d){return String(d)},ha1(d){return String(d)},register(d){if(typeof d=="boolean")return d},register_expires(d){if(O.isDecimal(d)){const l=Number(d);if(l>=0)return l}},register_from_tag_trail(d){return typeof d=="function"?d:String(d)},registrar_server(d){/^sip:/i.test(d)||(d=`${y.SIP}:${d}`);const l=_.parse(d);if(l)return l.user?void 0:l},use_preloaded_route(d){if(typeof d=="boolean")return d},extra_headers(d){const l=[];if(Array.isArray(d)&&d.length)for(const g of d)typeof g=="string"&&l.push(g);else return;return l}}};return ft.load=(d,l)=>{for(const g in h.mandatory)if(l.hasOwnProperty(g)){const c=l[g],R=h.mandatory[g](c);if(R!==void 0)d[g]=R;else throw new t.ConfigurationError(g,c)}else throw new t.ConfigurationError(g);for(const g in h.optional)if(l.hasOwnProperty(g)){const c=l[g];if(O.isEmpty(c))continue;const R=h.optional[g](c);if(R!==void 0)d[g]=R;else throw new t.ConfigurationError(g,c)}},ft}var fs,Wn;function ui(){if(Wn)return fs;Wn=1;const O=Ie().EventEmitter,y=oe(),i=ie(),_=Jl(),E=Zn(),t=ri(),h=ni(),d=Be(),l=li(),g=ue(),c=Re(),R=ye(),x=ii(),S=ve(),N=ai(),k=oi(),C=new y("UA"),I={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};fs=class extends O{static get C(){return I}constructor(p){if(!p)throw new TypeError("Not enough arguments");const A=["password","ha1","authorization_jwt"];C.debug("new() [configuration:%o]",Object.entries(p).filter(([D])=>!A.includes(D))),super(),this._cache={credentials:{}},this._configuration=Object.assign({},k.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=I.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null;try{this._loadConfig(p)}catch(D){throw this._status=I.STATUS_NOT_READY,this._error=I.CONFIGURATION_ERROR,D}this._registrator=new _(this)}get C(){return I}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){C.debug("start()"),this._status===I.STATUS_INIT?this._transport.connect():this._status===I.STATUS_USER_CLOSED?(C.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=I.STATUS_INIT,this._transport.connect()):this._status===I.STATUS_READY?C.debug("UA is in READY status, not restarted"):C.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){C.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(p){C.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(p)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(p,A){C.debug("call()");const D=new E(this);return D.connect(p,A),D}sendMessage(p,A,D){C.debug("sendMessage()");const v=new t(this);return v.send(p,A,D),v}sendOptions(p,A,D){C.debug("sendOptions()");const v=new h(this);return v.send(p,A,D),v}terminateSessions(p){C.debug("terminateSessions()");for(const A in this._sessions)this._sessions[A].isEnded()||this._sessions[A].terminate(p)}stop(){if(C.debug("stop()"),this._dynConfiguration={},this._status===I.STATUS_USER_CLOSED){C.debug("UA already closed");return}this._registrator.close();const p=Object.keys(this._sessions).length;for(const D in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,D)){C.debug(`closing session ${D}`);try{this._sessions[D].terminate()}catch{}}for(const D in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,D))try{this._applicants[D].close()}catch{}this._status=I.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&p===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(p){return g.normalizeTarget(p,this._configuration.hostport_params)}get(p){switch(p){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:C.warn('get() | cannot get "%s" parameter in runtime',p);return}}set(p,A){switch(p){case"authorization_user":{this._configuration.authorization_user=String(A);break}case"password":{this._configuration.password=String(A);break}case"realm":{this._configuration.realm=String(A);break}case"ha1":{this._configuration.ha1=String(A),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(A);break}case"display_name":{this._configuration.display_name=A;break}case"extra_headers":{this._configuration.extra_headers=A;break}default:return C.warn('set() | cannot set "%s" parameter in runtime',p),!1}return!0}newTransaction(p){this._transactions[p.type][p.id]=p,this.emit("newTransaction",{transaction:p})}destroyTransaction(p){delete this._transactions[p.type][p.id],this.emit("transactionDestroyed",{transaction:p})}newDialog(p){this._dialogs[p.id]=p}destroyDialog(p){delete this._dialogs[p.id]}newMessage(p,A){this._applicants[p]=p,this.emit("newMessage",A)}newOptions(p,A){this._applicants[p]=p,this.emit("newOptions",A)}destroyMessage(p){delete this._applicants[p]}newRTCSession(p,A){this._sessions[p.id]=p,this.emit("newRTCSession",A)}destroyRTCSession(p){delete this._sessions[p.id]}registered(p){this.emit("registered",p)}unregistered(p){this.emit("unregistered",p)}registrationFailed(p){this.emit("registrationFailed",p)}receiveRequest(p){const A=p.method;if(p.ruri.user!==this._configuration.uri.user&&p.ruri.user!==this._contact.uri.user){C.debug("Request-URI does not point to us"),p.method!==i.ACK&&p.reply_sl(404);return}if(p.ruri.scheme===i.SIPS){p.reply_sl(416);return}if(d.checkTransaction(this,p))return;if(A===i.INVITE?new d.InviteServerTransaction(this,this._transport,p):A!==i.ACK&&A!==i.CANCEL&&new d.NonInviteServerTransaction(this,this._transport,p),A===i.OPTIONS){if(this.listeners("newOptions").length===0){p.reply(200);return}new h(this).init_incoming(p)}else if(A===i.MESSAGE){if(this.listeners("newMessage").length===0){p.reply(405);return}new t(this).init_incoming(p)}else if(A===i.INVITE&&!p.to_tag&&this.listeners("newRTCSession").length===0){p.reply(405);return}let D,v;if(p.to_tag)D=this._findDialog(p.call_id,p.from_tag,p.to_tag),D?D.receiveRequest(p):A===i.NOTIFY?(v=this._findSession(p),v?v.receiveRequest(p):(C.debug("received NOTIFY request for a non existent subscription"),p.reply(481,"Subscription does not exist"))):A!==i.ACK&&p.reply(481);else switch(A){case i.INVITE:if(window.RTCPeerConnection)if(p.hasHeader("replaces")){const w=p.replaces;D=this._findDialog(w.call_id,w.from_tag,w.to_tag),D?(v=D.owner,v.isEnded()?p.reply(603):v.receiveRequest(p)):p.reply(481)}else v=new E(this),v.init_incoming(p);else C.warn("INVITE received but WebRTC is not supported"),p.reply(488);break;case i.BYE:p.reply(481);break;case i.CANCEL:v=this._findSession(p),v?v.receiveRequest(p):C.debug("received CANCEL request for a non existent session");break;case i.ACK:break;case i.NOTIFY:this.emit("sipEvent",{event:p.event,request:p}),p.reply(200);break;default:p.reply(405);break}}_findSession({call_id:p,from_tag:A,to_tag:D}){const v=p+A,w=this._sessions[v],U=p+D,M=this._sessions[U];return w||M||null}_findDialog(p,A,D){let v=p+A+D,w=this._dialogs[v];return w||(v=p+D+A,w=this._dialogs[v],w||null)}_loadConfig(p){try{k.load(this._configuration,p)}catch(v){throw v}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=g.newUUID()),this._configuration.jssip_id=g.createRandomToken(5);const A=this._configuration.uri.clone();A.user=null,this._configuration.hostport_params=A.toString().replace(/^sip:/i,"");try{this._transport=new l(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=H.bind(this),this._transport.onconnect=F.bind(this),this._transport.ondisconnect=o.bind(this),this._transport.ondata=f.bind(this)}catch(v){throw C.warn(v),new c.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const v=this._configuration.uri.clone();v.user=null,v.clearParams(),v.clearHeaders(),this._configuration.registrar_server=v}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new R("sip",g.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(v={}){const w=v.anonymous||null,U=v.outbound||null;let M="<";return w?M+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":M+=this.pub_gruu||this.uri.toString(),U&&(w?!this.temp_gruu:!this.pub_gruu)&&(M+=";ob"),M+=">",M}};const D=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register","extra_headers"];for(const v in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,v)&&(D.indexOf(v)!==-1?Object.defineProperty(this._configuration,v,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,v,{writable:!1,configurable:!1}));C.debug("configuration parameters after validation:");for(const v in this._configuration)if(Object.prototype.hasOwnProperty.call(k.settings,v))switch(v){case"uri":case"registrar_server":C.debug(`- ${v}: ${this._configuration[v]}`);break;case"password":case"ha1":case"authorization_jwt":C.debug(`- ${v}: NOT SHOWN`);break;default:C.debug(`- ${v}: ${JSON.stringify(this._configuration[v])}`)}}};function H(T){this.emit("connecting",T)}function F(T){this._status!==I.STATUS_USER_CLOSED&&(this._status=I.STATUS_READY,this._error=null,this.emit("connected",T),this._dynConfiguration.register&&this._registrator.register())}function o(T){const p=["nict","ict","nist","ist"];for(const A of p)for(const D in this._transactions[A])Object.prototype.hasOwnProperty.call(this._transactions[A],D)&&this._transactions[A][D].onTransportError();this.emit("disconnected",T),this._registrator.onTransportClosed(),this._status!==I.STATUS_USER_CLOSED&&(this._status=I.STATUS_NOT_READY,this._error=I.NETWORK_ERROR)}function f(T){const p=T.transport;let A=T.message;if(A=x.parseMessage(A,this),!!A&&!(this._status===I.STATUS_USER_CLOSED&&A instanceof S.IncomingRequest)&&N(A,this,p)){if(A instanceof S.IncomingRequest)A.transport=p,this.receiveRequest(A);else if(A instanceof S.IncomingResponse){let D;switch(A.method){case i.INVITE:D=this._transactions.ict[A.via_branch],D&&D.receiveResponse(A);break;case i.ACK:break;default:D=this._transactions.nict[A.via_branch],D&&D.receiveResponse(A);break}}}}return fs}var hs,Vn;function ci(){if(Vn)return hs;Vn=1;const O=oe(),y=ge(),i=new O("WebSocketInterface");return hs=class{constructor(E){i.debug('new() [url:"%s"]',E),this._url=E,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=y.parse(E,"absoluteURI");if(t===-1)throw i.warn(`invalid WebSocket URI: ${E}`),new TypeError(`Invalid argument: ${E}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw i.warn(`invalid WebSocket URI scheme: ${t.scheme}`),new TypeError(`Invalid argument: ${E}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:""};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(E){this._via_transport=E.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(i.debug("connect()"),this.isConnected()){i.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){i.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),i.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(E){this._onError(E)}}disconnect(){i.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(E){return i.debug("send()"),this.isConnected()?(this._ws.send(E),!0):(i.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){i.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:E,code:t,reason:h}){i.debug(`WebSocket ${this._url} closed`),E===!1&&i.debug("WebSocket abrupt disconnection"),this.ondisconnect(!E,t,h)}_onMessage({data:E}){i.debug("received WebSocket message"),this.ondata(E)}_onError(E){i.warn(`WebSocket ${this._url} error: `,E)}},hs}var ds,jn;function fi(){if(jn)return ds;jn=1;const O=zn,y=ie(),i=Re(),_=ue(),E=ui(),t=ye(),h=Ts(),d=ge(),l=ci(),g=ps()("JsSIP"),c=Zn();return g("version %s",O.version),ds={C:y,Exceptions:i,Utils:_,UA:E,URI:t,NameAddrHeader:h,WebSocketInterface:l,Grammar:d,RTCSession:c,debug:ps(),get name(){return O.title},get version(){return O.version}},ds}var hi=fi();const gs=Gl(hi);let xe=null,_s=null;function di(O){return`${O.websocketUrl}|${O.sipUri}|${O.authorizationUser}`}function _i(O){const i={sockets:[new gs.WebSocketInterface(O.websocketUrl)],uri:O.sipUri,password:O.password,registrar_server:O.registrarServer,display_name:O.displayName,authorization_user:O.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},_=new gs.UA(i),E=document.createElement("audio");E.autoplay=!0;const t={ua:_,audio:E,isStarted:!1,listeners:new Set};return _.on("connecting",()=>{t.listeners.forEach(h=>h.onConnecting?.())}),_.on("connected",()=>{t.listeners.forEach(h=>h.onConnected?.())}),_.on("disconnected",()=>{t.listeners.forEach(h=>h.onDisconnected?.())}),_.on("registered",()=>{t.listeners.forEach(h=>h.onRegistered?.())}),_.on("unregistered",()=>{t.listeners.forEach(h=>h.onUnregistered?.())}),_.on("registrationFailed",h=>{t.listeners.forEach(d=>d.onRegistrationFailed?.(h?.cause))}),_.on("newRTCSession",h=>{const d=h.session;d.direction==="outgoing"&&(t.listeners.forEach(l=>l.onNewSession?.(d)),d.connection&&(d.connection.addEventListener("addstream",l=>{if(!l.streams?.length)return;const g=document.createElement("audio");g.srcObject=l.streams[0],g.play()}),d.connection.addEventListener("track",l=>{const g=document.createElement("audio");g.srcObject=l.streams[0],g.play()})))}),t}function Kn(O){const y=di(O);if(xe&&_s===y)return xe;if(xe&&_s!==y){try{xe.ua.stop()}catch{}xe=null}return _s=y,xe=_i(O),xe}class pi{constructor(y,i={},_={}){this.config=y,this.events=i,this.options={persistHistory:_.persistHistory??!0,historyKey:_.historyKey??"tbi-phone-call-history",maxHistoryItems:_.maxHistoryItems??50},this.listener={onConnecting:()=>{this.updateState({connectionStatus:"connecting"}),this.events.onConnecting?.(),this.events.onConnectionChange?.("connecting")},onConnected:()=>{this.updateState({connectionStatus:"connected"}),this.events.onConnected?.(),this.events.onConnectionChange?.("connected")},onDisconnected:()=>{this.updateState({connectionStatus:"disconnected",isReady:!1}),this.events.onDisconnected?.(),this.events.onConnectionChange?.("disconnected")},onRegistered:()=>{this.updateState({isReady:!0,connectionStatus:"connected"}),this.events.onRegistered?.(),this.events.onConnectionChange?.("connected")},onUnregistered:()=>{this.updateState({isReady:!1}),this.events.onUnregistered?.()},onRegistrationFailed:E=>{console.error("Registration failed:",E),this.updateState({isReady:!1,connectionStatus:"failed"}),this.events.onRegistrationFailed?.(E),this.events.onConnectionChange?.("failed")},onNewSession:E=>{this.currentSession=E}}}uaInstance=null;currentSession=null;callStartedTS=null;durationInterval=null;startCallEventListener=null;_state={status:"disconnected",callNumber:"",callHistory:[],currentCallDuration:0,isReady:!1,connectionStatus:"connecting"};events={};options;listener;get state(){return this._state}get ua(){return this.uaInstance?.ua??null}initialize(){this.uaInstance=Kn(this.config),this.uaInstance.ua.isRegistered()?this.updateState({isReady:!0,connectionStatus:"connected"}):this.uaInstance.ua.isConnected()&&this.updateState({connectionStatus:"connected"}),this.uaInstance.listeners.add(this.listener),this.uaInstance.isStarted||(this.uaInstance.ua.start(),this.uaInstance.isStarted=!0),this.loadHistory(),this.startCallEventListener=y=>{const _=y.detail.number;this._state.status==="disconnected"&&(!this.uaInstance||!this._state.isReady?this.initializeAndCall(_):this.startCall(_))},window.addEventListener("StartCallEvent",this.startCallEventListener)}destroy(){this.uaInstance&&this.uaInstance.listeners.delete(this.listener),this.startCallEventListener&&(window.removeEventListener("StartCallEvent",this.startCallEventListener),this.startCallEventListener=null),this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null)}setCallNumber(y){this.updateState({callNumber:y})}startCall(y){if(!y.trim()||!this.uaInstance)return;if(!this._state.isReady){console.warn("Phone is not ready yet. Please wait for registration.");return}this.updateState({callNumber:y}),this.events.onCallStart?.(y);const _={eventHandlers:{progress:()=>{this.updateState({status:"progress"}),this.events.onStatusChange?.("progress")},failed:E=>{console.error("Call failed:",E?.cause),this.updateState({status:"failed"}),this.events.onStatusChange?.("failed"),this.addToHistory(y,0,"failed"),this.events.onCallEnd?.(y,0,"failed"),this.currentSession=null,setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected")},3e3)},ended:()=>{this.updateState({status:"ended"}),this.events.onStatusChange?.("ended");const E=this.callStartedTS?Math.floor((Date.now()-this.callStartedTS)/1e3):0;this.addToHistory(y,E,"completed"),this.events.onCallEnd?.(y,E,"completed"),this.currentSession=null,this.stopDurationTimer(),setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected"),this.callStartedTS=null},2e3)},confirmed:()=>{this.callStartedTS=Date.now(),this.updateState({status:"confirmed"}),this.events.onStatusChange?.("confirmed"),this.startDurationTimer()}},mediaConstraints:{audio:!0,video:!1}};this.updateState({status:"progress"}),this.events.onStatusChange?.("progress");try{const E=this.uaInstance.ua.call(y,_);this.currentSession=E}catch(E){console.error("Failed to start call:",E),this.updateState({status:"failed"}),this.events.onStatusChange?.("failed"),this.addToHistory(y,0,"failed"),setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected")},3e3)}}endCall(){this.currentSession&&(this.currentSession.terminate(),this.currentSession=null)}initializeAndCall(y){if(this.uaInstance&&this._state.isReady){this.startCall(y);return}if(this.uaInstance||(this.uaInstance=Kn(this.config),this.uaInstance.ua.isRegistered()?this.updateState({isReady:!0,connectionStatus:"connected"}):this.uaInstance.ua.isConnected()&&this.updateState({connectionStatus:"connected"}),this.uaInstance.listeners.add(this.listener),this.loadHistory()),this.uaInstance.ua.isRegistered()){this.updateState({isReady:!0,connectionStatus:"connected"}),this.startCall(y);return}const i={onRegistered:()=>{this.uaInstance?.listeners.delete(i),this.startCall(y)},onRegistrationFailed:_=>{console.error("Registration failed while trying to start call:",_),this.uaInstance?.listeners.delete(i)}};this.uaInstance.listeners.add(i),this.uaInstance.isStarted||(this.uaInstance.ua.start(),this.uaInstance.isStarted=!0)}clearHistory(){this.updateState({callHistory:[]}),this.options.persistHistory&&localStorage.removeItem(this.options.historyKey)}setEvents(y){this.events={...this.events,...y}}updateState(y){this._state={...this._state,...y}}loadHistory(){if(!this.options.persistHistory)return;const y=localStorage.getItem(this.options.historyKey);if(y)try{this.updateState({callHistory:JSON.parse(y)})}catch(i){console.error("Error loading call history",i)}}saveHistory(){this.options.persistHistory&&this._state.callHistory.length>0&&localStorage.setItem(this.options.historyKey,JSON.stringify(this._state.callHistory))}addToHistory(y,i,_){const t=[{id:Date.now().toString(),number:y,timestamp:Date.now(),duration:i,status:_},...this._state.callHistory].slice(0,this.options.maxHistoryItems);this.updateState({callHistory:t}),this.saveHistory(),this.events.onHistoryUpdate?.(t)}startDurationTimer(){this.stopDurationTimer(),this.durationInterval=setInterval(()=>{if(this.callStartedTS){const y=Math.floor((Date.now()-this.callStartedTS)/1e3);this.updateState({currentCallDuration:y}),this.events.onDurationUpdate?.(y)}},1e3)}stopDurationTimer(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.updateState({currentCallDuration:0})}}exports.JsSIP=gs;exports.PhoneManager=pi;exports.cn=$l;exports.defaultLabels=ql;exports.formatDuration=kl;
68
+ `,c.send(T)}return cs}var ft={},Bn;function oi(){if(Bn)return ft;Bn=1;const O=ue(),y=ie(),i=ge(),_=ye(),E=el(),t=Re();ft.settings={authorization_user:null,password:null,realm:null,ha1:null,authorization_jwt:null,display_name:null,uri:null,contact_uri:null,instance_id:null,use_preloaded_route:!1,session_timers:!0,session_timers_refresh_method:y.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,register_from_tag_trail:"",registrar_server:null,sockets:null,connection_recovery_max_interval:y.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:y.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${O.createRandomToken(12)}.invalid`};const h={mandatory:{sockets(d){const l=[];if(E.isSocket(d))l.push({socket:d});else if(Array.isArray(d)&&d.length)for(const g of d)Object.prototype.hasOwnProperty.call(g,"socket")&&E.isSocket(g.socket)?l.push(g):E.isSocket(g)&&l.push({socket:g});else return;return l},uri(d){/^sip:/i.test(d)||(d=`${y.SIP}:${d}`);const l=_.parse(d);if(l)return l.user?l:void 0}},optional:{authorization_user(d){if(i.parse(`"${d}"`,"quoted_string")!==-1)return d},authorization_jwt(d){if(typeof d=="string")return d},user_agent(d){if(typeof d=="string")return d},connection_recovery_max_interval(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},connection_recovery_min_interval(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},contact_uri(d){if(typeof d=="string"){const l=i.parse(d,"SIP_URI");if(l!==-1)return l}},display_name(d){return d},instance_id(d){if(/^uuid:/i.test(d)&&(d=d.substr(5)),i.parse(d,"uuid")!==-1)return d},no_answer_timeout(d){if(O.isDecimal(d)){const l=Number(d);if(l>0)return l}},session_timers(d){if(typeof d=="boolean")return d},session_timers_refresh_method(d){if(typeof d=="string"&&(d=d.toUpperCase(),d===y.INVITE||d===y.UPDATE))return d},session_timers_force_refresher(d){if(typeof d=="boolean")return d},password(d){return String(d)},realm(d){return String(d)},ha1(d){return String(d)},register(d){if(typeof d=="boolean")return d},register_expires(d){if(O.isDecimal(d)){const l=Number(d);if(l>=0)return l}},register_from_tag_trail(d){return typeof d=="function"?d:String(d)},registrar_server(d){/^sip:/i.test(d)||(d=`${y.SIP}:${d}`);const l=_.parse(d);if(l)return l.user?void 0:l},use_preloaded_route(d){if(typeof d=="boolean")return d},extra_headers(d){const l=[];if(Array.isArray(d)&&d.length)for(const g of d)typeof g=="string"&&l.push(g);else return;return l}}};return ft.load=(d,l)=>{for(const g in h.mandatory)if(l.hasOwnProperty(g)){const c=l[g],R=h.mandatory[g](c);if(R!==void 0)d[g]=R;else throw new t.ConfigurationError(g,c)}else throw new t.ConfigurationError(g);for(const g in h.optional)if(l.hasOwnProperty(g)){const c=l[g];if(O.isEmpty(c))continue;const R=h.optional[g](c);if(R!==void 0)d[g]=R;else throw new t.ConfigurationError(g,c)}},ft}var fs,Wn;function ui(){if(Wn)return fs;Wn=1;const O=Ie().EventEmitter,y=oe(),i=ie(),_=Jl(),E=Zn(),t=ri(),h=ni(),d=Be(),l=li(),g=ue(),c=Re(),R=ye(),x=ii(),S=ve(),N=ai(),k=oi(),C=new y("UA"),I={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};fs=class extends O{static get C(){return I}constructor(p){if(!p)throw new TypeError("Not enough arguments");const A=["password","ha1","authorization_jwt"];C.debug("new() [configuration:%o]",Object.entries(p).filter(([D])=>!A.includes(D))),super(),this._cache={credentials:{}},this._configuration=Object.assign({},k.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=I.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null;try{this._loadConfig(p)}catch(D){throw this._status=I.STATUS_NOT_READY,this._error=I.CONFIGURATION_ERROR,D}this._registrator=new _(this)}get C(){return I}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){C.debug("start()"),this._status===I.STATUS_INIT?this._transport.connect():this._status===I.STATUS_USER_CLOSED?(C.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=I.STATUS_INIT,this._transport.connect()):this._status===I.STATUS_READY?C.debug("UA is in READY status, not restarted"):C.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){C.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(p){C.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(p)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(p,A){C.debug("call()");const D=new E(this);return D.connect(p,A),D}sendMessage(p,A,D){C.debug("sendMessage()");const v=new t(this);return v.send(p,A,D),v}sendOptions(p,A,D){C.debug("sendOptions()");const v=new h(this);return v.send(p,A,D),v}terminateSessions(p){C.debug("terminateSessions()");for(const A in this._sessions)this._sessions[A].isEnded()||this._sessions[A].terminate(p)}stop(){if(C.debug("stop()"),this._dynConfiguration={},this._status===I.STATUS_USER_CLOSED){C.debug("UA already closed");return}this._registrator.close();const p=Object.keys(this._sessions).length;for(const D in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,D)){C.debug(`closing session ${D}`);try{this._sessions[D].terminate()}catch{}}for(const D in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,D))try{this._applicants[D].close()}catch{}this._status=I.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&p===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(p){return g.normalizeTarget(p,this._configuration.hostport_params)}get(p){switch(p){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:C.warn('get() | cannot get "%s" parameter in runtime',p);return}}set(p,A){switch(p){case"authorization_user":{this._configuration.authorization_user=String(A);break}case"password":{this._configuration.password=String(A);break}case"realm":{this._configuration.realm=String(A);break}case"ha1":{this._configuration.ha1=String(A),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(A);break}case"display_name":{this._configuration.display_name=A;break}case"extra_headers":{this._configuration.extra_headers=A;break}default:return C.warn('set() | cannot set "%s" parameter in runtime',p),!1}return!0}newTransaction(p){this._transactions[p.type][p.id]=p,this.emit("newTransaction",{transaction:p})}destroyTransaction(p){delete this._transactions[p.type][p.id],this.emit("transactionDestroyed",{transaction:p})}newDialog(p){this._dialogs[p.id]=p}destroyDialog(p){delete this._dialogs[p.id]}newMessage(p,A){this._applicants[p]=p,this.emit("newMessage",A)}newOptions(p,A){this._applicants[p]=p,this.emit("newOptions",A)}destroyMessage(p){delete this._applicants[p]}newRTCSession(p,A){this._sessions[p.id]=p,this.emit("newRTCSession",A)}destroyRTCSession(p){delete this._sessions[p.id]}registered(p){this.emit("registered",p)}unregistered(p){this.emit("unregistered",p)}registrationFailed(p){this.emit("registrationFailed",p)}receiveRequest(p){const A=p.method;if(p.ruri.user!==this._configuration.uri.user&&p.ruri.user!==this._contact.uri.user){C.debug("Request-URI does not point to us"),p.method!==i.ACK&&p.reply_sl(404);return}if(p.ruri.scheme===i.SIPS){p.reply_sl(416);return}if(d.checkTransaction(this,p))return;if(A===i.INVITE?new d.InviteServerTransaction(this,this._transport,p):A!==i.ACK&&A!==i.CANCEL&&new d.NonInviteServerTransaction(this,this._transport,p),A===i.OPTIONS){if(this.listeners("newOptions").length===0){p.reply(200);return}new h(this).init_incoming(p)}else if(A===i.MESSAGE){if(this.listeners("newMessage").length===0){p.reply(405);return}new t(this).init_incoming(p)}else if(A===i.INVITE&&!p.to_tag&&this.listeners("newRTCSession").length===0){p.reply(405);return}let D,v;if(p.to_tag)D=this._findDialog(p.call_id,p.from_tag,p.to_tag),D?D.receiveRequest(p):A===i.NOTIFY?(v=this._findSession(p),v?v.receiveRequest(p):(C.debug("received NOTIFY request for a non existent subscription"),p.reply(481,"Subscription does not exist"))):A!==i.ACK&&p.reply(481);else switch(A){case i.INVITE:if(window.RTCPeerConnection)if(p.hasHeader("replaces")){const w=p.replaces;D=this._findDialog(w.call_id,w.from_tag,w.to_tag),D?(v=D.owner,v.isEnded()?p.reply(603):v.receiveRequest(p)):p.reply(481)}else v=new E(this),v.init_incoming(p);else C.warn("INVITE received but WebRTC is not supported"),p.reply(488);break;case i.BYE:p.reply(481);break;case i.CANCEL:v=this._findSession(p),v?v.receiveRequest(p):C.debug("received CANCEL request for a non existent session");break;case i.ACK:break;case i.NOTIFY:this.emit("sipEvent",{event:p.event,request:p}),p.reply(200);break;default:p.reply(405);break}}_findSession({call_id:p,from_tag:A,to_tag:D}){const v=p+A,w=this._sessions[v],U=p+D,M=this._sessions[U];return w||M||null}_findDialog(p,A,D){let v=p+A+D,w=this._dialogs[v];return w||(v=p+D+A,w=this._dialogs[v],w||null)}_loadConfig(p){try{k.load(this._configuration,p)}catch(v){throw v}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=g.newUUID()),this._configuration.jssip_id=g.createRandomToken(5);const A=this._configuration.uri.clone();A.user=null,this._configuration.hostport_params=A.toString().replace(/^sip:/i,"");try{this._transport=new l(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=H.bind(this),this._transport.onconnect=F.bind(this),this._transport.ondisconnect=o.bind(this),this._transport.ondata=f.bind(this)}catch(v){throw C.warn(v),new c.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const v=this._configuration.uri.clone();v.user=null,v.clearParams(),v.clearHeaders(),this._configuration.registrar_server=v}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new R("sip",g.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(v={}){const w=v.anonymous||null,U=v.outbound||null;let M="<";return w?M+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":M+=this.pub_gruu||this.uri.toString(),U&&(w?!this.temp_gruu:!this.pub_gruu)&&(M+=";ob"),M+=">",M}};const D=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register","extra_headers"];for(const v in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,v)&&(D.indexOf(v)!==-1?Object.defineProperty(this._configuration,v,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,v,{writable:!1,configurable:!1}));C.debug("configuration parameters after validation:");for(const v in this._configuration)if(Object.prototype.hasOwnProperty.call(k.settings,v))switch(v){case"uri":case"registrar_server":C.debug(`- ${v}: ${this._configuration[v]}`);break;case"password":case"ha1":case"authorization_jwt":C.debug(`- ${v}: NOT SHOWN`);break;default:C.debug(`- ${v}: ${JSON.stringify(this._configuration[v])}`)}}};function H(T){this.emit("connecting",T)}function F(T){this._status!==I.STATUS_USER_CLOSED&&(this._status=I.STATUS_READY,this._error=null,this.emit("connected",T),this._dynConfiguration.register&&this._registrator.register())}function o(T){const p=["nict","ict","nist","ist"];for(const A of p)for(const D in this._transactions[A])Object.prototype.hasOwnProperty.call(this._transactions[A],D)&&this._transactions[A][D].onTransportError();this.emit("disconnected",T),this._registrator.onTransportClosed(),this._status!==I.STATUS_USER_CLOSED&&(this._status=I.STATUS_NOT_READY,this._error=I.NETWORK_ERROR)}function f(T){const p=T.transport;let A=T.message;if(A=x.parseMessage(A,this),!!A&&!(this._status===I.STATUS_USER_CLOSED&&A instanceof S.IncomingRequest)&&N(A,this,p)){if(A instanceof S.IncomingRequest)A.transport=p,this.receiveRequest(A);else if(A instanceof S.IncomingResponse){let D;switch(A.method){case i.INVITE:D=this._transactions.ict[A.via_branch],D&&D.receiveResponse(A);break;case i.ACK:break;default:D=this._transactions.nict[A.via_branch],D&&D.receiveResponse(A);break}}}}return fs}var hs,Vn;function ci(){if(Vn)return hs;Vn=1;const O=oe(),y=ge(),i=new O("WebSocketInterface");return hs=class{constructor(E){i.debug('new() [url:"%s"]',E),this._url=E,this._sip_uri=null,this._via_transport=null,this._ws=null;const t=y.parse(E,"absoluteURI");if(t===-1)throw i.warn(`invalid WebSocket URI: ${E}`),new TypeError(`Invalid argument: ${E}`);if(t.scheme!=="wss"&&t.scheme!=="ws")throw i.warn(`invalid WebSocket URI scheme: ${t.scheme}`),new TypeError(`Invalid argument: ${E}`);this._sip_uri=`sip:${t.host}${t.port?`:${t.port}`:""};transport=ws`,this._via_transport=t.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(E){this._via_transport=E.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(i.debug("connect()"),this.isConnected()){i.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){i.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),i.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(E){this._onError(E)}}disconnect(){i.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(E){return i.debug("send()"),this.isConnected()?(this._ws.send(E),!0):(i.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){i.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:E,code:t,reason:h}){i.debug(`WebSocket ${this._url} closed`),E===!1&&i.debug("WebSocket abrupt disconnection"),this.ondisconnect(!E,t,h)}_onMessage({data:E}){i.debug("received WebSocket message"),this.ondata(E)}_onError(E){i.warn(`WebSocket ${this._url} error: `,E)}},hs}var ds,jn;function fi(){if(jn)return ds;jn=1;const O=zn,y=ie(),i=Re(),_=ue(),E=ui(),t=ye(),h=Ts(),d=ge(),l=ci(),g=ps()("JsSIP"),c=Zn();return g("version %s",O.version),ds={C:y,Exceptions:i,Utils:_,UA:E,URI:t,NameAddrHeader:h,WebSocketInterface:l,Grammar:d,RTCSession:c,debug:ps(),get name(){return O.title},get version(){return O.version}},ds}var hi=fi();const gs=Gl(hi);let xe=null,_s=null;function di(O){return`${O.websocketUrl}|${O.sipUri}|${O.authorizationUser}`}function _i(O){const i={sockets:[new gs.WebSocketInterface(O.websocketUrl)],uri:O.sipUri,password:O.password,registrar_server:O.registrarServer,display_name:O.displayName,authorization_user:O.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},_=new gs.UA(i),E=document.createElement("audio");E.autoplay=!0;const t={ua:_,audio:E,isStarted:!1,listeners:new Set};return _.on("connecting",()=>{t.listeners.forEach(h=>h.onConnecting?.())}),_.on("connected",()=>{t.listeners.forEach(h=>h.onConnected?.())}),_.on("disconnected",()=>{t.listeners.forEach(h=>h.onDisconnected?.())}),_.on("registered",()=>{t.listeners.forEach(h=>h.onRegistered?.())}),_.on("unregistered",()=>{t.listeners.forEach(h=>h.onUnregistered?.())}),_.on("registrationFailed",h=>{t.listeners.forEach(d=>d.onRegistrationFailed?.(h?.cause))}),_.on("newRTCSession",h=>{const d=h.session;d.direction==="outgoing"&&(t.listeners.forEach(l=>l.onNewSession?.(d)),d.connection&&(d.connection.addEventListener("addstream",l=>{if(!l.streams?.length)return;const g=document.createElement("audio");g.srcObject=l.streams[0],g.play()}),d.connection.addEventListener("track",l=>{const g=document.createElement("audio");g.srcObject=l.streams[0],g.play()})))}),t}function Kn(O){const y=di(O);if(xe&&_s===y)return xe;if(xe&&_s!==y){try{xe.ua.stop()}catch{}xe=null}return _s=y,xe=_i(O),xe}class pi{constructor(y,i={},_={}){this.config=y,this.events=i,this.options={persistHistory:_.persistHistory??!0,historyKey:_.historyKey??"tbi-phone-call-history",maxHistoryItems:_.maxHistoryItems??50},this.listener={onConnecting:()=>{this.updateState({connectionStatus:"connecting"}),this.events.onConnecting?.(),this.events.onConnectionChange?.("connecting")},onConnected:()=>{this.updateState({connectionStatus:"connected"}),this.events.onConnected?.(),this.events.onConnectionChange?.("connected")},onDisconnected:()=>{this.updateState({connectionStatus:"disconnected",isReady:!1}),this.events.onDisconnected?.(),this.events.onConnectionChange?.("disconnected")},onRegistered:()=>{this.updateState({isReady:!0,connectionStatus:"connected"}),this.events.onRegistered?.(),this.events.onConnectionChange?.("connected")},onUnregistered:()=>{this.updateState({isReady:!1}),this.events.onUnregistered?.()},onRegistrationFailed:E=>{console.error("Registration failed:",E),this.updateState({isReady:!1,connectionStatus:"failed"}),this.events.onRegistrationFailed?.(E),this.events.onConnectionChange?.("failed")},onNewSession:E=>{this.currentSession=E}}}uaInstance=null;currentSession=null;callStartedTS=null;durationInterval=null;startCallEventListener=null;_state={status:"disconnected",callNumber:"",callHistory:[],currentCallDuration:0,isReady:!1,connectionStatus:"connecting"};events={};options;listener;get state(){return this._state}get ua(){return this.uaInstance?.ua??null}initialize(){this.uaInstance=Kn(this.config),this.uaInstance.ua.isRegistered()?this.updateState({isReady:!0,connectionStatus:"connected"}):this.uaInstance.ua.isConnected()&&this.updateState({connectionStatus:"connected"}),this.uaInstance.listeners.add(this.listener),this.uaInstance.isStarted||(this.uaInstance.ua.start(),this.uaInstance.isStarted=!0),this.loadHistory(),this.startCallEventListener=y=>{const _=y.detail.number;this._state.status==="disconnected"&&(this.uaInstance?.ua.isRegistered()&&!this._state.isReady&&this.updateState({isReady:!0,connectionStatus:"connected"}),!this.uaInstance||!this._state.isReady?this.initializeAndCall(_):this.startCall(_))},window.addEventListener("StartCallEvent",this.startCallEventListener)}destroy(){this.uaInstance&&this.uaInstance.listeners.delete(this.listener),this.startCallEventListener&&(window.removeEventListener("StartCallEvent",this.startCallEventListener),this.startCallEventListener=null),this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null)}setCallNumber(y){this.updateState({callNumber:y})}startCall(y){if(!y.trim()||!this.uaInstance)return;if(!this._state.isReady){console.warn("Phone is not ready yet. Please wait for registration.");return}this.updateState({callNumber:y}),this.events.onCallStart?.(y);const _={eventHandlers:{progress:()=>{this.updateState({status:"progress"}),this.events.onStatusChange?.("progress")},failed:E=>{console.error("Call failed:",E?.cause),this.updateState({status:"failed"}),this.events.onStatusChange?.("failed"),this.addToHistory(y,0,"failed"),this.events.onCallEnd?.(y,0,"failed"),this.currentSession=null,setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected")},3e3)},ended:()=>{this.updateState({status:"ended"}),this.events.onStatusChange?.("ended");const E=this.callStartedTS?Math.floor((Date.now()-this.callStartedTS)/1e3):0;this.addToHistory(y,E,"completed"),this.events.onCallEnd?.(y,E,"completed"),this.currentSession=null,this.stopDurationTimer(),setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected"),this.callStartedTS=null},2e3)},confirmed:()=>{this.callStartedTS=Date.now(),this.updateState({status:"confirmed"}),this.events.onStatusChange?.("confirmed"),this.startDurationTimer()}},mediaConstraints:{audio:!0,video:!1}};this.updateState({status:"progress"}),this.events.onStatusChange?.("progress");try{const E=this.uaInstance.ua.call(y,_);this.currentSession=E}catch(E){console.error("Failed to start call:",E),this.updateState({status:"failed"}),this.events.onStatusChange?.("failed"),this.addToHistory(y,0,"failed"),setTimeout(()=>{this.updateState({status:"disconnected"}),this.events.onStatusChange?.("disconnected")},3e3)}}endCall(){this.currentSession&&(this.currentSession.terminate(),this.currentSession=null)}initializeAndCall(y){if(this.uaInstance&&this._state.isReady){this.startCall(y);return}if(this.uaInstance||(this.uaInstance=Kn(this.config),this.uaInstance.ua.isRegistered()?this.updateState({isReady:!0,connectionStatus:"connected"}):this.uaInstance.ua.isConnected()&&this.updateState({connectionStatus:"connected"}),this.uaInstance.listeners.add(this.listener),this.loadHistory()),this.uaInstance.ua.isRegistered()){this.updateState({isReady:!0,connectionStatus:"connected"}),this.startCall(y);return}const i={onRegistered:()=>{this.uaInstance?.listeners.delete(i),this.startCall(y)},onRegistrationFailed:_=>{console.error("Registration failed while trying to start call:",_),this.uaInstance?.listeners.delete(i)}};this.uaInstance.listeners.add(i),this.uaInstance.isStarted||(this.uaInstance.ua.start(),this.uaInstance.isStarted=!0)}clearHistory(){this.updateState({callHistory:[]}),this.options.persistHistory&&localStorage.removeItem(this.options.historyKey)}setEvents(y){this.events={...this.events,...y}}updateState(y){this._state={...this._state,...y}}loadHistory(){if(!this.options.persistHistory)return;const y=localStorage.getItem(this.options.historyKey);if(y)try{this.updateState({callHistory:JSON.parse(y)})}catch(i){console.error("Error loading call history",i)}}saveHistory(){this.options.persistHistory&&this._state.callHistory.length>0&&localStorage.setItem(this.options.historyKey,JSON.stringify(this._state.callHistory))}addToHistory(y,i,_){const t=[{id:Date.now().toString(),number:y,timestamp:Date.now(),duration:i,status:_},...this._state.callHistory].slice(0,this.options.maxHistoryItems);this.updateState({callHistory:t}),this.saveHistory(),this.events.onHistoryUpdate?.(t)}startDurationTimer(){this.stopDurationTimer(),this.durationInterval=setInterval(()=>{if(this.callStartedTS){const y=Math.floor((Date.now()-this.callStartedTS)/1e3);this.updateState({currentCallDuration:y}),this.events.onDurationUpdate?.(y)}},1e3)}stopDurationTimer(){this.durationInterval&&(clearInterval(this.durationInterval),this.durationInterval=null),this.updateState({currentCallDuration:0})}}exports.JsSIP=gs;exports.PhoneManager=pi;exports.cn=$l;exports.defaultLabels=ql;exports.formatDuration=kl;
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./usePhoneManager-CfG7kttP.cjs"),o=require("./index-1EBiLrV_.cjs");exports.Phone=e.Phone;exports.PhoneProvider=e.PhoneProvider;exports.default=e.Phone;exports.usePhone=e.usePhone;exports.usePhoneManager=e.usePhoneManager;exports.cn=o.cn;exports.defaultLabels=o.defaultLabels;exports.formatDuration=o.formatDuration;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("./usePhoneManager-DD0_VgK7.cjs"),o=require("./index-BofRGPCe.cjs");exports.Phone=e.Phone;exports.PhoneProvider=e.PhoneProvider;exports.default=e.Phone;exports.usePhone=e.usePhone;exports.usePhoneManager=e.usePhoneManager;exports.cn=o.cn;exports.defaultLabels=o.defaultLabels;exports.formatDuration=o.formatDuration;
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { P as e } from "./usePhoneManager-CjRcDBFA.js";
2
- import { a as s, u as t, b as f } from "./usePhoneManager-CjRcDBFA.js";
3
- import { c as u, d as P, f as m } from "./index-8z_LWKp3.js";
1
+ import { P as e } from "./usePhoneManager-DwW3kOED.js";
2
+ import { a as s, u as t, b as f } from "./usePhoneManager-DwW3kOED.js";
3
+ import { c as u, d as P, f as m } from "./index-BP63oarb.js";
4
4
  export {
5
5
  e as Phone,
6
6
  s as PhoneProvider,
@@ -1 +1 @@
1
- {"version":3,"file":"Phone.d.ts","sourceRoot":"","sources":["../../src/react/Phone.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAoB,MAAM,UAAU,CAAC;AAsZ7D,MAAM,CAAC,OAAO,UAAU,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,EAAE,UAAU,2CAW9G"}
1
+ {"version":3,"file":"Phone.d.ts","sourceRoot":"","sources":["../../src/react/Phone.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAoB,MAAM,UAAU,CAAC;AAoZ7D,MAAM,CAAC,OAAO,UAAU,KAAK,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,EAAE,EAAE,UAAU,2CAW9G"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("../usePhoneManager-CfG7kttP.cjs");exports.Phone=e.Phone;exports.PhoneProvider=e.PhoneProvider;exports.default=e.Phone;exports.usePhone=e.usePhone;exports.usePhoneManager=e.usePhoneManager;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("../usePhoneManager-DD0_VgK7.cjs");exports.Phone=e.Phone;exports.PhoneProvider=e.PhoneProvider;exports.default=e.Phone;exports.usePhone=e.usePhone;exports.usePhoneManager=e.usePhoneManager;
@@ -1,5 +1,5 @@
1
- import { P as o } from "../usePhoneManager-CjRcDBFA.js";
2
- import { a as s, u as P, b as n } from "../usePhoneManager-CjRcDBFA.js";
1
+ import { P as o } from "../usePhoneManager-DwW3kOED.js";
2
+ import { a as s, u as P, b as n } from "../usePhoneManager-DwW3kOED.js";
3
3
  export {
4
4
  o as Phone,
5
5
  s as PhoneProvider,
@@ -1 +1 @@
1
- "use strict";const e=require("react/jsx-runtime"),s=require("react"),P=require("./index-1EBiLrV_.cjs");let L=null,O=null;function ee(t){return`${t.websocketUrl}|${t.sipUri}|${t.authorizationUser}`}function te(t){const h=ee(t);if(L&&O===h)return L;if(L&&O!==h){try{L.ua.stop()}catch{}L=null}O=h;const u={sockets:[new P.JsSIP.WebSocketInterface(t.websocketUrl)],uri:t.sipUri,password:t.password,registrar_server:t.registrarServer,display_name:t.displayName,authorization_user:t.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},d=new P.JsSIP.UA(u),v=document.createElement("audio");v.autoplay=!0;const x={ua:d,audio:v,isStarted:!1,listeners:new Set};return d.on("connecting",()=>{x.listeners.forEach(a=>a.onConnecting?.())}),d.on("connected",()=>{x.listeners.forEach(a=>a.onConnected?.())}),d.on("disconnected",()=>{x.listeners.forEach(a=>a.onDisconnected?.())}),d.on("registered",()=>{x.listeners.forEach(a=>a.onRegistered?.())}),d.on("unregistered",()=>{x.listeners.forEach(a=>a.onUnregistered?.())}),d.on("registrationFailed",a=>{x.listeners.forEach(l=>l.onRegistrationFailed?.(a?.cause))}),d.on("newRTCSession",a=>{const l=a.session;if(l.direction==="incoming"){const n=l.remote_identity,f=n?.uri?.user||"Unknown",S=n?.display_name||void 0;x.listeners.forEach(C=>C.onIncomingSession?.(l,f,S)),l.on("peerconnection",()=>{l.connection.addEventListener("addstream",C=>{var j=document.createElement("audio");C.streams!==void 0&&C.streams.length!==0&&(j.srcObject=C.streams[0],j.play())}),l.connection.addEventListener("track",C=>{var j=document.createElement("audio");j.srcObject=C.streams[0],j.play()})});return}x.listeners.forEach(n=>n.onNewSession?.(l)),l.connection&&(l.connection.addEventListener("addstream",n=>{var f=document.createElement("audio");n.streams!==void 0&&n.streams.length!==0&&(f.srcObject=n.streams[0],f.play())}),l.connection.addEventListener("track",n=>{var f=document.createElement("audio");f.srcObject=n.streams[0],f.play()}))}),L=x,x}function se(t){t.isStarted||(t.ua.start(),t.isStarted=!0)}function ne(t,h){t.listeners.add(h)}function re(t,h){t.listeners.delete(h)}function ae(t){return{isReady:t.ua.isRegistered(),isConnected:t.ua.isConnected()}}const K=s.createContext(null);function J({config:t,children:h,onCallStart:i,onCallEnd:u,onStatusChange:d,onIncomingCall:v}){const[x,a]=s.useState(""),[l,n]=s.useState("disconnected"),[f,S]=s.useState(null),[C,j]=s.useState(0),[D,H]=s.useState([]),[M,b]=s.useState(!1),[c,w]=s.useState("disconnected"),[m,I]=s.useState(!1),[k,U]=s.useState(null),N=s.useRef(null),o=s.useRef(null),E=s.useRef(null);s.useEffect(()=>{o.current=f},[f]);const G=s.useCallback(()=>{m||(I(!0),w("connecting"))},[m]);s.useEffect(()=>{if(!m)return;const r=te(t);E.current=r;const p=ae(r);p.isReady?(b(!0),w("connected")):p.isConnected&&w("connected");const z={onConnecting:()=>w("connecting"),onConnected:()=>w("connected"),onDisconnected:()=>{w("disconnected"),b(!1)},onRegistered:()=>{b(!0),w("connected")},onUnregistered:()=>b(!1),onRegistrationFailed:y=>{console.error("Registration failed:",y),b(!1),w("failed")},onNewSession:y=>{N.current=y},onIncomingSession:(y,g,_)=>{if(N.current){y.terminate({status_code:486,reason_phrase:"Busy Here"});return}U({session:y,callerNumber:g,callerName:_}),a(g),n("ringing"),v?.(g,_),y.on("failed",B=>{console.error("Incoming call failed:",B?.cause),n("failed"),R(g,0,"missed"),U(null),N.current=null,setTimeout(()=>n("disconnected"),3e3)}),y.on("ended",()=>{n("ended");const B=o.current,F=B?Math.floor((Date.now()-B)/1e3):0;R(g,F,"completed"),u?.(g,F,"completed"),U(null),N.current=null,setTimeout(()=>{n("disconnected"),S(null)},2e3)}),y.on("confirmed",()=>{n("confirmed"),S(Date.now()),U(null)})}};return ne(r,z),se(r),()=>{re(r,z)}},[m,t.websocketUrl,t.sipUri,t.password,t.registrarServer,t.displayName,t.authorizationUser]),s.useEffect(()=>{d?.(l)},[l,d]),s.useEffect(()=>{const r=localStorage.getItem("tbi-phone-call-history");if(r)try{H(JSON.parse(r))}catch(p){console.error("Error loading call history",p)}},[]),s.useEffect(()=>{D.length>0&&localStorage.setItem("tbi-phone-call-history",JSON.stringify(D))},[D]),s.useEffect(()=>{if(l==="confirmed"&&f){const r=setInterval(()=>{j(Math.floor((Date.now()-f)/1e3))},1e3);return()=>clearInterval(r)}else j(0)},[l,f]),s.useEffect(()=>{const r=p=>{const z=p.detail.number;l==="disconnected"&&$(z)};return window.addEventListener("StartCallEvent",r),()=>{window.removeEventListener("StartCallEvent",r)}},[l]);const R=s.useCallback((r,p,z)=>{const y={id:Date.now().toString(),number:r,timestamp:Date.now(),duration:p,status:z};H(g=>[y,...g].slice(0,50))},[]),Q=s.useCallback(()=>{N.current&&(N.current.terminate(),N.current=null),U(null)},[]),X=s.useCallback(()=>{if(!k)return;const{session:r,callerNumber:p}=k,z={mediaConstraints:{audio:!0,video:!1}};try{r.answer(z),N.current=r,i?.(p)}catch(y){console.error("Failed to answer call:",y),n("failed"),R(p,0,"missed"),U(null),setTimeout(()=>n("disconnected"),3e3)}},[k,i,R]),Y=s.useCallback(()=>{if(!k)return;const{session:r,callerNumber:p}=k;try{r.terminate({status_code:603,reason_phrase:"Decline"})}catch(z){console.error("Failed to reject call:",z)}R(p,0,"missed"),U(null),n("disconnected")},[k,R]),$=s.useCallback(r=>{const p=E.current;if(!r.trim()||!p)return;if(!M){console.warn("Phone is not ready yet. Please wait for registration.");return}a(r),i?.(r);const y={eventHandlers:{progress:()=>{n("progress")},failed:g=>{console.error("Call failed:",g?.cause),n("failed"),R(r,0,"failed"),u?.(r,0,"failed"),N.current=null,setTimeout(()=>n("disconnected"),3e3)},ended:()=>{n("ended");const g=o.current,_=g?Math.floor((Date.now()-g)/1e3):0;R(r,_,"completed"),u?.(r,_,"completed"),N.current=null,setTimeout(()=>{n("disconnected"),S(null)},2e3)},confirmed:()=>{n("confirmed"),S(Date.now())}},mediaConstraints:{audio:!0,video:!1}};n("progress");try{const g=p.ua.call(r,y);N.current=g}catch(g){console.error("Failed to start call:",g),n("failed"),R(r,0,"failed"),setTimeout(()=>n("disconnected"),3e3)}},[R,i,u,M]),Z={status:l,callNumber:x,setCallNumber:a,callHistory:D,currentCallDuration:C,startCall:$,endCall:Q,answerCall:X,rejectCall:Y,isReady:M,connectionStatus:c,isInitialized:m,initialize:G,incomingCall:k};return e.jsx(K.Provider,{value:Z,children:h})}function q(){const t=s.useContext(K);if(!t)throw new Error("usePhone must be used within a PhoneProvider");return t}const A=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})}),V=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})}),le=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.12-.74-.03-1.02.24l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"})}),T=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})}),W=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"})}),oe=({className:t})=>e.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"}),e.jsx("path",{d:"M16 3l-5 5-2-2-1.5 1.5L11 11l6.5-6.5z"})]}),ce=({className:t})=>e.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"}),e.jsx("path",{d:"M19 6.41L17.59 5 15 7.59 12.41 5 11 6.41 13.59 9 11 11.59 12.41 13 15 10.41 17.59 13 19 11.59 16.41 9z"})]}),ie=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"})}),de=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}),ue=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z"})});function me({className:t,labels:h}){const{status:i,callNumber:u,setCallNumber:d,callHistory:v,currentCallDuration:x,startCall:a,endCall:l,answerCall:n,rejectCall:f,isReady:S,connectionStatus:C,isInitialized:j,initialize:D,incomingCall:H}=q(),[M,b]=s.useState(!1),c={...P.defaultLabels,...h},m=(()=>{switch(i){case"ringing":return{text:c.incomingCall,color:"text-blue-500",Icon:V};case"progress":return{text:`${c.calling}...`,color:"text-yellow-500",Icon:V};case"confirmed":return{text:`${c.inCall} - ${P.formatDuration(x)}`,color:"text-green-500",Icon:le};case"failed":return{text:c.callEnded,color:"text-red-500",Icon:W};case"ended":return{text:c.callEnded,color:"text-gray-500",Icon:T};default:return{text:c.inactive,color:"text-gray-300",Icon:A}}})();return e.jsxs("div",{className:P.cn("tbi-phone w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg border border-gray-200 p-2",t),children:[!j&&e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("button",{onClick:D,className:"h-8 w-8 flex items-center justify-center rounded-xl bg-gray-100 hover:bg-green-100 hover:text-green-600 text-gray-500 transition-colors",type:"button",title:c.turnOn,children:e.jsx(ue,{className:"w-5 h-5"})})}),j&&i==="disconnected"&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("button",{onClick:()=>b(!0),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors",type:"button",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("input",{type:"text",value:u,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&a(u)},placeholder:c.placeholder,className:"flex-1 w-full h-8 px-3 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"}),e.jsx("button",{onClick:()=>a(u),disabled:u.length<9||!S,className:"h-8 w-8 flex items-center justify-center rounded-xl bg-green-500 hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white transition-colors",type:"button",title:S?"Call":"Connecting...",children:C==="connecting"?e.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):e.jsx(A,{className:"w-4 h-4"})})]}),i==="progress"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-yellow-500 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 rounded-full border-4 border-yellow-500/30 animate-ping"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-base font-semibold",children:[c.calling," ",u]}),e.jsx("p",{className:"text-sm text-gray-500",children:c.waitingResponse})]}),e.jsxs("button",{onClick:l,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.cancel]})]}),i==="ringing"&&H&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-blue-500 animate-bounce"}),e.jsx("div",{className:"absolute inset-0 rounded-full border-4 border-blue-500/30 animate-ping"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:c.incomingCall}),e.jsx("p",{className:"text-base font-semibold",children:H.callerNumber}),H.callerName&&e.jsx("p",{className:"text-sm text-gray-600",children:H.callerName})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("button",{onClick:f,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.reject]}),e.jsxs("button",{onClick:n,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-green-500 hover:bg-green-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(A,{className:"w-4 h-4"}),c.answer]})]})]}),i==="confirmed"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-green-500"}),e.jsx("div",{className:"absolute inset-0 rounded-full bg-green-500/20 animate-pulse"})]}),e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("p",{className:"text-xl font-bold",children:u}),e.jsx("p",{className:"text-2xl font-mono text-green-600 tabular-nums",children:P.formatDuration(x)})]}),e.jsxs("button",{onClick:l,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.hangUp]})]}),(i==="failed"||i==="ended")&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsx(m.Icon,{className:P.cn("w-12 h-12",i==="failed"?"text-red-500":"text-gray-500")}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-base font-semibold",children:m.text})})]}),M&&e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>b(!1)}),e.jsx("div",{className:"fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-xl",style:{backgroundColor:"white"},children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:c.callHistory}),e.jsx("p",{className:"text-sm text-gray-500",children:v.length===0?c.noCallsRegistered:`${v.length} ${c.callsRegistered}`})]}),e.jsx("button",{onClick:()=>b(!1),className:"h-8 w-8 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors",type:"button",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:v.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500",children:[e.jsx(T,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:c.noCalls})]}):e.jsx("div",{className:"space-y-2",children:v.map((I,k)=>e.jsx(xe,{entry:I,index:k,onCall:()=>{d(I.number),b(!1),a(I.number)}},I.id))})})]})})]})]})}function xe({entry:t,index:h,onCall:i}){const u=()=>{switch(t.status){case"completed":return e.jsx(oe,{className:"w-4 h-4 text-green-600"});case"failed":return e.jsx(ce,{className:"w-4 h-4 text-red-600"});case"missed":return e.jsx(W,{className:"w-4 h-4 text-yellow-600"})}},d=()=>{switch(t.status){case"completed":return"bg-green-100";case"failed":return"bg-red-100";case"missed":return"bg-yellow-100"}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors duration-200",style:{animationDelay:`${h*30}ms`},children:[e.jsx("div",{className:P.cn("w-9 h-9 rounded-full flex items-center justify-center shrink-0",d()),children:u()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t.number}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:new Date(t.timestamp).toLocaleString("es-ES",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),t.duration>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"font-mono tabular-nums",children:P.formatDuration(t.duration)})]})]})]}),e.jsx("button",{onClick:i,className:"h-8 w-8 flex items-center justify-center shrink-0 rounded-lg hover:bg-gray-100 transition-colors",type:"button",children:e.jsx(A,{className:"w-4 h-4"})})]})}function he({config:t,className:h,onCallStart:i,onCallEnd:u,onStatusChange:d,labels:v}){return e.jsx(J,{config:t,onCallStart:i,onCallEnd:u,onStatusChange:d,children:e.jsx(me,{className:h,labels:v})})}function fe(t,h={}){const{onCallStart:i,onCallEnd:u,onStatusChange:d,onConnectionChange:v,persistHistory:x=!0,historyKey:a="tbi-phone-call-history"}=h,[l,n]=s.useState("disconnected"),[f,S]=s.useState(""),[C,j]=s.useState([]),[D,H]=s.useState(0),[M,b]=s.useState(!1),[c,w]=s.useState("connecting"),m=s.useRef(null);s.useEffect(()=>{const o=new P.PhoneManager(t,{onStatusChange:E=>{n(E),d?.(E)},onConnectionChange:E=>{w(E),(E==="connected"||E==="disconnected"||E==="failed")&&b(o.state.isReady),v?.(E)},onCallStart:i,onCallEnd:u,onDurationUpdate:H,onHistoryUpdate:j,onRegistered:()=>b(!0),onUnregistered:()=>b(!1)},{persistHistory:x,historyKey:a});return o.initialize(),m.current=o,n(o.state.status),S(o.state.callNumber),j(o.state.callHistory),b(o.state.isReady),w(o.state.connectionStatus),()=>{o.destroy(),m.current=null}},[t.websocketUrl,t.sipUri,t.password,t.registrarServer,t.displayName,t.authorizationUser,x,a]),s.useEffect(()=>{m.current&&m.current.setEvents({onCallStart:i,onCallEnd:u,onStatusChange:o=>{n(o),d?.(o)},onConnectionChange:o=>{w(o),v?.(o)}})},[i,u,d,v]);const I=s.useCallback(o=>{S(o),m.current?.setCallNumber(o)},[]),k=s.useCallback(o=>{m.current?.startCall(o)},[]),U=s.useCallback(()=>{m.current?.endCall()},[]),N=s.useCallback(()=>{m.current?.clearHistory(),j([])},[]);return{status:l,callNumber:f,setCallNumber:I,callHistory:C,clearCallHistory:N,currentCallDuration:D,startCall:k,endCall:U,isReady:M,connectionStatus:c,ua:m.current?.ua??null}}exports.Phone=he;exports.PhoneProvider=J;exports.usePhone=q;exports.usePhoneManager=fe;
1
+ "use strict";const e=require("react/jsx-runtime"),s=require("react"),P=require("./index-BofRGPCe.cjs");let L=null,O=null;function ee(t){return`${t.websocketUrl}|${t.sipUri}|${t.authorizationUser}`}function te(t){const h=ee(t);if(L&&O===h)return L;if(L&&O!==h){try{L.ua.stop()}catch{}L=null}O=h;const u={sockets:[new P.JsSIP.WebSocketInterface(t.websocketUrl)],uri:t.sipUri,password:t.password,registrar_server:t.registrarServer,display_name:t.displayName,authorization_user:t.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},d=new P.JsSIP.UA(u),v=document.createElement("audio");v.autoplay=!0;const x={ua:d,audio:v,isStarted:!1,listeners:new Set};return d.on("connecting",()=>{x.listeners.forEach(a=>a.onConnecting?.())}),d.on("connected",()=>{x.listeners.forEach(a=>a.onConnected?.())}),d.on("disconnected",()=>{x.listeners.forEach(a=>a.onDisconnected?.())}),d.on("registered",()=>{x.listeners.forEach(a=>a.onRegistered?.())}),d.on("unregistered",()=>{x.listeners.forEach(a=>a.onUnregistered?.())}),d.on("registrationFailed",a=>{x.listeners.forEach(o=>o.onRegistrationFailed?.(a?.cause))}),d.on("newRTCSession",a=>{const o=a.session;if(o.direction==="incoming"){const n=o.remote_identity,f=n?.uri?.user||"Unknown",S=n?.display_name||void 0;x.listeners.forEach(C=>C.onIncomingSession?.(o,f,S)),o.on("peerconnection",()=>{o.connection.addEventListener("addstream",C=>{var j=document.createElement("audio");C.streams!==void 0&&C.streams.length!==0&&(j.srcObject=C.streams[0],j.play())}),o.connection.addEventListener("track",C=>{var j=document.createElement("audio");j.srcObject=C.streams[0],j.play()})});return}x.listeners.forEach(n=>n.onNewSession?.(o)),o.connection&&(o.connection.addEventListener("addstream",n=>{var f=document.createElement("audio");n.streams!==void 0&&n.streams.length!==0&&(f.srcObject=n.streams[0],f.play())}),o.connection.addEventListener("track",n=>{var f=document.createElement("audio");f.srcObject=n.streams[0],f.play()}))}),L=x,x}function se(t){t.isStarted||(t.ua.start(),t.isStarted=!0)}function ne(t,h){t.listeners.add(h)}function re(t,h){t.listeners.delete(h)}function ae(t){return{isReady:t.ua.isRegistered(),isConnected:t.ua.isConnected()}}const K=s.createContext(null);function J({config:t,children:h,onCallStart:i,onCallEnd:u,onStatusChange:d,onIncomingCall:v}){const[x,a]=s.useState(""),[o,n]=s.useState("disconnected"),[f,S]=s.useState(null),[C,j]=s.useState(0),[U,D]=s.useState([]),[M,b]=s.useState(!1),[c,w]=s.useState("disconnected"),[m,I]=s.useState(!1),[k,H]=s.useState(null),N=s.useRef(null),l=s.useRef(null),E=s.useRef(null);s.useEffect(()=>{l.current=f},[f]);const G=s.useCallback(()=>{m||(I(!0),w("connecting"))},[m]);s.useEffect(()=>{if(!m)return;const r=te(t);E.current=r;const p=ae(r);p.isReady?(b(!0),w("connected")):p.isConnected&&w("connected");const z={onConnecting:()=>w("connecting"),onConnected:()=>w("connected"),onDisconnected:()=>{w("disconnected"),b(!1)},onRegistered:()=>{b(!0),w("connected")},onUnregistered:()=>b(!1),onRegistrationFailed:y=>{console.error("Registration failed:",y),b(!1),w("failed")},onNewSession:y=>{N.current=y},onIncomingSession:(y,g,_)=>{if(N.current){y.terminate({status_code:486,reason_phrase:"Busy Here"});return}H({session:y,callerNumber:g,callerName:_}),a(g),n("ringing"),v?.(g,_),y.on("failed",B=>{console.error("Incoming call failed:",B?.cause),n("failed"),R(g,0,"missed"),H(null),N.current=null,setTimeout(()=>n("disconnected"),3e3)}),y.on("ended",()=>{n("ended");const B=l.current,F=B?Math.floor((Date.now()-B)/1e3):0;R(g,F,"completed"),u?.(g,F,"completed"),H(null),N.current=null,setTimeout(()=>{n("disconnected"),S(null)},2e3)}),y.on("confirmed",()=>{n("confirmed"),S(Date.now()),H(null)})}};return ne(r,z),se(r),()=>{re(r,z)}},[m,t.websocketUrl,t.sipUri,t.password,t.registrarServer,t.displayName,t.authorizationUser]),s.useEffect(()=>{d?.(o)},[o,d]),s.useEffect(()=>{const r=localStorage.getItem("tbi-phone-call-history");if(r)try{D(JSON.parse(r))}catch(p){console.error("Error loading call history",p)}},[]),s.useEffect(()=>{U.length>0&&localStorage.setItem("tbi-phone-call-history",JSON.stringify(U))},[U]),s.useEffect(()=>{if(o==="confirmed"&&f){const r=setInterval(()=>{j(Math.floor((Date.now()-f)/1e3))},1e3);return()=>clearInterval(r)}else j(0)},[o,f]),s.useEffect(()=>{const r=p=>{const z=p.detail.number;o==="disconnected"&&$(z)};return window.addEventListener("StartCallEvent",r),()=>{window.removeEventListener("StartCallEvent",r)}},[o]);const R=s.useCallback((r,p,z)=>{const y={id:Date.now().toString(),number:r,timestamp:Date.now(),duration:p,status:z};D(g=>[y,...g].slice(0,50))},[]),Q=s.useCallback(()=>{N.current&&(N.current.terminate(),N.current=null),H(null)},[]),X=s.useCallback(()=>{if(!k)return;const{session:r,callerNumber:p}=k,z={mediaConstraints:{audio:!0,video:!1}};try{r.answer(z),N.current=r,i?.(p)}catch(y){console.error("Failed to answer call:",y),n("failed"),R(p,0,"missed"),H(null),setTimeout(()=>n("disconnected"),3e3)}},[k,i,R]),Y=s.useCallback(()=>{if(!k)return;const{session:r,callerNumber:p}=k;try{r.terminate({status_code:603,reason_phrase:"Decline"})}catch(z){console.error("Failed to reject call:",z)}R(p,0,"missed"),H(null),n("disconnected")},[k,R]),$=s.useCallback(r=>{const p=E.current;if(!r.trim()||!p)return;if(!M){console.warn("Phone is not ready yet. Please wait for registration.");return}a(r),i?.(r);const y={eventHandlers:{progress:()=>{n("progress")},failed:g=>{console.error("Call failed:",g?.cause),n("failed"),R(r,0,"failed"),u?.(r,0,"failed"),N.current=null,setTimeout(()=>n("disconnected"),3e3)},ended:()=>{n("ended");const g=l.current,_=g?Math.floor((Date.now()-g)/1e3):0;R(r,_,"completed"),u?.(r,_,"completed"),N.current=null,setTimeout(()=>{n("disconnected"),S(null)},2e3)},confirmed:()=>{n("confirmed"),S(Date.now())}},mediaConstraints:{audio:!0,video:!1}};n("progress");try{const g=p.ua.call(r,y);N.current=g}catch(g){console.error("Failed to start call:",g),n("failed"),R(r,0,"failed"),setTimeout(()=>n("disconnected"),3e3)}},[R,i,u,M]),Z={status:o,callNumber:x,setCallNumber:a,callHistory:U,currentCallDuration:C,startCall:$,endCall:Q,answerCall:X,rejectCall:Y,isReady:M,connectionStatus:c,isInitialized:m,initialize:G,incomingCall:k};return e.jsx(K.Provider,{value:Z,children:h})}function q(){const t=s.useContext(K);if(!t)throw new Error("usePhone must be used within a PhoneProvider");return t}const A=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})}),V=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})}),oe=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.12-.74-.03-1.02.24l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"})}),T=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})}),W=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"})}),le=({className:t})=>e.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"}),e.jsx("path",{d:"M16 3l-5 5-2-2-1.5 1.5L11 11l6.5-6.5z"})]}),ce=({className:t})=>e.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"}),e.jsx("path",{d:"M19 6.41L17.59 5 15 7.59 12.41 5 11 6.41 13.59 9 11 11.59 12.41 13 15 10.41 17.59 13 19 11.59 16.41 9z"})]}),ie=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"})}),de=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})}),ue=({className:t})=>e.jsx("svg",{className:t,viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M13 3h-2v10h2V3zm4.83 2.17l-1.42 1.42C17.99 7.86 19 9.81 19 12c0 3.87-3.13 7-7 7s-7-3.13-7-7c0-2.19 1.01-4.14 2.58-5.42L6.17 5.17C4.23 6.82 3 9.26 3 12c0 4.97 4.03 9 9 9s9-4.03 9-9c0-2.74-1.23-5.18-3.17-6.83z"})});function me({className:t,labels:h}){const{status:i,callNumber:u,setCallNumber:d,callHistory:v,currentCallDuration:x,startCall:a,endCall:o,answerCall:n,rejectCall:f,isReady:S,connectionStatus:C,isInitialized:j,initialize:U,incomingCall:D}=q(),[M,b]=s.useState(!1),c={...P.defaultLabels,...h},m=(()=>{switch(i){case"ringing":return{text:c.incomingCall,color:"text-blue-500",Icon:V};case"progress":return{text:`${c.calling}...`,color:"text-yellow-500",Icon:V};case"confirmed":return{text:`${c.inCall} - ${P.formatDuration(x)}`,color:"text-green-500",Icon:oe};case"failed":return{text:c.callEnded,color:"text-red-500",Icon:W};case"ended":return{text:c.callEnded,color:"text-gray-500",Icon:T};default:return{text:c.inactive,color:"text-gray-300",Icon:A}}})();return e.jsxs("div",{className:P.cn("tbi-phone w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg border border-gray-200 p-2",t),children:[!j&&e.jsx("div",{className:"flex items-center justify-center",children:e.jsx("button",{onClick:U,className:"h-8 w-8 flex items-center justify-center rounded-xl bg-gray-100 hover:bg-green-100 hover:text-green-600 text-gray-500 transition-colors",type:"button",title:c.turnOn,children:e.jsx(ue,{className:"w-5 h-5"})})}),j&&i==="disconnected"&&e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("button",{onClick:()=>b(!0),className:"h-8 w-8 flex items-center justify-center rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors",type:"button",children:e.jsx(ie,{className:"w-4 h-4"})}),e.jsx("input",{type:"text",value:u,onChange:I=>d(I.target.value),onKeyDown:I=>{I.key==="Enter"&&a(u)},placeholder:c.placeholder,className:"flex-1 w-full h-8 px-3 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"}),e.jsx("button",{onClick:()=>a(u),disabled:u.length<9||!S,className:"h-8 w-8 flex items-center justify-center rounded-xl bg-green-500 hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white transition-colors",type:"button",title:S?"Call":"Connecting...",children:C==="connecting"?e.jsx("div",{className:"w-4 h-4 border-2 border-white rounded-full animate-spin"}):e.jsx(A,{className:"w-4 h-4"})})]}),i==="progress"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-yellow-500 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 rounded-full border-4 border-yellow-500/30 animate-ping"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-base font-semibold",children:[c.calling," ",u]}),e.jsx("p",{className:"text-sm text-gray-500",children:c.waitingResponse})]}),e.jsxs("button",{onClick:o,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.cancel]})]}),i==="ringing"&&D&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-blue-500 animate-bounce"}),e.jsx("div",{className:"absolute inset-0 rounded-full border-4 border-blue-500/30 animate-ping"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-sm text-gray-500",children:c.incomingCall}),e.jsx("p",{className:"text-base font-semibold",children:D.callerNumber})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("button",{onClick:f,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.reject]}),e.jsxs("button",{onClick:n,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-green-500 hover:bg-green-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(A,{className:"w-4 h-4"}),c.answer]})]})]}),i==="confirmed"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-6",children:[e.jsxs("div",{className:"relative",children:[e.jsx(m.Icon,{className:"w-12 h-12 text-green-500"}),e.jsx("div",{className:"absolute inset-0 rounded-full bg-green-500/20 animate-pulse"})]}),e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("p",{className:"text-xl font-bold",children:u}),e.jsx("p",{className:"text-2xl font-mono text-green-600 tabular-nums",children:P.formatDuration(x)})]}),e.jsxs("button",{onClick:o,className:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button",children:[e.jsx(T,{className:"w-4 h-4"}),c.hangUp]})]}),(i==="failed"||i==="ended")&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-6",children:[e.jsx(m.Icon,{className:P.cn("w-12 h-12",i==="failed"?"text-red-500":"text-gray-500")}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-base font-semibold",children:m.text})})]}),M&&e.jsxs("div",{className:"fixed inset-0 z-50 flex",children:[e.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>b(!1)}),e.jsx("div",{className:"fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-xl",style:{backgroundColor:"white"},children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:c.callHistory}),e.jsx("p",{className:"text-sm text-gray-500",children:v.length===0?c.noCallsRegistered:`${v.length} ${c.callsRegistered}`})]}),e.jsx("button",{onClick:()=>b(!1),className:"h-8 w-8 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors",type:"button",children:e.jsx(de,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:v.length===0?e.jsxs("div",{className:"text-center py-12 text-gray-500",children:[e.jsx(T,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:c.noCalls})]}):e.jsx("div",{className:"space-y-2",children:v.map((I,k)=>e.jsx(xe,{entry:I,index:k,onCall:()=>{d(I.number),b(!1),a(I.number)}},I.id))})})]})})]})]})}function xe({entry:t,index:h,onCall:i}){const u=()=>{switch(t.status){case"completed":return e.jsx(le,{className:"w-4 h-4 text-green-600"});case"failed":return e.jsx(ce,{className:"w-4 h-4 text-red-600"});case"missed":return e.jsx(W,{className:"w-4 h-4 text-yellow-600"})}},d=()=>{switch(t.status){case"completed":return"bg-green-100";case"failed":return"bg-red-100";case"missed":return"bg-yellow-100"}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors duration-200",style:{animationDelay:`${h*30}ms`},children:[e.jsx("div",{className:P.cn("w-9 h-9 rounded-full flex items-center justify-center shrink-0",d()),children:u()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t.number}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:[e.jsx("span",{children:new Date(t.timestamp).toLocaleString("es-ES",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),t.duration>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"font-mono tabular-nums",children:P.formatDuration(t.duration)})]})]})]}),e.jsx("button",{onClick:i,className:"h-8 w-8 flex items-center justify-center shrink-0 rounded-lg hover:bg-gray-100 transition-colors",type:"button",children:e.jsx(A,{className:"w-4 h-4"})})]})}function he({config:t,className:h,onCallStart:i,onCallEnd:u,onStatusChange:d,labels:v}){return e.jsx(J,{config:t,onCallStart:i,onCallEnd:u,onStatusChange:d,children:e.jsx(me,{className:h,labels:v})})}function fe(t,h={}){const{onCallStart:i,onCallEnd:u,onStatusChange:d,onConnectionChange:v,persistHistory:x=!0,historyKey:a="tbi-phone-call-history"}=h,[o,n]=s.useState("disconnected"),[f,S]=s.useState(""),[C,j]=s.useState([]),[U,D]=s.useState(0),[M,b]=s.useState(!1),[c,w]=s.useState("connecting"),m=s.useRef(null);s.useEffect(()=>{const l=new P.PhoneManager(t,{onStatusChange:E=>{n(E),d?.(E)},onConnectionChange:E=>{w(E),(E==="connected"||E==="disconnected"||E==="failed")&&b(l.state.isReady),v?.(E)},onCallStart:i,onCallEnd:u,onDurationUpdate:D,onHistoryUpdate:j,onRegistered:()=>b(!0),onUnregistered:()=>b(!1)},{persistHistory:x,historyKey:a});return l.initialize(),m.current=l,n(l.state.status),S(l.state.callNumber),j(l.state.callHistory),b(l.state.isReady),w(l.state.connectionStatus),()=>{l.destroy(),m.current=null}},[t.websocketUrl,t.sipUri,t.password,t.registrarServer,t.displayName,t.authorizationUser,x,a]),s.useEffect(()=>{m.current&&m.current.setEvents({onCallStart:i,onCallEnd:u,onStatusChange:l=>{n(l),d?.(l)},onConnectionChange:l=>{w(l),v?.(l)}})},[i,u,d,v]);const I=s.useCallback(l=>{S(l),m.current?.setCallNumber(l)},[]),k=s.useCallback(l=>{m.current?.startCall(l)},[]),H=s.useCallback(()=>{m.current?.endCall()},[]),N=s.useCallback(()=>{m.current?.clearHistory(),j([])},[]);return{status:o,callNumber:f,setCallNumber:I,callHistory:C,clearCallHistory:N,currentCallDuration:U,startCall:k,endCall:H,isReady:M,connectionStatus:c,ua:m.current?.ua??null}}exports.Phone=he;exports.PhoneProvider=J;exports.usePhone=q;exports.usePhoneManager=fe;
@@ -1,6 +1,6 @@
1
1
  import { jsx as t, jsxs as s, Fragment as se } from "react/jsx-runtime";
2
- import { useState as v, useRef as $, useEffect as j, useCallback as U, createContext as oe, useContext as ae } from "react";
3
- import { J as G, d as le, c as K, f as J, P as ce } from "./index-8z_LWKp3.js";
2
+ import { useState as v, useRef as $, useEffect as M, useCallback as U, createContext as oe, useContext as ae } from "react";
3
+ import { J as G, d as le, c as K, f as J, P as ce } from "./index-BP63oarb.js";
4
4
  let _ = null, V = null;
5
5
  function ie(e) {
6
6
  return `${e.websocketUrl}|${e.sipUri}|${e.authorizationUser}`;
@@ -94,14 +94,14 @@ function ge({
94
94
  onStatusChange: d,
95
95
  onIncomingCall: y
96
96
  }) {
97
- const [h, o] = v(""), [a, n] = v("disconnected"), [g, z] = v(null), [N, b] = v(0), [L, D] = v([]), [T, C] = v(!1), [c, I] = v("disconnected"), [m, k] = v(!1), [E, M] = v(null), S = $(null), l = $(null), H = $(null);
98
- j(() => {
97
+ const [h, o] = v(""), [a, n] = v("disconnected"), [g, z] = v(null), [N, b] = v(0), [j, L] = v([]), [T, C] = v(!1), [c, I] = v("disconnected"), [m, k] = v(!1), [E, D] = v(null), S = $(null), l = $(null), H = $(null);
98
+ M(() => {
99
99
  l.current = g;
100
100
  }, [g]);
101
101
  const Z = U(() => {
102
102
  m || (k(!0), I("connecting"));
103
103
  }, [m]);
104
- j(() => {
104
+ M(() => {
105
105
  if (!m) return;
106
106
  const r = de(e);
107
107
  H.current = r;
@@ -128,35 +128,35 @@ function ge({
128
128
  w.terminate({ status_code: 486, reason_phrase: "Busy Here" });
129
129
  return;
130
130
  }
131
- M({ session: w, callerNumber: p, callerName: B }), o(p), n("ringing"), y?.(p, B), w.on("failed", (O) => {
132
- console.error("Incoming call failed:", O?.cause), n("failed"), P(p, 0, "missed"), M(null), S.current = null, setTimeout(() => n("disconnected"), 3e3);
131
+ D({ session: w, callerNumber: p, callerName: B }), o(p), n("ringing"), y?.(p, B), w.on("failed", (O) => {
132
+ console.error("Incoming call failed:", O?.cause), n("failed"), P(p, 0, "missed"), D(null), S.current = null, setTimeout(() => n("disconnected"), 3e3);
133
133
  }), w.on("ended", () => {
134
134
  n("ended");
135
135
  const O = l.current, q = O ? Math.floor((Date.now() - O) / 1e3) : 0;
136
- P(p, q, "completed"), u?.(p, q, "completed"), M(null), S.current = null, setTimeout(() => {
136
+ P(p, q, "completed"), u?.(p, q, "completed"), D(null), S.current = null, setTimeout(() => {
137
137
  n("disconnected"), z(null);
138
138
  }, 2e3);
139
139
  }), w.on("confirmed", () => {
140
- n("confirmed"), z(Date.now()), M(null);
140
+ n("confirmed"), z(Date.now()), D(null);
141
141
  });
142
142
  }
143
143
  };
144
144
  return me(r, R), ue(r), () => {
145
145
  he(r, R);
146
146
  };
147
- }, [m, e.websocketUrl, e.sipUri, e.password, e.registrarServer, e.displayName, e.authorizationUser]), j(() => {
147
+ }, [m, e.websocketUrl, e.sipUri, e.password, e.registrarServer, e.displayName, e.authorizationUser]), M(() => {
148
148
  d?.(a);
149
- }, [a, d]), j(() => {
149
+ }, [a, d]), M(() => {
150
150
  const r = localStorage.getItem("tbi-phone-call-history");
151
151
  if (r)
152
152
  try {
153
- D(JSON.parse(r));
153
+ L(JSON.parse(r));
154
154
  } catch (x) {
155
155
  console.error("Error loading call history", x);
156
156
  }
157
- }, []), j(() => {
158
- L.length > 0 && localStorage.setItem("tbi-phone-call-history", JSON.stringify(L));
159
- }, [L]), j(() => {
157
+ }, []), M(() => {
158
+ j.length > 0 && localStorage.setItem("tbi-phone-call-history", JSON.stringify(j));
159
+ }, [j]), M(() => {
160
160
  if (a === "confirmed" && g) {
161
161
  const r = setInterval(() => {
162
162
  b(Math.floor((Date.now() - g) / 1e3));
@@ -164,7 +164,7 @@ function ge({
164
164
  return () => clearInterval(r);
165
165
  } else
166
166
  b(0);
167
- }, [a, g]), j(() => {
167
+ }, [a, g]), M(() => {
168
168
  const r = (x) => {
169
169
  const R = x.detail.number;
170
170
  a === "disconnected" && W(R);
@@ -181,9 +181,9 @@ function ge({
181
181
  duration: x,
182
182
  status: R
183
183
  };
184
- D((p) => [w, ...p].slice(0, 50));
184
+ L((p) => [w, ...p].slice(0, 50));
185
185
  }, []), ee = U(() => {
186
- S.current && (S.current.terminate(), S.current = null), M(null);
186
+ S.current && (S.current.terminate(), S.current = null), D(null);
187
187
  }, []), te = U(() => {
188
188
  if (!E) return;
189
189
  const { session: r, callerNumber: x } = E, R = {
@@ -192,7 +192,7 @@ function ge({
192
192
  try {
193
193
  r.answer(R), S.current = r, i?.(x);
194
194
  } catch (w) {
195
- console.error("Failed to answer call:", w), n("failed"), P(x, 0, "missed"), M(null), setTimeout(() => n("disconnected"), 3e3);
195
+ console.error("Failed to answer call:", w), n("failed"), P(x, 0, "missed"), D(null), setTimeout(() => n("disconnected"), 3e3);
196
196
  }
197
197
  }, [E, i, P]), ne = U(() => {
198
198
  if (!E) return;
@@ -202,7 +202,7 @@ function ge({
202
202
  } catch (R) {
203
203
  console.error("Failed to reject call:", R);
204
204
  }
205
- P(x, 0, "missed"), M(null), n("disconnected");
205
+ P(x, 0, "missed"), D(null), n("disconnected");
206
206
  }, [E, P]), W = U((r) => {
207
207
  const x = H.current;
208
208
  if (!r.trim() || !x) return;
@@ -243,7 +243,7 @@ function ge({
243
243
  status: a,
244
244
  callNumber: h,
245
245
  setCallNumber: o,
246
- callHistory: L,
246
+ callHistory: j,
247
247
  currentCallDuration: N,
248
248
  startCall: W,
249
249
  endCall: ee,
@@ -284,8 +284,8 @@ function Ne({ className: e, labels: f }) {
284
284
  isReady: z,
285
285
  connectionStatus: N,
286
286
  isInitialized: b,
287
- initialize: L,
288
- incomingCall: D
287
+ initialize: j,
288
+ incomingCall: L
289
289
  } = pe(), [T, C] = v(!1), c = { ...le, ...f }, m = (() => {
290
290
  switch (i) {
291
291
  case "ringing":
@@ -309,7 +309,7 @@ function Ne({ className: e, labels: f }) {
309
309
  !b && /* @__PURE__ */ t("div", { className: "flex items-center justify-center", children: /* @__PURE__ */ t(
310
310
  "button",
311
311
  {
312
- onClick: L,
312
+ onClick: j,
313
313
  className: "h-8 w-8 flex items-center justify-center rounded-xl bg-gray-100 hover:bg-green-100 hover:text-green-600 text-gray-500 transition-colors",
314
314
  type: "button",
315
315
  title: c.turnOn,
@@ -347,7 +347,7 @@ function Ne({ className: e, labels: f }) {
347
347
  className: "h-8 w-8 flex items-center justify-center rounded-xl bg-green-500 hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white transition-colors",
348
348
  type: "button",
349
349
  title: z ? "Call" : "Connecting...",
350
- children: N === "connecting" ? /* @__PURE__ */ t("div", { className: "w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" }) : /* @__PURE__ */ t(F, { className: "w-4 h-4" })
350
+ children: N === "connecting" ? /* @__PURE__ */ t("div", { className: "w-4 h-4 border-2 border-white rounded-full animate-spin" }) : /* @__PURE__ */ t(F, { className: "w-4 h-4" })
351
351
  }
352
352
  )
353
353
  ] }),
@@ -377,15 +377,14 @@ function Ne({ className: e, labels: f }) {
377
377
  }
378
378
  )
379
379
  ] }),
380
- i === "ringing" && D && /* @__PURE__ */ s("div", { className: "flex flex-col items-center gap-3 py-6", children: [
380
+ i === "ringing" && L && /* @__PURE__ */ s("div", { className: "flex flex-col items-center gap-3 py-6", children: [
381
381
  /* @__PURE__ */ s("div", { className: "relative", children: [
382
382
  /* @__PURE__ */ t(m.Icon, { className: "w-12 h-12 text-blue-500 animate-bounce" }),
383
383
  /* @__PURE__ */ t("div", { className: "absolute inset-0 rounded-full border-4 border-blue-500/30 animate-ping" })
384
384
  ] }),
385
385
  /* @__PURE__ */ s("div", { className: "text-center", children: [
386
386
  /* @__PURE__ */ t("p", { className: "text-sm text-gray-500", children: c.incomingCall }),
387
- /* @__PURE__ */ t("p", { className: "text-base font-semibold", children: D.callerNumber }),
388
- D.callerName && /* @__PURE__ */ t("p", { className: "text-sm text-gray-600", children: D.callerName })
387
+ /* @__PURE__ */ t("p", { className: "text-base font-semibold", children: L.callerNumber })
389
388
  ] }),
390
389
  /* @__PURE__ */ s("div", { className: "flex gap-3", children: [
391
390
  /* @__PURE__ */ s(
@@ -572,8 +571,8 @@ function He(e, f = {}) {
572
571
  onConnectionChange: y,
573
572
  persistHistory: h = !0,
574
573
  historyKey: o = "tbi-phone-call-history"
575
- } = f, [a, n] = v("disconnected"), [g, z] = v(""), [N, b] = v([]), [L, D] = v(0), [T, C] = v(!1), [c, I] = v("connecting"), m = $(null);
576
- j(() => {
574
+ } = f, [a, n] = v("disconnected"), [g, z] = v(""), [N, b] = v([]), [j, L] = v(0), [T, C] = v(!1), [c, I] = v("connecting"), m = $(null);
575
+ M(() => {
577
576
  const l = new ce(
578
577
  e,
579
578
  {
@@ -585,7 +584,7 @@ function He(e, f = {}) {
585
584
  },
586
585
  onCallStart: i,
587
586
  onCallEnd: u,
588
- onDurationUpdate: D,
587
+ onDurationUpdate: L,
589
588
  onHistoryUpdate: b,
590
589
  onRegistered: () => C(!0),
591
590
  onUnregistered: () => C(!1)
@@ -607,7 +606,7 @@ function He(e, f = {}) {
607
606
  e.authorizationUser,
608
607
  h,
609
608
  o
610
- ]), j(() => {
609
+ ]), M(() => {
611
610
  m.current && m.current.setEvents({
612
611
  onCallStart: i,
613
612
  onCallEnd: u,
@@ -623,7 +622,7 @@ function He(e, f = {}) {
623
622
  z(l), m.current?.setCallNumber(l);
624
623
  }, []), E = U((l) => {
625
624
  m.current?.startCall(l);
626
- }, []), M = U(() => {
625
+ }, []), D = U(() => {
627
626
  m.current?.endCall();
628
627
  }, []), S = U(() => {
629
628
  m.current?.clearHistory(), b([]);
@@ -634,9 +633,9 @@ function He(e, f = {}) {
634
633
  setCallNumber: k,
635
634
  callHistory: N,
636
635
  clearCallHistory: S,
637
- currentCallDuration: L,
636
+ currentCallDuration: j,
638
637
  startCall: E,
639
- endCall: M,
638
+ endCall: D,
640
639
  isReady: T,
641
640
  connectionStatus: c,
642
641
  ua: m.current?.ua ?? null
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("vue"),B=require("../index-1EBiLrV_.cjs"),Z={key:0,class:"flex gap-2 items-center"},ee=["placeholder"],te=["disabled","title"],ne={key:0,class:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"},oe={key:1,class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},le={key:1,class:"flex flex-col items-center gap-3 py-6"},ae={class:"text-center"},se={class:"text-base font-semibold"},re={class:"text-sm text-gray-500"},ce={key:2,class:"flex flex-col items-center gap-3 py-6"},ie={class:"text-center"},de={class:"text-sm text-gray-500"},ue={class:"text-base font-semibold"},me={key:0,class:"text-sm text-gray-600"},ve={class:"flex gap-3"},fe={key:3,class:"flex flex-col items-center gap-4 py-6"},ge={class:"text-center space-y-1"},pe={class:"text-xl font-bold"},he={class:"text-2xl font-mono text-green-600 tabular-nums"},ye={key:4,class:"flex flex-col items-center gap-3 py-6"},Ce={key:0,d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"},Ee={key:1,d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"},xe={class:"text-center"},we={class:"text-base font-semibold"},be={key:0,class:"fixed inset-0 z-50 flex"},Se={class:"fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-xl",style:{"background-color":"white"}},ke={class:"flex flex-col h-full"},Ne={class:"flex items-center justify-between p-4 border-b"},Ve={class:"text-lg font-semibold"},_e={class:"text-sm text-gray-500"},Be={class:"flex-1 overflow-y-auto p-4"},De={key:0,class:"text-center py-12 text-gray-500"},ze={key:1,class:"space-y-2"},Me={key:2,d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"},Ie={class:"flex-1 min-w-0"},He={class:"font-medium text-sm truncate"},Ue={class:"flex items-center gap-2 text-xs text-gray-500"},Te={class:"font-mono tabular-nums"},Pe=["onClick"],G=e.defineComponent({__name:"Phone",props:{config:{},className:{default:""},labels:{default:()=>({})},onCallStart:{},onCallEnd:{},onStatusChange:{},onIncomingCall:{}},emits:["callStart","callEnd","statusChange","incomingCall"],setup(E,{emit:T}){const i=E,d=T;let s=null,I=null;function r(l){return`${l.websocketUrl}|${l.sipUri}|${l.authorizationUser}`}function h(l){const t=r(l);if(s&&I===t)return s;if(s&&I!==t){try{s.ua.stop()}catch{}s=null}I=t;const g={sockets:[new B.JsSIP.WebSocketInterface(l.websocketUrl)],uri:l.sipUri,password:l.password,registrar_server:l.registrarServer,display_name:l.displayName,authorization_user:l.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},N=new B.JsSIP.UA(g),L=document.createElement("audio");L.autoplay=!0;const U={ua:N,audio:L,isStarted:!1,listeners:new Set};return N.on("connecting",()=>{U.listeners.forEach(_=>_.onConnecting?.())}),N.on("connected",()=>{U.listeners.forEach(_=>_.onConnected?.())}),N.on("disconnected",()=>{U.listeners.forEach(_=>_.onDisconnected?.())}),N.on("registered",()=>{U.listeners.forEach(_=>_.onRegistered?.())}),N.on("unregistered",()=>{U.listeners.forEach(_=>_.onUnregistered?.())}),N.on("registrationFailed",_=>{U.listeners.forEach(z=>z.onRegistrationFailed?.(_?.cause))}),N.on("newRTCSession",_=>{const z=_.session;if(z.direction==="incoming"){const R=z.remote_identity,j=R?.uri?.user||"Unknown",Y=R?.display_name||void 0;U.listeners.forEach(F=>F.onIncomingSession?.(z,j,Y)),z.on("peerconnection",()=>{z.connection.addEventListener("addstream",F=>{if(!F.streams?.length)return;const K=document.createElement("audio");K.srcObject=F.streams[0],K.play()}),z.connection.addEventListener("track",F=>{const K=document.createElement("audio");K.srcObject=F.streams[0],K.play()})});return}U.listeners.forEach(R=>R.onNewSession?.(z)),z.connection&&(z.connection.addEventListener("addstream",R=>{if(!R.streams?.length)return;const j=document.createElement("audio");j.srcObject=R.streams[0],j.play()}),z.connection.addEventListener("track",R=>{const j=document.createElement("audio");j.srcObject=R.streams[0],j.play()}))}),s=U,U}const n=e.ref("disconnected"),u=e.ref(""),v=e.ref([]),w=e.ref(0),c=e.ref(!1),f=e.ref("connecting"),b=e.ref(!1),o=e.ref(null);let p=null,k=null,C=null,V=null,x=null;const S=e.computed(()=>({...B.defaultLabels,...i.labels})),J=e.computed(()=>{switch(n.value){case"ringing":return{text:S.value.incomingCall,color:"text-blue-500",icon:"ring"};case"progress":return{text:`${S.value.calling}...`,color:"text-yellow-500",icon:"ring"};case"confirmed":return{text:`${S.value.inCall} - ${B.formatDuration(w.value)}`,color:"text-green-500",icon:"inTalk"};case"failed":return{text:S.value.callEnded,color:"text-red-500",icon:"missed"};case"ended":return{text:S.value.callEnded,color:"text-gray-500",icon:"hangup"};default:return{text:S.value.inactive,color:"text-gray-300",icon:"phone"}}});function H(l,t,a){const g={id:Date.now().toString(),number:l,timestamp:Date.now(),duration:t,status:a};v.value=[g,...v.value].slice(0,50),localStorage.setItem("tbi-phone-call-history",JSON.stringify(v.value))}function y(){k&&(k.terminate(),k=null),o.value=null}function D(){if(!o.value)return;const{session:l,callerNumber:t}=o.value,a={mediaConstraints:{audio:!0,video:!1}};try{l.answer(a),k=l,i.onCallStart?.(t),d("callStart",t)}catch(g){console.error("Failed to answer call:",g),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(t,0,"missed"),o.value=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}}function M(){if(!o.value)return;const{session:l,callerNumber:t}=o.value;try{l.terminate({status_code:603,reason_phrase:"Decline"})}catch(a){console.error("Failed to reject call:",a)}H(t,0,"missed"),o.value=null,n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")}function m(l){if(!l.trim()||!p)return;if(!c.value){console.warn("Phone is not ready yet. Please wait for registration.");return}u.value=l,i.onCallStart?.(l),d("callStart",l);const a={eventHandlers:{progress:()=>{n.value="progress",i.onStatusChange?.("progress"),d("statusChange","progress")},failed:g=>{console.error("Call failed:",g?.cause),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(l,0,"failed"),i.onCallEnd?.(l,0,"failed"),d("callEnd",l,0,"failed"),k=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)},ended:()=>{n.value="ended",i.onStatusChange?.("ended"),d("statusChange","ended");const g=C?Math.floor((Date.now()-C)/1e3):0;H(l,g,"completed"),i.onCallEnd?.(l,g,"completed"),d("callEnd",l,g,"completed"),k=null,V&&(clearInterval(V),V=null),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected"),C=null,w.value=0},2e3)},confirmed:()=>{n.value="confirmed",i.onStatusChange?.("confirmed"),d("statusChange","confirmed"),C=Date.now(),V=setInterval(()=>{C&&(w.value=Math.floor((Date.now()-C)/1e3))},1e3)}},mediaConstraints:{audio:!0,video:!1}};n.value="progress",i.onStatusChange?.("progress"),d("statusChange","progress");try{k=p.ua.call(l,a)}catch(g){console.error("Failed to start call:",g),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(l,0,"failed"),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}}function P(l){l.key==="Enter"&&m(u.value)}function O(l){u.value=l.number,b.value=!1,m(l.number)}function $(l){switch(l){case"completed":return"bg-green-100";case"failed":return"bg-red-100";case"missed":return"bg-yellow-100"}}function Q(l){switch(l){case"completed":return"text-green-600";case"failed":return"text-red-600";case"missed":return"text-yellow-600"}}function X(l){return new Date(l).toLocaleString("es-ES",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}return e.onMounted(()=>{p=h(i.config),p.ua.isRegistered()?(c.value=!0,f.value="connected"):p.ua.isConnected()&&(f.value="connected"),x={onConnecting:()=>{f.value="connecting"},onConnected:()=>{f.value="connected"},onDisconnected:()=>{f.value="disconnected",c.value=!1},onRegistered:()=>{c.value=!0,f.value="connected"},onUnregistered:()=>{c.value=!1},onRegistrationFailed:a=>{console.error("Registration failed:",a),c.value=!1,f.value="failed"},onNewSession:a=>{k=a},onIncomingSession:(a,g,N)=>{if(k){a.terminate({status_code:486,reason_phrase:"Busy Here"});return}o.value={session:a,callerNumber:g,callerName:N},u.value=g,n.value="ringing",i.onStatusChange?.("ringing"),d("statusChange","ringing"),i.onIncomingCall?.(g,N),d("incomingCall",g,N),a.on("failed",L=>{console.error("Incoming call failed:",L?.cause),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(g,0,"missed"),o.value=null,k=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}),a.on("ended",()=>{n.value="ended",i.onStatusChange?.("ended"),d("statusChange","ended");const L=C?Math.floor((Date.now()-C)/1e3):0;H(g,L,"completed"),i.onCallEnd?.(g,L,"completed"),d("callEnd",g,L,"completed"),o.value=null,k=null,V&&(clearInterval(V),V=null),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected"),C=null,w.value=0},2e3)}),a.on("confirmed",()=>{n.value="confirmed",i.onStatusChange?.("confirmed"),d("statusChange","confirmed"),C=Date.now(),o.value=null,V=setInterval(()=>{C&&(w.value=Math.floor((Date.now()-C)/1e3))},1e3)})}},p.listeners.add(x),p.isStarted||(p.ua.start(),p.isStarted=!0);const l=localStorage.getItem("tbi-phone-call-history");if(l)try{v.value=JSON.parse(l)}catch(a){console.error("Error loading call history",a)}const t=a=>{const N=a.detail.number;n.value==="disconnected"&&m(N)};window.addEventListener("StartCallEvent",t)}),e.onUnmounted(()=>{V&&clearInterval(V),p&&x&&p.listeners.delete(x)}),(l,t)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(e.unref(B.cn)("tbi-phone w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg border border-gray-200 p-2",E.className))},[n.value==="disconnected"?(e.openBlock(),e.createElementBlock("div",Z,[e.createElementVNode("button",{onClick:t[0]||(t[0]=a=>b.value=!0),class:"h-8 w-8 flex items-center justify-center rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors",type:"button"},[...t[5]||(t[5]=[e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"})],-1)])]),e.withDirectives(e.createElementVNode("input",{type:"text","onUpdate:modelValue":t[1]||(t[1]=a=>u.value=a),onKeydown:P,placeholder:S.value.placeholder,class:"flex-1 w-full h-8 px-3 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"},null,40,ee),[[e.vModelText,u.value]]),e.createElementVNode("button",{onClick:t[2]||(t[2]=a=>m(u.value)),disabled:u.value.length<9||!c.value,class:"h-8 w-8 flex items-center justify-center rounded-xl bg-green-500 hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white transition-colors",type:"button",title:c.value?"Call":"Connecting..."},[f.value==="connecting"?(e.openBlock(),e.createElementBlock("div",ne)):(e.openBlock(),e.createElementBlock("svg",oe,[...t[6]||(t[6]=[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)])]))],8,te)])):e.createCommentVNode("",!0),n.value==="progress"?(e.openBlock(),e.createElementBlock("div",le,[t[8]||(t[8]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-yellow-500 animate-pulse",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full border-4 border-yellow-500/30 animate-ping"})],-1)),e.createElementVNode("div",ae,[e.createElementVNode("p",se,e.toDisplayString(S.value.calling)+" "+e.toDisplayString(u.value),1),e.createElementVNode("p",re,e.toDisplayString(S.value.waitingResponse),1)]),e.createElementVNode("button",{onClick:y,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[7]||(t[7]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.cancel),1)])])):e.createCommentVNode("",!0),n.value==="ringing"&&o.value?(e.openBlock(),e.createElementBlock("div",ce,[t[11]||(t[11]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-blue-500 animate-bounce",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full border-4 border-blue-500/30 animate-ping"})],-1)),e.createElementVNode("div",ie,[e.createElementVNode("p",de,e.toDisplayString(S.value.incomingCall),1),e.createElementVNode("p",ue,e.toDisplayString(o.value.callerNumber),1),o.value.callerName?(e.openBlock(),e.createElementBlock("p",me,e.toDisplayString(o.value.callerName),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",ve,[e.createElementVNode("button",{onClick:M,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[9]||(t[9]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.reject),1)]),e.createElementVNode("button",{onClick:D,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-green-500 hover:bg-green-600 text-white text-sm font-medium transition-colors",type:"button"},[t[10]||(t[10]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.answer),1)])])])):e.createCommentVNode("",!0),n.value==="confirmed"?(e.openBlock(),e.createElementBlock("div",fe,[t[13]||(t[13]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-green-500",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.12-.74-.03-1.02.24l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full bg-green-500/20 animate-pulse"})],-1)),e.createElementVNode("div",ge,[e.createElementVNode("p",pe,e.toDisplayString(u.value),1),e.createElementVNode("p",he,e.toDisplayString(e.unref(B.formatDuration)(w.value)),1)]),e.createElementVNode("button",{onClick:y,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[12]||(t[12]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.hangUp),1)])])):e.createCommentVNode("",!0),n.value==="failed"||n.value==="ended"?(e.openBlock(),e.createElementBlock("div",ye,[(e.openBlock(),e.createElementBlock("svg",{class:e.normalizeClass(e.unref(B.cn)("w-12 h-12",n.value==="failed"?"text-red-500":"text-gray-500")),viewBox:"0 0 24 24",fill:"currentColor"},[n.value==="failed"?(e.openBlock(),e.createElementBlock("path",Ce)):(e.openBlock(),e.createElementBlock("path",Ee))],2)),e.createElementVNode("div",xe,[e.createElementVNode("p",we,e.toDisplayString(J.value.text),1)])])):e.createCommentVNode("",!0),(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[b.value?(e.openBlock(),e.createElementBlock("div",be,[e.createElementVNode("div",{class:"fixed inset-0 bg-black/50",onClick:t[3]||(t[3]=a=>b.value=!1)}),e.createElementVNode("div",Se,[e.createElementVNode("div",ke,[e.createElementVNode("div",Ne,[e.createElementVNode("div",null,[e.createElementVNode("h2",Ve,e.toDisplayString(S.value.callHistory),1),e.createElementVNode("p",_e,e.toDisplayString(v.value.length===0?S.value.noCallsRegistered:`${v.value.length} ${S.value.callsRegistered}`),1)]),e.createElementVNode("button",{onClick:t[4]||(t[4]=a=>b.value=!1),class:"h-8 w-8 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors",type:"button"},[...t[14]||(t[14]=[e.createElementVNode("svg",{class:"w-5 h-5",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})],-1)])])]),e.createElementVNode("div",Be,[v.value.length===0?(e.openBlock(),e.createElementBlock("div",De,[t[15]||(t[15]=e.createElementVNode("svg",{class:"w-12 h-12 mx-auto mb-2 opacity-50",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createElementVNode("p",null,e.toDisplayString(S.value.noCalls),1)])):(e.openBlock(),e.createElementBlock("div",ze,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,(a,g)=>(e.openBlock(),e.createElementBlock("div",{key:a.id,class:"flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors duration-200",style:e.normalizeStyle({animationDelay:`${g*30}ms`})},[e.createElementVNode("div",{class:e.normalizeClass(e.unref(B.cn)("w-9 h-9 rounded-full flex items-center justify-center shrink-0",$(a.status)))},[(e.openBlock(),e.createElementBlock("svg",{class:e.normalizeClass(e.unref(B.cn)("w-4 h-4",Q(a.status))),viewBox:"0 0 24 24",fill:"currentColor"},[a.status==="completed"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[t[16]||(t[16]=e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)),t[17]||(t[17]=e.createElementVNode("path",{d:"M16 3l-5 5-2-2-1.5 1.5L11 11l6.5-6.5z"},null,-1))],64)):a.status==="failed"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[t[18]||(t[18]=e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)),t[19]||(t[19]=e.createElementVNode("path",{d:"M19 6.41L17.59 5 15 7.59 12.41 5 11 6.41 13.59 9 11 11.59 12.41 13 15 10.41 17.59 13 19 11.59 16.41 9z"},null,-1))],64)):(e.openBlock(),e.createElementBlock("path",Me))],2))],2),e.createElementVNode("div",Ie,[e.createElementVNode("p",He,e.toDisplayString(a.number),1),e.createElementVNode("div",Ue,[e.createElementVNode("span",null,e.toDisplayString(X(a.timestamp)),1),a.duration>0?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[t[20]||(t[20]=e.createElementVNode("span",null,"•",-1)),e.createElementVNode("span",Te,e.toDisplayString(e.unref(B.formatDuration)(a.duration)),1)],64)):e.createCommentVNode("",!0)])]),e.createElementVNode("button",{onClick:N=>O(a),class:"h-8 w-8 flex items-center justify-center shrink-0 rounded-lg hover:bg-gray-100 transition-colors",type:"button"},[...t[21]||(t[21]=[e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})],-1)])],8,Pe)],4))),128))]))])])])])):e.createCommentVNode("",!0)]))],2))}}),W=Symbol("Phone");let A=null,q=null;function Re(E){return`${E.websocketUrl}|${E.sipUri}|${E.authorizationUser}`}function Le(E){const T=Re(E);if(A&&q===T)return A;if(A&&q!==T){try{A.ua.stop()}catch{}A=null}q=T;const d={sockets:[new B.JsSIP.WebSocketInterface(E.websocketUrl)],uri:E.sipUri,password:E.password,registrar_server:E.registrarServer,display_name:E.displayName,authorization_user:E.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},s=new B.JsSIP.UA(d),I=document.createElement("audio");I.autoplay=!0;const r={ua:s,audio:I,isStarted:!1,listeners:new Set};return s.on("connecting",()=>{r.listeners.forEach(h=>h.onConnecting?.())}),s.on("connected",()=>{r.listeners.forEach(h=>h.onConnected?.())}),s.on("disconnected",()=>{r.listeners.forEach(h=>h.onDisconnected?.())}),s.on("registered",()=>{r.listeners.forEach(h=>h.onRegistered?.())}),s.on("unregistered",()=>{r.listeners.forEach(h=>h.onUnregistered?.())}),s.on("registrationFailed",h=>{r.listeners.forEach(n=>n.onRegistrationFailed?.(h?.cause))}),s.on("newRTCSession",h=>{const n=h.session;if(n.direction==="incoming"){const u=n.remote_identity,v=u?.uri?.user||"Unknown",w=u?.display_name||void 0;r.listeners.forEach(c=>c.onIncomingSession?.(n,v,w)),n.on("peerconnection",()=>{n.connection.addEventListener("addstream",c=>{if(!c.streams?.length)return;const f=document.createElement("audio");f.srcObject=c.streams[0],f.play()}),n.connection.addEventListener("track",c=>{const f=document.createElement("audio");f.srcObject=c.streams[0],f.play()})});return}r.listeners.forEach(u=>u.onNewSession?.(n)),n.connection&&(n.connection.addEventListener("addstream",u=>{if(!u.streams?.length)return;const v=document.createElement("audio");v.srcObject=u.streams[0],v.play()}),n.connection.addEventListener("track",u=>{const v=document.createElement("audio");v.srcObject=u.streams[0],v.play()}))}),A=r,r}function je(E){const{config:T,onCallStart:i,onCallEnd:d,onStatusChange:s,onIncomingCall:I}=E,r=e.ref("disconnected"),h=e.ref(""),n=e.ref([]),u=e.ref(0),v=e.ref(!1),w=e.ref("connecting"),c=e.ref(null);let f=null,b=null,o=null,p=null;const k=y=>{h.value=y},C=(y,D,M)=>{const m={id:Date.now().toString(),number:y,timestamp:Date.now(),duration:D,status:M};n.value=[m,...n.value].slice(0,50),localStorage.setItem("tbi-phone-call-history",JSON.stringify(n.value))},V=()=>{b&&(b.terminate(),b=null),c.value=null},x=()=>{if(!c.value)return;const{session:y,callerNumber:D}=c.value,M={mediaConstraints:{audio:!0,video:!1}};try{y.answer(M),b=y,i?.(D)}catch(m){console.error("Failed to answer call:",m),r.value="failed",s?.("failed"),C(D,0,"missed"),c.value=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}},S=()=>{if(!c.value)return;const{session:y,callerNumber:D}=c.value;try{y.terminate({status_code:603,reason_phrase:"Decline"})}catch(M){console.error("Failed to reject call:",M)}C(D,0,"missed"),c.value=null,r.value="disconnected",s?.("disconnected")},J=y=>{if(!y.trim()||!f)return;if(!v.value){console.warn("Phone is not ready yet. Please wait for registration.");return}h.value=y,i?.(y);const M={eventHandlers:{progress:()=>{r.value="progress",s?.("progress")},failed:m=>{console.error("Call failed:",m?.cause),r.value="failed",s?.("failed"),C(y,0,"failed"),d?.(y,0,"failed"),b=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)},ended:()=>{r.value="ended",s?.("ended");const m=o?Math.floor((Date.now()-o)/1e3):0;C(y,m,"completed"),d?.(y,m,"completed"),b=null,p&&(clearInterval(p),p=null),setTimeout(()=>{r.value="disconnected",s?.("disconnected"),o=null,u.value=0},2e3)},confirmed:()=>{r.value="confirmed",s?.("confirmed"),o=Date.now(),p=setInterval(()=>{o&&(u.value=Math.floor((Date.now()-o)/1e3))},1e3)}},mediaConstraints:{audio:!0,video:!1}};r.value="progress",s?.("progress");try{b=f.ua.call(y,M)}catch(m){console.error("Failed to start call:",m),r.value="failed",s?.("failed"),C(y,0,"failed"),setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}};e.onMounted(()=>{f=Le(T),f.ua.isRegistered()?(v.value=!0,w.value="connected"):f.ua.isConnected()&&(w.value="connected");const y={onConnecting:()=>{w.value="connecting"},onConnected:()=>{w.value="connected"},onDisconnected:()=>{w.value="disconnected",v.value=!1},onRegistered:()=>{v.value=!0,w.value="connected"},onUnregistered:()=>{v.value=!1},onRegistrationFailed:m=>{console.error("Registration failed:",m),v.value=!1,w.value="failed"},onNewSession:m=>{b=m},onIncomingSession:(m,P,O)=>{if(b){m.terminate({status_code:486,reason_phrase:"Busy Here"});return}c.value={session:m,callerNumber:P,callerName:O},h.value=P,r.value="ringing",s?.("ringing"),I?.(P,O),m.on("failed",$=>{console.error("Incoming call failed:",$?.cause),r.value="failed",s?.("failed"),C(P,0,"missed"),c.value=null,b=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}),m.on("ended",()=>{r.value="ended",s?.("ended");const $=o?Math.floor((Date.now()-o)/1e3):0;C(P,$,"completed"),d?.(P,$,"completed"),c.value=null,b=null,p&&(clearInterval(p),p=null),setTimeout(()=>{r.value="disconnected",s?.("disconnected"),o=null,u.value=0},2e3)}),m.on("confirmed",()=>{r.value="confirmed",s?.("confirmed"),o=Date.now(),c.value=null,p=setInterval(()=>{o&&(u.value=Math.floor((Date.now()-o)/1e3))},1e3)})}};f.listeners.add(y),f.isStarted||(f.ua.start(),f.isStarted=!0);const D=localStorage.getItem("tbi-phone-call-history");if(D)try{n.value=JSON.parse(D)}catch(m){console.error("Error loading call history",m)}const M=m=>{const O=m.detail.number;r.value==="disconnected"&&J(O)};window.addEventListener("StartCallEvent",M)}),e.onUnmounted(()=>{p&&clearInterval(p)});const H={status:e.readonly(r),callNumber:h,setCallNumber:k,callHistory:e.readonly(n),currentCallDuration:e.readonly(u),startCall:J,endCall:V,answerCall:x,rejectCall:S,isReady:e.readonly(v),connectionStatus:e.readonly(w),incomingCall:e.readonly(c)};return e.provide(W,H),H}function Oe(){const E=e.inject(W);if(!E)throw new Error("usePhone must be used within a component that has called usePhoneProvider");return E}function $e(E,T={}){const{onCallStart:i,onCallEnd:d,onStatusChange:s,onConnectionChange:I,persistHistory:r=!0,historyKey:h="tbi-phone-call-history"}=T,n=e.ref("disconnected"),u=e.ref(""),v=e.ref([]),w=e.ref(0),c=e.ref(!1),f=e.ref("connecting"),b=e.ref(null);let o=null;e.onMounted(()=>{o=new B.PhoneManager(E,{onStatusChange:x=>{n.value=x,s?.(x)},onConnectionChange:x=>{f.value=x,o&&(c.value=o.state.isReady),I?.(x)},onCallStart:i,onCallEnd:d,onDurationUpdate:x=>{w.value=x},onHistoryUpdate:x=>{v.value=x},onRegistered:()=>{c.value=!0},onUnregistered:()=>{c.value=!1}},{persistHistory:r,historyKey:h}),o.initialize(),n.value=o.state.status,u.value=o.state.callNumber,v.value=o.state.callHistory,c.value=o.state.isReady,f.value=o.state.connectionStatus,b.value=o.ua}),e.onUnmounted(()=>{o&&(o.destroy(),o=null)});const p=x=>{u.value=x,o?.setCallNumber(x)},k=x=>{o?.startCall(x)},C=()=>{o?.endCall()},V=()=>{o?.clearHistory(),v.value=[]};return{status:e.readonly(n),callNumber:u,setCallNumber:p,callHistory:e.readonly(v),clearCallHistory:V,currentCallDuration:e.readonly(w),startCall:k,endCall:C,isReady:e.readonly(c),connectionStatus:e.readonly(f),ua:b}}exports.Phone=G;exports.PhoneKey=W;exports.default=G;exports.usePhone=Oe;exports.usePhoneManager=$e;exports.usePhoneProvider=je;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const e=require("vue"),B=require("../index-BofRGPCe.cjs"),Z={key:0,class:"flex gap-2 items-center"},ee=["placeholder"],te=["disabled","title"],ne={key:0,class:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"},oe={key:1,class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},le={key:1,class:"flex flex-col items-center gap-3 py-6"},ae={class:"text-center"},se={class:"text-base font-semibold"},re={class:"text-sm text-gray-500"},ce={key:2,class:"flex flex-col items-center gap-3 py-6"},ie={class:"text-center"},de={class:"text-sm text-gray-500"},ue={class:"text-base font-semibold"},me={key:0,class:"text-sm text-gray-600"},ve={class:"flex gap-3"},fe={key:3,class:"flex flex-col items-center gap-4 py-6"},ge={class:"text-center space-y-1"},pe={class:"text-xl font-bold"},he={class:"text-2xl font-mono text-green-600 tabular-nums"},ye={key:4,class:"flex flex-col items-center gap-3 py-6"},Ce={key:0,d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"},Ee={key:1,d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"},xe={class:"text-center"},we={class:"text-base font-semibold"},be={key:0,class:"fixed inset-0 z-50 flex"},Se={class:"fixed right-0 top-0 h-full w-full max-w-md bg-white shadow-xl",style:{"background-color":"white"}},ke={class:"flex flex-col h-full"},Ne={class:"flex items-center justify-between p-4 border-b"},Ve={class:"text-lg font-semibold"},_e={class:"text-sm text-gray-500"},Be={class:"flex-1 overflow-y-auto p-4"},De={key:0,class:"text-center py-12 text-gray-500"},ze={key:1,class:"space-y-2"},Me={key:2,d:"M6.5 5.5 12 11l7-7-1-1-6 6-4.5-4.5H11V3H5v6h1.5V5.5zm17.21 11.17C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71s.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73 1.6 0 3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.67 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71s-.12-.52-.3-.7z"},Ie={class:"flex-1 min-w-0"},He={class:"font-medium text-sm truncate"},Ue={class:"flex items-center gap-2 text-xs text-gray-500"},Te={class:"font-mono tabular-nums"},Pe=["onClick"],G=e.defineComponent({__name:"Phone",props:{config:{},className:{default:""},labels:{default:()=>({})},onCallStart:{},onCallEnd:{},onStatusChange:{},onIncomingCall:{}},emits:["callStart","callEnd","statusChange","incomingCall"],setup(E,{emit:T}){const i=E,d=T;let s=null,I=null;function r(l){return`${l.websocketUrl}|${l.sipUri}|${l.authorizationUser}`}function h(l){const t=r(l);if(s&&I===t)return s;if(s&&I!==t){try{s.ua.stop()}catch{}s=null}I=t;const g={sockets:[new B.JsSIP.WebSocketInterface(l.websocketUrl)],uri:l.sipUri,password:l.password,registrar_server:l.registrarServer,display_name:l.displayName,authorization_user:l.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},N=new B.JsSIP.UA(g),L=document.createElement("audio");L.autoplay=!0;const U={ua:N,audio:L,isStarted:!1,listeners:new Set};return N.on("connecting",()=>{U.listeners.forEach(_=>_.onConnecting?.())}),N.on("connected",()=>{U.listeners.forEach(_=>_.onConnected?.())}),N.on("disconnected",()=>{U.listeners.forEach(_=>_.onDisconnected?.())}),N.on("registered",()=>{U.listeners.forEach(_=>_.onRegistered?.())}),N.on("unregistered",()=>{U.listeners.forEach(_=>_.onUnregistered?.())}),N.on("registrationFailed",_=>{U.listeners.forEach(z=>z.onRegistrationFailed?.(_?.cause))}),N.on("newRTCSession",_=>{const z=_.session;if(z.direction==="incoming"){const R=z.remote_identity,j=R?.uri?.user||"Unknown",Y=R?.display_name||void 0;U.listeners.forEach(F=>F.onIncomingSession?.(z,j,Y)),z.on("peerconnection",()=>{z.connection.addEventListener("addstream",F=>{if(!F.streams?.length)return;const K=document.createElement("audio");K.srcObject=F.streams[0],K.play()}),z.connection.addEventListener("track",F=>{const K=document.createElement("audio");K.srcObject=F.streams[0],K.play()})});return}U.listeners.forEach(R=>R.onNewSession?.(z)),z.connection&&(z.connection.addEventListener("addstream",R=>{if(!R.streams?.length)return;const j=document.createElement("audio");j.srcObject=R.streams[0],j.play()}),z.connection.addEventListener("track",R=>{const j=document.createElement("audio");j.srcObject=R.streams[0],j.play()}))}),s=U,U}const n=e.ref("disconnected"),u=e.ref(""),v=e.ref([]),w=e.ref(0),c=e.ref(!1),f=e.ref("connecting"),b=e.ref(!1),o=e.ref(null);let p=null,k=null,C=null,V=null,x=null;const S=e.computed(()=>({...B.defaultLabels,...i.labels})),J=e.computed(()=>{switch(n.value){case"ringing":return{text:S.value.incomingCall,color:"text-blue-500",icon:"ring"};case"progress":return{text:`${S.value.calling}...`,color:"text-yellow-500",icon:"ring"};case"confirmed":return{text:`${S.value.inCall} - ${B.formatDuration(w.value)}`,color:"text-green-500",icon:"inTalk"};case"failed":return{text:S.value.callEnded,color:"text-red-500",icon:"missed"};case"ended":return{text:S.value.callEnded,color:"text-gray-500",icon:"hangup"};default:return{text:S.value.inactive,color:"text-gray-300",icon:"phone"}}});function H(l,t,a){const g={id:Date.now().toString(),number:l,timestamp:Date.now(),duration:t,status:a};v.value=[g,...v.value].slice(0,50),localStorage.setItem("tbi-phone-call-history",JSON.stringify(v.value))}function y(){k&&(k.terminate(),k=null),o.value=null}function D(){if(!o.value)return;const{session:l,callerNumber:t}=o.value,a={mediaConstraints:{audio:!0,video:!1}};try{l.answer(a),k=l,i.onCallStart?.(t),d("callStart",t)}catch(g){console.error("Failed to answer call:",g),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(t,0,"missed"),o.value=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}}function M(){if(!o.value)return;const{session:l,callerNumber:t}=o.value;try{l.terminate({status_code:603,reason_phrase:"Decline"})}catch(a){console.error("Failed to reject call:",a)}H(t,0,"missed"),o.value=null,n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")}function m(l){if(!l.trim()||!p)return;if(!c.value){console.warn("Phone is not ready yet. Please wait for registration.");return}u.value=l,i.onCallStart?.(l),d("callStart",l);const a={eventHandlers:{progress:()=>{n.value="progress",i.onStatusChange?.("progress"),d("statusChange","progress")},failed:g=>{console.error("Call failed:",g?.cause),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(l,0,"failed"),i.onCallEnd?.(l,0,"failed"),d("callEnd",l,0,"failed"),k=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)},ended:()=>{n.value="ended",i.onStatusChange?.("ended"),d("statusChange","ended");const g=C?Math.floor((Date.now()-C)/1e3):0;H(l,g,"completed"),i.onCallEnd?.(l,g,"completed"),d("callEnd",l,g,"completed"),k=null,V&&(clearInterval(V),V=null),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected"),C=null,w.value=0},2e3)},confirmed:()=>{n.value="confirmed",i.onStatusChange?.("confirmed"),d("statusChange","confirmed"),C=Date.now(),V=setInterval(()=>{C&&(w.value=Math.floor((Date.now()-C)/1e3))},1e3)}},mediaConstraints:{audio:!0,video:!1}};n.value="progress",i.onStatusChange?.("progress"),d("statusChange","progress");try{k=p.ua.call(l,a)}catch(g){console.error("Failed to start call:",g),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(l,0,"failed"),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}}function P(l){l.key==="Enter"&&m(u.value)}function O(l){u.value=l.number,b.value=!1,m(l.number)}function $(l){switch(l){case"completed":return"bg-green-100";case"failed":return"bg-red-100";case"missed":return"bg-yellow-100"}}function Q(l){switch(l){case"completed":return"text-green-600";case"failed":return"text-red-600";case"missed":return"text-yellow-600"}}function X(l){return new Date(l).toLocaleString("es-ES",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}return e.onMounted(()=>{p=h(i.config),p.ua.isRegistered()?(c.value=!0,f.value="connected"):p.ua.isConnected()&&(f.value="connected"),x={onConnecting:()=>{f.value="connecting"},onConnected:()=>{f.value="connected"},onDisconnected:()=>{f.value="disconnected",c.value=!1},onRegistered:()=>{c.value=!0,f.value="connected"},onUnregistered:()=>{c.value=!1},onRegistrationFailed:a=>{console.error("Registration failed:",a),c.value=!1,f.value="failed"},onNewSession:a=>{k=a},onIncomingSession:(a,g,N)=>{if(k){a.terminate({status_code:486,reason_phrase:"Busy Here"});return}o.value={session:a,callerNumber:g,callerName:N},u.value=g,n.value="ringing",i.onStatusChange?.("ringing"),d("statusChange","ringing"),i.onIncomingCall?.(g,N),d("incomingCall",g,N),a.on("failed",L=>{console.error("Incoming call failed:",L?.cause),n.value="failed",i.onStatusChange?.("failed"),d("statusChange","failed"),H(g,0,"missed"),o.value=null,k=null,setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected")},3e3)}),a.on("ended",()=>{n.value="ended",i.onStatusChange?.("ended"),d("statusChange","ended");const L=C?Math.floor((Date.now()-C)/1e3):0;H(g,L,"completed"),i.onCallEnd?.(g,L,"completed"),d("callEnd",g,L,"completed"),o.value=null,k=null,V&&(clearInterval(V),V=null),setTimeout(()=>{n.value="disconnected",i.onStatusChange?.("disconnected"),d("statusChange","disconnected"),C=null,w.value=0},2e3)}),a.on("confirmed",()=>{n.value="confirmed",i.onStatusChange?.("confirmed"),d("statusChange","confirmed"),C=Date.now(),o.value=null,V=setInterval(()=>{C&&(w.value=Math.floor((Date.now()-C)/1e3))},1e3)})}},p.listeners.add(x),p.isStarted||(p.ua.start(),p.isStarted=!0);const l=localStorage.getItem("tbi-phone-call-history");if(l)try{v.value=JSON.parse(l)}catch(a){console.error("Error loading call history",a)}const t=a=>{const N=a.detail.number;n.value==="disconnected"&&m(N)};window.addEventListener("StartCallEvent",t)}),e.onUnmounted(()=>{V&&clearInterval(V),p&&x&&p.listeners.delete(x)}),(l,t)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(e.unref(B.cn)("tbi-phone w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg border border-gray-200 p-2",E.className))},[n.value==="disconnected"?(e.openBlock(),e.createElementBlock("div",Z,[e.createElementVNode("button",{onClick:t[0]||(t[0]=a=>b.value=!0),class:"h-8 w-8 flex items-center justify-center rounded-xl border border-gray-200 hover:bg-gray-50 transition-colors",type:"button"},[...t[5]||(t[5]=[e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"})],-1)])]),e.withDirectives(e.createElementVNode("input",{type:"text","onUpdate:modelValue":t[1]||(t[1]=a=>u.value=a),onKeydown:P,placeholder:S.value.placeholder,class:"flex-1 w-full h-8 px-3 rounded-xl border border-gray-200 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent"},null,40,ee),[[e.vModelText,u.value]]),e.createElementVNode("button",{onClick:t[2]||(t[2]=a=>m(u.value)),disabled:u.value.length<9||!c.value,class:"h-8 w-8 flex items-center justify-center rounded-xl bg-green-500 hover:bg-green-600 disabled:bg-gray-300 disabled:cursor-not-allowed text-white transition-colors",type:"button",title:c.value?"Call":"Connecting..."},[f.value==="connecting"?(e.openBlock(),e.createElementBlock("div",ne)):(e.openBlock(),e.createElementBlock("svg",oe,[...t[6]||(t[6]=[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)])]))],8,te)])):e.createCommentVNode("",!0),n.value==="progress"?(e.openBlock(),e.createElementBlock("div",le,[t[8]||(t[8]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-yellow-500 animate-pulse",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full border-4 border-yellow-500/30 animate-ping"})],-1)),e.createElementVNode("div",ae,[e.createElementVNode("p",se,e.toDisplayString(S.value.calling)+" "+e.toDisplayString(u.value),1),e.createElementVNode("p",re,e.toDisplayString(S.value.waitingResponse),1)]),e.createElementVNode("button",{onClick:y,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[7]||(t[7]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.cancel),1)])])):e.createCommentVNode("",!0),n.value==="ringing"&&o.value?(e.openBlock(),e.createElementBlock("div",ce,[t[11]||(t[11]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-blue-500 animate-bounce",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M15.05 5A7 7 0 0 1 19 8.95M15.05 1A11 11 0 0 1 23 8.94m-1 7.98v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full border-4 border-blue-500/30 animate-ping"})],-1)),e.createElementVNode("div",ie,[e.createElementVNode("p",de,e.toDisplayString(S.value.incomingCall),1),e.createElementVNode("p",ue,e.toDisplayString(o.value.callerNumber),1),o.value.callerName?(e.openBlock(),e.createElementBlock("p",me,e.toDisplayString(o.value.callerName),1)):e.createCommentVNode("",!0)]),e.createElementVNode("div",ve,[e.createElementVNode("button",{onClick:M,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[9]||(t[9]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.reject),1)]),e.createElementVNode("button",{onClick:D,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-green-500 hover:bg-green-600 text-white text-sm font-medium transition-colors",type:"button"},[t[10]||(t[10]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.answer),1)])])])):e.createCommentVNode("",!0),n.value==="confirmed"?(e.openBlock(),e.createElementBlock("div",fe,[t[13]||(t[13]=e.createElementVNode("div",{class:"relative"},[e.createElementVNode("svg",{class:"w-12 h-12 text-green-500",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.12-.74-.03-1.02.24l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"})]),e.createElementVNode("div",{class:"absolute inset-0 rounded-full bg-green-500/20 animate-pulse"})],-1)),e.createElementVNode("div",ge,[e.createElementVNode("p",pe,e.toDisplayString(u.value),1),e.createElementVNode("p",he,e.toDisplayString(e.unref(B.formatDuration)(w.value)),1)]),e.createElementVNode("button",{onClick:y,class:"flex items-center gap-2 px-6 py-2 rounded-full bg-red-500 hover:bg-red-600 text-white text-sm font-medium transition-colors",type:"button"},[t[12]||(t[12]=e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createTextVNode(" "+e.toDisplayString(S.value.hangUp),1)])])):e.createCommentVNode("",!0),n.value==="failed"||n.value==="ended"?(e.openBlock(),e.createElementBlock("div",ye,[(e.openBlock(),e.createElementBlock("svg",{class:e.normalizeClass(e.unref(B.cn)("w-12 h-12",n.value==="failed"?"text-red-500":"text-gray-500")),viewBox:"0 0 24 24",fill:"currentColor"},[n.value==="failed"?(e.openBlock(),e.createElementBlock("path",Ce)):(e.openBlock(),e.createElementBlock("path",Ee))],2)),e.createElementVNode("div",xe,[e.createElementVNode("p",we,e.toDisplayString(J.value.text),1)])])):e.createCommentVNode("",!0),(e.openBlock(),e.createBlock(e.Teleport,{to:"body"},[b.value?(e.openBlock(),e.createElementBlock("div",be,[e.createElementVNode("div",{class:"fixed inset-0 bg-black/50",onClick:t[3]||(t[3]=a=>b.value=!1)}),e.createElementVNode("div",Se,[e.createElementVNode("div",ke,[e.createElementVNode("div",Ne,[e.createElementVNode("div",null,[e.createElementVNode("h2",Ve,e.toDisplayString(S.value.callHistory),1),e.createElementVNode("p",_e,e.toDisplayString(v.value.length===0?S.value.noCallsRegistered:`${v.value.length} ${S.value.callsRegistered}`),1)]),e.createElementVNode("button",{onClick:t[4]||(t[4]=a=>b.value=!1),class:"h-8 w-8 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors",type:"button"},[...t[14]||(t[14]=[e.createElementVNode("svg",{class:"w-5 h-5",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})],-1)])])]),e.createElementVNode("div",Be,[v.value.length===0?(e.openBlock(),e.createElementBlock("div",De,[t[15]||(t[15]=e.createElementVNode("svg",{class:"w-12 h-12 mx-auto mb-2 opacity-50",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08a.956.956 0 0 1-.29-.7c0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28a11.27 11.27 0 0 0-2.67-1.85.996.996 0 0 1-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"})],-1)),e.createElementVNode("p",null,e.toDisplayString(S.value.noCalls),1)])):(e.openBlock(),e.createElementBlock("div",ze,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(v.value,(a,g)=>(e.openBlock(),e.createElementBlock("div",{key:a.id,class:"flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors duration-200",style:e.normalizeStyle({animationDelay:`${g*30}ms`})},[e.createElementVNode("div",{class:e.normalizeClass(e.unref(B.cn)("w-9 h-9 rounded-full flex items-center justify-center shrink-0",$(a.status)))},[(e.openBlock(),e.createElementBlock("svg",{class:e.normalizeClass(e.unref(B.cn)("w-4 h-4",Q(a.status))),viewBox:"0 0 24 24",fill:"currentColor"},[a.status==="completed"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[t[16]||(t[16]=e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)),t[17]||(t[17]=e.createElementVNode("path",{d:"M16 3l-5 5-2-2-1.5 1.5L11 11l6.5-6.5z"},null,-1))],64)):a.status==="failed"?(e.openBlock(),e.createElementBlock(e.Fragment,{key:1},[t[18]||(t[18]=e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"},null,-1)),t[19]||(t[19]=e.createElementVNode("path",{d:"M19 6.41L17.59 5 15 7.59 12.41 5 11 6.41 13.59 9 11 11.59 12.41 13 15 10.41 17.59 13 19 11.59 16.41 9z"},null,-1))],64)):(e.openBlock(),e.createElementBlock("path",Me))],2))],2),e.createElementVNode("div",Ie,[e.createElementVNode("p",He,e.toDisplayString(a.number),1),e.createElementVNode("div",Ue,[e.createElementVNode("span",null,e.toDisplayString(X(a.timestamp)),1),a.duration>0?(e.openBlock(),e.createElementBlock(e.Fragment,{key:0},[t[20]||(t[20]=e.createElementVNode("span",null,"•",-1)),e.createElementVNode("span",Te,e.toDisplayString(e.unref(B.formatDuration)(a.duration)),1)],64)):e.createCommentVNode("",!0)])]),e.createElementVNode("button",{onClick:N=>O(a),class:"h-8 w-8 flex items-center justify-center shrink-0 rounded-lg hover:bg-gray-100 transition-colors",type:"button"},[...t[21]||(t[21]=[e.createElementVNode("svg",{class:"w-4 h-4",viewBox:"0 0 24 24",fill:"currentColor"},[e.createElementVNode("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"})],-1)])],8,Pe)],4))),128))]))])])])])):e.createCommentVNode("",!0)]))],2))}}),W=Symbol("Phone");let A=null,q=null;function Re(E){return`${E.websocketUrl}|${E.sipUri}|${E.authorizationUser}`}function Le(E){const T=Re(E);if(A&&q===T)return A;if(A&&q!==T){try{A.ua.stop()}catch{}A=null}q=T;const d={sockets:[new B.JsSIP.WebSocketInterface(E.websocketUrl)],uri:E.sipUri,password:E.password,registrar_server:E.registrarServer,display_name:E.displayName,authorization_user:E.authorizationUser,connection_recovery_min_interval:2,connection_recovery_max_interval:30},s=new B.JsSIP.UA(d),I=document.createElement("audio");I.autoplay=!0;const r={ua:s,audio:I,isStarted:!1,listeners:new Set};return s.on("connecting",()=>{r.listeners.forEach(h=>h.onConnecting?.())}),s.on("connected",()=>{r.listeners.forEach(h=>h.onConnected?.())}),s.on("disconnected",()=>{r.listeners.forEach(h=>h.onDisconnected?.())}),s.on("registered",()=>{r.listeners.forEach(h=>h.onRegistered?.())}),s.on("unregistered",()=>{r.listeners.forEach(h=>h.onUnregistered?.())}),s.on("registrationFailed",h=>{r.listeners.forEach(n=>n.onRegistrationFailed?.(h?.cause))}),s.on("newRTCSession",h=>{const n=h.session;if(n.direction==="incoming"){const u=n.remote_identity,v=u?.uri?.user||"Unknown",w=u?.display_name||void 0;r.listeners.forEach(c=>c.onIncomingSession?.(n,v,w)),n.on("peerconnection",()=>{n.connection.addEventListener("addstream",c=>{if(!c.streams?.length)return;const f=document.createElement("audio");f.srcObject=c.streams[0],f.play()}),n.connection.addEventListener("track",c=>{const f=document.createElement("audio");f.srcObject=c.streams[0],f.play()})});return}r.listeners.forEach(u=>u.onNewSession?.(n)),n.connection&&(n.connection.addEventListener("addstream",u=>{if(!u.streams?.length)return;const v=document.createElement("audio");v.srcObject=u.streams[0],v.play()}),n.connection.addEventListener("track",u=>{const v=document.createElement("audio");v.srcObject=u.streams[0],v.play()}))}),A=r,r}function je(E){const{config:T,onCallStart:i,onCallEnd:d,onStatusChange:s,onIncomingCall:I}=E,r=e.ref("disconnected"),h=e.ref(""),n=e.ref([]),u=e.ref(0),v=e.ref(!1),w=e.ref("connecting"),c=e.ref(null);let f=null,b=null,o=null,p=null;const k=y=>{h.value=y},C=(y,D,M)=>{const m={id:Date.now().toString(),number:y,timestamp:Date.now(),duration:D,status:M};n.value=[m,...n.value].slice(0,50),localStorage.setItem("tbi-phone-call-history",JSON.stringify(n.value))},V=()=>{b&&(b.terminate(),b=null),c.value=null},x=()=>{if(!c.value)return;const{session:y,callerNumber:D}=c.value,M={mediaConstraints:{audio:!0,video:!1}};try{y.answer(M),b=y,i?.(D)}catch(m){console.error("Failed to answer call:",m),r.value="failed",s?.("failed"),C(D,0,"missed"),c.value=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}},S=()=>{if(!c.value)return;const{session:y,callerNumber:D}=c.value;try{y.terminate({status_code:603,reason_phrase:"Decline"})}catch(M){console.error("Failed to reject call:",M)}C(D,0,"missed"),c.value=null,r.value="disconnected",s?.("disconnected")},J=y=>{if(!y.trim()||!f)return;if(!v.value){console.warn("Phone is not ready yet. Please wait for registration.");return}h.value=y,i?.(y);const M={eventHandlers:{progress:()=>{r.value="progress",s?.("progress")},failed:m=>{console.error("Call failed:",m?.cause),r.value="failed",s?.("failed"),C(y,0,"failed"),d?.(y,0,"failed"),b=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)},ended:()=>{r.value="ended",s?.("ended");const m=o?Math.floor((Date.now()-o)/1e3):0;C(y,m,"completed"),d?.(y,m,"completed"),b=null,p&&(clearInterval(p),p=null),setTimeout(()=>{r.value="disconnected",s?.("disconnected"),o=null,u.value=0},2e3)},confirmed:()=>{r.value="confirmed",s?.("confirmed"),o=Date.now(),p=setInterval(()=>{o&&(u.value=Math.floor((Date.now()-o)/1e3))},1e3)}},mediaConstraints:{audio:!0,video:!1}};r.value="progress",s?.("progress");try{b=f.ua.call(y,M)}catch(m){console.error("Failed to start call:",m),r.value="failed",s?.("failed"),C(y,0,"failed"),setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}};e.onMounted(()=>{f=Le(T),f.ua.isRegistered()?(v.value=!0,w.value="connected"):f.ua.isConnected()&&(w.value="connected");const y={onConnecting:()=>{w.value="connecting"},onConnected:()=>{w.value="connected"},onDisconnected:()=>{w.value="disconnected",v.value=!1},onRegistered:()=>{v.value=!0,w.value="connected"},onUnregistered:()=>{v.value=!1},onRegistrationFailed:m=>{console.error("Registration failed:",m),v.value=!1,w.value="failed"},onNewSession:m=>{b=m},onIncomingSession:(m,P,O)=>{if(b){m.terminate({status_code:486,reason_phrase:"Busy Here"});return}c.value={session:m,callerNumber:P,callerName:O},h.value=P,r.value="ringing",s?.("ringing"),I?.(P,O),m.on("failed",$=>{console.error("Incoming call failed:",$?.cause),r.value="failed",s?.("failed"),C(P,0,"missed"),c.value=null,b=null,setTimeout(()=>{r.value="disconnected",s?.("disconnected")},3e3)}),m.on("ended",()=>{r.value="ended",s?.("ended");const $=o?Math.floor((Date.now()-o)/1e3):0;C(P,$,"completed"),d?.(P,$,"completed"),c.value=null,b=null,p&&(clearInterval(p),p=null),setTimeout(()=>{r.value="disconnected",s?.("disconnected"),o=null,u.value=0},2e3)}),m.on("confirmed",()=>{r.value="confirmed",s?.("confirmed"),o=Date.now(),c.value=null,p=setInterval(()=>{o&&(u.value=Math.floor((Date.now()-o)/1e3))},1e3)})}};f.listeners.add(y),f.isStarted||(f.ua.start(),f.isStarted=!0);const D=localStorage.getItem("tbi-phone-call-history");if(D)try{n.value=JSON.parse(D)}catch(m){console.error("Error loading call history",m)}const M=m=>{const O=m.detail.number;r.value==="disconnected"&&J(O)};window.addEventListener("StartCallEvent",M)}),e.onUnmounted(()=>{p&&clearInterval(p)});const H={status:e.readonly(r),callNumber:h,setCallNumber:k,callHistory:e.readonly(n),currentCallDuration:e.readonly(u),startCall:J,endCall:V,answerCall:x,rejectCall:S,isReady:e.readonly(v),connectionStatus:e.readonly(w),incomingCall:e.readonly(c)};return e.provide(W,H),H}function Oe(){const E=e.inject(W);if(!E)throw new Error("usePhone must be used within a component that has called usePhoneProvider");return E}function $e(E,T={}){const{onCallStart:i,onCallEnd:d,onStatusChange:s,onConnectionChange:I,persistHistory:r=!0,historyKey:h="tbi-phone-call-history"}=T,n=e.ref("disconnected"),u=e.ref(""),v=e.ref([]),w=e.ref(0),c=e.ref(!1),f=e.ref("connecting"),b=e.ref(null);let o=null;e.onMounted(()=>{o=new B.PhoneManager(E,{onStatusChange:x=>{n.value=x,s?.(x)},onConnectionChange:x=>{f.value=x,o&&(c.value=o.state.isReady),I?.(x)},onCallStart:i,onCallEnd:d,onDurationUpdate:x=>{w.value=x},onHistoryUpdate:x=>{v.value=x},onRegistered:()=>{c.value=!0},onUnregistered:()=>{c.value=!1}},{persistHistory:r,historyKey:h}),o.initialize(),n.value=o.state.status,u.value=o.state.callNumber,v.value=o.state.callHistory,c.value=o.state.isReady,f.value=o.state.connectionStatus,b.value=o.ua}),e.onUnmounted(()=>{o&&(o.destroy(),o=null)});const p=x=>{u.value=x,o?.setCallNumber(x)},k=x=>{o?.startCall(x)},C=()=>{o?.endCall()},V=()=>{o?.clearHistory(),v.value=[]};return{status:e.readonly(n),callNumber:u,setCallNumber:p,callHistory:e.readonly(v),clearCallHistory:V,currentCallDuration:e.readonly(w),startCall:k,endCall:C,isReady:e.readonly(c),connectionStatus:e.readonly(f),ua:b}}exports.Phone=G;exports.PhoneKey=W;exports.default=G;exports.usePhone=Oe;exports.usePhoneManager=$e;exports.usePhoneProvider=je;
package/dist/vue/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { defineComponent as fe, ref as b, computed as ie, onMounted as ae, onUnmounted as re, createElementBlock as w, openBlock as y, normalizeClass as Z, unref as G, createCommentVNode as F, createBlock as ge, createElementVNode as e, withDirectives as me, vModelText as he, toDisplayString as I, createTextVNode as ee, Teleport as pe, Fragment as te, renderList as Ce, normalizeStyle as ye, readonly as j, provide as xe, inject as we } from "vue";
2
- import { d as be, f as le, c as ne, J as oe, P as Se } from "../index-8z_LWKp3.js";
2
+ import { d as be, f as le, c as ne, J as oe, P as Se } from "../index-BP63oarb.js";
3
3
  const Ee = {
4
4
  key: 0,
5
5
  class: "flex gap-2 items-center"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbisoftware/phone",
3
- "version": "2.0.9",
3
+ "version": "2.0.11",
4
4
  "type": "module",
5
5
  "description": "A reusable SIP phone component for React and Vue applications",
6
6
  "author": "TBI",