@16x/webphone-sdk 3.0.1 → 3.0.2
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.
- package/CHANGELOG.md +8 -4
- package/LICENSE +0 -1
- package/README.md +1 -1
- package/dist/CCBarClient-DdLM2NKm.cjs +1 -0
- package/dist/{CCBarClient-BdbynNBi.js → CCBarClient-xC63i3Qd.js} +345 -156
- package/dist/{Diagnostics-Cw2HVrCD.js → Diagnostics-BhsVHELt.js} +9 -9
- package/dist/{Diagnostics-BYVvmxil.cjs → Diagnostics-CvH6cjih.cjs} +1 -1
- package/dist/JsSipAdapter-BM7I95Xb.cjs +1 -0
- package/dist/{JsSipAdapter-GHzVSCDh.js → JsSipAdapter-CV6q6UUY.js} +20 -13
- package/dist/SharedWorkerProtocol-V_x8Erjv.cjs +1 -0
- package/dist/{SharedWorkerProtocol-BqUafs8d.js → SharedWorkerProtocol-jfo9N5wa.js} +27 -17
- package/dist/core/CCBarClient.d.ts +14 -2
- package/dist/core/CallManager.d.ts +2 -0
- package/dist/diagnostics/Diagnostics.d.ts +1 -0
- package/dist/diagnostics/index.cjs +1 -1
- package/dist/diagnostics/index.d.ts +1 -1
- package/dist/diagnostics/index.js +3 -6
- package/dist/index.cjs +1 -1
- package/dist/index.js +9 -139
- package/dist/index.umd.js +17 -17
- package/dist/legacy/index.cjs +1 -1
- package/dist/legacy/index.js +2 -2
- package/dist/shared-worker.cjs +1 -1
- package/dist/shared-worker.js +13 -6
- package/dist/types.d.ts +5 -0
- package/dist/ui/XCallCCBarElement.d.ts +2 -0
- package/dist/ui/index.cjs +1 -1
- package/dist/ui/index.js +138 -130
- package/package.json +3 -1
- package/dist/CCBarClient-DKWdvgf5.cjs +0 -1
- package/dist/CCBarError-CIqJE8zK.cjs +0 -1
- package/dist/CCBarError-DSbPw2dA.js +0 -14
- package/dist/JsSipAdapter-jtGdoXrm.cjs +0 -1
- package/dist/SharedWorkerProtocol-CYN0AprP.cjs +0 -1
package/dist/ui/index.js
CHANGED
|
@@ -654,74 +654,82 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
654
654
|
];
|
|
655
655
|
}
|
|
656
656
|
#e;
|
|
657
|
-
#t =
|
|
658
|
-
#n =
|
|
659
|
-
#r = "
|
|
660
|
-
#i;
|
|
661
|
-
#a
|
|
662
|
-
#o =
|
|
657
|
+
#t = !1;
|
|
658
|
+
#n = [];
|
|
659
|
+
#r = "idle";
|
|
660
|
+
#i = "unknown";
|
|
661
|
+
#a;
|
|
662
|
+
#o = /* @__PURE__ */ new Set();
|
|
663
663
|
#s = "";
|
|
664
|
-
#c = "
|
|
665
|
-
#l =
|
|
664
|
+
#c = "";
|
|
665
|
+
#l = "offline";
|
|
666
666
|
#u = !1;
|
|
667
|
-
#d =
|
|
668
|
-
#f;
|
|
669
|
-
#p
|
|
667
|
+
#d = !1;
|
|
668
|
+
#f = Promise.resolve();
|
|
669
|
+
#p;
|
|
670
670
|
#m = !1;
|
|
671
|
-
#h;
|
|
671
|
+
#h = !1;
|
|
672
672
|
#g;
|
|
673
673
|
#_;
|
|
674
674
|
#v;
|
|
675
675
|
#y;
|
|
676
|
+
#b;
|
|
676
677
|
get messageResolver() {
|
|
677
|
-
return this.#
|
|
678
|
+
return this.#y;
|
|
678
679
|
}
|
|
679
680
|
set messageResolver(e) {
|
|
680
|
-
this.#
|
|
681
|
+
this.#y = e, this.shadowRoot !== null && this.render();
|
|
681
682
|
}
|
|
682
683
|
get client() {
|
|
683
684
|
return this.#e;
|
|
684
685
|
}
|
|
685
686
|
set client(e) {
|
|
686
|
-
this.#
|
|
687
|
+
this.#O(), this.#e = e, this.#D(), this.render();
|
|
688
|
+
}
|
|
689
|
+
get ownsClient() {
|
|
690
|
+
return this.#t;
|
|
691
|
+
}
|
|
692
|
+
set ownsClient(e) {
|
|
693
|
+
this.#t = e === !0;
|
|
687
694
|
}
|
|
688
695
|
connectedCallback() {
|
|
689
|
-
this.#
|
|
696
|
+
this.#V(), this.#B(), this.render();
|
|
690
697
|
}
|
|
691
698
|
disconnectedCallback() {
|
|
692
|
-
|
|
699
|
+
let e = this.#e, t = this.#t;
|
|
700
|
+
this.#O(), this.#G(), this.#b?.(), this.#b = void 0, t && (this.#e = void 0, e?.dispose());
|
|
693
701
|
}
|
|
694
702
|
attributeChangedCallback(e) {
|
|
695
|
-
this.#
|
|
703
|
+
this.#V(), e === "theme" && this.#B(), this.shadowRoot !== null && this.render();
|
|
696
704
|
}
|
|
697
705
|
render() {
|
|
698
|
-
let e = this.#
|
|
699
|
-
e !== void 0 && (e.innerHTML = `<style>${B}</style>`, e.append(this.#
|
|
706
|
+
let e = this.#k();
|
|
707
|
+
e !== void 0 && (e.innerHTML = `<style>${B}</style>`, e.append(this.#S(this.#x())));
|
|
700
708
|
}
|
|
701
|
-
#
|
|
709
|
+
#x() {
|
|
702
710
|
let e = this.#e?.getCalls?.().map((e) => ({
|
|
703
711
|
id: e.id,
|
|
704
712
|
state: e.state,
|
|
705
713
|
destination: e.destination,
|
|
706
|
-
direction: this.#
|
|
714
|
+
direction: this.#o.has(e.id) ? "inbound" : "outbound"
|
|
707
715
|
})) ?? [];
|
|
708
716
|
return z({
|
|
709
|
-
connectionState: this.#
|
|
710
|
-
permission: this.#
|
|
717
|
+
connectionState: this.#r,
|
|
718
|
+
permission: this.#i,
|
|
711
719
|
calls: e,
|
|
712
|
-
error: this.#
|
|
720
|
+
error: this.#a
|
|
713
721
|
});
|
|
714
722
|
}
|
|
715
|
-
#
|
|
716
|
-
let t = this.#
|
|
723
|
+
#S(e) {
|
|
724
|
+
let t = this.#z(), n = this.#_ ?? this.#g ?? K(e, t), r = {
|
|
717
725
|
...t,
|
|
718
726
|
status: n
|
|
719
|
-
}, i = this.#
|
|
720
|
-
return i.setAttribute("data-view", this.#
|
|
727
|
+
}, i = this.#C(e, r, n);
|
|
728
|
+
return i.setAttribute("data-view", this.#E() && !this.#m ? "setup" : e.kind), i.hasAttribute("data-layout") || i.setAttribute("data-layout", this.#E() ? "mobile" : "panel"), i;
|
|
721
729
|
}
|
|
722
|
-
#
|
|
723
|
-
if (this.#
|
|
724
|
-
enabling: this.#
|
|
730
|
+
#C(e, t, n) {
|
|
731
|
+
if (this.#E() && !this.#m) return N({
|
|
732
|
+
enabling: this.#h,
|
|
725
733
|
status: n,
|
|
726
734
|
enablePhone: t.enablePhone
|
|
727
735
|
});
|
|
@@ -732,12 +740,12 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
732
740
|
view: e,
|
|
733
741
|
messages: t
|
|
734
742
|
});
|
|
735
|
-
case "incoming": return this.#
|
|
743
|
+
case "incoming": return this.#E() ? P({
|
|
736
744
|
view: { kind: "ready" },
|
|
737
745
|
messages: t,
|
|
738
|
-
destination: this.#
|
|
739
|
-
muted: this.#
|
|
740
|
-
canDial: s(this.#
|
|
746
|
+
destination: this.#s,
|
|
747
|
+
muted: this.#u,
|
|
748
|
+
canDial: s(this.#s, this.#i, this.#r),
|
|
741
749
|
showOutputDevice: this.#e?.media.supportsOutputSelection() === !0
|
|
742
750
|
}) : j({
|
|
743
751
|
view: e,
|
|
@@ -749,121 +757,121 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
749
757
|
case "ready":
|
|
750
758
|
case "active":
|
|
751
759
|
case "held":
|
|
752
|
-
case "dialing": return this.#
|
|
760
|
+
case "dialing": return this.#E() ? P({
|
|
753
761
|
view: e.kind === "held" ? { kind: "ready" } : e,
|
|
754
762
|
messages: t,
|
|
755
|
-
destination: this.#
|
|
756
|
-
muted: this.#
|
|
757
|
-
canDial: s(this.#
|
|
763
|
+
destination: this.#s,
|
|
764
|
+
muted: this.#u,
|
|
765
|
+
canDial: s(this.#s, this.#i, this.#r),
|
|
758
766
|
showOutputDevice: this.#e?.media.supportsOutputSelection() === !0
|
|
759
767
|
}) : _({
|
|
760
|
-
mode: this.#
|
|
768
|
+
mode: this.#T() === "compact" ? "compact" : "panel",
|
|
761
769
|
view: e,
|
|
762
770
|
messages: t,
|
|
763
|
-
destination: this.#
|
|
764
|
-
muted: this.#
|
|
765
|
-
canDial: s(this.#
|
|
766
|
-
moreOpen: this.#
|
|
771
|
+
destination: this.#s,
|
|
772
|
+
muted: this.#u,
|
|
773
|
+
canDial: s(this.#s, this.#i, this.#r),
|
|
774
|
+
moreOpen: this.#d,
|
|
767
775
|
floating: this.hasAttribute("floating"),
|
|
768
|
-
connected: this.#
|
|
769
|
-
agentStatus: this.#
|
|
770
|
-
extension: this.#
|
|
771
|
-
calls: this.#
|
|
776
|
+
connected: this.#r === "connected",
|
|
777
|
+
agentStatus: this.#l,
|
|
778
|
+
extension: this.#c,
|
|
779
|
+
calls: this.#w()
|
|
772
780
|
});
|
|
773
781
|
default: return e;
|
|
774
782
|
}
|
|
775
783
|
}
|
|
776
|
-
#
|
|
784
|
+
#w() {
|
|
777
785
|
let e = this.#e?.getActiveCall?.()?.id;
|
|
778
786
|
return this.#e?.getCalls?.().map((t) => ({
|
|
779
787
|
id: t.id,
|
|
780
788
|
destination: t.destination,
|
|
781
789
|
state: t.state,
|
|
782
|
-
direction: this.#
|
|
790
|
+
direction: this.#o.has(t.id) ? "inbound" : "outbound",
|
|
783
791
|
current: t.id === e
|
|
784
792
|
})) ?? [];
|
|
785
793
|
}
|
|
786
|
-
#
|
|
794
|
+
#T() {
|
|
787
795
|
let e = this.getAttribute("mode");
|
|
788
796
|
return e === "compact" || e === "mobile" ? e : "panel";
|
|
789
797
|
}
|
|
790
|
-
#T() {
|
|
791
|
-
return this.#w() === "mobile";
|
|
792
|
-
}
|
|
793
798
|
#E() {
|
|
799
|
+
return this.#T() === "mobile";
|
|
800
|
+
}
|
|
801
|
+
#D() {
|
|
794
802
|
let e = this.#e;
|
|
795
|
-
e !== void 0 && (this.#
|
|
796
|
-
if (this.#
|
|
803
|
+
e !== void 0 && (this.#n.push(e.on("connection.stateChanged", (t) => {
|
|
804
|
+
if (this.#r = t.state, t.state !== "connected" && (this.#l = "offline"), t.state === "connected") {
|
|
797
805
|
let t = e.getAgent?.()?.extension?.trim();
|
|
798
|
-
t !== void 0 && t !== "" && (this.#
|
|
806
|
+
t !== void 0 && t !== "" && (this.#c = t);
|
|
799
807
|
}
|
|
800
|
-
})), this.#
|
|
801
|
-
(e.status === "available" || e.status === "offline" || e.status === "break") && (this.#
|
|
802
|
-
})), this.#
|
|
803
|
-
this.#
|
|
804
|
-
})), this.#
|
|
805
|
-
this.#
|
|
806
|
-
})), this.#
|
|
807
|
-
this.#
|
|
808
|
-
})), this.#
|
|
809
|
-
this.#
|
|
810
|
-
})), this.#
|
|
811
|
-
this.#
|
|
812
|
-
})), this.#
|
|
813
|
-
this.#
|
|
808
|
+
})), this.#n.push(e.on("agent.statusChanged", (e) => {
|
|
809
|
+
(e.status === "available" || e.status === "offline" || e.status === "break") && (this.#l = e.status);
|
|
810
|
+
})), this.#n.push(e.on("connection.failed", (e) => {
|
|
811
|
+
this.#r = "failed", this.#a = { code: e.error.code };
|
|
812
|
+
})), this.#n.push(e.on("media.permissionChanged", (e) => {
|
|
813
|
+
this.#i = e.permission;
|
|
814
|
+
})), this.#n.push(e.on("error", (e) => {
|
|
815
|
+
this.#a = { code: e.error.code };
|
|
816
|
+
})), this.#n.push(e.on("call.incoming", (e) => {
|
|
817
|
+
this.#o.add(e.callId);
|
|
818
|
+
})), this.#n.push(e.on("call.ended", (e) => {
|
|
819
|
+
this.#o.delete(e.callId), this.#u = !1;
|
|
820
|
+
})), this.#n.push(e.on("call.failed", () => {
|
|
821
|
+
this.#_ = this.#z().statusFailed;
|
|
814
822
|
})), U.forEach((t) => {
|
|
815
|
-
this.#
|
|
816
|
-
}), this.#
|
|
823
|
+
this.#n.push(e.on(t, () => this.render()));
|
|
824
|
+
}), this.#E() && typeof e.recover == "function" && (this.#v = a(e, {
|
|
817
825
|
onChecking: () => {
|
|
818
|
-
this.#
|
|
826
|
+
this.#g = this.#z().foregroundChecking, this.render();
|
|
819
827
|
},
|
|
820
828
|
onRecovered: () => {
|
|
821
|
-
this.#
|
|
829
|
+
this.#g = void 0, this.render();
|
|
822
830
|
},
|
|
823
831
|
onFailed: () => {
|
|
824
|
-
this.#
|
|
832
|
+
this.#g = this.#z().foregroundFailed, this.render();
|
|
825
833
|
}
|
|
826
834
|
})));
|
|
827
835
|
}
|
|
828
|
-
#D() {
|
|
829
|
-
let e = this.#t;
|
|
830
|
-
this.#t = [], e.forEach((e) => e()), this.#n = "idle", this.#r = "unknown", this.#c = "offline", this.#i = void 0, this.#a.clear(), this.#l = !1, this.#u = !1, this.#p = !1, this.#m = !1, this.#h = void 0, this.#_?.(), this.#_ = void 0;
|
|
831
|
-
}
|
|
832
836
|
#O() {
|
|
837
|
+
let e = this.#n;
|
|
838
|
+
this.#n = [], e.forEach((e) => e()), this.#r = "idle", this.#i = "unknown", this.#l = "offline", this.#a = void 0, this.#o.clear(), this.#u = !1, this.#d = !1, this.#m = !1, this.#h = !1, this.#g = void 0, this.#v?.(), this.#v = void 0;
|
|
839
|
+
}
|
|
840
|
+
#k() {
|
|
833
841
|
if (typeof this.attachShadow != "function") return;
|
|
834
842
|
let e = this.shadowRoot ?? this.attachShadow({ mode: "open" });
|
|
835
|
-
return H.has(e) || (H.add(e), e.addEventListener("click", (e) => this.#
|
|
843
|
+
return H.has(e) || (H.add(e), e.addEventListener("click", (e) => this.#A(e)), e.addEventListener("input", (e) => this.#P(e)), e.addEventListener("pointerdown", (e) => this.#H(e))), e;
|
|
836
844
|
}
|
|
837
|
-
#
|
|
845
|
+
#A(e) {
|
|
838
846
|
let t = J(e, this), n = t?.closest("[data-action=\"enable-phone\"]");
|
|
839
|
-
n instanceof HTMLButtonElement && (n.disabled = !0), this.#
|
|
840
|
-
this.#
|
|
847
|
+
n instanceof HTMLButtonElement && (n.disabled = !0), this.#f = this.#f.then(() => this.#F(t)).catch((e) => {
|
|
848
|
+
this.#_ = Y(e), this.render();
|
|
841
849
|
});
|
|
842
850
|
}
|
|
843
|
-
#
|
|
851
|
+
#j() {
|
|
844
852
|
let e = this.shadowRoot?.querySelector("input[name=\"destination\"]");
|
|
845
|
-
return e instanceof HTMLInputElement ? e.value : this.#
|
|
853
|
+
return e instanceof HTMLInputElement ? e.value : this.#s;
|
|
846
854
|
}
|
|
847
|
-
#
|
|
855
|
+
#M() {
|
|
848
856
|
let e = this.shadowRoot?.querySelector("input[name=\"extension\"]");
|
|
849
|
-
return e instanceof HTMLInputElement ? e.value.trim() : this.#
|
|
857
|
+
return e instanceof HTMLInputElement ? e.value.trim() : this.#c;
|
|
850
858
|
}
|
|
851
|
-
#
|
|
859
|
+
#N() {
|
|
852
860
|
let e = this.shadowRoot?.querySelector("input[name=\"transfer-target\"]");
|
|
853
861
|
return e instanceof HTMLInputElement ? e.value : "";
|
|
854
862
|
}
|
|
855
|
-
#
|
|
863
|
+
#P(e) {
|
|
856
864
|
let t = J(e, this);
|
|
857
865
|
if (t instanceof HTMLInputElement && t.name !== "transfer-target") {
|
|
858
866
|
if (t.name === "extension") {
|
|
859
|
-
this.#
|
|
867
|
+
this.#c = t.value.trim();
|
|
860
868
|
return;
|
|
861
869
|
}
|
|
862
|
-
this.#
|
|
870
|
+
this.#s = t.value, this.#L();
|
|
863
871
|
}
|
|
864
872
|
}
|
|
865
|
-
async #
|
|
866
|
-
if (this.#
|
|
873
|
+
async #F(e) {
|
|
874
|
+
if (this.#_ = void 0, e === void 0) return;
|
|
867
875
|
let t = e.closest("[data-call-id]");
|
|
868
876
|
if (t instanceof HTMLElement && t.dataset.callId !== void 0) {
|
|
869
877
|
await this.#e?.setActiveCall(t.dataset.callId);
|
|
@@ -871,7 +879,7 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
871
879
|
}
|
|
872
880
|
let n = e.closest("[data-digit]");
|
|
873
881
|
if (n instanceof HTMLElement && n.dataset.digit !== void 0) {
|
|
874
|
-
await this.#
|
|
882
|
+
await this.#I(n.dataset.digit);
|
|
875
883
|
return;
|
|
876
884
|
}
|
|
877
885
|
let r = e.closest("[data-action]");
|
|
@@ -880,20 +888,20 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
880
888
|
switch (r.getAttribute("data-action")) {
|
|
881
889
|
case "signin":
|
|
882
890
|
if (this.#e === void 0) return;
|
|
883
|
-
this.#
|
|
891
|
+
this.#c = this.#M(), await this.#e.media?.requestPermission?.(), await this.#e.initialize(), await this.#e.connect(this.#c === "" ? void 0 : { extension: this.#c });
|
|
884
892
|
return;
|
|
885
893
|
case "signout":
|
|
886
894
|
if (this.#e === void 0) return;
|
|
887
|
-
this.#
|
|
895
|
+
this.#l = "offline", await this.#e.disconnect();
|
|
888
896
|
return;
|
|
889
897
|
case "dial":
|
|
890
898
|
case "dial-internal":
|
|
891
|
-
if (this.#
|
|
892
|
-
this.#
|
|
899
|
+
if (this.#s = this.#j(), this.#e === void 0) return;
|
|
900
|
+
this.#i !== "granted" && await this.#e.media?.requestPermission?.(), await c(this.#e, this.#s, r.getAttribute("data-action") === "dial-internal" ? "extension" : void 0);
|
|
893
901
|
return;
|
|
894
902
|
case "mute":
|
|
895
903
|
if (a === void 0) return;
|
|
896
|
-
this.#
|
|
904
|
+
this.#u = await l(a, this.#u), this.#R();
|
|
897
905
|
return;
|
|
898
906
|
case "hold":
|
|
899
907
|
a !== void 0 && await u(a);
|
|
@@ -902,7 +910,7 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
902
910
|
a !== void 0 && await a.resume();
|
|
903
911
|
return;
|
|
904
912
|
case "transfer":
|
|
905
|
-
a !== void 0 && await f(a, this.#
|
|
913
|
+
a !== void 0 && await f(a, this.#N());
|
|
906
914
|
return;
|
|
907
915
|
case "hangup":
|
|
908
916
|
await a?.hangup();
|
|
@@ -914,16 +922,16 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
914
922
|
await a?.reject();
|
|
915
923
|
return;
|
|
916
924
|
case "enable-phone":
|
|
917
|
-
if (this.#e === void 0 || this.#
|
|
918
|
-
this.#
|
|
925
|
+
if (this.#e === void 0 || this.#m) return;
|
|
926
|
+
this.#h = !0;
|
|
919
927
|
try {
|
|
920
|
-
await i(this.#e), this.#
|
|
928
|
+
await i(this.#e), this.#m = !0;
|
|
921
929
|
} finally {
|
|
922
|
-
this.#
|
|
930
|
+
this.#h = !1, this.render();
|
|
923
931
|
}
|
|
924
932
|
return;
|
|
925
933
|
case "more":
|
|
926
|
-
this.#
|
|
934
|
+
this.#d = !this.#d, this.render();
|
|
927
935
|
return;
|
|
928
936
|
case "retry-permission":
|
|
929
937
|
await this.#e?.media.requestPermission();
|
|
@@ -939,32 +947,32 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
939
947
|
default: return;
|
|
940
948
|
}
|
|
941
949
|
}
|
|
942
|
-
async #
|
|
950
|
+
async #I(e) {
|
|
943
951
|
let t = this.#e?.getActiveCall?.();
|
|
944
952
|
if (t !== void 0 && (t.state === "active" || t.state === "held")) {
|
|
945
953
|
await d(t, e);
|
|
946
954
|
return;
|
|
947
955
|
}
|
|
948
|
-
this.#
|
|
956
|
+
this.#s += e;
|
|
949
957
|
let n = this.shadowRoot?.querySelector("input[name=\"destination\"]");
|
|
950
|
-
n instanceof HTMLInputElement && (n.value = this.#
|
|
958
|
+
n instanceof HTMLInputElement && (n.value = this.#s), this.#L();
|
|
951
959
|
}
|
|
952
|
-
#
|
|
953
|
-
let e = !s(this.#
|
|
960
|
+
#L() {
|
|
961
|
+
let e = !s(this.#s, this.#i, this.#r);
|
|
954
962
|
for (let t of ["dial", "dial-internal"]) {
|
|
955
963
|
let n = this.shadowRoot?.querySelector(`[data-action="${t}"]`);
|
|
956
964
|
n instanceof HTMLButtonElement && (n.disabled = e);
|
|
957
965
|
}
|
|
958
966
|
}
|
|
959
|
-
#L() {
|
|
960
|
-
let e = this.shadowRoot?.querySelector("[data-action=\"mute\"]");
|
|
961
|
-
e instanceof HTMLButtonElement && (e.setAttribute("aria-pressed", this.#l ? "true" : "false"), e.textContent = this.#l ? this.#R().unmute : this.#R().mute);
|
|
962
|
-
}
|
|
963
967
|
#R() {
|
|
964
|
-
|
|
968
|
+
let e = this.shadowRoot?.querySelector("[data-action=\"mute\"]");
|
|
969
|
+
e instanceof HTMLButtonElement && (e.setAttribute("aria-pressed", this.#u ? "true" : "false"), e.textContent = this.#u ? this.#z().unmute : this.#z().mute);
|
|
965
970
|
}
|
|
966
971
|
#z() {
|
|
967
|
-
this
|
|
972
|
+
return r(this.getAttribute("locale") ?? "zh-CN", void 0, this.#y);
|
|
973
|
+
}
|
|
974
|
+
#B() {
|
|
975
|
+
this.#b?.(), this.#b = void 0;
|
|
968
976
|
let e = this.getAttribute("theme") ?? "light";
|
|
969
977
|
if (e === "dark" || e === "light") {
|
|
970
978
|
this.setAttribute("data-theme", e);
|
|
@@ -977,31 +985,31 @@ var B = ":root,:host{--ccbar-color-surface:#fff;--ccbar-color-surface-muted:#f1f
|
|
|
977
985
|
let t = window.matchMedia("(prefers-color-scheme: dark)"), n = () => {
|
|
978
986
|
this.setAttribute("data-theme", t.matches ? "dark" : "light");
|
|
979
987
|
};
|
|
980
|
-
n(), t.addEventListener("change", n), this.#
|
|
988
|
+
n(), t.addEventListener("change", n), this.#b = () => t.removeEventListener("change", n);
|
|
981
989
|
}
|
|
982
|
-
#
|
|
990
|
+
#V() {
|
|
983
991
|
this.style.position = this.hasAttribute("floating") ? "fixed" : "";
|
|
984
992
|
}
|
|
985
|
-
#
|
|
993
|
+
#H(e) {
|
|
986
994
|
if (!(e instanceof PointerEvent) || !this.hasAttribute("floating") || !this.hasAttribute("draggable") || (e.target instanceof Element ? e.target.closest("[data-drag-handle]") : null) === null) return;
|
|
987
995
|
e.preventDefault();
|
|
988
996
|
let t = this.getBoundingClientRect();
|
|
989
|
-
this.#
|
|
997
|
+
this.#p = {
|
|
990
998
|
pointerId: e.pointerId,
|
|
991
999
|
offsetX: e.clientX - t.left,
|
|
992
1000
|
offsetY: e.clientY - t.top
|
|
993
|
-
}, window.addEventListener("pointermove", this.#
|
|
1001
|
+
}, window.addEventListener("pointermove", this.#U), window.addEventListener("pointerup", this.#W);
|
|
994
1002
|
}
|
|
995
|
-
#
|
|
996
|
-
if (this.#
|
|
997
|
-
let t = window.visualViewport, n = t?.width ?? window.innerWidth, r = t?.height ?? window.innerHeight, i = q(e.clientX - this.#
|
|
1003
|
+
#U = (e) => {
|
|
1004
|
+
if (this.#p === void 0 || e.pointerId !== this.#p.pointerId) return;
|
|
1005
|
+
let t = window.visualViewport, n = t?.width ?? window.innerWidth, r = t?.height ?? window.innerHeight, i = q(e.clientX - this.#p.offsetX, 0, Math.max(0, n - this.offsetWidth)), a = q(e.clientY - this.#p.offsetY, 0, Math.max(0, r - this.offsetHeight));
|
|
998
1006
|
this.style.left = `${i}px`, this.style.top = `${a}px`, this.style.right = "auto", this.style.bottom = "auto";
|
|
999
1007
|
};
|
|
1000
|
-
#
|
|
1001
|
-
this.#
|
|
1008
|
+
#W = (e) => {
|
|
1009
|
+
this.#p !== void 0 && e.pointerId === this.#p.pointerId && this.#G();
|
|
1002
1010
|
};
|
|
1003
|
-
#
|
|
1004
|
-
this.#
|
|
1011
|
+
#G() {
|
|
1012
|
+
this.#p = void 0, window.removeEventListener("pointermove", this.#U), window.removeEventListener("pointerup", this.#W);
|
|
1005
1013
|
}
|
|
1006
1014
|
};
|
|
1007
1015
|
function G(e = {}) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@16x/webphone-sdk",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.2",
|
|
4
|
+
"homepage": "https://www.npmjs.com/package/@16x/webphone-sdk",
|
|
4
5
|
"private": false,
|
|
5
6
|
"license": "UNLICENSED",
|
|
6
7
|
"publishConfig": {
|
|
@@ -82,6 +83,7 @@
|
|
|
82
83
|
"docs:check": "node scripts/check-docs-site.mjs",
|
|
83
84
|
"docs:test": "npm run docs:build && npx vitest run tests/docs-site/static-site.test.ts tests/docs-site/navigation.test.ts",
|
|
84
85
|
"customer:packages": "node scripts/create-customer-packages.mjs",
|
|
86
|
+
"publish:npm": "bash scripts/publish-npm.sh",
|
|
85
87
|
"verify:release": "npm run lint && npm run typecheck && npm test && npm run build && npm run build:examples && npm run verify:bundle && npm run pack:check && npm run sbom"
|
|
86
88
|
},
|
|
87
89
|
"dependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require("./CCBarError-CIqJE8zK.cjs"),t=require("./Diagnostics-BYVvmxil.cjs");var n=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set;n.add(t),this.handlers.set(e,n);let r=!0;return()=>{r&&(r=!1,n.delete(t))}}off(e,t){this.handlers.get(e)?.delete(t)}emit(e,t){[...this.handlers.get(e)??[]].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}},r={new:new Set([`dialing`,`ringing`,`failed`]),dialing:new Set([`ringing`,`connecting`,`ended`,`failed`]),ringing:new Set([`connecting`,`ended`,`failed`]),connecting:new Set([`active`,`ended`,`failed`]),active:new Set([`held`,`ended`,`failed`]),held:new Set([`active`,`ended`,`failed`]),ended:new Set,failed:new Set},i=(e,t)=>r[e].has(t);function a(e,t){if(!i(e,t))throw new o(e,t);return t}var o=class extends e.t{constructor(e,t){super(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{cause:{from:e,to:t}})}},s=a,c=60,l=class{tokenProvider;cachedToken;cachedRequestKey=``;refreshing;generation=0;constructor(e){this.tokenProvider=e}getValidToken(e){let t=e?.extension?.trim()??``;if(this.cachedToken&&this.cachedRequestKey===t&&!this.needsRefresh(this.cachedToken))return Promise.resolve(this.cachedToken.accessToken);if(!this.refreshing){let n=this.generation,r=this.refresh(e,t,n);this.refreshing=r,r.then(()=>this.clearRefresh(r),()=>this.clearRefresh(r))}return this.refreshing}invalidate(){this.generation+=1,this.cachedToken=void 0,this.cachedRequestKey=``,this.refreshing=void 0}needsRefresh(e){return e.expiresAt!==void 0&&e.expiresAt<=Math.floor(Date.now()/1e3)+c}async refresh(e,t,n){let r=await this.tokenProvider(e),i=typeof r==`string`?{accessToken:r}:r;return n===this.generation&&(this.cachedToken=i,this.cachedRequestKey=t),i.accessToken}clearRefresh(e){this.refreshing===e&&(this.refreshing=void 0)}},u={ORIGIN_NOT_ALLOWED:{code:`CONFIG_ORIGIN_NOT_ALLOWED`,category:`configuration`,retryable:!1},CAPABILITY_DENIED:{code:`CAPABILITY_NOT_SUPPORTED`,category:`capability`,retryable:!1},TOKEN_INVALID:{code:`AUTH_TOKEN_UNAVAILABLE`,category:`auth`,retryable:!1},TOKEN_EXPIRED:{code:`AUTH_TOKEN_EXPIRED`,category:`auth`,retryable:!1},INVALID_ARGUMENT:{code:`CONFIG_INVALID`,category:`configuration`,retryable:!1},INVALID_EXTENSION:{code:`CONFIG_INVALID`,category:`configuration`,retryable:!1},SEAT_NOT_FOUND:{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1},SESSION_NOT_FOUND:{code:`CALL_NOT_CONNECTED`,category:`call`,retryable:!1},SEAT_IN_USE:{code:`CALL_ALREADY_EXISTS`,category:`call`,retryable:!1},SESSION_CONFLICT:{code:`CALL_ALREADY_EXISTS`,category:`call`,retryable:!1},SEAT_NOT_ASSIGNED:{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1},QUEUE_NOT_ASSIGNED:{code:`CAPABILITY_NOT_SUPPORTED`,category:`capability`,retryable:!1},RATE_LIMITED:{code:`NETWORK_OFFLINE`,category:`network`,retryable:!0},SIP_GATEWAY_UNAVAILABLE:{code:`SIP_WS_UNAVAILABLE`,category:`registration`,retryable:!0},SERVICE_UNAVAILABLE:{code:`NETWORK_OFFLINE`,category:`network`,retryable:!0},INTERNAL_ERROR:{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!0}},d=class{tokenManager;fetcher;baseUrl;timeoutMs;constructor(e){this.tokenManager=new l(e.tokenProvider),this.fetcher=e.fetcher??fetch.bind(globalThis),this.baseUrl=e.baseUrl.replace(/\/$/,``),this.timeoutMs=e.timeoutMs??1e4}invalidateToken(){this.tokenManager.invalidate()}createSession(e){return this.request(`POST`,`/webphone/v1/sessions`,e).then(e=>this.requireData(e))}refreshSession(e,t={refresh:[`sip_register_ticket`,`wss_ticket`,`turn_credentials`]}){return this.request(`POST`,`/webphone/v1/sessions/${encodeURIComponent(e)}/refresh`,t).then(e=>this.requireData(e))}deleteSession(e){return this.request(`DELETE`,`/webphone/v1/sessions/${encodeURIComponent(e)}`).then(()=>void 0)}setAgentStatus(e){return this.request(`PUT`,`/webphone/v1/agents/me/status`,e).then(()=>void 0)}getCapabilities(){return this.request(`GET`,`/webphone/v1/capabilities`).then(e=>this.requireData(e))}async request(t,n,r){let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs);try{let e=await this.tokenManager.getValidToken(),a=await this.fetcher(`${this.baseUrl}${n}`,{method:t,headers:{Authorization:`Bearer ${e}`,...r===void 0?{}:{"Content-Type":`application/json`}},...r===void 0?{}:{body:JSON.stringify(r)},signal:i.signal}),o=await this.parseResponse(a);if(!a.ok||o.code!==`OK`)throw this.toCCBarError(a.status,o);return{data:o.data,requestId:o.requestId}}catch(t){throw t instanceof e.t?t:t instanceof DOMException&&t.name===`AbortError`?new e.t(`NETWORK_TIMEOUT`,`network`,!0,{cause:t}):new e.t(`NETWORK_OFFLINE`,`network`,!0,{cause:t})}finally{clearTimeout(a)}}requireData(t){if(t.data===void 0||t.data===null)throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{requestId:t.requestId});return t.data}async parseResponse(t){try{return await t.json()}catch(n){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,t.status>=500,{cause:n})}}toCCBarError(t,n){let r=u[n.code??``]??this.mapStatus(t);return new e.t(r.code,r.category,r.retryable,{requestId:n.requestId})}mapStatus(e){return e===401?{code:`AUTH_TOKEN_EXPIRED`,category:`auth`,retryable:!1}:e===403?{code:`AUTH_PERMISSION_DENIED`,category:`auth`,retryable:!1}:e>=500?{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!0}:{code:`SDK_INTERNAL_ERROR`,category:`internal`,retryable:!1}}},f=[`progress`,`accepted`,`confirmed`,`ended`,`failed`,`hold`,`unhold`],p=3e4,m=class{options;currentState=`new`;sessionUnsubscribers=[];capabilities;disposed=!1;pendingOperation;incomingOperation;ownerTabId;ownerLost=!1;id;destination;platform;constructor(t){this.options=t,this.id=t.id,this.destination=t.destination,this.platform=t.platform,this.capabilities=t.capabilities??new Set;try{f.forEach(e=>{this.sessionUnsubscribers.push(t.session.on(e,t=>this.handleSessionEvent(e,t)))})}catch(n){this.cleanupSessionListeners();try{t.session.terminate()}catch{}throw new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:n})}}get state(){return this.currentState}getResourceCounts(){return{timers:this.pendingOperation?.timer===void 0?0:1,listeners:this.sessionUnsubscribers.length}}async mute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.mute())}async unmute(e){this.assertNotDisposed(),this.assertOwner(e),this.assertMediaControlAllowed(),this.assertCapability(`mute`),this.invoke(()=>this.options.session.unmute())}async answer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.platform===`mobile-web`)throw this.capabilityError();this.assertCapability(`inbound`),this.assertIncomingOperationAvailable(),this.incomingOperation=`answer`;try{this.options.session.answer(e)}catch(e){throw this.incomingOperation=void 0,this.finishFailedIncomingOperation(e),this.operationError(e)}}async reject(e={},t){this.assertNotDisposed(),this.assertOwner(t),this.assertIncomingCall(),this.assertIncomingOperationAvailable(),this.incomingOperation=`reject`;let n;try{this.options.session.terminate()}catch(e){n=e}finally{this.incomingOperation=void 0,this.transitionIfStillRinging(`ended`,{reason:e.reason?.trim()||`rejected`})}if(n!==void 0)throw this.operationError(n)}async hold(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`active`),this.assertCapability(`hold`),await this.startPendingOperation(`hold`,`held`,()=>this.options.session.hold())}async resume(e){this.assertNotDisposed(),this.assertOwner(e),this.assertHoldCapability(),this.assertState(`held`),this.assertCapability(`hold`),await this.startPendingOperation(`resume`,`active`,()=>this.options.session.unhold())}async sendDtmf(e,t){if(this.assertNotDisposed(),this.assertOwner(t),!/^[0-9A-D*#]$/.test(e))throw this.operationError();this.assertState(`active`),this.assertCapability(`dtmf`),this.invoke(()=>this.options.session.sendDtmf(e))}async transfer(e,t){if(this.assertNotDisposed(),this.assertOwner(t),this.assertTransferCapability(),this.assertState(`active`),this.assertCapability(`blind_transfer`),!g(e)||e.target.trim()===``)throw this.operationError();this.invoke(()=>this.options.session.refer(e.target.trim()))}async hangup(e){if(this.assertNotDisposed(),this.assertOwner(e),h(this.currentState))throw this.operationError();try{this.options.session.terminate(),this.transitionTo(`ended`)}catch(e){throw this.operationError(e)}}beginOutbound(){this.assertNotDisposed(),this.assertCapability(`outbound`),this.transitionTo(`dialing`)}beginIncoming(){this.assertNotDisposed(),this.transitionTo(`ringing`)}setOwnerTabId(e){this.ownerTabId=e,this.ownerLost=!1}clearOwnerTabId(e={}){this.ownerTabId=void 0,this.ownerLost=e.lost===!0}getOwnerTabId(){return this.ownerTabId}assertOwnerForManager(e){this.assertOwner(e)}canBeReclaimed(){return this.currentState===`new`||this.currentState===`dialing`||this.currentState===`ringing`}dispose(){if(!this.disposed){if(this.rejectPendingOperation(),this.incomingOperation=void 0,this.disposed=!0,!h(this.currentState))try{this.options.session.terminate()}catch(e){this.reportOperationError(e)}this.cleanupSessionListeners();try{this.options.onDisposed?.()}catch{}}}handleSessionEvent(e,t){if((e===`accepted`||e===`confirmed`||e===`ended`||e===`failed`)&&(this.incomingOperation=void 0),!(this.disposed||h(this.currentState)))switch(e){case`progress`:this.transitionIfAllowed(`ringing`,t,e);break;case`accepted`:this.transitionIfAllowed(`connecting`,t,e);break;case`confirmed`:this.transitionToActive(t);break;case`hold`:this.transitionIfAllowed(`held`,t,e);break;case`unhold`:this.transitionIfAllowed(`active`,t,e);break;case`ended`:this.transitionIfAllowed(`ended`,t,e);break;case`failed`:this.transitionIfAllowed(`failed`,t,e)}}transitionToActive(e){this.currentState!==`active`&&((this.currentState===`dialing`||this.currentState===`ringing`)&&this.transitionTo(`connecting`,e),this.transitionIfAllowed(`active`,e,`confirmed`))}transitionIfAllowed(e,t,n){this.currentState!==e&&(i(this.currentState,e)?this.transitionTo(e,t):this.reportIllegalTransition(e,n))}transitionIfStillRinging(e,t){this.currentState===`ringing`&&this.transitionTo(e,t)}transitionTo(e,t){if(this.currentState===e)return;if(!i(this.currentState,e))throw this.operationError();let n=this.currentState;this.currentState=e,h(e)&&this.rejectPendingOperation();try{this.options.onStateChanged?.({callId:this.id,from:n,to:e},t)}catch{}finally{h(e)&&this.dispose()}}startPendingOperation(e,t,n){if(this.pendingOperation!==void 0)throw this.operationError();return new Promise((r,i)=>{let a={kind:e,nextState:t,resolve:r,reject:i};this.pendingOperation=a,a.timer=setTimeout(()=>this.timeoutPendingOperation(a),p);let o;try{o=n()}catch(e){this.rejectPendingOperation(e);return}o.then(()=>this.resolvePendingOperation(a),e=>this.rejectPendingOperation(e,a))})}resolvePendingOperation(e){if(this.pendingOperation===e){if(this.clearPendingTimer(e),this.pendingOperation=void 0,this.disposed||h(this.currentState)){e.reject(this.operationError());return}try{this.transitionTo(e.nextState),e.resolve()}catch(t){e.reject(this.operationError(t))}}}rejectPendingOperation(e,t){let n=this.pendingOperation;n===void 0||t!==void 0&&n!==t||(this.clearPendingTimer(n),this.pendingOperation=void 0,n.reject(this.operationError(e)))}timeoutPendingOperation(e){this.pendingOperation===e&&(this.rejectPendingOperation(Error(`${e.kind} operation timed out`),e),this.dispose())}clearPendingTimer(e){e.timer!==void 0&&(clearTimeout(e.timer),e.timer=void 0)}reportIllegalTransition(e,t){this.reportOperationError({event:t,from:this.currentState,to:e})}reportOperationError(t){let n=t instanceof e.t&&t.callId===this.id?t:this.operationError(t);try{this.options.onError?.(n)}catch{}}finishFailedIncomingOperation(e){try{this.options.session.terminate()}catch(t){e={operation:e,cleanup:t}}this.transitionIfStillRinging(`ended`,{reason:`incoming_operation_failed`,cause:e})}cleanupSessionListeners(){this.sessionUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}assertState(e){if(this.currentState!==e)throw this.operationError()}assertMediaControlAllowed(){if(this.currentState!==`active`&&this.currentState!==`held`)throw this.operationError()}assertHoldCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertTransferCapability(){if(this.platform===`mobile-web`)throw this.capabilityError()}assertIncomingCall(){if(this.options.incoming!==!0||this.currentState!==`ringing`)throw this.operationError()}assertIncomingOperationAvailable(){if(this.incomingOperation!==void 0)throw this.operationError()}assertCapability(e){if(!this.capabilities.has(e))throw this.capabilityError()}invoke(e){try{e()}catch(e){throw this.operationError(e)}}assertNotDisposed(){if(this.disposed)throw this.operationError()}assertOwner(e){if(e!==void 0&&(this.ownerLost||this.ownerTabId!==void 0&&this.ownerTabId!==e))throw this.operationError()}capabilityError(){return new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:this.id})}operationError(t){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:this.id,cause:t})}};function h(e){return e===`ended`||e===`failed`}function g(e){return typeof e==`object`&&!!e&&e.type===`blind`&&typeof e.target==`string`}var _=0;function v(){return _+=1,`call_${Date.now().toString(36)}_${_.toString(36)}`}var y=class{events=new b;calls=new Map;options;incomingUnsubscribe;activeCallId=null;incomingSessionSnapshot;callSessions=new Map;callOwners=new Map;ownerLostCalls=new Set;pendingDialCount=0;pendingDestinations=new Set;activeOperationPromise=Promise.resolve();operationGeneration=0;automaticActiveTransition;disposed=!1;terminalNotified=new Set;terminalOperations=new Map;disposeOperation;constructor(t){this.options=t,this.incomingSessionSnapshot=t.session;try{this.incomingUnsubscribe=t.sip.onIncoming(e=>this.handleIncoming(e))}catch(t){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}async dial(t,n){this.assertNotDisposed();let r=this.operationGeneration,i=t.destination.trim();if(i===``)throw new e.t(`CALL_INVALID_DESTINATION`,`call`,!1);this.requireCapability(n,`outbound`);let a=this.callLimit(n);if(this.options.platform===`mobile-web`&&this.calls.size+this.pendingDialCount>=a)throw this.capabilityError();if(this.calls.size+this.pendingDialCount>=a||this.pendingDestinations.has(i)||[...this.calls.values()].some(e=>e.destination===i))throw new e.t(`CALL_ALREADY_EXISTS`,`call`,!1);this.pendingDialCount+=1,this.pendingDestinations.add(i);let o=v(),s;try{s=await this.holdActiveCallForNewCall(),this.assertGeneration(r,o);let e;try{e=this.options.sip.dial(i,this.dialOptions(o,n,t.type))}catch(e){throw this.dialError(e,o)}this.assertGeneration(r,o);let a;try{a=new m({id:o,destination:i,platform:this.options.platform,capabilities:this.effectiveCapabilities(n),session:e,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){throw this.dialError(e,o)}if(!this.isCurrentGeneration(r))throw a.dispose(),this.callOperationError(a.id);this.calls.set(a.id,a),this.callSessions.set(a.id,e),this.options.onCallCreated?.(a.id,e);try{a.beginOutbound()}catch(e){throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.dialError(e,a.id)}if(!this.isCurrentGeneration(r))throw a.dispose(),this.calls.delete(a.id),this.callSessions.delete(a.id),this.callOperationError(a.id);return this.events.emit(`call.created`,{callId:a.id,state:a.state}),a}catch(e){if(this.isCurrentGeneration(r)&&s!==void 0&&this.isManagedCall(s)&&s.state===`held`)try{await s.resume()}catch(t){throw this.compensationError(s.id,void 0,e,t)}throw e}finally{--this.pendingDialCount,this.pendingDestinations.delete(i)}}async answer(e,t,n,r){this.assertNotDisposed();let i=this.requireCall(e);if(this.options.platform===`mobile-web`)throw this.capabilityError(e);let a={iceServers:t.iceServers,pcConfig:{iceServers:t.iceServers},...n===void 0?{}:{mediaConstraints:n}};await i.answer(a,r)}async reject(e,t,n){this.assertNotDisposed(),await this.requireCall(e).reject(t,n)}getCalls(){return[...this.calls.values()]}hasNonTerminalCalls(){return this.calls.size>0}getResourceCounts(){let e=[...this.calls.values()].map(e=>e.getResourceCounts());return{timers:e.reduce((e,t)=>e+t.timers,0),listeners:this.events.listenerCount()+e.reduce((e,t)=>e+t.listeners,0)}}getActiveCall(){return this.activeCallId===null?void 0:this.calls.get(this.activeCallId)}async setActiveCall(e,t){this.assertNotDisposed(),this.requireCall(e).assertOwnerForManager(t),await this.enqueueActiveOperation(t=>this.switchActiveCall(e,t))}async claimCall(e,t){this.assertNotDisposed();let n=t.trim();if(n===``)throw this.callOperationError(e);let r=this.requireCall(e),i=this.callOwners.get(e);if(i!==n){if(i!==void 0||this.ownerLostCalls.has(e)&&!r.canBeReclaimed())throw this.callOperationError(e);this.ownerLostCalls.delete(e),this.callOwners.set(e,n),r.setOwnerTabId(n),this.emitOwnershipChanged({callId:e,state:`owned`,ownerTabId:n})}}async releaseCall(e,t){this.assertNotDisposed();let n=this.requireCall(e);if(this.callOwners.get(e)!==t)throw this.callOperationError(e);this.callOwners.delete(e);let r=!n.canBeReclaimed();r?this.ownerLostCalls.add(e):this.ownerLostCalls.delete(e),n.clearOwnerTabId({lost:r}),this.emitOwnershipChanged({callId:e,state:r?`owner-lost`:`released`})}getCallOwner(e){return this.callOwners.get(e)}releaseOwnedCalls(e){for(let[t,n]of[...this.callOwners.entries()]){if(n!==e)continue;let r=this.calls.get(t);if(r===void 0){this.callOwners.delete(t),this.ownerLostCalls.delete(t);continue}this.callOwners.delete(t);let i=!r.canBeReclaimed();i?this.ownerLostCalls.add(t):this.ownerLostCalls.delete(t),r.clearOwnerTabId({lost:i}),this.emitOwnershipChanged({callId:t,state:i?`owner-lost`:`released`})}}dispose(e={}){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.operationGeneration+=1,this.automaticActiveTransition=void 0,this.activeOperationPromise=Promise.resolve(),this.events.clear();try{this.incomingUnsubscribe()}catch{}this.activeCallId=null;let t=[...this.calls.values()];this.calls.clear(),this.callSessions.clear(),this.callOwners.clear(),this.ownerLostCalls.clear();let n=Promise.all(t.map(async t=>{let n;try{e.terminateCalls===!0&&t.state!==`ended`&&t.state!==`failed`?await t.hangup():t.dispose()}catch(e){n=e,t.dispose()}try{await this.notifyCallTerminal(t.id)}catch(e){n??=e}if(n!==void 0)throw n})).then(()=>void 0);return this.disposeOperation=n,n}updateSession(e){this.disposed||(this.incomingSessionSnapshot=e)}async switchActiveCall(e,t){this.assertGeneration(t,e);let n=this.requireCall(e),r=this.getActiveCall();if(r?.id===n.id)return;if(n.state!==`held`&&n.state!==`active`)throw this.callOperationError(e);let i=n.state===`held`;try{if(r!==void 0&&await r.hold(),this.assertGeneration(t,n.id),n.state===`held`&&await n.resume(),this.assertGeneration(t,n.id),!this.isManagedCall(n)||n.state!==`active`)throw this.callOperationError(n.id);this.commitActive(n,t)}catch(a){if(!this.isCurrentGeneration(t))throw this.callOperationError(n.id,a);if(r===void 0)throw this.callOperationError(e,a);try{let e=n.state===`active`;i&&e&&this.isManagedCall(n)&&await n.hold(),this.assertGeneration(t,n.id),r.state===`held`&&this.isManagedCall(r)&&await r.resume(),this.assertGeneration(t,r.id),r.state===`active`&&this.isManagedCall(r)&&this.commitActive(r,t)}catch(e){throw this.compensationError(r.id,n.id,a,e)}throw this.isManagedCall(r)&&r.state===`active`&&this.commitActive(r,t),this.callOperationError(n.id,{operation:a,restoredCallId:r.id})}}handleStateChanged(e,t,n){if(this.disposed)return;let r=this.callSessions.get(e.id);if(r!==void 0&&this.options.onCallStateChanged?.(e.id,r),this.events.emit(`call.stateChanged`,t),t.to===`active`&&this.activeCallId!==e.id){let t=this.getActiveCall();if(this.options.autoHoldPreviousCall===!0&&t!==void 0&&t.id!==e.id&&t.state===`active`){let n=this.operationGeneration;this.enqueueActiveOperation(n=>this.switchAutomaticActiveCall(t,e,n)).catch(e=>{this.isCurrentGeneration(n)&&this.events.emit(`error`,{error:e})})}else this.commitActive(e)}t.to===`held`&&this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),(t.to===`ended`||t.to===`failed`)&&(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.activeCallId===e.id&&this.automaticActiveTransition?.previous.id!==e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})),this.notifyCallTerminal(e.id),t.to===`ended`?this.events.emit(`call.ended`,{callId:e.id,reason:x(n)}):this.events.emit(`call.failed`,{callId:e.id,error:S(n,e.id)}))}async switchAutomaticActiveCall(e,t,n){this.automaticActiveTransition={previous:e,target:t};let r;try{if(this.assertGeneration(n,t.id),!this.isManagedCall(t)||t.state!==`active`)return;if(!this.isManagedCall(e)||e.state!==`active`){this.commitActive(t,n);return}if(await e.hold(),this.assertGeneration(n,t.id),!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}if(!this.isManagedCall(t)||t.state!==`active`)r=Error(`target call is no longer active`);else{this.commitActive(t,n);return}}catch(e){r=e}finally{this.automaticActiveTransition?.target.id===t.id&&(this.automaticActiveTransition=void 0)}if(!this.isCurrentGeneration(n))return;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}let i=await this.restoreAutomaticActiveCall(e,t,r,n);if(this.isCurrentGeneration(n)){if(i.error!==void 0)throw i.error;if(!this.isManagedCall(e)){this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,n);return}throw this.callOperationError(t.id,{operation:r,restoredCallId:e.id})}}async restoreAutomaticActiveCall(e,t,n,r){if(!this.isCurrentGeneration(r))return{};if(!this.isManagedCall(e))return this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{};let i;try{this.isManagedCall(t)&&t.state===`active`&&await t.hold(),this.assertGeneration(r,t.id),this.isManagedCall(e)&&e.state===`held`&&await e.resume(),this.assertGeneration(r,e.id)}catch(e){i=e}return this.isCurrentGeneration(r)?this.isManagedCall(e)?i===void 0?(e.state===`active`&&this.commitActive(e,r),{}):{error:this.compensationError(e.id,t.id,n,i)}:(this.isManagedCall(t)&&t.state===`active`&&this.commitActive(t,r),{}):{}}handleDisposed(e){this.disposed||(this.calls.delete(e.id),this.callSessions.delete(e.id),this.callOwners.delete(e.id),this.ownerLostCalls.delete(e.id),this.notifyCallTerminal(e.id),this.activeCallId===e.id&&(this.activeCallId=null,this.events.emit(`call.activeChanged`,{callId:null})))}commitActive(e,t=this.operationGeneration){this.isCurrentGeneration(t)&&this.isManagedCall(e)&&e.state===`active`&&this.activeCallId!==e.id&&(this.activeCallId=e.id,this.events.emit(`call.activeChanged`,{callId:e.id}))}handleIncoming(t){if(this.disposed)return;let n=v();if(this.options.platform===`mobile-web`){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:this.capabilityError(n)});return}let r=this.incomingSessionSnapshot;if(r===void 0||!r.policy.incomingEnabled||!this.effectiveCapabilities(r).has(`inbound`)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:this.capabilityError(n)});return}let i=t.from??t.id;if(this.calls.size+this.pendingDialCount>=this.callLimit(r)){this.terminateUnsupportedIncoming(t),this.events.emit(`error`,{error:new e.t(`CALL_ALREADY_EXISTS`,`call`,!1,{callId:n})});return}let a;try{a=new m({id:n,destination:i,platform:this.options.platform,incoming:!0,capabilities:this.effectiveCapabilities(r),session:t,onStateChanged:(e,t)=>this.handleStateChanged(a,e,t),onError:e=>this.events.emit(`error`,{error:e}),onDisposed:()=>this.handleDisposed(a)})}catch(e){this.events.emit(`error`,{error:this.callOperationError(n,e)});return}this.calls.set(a.id,a),this.callSessions.set(a.id,t),this.options.onCallCreated?.(a.id,t);try{a.beginIncoming(),this.events.emit(`call.incoming`,{callId:a.id,from:i})}catch(e){a.dispose(),this.events.emit(`error`,{error:this.callOperationError(a.id,e)})}}terminateUnsupportedIncoming(e){try{e.terminate()}catch{}}async holdActiveCallForNewCall(){if(this.options.autoHoldPreviousCall!==!0)return;let e=this.getActiveCall();if(e!==void 0&&e.state===`active`)return await e.hold(),e}enqueueActiveOperation(e){let t=this.operationGeneration,n=()=>this.isCurrentGeneration(t)?e(t):Promise.reject(this.callOperationError(``)),r=this.activeOperationPromise.then(n,n);return this.activeOperationPromise=r.catch(()=>void 0),r}isManagedCall(e){return!this.disposed&&this.calls.get(e.id)===e&&e.state!==`ended`&&e.state!==`failed`}isCurrentGeneration(e){return!this.disposed&&this.operationGeneration===e}assertGeneration(e,t){if(!this.isCurrentGeneration(e))throw this.callOperationError(t??``)}effectiveCapabilities(e){let t=new Set(e.capabilities);return this.options.platform===`mobile-web`&&(t.delete(`inbound`),t.delete(`hold`),t.delete(`blind_transfer`)),t}requireCapability(e,t,n){if(!this.effectiveCapabilities(e).has(t))throw this.capabilityError(n)}requireCall(e){let t=this.calls.get(e);if(t===void 0)throw this.callOperationError(e);return t}emitOwnershipChanged(e){this.events.emit(`call.ownershipChanged`,e)}notifyCallTerminal(e){let t=this.terminalOperations.get(e);if(t!==void 0)return t;if(this.terminalNotified.has(e))return Promise.resolve();this.terminalNotified.add(e);let n;try{n=this.options.onCallTerminal?.(e)}catch(t){this.events.emit(`error`,{error:this.callOperationError(e,t)});let n=Promise.reject(this.callOperationError(e,t));return this.terminalOperations.set(e,n),n.catch(()=>void 0),n}let r=Promise.resolve(n).catch(t=>{throw this.events.emit(`error`,{error:this.callOperationError(e,t)}),t});return this.terminalOperations.set(e,r),r.catch(()=>void 0),r}assertNotDisposed(){if(this.disposed)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}callOperationError(t,n){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t,cause:n})}capabilityError(t){return new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}compensationError(e,t,n,r){return this.callOperationError(e,{operation:n,rollback:r,originalCallId:e,targetCallId:t})}callLimit(e){let t=this.options.platform===`mobile-web`?1:2,n=this.options.maxConcurrentCalls??t;return Math.min(t,Math.max(1,n),Math.max(1,e.policy.maxConcurrentCalls))}dialOptions(e,t,n){return{iceServers:t.iceServers,extraHeaders:[`X-XCall-Call-ID: ${e}`,`X-XCall-Session-ID: ${t.sessionId}`],...n===void 0?{}:{type:n}}}dialError(t,n){return t instanceof e.t?new e.t(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t}):new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}},b=class{handlers=new Map;on(e,t){let n=this.handlers.get(e)??new Set,r=t;n.add(r),this.handlers.set(e,n);let i=!0;return()=>{i&&(i=!1,n.delete(r))}}emit(e,t){let n=this.handlers.get(e);n!==void 0&&[...n].forEach(e=>{try{e(t)}catch{}})}listenerCount(){return[...this.handlers.values()].reduce((e,t)=>e+t.size,0)}clear(){this.handlers.clear()}};function x(e){if(typeof e!=`object`||!e||!(`reason`in e))return`ended`;let t=e.reason;return typeof t==`string`&&t!==``?t:`ended`}function S(t,n){if(t instanceof e.t)return new e.t(t.code,t.category,t.retryable,{requestId:t.requestId,callId:n,cause:t.cause??t});if(typeof t==`object`&&t&&`error`in t){let r=t.error;if(r instanceof e.t)return new e.t(r.code,r.category,r.retryable,{requestId:r.requestId,callId:n,cause:r.cause??r});if(r instanceof Error)return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:r})}return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:n,cause:t})}var C=class{mediaDevices;createAudioElement;outputCapability;outputDeviceId;outputGeneration=0;outputTail;constructor(e={}){this.mediaDevices=e.mediaDevices===null?void 0:e.mediaDevices??w(),this.createAudioElement=e.createAudioElement}async requestPermission(e={}){let t=this.requireMediaDevices(),n;try{n=await t.getUserMedia({audio:e})}catch(e){throw E(e)}T(n)}async getDevices(){if(this.mediaDevices===void 0)return[];try{return(await this.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`||e.kind===`audiooutput`&&this.supportsOutputSelection())}catch(e){throw te(e)}}getCapabilities(){return{input:this.mediaDevices!==void 0,output:this.supportsOutputSelection()}}supportsOutputSelection(){if(this.outputCapability!==void 0)return this.outputCapability;let e=this.createAudioElementSafely();return this.outputCapability=e!==void 0&&typeof e.setSinkId==`function`,this.outputCapability}async setOutputDevice(t,n){if(!this.supportsOutputSelection())throw new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);this.outputDeviceId=t;let r=++this.outputGeneration;n!==void 0&&await this.enqueueOutput(async()=>{r===this.outputGeneration&&await this.applyOutputDevice(t,n)})}async applyConfiguredOutputDevice(e){if(this.outputDeviceId===void 0||e===void 0)return;let t=this.outputDeviceId,n=this.outputGeneration;await this.enqueueOutput(async()=>{n===this.outputGeneration&&await this.applyOutputDevice(t,e)})}getOutputDeviceId(){return this.outputDeviceId}async applyOutputDevice(t,n){let r=n;if(typeof r.setSinkId!=`function`)throw new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);try{await r.setSinkId(t)}catch(e){throw ne(e)}}enqueueOutput(e){let t=this.outputTail,n=t===void 0?e():t.then(e,e),r=n.catch(()=>void 0);return this.outputTail=r,r.then(()=>{this.outputTail===r&&(this.outputTail=void 0)}),n}async openInputStream(e){let t=this.requireMediaDevices();try{return await t.getUserMedia({audio:{deviceId:{exact:e}}})}catch(e){throw ee(e)}}requireMediaDevices(){if(this.mediaDevices===void 0)throw new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return this.mediaDevices}createAudioElementSafely(){if(this.createAudioElement!==void 0)try{return this.createAudioElement()}catch{return}if(typeof document<`u`)try{return document.createElement(`audio`)}catch{return}}};function w(){return globalThis.navigator?.mediaDevices}function T(e){let t;try{t=e.getTracks()}catch{return}t.forEach(e=>{try{e.stop()}catch{}})}function ee(t){let n=D(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function E(t){let n=D(t);return n===`NotFoundError`||n===`OverconstrainedError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotReadableError`||n===`AbortError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function te(t){let n=D(t);return n===`NotFoundError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function ne(t){let n=D(t);return n===`NotFoundError`?new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{cause:t}):n===`NotAllowedError`||n===`SecurityError`?new e.t(`MEDIA_PERMISSION_DENIED`,`media`,!1,{cause:t}):n===`AbortError`||n===`NotReadableError`?new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{cause:t}):new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{cause:t})}function D(e){if(typeof e!=`object`||!e||!(`name`in e))return;let t=e.name;return typeof t==`string`?t:void 0}var O=class{createAudioElement;bindings=new Map;audioOwners=new Map;trackOwners=new Map;generations=new Map;pendingPlays=new Map;constructor(e=k){this.createAudioElement=e}async bind(t,n){let r=this.bindings.get(t);if(r?.stream===n)return;let i=A(t,n),a;try{a=this.createAudioElement()}catch(n){throw j(i,this.trackOwners),new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t,cause:n})}let o=this.audioOwners.get(a);if(o!==void 0&&o!==t)throw j(i,this.trackOwners),new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});try{a.autoplay=!0,a.playsInline=!0}catch(n){throw j(i,this.trackOwners),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}try{a.srcObject=n}catch(n){throw j(i,this.trackOwners),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:n})}this.acquireTracks(i),r!==void 0&&this.releaseBinding(r,r.audio!==a);let s=this.nextGeneration(t);this.audioOwners.set(a,t);let c={callId:t,audio:a,stream:n,tracks:i,generation:s};this.bindings.set(t,c),this.beginPlay(t);try{await a.play()}catch(n){if(!this.isCurrent(t,s))return;throw new e.t(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,s)}async play(t){let n=this.bindings.get(t);if(n===void 0)throw new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t});let r=n.generation;this.beginPlay(t);try{await n.audio.play()}catch(n){if(!this.isCurrent(t,r))return;throw new e.t(`MEDIA_PLAYBACK_BLOCKED`,`media`,!1,{callId:t,cause:n})}finally{this.finishPlay(t)}this.isCurrent(t,r)}getAudioElement(e){return this.bindings.get(e)?.audio}getResourceCounts(){return{tracks:this.trackOwners.size,audioElements:this.audioOwners.size}}release(e){this.nextGeneration(e);let t=this.bindings.get(e);t!==void 0&&this.releaseBinding(t),this.cleanupGeneration(e)}releaseAll(){[...this.bindings.keys()].forEach(e=>this.release(e))}releaseBinding(e,t=!0){if(this.bindings.get(e.callId)===e&&this.bindings.delete(e.callId),this.audioOwners.get(e.audio)===e.callId&&this.audioOwners.delete(e.audio),t)try{e.audio.srcObject=null}catch{}e.tracks.forEach(e=>this.releaseTrack(e))}acquireTracks(e){e.forEach(e=>this.trackOwners.set(e,(this.trackOwners.get(e)??0)+1))}releaseTrack(e){let t=this.trackOwners.get(e);if(t===void 0||t<=1){this.trackOwners.delete(e),N(e);return}this.trackOwners.set(e,t-1)}beginPlay(e){this.pendingPlays.set(e,(this.pendingPlays.get(e)??0)+1)}finishPlay(e){let t=this.pendingPlays.get(e)??0;t<=1?this.pendingPlays.delete(e):this.pendingPlays.set(e,t-1),this.cleanupGeneration(e)}nextGeneration(e){let t=(this.generations.get(e)??0)+1;return this.generations.set(e,t),t}cleanupGeneration(e){!this.bindings.has(e)&&!this.pendingPlays.has(e)&&this.generations.delete(e)}isCurrent(e,t){return this.generations.get(e)===t&&this.bindings.get(e)?.generation===t}};function k(){if(typeof document>`u`)throw new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1);return document.createElement(`audio`)}function A(t,n){try{return[...new Set(n.getAudioTracks())].filter(e=>e.kind===`audio`)}catch(r){try{return[...new Set(n.getTracks())].filter(e=>e.kind===`audio`)}catch(i){throw M(n),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t,cause:r??i})}}}function j(e,t){e.forEach(e=>{(t.get(e)??0)===0&&N(e)})}function M(e){try{[...new Set(e.getTracks())].filter(e=>e.kind===`audio`).forEach(N)}catch{}}function N(e){try{e.stop()}catch{}}var P=class{deviceManager;remoteAudio;getActiveCall;createRemoteStream;calls=new Map;resources=new Set;inputOperations=new Map;senderQueues=new Map;releaseOperations=new Map;callReleaseOperations=new Map;releaseErrors=new WeakMap;releaseAllOperation;disposeOperation;disposing=!1;disposed=!1;constructor(e={}){let t={mediaDevices:e.mediaDevices,createAudioElement:e.createAudioElement};this.deviceManager=new C(t),this.remoteAudio=new O(e.createAudioElement),this.getActiveCall=e.getActiveCall,this.createRemoteStream=e.createRemoteStream??V}requestPermission(e){return this.assertNotDisposed(),this.deviceManager.requestPermission(e)}getDevices(){return this.assertNotDisposed(),this.deviceManager.getDevices()}getCapabilities(){return this.assertNotDisposed(),this.deviceManager.getCapabilities()}supportsOutputSelection(){return this.assertNotDisposed(),this.deviceManager.supportsOutputSelection()}registerCallMedia(e,t){this.assertNotDisposed();let n=this.calls.get(e);n!==void 0&&this.releaseResource(n).catch(e=>{this.releaseErrors.set(n,e)});let r=F(t)?t:{peerConnection:t},i={callId:e,peerConnection:r.peerConnection,senders:new Map,localTracks:new Set,pendingTracks:new Set,generation:1,released:!1,peerClosed:!1};if(this.captureSenders(i,r.getSenderKind),this.resources.add(i),r.localTracks?.forEach(e=>{e.kind===`audio`&&i.localTracks.add(e)}),this.calls.set(e,i),r.trackSource!==void 0)try{i.trackSourceUnsubscribe=r.trackSource.onTrack(e=>this.handleTrackEvent(i,e))}catch{}return async()=>{let e=this.releaseOperations.get(i);if(e!==void 0)await e;else if(this.releaseErrors.has(i))throw this.releaseErrors.get(i);else await this.releaseResource(i);let t=this.releaseErrors.get(i);if(t!==void 0)throw t}}async setInputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.();this.assertActiveCall(n),this.assertDeviceSelectionCapability(n);let r=this.ensureCallMedia(n),i=(this.inputOperations.get(n.callId)??Promise.resolve()).then(()=>this.performInputSwitch(e,n,r),()=>this.performInputSwitch(e,n,r));this.inputOperations.set(n.callId,i);try{await i}finally{this.inputOperations.get(n.callId)===i&&this.inputOperations.delete(n.callId)}}setOutputDevice(e,t){this.assertNotDisposed();let n=t??this.getActiveCall?.()?.callId,r=n===void 0?void 0:this.remoteAudio.getAudioElement(n);return this.deviceManager.setOutputDevice(e,r)}async bindRemoteTrack(e,t){this.assertNotDisposed();let n;try{await this.remoteAudio.bind(e,t)}catch(e){n=e}let r;try{await this.deviceManager.applyConfiguredOutputDevice(this.remoteAudio.getAudioElement(e))}catch(e){r=e}if(n!==void 0)throw n;if(r!==void 0)throw r}playRemoteAudio(e){return this.assertNotDisposed(),this.remoteAudio.play(e)}getResourceCounts(){let e=new Set;this.resources.forEach(t=>{t.localTracks.forEach(t=>e.add(t)),t.pendingTracks.forEach(t=>e.add(t))});let t=this.remoteAudio.getResourceCounts();return{listeners:[...this.resources].filter(e=>e.trackSourceUnsubscribe!==void 0).length,tracks:e.size+t.tracks,peerConnections:this.resources.size,audioElements:t.audioElements}}releaseResource(t){let n=this.releaseOperations.get(t);if(n!==void 0)return n;if(!this.resources.has(t))return Promise.resolve();let r=t.callId;this.remoteAudio.release(r),this.releaseErrors.delete(t),this.calls.get(r)===t&&this.calls.delete(r),t.generation+=1,t.released=!0,this.unsubscribeTrackSource(t);let i=new Set([...t.localTracks,...t.pendingTracks]),a=[...t.senders.values()].filter(e=>e.audio).map(e=>({senderResource:e,promise:this.enqueueSender(t,e,()=>L(e.sender),!0)})),o=Promise.all(a.map(async e=>{try{return await e.promise,{senderResource:e.senderResource,cause:void 0}}catch(t){return{senderResource:e.senderResource,cause:t}}})).then(async n=>{let a=new Set,o=[];if(n.forEach(e=>{if(e.cause!==void 0){o.push(e.cause);let t=I(e.senderResource.sender);t?.kind===`audio`&&a.add(t);return}let t=I(e.senderResource.sender);t?.kind===`audio`&&i.add(t)}),i.forEach(e=>{a.has(e)||B(e)}),o.length>0)throw t.localTracks.clear(),t.pendingTracks.clear(),a.forEach(e=>t.localTracks.add(e)),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:o[0]});if(!t.peerClosed&&t.peerConnection.close!==void 0)try{await t.peerConnection.close(),t.peerClosed=!0}catch(n){let i=[...t.senders.values()].map(e=>I(e.sender)).find(e=>e?.kind===`audio`);throw t.localTracks.clear(),t.pendingTracks.clear(),i!=null&&t.localTracks.add(i),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:r,cause:n})}t.localTracks.clear(),t.pendingTracks.clear(),t.senders.clear(),this.resources.delete(t),this.releaseUnusedSenderQueues()}).catch(e=>{throw this.releaseErrors.set(t,e),this.calls.get(r)===void 0&&this.calls.set(r,t),e}).finally(()=>{this.releaseOperations.get(t)===o&&this.releaseOperations.delete(t)});return this.releaseOperations.set(t,o),o}releaseCall(e){let t=this.callReleaseOperations.get(e);if(t!==void 0)return t;let n=[...this.resources].filter(t=>t.callId===e);if(n.length===0)return Promise.resolve();let r=Promise.all(n.map(async e=>{try{return await this.releaseResource(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.callReleaseOperations.get(e)===r&&this.callReleaseOperations.delete(e)});return this.callReleaseOperations.set(e,r),r}releaseAll(){if(this.releaseAllOperation!==void 0)return this.releaseAllOperation;this.remoteAudio.releaseAll();let e=new Set([...this.resources].map(e=>e.callId)),t=Promise.all([...e].map(async e=>{try{return await this.releaseCall(e),{cause:void 0}}catch(e){return{cause:e}}})).then(e=>{let t=e.find(e=>e.cause!==void 0)?.cause;if(t!==void 0)throw t}).finally(()=>{this.releaseAllOperation===t&&(this.releaseAllOperation=void 0)});return this.releaseAllOperation=t,t}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposing=!0;let e=this.releaseAll(),t=this.waitForInputOperations(),n=Promise.allSettled([e,t]).then(e=>{let t=e.find(e=>e.status===`rejected`);if(t?.status===`rejected`)throw t.reason;this.inputOperations.clear(),this.disposed=!0,this.disposing=!1}).finally(()=>{this.disposeOperation===n&&!this.disposed&&(this.disposeOperation=void 0),!this.disposed&&this.disposeOperation===void 0&&(this.disposing=!1)});return this.disposeOperation=n,n}async waitForInputOperations(){let e=[...this.inputOperations.values()];e.length!==0&&await Promise.allSettled(e)}async performInputSwitch(t,n,r){if(this.assertActiveCall(n),this.assertDeviceSelectionCapability(n),!this.isCurrentResource(r)||n.peerConnection!==r.peerConnection)throw this.callOperationError(n.callId);let i=this.findAudioSender(r),a=I(i.sender),o=r.generation,s=await this.deviceManager.openInputStream(t),c;try{c=s.getTracks()}catch(t){throw R(s),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let l;try{l=s.getAudioTracks()}catch(t){throw z(c),new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:n.callId,cause:t})}let u=l[0];if(u===void 0)throw z(c),new e.t(`MEDIA_DEVICE_NOT_FOUND`,`media`,!1,{callId:n.callId});if(!this.canCommitInputSwitch(n,r,i,a,o))throw z(c),this.callOperationError(n.callId);c.forEach(e=>r.pendingTracks.add(e)),r.pendingTracks.add(u);try{await this.enqueueSender(r,i,()=>i.sender.replaceTrack(u))}catch(t){throw r.released?this.callOperationError(n.callId):(r.released||(c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),await this.rollbackSender(r,i,a,u),z(c)),new e.t(`MEDIA_DEVICE_IN_USE`,`media`,!0,{callId:n.callId,cause:t}))}if(!this.canCommitInputSwitch(n,r,i,u,o)){if(!r.released)try{await this.enqueueSender(r,i,()=>I(i.sender)===u?L(i.sender):Promise.resolve()),c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),z(c)}catch(t){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!0,{callId:n.callId,cause:t})}throw this.callOperationError(n.callId)}c.forEach(e=>r.pendingTracks.delete(e)),r.pendingTracks.delete(u),r.localTracks.add(u),a!==null&&a!==u&&(r.localTracks.delete(a),B(a)),c.forEach(e=>{e!==u&&B(e)})}ensureCallMedia(e){let t=this.calls.get(e.callId);if(t!==void 0&&t.peerConnection===e.peerConnection)return t;if(e.peerConnection===void 0)throw this.capabilityError(e.callId);this.registerCallMedia(e.callId,e.peerConnection);let n=this.calls.get(e.callId);if(n===void 0)throw this.callOperationError(e.callId);return n}captureSenders(t,n){let r;try{r=t.peerConnection.getSenders()}catch(n){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}r.forEach(r=>{let i=I(r),a;try{a=n?.(r)??r.senderKind??r.kind}catch(n){throw new e.t(`SDK_INTERNAL_ERROR`,`internal`,!1,{callId:t.callId,cause:n})}t.senders.set(r,{sender:r,audio:a===`audio`||a===void 0&&i?.kind===`audio`,queue:this.senderQueues.get(r)??this.createSenderQueue(r)}),i?.kind===`audio`&&t.localTracks.add(i)})}findAudioSender(e){let t=[...e.senders.values()].find(e=>e.audio&&(I(e.sender)?.kind===`audio`||I(e.sender)===null));if(t===void 0)throw this.capabilityError(e.callId);return t}handleTrackEvent(e,t){if(!this.isCurrentResource(e)||t.track.kind!==`audio`)return;let n=t.streams[0]??this.createRemoteStream(t.track);n!==void 0&&this.bindRemoteTrack(e.callId,n).catch(()=>void 0)}canCommitInputSwitch(e,t,n,r,i){if(this.disposed||!this.isCurrentResource(t,i)||e.state!==`active`||e.peerConnection!==t.peerConnection||!t.senders.has(n.sender))return!1;try{if(!t.peerConnection.getSenders().includes(n.sender))return!1}catch{return!1}return I(n.sender)===r}enqueueSender(e,t,n,r=!1){t.queue.pending+=1;let i=t.queue.chain.then(async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()},async()=>{if(e.released&&!r)throw this.callOperationError(e.callId);return n()}),a=i.finally(()=>{--t.queue.pending});return t.queue.chain=a.catch(()=>void 0),i}createSenderQueue(e){let t={chain:Promise.resolve(),pending:0};return this.senderQueues.set(e,t),t}releaseUnusedSenderQueues(){let e=new Set;this.resources.forEach(t=>t.senders.forEach(t=>e.add(t.sender))),this.senderQueues.forEach((t,n)=>{t.pending===0&&!e.has(n)&&this.senderQueues.delete(n)})}async rollbackSender(e,t,n,r){e.released||I(t.sender)!==r||await this.enqueueSender(e,t,()=>t.sender.replaceTrack(n)).catch(()=>void 0)}isCurrentResource(e,t=e.generation){return!this.disposed&&this.calls.get(e.callId)===e&&e.generation===t}unsubscribeTrackSource(e){let t=e.trackSourceUnsubscribe;if(e.trackSourceUnsubscribe=void 0,t!==void 0)try{t()}catch{}}assertActiveCall(t){if(t===void 0||t.state!==`active`)throw new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t?.callId})}assertDeviceSelectionCapability(e){if(e.capabilities===void 0||!e.capabilities.has(`device_selection`))throw this.capabilityError(e.callId)}capabilityError(t){return new e.t(`CAPABILITY_NOT_SUPPORTED`,`capability`,!1,{callId:t})}callOperationError(t){return new e.t(`CALL_OPERATION_NOT_ALLOWED`,`call`,!1,{callId:t})}assertNotDisposed(){if(this.disposed||this.disposing)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function F(e){return`peerConnection`in e}function I(e){try{return e.track}catch{return null}}function L(e){try{return e.replaceTrack(null)}catch(e){return Promise.reject(e)}}function R(e){try{z(e.getTracks())}catch{}}function z(e){e.forEach(B)}function B(e){try{e.stop()}catch{}}function V(e){if(typeof MediaStream<`u`)try{return new MediaStream([e])}catch{return}}function H(t,n={}){let r=new Map,i=new Map,a=new Set,o=n.ownershipRequired===!0,s=!1,c=!1,l,u=()=>t(),d=new P({getActiveCall:u});return{publicMedia:{requestPermission:()=>(f(),d.requestPermission()),getDevices:()=>(f(),d.getDevices()),getCapabilities:()=>(f(),d.getCapabilities()),supportsOutputSelection:()=>(f(),d.supportsOutputSelection()),setInputDevice:e=>(f(),d.setInputDevice(e,u())),setOutputDevice:e=>(f(),d.setOutputDevice(e)),playRemoteAudio:e=>(f(),d.playRemoteAudio(e)),releaseAll:()=>(f(),d.releaseAll())},registerCall(e,t){s||c||!U(t)||(i.set(e,t),(!o||a.has(e))&&p(e,t))},async setCallOwnership(e,t){if(s)return;if(t!==`owned`){a.delete(e),await d.releaseCall(e),r.delete(e);return}a.add(e);let n=i.get(e);n!==void 0&&p(e,n)},contextFor(e,t,n){let i=r.get(e);if(i!==void 0)return{callId:e,state:t,capabilities:n,peerConnection:i.peerConnection}},async releaseCall(e){s||(await d.releaseCall(e),r.delete(e),i.delete(e),a.delete(e))},releaseAll:async()=>{await d.releaseAll(),r.clear(),i.clear(),a.clear()},getResourceCounts:()=>d.getResourceCounts(),dispose:()=>{if(l!==void 0)return l;c=!0;let e=d.dispose().then(()=>{s=!0,c=!1,r.clear(),i.clear(),a.clear()}).finally(()=>{l===e&&!s&&(l=void 0,c=!1)});return l=e,e}};function f(){if(s)throw new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}function p(e,t){if(!U(t)||typeof t.getMediaRegistration!=`function`)return;let n=t.getMediaRegistration();if(W(n)&&r.get(e)?.peerConnection!==n.peerConnection){r.set(e,n);try{d.registerCallMedia(e,n)}catch{r.delete(e)}}}}function U(e){return typeof e==`object`&&!!e}function W(e){return typeof e==`object`&&!!e&&`peerConnection`in e&&typeof e.peerConnection==`object`&&e.peerConnection!==null}var G=1e3,K=3e4;function q(e,t=Math.random){let n=Math.min(K,G*2**Math.max(0,Math.floor(e))),r=Math.min(1,Math.max(0,t()));return Math.round(n*(1+r*.2))}var J=class{recover;random;isOnline;onAttempt;attempt=0;pendingTimer;running=!1;online=!0;generation=0;disposed=!1;restartAfterRun=!1;constructor(e){this.recover=e.recover,this.random=e.random??Math.random,this.isOnline=e.isOnline??(()=>!0),this.onAttempt=e.onAttempt}start(){if(this.disposed||!this.online||!this.isOnline()||this.pendingTimer!==void 0||this.running)return;let e=this.generation,t=q(this.attempt,this.random);this.pendingTimer=setTimeout(()=>{this.pendingTimer=void 0,this.run(e)},t)}notifyOffline(){this.disposed||(this.online=!1,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}notifyOnline(){this.disposed||(this.online=!0,this.running&&(this.restartAfterRun=!0),this.start())}cancel(){this.disposed||(this.generation+=1,this.clearPendingTimer(),this.attempt=0,this.restartAfterRun=!1)}dispose(){this.disposed||(this.disposed=!0,this.generation+=1,this.clearPendingTimer(),this.restartAfterRun=!1)}getTimerCount(){return this.pendingTimer===void 0?0:1}async run(e){if(this.disposed||!this.online||e!==this.generation||this.running)return;this.running=!0;try{this.onAttempt?.(this.attempt)}catch{}let t=!1;try{await this.recover(),this.isCurrent(e)&&(this.attempt=0)}catch{this.isCurrent(e)&&(this.attempt+=1,t=!0)}finally{this.running=!1}this.restartAfterRun?(this.restartAfterRun=!1,this.isCurrent(this.generation)&&this.start()):t&&this.isCurrent(e)&&this.start()}isCurrent(e){return!this.disposed&&this.online&&e===this.generation&&this.isOnline()}clearPendingTimer(){this.pendingTimer!==void 0&&(clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}},Y=class r{media;options;api;suppliedSip;sip;events=new n;mediaBridge;reconnect;diagnostics;callManager;session;state=`idle`;initialized=!1;disposed=!1;intentionalDisconnect=!1;deferredRebuild=!1;detectedPlatform;support;acceptingEvents=!0;connectOperation;disconnectOperation;refreshOperation;disposeOperation;refreshTimer;lifecycleGeneration=0;managerUnsubscribers=[];sipUnsubscribe;networkUnsubscribers=[];sessionDeleteOperations=new Map;deletedSessions=new Set;ownedSessionIds=new Set;terminalReleaseOperations=new Map;tokenRequest={};constructor(e){this.options=e;let n=e=>this.options.tokenProvider({...e,...this.tokenRequest});this.api=e.api===void 0?new d({baseUrl:e.baseUrl??``,tokenProvider:n}):re(e.api),this.suppliedSip=e.sip===void 0?void 0:ie(e.sip),this.mediaBridge=H(()=>this.getActiveMediaContext()),this.media=this.mediaBridge.publicMedia,this.reconnect=new J({recover:()=>this.recoverConnection(),onAttempt:e=>{this.disposed||this.events.emit(`connection.reconnecting`,{attempt:e})}}),this.diagnostics=new t.t({getSnapshot:()=>this.createDiagnosticsSnapshot(),getPermission:()=>this.readMicrophonePermission(),getDeviceNames:async()=>(await this.media.getDevices()).map(e=>e.label).filter(e=>e!==``)})}static async checkSupport(){let e=typeof navigator<`u`&&navigator.mediaDevices!==void 0,t=typeof WebSocket<`u`,n=Z(typeof navigator<`u`?navigator.userAgent:``);return{supported:e&&t,platform:n,hasMediaDevices:e,hasWebSocket:t,...e&&t?{}:{reason:`当前运行环境缺少 WebPhone 所需的浏览器能力`}}}async initialize(){if(this.assertNotDisposed(),this.initialized)return;let e=await r.checkSupport();this.support=e,this.options.platform===void 0&&(e.platform===`web`||e.platform===`mobile-web`)&&(this.detectedPlatform=e.platform),this.assertNotDisposed(),this.initialized=!0}connect(e){this.assertNotDisposed();let t=e?.extension?.trim();if(this.tokenRequest=t===void 0||t===``?{}:{extension:t},this.api.invalidateToken?.(),this.connectOperation!==void 0)return this.connectOperation;if(this.state===`connected`)return Promise.resolve();let n=this.lifecycleGeneration,r=this.performConnect(n).finally(()=>{this.connectOperation===r&&(this.connectOperation=void 0)});return this.connectOperation=r,r}disconnect(){if(this.assertNotDisposed(),this.disconnectOperation!==void 0)return this.disconnectOperation;if(this.state===`idle`&&this.connectOperation===void 0||this.state===`disconnected`&&this.connectOperation===void 0)return Promise.resolve();this.lifecycleGeneration+=1,this.acceptingEvents=!1;let e=this.performDisconnect().finally(()=>{this.disconnectOperation===e&&(this.disconnectOperation=void 0)});return this.disconnectOperation=e,e}dispose(){if(this.disposeOperation!==void 0)return this.disposeOperation;this.disposed=!0,this.lifecycleGeneration+=1,this.intentionalDisconnect=!0,this.acceptingEvents=!1,this.reconnect.dispose(),this.clearRefreshTimer(),this.detachNetworkListeners(),this.state=`disconnected`,this.diagnostics.log(`info`,`connection.stateChanged`,{state:`disconnected`}),this.detachSipListener(),this.detachManagerListeners();let e=!1,t=this.performDispose().then(()=>{e=!0}).finally(()=>{this.disposeOperation===t&&!e&&(this.disposeOperation=void 0)});return this.disposeOperation=t,t}recover(){return this.assertNotDisposed(),this.recoverConnection()}dial(t){this.assertConnected();let n=this.callManager,r=this.session;if(n===void 0||r===void 0)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1);return n.dial(t,r)}answer(t,n){this.assertConnected();let r=this.callManager,i=this.session;if(r===void 0||i===void 0)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1);return r.answer(t,i,n)}setActiveCall(t){this.assertConnected();let n=this.callManager;if(n===void 0)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1);return n.setActiveCall(t)}getCalls(){return this.callManager?.getCalls()??[]}getActiveCall(){return this.callManager?.getActiveCall()}getAgent(){return this.session?.agent}getDiagnostics(e={}){return this.diagnostics.getReport(e)}async setAgentStatus(e){this.assertNotDisposed(),await this.api.setAgentStatus({status:e,reason:``}),this.disposed||this.events.emit(`agent.statusChanged`,{status:e})}on(e,t){return this.disposed?()=>void 0:this.events.on(e,t)}off(e,t){this.events.off(e,t)}async performConnect(e){let t,n,r;try{await this.initialize(),this.assertGeneration(e);let i=this.resolvePlatform();this.intentionalDisconnect=!1,this.acceptingEvents=!0,this.setConnectionState(`connecting`),t=await this.api.createSession({sdkVersion:`0.1.0`,platform:i===`mobile-web`?`mobile_web`:`web`,...this.options.locale===void 0?{}:{locale:this.options.locale},requestedCapabilities:[...this.options.requestedCapabilities??ce(i)]}),this.ownedSessionIds.add(t.sessionId),this.assertGeneration(e),n=await this.getSip(),this.assertGeneration(e),this.session=t;let a=this.callManager??this.createCallManager(n,t,i);this.callManager===void 0&&(r=a),a.updateSession(t),this.callManager=a,this.attachSipListener(n),this.attachNetworkListeners(),await n.connect(t),this.assertGeneration(e),this.setConnectionState(`connected`),this.events.emit(`connection.registered`,{registered:!0}),this.scheduleRefresh(t)}catch(i){if(await this.rollbackConnect(t,n,r),this.disposed)throw this.disposedError();if(e!==this.lifecycleGeneration)throw i;let a=Q(i,`REGISTRATION_FAILED`,`registration`,!0);throw this.setConnectionState(`failed`),this.events.emit(`connection.failed`,{error:a}),a}}async performDisconnect(){let e,t=this.connectOperation;if(t!==void 0)try{await t}catch(t){$(t)||(e??=t)}let n=this.refreshOperation;if(n!==void 0)try{await n}catch(t){$(t)||(e??=t)}this.reconnect.cancel(),this.clearRefreshTimer(),this.intentionalDisconnect=!0,this.detachSipListener(),this.detachManagerListeners();let r=this.callManager,i=this.sip;this.callManager=void 0;try{await r?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{i!==void 0&&await i.disconnect()}catch(t){e??=t}this.session=void 0;try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.disposed||(this.acceptingEvents=!0,this.setConnectionState(`disconnected`)),e!==void 0)throw e}createCallManager(e,t,n){let r=new y({sip:e,platform:n,session:t,maxConcurrentCalls:this.options.maxConcurrentCalls,autoHoldPreviousCall:this.options.autoHoldPreviousCall,onCallCreated:(e,t)=>this.handleCallCreated(e,t),onCallStateChanged:(e,t)=>this.handleCallStateChanged(e,t),onCallTerminal:e=>this.handleCallTerminal(e)});return this.bindManagerEvents(r),r}async rollbackConnect(e,t,n){if(n!==void 0){this.detachManagerListeners(),this.callManager===n&&(this.callManager=void 0);try{await n.dispose({terminateCalls:!0})}catch{}}if(t!==void 0){this.detachSipListener();try{await t.disconnect()}catch{}}if(this.session===e&&(this.session=void 0),e!==void 0)try{await this.deleteSession(e.sessionId)}catch{}}async performDispose(){let e,t=[this.connectOperation,this.disconnectOperation,this.refreshOperation].filter(e=>e!==void 0);for(let n of t)try{await n}catch(t){$(t)||(e??=t)}let n=this.callManager;this.callManager=void 0;try{await n?.dispose({terminateCalls:!0})}catch(t){e??=t}try{await this.awaitMediaReleaseBarriers()}catch(t){e??=t}try{await this.media.releaseAll()}catch(t){ae(t)||(e??=t)}try{await this.mediaBridge.dispose()}catch(t){e??=t}try{await this.sip?.dispose()}catch(t){e??=t}try{await this.deleteOwnedSessions()}catch(t){e??=t}if(this.session=void 0,this.sipUnsubscribe=void 0,this.events.clear(),e!==void 0)throw e}async awaitMediaReleaseBarriers(){let e;for(let[t,n]of[...this.terminalReleaseOperations])try{await n,this.terminalReleaseOperations.delete(t)}catch(n){try{await this.mediaBridge.releaseCall(t),this.terminalReleaseOperations.delete(t)}catch(t){e??=t??n}}if(e!==void 0)throw e}detachSipListener(){let e=this.sipUnsubscribe;this.sipUnsubscribe=void 0;try{e?.()}catch{}}detachManagerListeners(){this.managerUnsubscribers.splice(0).forEach(e=>{try{e()}catch{}})}bindManagerEvents(e){[`call.created`,`call.incoming`,`call.stateChanged`,`call.activeChanged`,`call.ended`,`call.failed`,`error`].forEach(t=>{let n=e.on(t,e=>{this.acceptingEvents&&!this.disposed&&(this.diagnostics.log(t===`error`||t===`call.failed`?`error`:`info`,String(t),e),this.events.emit(t,e))});this.managerUnsubscribers.push(n)})}handleCallCreated(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallStateChanged(e,t){this.acceptingEvents&&!this.disposed&&this.mediaBridge.registerCall(e,t)}handleCallTerminal(e){let t=this.startTerminalRelease(e);return this.deferredRebuild&&!this.hasNonTerminalCalls()&&this.startDeferredRecovery(),t}startTerminalRelease(e){let t=this.terminalReleaseOperations.get(e);if(t!==void 0)return t;let n=this.mediaBridge.releaseCall(e).then(()=>{this.terminalReleaseOperations.get(e)===n&&this.terminalReleaseOperations.delete(e)}).catch(t=>{throw this.acceptingEvents&&!this.disposed&&this.events.emit(`error`,{error:Q(t,`SDK_INTERNAL_ERROR`,`internal`,!0,e)}),t});return this.terminalReleaseOperations.set(e,n),n}async startDeferredRecovery(){try{await this.awaitMediaReleaseBarriers(),this.deferredRebuild&&!this.hasNonTerminalCalls()&&!this.disposed&&(this.deferredRebuild=!1,this.clearRefreshTimer(),this.reconnect.start())}catch{this.disposed||this.reconnect.start()}}async refreshAndRebuild(){if(this.refreshOperation!==void 0)return this.refreshOperation;let e=this.performRefreshAndRebuild().finally(()=>{this.refreshOperation===e&&(this.refreshOperation=void 0)});return this.refreshOperation=e,e}async performRefreshAndRebuild(){if(this.disposed||this.session===void 0)return;let e=this.lifecycleGeneration,t=this.session;try{let n=await this.api.refreshSession(t.sessionId);if(!this.isCurrentGeneration(e)||this.session!==t)return;if(this.session=n,this.callManager?.updateSession(n),this.events.emit(`token.refreshed`,{expiresAt:n.expiresAt}),this.hasNonTerminalCalls()){this.deferredRebuild=!0,this.scheduleRefresh(n);return}let r=await this.getSip();if(!this.isCurrentGeneration(e))return;await r.connect(n),this.isCurrentGeneration(e)&&(this.deferredRebuild=!1,this.setConnectionState(`connected`),this.scheduleRefresh(n))}catch(n){if(!this.isCurrentGeneration(e))return;throw this.handleRefreshFailure(t,n),n}}handleRefreshFailure(e,t){if(this.disposed)return;let n=Q(t,`NETWORK_OFFLINE`,`network`,!0);this.events.emit(`token.expiring`,{expiresAt:e.expiresAt}),this.events.emit(`error`,{error:n}),this.deferredRebuild=!0,this.hasNonTerminalCalls()||this.reconnect.start()}scheduleRefresh(e){this.clearRefreshTimer();let t=e.expiresAt*1e3-Date.now()-6e4,n=Math.max(1e3,t);this.refreshTimer=setTimeout(()=>{this.refreshTimer=void 0,this.refreshAndRebuild().catch(()=>void 0)},n)}async recoverConnection(){this.disposed||this.hasNonTerminalCalls()||(await this.awaitMediaReleaseBarriers(),await this.refreshAndRebuild())}async getSip(){if(this.sip!==void 0)return this.sip;if(this.suppliedSip!==void 0)return this.sip=this.suppliedSip,this.sip;let[e,t]=await Promise.all([Promise.resolve().then(()=>require("./createJsSipFactory-2X4FBIU2.cjs")),Promise.resolve().then(()=>require("./JsSipAdapter-jtGdoXrm.cjs"))]);return this.sip=new t.JsSipAdapter(e.createJsSipFactory(),this.options.baseUrl),this.sip}attachSipListener(e){this.sipUnsubscribe===void 0&&e.onConnectionStateChanged!==void 0&&(this.sipUnsubscribe=e.onConnectionStateChanged((e,t)=>{if(!(this.disposed||this.intentionalDisconnect||!this.acceptingEvents)){if(e===`registered`){this.setConnectionState(`connected`);return}this.state===`connected`&&(this.setConnectionState(`reconnecting`),this.reconnect.start(),t!==void 0&&this.events.emit(`error`,{error:Q(t,`SIP_WS_UNAVAILABLE`,`registration`,!0)}))}}))}attachNetworkListeners(){if(this.networkUnsubscribers.length>0||typeof window>`u`)return;let e=window,t=()=>this.reconnect.notifyOnline(),n=()=>this.reconnect.notifyOffline();e.addEventListener(`online`,t),e.addEventListener(`offline`,n),this.networkUnsubscribers=[()=>e.removeEventListener(`online`,t),()=>e.removeEventListener(`offline`,n)]}detachNetworkListeners(){this.networkUnsubscribers.splice(0).forEach(e=>e())}getActiveMediaContext(){let e=this.callManager?.getActiveCall();return e===void 0?void 0:this.mediaBridge.contextFor(e.id,e.state,new Set(this.session?.capabilities??[]))}hasNonTerminalCalls(){return this.callManager?.hasNonTerminalCalls()??!1}clearRefreshTimer(){this.refreshTimer!==void 0&&(clearTimeout(this.refreshTimer),this.refreshTimer=void 0)}createDiagnosticsSnapshot(){let e=this.session;return{connectionState:this.state,calls:this.getCalls().map(e=>({callId:e.id,state:e.state,destination:e.destination})),permission:this.support?.hasMediaDevices===!1?`unsupported`:`unknown`,ice:X(e),wss:{configured:e!==void 0,secure:e?.transport.wssUrl.toLowerCase().startsWith(`wss://`)??!1,state:this.state},resources:this.getDiagnosticsResourceCounts()}}getDiagnosticsResourceCounts(){let e=this.mediaBridge.getResourceCounts(),t=this.callManager?.getResourceCounts()??{timers:0,listeners:0},n=this.sip?.getResourceCounts?.(),r=(this.callManager===void 0?0:1)+(this.sipUnsubscribe===void 0?0:1),i=this.session!==void 0&&this.state!==`idle`&&this.state!==`disconnected`;return{timers:(this.refreshTimer===void 0?0:1)+this.reconnect.getTimerCount()+t.timers,listeners:this.events.listenerCount()+t.listeners+e.listeners+this.networkUnsubscribers.length+(n?.listeners??r),tracks:e.tracks,peerConnections:e.peerConnections,audioElements:e.audioElements,webSockets:n?.webSockets??+!!i}}async readMicrophonePermission(){if(typeof navigator>`u`||navigator.mediaDevices===void 0)return`unsupported`;if(navigator.permissions===void 0)return`unknown`;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}deleteSession(e){if(this.deletedSessions.has(e))return Promise.resolve();let t=this.sessionDeleteOperations.get(e);if(t!==void 0)return t;let n=this.api.deleteSession(e).then(()=>{this.deletedSessions.add(e)}).finally(()=>{this.sessionDeleteOperations.get(e)===n&&this.sessionDeleteOperations.delete(e)});return this.sessionDeleteOperations.set(e,n),n}async deleteOwnedSessions(){let e;for(let t of[...this.ownedSessionIds])try{await this.deleteSession(t),this.ownedSessionIds.delete(t)}catch(t){e??=t}if(e!==void 0)throw e}resolvePlatform(){let t=this.options.platform??this.detectedPlatform;if(t===void 0)throw new e.t(`CONFIG_INVALID`,`configuration`,!1,{cause:this.support?.platform??`unknown`});return t}setConnectionState(e){this.state===e||this.disposed||(this.state=e,this.diagnostics.log(`info`,`connection.stateChanged`,{state:e}),this.events.emit(`connection.stateChanged`,{state:e===`disconnected`||e===`idle`?`offline`:e}))}assertConnected(){if(this.assertNotDisposed(),this.state!==`connected`||this.callManager===void 0||this.session===void 0)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1)}assertGeneration(t){if(this.disposed)throw this.disposedError();if(t!==this.lifecycleGeneration)throw new e.t(`CALL_NOT_CONNECTED`,`call`,!1)}isCurrentGeneration(e){return!this.disposed&&e===this.lifecycleGeneration}assertNotDisposed(){if(this.disposed)throw this.disposedError()}disposedError(){return new e.t(`SDK_ALREADY_DISPOSED`,`internal`,!1)}};function X(e){if(e===void 0)return{configured:!1,serverCount:0,stunServerCount:0,turnServerCount:0};let t=0,n=0;return e.iceServers.forEach(e=>{let r=e.urls.map(e=>e.toLowerCase());r.some(e=>e.startsWith(`stun:`))&&(t+=1),r.some(e=>e.startsWith(`turn:`)||e.startsWith(`turns:`))&&(n+=1)}),{configured:e.iceServers.length>0,serverCount:e.iceServers.length,stunServerCount:t,turnServerCount:n}}function Z(e){return e===``?`unknown`:/iPhone|iPad|Android/i.test(e)?`mobile-web`:`web`}function re(t){if(typeof t!=`object`||!t)throw new e.t(`CONFIG_INVALID`,`configuration`,!1);return t}function ie(t){if(typeof t!=`object`||!t)throw new e.t(`CONFIG_INVALID`,`configuration`,!1);return t}function Q(t,n,r,i,a){return t instanceof e.t?new e.t(t.code,t.category,t.retryable,{requestId:t.requestId,callId:a??t.callId,cause:t.cause??t}):new e.t(n,r,i,{callId:a,cause:t})}function ae(t){return t instanceof e.t&&t.code===`SDK_ALREADY_DISPOSED`}function $(t){return t instanceof e.t&&(t.code===`SDK_ALREADY_DISPOSED`||t.code===`CALL_NOT_CONNECTED`)}var oe=[`outbound`,`inbound`,`mute`,`hold`,`dtmf`,`blind_transfer`,`device_selection`],se=[`outbound`,`mute`,`dtmf`];function ce(e){return e===`mobile-web`?se:oe}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return r}});
|