@coventia/softphone 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/{call-DUVnDxsz.d.cts → call-VKq1I8yP.d.cts} +6 -0
  2. package/dist/{call-DUVnDxsz.d.ts → call-VKq1I8yP.d.ts} +6 -0
  3. package/dist/{chunk-YWI6EQYS.js → chunk-EYEDPD7Y.js} +108 -15
  4. package/dist/chunk-EYEDPD7Y.js.map +1 -0
  5. package/dist/element/index.d.ts +8 -2
  6. package/dist/element/index.js +334 -249
  7. package/dist/element/index.js.map +1 -1
  8. package/dist/{engine-CDjkrXHY.d.cts → engine-BlQBo2Ys.d.cts} +1 -1
  9. package/dist/{engine-EPCKf-Bl.d.ts → engine-C0BOkIcW.d.ts} +1 -1
  10. package/dist/index.cjs +199 -23
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +5 -5
  13. package/dist/index.d.ts +5 -5
  14. package/dist/index.js +90 -11
  15. package/dist/index.js.map +1 -1
  16. package/dist/react/index.d.cts +2 -2
  17. package/dist/react/index.d.ts +2 -2
  18. package/dist/{softphone-BtdgZWkm.d.ts → softphone-Cyq3hiIM.d.ts} +1 -1
  19. package/dist/{softphone-DHG9MTNg.d.cts → softphone-DlGV12Xp.d.cts} +1 -1
  20. package/dist/softphone.css +82 -34
  21. package/dist/{sources-5L2R4HTV.js → sources-IRKNQPWW.js} +6 -2
  22. package/dist/sources-IRKNQPWW.js.map +1 -0
  23. package/dist/testing/index.d.cts +2 -2
  24. package/dist/testing/index.d.ts +2 -2
  25. package/dist/ui/index.cjs +332 -247
  26. package/dist/ui/index.cjs.map +1 -1
  27. package/dist/ui/index.d.cts +17 -6
  28. package/dist/ui/index.d.ts +17 -6
  29. package/dist/ui/index.js +332 -247
  30. package/dist/ui/index.js.map +1 -1
  31. package/dist/zadarma/index.cjs +106 -13
  32. package/dist/zadarma/index.cjs.map +1 -1
  33. package/dist/zadarma/index.d.cts +2 -2
  34. package/dist/zadarma/index.d.ts +2 -2
  35. package/dist/zadarma/index.js +1 -1
  36. package/dist/zadarma-engine-L5DEFXUS.js +5 -0
  37. package/dist/{zadarma-engine-4VOPIBXG.js.map → zadarma-engine-L5DEFXUS.js.map} +1 -1
  38. package/package.json +1 -1
  39. package/dist/chunk-YWI6EQYS.js.map +0 -1
  40. package/dist/sources-5L2R4HTV.js.map +0 -1
  41. package/dist/zadarma-engine-4VOPIBXG.js +0 -5
@@ -1,5 +1,5 @@
1
- import { p as TokenSource } from '../call-DUVnDxsz.cjs';
2
- import { C as CallEngine } from '../engine-CDjkrXHY.cjs';
1
+ import { p as TokenSource } from '../call-VKq1I8yP.cjs';
2
+ import { C as CallEngine } from '../engine-BlQBo2Ys.cjs';
3
3
 
4
4
  /**
5
5
  * Provider quirk timers. All optional. A self-hosted provider supplies none of them — which is the
@@ -1,5 +1,5 @@
1
- import { p as TokenSource } from '../call-DUVnDxsz.js';
2
- import { C as CallEngine } from '../engine-EPCKf-Bl.js';
1
+ import { p as TokenSource } from '../call-VKq1I8yP.js';
2
+ import { C as CallEngine } from '../engine-C0BOkIcW.js';
3
3
 
4
4
  /**
5
5
  * Provider quirk timers. All optional. A self-hosted provider supplies none of them — which is the
@@ -1,4 +1,4 @@
1
- export { ZADARMA_QUIRKS, createZadarmaEngine } from '../chunk-YWI6EQYS.js';
1
+ export { ZADARMA_QUIRKS, createZadarmaEngine } from '../chunk-EYEDPD7Y.js';
2
2
  import '../chunk-2ZSOGGPO.js';
3
3
  import '../chunk-MHOJHG5E.js';
4
4
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ export { createZadarmaEngine } from './chunk-EYEDPD7Y.js';
2
+ import './chunk-2ZSOGGPO.js';
3
+ import './chunk-MHOJHG5E.js';
4
+ //# sourceMappingURL=zadarma-engine-L5DEFXUS.js.map
5
+ //# sourceMappingURL=zadarma-engine-L5DEFXUS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"zadarma-engine-4VOPIBXG.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"zadarma-engine-L5DEFXUS.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coventia/softphone",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Embeddable browser softphone SDK for Zadarma: a framework-free engine, React components, and a Web Component drop-in.",
5
5
  "type": "module",
6
6
  "author": "Coventia",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/transports/sip/media.ts","../src/transports/sip/ice.ts","../src/transports/sip/session.ts","../src/transports/sip/ua.ts","../src/transports/sip/real-factory.ts","../src/transports/providers/zadarma.ts","../src/transports/providers/zadarma-browser.ts","../src/transports/zadarma-engine.ts"],"names":["track"],"mappings":";;;;AAWO,SAAS,sBAAsB,QAAA,EAAiD;AACrF,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,GAAW,EAAE,QAAA,EAAU,EAAE,KAAA,EAAO,QAAA,EAAS,EAAE,GAAI,IAAA,EAAM,KAAA,EAAO,KAAA,EAAM;AACpF;AAoCO,SAAS,eAAA,CAAgB,SAAuB,KAAA,EAA2B;AAChF,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,KAAA;AAEJ,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KAA4B;AAC1C,IAAA,IAAI,OAAA,EAAS;AACb,IAAA,OAAA,GAAU,IAAA;AACV,IAAA,IAAI,KAAA,eAAoB,KAAK,CAAA;AAC7B,IAAA,IAAI;AACF,MAAA,KAAA,EAAM;AAAA,IACR,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF,CAAA;AAEA,EAAA,OAAA,CAAQ,EAAA,CAAG,cAAA,EAAgB,CAAC,EAAE,OAAM,KAAqB;AAGvD,IAAA,IAAI,CAAC,OAAO,KAAA,GAAQ,UAAA,CAAW,MAAM,MAAA,CAAO,KAAK,GAAG,KA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AAEA,EAAA,QAAA,CAAS,gBAAA,CAAiB,oBAAoB,kBAAkB,CAAA;AAEhE,EAAA,IAAI,QAAA,CAAS,eAAA,KAAoB,QAAA,EAAU,kBAAA,EAAmB;AAE9D,EAAA,OAAO,MAAM;AACX,IAAA,QAAA,CAAS,mBAAA,CAAoB,oBAAoB,kBAAkB,CAAA;AACnE,IAAA,MAAA,EAAQ,WAAA,CAAY,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA;AACpC,IAAA,MAAA,EAAQ,SAAA,EAAU;AAClB,IAAA,IAAI,OAAA,EAAS,GAAA,CAAI,eAAA,CAAgB,OAAO,CAAA;AAAA,EAC1C,CAAA;AACF;AAGO,SAAS,uBAAuB,MAAA,EAA2C;AAChF,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,aAAa,MAAM,CAAA;AAAA,IAC7B,sBAAsB,CAAC,GAAA,EAAK,GAAA,KAAQ,oBAAA,CAAqB,KAAK,GAAG,CAAA;AAAA,IACjE,gBAAA;AAAA,IACA;AAAA,GACF;AACF;;;AClTO,SAAS,oBAAoB,MAAA,EAA0C;AAI5E,EAAA,MAAM,WAAW,IAAI,eAAA;AAAA,IACnB,sBAAA,CAAuB,EAAE,GAAG,MAAA,EAAQ,aAAa,iBAAA,CAAkB,MAAA,CAAO,WAAW,CAAA,EAAG;AAAA,GAC1F;AACA,EAAA,OAAO,IAAI,aAAA,CAAc,QAAA,EAAU,gBAAgB,CAAA;AACrD","file":"chunk-YWI6EQYS.js","sourcesContent":["import type { JsSipSession, JsSipIceEvent } from './jssip.js';\r\n\r\n/**\r\n * What a leg asks the browser for. Audio only — `video: false` is explicit rather than omitted,\r\n * matching the legacy hook exactly.\r\n *\r\n * A FUNCTION, not the static constant this used to be: device selection (SPEC §7 Phase 2) means the\r\n * constraint depends on whichever input device is currently selected, which can change between calls\r\n * — a static object could never reflect that. `deviceId: null` (the default, no device chosen yet)\r\n * falls back to bare `audio: true`, letting the browser pick its own default exactly as before.\r\n */\r\nexport function buildAudioConstraints(deviceId: string | null): MediaStreamConstraints {\r\n return { audio: deviceId ? { deviceId: { exact: deviceId } } : true, video: false };\r\n}\r\n\r\n/**\r\n * The two most non-obvious, most load-bearing, most deletable-LOOKING pieces of the engine\r\n * (SPEC §3.1). Everything here is generic WebRTC — nothing Zadarma-specific — but it is exactly the\r\n * code a rewrite quietly drops, so the reasoning travels with it.\r\n *\r\n * No browser global is touched at module scope (SPEC §10.2): every function reaches for\r\n * `window`/`navigator` only when called, in a browser.\r\n */\r\n\r\n/**\r\n * A **safety net** on ICE gathering: send the INVITE anyway if gathering has not finished in `capMs`.\r\n *\r\n * JsSIP already releases the INVITE the moment gathering completes — it calls its own `ready()` both\r\n * on the end-of-candidates signal and on `icegatheringstatechange === 'complete'`. So the normal path\r\n * needs nothing from us. This exists only for the pathological one: against an unreachable STUN or\r\n * TURN server, Chrome can sit in `gathering` for ~40 s, and a phone that takes 40 s to ring is broken.\r\n *\r\n * **It deliberately does NOT settle on the first `typ srflx` candidate**, which is what it used to do.\r\n * One reflexive candidate is not \"enough for NAT traversal\" — it is enough only if it happens to be\r\n * the right one, and cutting gathering short there loses:\r\n *\r\n * - **the other address family.** A first srflx over IPv6 against an IPv4-only peer is useless; the\r\n * IPv4 one arrives moments later and never makes it into the offer.\r\n * - **the other interfaces.** On a multi-homed machine (Wi-Fi + VPN + Ethernet) the first srflx may\r\n * be the one that cannot reach the media server.\r\n * - **every relay candidate.** TURN needs an allocation round-trip, so `typ relay` always arrives\r\n * AFTER srflx. Settling early meant a configured TURN server could never appear in the SDP — the\r\n * relay would be paid for and never offered, and the call would fail exactly as if it were absent.\r\n *\r\n * This is SIP, not trickle ICE: whatever is in the offer is all the peer will ever see. So the cost of\r\n * settling early is permanent for that call, while the cost of waiting is a few hundred milliseconds.\r\n *\r\n * @returns a disposer that cancels the pending timer (call it on teardown).\r\n */\r\nexport function capIceGathering(session: JsSipSession, capMs: number): () => void {\r\n let settled = false;\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n\r\n const settle = (ready: () => void): void => {\r\n if (settled) return;\r\n settled = true;\r\n if (timer) clearTimeout(timer);\r\n try {\r\n ready();\r\n } catch {\r\n /* offer already sent */\r\n }\r\n };\r\n\r\n session.on('icecandidate', ({ ready }: JsSipIceEvent) => {\r\n // Armed on the first candidate of any kind; JsSIP wins the race whenever gathering completes\r\n // normally, which is the overwhelmingly common case.\r\n if (!timer) timer = setTimeout(() => settle(ready), capMs);\r\n });\r\n\r\n return () => {\r\n if (timer) clearTimeout(timer);\r\n };\r\n}\r\n","/**\r\n * ICE configuration — how the browser's media finds its way out of a NAT.\r\n *\r\n * **SDK infrastructure, not host configuration.** A partner integrating a softphone should not have\r\n * to learn what a STUN server is, and every host would otherwise solve the same problem identically.\r\n * So there is a working default here and nothing to configure.\r\n *\r\n * With no ICE servers at all, a browser offers only HOST candidates — its own LAN addresses — and the\r\n * far end has to reach `192.168.x.x` directly. That works only where the NAT happens to cooperate,\r\n * and fails on symmetric NAT and most corporate networks. Firefox says `ICE failed, add a STUN\r\n * server`; Chrome's version is worse, connecting a call that carries no audio.\r\n *\r\n * **STUN only, deliberately — there is no TURN here and it could not be added here.** STUN just\r\n * reports the browser's own public address: stateless, unauthenticated, free. TURN *relays the media*,\r\n * so it costs bandwidth and therefore needs credentials — and a credential compiled into a client\r\n * bundle is a public one, usable by anyone who opens devtools. A relay would have to be issued per\r\n * user and short-lived by a backend that knows who is asking (coturn's `use-auth-secret` scheme is\r\n * the usual shape). That is real infrastructure, and until a network actually demands it we do not\r\n * run any: the legacy CRM softphone shipped exactly this one STUN server and placed real calls for\r\n * years.\r\n */\r\n\r\n/**\r\n * Google's public STUN. No registration, and the de facto default for the WebRTC ecosystem — it is\r\n * also, verbatim, what the legacy `useSipUA.js` used, which is the strongest argument available that\r\n * it is sufficient for Zadarma.\r\n *\r\n * Two caveats worth a decision rather than a shrug: it carries **no SLA**, and every user's IP is\r\n * observed by Google. Both are fixed the same way — point this at a STUN server we run.\r\n */\r\nexport const DEFAULT_ICE_SERVERS: readonly RTCIceServer[] = [\r\n { urls: 'stun:stun.l.google.com:19302' },\r\n];\r\n\r\n/** The `pcConfig` JsSIP hands to `new RTCPeerConnection`, for every leg in either direction. */\r\nexport const PC_CONFIG: RTCConfiguration = { iceServers: [...DEFAULT_ICE_SERVERS] };\r\n","import type { EngineCall, EngineCallEvent } from '../../core/engine.js';\r\nimport type { HangupReason } from '../../core/call.js';\r\nimport type { CallDirection } from '../../core/types.js';\r\nimport type { JsSipEndEvent, JsSipSession } from './jssip.js';\r\nimport { buildAudioConstraints, capIceGathering } from './media.js';\r\nimport { PC_CONFIG } from './ice.js';\r\n\r\n/** Map JsSIP end/failed causes onto the SDK's HangupReason. Generic SIP, no provider specifics. */\r\nfunction mapEndReason(e: JsSipEndEvent): HangupReason {\r\n if (e.originator === 'local') return 'local';\r\n if (e.originator === 'remote') return 'remote';\r\n return 'failed';\r\n}\r\n/**\r\n * A JsSIP cause onto the SDK's HangupReason.\r\n *\r\n * The cases below are `JsSIP.C.causes`, and the status codes in the comments are its own\r\n * `SIP_ERROR_CAUSES` table — this must be read against that list rather than guessed at, because\r\n * `JsSipEndEvent.cause` is a bare `string`, so a case that never matches costs nothing at compile\r\n * time and silently falls to `failed`. That is exactly how `Unavailable` went unhandled: it is what\r\n * a call that rings out actually returns, and it was reaching `default`.\r\n *\r\n * `failed` is a real outcome, not a fallthrough — see CALL_END_CODES in `ua.ts`. Anything unmapped\r\n * still tells the user the call did not connect.\r\n */\r\nfunction mapFailReason(e: JsSipEndEvent): HangupReason {\r\n switch (e.cause) {\r\n // 486 Busy Here, 600 Busy Everywhere. Also what most endpoints send for a MANUAL DECLINE — SIP\r\n // does not distinguish the two, and neither can we, which is why the copy covers both.\r\n case 'Busy':\r\n return 'busy';\r\n /*\r\n `Rejected` is 403 / 603 Decline — an explicit refusal, sent by the endpoints that bother to.\r\n `Redirected` is 3xx: not literally a rejection, but it ends the same way — not connected, and\r\n nothing to retry.\r\n\r\n (Both comments sit ABOVE the group rather than between the labels. A comment between two `case`\r\n lines makes the first one non-empty to `no-fallthrough`, which then demands a `break` that\r\n would be unreachable.)\r\n */\r\n case 'Rejected':\r\n case 'Redirected':\r\n return 'rejected';\r\n /*\r\n `Unavailable` is 480 Temporarily Unavailable / 410 / 408 Request Timeout / 430 — THE ring-out\r\n case, and the one that was missing. `No Answer` and `Expires` are local: our own no-answer\r\n timer, and a session that expired.\r\n */\r\n case 'Unavailable':\r\n case 'No Answer':\r\n case 'Expires':\r\n return 'no-answer';\r\n case 'Canceled':\r\n /*\r\n BOTH directions produce this cause, meaning opposite things, and only the originator tells\r\n them apart: `remote` is the caller giving up while our phone rang (a missed call — `ua.ts`\r\n turns this one into `call/missed`), `local` is the user abandoning their own outbound call\r\n before it was picked up. This used to return `remote` for both, which told the host that the\r\n far end ended a call the user had just hung up on themselves.\r\n */\r\n return e.originator === 'local' ? 'local' : 'remote';\r\n // Everything else is a genuine failure worth naming: Not Found (404/604), Address Incomplete,\r\n // Incompatible SDP, Authentication Error, WebRTC Error, RTP Timeout, Connection Error…\r\n default:\r\n return 'failed';\r\n }\r\n}\r\n\r\nfunction remoteNumberOf(session: JsSipSession): string {\r\n const id = session.remote_identity;\r\n return id?.uri?.user ?? id?.uri?.toString() ?? '';\r\n}\r\n\r\nexport interface SipEngineCallDeps {\r\n readonly id: string;\r\n /** Turn an extension or bare number into a full SIP URI (the engine knows the domain). */\r\n readonly buildTarget: (target: string) => string;\r\n /** Place a consult leg on the same UA (attended transfer). */\r\n readonly placeConsult: (target: string) => Promise<SipEngineCall>;\r\n readonly iceGatheringCapMs?: number;\r\n /** ICE servers for the answer's peer connection — same set the engine uses outbound. */\r\n readonly pcConfig?: RTCConfiguration;\r\n /**\r\n * Called when THIS call is rejected (486), so the engine can start its provider re-ring guard\r\n * (SPEC §3.4). Tied to the reject ACTION, not to `ended` — a normal hangup must not start it.\r\n */\r\n readonly onReject?: () => void;\r\n /**\r\n * The currently-selected input device, read fresh at ANSWER time — an inbound call's `getUserMedia`\r\n * happens here, not at construction, so a device chosen after the call started ringing still takes\r\n * effect the moment it is picked up. `undefined`/`null` means no device chosen — the browser default.\r\n */\r\n readonly getInputDeviceId?: () => string | null;\r\n}\r\n\r\n/**\r\n * One JsSIP call, as an `EngineCall`. It translates JsSIP's events into the SDK's raw\r\n * `EngineCallEvent`s — and `Call` (core) turns those into the public state machine. Nothing here\r\n * knows the state machine, and nothing here is Zadarma-specific.\r\n */\r\nexport class SipEngineCall implements EngineCall {\r\n readonly id: string;\r\n readonly direction: CallDirection;\r\n readonly remoteNumber: string;\r\n\r\n readonly #session: JsSipSession;\r\n readonly #deps: SipEngineCallDeps;\r\n readonly #listeners = new Set<(event: EngineCallEvent) => void>();\r\n\r\n #ended = false;\r\n #cancelIceCap: (() => void) | null = null;\r\n /**\r\n * The stream behind a LIVE device swap (`swapInputDevice`), if one has happened. Distinct from\r\n * JsSIP's own original capture: that one is `_localMediaStreamLocallyGenerated` and JsSIP stops it\r\n * itself on close (see `#end`'s comment). This one is ours — obtained with our own `getUserMedia`\r\n * call, attached via `replaceTrack`, and never known to JsSIP at all — so nothing else will ever\r\n * stop it unless we do, here.\r\n */\r\n #swappedStream: MediaStream | null = null;\r\n\r\n constructor(session: JsSipSession, deps: SipEngineCallDeps) {\r\n this.#session = session;\r\n this.#deps = deps;\r\n this.id = deps.id;\r\n this.direction = session.direction === 'incoming' ? 'inbound' : 'outbound';\r\n this.remoteNumber = remoteNumberOf(session);\r\n this.#wire();\r\n }\r\n\r\n /** @internal — the underlying session, for `completeTransfer`'s REFER…Replaces. */\r\n get session(): JsSipSession {\r\n return this.#session;\r\n }\r\n\r\n onEvent(listener: (event: EngineCallEvent) => void): () => void {\r\n this.#listeners.add(listener);\r\n return () => this.#listeners.delete(listener);\r\n }\r\n\r\n // ── JsSIP events → raw engine signals ─────────────────────────────────────\r\n #wire(): void {\r\n const s = this.#session;\r\n\r\n /*\r\n * `progress` is OUTBOUND-only.\r\n *\r\n * JsSIP fires it in both directions, but it means opposite things: on an outbound call it is the\r\n * remote's `180`/`183` — the state we call `early`, possibly with early media. On an INBOUND call\r\n * it fires when *we* send `180 Ringing`, which is not a state change at all: the call is already\r\n * `ringing`, and the machine has no `ringing → early` edge because there is no such thing.\r\n *\r\n * Wiring it for both is what produced `illegal call transition ringing → early` on every real\r\n * inbound call. It was harmless — the transition was refused and the call rang and answered fine —\r\n * but it logged an error on a healthy path, and an error that fires when nothing is wrong is how\r\n * people learn to ignore the console.\r\n */\r\n if (this.direction === 'outbound') {\r\n s.on('progress', () => this.#fire({ type: 'progress', response: 'ringing' }));\r\n }\r\n\r\n /*\r\n * The remote audio. `ontrack` has to be wired on BOTH paths, because JsSIP creates the peer\r\n * connection at a different moment in each direction:\r\n *\r\n * INBOUND — created inside `answer()`, long after this runs. The event is the only way to see it.\r\n * OUTBOUND — created SYNCHRONOUSLY inside `ua.call()`: JsSIP's `connect()` calls\r\n * `_createRTCConnection()` before it returns, so `peerconnection` has already fired\r\n * by the time this object exists. Listening alone means `ontrack` is never set and\r\n * the caller hears silence — while the callee hears them perfectly, since the\r\n * outbound media path is unaffected.\r\n *\r\n * The legacy hook did exactly this: `if (session.connection) session.connection.ontrack = …`\r\n * right after `ua.call()`, plus the event for the answer path.\r\n */\r\n const wireRemoteTrack = (pc: RTCPeerConnection): void => {\r\n pc.ontrack = ({ streams }) => {\r\n if (streams[0]) this.#fire({ type: 'stream', stream: streams[0] });\r\n };\r\n };\r\n s.on('peerconnection', ({ peerconnection }) => wireRemoteTrack(peerconnection));\r\n if (s.connection) wireRemoteTrack(s.connection);\r\n\r\n // Outbound only: release the INVITE without waiting for full ICE gathering (SPEC §3.1).\r\n if (this.direction === 'outbound' && this.#deps.iceGatheringCapMs) {\r\n this.#cancelIceCap = capIceGathering(s, this.#deps.iceGatheringCapMs);\r\n }\r\n\r\n s.on('accepted', () => this.#onAccepted());\r\n s.on('ended', (e) => this.#end(mapEndReason(e), e.cause));\r\n s.on('failed', (e) => this.#end(mapFailReason(e), e.cause));\r\n s.on('hold', ({ originator }) => this.#fire({ type: 'held', originator }));\r\n s.on('unhold', ({ originator }) => this.#fire({ type: 'unheld', originator }));\r\n }\r\n\r\n /**\r\n * The call is live. Nothing to swap: JsSIP opened the real microphone when the session was created,\r\n * so the far end has had our actual audio from the first packet.\r\n *\r\n * There used to be a silent-mic dance here — place the call with a synthetic AudioContext track,\r\n * swap the real mic in on accept — so a Bluetooth headset stayed in A2DP while the phone rang. It\r\n * cost more than it bought: with no active capture, Firefox restricts ICE gathering and the offer\r\n * goes out with no candidates at all, which no STUN or TURN server can fix.\r\n */\r\n #onAccepted(): void {\r\n this.#fire({ type: 'accepted' });\r\n }\r\n\r\n // ── Commands ───────────────────────────────────────────────────────────────\r\n async answer(): Promise<void> {\r\n const deviceId = this.#deps.getInputDeviceId?.() ?? null;\r\n this.#session.answer({\r\n mediaConstraints: buildAudioConstraints(deviceId),\r\n pcConfig: this.#deps.pcConfig ?? PC_CONFIG,\r\n });\r\n }\r\n\r\n /**\r\n * Live-swap the outgoing microphone track — `CallEngine.setInputDevice` on a call that is already\r\n * connected. Never touches the FIRST call's capture: that one is JsSIP's own `getUserMedia`, opened\r\n * inside `answer()`/`ua.call()` (see `#onAccepted`'s comment on why that stays that way). This is\r\n * only for a device chosen AFTER the call is already live.\r\n *\r\n * `RTCRtpSender.replaceTrack` rather than a fresh `answer()`/re-INVITE: it needs no SDP\r\n * renegotiation and the far end never sees an interruption — exactly the mechanism real softphones\r\n * use for \"switch mic mid-call.\"\r\n */\r\n async swapInputDevice(deviceId: string | null): Promise<void> {\r\n const pc = this.#session.connection;\r\n if (!pc || this.#ended) return; // not connected yet, or already over — nothing to swap\r\n const sender = pc.getSenders().find((s) => s.track?.kind === 'audio');\r\n if (!sender) return;\r\n\r\n let stream: MediaStream;\r\n try {\r\n stream = await navigator.mediaDevices.getUserMedia(buildAudioConstraints(deviceId));\r\n } catch {\r\n // The chosen device vanished between selection and this call (unplugged, permission revoked,\r\n // a stale id) — nothing useful to do beyond leaving the current track exactly as it was.\r\n return;\r\n }\r\n if (this.#ended) {\r\n // The call ended while getUserMedia was in flight — don't attach a track to a dead sender,\r\n // and don't leak the capture we just opened.\r\n for (const track of stream.getTracks()) track.stop();\r\n return;\r\n }\r\n const [track] = stream.getAudioTracks();\r\n if (!track) return;\r\n\r\n await sender.replaceTrack(track);\r\n // Stop whatever we swapped in LAST time — never the original JsSIP capture, which this never\r\n // touches and which JsSIP stops itself on close.\r\n for (const oldTrack of this.#swappedStream?.getTracks() ?? []) oldTrack.stop();\r\n this.#swappedStream = stream;\r\n }\r\n\r\n async reject(): Promise<void> {\r\n this.#deps.onReject?.();\r\n this.#session.terminate({ status_code: 486, reason_phrase: 'Busy Here' });\r\n }\r\n\r\n async hangup(): Promise<void> {\r\n this.#session.terminate();\r\n }\r\n\r\n mute(muted: boolean): void {\r\n if (muted) this.#session.mute({ audio: true });\r\n else this.#session.unmute({ audio: true });\r\n }\r\n\r\n async hold(): Promise<void> {\r\n // JsSIP writes `a=sendonly` and fires 'hold' — which #wire translates to a `held` signal. One\r\n // path, so a locally-initiated hold and a remote one travel identically (SPEC §5.6).\r\n this.#session.hold();\r\n }\r\n\r\n async unhold(): Promise<void> {\r\n this.#session.unhold();\r\n }\r\n\r\n sendDigits(digits: string): void {\r\n this.#session.sendDTMF(digits);\r\n }\r\n\r\n async transfer(target: string): Promise<void> {\r\n // Blind transfer. JsSIP ends the session on a successful REFER; that surfaces as `ended`\r\n // (reason 'transferred' is set by the core when it sees the transfer intent — here it is a\r\n // normal local end).\r\n this.#session.refer(this.#deps.buildTarget(target));\r\n }\r\n\r\n async startConsult(target: string): Promise<EngineCall> {\r\n return this.#deps.placeConsult(target);\r\n }\r\n\r\n async completeTransfer(consult: EngineCall): Promise<void> {\r\n const consultSession = (consult as SipEngineCall).session;\r\n this.#session.refer(consultSession.remote_identity.uri.toString(), { replaces: consultSession });\r\n }\r\n\r\n // ── internals ──────────────────────────────────────────────────────────────\r\n #end(reason: HangupReason, cause?: string): void {\r\n if (this.#ended) return;\r\n this.#ended = true;\r\n this.#cancelIceCap?.();\r\n // The ORIGINAL microphone is NOT stopped here: JsSIP opened it (no `mediaStream` was passed), so\r\n // it owns it and stops the tracks itself on close. See `_localMediaStreamLocallyGenerated` in\r\n // JsSIP. A SWAPPED-IN one (`swapInputDevice`) is a different story — JsSIP never learned about\r\n // it, so it is ours to stop, or the capture (and the browser's mic indicator) outlives the call.\r\n for (const track of this.#swappedStream?.getTracks() ?? []) track.stop();\r\n this.#swappedStream = null;\r\n this.#fire({ type: 'ended', reason, cause });\r\n this.#listeners.clear();\r\n }\r\n\r\n #fire(event: EngineCallEvent): void {\r\n if (this.#ended && event.type !== 'ended') return;\r\n for (const listener of [...this.#listeners]) listener(event);\r\n }\r\n}\r\n","import type { CallEngine, EngineCall } from '../../core/engine.js';\r\nimport type { CallOptions, SoftphoneState } from '../../core/types.js';\r\nimport type { SipCredentials, SipProvider } from '../providers/provider.js';\r\nimport type { JsSipFactory, JsSipSession, JsSipUA, JsSipUAConfig } from './jssip.js';\r\nimport { SipEngineCall } from './session.js';\r\nimport { buildAudioConstraints } from './media.js';\r\nimport { PC_CONFIG } from './ice.js';\r\nimport { createError, isSoftphoneError } from '../../core/errors.js';\r\nimport type { NonFatalErrorCode, SoftphoneError, SoftphoneErrorCode } from '../../core/errors.js';\r\nimport type { HangupReason } from '../../core/call.js';\r\n\r\nconst DEFAULT_ICE_CAP_MS = 3000;\r\nconst REGISTER_EXPIRES = 580;\r\n/** Floor between signal rebuilds, so a persistently failing registrar cannot become a hot loop. */\r\nconst SIGNAL_REFRESH_DEBOUNCE_MS = 30_000;\r\n/** Same window, same reason: a retrying registrar must not become a stream of identical errors. */\r\nconst ERROR_DEBOUNCE_MS = 30_000;\r\n\r\n/**\r\n * Call outcomes worth telling the user about. Reasons NOT here (`local`, `remote`, `transferred`)\r\n * are ordinary endings — reporting them would turn every completed call into an error.\r\n *\r\n * `failed` MUST stay mapped. It is `mapFailReason`'s catch-all, so leaving it out means every cause\r\n * nobody thought to enumerate ends the call in silence — the user watches the dialpad come back with\r\n * no idea whether it rang, and the least-understood failures are the ones explained least.\r\n */\r\nconst CALL_END_CODES: Partial<Record<HangupReason, NonFatalErrorCode>> = {\r\n busy: 'call/busy',\r\n 'no-answer': 'call/no-answer',\r\n rejected: 'call/rejected',\r\n failed: 'call/failed',\r\n};\r\n\r\n/** `sip:100@pbx.example.com` → `pbx.example.com`. */\r\nfunction domainOf(credentials: SipCredentials): string {\r\n const at = credentials.uri.lastIndexOf('@');\r\n return at === -1 ? '' : credentials.uri.slice(at + 1);\r\n}\r\n\r\nlet callSeq = 0;\r\nconst nextCallId = (): string => `sip-${++callSeq}`;\r\n\r\n/**\r\n * The generic JsSIP call engine. A `CallEngine` driven by a `SipProvider` for credentials and\r\n * registration policy (SPEC §5.4).\r\n *\r\n * NOTHING here is Zadarma-specific — `grep -ri zadarma` over this directory must return nothing. The\r\n * push socket, the JSONP key exchange and the quirk-timer *values* all live in the provider (S4);\r\n * this engine only reads `provider.registrationMode`, `provider.incomingSignal` and\r\n * `provider.quirks` as data.\r\n *\r\n * Registration policy:\r\n * - `persistent` — provision + register once at start(); the standing UA both receives INVITEs\r\n * and places calls. The normal SIP model; our own infrastructure, later.\r\n * - `on-demand` — register only in response to `incomingSignal` (or to place a call), tear down\r\n * after. Zadarma's PBX ignores a standing registration (SPEC §3.2). The\r\n * no-INVITE teardown and reject-guard timers come from `provider.quirks`.\r\n */\r\nexport class SipCallEngine implements CallEngine {\r\n #state: SoftphoneState = 'stopped';\r\n #ua: JsSipUA | null = null;\r\n /** In-flight `#createUA()`. THE concurrency guard — see `#ensureUA`. */\r\n #uaInFlight: Promise<JsSipUA> | null = null;\r\n #domain = '';\r\n #activeCall: SipEngineCall | null = null;\r\n /**\r\n * The consult leg from `startConsult` (SPEC §5.6), if one is live on this UA right now.\r\n *\r\n * Tracked separately from `#activeCall` so `#maybeTeardownUA` can tell \"both legs are actually gone\"\r\n * apart from \"the main leg ended, but a consult is still up\" — see that method's own comment for the\r\n * bug this exists to prevent.\r\n */\r\n #consultCall: SipEngineCall | null = null;\r\n /** The chosen microphone, or `null` for the browser default. Read fresh by every new leg's\r\n * `mediaConstraints`, and pushed live to `#activeCall` by `setInputDevice`. */\r\n #inputDeviceId: string | null = null;\r\n\r\n readonly #incomingListeners = new Set<(call: EngineCall) => void>();\r\n readonly #stateListeners = new Set<(state: SoftphoneState) => void>();\r\n readonly #errorListeners = new Set<(error: SoftphoneError) => void>();\r\n #signalUnsub: (() => void) | null = null;\r\n #signalConnectionUnsub: (() => void) | null = null;\r\n #noInviteTimer: ReturnType<typeof setTimeout> | undefined;\r\n #rejectGuardUntil = 0;\r\n #signalRefreshAfter = 0;\r\n readonly #errorSentAfter = new Map<SoftphoneErrorCode, number>();\r\n\r\n private readonly now: () => number;\r\n #resolvedFactory: JsSipFactory | null = null;\r\n\r\n constructor(\r\n private readonly provider: SipProvider,\r\n // A factory OR an async loader. The loader form bridges sync construction with the dynamic\r\n // `import('jssip')` (SPEC §10.2) — tests still pass a plain FakeFactory.\r\n private readonly factory: JsSipFactory | (() => JsSipFactory | Promise<JsSipFactory>),\r\n options: { now?: () => number } = {},\r\n ) {\r\n this.now = options.now ?? Date.now;\r\n }\r\n\r\n async #resolveFactory(): Promise<JsSipFactory> {\r\n if (this.#resolvedFactory) return this.#resolvedFactory;\r\n this.#resolvedFactory =\r\n typeof this.factory === 'function' ? await this.factory() : this.factory;\r\n return this.#resolvedFactory;\r\n }\r\n\r\n get state(): SoftphoneState {\r\n return this.#state;\r\n }\r\n\r\n onIncoming(listener: (call: EngineCall) => void): () => void {\r\n this.#incomingListeners.add(listener);\r\n return () => this.#incomingListeners.delete(listener);\r\n }\r\n onStateChange(listener: (state: SoftphoneState) => void): () => void {\r\n this.#stateListeners.add(listener);\r\n return () => this.#stateListeners.delete(listener);\r\n }\r\n onError(listener: (error: SoftphoneError) => void): () => void {\r\n this.#errorListeners.add(listener);\r\n return () => this.#errorListeners.delete(listener);\r\n }\r\n\r\n /**\r\n * Switch the microphone: stored for every FUTURE leg's `mediaConstraints`, and — if a call is live\r\n * right now — pushed to it immediately via `SipEngineCall.swapInputDevice` (SPEC §7 Phase 2, device\r\n * management). `null` resets to the browser's own default device.\r\n */\r\n async setInputDevice(deviceId: string | null): Promise<void> {\r\n this.#inputDeviceId = deviceId;\r\n await this.#activeCall?.swapInputDevice(deviceId);\r\n }\r\n\r\n /**\r\n * Report a failure, at most once per code per `ERROR_DEBOUNCE_MS`.\r\n *\r\n * A failing registrar retries, and one emission per attempt would flood a host's logging and make\r\n * whatever the widget shows flicker. Debounced per CODE rather than globally, so a transport\r\n * failure is never swallowed because a registration failure happened to precede it.\r\n */\r\n #reportError(code: SoftphoneErrorCode, cause?: unknown): void {\r\n this.#emitError(createError(code, cause));\r\n }\r\n\r\n /**\r\n * Emit, debouncing FATAL codes only.\r\n *\r\n * A failing registrar retries, and one emission per attempt would flood a host's logging and make\r\n * whatever the widget shows flicker — so the same fatal code is reported at most once per window,\r\n * per CODE, so a transport failure is never swallowed because a registration failure preceded it.\r\n *\r\n * Non-fatal codes are never debounced: they describe one call each, and two busy tones in a row are\r\n * two facts, not a repeated one.\r\n */\r\n #emitError(error: SoftphoneError): void {\r\n if (error.fatal) {\r\n const now = this.now();\r\n if (now < (this.#errorSentAfter.get(error.code) ?? 0)) return;\r\n this.#errorSentAfter.set(error.code, now + ERROR_DEBOUNCE_MS);\r\n }\r\n for (const listener of [...this.#errorListeners]) listener(error);\r\n }\r\n\r\n async start(): Promise<void> {\r\n this.#setState('starting');\r\n if (this.provider.registrationMode === 'persistent') {\r\n await this.#ensureUA();\r\n this.#setState('online');\r\n } else {\r\n // On-demand: the push socket keeps us \"reachable\" without a standing registration. We only\r\n // register when it signals a call (or when we place one).\r\n const signal = this.provider.incomingSignal;\r\n if (signal) {\r\n await signal.connect();\r\n this.#signalUnsub = signal.onSignal(() => void this.#onIncomingSignal());\r\n /*\r\n * The signal channel IS our reachability, so it drives the reported state.\r\n *\r\n * Without this, `online` meant \"start() was called\" and nothing could ever contradict it —\r\n * the only other state transitions come from a UA that, in on-demand mode, exists solely for\r\n * the duration of a call. A dead push socket therefore looked identical to a healthy one, and\r\n * the phone silently stopped ringing while the widget said it was online.\r\n */\r\n this.#signalConnectionUnsub =\r\n signal.onConnectionChange?.((connected) =>\r\n this.#setState(connected ? 'online' : 'offline'),\r\n ) ?? null;\r\n }\r\n // Optimistic only when the signal cannot report: an existing provider without\r\n // `onConnectionChange` keeps the old behaviour rather than being stuck offline.\r\n this.#setState(signal?.onConnectionChange ? (signal.connected ? 'online' : 'offline') : 'online');\r\n }\r\n }\r\n\r\n async stop(): Promise<void> {\r\n this.#clearNoInviteTimer();\r\n this.#signalUnsub?.();\r\n this.#signalUnsub = null;\r\n this.#signalConnectionUnsub?.();\r\n this.#signalConnectionUnsub = null;\r\n this.provider.incomingSignal?.disconnect();\r\n this.#teardownUA();\r\n this.#setState('stopped');\r\n }\r\n\r\n async placeCall(destination: string, _options?: CallOptions): Promise<EngineCall> {\r\n const ua = await this.#ensureUA();\r\n const session = await this.#callWhenRegistered(ua, this.#buildTarget(destination));\r\n return this.#wrapCall(session);\r\n }\r\n\r\n // ── incoming (on-demand: push → register → INVITE) ────────────────────────\r\n async #onIncomingSignal(): Promise<void> {\r\n // Guard: after a reject, the provider may RE-RING us (Zadarma's return_timeout). Swallow those\r\n // for the quirk window (SPEC §3.4). Persistent providers set no guard, so this is a no-op there.\r\n if (this.now() < this.#rejectGuardUntil) return;\r\n if (this.#activeCall) return; // already on a call\r\n try {\r\n await this.#ensureUA();\r\n // The push is NOT an INVITE (SPEC §3.3): it fires for transfers, retries, hangups. If no INVITE\r\n // arrives within the quirk window, tear the fresh UA down so it doesn't block the next call.\r\n this.#armNoInviteTeardown();\r\n } catch {\r\n this.#teardownUA();\r\n }\r\n }\r\n\r\n #armNoInviteTeardown(): void {\r\n const ms = this.provider.quirks?.noInviteTeardownMs;\r\n if (!ms) return;\r\n this.#clearNoInviteTimer();\r\n // `#onIncomingSignal` (SPEC §3.3) re-arms this on EVERY push, including the generic \"answered\"\r\n // pushes Zadarma sends around unrelated account activity — one landed 300ms after a real transfer\r\n // completed here (live capture, 2026-08-04) and, checking only `#activeCall`, blew away the still-\r\n // live consult leg 5s later with the exact same premature-teardown bug `#maybeTeardownUA` exists to\r\n // prevent (§ its own comment). Same guard, same reason: a consult leg is still \"something on this\r\n // UA,\" even with no `#activeCall`.\r\n this.#noInviteTimer = setTimeout(() => this.#maybeTeardownUA(), ms);\r\n }\r\n /**\r\n * Rebuild the incoming-signal channel with fresh credentials, after a registration failure.\r\n *\r\n * Registration fails when the credentials behind it have gone stale — and for Zadarma those come\r\n * from the same WebRTC key the push socket is holding. Tearing down the UA alone leaves that stale\r\n * key in place, so every subsequent attempt fails the same way and the phone is dead until the page\r\n * is reloaded. Reconnecting re-fetches the key. The legacy hook did exactly this from both of its\r\n * `registrationFailed` handlers.\r\n *\r\n * Debounced, which the legacy was not: a provider failing every attempt would otherwise become a\r\n * tight loop against our backend and theirs.\r\n */\r\n async #refreshSignal(): Promise<void> {\r\n const signal = this.provider.incomingSignal;\r\n if (!signal) return;\r\n if (this.now() < this.#signalRefreshAfter) return;\r\n this.#signalRefreshAfter = this.now() + SIGNAL_REFRESH_DEBOUNCE_MS;\r\n try {\r\n signal.disconnect();\r\n await signal.connect();\r\n } catch {\r\n // Still disconnected, and the signal reports that — the engine surfaces it as `offline`\r\n // rather than claiming a reachability it does not have.\r\n }\r\n }\r\n\r\n #clearNoInviteTimer(): void {\r\n if (this.#noInviteTimer) clearTimeout(this.#noInviteTimer);\r\n this.#noInviteTimer = undefined;\r\n }\r\n\r\n #onNewSession(session: JsSipSession, originator: 'local' | 'remote'): void {\r\n if (originator !== 'remote') return; // our own outbound legs are wired at placeCall\r\n this.#clearNoInviteTimer();\r\n\r\n if (this.#activeCall || this.now() < this.#rejectGuardUntil) {\r\n session.terminate({ status_code: 486, reason_phrase: 'Busy Here' });\r\n return;\r\n }\r\n const call = this.#wrapCall(session);\r\n for (const listener of [...this.#incomingListeners]) listener(call);\r\n }\r\n\r\n // ── UA lifecycle ───────────────────────────────────────────────────────────\r\n /**\r\n * The single UA, created at most once — even under concurrent callers.\r\n *\r\n * **The `#ua` check alone is not a guard**, because everything after it awaits: two callers both\r\n * see `null`, both `provision()`, both build a UA, and both REGISTER the same extension. Zadarma\r\n * rejects the loser, `registrationFailed` tears down, and the survivor may be the one that was\r\n * torn down. The visible symptom is two `get_webphone_data.php` calls at startup and a phone that\r\n * never registers.\r\n *\r\n * Concurrency is the normal case here, not an edge: the push socket can signal twice in a\r\n * heartbeat (SPEC §3.3 — a push is not an INVITE; it fires for transfers, retries and hangups),\r\n * and `placeCall` can land on top of one. So the in-flight promise IS the guard.\r\n */\r\n async #ensureUA(): Promise<JsSipUA> {\r\n if (this.#ua) return this.#ua;\r\n this.#uaInFlight ??= this.#createUA().finally(() => {\r\n this.#uaInFlight = null;\r\n });\r\n return this.#uaInFlight;\r\n }\r\n\r\n async #createUA(): Promise<JsSipUA> {\r\n const factory = await this.#resolveFactory();\r\n\r\n /*\r\n * Report what actually went wrong, not the layer that caught it.\r\n *\r\n * A rejected voice token, a token endpoint that is down, and a carrier returning no credential\r\n * are three problems with three different fixes; the lower layers already raise the precise\r\n * `auth/*` code. Only supply the generic one when nothing more specific is known.\r\n *\r\n * Inline rather than a helper method: an extra async frame is an extra microtask, and the\r\n * no-INVITE teardown is armed the moment this resolves (QUIRK 1).\r\n */\r\n let credentials: SipCredentials;\r\n try {\r\n credentials = await this.provider.provision();\r\n } catch (cause) {\r\n if (isSoftphoneError(cause)) this.#emitError(cause);\r\n else this.#reportError('provider/provision-failed', cause);\r\n throw cause;\r\n }\r\n this.#domain = domainOf(credentials);\r\n const config = this.#uaConfig(credentials, factory);\r\n const ua = factory.createUA(config);\r\n\r\n ua.on('newRTCSession', ({ session, originator }) => this.#onNewSession(session, originator));\r\n ua.on('disconnected', ({ error }) => {\r\n if (!error) return; // a clean close (our own teardown) is not a failure\r\n this.#setState('reconnecting');\r\n this.#reportError('net/transport-failed', error);\r\n });\r\n ua.on('connected', () => this.#setState('online'));\r\n ua.on('registrationFailed', (e) => {\r\n /*\r\n * On Zadarma the usual cause is geo-routing (SPEC §3.1): a registrar in the wrong datacenter\r\n * answers a bare 401 with no auth challenge. The registrar `domain` is what\r\n * `get_webphone_data.php` handed back, so it is the one detail that makes this diagnosable —\r\n * it rides along as the error's `cause` rather than only reaching a console nobody is reading.\r\n */\r\n const detail = e as { cause?: string; response?: { status_code?: number } } | undefined;\r\n this.#reportError('net/registration-failed', {\r\n cause: detail?.cause,\r\n status: detail?.response?.status_code,\r\n domain: this.#domain,\r\n hint: 'A bare 401 with no auth challenge usually means the registrar is in the wrong datacenter (SPEC §3.1).',\r\n });\r\n this.#teardownUA();\r\n void this.#refreshSignal();\r\n });\r\n\r\n this.#ua = ua;\r\n ua.start();\r\n return ua;\r\n }\r\n\r\n #uaConfig(credentials: SipCredentials, factory: JsSipFactory): JsSipUAConfig {\r\n return {\r\n sockets: [factory.createWebSocket(credentials.wsUrl)],\r\n uri: credentials.uri,\r\n authorization_user: credentials.authUser,\r\n password: credentials.password,\r\n register: true,\r\n register_expires: REGISTER_EXPIRES,\r\n connection_recovery_min_interval: 2,\r\n connection_recovery_max_interval: 30,\r\n // Generic — NOT a provider brand string. If a provider ever requires a specific UA header it\r\n // belongs in the provider, not hard-coded here.\r\n // NOT ours to choose: Zadarma refuses to register any client whose User-Agent it does not\r\n // recognise (see ProviderQuirks.userAgent). The provider decides; the engine just sends it.\r\n user_agent: this.provider.quirks?.userAgent ?? 'Coventia Softphone',\r\n };\r\n }\r\n\r\n #teardownUA(): void {\r\n this.#uaInFlight = null;\r\n if (!this.#ua) return;\r\n try {\r\n this.#ua.terminateSessions({ status_code: 487 });\r\n this.#ua.stop();\r\n } catch {\r\n /* already stopped */\r\n }\r\n this.#ua = null;\r\n this.#activeCall = null;\r\n this.#consultCall = null;\r\n }\r\n\r\n /** Place a call once the UA is registered (its 200 OK for REGISTER has arrived). */\r\n /**\r\n * **No `mediaStream`** — JsSIP calls `getUserMedia` itself, which is what opens a real capture.\r\n *\r\n * That is load-bearing, not incidental. Firefox restricts ICE gathering on a page with no active\r\n * capture: it discards every address but the default route's (\"Ignoring addr from interface other\r\n * than …\" in about:webrtc) and can end up gathering NOTHING, so the INVITE goes out with\r\n * `c=IN IP4 0.0.0.0` and no candidates at all. No STUN or TURN server can rescue an offer that\r\n * contains no candidates. The legacy hook passed `mediaConstraints` and nothing else, for what\r\n * turns out to be a very good reason.\r\n */\r\n #callWhenRegistered(ua: JsSipUA, target: string): Promise<JsSipSession> {\r\n const options = { mediaConstraints: buildAudioConstraints(this.#inputDeviceId), pcConfig: PC_CONFIG };\r\n if (ua.isRegistered()) return Promise.resolve(ua.call(target, options));\r\n return new Promise<JsSipSession>((resolve) => {\r\n ua.on('registered', () => resolve(ua.call(target, options)));\r\n });\r\n }\r\n\r\n #wrapCall(session: JsSipSession): SipEngineCall {\r\n const call = new SipEngineCall(session, {\r\n id: nextCallId(),\r\n buildTarget: (t) => this.#buildTarget(t),\r\n placeConsult: (t) => this.#placeConsult(t),\r\n // The guard is tied to the reject ACTION, not to `ended` — a normal hangup must not arm it.\r\n onReject: () => this.#startRejectGuard(),\r\n iceGatheringCapMs: this.provider.quirks?.iceGatheringCapMs ?? DEFAULT_ICE_CAP_MS,\r\n // Inbound answers open their own peer connection, so they need the same ICE servers the\r\n // outbound leg got. Missing here, an ANSWERED call is the one that fails — the half nobody\r\n // tests until a real person picks up.\r\n pcConfig: PC_CONFIG,\r\n // Read fresh at answer() time, not captured now — a device chosen while the phone is still\r\n // ringing must still apply once it is picked up.\r\n getInputDeviceId: () => this.#inputDeviceId,\r\n });\r\n\r\n this.#activeCall = call;\r\n call.onEvent((event) => {\r\n if (event.type === 'ended') {\r\n /*\r\n The outcome of a call, as a code the widget can show: \"Sin respuesta\", \"Llamada rechazada\".\r\n A normal hangup by either side is not an error.\r\n\r\n A MISSED call is the one outcome `reason` cannot carry on its own. The caller CANCELling\r\n while our phone rings is an ordinary `remote` ending, so it would pass in silence — and it\r\n is the case the user is least able to reconstruct, because they never saw the call. JsSIP\r\n sends the same `Canceled` cause when the user abandons their OWN outbound call, so the\r\n direction is what separates a call that was missed from one that was given up on.\r\n */\r\n const missed = call.direction === 'inbound' && event.cause === 'Canceled';\r\n const code = missed ? 'call/missed' : CALL_END_CODES[event.reason];\r\n // The raw cause rides along so a `call/failed` in a host's logs says which failure it was.\r\n if (code) this.#reportError(code, event.cause);\r\n if (this.#activeCall === call) this.#activeCall = null;\r\n this.#maybeTeardownUA();\r\n }\r\n });\r\n return call;\r\n }\r\n\r\n async #placeConsult(target: string): Promise<SipEngineCall> {\r\n const ua = await this.#ensureUA();\r\n const consultSession = ua.call(this.#buildTarget(target), {\r\n mediaConstraints: buildAudioConstraints(this.#inputDeviceId),\r\n pcConfig: PC_CONFIG,\r\n });\r\n const consultCall = new SipEngineCall(consultSession, {\r\n id: nextCallId(),\r\n buildTarget: (x) => this.#buildTarget(x),\r\n placeConsult: () => Promise.reject(new Error('cannot consult from a consult leg')),\r\n iceGatheringCapMs: this.provider.quirks?.iceGatheringCapMs ?? DEFAULT_ICE_CAP_MS,\r\n });\r\n this.#consultCall = consultCall;\r\n consultCall.onEvent((event) => {\r\n if (event.type === 'ended') {\r\n if (this.#consultCall === consultCall) this.#consultCall = null;\r\n this.#maybeTeardownUA();\r\n }\r\n });\r\n return consultCall;\r\n }\r\n\r\n /**\r\n * On-demand registration (SPEC §3.3): the UA is disposable once NOTHING is left on it — but \"the\r\n * main leg ended\" (or \"no INVITE followed this push\") is not the same fact as \"nothing is left.\"\r\n * `completeTransfer()` (SPEC §5.6) ends the main leg via a REFER…Replaces BYE *while the consult leg\r\n * is still what the PBX needs to bridge the caller onto* — tearing the UA down (and with it, EVERY\r\n * session on it, via `terminateSessions`) the instant the main leg's `ended` fires killed that\r\n * consult leg out from under the transfer before the bridge could use it, and the caller was simply\r\n * gone. Two real call sites hit this independently (found live, 2026-08-04): the main leg's own\r\n * `ended` handler, and `#armNoInviteTeardown`'s 5s timer — the latter re-arms on EVERY push,\r\n * including unrelated \"answered\" pushes Zadarma sends around other account activity, so it can fire\r\n * minutes after a transfer with no `#activeCall` and no idea a consult leg is mid-handoff. Both now\r\n * route through here rather than checking `#activeCall` alone.\r\n */\r\n #maybeTeardownUA(): void {\r\n if (this.provider.registrationMode !== 'on-demand') return;\r\n if (this.#activeCall || this.#consultCall) return;\r\n this.#teardownUA();\r\n }\r\n\r\n #startRejectGuard(): void {\r\n const ms = this.provider.quirks?.rejectGuardMs;\r\n if (ms) this.#rejectGuardUntil = this.now() + ms;\r\n }\r\n\r\n #buildTarget(target: string): string {\r\n return target.includes('@') ? target : `sip:${target}@${this.#domain}`;\r\n }\r\n\r\n #setState(state: SoftphoneState): void {\r\n if (state === this.#state) return;\r\n this.#state = state;\r\n for (const listener of [...this.#stateListeners]) listener(state);\r\n }\r\n}\r\n","import type { JsSipFactory, JsSipUA, JsSipUAConfig } from './jssip.js';\r\n\r\n/**\r\n * The REAL JsSipFactory — the only place `jssip` is loaded, via a **dynamic import** so that merely\r\n * importing `@coventia/softphone` never pulls it. jssip is CJS and touches browser globals; a static\r\n * import would break `import` under SSR (SPEC §10.2) and drag ~66 KB into every bundle.\r\n *\r\n * Because the import is async but `JsSipFactory.createUA` is sync, we load jssip once up front via\r\n * `loadJsSipFactory()` and hand back a fully-synchronous factory.\r\n */\r\n\r\ninterface JsSipModule {\r\n UA: new (config: JsSipUAConfig) => JsSipUA;\r\n WebSocketInterface: new (url: string) => unknown;\r\n}\r\n\r\nlet cached: JsSipFactory | null = null;\r\n\r\nexport async function loadJsSipFactory(): Promise<JsSipFactory> {\r\n if (cached) return cached;\r\n const mod = (await import('jssip')) as unknown as { default?: JsSipModule } & Partial<JsSipModule>;\r\n const JsSIP = (mod.default ?? mod) as JsSipModule;\r\n if (!JsSIP?.UA || !JsSIP?.WebSocketInterface) {\r\n throw new Error('jssip: unexpected module shape (no UA / WebSocketInterface)');\r\n }\r\n cached = {\r\n createWebSocket: (wsUrl) => new JsSIP.WebSocketInterface(wsUrl),\r\n createUA: (config) => new JsSIP.UA(config),\r\n };\r\n return cached;\r\n}\r\n","import type {\r\n IncomingSignal,\r\n ProviderQuirks,\r\n RegistrationMode,\r\n SipCredentials,\r\n SipProvider,\r\n} from './provider.js';\r\n\r\n/**\r\n * The Zadarma provider — the FIRST (and, for now, only) `SipProvider`. Everything Zadarma-specific\r\n * that the generic SIP engine (`transports/sip/`) must not know lives here, expressed as data the\r\n * engine reads (SPEC §5.4).\r\n *\r\n * Network I/O is INJECTED (`ZadarmaDeps`) for two reasons: the JSONP exchange and the push socket\r\n * are browser-only, and the quirk tests (SPEC §3, the S4 safety net) must drive this without a\r\n * browser, a network, or a real call.\r\n */\r\n\r\n/**\r\n * The presence heartbeat Zadarma's push gateway expects, and how long before key expiry we rebuild\r\n * the socket. Both are Zadarma's numbers, carried over from the CRM hook that ran them in production.\r\n */\r\nconst PING = { localMs: 30_000, globalMs: 60_000 } as const;\r\nconst KEY_REFRESH_BUFFER_MS = 2 * 60 * 60 * 1000;\r\n\r\n/** The Zadarma quirk-timer values (SPEC §3). The engine reads these; it never hard-codes them. */\r\nexport const ZADARMA_QUIRKS: ProviderQuirks = {\r\n // Zadarma's registrar REFUSES to register a WebRTC client with any other User-Agent — a clean 401\r\n // after a valid digest challenge, indistinguishable from a wrong password (§3.1). The old CRM\r\n // hook carried this string; the port dropped it, and registration failed for exactly that reason.\r\n userAgent: 'Zadarma webRTC',\r\n // Zadarma re-rings a declined call for ~30 s (return_timeout). Swallow those (§3.4).\r\n rejectGuardMs: 35_000,\r\n // A push is not an INVITE (§3.3). If none arrives, tear the fresh UA down.\r\n noInviteTeardownMs: 5_000,\r\n // A ceiling on ICE gathering, not a target: JsSIP sends as soon as gathering completes. 3 s leaves\r\n // room for a TURN allocation (whose relay candidates arrive last) while still bounding the ~40 s\r\n // Chrome can spend against an unreachable server. See `capIceGathering`.\r\n iceGatheringCapMs: 3_000,\r\n};\r\n\r\nexport interface ZadarmaKeyResponse {\r\n readonly key: string;\r\n readonly sip: string;\r\n readonly keyExpiresAt?: string;\r\n}\r\n\r\n/** The minimal push-socket surface we consume (Zadarma's Socket.IO v2 gateway). */\r\nexport interface ZadarmaPushSocket {\r\n on(event: 'connect' | 'disconnect' | 'connect_error' | 'update', cb: () => void): void;\r\n /**\r\n * Send to the gateway. Needed for the presence pings — see `PING`.\r\n *\r\n * Its absence is why the extension went offline after a few idle minutes: the socket cannot be\r\n * kept alive by a client that has no way to say anything on it.\r\n */\r\n emit(event: string, payload?: unknown): void;\r\n close(): void;\r\n readonly connected: boolean;\r\n}\r\n\r\nexport interface ZadarmaDeps {\r\n /**\r\n * Fetch `{ key, sip }` from the Coventia backend (authenticated with the voice token upstream).\r\n * The key is a scoped, refreshable credential — NEVER a stored SIP password (SPEC §6.4, §6.5).\r\n */\r\n fetchKey(): Promise<ZadarmaKeyResponse>;\r\n\r\n /**\r\n * Exchange the key for ephemeral SIP credentials. MUST run in the browser: Zadarma geo-routes the\r\n * registrar `domain` (and the matching `pass`) to the caller's region (SPEC §3.1). The returned\r\n * password is ephemeral and must never be persisted.\r\n */\r\n exchangeWebphoneData(key: string, sip: string): Promise<{ pass: string; domain: string }>;\r\n\r\n /** Open the Zadarma push socket for a `(key, sip)`. */\r\n createPushSocket(url: string): ZadarmaPushSocket;\r\n\r\n /**\r\n * OPTIONAL: proactively rebuild the push socket, via `cb`, while the tab is hidden.\r\n *\r\n * The obvious fix — ping more often — does not work: `push-socket-reliability.md` §5.2 confirmed\r\n * empirically that Zadarma's gateway is keyed to the raw Engine.IO ping specifically, and that ping\r\n * dies under background-tab timer throttling no matter how much other traffic the socket carries.\r\n * Rather than trying to keep a fragile internal timer alive, `cb` tears the connection down and\r\n * rebuilds it on a schedule safely inside the failure window (§5.3) — a fresh socket always gets\r\n * its own fresh, reliably-successful first ping cycle.\r\n *\r\n * Returns a teardown function. Omitted (tests, SSR, no `Worker`) and `ZadarmaPushSignal` simply\r\n * does not self-heal in the background — exactly today's behaviour.\r\n */\r\n watchBackgroundReconnect?(cb: () => void): () => void;\r\n}\r\n\r\n/** `wss://ws.zadarma.com/webrtc_pushes?key=…&integrationType=site&sipId=…` */\r\nexport function buildPushUrl(key: string, sip: string): string {\r\n const params = new URLSearchParams({ key, integrationType: 'site', sipId: sip });\r\n return `wss://ws.zadarma.com/webrtc_pushes?${params.toString()}`;\r\n}\r\n\r\n/**\r\n * The push socket as an `IncomingSignal`. Its `connect()` fetches a key and opens the socket; a\r\n * Zadarma `update` becomes an out-of-band incoming signal the engine reacts to (SPEC §3.2–3.3).\r\n *\r\n * The engine deliberately does NOT ring on this signal — it rings on the SIP INVITE. This only tells\r\n * the engine to register a UA so Zadarma will *send* the INVITE.\r\n */\r\nexport class ZadarmaPushSignal implements IncomingSignal {\r\n #socket: ZadarmaPushSocket | null = null;\r\n #connected = false;\r\n #pingTimers: Array<ReturnType<typeof setInterval>> = [];\r\n #refreshTimer: ReturnType<typeof setTimeout> | undefined;\r\n #unwatchBackground: (() => void) | undefined;\r\n #closed = false;\r\n readonly #listeners = new Set<() => void>();\r\n readonly #connectionListeners = new Set<(connected: boolean) => void>();\r\n\r\n constructor(private readonly deps: ZadarmaDeps) {}\r\n\r\n async connect(): Promise<void> {\r\n if (this.#socket) return;\r\n this.#closed = false;\r\n // Armed once per signal lifetime, not per reopen — `#reopen()` itself is the callback.\r\n this.#unwatchBackground ??= this.deps.watchBackgroundReconnect?.(() => void this.#reopen());\r\n await this.#open();\r\n }\r\n\r\n async #open(): Promise<void> {\r\n const { key, sip, keyExpiresAt } = await this.deps.fetchKey();\r\n if (this.#closed) return;\r\n\r\n const socket = this.deps.createPushSocket(buildPushUrl(key, sip));\r\n this.#socket = socket;\r\n\r\n socket.on('connect', () => {\r\n this.#setConnected(true);\r\n this.#startPings(socket);\r\n });\r\n socket.on('update', () => this.#emit());\r\n // Both mean the same thing to us: no INVITE can arrive right now.\r\n socket.on('disconnect', () => {\r\n this.#stopPings();\r\n this.#setConnected(false);\r\n });\r\n socket.on('connect_error', () => {\r\n this.#stopPings();\r\n this.#setConnected(false);\r\n });\r\n\r\n this.#armRefresh(keyExpiresAt);\r\n }\r\n\r\n /**\r\n * Presence pings — **the reason an idle tab keeps receiving calls**.\r\n *\r\n * Zadarma's gateway decides whether the extension is online, and it decides from these. Without\r\n * them the socket goes quiet, Zadarma marks the extension offline within minutes, and INVITEs stop\r\n * being routed — with no error anywhere, because nothing failed. The only visible symptom is that\r\n * the phone silently stops ringing until the page is reloaded.\r\n *\r\n * The names and intervals are Zadarma's, taken from the CRM hook that ran this in production for\r\n * years. They are not ours to tune.\r\n */\r\n #startPings(socket: ZadarmaPushSocket): void {\r\n this.#stopPings();\r\n this.#pingTimers = [\r\n setInterval(() => socket.emit('localPing', {}), PING.localMs),\r\n setInterval(() => socket.emit('globalPing', {}), PING.globalMs),\r\n ];\r\n }\r\n\r\n #stopPings(): void {\r\n for (const t of this.#pingTimers) clearInterval(t);\r\n this.#pingTimers = [];\r\n }\r\n\r\n /**\r\n * Rebuild the socket before the WebRTC key expires.\r\n *\r\n * The key is baked into the socket URL, so socket.io's own reconnection re-presents whatever it was\r\n * given at construction. A tab left open past the key's 72 h lifetime would reconnect forever with\r\n * a dead credential. Absolute, from the backend's `key_expires_at`, so it targets the real expiry\r\n * rather than restarting a countdown on every reconnect.\r\n */\r\n #armRefresh(keyExpiresAt: string | undefined): void {\r\n clearTimeout(this.#refreshTimer);\r\n if (!keyExpiresAt) return;\r\n const ms = new Date(keyExpiresAt).getTime() - Date.now() - KEY_REFRESH_BUFFER_MS;\r\n if (!Number.isFinite(ms) || ms <= 0) return;\r\n this.#refreshTimer = setTimeout(() => void this.#reopen(), ms);\r\n }\r\n\r\n async #reopen(): Promise<void> {\r\n if (this.#closed) return;\r\n this.#stopPings();\r\n this.#socket?.close();\r\n this.#socket = null;\r\n this.#setConnected(false);\r\n try {\r\n await this.#open();\r\n } catch {\r\n // A failed refresh leaves us disconnected and SAYING so, which is the point: the engine can\r\n // surface it instead of the phone quietly never ringing again.\r\n }\r\n }\r\n\r\n disconnect(): void {\r\n this.#closed = true;\r\n this.#stopPings();\r\n clearTimeout(this.#refreshTimer);\r\n this.#refreshTimer = undefined;\r\n this.#unwatchBackground?.();\r\n this.#unwatchBackground = undefined;\r\n this.#socket?.close();\r\n this.#socket = null;\r\n this.#setConnected(false);\r\n }\r\n\r\n onSignal(listener: () => void): () => void {\r\n this.#listeners.add(listener);\r\n return () => this.#listeners.delete(listener);\r\n }\r\n\r\n onConnectionChange(listener: (connected: boolean) => void): () => void {\r\n this.#connectionListeners.add(listener);\r\n return () => this.#connectionListeners.delete(listener);\r\n }\r\n\r\n get connected(): boolean {\r\n return this.#connected;\r\n }\r\n\r\n #setConnected(connected: boolean): void {\r\n if (this.#connected === connected) return;\r\n this.#connected = connected;\r\n for (const listener of [...this.#connectionListeners]) listener(connected);\r\n }\r\n\r\n #emit(): void {\r\n for (const listener of [...this.#listeners]) listener();\r\n }\r\n}\r\n\r\nexport class ZadarmaProvider implements SipProvider {\r\n readonly name = 'zadarma';\r\n // Zadarma's PBX ignores a standing registration — it routes INVITEs only to a UA that registered\r\n // in response to a push (SPEC §3.2). Hence on-demand.\r\n readonly registrationMode: RegistrationMode = 'on-demand';\r\n readonly quirks: ProviderQuirks = ZADARMA_QUIRKS;\r\n readonly incomingSignal: IncomingSignal;\r\n\r\n constructor(private readonly deps: ZadarmaDeps) {\r\n this.incomingSignal = new ZadarmaPushSignal(deps);\r\n }\r\n\r\n /**\r\n * Per-registration credentialing: fetch a scoped key, then exchange it in the browser for\r\n * ephemeral SIP creds. The key fetch is cheap and backend-cached; doing it here (rather than\r\n * sharing state with the push signal) keeps the two paths independent.\r\n */\r\n async provision(): Promise<SipCredentials> {\r\n const { key, sip } = await this.deps.fetchKey();\r\n const { pass, domain } = await this.deps.exchangeWebphoneData(key, sip);\r\n return {\r\n uri: `sip:${sip}@${domain}`,\r\n authUser: sip,\r\n password: pass,\r\n wsUrl: `wss://${domain}:4443`,\r\n };\r\n }\r\n}\r\n","import type { TokenSource } from '../../core/types.js';\r\nimport { invalidateToken } from '../../core/token-cache.js';\r\nimport { createError } from '../../core/errors.js';\r\nimport type { ZadarmaDeps, ZadarmaKeyResponse, ZadarmaPushSocket } from './zadarma.js';\r\n\r\n/** The key fetch was refused. Distinct so only THIS failure triggers a token re-mint. */\r\nclass UnauthorizedKeyError extends Error {}\r\n\r\n/**\r\n * The REAL, browser-only Zadarma network deps: the backend key fetch, the JSONP credential exchange,\r\n * and the Socket.IO v2 push socket. Isolated here (not in zadarma.ts) so the provider stays\r\n * unit-testable and so these browser globals never enter the SSR import path — `socket.io-client` is\r\n * dynamically imported, and every function touches `window`/`document`/`fetch` only when called\r\n * (SPEC §10.2).\r\n *\r\n * Ported from the legacy `useSipUA.js` / `useZadarmaWebrtcLogin.js`, with the geo-routing rationale\r\n * intact (SPEC §3.1).\r\n */\r\n\r\nexport interface ZadarmaBrowserConfig {\r\n /** Coventia backend base URL, e.g. `https://api.coventia.es`. */\r\n readonly apiBase: string;\r\n /** Provides the auth token for the backend key fetch. */\r\n readonly tokenSource: TokenSource;\r\n /** Selected organization id, appended to the key request. */\r\n readonly organizationId?: string | undefined;\r\n}\r\n\r\n/**\r\n * Fetch `{ key, sip }` from the Coventia backend.\r\n *\r\n * Today this targets the existing `/phone/webrtc/key`, authenticated with the CRM's own session.\r\n * Phase 2 moves it to `/api/v1/phone/webrtc/key`, authenticated with a voice token and CORS-gated —\r\n * which is what lets a PARTNER's browser call it from their origin (SPEC §6.6, hop ③). Only the URL\r\n * and the credential change; this function's shape does not, which is the point.\r\n *\r\n * The key is a scoped, refreshable credential — never a stored SIP password (SPEC §6.4).\r\n */\r\nexport function makeFetchKey(config: ZadarmaBrowserConfig): () => Promise<ZadarmaKeyResponse> {\r\n const attempt = async (): Promise<ZadarmaKeyResponse> => {\r\n // The host's own endpoint failing is a DIFFERENT failure from us refusing their token, and the\r\n // fix differs too — \"your broker is down\" vs \"mint a fresh one\". Flattening both into one code\r\n // would send an integrator to the wrong place.\r\n let token: string;\r\n try {\r\n ({ token } = await config.tokenSource.getToken());\r\n } catch (cause) {\r\n throw createError('auth/token-fetch-failed', cause);\r\n }\r\n const qs = config.organizationId\r\n ? `?organization_id=${encodeURIComponent(config.organizationId)}`\r\n : '';\r\n const res = await fetch(`${config.apiBase}/phone/webrtc/key${qs}`, {\r\n headers: { Authorization: token },\r\n });\r\n if (!res.ok) {\r\n const body = (await res.json().catch(() => null)) as { message?: string } | null;\r\n const message = body?.message ?? `webrtc/key HTTP ${res.status}`;\r\n throw res.status === 401 ? new UnauthorizedKeyError(message) : new Error(message);\r\n }\r\n const data = (await res.json()) as {\r\n key: string;\r\n sip: string;\r\n key_expires_at?: string;\r\n };\r\n return {\r\n key: data.key,\r\n sip: data.sip,\r\n ...(data.key_expires_at ? { keyExpiresAt: data.key_expires_at } : {}),\r\n };\r\n };\r\n\r\n /*\r\n * Retry once on 401 with a fresh token — same reasoning as `createGet`, and it matters more here:\r\n * this runs per registration, so a token revoked mid-session would otherwise block every call\r\n * until its TTL elapsed.\r\n */\r\n return async () => {\r\n try {\r\n return await attempt();\r\n } catch (error) {\r\n if (!(error instanceof UnauthorizedKeyError)) throw error;\r\n invalidateToken(config.tokenSource);\r\n try {\r\n return await attempt();\r\n } catch (retryError) {\r\n // Refused twice, the second time with a freshly minted token — so the credential itself is\r\n // rejected, not merely stale.\r\n if (retryError instanceof UnauthorizedKeyError) {\r\n throw createError('auth/token-rejected', retryError);\r\n }\r\n throw retryError;\r\n }\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * Exchange the key for `{ pass, domain }` via Zadarma's `get_webphone_data.php`.\r\n *\r\n * **MUST run in the browser** (SPEC §3.1) — this is the load-bearing constraint and it has not\r\n * changed: Zadarma geo-routes the registrar `domain`, and the `pass` that matches it, to the\r\n * datacenter nearest the *caller's* IP. Called server-side it pins every user to the backend's\r\n * region and REGISTER is refused.\r\n *\r\n * **`fetch`, not a `<script>` tag.** The endpoint is JSONP-shaped — it always answers\r\n * `callbackName({...})`, with no raw-JSON mode — but it now sends `Access-Control-Allow-Origin: *`,\r\n * so the response is readable and the wrapper is just text to strip. Verified against the live\r\n * endpoint before switching.\r\n *\r\n * The old `<script>` injection worked, but cost three things:\r\n * - **A console warning on every call.** The response is served as `application/json`, and a\r\n * classic script with a non-JS MIME type warns in Firefox (\"loaded despite its MIME type…\").\r\n * It executes, so it was harmless — but it is noise in a console that should stay readable, and\r\n * nothing on our side could silence it.\r\n * - **A CSP demand we should not make.** A `<script src>` to a third-party origin needs\r\n * `script-src https://api.zadarma.com` — permission to EXECUTE their code. `fetch` needs\r\n * `connect-src`, which is permission to TALK to them. For a reseller embedding this SDK that is\r\n * a materially smaller ask (SPEC §7, Phase 3: we publish the CSP directives).\r\n * - **A global.** A `window[cbName]` per exchange, plus a `<script>` in `<head>` to clean up.\r\n *\r\n * What we keep is real error handling: an HTTP status, a network failure and a timeout are now\r\n * distinguishable, where a `<script>` could only ever report \"onerror\".\r\n */\r\nexport async function exchangeWebphoneData(\r\n key: string,\r\n sip: string,\r\n timeoutMs = 10_000,\r\n): Promise<{ pass: string; domain: string }> {\r\n const params = new URLSearchParams({\r\n // Still sent: the endpoint wraps its response either way, and naming the callback keeps the\r\n // wrapper predictable rather than relying on their default.\r\n jsonpCallback: 'cv',\r\n integrationType: 'site',\r\n key,\r\n sipId: sip,\r\n });\r\n\r\n let res: Response;\r\n try {\r\n res = await fetch(\r\n `https://api.zadarma.com/sys/webrtc/get_webphone_data.php?${params.toString()}`,\r\n { signal: AbortSignal.timeout(timeoutMs) },\r\n );\r\n } catch (cause) {\r\n const timedOut = cause instanceof DOMException && cause.name === 'TimeoutError';\r\n throw new Error(timedOut ? 'get_webphone_data timed out' : 'get_webphone_data network error', {\r\n cause,\r\n });\r\n }\r\n if (!res.ok) throw new Error(`get_webphone_data HTTP ${res.status}`);\r\n\r\n const data = parseJsonp(await res.text());\r\n if (!data || data.error || !data.pass || !data.domain) {\r\n throw new Error(data?.error?.content ?? 'get_webphone_data: missing SIP credentials');\r\n }\r\n return { pass: data.pass, domain: data.domain };\r\n}\r\n\r\ninterface WebphoneData {\r\n error?: { content?: string };\r\n pass?: string;\r\n domain?: string;\r\n}\r\n\r\n/**\r\n * `cv({...})` → the object.\r\n *\r\n * Sliced between the FIRST `(` and the LAST `)` rather than matched against the callback name we\r\n * sent: the endpoint ignores an empty `jsonpCallback` and falls back to its own literal\r\n * `jsonpCallback(...)`, so trusting the name we asked for would break on a response we can see it\r\n * actually returns.\r\n */\r\nfunction parseJsonp(text: string): WebphoneData | null {\r\n const open = text.indexOf('(');\r\n const close = text.lastIndexOf(')');\r\n const body = open !== -1 && close > open ? text.slice(open + 1, close) : text;\r\n try {\r\n return JSON.parse(body) as WebphoneData;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Open the Zadarma push socket (Socket.IO **v2** — their gateway is v2, hence the pinned dependency).\r\n * `socket.io-client` is dynamically imported so it never enters the SSR bundle.\r\n *\r\n * Note: because the ZadarmaPushSocket surface is synchronous but the socket.io import is async, the\r\n * returned wrapper connects lazily and buffers `on()` registrations until the client is ready.\r\n */\r\nexport function createPushSocket(url: string): ZadarmaPushSocket {\r\n const handlers = new Map<string, Array<() => void>>();\r\n let client: {\r\n on(e: string, cb: () => void): void;\r\n emit(e: string, payload?: unknown): void;\r\n close(): void;\r\n connected?: boolean;\r\n } | null = null;\r\n let closed = false;\r\n\r\n void (async () => {\r\n // A LITERAL specifier, and it must stay one. This was `const s = 'socket.io-client-v2'` behind an\r\n // indirection to dodge TS7016 on an untyped module — which no bundler can statically analyse, so\r\n // the browser got a bare specifier, the push socket never connected, `start()` rejected, and the\r\n // softphone never reached `online`. The types now come from `src/socket-io.d.ts`, which is what\r\n // should have solved it in the first place (`jssip` was always a literal and always worked).\r\n const mod = await import('socket.io-client-v2');\r\n if (closed) return;\r\n // v2's connector arrives as `default` under ESM interop and as `io` when it does not.\r\n const connect = mod.default ?? mod.io;\r\n if (!connect) throw new Error('socket.io-client-v2: no connect export');\r\n const c = connect(url, {\r\n transports: ['websocket'],\r\n reconnection: true,\r\n // The push socket drops on a schedule under background-tab timer throttling, NOT from network\r\n // flakiness — every reconnect observed succeeds on the first attempt (push-socket-reliability.md\r\n // §2.3, §5.1). There is nothing to back off from on that first attempt, so waiting the old 10s\r\n // before retrying was pure, uncontested exposure — an inbound call landing in that window is\r\n // lost, unqueued (Zadarma's gateway speaks EIO3, no offline redelivery). `reconnectionDelayMax`\r\n // stays as the ceiling for a genuinely down gateway, where backing off still matters.\r\n reconnectionDelay: 300,\r\n reconnectionDelayMax: 30_000,\r\n });\r\n client = c;\r\n for (const [event, cbs] of handlers) for (const cb of cbs) c!.on(event, cb);\r\n })();\r\n\r\n return {\r\n on(event, cb) {\r\n const list = handlers.get(event) ?? [];\r\n list.push(cb);\r\n handlers.set(event, list);\r\n client?.on(event, cb);\r\n },\r\n emit(event, payload) {\r\n // Dropped rather than queued when the client is not up yet: every caller is a periodic ping,\r\n // so the next one is seconds away and a replayed backlog would be worse than a missed beat.\r\n client?.emit(event, payload);\r\n },\r\n close() {\r\n closed = true;\r\n client?.close();\r\n },\r\n get connected() {\r\n return client?.connected ?? false;\r\n },\r\n };\r\n}\r\n\r\n/** How long the tab can stay hidden before we proactively rebuild the socket. See `watchBackgroundReconnect`. */\r\nconst BACKGROUND_RECONNECT_MS = 20_000;\r\n\r\n/**\r\n * The Worker's entire job: an alarm clock, nothing else. It owns no socket state and knows nothing\r\n * about Zadarma — Chrome does not apply background-tab timer throttling to Worker threads, only to\r\n * the page's own JS context, so ticking here stays reliable exactly where `setInterval` on the main\r\n * thread was proven not to be (`push-socket-reliability.md` §5.2, §5.3). `start`/`stop` rather than\r\n * a fire-and-forget interval so the SAME worker can be reused across every hidden/visible cycle in a\r\n * session instead of being spun up and torn down each time.\r\n */\r\nconst HEARTBEAT_WORKER_SOURCE = `\r\n let timer;\r\n self.onmessage = (e) => {\r\n if (e.data.type === 'start') timer = setInterval(() => self.postMessage('tick'), e.data.intervalMs);\r\n else if (e.data.type === 'stop') { clearInterval(timer); timer = undefined; }\r\n };\r\n`;\r\n\r\n/**\r\n * Proactively rebuilds the push socket, via `cb`, on a schedule while the tab is hidden — the real\r\n * implementation of the optional `ZadarmaDeps` seam (`zadarma.ts`).\r\n *\r\n * **Constructed lazily, only when called** (SPEC §10.3 — no browser globals at module scope): safe\r\n * to import on a server, and a host that never calls it (tests, an environment with no `Worker`)\r\n * pays nothing.\r\n */\r\nexport function watchBackgroundReconnect(cb: () => void): () => void {\r\n if (typeof document === 'undefined' || typeof Worker === 'undefined') return () => {};\r\n\r\n let worker: Worker | null = null;\r\n let blobUrl: string | null = null;\r\n\r\n const ensureWorker = (): Worker => {\r\n if (!worker) {\r\n blobUrl = URL.createObjectURL(new Blob([HEARTBEAT_WORKER_SOURCE], { type: 'application/javascript' }));\r\n worker = new Worker(blobUrl);\r\n worker.onmessage = (e: MessageEvent) => {\r\n if (e.data === 'tick') cb();\r\n };\r\n }\r\n return worker;\r\n };\r\n\r\n const onVisibilityChange = (): void => {\r\n if (document.visibilityState === 'hidden') {\r\n ensureWorker().postMessage({ type: 'start', intervalMs: BACKGROUND_RECONNECT_MS });\r\n } else {\r\n worker?.postMessage({ type: 'stop' });\r\n }\r\n };\r\n\r\n document.addEventListener('visibilitychange', onVisibilityChange);\r\n // A signal can `connect()` while the tab is already hidden (e.g. a backgrounded pre-loaded tab).\r\n if (document.visibilityState === 'hidden') onVisibilityChange();\r\n\r\n return () => {\r\n document.removeEventListener('visibilitychange', onVisibilityChange);\r\n worker?.postMessage({ type: 'stop' });\r\n worker?.terminate();\r\n if (blobUrl) URL.revokeObjectURL(blobUrl);\r\n };\r\n}\r\n\r\n/** Assemble the real browser deps for a `ZadarmaProvider`. */\r\nexport function makeZadarmaBrowserDeps(config: ZadarmaBrowserConfig): ZadarmaDeps {\r\n return {\r\n fetchKey: makeFetchKey(config),\r\n exchangeWebphoneData: (key, sip) => exchangeWebphoneData(key, sip),\r\n createPushSocket,\r\n watchBackgroundReconnect,\r\n };\r\n}\r\n","import { SipCallEngine } from './sip/ua.js';\r\nimport { loadJsSipFactory } from './sip/real-factory.js';\r\nimport { ZadarmaProvider } from './providers/zadarma.js';\r\nimport { makeZadarmaBrowserDeps, type ZadarmaBrowserConfig } from './providers/zadarma-browser.js';\r\nimport { cachedTokenSource } from '../core/token-cache.js';\r\nimport type { CallEngine } from '../core/engine.js';\r\n\r\n/**\r\n * Assemble a production Zadarma call engine: the real browser deps (backend key fetch + JSONP\r\n * exchange + push socket) → `ZadarmaProvider` → `SipCallEngine`, with jssip loaded lazily via a\r\n * dynamic import (SPEC §10.2 — importing the package stays SSR-safe).\r\n *\r\n * This is the real thing the app and the e2e smoke test use. It is intentionally NOT the automatic\r\n * default of `createSoftphone` yet — the app wires it explicitly in S9, and the voice-token endpoint\r\n * migration is Phase 2 (SPEC §6).\r\n */\r\nexport function createZadarmaEngine(config: ZadarmaBrowserConfig): CallEngine {\r\n // Cached here as well as in `createSoftphone`: a host passes the same `TokenSource` object to both,\r\n // and `cachedTokenSource` is keyed on that object — so the two share ONE token rather than minting\r\n // one each. Without this the WebRTC-key fetch, which runs per registration, would be uncached.\r\n const provider = new ZadarmaProvider(\r\n makeZadarmaBrowserDeps({ ...config, tokenSource: cachedTokenSource(config.tokenSource) }),\r\n );\r\n return new SipCallEngine(provider, loadJsSipFactory);\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sources.ts","../src/coventia/api.ts","../src/coventia/sources.ts"],"names":["resolve"],"mappings":";;;AAqBO,SAAS,SAAS,MAAA,EAAwB;AAC/C,EAAA,OAAO,OAAO,MAAA,IAAU,EAAE,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/C;AAaO,SAAS,qBAAA,CAAsB,KAAgC,MAAA,EAA+B;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MACtB,CAAA,GAAG;AAAA,IACL,CAAC,CAAA;AAAA,EACH,CAAA;AAEA,EAAA,MAAM,QAAA,GAAW,OAAO,QAAA,IAAY,gBAAA;AASpC,EAAA,MAAM,OAAA,GACJ,OAAO,cAAA,KACN,MAAA,CAAO,WAAW,oBAAA,CAAqB,MAAA,CAAO,QAAQ,CAAA,GAAI,eAAA,CAAA;AAK7D,EAAA,MAAM,OAAA,GAAU,kBAAA,CAAmB,UAAA,EAAY,OAAO,CAAA;AAEtD,EAAA,MAAM,gBAAA,GAAmB,OAAO,gBAAA,IAAoB,wBAAA;AACpD,EAAA,MAAM,QAAA,GAAW,OAAO,QAAA,IAAY,gBAAA;AAEpC,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA,EAAgB,OAAA;AAAA,IAChB,UAAA,EAAY,kBAAA;AAAA,IACZ,gBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"sources-5L2R4HTV.js","sourcesContent":["/**\r\n * **Internal.** Not exported from any entry point.\r\n *\r\n * The rules that are about **phone numbers and names** rather than about any backend: universal,\r\n * easy to get subtly wrong, and worth getting right once.\r\n *\r\n * These were public while a host had to build their own sources. They no longer do — a provider\r\n * supplies `coventia.contacts` and everything else (caller ID, history names) is derived from it in\r\n * `coventia/sources.ts`, the only caller left. Exported API is a contract owed forever, so it should\r\n * not outlive its consumers.\r\n */\r\nimport type { Contact } from './core/types.js';\r\nimport type { CallHistoryEntry, HistorySource } from './ui/types.js';\r\n\r\n/**\r\n * A number reduced to the digits telephony actually matches on — `'+34 600 111 222'` → `'34600111222'`.\r\n *\r\n * Comparing numbers as raw strings is the bug this exists to prevent: the same line arrives as\r\n * `+34600111222` from a SIP header, `34600111222` from a database, and `+34 600 111 222` from a human,\r\n * and all three are one contact.\r\n */\r\nexport function toDigits(number: string): string {\r\n return String(number ?? '').replace(/\\D/g, '');\r\n}\r\n\r\n/**\r\n * Decide whether a resolved string is really a **name** — the \"don't echo the bare number\" rule.\r\n *\r\n * A contact saved as its own number (\"+34 600 111 222\") resolves to a \"name\" that is just the number\r\n * reformatted. Showing it puts `+34600111222` where a name belongs, or worse, a *differently*\r\n * formatted copy of the number the widget is already displaying an inch away.\r\n *\r\n * This is the SDK deciding what it is willing to call a name, so it holds for every host — not only\r\n * for a backend that happens to be careful. Returns `null` when there is no name worth showing, which\r\n * is the signal to keep displaying the number.\r\n */\r\nexport function normalizeResolvedName(raw: string | null | undefined, number: string): string | null {\r\n if (!raw) return null;\r\n const trimmed = String(raw).trim();\r\n if (!trimmed) return null;\r\n const digits = toDigits(number);\r\n if (!digits) return trimmed;\r\n return toDigits(trimmed) === digits ? null : trimmed;\r\n}\r\n\r\n/**\r\n * Wrap a `HistorySource` so its entries get caller names, resolved once per distinct number.\r\n *\r\n * A call log is the same handful of numbers over and over, so the naive \"resolve each row\" costs a\r\n * request per row and hammers the backend with duplicates. This dedupes **by digits** (see\r\n * `toDigits` — `+34600111222` and `34600111222` are one lookup), caches across pages, and remembers\r\n * misses so an unknown number is not re-asked forever.\r\n *\r\n * A failed lookup leaves the entry's `name` null and is NOT cached, so a later page retries: the\r\n * number is still callable, and an unreachable name service must not empty the tab.\r\n *\r\n * const history = withNameResolution(myHistorySource, myResolveContact);\r\n */\r\nexport function withNameResolution(\r\n source: HistorySource,\r\n resolve: (number: string, signal?: AbortSignal) => Promise<Contact | null>,\r\n): HistorySource {\r\n const cache = new Map<string, string | null>();\r\n\r\n return async (params) => {\r\n const entries = await source(params);\r\n\r\n // Only entries that still NEED a name. A source that already knows one (its own join, its own\r\n // cache) must not cost a lookup — the numbers it named are not our business.\r\n const wanted = [\r\n ...new Set(entries.filter((e) => e.name === null).map((e) => toDigits(e.number))),\r\n ].filter((d) => d !== '' && !cache.has(d));\r\n await Promise.all(\r\n wanted.map(async (digits) => {\r\n try {\r\n const contact = await resolve(digits);\r\n cache.set(digits, normalizeResolvedName(contact?.name ?? null, digits));\r\n } catch {\r\n // Deliberately not cached — a transient failure must not become a permanent blank.\r\n }\r\n }),\r\n );\r\n\r\n return entries.map((e): CallHistoryEntry => {\r\n // Never overwrite a name the source already knew.\r\n if (e.name !== null) return e;\r\n const resolved = cache.get(toDigits(e.number)) ?? null;\r\n return resolved === null ? e : { ...e, name: resolved };\r\n });\r\n };\r\n}\r\n","import { invalidateToken } from '../core/token-cache.js';\r\nimport type { TokenSource } from '../core/types.js';\r\n\r\n/** A failed backend call. `status` is the HTTP status, or 0 when the request never completed. */\r\nexport class ApiError extends Error {\r\n readonly status: number;\r\n\r\n constructor(status: number, message: string) {\r\n super(message);\r\n this.name = 'ApiError';\r\n this.status = status;\r\n }\r\n}\r\n\r\nexport type QueryParams = Readonly<Record<string, string | number | undefined>>;\r\n\r\n/**\r\n * A minimal authenticated GET against Coventia's phone service.\r\n *\r\n * Lives under `coventia/` rather than `core/`: the core ships no HTTP at all, so a partner on their\r\n * own backend never loads this.\r\n */\r\ninterface RequestConfig {\r\n readonly baseUrl: string;\r\n readonly tokenSource: TokenSource;\r\n readonly fetch?: typeof globalThis.fetch;\r\n}\r\n\r\n/**\r\n * Shared by `createGet` and `createPost`: one attempt against the backend, with the 401-retry-once\r\n * policy both need (see `createGet`'s own note on why). `method` is the only thing that differs\r\n * between the two — this backend's phone routes take every parameter as a query string, GET or POST\r\n * alike (the presence ticket mint is a POST with no body, `organization_id` on the query, same as any\r\n * GET here), so there is nothing else for a request body to carry.\r\n */\r\nfunction createRequest(config: RequestConfig, method: 'GET' | 'POST') {\r\n // Bound, not passed by reference: an unbound `fetch` throws \"Illegal invocation\" in some browsers.\r\n const doFetch: typeof globalThis.fetch = config.fetch\r\n ? config.fetch\r\n : (...args) => globalThis.fetch(...args);\r\n const base = config.baseUrl.replace(/\\/+$/, '');\r\n\r\n /**\r\n * One attempt. Split out so a 401 can be retried exactly once with a fresh token — see the\r\n * returned function's own note.\r\n */\r\n async function attempt<T>(path: string, params: QueryParams, signal?: AbortSignal): Promise<T> {\r\n const { token } = await config.tokenSource.getToken(signal);\r\n const qs = new URLSearchParams();\r\n for (const [k, v] of Object.entries(params)) {\r\n if (v !== undefined && v !== '') qs.set(k, String(v));\r\n }\r\n const query = qs.toString();\r\n\r\n const res = await doFetch(`${base}${path}${query ? `?${query}` : ''}`, {\r\n method,\r\n // The RAW token, no `Bearer ` prefix — see `VoiceToken.token` (SPEC §6.1).\r\n headers: { Authorization: token },\r\n ...(signal ? { signal } : {}),\r\n });\r\n\r\n const body: unknown = await res.json().catch(() => null);\r\n const message = (body as { message?: string } | null)?.message ?? `${path} — HTTP ${res.status}`;\r\n\r\n if (!res.ok) throw new ApiError(res.status, message);\r\n // This backend answers 200 with `{ success: false }` on handled failures, so the status alone is\r\n // not enough to know a call worked.\r\n if ((body as { success?: boolean } | null)?.success === false) {\r\n throw new ApiError(res.status, message);\r\n }\r\n return body as T;\r\n }\r\n\r\n /**\r\n * Retry once on 401, with a freshly minted token.\r\n *\r\n * A cached token can be rejected before its nominal expiry — revoked on logout, or invalidated when\r\n * the extension is re-provisioned. Without this the cache would keep handing back the dead one for\r\n * up to its full TTL, so `revokeVoiceTokensForUser` would not actually stop a running softphone.\r\n *\r\n * Exactly one retry: a second 401 means the credential itself is refused, not stale, and retrying\r\n * would be a loop against the host's token endpoint.\r\n */\r\n return async function request<T>(path: string, params: QueryParams = {}, signal?: AbortSignal): Promise<T> {\r\n try {\r\n return await attempt<T>(path, params, signal);\r\n } catch (error) {\r\n if (!(error instanceof ApiError) || error.status !== 401) throw error;\r\n invalidateToken(config.tokenSource);\r\n return attempt<T>(path, params, signal);\r\n }\r\n };\r\n}\r\n\r\n/**\r\n * A minimal authenticated GET against Coventia's phone service.\r\n *\r\n * Lives under `coventia/` rather than `core/`: the core ships no HTTP at all, so a partner on their\r\n * own backend never loads this.\r\n */\r\nexport function createGet(config: RequestConfig) {\r\n return createRequest(config, 'GET');\r\n}\r\n\r\n/** The POST counterpart — today, only the presence ticket mint (`POST /presence/ticket`) uses it. */\r\nexport function createPost(config: RequestConfig) {\r\n return createRequest(config, 'POST');\r\n}\r\n","import { normalizeResolvedName, toDigits, withNameResolution } from '../sources.js';\r\nimport { createGet, createPost } from './api.js';\r\nimport type {\r\n Contact,\r\n PresenceCallbacks,\r\n PresenceConnection,\r\n PresenceEntry,\r\n PresenceSource,\r\n PresenceState,\r\n TokenSource,\r\n TransferOutcomeEntry,\r\n TransferOutcomesPage,\r\n TransferOutcomeSource,\r\n} from '../core/types.js';\r\nimport type {\r\n AgentsDirectory,\r\n CallDetail,\r\n CallHandler,\r\n CallHistoryEntry,\r\n CallOutcome,\r\n ContactsPage,\r\n ContactsSource,\r\n HistorySource,\r\n} from '../ui/types.js';\r\n\r\nexport interface CoventiaSourcesConfig {\r\n /** Coventia backend base URL, e.g. `https://api.coventia.es`. */\r\n readonly baseUrl: string;\r\n readonly tokenSource: TokenSource;\r\n /**\r\n * Only for session-authenticated hosts. A voice token carries the organization in its claim and\r\n * the backend pins it from there, so a partner omits this and cannot point the SDK at a tenant\r\n * their token does not cover. See `CoventiaBackendConfig.organizationId`.\r\n */\r\n readonly organizationId?: string;\r\n /**\r\n * Where the phone routes live. `/phone` today; `/api/v1/phone` once the partner API ships (§6.6),\r\n * at which point only this string changes.\r\n */\r\n readonly basePath?: string;\r\n /**\r\n * **The one thing a provider implements.** Their contact list, searched on their own backend.\r\n *\r\n * Supplying this is enough for everything: it drives the Contactos tab, and caller ID is DERIVED\r\n * from it by searching for the incoming number (see `resolverFromContacts`). One source means the\r\n * Contactos tab, a live call and a history row can never disagree about who a number belongs to —\r\n * which they did when the list and the lookup were separate overrides.\r\n *\r\n * The matching happens on their backend, where the CRM is: we send the number as `search` and take\r\n * an exact digit match from the results.\r\n */\r\n readonly contacts?: ContactsSource;\r\n\r\n /**\r\n * Caller ID, only if searching the list is not how their CRM answers \"who is this number\".\r\n *\r\n * Rarely needed — `contacts` already derives it. Worth setting when a dedicated lookup is cheaper\r\n * than a search, or when the number lives on a record that search does not return.\r\n */\r\n readonly resolveContact?: (number: string) => Promise<Contact | null>;\r\n /** Overrides polling `/transfers/outcomes` — see `CoventiaBackendConfig.transferOutcomes`. */\r\n readonly transferOutcomes?: TransferOutcomeSource;\r\n /** Overrides the presence WebSocket — see `CoventiaBackendConfig.presence`. */\r\n readonly presence?: PresenceSource;\r\n readonly fetch?: typeof globalThis.fetch;\r\n /** Overridable for tests — a fake `WebSocket` constructor. Defaults to `globalThis.WebSocket`. */\r\n readonly WebSocket?: typeof globalThis.WebSocket;\r\n}\r\n\r\nexport interface CoventiaSources {\r\n /** The Contactos tab. A partner may replace this with their own; everything else cannot be. */\r\n readonly contacts: ContactsSource;\r\n /** The Historial tab. **Coventia's, always** — we store the calls and the recordings. */\r\n readonly history: HistorySource;\r\n /** Caller ID for an incoming number, for `SoftphoneConfig.resolveContact`. */\r\n readonly resolveContact: (number: string) => Promise<Contact | null>;\r\n /** The Historial tab's \"filter by person\" directory. Always Coventia's own org membership. */\r\n readonly listAgents: () => Promise<AgentsDirectory>;\r\n /** Phase A (transfer outcome relay) — polled by the transfer watch, never by UI directly. */\r\n readonly transferOutcomes: TransferOutcomeSource;\r\n /** Phase B (presence-gated transfer picker) — opened by `presence-socket.ts`, never by UI directly. */\r\n readonly presence: PresenceSource;\r\n}\r\n\r\n/** What `/agents` returns. */\r\ninterface AgentRow {\r\n readonly user_id: string;\r\n readonly name: string | null;\r\n}\r\n\r\n/** What `/webrtc/contacts` returns. **The only place `wa_id` is named in the whole SDK.** */\r\ninterface WhatsAppContactRow {\r\n readonly wa_id: string;\r\n readonly name: string | null;\r\n}\r\n\r\n/**\r\n * `wa_id` → `Contact`.\r\n *\r\n * `id` IS the `wa_id`, and that leaks nothing: the backend serves callable contacts only\r\n * (`wa_id: /^[0-9]+$/`), so the value is literally the phone digits and carries nothing `phone` does\r\n * not. What the boundary removes is the SHAPE — no `custom_username`/`username` coalescing, no\r\n * WhatsApp field names past this function.\r\n */\r\nconst toContact = (row: WhatsAppContactRow): Contact => ({\r\n id: row.wa_id,\r\n name: row.name,\r\n phone: `+${row.wa_id}`,\r\n});\r\n\r\n/** One hop in `handled_by_chain`, as Mongo stores it — no `name` (see `HandledByChainRow`'s own note). */\r\ninterface HandledByChainRow {\r\n readonly ext?: string;\r\n readonly user_id?: string | null;\r\n}\r\n\r\n/** The same hop, enriched by `GET /calls/:id` with a resolved display name. */\r\ninterface EnrichedHandledByChainRow extends HandledByChainRow {\r\n readonly name?: string | null;\r\n}\r\n\r\n/** A row from `/calls`. The backend spreads raw Mongo docs, so every read below is defensive. */\r\ninterface CallRow {\r\n readonly _id?: string;\r\n /** The PBX's vocabulary: `incoming` | `outgoing`. NOT the SDK's `inbound`/`outbound`. */\r\n readonly direction?: string;\r\n readonly caller_id?: string;\r\n readonly called_did?: string;\r\n readonly destination?: string;\r\n readonly disposition?: string;\r\n readonly duration?: number;\r\n readonly created_at?: string | number;\r\n readonly recording_count?: number;\r\n readonly handled_by_chain?: readonly HandledByChainRow[];\r\n /** The transfer route as bare extensions — populated even when `handled_by_chain` isn't (older\r\n * docs, written before the chain existed). */\r\n readonly extensions?: readonly string[];\r\n readonly internal?: string;\r\n readonly last_internal?: string;\r\n}\r\n\r\nconst toDirection = (raw: string | undefined): 'inbound' | 'outbound' =>\r\n raw === 'outgoing' ? 'outbound' : 'inbound';\r\n\r\n/** Which field holds the other party depends on the direction. */\r\nconst otherParty = (row: CallRow): string =>\r\n toDirection(row.direction) === 'outbound'\r\n ? (row.called_did ?? row.destination ?? '')\r\n : (row.caller_id ?? '');\r\n\r\n/**\r\n * Who handled the call, in order. Prefers the real chain (`ext` + resolved `user_id`); falls back to\r\n * bare extensions ONLY when there is no chain at all — a doc written before `handled_by_chain` existed.\r\n * Unifies both shapes into one `CallHandler[]` so the UI never has to know which source it came from:\r\n * a bare extension is just a handler with `userId: null, name: null`.\r\n */\r\nfunction toHandledBy(row: CallRow, chain: readonly EnrichedHandledByChainRow[] = row.handled_by_chain ?? []): readonly CallHandler[] {\r\n if (chain.length > 0) {\r\n return chain\r\n .filter((h): h is EnrichedHandledByChainRow & { ext: string } => Boolean(h?.ext))\r\n .map((h) => ({ extension: h.ext, userId: h.user_id ?? null, name: h.name ?? null }));\r\n }\r\n const bare = row.extensions?.length ? row.extensions : [row.internal, row.last_internal];\r\n return [...new Set(bare.filter((e): e is string => Boolean(e)))].map((extension) => ({\r\n extension,\r\n userId: null,\r\n name: null,\r\n }));\r\n}\r\n\r\n/**\r\n * \"Not answered\" is ANY non-empty disposition other than `answered` — `no answer`, `busy`, `cancel`,\r\n * `failed`, `congestion`, and whatever Zadarma adds next.\r\n *\r\n * Open-ended rather than an allow-list, so an unrecognised value surfaces under \"Perdidas\" instead of\r\n * vanishing. **An EMPTY disposition counts as ANSWERED**, so a call of unknown status is not wrongly\r\n * flagged. Both halves are load-bearing.\r\n */\r\nconst isMissed = (row: CallRow): boolean => {\r\n const d = String(row.disposition ?? '').trim().toLowerCase();\r\n return d !== '' && d !== 'answered';\r\n};\r\n\r\n/**\r\n * The PBX's own vocabulary translated to the SDK's, for a call `isMissed`. Never returns Zadarma's\r\n * raw string — an unrecognised or future value falls into `'unavailable'` rather than leaking through\r\n * or being dropped, same open-ended reasoning `isMissed` itself documents.\r\n */\r\nconst toOutcome = (row: CallRow): CallOutcome => {\r\n switch (String(row.disposition ?? '').trim().toLowerCase()) {\r\n case 'no answer':\r\n return 'no-answer';\r\n case 'busy':\r\n return 'busy';\r\n case 'cancel':\r\n return 'cancelled';\r\n case 'failed':\r\n return 'failed';\r\n default:\r\n return 'unavailable';\r\n }\r\n};\r\n\r\n/**\r\n * Caller ID, derived from a contacts source: ask it for the number and take an exact match.\r\n *\r\n * This is why a provider only has to implement ONE function. Their search endpoint already knows how\r\n * to match a phone number — it is the same question the Contactos tab asks, with a different query —\r\n * and doing it on their backend is where the CRM actually lives.\r\n *\r\n * **Exact digit match only.** A search for a number can return partial or fuzzy hits, and naming a\r\n * caller after a near-miss is worse than showing the bare number: the user trusts the name.\r\n * `toDigits` on both sides so `+34 600 111 222` and `34600111222` compare equal.\r\n */\r\nexport function resolverFromContacts(\r\n contacts: ContactsSource,\r\n): (number: string) => Promise<Contact | null> {\r\n return async (number) => {\r\n const digits = toDigits(number);\r\n if (!digits) return null;\r\n // The number as the PBX reported it — their backend has the most to work with that way. `limit`\r\n // is small: we want one exact hit, not a page of near misses.\r\n const page = await contacts({ search: number, skip: 0, limit: 10 });\r\n return page.items.find((c) => toDigits(c.phone) === digits) ?? null;\r\n };\r\n}\r\n\r\nconst toDate = (raw: string | number | undefined): Date => {\r\n if (raw === undefined) return new Date(0);\r\n const d = new Date(raw);\r\n return Number.isNaN(d.getTime()) ? new Date(0) : d;\r\n};\r\n\r\n/** What `GET /transfers/outcomes` returns per entry — `transferOutcomeStore.js`'s own wire shape. */\r\ninterface TransferOutcomeRow {\r\n readonly id?: string;\r\n readonly target?: string;\r\n /** The backend's wire value; `'connected'` or anything else (`'not_connected'`) maps below. */\r\n readonly status?: string;\r\n readonly at?: string;\r\n}\r\n\r\n/** `not_connected` → `'not-connected'` (spec §4 D2's kebab-case, matching `HangupReason`) — the ONE\r\n * place that translation happens; open-ended rather than an allow-list, so an unrecognised status\r\n * fails safe as `'not-connected'` (the agent gets told, never silently nothing) rather than throwing. */\r\nconst toTransferOutcome = (row: TransferOutcomeRow): TransferOutcomeEntry => ({\r\n id: row.id ?? '',\r\n target: row.target ?? '',\r\n status: row.status === 'connected' ? 'connected' : 'not-connected',\r\n at: toDate(row.at),\r\n});\r\n\r\n/** What the presence WebSocket's `snapshot`/`delta` messages carry per agent — `presenceSocket.js`'s\r\n * own wire shape (`docs/specs/transfer-presence-picker.md` §4.3, plan §2). */\r\ninterface PresenceAgentRow {\r\n readonly userId?: string;\r\n readonly extension?: string;\r\n readonly name?: string | null;\r\n readonly state?: string;\r\n}\r\n\r\n/** Open-ended rather than an allow-list, matching `toTransferOutcome`'s own reasoning for an\r\n * unrecognised value: fails safe as `'desconectado'` (never wrongly reachable) rather than throwing. */\r\nconst toPresenceState = (raw: string | undefined): PresenceState =>\r\n raw === 'disponible' || raw === 'en_llamada' ? raw : 'desconectado';\r\n\r\nconst toPresenceEntry = (row: PresenceAgentRow): PresenceEntry => ({\r\n userId: row.userId ?? '',\r\n extension: row.extension ?? '',\r\n name: row.name ?? null,\r\n state: toPresenceState(row.state),\r\n});\r\n\r\n/** `POST /presence/ticket`'s response (`presenceTicketStore.js`'s own wire shape). */\r\ninterface PresenceTicketResponse {\r\n readonly success?: boolean;\r\n readonly ticket?: string;\r\n readonly expires_in?: number;\r\n}\r\n\r\n/** `https://api.coventia.es` → `wss://api.coventia.es`; `http://` → `ws://`. Scheme swapped, and any\r\n * trailing slash trimmed — same normalisation `createGet`/`createPost` apply to `baseUrl` internally,\r\n * needed again here since this function works from the raw config value, not their trimmed copy. */\r\nconst toWebSocketUrl = (httpUrl: string): string => httpUrl.replace(/^http/, 'ws').replace(/\\/+$/, '');\r\n\r\n/**\r\n * Coventia's phone service, as the sources the widget asks for.\r\n *\r\n * **This is the anti-corruption layer.** The backend speaks WhatsApp's data model; the SDK speaks\r\n * `Contact` and `CallHistoryEntry`. The translation happens here and nowhere else — enforced by\r\n * structure, since `core/` cannot reach `coventia/` and a partner never imports it.\r\n */\r\nexport function coventiaSources(config: CoventiaSourcesConfig): CoventiaSources {\r\n const get = createGet(config);\r\n const post = createPost(config);\r\n const base = config.basePath ?? '/phone';\r\n // Absent for a voice token, which already names the organization. Spread into every query below,\r\n // so omitting it removes the parameter entirely rather than sending `organization_id=undefined`.\r\n const org = config.organizationId ? { organization_id: config.organizationId } : {};\r\n\r\n const coventiaContacts: ContactsSource = async ({ search, skip, limit }): Promise<ContactsPage> => {\r\n const body = await get<{ contacts?: readonly WhatsAppContactRow[]; total?: number }>(\r\n `${base}/webrtc/contacts`,\r\n { ...org, search, skip, limit },\r\n );\r\n return { items: (body.contacts ?? []).map(toContact), total: body.total ?? 0 };\r\n };\r\n\r\n const coventiaResolve = async (number: string): Promise<Contact | null> => {\r\n const digits = toDigits(number);\r\n if (!digits) return null;\r\n const body = await get<{ name?: string | null }>(`${base}/webrtc/caller-name`, {\r\n ...org,\r\n number: digits,\r\n });\r\n // Re-applied on top of the backend's own rule: a contact saved as its own number resolves to a\r\n // \"name\" that is just the number reformatted, and showing that puts +34600111222 where a name\r\n // belongs — next to the number the widget is already displaying.\r\n const name = normalizeResolvedName(body.name ?? null, digits);\r\n return name === null ? null : { id: digits, name, phone: `+${digits}` };\r\n };\r\n\r\n const rawHistory: HistorySource = async ({\r\n skip,\r\n limit,\r\n missed,\r\n userId,\r\n }): Promise<readonly CallHistoryEntry[]> => {\r\n const body = await get<{ calls?: readonly CallRow[] }>(`${base}/calls`, {\r\n ...org,\r\n skip,\r\n limit,\r\n // Omitted rather than `'false'` — the backend only special-cases `missed=true`, so leaving it\r\n // out entirely for \"Todas\" is equivalent and one less thing for a param dump to explain.\r\n missed: missed ? 'true' : undefined,\r\n user_id: userId,\r\n });\r\n return (body.calls ?? []).map((row): CallHistoryEntry => {\r\n const id = row._id ?? '';\r\n const recorded = (row.recording_count ?? 0) > 0;\r\n const missedRow = isMissed(row);\r\n const handledBy = toHandledBy(row);\r\n return {\r\n id,\r\n direction: toDirection(row.direction),\r\n number: otherParty(row),\r\n // Filled by `withNameResolution` at the mount — deduped by digits and cached across pages.\r\n name: null,\r\n at: toDate(row.created_at),\r\n durationSec: row.duration ?? 0,\r\n missed: missedRow,\r\n ...(missedRow ? { outcome: toOutcome(row) } : {}),\r\n // The DID is only ever the ORG's own number, which only an inbound call dials — an outbound\r\n // row's `called_did` is the OTHER party (already `number` above); showing it again as \"DID\"\r\n // would just repeat the row under a wrong label.\r\n ...(toDirection(row.direction) === 'inbound' && row.called_did ? { did: row.called_did } : {}),\r\n recorded,\r\n handledBy,\r\n // The detail page's one enrichment fetch — signed recording URLs, plus this SAME chain with\r\n // names resolved. Skipped when there is nothing to enrich: minting signed URLs and resolving\r\n // names for a page of 30 calls nobody opens is pure waste.\r\n ...(recorded || handledBy.length > 0\r\n ? {\r\n loadDetail: async (): Promise<CallDetail> => {\r\n // Unlike `/calls` (rows spread flat into `calls: []`), `/calls/:id` wraps its one\r\n // result in `call` — `recordings.js`'s `res.json({ success, call: {...} })`.\r\n const detail = await get<{\r\n call?: {\r\n recording_urls?: readonly string[];\r\n handled_by_chain?: readonly EnrichedHandledByChainRow[];\r\n };\r\n }>(`${base}/calls/${encodeURIComponent(id)}`, org);\r\n return {\r\n recordingUrls: detail.call?.recording_urls ?? [],\r\n // `row`'s own bare-extension fields (read inside `toHandledBy` when the chain\r\n // passed here is empty) still work as the fallback — only the CHAIN comes from the\r\n // enriched response; the rest of `row` is unchanged.\r\n handledBy: toHandledBy(row, detail.call?.handled_by_chain ?? []),\r\n };\r\n },\r\n }\r\n : {}),\r\n };\r\n });\r\n };\r\n\r\n const coventiaListAgents = async (): Promise<AgentsDirectory> => {\r\n const body = await get<{ me?: AgentRow | null; people?: readonly AgentRow[] }>(\r\n `${base}/agents`,\r\n org,\r\n );\r\n const toAgent = (row: AgentRow) => ({ userId: row.user_id, name: row.name });\r\n return {\r\n me: body.me ? toAgent(body.me) : null,\r\n people: (body.people ?? []).map(toAgent),\r\n };\r\n };\r\n\r\n /**\r\n * Phase A (transfer outcome relay). `since` omitted on the caller's very first poll — that call\r\n * exists only to learn the starting `cursor`, per spec §5.3; this source is a thin, honest wrapper\r\n * around the endpoint and does not itself implement that \"discard the first page\" rule, which\r\n * belongs to the transfer watch (plan T5) that calls it.\r\n */\r\n const coventiaTransferOutcomes: TransferOutcomeSource = async ({ since }): Promise<TransferOutcomesPage> => {\r\n const body = await get<{ cursor?: string; outcomes?: readonly TransferOutcomeRow[] }>(\r\n `${base}/transfers/outcomes`,\r\n { ...org, since },\r\n );\r\n return {\r\n cursor: body.cursor ?? '0',\r\n outcomes: (body.outcomes ?? []).map(toTransferOutcome),\r\n };\r\n };\r\n\r\n /**\r\n * Phase B (presence-gated transfer picker). Mints a fresh, one-time ticket (never the real voice\r\n * token — spec §4.2's \"decided 2026-09-24: where the token travels\") and opens the WebSocket with\r\n * it. Called fresh on every (re)connect by `presence-socket.ts`, which owns retry/backoff — this\r\n * function is a single, honest attempt, the same division of labour `coventiaTransferOutcomes` has\r\n * with the transfer watch that calls IT.\r\n */\r\n const coventiaPresence: PresenceSource = (callbacks: PresenceCallbacks): Promise<PresenceConnection> => {\r\n const WS = config.WebSocket ?? globalThis.WebSocket;\r\n return new Promise<PresenceConnection>((resolve, reject) => {\r\n void (async () => {\r\n let ticket: string;\r\n try {\r\n const body = await post<PresenceTicketResponse>(`${base}/presence/ticket`, org);\r\n if (!body.ticket) throw new Error('presence ticket mint returned no ticket');\r\n ticket = body.ticket;\r\n } catch (error) {\r\n reject(error instanceof Error ? error : new Error(String(error)));\r\n return;\r\n }\r\n\r\n const wsUrl = `${toWebSocketUrl(config.baseUrl)}${base}/presence?ticket=${encodeURIComponent(ticket)}`;\r\n const ws = new WS(wsUrl);\r\n let settled = false;\r\n\r\n ws.onopen = () => {\r\n if (settled) return;\r\n settled = true;\r\n resolve({\r\n reportCallState: (onCall) => {\r\n if (ws.readyState !== WS.OPEN) return;\r\n ws.send(JSON.stringify({ type: 'call-state', onCall }));\r\n },\r\n close: () => {\r\n // Detached first — a deliberate close must never be reported to the caller as a drop\r\n // (`PresenceConnection.close`'s own contract).\r\n ws.onclose = null;\r\n ws.onerror = null;\r\n ws.close();\r\n },\r\n });\r\n };\r\n\r\n ws.onmessage = (event: MessageEvent) => {\r\n let data: unknown;\r\n try {\r\n data = JSON.parse(String(event.data));\r\n } catch {\r\n return; // not JSON — ignore rather than tear down the connection over one stray frame\r\n }\r\n const msg = data as {\r\n type?: string;\r\n agents?: readonly PresenceAgentRow[];\r\n agent?: PresenceAgentRow;\r\n };\r\n if (msg.type === 'snapshot') {\r\n callbacks.onSnapshot((msg.agents ?? []).map(toPresenceEntry));\r\n } else if (msg.type === 'delta' && msg.agent) {\r\n callbacks.onDelta(toPresenceEntry(msg.agent));\r\n }\r\n };\r\n\r\n ws.onclose = () => {\r\n if (!settled) {\r\n // Never actually opened (ticket refused, network refusal, ...) — indistinguishable from a\r\n // drop to `presence-socket.ts`, which is exactly why this rejects rather than calling\r\n // `onClose`: there is no `PresenceConnection` yet for that callback to be about.\r\n settled = true;\r\n reject(new Error('presence socket closed before opening'));\r\n return;\r\n }\r\n callbacks.onClose();\r\n };\r\n\r\n // A real WebSocket always follows `error` with `close` — nothing extra to do here, and a\r\n // browser gives an `error` event no further detail worth reporting anyway.\r\n ws.onerror = () => {};\r\n })();\r\n });\r\n };\r\n\r\n const contacts = config.contacts ?? coventiaContacts;\r\n\r\n /*\r\n * Caller ID follows the CONTACT LIST, not a separate setting.\r\n *\r\n * A provider who supplies `contacts` gets a resolver derived from it, so the tab, a live call and a\r\n * history row always name the same number the same way. Supplying only the list used to leave\r\n * caller ID on ours — the same person appearing twice under two names inside one widget.\r\n */\r\n const resolve =\r\n config.resolveContact ??\r\n (config.contacts ? resolverFromContacts(config.contacts) : coventiaResolve);\r\n\r\n // Names, resolved once per distinct number and cached across pages — a call log is the same handful\r\n // of numbers over and over. Wrapped HERE rather than left to the caller: the raw rows carry\r\n // `name: null`, so a caller who forgets this gets a history of bare numbers and no error.\r\n const history = withNameResolution(rawHistory, resolve);\r\n\r\n const transferOutcomes = config.transferOutcomes ?? coventiaTransferOutcomes;\r\n const presence = config.presence ?? coventiaPresence;\r\n\r\n return {\r\n contacts,\r\n history,\r\n resolveContact: resolve,\r\n listAgents: coventiaListAgents,\r\n transferOutcomes,\r\n presence,\r\n };\r\n}\r\n"]}
@@ -1,5 +0,0 @@
1
- export { createZadarmaEngine } from './chunk-YWI6EQYS.js';
2
- import './chunk-2ZSOGGPO.js';
3
- import './chunk-MHOJHG5E.js';
4
- //# sourceMappingURL=zadarma-engine-4VOPIBXG.js.map
5
- //# sourceMappingURL=zadarma-engine-4VOPIBXG.js.map