@coventia/softphone 0.3.0 → 0.5.0

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 (60) hide show
  1. package/dist/{call-CaPDWVk3.d.cts → call-FqcvDg1t.d.cts} +168 -12
  2. package/dist/{call-CaPDWVk3.d.ts → call-FqcvDg1t.d.ts} +168 -12
  3. package/dist/chunk-5E5OEXS2.js +14 -0
  4. package/dist/chunk-5E5OEXS2.js.map +1 -0
  5. package/dist/{chunk-EYEDPD7Y.js → chunk-6RR6G35E.js} +92 -17
  6. package/dist/chunk-6RR6G35E.js.map +1 -0
  7. package/dist/{chunk-2ZSOGGPO.js → chunk-FRXHEHQA.js} +15 -2
  8. package/dist/chunk-FRXHEHQA.js.map +1 -0
  9. package/dist/{chunk-UHNLEBBO.js → chunk-I3RSC52R.js} +28 -3
  10. package/dist/chunk-I3RSC52R.js.map +1 -0
  11. package/dist/chunk-M76SAXXM.js +13 -0
  12. package/dist/chunk-M76SAXXM.js.map +1 -0
  13. package/dist/{chunk-7R6LOOAI.js → chunk-N4PLEYFJ.js} +4 -2
  14. package/dist/chunk-N4PLEYFJ.js.map +1 -0
  15. package/dist/element/index.d.ts +198 -6
  16. package/dist/element/index.js +1160 -489
  17. package/dist/element/index.js.map +1 -1
  18. package/dist/{engine-BgBsIcEa.d.ts → engine-CsNRD7B7.d.ts} +1 -1
  19. package/dist/{engine-CU2rEo3g.d.cts → engine-CzOCrfY9.d.cts} +1 -1
  20. package/dist/index.cjs +675 -53
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +16 -6
  23. package/dist/index.d.ts +16 -6
  24. package/dist/index.js +453 -37
  25. package/dist/index.js.map +1 -1
  26. package/dist/react/index.cjs +26 -0
  27. package/dist/react/index.cjs.map +1 -1
  28. package/dist/react/index.d.cts +24 -5
  29. package/dist/react/index.d.ts +24 -5
  30. package/dist/react/index.js +2 -2
  31. package/dist/{softphone-DEt0TtQw.d.ts → softphone-By9sizlV.d.ts} +44 -3
  32. package/dist/{softphone-dZMkW8V1.d.cts → softphone-JZvJdzU3.d.cts} +44 -3
  33. package/dist/softphone.css +254 -23
  34. package/dist/{sources-M3GYMS6V.js → sources-QL2LRZVH.js} +93 -8
  35. package/dist/sources-QL2LRZVH.js.map +1 -0
  36. package/dist/testing/index.cjs +13 -0
  37. package/dist/testing/index.cjs.map +1 -1
  38. package/dist/testing/index.d.cts +2 -2
  39. package/dist/testing/index.d.ts +2 -2
  40. package/dist/testing/index.js +1 -1
  41. package/dist/ui/index.cjs +670 -20
  42. package/dist/ui/index.cjs.map +1 -1
  43. package/dist/ui/index.d.cts +2 -2
  44. package/dist/ui/index.d.ts +2 -2
  45. package/dist/ui/index.js +642 -22
  46. package/dist/ui/index.js.map +1 -1
  47. package/dist/zadarma/index.cjs +111 -14
  48. package/dist/zadarma/index.cjs.map +1 -1
  49. package/dist/zadarma/index.d.cts +5 -6
  50. package/dist/zadarma/index.d.ts +5 -6
  51. package/dist/zadarma/index.js +3 -2
  52. package/dist/zadarma-engine-TIUE7PZ7.js +6 -0
  53. package/dist/{zadarma-engine-L5DEFXUS.js.map → zadarma-engine-TIUE7PZ7.js.map} +1 -1
  54. package/package.json +1 -1
  55. package/dist/chunk-2ZSOGGPO.js.map +0 -1
  56. package/dist/chunk-7R6LOOAI.js.map +0 -1
  57. package/dist/chunk-EYEDPD7Y.js.map +0 -1
  58. package/dist/chunk-UHNLEBBO.js.map +0 -1
  59. package/dist/sources-M3GYMS6V.js.map +0 -1
  60. package/dist/zadarma-engine-L5DEFXUS.js +0 -5
@@ -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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AEA,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,QAAA;AAAA,IACA;AAAA,GACF;AACF","file":"sources-M3GYMS6V.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 RingtoneSettings,\r\n RingtoneSource,\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 /** The caller's ringtone settings (custom-ringtone.md §4.3–4.4). */\r\n readonly ringtones: RingtoneSource;\r\n}\r\n\r\n/** What every `/ringtones` route returns (backend `routes/ringtones.js`). */\r\ninterface RingtonesResponse {\r\n readonly catalogue?: ReadonlyArray<{\r\n readonly id: string;\r\n readonly name: string;\r\n readonly path: string | null;\r\n readonly loop?: { readonly start: number; readonly end: number } | null;\r\n }>;\r\n readonly orgDefault?: string | null;\r\n readonly user?: string | null;\r\n readonly effective?: string;\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 bye: () => {\r\n if (ws.readyState !== WS.OPEN) return;\r\n ws.send(JSON.stringify({ type: 'bye' }));\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 /*\r\n * Ringtone settings. The backend answers with a `path` from the API root rather than a URL (behind its\r\n * proxy it cannot know its own public host — custom-ringtone-plan.md §2), so the file URL is built here\r\n * exactly the way every request URL is: `baseUrl` + path. The UI only ever sees absolute URLs.\r\n */\r\n const fileBase = config.baseUrl.replace(/\\/+$/, '');\r\n /** Loop points only when they are usable numbers in order — anything else means \"loop the whole file\". */\r\n const toLoop = (l: { start: number; end: number } | null | undefined) =>\r\n l && Number.isFinite(l.start) && Number.isFinite(l.end) && l.start >= 0 && l.end > l.start\r\n ? { start: l.start, end: l.end }\r\n : null;\r\n const toRingtoneSettings = (body: RingtonesResponse): RingtoneSettings => {\r\n const catalogue = (body.catalogue ?? []).map((r) => ({\r\n id: r.id,\r\n name: r.name,\r\n url: r.path ? `${fileBase}${r.path}` : null,\r\n loop: r.path ? toLoop(r.loop) : null,\r\n }));\r\n // Defensive only — the backend always resolves `effective` to a catalogue id. If a malformed answer\r\n // ever named something else, the built-in tone (the entry with no file) is the safe reading.\r\n const builtIn = catalogue.find((r) => r.url === null)?.id ?? 'clasico';\r\n const effective = catalogue.some((r) => r.id === body.effective) ? (body.effective as string) : builtIn;\r\n return { catalogue, orgDefault: body.orgDefault ?? null, mine: body.user ?? null, effective };\r\n };\r\n\r\n /*\r\n * The last settings this user had, remembered in localStorage (custom-ringtone.md §4.4, added 2026-10-15):\r\n * at startup the softphone can start loading the right file — usually straight from the browser's HTTP\r\n * cache — before the backend has answered, which closes the \"first second after start\" window in which a\r\n * call would otherwise ring the built-in tone. Fresh settings from the backend always replace them.\r\n *\r\n * Keyed by backend, organization and user (the token's identity), so two people sharing a browser — or one\r\n * person in two organizations — never see each other's choice. Never throws: storage may be blocked.\r\n */\r\n const CACHE_PREFIX = 'coventia-softphone:ringtones:';\r\n const cacheKey = async (): Promise<string | null> => {\r\n try {\r\n const { identity } = await config.tokenSource.getToken();\r\n return `${CACHE_PREFIX}${fileBase}|${config.organizationId ?? '-'}|${identity}`;\r\n } catch {\r\n return null;\r\n }\r\n };\r\n const remember = async (settings: RingtoneSettings): Promise<RingtoneSettings> => {\r\n const key = await cacheKey();\r\n try {\r\n if (key) globalThis.localStorage?.setItem(key, JSON.stringify(settings));\r\n } catch {\r\n /* blocked or full — nothing to remember, nothing lost */\r\n }\r\n return settings;\r\n };\r\n const recall = async (): Promise<RingtoneSettings | null> => {\r\n const key = await cacheKey();\r\n try {\r\n const raw = key ? globalThis.localStorage?.getItem(key) : null;\r\n const s = raw ? (JSON.parse(raw) as RingtoneSettings) : null;\r\n // Only a well-formed record whose effective ringtone is in its own catalogue; anything else is ignored.\r\n const ok =\r\n s &&\r\n Array.isArray(s.catalogue) &&\r\n s.catalogue.every((r) => typeof r?.id === 'string' && typeof r.name === 'string' && (r.url === null || typeof r.url === 'string')) &&\r\n s.catalogue.some((r) => r.id === s.effective);\r\n return ok ? { ...s, catalogue: s.catalogue.map((r) => ({ ...r, loop: toLoop(r.loop) })) } : null;\r\n } catch {\r\n return null;\r\n }\r\n };\r\n\r\n const ringtones: RingtoneSource = {\r\n get: async (signal) =>\r\n remember(toRingtoneSettings(await get<RingtonesResponse>(`${base}/ringtones`, org, signal))),\r\n // `null` clears: the empty id is dropped from the query by the request helper, and the backend reads a\r\n // missing `ringtone_id` as \"clear\".\r\n setMine: async (id) =>\r\n remember(\r\n toRingtoneSettings(await post<RingtonesResponse>(`${base}/ringtones/user`, { ...org, ringtone_id: id ?? '' })),\r\n ),\r\n cached: recall,\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 ringtones,\r\n };\r\n}\r\n"]}
@@ -1,5 +0,0 @@
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