eve 0.63.0 → 0.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (485) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/src/ai/evaluate.js +1 -1
  3. package/dist/src/channel/channel-address.d.ts +4 -1
  4. package/dist/src/channel/channel-address.js +1 -1
  5. package/dist/src/channel/channel-operations.d.ts +4 -1
  6. package/dist/src/channel/cross-channel-receive.d.ts +4 -1
  7. package/dist/src/channel/cross-channel-receive.js +1 -1
  8. package/dist/src/channel/session.d.ts +3 -1
  9. package/dist/src/channel/session.js +1 -1
  10. package/dist/src/channel/types.d.ts +7 -0
  11. package/dist/src/chunks/{use-eve-agent-C5-yqRuq.js → use-eve-agent-BdKlQF32.js} +8 -8
  12. package/dist/src/chunks/{use-eve-agent-CVWk5KKy.js → use-eve-agent-IIuxkn6y.js} +8 -8
  13. package/dist/src/cli/commands/build.js +1 -1
  14. package/dist/src/cli/commands/init-agent-workspace.d.ts +2 -0
  15. package/dist/src/cli/commands/init.js +1 -1
  16. package/dist/src/cli/commands/registry-pnpm-build-policy-flow.d.ts +1 -1
  17. package/dist/src/cli/commands/registry-pnpm-build-policy-flow.js +1 -1
  18. package/dist/src/cli/dev/tui/line-editor.d.ts +11 -1
  19. package/dist/src/cli/dev/tui/line-editor.js +3 -3
  20. package/dist/src/cli/dev/tui/model-picker.d.ts +2 -0
  21. package/dist/src/cli/dev/tui/model-picker.js +1 -1
  22. package/dist/src/cli/dev/tui/runner.d.ts +0 -1
  23. package/dist/src/cli/dev/tui/runner.js +2 -2
  24. package/dist/src/cli/dev/tui/setup-panel.js +1 -1
  25. package/dist/src/cli/dev/tui/setup-selection-input.js +1 -1
  26. package/dist/src/cli/dev/tui/stream-format.d.ts +6 -0
  27. package/dist/src/cli/dev/tui/stream-format.js +2 -2
  28. package/dist/src/cli/dev/tui/terminal-renderer.d.ts +0 -1
  29. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  30. package/dist/src/cli/run.js +1 -1
  31. package/dist/src/client/agent-info-schema.d.ts +8 -14
  32. package/dist/src/client/agent-info-schema.js +1 -1
  33. package/dist/src/client/eve-agent-store.js +1 -1
  34. package/dist/src/client/session.js +1 -1
  35. package/dist/src/client/types.d.ts +4 -2
  36. package/dist/src/compiled/.vendor-stamp.json +11 -11
  37. package/dist/src/compiled/@chat-adapter/slack/_chat-adapter-shared.d.ts +1 -0
  38. package/dist/src/compiled/@chat-adapter/slack/api.d.ts +3 -2
  39. package/dist/src/compiled/@chat-adapter/slack/api.js +1 -1
  40. package/dist/src/compiled/@chat-adapter/slack/blocks.js +1 -1
  41. package/dist/src/compiled/@chat-adapter/slack/format.js +1 -1
  42. package/dist/src/compiled/@chat-adapter/slack/index.d.ts +410 -63
  43. package/dist/src/compiled/@chat-adapter/slack/index.js +47 -25
  44. package/dist/src/compiled/@chat-adapter/twilio/api.d.ts +5 -1
  45. package/dist/src/compiled/@chat-adapter/twilio/api.js +1 -1
  46. package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +37 -3
  47. package/dist/src/compiled/@chat-adapter/twilio/index.js +5 -1
  48. package/dist/src/compiled/@chat-adapter/twilio/webhook.d.ts +2 -2
  49. package/dist/src/compiled/@chat-adapter/twilio/webhook.js +1 -1
  50. package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.js +6 -6
  51. package/dist/src/compiled/@photon-ai/chat-adapter-imessage/index.js +50 -50
  52. package/dist/src/compiled/@vercel/sandbox/index.js +4 -4
  53. package/dist/src/compiled/@workflow/core/attribute-changes.d.ts +2 -1
  54. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +6 -3
  55. package/dist/src/compiled/@workflow/core/index.js +2 -2
  56. package/dist/src/compiled/@workflow/core/private.d.ts +37 -5
  57. package/dist/src/compiled/@workflow/core/private.js +1 -1
  58. package/dist/src/compiled/@workflow/core/runtime/deployment-guard.d.ts +2 -1
  59. package/dist/src/compiled/@workflow/core/runtime/helpers.js +1 -1
  60. package/dist/src/compiled/@workflow/core/runtime/invocations.d.ts +35 -0
  61. package/dist/src/compiled/@workflow/core/runtime/lifecycle-hooks.d.ts +90 -0
  62. package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +2 -1
  63. package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +8 -6
  64. package/dist/src/compiled/@workflow/core/runtime/step-single-flight.d.ts +1 -1
  65. package/dist/src/compiled/@workflow/core/runtime.js +4 -4
  66. package/dist/src/compiled/@workflow/core/serialization.d.ts +5 -1
  67. package/dist/src/compiled/@workflow/core/serialization.js +1 -1
  68. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  69. package/dist/src/compiled/@workflow/core/workflow/set-attributes.d.ts +4 -0
  70. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  71. package/dist/src/compiled/@workflow/world/analytics.d.ts +1 -1
  72. package/dist/src/compiled/@workflow/world/attributes-validation.d.ts +5 -0
  73. package/dist/src/compiled/@workflow/world/events.d.ts +2 -2
  74. package/dist/src/compiled/@workflow/world/index.d.ts +2 -1
  75. package/dist/src/compiled/@workflow/world/interfaces.d.ts +12 -1
  76. package/dist/src/compiled/@workflow/world/invocation.d.ts +19 -0
  77. package/dist/src/compiled/@workflow/world/queue.d.ts +24 -3
  78. package/dist/src/compiled/@workflow/world-local/index.js +3 -3
  79. package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
  80. package/dist/src/compiled/_chunks/node/chunk-6QHBXN7B-gl4n6nmi.js +12 -0
  81. package/dist/src/compiled/_chunks/node/chunk-7WDLOIRP-B_IWkVtZ.js +1 -0
  82. package/dist/src/compiled/_chunks/node/chunk-KBOOTKHF-DJqFk2r1.js +1 -0
  83. package/dist/src/compiled/_chunks/node/chunk-TREVQR3E-CLsTAn-O.js +1 -0
  84. package/dist/src/compiled/_chunks/node/dist-DYDVZ-FS.js +98 -0
  85. package/dist/src/compiled/_chunks/node/dist-iEFkK9qw.js +6 -0
  86. package/dist/src/compiled/_chunks/workflow/attribute-changes-DFx4eluc.js +6 -0
  87. package/dist/src/compiled/_chunks/workflow/{dist-D38gP7YF.js → dist-DjECvUyK.js} +1 -1
  88. package/dist/src/compiled/_chunks/workflow/{frames-QcJfYHmh.js → frames-D_Q-7A1N.js} +2 -2
  89. package/dist/src/compiled/_chunks/workflow/{helpers-6kObVbfS.js → helpers-Bw52uyzw.js} +1 -1
  90. package/dist/src/compiled/_chunks/workflow/{logger-NN5YHpYy.js → logger-DFNCa8Nl.js} +1 -1
  91. package/dist/src/compiled/_chunks/workflow/resume-hook-BhA_nDEV.js +1 -0
  92. package/dist/src/compiled/_chunks/workflow/{run-DJevv8zz.js → run-BT6SQv5f.js} +1 -1
  93. package/dist/src/compiled/_chunks/workflow/{serialization-C5KgPESk.js → serialization-Cl0SYU0I.js} +3 -3
  94. package/dist/src/compiled/_chunks/workflow/sleep-DB4AH9-A.js +1 -0
  95. package/dist/src/compiled/_chunks/workflow/{wait-until-BMY_tOr-.js → wait-until-Dzhr6tzf.js} +1 -1
  96. package/dist/src/compiled/_chunks/workflow/{ws-transport-DSDcKH08.js → ws-transport-BpTMh40s.js} +1 -1
  97. package/dist/src/compiled/chat/index.d.ts +1 -725
  98. package/dist/src/compiled/chat/index.js +1 -1
  99. package/dist/src/compiler/artifacts.d.ts +1 -0
  100. package/dist/src/compiler/artifacts.js +1 -1
  101. package/dist/src/compiler/extension-compatibility.d.ts +23 -15
  102. package/dist/src/compiler/extension-compatibility.js +1 -1
  103. package/dist/src/compiler/manifest.d.ts +14 -18
  104. package/dist/src/compiler/manifest.js +1 -1
  105. package/dist/src/compiler/normalize-helpers.js +1 -1
  106. package/dist/src/compiler/normalize-sandbox.d.ts +2 -7
  107. package/dist/src/compiler/normalize-sandbox.js +1 -1
  108. package/dist/src/compiler/workspace-resources.js +1 -1
  109. package/dist/src/context/build-callback-context.d.ts +2 -0
  110. package/dist/src/context/build-callback-context.js +1 -1
  111. package/dist/src/context/container.d.ts +1 -1
  112. package/dist/src/context/container.js +1 -1
  113. package/dist/src/context/key-names.d.ts +1 -0
  114. package/dist/src/context/key-names.js +1 -1
  115. package/dist/src/context/keys.d.ts +7 -2
  116. package/dist/src/context/keys.js +1 -1
  117. package/dist/src/context/providers/sandbox.js +1 -1
  118. package/dist/src/context/providers/session.d.ts +19 -2
  119. package/dist/src/context/session-context.d.ts +1 -1
  120. package/dist/src/discover/sandbox.js +1 -1
  121. package/dist/src/evals/cli/eval.js +1 -1
  122. package/dist/src/evals/context.d.ts +1 -0
  123. package/dist/src/evals/context.js +1 -1
  124. package/dist/src/evals/define-eval-config.d.ts +7 -7
  125. package/dist/src/evals/define-eval-config.js +1 -1
  126. package/dist/src/evals/define-eval.d.ts +5 -2
  127. package/dist/src/evals/index.d.ts +1 -1
  128. package/dist/src/evals/runner/execute-eval.d.ts +2 -0
  129. package/dist/src/evals/runner/execute-eval.js +1 -1
  130. package/dist/src/evals/runner/execute-task.d.ts +2 -0
  131. package/dist/src/evals/runner/execute-task.js +1 -1
  132. package/dist/src/evals/runner/run-evals.d.ts +2 -0
  133. package/dist/src/evals/runner/run-evals.js +1 -1
  134. package/dist/src/evals/target.js +1 -1
  135. package/dist/src/evals/types.d.ts +22 -6
  136. package/dist/src/eve-channel/create-request.d.ts +2 -1
  137. package/dist/src/eve-channel/delivery-policy-request.d.ts +4 -0
  138. package/dist/src/eve-channel/delivery-policy-request.js +1 -0
  139. package/dist/src/eve-channel/index.js +1 -1
  140. package/dist/src/eve-channel/request.d.ts +2 -1
  141. package/dist/src/eve-channel/request.js +1 -1
  142. package/dist/src/execution/coordination-dispatch-shared.d.ts +2 -1
  143. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  144. package/dist/src/execution/dynamic-workflow/tool.js +1 -1
  145. package/dist/src/execution/runtime-context.js +1 -1
  146. package/dist/src/execution/sandbox/active-handles.d.ts +7 -8
  147. package/dist/src/execution/sandbox/active-handles.js +1 -1
  148. package/dist/src/execution/sandbox/bash.js +1 -1
  149. package/dist/src/execution/sandbox/bindings/docker-cli.d.ts +1 -1
  150. package/dist/src/execution/sandbox/bindings/docker-cli.js +1 -1
  151. package/dist/src/execution/sandbox/bindings/docker-container.d.ts +2 -2
  152. package/dist/src/execution/sandbox/bindings/docker-container.js +1 -1
  153. package/dist/src/execution/sandbox/bindings/docker-network.d.ts +1 -1
  154. package/dist/src/execution/sandbox/bindings/docker-network.js +1 -1
  155. package/dist/src/execution/sandbox/bindings/docker-options.d.ts +4 -5
  156. package/dist/src/execution/sandbox/bindings/docker-options.js +1 -1
  157. package/dist/src/execution/sandbox/bindings/docker-session.d.ts +0 -1
  158. package/dist/src/execution/sandbox/bindings/docker-session.js +2 -2
  159. package/dist/src/execution/sandbox/bindings/docker.d.ts +16 -18
  160. package/dist/src/execution/sandbox/bindings/docker.js +1 -1
  161. package/dist/src/execution/sandbox/bindings/immutable-resources.d.ts +21 -0
  162. package/dist/src/execution/sandbox/bindings/immutable-resources.js +2 -0
  163. package/dist/src/execution/sandbox/bindings/just-bash-runtime.d.ts +9 -5
  164. package/dist/src/execution/sandbox/bindings/just-bash-runtime.js +1 -1
  165. package/dist/src/execution/sandbox/bindings/just-bash.d.ts +13 -26
  166. package/dist/src/execution/sandbox/bindings/just-bash.js +1 -1
  167. package/dist/src/execution/sandbox/bindings/{local-backend-utils.d.ts → local-provider-utils.d.ts} +7 -5
  168. package/dist/src/execution/sandbox/bindings/local-provider-utils.js +1 -0
  169. package/dist/src/execution/sandbox/bindings/local.d.ts +3 -3
  170. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  171. package/dist/src/execution/sandbox/bindings/microsandbox-create.js +1 -1
  172. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.d.ts +30 -8
  173. package/dist/src/execution/sandbox/bindings/microsandbox-lifecycle.js +1 -1
  174. package/dist/src/execution/sandbox/bindings/microsandbox-metadata.d.ts +9 -1
  175. package/dist/src/execution/sandbox/bindings/microsandbox-metadata.js +1 -1
  176. package/dist/src/execution/sandbox/bindings/microsandbox-network.js +1 -1
  177. package/dist/src/execution/sandbox/bindings/microsandbox-options.d.ts +10 -4
  178. package/dist/src/execution/sandbox/bindings/microsandbox-options.js +1 -1
  179. package/dist/src/execution/sandbox/bindings/microsandbox-platform.js +1 -1
  180. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.d.ts +7 -5
  181. package/dist/src/execution/sandbox/bindings/microsandbox-runtime.js +1 -1
  182. package/dist/src/execution/sandbox/bindings/microsandbox-templates.js +1 -1
  183. package/dist/src/execution/sandbox/bindings/microsandbox.d.ts +11 -21
  184. package/dist/src/execution/sandbox/bindings/microsandbox.js +1 -1
  185. package/dist/src/execution/sandbox/bindings/vercel-base-runtime.js +2 -2
  186. package/dist/src/execution/sandbox/bindings/vercel-credentials.js +1 -1
  187. package/dist/src/execution/sandbox/bindings/vercel-errors.js +1 -1
  188. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.d.ts +2 -2
  189. package/dist/src/execution/sandbox/bindings/vercel-lifecycle.js +1 -1
  190. package/dist/src/execution/sandbox/bindings/vercel-lookup.js +1 -1
  191. package/dist/src/execution/sandbox/bindings/vercel-options.d.ts +1 -2
  192. package/dist/src/execution/sandbox/bindings/vercel-options.js +1 -1
  193. package/dist/src/execution/sandbox/bindings/vercel.d.ts +20 -12
  194. package/dist/src/execution/sandbox/bindings/vercel.js +2 -2
  195. package/dist/src/execution/sandbox/development-cleanup.js +1 -1
  196. package/dist/src/execution/sandbox/development-lazy-prewarm.d.ts +7 -0
  197. package/dist/src/execution/sandbox/development-lazy-prewarm.js +1 -0
  198. package/dist/src/execution/sandbox/development-run.d.ts +2 -3
  199. package/dist/src/execution/sandbox/dockerfile.d.ts +25 -0
  200. package/dist/src/execution/sandbox/dockerfile.js +1 -0
  201. package/dist/src/execution/sandbox/ensure.d.ts +0 -17
  202. package/dist/src/execution/sandbox/ensure.js +1 -1
  203. package/dist/src/execution/sandbox/logging-session.js +1 -1
  204. package/dist/src/execution/sandbox/prewarm.d.ts +23 -27
  205. package/dist/src/execution/sandbox/prewarm.js +1 -2
  206. package/dist/src/execution/sandbox/provider-files.d.ts +2 -0
  207. package/dist/src/execution/sandbox/provider-files.js +1 -0
  208. package/dist/src/execution/sandbox/provider-host-development.d.ts +2 -0
  209. package/dist/src/execution/sandbox/provider-host-development.js +1 -0
  210. package/dist/src/execution/sandbox/provider-host.d.ts +2 -0
  211. package/dist/src/execution/sandbox/provider-host.js +1 -0
  212. package/dist/src/execution/sandbox/provider-identity.d.ts +1 -0
  213. package/dist/src/execution/sandbox/provider-identity.js +1 -0
  214. package/dist/src/execution/sandbox/ripgrep-probe.d.ts +0 -7
  215. package/dist/src/execution/sandbox/ripgrep-probe.js +1 -1
  216. package/dist/src/execution/sandbox/session.d.ts +8 -8
  217. package/dist/src/execution/sandbox/session.js +1 -1
  218. package/dist/src/execution/session/handoff-steps.js +1 -1
  219. package/dist/src/execution/session/handoff.d.ts +1 -1
  220. package/dist/src/execution/session/handoff.js +1 -1
  221. package/dist/src/execution/session/input-queue.d.ts +2 -1
  222. package/dist/src/execution/session/input-queue.js +1 -1
  223. package/dist/src/execution/session/next-input.js +1 -1
  224. package/dist/src/execution/session/program.js +1 -1
  225. package/dist/src/execution/session/turn-step.js +1 -1
  226. package/dist/src/execution/session-inbox/protocol.js +1 -1
  227. package/dist/src/execution/tasks/parent/tool-execution.js +1 -1
  228. package/dist/src/execution/tools/agent-router-workflow.js +1 -1
  229. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  230. package/dist/src/execution/tools/subagent/emit-event-step.js +1 -1
  231. package/dist/src/execution/tools/subagent/invoke-preparation.js +1 -1
  232. package/dist/src/execution/tools/subagent/start.d.ts +1 -0
  233. package/dist/src/framework/sources/modules/sandbox.d.ts +2 -1
  234. package/dist/src/framework/sources/modules/sandbox.js +1 -1
  235. package/dist/src/harness/approval-delivery-coordinator.js +1 -1
  236. package/dist/src/harness/hitl/approval-input-requests.d.ts +1 -1
  237. package/dist/src/harness/hitl/approval-input-requests.js +1 -1
  238. package/dist/src/harness/input-requests.d.ts +6 -0
  239. package/dist/src/harness/input-requests.js +1 -1
  240. package/dist/src/harness/messages.d.ts +2 -1
  241. package/dist/src/harness/messages.js +1 -1
  242. package/dist/src/harness/pending-input-batches.d.ts +1 -0
  243. package/dist/src/harness/pending-input-batches.js +1 -1
  244. package/dist/src/harness/tool-loop.js +2 -2
  245. package/dist/src/instrumentation/ai-sdk-warnings.d.ts +6 -0
  246. package/dist/src/instrumentation/ai-sdk-warnings.js +1 -0
  247. package/dist/src/instrumentation/runtime.d.ts +1 -0
  248. package/dist/src/instrumentation/runtime.js +1 -1
  249. package/dist/src/internal/application/compiled-artifacts.d.ts +2 -0
  250. package/dist/src/internal/application/compiled-artifacts.js +2 -2
  251. package/dist/src/internal/application/optional-package-install.d.ts +3 -0
  252. package/dist/src/internal/application/optional-package-install.js +2 -2
  253. package/dist/src/internal/application/output-publication-lock.d.ts +6 -0
  254. package/dist/src/internal/application/output-publication-lock.js +1 -1
  255. package/dist/src/internal/application/output-publication.js +1 -1
  256. package/dist/src/internal/application/package.js +1 -1
  257. package/dist/src/internal/authored-module-loader.d.ts +1 -0
  258. package/dist/src/internal/authored-module-loader.js +1 -1
  259. package/dist/src/internal/authored-runtime-modules.d.ts +1 -0
  260. package/dist/src/internal/nitro/development-generation.js +1 -1
  261. package/dist/src/internal/nitro/host/artifacts-config.d.ts +6 -1
  262. package/dist/src/internal/nitro/host/artifacts-config.js +1 -1
  263. package/dist/src/internal/nitro/host/build-application.js +1 -1
  264. package/dist/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.d.ts +16 -0
  265. package/dist/src/internal/nitro/host/compiled-sandbox-provider-prune-plugin.js +5 -0
  266. package/dist/src/internal/nitro/host/configure-nitro-routes.js +2 -2
  267. package/dist/src/internal/nitro/host/create-application-nitro.d.ts +3 -3
  268. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  269. package/dist/src/internal/nitro/host/dev-authored-rebuild-coordinator.js +1 -1
  270. package/dist/src/internal/nitro/host/dev-host-fingerprint.js +1 -1
  271. package/dist/src/internal/nitro/host/development-runtime-prune-plugin.d.ts +9 -0
  272. package/dist/src/internal/nitro/host/development-runtime-prune-plugin.js +2 -0
  273. package/dist/src/internal/nitro/host/prepare-application-host.d.ts +1 -0
  274. package/dist/src/internal/nitro/host/prepare-application-host.js +1 -1
  275. package/dist/src/internal/nitro/host/sandbox-shutdown-plugin.js +1 -1
  276. package/dist/src/internal/nitro/host/start-development-server.js +2 -2
  277. package/dist/src/internal/nitro/host/start-production-server.js +2 -2
  278. package/dist/src/internal/nitro/host/types.d.ts +1 -1
  279. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  280. package/dist/src/internal/nitro/routes/runtime-artifacts.d.ts +1 -0
  281. package/dist/src/internal/nitro/routes/runtime-artifacts.js +1 -1
  282. package/dist/src/internal/runtime-registry.d.ts +2 -2
  283. package/dist/src/internal/vercel/build-agent-workspace.d.ts +3 -1
  284. package/dist/src/internal/vercel/build-agent-workspace.js +1 -1
  285. package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +4 -5
  286. package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +2 -2
  287. package/dist/src/public/channels/github/checkout.js +1 -1
  288. package/dist/src/public/channels/index.d.ts +1 -1
  289. package/dist/src/public/channels/slack/slackChannel.d.ts +3 -1
  290. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  291. package/dist/src/public/definitions/channel.d.ts +1 -1
  292. package/dist/src/public/definitions/sandbox.d.ts +5 -43
  293. package/dist/src/public/definitions/sandbox.js +1 -1
  294. package/dist/src/public/local-dev.d.ts +4 -5
  295. package/dist/src/public/next/vercel-output-config.js +1 -1
  296. package/dist/src/public/sandbox/docker-sandbox.d.ts +16 -40
  297. package/dist/src/public/sandbox/docker.d.ts +2 -2
  298. package/dist/src/public/sandbox/docker.js +1 -1
  299. package/dist/src/public/sandbox/index.d.ts +4 -9
  300. package/dist/src/public/sandbox/index.js +1 -1
  301. package/dist/src/public/sandbox/just-bash-sandbox.d.ts +11 -6
  302. package/dist/src/public/sandbox/just-bash.d.ts +2 -2
  303. package/dist/src/public/sandbox/just-bash.js +1 -1
  304. package/dist/src/public/sandbox/microsandbox-sandbox.d.ts +11 -17
  305. package/dist/src/public/sandbox/microsandbox.d.ts +2 -2
  306. package/dist/src/public/sandbox/microsandbox.js +1 -1
  307. package/dist/src/public/sandbox/provider.d.ts +1 -0
  308. package/dist/src/public/sandbox/provider.js +1 -0
  309. package/dist/src/public/sandbox/vercel-sandbox.d.ts +10 -41
  310. package/dist/src/public/sandbox/vercel.d.ts +2 -2
  311. package/dist/src/public/sandbox/vercel.js +1 -1
  312. package/dist/src/runtime/cache-key.js +1 -1
  313. package/dist/src/runtime/compiled-artifacts-source.d.ts +6 -1
  314. package/dist/src/runtime/compiled-artifacts-source.js +1 -1
  315. package/dist/src/runtime/loaders/artifact-paths.d.ts +1 -0
  316. package/dist/src/runtime/loaders/artifact-paths.js +1 -1
  317. package/dist/src/runtime/loaders/bundled-artifacts.d.ts +3 -0
  318. package/dist/src/runtime/loaders/bundled-artifacts.js +1 -1
  319. package/dist/src/runtime/loaders/compile-metadata.js +1 -1
  320. package/dist/src/runtime/loaders/manifest.js +1 -1
  321. package/dist/src/runtime/loaders/module-map.js +1 -1
  322. package/dist/src/runtime/local-dev-capability.d.ts +14 -12
  323. package/dist/src/runtime/local-dev-capability.js +1 -1
  324. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  325. package/dist/src/runtime/resolve-sandbox.d.ts +1 -10
  326. package/dist/src/runtime/resolve-sandbox.js +1 -1
  327. package/dist/src/runtime/sandbox/prepared-artifacts.d.ts +13 -0
  328. package/dist/src/runtime/sandbox/prepared-artifacts.js +1 -0
  329. package/dist/src/runtime/sandbox/registry.d.ts +2 -9
  330. package/dist/src/runtime/sandbox/registry.js +1 -1
  331. package/dist/src/runtime/sessions/runtime-session.js +1 -1
  332. package/dist/src/runtime/types.d.ts +13 -26
  333. package/dist/src/runtime/workspace/types.d.ts +1 -1
  334. package/dist/src/sandbox/providers/default.d.ts +27 -0
  335. package/dist/src/sandbox/providers/default.js +1 -0
  336. package/dist/src/sandbox/providers/docker.d.ts +11 -0
  337. package/dist/src/sandbox/providers/docker.js +1 -0
  338. package/dist/src/sandbox/providers/just-bash.d.ts +4 -0
  339. package/dist/src/sandbox/providers/just-bash.js +1 -0
  340. package/dist/src/sandbox/providers/microsandbox.d.ts +12 -0
  341. package/dist/src/sandbox/providers/microsandbox.js +1 -0
  342. package/dist/src/sandbox/providers/vercel.d.ts +12 -0
  343. package/dist/src/sandbox/providers/vercel.js +1 -0
  344. package/dist/src/sandbox/providers.d.ts +5 -0
  345. package/dist/src/sandbox/providers.js +1 -0
  346. package/dist/src/sandbox/state.d.ts +6 -25
  347. package/dist/src/self-modification/extension/subagents/agent/agent.d.ts +1 -1
  348. package/dist/src/self-modification/extension/subagents/agent/agent.js +1 -1
  349. package/dist/src/self-modification/extension/subagents/agent/sandbox.d.ts +2 -25
  350. package/dist/src/self-modification/extension/subagents/agent/sandbox.js +1 -1
  351. package/dist/src/self-modification/extension/subagents/agent/tools/publish.js +1 -1
  352. package/dist/src/self-modification/extension/subagents/agent/tools/registry_add.js +1 -1
  353. package/dist/src/self-modification/filesystem.d.ts +3 -1
  354. package/dist/src/self-modification/filesystem.js +1 -1
  355. package/dist/src/self-modification/git-workspace.d.ts +1 -1
  356. package/dist/src/self-modification/git.d.ts +1 -1
  357. package/dist/src/self-modification/sandbox.d.ts +14 -9
  358. package/dist/src/self-modification/sandbox.js +1 -1
  359. package/dist/src/setup/boxes/select-model.js +1 -1
  360. package/dist/src/setup/cli/select-state.d.ts +4 -2
  361. package/dist/src/setup/cli/select-state.js +1 -1
  362. package/dist/src/setup/flows/model-login.js +1 -1
  363. package/dist/src/{cli/commands/registry-pnpm-build-policy.d.ts → setup/primitives/pm/pnpm-build-policy.d.ts} +4 -0
  364. package/dist/src/setup/primitives/pm/pnpm-build-policy.js +8 -0
  365. package/dist/src/setup/primitives/pm/pnpm.js +3 -2
  366. package/dist/src/setup/scaffold/create/project.js +1 -1
  367. package/dist/src/shared/default-agent-model.d.ts +1 -1
  368. package/dist/src/shared/default-agent-model.js +1 -1
  369. package/dist/src/shared/sandbox-environment.d.ts +45 -0
  370. package/dist/src/shared/sandbox-environment.js +1 -0
  371. package/dist/src/shared/sandbox-network-policy.d.ts +8 -3
  372. package/dist/src/shared/sandbox-network-policy.js +1 -1
  373. package/dist/src/shared/sandbox-prepared-artifacts.d.ts +16 -0
  374. package/dist/src/shared/sandbox-prepared-artifacts.js +1 -0
  375. package/dist/src/shared/sandbox-provider.d.ts +112 -0
  376. package/dist/src/shared/sandbox-provider.js +1 -0
  377. package/dist/src/shared/sandbox-session.d.ts +18 -41
  378. package/dist/src/shared/sandbox-template-error.d.ts +9 -0
  379. package/dist/src/shared/sandbox-template-error.js +1 -0
  380. package/dist/src/subagents/tool.d.ts +1 -1
  381. package/dist/src/subagents/tool.js +1 -1
  382. package/dist/src/svelte/index.js +1 -1
  383. package/dist/src/svelte/use-eve-agent.js +1 -1
  384. package/dist/src/tasks/delivery-context.d.ts +6 -4
  385. package/dist/src/tasks/delivery-context.js +1 -1
  386. package/dist/src/tasks/delivery-policy.d.ts +2 -0
  387. package/dist/src/tasks/delivery-policy.js +1 -1
  388. package/dist/src/tools/framework/agent-contract.js +1 -1
  389. package/dist/src/vue/index.js +1 -1
  390. package/dist/src/vue/use-eve-agent.js +1 -1
  391. package/docs/README.md +40 -45
  392. package/docs/agent-config.md +2 -2
  393. package/docs/channels/eve.mdx +1 -1
  394. package/docs/channels/overview.mdx +48 -0
  395. package/docs/channels/slack.mdx +1 -1
  396. package/docs/concepts/execution-model-and-durability.mdx +1 -1
  397. package/docs/concepts/sessions-runs-and-streaming.md +3 -3
  398. package/docs/dynamic-configuration/meta.json +5 -0
  399. package/docs/evals/overview.mdx +43 -0
  400. package/docs/getting-started.mdx +1 -1
  401. package/docs/guides/client/overview.mdx +1 -1
  402. package/docs/guides/deployment/overview.md +1 -1
  403. package/docs/guides/deployment/self-hosting.md +5 -5
  404. package/docs/guides/deployment/vercel.mdx +10 -18
  405. package/docs/guides/dev-tui.md +1 -1
  406. package/docs/guides/hooks.md +4 -0
  407. package/docs/guides/instrumentation/instrumentation.mdx +1 -1
  408. package/docs/guides/instrumentation/migration.md +1 -6
  409. package/docs/guides/instrumentation/otel.mdx +15 -47
  410. package/docs/memory/meta.json +1 -1
  411. package/docs/memory/overview.mdx +4 -0
  412. package/docs/meta.json +13 -16
  413. package/docs/patterns/meta.json +2 -2
  414. package/docs/protocols/acp.md +1 -1
  415. package/docs/protocols/ucp.mdx +1 -1
  416. package/docs/reference/cli.md +10 -9
  417. package/docs/reference/meta.json +4 -1
  418. package/docs/reference/typescript-api.md +2 -25
  419. package/docs/sandbox/default.mdx +17 -0
  420. package/docs/sandbox/docker.mdx +29 -0
  421. package/docs/sandbox/index.mdx +218 -0
  422. package/docs/sandbox/just-bash.mdx +24 -0
  423. package/docs/sandbox/meta.json +5 -0
  424. package/docs/sandbox/microsandbox.mdx +31 -0
  425. package/docs/sandbox/vercel.mdx +106 -0
  426. package/docs/schedules.mdx +35 -1
  427. package/docs/subagents/index.mdx +31 -13
  428. package/docs/subagents/meta.json +1 -1
  429. package/docs/tools/overview.mdx +14 -6
  430. package/docs/tutorial/run-analysis.mdx +6 -5
  431. package/package.json +20 -11
  432. package/dist/src/cli/commands/registry-pnpm-build-policy.js +0 -6
  433. package/dist/src/compiled/_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js +0 -1
  434. package/dist/src/compiled/_chunks/node/chunk-AYN7QRWH-B__hKQV7.js +0 -1
  435. package/dist/src/compiled/_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js +0 -1
  436. package/dist/src/compiled/_chunks/node/dist-CweJdVFE.js +0 -6
  437. package/dist/src/compiled/_chunks/node/dist-Da54NuK8.js +0 -96
  438. package/dist/src/compiled/_chunks/workflow/attribute-changes-A6HfMNG3.js +0 -6
  439. package/dist/src/compiled/_chunks/workflow/resume-hook-CAqlhwic.js +0 -1
  440. package/dist/src/compiled/_chunks/workflow/sleep-CbUwdv6O.js +0 -1
  441. package/dist/src/compiled/chat/_mdast.d.ts +0 -24
  442. package/dist/src/compiled/chat/_workflow-serde.d.ts +0 -3
  443. package/dist/src/compiled/chat/jsx-runtime-_JEEAotp.d.ts +0 -907
  444. package/dist/src/execution/sandbox/bindings/local-backend-utils.js +0 -1
  445. package/dist/src/execution/sandbox/development-prewarm.d.ts +0 -15
  446. package/dist/src/execution/sandbox/development-prewarm.js +0 -1
  447. package/dist/src/execution/sandbox/lazy-backend.d.ts +0 -15
  448. package/dist/src/execution/sandbox/lazy-backend.js +0 -1
  449. package/dist/src/execution/sandbox/template-prewarm-lock.d.ts +0 -8
  450. package/dist/src/execution/sandbox/template-prewarm-lock.js +0 -1
  451. package/dist/src/internal/authored-definition/sandbox.d.ts +0 -17
  452. package/dist/src/internal/authored-definition/sandbox.js +0 -1
  453. package/dist/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.d.ts +0 -16
  454. package/dist/src/internal/nitro/host/compiled-sandbox-backend-prune-plugin.js +0 -2
  455. package/dist/src/public/definitions/sandbox-backend.d.ts +0 -17
  456. package/dist/src/public/definitions/sandbox-backend.js +0 -1
  457. package/dist/src/public/sandbox/backends/default.d.ts +0 -1
  458. package/dist/src/public/sandbox/backends/default.js +0 -1
  459. package/dist/src/public/sandbox/backends/docker.d.ts +0 -1
  460. package/dist/src/public/sandbox/backends/docker.js +0 -1
  461. package/dist/src/public/sandbox/backends/just-bash.d.ts +0 -1
  462. package/dist/src/public/sandbox/backends/just-bash.js +0 -1
  463. package/dist/src/public/sandbox/backends/microsandbox.d.ts +0 -1
  464. package/dist/src/public/sandbox/backends/microsandbox.js +0 -1
  465. package/dist/src/public/sandbox/backends/vercel.d.ts +0 -1
  466. package/dist/src/public/sandbox/backends/vercel.js +0 -1
  467. package/dist/src/runtime/sandbox/keys.d.ts +0 -42
  468. package/dist/src/runtime/sandbox/keys.js +0 -1
  469. package/dist/src/runtime/sandbox/template-plan.d.ts +0 -24
  470. package/dist/src/runtime/sandbox/template-plan.js +0 -1
  471. package/dist/src/sandbox/backends/default.d.ts +0 -42
  472. package/dist/src/sandbox/backends/default.js +0 -1
  473. package/dist/src/sandbox/backends/docker.d.ts +0 -14
  474. package/dist/src/sandbox/backends/docker.js +0 -1
  475. package/dist/src/sandbox/backends/just-bash.d.ts +0 -17
  476. package/dist/src/sandbox/backends/just-bash.js +0 -1
  477. package/dist/src/sandbox/backends/microsandbox.d.ts +0 -17
  478. package/dist/src/sandbox/backends/microsandbox.js +0 -1
  479. package/dist/src/sandbox/backends/vercel.d.ts +0 -30
  480. package/dist/src/sandbox/backends/vercel.js +0 -1
  481. package/dist/src/shared/sandbox-backend.d.ts +0 -176
  482. package/dist/src/shared/sandbox-backend.js +0 -1
  483. package/dist/src/shared/sandbox-definition.d.ts +0 -112
  484. package/dist/src/shared/sandbox-definition.js +0 -1
  485. package/docs/sandbox.mdx +0 -342
@@ -53,6 +53,9 @@ interface TwilioCallResource {
53
53
  }
54
54
  interface SendTwilioMessageOptions extends TwilioApiOptions {
55
55
  body?: string;
56
+ contentSid?: string;
57
+ contentVariables?: Record<string, string> | string;
58
+ fallbackFrom?: string;
56
59
  from?: string;
57
60
  mediaUrl?: readonly string[] | string;
58
61
  messagingServiceSid?: string;
@@ -104,5 +107,6 @@ declare function updateTwilioCall(options: UpdateTwilioCallOptions): Promise<Twi
104
107
  declare function fetchTwilioMedia(options: FetchTwilioMediaOptions): Promise<ArrayBuffer>;
105
108
  declare function listTwilioMessages(options?: ListTwilioMessagesOptions): Promise<TwilioMessageResource[]>;
106
109
  declare function encodeTwilioForm(fields: TwilioFormFields): URLSearchParams;
110
+ declare function encodeBase64Utf8(value: string): string;
107
111
 
108
- export { type CallTwilioApiOptions, type DeleteTwilioMessageOptions, type FetchTwilioMediaOptions, type FetchTwilioMessageOptions, type ListTwilioMessagesOptions, type SendTwilioMessageOptions, TwilioApiError, type TwilioApiOptions, type TwilioApiResponse, type TwilioCallResource, type TwilioCredential, type TwilioCredentials, type TwilioFetch, type TwilioFormFields, type TwilioFormValue, type TwilioMessageResource, type UpdateTwilioCallOptions, callTwilioApi, deleteTwilioMessage, encodeTwilioForm, fetchTwilioMedia, fetchTwilioMessage, listTwilioMessages, resolveTwilioCredential, sendTwilioMessage, updateTwilioCall };
112
+ export { type CallTwilioApiOptions, type DeleteTwilioMessageOptions, type FetchTwilioMediaOptions, type FetchTwilioMessageOptions, type ListTwilioMessagesOptions, type SendTwilioMessageOptions, TwilioApiError, type TwilioApiOptions, type TwilioApiResponse, type TwilioCallResource, type TwilioCredential, type TwilioCredentials, type TwilioFetch, type TwilioFormFields, type TwilioFormValue, type TwilioMessageResource, type UpdateTwilioCallOptions, callTwilioApi, deleteTwilioMessage, encodeBase64Utf8, encodeTwilioForm, fetchTwilioMedia, fetchTwilioMessage, listTwilioMessages, resolveTwilioCredential, sendTwilioMessage, updateTwilioCall };
@@ -1 +1 @@
1
- import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c,u as l}from"../../_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js";export{c as TwilioApiError,i as callTwilioApi,o as deleteTwilioMessage,n as encodeTwilioForm,e as fetchTwilioMedia,a as fetchTwilioMessage,s as listTwilioMessages,t as resolveTwilioCredential,r as sendTwilioMessage,l as updateTwilioCall};
1
+ import{a as e,c as t,d as n,i as r,l as i,n as a,o,r as s,s as c,t as l,u}from"../../_chunks/node/chunk-KBOOTKHF-DJqFk2r1.js";export{l as TwilioApiError,a as callTwilioApi,s as deleteTwilioMessage,r as encodeBase64Utf8,e as encodeTwilioForm,o as fetchTwilioMedia,c as fetchTwilioMessage,t as listTwilioMessages,i as resolveTwilioCredential,u as sendTwilioMessage,n as updateTwilioCall};
@@ -1,6 +1,7 @@
1
+ import { T as TwilioWebhookPayload, a as TwilioWebhookUrl, b as TwilioWebhookVerifier, c as TwilioMediaPayload, d as TwilioChannelMetadata } from './types-BaIqtt65.js';
2
+ export { e as TwilioChannel, i as inferTwilioChannel, f as isRcsAddress, g as isRcsCapableSender, n as normalizeRcsSenderId, r as resolveInboundThreadSender } from './types-BaIqtt65.js';
1
3
  import { BaseFormatConverter, Root, AdapterPostableMessage, Logger, CardElement, Adapter, ChatInstance, WebhookOptions, RawMessage, Message, FetchOptions, FetchResult, ThreadInfo, UserInfo, FormattedContent, Attachment } from '#compiled/chat/index.js';
2
4
  import { TwilioMessageResource, TwilioCredential, TwilioFetch, TwilioApiOptions } from './api.js';
3
- import { T as TwilioWebhookPayload, a as TwilioWebhookUrl, b as TwilioWebhookVerifier, c as TwilioMediaPayload } from './types-WYjTBVDi.js';
4
5
 
5
6
  declare class TwilioFormatConverter extends BaseFormatConverter {
6
7
  toAst(text: string): Root;
@@ -16,10 +17,12 @@ interface TwilioAdapterConfig {
16
17
  accountSid?: TwilioCredential;
17
18
  apiUrl?: string;
18
19
  authToken?: TwilioCredential;
20
+ contentApiUrl?: string;
19
21
  fetch?: TwilioFetch;
20
22
  logger?: Logger;
21
23
  messagingServiceSid?: string;
22
24
  phoneNumber?: string;
25
+ rcsSenderId?: string;
23
26
  statusCallbackUrl?: string;
24
27
  userName?: string;
25
28
  webhookUrl?: TwilioWebhookUrl;
@@ -27,28 +30,54 @@ interface TwilioAdapterConfig {
27
30
  }
28
31
  type TwilioRawMessage = TwilioMessageResource | TwilioWebhookPayload;
29
32
 
33
+ declare function encodeTwilioCallbackData(actionId: string, value?: string): string;
34
+ declare function decodeTwilioCallbackData(data?: string): {
35
+ actionId: string;
36
+ value: string | undefined;
37
+ };
38
+
39
+ type TwilioRcsContentResult = {
40
+ contentBody: TwilioContentBody;
41
+ type: "content";
42
+ } | {
43
+ text: string;
44
+ type: "text";
45
+ };
46
+ interface TwilioContentBody {
47
+ friendly_name?: string;
48
+ language: string;
49
+ types: Record<string, unknown>;
50
+ variables?: Record<string, string>;
51
+ }
52
+
30
53
  declare function cardToTwilioText(card: CardElement): string;
54
+ declare function cardToTwilioRcs(card: CardElement): TwilioRcsContentResult;
31
55
 
32
56
  declare class TwilioAdapter implements Adapter<TwilioThreadId, TwilioRawMessage> {
33
57
  readonly name = "twilio";
34
- readonly lockScope: "channel";
58
+ readonly lockScope: "thread";
35
59
  readonly persistThreadHistory = true;
36
60
  readonly userName: string;
37
61
  protected chat: ChatInstance | null;
38
62
  protected readonly accountSid?: TwilioAdapterConfig["accountSid"];
39
63
  protected readonly apiUrl?: string;
40
64
  protected readonly authToken?: TwilioAdapterConfig["authToken"];
65
+ protected readonly contentApiUrl?: string;
41
66
  protected readonly fetch?: TwilioAdapterConfig["fetch"];
42
67
  protected readonly formatConverter: TwilioFormatConverter;
43
68
  protected readonly logger: Logger;
44
69
  protected readonly messagingServiceSid?: string;
45
70
  protected readonly phoneNumber?: string;
71
+ protected readonly rcsSenderId?: string;
46
72
  protected readonly statusCallbackUrl?: string;
47
73
  protected readonly webhookUrl?: TwilioAdapterConfig["webhookUrl"];
48
74
  protected readonly webhookVerifier?: TwilioAdapterConfig["webhookVerifier"];
49
75
  constructor(config?: TwilioAdapterConfig);
50
76
  initialize(chat: ChatInstance): Promise<void>;
51
77
  handleWebhook(request: Request, options?: WebhookOptions): Promise<Response>;
78
+ protected handleButtonAction(payload: TwilioWebhookPayload & {
79
+ kind: "action";
80
+ }, options?: WebhookOptions): void;
52
81
  postMessage(threadId: string, message: AdapterPostableMessage): Promise<RawMessage<TwilioRawMessage>>;
53
82
  editMessage(): Promise<RawMessage<TwilioRawMessage>>;
54
83
  deleteMessage(_threadId: string, messageId: string): Promise<void>;
@@ -76,9 +105,14 @@ declare class TwilioAdapter implements Adapter<TwilioThreadId, TwilioRawMessage>
76
105
  protected twilioAttachment(media: TwilioMediaPayload): Attachment;
77
106
  protected apiOptions(): TwilioApiOptions;
78
107
  protected defaultSender(): string;
108
+ protected inboundThreadSender(payload: {
109
+ channelMetadata?: TwilioChannelMetadata;
110
+ messagingServiceSid?: string;
111
+ to: string;
112
+ }): string;
79
113
  protected author(userId: string, isMe: boolean): Message["author"];
80
114
  protected threadIdForResource(raw: TwilioMessageResource, fallback: TwilioThreadId): string;
81
115
  }
82
116
  declare function createTwilioAdapter(config?: TwilioAdapterConfig): TwilioAdapter;
83
117
 
84
- export { TwilioAdapter, type TwilioAdapterConfig, TwilioFormatConverter, type TwilioRawMessage, type TwilioThreadId, cardToTwilioText, createTwilioAdapter };
118
+ export { TwilioAdapter, type TwilioAdapterConfig, TwilioChannelMetadata, type TwilioContentBody, TwilioFormatConverter, type TwilioRawMessage, type TwilioRcsContentResult, type TwilioThreadId, cardToTwilioRcs, cardToTwilioText, createTwilioAdapter, decodeTwilioCallbackData, encodeTwilioCallbackData };
@@ -1 +1,5 @@
1
- import{C as e,Et as t,Ft as n,Mt as r,b as i,bt as a,kt as o,tt as s,u as c}from"../../_chunks/node/dist-Da54NuK8.js";import{a as l,d as u,f as d,i as f,u as p}from"../../_chunks/node/dist-CweJdVFE.js";import{n as m,r as h,t as g}from"../../_chunks/node/chunk-PFJ2G64A-B79fSABi.js";import{a as _,l as v,o as y,r as b,s as x}from"../../_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js";import{a as S,n as C,r as w}from"../../_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js";function T(e){return l(e).replace(/\*/g,``)}var E=class extends s{toAst(e){return t(e)}fromAst(e){let t=n(structuredClone(e),e=>a(e)?{type:`code`,value:r(e)}:e);return o(t).trim()}renderPostable(e){return typeof e==`string`?e:`raw`in e?e.raw:`markdown`in e?this.fromMarkdown(e.markdown):`ast`in e?this.fromAst(e.ast):super.renderPostable(e)}};function D(e){return`twilio:${encodeURIComponent(e.sender)}:${encodeURIComponent(e.recipient)}`}function O(e){let[t,n,r]=e.split(`:`);if(t!==`twilio`||!n||!r)throw new f(`twilio`,`Invalid Twilio thread ID: ${e}`);return{recipient:decodeURIComponent(r),sender:decodeURIComponent(n)}}function k(e){let t=O(e);return`twilio:${encodeURIComponent(t.sender)}`}function A(){return new Response(`<Response></Response>`,{headers:{"content-type":`application/xml`},status:200})}function j(e){return e.startsWith(`MG`)?{messagingServiceSid:e}:{from:e}}function M(e){return e?.startsWith(`image/`)?`image`:e?.startsWith(`video/`)?`video`:e?.startsWith(`audio/`)?`audio`:`file`}var N=class{name=`twilio`;lockScope=`channel`;persistThreadHistory=!0;userName;chat=null;accountSid;apiUrl;authToken;fetch;formatConverter=new E;logger;messagingServiceSid;phoneNumber;statusCallbackUrl;webhookUrl;webhookVerifier;constructor(e={}){this.accountSid=e.accountSid,this.apiUrl=e.apiUrl,this.authToken=e.authToken,this.fetch=e.fetch,this.logger=e.logger??new c(`info`).child(`twilio`),this.messagingServiceSid=e.messagingServiceSid??process.env.TWILIO_MESSAGING_SERVICE_SID,this.phoneNumber=e.phoneNumber??process.env.TWILIO_PHONE_NUMBER,this.statusCallbackUrl=e.statusCallbackUrl,this.userName=e.userName??`bot`,this.webhookUrl=e.webhookUrl,this.webhookVerifier=e.webhookVerifier}async initialize(e){this.chat=e,this.logger.info(`Twilio adapter initialized`,{messagingServiceSid:this.messagingServiceSid,phoneNumber:this.phoneNumber})}async handleWebhook(e,t){let n;try{n=await S(e,{authToken:this.authToken,webhookUrl:this.webhookUrl,webhookVerifier:this.webhookVerifier})}catch(e){if(e instanceof w)return new Response(`Invalid signature`,{status:401});if(e instanceof C)return new Response(`Invalid webhook`,{status:400});throw e}if(n.kind!==`text`||!this.chat)return A();let r=this.encodeThreadId({recipient:n.from,sender:n.to}),i=this.parseTwilioTextPayload(n,r);return this.chat.processMessage(this,r,i,t),A()}async postMessage(e,t){let n=this.decodeThreadId(e),r=this.renderPostableText(t),i=this.mediaUrls(t);if(!r&&i.length===0)throw new f(`twilio`,`Message text cannot be empty`);let a=await v({...this.apiOptions(),body:r||i.length===0?h(r):void 0,mediaUrl:i,statusCallbackUrl:this.statusCallbackUrl,to:n.recipient,...j(n.sender)});return{id:a.sid,raw:a,threadId:this.threadIdForResource(a,n)}}async editMessage(){throw new e(`Twilio does not support editing sent messages`,`editMessage`)}async deleteMessage(e,t){await b({...this.apiOptions(),messageSid:t})}async addReaction(){throw new e(`Twilio does not support message reactions`,`addReaction`)}async removeReaction(){throw new e(`Twilio does not support message reactions`,`removeReaction`)}async startTyping(){}parseMessage(e){if(F(e)){if(e.kind!==`text`)throw new f(`twilio`,`Cannot parse unsupported webhook`);return this.parseTwilioTextPayload(e,this.encodeThreadId({recipient:e.from,sender:e.to}))}return this.parseTwilioResource(e,void 0)}async fetchMessage(e,t){let n=this.decodeThreadId(e);try{let e=await y({...this.apiOptions(),messageSid:t});return this.parseTwilioResource(e,n)}catch{return null}}async fetchMessages(e,t={}){let n=this.decodeThreadId(e),r=t.limit??50,[i,a]=await Promise.all([x({...this.apiOptions(),from:n.sender,limit:r,to:n.recipient}),x({...this.apiOptions(),from:n.recipient,limit:r,to:n.sender})]);return{messages:[...i,...a].map(e=>this.parseTwilioResource(e,n)).sort((e,t)=>e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()).slice(-r)}}async fetchThread(e){let t=this.decodeThreadId(e);return{channelId:this.channelIdFromThreadId(e),channelName:t.sender,id:e,isDM:!0,metadata:{...t}}}async getUser(e){return{fullName:e,isBot:!1,userId:e,userName:e}}async openDM(e){return this.encodeThreadId({recipient:e,sender:this.defaultSender()})}isDM(e){return e.startsWith(`twilio:`)}channelIdFromThreadId(e){return k(e)}encodeThreadId(e){return D(e)}decodeThreadId(e){return O(e)}renderFormatted(e){return this.formatConverter.fromAst(e)}rehydrateAttachment(e){let t=e.fetchMetadata?.twilioMediaUrl??e.url;return t?this.twilioAttachment({contentType:e.mimeType,url:t}):e}parseTwilioTextPayload(e,t){return new i({attachments:e.media.map(e=>this.twilioAttachment(e)),author:this.author(e.from,!1),formatted:this.formatConverter.toAst(e.body),id:e.messageSid??`twilio:${Date.now()}`,metadata:{dateSent:new Date,edited:!1},raw:e,text:e.body,threadId:t})}parseTwilioResource(e,t){let n=e.direction?.startsWith(`outbound`)??!1,r=e.from??e.messaging_service_sid??(n?t?.sender:t?.recipient),a=e.to??(n?t?.recipient:t?.sender);if(!(r&&a))throw new f(`twilio`,`Twilio message is missing routing`);let o=e.body??``,s=n?{recipient:t?.recipient??a,sender:t?.sender??r}:{recipient:r,sender:a};return new i({attachments:[],author:this.author(n?s.sender:r,n),formatted:this.formatConverter.toAst(o),id:e.sid,metadata:{dateSent:I(e.date_sent??e.date_created),edited:!1},raw:e,text:o,threadId:this.encodeThreadId(s)})}renderPostableText(e){let t=p(e),n=t?T(t):this.formatConverter.renderPostable(e);return m(n,{limit:g}).text}mediaUrls(e){if(u(e).length>0)throw new f(`twilio`,`Twilio adapter supports media attachments by public URL only`);let t=d(e),n=[];for(let e of t){if(typeof e.url!=`string`||e.url.length===0)throw new f(`twilio`,`Twilio adapter supports media attachments by public URL only`);n.push(e.url)}return n}twilioAttachment(e){return{fetchData:async()=>Buffer.from(await _({...this.apiOptions(),url:e.url})),fetchMetadata:{twilioMediaUrl:e.url},mimeType:e.contentType,type:M(e.contentType),url:e.url}}apiOptions(){return{apiUrl:this.apiUrl,credentials:{accountSid:this.accountSid,authToken:this.authToken},fetch:this.fetch}}defaultSender(){let e=this.phoneNumber??this.messagingServiceSid;if(!e)throw new f(`twilio`,`phoneNumber or messagingServiceSid is required`);return e}author(e,t){return{fullName:e,isBot:t,isMe:t,userId:e,userName:e}}threadIdForResource(e,t){return this.parseTwilioResource(e,t).threadId}};function P(e={}){return new N(e)}function F(e){return`kind`in e}function I(e){let t=e?new Date(e):new Date;return Number.isNaN(t.getTime())?new Date:t}export{N as TwilioAdapter,E as TwilioFormatConverter,T as cardToTwilioText,P as createTwilioAdapter};
1
+ import{At as e,It as t,Nt as n,X as r,Y as i,at as a,q as o,wt as s,zt as c}from"../../_chunks/node/dist-DYDVZ-FS.js";import{a as ee,d as l,f as te,i as u,p as ne}from"../../_chunks/node/dist-iEFkK9qw.js";import{n as re,r as ie,t as d}from"../../_chunks/node/chunk-PFJ2G64A-B79fSABi.js";import{c as f,i as p,l as m,o as ae,r as oe,s as h,u as g}from"../../_chunks/node/chunk-KBOOTKHF-DJqFk2r1.js";import{a as _,c as v,d as y,f as b,i as x,l as S,n as C,o as w,r as T,s as E}from"../../_chunks/node/chunk-TREVQR3E-CLsTAn-O.js";import{createHash as se}from"crypto";var ce=`https://content.twilio.com`,le=50,ue=20,de=200,fe=/^twilio\//,D=new Map;function pe(e,t,n){return`${e}:${t}:${A(n)}`}function O(e,t){if(D.delete(e),D.set(e,t),D.size>de){let e=D.keys().next().value;e!==void 0&&D.delete(e)}}function k(e){return e.contentApiUrl??e.apiUrl??e.apiBaseUrl??ce}function A(e){let{language:t,types:n,variables:r}=e;return se(`sha256`).update(JSON.stringify({language:t,types:n,variables:r??null})).digest(`hex`)}function j(e){return`chat_sdk_${Object.keys(e.types).find(e=>e.startsWith(`twilio/`))?.replace(fe,``)??`text`}_${A(e).slice(0,16)}`}async function M(e){let t=pe(await m(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),k(e),e.contentBody),n=D.get(t);if(n)return{friendly_name:j(e.contentBody),sid:n};let r=j(e.contentBody),i=await I(e,r);if(i?.sid)return O(t,i.sid),i;let a={...e.contentBody,friendly_name:r};try{let n=await N({...e,contentBody:a});return O(t,n.sid),n}catch(n){if(!F(n))throw n;let i=await I(e,r);if(!i?.sid)throw n;return O(t,i.sid),i}}async function N(e){let t=await m(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),n=await m(e.credentials?.authToken,`TWILIO_AUTH_TOKEN`),r=new URL(`/v1/Content`,k(e)),i=await(e.fetch??fetch)(r,{body:JSON.stringify(e.contentBody),headers:{authorization:`Basic ${p(`${t}:${n}`)}`,"content-type":`application/json`},method:`POST`}),a=await i.text(),o;try{o=JSON.parse(a)}catch{o=a}if(!i.ok)throw new P(`Content API returned HTTP ${i.status}: ${typeof o==`string`?o:JSON.stringify(o)}`,i.status,o);return o}var P=class extends Error{status;body;constructor(e,t,n){super(e),this.name=`TwilioContentApiError`,this.status=t,this.body=n}};function F(e){if(!(e instanceof P))return!1;if(e.status===409)return!0;let t=typeof e.body==`object`&&e.body!==null&&`message`in e.body&&typeof e.body.message==`string`?e.body.message.toLowerCase():e.message.toLowerCase();return t.includes(`friendly`)&&t.includes(`exist`)}async function I(e,t){let n=await m(e.credentials?.accountSid,`TWILIO_ACCOUNT_SID`),r=await m(e.credentials?.authToken,`TWILIO_AUTH_TOKEN`),i=new URL(`/v1/Content`,k(e));i.searchParams.set(`PageSize`,String(le));let a=e.fetch??fetch,o=`Basic ${p(`${n}:${r}`)}`,s=0;for(;i&&s<ue;){s+=1;let e=await a(i,{headers:{authorization:o},method:`GET`}),n=await e.text(),r;try{r=JSON.parse(n)}catch{return null}if(!e.ok)return null;let c=r.contents?.find(e=>e.friendly_name===t);if(c)return c;i=r.meta?.next_page_url??null}return null}var L=11,R=25,z=200,B=2,V=`Message from bot`;function H(e){return ee(e).replace(/\*/g,``)}function U(e){let t=G(e.children);if(!t)return{text:H(e),type:`text`};let n=_e(t),r=ve(t);return n.length>0?e.imageUrl||e.title||r.length>0?he(e,n,r):me(e,n):r.length>0?ge(e,r):{text:H(e),type:`text`}}function me(e,t){return{type:`content`,contentBody:{language:`en`,types:{"twilio/quick-reply":{body:K(e)||e.title||`Choose an option`,actions:t.slice(0,L).map(e=>({id:_(e.id,e.value),title:J(e.label,R),type:`quick_reply`}))},"twilio/text":{body:W(e)}}}}}function he(e,t,n){let r=[...t.map(e=>({id:_(e.id,e.value),title:J(e.label,R),type:`quick_reply`})),...n.map(e=>({title:J(e.label,R),type:`URL`,url:e.url}))].slice(0,L),i={title:J(e.title??`Menu`,z),body:K(e)||e.subtitle||` `,actions:r};return e.imageUrl&&(i.media=[e.imageUrl]),{type:`content`,contentBody:{language:`en`,types:{"twilio/card":i,"twilio/text":{body:W(e)}}}}}function ge(e,t){let n=t.slice(0,B),r=t.slice(B);return{type:`content`,contentBody:{language:`en`,types:{"twilio/call-to-action":{body:[K(e)||e.title||`See link`,...r.map(e=>`${e.label}: ${e.url}`)].join(`
2
+ `),actions:n.map(e=>({title:J(e.label,R),type:`URL`,url:e.url}))},"twilio/text":{body:W(e)}}}}}function W(e){return H(e)||V}function G(e){for(let t of e){if(t.type===`actions`)return t;if(t.type===`section`){let e=G(t.children);if(e)return e}}return null}function _e(e){let t=[];for(let n of e.children)n.type===`button`&&n.id&&t.push(n);return t.slice(0,L)}function ve(e){let t=[];for(let n of e.children)n.type===`link-button`&&t.push(n);return t}function K(e){let t=[];e.subtitle&&t.push(e.subtitle);for(let n of e.children){if(n.type===`actions`)continue;let e=q(n);e&&t.push(e)}return t.join(`
3
+ `)}function q(e){switch(e.type){case`text`:return e.content;case`fields`:return e.children.map(e=>`${e.label}: ${e.value}`).join(`
4
+ `);case`actions`:return null;case`section`:return e.children.map(q).filter(Boolean).join(`
5
+ `);default:return null}}function J(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}var Y=class extends a{toAst(t){return e(t)}fromAst(e){let r=c(structuredClone(e),e=>s(e)?{type:`code`,value:t(e)}:e);return n(r).trim()}renderPostable(e){return typeof e==`string`?e:`raw`in e?e.raw:`markdown`in e?this.fromMarkdown(e.markdown):`ast`in e?this.fromAst(e.ast):super.renderPostable(e)}};function ye(e){return`twilio:${encodeURIComponent(e.sender)}:${encodeURIComponent(e.recipient)}`}function X(e){let[t,n,r]=e.split(`:`);if(t!==`twilio`||!n||!r)throw new u(`twilio`,`Invalid Twilio thread ID: ${e}`);return{recipient:decodeURIComponent(r),sender:decodeURIComponent(n)}}function be(e){return X(e),e}function Z(){return new Response(`<Response></Response>`,{headers:{"content-type":`application/xml`},status:200})}function Q(e){return e.startsWith(`MG`)?{messagingServiceSid:e}:{from:e}}function xe(e){return e?.startsWith(`image/`)?`image`:e?.startsWith(`video/`)?`video`:e?.startsWith(`audio/`)?`audio`:`file`}var $=class{name=`twilio`;lockScope=`thread`;persistThreadHistory=!0;userName;chat=null;accountSid;apiUrl;authToken;contentApiUrl;fetch;formatConverter=new Y;logger;messagingServiceSid;phoneNumber;rcsSenderId;statusCallbackUrl;webhookUrl;webhookVerifier;constructor(e={}){this.accountSid=e.accountSid,this.apiUrl=e.apiUrl,this.authToken=e.authToken,this.contentApiUrl=e.contentApiUrl,this.fetch=e.fetch,this.logger=e.logger??new o(`info`).child(`twilio`),this.messagingServiceSid=e.messagingServiceSid??process.env.TWILIO_MESSAGING_SERVICE_SID,this.phoneNumber=e.phoneNumber??process.env.TWILIO_PHONE_NUMBER,this.rcsSenderId=e.rcsSenderId??process.env.TWILIO_RCS_SENDER_ID,this.statusCallbackUrl=e.statusCallbackUrl,this.userName=e.userName??`bot`,this.webhookUrl=e.webhookUrl,this.webhookVerifier=e.webhookVerifier}async initialize(e){this.chat=e,this.logger.info(`Twilio adapter initialized`,{messagingServiceSid:this.messagingServiceSid,phoneNumber:this.phoneNumber})}async handleWebhook(e,t){let n;try{n=await y(e,{authToken:this.authToken,webhookUrl:this.webhookUrl,webhookVerifier:this.webhookVerifier})}catch(e){if(e instanceof T)return new Response(`Invalid signature`,{status:401});if(e instanceof C)return new Response(`Invalid webhook`,{status:400});throw e}if(!this.chat)return Z();if(n.kind===`action`)return this.handleButtonAction(n,t),Z();if(n.kind===`text`){let e=this.encodeThreadId({recipient:n.from,sender:this.inboundThreadSender(n)}),r=this.parseTwilioTextPayload(n,e);return this.chat.processMessage(this,e,r,t),Z()}return n.kind===`status`&&n.eventType&&this.logger.debug(`Twilio status event`,{eventType:n.eventType,messageSid:n.messageSid,channelPrefix:n.channelPrefix}),Z()}handleButtonAction(e,t){if(!this.chat)return;let n=this.encodeThreadId({recipient:e.from,sender:this.inboundThreadSender(e)}),{actionId:r,value:i}=x(e.buttonPayload);this.chat.processAction({adapter:this,actionId:r,value:i??e.buttonText,messageId:e.messageSid??`action:${Date.now()}`,threadId:n,user:{userId:e.from,userName:e.from,fullName:e.from,isBot:!1,isMe:!1},raw:e},t)}async postMessage(e,t){let n=this.decodeThreadId(e),r=l(t);if(r&&v(n.sender)){let e=U(r);if(e.type===`content`){let t;try{t=(await M({...this.apiOptions(),contentApiUrl:this.contentApiUrl,contentBody:e.contentBody})).sid}catch(e){this.logger.warn(`RCS content template resolution failed, falling back to text`,{error:String(e)})}if(t){let e=await g({...this.apiOptions(),contentSid:t,statusCallbackUrl:this.statusCallbackUrl,to:n.recipient,...Q(n.sender)});return{id:e.sid,raw:e,threadId:this.threadIdForResource(e,n)}}}}let i=this.renderPostableText(t),a=this.mediaUrls(t);if(!i&&a.length===0)throw new u(`twilio`,`Message text cannot be empty`);let o=await g({...this.apiOptions(),body:i||a.length===0?ie(i):void 0,mediaUrl:a,statusCallbackUrl:this.statusCallbackUrl,to:n.recipient,...Q(n.sender)});return{id:o.sid,raw:o,threadId:this.threadIdForResource(o,n)}}async editMessage(){throw new r(`Twilio does not support editing sent messages`,`editMessage`)}async deleteMessage(e,t){await oe({...this.apiOptions(),messageSid:t})}async addReaction(){throw new r(`Twilio does not support message reactions`,`addReaction`)}async removeReaction(){throw new r(`Twilio does not support message reactions`,`removeReaction`)}async startTyping(){}parseMessage(e){if(we(e)){if(e.kind===`action`)throw new u(`twilio`,`Cannot parse action webhook as message`);if(e.kind!==`text`)throw new u(`twilio`,`Cannot parse unsupported webhook`);return this.parseTwilioTextPayload(e,this.encodeThreadId({recipient:e.from,sender:this.inboundThreadSender(e)}))}return this.parseTwilioResource(e,void 0)}async fetchMessage(e,t){let n=this.decodeThreadId(e);try{let e=await h({...this.apiOptions(),messageSid:t});return this.parseTwilioResource(e,n)}catch{return null}}async fetchMessages(e,t={}){let n=this.decodeThreadId(e),r=t.limit??50,[i,a]=await Promise.all([f({...this.apiOptions(),from:n.sender,limit:r,to:n.recipient}),f({...this.apiOptions(),from:n.recipient,limit:r,to:n.sender})]);return{messages:[...i,...a].map(e=>this.parseTwilioResource(e,n)).sort((e,t)=>e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()).slice(-r)}}async fetchThread(e){let t=this.decodeThreadId(e);return{channelId:this.channelIdFromThreadId(e),channelName:t.sender,id:e,isDM:!0,metadata:{...t}}}async getUser(e){return{fullName:e,isBot:!1,userId:e,userName:e}}async openDM(e){return this.encodeThreadId({recipient:e,sender:this.defaultSender()})}isDM(e){return e.startsWith(`twilio:`)}channelIdFromThreadId(e){return be(e)}encodeThreadId(e){return ye(e)}decodeThreadId(e){return X(e)}renderFormatted(e){return this.formatConverter.fromAst(e)}rehydrateAttachment(e){let t=e.fetchMetadata?.twilioMediaUrl??e.url;return t&&Ce.test(t)?this.twilioAttachment({contentType:e.mimeType,url:t}):e}parseTwilioTextPayload(e,t){let n=e.media.map(e=>this.twilioAttachment(e));if(e.latitude&&e.longitude){let t={latitude:e.latitude,longitude:e.longitude};e.address&&(t.address=e.address),e.label&&(t.label=e.label),n.push({fetchMetadata:t,type:`file`,url:`geo:${e.latitude},${e.longitude}`})}return new i({attachments:n,author:this.author(e.from,!1),formatted:this.formatConverter.toAst(e.body),id:e.messageSid??`twilio:${Date.now()}`,metadata:{dateSent:new Date,edited:!1},raw:e,text:e.body,threadId:t})}parseTwilioResource(e,t){let n=e.direction?.startsWith(`outbound`)??!1,r=e.from??e.messaging_service_sid??(n?t?.sender:t?.recipient),a=e.to??(n?t?.recipient:t?.sender);if(!(r&&a))throw new u(`twilio`,`Twilio message is missing routing`);let o=e.body??``,s=n?{recipient:t?.recipient??a,sender:t?.sender??r}:{recipient:r,sender:a};return new i({attachments:[],author:this.author(n?s.sender:r,n),formatted:this.formatConverter.toAst(o),id:e.sid,metadata:{dateSent:Te(e.date_sent??e.date_created),edited:!1},raw:e,text:o,threadId:this.encodeThreadId(s)})}renderPostableText(e){let t=l(e),n=t?H(t)||V:this.formatConverter.renderPostable(e);return re(n,{limit:d}).text}mediaUrls(e){if(te(e).length>0)throw new u(`twilio`,`Twilio adapter supports media attachments by public URL only`);let t=ne(e),n=[];for(let e of t){if(typeof e.url!=`string`||e.url.length===0)throw new u(`twilio`,`Twilio adapter supports media attachments by public URL only`);n.push(e.url)}return n}twilioAttachment(e){return{fetchData:async()=>Buffer.from(await ae({...this.apiOptions(),url:e.url})),fetchMetadata:{twilioMediaUrl:e.url},mimeType:e.contentType,type:xe(e.contentType),url:e.url}}apiOptions(){return{apiUrl:this.apiUrl,credentials:{accountSid:this.accountSid,authToken:this.authToken},fetch:this.fetch}}defaultSender(){let e=this.phoneNumber??this.messagingServiceSid??(this.rcsSenderId?S(this.rcsSenderId):void 0);if(!e)throw new u(`twilio`,`phoneNumber, messagingServiceSid, or rcsSenderId is required`);return e}inboundThreadSender(e){return b({channelMetadata:e.channelMetadata,messagingServiceSid:e.messagingServiceSid,messagingServiceSidConfig:this.messagingServiceSid,rcsSenderIdConfig:this.rcsSenderId,to:e.to})}author(e,t){return{fullName:e,isBot:t,isMe:t,userId:e,userName:e}}threadIdForResource(e,t){return this.parseTwilioResource(e,t).threadId}};function Se(e={}){return new $(e)}var Ce=/^https?:\/\//;function we(e){return`kind`in e}function Te(e){let t=e?new Date(e):new Date;return Number.isNaN(t.getTime())?new Date:t}export{$ as TwilioAdapter,Y as TwilioFormatConverter,U as cardToTwilioRcs,H as cardToTwilioText,Se as createTwilioAdapter,x as decodeTwilioCallbackData,_ as encodeTwilioCallbackData,w as inferTwilioChannel,E as isRcsAddress,v as isRcsCapableSender,S as normalizeRcsSenderId,b as resolveInboundThreadSender};
@@ -1,5 +1,5 @@
1
- import { T as TwilioWebhookPayload, a as TwilioWebhookUrl, d as TwilioVerifyOptions, e as TwilioVerifiedRequest, f as TwilioReadOptions } from './types-WYjTBVDi.js';
2
- export { g as TwilioHeaderValue, h as TwilioHeaders, c as TwilioMediaPayload, i as TwilioStatusPayload, j as TwilioTextPayload, k as TwilioUnsupportedPayload, l as TwilioWebhookError, m as TwilioWebhookParseError, n as TwilioWebhookVerificationError, b as TwilioWebhookVerifier } from './types-WYjTBVDi.js';
1
+ import { T as TwilioWebhookPayload, a as TwilioWebhookUrl, h as TwilioVerifyOptions, j as TwilioVerifiedRequest, k as TwilioReadOptions } from './types-BaIqtt65.js';
2
+ export { l as TwilioActionPayload, m as TwilioHeaderValue, o as TwilioHeaders, c as TwilioMediaPayload, p as TwilioStatusPayload, q as TwilioTextPayload, s as TwilioUnsupportedPayload, t as TwilioWebhookError, u as TwilioWebhookParseError, v as TwilioWebhookVerificationError, b as TwilioWebhookVerifier } from './types-BaIqtt65.js';
3
3
  import './api.js';
4
4
 
5
5
  declare function parseTwilioWebhookBody(params: URLSearchParams): TwilioWebhookPayload;
@@ -1 +1 @@
1
- import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"../../_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js";export{c as TwilioWebhookError,i as TwilioWebhookParseError,o as TwilioWebhookVerificationError,n as parseTwilioWebhookBody,e as readTwilioWebhook,a as resolveTwilioWebhookUrl,s as signTwilioRequest,t as twilioSignatureBase,r as verifyTwilioRequest};
1
+ import{d as e,g as t,h as n,m as r,n as i,p as a,r as o,t as s,u as c}from"../../_chunks/node/chunk-TREVQR3E-CLsTAn-O.js";export{s as TwilioWebhookError,i as TwilioWebhookParseError,o as TwilioWebhookVerificationError,c as parseTwilioWebhookBody,e as readTwilioWebhook,a as resolveTwilioWebhookUrl,r as signTwilioRequest,n as twilioSignatureBase,t as verifyTwilioRequest};
@@ -1,8 +1,8 @@
1
- import{t as e}from"../../_chunks/node/rolldown-runtime-tZXQYakl.js";import{B as t,C as n,Et as r,K as i,Pt as a,b as o,jt as s,kt as c,q as l,tt as u,u as d,wt as f}from"../../_chunks/node/dist-Da54NuK8.js";function p(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function m(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let h=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return h=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(+e^n()&15>>e/4).toString(16))};function g(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const _=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var v=class extends Error{},y=class e extends v{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n;let a=n;this.code=a?.code,this.doc_url=a?.doc_url,this.retry_after=a?.retry_after}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new x({message:r,cause:_(n)});let a=n?.error;return t===400?new C(t,a,r,i):t===401?new w(t,a,r,i):t===403?new T(t,a,r,i):t===404?new E(t,a,r,i):t===409?new D(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},b=class extends y{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},x=class extends y{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},S=class extends x{constructor({message:e}={}){super({message:e??`Request timed out.`})}},C=class extends y{},w=class extends y{},T=class extends y{},E=class extends y{},D=class extends y{},ee=class extends y{},te=class extends y{},ne=class extends y{};const re=/^[a-z][a-z0-9+.-]*:/i,ie=e=>re.test(e);let O=e=>(O=Array.isArray,O(e)),ae=O;function oe(e){return typeof e==`object`?e??{}:{}}function se(e){if(!e)return!0;for(let t in e)return!1;return!0}function ce(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const le=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new v(`${e} must be an integer`);if(t<0)throw new v(`${e} must be a positive integer`);return t},ue=e=>{try{return JSON.parse(e)}catch{return}},de=e=>new Promise(t=>setTimeout(t,e)),k=`0.47.1`;function fe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const pe=()=>{let e=fe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(Deno.build.os),"X-Stainless-Arch":he(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(globalThis.process.platform??`unknown`),"X-Stainless-Arch":he(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=me();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function me(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const he=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ge=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let _e;const ve=()=>_e??=pe();function ye(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new LinqAPIV3({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function be(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function xe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function Se(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ce=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),we=`RFC3986`,Te=e=>String(e),Ee={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Te};let A=(e,t)=>(A=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),A(e,t));const j=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),M=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=M){let t=a.length>=M?a.slice(e,e+M):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=j[r];continue}if(r<2048){n[n.length]=j[192|r>>6]+j[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=j[224|r>>12]+j[128|r>>6&63]+j[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=j[240|r>>18]+j[128|r>>12&63]+j[128|r>>6&63]+j[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(O(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,O(t)?t:[t])};let Me;const N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:we,formatter:Te,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const P={};function Pe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(P))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(P)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&O(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,N.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,N.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,N.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let C;if(n===`comma`&&O(v))h&&c&&(v=ke(v,c)),C=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(O(l))C=l;else{let e=Object.keys(v);C=u?e.sort(u):e}let w=s?String(t).replace(/\./g,`%2E`):String(t),T=r&&O(v)&&v.length===1?w+`[]`:w;if(i&&O(v)&&v.length===0)return T+`[]`;for(let t=0;t<C.length;++t){let y=C[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let w=d&&s?y.replace(/\./g,`%2E`):y,E=O(v)?typeof n==`function`?n(T,w):T:T+(d?`.`+w:`[`+w+`]`);_.set(e,b);let D=new WeakMap;D.set(P,_),je(S,Pe(x,E,n,r,i,a,o,s,n===`comma`&&h&&O(v)?null:c,l,u,d,f,p,m,h,g,D))}return S}function Fe(e=N){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||N.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=we;if(e.format!==void 0){if(!A(Ee,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Ee[n],i=N.filter;(typeof e.filter==`function`||O(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:N.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:N.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?N.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:N.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:N.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:N.strictNullHandling}}function Ie(e,t={}){let n=e,r=Fe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):O(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Pe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Le(e){return Ie(e,{arrayFormat:`comma`})}const F={off:0,error:200,warn:300,info:400,debug:500},Re=(e,t,n)=>{if(e){if(ce(F,e))return e;R(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(F))}`)}};function I(){}function L(e,t,n){return!t||F[e]>F[n]?I:t[e].bind(t)}const ze={error:I,warn:I,info:I,debug:I};let Be=new WeakMap;function R(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return ze;let r=Be.get(t);if(r&&r[0]===n)return r[1];let i={error:L(`error`,t,n),warn:L(`warn`,t,n),info:L(`info`,t,n),debug:L(`debug`,t,n)};return Be.set(t,[n,i]),i}const z=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Ve(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return R(e).debug(`[${r}] response parsed`,z({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var B,He=class e extends Promise{constructor(e,t,n=Ve){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,B.set(this,void 0),p(this,B,e,`f`)}_thenUnwrap(t){return new e(m(this,B,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(m(this,B,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};B=new WeakMap;var V,Ue=class{constructor(e,t,n,r){V.set(this,void 0),p(this,V,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await m(this,V,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(V=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},We=class extends He{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Ve(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Ge=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.chats=n.chats||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.chats??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}},Ke=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.messages=n.messages||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.messages??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}};const qe=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function H(e,t,n){return qe(),new File(e,t??`unknown_file`,n)}function Je(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Ye=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Xe=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ze=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Xe(e),Qe=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $e(e,t,n){if(qe(),e=await e,Ze(e))return e instanceof File?e:H([await e.arrayBuffer()],e.name);if(Qe(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),H(await U(r),t,n)}let r=await U(e);if(t||=Je(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return H(r,t,n)}async function U(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Xe(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ye(e))for await(let n of e)t.push(...await U(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${et(e)}`)}return t}function et(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var W=class{constructor(e){this._client=e}};const tt=Symbol(`brand.privateNullableHeaders`);function*nt(e){if(!e)return;if(tt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ae(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ae(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const G=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of nt(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[tt]:!0,values:t,nulls:n}};function rt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const it=Object.freeze(Object.create(null)),K=((e=rt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??it)??it)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new v(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
1
+ import{t as e}from"../../_chunks/node/rolldown-runtime-tZXQYakl.js";import{At as t,Ft as n,L as r,N as i,Nt as a,Ot as o,R as s,Rt as c,X as l,Y as u,at as d,q as f}from"../../_chunks/node/dist-DYDVZ-FS.js";function p(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function m(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let h=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return h=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(+e^n()&15>>e/4).toString(16))};function g(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const _=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var v=class extends Error{},y=class e extends v{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n;let a=n;this.code=a?.code,this.doc_url=a?.doc_url,this.retry_after=a?.retry_after}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new x({message:r,cause:_(n)});let a=n?.error;return t===400?new C(t,a,r,i):t===401?new w(t,a,r,i):t===403?new T(t,a,r,i):t===404?new E(t,a,r,i):t===409?new D(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},b=class extends y{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},x=class extends y{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},S=class extends x{constructor({message:e}={}){super({message:e??`Request timed out.`})}},C=class extends y{},w=class extends y{},T=class extends y{},E=class extends y{},D=class extends y{},ee=class extends y{},te=class extends y{},ne=class extends y{};const re=/^[a-z][a-z0-9+.-]*:/i,ie=e=>re.test(e);let O=e=>(O=Array.isArray,O(e)),ae=O;function oe(e){return typeof e==`object`?e??{}:{}}function se(e){if(!e)return!0;for(let t in e)return!1;return!0}function ce(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const le=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new v(`${e} must be an integer`);if(t<0)throw new v(`${e} must be a positive integer`);return t},ue=e=>{try{return JSON.parse(e)}catch{return}},de=e=>new Promise(t=>setTimeout(t,e)),k=`0.47.1`;function fe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const pe=()=>{let e=fe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(Deno.build.os),"X-Stainless-Arch":he(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(globalThis.process.platform??`unknown`),"X-Stainless-Arch":he(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=me();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function me(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const he=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ge=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let _e;const ve=()=>_e??=pe();function ye(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new LinqAPIV3({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function be(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function xe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function Se(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ce=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),we=`RFC3986`,Te=e=>String(e),Ee={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Te};let A=(e,t)=>(A=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),A(e,t));const j=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),M=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=M){let t=a.length>=M?a.slice(e,e+M):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=j[r];continue}if(r<2048){n[n.length]=j[192|r>>6]+j[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=j[224|r>>12]+j[128|r>>6&63]+j[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=j[240|r>>18]+j[128|r>>12&63]+j[128|r>>6&63]+j[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(O(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,O(t)?t:[t])};let Me;const N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:we,formatter:Te,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const P={};function Pe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(P))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(P)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&O(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,N.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,N.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,N.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let C;if(n===`comma`&&O(v))h&&c&&(v=ke(v,c)),C=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(O(l))C=l;else{let e=Object.keys(v);C=u?e.sort(u):e}let w=s?String(t).replace(/\./g,`%2E`):String(t),T=r&&O(v)&&v.length===1?w+`[]`:w;if(i&&O(v)&&v.length===0)return T+`[]`;for(let t=0;t<C.length;++t){let y=C[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let w=d&&s?y.replace(/\./g,`%2E`):y,E=O(v)?typeof n==`function`?n(T,w):T:T+(d?`.`+w:`[`+w+`]`);_.set(e,b);let D=new WeakMap;D.set(P,_),je(S,Pe(x,E,n,r,i,a,o,s,n===`comma`&&h&&O(v)?null:c,l,u,d,f,p,m,h,g,D))}return S}function Fe(e=N){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||N.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=we;if(e.format!==void 0){if(!A(Ee,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Ee[n],i=N.filter;(typeof e.filter==`function`||O(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:N.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:N.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?N.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:N.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:N.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:N.strictNullHandling}}function Ie(e,t={}){let n=e,r=Fe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):O(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Pe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Le(e){return Ie(e,{arrayFormat:`comma`})}const F={off:0,error:200,warn:300,info:400,debug:500},Re=(e,t,n)=>{if(e){if(ce(F,e))return e;R(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(F))}`)}};function I(){}function L(e,t,n){return!t||F[e]>F[n]?I:t[e].bind(t)}const ze={error:I,warn:I,info:I,debug:I};let Be=new WeakMap;function R(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return ze;let r=Be.get(t);if(r&&r[0]===n)return r[1];let i={error:L(`error`,t,n),warn:L(`warn`,t,n),info:L(`info`,t,n),debug:L(`debug`,t,n)};return Be.set(t,[n,i]),i}const z=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Ve(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return R(e).debug(`[${r}] response parsed`,z({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var B,He=class e extends Promise{constructor(e,t,n=Ve){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,B.set(this,void 0),p(this,B,e,`f`)}_thenUnwrap(t){return new e(m(this,B,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(m(this,B,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};B=new WeakMap;var V,Ue=class{constructor(e,t,n,r){V.set(this,void 0),p(this,V,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await m(this,V,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(V=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},We=class extends He{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Ve(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Ge=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.chats=n.chats||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.chats??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}},Ke=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.messages=n.messages||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.messages??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}};const qe=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function H(e,t,n){return qe(),new File(e,t??`unknown_file`,n)}function Je(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Ye=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Xe=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ze=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Xe(e),Qe=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $e(e,t,n){if(qe(),e=await e,Ze(e))return e instanceof File?e:H([await e.arrayBuffer()],e.name);if(Qe(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),H(await U(r),t,n)}let r=await U(e);if(t||=Je(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return H(r,t,n)}async function U(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Xe(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ye(e))for await(let n of e)t.push(...await U(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${et(e)}`)}return t}function et(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var W=class{constructor(e){this._client=e}};const tt=Symbol(`brand.privateNullableHeaders`);function*nt(e){if(!e)return;if(tt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ae(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ae(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const G=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of nt(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[tt]:!0,values:t,nulls:n}};function rt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const it=Object.freeze(Object.create(null)),K=((e=rt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??it)??it)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new v(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
2
2
  `)}\n${a}\n${t}`)}return a})(rt);var at=class extends W{create(e,t){return this._client.post(`/v3/attachments`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/attachments/${e}`,t)}delete(e,t){return this._client.delete(K`/v3/attachments/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},ot=class extends W{retrieve(e={},t){return this._client.get(`/v3/available_number`,{query:e,...t})}},st=class extends W{list(e){return this._client.get(`/v3/blocked_handles`,e)}block(e,t){return this._client.post(`/v3/blocked_handles`,{body:e,...t})}unblock(e,t){return this._client.delete(`/v3/blocked_handles`,{body:e,...t,headers:G([{Accept:`*/*`},t?.headers])})}},ct=class extends W{checkIMessage(e,t){return this._client.post(`/v3/capability/check_imessage`,{body:e,...t})}checkRCS(e,t){return this._client.post(`/v3/capability/check_rcs`,{body:e,...t})}},lt=class extends W{remove(e,t){return this._client.delete(K`/v3/chats/${e}/background`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}set(e,t,n){return this._client.post(K`/v3/chats/${e}/background`,{body:t,...n,headers:G([{Accept:`*/*`},n?.headers])})}},ut=class extends W{retrieve(e,t){return this._client.get(K`/v3/chats/${e}/location`,{...t,headers:G([{Accept:`application/geo+json`},t?.headers])})}request(e,t){return this._client.post(K`/v3/chats/${e}/location/request`,t)}},dt=class extends W{list(e,t={},n){return this._client.getAPIList(K`/v3/chats/${e}/messages`,Ke,{query:t,...n})}send(e,t,n){return this._client.post(K`/v3/chats/${e}/messages`,{body:t,...n})}},ft=class extends W{add(e,t,n){return this._client.post(K`/v3/chats/${e}/participants`,{body:t,...n})}remove(e,t,n){return this._client.delete(K`/v3/chats/${e}/participants`,{body:t,...n})}},pt=class extends W{create(e,t,n){return this._client.post(K`/v3/chats/${e}/polls`,{body:t,...n})}},mt=class extends W{start(e,t){return this._client.post(K`/v3/chats/${e}/typing`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}stop(e,t){return this._client.delete(K`/v3/chats/${e}/typing`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},q=class extends W{constructor(){super(...arguments),this.participants=new ft(this._client),this.typing=new mt(this._client),this.messages=new dt(this._client),this.location=new ut(this._client),this.polls=new pt(this._client),this.background=new lt(this._client)}create(e,t){return this._client.post(`/v3/chats`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/chats/${e}`,t)}update(e,t,n){return this._client.put(K`/v3/chats/${e}`,{body:t,...n})}leaveChat(e,t){return this._client.post(K`/v3/chats/${e}/leave`,t)}listChats(e={},t){return this._client.getAPIList(`/v3/chats`,Ge,{query:e,...t})}markAsRead(e,t){return this._client.post(K`/v3/chats/${e}/read`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}sendVoicememo(e,t,n){return this._client.post(K`/v3/chats/${e}/voicememo`,{body:t,...n})}shareContactCard(e,t){return this._client.post(K`/v3/chats/${e}/share_contact_card`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}};q.Participants=ft,q.Typing=mt,q.Messages=dt,q.Location=ut,q.Polls=pt,q.Background=lt;var ht=class extends W{create(e,t){return this._client.post(`/v3/contact_card`,{body:e,...t})}retrieve(e={},t){return this._client.get(`/v3/contact_card`,{query:e,...t})}update(e,t){let{phone_number:n,...r}=e;return this._client.patch(`/v3/contact_card`,{query:{phone_number:n},body:r,...t})}},gt=class extends W{retrieve(e,t){return this._client.get(K`/v3/experiences/${e}`,t)}list(e){return this._client.get(`/v3/experiences`,e)}},_t=class extends W{retrieve(e,t){return this._client.get(K`/v3/messages/${e}/poll`,t)}addOptions(e,t,n){return this._client.post(K`/v3/messages/${e}/poll/options`,{body:t,...n})}vote(e,t,n){return this._client.post(K`/v3/messages/${e}/poll/votes`,{body:t,...n})}},J=class extends W{constructor(){super(...arguments),this.poll=new _t(this._client)}create(e,t){let{"Idempotency-Key":n,...r}=e;return this._client.post(`/v3/messages`,{body:r,...t,headers:G([{...n==null?void 0:{"Idempotency-Key":n}},t?.headers])})}retrieve(e,t){return this._client.get(K`/v3/messages/${e}`,t)}update(e,t,n){return this._client.patch(K`/v3/messages/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(K`/v3/messages/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}addReaction(e,t,n){return this._client.post(K`/v3/messages/${e}/reactions`,{body:t,...n})}listMessagesThread(e,t={},n){return this._client.getAPIList(K`/v3/messages/${e}/thread`,Ke,{query:t,...n})}updateAppCard(e,t,n){return this._client.post(K`/v3/messages/${e}/update`,{body:t,...n})}};J.Poll=_t;var vt=class extends W{connect(e,t){return this._client.post(K`/v3/payments/handles/${e}/connect`,t)}connection(e,t){return this._client.get(K`/v3/payments/handles/${e}/connection`,t)}revoke(e,t){return this._client.delete(K`/v3/payments/handles/${e}/connection`,t)}verify(e,t,n){return this._client.post(K`/v3/payments/handles/${e}/verify`,{body:t,...n})}},yt=class extends W{retrieve(e,t){return this._client.get(K`/v3/payments/providers/${e}`,t)}connect(e,t,n){return this._client.post(K`/v3/payments/providers/${e}/connect`,{body:t,...n})}},bt=class extends W{create(e,t){let{"Idempotency-Key":n,...r}=e;return this._client.post(`/v3/payment_requests`,{body:r,...t,headers:G([{...n==null?void 0:{"Idempotency-Key":n}},t?.headers])})}retrieve(e,t){return this._client.get(K`/v3/payment_requests/${e}`,t)}list(e={},t){return this._client.get(`/v3/payment_requests`,{query:e,...t})}cancel(e,t){return this._client.post(K`/v3/payment_requests/${e}/cancel`,t)}},xt=class extends W{create(e,t){return this._client.post(`/v3/payments`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/payments/${e}`,t)}cancel(e,t){return this._client.post(K`/v3/payments/${e}/cancel`,t)}credentials(e,t){return this._client.get(K`/v3/payments/${e}/credentials`,t)}},St=class extends W{update(e,t,n){return this._client.put(K`/v3/phone_numbers/${e}`,{body:t,...n})}list(e){return this._client.get(`/v3/phone_numbers`,e)}getReputationAudit(e,t,n){let{phoneNumber:r}=t;return this._client.get(K`/v3/phone_numbers/${r}/reputation_audit/${e}`,n)}startReputationAudit(e,t){return this._client.post(K`/v3/phone_numbers/${e}/reputation_audit`,t)}},Ct=class extends W{list(e){return this._client.get(`/v3/phonenumbers`,e)}},wt=class extends W{list(e){return this._client.get(`/v3/webhook-events`,e)}},Tt=class extends W{create(e,t){return this._client.post(`/v3/webhook-subscriptions`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/webhook-subscriptions/${e}`,t)}update(e,t,n){return this._client.put(K`/v3/webhook-subscriptions/${e}`,{body:t,...n})}list(e){return this._client.get(`/v3/webhook-subscriptions`,e)}delete(e,t){return this._client.delete(K`/v3/webhook-subscriptions/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},Et=e((e=>{var t=e&&e.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){e===void 0&&(e=`=`),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},e.prototype.encode=function(e){for(var t=``,n=0;n<e.length-2;n+=3){var r=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),t+=this._encodeByte(r>>>6&63),t+=this._encodeByte(r>>>0&63)}var i=e.length-n;if(i>0){var r=e[n]<<16|(i===2?e[n+1]<<8:0);t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),t+=i===2?this._encodeByte(r>>>6&63):this._paddingCharacter||``,t+=this._paddingCharacter||``}return t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(e.length===0)return new Uint8Array;for(var t=this._getPaddingLength(e),r=e.length-t,i=new Uint8Array(this.maxDecodedLength(r)),a=0,o=0,s=0,c=0,l=0,u=0,d=0;o<r-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),u=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=c<<2|l>>>4,i[a++]=l<<4|u>>>2,i[a++]=u<<6|d,s|=c&n,s|=l&n,s|=u&n,s|=d&n;if(o<r-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),i[a++]=c<<2|l>>>4,s|=c&n,s|=l&n),o<r-2&&(u=this._decodeChar(e.charCodeAt(o+2)),i[a++]=l<<4|u>>>2,s|=u&n),o<r-3&&(d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=u<<6|d,s|=d&n),s!==0)throw Error(`Base64Coder: incorrect characters for decoding`);return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-n+e-43+62,t+=(46-e&e-48)>>>8&-n+e-47+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw Error(`Base64Coder: incorrect padding`)}return t},e}();e.Coder=r;var i=new r;function a(e){return i.encode(e)}e.encode=a;function o(e){return i.decode(e)}e.decode=o;var s=function(e){t(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},r.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-n+e-45+62,t+=(94-e&e-96)>>>8&-n+e-95+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},r}(r);e.URLSafeCoder=s;var c=new s;function l(e){return c.encode(e)}e.encodeURLSafe=l;function u(e){return c.decode(e)}e.decodeURLSafe=u,e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}})),Dt=e(((e,t)=>{(function(e,n){var r={};n(r);var i=r.default;for(var a in r)i[a]=r[a];typeof t==`object`&&typeof t.exports==`object`?t.exports=i:typeof define==`function`&&define.amd?define(function(){return i}):e.sha256=i})(e,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,r,i,a){for(var o,s,c,l,u,d,f,p,m,h,g,_,v;a>=64;){for(o=n[0],s=n[1],c=n[2],l=n[3],u=n[4],d=n[5],f=n[6],p=n[7],h=0;h<16;h++)g=i+h*4,e[h]=(r[g]&255)<<24|(r[g+1]&255)<<16|(r[g+2]&255)<<8|r[g+3]&255;for(h=16;h<64;h++)m=e[h-2],_=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,m=e[h-15],v=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[h]=(_+e[h-7]|0)+(v+e[h-16]|0);for(h=0;h<64;h++)_=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&d^~u&f)|0)+(p+(t[h]+e[h]|0)|0)|0,v=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&s^o&c^s&c)|0,p=f,f=d,d=u,u=l+_|0,l=c,c=s,s=o,o=_+v|0;n[0]+=o,n[1]+=s,n[2]+=c,n[3]+=l,n[4]+=u,n[5]+=d,n[6]+=f,n[7]+=p,i+=64,a-=64}return i}var r=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(var e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this.finished)throw Error(`SHA256: can't update because hash was finished.`);var r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=n(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,r=this.bufferLength,i=t/536870912|0,a=t<<3,o=t%64<56?64:128;this.buffer[r]=128;for(var s=r+1;s<o-8;s++)this.buffer[s]=0;this.buffer[o-8]=i>>>24&255,this.buffer[o-7]=i>>>16&255,this.buffer[o-6]=i>>>8&255,this.buffer[o-5]=i>>>0&255,this.buffer[o-4]=a>>>24&255,this.buffer[o-3]=a>>>16&255,this.buffer[o-2]=a>>>8&255,this.buffer[o-1]=a>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(var s=0;s<8;s++)e[s*4+0]=this.state[s]>>>24&255,e[s*4+1]=this.state[s]>>>16&255,e[s*4+2]=this.state[s]>>>8&255,e[s*4+3]=this.state[s]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=r;var i=function(){function e(e){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)new r().update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(var n=0;n<t.length;n++)t[n]^=54;this.inner.update(t);for(var n=0;n<t.length;n++)t[n]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();e.HMAC=i;function a(e){var t=new r().update(e),n=t.digest();return t.clean(),n}e.hash=a,e.default=a;function o(e,t){var n=new i(e).update(t),r=n.digest();return n.clean(),r}e.hmac=o;function s(e,t,n,r){var i=r[0];if(i===0)throw Error(`hkdf: cannot expand more`);t.reset(),i>1&&t.update(e),n&&t.update(n),t.update(r),t.finish(e),r[0]++}var c=new Uint8Array(e.digestLength);function l(e,t,n,r){t===void 0&&(t=c),r===void 0&&(r=32);for(var a=new Uint8Array([1]),l=new i(o(t,e)),u=new Uint8Array(l.digestLength),d=u.length,f=new Uint8Array(r),p=0;p<r;p++)d===u.length&&(s(u,l,n,a),d=0),f[p]=u[d++];return l.clean(),u.fill(0),a.fill(0),f}e.hkdf=l;function u(e,t,n,r){for(var a=new i(e),o=a.digestLength,s=new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),u=new Uint8Array(r),d=0;d*o<r;d++){var f=d+1;s[0]=f>>>24&255,s[1]=f>>>16&255,s[2]=f>>>8&255,s[3]=f>>>0&255,a.reset(),a.update(t),a.update(s),a.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(var p=2;p<=n;p++){a.reset(),a.update(l).finish(l);for(var m=0;m<o;m++)c[m]^=l[m]}for(var p=0;p<o&&d*o+p<r;p++)u[d*o+p]=c[p]}for(var d=0;d<o;d++)c[d]=l[d]=0;for(var d=0;d<4;d++)s[d]=0;return a.clean(),u}e.pbkdf2=u})})),Ot=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=n;function t(e,t=``){if(!e)throw Error(t)}function n(e,n){if(e.byteLength!==n.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),t(e instanceof DataView),t(n instanceof DataView);let r=e.byteLength,i=0,a=-1;for(;++a<r;)i|=e.getUint8(a)^n.getUint8(a);return i===0}})),kt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;let t=Et(),n=Dt(),r=Ot();var i=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`ExtendableError`,this.stack=Error(t).stack}},a=class e extends i{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`WebhookVerificationError`}};e.WebhookVerificationError=a;var o=class e{constructor(n,r){if(r?.format===`raw`)this.key=n instanceof Uint8Array?n:Uint8Array.from(n,e=>e.charCodeAt(0));else{if(typeof n!=`string`)throw Error(`Expected secret to be of type string`);n.startsWith(e.prefix)&&(n=n.substring(e.prefix.length)),this.key=t.decode(n)}if(this.key.length===0)throw Error(`Secret can't be empty.`)}verify(e,t,n){let i=n?.jsonParse??!0,o={};for(let e of Object.keys(t))o[e.toLowerCase()]=t[e];let s=o[`webhook-id`],c=o[`webhook-signature`],l=o[`webhook-timestamp`];if(!c||!s||!l)throw new a(`Missing required headers`);let u=this.verifyTimestamp(l),d=this.sign(s,u,e).split(`,`)[1],f=c.split(` `),p=new globalThis.TextEncoder;for(let t of f){let[n,a]=t.split(`,`);if(n===`v1`&&(0,r.timingSafeEqual)(p.encode(a),p.encode(d))){let t=e.toString();return t===``?void 0:i?JSON.parse(t):void 0}}throw new a(`No matching signature found`)}sign(e,r,i){if(typeof i!=`string`){if(i.constructor.name===`Buffer`)i=i.toString();else throw Error(`Expected payload to be of type string or Buffer.`)}let a=new TextEncoder,o=Math.floor(r.getTime()/1e3),s=a.encode(`${e}.${o}.${i}`);return`v1,${t.encode(n.hmac(this.key,s))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),n=parseInt(e,10);if(Number.isNaN(n))throw new a(`Invalid Signature Headers`);if(t-n>300)throw new a(`Message timestamp too old`);if(n>t+300)throw new a(`Message timestamp too new`);return new Date(n*1e3)}};e.Webhook=o,o.prefix=`whsec_`}))(),At=class extends W{unwrap(e,{headers:t,key:n}){if(t!==void 0){let r=n===void 0?this._client.webhookSecret:n;if(r===null)throw Error(`Webhook key must not be null in order to unwrap`);new kt.Webhook(r).verify(e,t)}return JSON.parse(e)}};const Y=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var X,jt,Z,Mt,Q=class{constructor({baseURL:e=Y(`LINQ_API_V3_BASE_URL`),apiKey:t=Y(`LINQ_API_V3_API_KEY`),webhookSecret:n=Y(`LINQ_WEBHOOK_SECRET`)??null,...r}={}){if(X.add(this),Z.set(this,void 0),this.chats=new q(this),this.messages=new J(this),this.attachments=new at(this),this.phonenumbers=new Ct(this),this.phoneNumbers=new St(this),this.availableNumber=new ot(this),this.paymentRequests=new bt(this),this.paymentProviders=new yt(this),this.paymentHandles=new vt(this),this.payments=new xt(this),this.blockedHandles=new st(this),this.experiences=new gt(this),this.webhookEvents=new wt(this),this.webhookSubscriptions=new Tt(this),this.capability=new ct(this),this.webhooks=new At(this),this.contactCard=new ht(this),t===void 0)throw new v(`The LINQ_API_V3_API_KEY environment variable is missing or empty; either provide it, or instantiate the LinqAPIV3 client with an apiKey option, like new LinqAPIV3({ apiKey: 'My API Key' }).`);let i={apiKey:t,webhookSecret:n,...r,baseURL:e||`https://api.linqapp.com/api/partner`};this.baseURL=i.baseURL,this.timeout=i.timeout??jt.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Re(i.logLevel,`ClientOptions.logLevel`,this)??Re(Y(`LINQ_API_V3_LOG`),`process.env['LINQ_API_V3_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ye(),p(this,Z,Ce,`f`);let o=Y(`LINQ_API_V3_CUSTOM_HEADERS`);if(o){let e={};for(let t of o.split(`
3
- `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}this._options=i,this.apiKey=t,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return G([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Le(e)}getUserAgent(){return`${this.constructor.name}/JS ${k}`}defaultIdempotencyKey(){return`stainless-node-retry-${h()}`}makeStatusError(e,t,n,r){return y.generate(e,t,n,r)}buildURL(e,t,n){let r=!m(this,X,`m`,Mt).call(this)&&n||this.baseURL,i=ie(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!se(a)||!se(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new He(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(R(this).debug(`[${c}] sending request`,z({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new b;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(_),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new b;let i=g(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new S:new x({cause:f})}let m=`[${c}${l}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Se(f.body),R(this).info(`${m} - ${e}`),R(this).debug(`[${c}] response error (${e})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;R(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>_(e).message),o=ue(a),s=o?void 0:a;throw R(this).debug(`[${c}] response error (${i})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return R(this).info(m),R(this).debug(`[${c}] response start`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new We(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await de(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&le(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=G([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ve()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?m(this,Z,`f`).call(this,{body:t,headers:G([n])}):{bodyHeaders:void 0,body:void 0};let r=G([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:xe(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:m(this,Z,`f`).call(this,{body:t,headers:r})}};jt=Q,Z=new WeakMap,X=new WeakSet,Mt=function(){return this.baseURL!==`https://api.linqapp.com/api/partner`},Q.LinqAPIV3=jt,Q.DEFAULT_TIMEOUT=6e4,Q.LinqAPIV3Error=v,Q.APIError=y,Q.APIConnectionError=x,Q.APIConnectionTimeoutError=S,Q.APIUserAbortError=b,Q.NotFoundError=E,Q.ConflictError=D,Q.RateLimitError=te,Q.BadRequestError=C,Q.AuthenticationError=w,Q.InternalServerError=ne,Q.PermissionDeniedError=T,Q.UnprocessableEntityError=ee,Q.toFile=$e,Q.Chats=q,Q.Messages=J,Q.Attachments=at,Q.Phonenumbers=Ct,Q.PhoneNumbers=St,Q.AvailableNumber=ot,Q.PaymentRequests=bt,Q.PaymentProviders=yt,Q.PaymentHandles=vt,Q.Payments=xt,Q.BlockedHandles=st,Q.Experiences=gt,Q.WebhookEvents=wt,Q.WebhookSubscriptions=Tt,Q.Capability=ct,Q.Webhooks=At,Q.ContactCard=ht;function $(e){return typeof e==`object`&&!!e}function Nt(e){return typeof e==`string`||!$(e)?null:l(e)?e:l(e.card)?e.card:null}function Pt(e){return e.startsWith(`https://`)}function Ft(e){let t=[];return e.imageUrl&&Pt(e.imageUrl)&&t.push(e.imageUrl),It(e.children,t),t}function It(e,t){for(let n of e)n.type===`image`&&Pt(n.url)?t.push(n.url):n.type===`section`&&It(n.children,t)}function Lt(e){let t=[];e.title&&t.push(e.title),e.subtitle&&t.push(e.subtitle);for(let n of e.children){let e=Rt(n);e&&t.push(e)}return t.join(`
4
- `)}function Rt(e){switch(e.type){case`text`:return f(e.content).trim()||null;case`fields`:return e.children.map(e=>`${e.label}: ${e.value}`).join(`
5
- `);case`link`:return Bt(e.label,e.url);case`divider`:return`———`;case`image`:return Pt(e.url)?null:Bt(e.alt,e.url);case`table`:return s(e.headers,e.rows);case`section`:{let t=e.children.map(e=>Rt(e)).filter(e=>!!e);return t.length>0?t.join(`
3
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}this._options=i,this.apiKey=t,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return G([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Le(e)}getUserAgent(){return`${this.constructor.name}/JS ${k}`}defaultIdempotencyKey(){return`stainless-node-retry-${h()}`}makeStatusError(e,t,n,r){return y.generate(e,t,n,r)}buildURL(e,t,n){let r=!m(this,X,`m`,Mt).call(this)&&n||this.baseURL,i=ie(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!se(a)||!se(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new He(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(R(this).debug(`[${c}] sending request`,z({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new b;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(_),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new b;let i=g(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new S:new x({cause:f})}let m=`[${c}${l}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Se(f.body),R(this).info(`${m} - ${e}`),R(this).debug(`[${c}] response error (${e})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;R(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>_(e).message),o=ue(a),s=o?void 0:a;throw R(this).debug(`[${c}] response error (${i})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return R(this).info(m),R(this).debug(`[${c}] response start`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new We(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await de(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&le(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=G([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ve()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?m(this,Z,`f`).call(this,{body:t,headers:G([n])}):{bodyHeaders:void 0,body:void 0};let r=G([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:xe(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:m(this,Z,`f`).call(this,{body:t,headers:r})}};jt=Q,Z=new WeakMap,X=new WeakSet,Mt=function(){return this.baseURL!==`https://api.linqapp.com/api/partner`},Q.LinqAPIV3=jt,Q.DEFAULT_TIMEOUT=6e4,Q.LinqAPIV3Error=v,Q.APIError=y,Q.APIConnectionError=x,Q.APIConnectionTimeoutError=S,Q.APIUserAbortError=b,Q.NotFoundError=E,Q.ConflictError=D,Q.RateLimitError=te,Q.BadRequestError=C,Q.AuthenticationError=w,Q.InternalServerError=ne,Q.PermissionDeniedError=T,Q.UnprocessableEntityError=ee,Q.toFile=$e,Q.Chats=q,Q.Messages=J,Q.Attachments=at,Q.Phonenumbers=Ct,Q.PhoneNumbers=St,Q.AvailableNumber=ot,Q.PaymentRequests=bt,Q.PaymentProviders=yt,Q.PaymentHandles=vt,Q.Payments=xt,Q.BlockedHandles=st,Q.Experiences=gt,Q.WebhookEvents=wt,Q.WebhookSubscriptions=Tt,Q.Capability=ct,Q.Webhooks=At,Q.ContactCard=ht;function $(e){return typeof e==`object`&&!!e}function Nt(e){return typeof e==`string`||!$(e)?null:s(e)?e:s(e.card)?e.card:null}function Pt(e){return e.startsWith(`https://`)}function Ft(e){let t=[];return e.imageUrl&&Pt(e.imageUrl)&&t.push(e.imageUrl),It(e.children,t),t}function It(e,t){for(let n of e)n.type===`image`&&Pt(n.url)?t.push(n.url):n.type===`section`&&It(n.children,t)}function Lt(e){let t=[];e.title&&t.push(e.title),e.subtitle&&t.push(e.subtitle);for(let n of e.children){let e=Rt(n);e&&t.push(e)}return t.join(`
4
+ `)}function Rt(e){switch(e.type){case`text`:return o(e.content).trim()||null;case`fields`:return e.children.map(e=>`${e.label}: ${e.value}`).join(`
5
+ `);case`link`:return Bt(e.label,e.url);case`divider`:return`———`;case`image`:return Pt(e.url)?null:Bt(e.alt,e.url);case`table`:return n(e.headers,e.rows);case`section`:{let t=e.children.map(e=>Rt(e)).filter(e=>!!e);return t.length>0?t.join(`
6
6
  `):null}case`actions`:return zt(e);default:return null}}function zt(e){let t=[],n=[];for(let r of e.children)switch(r.type){case`button`:n.push(r.label);break;case`link-button`:{let e=Bt(r.label,r.url);e&&t.push(e);break}case`select`:case`radio_select`:{let e=r.options.map(e=>e.label).join(`, `);t.push(e?`${r.label}: ${e}`:r.label);break}}return n.length>0&&t.unshift(`Options: ${n.join(`, `)}`),t.length>0?t.join(`
7
- `):null}function Bt(e,t){return e&&e!==t?`${e}: ${t}`:t}function Vt(e){return Ht(e.children)}function Ht(e){return e.some(e=>e.type===`section`?Ht(e.children):e.type===`actions`&&e.children.some(e=>e.type===`button`||e.type===`select`||e.type===`radio_select`))}const Ut={strong:`bold`,emphasis:`italic`,delete:`strikethrough`};function Wt(e){let t=[],n=[],r=0,i=e=>{typeof e==`string`&&e&&(t.push(e),r+=e.length)},a=e=>{if(Array.isArray(e)){o(e);return}if(!e||typeof e!=`object`)return;let t=e,s=typeof t.type==`string`?Ut[t.type]:void 0,c=r;`value`in t?i(t.value):t.alt?i(t.alt):`children`in t&&a(t.children),s&&r>c&&n.push({range:[c,r],style:s})},o=e=>{for(let t of e)a(t)};return a(e),{value:t.join(``),decorations:n}}function Gt({value:e,decorations:t}){let n=e.length-e.trimStart().length,r=e.trim();if(!n&&r.length===e.length)return{value:r,decorations:t};let i=[];for(let e of t){let[t,a]=e.range,o=Math.min(Math.max((t??0)-n,0),r.length),s=Math.min(Math.max((a??0)-n,0),r.length);s>o&&i.push({...e,range:[o,s]})}return{value:r,decorations:i}}function Kt(e){for(let[t,n]of e.entries())if(n.animation){for(let[r,i]of e.entries())if(t!==r&&qt(n.range,i.range))throw Error(`Linq text animation range [${String(n.range)}] overlaps another decoration at [${String(i.range)}] — animations cannot overlap other decorations.`)}}function qt(e,t){return(e[0]??0)<(t[1]??0)&&(t[0]??0)<(e[1]??0)}var Jt=class extends u{toAst(e){return r(e)}fromAst(e){return a(e)}renderDecoratedPostable(e){if(e&&typeof e==`object`){if(`markdown`in e)return Wt(r(e.markdown));if(`ast`in e)return Wt(e.ast)}return{value:this.renderPostable(e),decorations:[]}}cardToFallbackText(e){return Lt(e)}};function Yt(e,t){let n=Qt(e),i=n.parts.flatMap(e=>e.type===`media`?[on(e)]:[]),a=rn(n.parts,i),s=an(n.parts),c=n.isMe,l=n.sender?.id||n.sender?.handle||`unknown`,u=n.sender?.handle||n.sender?.id||`unknown`;return new o({id:n.id,threadId:t({chatId:n.chatId,isGroup:n.isGroup}),text:a,formatted:r(a),raw:e,author:{userId:l,userName:u,fullName:u,isBot:c,isMe:c},metadata:{dateSent:nn(n.sentAt),edited:n.edited,editedAt:n.editedAt?nn(n.editedAt):void 0},attachments:i,links:s})}function Xt(e){return e.event_type===`message.received`}function Zt(e){return e.event_type===`reaction.added`||e.event_type===`reaction.removed`}function Qt(e){if($t(e))return{id:e.id,chatId:e.chat.id,isGroup:e.chat.is_group??void 0,parts:e.parts,isMe:e.direction===`outbound`||e.sender_handle.is_me===!0,sender:e.sender_handle,sentAt:e.sent_at,edited:!1};if(en(e))return{id:e.message.id,chatId:e.chat_id,isGroup:void 0,parts:e.message.parts,isMe:!0,sender:e.message.from_handle,sentAt:e.message.sent_at||e.message.created_at,edited:!1};if(tn(e)){let t=e.updated_at!==e.created_at;return{id:e.id,chatId:e.chat_id,isGroup:void 0,parts:e.parts??[],isMe:e.is_from_me||e.from_handle?.is_me===!0,sender:e.from_handle,sentAt:e.sent_at||e.created_at,edited:t,editedAt:t?e.updated_at:void 0}}throw new n(`parseMessage only supports Linq message payloads`)}function $t(e){return $(e)&&`chat`in e&&`direction`in e&&`sender_handle`in e}function en(e){return $(e)&&`chat_id`in e&&`message`in e&&$(e.message)}function tn(e){return $(e)&&`chat_id`in e&&`is_from_me`in e&&`created_at`in e}function nn(e){if(e){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function rn(e,t){let n=e.flatMap(e=>(e.type===`text`||e.type===`link`)&&typeof e.value==`string`?[e.value]:[]),r=t.map(e=>{let t=e.name||e.mimeType||e.type;return`[${e.type} attachment: ${t}]`});return[...n,...r].join(`
8
- `).trim()}function an(e){let t=new Set;for(let n of e){if(n.type===`link`){t.add(n.value);continue}if(n.type===`text`)for(let e of cn(n.value))t.add(e)}return[...t].map(e=>({url:e}))}function on(e){return{type:sn(e.mime_type),url:e.url,name:e.filename,mimeType:e.mime_type,size:e.size_bytes,width:e.width??e.width_px,height:e.height??e.height_px,fetchMetadata:{url:e.url},fetchData:async()=>{let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to fetch Linq attachment ${e.id||e.url}: ${t.status}`);return Buffer.from(await t.arrayBuffer())}}}function sn(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`file`}function cn(e){return(e.match(/https?:\/\/[^\s<>()]+/gi)??[]).map(e=>e.replace(/[.,!?;:]+$/g,``))}const ln={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`,mp4:`video/mp4`,mov:`video/quicktime`,m4v:`video/x-m4v`,"3gp":`video/3gpp`,m4a:`audio/x-m4a`,mp3:`audio/mpeg`,aac:`audio/aac`,wav:`audio/x-wav`,aiff:`audio/x-aiff`,caf:`audio/x-caf`,amr:`audio/amr`,pdf:`application/pdf`,txt:`text/plain`,csv:`text/csv`,rtf:`text/rtf`,vcf:`text/vcard`,ics:`text/calendar`,html:`text/html`,htm:`text/html`,json:`application/json`,zip:`application/zip`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};function un(e){return typeof e==`string`||!$(e)?{attachments:[],files:[]}:{attachments:Array.isArray(e.attachments)?e.attachments:[],files:Array.isArray(e.files)?e.files:[]}}async function dn(e,t){let{attachments:n,files:r}=un(t);if(n.length===0&&r.length===0)return[];let i=[];for(let t of n)i.push(await fn(e,t));for(let t of r)i.push(await pn(e,t));return i}async function fn(e,t){if(t.url&&t.url.startsWith(`https://`)&&!_n(t.size))return{type:`media`,url:t.url};let n=await hn(t),r=t.name??bn(t.mimeType);return{type:`media`,attachment_id:await mn(e,n,r,vn(t.mimeType,r))}}async function pn(e,t){let n=await gn(t.data),r=vn(t.mimeType,t.filename);return{type:`media`,attachment_id:await mn(e,n,t.filename,r)}}async function mn(e,t,n,r){let i=await e.attachments.create({filename:n,content_type:r,size_bytes:t.byteLength}),a=await fetch(i.upload_url,{method:i.http_method,headers:i.required_headers,body:t});if(!a.ok)throw Error(`Failed to upload Linq attachment ${n}: ${a.status} ${a.statusText}`);return i.attachment_id}async function hn(e){if(e.data!=null)return gn(e.data);if(typeof e.fetchData==`function`)return gn(await e.fetchData());if(e.url){let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to download Linq attachment ${e.name??e.url}: ${t.status}`);return new Uint8Array(await t.arrayBuffer())}throw Error(`Outbound attachment ${e.name??`(unnamed)`} has no data, fetchData, or url to send`)}async function gn(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw Error(`Unsupported attachment data type; expected Buffer, Blob, or ArrayBuffer`)}function _n(e){return typeof e==`number`&&e>10485760}function vn(e,t){if(e&&e.trim())return yn(e.trim());let n=t.split(`.`).pop()?.toLowerCase(),r=n?ln[n]:void 0;if(r)return r;throw Error(`Cannot determine content type for attachment "${t}"; set mimeType on the attachment`)}function yn(e){let t=e.toLowerCase();return t===`image/jpg`?`image/jpeg`:t}function bn(e){let t=e?xn(e):void 0;return t?`attachment.${t}`:`attachment`}function xn(e){let t=yn(e);for(let[e,n]of Object.entries(ln))if(n===t)return e}const Sn={like:`thumbs_up`,dislike:`thumbs_down`,love:`heart`,laugh:`laugh`,emphasize:`exclamation`,question:`question`};function Cn(e){if(e.reaction_type===`custom`)return e.custom_emoji?{emoji:t.fromGChat(e.custom_emoji),rawEmoji:e.custom_emoji}:null;let n=Sn[e.reaction_type];return n?{emoji:i(n),rawEmoji:e.reaction_type}:null}function wn(e){let n=typeof e==`string`?e:e.name,r=n.trim().replace(/^\{\{emoji:/,``).replace(/\}\}$/,``).replace(/^:+|:+$/g,``).toLowerCase();return[`thumbs_up`,`thumbsup`,`+1`,`like`,`👍`].includes(r)?{type:`like`}:[`thumbs_down`,`thumbsdown`,`-1`,`dislike`,`👎`].includes(r)?{type:`dislike`}:[`heart`,`love`,`❤️`,`❤`].includes(r)?{type:`love`}:[`laugh`,`joy`,`rofl`,`😂`,`🤣`].includes(r)?{type:`laugh`}:[`exclamation`,`emphasize`,`!!`,`!`,`‼️`,`‼`,`❗`].includes(r)?{type:`emphasize`}:[`question`,`?`,`❓`].includes(r)?{type:`question`}:{type:`custom`,custom_emoji:t.toDiscord(n)}}async function Tn(e,t){if(!t)return{ok:!1,response:new Response(`Linq webhook signing secret is not configured`,{status:503})};let n=await e.text();try{new kt.Webhook(t).verify(n,Object.fromEntries(e.headers))}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(n)}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}const En={"message.sent":`sent`,"message.delivered":`delivered`,"message.read":`read`,"message.failed":`failed`};var Dn=class{name=`linq`;userName=`linq`;apiClient;baseURL;converter=new Jt;credentials;signingSecret;webhookVerifier;chat=null;logger;chatKinds=new Map;deliveryStatusListeners=new Set;constructor(e){if(!e.credentials&&!e.apiKey)throw Error(`Linq requires apiKey or a credentials provider.`);if(!e.webhookVerifier&&!e.credentials&&!e.signingSecret)throw Error(`Linq requires signingSecret or a webhookVerifier.`);this.apiClient=e.apiKey?new Q({apiKey:e.apiKey,baseURL:e.baseURL}):null,this.baseURL=e.baseURL,this.credentials=e.credentials,this.signingSecret=e.signingSecret,this.webhookVerifier=e.webhookVerifier,this.logger=new d}async getApiClient(){if(this.apiClient)return this.apiClient;let e=await this.credentials?.();if(!e?.apiKey)throw Error(`Linq credentials did not provide an API key.`);return new Q({apiKey:e.apiKey,baseURL:this.baseURL})}async getSigningSecret(){if(this.signingSecret)return this.signingSecret;let e=await this.credentials?.();if(!e?.signingSecret)throw Error(`Linq credentials did not provide a webhook signing secret.`);return e.signingSecret}async initialize(e){this.chat=e,this.logger=e.getLogger(`linq`)}encodeThreadId(e){return e.pendingHandle?`linq:pending:${e.pendingHandle}`:(e.isGroup!==void 0&&this.chatKinds.set(e.chatId,e.isGroup),`linq:${e.chatId}`)}decodeThreadId(e){let[t,n,r]=e.split(`:`);if(t!==`linq`||!n)throw Error(`Invalid Linq thread ID: ${e}`);if(n===`pending`){let t=e.slice(13);if(!t)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:``,pendingHandle:t,isGroup:!1}}if(r===`group`||r===`dm`){let e=r===`group`;return this.chatKinds.set(n,e),{chatId:n,isGroup:e}}if(r!==void 0)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:n,isGroup:this.chatKinds.get(n)}}async fetchMessages(e,t){let n=this.requireChatId(e),r=await(await this.getApiClient()).chats.messages.list(n,{cursor:t?.cursor,limit:t?.limit});return{messages:r.messages.map(e=>this.parseMessage(e)).sort(function(e,t){return e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()}),nextCursor:r.next_cursor||void 0}}async fetchMessage(e,t){try{let e=await(await this.getApiClient()).messages.retrieve(t);return this.parseMessage(e)}catch(e){if($(e)&&e.status===404)return null;throw e}}async postMessage(e,t,n={}){let{chatId:r,pendingHandle:i}=this.decodeThreadId(e),{value:a,decorations:o}=Gt(this.converter.renderDecoratedPostable(t)),s=await dn(await this.getApiClient(),t),c=[];if(a){let e=[...o,...n.textDecorations??[]];Kt(e),c.push(e.length?{type:`text`,value:a,text_decorations:e}:{type:`text`,value:a})}let l=Nt(t);if(l){Vt(l)&&this.logger.warn(`Card buttons/selects were flattened to text — onAction() handlers never fire over iMessage/SMS. Use LinkButton/CardLink URLs or handle plain-text replies instead.`);for(let e of Ft(l))c.push({type:`media`,url:e})}if(c.push(...s),c.length===0)throw Error(`Linq message must include text or media.`);let u=await this.getApiClient(),d=n.idempotencyKey?{idempotency_key:n.idempotencyKey}:{};if(i){let e=await u.messages.create({to:[i],message:{parts:c,...d}});return{id:e.message.id,threadId:this.encodeThreadId({chatId:e.chat_id}),raw:e}}let f=await u.chats.messages.send(r,{message:{parts:c,...d}});return{id:f.message.id,threadId:this.encodeThreadId({chatId:f.chat_id||r}),raw:f}}requireChatId(e){let{chatId:t,pendingHandle:n}=this.decodeThreadId(e);if(n)throw Error(`Linq thread ${e} has no chat yet — send a message first to create it.`);return t}async openDM(e){let t=e.trim();if(!t)throw Error(`Linq openDM requires a handle.`);return this.encodeThreadId({chatId:``,pendingHandle:t})}async editMessage(e,t,n){let r=this.requireChatId(e),i=this.converter.renderPostable(n).trim();if(!i)throw Error(`Linq message text cannot be empty.`);let a=await(await this.getApiClient()).messages.update(t,{text:i,part_index:0});return{id:a.id,threadId:this.encodeThreadId({chatId:a.chat_id||r}),raw:a}}deleteMessage(e,t){throw new n(`deleteMessage is not implemented`)}async addReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`add`,...wn(n)})}async removeReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`remove`,...wn(n)})}async fetchThread(e){let t=this.requireChatId(e),n=await(await this.getApiClient()).chats.retrieve(t);return{id:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelId:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelName:n.display_name??void 0,isDM:!n.is_group,metadata:{chat:n}}}async startTyping(e,t){let n=this.requireChatId(e),{isGroup:r}=this.decodeThreadId(e);if(r!==!0)try{await(await this.getApiClient()).chats.typing.start(n)}catch(e){if($(e)&&e.status===403)return;throw e}}async markRead(e,t){let{chatId:n}=this.decodeThreadId(e);await(await this.getApiClient()).chats.markAsRead(n)}async stream(e,t){let n=``;for await(let e of t){if(typeof e==`string`){n+=e;continue}e.type===`markdown_text`&&(n+=e.text)}return this.postMessage(e,n.trim()?{markdown:n}:` `)}async handleWebhook(e,t){let n=this.webhookVerifier?await this.verifyTrustedWebhook(e):await Tn(e,await this.getSigningSecret());if(!n.ok)return n.response;let{event:r}=n;if(this.chat&&Xt(r)&&r.data.direction===`inbound`){let e=r.data.chat.id,n=r.data.chat.is_group??void 0;if(n===void 0&&!this.chatKinds.has(e))try{let t=await(await this.getApiClient()).chats.retrieve(e);this.chatKinds.set(e,t.is_group)}catch(t){this.logger.warn(`Failed to resolve Linq chat kind for ${e}`,{error:t})}let i=this.encodeThreadId({chatId:e,isGroup:n});this.chat.processMessage(this,i,async()=>this.parseMessage(r.data),t)}else if(this.chat&&Zt(r))this.processReactionWebhook(this.chat,r,t);else{let e=En[r.event_type];e&&this.processDeliveryStatusWebhook(r,e)}return new Response(`OK`,{status:200})}async verifyTrustedWebhook(e){let t=new Uint8Array(await e.arrayBuffer());try{if(await this.webhookVerifier?.(e,t)===!1)return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(new TextDecoder().decode(t))}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}onDeliveryStatus(e){return this.deliveryStatusListeners.add(e),()=>{this.deliveryStatusListeners.delete(e)}}emitDeliveryStatus(e){for(let t of this.deliveryStatusListeners)try{t(e)}catch(e){this.logger.warn(`Linq delivery-status listener threw`,{error:e})}}processDeliveryStatusWebhook(e,t){if(this.deliveryStatusListeners.size===0)return;let n=e.data,r=n.chat?.id,i=n.id;if(!r||!i){this.logger.debug(`Ignoring Linq ${e.event_type} webhook without chat/message ID`);return}let a={status:t,threadId:this.encodeThreadId({chatId:r}),messageId:i,raw:e,...n.error?{error:n.error}:{}};this.emitDeliveryStatus(a)}processReactionWebhook(e,t,n){let{chat_id:r,message_id:i}=t.data;if(!r||!i){this.logger.debug(`Ignoring Linq ${t.event_type} webhook without chat/message ID`);return}let a=Cn(t.data);if(!a){this.logger.debug(`Ignoring Linq ${t.event_type} webhook with unsupported reaction type ${t.data.reaction_type}`);return}let o=t.data.from_handle,s=t.data.is_from_me||o?.is_me===!0,c=o?.id||o?.handle||t.data.from||`unknown`,l=o?.handle||t.data.from||c;e.processReaction({adapter:this,added:t.event_type===`reaction.added`,emoji:a.emoji,rawEmoji:a.rawEmoji,messageId:i,threadId:this.encodeThreadId({chatId:r}),raw:t,user:{userId:c,userName:l,fullName:l,isBot:s,isMe:s}},n)}parseMessage(e){return Yt(e,e=>this.encodeThreadId(e))}rehydrateAttachment(e){let t=e.fetchMetadata?.url??e.url;return t?{...e,fetchData:async()=>{let e=await fetch(t);if(!e.ok)throw Error(`Failed to fetch Linq attachment ${t}: ${e.status}`);return Buffer.from(await e.arrayBuffer())}}:e}renderFormatted(e){return c(e).trim()}channelIdFromThreadId(e){return e}isDM(e){return this.decodeThreadId(e).isGroup===!1}};function On(e){return new Dn(e)}export{On as createLinqAdapter};
7
+ `):null}function Bt(e,t){return e&&e!==t?`${e}: ${t}`:t}function Vt(e){return Ht(e.children)}function Ht(e){return e.some(e=>e.type===`section`?Ht(e.children):e.type===`actions`&&e.children.some(e=>e.type===`button`||e.type===`select`||e.type===`radio_select`))}const Ut={strong:`bold`,emphasis:`italic`,delete:`strikethrough`};function Wt(e){let t=[],n=[],r=0,i=e=>{typeof e==`string`&&e&&(t.push(e),r+=e.length)},a=e=>{if(Array.isArray(e)){o(e);return}if(!e||typeof e!=`object`)return;let t=e,s=typeof t.type==`string`?Ut[t.type]:void 0,c=r;`value`in t?i(t.value):t.alt?i(t.alt):`children`in t&&a(t.children),s&&r>c&&n.push({range:[c,r],style:s})},o=e=>{for(let t of e)a(t)};return a(e),{value:t.join(``),decorations:n}}function Gt({value:e,decorations:t}){let n=e.length-e.trimStart().length,r=e.trim();if(!n&&r.length===e.length)return{value:r,decorations:t};let i=[];for(let e of t){let[t,a]=e.range,o=Math.min(Math.max((t??0)-n,0),r.length),s=Math.min(Math.max((a??0)-n,0),r.length);s>o&&i.push({...e,range:[o,s]})}return{value:r,decorations:i}}function Kt(e){for(let[t,n]of e.entries())if(n.animation){for(let[r,i]of e.entries())if(t!==r&&qt(n.range,i.range))throw Error(`Linq text animation range [${String(n.range)}] overlaps another decoration at [${String(i.range)}] — animations cannot overlap other decorations.`)}}function qt(e,t){return(e[0]??0)<(t[1]??0)&&(t[0]??0)<(e[1]??0)}var Jt=class extends d{toAst(e){return t(e)}fromAst(e){return c(e)}renderDecoratedPostable(e){if(e&&typeof e==`object`){if(`markdown`in e)return Wt(t(e.markdown));if(`ast`in e)return Wt(e.ast)}return{value:this.renderPostable(e),decorations:[]}}cardToFallbackText(e){return Lt(e)}};function Yt(e,n){let r=Qt(e),i=r.parts.flatMap(e=>e.type===`media`?[on(e)]:[]),a=rn(r.parts,i),o=an(r.parts),s=r.isMe,c=r.sender?.id||r.sender?.handle||`unknown`,l=r.sender?.handle||r.sender?.id||`unknown`;return new u({id:r.id,threadId:n({chatId:r.chatId,isGroup:r.isGroup}),text:a,formatted:t(a),raw:e,author:{userId:c,userName:l,fullName:l,isBot:s,isMe:s},metadata:{dateSent:nn(r.sentAt),edited:r.edited,editedAt:r.editedAt?nn(r.editedAt):void 0},attachments:i,links:o})}function Xt(e){return e.event_type===`message.received`}function Zt(e){return e.event_type===`reaction.added`||e.event_type===`reaction.removed`}function Qt(e){if($t(e))return{id:e.id,chatId:e.chat.id,isGroup:e.chat.is_group??void 0,parts:e.parts,isMe:e.direction===`outbound`||e.sender_handle.is_me===!0,sender:e.sender_handle,sentAt:e.sent_at,edited:!1};if(en(e))return{id:e.message.id,chatId:e.chat_id,isGroup:void 0,parts:e.message.parts,isMe:!0,sender:e.message.from_handle,sentAt:e.message.sent_at||e.message.created_at,edited:!1};if(tn(e)){let t=e.updated_at!==e.created_at;return{id:e.id,chatId:e.chat_id,isGroup:void 0,parts:e.parts??[],isMe:e.is_from_me||e.from_handle?.is_me===!0,sender:e.from_handle,sentAt:e.sent_at||e.created_at,edited:t,editedAt:t?e.updated_at:void 0}}throw new l(`parseMessage only supports Linq message payloads`)}function $t(e){return $(e)&&`chat`in e&&`direction`in e&&`sender_handle`in e}function en(e){return $(e)&&`chat_id`in e&&`message`in e&&$(e.message)}function tn(e){return $(e)&&`chat_id`in e&&`is_from_me`in e&&`created_at`in e}function nn(e){if(e){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function rn(e,t){let n=e.flatMap(e=>(e.type===`text`||e.type===`link`)&&typeof e.value==`string`?[e.value]:[]),r=t.map(e=>{let t=e.name||e.mimeType||e.type;return`[${e.type} attachment: ${t}]`});return[...n,...r].join(`
8
+ `).trim()}function an(e){let t=new Set;for(let n of e){if(n.type===`link`){t.add(n.value);continue}if(n.type===`text`)for(let e of cn(n.value))t.add(e)}return[...t].map(e=>({url:e}))}function on(e){return{type:sn(e.mime_type),url:e.url,name:e.filename,mimeType:e.mime_type,size:e.size_bytes,width:e.width??e.width_px,height:e.height??e.height_px,fetchMetadata:{url:e.url},fetchData:async()=>{let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to fetch Linq attachment ${e.id||e.url}: ${t.status}`);return Buffer.from(await t.arrayBuffer())}}}function sn(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`file`}function cn(e){return(e.match(/https?:\/\/[^\s<>()]+/gi)??[]).map(e=>e.replace(/[.,!?;:]+$/g,``))}const ln={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`,mp4:`video/mp4`,mov:`video/quicktime`,m4v:`video/x-m4v`,"3gp":`video/3gpp`,m4a:`audio/x-m4a`,mp3:`audio/mpeg`,aac:`audio/aac`,wav:`audio/x-wav`,aiff:`audio/x-aiff`,caf:`audio/x-caf`,amr:`audio/amr`,pdf:`application/pdf`,txt:`text/plain`,csv:`text/csv`,rtf:`text/rtf`,vcf:`text/vcard`,ics:`text/calendar`,html:`text/html`,htm:`text/html`,json:`application/json`,zip:`application/zip`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};function un(e){return typeof e==`string`||!$(e)?{attachments:[],files:[]}:{attachments:Array.isArray(e.attachments)?e.attachments:[],files:Array.isArray(e.files)?e.files:[]}}async function dn(e,t){let{attachments:n,files:r}=un(t);if(n.length===0&&r.length===0)return[];let i=[];for(let t of n)i.push(await fn(e,t));for(let t of r)i.push(await pn(e,t));return i}async function fn(e,t){if(t.url&&t.url.startsWith(`https://`)&&!_n(t.size))return{type:`media`,url:t.url};let n=await hn(t),r=t.name??bn(t.mimeType);return{type:`media`,attachment_id:await mn(e,n,r,vn(t.mimeType,r))}}async function pn(e,t){let n=await gn(t.data),r=vn(t.mimeType,t.filename);return{type:`media`,attachment_id:await mn(e,n,t.filename,r)}}async function mn(e,t,n,r){let i=await e.attachments.create({filename:n,content_type:r,size_bytes:t.byteLength}),a=await fetch(i.upload_url,{method:i.http_method,headers:i.required_headers,body:t});if(!a.ok)throw Error(`Failed to upload Linq attachment ${n}: ${a.status} ${a.statusText}`);return i.attachment_id}async function hn(e){if(e.data!=null)return gn(e.data);if(typeof e.fetchData==`function`)return gn(await e.fetchData());if(e.url){let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to download Linq attachment ${e.name??e.url}: ${t.status}`);return new Uint8Array(await t.arrayBuffer())}throw Error(`Outbound attachment ${e.name??`(unnamed)`} has no data, fetchData, or url to send`)}async function gn(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw Error(`Unsupported attachment data type; expected Buffer, Blob, or ArrayBuffer`)}function _n(e){return typeof e==`number`&&e>10485760}function vn(e,t){if(e&&e.trim())return yn(e.trim());let n=t.split(`.`).pop()?.toLowerCase(),r=n?ln[n]:void 0;if(r)return r;throw Error(`Cannot determine content type for attachment "${t}"; set mimeType on the attachment`)}function yn(e){let t=e.toLowerCase();return t===`image/jpg`?`image/jpeg`:t}function bn(e){let t=e?xn(e):void 0;return t?`attachment.${t}`:`attachment`}function xn(e){let t=yn(e);for(let[e,n]of Object.entries(ln))if(n===t)return e}const Sn={like:`thumbs_up`,dislike:`thumbs_down`,love:`heart`,laugh:`laugh`,emphasize:`exclamation`,question:`question`};function Cn(e){if(e.reaction_type===`custom`)return e.custom_emoji?{emoji:i.fromGChat(e.custom_emoji),rawEmoji:e.custom_emoji}:null;let t=Sn[e.reaction_type];return t?{emoji:r(t),rawEmoji:e.reaction_type}:null}function wn(e){let t=typeof e==`string`?e:e.name,n=t.trim().replace(/^\{\{emoji:/,``).replace(/\}\}$/,``).replace(/^:+|:+$/g,``).toLowerCase();return[`thumbs_up`,`thumbsup`,`+1`,`like`,`👍`].includes(n)?{type:`like`}:[`thumbs_down`,`thumbsdown`,`-1`,`dislike`,`👎`].includes(n)?{type:`dislike`}:[`heart`,`love`,`❤️`,`❤`].includes(n)?{type:`love`}:[`laugh`,`joy`,`rofl`,`😂`,`🤣`].includes(n)?{type:`laugh`}:[`exclamation`,`emphasize`,`!!`,`!`,`‼️`,`‼`,`❗`].includes(n)?{type:`emphasize`}:[`question`,`?`,`❓`].includes(n)?{type:`question`}:{type:`custom`,custom_emoji:i.toDiscord(t)}}async function Tn(e,t){if(!t)return{ok:!1,response:new Response(`Linq webhook signing secret is not configured`,{status:503})};let n=await e.text();try{new kt.Webhook(t).verify(n,Object.fromEntries(e.headers))}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(n)}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}const En={"message.sent":`sent`,"message.delivered":`delivered`,"message.read":`read`,"message.failed":`failed`};var Dn=class{name=`linq`;userName=`linq`;apiClient;baseURL;converter=new Jt;credentials;signingSecret;webhookVerifier;chat=null;logger;chatKinds=new Map;deliveryStatusListeners=new Set;constructor(e){if(!e.credentials&&!e.apiKey)throw Error(`Linq requires apiKey or a credentials provider.`);if(!e.webhookVerifier&&!e.credentials&&!e.signingSecret)throw Error(`Linq requires signingSecret or a webhookVerifier.`);this.apiClient=e.apiKey?new Q({apiKey:e.apiKey,baseURL:e.baseURL}):null,this.baseURL=e.baseURL,this.credentials=e.credentials,this.signingSecret=e.signingSecret,this.webhookVerifier=e.webhookVerifier,this.logger=new f}async getApiClient(){if(this.apiClient)return this.apiClient;let e=await this.credentials?.();if(!e?.apiKey)throw Error(`Linq credentials did not provide an API key.`);return new Q({apiKey:e.apiKey,baseURL:this.baseURL})}async getSigningSecret(){if(this.signingSecret)return this.signingSecret;let e=await this.credentials?.();if(!e?.signingSecret)throw Error(`Linq credentials did not provide a webhook signing secret.`);return e.signingSecret}async initialize(e){this.chat=e,this.logger=e.getLogger(`linq`)}encodeThreadId(e){return e.pendingHandle?`linq:pending:${e.pendingHandle}`:(e.isGroup!==void 0&&this.chatKinds.set(e.chatId,e.isGroup),`linq:${e.chatId}`)}decodeThreadId(e){let[t,n,r]=e.split(`:`);if(t!==`linq`||!n)throw Error(`Invalid Linq thread ID: ${e}`);if(n===`pending`){let t=e.slice(13);if(!t)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:``,pendingHandle:t,isGroup:!1}}if(r===`group`||r===`dm`){let e=r===`group`;return this.chatKinds.set(n,e),{chatId:n,isGroup:e}}if(r!==void 0)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:n,isGroup:this.chatKinds.get(n)}}async fetchMessages(e,t){let n=this.requireChatId(e),r=await(await this.getApiClient()).chats.messages.list(n,{cursor:t?.cursor,limit:t?.limit});return{messages:r.messages.map(e=>this.parseMessage(e)).sort(function(e,t){return e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()}),nextCursor:r.next_cursor||void 0}}async fetchMessage(e,t){try{let e=await(await this.getApiClient()).messages.retrieve(t);return this.parseMessage(e)}catch(e){if($(e)&&e.status===404)return null;throw e}}async postMessage(e,t,n={}){let{chatId:r,pendingHandle:i}=this.decodeThreadId(e),{value:a,decorations:o}=Gt(this.converter.renderDecoratedPostable(t)),s=await dn(await this.getApiClient(),t),c=[];if(a){let e=[...o,...n.textDecorations??[]];Kt(e),c.push(e.length?{type:`text`,value:a,text_decorations:e}:{type:`text`,value:a})}let l=Nt(t);if(l){Vt(l)&&this.logger.warn(`Card buttons/selects were flattened to text — onAction() handlers never fire over iMessage/SMS. Use LinkButton/CardLink URLs or handle plain-text replies instead.`);for(let e of Ft(l))c.push({type:`media`,url:e})}if(c.push(...s),c.length===0)throw Error(`Linq message must include text or media.`);let u=await this.getApiClient(),d=n.idempotencyKey?{idempotency_key:n.idempotencyKey}:{};if(i){let e=await u.messages.create({to:[i],message:{parts:c,...d}});return{id:e.message.id,threadId:this.encodeThreadId({chatId:e.chat_id}),raw:e}}let f=await u.chats.messages.send(r,{message:{parts:c,...d}});return{id:f.message.id,threadId:this.encodeThreadId({chatId:f.chat_id||r}),raw:f}}requireChatId(e){let{chatId:t,pendingHandle:n}=this.decodeThreadId(e);if(n)throw Error(`Linq thread ${e} has no chat yet — send a message first to create it.`);return t}async openDM(e){let t=e.trim();if(!t)throw Error(`Linq openDM requires a handle.`);return this.encodeThreadId({chatId:``,pendingHandle:t})}async editMessage(e,t,n){let r=this.requireChatId(e),i=this.converter.renderPostable(n).trim();if(!i)throw Error(`Linq message text cannot be empty.`);let a=await(await this.getApiClient()).messages.update(t,{text:i,part_index:0});return{id:a.id,threadId:this.encodeThreadId({chatId:a.chat_id||r}),raw:a}}deleteMessage(e,t){throw new l(`deleteMessage is not implemented`)}async addReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`add`,...wn(n)})}async removeReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`remove`,...wn(n)})}async fetchThread(e){let t=this.requireChatId(e),n=await(await this.getApiClient()).chats.retrieve(t);return{id:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelId:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelName:n.display_name??void 0,isDM:!n.is_group,metadata:{chat:n}}}async startTyping(e,t){let n=this.requireChatId(e),{isGroup:r}=this.decodeThreadId(e);if(r!==!0)try{await(await this.getApiClient()).chats.typing.start(n)}catch(e){if($(e)&&e.status===403)return;throw e}}async markRead(e,t){let{chatId:n}=this.decodeThreadId(e);await(await this.getApiClient()).chats.markAsRead(n)}async stream(e,t){let n=``;for await(let e of t){if(typeof e==`string`){n+=e;continue}e.type===`markdown_text`&&(n+=e.text)}return this.postMessage(e,n.trim()?{markdown:n}:` `)}async handleWebhook(e,t){let n=this.webhookVerifier?await this.verifyTrustedWebhook(e):await Tn(e,await this.getSigningSecret());if(!n.ok)return n.response;let{event:r}=n;if(this.chat&&Xt(r)&&r.data.direction===`inbound`){let e=r.data.chat.id,n=r.data.chat.is_group??void 0;if(n===void 0&&!this.chatKinds.has(e))try{let t=await(await this.getApiClient()).chats.retrieve(e);this.chatKinds.set(e,t.is_group)}catch(t){this.logger.warn(`Failed to resolve Linq chat kind for ${e}`,{error:t})}let i=this.encodeThreadId({chatId:e,isGroup:n});this.chat.processMessage(this,i,async()=>this.parseMessage(r.data),t)}else if(this.chat&&Zt(r))this.processReactionWebhook(this.chat,r,t);else{let e=En[r.event_type];e&&this.processDeliveryStatusWebhook(r,e)}return new Response(`OK`,{status:200})}async verifyTrustedWebhook(e){let t=new Uint8Array(await e.arrayBuffer());try{if(await this.webhookVerifier?.(e,t)===!1)return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(new TextDecoder().decode(t))}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}onDeliveryStatus(e){return this.deliveryStatusListeners.add(e),()=>{this.deliveryStatusListeners.delete(e)}}emitDeliveryStatus(e){for(let t of this.deliveryStatusListeners)try{t(e)}catch(e){this.logger.warn(`Linq delivery-status listener threw`,{error:e})}}processDeliveryStatusWebhook(e,t){if(this.deliveryStatusListeners.size===0)return;let n=e.data,r=n.chat?.id,i=n.id;if(!r||!i){this.logger.debug(`Ignoring Linq ${e.event_type} webhook without chat/message ID`);return}let a={status:t,threadId:this.encodeThreadId({chatId:r}),messageId:i,raw:e,...n.error?{error:n.error}:{}};this.emitDeliveryStatus(a)}processReactionWebhook(e,t,n){let{chat_id:r,message_id:i}=t.data;if(!r||!i){this.logger.debug(`Ignoring Linq ${t.event_type} webhook without chat/message ID`);return}let a=Cn(t.data);if(!a){this.logger.debug(`Ignoring Linq ${t.event_type} webhook with unsupported reaction type ${t.data.reaction_type}`);return}let o=t.data.from_handle,s=t.data.is_from_me||o?.is_me===!0,c=o?.id||o?.handle||t.data.from||`unknown`,l=o?.handle||t.data.from||c;e.processReaction({adapter:this,added:t.event_type===`reaction.added`,emoji:a.emoji,rawEmoji:a.rawEmoji,messageId:i,threadId:this.encodeThreadId({chatId:r}),raw:t,user:{userId:c,userName:l,fullName:l,isBot:s,isMe:s}},n)}parseMessage(e){return Yt(e,e=>this.encodeThreadId(e))}rehydrateAttachment(e){let t=e.fetchMetadata?.url??e.url;return t?{...e,fetchData:async()=>{let e=await fetch(t);if(!e.ok)throw Error(`Failed to fetch Linq attachment ${t}: ${e.status}`);return Buffer.from(await e.arrayBuffer())}}:e}renderFormatted(e){return a(e).trim()}channelIdFromThreadId(e){return e}isDM(e){return this.decodeThreadId(e).isGroup===!1}};function On(e){return new Dn(e)}export{On as createLinqAdapter};