@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
@@ -0,0 +1,45 @@
1
+ import { NatsConnection } from "nats";
2
+ import { RelaySlots } from "./relaySlots";
3
+ export type RelayRequest = {
4
+ userRef: string;
5
+ /** The caller's workspace; the region serves only that workspace's records (PR-14). */
6
+ workspaceRef: string;
7
+ op: "record.get" | "record.part";
8
+ callRef: string;
9
+ part?: string;
10
+ range?: string;
11
+ /** record.get: the unredacted original (the control plane checked the role). */
12
+ original?: boolean;
13
+ version?: number;
14
+ };
15
+ /** A relay that could not complete: `region_offline` (no answer), or the cell's error code. */
16
+ export declare class RelayError extends Error {
17
+ readonly code: string;
18
+ constructor(code: string, message?: string);
19
+ }
20
+ export declare const RELAY_CHUNK_MAX: number;
21
+ /**
22
+ * Fetches call content from a private cell over the link (PR-5, task 2.5). The reply inbox is under
23
+ * `region.R._INBOX` so it stays inside the region's subjects (RG-B4). Chunks are yielded in `seq`
24
+ * order as they arrive; nothing is buffered beyond out-of-order chunks or written anywhere.
25
+ */
26
+ export declare function createRelayClient(nc: NatsConnection, options?: {
27
+ firstChunkTimeoutMs?: number;
28
+ idleTimeoutMs?: number;
29
+ maxBytes?: number;
30
+ /** Relays in flight per region; more answer `rate_limited` (HTTP 429). */
31
+ maxConcurrent?: number;
32
+ /**
33
+ * Where the relays in flight are counted: the database in production, so the limit is per
34
+ * region across every replica (ST-4); this process's memory by default.
35
+ */
36
+ slots?: RelaySlots;
37
+ }): {
38
+ /** Opens a relay; resolves once the first chunk is in (so the HTTP status is known). */
39
+ open(regionRef: string, request: RelayRequest): Promise<{
40
+ contentType: string;
41
+ chunks: AsyncGenerator<Buffer<ArrayBufferLike>, any, any>;
42
+ close: () => void;
43
+ }>;
44
+ };
45
+ export type RelayClient = ReturnType<typeof createRelayClient>;
@@ -0,0 +1,203 @@
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
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
19
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
20
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
21
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
22
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
23
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
24
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
25
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
26
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
27
+ function fulfill(value) { resume("next", value); }
28
+ function reject(value) { resume("throw", value); }
29
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.RELAY_CHUNK_MAX = exports.RelayError = void 0;
33
+ exports.createRelayClient = createRelayClient;
34
+ /**
35
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
36
+ * http://github.com/fonoster/fonoster
37
+ *
38
+ * This file is part of Fonoster
39
+ *
40
+ * Licensed under the MIT License (the "License");
41
+ * you may not use this file except in compliance with
42
+ * the License. You may obtain a copy of the License at
43
+ *
44
+ * https://opensource.org/licenses/MIT
45
+ *
46
+ * Unless required by applicable law or agreed to in writing, software
47
+ * distributed under the License is distributed on an "AS IS" BASIS,
48
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
49
+ * See the License for the specific language governing permissions and
50
+ * limitations under the License.
51
+ */
52
+ const crypto_1 = require("crypto");
53
+ const nats_1 = require("nats");
54
+ const relaySlots_1 = require("./relaySlots");
55
+ const types_1 = require("./types");
56
+ const sc = (0, nats_1.StringCodec)();
57
+ /** A relay that could not complete: `region_offline` (no answer), or the cell's error code. */
58
+ class RelayError extends Error {
59
+ constructor(code, message) {
60
+ super(message !== null && message !== void 0 ? message : code);
61
+ this.code = code;
62
+ }
63
+ }
64
+ exports.RelayError = RelayError;
65
+ exports.RELAY_CHUNK_MAX = 512 * 1024;
66
+ /**
67
+ * Fetches call content from a private cell over the link (PR-5, task 2.5). The reply inbox is under
68
+ * `region.R._INBOX` so it stays inside the region's subjects (RG-B4). Chunks are yielded in `seq`
69
+ * order as they arrive; nothing is buffered beyond out-of-order chunks or written anywhere.
70
+ */
71
+ function createRelayClient(nc, options = {}) {
72
+ var _a, _b, _c, _d, _e;
73
+ const slots = (_a = options.slots) !== null && _a !== void 0 ? _a : (0, relaySlots_1.memoryRelaySlots)();
74
+ const maxConcurrent = (_b = options.maxConcurrent) !== null && _b !== void 0 ? _b : 8;
75
+ const firstTimeout = (_c = options.firstChunkTimeoutMs) !== null && _c !== void 0 ? _c : 5000;
76
+ const idleTimeout = (_d = options.idleTimeoutMs) !== null && _d !== void 0 ? _d : 10000;
77
+ const maxBytes = (_e = options.maxBytes) !== null && _e !== void 0 ? _e : 256 * 1024 * 1024;
78
+ return {
79
+ /** Opens a relay; resolves once the first chunk is in (so the HTTP status is known). */
80
+ open(regionRef, request) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ var _a;
83
+ const release = yield slots.acquire(regionRef, maxConcurrent);
84
+ if (!release)
85
+ throw new RelayError("rate_limited", "too many downloads from this region at once");
86
+ const id = (0, crypto_1.randomUUID)();
87
+ const inbox = `${(0, types_1.subjects)(regionRef).inbox}.${id}`;
88
+ const sub = nc.subscribe(inbox);
89
+ const pending = new Map();
90
+ let next = 0;
91
+ let done = false;
92
+ let waiter;
93
+ const queue = [];
94
+ const deliver = (c) => {
95
+ if (waiter) {
96
+ const w = waiter;
97
+ waiter = undefined;
98
+ w(c);
99
+ }
100
+ else
101
+ queue.push(c);
102
+ };
103
+ void (() => __awaiter(this, void 0, void 0, function* () {
104
+ var _a, e_1, _b, _c;
105
+ var _d, _e;
106
+ try {
107
+ for (var _f = true, sub_1 = __asyncValues(sub), sub_1_1; sub_1_1 = yield sub_1.next(), _a = sub_1_1.done, !_a; _f = true) {
108
+ _c = sub_1_1.value;
109
+ _f = false;
110
+ const m = _c;
111
+ let c;
112
+ try {
113
+ c = JSON.parse(sc.decode(m.data));
114
+ }
115
+ catch (_g) {
116
+ continue;
117
+ }
118
+ if (c.id !== id)
119
+ continue;
120
+ if (c.type === "region.relay.error") {
121
+ deliver(new RelayError((_d = c.code) !== null && _d !== void 0 ? _d : "relay_failed", c.message));
122
+ continue;
123
+ }
124
+ pending.set(Number((_e = c.seq) !== null && _e !== void 0 ? _e : 0), c);
125
+ while (pending.has(next)) {
126
+ deliver(pending.get(next));
127
+ pending.delete(next);
128
+ next++;
129
+ }
130
+ }
131
+ }
132
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
133
+ finally {
134
+ try {
135
+ if (!_f && !_a && (_b = sub_1.return)) yield _b.call(sub_1);
136
+ }
137
+ finally { if (e_1) throw e_1.error; }
138
+ }
139
+ }))();
140
+ const take = (timeoutMs) => new Promise((resolve, reject) => {
141
+ const settle = (c) => {
142
+ clearTimeout(timer);
143
+ if (c instanceof Error)
144
+ reject(c);
145
+ else
146
+ resolve(c);
147
+ };
148
+ const timer = setTimeout(() => {
149
+ waiter = undefined;
150
+ reject(new RelayError("region_offline", "the private region did not answer; it may be offline"));
151
+ }, timeoutMs);
152
+ const queued = queue.shift();
153
+ if (queued)
154
+ settle(queued);
155
+ else
156
+ waiter = settle;
157
+ });
158
+ const close = () => {
159
+ done = true;
160
+ sub.unsubscribe();
161
+ release();
162
+ };
163
+ nc.publish((0, types_1.subjects)(regionRef).relay, sc.encode(JSON.stringify(Object.assign({ type: "region.relay", id }, request))), { reply: inbox });
164
+ let first;
165
+ try {
166
+ first = yield take(firstTimeout);
167
+ }
168
+ catch (e) {
169
+ close();
170
+ throw e;
171
+ }
172
+ function chunks() {
173
+ return __asyncGenerator(this, arguments, function* chunks_1() {
174
+ var _a;
175
+ let c = first;
176
+ let total = 0;
177
+ try {
178
+ while (c) {
179
+ const data = Buffer.from((_a = c.data) !== null && _a !== void 0 ? _a : "", "base64");
180
+ total += data.length;
181
+ if (total > maxBytes)
182
+ throw new RelayError("too_large", "relayed content exceeds the limit");
183
+ if (data.length)
184
+ yield yield __await(data);
185
+ if (c.last || done)
186
+ return yield __await(void 0);
187
+ c = yield __await(take(idleTimeout));
188
+ }
189
+ }
190
+ finally {
191
+ close();
192
+ }
193
+ });
194
+ }
195
+ return {
196
+ contentType: (_a = first.contentType) !== null && _a !== void 0 ? _a : "application/octet-stream",
197
+ chunks: chunks(),
198
+ close
199
+ };
200
+ });
201
+ }
202
+ };
203
+ }
@@ -0,0 +1,7 @@
1
+ import { Response } from "express";
2
+ import { RelayClient, RelayRequest } from "./relay";
3
+ /**
4
+ * Streams relayed content into an HTTP response: headers once the first chunk is in, then each
5
+ * chunk as it arrives. Nothing is written to disk or storage (contract §5).
6
+ */
7
+ export declare function relayToResponse(client: RelayClient, regionRef: string, request: RelayRequest, res: Response, headers?: Record<string, string>): Promise<Response<any, Record<string, any>>>;
@@ -0,0 +1,107 @@
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
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.relayToResponse = relayToResponse;
20
+ /**
21
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
22
+ * http://github.com/fonoster/fonoster
23
+ *
24
+ * This file is part of Fonoster
25
+ *
26
+ * Licensed under the MIT License (the "License");
27
+ * you may not use this file except in compliance with
28
+ * the License. You may obtain a copy of the License at
29
+ *
30
+ * https://opensource.org/licenses/MIT
31
+ *
32
+ * Unless required by applicable law or agreed to in writing, software
33
+ * distributed under the License is distributed on an "AS IS" BASIS,
34
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35
+ * See the License for the specific language governing permissions and
36
+ * limitations under the License.
37
+ */
38
+ const logger_1 = require("@fonoster/logger");
39
+ const relay_1 = require("./relay");
40
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
41
+ const STATUS = {
42
+ region_offline: 503,
43
+ not_found: 404,
44
+ contents_deleted: 410,
45
+ erased: 410,
46
+ permission_denied: 403,
47
+ too_large: 413,
48
+ rate_limited: 429
49
+ };
50
+ /**
51
+ * Streams relayed content into an HTTP response: headers once the first chunk is in, then each
52
+ * chunk as it arrives. Nothing is written to disk or storage (contract §5).
53
+ */
54
+ function relayToResponse(client_1, regionRef_1, request_1, res_1) {
55
+ return __awaiter(this, arguments, void 0, function* (client, regionRef, request, res, headers = {}) {
56
+ var _a, e_1, _b, _c;
57
+ var _d;
58
+ let opened;
59
+ try {
60
+ opened = yield client.open(regionRef, request);
61
+ }
62
+ catch (e) {
63
+ const code = e instanceof relay_1.RelayError ? e.code : "relay_failed";
64
+ return res.status((_d = STATUS[code]) !== null && _d !== void 0 ? _d : 502).json({
65
+ error: code,
66
+ message: code === "region_offline"
67
+ ? "Your region is offline; the call's content stays in your region"
68
+ : e.message
69
+ });
70
+ }
71
+ res.status(200);
72
+ res.setHeader("content-type", opened.contentType);
73
+ res.setHeader("cache-control", "no-store");
74
+ for (const [k, v] of Object.entries(headers))
75
+ res.setHeader(k, v);
76
+ // The browser went away: stop the relay and free its slot.
77
+ res.once("close", () => opened.close());
78
+ try {
79
+ try {
80
+ for (var _e = true, _f = __asyncValues(opened.chunks), _g; _g = yield _f.next(), _a = _g.done, !_a; _e = true) {
81
+ _c = _g.value;
82
+ _e = false;
83
+ const chunk = _c;
84
+ if (res.destroyed)
85
+ break;
86
+ if (!res.write(chunk))
87
+ yield new Promise((resolve) => {
88
+ res.once("drain", resolve);
89
+ res.once("close", resolve);
90
+ });
91
+ }
92
+ }
93
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
94
+ finally {
95
+ try {
96
+ if (!_e && !_a && (_b = _f.return)) yield _b.call(_f);
97
+ }
98
+ finally { if (e_1) throw e_1.error; }
99
+ }
100
+ res.end();
101
+ }
102
+ catch (e) {
103
+ logger.warn(`relay from ${regionRef} broke off: ${e.message}`);
104
+ res.destroy(e);
105
+ }
106
+ });
107
+ }
@@ -0,0 +1,18 @@
1
+ import { RegionsDb } from "./types";
2
+ /**
3
+ * Concurrent relays per private region (ST-4). `acquire` answers a release function, or
4
+ * undefined when the region already has `max` relays in flight.
5
+ */
6
+ export type RelaySlots = {
7
+ acquire(regionRef: string, max: number): Promise<(() => void) | undefined>;
8
+ };
9
+ /** This process only: with N replicas a region gets up to N × max (tests, no database). */
10
+ export declare function memoryRelaySlots(): RelaySlots;
11
+ /**
12
+ * Slots shared by every apiserver replica: one row per (region, slot number) in Postgres, leased
13
+ * by the replica relaying the download and refreshed while it runs, so the limit holds across the
14
+ * cluster and a slot of a replica that died frees itself when its lease runs out.
15
+ */
16
+ export declare function prismaRelaySlots(db: RegionsDb, options?: {
17
+ leaseMs?: number;
18
+ }): RelaySlots;
@@ -0,0 +1,118 @@
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.memoryRelaySlots = memoryRelaySlots;
13
+ exports.prismaRelaySlots = prismaRelaySlots;
14
+ /**
15
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
16
+ * http://github.com/fonoster/fonoster
17
+ *
18
+ * This file is part of Fonoster
19
+ *
20
+ * Licensed under the MIT License (the "License");
21
+ * you may not use this file except in compliance with
22
+ * the License. You may obtain a copy of the License at
23
+ *
24
+ * https://opensource.org/licenses/MIT
25
+ *
26
+ * Unless required by applicable law or agreed to in writing, software
27
+ * distributed under the License is distributed on an "AS IS" BASIS,
28
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
+ * See the License for the specific language governing permissions and
30
+ * limitations under the License.
31
+ */
32
+ const crypto_1 = require("crypto");
33
+ /** This process only: with N replicas a region gets up to N × max (tests, no database). */
34
+ function memoryRelaySlots() {
35
+ const inFlight = new Map();
36
+ return {
37
+ acquire(regionRef, max) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ var _a;
40
+ const busy = (_a = inFlight.get(regionRef)) !== null && _a !== void 0 ? _a : 0;
41
+ if (busy >= max)
42
+ return undefined;
43
+ inFlight.set(regionRef, busy + 1);
44
+ let released = false;
45
+ return () => {
46
+ var _a;
47
+ if (released)
48
+ return;
49
+ released = true;
50
+ const n = ((_a = inFlight.get(regionRef)) !== null && _a !== void 0 ? _a : 1) - 1;
51
+ if (n > 0)
52
+ inFlight.set(regionRef, n);
53
+ else
54
+ inFlight.delete(regionRef);
55
+ };
56
+ });
57
+ }
58
+ };
59
+ }
60
+ /**
61
+ * Slots shared by every apiserver replica: one row per (region, slot number) in Postgres, leased
62
+ * by the replica relaying the download and refreshed while it runs, so the limit holds across the
63
+ * cluster and a slot of a replica that died frees itself when its lease runs out.
64
+ */
65
+ function prismaRelaySlots(db, options = {}) {
66
+ var _a;
67
+ const leaseMs = (_a = options.leaseMs) !== null && _a !== void 0 ? _a : 30000;
68
+ return {
69
+ acquire(regionRef, max) {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ var _a;
72
+ const holder = (0, crypto_1.randomUUID)();
73
+ // Takes the lowest slot that is free or whose lease ran out. Two replicas racing for the
74
+ // same slot: the primary key lets one in, the other tries again.
75
+ for (let attempt = 0; attempt < 3; attempt++) {
76
+ const rows = yield db.$queryRaw `
77
+ INSERT INTO "region_relay_slots" ("region_ref", "slot", "holder", "expires_at")
78
+ SELECT ${regionRef}, s, ${holder}, now() + (${leaseMs} * interval '1 millisecond')
79
+ FROM generate_series(0, ${max}::int - 1) AS s
80
+ WHERE s NOT IN (
81
+ SELECT "slot" FROM "region_relay_slots"
82
+ WHERE "region_ref" = ${regionRef} AND "expires_at" > now()
83
+ )
84
+ ORDER BY s
85
+ LIMIT 1
86
+ ON CONFLICT ("region_ref", "slot") DO UPDATE
87
+ SET "holder" = EXCLUDED."holder", "expires_at" = EXCLUDED."expires_at"
88
+ WHERE "region_relay_slots"."expires_at" <= now()
89
+ RETURNING "slot"`;
90
+ if (rows.length) {
91
+ const slot = rows[0].slot;
92
+ const refresh = setInterval(() => void db.$executeRaw `
93
+ UPDATE "region_relay_slots"
94
+ SET "expires_at" = now() + (${leaseMs} * interval '1 millisecond')
95
+ WHERE "region_ref" = ${regionRef} AND "slot" = ${slot} AND "holder" = ${holder}`.catch(() => undefined), Math.max(1000, Math.floor(leaseMs / 3)));
96
+ (_a = refresh.unref) === null || _a === void 0 ? void 0 : _a.call(refresh);
97
+ let released = false;
98
+ return () => {
99
+ if (released)
100
+ return;
101
+ released = true;
102
+ clearInterval(refresh);
103
+ void db.$executeRaw `
104
+ DELETE FROM "region_relay_slots"
105
+ WHERE "region_ref" = ${regionRef} AND "slot" = ${slot} AND "holder" = ${holder}`.catch(() => undefined);
106
+ };
107
+ }
108
+ const [{ busy }] = yield db.$queryRaw `
109
+ SELECT count(*)::int AS busy FROM "region_relay_slots"
110
+ WHERE "region_ref" = ${regionRef} AND "expires_at" > now()`;
111
+ if (busy >= max)
112
+ return undefined;
113
+ }
114
+ return undefined;
115
+ });
116
+ }
117
+ };
118
+ }
@@ -0,0 +1,111 @@
1
+ import { Router } from "express";
2
+ import { NatsConnection } from "nats";
3
+ import { ConfigSync, SnapshotSources } from "./configSync";
4
+ import { RegionSigner } from "./enrollmentToken";
5
+ import { RegionNatsAuth } from "./natsAuth";
6
+ import { RelayClient } from "./relay";
7
+ import { RegionService } from "./service";
8
+ import { PublicRegion, RegionsDb, WorkspaceDirectory } from "./types";
9
+ export type RegionsConfig = {
10
+ public: PublicRegion[];
11
+ controlPlaneUrl?: string;
12
+ leafUrl?: string;
13
+ allowInsecureLeaf: boolean;
14
+ signingKey?: {
15
+ file: string;
16
+ kid?: string;
17
+ };
18
+ hub?: {
19
+ url: string;
20
+ credentialsFile: string;
21
+ systemCredentialsFile: string;
22
+ operatorSeedFile: string;
23
+ accountSeedFile: string;
24
+ };
25
+ relay: {
26
+ firstChunkTimeoutMs: number;
27
+ idleTimeoutMs: number;
28
+ maxBytes: number;
29
+ maxConcurrent?: number;
30
+ };
31
+ currentVersion?: string;
32
+ configDebounceMs: number;
33
+ /** PR-19: the admin API's only credential (resolved from secret:// by the config loader). */
34
+ operatorKey?: string;
35
+ privateRegionMonthlyFeeCents?: number;
36
+ };
37
+ export type RegionsRuntime = {
38
+ service: RegionService;
39
+ configSync?: ConfigSync;
40
+ relay?: RelayClient;
41
+ signer?: RegionSigner;
42
+ publicRegions: PublicRegion[];
43
+ /** Private regions are on (signing key + hub); otherwise `routers` is empty. */
44
+ privateRegions: boolean;
45
+ routers: {
46
+ path: string;
47
+ router: Router;
48
+ }[];
49
+ /** A workspace's synced config changed (numbers, apps, Routr resources, webhooks, policy). */
50
+ onConfigChange(accessKeyId: string): void;
51
+ /** The ref of the enrolled-region row a workspace is bound to (content is relayed from it). */
52
+ regionOf(accessKeyId: string): Promise<string | undefined>;
53
+ close(): Promise<void>;
54
+ };
55
+ /** Starts private regions on the control plane: service, hub link, config sync, relay, routes. */
56
+ export declare function runRegions(config: RegionsConfig, deps: {
57
+ db: RegionsDb;
58
+ identityPublicKey: string;
59
+ /** Identity's issuer and audience, checked on user tokens. */
60
+ identityTokenOptions?: {
61
+ issuer?: string;
62
+ audience?: string;
63
+ };
64
+ issuer: string;
65
+ defaultControlPlaneUrl: string;
66
+ defaultLeafUrl: string;
67
+ currentVersion: string;
68
+ sources: SnapshotSources;
69
+ /** Tests pass connections instead of hub files. */
70
+ hubConnections?: {
71
+ nc: NatsConnection;
72
+ system?: NatsConnection;
73
+ };
74
+ natsSeeds?: {
75
+ operatorSeed: string;
76
+ accountSeed: string;
77
+ };
78
+ signer?: RegionSigner;
79
+ /** Tests on a plain NATS server (no hub) pass their own issuer/revoker. */
80
+ natsAuth?: RegionNatsAuth;
81
+ /** Identity's workspaces (tests); production attaches it through the workspace hooks. */
82
+ directory?: WorkspaceDirectory;
83
+ /** The cloud's SIP root domain (workspace domains end with it). */
84
+ rootDomain?: () => string;
85
+ }): Promise<RegionsRuntime>;
86
+ /**
87
+ * The hooks Identity calls (PR-1, PR-14, PR-15): which region a new workspace may pick, and that a
88
+ * workspace joined or left a region. Identity is built before the regions runtime starts, so the
89
+ * hooks delegate to it once attached; Identity attaches its workspace directory the same way.
90
+ */
91
+ export declare function createWorkspaceRegionHooks(publicRegions: PublicRegion[]): {
92
+ publicRegions: string[];
93
+ defaultRegion: string;
94
+ attach(r: RegionsRuntime): void;
95
+ attachDirectory(d: WorkspaceDirectory): void;
96
+ /** Identity's workspaces once attached (usage ingest resolves owners with it). */
97
+ directory(): WorkspaceDirectory | undefined;
98
+ /**
99
+ * The `Workspace.region` value for what the caller picked: an offered public region id, or
100
+ * one of the caller's private regions (id or ref). Throws RegionError 400 otherwise.
101
+ */
102
+ resolveRegion(ownerRef: string, requested?: string): Promise<{
103
+ region: any;
104
+ }>;
105
+ /** A workspace joined (created) or left (deleted) a region: resync that region. */
106
+ workspaceChanged(workspace: {
107
+ accessKeyId: string;
108
+ region: string;
109
+ }): void;
110
+ };
111
+ export type WorkspaceRegionHooks = ReturnType<typeof createWorkspaceRegionHooks>;