@signalwire/sdk 2.0.5 → 3.6.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 (659) hide show
  1. package/CHANGELOG.md +821 -0
  2. package/LICENSE +21 -0
  3. package/README.md +163 -68
  4. package/dist/AGENTS.md +13 -0
  5. package/dist/AgentBase.d.ts +510 -126
  6. package/dist/AgentBase.js +1581 -455
  7. package/dist/AgentBase.js.map +1 -1
  8. package/dist/AgentServer.d.ts +21 -0
  9. package/dist/AgentServer.js +154 -47
  10. package/dist/AgentServer.js.map +1 -1
  11. package/dist/AuthHandler.d.ts +14 -2
  12. package/dist/AuthHandler.js +7 -2
  13. package/dist/AuthHandler.js.map +1 -1
  14. package/dist/ConfigLoader.d.ts +5 -13
  15. package/dist/ConfigLoader.js +15 -29
  16. package/dist/ConfigLoader.js.map +1 -1
  17. package/dist/ContextBuilder.d.ts +202 -9
  18. package/dist/ContextBuilder.js +219 -36
  19. package/dist/ContextBuilder.js.map +1 -1
  20. package/dist/DataMap.d.ts +186 -45
  21. package/dist/DataMap.js +210 -52
  22. package/dist/DataMap.js.map +1 -1
  23. package/dist/FunctionResult.d.ts +309 -83
  24. package/dist/FunctionResult.js +483 -116
  25. package/dist/FunctionResult.js.map +1 -1
  26. package/dist/Logger.d.ts +30 -5
  27. package/dist/Logger.js +77 -19
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/POM/PromptObjectModel.d.ts +12 -1
  30. package/dist/POM/PromptObjectModel.js +25 -9
  31. package/dist/POM/PromptObjectModel.js.map +1 -1
  32. package/dist/ParameterSchema.d.ts +306 -0
  33. package/dist/ParameterSchema.js +251 -0
  34. package/dist/ParameterSchema.js.map +1 -0
  35. package/dist/PlatformContracts.d.ts +21 -0
  36. package/dist/PlatformContracts.generated.d.ts +109 -0
  37. package/dist/PlatformContracts.generated.js +8 -0
  38. package/dist/PlatformContracts.generated.js.map +1 -0
  39. package/dist/PlatformContracts.js +2 -0
  40. package/dist/PlatformContracts.js.map +1 -0
  41. package/dist/PomBuilder.d.ts +18 -0
  42. package/dist/PomBuilder.js +53 -3
  43. package/dist/PomBuilder.js.map +1 -1
  44. package/dist/PostPrompt.d.ts +110 -0
  45. package/dist/PostPrompt.js +204 -0
  46. package/dist/PostPrompt.js.map +1 -0
  47. package/dist/PromptManager.d.ts +22 -1
  48. package/dist/PromptManager.js +28 -1
  49. package/dist/PromptManager.js.map +1 -1
  50. package/dist/PublicFetch.d.ts +132 -0
  51. package/dist/PublicFetch.js +311 -0
  52. package/dist/PublicFetch.js.map +1 -0
  53. package/dist/RobotsTxt.d.ts +41 -0
  54. package/dist/RobotsTxt.js +152 -0
  55. package/dist/RobotsTxt.js.map +1 -0
  56. package/dist/SWMLHandler.js.map +1 -1
  57. package/dist/SWMLService.d.ts +169 -59
  58. package/dist/SWMLService.js +456 -129
  59. package/dist/SWMLService.js.map +1 -1
  60. package/dist/SchemaUtils.d.ts +115 -2
  61. package/dist/SchemaUtils.js +444 -12
  62. package/dist/SchemaUtils.js.map +1 -1
  63. package/dist/SecurityUtils.d.ts +49 -9
  64. package/dist/SecurityUtils.js +153 -51
  65. package/dist/SecurityUtils.js.map +1 -1
  66. package/dist/SemanticGate.d.ts +183 -0
  67. package/dist/SemanticGate.js +533 -0
  68. package/dist/SemanticGate.js.map +1 -0
  69. package/dist/ServerlessAdapter.d.ts +156 -7
  70. package/dist/ServerlessAdapter.js +399 -42
  71. package/dist/ServerlessAdapter.js.map +1 -1
  72. package/dist/SessionManager.d.ts +11 -2
  73. package/dist/SessionManager.js +50 -18
  74. package/dist/SessionManager.js.map +1 -1
  75. package/dist/SslConfig.d.ts +2 -1
  76. package/dist/SslConfig.js +4 -1
  77. package/dist/SslConfig.js.map +1 -1
  78. package/dist/SwaigActions.generated.d.ts +23 -0
  79. package/dist/SwaigActions.generated.js +8 -0
  80. package/dist/SwaigActions.generated.js.map +1 -0
  81. package/dist/SwaigContracts.d.ts +15 -0
  82. package/dist/SwaigContracts.generated.d.ts +264 -0
  83. package/dist/SwaigContracts.generated.js +12 -0
  84. package/dist/SwaigContracts.generated.js.map +1 -0
  85. package/dist/SwaigContracts.js +2 -0
  86. package/dist/SwaigContracts.js.map +1 -0
  87. package/dist/SwaigFunction.d.ts +139 -7
  88. package/dist/SwaigFunction.js +170 -22
  89. package/dist/SwaigFunction.js.map +1 -1
  90. package/dist/SwmlBuilder.d.ts +68 -19
  91. package/dist/SwmlBuilder.js +74 -38
  92. package/dist/SwmlBuilder.js.map +1 -1
  93. package/dist/SwmlVerbMethods.generated.d.ts +41 -4
  94. package/dist/SwmlVerbMethods.generated.js +1 -1
  95. package/dist/TypeInference.d.ts +39 -3
  96. package/dist/TypeInference.js +256 -16
  97. package/dist/TypeInference.js.map +1 -1
  98. package/dist/WebService.d.ts +79 -11
  99. package/dist/WebService.js +320 -109
  100. package/dist/WebService.js.map +1 -1
  101. package/dist/WebhookMiddleware.d.ts +119 -0
  102. package/dist/WebhookMiddleware.js +271 -0
  103. package/dist/WebhookMiddleware.js.map +1 -0
  104. package/dist/WebhookValidator.d.ts +92 -0
  105. package/dist/WebhookValidator.js +409 -0
  106. package/dist/WebhookValidator.js.map +1 -0
  107. package/dist/agents/BedrockAgent.d.ts +162 -0
  108. package/dist/agents/BedrockAgent.js +323 -0
  109. package/dist/agents/BedrockAgent.js.map +1 -0
  110. package/dist/ai-chat/AIChatClient.d.ts +316 -0
  111. package/dist/ai-chat/AIChatClient.js +535 -0
  112. package/dist/ai-chat/AIChatClient.js.map +1 -0
  113. package/dist/ai-chat/ChatGateway.d.ts +408 -0
  114. package/dist/ai-chat/ChatGateway.js +747 -0
  115. package/dist/ai-chat/ChatGateway.js.map +1 -0
  116. package/dist/ai-chat/HandoffRouter.d.ts +282 -0
  117. package/dist/ai-chat/HandoffRouter.js +518 -0
  118. package/dist/ai-chat/HandoffRouter.js.map +1 -0
  119. package/dist/ai-chat/index.d.ts +12 -0
  120. package/dist/ai-chat/index.js +10 -0
  121. package/dist/ai-chat/index.js.map +1 -0
  122. package/dist/capabilities.d.ts +64 -0
  123. package/dist/capabilities.js +95 -0
  124. package/dist/capabilities.js.map +1 -0
  125. package/dist/cli/agent-loader.d.ts +32 -6
  126. package/dist/cli/agent-loader.js +92 -33
  127. package/dist/cli/agent-loader.js.map +1 -1
  128. package/dist/cli/datamap-exec.d.ts +175 -0
  129. package/dist/cli/datamap-exec.js +1284 -0
  130. package/dist/cli/datamap-exec.js.map +1 -0
  131. package/dist/cli/function-args.d.ts +40 -0
  132. package/dist/cli/function-args.js +146 -0
  133. package/dist/cli/function-args.js.map +1 -0
  134. package/dist/cli/simulation.d.ts +99 -0
  135. package/dist/cli/simulation.js +490 -0
  136. package/dist/cli/simulation.js.map +1 -0
  137. package/dist/cli/swaig-test.d.ts +12 -25
  138. package/dist/cli/swaig-test.js +935 -371
  139. package/dist/cli/swaig-test.js.map +1 -1
  140. package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
  141. package/dist/cli/tsdocs/agentsNote.js +92 -0
  142. package/dist/cli/tsdocs/agentsNote.js.map +1 -0
  143. package/dist/cli/tsdocs/api-index.json +1 -0
  144. package/dist/cli/tsdocs/api.d.ts +91 -0
  145. package/dist/cli/tsdocs/api.js +372 -0
  146. package/dist/cli/tsdocs/api.js.map +1 -0
  147. package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
  148. package/dist/cli/tsdocs/apiTypes.js +7 -0
  149. package/dist/cli/tsdocs/apiTypes.js.map +1 -0
  150. package/dist/cli/tsdocs/bin.d.ts +6 -0
  151. package/dist/cli/tsdocs/bin.js +23 -0
  152. package/dist/cli/tsdocs/bin.js.map +1 -0
  153. package/dist/cli/tsdocs/files.d.ts +108 -0
  154. package/dist/cli/tsdocs/files.js +287 -0
  155. package/dist/cli/tsdocs/files.js.map +1 -0
  156. package/dist/cli/tsdocs/index.d.ts +28 -0
  157. package/dist/cli/tsdocs/index.js +307 -0
  158. package/dist/cli/tsdocs/index.js.map +1 -0
  159. package/dist/cli/tsdocs/live.d.ts +41 -0
  160. package/dist/cli/tsdocs/live.js +202 -0
  161. package/dist/cli/tsdocs/live.js.map +1 -0
  162. package/dist/cli/tsdocs/locate.d.ts +51 -0
  163. package/dist/cli/tsdocs/locate.js +75 -0
  164. package/dist/cli/tsdocs/locate.js.map +1 -0
  165. package/dist/cli/tsdocs/render.d.ts +75 -0
  166. package/dist/cli/tsdocs/render.js +323 -0
  167. package/dist/cli/tsdocs/render.js.map +1 -0
  168. package/dist/cli/tsdocs/topics.d.ts +43 -0
  169. package/dist/cli/tsdocs/topics.js +920 -0
  170. package/dist/cli/tsdocs/topics.js.map +1 -0
  171. package/dist/index.d.ts +49 -68
  172. package/dist/index.js +45 -73
  173. package/dist/index.js.map +1 -1
  174. package/dist/livewire/index.d.ts +229 -155
  175. package/dist/livewire/index.js +298 -195
  176. package/dist/livewire/index.js.map +1 -1
  177. package/dist/llms.txt +65 -0
  178. package/dist/prefabs/CallSessionStore.d.ts +52 -0
  179. package/dist/prefabs/CallSessionStore.js +72 -0
  180. package/dist/prefabs/CallSessionStore.js.map +1 -0
  181. package/dist/prefabs/ConciergeAgent.d.ts +13 -1
  182. package/dist/prefabs/ConciergeAgent.js +36 -31
  183. package/dist/prefabs/ConciergeAgent.js.map +1 -1
  184. package/dist/prefabs/FAQBotAgent.d.ts +9 -1
  185. package/dist/prefabs/FAQBotAgent.js +113 -47
  186. package/dist/prefabs/FAQBotAgent.js.map +1 -1
  187. package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
  188. package/dist/prefabs/InfoGathererAgent.js +67 -58
  189. package/dist/prefabs/InfoGathererAgent.js.map +1 -1
  190. package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
  191. package/dist/prefabs/ReceptionistAgent.js +39 -31
  192. package/dist/prefabs/ReceptionistAgent.js.map +1 -1
  193. package/dist/prefabs/SurveyAgent.d.ts +22 -4
  194. package/dist/prefabs/SurveyAgent.js +84 -68
  195. package/dist/prefabs/SurveyAgent.js.map +1 -1
  196. package/dist/relay/Action.d.ts +44 -21
  197. package/dist/relay/Action.js +75 -17
  198. package/dist/relay/Action.js.map +1 -1
  199. package/dist/relay/Call.d.ts +312 -47
  200. package/dist/relay/Call.js +369 -18
  201. package/dist/relay/Call.js.map +1 -1
  202. package/dist/relay/Deferred.js.map +1 -1
  203. package/dist/relay/Message.d.ts +26 -5
  204. package/dist/relay/Message.js +36 -6
  205. package/dist/relay/Message.js.map +1 -1
  206. package/dist/relay/RelayClient.d.ts +44 -17
  207. package/dist/relay/RelayClient.js +175 -65
  208. package/dist/relay/RelayClient.js.map +1 -1
  209. package/dist/relay/RelayError.d.ts +14 -0
  210. package/dist/relay/RelayError.js +15 -0
  211. package/dist/relay/RelayError.js.map +1 -1
  212. package/dist/relay/RelayEvent.d.ts +96 -65
  213. package/dist/relay/RelayEvent.js +85 -56
  214. package/dist/relay/RelayEvent.js.map +1 -1
  215. package/dist/relay/closedSets.d.ts +111 -0
  216. package/dist/relay/closedSets.js +83 -0
  217. package/dist/relay/closedSets.js.map +1 -0
  218. package/dist/relay/index.d.ts +3 -1
  219. package/dist/relay/index.js +1 -0
  220. package/dist/relay/index.js.map +1 -1
  221. package/dist/relay/normalize.js.map +1 -1
  222. package/dist/relay/protocol.types.generated.d.ts +1195 -0
  223. package/dist/relay/protocol.types.generated.js +8 -0
  224. package/dist/relay/protocol.types.generated.js.map +1 -0
  225. package/dist/relay/types.d.ts +73 -42
  226. package/dist/rest/HttpClient.d.ts +36 -8
  227. package/dist/rest/HttpClient.js +233 -40
  228. package/dist/rest/HttpClient.js.map +1 -1
  229. package/dist/rest/RequestOptions.d.ts +110 -0
  230. package/dist/rest/RequestOptions.js +113 -0
  231. package/dist/rest/RequestOptions.js.map +1 -0
  232. package/dist/rest/RestError.d.ts +52 -6
  233. package/dist/rest/RestError.js +89 -5
  234. package/dist/rest/RestError.js.map +1 -1
  235. package/dist/rest/base/CrudResource.d.ts +16 -26
  236. package/dist/rest/base/CrudResource.js +19 -33
  237. package/dist/rest/base/CrudResource.js.map +1 -1
  238. package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
  239. package/dist/rest/base/CrudWithAddresses.js +2 -2
  240. package/dist/rest/base/CrudWithAddresses.js.map +1 -1
  241. package/dist/rest/base/FabricResource.d.ts +15 -0
  242. package/dist/rest/base/FabricResource.js +16 -0
  243. package/dist/rest/base/FabricResource.js.map +1 -0
  244. package/dist/rest/base/ReadResource.d.ts +62 -0
  245. package/dist/rest/base/ReadResource.js +69 -0
  246. package/dist/rest/base/ReadResource.js.map +1 -0
  247. package/dist/rest/callHandler.d.ts +5 -2
  248. package/dist/rest/callHandler.js +4 -1
  249. package/dist/rest/callHandler.js.map +1 -1
  250. package/dist/rest/index.d.ts +18 -77
  251. package/dist/rest/index.js +47 -120
  252. package/dist/rest/index.js.map +1 -1
  253. package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
  254. package/dist/rest/namespaces/_client_tree_generated.js +171 -0
  255. package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
  256. package/dist/rest/namespaces/addresses.d.ts +3 -42
  257. package/dist/rest/namespaces/addresses.js +3 -50
  258. package/dist/rest/namespaces/addresses.js.map +1 -1
  259. package/dist/rest/namespaces/calling.d.ts +6 -378
  260. package/dist/rest/namespaces/calling.js +6 -473
  261. package/dist/rest/namespaces/calling.js.map +1 -1
  262. package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
  263. package/dist/rest/namespaces/calling.resources.generated.js +477 -0
  264. package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
  265. package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
  266. package/dist/rest/namespaces/calling.types.generated.js +8 -0
  267. package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
  268. package/dist/rest/namespaces/chat.d.ts +4 -18
  269. package/dist/rest/namespaces/chat.js +4 -21
  270. package/dist/rest/namespaces/chat.js.map +1 -1
  271. package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
  272. package/dist/rest/namespaces/chat.resources.generated.js +29 -0
  273. package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
  274. package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
  275. package/dist/rest/namespaces/chat.types.generated.js +8 -0
  276. package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
  277. package/dist/rest/namespaces/datasphere.d.ts +6 -62
  278. package/dist/rest/namespaces/datasphere.js +6 -72
  279. package/dist/rest/namespaces/datasphere.js.map +1 -1
  280. package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
  281. package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
  282. package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
  283. package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
  284. package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
  285. package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
  286. package/dist/rest/namespaces/fabric.d.ts +11 -327
  287. package/dist/rest/namespaces/fabric.js +14 -439
  288. package/dist/rest/namespaces/fabric.js.map +1 -1
  289. package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
  290. package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
  291. package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
  292. package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
  293. package/dist/rest/namespaces/fabric.types.generated.js +8 -0
  294. package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
  295. package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
  296. package/dist/rest/namespaces/fax.resources.generated.js +14 -0
  297. package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
  298. package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
  299. package/dist/rest/namespaces/fax.types.generated.js +8 -0
  300. package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
  301. package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
  302. package/dist/rest/namespaces/imported-numbers.js +3 -21
  303. package/dist/rest/namespaces/imported-numbers.js.map +1 -1
  304. package/dist/rest/namespaces/logs.d.ts +10 -101
  305. package/dist/rest/namespaces/logs.js +10 -128
  306. package/dist/rest/namespaces/logs.js.map +1 -1
  307. package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
  308. package/dist/rest/namespaces/logs.resources.generated.js +17 -0
  309. package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
  310. package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
  311. package/dist/rest/namespaces/logs.types.generated.js +8 -0
  312. package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
  313. package/dist/rest/namespaces/lookup.d.ts +3 -25
  314. package/dist/rest/namespaces/lookup.js +3 -27
  315. package/dist/rest/namespaces/lookup.js.map +1 -1
  316. package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
  317. package/dist/rest/namespaces/message.resources.generated.js +14 -0
  318. package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
  319. package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
  320. package/dist/rest/namespaces/message.types.generated.js +8 -0
  321. package/dist/rest/namespaces/message.types.generated.js.map +1 -0
  322. package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
  323. package/dist/rest/namespaces/messages.resources.generated.js +44 -0
  324. package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
  325. package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
  326. package/dist/rest/namespaces/messages.types.generated.js +8 -0
  327. package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
  328. package/dist/rest/namespaces/mfa.d.ts +3 -42
  329. package/dist/rest/namespaces/mfa.js +3 -49
  330. package/dist/rest/namespaces/mfa.js.map +1 -1
  331. package/dist/rest/namespaces/number-groups.d.ts +3 -45
  332. package/dist/rest/namespaces/number-groups.js +3 -53
  333. package/dist/rest/namespaces/number-groups.js.map +1 -1
  334. package/dist/rest/namespaces/phone-numbers.d.ts +8 -196
  335. package/dist/rest/namespaces/phone-numbers.js +8 -230
  336. package/dist/rest/namespaces/phone-numbers.js.map +1 -1
  337. package/dist/rest/namespaces/project.d.ts +6 -42
  338. package/dist/rest/namespaces/project.js +6 -51
  339. package/dist/rest/namespaces/project.js.map +1 -1
  340. package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
  341. package/dist/rest/namespaces/project.resources.generated.js +44 -0
  342. package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
  343. package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
  344. package/dist/rest/namespaces/project.types.generated.js +8 -0
  345. package/dist/rest/namespaces/project.types.generated.js.map +1 -0
  346. package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
  347. package/dist/rest/namespaces/projects.resources.generated.js +25 -0
  348. package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
  349. package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
  350. package/dist/rest/namespaces/projects.types.generated.js +8 -0
  351. package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
  352. package/dist/rest/namespaces/pubsub.d.ts +4 -18
  353. package/dist/rest/namespaces/pubsub.js +4 -21
  354. package/dist/rest/namespaces/pubsub.js.map +1 -1
  355. package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
  356. package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
  357. package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
  358. package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
  359. package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
  360. package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
  361. package/dist/rest/namespaces/queues.d.ts +3 -38
  362. package/dist/rest/namespaces/queues.js +3 -44
  363. package/dist/rest/namespaces/queues.js.map +1 -1
  364. package/dist/rest/namespaces/recordings.d.ts +3 -34
  365. package/dist/rest/namespaces/recordings.js +3 -40
  366. package/dist/rest/namespaces/recordings.js.map +1 -1
  367. package/dist/rest/namespaces/registry.d.ts +6 -137
  368. package/dist/rest/namespaces/registry.js +6 -173
  369. package/dist/rest/namespaces/registry.js.map +1 -1
  370. package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
  371. package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
  372. package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
  373. package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
  374. package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
  375. package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
  376. package/dist/rest/namespaces/short-codes.d.ts +3 -35
  377. package/dist/rest/namespaces/short-codes.js +3 -41
  378. package/dist/rest/namespaces/short-codes.js.map +1 -1
  379. package/dist/rest/namespaces/sip-profile.d.ts +3 -24
  380. package/dist/rest/namespaces/sip-profile.js +3 -29
  381. package/dist/rest/namespaces/sip-profile.js.map +1 -1
  382. package/dist/rest/namespaces/verified-callers.d.ts +3 -29
  383. package/dist/rest/namespaces/verified-callers.js +3 -34
  384. package/dist/rest/namespaces/verified-callers.js.map +1 -1
  385. package/dist/rest/namespaces/video.d.ts +10 -227
  386. package/dist/rest/namespaces/video.js +10 -288
  387. package/dist/rest/namespaces/video.js.map +1 -1
  388. package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
  389. package/dist/rest/namespaces/video.resources.generated.js +171 -0
  390. package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
  391. package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
  392. package/dist/rest/namespaces/video.types.generated.js +8 -0
  393. package/dist/rest/namespaces/video.types.generated.js.map +1 -0
  394. package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
  395. package/dist/rest/namespaces/voice.resources.generated.js +17 -0
  396. package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
  397. package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
  398. package/dist/rest/namespaces/voice.types.generated.js +8 -0
  399. package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
  400. package/dist/rest/pagination.d.ts +5 -1
  401. package/dist/rest/pagination.js +40 -20
  402. package/dist/rest/pagination.js.map +1 -1
  403. package/dist/rest/types.d.ts +21 -3
  404. package/dist/schema.json +299 -98
  405. package/dist/skills/SkillBase.d.ts +111 -21
  406. package/dist/skills/SkillBase.js +100 -17
  407. package/dist/skills/SkillBase.js.map +1 -1
  408. package/dist/skills/SkillManager.d.ts +66 -13
  409. package/dist/skills/SkillManager.js +101 -20
  410. package/dist/skills/SkillManager.js.map +1 -1
  411. package/dist/skills/SkillName.d.ts +44 -0
  412. package/dist/skills/SkillName.js +2 -0
  413. package/dist/skills/SkillName.js.map +1 -0
  414. package/dist/skills/SkillRegistry.d.ts +22 -11
  415. package/dist/skills/SkillRegistry.js +47 -17
  416. package/dist/skills/SkillRegistry.js.map +1 -1
  417. package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
  418. package/dist/skills/builtin/api_ninjas_trivia.js +18 -6
  419. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
  420. package/dist/skills/builtin/ask_claude.d.ts +14 -4
  421. package/dist/skills/builtin/ask_claude.js +36 -14
  422. package/dist/skills/builtin/ask_claude.js.map +1 -1
  423. package/dist/skills/builtin/claude_skills.d.ts +3 -1
  424. package/dist/skills/builtin/claude_skills.js +19 -15
  425. package/dist/skills/builtin/claude_skills.js.map +1 -1
  426. package/dist/skills/builtin/custom_skills.d.ts +10 -3
  427. package/dist/skills/builtin/custom_skills.js +26 -9
  428. package/dist/skills/builtin/custom_skills.js.map +1 -1
  429. package/dist/skills/builtin/datasphere.d.ts +5 -3
  430. package/dist/skills/builtin/datasphere.js +21 -22
  431. package/dist/skills/builtin/datasphere.js.map +1 -1
  432. package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
  433. package/dist/skills/builtin/datasphere_serverless.js +17 -6
  434. package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
  435. package/dist/skills/builtin/datetime.d.ts +3 -1
  436. package/dist/skills/builtin/datetime.js +11 -7
  437. package/dist/skills/builtin/datetime.js.map +1 -1
  438. package/dist/skills/builtin/google_maps.d.ts +29 -14
  439. package/dist/skills/builtin/google_maps.js +89 -269
  440. package/dist/skills/builtin/google_maps.js.map +1 -1
  441. package/dist/skills/builtin/index.d.ts +8 -6
  442. package/dist/skills/builtin/index.js +8 -6
  443. package/dist/skills/builtin/index.js.map +1 -1
  444. package/dist/skills/builtin/info_gatherer.d.ts +4 -2
  445. package/dist/skills/builtin/info_gatherer.js +20 -12
  446. package/dist/skills/builtin/info_gatherer.js.map +1 -1
  447. package/dist/skills/builtin/joke.d.ts +16 -6
  448. package/dist/skills/builtin/joke.js +54 -37
  449. package/dist/skills/builtin/joke.js.map +1 -1
  450. package/dist/skills/builtin/math.d.ts +3 -1
  451. package/dist/skills/builtin/math.js +14 -9
  452. package/dist/skills/builtin/math.js.map +1 -1
  453. package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
  454. package/dist/skills/builtin/mcp_gateway.js +77 -46
  455. package/dist/skills/builtin/mcp_gateway.js.map +1 -1
  456. package/dist/skills/builtin/native_vector_search.d.ts +19 -5
  457. package/dist/skills/builtin/native_vector_search.js +179 -61
  458. package/dist/skills/builtin/native_vector_search.js.map +1 -1
  459. package/dist/skills/builtin/play_background_file.d.ts +21 -15
  460. package/dist/skills/builtin/play_background_file.js +43 -122
  461. package/dist/skills/builtin/play_background_file.js.map +1 -1
  462. package/dist/skills/builtin/spider.d.ts +42 -4
  463. package/dist/skills/builtin/spider.js +277 -104
  464. package/dist/skills/builtin/spider.js.map +1 -1
  465. package/dist/skills/builtin/swml_transfer.d.ts +14 -3
  466. package/dist/skills/builtin/swml_transfer.js +45 -24
  467. package/dist/skills/builtin/swml_transfer.js.map +1 -1
  468. package/dist/skills/builtin/weather_api.d.ts +24 -13
  469. package/dist/skills/builtin/weather_api.js +38 -30
  470. package/dist/skills/builtin/weather_api.js.map +1 -1
  471. package/dist/skills/builtin/web_search.d.ts +48 -10
  472. package/dist/skills/builtin/web_search.js +294 -100
  473. package/dist/skills/builtin/web_search.js.map +1 -1
  474. package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
  475. package/dist/skills/builtin/wikipedia_search.js +14 -13
  476. package/dist/skills/builtin/wikipedia_search.js.map +1 -1
  477. package/dist/skills/index.d.ts +3 -2
  478. package/dist/skills/index.js +1 -1
  479. package/dist/skills/index.js.map +1 -1
  480. package/dist/swml_verbs_generated.d.ts +2824 -0
  481. package/dist/swml_verbs_generated.js +12 -0
  482. package/dist/swml_verbs_generated.js.map +1 -0
  483. package/dist/types.d.ts +59 -6
  484. package/dist/web.d.ts +27 -0
  485. package/dist/web.js +20 -0
  486. package/dist/web.js.map +1 -0
  487. package/docs/agent-guide.md +1034 -0
  488. package/docs/ai_chat.md +560 -0
  489. package/docs/api-reference.md +3641 -0
  490. package/docs/architecture.md +846 -0
  491. package/docs/bedrock_agent.md +411 -0
  492. package/docs/cli-guide.md +403 -0
  493. package/docs/cloud_functions_guide.md +399 -0
  494. package/docs/configuration.md +548 -0
  495. package/docs/contexts-guide.md +884 -0
  496. package/docs/datamap-guide.md +1207 -0
  497. package/docs/developer_pain_points.md +548 -0
  498. package/docs/llm_parameters.md +298 -0
  499. package/docs/mcp_gateway_reference.md +354 -0
  500. package/docs/mcp_integration.md +162 -0
  501. package/docs/pgi_agent_guide.md +1820 -0
  502. package/docs/prefabs-guide.md +815 -0
  503. package/docs/programmatically_governed_inference.md +301 -0
  504. package/docs/sdk_features.md +501 -0
  505. package/docs/security.md +559 -0
  506. package/docs/serverless-guide.md +520 -0
  507. package/docs/skills-guide.md +1223 -0
  508. package/docs/skills-system.md +405 -0
  509. package/docs/skills_parameter_schema.md +417 -0
  510. package/docs/swaig-reference.md +1986 -0
  511. package/docs/swml_service_guide.md +573 -0
  512. package/docs/third_party_skills.md +410 -0
  513. package/docs/web_service.md +666 -0
  514. package/examples/README.md +202 -0
  515. package/examples/advanced-datamap.ts +108 -0
  516. package/examples/advanced-dynamic-config.ts +70 -0
  517. package/examples/auto-vivified.ts +95 -0
  518. package/examples/call-flow.ts +65 -0
  519. package/examples/comprehensive-dynamic.ts +125 -0
  520. package/examples/contexts-steps.ts +65 -0
  521. package/examples/custom-path.ts +45 -0
  522. package/examples/datamap-tools.ts +51 -0
  523. package/examples/datasphere-multi-instance.ts +66 -0
  524. package/examples/datasphere-serverless-env.ts +87 -0
  525. package/examples/datasphere-webhook-env.ts +65 -0
  526. package/examples/datasphere.ts +56 -0
  527. package/examples/declarative.ts +100 -0
  528. package/examples/dynamic-config.ts +54 -0
  529. package/examples/dynamic-info-gatherer.ts +69 -0
  530. package/examples/dynamic-swml-service.ts +67 -0
  531. package/examples/gather-info.ts +95 -0
  532. package/examples/gather-per-question-functions-demo.ts +139 -0
  533. package/examples/joke-agent.ts +34 -0
  534. package/examples/kubernetes-agent.ts +45 -0
  535. package/examples/llm-params.ts +75 -0
  536. package/examples/mcp-agent.ts +89 -0
  537. package/examples/mcp-gateway.ts +81 -0
  538. package/examples/multi-agent.ts +80 -0
  539. package/examples/multi-endpoint.ts +79 -0
  540. package/examples/pgi/case-domain.ts +114 -0
  541. package/examples/pgi/serve.ts +16 -0
  542. package/examples/pgi/support-agent.ts +265 -0
  543. package/examples/pom-prompt.ts +70 -0
  544. package/examples/prefab-concierge.ts +42 -0
  545. package/examples/prefab-faq.ts +58 -0
  546. package/examples/prefab-info-gatherer.ts +33 -0
  547. package/examples/prefab-receptionist.ts +36 -0
  548. package/examples/prefab-survey.ts +69 -0
  549. package/examples/quickstart-agent.ts +29 -0
  550. package/examples/quickstart-relay.ts +25 -0
  551. package/examples/quickstart-rest.ts +25 -0
  552. package/examples/record-call.ts +65 -0
  553. package/examples/relay-demo.ts +33 -0
  554. package/examples/room-and-sip.ts +93 -0
  555. package/examples/serverless-lambda.ts +43 -0
  556. package/examples/session-state.ts +83 -0
  557. package/examples/simple-agent.ts +36 -0
  558. package/examples/simple-static.ts +29 -0
  559. package/examples/skills-demo.ts +41 -0
  560. package/examples/step-function-inheritance-demo.ts +124 -0
  561. package/examples/swaig-features.ts +193 -0
  562. package/examples/swml-service-routing.ts +66 -0
  563. package/examples/swml-service.ts +38 -0
  564. package/examples/swmlservice_ai_sidecar.ts +104 -0
  565. package/examples/swmlservice_swaig_standalone.ts +79 -0
  566. package/examples/tap.ts +67 -0
  567. package/examples/typed-tools.ts +68 -0
  568. package/examples/verb-methods.ts +45 -0
  569. package/examples/web-search-multi-instance.ts +75 -0
  570. package/examples/web-search.ts +38 -0
  571. package/examples/wikipedia.ts +36 -0
  572. package/livewire/README.md +164 -0
  573. package/livewire/docs/migration-guide.md +251 -0
  574. package/livewire/examples/livewire-basic-agent.ts +74 -0
  575. package/livewire/examples/livewire-handoff.ts +196 -0
  576. package/livewire/examples/livewire-multi-tool.ts +121 -0
  577. package/package.json +85 -13
  578. package/relay/README.md +101 -0
  579. package/relay/docs/call-methods.md +622 -0
  580. package/relay/docs/client-reference.md +281 -0
  581. package/relay/docs/events.md +193 -0
  582. package/relay/docs/getting-started.md +221 -0
  583. package/relay/docs/guide.md +386 -0
  584. package/relay/docs/messaging.md +246 -0
  585. package/relay/examples/relay-inbound.ts +66 -0
  586. package/relay/examples/relay-messaging.ts +74 -0
  587. package/relay/examples/relay-outbound.ts +76 -0
  588. package/rest/README.md +141 -0
  589. package/rest/docs/calling.md +313 -0
  590. package/rest/docs/client-reference.md +149 -0
  591. package/rest/docs/fabric.md +192 -0
  592. package/rest/docs/getting-started.md +138 -0
  593. package/rest/docs/guide.md +421 -0
  594. package/rest/docs/namespaces.md +367 -0
  595. package/rest/docs/phone-binding.md +116 -0
  596. package/rest/examples/rest-10dlc-registration.ts +177 -0
  597. package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
  598. package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
  599. package/rest/examples/rest-calling-play-and-record.ts +98 -0
  600. package/rest/examples/rest-client.ts +59 -0
  601. package/rest/examples/rest-datasphere-search.ts +81 -0
  602. package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
  603. package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
  604. package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
  605. package/rest/examples/rest-manage-resources.ts +64 -0
  606. package/rest/examples/rest-phone-number-management.ts +200 -0
  607. package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
  608. package/rest/examples/rest-video-rooms.ts +186 -0
  609. package/tutorial/fred/fred.ts +218 -0
  610. package/tutorial/fred/tutorial/01-introduction.md +141 -0
  611. package/tutorial/fred/tutorial/02-setup.md +304 -0
  612. package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
  613. package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
  614. package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
  615. package/tutorial/fred/tutorial/06-running-testing.md +642 -0
  616. package/tutorial/fred/tutorial/README.md +56 -0
  617. package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
  618. package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
  619. package/tutorial/full-guardrails-agent/handlers.ts +436 -0
  620. package/tutorial/full-guardrails-agent/penny.ts +305 -0
  621. package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
  622. package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
  623. package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
  624. package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
  625. package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
  626. package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
  627. package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
  628. package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
  629. package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
  630. package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
  631. package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
  632. package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
  633. package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
  634. package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
  635. package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
  636. package/tutorial/full-guardrails-agent/workflow.ts +219 -0
  637. package/tutorial/multi_agents/README.md +175 -0
  638. package/tutorial/multi_agents/advanced_agent.ts +395 -0
  639. package/tutorial/multi_agents/extending_agents.ts +641 -0
  640. package/tutorial/multi_agents/knowledge.ts +59 -0
  641. package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
  642. package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
  643. package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
  644. package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
  645. package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
  646. package/tutorial/multi_agents/pc_builder.ts +529 -0
  647. package/tutorial/multi_agents/sales_agent.ts +88 -0
  648. package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
  649. package/tutorial/multi_agents/sales_knowledge.md +139 -0
  650. package/tutorial/multi_agents/support_knowledge.md +256 -0
  651. package/dist/cli/mock-data.d.ts +0 -37
  652. package/dist/cli/mock-data.js +0 -80
  653. package/dist/cli/mock-data.js.map +0 -1
  654. package/dist/generateVerbTypes.d.ts +0 -11
  655. package/dist/generateVerbTypes.js +0 -265
  656. package/dist/generateVerbTypes.js.map +0 -1
  657. package/dist/rest/namespaces/compat.d.ts +0 -585
  658. package/dist/rest/namespaces/compat.js +0 -735
  659. package/dist/rest/namespaces/compat.js.map +0 -1
@@ -0,0 +1,1284 @@
1
+ /**
2
+ * DataMap execution for swaig-test: runs a DataMap function locally the way
3
+ * the platform runs it (mod_openai's actions.c and swaig.c), so
4
+ * `swaig-test --exec` can test one without a call.
5
+ *
6
+ * The pipeline, as the platform processes a data_map:
7
+ *
8
+ * 1. The top-level `expressions`, against the call data. The first one that
9
+ * produces an output ends the function.
10
+ * 2. The first webhook it requests. A webhook in a list is skipped, without a
11
+ * request, when none of its `require_args` is among the arguments, when it
12
+ * has neither `output` nor `expressions`, or when it has no `url`. Once one
13
+ * is requested, no later webhook runs. It fails when the response has
14
+ * `parse_error` or `protocol_error` (a body that is empty or isn't JSON, a
15
+ * request that doesn't complete) or one of its `error_keys`, whatever the
16
+ * key's value. A status outside 200-299 doesn't fail it by itself; the
17
+ * status is then in the response as `http_code`. If it succeeds, its
18
+ * `foreach`, then its `expressions`, then its `output` build the result
19
+ * from the response. A matched webhook expression's result is expanded a
20
+ * second time, against the same data.
21
+ * 3. The data_map's own `output`, when nothing above produced a result.
22
+ * 4. Otherwise the platform's generic error,
23
+ * `{ response: "There was an error processing this request." }`.
24
+ *
25
+ * `expressions` can be one expression object instead of a list. `webhooks`
26
+ * can be one webhook object, which the platform runs without checking its
27
+ * `require_args` or its errors, so its `foreach`, `expressions` and `output`
28
+ * read an error response (`${parse_error}`, `${raw_response}`,
29
+ * `${http_code}`).
30
+ *
31
+ * The request is a POST when the webhook has `params` (its JSON body, with
32
+ * the arguments merged in by `input_args_as_params`) or its method is POST,
33
+ * and a GET otherwise. Header values are sent as written. Credentials in the
34
+ * url become basic authentication. Redirects are followed as the platform's
35
+ * curl follows them, and every request, redirects included, refuses private
36
+ * and internal addresses.
37
+ *
38
+ * Template data, per stage:
39
+ *
40
+ * - The call data: the `callData` option (the platform's call details, such
41
+ * as `global_data` or `caller_id_num`) at the root, `meta_data` (the
42
+ * function's `meta_data` merged key by key over `global_data`, as the
43
+ * platform merges them when it loads the function), the `prompt_vars`
44
+ * merged into the root, `args` (the arguments) and an empty `input`. The
45
+ * top-level expressions, a webhook's `url` and `params`, and the data_map's
46
+ * own `output` read it, so they write an argument as `${args.city}`. The
47
+ * data_map's own `output` also has `prompt_vars`.
48
+ * - A webhook's `foreach`, `expressions` and `output` read its response: a
49
+ * JSON object's fields at the root (`${current.temp_f}`), a JSON array under
50
+ * `array`, with `prompt_vars`, `global_data` and `input` (a copy of the call
51
+ * data) added. The arguments are `${input.args.city}` there.
52
+ *
53
+ * Templates: `${path}` and `%{path}` read a path of dotted names, matched
54
+ * without regard to ASCII case, each with at most one `[n]` index (negative
55
+ * from the end). The helpers `lc:`, `enc:` and `fmt_ph:` come first, in any
56
+ * case, and apply in a fixed order: `fmt_ph`, then `lc`, then `enc`. Any other
57
+ * name before a colon is part of the path. A template nested in the path
58
+ * expands first, one level deep. A value that isn't a string is inserted as
59
+ * cJSON prints it (72.5 as `72.500000`). A path that doesn't resolve expands
60
+ * to an empty string, and the simulator says so on stderr. An output is
61
+ * expanded as JSON text and parsed, as on the platform, so a template that
62
+ * inserts an object into a string breaks it.
63
+ *
64
+ * Where the simulator can't do what the platform does:
65
+ *
66
+ * - Without the optional libphonenumber-js package, `fmt_ph` formats only a
67
+ * North American number, as `(NPA) NXX-XXXX`, and leaves any other value as
68
+ * it is, saying so on stderr. The platform formats any valid number, and
69
+ * writes `INVALID NUMBER` for one that isn't; with libphonenumber-js
70
+ * installed, so does the simulator. Either way, it reads a vanity number's
71
+ * letters as keypad digits, as the platform's libphonenumber does.
72
+ * - `@{...}` functions are left as they are.
73
+ * - An expression's `expr` isn't evaluated: only its `pattern` is tried.
74
+ * - Patterns are JavaScript regular expressions, where the platform uses PCRE.
75
+ * - The platform follows no redirect for a request it signs; the simulator
76
+ * doesn't sign requests.
77
+ *
78
+ * Mirrors signalwire-python's `signalwire.cli.execution.datamap_exec`.
79
+ */
80
+ import { createRequire } from 'node:module';
81
+ import { join } from 'node:path';
82
+ import { pathToFileURL } from 'node:url';
83
+ import { _publicFetch } from '../PublicFetch.js';
84
+ /** The result the platform returns when nothing produced an output. */
85
+ export const PLATFORM_ERROR_RESPONSE = 'There was an error processing this request.';
86
+ /** The platform's whole-request timeout for a webhook, in seconds (CURLOPT_TIMEOUT). */
87
+ const HTTP_REQUEST_TIMEOUT = 120;
88
+ /** The characters FreeSWITCH's `SWITCH_URL_UNSAFE` lists, which `enc:` encodes. */
89
+ const URL_UNSAFE = '\r\n #%&+:;<=>?@[\\]^`{|}"';
90
+ const HEX = '0123456789ABCDEF';
91
+ /** Template paths longer than this (in bytes), or deeper, don't resolve. */
92
+ const MAX_PATH_LENGTH = 1024;
93
+ const MAX_PATH_DEPTH = 128;
94
+ const INT_MAX = 2 ** 31 - 1;
95
+ /** The stages that read a webhook's response rather than the call data. */
96
+ const RESPONSE_STAGES = new Set(['webhook foreach', 'webhook expressions', 'webhook output']);
97
+ /** Marks a value that isn't there: a path that doesn't resolve, JSON that doesn't parse. */
98
+ const MISSING = Symbol('missing');
99
+ function isPlainObject(value) {
100
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
101
+ }
102
+ /** Lowercase ASCII letters only, as C's tolower() does. */
103
+ function asciiLower(text) {
104
+ return text.replace(/[A-Z]/g, (c) => c.toLowerCase());
105
+ }
106
+ /** Set a member as data, so a key such as `__proto__` is an ordinary key. */
107
+ function setItem(obj, key, value) {
108
+ Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true });
109
+ }
110
+ /**
111
+ * A named member of an object, matched without regard to ASCII case, as
112
+ * cJSON_GetObjectItem() finds it: the first match wins, and arrays and
113
+ * scalars have no named members.
114
+ */
115
+ function objectItem(container, name) {
116
+ if (!isPlainObject(container))
117
+ return MISSING;
118
+ const wanted = asciiLower(name);
119
+ for (const key of Object.keys(container)) {
120
+ if (asciiLower(key) === wanted)
121
+ return container[key];
122
+ }
123
+ return MISSING;
124
+ }
125
+ function hasItem(container, name) {
126
+ return objectItem(container, name) !== MISSING;
127
+ }
128
+ /**
129
+ * Add a member as cJSON_AddItemToObject() does: cJSON appends a second member
130
+ * with the same name, and lookups find the first, so an existing member keeps
131
+ * its value.
132
+ */
133
+ function addItem(container, name, value) {
134
+ if (!hasItem(container, name))
135
+ setItem(container, name, value);
136
+ }
137
+ /** Delete the first member matching `name` without regard to ASCII case. */
138
+ function deleteItem(container, name) {
139
+ const wanted = asciiLower(name);
140
+ for (const key of Object.keys(container)) {
141
+ if (asciiLower(key) === wanted) {
142
+ delete container[key];
143
+ return;
144
+ }
145
+ }
146
+ }
147
+ /** Replace a member, as cJSON_Merge() with replace does. */
148
+ function replaceItem(container, name, value) {
149
+ deleteItem(container, name);
150
+ setItem(container, name, value);
151
+ }
152
+ /** A member's value if it is a string, as cJSON_GetObjectCstr() returns it. */
153
+ function stringItem(container, name) {
154
+ const value = objectItem(container, name);
155
+ return typeof value === 'string' ? value : null;
156
+ }
157
+ /** C's atoi(): the leading integer, or 0. */
158
+ function atoi(text) {
159
+ const match = /^[ \t\n\v\f\r]*([+-]?\d+)/.exec(text);
160
+ return match ? Number.parseInt(match[1], 10) : 0;
161
+ }
162
+ /** mod_openai's cJSON_FSTrue(): JSON true, or a string FreeSWITCH's switch_true() accepts. */
163
+ function isTrue(value) {
164
+ if (value === true)
165
+ return true;
166
+ if (typeof value !== 'string')
167
+ return false;
168
+ if (['yes', 'on', 'true', 't', 'enabled', 'active', 'allow'].includes(value.toLowerCase())) {
169
+ return true;
170
+ }
171
+ return /^[+-]?\d+(\.\d+)?$/.test(value.trim()) && atoi(value) !== 0;
172
+ }
173
+ const CJSON_ESCAPES = {
174
+ '"': '\\"',
175
+ '\\': '\\\\',
176
+ '\b': '\\b',
177
+ '\f': '\\f',
178
+ '\n': '\\n',
179
+ '\r': '\\r',
180
+ '\t': '\\t',
181
+ };
182
+ /** A string as cJSON prints it. */
183
+ function cjsonString(text) {
184
+ let out = '"';
185
+ for (const ch of text) {
186
+ const code = ch.charCodeAt(0);
187
+ if (CJSON_ESCAPES[ch])
188
+ out += CJSON_ESCAPES[ch];
189
+ else if (code < 32)
190
+ out += `\\u${code.toString(16).padStart(4, '0')}`;
191
+ else
192
+ out += ch;
193
+ }
194
+ return out + '"';
195
+ }
196
+ /**
197
+ * A value as FreeSWITCH's cJSON_Print() formats it: a whole number without a
198
+ * decimal point, any other number with six decimal places (72.5 is
199
+ * `72.500000`), and an object over several lines, one tab per level.
200
+ */
201
+ function cjsonPrint(value, depth = 0) {
202
+ if (value === null || value === undefined)
203
+ return 'null';
204
+ if (value === true)
205
+ return 'true';
206
+ if (value === false)
207
+ return 'false';
208
+ if (typeof value === 'number') {
209
+ if (!Number.isFinite(value))
210
+ return 'null';
211
+ return Number.isInteger(value) ? BigInt(value).toString() : value.toFixed(6);
212
+ }
213
+ if (typeof value === 'string')
214
+ return cjsonString(value);
215
+ if (Array.isArray(value))
216
+ return `[${value.map((v) => cjsonPrint(v, depth + 1)).join(', ')}]`;
217
+ if (isPlainObject(value)) {
218
+ const inner = depth + 1;
219
+ const members = Object.entries(value).map(([k, v]) => `${'\t'.repeat(inner)}${cjsonString(k)}:\t${cjsonPrint(v, inner)}`);
220
+ if (members.length === 0)
221
+ return `{\n${'\t'.repeat(depth)}}`;
222
+ return `{\n${members.join(',\n')}\n${'\t'.repeat(depth)}}`;
223
+ }
224
+ return cjsonString(String(value));
225
+ }
226
+ /**
227
+ * Parse JSON as cJSON_Parse() does, or return MISSING. cJSON skips a byte
228
+ * order mark and leading whitespace, accepts control characters inside
229
+ * strings, reads the first value and ignores anything after it, and keeps
230
+ * the first of two members with the same name.
231
+ */
232
+ function cjsonParse(text) {
233
+ let i = 0;
234
+ if (text.charCodeAt(0) === 0xfeff)
235
+ i = 1;
236
+ const skip = () => {
237
+ while (i < text.length && text.charCodeAt(i) <= 32)
238
+ i++;
239
+ };
240
+ const fail = () => {
241
+ throw new SyntaxError('invalid JSON');
242
+ };
243
+ const parseString = () => {
244
+ let out = '';
245
+ i++; // the opening quote
246
+ while (i < text.length && text[i] !== '"') {
247
+ const ch = text[i];
248
+ if (ch !== '\\') {
249
+ out += ch;
250
+ i++;
251
+ continue;
252
+ }
253
+ const esc = text[i + 1];
254
+ const simple = {
255
+ b: '\b',
256
+ f: '\f',
257
+ n: '\n',
258
+ r: '\r',
259
+ t: '\t',
260
+ '"': '"',
261
+ '\\': '\\',
262
+ '/': '/',
263
+ };
264
+ if (esc !== undefined && esc in simple) {
265
+ out += simple[esc];
266
+ i += 2;
267
+ }
268
+ else if (esc === 'u' && /^[0-9a-fA-F]{4}$/.test(text.slice(i + 2, i + 6))) {
269
+ out += String.fromCharCode(Number.parseInt(text.slice(i + 2, i + 6), 16));
270
+ i += 6;
271
+ }
272
+ else {
273
+ fail();
274
+ }
275
+ }
276
+ if (i >= text.length)
277
+ fail();
278
+ i++; // the closing quote
279
+ return out;
280
+ };
281
+ const parseValue = (depth) => {
282
+ if (depth > 1000)
283
+ fail();
284
+ skip();
285
+ const ch = text[i];
286
+ if (ch === '"')
287
+ return parseString();
288
+ if (ch === '{') {
289
+ i++;
290
+ const obj = {};
291
+ skip();
292
+ if (text[i] === '}') {
293
+ i++;
294
+ return obj;
295
+ }
296
+ for (;;) {
297
+ skip();
298
+ if (text[i] !== '"')
299
+ fail();
300
+ const key = parseString();
301
+ skip();
302
+ if (text[i] !== ':')
303
+ fail();
304
+ i++;
305
+ const value = parseValue(depth + 1);
306
+ if (!Object.hasOwn(obj, key))
307
+ setItem(obj, key, value);
308
+ skip();
309
+ if (text[i] === ',') {
310
+ i++;
311
+ continue;
312
+ }
313
+ if (text[i] === '}') {
314
+ i++;
315
+ return obj;
316
+ }
317
+ fail();
318
+ }
319
+ }
320
+ if (ch === '[') {
321
+ i++;
322
+ const arr = [];
323
+ skip();
324
+ if (text[i] === ']') {
325
+ i++;
326
+ return arr;
327
+ }
328
+ for (;;) {
329
+ arr.push(parseValue(depth + 1));
330
+ skip();
331
+ if (text[i] === ',') {
332
+ i++;
333
+ continue;
334
+ }
335
+ if (text[i] === ']') {
336
+ i++;
337
+ return arr;
338
+ }
339
+ fail();
340
+ }
341
+ }
342
+ for (const [word, value] of [
343
+ ['null', null],
344
+ ['false', false],
345
+ ['true', true],
346
+ ]) {
347
+ if (text.startsWith(word, i)) {
348
+ i += word.length;
349
+ return value;
350
+ }
351
+ }
352
+ const number = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/.exec(text.slice(i));
353
+ if (!number)
354
+ fail();
355
+ i += number[0].length;
356
+ return Number(number[0]);
357
+ };
358
+ try {
359
+ return parseValue(0);
360
+ }
361
+ catch {
362
+ return MISSING;
363
+ }
364
+ }
365
+ /**
366
+ * URL-encodes a value, for `enc:` and `form_param`, as the platform does with
367
+ * FreeSWITCH's `switch_url_encode`: each byte of the UTF-8 text that is a
368
+ * control character, non-ASCII, or in `SWITCH_URL_UNSAFE` becomes `%XX`, and
369
+ * every other printable ASCII character (`/`, `,`, `$`, `!`, `(` and so on)
370
+ * stays. A `%` that already starts an uppercase `%XX` isn't encoded again.
371
+ */
372
+ function urlEncode(value) {
373
+ const bytes = new TextEncoder().encode(value);
374
+ let out = '';
375
+ for (let i = 0; i < bytes.length; i++) {
376
+ const b = bytes[i];
377
+ const ch = String.fromCharCode(b);
378
+ const escaped = ch === '%' &&
379
+ i + 2 < bytes.length &&
380
+ HEX.includes(String.fromCharCode(bytes[i + 1])) &&
381
+ HEX.includes(String.fromCharCode(bytes[i + 2]));
382
+ if (!escaped && (b < 0x20 || b > 0x7e || URL_UNSAFE.includes(ch))) {
383
+ out += `%${HEX[b >> 4]}${HEX[b & 0x0f]}`;
384
+ }
385
+ else {
386
+ out += ch;
387
+ }
388
+ }
389
+ return out;
390
+ }
391
+ /**
392
+ * libphonenumber-js, when it's installed: a port of the libphonenumber the
393
+ * platform formats `fmt_ph` with. It's optional, so it's found at run time,
394
+ * from the SDK's own location or else from the working directory's project,
395
+ * with its full metadata (`/max`), which validates as libphonenumber does.
396
+ */
397
+ async function loadPhoneNumbers() {
398
+ const specifier = 'libphonenumber-js/max';
399
+ const usable = (mod) => {
400
+ for (const candidate of [mod, mod?.default]) {
401
+ const parse = candidate
402
+ ?.parsePhoneNumberFromString;
403
+ if (typeof parse === 'function')
404
+ return { parsePhoneNumberFromString: parse };
405
+ }
406
+ return null;
407
+ };
408
+ try {
409
+ return usable(await import(specifier));
410
+ }
411
+ catch {
412
+ // Not next to the SDK; try the project in the working directory
413
+ }
414
+ try {
415
+ const require = createRequire(join(process.cwd(), 'noop.js'));
416
+ return usable(await import(pathToFileURL(require.resolve(specifier)).href));
417
+ }
418
+ catch {
419
+ return null;
420
+ }
421
+ }
422
+ let phoneNumbers = await loadPhoneNumbers();
423
+ /**
424
+ * Replace the libphonenumber-js that `fmt_ph` uses, for tests: null simulates
425
+ * a project without it.
426
+ *
427
+ * @param lib - The library, or null for none.
428
+ * @returns The one it replaced.
429
+ * @internal
430
+ */
431
+ export function _setPhoneNumbers(lib) {
432
+ const previous = phoneNumbers;
433
+ phoneNumbers = lib;
434
+ return previous;
435
+ }
436
+ // Google libphonenumber's parsing patterns (phonenumberutil.cc), for the
437
+ // alphabetic numbers libphonenumber-js leaves out.
438
+ const PHONE_PUNCTUATION = '\\-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F \u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C';
439
+ const EXTN_AFTER_LABEL = '[:.\uFF0E]?[ \u00A0\\t,\\-]*';
440
+ const EXTN_PATTERN = [
441
+ ';ext=(\\p{Nd}{1,20})',
442
+ '[ \u00A0\\t,]*(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|(?:\uFF45)?\uFF58\uFF54(?:\uFF4E)?|\u0434\u043E\u0431|anexo)' +
443
+ `${EXTN_AFTER_LABEL}(\\p{Nd}{1,20})#?`,
444
+ `[ \u00A0\\t,]*(?:[x\uFF58#\uFF03~\uFF5E]|int|\uFF49\uFF4E\uFF54)${EXTN_AFTER_LABEL}(\\p{Nd}{1,9})#?`,
445
+ '[\\- ]+(\\p{Nd}{1,6})#',
446
+ `[ \u00A0\\t]*(?:,{2}|;)${EXTN_AFTER_LABEL}(\\p{Nd}{1,15})#?`,
447
+ `[ \u00A0\\t]*(?:,)+${EXTN_AFTER_LABEL}(\\p{Nd}{1,9})#?`,
448
+ ].join('|');
449
+ /** An extension at the end of a number (extn_pattern_). */
450
+ const PHONE_EXTENSION = new RegExp(`(?:${EXTN_PATTERN})$`, 'iu');
451
+ /** A string that could be a phone number (valid_phone_number_pattern_). */
452
+ const VIABLE_PHONE_NUMBER = new RegExp(`^(?:\\p{Nd}{2}|[+\uFF0B]*(?:[${PHONE_PUNCTUATION}*]*\\p{Nd}){3,}` +
453
+ `[${PHONE_PUNCTUATION}*a-z\\p{Nd}]*(?:${EXTN_PATTERN})?)$`, 'iu');
454
+ /** Three or more letters make a vanity number (valid_alpha_phone_pattern_). */
455
+ const VANITY_NUMBER = /(?:.*?[a-z]){3}/iu;
456
+ /** The ITU E.161 keypad, as libphonenumber maps a letter. */
457
+ const KEYPAD = {};
458
+ for (const [digit, letters] of Object.entries({
459
+ 2: 'ABC',
460
+ 3: 'DEF',
461
+ 4: 'GHI',
462
+ 5: 'JKL',
463
+ 6: 'MNO',
464
+ 7: 'PQRS',
465
+ 8: 'TUV',
466
+ 9: 'WXYZ',
467
+ })) {
468
+ for (const letter of letters)
469
+ KEYPAD[letter] = KEYPAD[letter.toLowerCase()] = digit;
470
+ }
471
+ function isViablePhoneNumber(text) {
472
+ return text.length >= 2 && VIABLE_PHONE_NUMBER.test(text);
473
+ }
474
+ /**
475
+ * A value as Google's libphonenumber, which the platform uses, reads it
476
+ * before parsing, for libphonenumber-js to parse. The number starts at its
477
+ * first `+` or digit, trailing punctuation and a second number after `/x`
478
+ * are dropped, and a value that couldn't be a phone number is empty. An
479
+ * extension is split off, as `;ext=`. The rest is normalized: when it has
480
+ * three or more letters, it's a vanity number, whose letters are keypad
481
+ * digits, so `+1 412 535 abcd` is `+14125352223`; otherwise only its digits
482
+ * are kept. libphonenumber-js leaves vanity numbers out, and reads some other
483
+ * letters differently.
484
+ */
485
+ function phoneNumberText(value) {
486
+ if (value.includes(';phone-context='))
487
+ return value;
488
+ const start = value.search(/[+\uFF0B\p{Nd}]/u);
489
+ if (start < 0)
490
+ return '';
491
+ let number = value.slice(start).replace(/[^\p{N}\p{L}#]+$/u, '');
492
+ const second = /(.*)[\\/] *x/u.exec(number);
493
+ if (second)
494
+ number = second[1];
495
+ const isdn = number.indexOf(';isub=');
496
+ if (isdn > 0)
497
+ number = number.slice(0, isdn);
498
+ if (!isViablePhoneNumber(number))
499
+ return '';
500
+ let extension = '';
501
+ const ext = PHONE_EXTENSION.exec(number);
502
+ const extDigits = ext?.slice(1).find(Boolean);
503
+ if (ext && extDigits && isViablePhoneNumber(number.slice(0, ext.index))) {
504
+ extension = `;ext=${extDigits}`;
505
+ number = number.slice(0, ext.index);
506
+ }
507
+ const plus = /^[+\uFF0B]+/u.test(number) ? '+' : '';
508
+ const rest = number.replace(/^[+\uFF0B]+/u, '');
509
+ let digits = '';
510
+ if (VANITY_NUMBER.test(rest)) {
511
+ // Letters and ASCII digits, as keypad digits; anything else is dropped
512
+ for (const ch of rest)
513
+ digits += KEYPAD[ch] ?? (/[0-9]/.test(ch) ? ch : '');
514
+ }
515
+ else {
516
+ // Digits in any script, as ASCII digits; anything else is dropped
517
+ for (const ch of rest)
518
+ digits += asciiDigit(ch);
519
+ }
520
+ return `${plus}${digits}${extension}`;
521
+ }
522
+ /**
523
+ * A decimal digit in any script as an ASCII digit, or an empty string. The
524
+ * digits of a script run from 0 to 9 in consecutive code points.
525
+ */
526
+ function asciiDigit(ch) {
527
+ if (!/\p{Nd}/u.test(ch))
528
+ return '';
529
+ let zero = ch.codePointAt(0);
530
+ while (/\p{Nd}/u.test(String.fromCodePoint(zero - 1)))
531
+ zero--;
532
+ return String((ch.codePointAt(0) - zero) % 10);
533
+ }
534
+ /**
535
+ * The `fmt_ph` helper. The platform formats with libphonenumber in the
536
+ * national format, reading a number without a country code as a US number,
537
+ * and writes `INVALID NUMBER` for one it can't validate. With libphonenumber-js
538
+ * installed, the simulator does the same. Without it, it formats a ten-digit
539
+ * North American number, with or without its leading 1, as `(NPA) NXX-XXXX`,
540
+ * and returns null for anything else. Either way, the value is first read as
541
+ * libphonenumber reads it, the letters of a vanity number as keypad digits.
542
+ */
543
+ function formatPhoneNational(value) {
544
+ const text = phoneNumberText(value);
545
+ if (phoneNumbers) {
546
+ try {
547
+ const number = phoneNumbers.parsePhoneNumberFromString(text, 'US');
548
+ return number?.isValid() ? number.formatNational() : 'INVALID NUMBER';
549
+ }
550
+ catch {
551
+ return 'INVALID NUMBER';
552
+ }
553
+ }
554
+ const [number = '', extension] = text.split(';ext=');
555
+ let digits = number.replace(/\D/g, '');
556
+ if (digits.length === 11 && digits.startsWith('1'))
557
+ digits = digits.slice(1);
558
+ // After a +, only country code 1 is North American
559
+ else if (number.startsWith('+'))
560
+ return null;
561
+ if (digits.length === 10 && /[2-9]/.test(digits[0]) && /[2-9]/.test(digits[3])) {
562
+ const formatted = `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
563
+ return extension ? `${formatted} ext. ${extension}` : formatted;
564
+ }
565
+ return null;
566
+ }
567
+ /** The index of the `}` matching the `{` at `start`, or -1. */
568
+ function findEndBrace(text, start) {
569
+ let depth = 0;
570
+ for (let i = start; i < text.length; i++) {
571
+ if (text[i] === '{')
572
+ depth++;
573
+ else if (text[i] === '}') {
574
+ depth--;
575
+ if (depth === 0)
576
+ return i;
577
+ }
578
+ }
579
+ return -1;
580
+ }
581
+ /**
582
+ * The value at a template path, or MISSING, as the platform's
583
+ * get_json_object() finds it. Dots separate names, matched without regard to
584
+ * ASCII case. One `[n]` may end a name, and a negative `n` counts from the
585
+ * end. A path ending in a dot doesn't resolve, and an empty path is the whole
586
+ * data.
587
+ */
588
+ function lookup(data, path) {
589
+ if (new TextEncoder().encode(path).length > MAX_PATH_LENGTH || path.endsWith('.')) {
590
+ return MISSING;
591
+ }
592
+ let current = data;
593
+ const tokens = path.split('.').filter(Boolean);
594
+ for (const [n, token] of tokens.entries()) {
595
+ if (n + 1 > MAX_PATH_DEPTH)
596
+ return MISSING;
597
+ const open = token.indexOf('[');
598
+ if (open < 0) {
599
+ current = objectItem(current, token);
600
+ if (current === MISSING)
601
+ return MISSING;
602
+ continue;
603
+ }
604
+ const rest = token.slice(open + 1);
605
+ const close = rest.indexOf(']');
606
+ if (close < 0)
607
+ return MISSING;
608
+ const indexText = rest.slice(0, close);
609
+ if (rest.slice(close + 1) || !/^[ \t\n\v\f\r]*[+-]?\d+$/.test(indexText))
610
+ return MISSING;
611
+ let index = Number.parseInt(indexText.trim(), 10);
612
+ if (index > INT_MAX)
613
+ return MISSING;
614
+ current = objectItem(current, token.slice(0, open));
615
+ if (!Array.isArray(current))
616
+ return MISSING;
617
+ if (index < 0)
618
+ index += current.length;
619
+ if (index < 0 || index >= current.length)
620
+ return MISSING;
621
+ current = current[index];
622
+ }
623
+ return current;
624
+ }
625
+ /**
626
+ * A resolved value as a template inserts it: a string as it is, with `"` and
627
+ * `\` backslash-escaped when the template is JSON text, and anything else as
628
+ * cJSON prints it, without escaping.
629
+ */
630
+ function valueText(value, escapeJson) {
631
+ if (typeof value === 'string') {
632
+ return escapeJson ? value.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : value;
633
+ }
634
+ return cjsonPrint(value);
635
+ }
636
+ /** Expand `${...}` and `%{...}` templates as the platform's _expand_jsonvars() does. */
637
+ function expand(template, data, escapeJson = false, nested = true, notes) {
638
+ let out = '';
639
+ let i = 0;
640
+ while (i < template.length) {
641
+ const ch = template[i];
642
+ if ((ch !== '$' && ch !== '%') || template[i + 1] !== '{') {
643
+ out += ch;
644
+ i++;
645
+ continue;
646
+ }
647
+ const end = findEndBrace(template, i + 1);
648
+ if (end < 0) {
649
+ // No closing brace: the text stays as written
650
+ out += ch;
651
+ i++;
652
+ continue;
653
+ }
654
+ if (end === i + 2) {
655
+ // ${} expands to nothing
656
+ i = end + 1;
657
+ continue;
658
+ }
659
+ let body = template.slice(i + 2, end);
660
+ let lowercase = false;
661
+ let encode = false;
662
+ let phone = false;
663
+ for (;;) {
664
+ const head = asciiLower(body.slice(0, 7));
665
+ if (head.startsWith('lc:')) {
666
+ body = body.slice(3);
667
+ lowercase = true;
668
+ }
669
+ else if (head === 'fmt_ph:') {
670
+ body = body.slice(7);
671
+ phone = true;
672
+ }
673
+ else if (head.startsWith('enc:')) {
674
+ body = body.slice(4);
675
+ encode = true;
676
+ }
677
+ else {
678
+ break;
679
+ }
680
+ }
681
+ let path = body;
682
+ if (nested && (path.includes('${') || path.includes('%{'))) {
683
+ path = expand(path, data, escapeJson, false);
684
+ }
685
+ const raw = template.slice(i, end + 1);
686
+ const value = lookup(data, path);
687
+ if (value === MISSING) {
688
+ notes?.push({ raw, path, kind: 'unresolved' });
689
+ }
690
+ else {
691
+ let text = valueText(value, escapeJson);
692
+ // The helpers apply in this order, whatever order they are written in
693
+ if (phone && text) {
694
+ const formatted = formatPhoneNational(text);
695
+ if (formatted === null)
696
+ notes?.push({ raw, path, kind: 'fmt_ph', value: text });
697
+ else
698
+ text = formatted;
699
+ }
700
+ if (lowercase && text)
701
+ text = asciiLower(text);
702
+ if (encode && text)
703
+ text = urlEncode(text);
704
+ out += text;
705
+ }
706
+ i = end + 1;
707
+ }
708
+ return out;
709
+ }
710
+ /**
711
+ * Expand DataMap templates in a string as the platform does: `${path}` and
712
+ * `%{path}` read a value from `data`, names matched without regard to case,
713
+ * with the `lc:`, `enc:` and `fmt_ph:` helpers. A path that doesn't resolve
714
+ * expands to an empty string. A template nested in a path expands first, one
715
+ * level deep, and a value that isn't a string is inserted as cJSON prints it.
716
+ * `@{...}` functions are left as they are.
717
+ *
718
+ * @param template - Text with `${...}` or `%{...}` templates.
719
+ * @param data - The template data.
720
+ * @returns The expanded text.
721
+ */
722
+ export function expandTemplate(template, data) {
723
+ if (!template)
724
+ return '';
725
+ return expand(template, data);
726
+ }
727
+ /**
728
+ * Expand the templates in a value (an output object, say) as the platform
729
+ * does: printed as JSON text, expanded with `"` and `\` in string values
730
+ * escaped, and parsed again. A template that inserts an object or array
731
+ * into a string breaks the JSON.
732
+ *
733
+ * @param value - The value to expand.
734
+ * @param data - The template data.
735
+ * @returns The expanded value, or undefined when the expanded text isn't JSON.
736
+ */
737
+ export function expandValue(value, data) {
738
+ const parsed = cjsonParse(expand(cjsonPrint(value), data, true));
739
+ return parsed === MISSING ? undefined : parsed;
740
+ }
741
+ /**
742
+ * A pattern as the platform matches it, with FreeSWITCH's
743
+ * switch_regex_match(): one that doesn't start with `/` is wrapped as
744
+ * `/pattern/i`, so it is searched for without regard to case; one written
745
+ * `/pattern/flags` takes only its own `i` and `s` flags. A leading PCRE flag
746
+ * group such as `(?i)`, which JavaScript doesn't accept, becomes the same
747
+ * flags. Returns null for a pattern that isn't valid.
748
+ */
749
+ function platformRegExp(pattern) {
750
+ let source = pattern;
751
+ let flags = 'i';
752
+ if (pattern.startsWith('/')) {
753
+ const end = pattern.lastIndexOf('/');
754
+ if (end === 0)
755
+ return null;
756
+ source = pattern.slice(1, end);
757
+ const opts = pattern.slice(end + 1);
758
+ flags = (opts.includes('i') ? 'i' : '') + (opts.includes('s') ? 's' : '');
759
+ }
760
+ const inline = /^\(\?([is]+)\)/.exec(source);
761
+ if (inline) {
762
+ source = source.slice(inline[0].length);
763
+ for (const flag of inline[1])
764
+ if (!flags.includes(flag))
765
+ flags += flag;
766
+ }
767
+ try {
768
+ return new RegExp(source, flags);
769
+ }
770
+ catch {
771
+ return null;
772
+ }
773
+ }
774
+ /** A curl result code standing in for a request that didn't complete. */
775
+ function curlErrorCode(err) {
776
+ const message = err instanceof Error ? err.message : String(err);
777
+ const code = String(err?.cause?.code ?? '');
778
+ if (/timed out|aborted/i.test(message) || err?.name === 'AbortError')
779
+ return 28;
780
+ if (/Too many redirects/.test(message))
781
+ return 47;
782
+ if (/CERT|TLS|SSL|SELF_SIGNED/i.test(code) || /certificate|TLS|SSL/i.test(message))
783
+ return 35;
784
+ if (/Refused|ECONNREFUSED|ECONNRESET|ENOTFOUND|EHOSTUNREACH|ENETUNREACH/.test(message + code)) {
785
+ return 7;
786
+ }
787
+ return 1;
788
+ }
789
+ /** One simulated call of a DataMap function. */
790
+ class Run {
791
+ verbose;
792
+ out;
793
+ notes = [];
794
+ constructor(verbose, out) {
795
+ this.verbose = verbose;
796
+ this.out = out;
797
+ }
798
+ say(line) {
799
+ if (this.verbose)
800
+ this.out(line);
801
+ }
802
+ expand(template, data, stage, escapeJson = false) {
803
+ const found = [];
804
+ const text = expand(template, data, escapeJson, true, found);
805
+ for (const note of found)
806
+ this.notes.push({ note, stage });
807
+ return text;
808
+ }
809
+ /** Expand an output or expression result as JSON text, then parse it, as the platform does. */
810
+ expandJson(value, data, stage) {
811
+ return cjsonParse(this.expand(cjsonPrint(value), data, stage, true));
812
+ }
813
+ /** Say which templates expanded to nothing, with a hint for common mistakes. */
814
+ report() {
815
+ const seen = new Set();
816
+ for (const { note, stage } of this.notes) {
817
+ const key = `${note.kind}\0${note.raw}\0${stage}`;
818
+ if (seen.has(key))
819
+ continue;
820
+ seen.add(key);
821
+ if (note.kind === 'fmt_ph') {
822
+ this.out(`Note: ${note.raw} in the ${stage}: the simulator formats only North American ` +
823
+ `numbers, so it left "${note.value}" as it is. The platform formats a valid number ` +
824
+ 'in its national format, and writes INVALID NUMBER for one that is not valid; ' +
825
+ 'install the libphonenumber-js package to simulate that.');
826
+ continue;
827
+ }
828
+ let line = `Note: ${note.raw} in the ${stage} expands to an empty string on the platform.`;
829
+ const lowered = asciiLower(note.path);
830
+ const prefix = /^([A-Za-z_]\w*):(.*)$/.exec(note.path);
831
+ if (lowered.startsWith('response.')) {
832
+ line +=
833
+ " The platform reads a webhook's JSON response from the root: " +
834
+ 'write ${<field>}, not ${response.<field>}.';
835
+ }
836
+ else if (RESPONSE_STAGES.has(stage) && lowered.startsWith('args.')) {
837
+ line +=
838
+ " In a webhook's foreach, expressions and output, the arguments are under " +
839
+ `input: write \${input.${note.path}}.`;
840
+ }
841
+ else if (!RESPONSE_STAGES.has(stage) && lowered.startsWith('input.')) {
842
+ line +=
843
+ ' input is empty until a webhook responds; read the call data directly here, ' +
844
+ `as \${${note.path.slice('input.'.length)}}.`;
845
+ }
846
+ else if (prefix) {
847
+ line +=
848
+ ` "${prefix[1]}:" is not a template helper: the platform's helpers are lc:, enc: ` +
849
+ `and fmt_ph:, so it reads "${note.path}" as a path.` +
850
+ (asciiLower(prefix[1]) === 'url' ? ` To URL-encode, write \${enc:${prefix[2]}}.` : '');
851
+ }
852
+ this.out(line);
853
+ }
854
+ }
855
+ }
856
+ /** The first expression result, or MISSING, as get_input_from_expressions() finds it. */
857
+ function runExpressions(run, expressions, data, stage) {
858
+ for (const item of Array.isArray(expressions) ? expressions : [expressions]) {
859
+ const reply = parseExpression(run, item, data, stage);
860
+ if (reply !== MISSING)
861
+ return reply;
862
+ }
863
+ return MISSING;
864
+ }
865
+ /** One expression's result, or MISSING when it produces none, as parse_expression() does. */
866
+ function parseExpression(run, item, data, stage) {
867
+ let subjectTemplate = stringItem(item, 'string');
868
+ const pattern = stringItem(item, 'pattern');
869
+ const expr = stringItem(item, 'expr');
870
+ if (subjectTemplate === null) {
871
+ // With neither string nor expr, an expression never matches
872
+ if (expr === null)
873
+ return MISSING;
874
+ subjectTemplate = expr;
875
+ }
876
+ const output = objectItem(item, 'output');
877
+ const nomatch = objectItem(item, 'nomatch-output');
878
+ if (output === MISSING)
879
+ return MISSING;
880
+ const subject = run.expand(subjectTemplate, data, stage);
881
+ let matched = false;
882
+ if (expr !== null) {
883
+ run.say(`An expression's expr isn't evaluated by the simulator: ${expr}`);
884
+ }
885
+ if (pattern !== null) {
886
+ const re = platformRegExp(pattern);
887
+ if (re)
888
+ matched = re.test(subject);
889
+ else
890
+ run.say(`Expression pattern isn't a valid regular expression: ${pattern}`);
891
+ run.say(`Expression "${subject}" against ${pattern}: ${matched ? 'match' : 'no match'}`);
892
+ }
893
+ if (matched)
894
+ return run.expandJson(output, data, stage);
895
+ if (nomatch !== MISSING)
896
+ return run.expandJson(nomatch, data, stage);
897
+ return MISSING;
898
+ }
899
+ /** The call data templates read before a webhook responds, as the platform builds it. */
900
+ function buildCallData(fn, args, callData) {
901
+ const extra = structuredClone(callData ?? {});
902
+ const rawPromptVars = extra['prompt_vars'];
903
+ delete extra['prompt_vars'];
904
+ const promptVars = isPlainObject(rawPromptVars) ? rawPromptVars : {};
905
+ const data = {};
906
+ if (typeof fn['function'] === 'string')
907
+ data['function'] = fn['function'];
908
+ for (const [key, value] of Object.entries(extra))
909
+ replaceItem(data, key, value);
910
+ // The platform merges the function's meta_data over the global data, key
911
+ // by key, when it loads the function (app_config.c, cJSON_Merge with
912
+ // replace); a call's meta_data is that object, not one from the call data.
913
+ const metaData = {};
914
+ for (const source of [objectItem(data, 'global_data'), fn['meta_data']]) {
915
+ if (!isPlainObject(source))
916
+ continue;
917
+ for (const [key, value] of Object.entries(source)) {
918
+ replaceItem(metaData, key, structuredClone(value));
919
+ }
920
+ }
921
+ replaceItem(data, 'meta_data', metaData);
922
+ // As on the platform, the prompt variables are merged into the root
923
+ for (const [key, value] of Object.entries(promptVars)) {
924
+ replaceItem(data, key, structuredClone(value));
925
+ }
926
+ addItem(data, 'args', structuredClone(args));
927
+ addItem(data, 'input', {});
928
+ return { data, promptVars, globalData: objectItem(data, 'global_data') };
929
+ }
930
+ /**
931
+ * Run a DataMap function locally, as the platform runs it.
932
+ *
933
+ * @param fn - The function's SWAIG entry (`{ function, data_map, meta_data, ... }`)
934
+ * or its `data_map` alone.
935
+ * @param args - The function's arguments.
936
+ * @param opts - Verbose output, the call data, and the fetch to use.
937
+ * @returns The function's result: the expanded output (an object or a
938
+ * string), `{ response: PLATFORM_ERROR_RESPONSE }` when nothing produced a
939
+ * result, as on the platform, or an `{ error }` object when the expanded
940
+ * output isn't JSON, where the platform gets no result.
941
+ */
942
+ export async function executeDataMap(fn, args, opts = {}) {
943
+ const log = opts.log ?? ((line) => void process.stderr.write(`${line}\n`));
944
+ const run = new Run(opts.verbose === true, log);
945
+ try {
946
+ return await execute(run, fn, args, opts);
947
+ }
948
+ finally {
949
+ run.report();
950
+ }
951
+ }
952
+ async function execute(run, fn, args, opts) {
953
+ const dataMap = (isPlainObject(fn['data_map']) ? fn['data_map'] : fn);
954
+ const { data, promptVars, globalData } = buildCallData(fn, args, opts.callData);
955
+ run.say('=== DataMap Function Execution ===');
956
+ run.say(`Args: ${JSON.stringify(args)}`);
957
+ if (opts.callData)
958
+ run.say(`Call data: ${JSON.stringify(data)}`);
959
+ // 1. The top-level expressions, against the call data
960
+ const expressions = objectItem(dataMap, 'expressions');
961
+ if (expressions !== MISSING) {
962
+ const reply = runExpressions(run, expressions, data, 'top-level expressions');
963
+ if (reply !== MISSING)
964
+ return reply;
965
+ }
966
+ // 2. The first webhook requested
967
+ const webhooks = objectItem(dataMap, 'webhooks');
968
+ if (webhooks !== MISSING) {
969
+ const { reply, match } = await runWebhooks(run, webhooks, data, opts);
970
+ if (match) {
971
+ // The response is the root of the template data; the call data is under input
972
+ const rdata = isPlainObject(reply) ? reply : {};
973
+ addItem(rdata, 'prompt_vars', structuredClone(promptVars));
974
+ if (globalData !== MISSING)
975
+ addItem(rdata, 'global_data', structuredClone(globalData));
976
+ addItem(rdata, 'input', structuredClone(data));
977
+ const foreach = objectItem(match, 'foreach');
978
+ if (foreach !== MISSING)
979
+ processForeach(run, foreach, rdata);
980
+ let response = MISSING;
981
+ let processed = false;
982
+ const hookExpressions = objectItem(match, 'expressions');
983
+ if (hookExpressions !== MISSING) {
984
+ const result = runExpressions(run, hookExpressions, rdata, 'webhook expressions');
985
+ if (result !== MISSING) {
986
+ // The platform expands a matched result a second time
987
+ response = run.expandJson(result, rdata, 'webhook expressions');
988
+ processed = true;
989
+ }
990
+ else {
991
+ run.say('No webhook expression matched');
992
+ }
993
+ }
994
+ const output = objectItem(match, 'output');
995
+ if (response === MISSING && output !== MISSING) {
996
+ response = run.expandJson(output, rdata, 'webhook output');
997
+ processed = true;
998
+ }
999
+ if (processed)
1000
+ return finish(run, response);
1001
+ }
1002
+ }
1003
+ // 3. The data_map's own output
1004
+ const output = objectItem(dataMap, 'output');
1005
+ if (output !== MISSING) {
1006
+ run.say('No webhook produced a result; using the data_map output');
1007
+ addItem(data, 'prompt_vars', structuredClone(promptVars));
1008
+ return finish(run, run.expandJson(output, data, 'top-level output'));
1009
+ }
1010
+ // 4. The platform's generic error
1011
+ run.say('Nothing produced a result; the platform returns its generic error');
1012
+ return { response: PLATFORM_ERROR_RESPONSE };
1013
+ }
1014
+ function finish(run, response) {
1015
+ if (response === MISSING) {
1016
+ run.say("The expanded output isn't valid JSON");
1017
+ return {
1018
+ error: "The expanded output isn't valid JSON, so the platform gets no result from this " +
1019
+ 'function. A template that inserts an object or array into a string causes this.',
1020
+ };
1021
+ }
1022
+ return response;
1023
+ }
1024
+ /**
1025
+ * Request the first eligible webhook, as get_input_from_webhooks() does.
1026
+ * Returns the reply, with an array wrapped as `{ array: [...] }`, and the
1027
+ * webhook when its reply counts as a success.
1028
+ */
1029
+ async function runWebhooks(run, webhooks, data, opts) {
1030
+ let reply = MISSING;
1031
+ let match = null;
1032
+ if (Array.isArray(webhooks)) {
1033
+ for (const [i, item] of webhooks.entries()) {
1034
+ run.say(`\n=== Webhook ${i + 1}/${webhooks.length} ===`);
1035
+ const requireArgs = objectItem(item, 'require_args');
1036
+ let eligible = true;
1037
+ if (requireArgs !== MISSING && !anyPresent(requireArgs, objectItem(data, 'args'))) {
1038
+ // Any one of the listed arguments is enough
1039
+ run.say('Skipped: none of its require_args is present');
1040
+ eligible = false;
1041
+ }
1042
+ if (!hasItem(item, 'output') && !hasItem(item, 'expressions')) {
1043
+ run.say('Skipped: a webhook must have output or expressions');
1044
+ eligible = false;
1045
+ }
1046
+ if (!eligible)
1047
+ continue;
1048
+ reply = await request(run, item, data, opts);
1049
+ if (reply === MISSING) {
1050
+ run.say('Skipped: the webhook has no url');
1051
+ continue;
1052
+ }
1053
+ const reason = failure(reply, objectItem(item, 'error_keys'));
1054
+ if (reason) {
1055
+ run.say(`Webhook ${i + 1} failed: ${reason}. The platform tries no later webhook; ` +
1056
+ 'the data_map output runs instead.');
1057
+ }
1058
+ else {
1059
+ match = item;
1060
+ }
1061
+ break;
1062
+ }
1063
+ }
1064
+ else if (isPlainObject(webhooks)) {
1065
+ // A single webhook object is never checked for errors
1066
+ run.say('\n=== Webhook ===');
1067
+ if (hasItem(webhooks, 'output') || hasItem(webhooks, 'expressions')) {
1068
+ reply = await request(run, webhooks, data, opts);
1069
+ if (reply !== MISSING)
1070
+ match = webhooks;
1071
+ }
1072
+ else {
1073
+ run.say('Skipped: a webhook must have output or expressions');
1074
+ }
1075
+ }
1076
+ if (Array.isArray(reply))
1077
+ reply = { array: reply };
1078
+ return { reply, match };
1079
+ }
1080
+ /** mod_openai's args_present(): whether any of the named keys is present. */
1081
+ function anyPresent(keys, container) {
1082
+ const list = Array.isArray(keys) ? keys : [keys];
1083
+ return list.some((k) => typeof k === 'string' && hasItem(container, k));
1084
+ }
1085
+ /** Why a webhook's reply counts as a failure, or an empty string. */
1086
+ function failure(reply, errorKeys) {
1087
+ for (const key of ['parse_error', 'protocol_error']) {
1088
+ if (hasItem(reply, key))
1089
+ return `the response has ${key}`;
1090
+ }
1091
+ if (errorKeys === MISSING)
1092
+ return '';
1093
+ // A listed key fails the webhook when it is present, whatever its value
1094
+ for (const key of Array.isArray(errorKeys) ? errorKeys : [errorKeys]) {
1095
+ if (typeof key === 'string' && hasItem(reply, key)) {
1096
+ return `the response has the error key '${key}'`;
1097
+ }
1098
+ }
1099
+ return '';
1100
+ }
1101
+ /**
1102
+ * Send one webhook's request as parse_webhook() does, and return its reply,
1103
+ * or MISSING when the webhook has no url.
1104
+ */
1105
+ async function request(run, webhook, data, opts) {
1106
+ let url = stringItem(webhook, 'url');
1107
+ if (url === null)
1108
+ return MISSING;
1109
+ const method = stringItem(webhook, 'method');
1110
+ const formParam = stringItem(webhook, 'form_param');
1111
+ let params = objectItem(webhook, 'params');
1112
+ const headers = objectItem(webhook, 'headers');
1113
+ if (isTrue(objectItem(webhook, 'input_args_as_params'))) {
1114
+ const args = objectItem(data, 'args');
1115
+ if (args !== MISSING) {
1116
+ if (isPlainObject(params) && isPlainObject(args)) {
1117
+ const merged = structuredClone(params);
1118
+ for (const [key, value] of Object.entries(args)) {
1119
+ replaceItem(merged, key, structuredClone(value));
1120
+ }
1121
+ params = merged;
1122
+ }
1123
+ else if (params === MISSING) {
1124
+ params = args;
1125
+ }
1126
+ }
1127
+ }
1128
+ // Credentials in the url become basic authentication, sent only to their origin
1129
+ let authorization;
1130
+ const credentials = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#@]*)@/.exec(url);
1131
+ if (credentials) {
1132
+ const [user, ...rest] = credentials[2].split(':');
1133
+ const decode = (s) => {
1134
+ try {
1135
+ return decodeURIComponent(s);
1136
+ }
1137
+ catch {
1138
+ return s;
1139
+ }
1140
+ };
1141
+ const pair = `${decode(user)}:${decode(rest.join(':'))}`;
1142
+ authorization = `Basic ${Buffer.from(pair).toString('base64')}`;
1143
+ url = credentials[1] + url.slice(credentials[0].length);
1144
+ }
1145
+ url = run.expand(url, data, 'webhook url');
1146
+ let post = method !== null && method.toLowerCase() === 'post';
1147
+ let body;
1148
+ if (params !== MISSING) {
1149
+ // params are the request body, so a webhook with params is a POST
1150
+ post = true;
1151
+ body = run.expand(cjsonPrint(params), data, 'webhook params', true);
1152
+ if (formParam !== null)
1153
+ body = `${formParam}=${urlEncode(body)}`;
1154
+ }
1155
+ if (hasItem(webhook, 'body')) {
1156
+ run.say("The platform doesn't send a webhook's body key; params is the request body");
1157
+ }
1158
+ const requestHeaders = {
1159
+ 'Content-Type': formParam !== null ? 'application/x-www-form-urlencoded' : 'application/json',
1160
+ 'User-Agent': 'SignalWire-CallFabric/1.0',
1161
+ };
1162
+ if (authorization)
1163
+ requestHeaders['Authorization'] = authorization;
1164
+ if (isPlainObject(headers)) {
1165
+ // Header values are sent as written; templates in them aren't expanded
1166
+ for (const [name, value] of Object.entries(headers)) {
1167
+ if (typeof value !== 'string')
1168
+ continue;
1169
+ for (const existing of Object.keys(requestHeaders)) {
1170
+ if (existing.toLowerCase() === name.toLowerCase())
1171
+ delete requestHeaders[existing];
1172
+ }
1173
+ requestHeaders[name] = value;
1174
+ }
1175
+ }
1176
+ const httpMethod = post ? 'POST' : 'GET';
1177
+ if (method !== null && method.toUpperCase() !== httpMethod) {
1178
+ run.say(`The platform sends ${httpMethod}, not ${method}`);
1179
+ }
1180
+ run.say(`${httpMethod} ${url}`);
1181
+ if (body !== undefined)
1182
+ run.say(`Request body: ${body}`);
1183
+ const fetchImpl = opts.fetchImpl ??
1184
+ ((target, init) => _publicFetch(target, {
1185
+ method: init.method,
1186
+ headers: init.headers,
1187
+ body: init.body,
1188
+ signal: init.signal,
1189
+ // The platform's curl settings: up to 15 redirects, a POST sent again
1190
+ // with its body after any of them. Every hop is still checked.
1191
+ redirectMode: 'curl',
1192
+ onStatus: init.onStatus,
1193
+ }));
1194
+ // Each status received, redirects included
1195
+ const statuses = [];
1196
+ let status = 0;
1197
+ let text = '';
1198
+ let curlError = null;
1199
+ const controller = new AbortController();
1200
+ const timer = setTimeout(() => controller.abort(), (opts.timeoutSeconds ?? HTTP_REQUEST_TIMEOUT) * 1000);
1201
+ try {
1202
+ // The timeout covers the body too: headers can arrive and the body stall.
1203
+ const response = await fetchImpl(url, {
1204
+ method: httpMethod,
1205
+ headers: requestHeaders,
1206
+ body,
1207
+ signal: controller.signal,
1208
+ onStatus: (received) => void statuses.push(received),
1209
+ });
1210
+ status = response.status;
1211
+ text = await Promise.race([
1212
+ response.text(),
1213
+ new Promise((_resolve, reject) => {
1214
+ const abort = () => reject(new Error('webhook timed out'));
1215
+ if (controller.signal.aborted)
1216
+ abort();
1217
+ controller.signal.addEventListener('abort', abort, { once: true });
1218
+ }),
1219
+ ]);
1220
+ run.say(`Response status: ${status}`);
1221
+ }
1222
+ catch (err) {
1223
+ // As curl reports it, the status is the last one received, redirects
1224
+ // included, or 0 when none was
1225
+ status = statuses.at(-1) ?? status;
1226
+ curlError = curlErrorCode(err);
1227
+ run.say(`Request failed: ${err instanceof Error ? err.message : String(err)}`);
1228
+ }
1229
+ finally {
1230
+ clearTimeout(timer);
1231
+ }
1232
+ let reply = text ? cjsonParse(text) : MISSING;
1233
+ const parseError = reply === MISSING;
1234
+ if (parseError || curlError !== null || status < 200 || status > 299) {
1235
+ if (reply === MISSING)
1236
+ reply = {};
1237
+ if (isPlainObject(reply)) {
1238
+ if (parseError) {
1239
+ setItem(reply, 'parse_error', true);
1240
+ setItem(reply, 'raw_response', text);
1241
+ }
1242
+ if (curlError !== null) {
1243
+ setItem(reply, 'protocol_error', true);
1244
+ setItem(reply, 'http_req_result', curlError);
1245
+ }
1246
+ setItem(reply, 'http_code', status);
1247
+ }
1248
+ run.say(`Response data: ${JSON.stringify(reply)}`);
1249
+ }
1250
+ return reply;
1251
+ }
1252
+ /** Build a foreach's text into its output_key, as process_foreach() does. */
1253
+ function processForeach(run, foreach, data) {
1254
+ const inputKey = stringItem(foreach, 'input_key');
1255
+ const outputKey = stringItem(foreach, 'output_key');
1256
+ const append = stringItem(foreach, 'append');
1257
+ if (inputKey === null || outputKey === null || append === null) {
1258
+ run.say('foreach needs input_key, output_key and append; skipping it');
1259
+ return;
1260
+ }
1261
+ const items = lookup(data, inputKey);
1262
+ if (!Array.isArray(items)) {
1263
+ run.say(`foreach: ${inputKey} isn't an array in the response; skipping it`);
1264
+ return;
1265
+ }
1266
+ let count = items.length;
1267
+ const limit = objectItem(foreach, 'max');
1268
+ if (limit !== MISSING) {
1269
+ const max = typeof limit === 'string' ? atoi(limit) : typeof limit === 'number' ? Math.trunc(limit) : 0;
1270
+ if (max > 0)
1271
+ count = Math.min(count, max);
1272
+ }
1273
+ const parts = [];
1274
+ for (const item of items.slice(0, count)) {
1275
+ // this is the current element, and everything else stays readable
1276
+ deleteItem(data, 'this');
1277
+ setItem(data, 'this', structuredClone(item));
1278
+ parts.push(run.expand(append, data, 'webhook foreach'));
1279
+ deleteItem(data, 'this');
1280
+ }
1281
+ addItem(data, outputKey, parts.join(''));
1282
+ run.say(`foreach: ${count} item(s) into ${outputKey}`);
1283
+ }
1284
+ //# sourceMappingURL=datamap-exec.js.map