@fonoster/apiserver 0.27.0 → 0.31.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 (376) hide show
  1. package/dist/applications/buildService.d.ts +5 -1
  2. package/dist/applications/buildService.js +10 -7
  3. package/dist/applications/createCreateApplication.d.ts +6 -2
  4. package/dist/applications/createCreateApplication.js +24 -16
  5. package/dist/applications/createCreateTestToken.d.ts +3 -1
  6. package/dist/applications/createCreateTestToken.js +18 -13
  7. package/dist/applications/createGetApplication.js +2 -2
  8. package/dist/applications/createGetFnUtil.d.ts +22 -18
  9. package/dist/applications/createGetFnUtil.js +3 -5
  10. package/dist/applications/createListApplications.js +3 -4
  11. package/dist/applications/createRotateSigningSecret.d.ts +9 -0
  12. package/dist/{calls/createFetchSingleCall.js → applications/createRotateSigningSecret.js} +23 -20
  13. package/dist/applications/createUpdateApplication.d.ts +6 -2
  14. package/dist/applications/createUpdateApplication.js +35 -36
  15. package/dist/applications/evalKeys.d.ts +9 -0
  16. package/dist/{voice/handlers/dial/recordChannel.js → applications/evalKeys.js} +17 -12
  17. package/dist/applications/session/appModel.d.ts +225 -0
  18. package/dist/applications/session/appModel.js +331 -0
  19. package/dist/applications/types.d.ts +1 -27
  20. package/dist/billing/buildService.d.ts +24 -0
  21. package/dist/billing/buildService.js +116 -0
  22. package/dist/bin/entrypoint.d.ts +1 -0
  23. package/dist/bin/entrypoint.js +180 -0
  24. package/dist/bin/healthcheck.d.ts +2 -0
  25. package/dist/{voice/utils/VoiceServiceClientConstructor.js → bin/healthcheck.js} +24 -9
  26. package/dist/bin/regionHubSetup.d.ts +2 -0
  27. package/dist/bin/regionHubSetup.js +67 -0
  28. package/dist/bin/usage.d.ts +2 -0
  29. package/dist/bin/usage.js +119 -0
  30. package/dist/calls/buildService.d.ts +1 -20
  31. package/dist/calls/buildService.js +59 -6
  32. package/dist/calls/createCall.d.ts +17 -2
  33. package/dist/calls/createCall.js +64 -11
  34. package/dist/calls/createCallPublisher.d.ts +40 -2
  35. package/dist/calls/createCallPublisher.js +43 -9
  36. package/dist/calls/createIsWorkspaceNumber.d.ts +41 -0
  37. package/dist/calls/createIsWorkspaceNumber.js +39 -0
  38. package/dist/calls/createTrackCall.d.ts +55 -2
  39. package/dist/calls/createTrackCall.js +230 -16
  40. package/dist/calls/getCall.d.ts +4 -2
  41. package/dist/calls/getCall.js +2 -3
  42. package/dist/calls/listCalls.d.ts +4 -2
  43. package/dist/calls/listCalls.js +2 -3
  44. package/dist/calls/types.d.ts +11 -2
  45. package/dist/calls/types.js +10 -0
  46. package/dist/{core/buildWelcomeDemoService.d.ts → capabilities/buildService.d.ts} +8 -8
  47. package/dist/capabilities/buildService.js +17 -0
  48. package/dist/capabilities/createGetCapabilities.d.ts +78 -0
  49. package/dist/capabilities/createGetCapabilities.js +98 -0
  50. package/dist/{voice/handlers/utils → capabilities}/index.d.ts +2 -3
  51. package/dist/{voice/handlers/utils → capabilities}/index.js +4 -3
  52. package/dist/config/index.d.ts +23 -0
  53. package/dist/config/index.js +102 -0
  54. package/dist/config/schema.d.ts +1919 -0
  55. package/dist/config/schema.js +357 -0
  56. package/dist/core/allowList.js +2 -1
  57. package/dist/core/applyCatalog.d.ts +10 -0
  58. package/dist/{voice/client/GrpcClientHandler.js → core/applyCatalog.js} +45 -51
  59. package/dist/core/db.d.ts +3 -1
  60. package/dist/core/db.js +2 -1
  61. package/dist/core/durableConsumer.d.ts +41 -0
  62. package/dist/core/durableConsumer.js +104 -0
  63. package/dist/core/httpBridge.d.ts +24 -6
  64. package/dist/core/httpBridge.js +3 -25
  65. package/dist/core/identityConfig.d.ts +2 -35
  66. package/dist/core/identityConfig.js +3 -36
  67. package/dist/core/regionHooks.d.ts +15 -0
  68. package/dist/{calls/influxdb.js → core/regionHooks.js} +4 -8
  69. package/dist/core/runServices.js +98 -15
  70. package/dist/core/services.d.ts +96 -6
  71. package/dist/core/services.js +49 -10
  72. package/dist/{voice/errors/index.d.ts → core/telemetry.d.ts} +2 -2
  73. package/dist/core/telemetry.js +42 -0
  74. package/dist/{applications/utils/convertToApplicationData.d.ts → core/telemetryInterceptor.d.ts} +10 -4
  75. package/dist/core/telemetryInterceptor.js +57 -0
  76. package/dist/core/testTokenConfig.js +4 -1
  77. package/dist/core/upsertRoomrPeer.d.ts +6 -0
  78. package/dist/core/{upsertDefaultPeer.js → upsertRoomrPeer.js} +31 -30
  79. package/dist/envs.d.ts +136 -23
  80. package/dist/envs.js +108 -143
  81. package/dist/index.js +39 -21
  82. package/dist/outbound/createNodeDirectory.d.ts +86 -0
  83. package/dist/outbound/createNodeDirectory.js +140 -0
  84. package/dist/{voice/integrations → outbound}/index.d.ts +4 -1
  85. package/dist/{voice/errors → outbound}/index.js +4 -2
  86. package/dist/outbound/placeOutboundCall.d.ts +96 -0
  87. package/dist/outbound/placeOutboundCall.js +172 -0
  88. package/dist/outbound/placementSweep.d.ts +56 -0
  89. package/dist/outbound/placementSweep.js +127 -0
  90. package/dist/outbound/runOutboundCalls.d.ts +52 -0
  91. package/dist/outbound/runOutboundCalls.js +171 -0
  92. package/dist/providers/createProvidersHandlers.d.ts +39 -0
  93. package/dist/providers/createProvidersHandlers.js +229 -0
  94. package/dist/providers/index.d.ts +47 -0
  95. package/dist/{voice/client → providers}/index.js +15 -6
  96. package/dist/providers/registryUsage.d.ts +48 -0
  97. package/dist/providers/registryUsage.js +236 -0
  98. package/dist/records/createIndexRecord.d.ts +42 -0
  99. package/dist/records/createIndexRecord.js +185 -0
  100. package/dist/records/createRecordsRouter.d.ts +61 -0
  101. package/dist/records/createRecordsRouter.js +330 -0
  102. package/dist/records/createSearchRecords.d.ts +51 -0
  103. package/dist/records/createSearchRecords.js +134 -0
  104. package/dist/{voice/filters → records}/index.d.ts +6 -6
  105. package/dist/{voice/filters → records}/index.js +6 -6
  106. package/dist/records/maintenance.d.ts +33 -0
  107. package/dist/records/maintenance.js +166 -0
  108. package/dist/records/runCallRecords.d.ts +48 -0
  109. package/dist/records/runCallRecords.js +49 -0
  110. package/dist/{events/createPerCallCache.d.ts → records/stores.d.ts} +4 -7
  111. package/dist/{voice/handlers/utils/isDtmf.js → records/stores.js} +9 -3
  112. package/dist/records/types.d.ts +104 -0
  113. package/dist/regions/configSync.d.ts +130 -0
  114. package/dist/regions/configSync.js +316 -0
  115. package/dist/regions/createRegionsRouter.d.ts +151 -0
  116. package/dist/regions/createRegionsRouter.js +391 -0
  117. package/dist/regions/endpoints.d.ts +41 -0
  118. package/dist/regions/endpoints.js +90 -0
  119. package/dist/regions/enrollmentToken.d.ts +41 -0
  120. package/dist/regions/enrollmentToken.js +94 -0
  121. package/dist/regions/httpAuth.d.ts +39 -0
  122. package/dist/regions/httpAuth.js +78 -0
  123. package/dist/regions/ids.d.ts +15 -0
  124. package/dist/regions/ids.js +81 -0
  125. package/dist/{voice/client → regions}/index.d.ts +17 -6
  126. package/dist/regions/index.js +51 -0
  127. package/dist/regions/link.d.ts +17 -0
  128. package/dist/regions/link.js +170 -0
  129. package/dist/regions/natsAuth.d.ts +41 -0
  130. package/dist/regions/natsAuth.js +64 -0
  131. package/dist/regions/natsJwt.d.ts +23 -0
  132. package/dist/regions/natsJwt.js +26 -0
  133. package/dist/regions/relay.d.ts +45 -0
  134. package/dist/regions/relay.js +203 -0
  135. package/dist/regions/relayHttp.d.ts +7 -0
  136. package/dist/regions/relayHttp.js +107 -0
  137. package/dist/regions/relaySlots.d.ts +18 -0
  138. package/dist/regions/relaySlots.js +118 -0
  139. package/dist/regions/runRegions.d.ts +111 -0
  140. package/dist/regions/runRegions.js +235 -0
  141. package/dist/regions/service.d.ts +129 -0
  142. package/dist/regions/service.js +558 -0
  143. package/dist/regions/sources.d.ts +20 -0
  144. package/dist/regions/sources.js +191 -0
  145. package/dist/regions/status.d.ts +35 -0
  146. package/dist/regions/status.js +63 -0
  147. package/dist/regions/types.d.ts +123 -0
  148. package/dist/regions/types.js +41 -0
  149. package/dist/{voice/integrations/getSttConfig.d.ts → regions/withConfigChangeHook.d.ts} +13 -7
  150. package/dist/regions/withConfigChangeHook.js +44 -0
  151. package/dist/secrets/createGetFnUtil.d.ts +2 -2
  152. package/dist/session/createSessionRouter.d.ts +49 -0
  153. package/dist/session/createSessionRouter.js +206 -0
  154. package/dist/{voice/handlers/dial → session}/index.d.ts +1 -1
  155. package/dist/{voice/handlers/dial → session}/index.js +1 -1
  156. package/dist/usage/buildService.d.ts +16 -0
  157. package/dist/{voice/integrations/getTtsConfig.js → usage/buildService.js} +13 -7
  158. package/dist/{voice/tts/utils/convertUlawToPCM16.d.ts → usage/createGetUsage.d.ts} +7 -6
  159. package/dist/usage/createGetUsage.js +118 -0
  160. package/dist/usage/ingestUsage.d.ts +7 -0
  161. package/dist/usage/ingestUsage.js +87 -0
  162. package/dist/usage/publishRecordedUsage.d.ts +52 -0
  163. package/dist/usage/publishRecordedUsage.js +103 -0
  164. package/dist/{utils/createHandleDialEventsWithNats.d.ts → usage/publishUsage.d.ts} +10 -4
  165. package/dist/usage/publishUsage.js +50 -0
  166. package/dist/usage/rebuildUsage.d.ts +48 -0
  167. package/dist/usage/rebuildUsage.js +104 -0
  168. package/dist/usage/runUsageConsumer.d.ts +22 -0
  169. package/dist/usage/runUsageConsumer.js +78 -0
  170. package/dist/usage/snapshotStorage.d.ts +14 -0
  171. package/dist/usage/snapshotStorage.js +95 -0
  172. package/dist/{voice/integrations/getTtsConfig.d.ts → usage/types.d.ts} +17 -6
  173. package/dist/utils/createCheckNumberPreconditions.js +4 -0
  174. package/dist/utils/index.d.ts +0 -2
  175. package/dist/utils/index.js +0 -2
  176. package/dist/voice/stt/Deepgram.d.ts +4 -57
  177. package/dist/voice/stt/Deepgram.js +15 -286
  178. package/dist/voice/stt/Google.d.ts +4 -15
  179. package/dist/voice/stt/Google.js +7 -103
  180. package/dist/voice/stt/types.d.ts +2 -38
  181. package/dist/voice/stt/types.js +25 -3
  182. package/dist/voice/tts/Azure.d.ts +4 -34
  183. package/dist/voice/tts/Azure.js +25 -105
  184. package/dist/voice/tts/Deepgram.d.ts +4 -38
  185. package/dist/voice/tts/Deepgram.js +25 -82
  186. package/dist/voice/tts/ElevenLabs.d.ts +4 -18
  187. package/dist/voice/tts/ElevenLabs.js +6 -97
  188. package/dist/voice/tts/Google.d.ts +4 -38
  189. package/dist/voice/tts/Google.js +25 -91
  190. package/dist/webhooks/createWebhooksHandlers.d.ts +37 -0
  191. package/dist/webhooks/createWebhooksHandlers.js +217 -0
  192. package/dist/webhooks/index.d.ts +37 -0
  193. package/dist/webhooks/index.js +51 -0
  194. package/dist/webhooks/lostCalls.d.ts +49 -0
  195. package/dist/webhooks/lostCalls.js +147 -0
  196. package/dist/webhooks/nodeCallEvents.d.ts +73 -0
  197. package/dist/webhooks/nodeCallEvents.js +177 -0
  198. package/dist/webhooks/runWebhookFanout.d.ts +44 -0
  199. package/dist/webhooks/runWebhookFanout.js +202 -0
  200. package/package.json +21 -31
  201. package/dist/applications/utils/applicationWithEncodedStruct.d.ts +0 -3
  202. package/dist/applications/utils/applicationWithEncodedStruct.js +0 -50
  203. package/dist/applications/utils/convertToApplicationData.js +0 -37
  204. package/dist/applications/validation/assistantWithoutApiKeySchema.d.ts +0 -786
  205. package/dist/applications/validation/assistantWithoutApiKeySchema.js +0 -35
  206. package/dist/applications/validation/createValidationSchema.d.ts +0 -1474
  207. package/dist/applications/validation/createValidationSchema.js +0 -67
  208. package/dist/applications/validation/prepareForValidation.d.ts +0 -21
  209. package/dist/applications/validation/prepareForValidation.js +0 -35
  210. package/dist/applications/validation/speechValidators.d.ts +0 -47
  211. package/dist/applications/validation/speechValidators.js +0 -50
  212. package/dist/applications/validation/validOrThrow.d.ts +0 -21
  213. package/dist/applications/validation/validOrThrow.js +0 -15
  214. package/dist/calls/createFetchCalls.d.ts +0 -22
  215. package/dist/calls/createFetchCalls.js +0 -88
  216. package/dist/calls/createFetchSingleCall.d.ts +0 -22
  217. package/dist/calls/influxdb.d.ts +0 -2
  218. package/dist/calls/runCallManager.d.ts +0 -8
  219. package/dist/calls/runCallManager.js +0 -75
  220. package/dist/core/buildWelcomeDemoService.js +0 -97
  221. package/dist/core/upsertDefaultPeer.d.ts +0 -2
  222. package/dist/events/amdResultCache.d.ts +0 -23
  223. package/dist/events/amdResultCache.js +0 -35
  224. package/dist/events/createInfluxDbPub.d.ts +0 -13
  225. package/dist/events/createInfluxDbPub.js +0 -89
  226. package/dist/events/createPerCallCache.js +0 -46
  227. package/dist/events/mapCallDirectionToEnum.d.ts +0 -21
  228. package/dist/events/mapCallDirectionToEnum.js +0 -37
  229. package/dist/events/nats.d.ts +0 -10
  230. package/dist/events/nats.js +0 -82
  231. package/dist/events/transformEvent.d.ts +0 -2
  232. package/dist/events/transformEvent.js +0 -87
  233. package/dist/events/types.d.ts +0 -26
  234. package/dist/utils/createHandleDialEventsWithNats.js +0 -24
  235. package/dist/utils/createHandleDialEventsWithVoiceClient.d.ts +0 -23
  236. package/dist/utils/createHandleDialEventsWithVoiceClient.js +0 -27
  237. package/dist/utils/getIntegrationsFromFile.d.ts +0 -2
  238. package/dist/utils/getIntegrationsFromFile.js +0 -49
  239. package/dist/utils/mapDialStatus.d.ts +0 -21
  240. package/dist/utils/mapDialStatus.js +0 -38
  241. package/dist/voice/VoiceDispatcher.d.ts +0 -21
  242. package/dist/voice/VoiceDispatcher.js +0 -122
  243. package/dist/voice/amd/mapAsteriskAmd.d.ts +0 -38
  244. package/dist/voice/amd/mapAsteriskAmd.js +0 -68
  245. package/dist/voice/client/AudioSocketHandler.d.ts +0 -38
  246. package/dist/voice/client/AudioSocketHandler.js +0 -70
  247. package/dist/voice/client/AuthorizationHandler.d.ts +0 -13
  248. package/dist/voice/client/AuthorizationHandler.js +0 -78
  249. package/dist/voice/client/ExternalMediaHandler.d.ts +0 -32
  250. package/dist/voice/client/ExternalMediaHandler.js +0 -59
  251. package/dist/voice/client/GrpcClientHandler.d.ts +0 -36
  252. package/dist/voice/client/SpeechHandler.d.ts +0 -60
  253. package/dist/voice/client/SpeechHandler.js +0 -120
  254. package/dist/voice/client/VoiceClientImpl.d.ts +0 -79
  255. package/dist/voice/client/VoiceClientImpl.js +0 -198
  256. package/dist/voice/connectToAri.d.ts +0 -2
  257. package/dist/voice/connectToAri.js +0 -81
  258. package/dist/voice/createCreateVoiceClient.d.ts +0 -9
  259. package/dist/voice/createCreateVoiceClient.js +0 -97
  260. package/dist/voice/errors/ChannelVarNotFoundError.d.ts +0 -23
  261. package/dist/voice/errors/ChannelVarNotFoundError.js +0 -10
  262. package/dist/voice/errors/MethodNotImplementedError.d.ts +0 -22
  263. package/dist/voice/errors/MethodNotImplementedError.js +0 -27
  264. package/dist/voice/filters/AudioFilterFactory.d.ts +0 -35
  265. package/dist/voice/filters/AudioFilterFactory.js +0 -94
  266. package/dist/voice/filters/aiCoustics/createAiCousticsFilter.d.ts +0 -64
  267. package/dist/voice/filters/aiCoustics/createAiCousticsFilter.js +0 -252
  268. package/dist/voice/filters/aiCoustics/types.d.ts +0 -45
  269. package/dist/voice/filters/aiCoustics/types.js +0 -29
  270. package/dist/voice/filters/createAudioFilterChain.d.ts +0 -9
  271. package/dist/voice/filters/createAudioFilterChain.js +0 -171
  272. package/dist/voice/filters/createAudioFilterSession.d.ts +0 -15
  273. package/dist/voice/filters/createAudioFilterSession.js +0 -114
  274. package/dist/voice/filters/pcm.d.ts +0 -21
  275. package/dist/voice/filters/pcm.js +0 -37
  276. package/dist/voice/filters/types.d.ts +0 -61
  277. package/dist/voice/filters/types.js +0 -26
  278. package/dist/voice/handlers/createAnswerHandler.d.ts +0 -23
  279. package/dist/voice/handlers/createAnswerHandler.js +0 -24
  280. package/dist/voice/handlers/createHangupHandler.d.ts +0 -23
  281. package/dist/voice/handlers/createHangupHandler.js +0 -28
  282. package/dist/voice/handlers/createMuteHandler.d.ts +0 -4
  283. package/dist/voice/handlers/createMuteHandler.js +0 -27
  284. package/dist/voice/handlers/createPlayDtmfHandler.d.ts +0 -4
  285. package/dist/voice/handlers/createPlayDtmfHandler.js +0 -27
  286. package/dist/voice/handlers/createPlayHandler.d.ts +0 -4
  287. package/dist/voice/handlers/createPlayHandler.js +0 -33
  288. package/dist/voice/handlers/createPlaybackControlHandler.d.ts +0 -4
  289. package/dist/voice/handlers/createPlaybackControlHandler.js +0 -62
  290. package/dist/voice/handlers/createRecordHandler.d.ts +0 -4
  291. package/dist/voice/handlers/createRecordHandler.js +0 -58
  292. package/dist/voice/handlers/createSayHandler.d.ts +0 -4
  293. package/dist/voice/handlers/createSayHandler.js +0 -31
  294. package/dist/voice/handlers/createSetAudioFiltersHandler.d.ts +0 -11
  295. package/dist/voice/handlers/createSetAudioFiltersHandler.js +0 -74
  296. package/dist/voice/handlers/createStopSayHandler.d.ts +0 -3
  297. package/dist/voice/handlers/createStopSayHandler.js +0 -34
  298. package/dist/voice/handlers/createStreamGatherHandler.d.ts +0 -3
  299. package/dist/voice/handlers/createStreamGatherHandler.js +0 -74
  300. package/dist/voice/handlers/createStreamHandler.d.ts +0 -3
  301. package/dist/voice/handlers/createStreamHandler.js +0 -70
  302. package/dist/voice/handlers/createUnmuteHandler.d.ts +0 -4
  303. package/dist/voice/handlers/createUnmuteHandler.js +0 -27
  304. package/dist/voice/handlers/dial/createDialHandler.d.ts +0 -23
  305. package/dist/voice/handlers/dial/createDialHandler.js +0 -78
  306. package/dist/voice/handlers/dial/handleChannelLeftBridge.d.ts +0 -24
  307. package/dist/voice/handlers/dial/handleChannelLeftBridge.js +0 -29
  308. package/dist/voice/handlers/dial/handleStasisEnd.d.ts +0 -21
  309. package/dist/voice/handlers/dial/handleStasisEnd.js +0 -19
  310. package/dist/voice/handlers/dial/handleStasisStart.d.ts +0 -27
  311. package/dist/voice/handlers/dial/handleStasisStart.js +0 -52
  312. package/dist/voice/handlers/dial/recordChannel.d.ts +0 -22
  313. package/dist/voice/handlers/gather/createGatherHandler.d.ts +0 -3
  314. package/dist/voice/handlers/gather/createGatherHandler.js +0 -86
  315. package/dist/voice/handlers/gather/getTimeoutPromise.d.ts +0 -26
  316. package/dist/voice/handlers/gather/getTimeoutPromise.js +0 -18
  317. package/dist/voice/handlers/index.d.ts +0 -33
  318. package/dist/voice/handlers/index.js +0 -49
  319. package/dist/voice/handlers/utils/awaitForPlaybackFinished.d.ts +0 -21
  320. package/dist/voice/handlers/utils/awaitForPlaybackFinished.js +0 -25
  321. package/dist/voice/handlers/utils/awaitForRecordingFinished.d.ts +0 -5
  322. package/dist/voice/handlers/utils/awaitForRecordingFinished.js +0 -53
  323. package/dist/voice/handlers/utils/isDtmf.d.ts +0 -20
  324. package/dist/voice/handlers/utils/textChunksByClause.d.ts +0 -2
  325. package/dist/voice/handlers/utils/textChunksByClause.js +0 -41
  326. package/dist/voice/handlers/utils/textChunksByFirstNaturalPause.d.ts +0 -2
  327. package/dist/voice/handlers/utils/textChunksByFirstNaturalPause.js +0 -34
  328. package/dist/voice/handlers/utils/withErrorHandling.d.ts +0 -22
  329. package/dist/voice/handlers/utils/withErrorHandling.js +0 -38
  330. package/dist/voice/integrations/ApplicationNotFoundError.d.ts +0 -22
  331. package/dist/voice/integrations/ApplicationNotFoundError.js +0 -28
  332. package/dist/voice/integrations/createCreateContainer.d.ts +0 -4
  333. package/dist/voice/integrations/createCreateContainer.js +0 -76
  334. package/dist/voice/integrations/getSttConfig.js +0 -30
  335. package/dist/voice/integrations/index.js +0 -35
  336. package/dist/voice/integrations/types.d.ts +0 -29
  337. package/dist/voice/stt/AbstractSpeechToText.d.ts +0 -33
  338. package/dist/voice/stt/AbstractSpeechToText.js +0 -19
  339. package/dist/voice/stt/SpeechToTextFactory.d.ts +0 -9
  340. package/dist/voice/stt/SpeechToTextFactory.js +0 -43
  341. package/dist/voice/transcribeOnConnection.d.ts +0 -35
  342. package/dist/voice/transcribeOnConnection.js +0 -91
  343. package/dist/voice/tts/AbstractTextToSpeech.d.ts +0 -40
  344. package/dist/voice/tts/AbstractTextToSpeech.js +0 -50
  345. package/dist/voice/tts/TextToSpeechFactory.d.ts +0 -8
  346. package/dist/voice/tts/TextToSpeechFactory.js +0 -47
  347. package/dist/voice/tts/types.d.ts +0 -48
  348. package/dist/voice/tts/types.js +0 -2
  349. package/dist/voice/tts/utils/convertUlawToPCM16.js +0 -40
  350. package/dist/voice/tts/utils/createChunkedSynthesisStream.d.ts +0 -28
  351. package/dist/voice/tts/utils/createChunkedSynthesisStream.js +0 -78
  352. package/dist/voice/tts/utils/createErrorStream.d.ts +0 -21
  353. package/dist/voice/tts/utils/createErrorStream.js +0 -28
  354. package/dist/voice/tts/utils/index.d.ts +0 -23
  355. package/dist/voice/tts/utils/index.js +0 -39
  356. package/dist/voice/tts/utils/isSsml.d.ts +0 -20
  357. package/dist/voice/tts/utils/isSsml.js +0 -25
  358. package/dist/voice/tts/utils/streamToBuffer.d.ts +0 -20
  359. package/dist/voice/tts/utils/streamToBuffer.js +0 -60
  360. package/dist/voice/types/ari.d.ts +0 -43
  361. package/dist/voice/types/ari.js +0 -48
  362. package/dist/voice/types/index.d.ts +0 -20
  363. package/dist/voice/types/index.js +0 -36
  364. package/dist/voice/types/voice.d.ts +0 -67
  365. package/dist/voice/types/voice.js +0 -2
  366. package/dist/voice/utils/VoiceServiceClientConstructor.d.ts +0 -3
  367. package/dist/voice/utils/createExternalMediaConfig.d.ts +0 -12
  368. package/dist/voice/utils/createExternalMediaConfig.js +0 -37
  369. package/dist/voice/utils/createGetChannelVar.d.ts +0 -22
  370. package/dist/voice/utils/createGetChannelVar.js +0 -27
  371. package/dist/voice/utils/createGetChannelVarWithoutThrow.d.ts +0 -22
  372. package/dist/voice/utils/createGetChannelVarWithoutThrow.js +0 -26
  373. package/dist/voice/utils/index.d.ts +0 -22
  374. package/dist/voice/utils/index.js +0 -38
  375. /package/dist/{events → records}/types.js +0 -0
  376. /package/dist/{voice/integrations → usage}/types.js +0 -0
@@ -18,8 +18,23 @@
18
18
  */
19
19
  import { GrpcErrorMessage } from "@fonoster/common";
20
20
  import { Prisma } from "../core/db";
21
+ import { IsWorkspaceNumber } from "./createIsWorkspaceNumber";
21
22
  import { CallPublisher } from "./types";
22
- declare function createCall(prisma: Prisma, publisher: CallPublisher): (call: {
23
+ /**
24
+ * Asks whether an outbound call may start (add-billing-service D7). A refusal names its reason;
25
+ * an unanswered or failed check admits the call.
26
+ */
27
+ type AdmitCall = (request: {
28
+ callRef: string;
29
+ appRef: string;
30
+ accessKeyId: string;
31
+ from: string;
32
+ to: string;
33
+ }) => Promise<{
34
+ authorized: boolean;
35
+ reason?: string;
36
+ }>;
37
+ declare function createCall(prisma: Prisma, publisher: CallPublisher, isWorkspaceNumber: IsWorkspaceNumber, admitCall?: AdmitCall): (call: {
23
38
  request: unknown;
24
39
  }, callback: (error?: import("@fonoster/common").GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
25
- export { createCall };
40
+ export { AdmitCall, createCall };
@@ -30,17 +30,21 @@ exports.createCall = createCall;
30
30
  */
31
31
  const common_1 = require("@fonoster/common");
32
32
  const logger_1 = require("@fonoster/logger");
33
+ const grpc_js_1 = require("@grpc/grpc-js");
33
34
  const pb_util_1 = require("pb-util");
34
35
  const uuid_1 = require("uuid");
35
36
  const notFoundError_1 = require("../core/notFoundError");
37
+ const types_1 = require("./types");
36
38
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
37
- function createCall(prisma, publisher) {
39
+ function createCall(prisma, publisher, isWorkspaceNumber, admitCall) {
38
40
  const fn = (call, callback) => __awaiter(this, void 0, void 0, function* () {
41
+ var _a, _b;
39
42
  const { request } = call;
40
43
  const { from, to, appRef, timeout, metadata } = request;
41
44
  const ref = (0, uuid_1.v4)();
42
45
  const effectiveMetadata = metadata ? pb_util_1.struct.decode(metadata) : {};
43
- logger.verbose("call to createCall", Object.assign(Object.assign({}, request), { ref }));
46
+ // Not the whole request: metadata may carry the app's secrets (M11).
47
+ logger.verbose("call to createCall", { ref, appRef });
44
48
  const accessKeyId = (0, common_1.getAccessKeyIdFromCall)(call);
45
49
  const app = yield prisma.application.findUnique({
46
50
  where: { ref: appRef, accessKeyId }
@@ -48,15 +52,64 @@ function createCall(prisma, publisher) {
48
52
  if (!app) {
49
53
  throw (0, notFoundError_1.notFoundError)(`Application with ref ${appRef} not found`);
50
54
  }
51
- publisher.publishCall({
52
- ref,
53
- from,
54
- to,
55
- appRef,
56
- accessKeyId,
57
- timeout: timeout || 30,
58
- metadata: effectiveMetadata
59
- });
55
+ // `from` picks the trunk the call leaves by (X-Dod-Number), so it must be one of the
56
+ // workspace's own Numbers; another workspace's number is reported like an unknown one.
57
+ if (!(yield isWorkspaceNumber(accessKeyId, from))) {
58
+ callback({
59
+ code: grpc_js_1.status.PERMISSION_DENIED,
60
+ message: `The number ${from} is not a Number of this workspace`
61
+ });
62
+ return;
63
+ }
64
+ // Admission before any SIP (voice-session, "Calls are admitted before they start").
65
+ if (admitCall) {
66
+ const decision = yield admitCall({
67
+ callRef: ref,
68
+ appRef,
69
+ accessKeyId,
70
+ from,
71
+ to
72
+ });
73
+ if (!decision.authorized) {
74
+ const reason = (_a = decision.reason) !== null && _a !== void 0 ? _a : "not_authorized";
75
+ logger.info("call refused", { ref, reason });
76
+ callback({
77
+ code: grpc_js_1.status.FAILED_PRECONDITION,
78
+ message: `The call was refused: ${reason}`
79
+ });
80
+ return;
81
+ }
82
+ }
83
+ // Placement answers once a Roomr node has accepted the call, so a call with no capacity
84
+ // fails here (RESOURCE_EXHAUSTED) instead of TrackCall reporting FAILED later.
85
+ try {
86
+ yield publisher.publishCall({
87
+ ref,
88
+ from,
89
+ to,
90
+ appRef,
91
+ accessKeyId,
92
+ timeout: timeout || 30,
93
+ metadata: effectiveMetadata
94
+ });
95
+ }
96
+ catch (e) {
97
+ if (!(e instanceof types_1.CallPlacementError))
98
+ throw e;
99
+ logger.warn("call not placed", { ref, code: e.code, message: e.message });
100
+ const code = (_b = {
101
+ no_capacity: grpc_js_1.status.RESOURCE_EXHAUSTED,
102
+ invalid_argument: grpc_js_1.status.INVALID_ARGUMENT,
103
+ already_exists: grpc_js_1.status.ALREADY_EXISTS
104
+ }[e.code]) !== null && _b !== void 0 ? _b : grpc_js_1.status.UNAVAILABLE;
105
+ callback({
106
+ code,
107
+ message: code === grpc_js_1.status.RESOURCE_EXHAUSTED
108
+ ? `No capacity to place the call: ${e.message}`
109
+ : `The call could not be placed: ${e.message}`
110
+ });
111
+ return;
112
+ }
60
113
  callback(null, { ref });
61
114
  });
62
115
  return (0, common_1.withErrorHandlingAndValidation)(fn, common_1.Validators.createCallRequestSchema);
@@ -1,7 +1,45 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { NatsTarget } from "@fonoster/common";
20
+ import { NatsConnection } from "nats";
1
21
  import { CreateCallRequest } from "./types";
2
- declare function createCallPublisher(natsUrl: string): Promise<{
22
+ declare function createCallPublisher(nats: NatsTarget): Promise<{
23
+ /**
24
+ * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
25
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
26
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
27
+ * said, `unavailable` otherwise (no replica answered included).
28
+ */
3
29
  publishCall: (request: CreateCallRequest & {
4
30
  ref: string;
5
31
  }) => Promise<void>;
6
32
  }>;
7
- export { createCallPublisher };
33
+ /** The CallPublisher over an open NATS connection. */
34
+ declare function callPublisher(nc: NatsConnection): {
35
+ /**
36
+ * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
37
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
38
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
39
+ * said, `unavailable` otherwise (no replica answered included).
40
+ */
41
+ publishCall: (request: CreateCallRequest & {
42
+ ref: string;
43
+ }) => Promise<void>;
44
+ };
45
+ export { callPublisher, createCallPublisher };
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.callPublisher = callPublisher;
12
13
  exports.createCallPublisher = createCallPublisher;
13
14
  /**
14
15
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
@@ -28,19 +29,52 @@ exports.createCallPublisher = createCallPublisher;
28
29
  * See the License for the specific language governing permissions and
29
30
  * limitations under the License.
30
31
  */
32
+ const common_1 = require("@fonoster/common");
31
33
  const logger_1 = require("@fonoster/logger");
32
34
  const nats_1 = require("nats");
33
35
  const envs_1 = require("../envs");
36
+ const types_1 = require("./types");
34
37
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
35
- function createCallPublisher(natsUrl) {
38
+ const sc = (0, nats_1.StringCodec)();
39
+ /**
40
+ * How long CreateCall waits for the placement: CreateRoom (a retry on a timeout, up to three
41
+ * nodes), AppBridge's claim and CreateCall (a retry on a timeout), 2 s each, plus margin.
42
+ */
43
+ const PLACE_TIMEOUT_MS = 15000;
44
+ function createCallPublisher(nats) {
36
45
  return __awaiter(this, void 0, void 0, function* () {
37
- logger.verbose("connecting to nats", { natsUrl });
38
- const nc = yield (0, nats_1.connect)({ servers: natsUrl, maxReconnectAttempts: -1 });
39
- return {
40
- publishCall: (request) => __awaiter(this, void 0, void 0, function* () {
41
- logger.verbose("publishing call", { ref: request.ref });
42
- nc.publish(envs_1.CALLS_CREATE_SUBJECT, JSON.stringify(request));
43
- })
44
- };
46
+ const options = (0, common_1.natsConnectOptions)(nats);
47
+ logger.verbose("connecting to nats", { natsUrl: options.servers });
48
+ const nc = yield (0, nats_1.connect)(Object.assign(Object.assign({}, options), { maxReconnectAttempts: -1 }));
49
+ return callPublisher(nc);
45
50
  });
46
51
  }
52
+ /** The CallPublisher over an open NATS connection. */
53
+ function callPublisher(nc) {
54
+ return {
55
+ /**
56
+ * Asks the outbound placement (any replica's `calls.create` queue group) to place the call,
57
+ * and resolves once a Roomr node has accepted CreateCall. Rejects with a CallPlacementError:
58
+ * `no_capacity` when no node took it, `invalid_argument` or `already_exists` as the node
59
+ * said, `unavailable` otherwise (no replica answered included).
60
+ */
61
+ publishCall: (request) => __awaiter(this, void 0, void 0, function* () {
62
+ var _a, _b;
63
+ logger.verbose("placing call", { ref: request.ref });
64
+ let reply;
65
+ try {
66
+ const msg = yield nc.request(envs_1.CALLS_CREATE_SUBJECT, sc.encode(JSON.stringify(request)), { timeout: PLACE_TIMEOUT_MS });
67
+ reply = JSON.parse(sc.decode(msg.data));
68
+ }
69
+ catch (e) {
70
+ const code = e.code;
71
+ throw new types_1.CallPlacementError("unavailable", code === nats_1.ErrorCode.NoResponders
72
+ ? "no call placement is running"
73
+ : `call placement did not answer: ${e.message}`);
74
+ }
75
+ if (reply.type !== "ack") {
76
+ throw new types_1.CallPlacementError(String((_a = reply.code) !== null && _a !== void 0 ? _a : "error"), String((_b = reply.message) !== null && _b !== void 0 ? _b : "the call could not be placed"));
77
+ }
78
+ })
79
+ };
80
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ /** One page of Routr's numbers (the Routr SDK's listNumbers). */
20
+ type NumbersPage = {
21
+ items?: {
22
+ telUrl?: string;
23
+ extended?: Record<string, unknown> | null;
24
+ }[];
25
+ nextPageToken?: string;
26
+ };
27
+ type NumbersLister = {
28
+ listNumbers(request: {
29
+ pageSize: number;
30
+ pageToken?: string;
31
+ }): Promise<NumbersPage>;
32
+ };
33
+ /** Whether `e164` (CreateCall's `from`) is a Number of the workspace `accessKeyId`. */
34
+ type IsWorkspaceNumber = (accessKeyId: string, e164: string) => Promise<boolean>;
35
+ /**
36
+ * CreateCall's `from` becomes X-Dod-Number, which Routr uses to pick the Number's trunk, so it
37
+ * must be one of the caller's own Numbers (security review C2). Routr has no lookup by telUrl in
38
+ * its API, so this pages through the Numbers and matches `tel:<from>` and the workspace.
39
+ */
40
+ declare function createIsWorkspaceNumber(numbers: NumbersLister): IsWorkspaceNumber;
41
+ export { createIsWorkspaceNumber, IsWorkspaceNumber, NumbersLister };
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createIsWorkspaceNumber = createIsWorkspaceNumber;
13
+ const PAGE_SIZE = 200;
14
+ const MAX_PAGES = 100;
15
+ /**
16
+ * CreateCall's `from` becomes X-Dod-Number, which Routr uses to pick the Number's trunk, so it
17
+ * must be one of the caller's own Numbers (security review C2). Routr has no lookup by telUrl in
18
+ * its API, so this pages through the Numbers and matches `tel:<from>` and the workspace.
19
+ */
20
+ function createIsWorkspaceNumber(numbers) {
21
+ return (accessKeyId, e164) => __awaiter(this, void 0, void 0, function* () {
22
+ var _a, _b;
23
+ if (!accessKeyId || !e164)
24
+ return false;
25
+ const telUrl = `tel:${e164}`;
26
+ let pageToken;
27
+ for (let page = 0; page < MAX_PAGES; page++) {
28
+ const res = yield numbers.listNumbers({ pageSize: PAGE_SIZE, pageToken });
29
+ for (const n of (_a = res.items) !== null && _a !== void 0 ? _a : []) {
30
+ if (n.telUrl === telUrl && ((_b = n.extended) === null || _b === void 0 ? void 0 : _b.accessKeyId) === accessKeyId)
31
+ return true;
32
+ }
33
+ if (!res.nextPageToken || res.nextPageToken === pageToken)
34
+ return false;
35
+ pageToken = res.nextPageToken;
36
+ }
37
+ return false;
38
+ });
39
+ }
@@ -1,5 +1,58 @@
1
+ import { BaseApiObject } from "@fonoster/types";
1
2
  import { NatsConnection } from "nats";
2
- declare function createTrackCall(nc: NatsConnection): (call: {
3
+ import { TrackCallResponse } from "./types";
4
+ /** Timings of TrackCall's own end of a call (control-plane, "TrackCall always ends"). */
5
+ export declare const TRACK_CALL_DEFAULTS: {
6
+ /** A stream whose call never reached a Roomr node (no node in this long) ends FAILED. */
7
+ noNodeMs: number;
8
+ /** The call's Roomr node is gone after this long without its heartbeat (3 beats of 2 s). */
9
+ nodeStaleMs: number;
10
+ /** No call outlives the Roomr node's MaxDuration (4 h); a stream ends FAILED after this. */
11
+ maxMs: number;
12
+ /** How often open streams are checked. */
13
+ sweepMs: number;
14
+ };
15
+ export type TrackCallOptions = Partial<typeof TRACK_CALL_DEFAULTS> & {
16
+ now?: () => number;
17
+ };
18
+ type TrackMessage = Partial<TrackCallResponse> & {
19
+ ref: string;
20
+ /** The call is over (the room ended): close the stream. */
21
+ final?: boolean;
22
+ /** The Roomr node that holds the call, when the message says. */
23
+ nodeRef?: string;
24
+ };
25
+ /**
26
+ * One message as a TrackCall message: the control plane's `{ref, status}` (on
27
+ * `calls.<ref>.events`) as is, and the Roomr node's call.ringing, call.answered and call.ended
28
+ * (on `roomr.events.<call_ref>`) translated. Undefined for anything else (receivers ignore
29
+ * unknown event types).
30
+ */
31
+ declare function toTrackMessage(event: Record<string, unknown>, subject?: string): TrackMessage | undefined;
32
+ /**
33
+ * TrackCall: status updates of an API-originated call, from the call's own subjects. The replica
34
+ * that placed the call publishes TRYING (and FAILED) on `calls.<ref>.events`, and the Roomr node
35
+ * publishes the call's events on `roomr.events.<ref>`, so any replica serves TrackCall for any
36
+ * call, even after the placing replica is gone. The SDK subscribes right after CreateCall
37
+ * returns, and the first statuses can come before that, so each call's messages are kept for a
38
+ * while and replayed (also to a second TrackCall for the same call).
39
+ *
40
+ * Every stream ends: on the call's final status, when the client goes away, with FAILED when
41
+ * the call's Roomr node stops sending heartbeats before the final, when no node ever takes the
42
+ * call, or after `maxMs` at most. `node.down` alone does not fail a call: a draining node says it
43
+ * and keeps its live calls, so a call fails after `node.down` only when nothing (no heartbeat, no
44
+ * event of the call) comes from its node for `nodeStaleMs`, i.e. the node exited.
45
+ */
46
+ declare function createTrackCallHandler(nc: NatsConnection, options?: TrackCallOptions): {
47
+ trackCall: (call: {
48
+ request: BaseApiObject;
49
+ }) => void;
50
+ /** Open streams (tests and metrics). */
51
+ size: () => number;
52
+ sweep: () => void;
53
+ stop(): void;
54
+ };
55
+ declare function createTrackCall(nc: NatsConnection, options?: TrackCallOptions): (call: {
3
56
  request: unknown;
4
57
  }, callback: (error?: import("@fonoster/common").GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
5
- export { createTrackCall };
58
+ export { createTrackCall, createTrackCallHandler, toTrackMessage };
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TRACK_CALL_DEFAULTS = void 0;
3
4
  exports.createTrackCall = createTrackCall;
5
+ exports.createTrackCallHandler = createTrackCallHandler;
6
+ exports.toTrackMessage = toTrackMessage;
4
7
  /**
5
8
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
6
9
  * http://github.com/fonoster/fonoster
@@ -28,36 +31,247 @@ const FINAL_STATUSES = [
28
31
  common_1.DialStatus.NOANSWER
29
32
  ];
30
33
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
31
- function createTrackCall(nc) {
32
- const trackingCallsMap = new Map();
33
- const subscription = nc.subscribe(envs_1.CALLS_TRACK_CALL_SUBJECT);
34
- subscription.callback = (err, msg) => {
34
+ /** Statuses that arrive before TrackCall subscribes are kept this long and replayed. */
35
+ const KEEP_MS = 120000;
36
+ /** Timings of TrackCall's own end of a call (control-plane, "TrackCall always ends"). */
37
+ exports.TRACK_CALL_DEFAULTS = {
38
+ /** A stream whose call never reached a Roomr node (no node in this long) ends FAILED. */
39
+ noNodeMs: 30000,
40
+ /** The call's Roomr node is gone after this long without its heartbeat (3 beats of 2 s). */
41
+ nodeStaleMs: 6000,
42
+ /** No call outlives the Roomr node's MaxDuration (4 h); a stream ends FAILED after this. */
43
+ maxMs: 4 * 60 * 60000 + 5 * 60000,
44
+ /** How often open streams are checked. */
45
+ sweepMs: 1000
46
+ };
47
+ /** call.ended causes of an unanswered call → the Calls API's DialStatus names (else FAILED). */
48
+ const UNANSWERED = {
49
+ busy: common_1.DialStatus.BUSY,
50
+ no_answer: common_1.DialStatus.NOANSWER
51
+ };
52
+ /**
53
+ * One message as a TrackCall message: the control plane's `{ref, status}` (on
54
+ * `calls.<ref>.events`) as is, and the Roomr node's call.ringing, call.answered and call.ended
55
+ * (on `roomr.events.<call_ref>`) translated. Undefined for anything else (receivers ignore
56
+ * unknown event types).
57
+ */
58
+ function toTrackMessage(event, subject = "") {
59
+ var _a, _b, _c, _d;
60
+ const tokens = subject.split(".");
61
+ const fromSubject = tokens[0] === "roomr" ? tokens[2] : tokens[1];
62
+ const ref = String((_c = (_b = (_a = event.ref) !== null && _a !== void 0 ? _a : event.call_ref) !== null && _b !== void 0 ? _b : fromSubject) !== null && _c !== void 0 ? _c : "");
63
+ if (!ref)
64
+ return undefined;
65
+ const node = typeof event.node_ref === "string" && event.node_ref
66
+ ? { nodeRef: event.node_ref }
67
+ : {};
68
+ switch (event.type) {
69
+ case "call.started":
70
+ return node.nodeRef ? Object.assign({ ref }, node) : undefined;
71
+ case "call.ringing":
72
+ return Object.assign({ ref, status: common_1.DialStatus.PROGRESS }, node);
73
+ case "call.answered":
74
+ return Object.assign({ ref, status: common_1.DialStatus.ANSWER }, node);
75
+ case "call.ended":
76
+ // An answered call just ends; an unanswered one ends with its dial status.
77
+ return event.answered === true
78
+ ? Object.assign({ ref, final: true }, node) : Object.assign({ ref, status: (_d = UNANSWERED[String(event.cause)]) !== null && _d !== void 0 ? _d : common_1.DialStatus.FAILED, final: true }, node);
79
+ case undefined:
80
+ // The control plane's {ref, status}, {ref, final} and {ref, node_ref} (a node took it).
81
+ return event.status !== undefined || event.final === true || node.nodeRef
82
+ ? Object.assign(Object.assign(Object.assign({ ref }, (event.status !== undefined ? { status: event.status } : {})), (event.final === true ? { final: true } : {})), node)
83
+ : undefined;
84
+ default:
85
+ return undefined;
86
+ }
87
+ }
88
+ /**
89
+ * TrackCall: status updates of an API-originated call, from the call's own subjects. The replica
90
+ * that placed the call publishes TRYING (and FAILED) on `calls.<ref>.events`, and the Roomr node
91
+ * publishes the call's events on `roomr.events.<ref>`, so any replica serves TrackCall for any
92
+ * call, even after the placing replica is gone. The SDK subscribes right after CreateCall
93
+ * returns, and the first statuses can come before that, so each call's messages are kept for a
94
+ * while and replayed (also to a second TrackCall for the same call).
95
+ *
96
+ * Every stream ends: on the call's final status, when the client goes away, with FAILED when
97
+ * the call's Roomr node stops sending heartbeats before the final, when no node ever takes the
98
+ * call, or after `maxMs` at most. `node.down` alone does not fail a call: a draining node says it
99
+ * and keeps its live calls, so a call fails after `node.down` only when nothing (no heartbeat, no
100
+ * event of the call) comes from its node for `nodeStaleMs`, i.e. the node exited.
101
+ */
102
+ function createTrackCallHandler(nc, options = {}) {
103
+ var _a, _b;
104
+ const o = Object.assign(Object.assign({}, exports.TRACK_CALL_DEFAULTS), options);
105
+ const now = (_a = options.now) !== null && _a !== void 0 ? _a : Date.now;
106
+ const tracked = new Map();
107
+ /** Recent messages per call (insertion order is first-seen order). */
108
+ const recent = new Map();
109
+ /** Last heartbeat per Roomr node. */
110
+ const beats = new Map();
111
+ /** When each Roomr node said node.down (cleared by its next heartbeat). */
112
+ const downAt = new Map();
113
+ const subscription = nc.subscribe(envs_1.CALL_EVENTS_WILDCARD);
114
+ const mediaEvents = nc.subscribe(envs_1.MEDIA_CALL_EVENTS_WILDCARD);
115
+ const untrack = (t) => {
116
+ const set = tracked.get(t.ref);
117
+ if (!(set === null || set === void 0 ? void 0 : set.delete(t)))
118
+ return false;
119
+ if (set.size === 0)
120
+ tracked.delete(t.ref);
121
+ return true;
122
+ };
123
+ /** Ends a stream that got no final status: FAILED, then the end. */
124
+ const fail = (t, why) => {
125
+ if (!untrack(t))
126
+ return;
127
+ logger.warn(`TrackCall ${t.ref}: ${why}; ending with FAILED`);
128
+ try {
129
+ t.stream.write({ ref: t.ref, status: common_1.DialStatus.FAILED });
130
+ t.stream.end();
131
+ }
132
+ catch (_a) {
133
+ // the client is gone
134
+ }
135
+ };
136
+ /** Writes one message; returns true when the stream is done. */
137
+ const deliver = (t, message) => {
138
+ const { ref, status } = message;
139
+ if (message.nodeRef && message.nodeRef !== t.nodeRef) {
140
+ t.nodeRef = message.nodeRef;
141
+ }
142
+ // Any message of the call proves its node is still there (a draining node sends no heartbeats).
143
+ if (t.nodeRef)
144
+ t.nodeAt = now();
145
+ if (status)
146
+ t.stream.write({ ref, status });
147
+ const done = message.final === true || (!!status && FINAL_STATUSES.includes(status));
148
+ if (done) {
149
+ untrack(t);
150
+ setTimeout(() => t.stream.end(), 500);
151
+ }
152
+ return done;
153
+ };
154
+ const onEvent = (err, msg) => {
155
+ var _a, _b, _c;
35
156
  // We can't do much more than log the error
36
157
  if (err) {
37
158
  logger.error("call to subscription.callback", { err });
38
159
  return;
39
160
  }
40
- const { ref, status } = msg === null || msg === void 0 ? void 0 : msg.json();
161
+ let message;
162
+ try {
163
+ const event = msg === null || msg === void 0 ? void 0 : msg.json();
164
+ // Any event of a call, status or not, shows its node is still there (a draining node
165
+ // sends no heartbeats).
166
+ const eventRef = typeof (event === null || event === void 0 ? void 0 : event.call_ref) === "string" ? event.call_ref : "";
167
+ for (const t of (_a = tracked.get(eventRef)) !== null && _a !== void 0 ? _a : [])
168
+ if (t.nodeRef && t.nodeRef === event.node_ref)
169
+ t.nodeAt = now();
170
+ message = toTrackMessage(event, msg === null || msg === void 0 ? void 0 : msg.subject);
171
+ }
172
+ catch (_d) {
173
+ return; // not JSON
174
+ }
175
+ if (!message)
176
+ return;
177
+ const { ref, status } = message;
41
178
  logger.verbose("call to subscription.callback", { ref, status });
42
- const stream = trackingCallsMap.get(ref);
43
- if (!stream) {
44
- // There is not request to track this call
179
+ const kept = (_b = recent.get(ref)) !== null && _b !== void 0 ? _b : { at: now(), messages: [] };
180
+ kept.messages.push(message);
181
+ recent.set(ref, kept);
182
+ for (const t of [...((_c = tracked.get(ref)) !== null && _c !== void 0 ? _c : [])])
183
+ deliver(t, message);
184
+ };
185
+ subscription.callback = onEvent;
186
+ mediaEvents.callback = onEvent;
187
+ const onHeartbeat = (err, msg) => {
188
+ if (err)
45
189
  return;
190
+ let event;
191
+ try {
192
+ event = msg === null || msg === void 0 ? void 0 : msg.json();
46
193
  }
47
- if (FINAL_STATUSES.includes(status)) {
48
- stream.write({ ref, status });
49
- setTimeout(() => stream.end(), 500);
50
- trackingCallsMap.delete(ref);
194
+ catch (_a) {
195
+ return;
51
196
  }
52
- else {
53
- stream.write({ ref, status });
197
+ const nodeRef = typeof (event === null || event === void 0 ? void 0 : event.node_ref) === "string" ? event.node_ref : "";
198
+ if (!nodeRef)
199
+ return;
200
+ if (event.type === "node.heartbeat") {
201
+ beats.set(nodeRef, now());
202
+ downAt.delete(nodeRef);
54
203
  }
204
+ else if (event.type === "node.down") {
205
+ // Only a mark: the node may be draining with live calls (see the sweep).
206
+ downAt.set(nodeRef, now());
207
+ }
208
+ };
209
+ const heartbeats = nc.subscribe(envs_1.NODE_HEARTBEAT_WILDCARD, {
210
+ callback: onHeartbeat
211
+ });
212
+ const sweep = () => {
213
+ var _a, _b, _c;
214
+ const at = now();
215
+ for (const [ref, kept] of recent) {
216
+ if (at - kept.at <= KEEP_MS)
217
+ break;
218
+ recent.delete(ref);
219
+ }
220
+ for (const [nodeRef, seen] of beats)
221
+ if (at - seen > KEEP_MS)
222
+ beats.delete(nodeRef);
223
+ for (const [nodeRef, down] of downAt)
224
+ if (at - down > KEEP_MS)
225
+ downAt.delete(nodeRef);
226
+ for (const set of [...tracked.values()])
227
+ for (const t of [...set]) {
228
+ if (at - t.startedAt > o.maxMs) {
229
+ fail(t, "no final status in time");
230
+ }
231
+ else if (!t.nodeRef) {
232
+ if (at - t.startedAt > o.noNodeMs)
233
+ fail(t, "no Roomr node took the call");
234
+ }
235
+ else {
236
+ const seen = Math.max((_a = beats.get(t.nodeRef)) !== null && _a !== void 0 ? _a : 0, (_b = downAt.get(t.nodeRef)) !== null && _b !== void 0 ? _b : 0, (_c = t.nodeAt) !== null && _c !== void 0 ? _c : 0);
237
+ if (at - seen > o.nodeStaleMs)
238
+ fail(t, `Roomr node ${t.nodeRef} missed its heartbeats`);
239
+ }
240
+ }
55
241
  };
242
+ const timer = setInterval(sweep, o.sweepMs);
243
+ (_b = timer.unref) === null || _b === void 0 ? void 0 : _b.call(timer);
56
244
  const trackCall = (call) => {
245
+ var _a, _b, _c;
57
246
  const stream = call;
58
247
  const { ref } = call.request;
59
248
  logger.verbose("call to trackCall", { ref });
60
- trackingCallsMap.set(ref, stream);
249
+ const t = { ref, stream, startedAt: now() };
250
+ let set = tracked.get(ref);
251
+ if (!set)
252
+ tracked.set(ref, (set = new Set()));
253
+ set.add(t);
254
+ // The client went away (cancelled the stream or lost its connection).
255
+ for (const event of ["cancelled", "close", "error"])
256
+ (_a = stream.on) === null || _a === void 0 ? void 0 : _a.call(stream, event, () => untrack(t));
257
+ for (const message of (_c = (_b = recent.get(ref)) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : [])
258
+ if (deliver(t, message))
259
+ return;
61
260
  };
62
- return (0, common_1.withErrorHandlingAndValidation)(trackCall, common_1.Validators.baseApiObjectSchema);
261
+ return {
262
+ trackCall,
263
+ /** Open streams (tests and metrics). */
264
+ size: () => [...tracked.values()].reduce((n, s) => n + s.size, 0),
265
+ sweep,
266
+ stop() {
267
+ var _a, _b, _c;
268
+ clearInterval(timer);
269
+ (_a = subscription.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(subscription);
270
+ (_b = mediaEvents.unsubscribe) === null || _b === void 0 ? void 0 : _b.call(mediaEvents);
271
+ (_c = heartbeats.unsubscribe) === null || _c === void 0 ? void 0 : _c.call(heartbeats);
272
+ }
273
+ };
274
+ }
275
+ function createTrackCall(nc, options) {
276
+ return (0, common_1.withErrorHandlingAndValidation)(createTrackCallHandler(nc, options).trackCall, common_1.Validators.baseApiObjectSchema);
63
277
  }