outbound-sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/dist/alerts/index.d.ts +2 -0
  4. package/dist/alerts/index.js +140 -0
  5. package/dist/alerts/plugin.d.ts +58 -0
  6. package/dist/audit/index.d.ts +33 -0
  7. package/dist/audit/index.js +60 -0
  8. package/dist/benchmarks/index.d.ts +29 -0
  9. package/dist/benchmarks/index.js +72 -0
  10. package/dist/budget/index.d.ts +21 -0
  11. package/dist/budget/index.js +71 -0
  12. package/dist/cache/index.d.ts +31 -0
  13. package/dist/cache/index.js +11 -0
  14. package/dist/cards/content.d.ts +43 -0
  15. package/dist/cards/copy-cards.d.ts +2 -0
  16. package/dist/cards/format.d.ts +39 -0
  17. package/dist/cards/index.d.ts +9 -0
  18. package/dist/cards/index.js +2070 -0
  19. package/dist/cards/notify-cards.d.ts +14 -0
  20. package/dist/cards/ops-cards.d.ts +2 -0
  21. package/dist/cards/parts.d.ts +22 -0
  22. package/dist/cards/people-cards.d.ts +2 -0
  23. package/dist/cards/render.d.ts +28 -0
  24. package/dist/cards/sender-cards.d.ts +2 -0
  25. package/dist/cards/slack-rich.d.ts +19 -0
  26. package/dist/cards/slack-text.d.ts +10 -0
  27. package/dist/cards/slack.d.ts +21 -0
  28. package/dist/cards/spec.d.ts +86 -0
  29. package/dist/cards/tool-cards.d.ts +4 -0
  30. package/dist/chunks/chunk-4O2HRTTI.js +75 -0
  31. package/dist/chunks/chunk-4PSO6JEK.js +357 -0
  32. package/dist/chunks/chunk-6CVZOUHB.js +152 -0
  33. package/dist/chunks/chunk-AFU5E5QB.js +714 -0
  34. package/dist/chunks/chunk-DJ2IUQEU.js +111 -0
  35. package/dist/chunks/chunk-E7JHLNLG.js +187 -0
  36. package/dist/chunks/chunk-FHKSLCVW.js +154 -0
  37. package/dist/chunks/chunk-FKH5N47I.js +40 -0
  38. package/dist/chunks/chunk-HZCTYL22.js +29 -0
  39. package/dist/chunks/chunk-IPUYZD4O.js +25 -0
  40. package/dist/chunks/chunk-IVH3NMQZ.js +61 -0
  41. package/dist/chunks/chunk-LVYG7XZJ.js +45 -0
  42. package/dist/chunks/chunk-NAKXLBA6.js +30 -0
  43. package/dist/chunks/chunk-NAWZ73QS.js +22 -0
  44. package/dist/chunks/chunk-PMSSUWD7.js +636 -0
  45. package/dist/chunks/chunk-PURHK3JU.js +432 -0
  46. package/dist/chunks/chunk-R3Y56YVF.js +43 -0
  47. package/dist/chunks/chunk-RCZ7ZZFU.js +92 -0
  48. package/dist/chunks/chunk-SBIZDCRY.js +106 -0
  49. package/dist/chunks/chunk-U2D34ARZ.js +41 -0
  50. package/dist/chunks/chunk-UAT3JSJZ.js +331 -0
  51. package/dist/chunks/chunk-VQSCHOBV.js +111 -0
  52. package/dist/chunks/chunk-XC6CZP73.js +80 -0
  53. package/dist/chunks/chunk-XNFESPZH.js +2307 -0
  54. package/dist/chunks/chunk-YOTW5ESM.js +118 -0
  55. package/dist/cli/bin.d.ts +2 -0
  56. package/dist/cli/bin.js +35 -0
  57. package/dist/cli/commands.d.ts +19 -0
  58. package/dist/cli/config.d.ts +22 -0
  59. package/dist/cli/index.d.ts +17 -0
  60. package/dist/cli/index.js +30 -0
  61. package/dist/cli/mcp.d.ts +14 -0
  62. package/dist/cli/stdio.d.ts +9 -0
  63. package/dist/clients/index.d.ts +2 -0
  64. package/dist/clients/index.js +117 -0
  65. package/dist/clients/plugin.d.ts +42 -0
  66. package/dist/combine/account.d.ts +4 -0
  67. package/dist/combine/adapter.d.ts +9 -0
  68. package/dist/combine/index.d.ts +2 -0
  69. package/dist/combine/index.js +420 -0
  70. package/dist/combine/route.d.ts +24 -0
  71. package/dist/exporter/index.d.ts +29 -0
  72. package/dist/exporter/index.js +77 -0
  73. package/dist/failover/index.d.ts +11 -0
  74. package/dist/failover/index.js +45 -0
  75. package/dist/fixtures/index.d.ts +27 -0
  76. package/dist/fixtures/index.js +260 -0
  77. package/dist/fixtures/scrub.d.ts +5 -0
  78. package/dist/heyreach/account.d.ts +11 -0
  79. package/dist/heyreach/adapter.d.ts +5 -0
  80. package/dist/heyreach/capabilities.d.ts +70 -0
  81. package/dist/heyreach/client.d.ts +18 -0
  82. package/dist/heyreach/inbox.d.ts +7 -0
  83. package/dist/heyreach/index.d.ts +25 -0
  84. package/dist/heyreach/index.js +1931 -0
  85. package/dist/heyreach/leads.d.ts +4 -0
  86. package/dist/heyreach/lookup.d.ts +15 -0
  87. package/dist/heyreach/map-account.d.ts +31 -0
  88. package/dist/heyreach/map-sequence.d.ts +5 -0
  89. package/dist/heyreach/map-stats.d.ts +13 -0
  90. package/dist/heyreach/map.d.ts +37 -0
  91. package/dist/heyreach/native-organization.d.ts +128 -0
  92. package/dist/heyreach/native-voice.d.ts +106 -0
  93. package/dist/heyreach/native.d.ts +496 -0
  94. package/dist/heyreach/paging.d.ts +7 -0
  95. package/dist/heyreach/webhooks.d.ts +3 -0
  96. package/dist/identity/index.d.ts +3 -0
  97. package/dist/identity/index.js +159 -0
  98. package/dist/identity/keys.d.ts +9 -0
  99. package/dist/identity/plugin.d.ts +34 -0
  100. package/dist/index.d.ts +33 -0
  101. package/dist/index.js +131 -0
  102. package/dist/insights/copy/copy-audit.d.ts +55 -0
  103. package/dist/insights/copy/copy-checks.d.ts +44 -0
  104. package/dist/insights/copy/copy-reuse.d.ts +59 -0
  105. package/dist/insights/copy/index.d.ts +67 -0
  106. package/dist/insights/copy/reply-timing.d.ts +63 -0
  107. package/dist/insights/copy/shared.d.ts +53 -0
  108. package/dist/insights/copy/step-funnel.d.ts +66 -0
  109. package/dist/insights/copy/variant-test.d.ts +64 -0
  110. package/dist/insights/define.d.ts +98 -0
  111. package/dist/insights/index.d.ts +10 -0
  112. package/dist/insights/index.js +4937 -0
  113. package/dist/insights/ops/anomalies.d.ts +80 -0
  114. package/dist/insights/ops/campaign-diagnosis.d.ts +39 -0
  115. package/dist/insights/ops/campaign-ranking.d.ts +56 -0
  116. package/dist/insights/ops/channel-mix.d.ts +44 -0
  117. package/dist/insights/ops/client-report.d.ts +76 -0
  118. package/dist/insights/ops/diagnosis-checks.d.ts +48 -0
  119. package/dist/insights/ops/index.d.ts +135 -0
  120. package/dist/insights/ops/period-comparison.d.ts +86 -0
  121. package/dist/insights/ops/pipeline-forecast.d.ts +44 -0
  122. package/dist/insights/ops/shared.d.ts +155 -0
  123. package/dist/insights/ops/tag-rollup.d.ts +32 -0
  124. package/dist/insights/people/account-summary.d.ts +68 -0
  125. package/dist/insights/people/dropped-replies.d.ts +51 -0
  126. package/dist/insights/people/find.d.ts +18 -0
  127. package/dist/insights/people/hot-leads.d.ts +67 -0
  128. package/dist/insights/people/index.d.ts +88 -0
  129. package/dist/insights/people/lead-collisions.d.ts +43 -0
  130. package/dist/insights/people/person-summary.d.ts +46 -0
  131. package/dist/insights/people/personalization-gaps.d.ts +60 -0
  132. package/dist/insights/people/read.d.ts +40 -0
  133. package/dist/insights/people/suppression-check.d.ts +53 -0
  134. package/dist/insights/plugin.d.ts +40 -0
  135. package/dist/insights/registry.d.ts +335 -0
  136. package/dist/insights/senders/bounce-watch.d.ts +70 -0
  137. package/dist/insights/senders/domain-health.d.ts +69 -0
  138. package/dist/insights/senders/index.d.ts +74 -0
  139. package/dist/insights/senders/read.d.ts +37 -0
  140. package/dist/insights/senders/sender-capacity.d.ts +67 -0
  141. package/dist/insights/senders/sender-load.d.ts +52 -0
  142. package/dist/insights/senders/settings-audit.d.ts +48 -0
  143. package/dist/insights/senders/warmup-readiness.d.ts +39 -0
  144. package/dist/insights/stats.d.ts +45 -0
  145. package/dist/insights/tools.d.ts +16 -0
  146. package/dist/insights/types.d.ts +4 -0
  147. package/dist/instantly/adapter-account.d.ts +5 -0
  148. package/dist/instantly/adapter-mail.d.ts +3 -0
  149. package/dist/instantly/adapter.d.ts +7 -0
  150. package/dist/instantly/capabilities.d.ts +85 -0
  151. package/dist/instantly/client.d.ts +24 -0
  152. package/dist/instantly/index.d.ts +27 -0
  153. package/dist/instantly/index.js +2627 -0
  154. package/dist/instantly/map-account.d.ts +38 -0
  155. package/dist/instantly/map-lead.d.ts +18 -0
  156. package/dist/instantly/map-stats.d.ts +25 -0
  157. package/dist/instantly/map.d.ts +22 -0
  158. package/dist/instantly/native-agents-sales.d.ts +161 -0
  159. package/dist/instantly/native-agents.d.ts +156 -0
  160. package/dist/instantly/native-campaigns.d.ts +101 -0
  161. package/dist/instantly/native-leads.d.ts +93 -0
  162. package/dist/instantly/native-params.d.ts +7 -0
  163. package/dist/instantly/native-search.d.ts +82 -0
  164. package/dist/instantly/native-senders.d.ts +182 -0
  165. package/dist/instantly/native-supersearch.d.ts +149 -0
  166. package/dist/instantly/native-workspace.d.ts +170 -0
  167. package/dist/instantly/native.d.ts +1081 -0
  168. package/dist/instantly/pages.d.ts +29 -0
  169. package/dist/instantly/stats.d.ts +5 -0
  170. package/dist/instantly/webhooks.d.ts +3 -0
  171. package/dist/internal/adapter.d.ts +211 -0
  172. package/dist/internal/capabilities.d.ts +104 -0
  173. package/dist/internal/client.d.ts +15 -0
  174. package/dist/internal/concurrency.d.ts +8 -0
  175. package/dist/internal/cursor.d.ts +10 -0
  176. package/dist/internal/engine/budget.d.ts +44 -0
  177. package/dist/internal/engine/engine.d.ts +45 -0
  178. package/dist/internal/engine/rate-store.d.ts +25 -0
  179. package/dist/internal/engine/request.d.ts +34 -0
  180. package/dist/internal/engine/retry.d.ts +21 -0
  181. package/dist/internal/engine/runtime.d.ts +13 -0
  182. package/dist/internal/entities-account.d.ts +205 -0
  183. package/dist/internal/entities.d.ts +493 -0
  184. package/dist/internal/env.d.ts +4 -0
  185. package/dist/internal/errors.d.ts +62 -0
  186. package/dist/internal/fields.d.ts +462 -0
  187. package/dist/internal/hooks.d.ts +55 -0
  188. package/dist/internal/json.d.ts +49 -0
  189. package/dist/internal/lead-fields.d.ts +21 -0
  190. package/dist/internal/lead-status.d.ts +13 -0
  191. package/dist/internal/limits.d.ts +34 -0
  192. package/dist/internal/metrics.d.ts +64 -0
  193. package/dist/internal/native.d.ts +81 -0
  194. package/dist/internal/outbound/api.d.ts +292 -0
  195. package/dist/internal/outbound/collections.d.ts +31 -0
  196. package/dist/internal/outbound/core.d.ts +36 -0
  197. package/dist/internal/outbound/create.d.ts +16 -0
  198. package/dist/internal/outbound/handles.d.ts +7 -0
  199. package/dist/internal/outbound/native.d.ts +4 -0
  200. package/dist/internal/outbound/operation-shared.d.ts +28 -0
  201. package/dist/internal/outbound/operations-account.d.ts +41 -0
  202. package/dist/internal/outbound/operations.d.ts +42 -0
  203. package/dist/internal/outbound/outbound.d.ts +67 -0
  204. package/dist/internal/outbound/plugins.d.ts +40 -0
  205. package/dist/internal/outbound/raw.d.ts +9 -0
  206. package/dist/internal/outbound/specs-account.d.ts +20 -0
  207. package/dist/internal/outbound/specs.d.ts +14 -0
  208. package/dist/internal/outbound/stats.d.ts +7 -0
  209. package/dist/internal/outbound/validate.d.ts +5 -0
  210. package/dist/internal/outbound/walker.d.ts +22 -0
  211. package/dist/internal/page.d.ts +14 -0
  212. package/dist/internal/record.d.ts +36 -0
  213. package/dist/internal/records.d.ts +7 -0
  214. package/dist/internal/redact.d.ts +18 -0
  215. package/dist/internal/ref.d.ts +16 -0
  216. package/dist/internal/sequence.d.ts +14 -0
  217. package/dist/internal/sha256.d.ts +6 -0
  218. package/dist/internal/text.d.ts +11 -0
  219. package/dist/internal/url.d.ts +9 -0
  220. package/dist/loader/index.d.ts +24 -0
  221. package/dist/loader/index.js +16 -0
  222. package/dist/memory/account-reads.d.ts +5 -0
  223. package/dist/memory/account.d.ts +81 -0
  224. package/dist/memory/adapter.d.ts +16 -0
  225. package/dist/memory/data.d.ts +137 -0
  226. package/dist/memory/demo.d.ts +7 -0
  227. package/dist/memory/index.d.ts +5 -0
  228. package/dist/memory/index.js +867 -0
  229. package/dist/memory/stats.d.ts +6 -0
  230. package/dist/memory/store.d.ts +18 -0
  231. package/dist/providers/index.d.ts +22 -0
  232. package/dist/providers/index.js +10 -0
  233. package/dist/reconcile/index.d.ts +2 -0
  234. package/dist/reconcile/index.js +72 -0
  235. package/dist/reconcile/plugin.d.ts +55 -0
  236. package/dist/redact/index.d.ts +2 -0
  237. package/dist/redact/index.js +197 -0
  238. package/dist/redact/plugin.d.ts +22 -0
  239. package/dist/redis/index.d.ts +41 -0
  240. package/dist/redis/index.js +114 -0
  241. package/dist/smartlead/account.d.ts +5 -0
  242. package/dist/smartlead/adapter.d.ts +5 -0
  243. package/dist/smartlead/capabilities.d.ts +87 -0
  244. package/dist/smartlead/client.d.ts +18 -0
  245. package/dist/smartlead/hmac.d.ts +7 -0
  246. package/dist/smartlead/index.d.ts +24 -0
  247. package/dist/smartlead/index.js +2329 -0
  248. package/dist/smartlead/leads.d.ts +9 -0
  249. package/dist/smartlead/lookup.d.ts +8 -0
  250. package/dist/smartlead/mail.d.ts +5 -0
  251. package/dist/smartlead/map-account.d.ts +34 -0
  252. package/dist/smartlead/map-messages.d.ts +31 -0
  253. package/dist/smartlead/map-stats.d.ts +36 -0
  254. package/dist/smartlead/map.d.ts +62 -0
  255. package/dist/smartlead/native-analytics.d.ts +242 -0
  256. package/dist/smartlead/native-campaigns.d.ts +211 -0
  257. package/dist/smartlead/native-inbox.d.ts +141 -0
  258. package/dist/smartlead/native-params.d.ts +12 -0
  259. package/dist/smartlead/native-services.d.ts +204 -0
  260. package/dist/smartlead/native.d.ts +785 -0
  261. package/dist/smartlead/shared.d.ts +29 -0
  262. package/dist/smartlead/stats.d.ts +5 -0
  263. package/dist/smartlead/webhooks.d.ts +3 -0
  264. package/dist/sync/index.d.ts +2 -0
  265. package/dist/sync/index.js +158 -0
  266. package/dist/sync/plugin.d.ts +58 -0
  267. package/dist/tools/account-tools.d.ts +21 -0
  268. package/dist/tools/ai-sdk.d.ts +8 -0
  269. package/dist/tools/ai-sdk.js +28 -0
  270. package/dist/tools/campaign-tools.d.ts +59 -0
  271. package/dist/tools/claude-agent.d.ts +18 -0
  272. package/dist/tools/claude-agent.js +42 -0
  273. package/dist/tools/index.d.ts +28 -0
  274. package/dist/tools/index.js +22 -0
  275. package/dist/tools/people-tools.d.ts +19 -0
  276. package/dist/tools/registry.d.ts +34 -0
  277. package/dist/tools/shared.d.ts +75 -0
  278. package/dist/tracing/index.d.ts +25 -0
  279. package/dist/tracing/index.js +69 -0
  280. package/dist/webhooks/index.d.ts +3 -0
  281. package/dist/webhooks/index.js +227 -0
  282. package/dist/webhooks/parse.d.ts +41 -0
  283. package/dist/webhooks/secret.d.ts +4 -0
  284. package/package.json +181 -4
@@ -0,0 +1,2307 @@
1
+ import {
2
+ defaultRateLimitStore
3
+ } from "./chunk-4O2HRTTI.js";
4
+ import {
5
+ buildUrl
6
+ } from "./chunk-NAWZ73QS.js";
7
+ import {
8
+ sha256Hex
9
+ } from "./chunk-FHKSLCVW.js";
10
+ import {
11
+ CAPABILITY_KEYS,
12
+ blockEntrySchema,
13
+ campaignProgressSchema,
14
+ campaignSettingsSchema,
15
+ intersectCapabilities,
16
+ leadListSchema,
17
+ placementTestSchema,
18
+ requireCapability,
19
+ resolveCapabilities,
20
+ resolveFields,
21
+ senderHealthSchema,
22
+ tagSchema,
23
+ webhookSubscriptionSchema
24
+ } from "./chunk-UAT3JSJZ.js";
25
+ import {
26
+ campaignSchema,
27
+ leadSchema,
28
+ messageSchema,
29
+ metricRowSchema,
30
+ replySchema,
31
+ senderSchema,
32
+ sequenceSchema,
33
+ workspaceSchema
34
+ } from "./chunk-4PSO6JEK.js";
35
+ import {
36
+ sourceIdFor
37
+ } from "./chunk-LVYG7XZJ.js";
38
+ import {
39
+ OutboundError,
40
+ redactUrl
41
+ } from "./chunk-E7JHLNLG.js";
42
+ import {
43
+ count,
44
+ field,
45
+ isJsonObject,
46
+ isString,
47
+ parseJson
48
+ } from "./chunk-VQSCHOBV.js";
49
+
50
+ // src/internal/limits.ts
51
+ var DEFAULT_CONCURRENCY = 8;
52
+ var DEFAULT_SHARE = 0.5;
53
+ var scaleWindow = (window, share) => ({
54
+ perMs: window.perMs,
55
+ requests: Math.max(1, Math.floor(window.requests * share))
56
+ });
57
+
58
+ // src/internal/engine/retry.ts
59
+ var BASE_MS = 1e3;
60
+ var CAP_MS = 6e4;
61
+ var fullJitterBackoff = (attempt2, random) => Math.floor(random * Math.min(CAP_MS, BASE_MS * 2 ** (attempt2 - 1)));
62
+ var DEFAULT_RETRIES = 4;
63
+ var resolveRetryPolicy = (option) => {
64
+ if (option === void 0) {
65
+ return { backoff: fullJitterBackoff, max: DEFAULT_RETRIES };
66
+ }
67
+ if (isRetryCount(option)) {
68
+ return { backoff: fullJitterBackoff, max: Math.max(0, Math.floor(option)) };
69
+ }
70
+ return {
71
+ backoff: option.backoff ?? fullJitterBackoff,
72
+ max: Math.max(0, Math.floor(option.max))
73
+ };
74
+ };
75
+ var isRetryCount = (option) => typeof option === "number";
76
+ var secondsFromBody = (body) => {
77
+ if (!isJsonObject(body)) {
78
+ return void 0;
79
+ }
80
+ for (const key of ["retry_after", "retryAfter", "retry_after_seconds"]) {
81
+ const seconds = count(field(body, key));
82
+ if (seconds !== null) {
83
+ return seconds;
84
+ }
85
+ }
86
+ return void 0;
87
+ };
88
+ var parseRetryAfter = (headers, body, now) => {
89
+ const header = headers.get("retry-after");
90
+ if (header !== null && header.trim() !== "") {
91
+ const seconds2 = Number(header);
92
+ if (Number.isFinite(seconds2)) {
93
+ return Math.max(0, Math.ceil(seconds2 * 1e3));
94
+ }
95
+ const date = Date.parse(header);
96
+ if (!Number.isNaN(date)) {
97
+ return Math.max(0, date - now);
98
+ }
99
+ }
100
+ const seconds = secondsFromBody(body);
101
+ return seconds === void 0 ? void 0 : Math.max(0, Math.ceil(seconds * 1e3));
102
+ };
103
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
104
+ 408,
105
+ 429,
106
+ 500,
107
+ 502,
108
+ 503,
109
+ 504
110
+ ]);
111
+ var isRetryableStatus = (status) => RETRYABLE_STATUSES.has(status);
112
+
113
+ // src/internal/hooks.ts
114
+ var ignore = () => {
115
+ };
116
+ var fire = (hook, event) => {
117
+ if (hook === void 0) {
118
+ return;
119
+ }
120
+ try {
121
+ Promise.resolve(hook(event)).catch(ignore);
122
+ } catch {
123
+ ignore();
124
+ }
125
+ };
126
+ var mergeHooks = (all) => {
127
+ const defined = all.filter((hooks) => hooks !== void 0);
128
+ return {
129
+ onAction: (event) => {
130
+ for (const hooks of defined) {
131
+ fire(hooks.onAction, event);
132
+ }
133
+ },
134
+ onError: (event) => {
135
+ for (const hooks of defined) {
136
+ fire(hooks.onError, event);
137
+ }
138
+ },
139
+ onRequest: (event) => {
140
+ for (const hooks of defined) {
141
+ fire(hooks.onRequest, event);
142
+ }
143
+ },
144
+ onRetry: (event) => {
145
+ for (const hooks of defined) {
146
+ fire(hooks.onRetry, event);
147
+ }
148
+ },
149
+ onThrottle: (event) => {
150
+ for (const hooks of defined) {
151
+ fire(hooks.onThrottle, event);
152
+ }
153
+ }
154
+ };
155
+ };
156
+
157
+ // src/internal/engine/runtime.ts
158
+ var defaultRuntime = {
159
+ fetch: (input, init) => fetch(input, init),
160
+ now: () => Date.now(),
161
+ random: () => Math.random(),
162
+ timer: (ms, onFire) => {
163
+ const handle = setTimeout(onFire, ms);
164
+ return () => {
165
+ clearTimeout(handle);
166
+ };
167
+ }
168
+ };
169
+ var abortedError = (provider) => new OutboundError("Provider", "The call was aborted", {
170
+ aborted: true,
171
+ provider
172
+ });
173
+ var sleep = (runtime, ms, provider, signal) => (
174
+ // oxlint-disable-next-line promise/avoid-new -- wraps a callback timer.
175
+ new Promise((resolve2, reject) => {
176
+ if (signal?.aborted) {
177
+ reject(abortedError(provider));
178
+ return;
179
+ }
180
+ const onAbort = () => {
181
+ cancel();
182
+ reject(abortedError(provider));
183
+ };
184
+ const cancel = runtime.timer(Math.max(0, ms), () => {
185
+ signal?.removeEventListener("abort", onAbort);
186
+ resolve2();
187
+ });
188
+ signal?.addEventListener("abort", onAbort, { once: true });
189
+ })
190
+ );
191
+
192
+ // src/internal/engine/budget.ts
193
+ var DEFAULT_LANE = "default";
194
+ var MIN_FACTOR = 0.1;
195
+ var RECOVERY_STEP = 0.05;
196
+ var Budget = class {
197
+ #options;
198
+ #waiting = [];
199
+ #inFlight = 0;
200
+ /** Drops to slow down after a 429, then recovers toward 1. */
201
+ #factor = 1;
202
+ constructor(options) {
203
+ this.#options = options;
204
+ }
205
+ #windows(lane) {
206
+ const { limits, share } = this.#options;
207
+ const declared = lane === DEFAULT_LANE ? limits.windows : limits.lanes?.[lane] ?? [];
208
+ return declared.map((window) => scaleWindow(window, share * this.#factor));
209
+ }
210
+ #storeKey(lane) {
211
+ return lane === DEFAULT_LANE ? this.#options.key : `${this.#options.key}#${lane}`;
212
+ }
213
+ async #reserve(lane, now) {
214
+ const { store } = this.#options;
215
+ if (lane !== DEFAULT_LANE) {
216
+ const laneWait = await store.reserve(
217
+ this.#storeKey(lane),
218
+ this.#windows(lane),
219
+ now
220
+ );
221
+ if (laneWait > 0) {
222
+ return laneWait;
223
+ }
224
+ }
225
+ return await store.reserve(
226
+ this.#options.key,
227
+ this.#windows(DEFAULT_LANE),
228
+ now
229
+ );
230
+ }
231
+ async #enter(options) {
232
+ const cap = this.#options.limits.concurrency ?? DEFAULT_CONCURRENCY;
233
+ if (this.#inFlight < cap) {
234
+ this.#inFlight += 1;
235
+ return;
236
+ }
237
+ await new Promise((resolve2, reject) => {
238
+ const onAbort = () => {
239
+ const index = this.#waiting.indexOf(enter);
240
+ if (index !== -1) {
241
+ this.#waiting.splice(index, 1);
242
+ }
243
+ reject(abortedError(this.#options.provider));
244
+ };
245
+ const enter = () => {
246
+ options.signal?.removeEventListener("abort", onAbort);
247
+ resolve2();
248
+ };
249
+ this.#waiting.push(enter);
250
+ options.signal?.addEventListener("abort", onAbort, { once: true });
251
+ });
252
+ }
253
+ /**
254
+ * Waits for a concurrency slot and for room in every window. Returns how
255
+ * long it waited. The caller must call `release()` afterwards.
256
+ */
257
+ async acquire(options) {
258
+ const { provider } = this.#options;
259
+ const { deadlineAt, hooks, lane, runtime, signal } = options;
260
+ if (signal?.aborted) {
261
+ throw abortedError(provider);
262
+ }
263
+ await this.#enter(options);
264
+ let waited = 0;
265
+ try {
266
+ for (; ; ) {
267
+ const now = runtime.now();
268
+ const waitMs = await this.#reserve(lane, now);
269
+ if (waitMs === 0) {
270
+ return waited;
271
+ }
272
+ if (deadlineAt !== void 0 && now + waitMs > deadlineAt) {
273
+ throw new OutboundError(
274
+ "RateLimited",
275
+ `${provider} rate budget is full and the deadline would pass before it frees up`,
276
+ { provider, retryAfterMs: waitMs, timedOut: true }
277
+ );
278
+ }
279
+ fire(hooks.onThrottle, { lane, provider, waitMs });
280
+ await sleep(runtime, waitMs, provider, signal);
281
+ waited += waitMs;
282
+ }
283
+ } catch (error) {
284
+ this.release();
285
+ throw error;
286
+ }
287
+ }
288
+ release() {
289
+ const resume = this.#waiting.shift();
290
+ if (resume === void 0) {
291
+ this.#inFlight = Math.max(0, this.#inFlight - 1);
292
+ } else {
293
+ resume();
294
+ }
295
+ }
296
+ /** Called on a 429: pause the lane and halve the rate. */
297
+ async rateLimited(lane, retryAfterMs, now) {
298
+ this.#factor = Math.max(MIN_FACTOR, this.#factor / 2);
299
+ await this.#options.store.pause(this.#storeKey(lane), now + retryAfterMs);
300
+ }
301
+ /** Called when the vendor's headers say the window is spent. */
302
+ async exhausted(resetInMs, now) {
303
+ await this.#options.store.pause(this.#options.key, now + resetInMs);
304
+ }
305
+ /** Called on a success: climb back toward the declared rate. */
306
+ succeeded() {
307
+ this.#factor = Math.min(1, this.#factor + RECOVERY_STEP);
308
+ }
309
+ async usage(now) {
310
+ const lanes = [
311
+ DEFAULT_LANE,
312
+ ...Object.keys(this.#options.limits.lanes ?? {})
313
+ ];
314
+ const perLane = await Promise.all(
315
+ lanes.map(async (lane) => {
316
+ const windows = this.#windows(lane);
317
+ const used = await this.#options.store.usage(
318
+ this.#storeKey(lane),
319
+ windows,
320
+ now
321
+ );
322
+ return windows.map((window, index) => ({
323
+ lane,
324
+ perMs: window.perMs,
325
+ requests: window.requests,
326
+ used: used[index] ?? 0
327
+ }));
328
+ })
329
+ );
330
+ return perLane.flat();
331
+ }
332
+ };
333
+
334
+ // src/internal/engine/request.ts
335
+ var DEFAULT_TIMEOUT_MS = 3e4;
336
+ var TIMED_OUT = /* @__PURE__ */ Symbol("timed-out");
337
+ var readBody = async (response) => {
338
+ const raw = await response.text();
339
+ if (raw === "") {
340
+ return null;
341
+ }
342
+ return parseJson(raw) ?? raw;
343
+ };
344
+ var fetchOnce = async (spec, environment) => {
345
+ const { runtime, state } = environment;
346
+ const controller = new AbortController();
347
+ const onCallerAbort = () => {
348
+ controller.abort();
349
+ };
350
+ let timedOut = false;
351
+ const cancelTimer = runtime.timer(state.timeoutMs, () => {
352
+ timedOut = true;
353
+ controller.abort();
354
+ });
355
+ state.signal?.addEventListener("abort", onCallerAbort, { once: true });
356
+ try {
357
+ return await runtime.fetch(spec.url, {
358
+ headers: {
359
+ accept: "application/json",
360
+ ...spec.body === void 0 ? void 0 : { "content-type": "application/json" },
361
+ ...spec.headers
362
+ },
363
+ method: spec.method,
364
+ signal: controller.signal,
365
+ ...spec.body === void 0 ? void 0 : { body: JSON.stringify(spec.body) }
366
+ });
367
+ } catch (error) {
368
+ throw timedOut ? TIMED_OUT : error;
369
+ } finally {
370
+ cancelTimer();
371
+ state.signal?.removeEventListener("abort", onCallerAbort);
372
+ }
373
+ };
374
+ var noteHeaders = async (response, environment) => {
375
+ const { adapter, budget, runtime } = environment;
376
+ const names = adapter.limits.headers;
377
+ if (names?.remaining === void 0 || names.reset === void 0) {
378
+ return;
379
+ }
380
+ const remaining = count(response.headers.get(names.remaining));
381
+ const reset = count(response.headers.get(names.reset));
382
+ if (remaining === null || reset === null || remaining > 0) {
383
+ return;
384
+ }
385
+ const now = runtime.now();
386
+ const resetInMs = names.resetUnit === "epoch-seconds" ? reset * 1e3 - now : reset * 1e3;
387
+ if (resetInMs > 0) {
388
+ await budget.exhausted(resetInMs, now);
389
+ }
390
+ };
391
+ var failureFor = async (response, body, spec, environment) => {
392
+ const { adapter, budget, runtime } = environment;
393
+ const now = runtime.now();
394
+ const retryAfterMs = parseRetryAfter(response.headers, body, now);
395
+ const failure = { body, retryAfterMs, status: response.status };
396
+ const error = adapter.mapError(failure);
397
+ if (response.status === 429) {
398
+ await budget.rateLimited(
399
+ spec.lane ?? DEFAULT_LANE,
400
+ retryAfterMs ?? 1e3,
401
+ now
402
+ );
403
+ }
404
+ if (!isRetryableStatus(response.status)) {
405
+ throw error;
406
+ }
407
+ return retryAfterMs === void 0 ? { error, kind: "retry" } : { error, kind: "retry", retryAfterMs };
408
+ };
409
+ var attempt = async (spec, environment, attemptNumber) => {
410
+ const { adapter, budget, hooks, runtime, state } = environment;
411
+ const lane = spec.lane ?? DEFAULT_LANE;
412
+ state.throttledMs += await budget.acquire({
413
+ deadlineAt: state.deadlineAt,
414
+ hooks,
415
+ lane,
416
+ runtime,
417
+ signal: state.signal
418
+ });
419
+ try {
420
+ assertRequestBudget(environment);
421
+ state.beforeRequest?.();
422
+ } catch (error) {
423
+ budget.release();
424
+ throw error;
425
+ }
426
+ state.requests += 1;
427
+ const startedAt = runtime.now();
428
+ let status = null;
429
+ try {
430
+ const response = await fetchOnce(spec, environment);
431
+ ({ status } = response);
432
+ const body = await readBody(response);
433
+ await noteHeaders(response, environment);
434
+ if (response.ok) {
435
+ budget.succeeded();
436
+ return {
437
+ kind: "ok",
438
+ response: { body, headers: response.headers, status: response.status }
439
+ };
440
+ }
441
+ return await failureFor(response, body, spec, environment);
442
+ } catch (error) {
443
+ if (OutboundError.is(error)) {
444
+ throw error;
445
+ }
446
+ if (state.signal?.aborted) {
447
+ throw abortedError(adapter.name);
448
+ }
449
+ const timedOut = error === TIMED_OUT;
450
+ const message = timedOut ? `${adapter.name} did not answer within ${state.timeoutMs} ms` : `${adapter.name} request failed: ${error instanceof Error ? error.message : String(error)}`;
451
+ return {
452
+ error: new OutboundError("Provider", message, {
453
+ cause: timedOut ? void 0 : error,
454
+ provider: adapter.name,
455
+ secrets: adapter.secrets,
456
+ timedOut
457
+ }),
458
+ kind: "retry"
459
+ };
460
+ } finally {
461
+ budget.release();
462
+ fire(hooks.onRequest, {
463
+ attempt: attemptNumber,
464
+ durationMs: runtime.now() - startedAt,
465
+ lane,
466
+ method: spec.method,
467
+ provider: adapter.name,
468
+ status,
469
+ url: redactUrl(spec.url, adapter.secrets)
470
+ });
471
+ }
472
+ };
473
+ var assertRequestBudget = (environment) => {
474
+ const { adapter, state } = environment;
475
+ if (state.maxRequests !== void 0 && state.requests >= state.maxRequests) {
476
+ throw new OutboundError(
477
+ "RateLimited",
478
+ `The call used its budget of ${state.maxRequests} request(s) to ${adapter.name}`,
479
+ { provider: adapter.name }
480
+ );
481
+ }
482
+ };
483
+ var exhausted = (error, timedOut) => timedOut ? new OutboundError(error.code, error.message, {
484
+ cause: error.cause,
485
+ provider: error.provider,
486
+ retryAfterMs: error.retryAfterMs,
487
+ status: error.status,
488
+ timedOut: true
489
+ }) : error;
490
+ var execute = async (spec, environment) => {
491
+ const { adapter, hooks, runtime, state } = environment;
492
+ for (let attemptNumber = 1; ; attemptNumber += 1) {
493
+ assertRequestBudget(environment);
494
+ const result = await attempt(spec, environment, attemptNumber);
495
+ if (result.kind === "ok") {
496
+ return result.response;
497
+ }
498
+ if (attemptNumber > state.retry.max) {
499
+ throw result.error;
500
+ }
501
+ const backoff = state.retry.backoff(attemptNumber, runtime.random());
502
+ const delayMs = Math.max(result.retryAfterMs ?? 0, backoff);
503
+ if (state.deadlineAt !== void 0 && runtime.now() + delayMs > state.deadlineAt) {
504
+ throw exhausted(result.error, true);
505
+ }
506
+ fire(hooks.onRetry, {
507
+ attempt: attemptNumber,
508
+ delayMs,
509
+ provider: adapter.name,
510
+ reason: result.error.message,
511
+ url: redactUrl(spec.url, adapter.secrets)
512
+ });
513
+ await sleep(runtime, delayMs, adapter.name, state.signal);
514
+ }
515
+ };
516
+
517
+ // src/internal/engine/engine.ts
518
+ var BUDGETS = /* @__PURE__ */ Symbol.for("outbound-sdk.budgets");
519
+ var budgetsFor = (store) => {
520
+ const scope = globalThis;
521
+ scope[BUDGETS] ??= /* @__PURE__ */ new WeakMap();
522
+ let budgets = scope[BUDGETS].get(store);
523
+ if (budgets === void 0) {
524
+ budgets = /* @__PURE__ */ new Map();
525
+ scope[BUDGETS].set(store, budgets);
526
+ }
527
+ return budgets;
528
+ };
529
+ var credentialKey = (adapter) => adapter.secrets.length === 0 ? `${adapter.name}:${adapter.workspaceId}` : `${adapter.name}:${sha256Hex(adapter.secrets.join("")).slice(0, 24)}`;
530
+ var RequestEngine = class {
531
+ #runtime;
532
+ #store;
533
+ #hooks;
534
+ #share;
535
+ #defaults;
536
+ constructor(options = {}) {
537
+ this.#runtime = { ...defaultRuntime, ...options.runtime };
538
+ this.#store = options.store ?? defaultRateLimitStore();
539
+ this.#hooks = options.hooks ?? {};
540
+ this.#share = options.share ?? DEFAULT_SHARE;
541
+ this.#defaults = options.defaults ?? {};
542
+ if (!(this.#share > 0 && this.#share <= 1)) {
543
+ throw new OutboundError(
544
+ "Invalid",
545
+ "share must be greater than 0 and at most 1"
546
+ );
547
+ }
548
+ }
549
+ get hooks() {
550
+ return this.#hooks;
551
+ }
552
+ now() {
553
+ return this.#runtime.now();
554
+ }
555
+ #budget(adapter) {
556
+ const budgets = budgetsFor(this.#store);
557
+ const key = credentialKey(adapter);
558
+ let budget = budgets.get(key);
559
+ if (budget === void 0) {
560
+ budget = new Budget({
561
+ key,
562
+ limits: adapter.limits,
563
+ provider: adapter.name,
564
+ share: this.#share,
565
+ store: this.#store
566
+ });
567
+ budgets.set(key, budget);
568
+ }
569
+ return budget;
570
+ }
571
+ /** Starts the accounting for one SDK call. */
572
+ begin(options = {}) {
573
+ const merged = { ...this.#defaults, ...options };
574
+ return {
575
+ beforeRequest: void 0,
576
+ deadlineAt: merged.deadline === void 0 ? void 0 : this.now() + merged.deadline,
577
+ maxRequests: merged.maxRequests,
578
+ requests: 0,
579
+ retry: resolveRetryPolicy(merged.retries),
580
+ signal: merged.signal,
581
+ throttledMs: 0,
582
+ timeoutMs: merged.timeout ?? DEFAULT_TIMEOUT_MS
583
+ };
584
+ }
585
+ contextFor(adapter, state) {
586
+ return {
587
+ forAdapter: (other) => this.contextFor(other, state),
588
+ request: (spec) => execute(spec, {
589
+ adapter,
590
+ budget: this.#budget(adapter),
591
+ hooks: this.#hooks,
592
+ runtime: this.#runtime,
593
+ state
594
+ })
595
+ };
596
+ }
597
+ async limits(adapter) {
598
+ return {
599
+ provider: adapter.name,
600
+ share: this.#share,
601
+ source: adapter.limits.source,
602
+ windows: await this.#budget(adapter).usage(this.now()),
603
+ workspaceId: adapter.workspaceId
604
+ };
605
+ }
606
+ };
607
+
608
+ // src/internal/cursor.ts
609
+ var VERSION = 1;
610
+ var toBase64Url = (value) => {
611
+ const bytes = new TextEncoder().encode(value);
612
+ let binary = "";
613
+ for (const byte of bytes) {
614
+ binary += String.fromCodePoint(byte);
615
+ }
616
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/[=]+$/u, "");
617
+ };
618
+ var fromBase64Url = (value) => {
619
+ try {
620
+ const binary = atob(value.replaceAll("-", "+").replaceAll("_", "/"));
621
+ const bytes = Uint8Array.from(binary, (char) => char.codePointAt(0) ?? 0);
622
+ return new TextDecoder().decode(bytes);
623
+ } catch {
624
+ return void 0;
625
+ }
626
+ };
627
+ var encodeCursor = (scope, next) => toBase64Url(
628
+ JSON.stringify({
629
+ a: scope.action,
630
+ n: next,
631
+ p: scope.provider,
632
+ v: VERSION,
633
+ w: scope.workspaceId
634
+ })
635
+ );
636
+ var decodeCursor = (scope, cursor) => {
637
+ const decoded = fromBase64Url(cursor);
638
+ const parsed = decoded === void 0 ? void 0 : parseJson(decoded);
639
+ const next = field(parsed, "n");
640
+ const matches2 = field(parsed, "v") === VERSION && field(parsed, "p") === scope.provider && field(parsed, "w") === scope.workspaceId && field(parsed, "a") === scope.action;
641
+ if (!matches2 || next === void 0) {
642
+ const owner = isString(field(parsed, "a")) ? ` (it belongs to ${String(field(parsed, "a"))})` : "";
643
+ throw new OutboundError(
644
+ "Invalid",
645
+ `The cursor is not valid for ${scope.action}${owner}`,
646
+ {
647
+ provider: scope.provider
648
+ }
649
+ );
650
+ }
651
+ return next;
652
+ };
653
+
654
+ // src/internal/outbound/core.ts
655
+ var infoFor = (core, state) => ({
656
+ adapter: core.adapter,
657
+ provider: core.adapter.name,
658
+ state,
659
+ workspaceId: core.adapter.workspaceId
660
+ });
661
+ var toOutboundError = (core, cause) => OutboundError.is(cause) ? cause : core.adapter.mapError(cause);
662
+ var perform = async (core, action, options, body, shared, isAnswer) => {
663
+ const state = shared ?? core.engine.begin(options);
664
+ const startedAt = core.engine.now();
665
+ const { hooks } = core.engine;
666
+ const scope = {
667
+ action,
668
+ provider: core.adapter.name,
669
+ workspaceId: core.adapter.workspaceId
670
+ };
671
+ const done = () => {
672
+ fire(hooks.onAction, {
673
+ ...scope,
674
+ durationMs: core.engine.now() - startedAt,
675
+ requests: state.requests,
676
+ throttledMs: state.throttledMs
677
+ });
678
+ };
679
+ try {
680
+ const result = await body(state);
681
+ done();
682
+ return result;
683
+ } catch (error) {
684
+ const mapped = toOutboundError(core, error);
685
+ if (isAnswer?.(mapped) === true) {
686
+ done();
687
+ } else {
688
+ fire(hooks.onError, { ...scope, error: mapped });
689
+ }
690
+ throw mapped;
691
+ }
692
+ };
693
+ var metaFor = (core, state, input) => ({
694
+ complete: input.complete,
695
+ evidence: input.evidence,
696
+ fetchedAt: input.fetchedAt ?? new Date(core.engine.now()).toISOString(),
697
+ provider: core.adapter.name,
698
+ requests: state.requests,
699
+ stale: input.stale ?? false,
700
+ throttledMs: state.throttledMs,
701
+ workspaceId: core.adapter.workspaceId
702
+ });
703
+ var matches = (schema, record) => schema.safeParse(record).success;
704
+ var checked = (core, schema, records, action) => {
705
+ const items = [];
706
+ for (const record of records) {
707
+ if (!matches(schema, record)) {
708
+ const issue = schema.safeParse(record).error?.issues[0];
709
+ const where = issue === void 0 ? "" : ` at ${issue.path.join(".")}: ${issue.message}`;
710
+ throw new OutboundError(
711
+ "Provider",
712
+ `The ${core.adapter.name} adapter returned an invalid record for ${action}${where}`,
713
+ { provider: core.adapter.name }
714
+ );
715
+ }
716
+ items.push(record);
717
+ }
718
+ return items;
719
+ };
720
+
721
+ // src/internal/outbound/validate.ts
722
+ var DATE = /^\d{4}-\d{2}-\d{2}$/u;
723
+ var invalid = (message) => new OutboundError("Invalid", message);
724
+ var normalizeInstant = (value, name) => {
725
+ if (value === void 0) {
726
+ return void 0;
727
+ }
728
+ const time = Date.parse(value);
729
+ if (Number.isNaN(time)) {
730
+ throw invalid(
731
+ `${name} must be an ISO 8601 date or timestamp, got "${value}"`
732
+ );
733
+ }
734
+ return new Date(time).toISOString();
735
+ };
736
+ var normalizeRange = (range) => {
737
+ const since = normalizeInstant(range.since, "since");
738
+ const until = normalizeInstant(range.until, "until");
739
+ if (since !== void 0 && until !== void 0 && since > until) {
740
+ throw invalid("since must not be after until");
741
+ }
742
+ return { since, until };
743
+ };
744
+ var assertDay = (value, name) => {
745
+ if (value !== void 0 && (!DATE.test(value) || Number.isNaN(Date.parse(value)))) {
746
+ throw invalid(`${name} must be a date in YYYY-MM-DD form, got "${value}"`);
747
+ }
748
+ return value;
749
+ };
750
+ var assertLimit = (limit) => {
751
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1)) {
752
+ throw invalid(`limit must be a positive integer, got ${limit}`);
753
+ }
754
+ return limit;
755
+ };
756
+ var assertId = (id, what) => {
757
+ if (id.trim() === "") {
758
+ throw invalid(`${what} id must not be empty`);
759
+ }
760
+ return id;
761
+ };
762
+
763
+ // src/internal/outbound/walker.ts
764
+ var PageWalker = class {
765
+ #options;
766
+ #cursor;
767
+ #meta;
768
+ #truncated = false;
769
+ constructor(options) {
770
+ this.#options = options;
771
+ this.#cursor = options.cursor;
772
+ }
773
+ get cursor() {
774
+ return this.#cursor;
775
+ }
776
+ get meta() {
777
+ return this.#meta;
778
+ }
779
+ get truncated() {
780
+ return this.#truncated;
781
+ }
782
+ async *[Symbol.asyncIterator]() {
783
+ const { fetchPage: fetchPage2, keyOf, max } = this.#options;
784
+ const seen = /* @__PURE__ */ new Set();
785
+ let state;
786
+ let yielded = 0;
787
+ for (; ; ) {
788
+ const fetched = await fetchPage2(this.#cursor, state);
789
+ ({ state } = fetched);
790
+ this.#meta = fetched.page.meta;
791
+ for (const item of fetched.page.items) {
792
+ const key = keyOf(item);
793
+ if (key === void 0 || !seen.has(key)) {
794
+ if (key !== void 0) {
795
+ seen.add(key);
796
+ }
797
+ if (max !== void 0 && yielded >= max) {
798
+ this.#truncated = true;
799
+ return;
800
+ }
801
+ yielded += 1;
802
+ yield item;
803
+ }
804
+ }
805
+ this.#cursor = fetched.page.cursor;
806
+ if (this.#cursor === void 0) {
807
+ return;
808
+ }
809
+ if (max !== void 0 && yielded >= max) {
810
+ this.#truncated = true;
811
+ return;
812
+ }
813
+ }
814
+ }
815
+ async toArray() {
816
+ const items = [];
817
+ for await (const item of this) {
818
+ items.push(item);
819
+ }
820
+ return items;
821
+ }
822
+ };
823
+
824
+ // src/internal/outbound/collections.ts
825
+ var DEFAULT_BULK_CONCURRENCY = 4;
826
+ var cursorScope = (core, action) => ({
827
+ action,
828
+ provider: core.adapter.name,
829
+ workspaceId: core.adapter.workspaceId
830
+ });
831
+ var fetchPage = (core, spec, request, options, shared) => perform(
832
+ core,
833
+ spec.action,
834
+ options,
835
+ async (state) => {
836
+ const scope = cursorScope(core, spec.action);
837
+ const next = request.cursor === void 0 ? void 0 : decodeCursor(scope, request.cursor);
838
+ const output2 = await core.run(
839
+ spec.toOperation(request.filters, { limit: request.limit, next }),
840
+ infoFor(core, state)
841
+ );
842
+ const complete = output2.next === void 0;
843
+ const page = {
844
+ complete,
845
+ cursor: output2.next === void 0 ? void 0 : encodeCursor(scope, output2.next),
846
+ items: checked(core, spec.schema, output2.items, spec.action),
847
+ meta: metaFor(core, state, {
848
+ complete,
849
+ evidence: output2.evidence,
850
+ fetchedAt: output2.fetchedAt,
851
+ stale: output2.stale
852
+ })
853
+ };
854
+ return { page, state };
855
+ },
856
+ shared
857
+ );
858
+ var makeReadCollection = (core, spec) => ({
859
+ list: async (options) => {
860
+ const filters = spec.prepare(options ?? {});
861
+ const limit = assertLimit(options?.limit);
862
+ const { page } = await fetchPage(
863
+ core,
864
+ spec,
865
+ { cursor: options?.cursor, filters, limit },
866
+ options
867
+ );
868
+ return page;
869
+ },
870
+ listAll: (options) => {
871
+ const filters = spec.prepare(options ?? {});
872
+ const limit = assertLimit(options?.limit);
873
+ const walkOptions = options;
874
+ return new PageWalker({
875
+ cursor: walkOptions?.cursor,
876
+ fetchPage: (cursor, state) => fetchPage(core, spec, { cursor, filters, limit }, options, state),
877
+ keyOf: (item) => spec.keyOf(item, filters),
878
+ max: walkOptions?.max
879
+ });
880
+ }
881
+ });
882
+ var isMissing = (error) => error.code === "NotFound";
883
+ var getOne = (core, spec, id, options, shared, missingIsAnswer = false) => perform(
884
+ core,
885
+ spec.action,
886
+ options,
887
+ async (state) => {
888
+ const output2 = await core.run(
889
+ spec.toOperation(assertId(id, spec.what)),
890
+ infoFor(core, state)
891
+ );
892
+ const [item] = checked(core, spec.schema, output2.items, spec.action);
893
+ if (item === void 0) {
894
+ throw new OutboundError(
895
+ "NotFound",
896
+ `${spec.what} ${id} was not found`,
897
+ {
898
+ provider: core.adapter.name
899
+ }
900
+ );
901
+ }
902
+ return {
903
+ ...item,
904
+ meta: metaFor(core, state, {
905
+ complete: true,
906
+ evidence: output2.evidence,
907
+ fetchedAt: output2.fetchedAt,
908
+ stale: output2.stale
909
+ })
910
+ };
911
+ },
912
+ shared,
913
+ missingIsAnswer ? isMissing : void 0
914
+ );
915
+ var makeGetter = (core, spec) => async (id, options) => {
916
+ spec.prepare();
917
+ return await getOne(core, spec, id, options);
918
+ };
919
+ var getMany = async (core, spec, ids, options) => {
920
+ spec.prepare();
921
+ const state = core.engine.begin(options);
922
+ const results = [];
923
+ const errors = [];
924
+ const queue = [...ids];
925
+ const worker = async () => {
926
+ for (let id = queue.shift(); id !== void 0; id = queue.shift()) {
927
+ try {
928
+ const value = await getOne(core, spec, id, options, state, true);
929
+ results.push({ id, value });
930
+ } catch (error) {
931
+ errors.push({ error: toOutboundError(core, error), id });
932
+ }
933
+ }
934
+ };
935
+ const workers = Math.max(
936
+ 1,
937
+ Math.min(options?.concurrency ?? DEFAULT_BULK_CONCURRENCY, ids.length)
938
+ );
939
+ await Promise.all(Array.from({ length: workers }, worker));
940
+ const order = new Map(ids.map((id, index) => [id, index]));
941
+ const byOrder = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
942
+ return {
943
+ errors: errors.toSorted(byOrder),
944
+ results: results.toSorted(byOrder)
945
+ };
946
+ };
947
+ var makeCollection = (core, listSpec, getSpec) => ({
948
+ ...makeReadCollection(core, listSpec),
949
+ exists: async (id, options) => {
950
+ getSpec.prepare();
951
+ try {
952
+ await getOne(core, getSpec, id, options, void 0, true);
953
+ return true;
954
+ } catch (error) {
955
+ if (OutboundError.is(error) && isMissing(error)) {
956
+ return false;
957
+ }
958
+ throw error;
959
+ }
960
+ },
961
+ get: makeGetter(core, getSpec),
962
+ getMany: (ids, options) => getMany(core, getSpec, ids, options)
963
+ });
964
+
965
+ // src/internal/outbound/specs-account.ts
966
+ var refOf = (item) => item.ref;
967
+ var settingsGet = (core) => ({
968
+ action: "campaigns.settings",
969
+ prepare: () => {
970
+ requireCapability(
971
+ core.gate,
972
+ "campaigns.settings",
973
+ "Reading a campaign's settings"
974
+ );
975
+ },
976
+ schema: campaignSettingsSchema,
977
+ toOperation: (id) => ({ id, kind: "campaigns.settings" }),
978
+ what: "Settings for campaign"
979
+ });
980
+ var progressGet = (core) => ({
981
+ action: "campaigns.progress",
982
+ prepare: () => {
983
+ requireCapability(
984
+ core.gate,
985
+ "campaigns.progress",
986
+ "Reading a campaign's progress"
987
+ );
988
+ },
989
+ schema: campaignProgressSchema,
990
+ toOperation: (id) => ({ id, kind: "campaigns.progress" }),
991
+ what: "Progress for campaign"
992
+ });
993
+ var healthGet = (core) => ({
994
+ action: "senders.health",
995
+ prepare: () => {
996
+ requireCapability(core.gate, "senders.health", "Reading a sender's health");
997
+ },
998
+ schema: senderHealthSchema,
999
+ toOperation: (id) => ({ id, kind: "senders.health" }),
1000
+ what: "Health for sender"
1001
+ });
1002
+ var subsequenceList = (core) => ({
1003
+ action: "sequence.subsequences",
1004
+ keyOf: refOf,
1005
+ prepare: (filters) => {
1006
+ requireCapability(
1007
+ core.gate,
1008
+ "sequence.subsequences",
1009
+ "Listing a campaign's subsequences"
1010
+ );
1011
+ return { campaignId: filters.campaignId };
1012
+ },
1013
+ schema: sequenceSchema,
1014
+ toOperation: (filters, page) => {
1015
+ if (filters.campaignId === void 0) {
1016
+ throw new OutboundError("Invalid", "Subsequences need a campaign id");
1017
+ }
1018
+ return {
1019
+ kind: "sequence.subsequences",
1020
+ query: { campaignId: filters.campaignId, ...page }
1021
+ };
1022
+ }
1023
+ });
1024
+ var listList = (core) => ({
1025
+ action: "lists.list",
1026
+ keyOf: refOf,
1027
+ prepare: () => {
1028
+ requireCapability(core.gate, "lists.list", "Listing lead lists");
1029
+ return {};
1030
+ },
1031
+ schema: leadListSchema,
1032
+ toOperation: (_filters, page) => ({ kind: "lists.list", query: page })
1033
+ });
1034
+ var listGet = (core) => ({
1035
+ action: "lists.get",
1036
+ prepare: () => {
1037
+ requireCapability(core.gate, "lists.get", "Reading a lead list");
1038
+ },
1039
+ schema: leadListSchema,
1040
+ toOperation: (id) => ({ id, kind: "lists.get" }),
1041
+ what: "List"
1042
+ });
1043
+ var webhookGet = (core) => ({
1044
+ action: "webhooks.get",
1045
+ prepare: () => {
1046
+ requireCapability(core.gate, "webhooks.get", "Reading a webhook");
1047
+ },
1048
+ schema: webhookSubscriptionSchema,
1049
+ toOperation: (id) => ({ id, kind: "webhooks.get" }),
1050
+ what: "Webhook"
1051
+ });
1052
+ var blocklistList = (core) => ({
1053
+ action: "blocklist.list",
1054
+ keyOf: refOf,
1055
+ prepare: () => {
1056
+ requireCapability(core.gate, "blocklist", "Listing the block list");
1057
+ return {};
1058
+ },
1059
+ schema: blockEntrySchema,
1060
+ toOperation: (_filters, page) => ({ kind: "blocklist.list", query: page })
1061
+ });
1062
+ var placementTestList = (core) => ({
1063
+ action: "placementTests.list",
1064
+ keyOf: refOf,
1065
+ prepare: () => {
1066
+ requireCapability(
1067
+ core.gate,
1068
+ "placementTests.list",
1069
+ "Listing inbox placement tests"
1070
+ );
1071
+ return {};
1072
+ },
1073
+ schema: placementTestSchema,
1074
+ toOperation: (_filters, page) => ({
1075
+ kind: "placementTests.list",
1076
+ query: page
1077
+ })
1078
+ });
1079
+ var tagList = (core) => ({
1080
+ action: "tags.list",
1081
+ keyOf: refOf,
1082
+ prepare: () => {
1083
+ requireCapability(core.gate, "tags", "Listing tags");
1084
+ return {};
1085
+ },
1086
+ schema: tagSchema,
1087
+ toOperation: (_filters, page) => ({ kind: "tags.list", query: page })
1088
+ });
1089
+ var webhookList = (core) => ({
1090
+ action: "webhooks.list",
1091
+ keyOf: refOf,
1092
+ prepare: (filters) => {
1093
+ requireCapability(core.gate, "webhooks.list", "Listing webhooks");
1094
+ return { campaignId: filters.campaignId };
1095
+ },
1096
+ schema: webhookSubscriptionSchema,
1097
+ toOperation: (filters, page) => ({
1098
+ kind: "webhooks.list",
1099
+ query: { ...filters, ...page }
1100
+ })
1101
+ });
1102
+
1103
+ // src/internal/outbound/specs.ts
1104
+ var wantsBody = (include) => include?.includes("body") ?? false;
1105
+ var hasRange = (filters) => filters.since !== void 0 || filters.until !== void 0;
1106
+ var refOf2 = (item) => item.ref;
1107
+ var campaignList = (core) => ({
1108
+ action: "campaigns.list",
1109
+ keyOf: refOf2,
1110
+ prepare: (filters) => {
1111
+ if (filters.status !== void 0) {
1112
+ requireCapability(
1113
+ core.gate,
1114
+ "campaigns.status",
1115
+ "Filtering campaigns by status"
1116
+ );
1117
+ }
1118
+ if (filters.senderId !== void 0) {
1119
+ requireCapability(
1120
+ core.gate,
1121
+ "campaigns.bySender",
1122
+ "Listing a sender's campaigns"
1123
+ );
1124
+ }
1125
+ return { senderId: filters.senderId, status: filters.status };
1126
+ },
1127
+ schema: campaignSchema,
1128
+ toOperation: (filters, page) => ({
1129
+ kind: "campaigns.list",
1130
+ query: { ...filters, ...page }
1131
+ })
1132
+ });
1133
+ var campaignGet = () => ({
1134
+ action: "campaigns.get",
1135
+ prepare: () => {
1136
+ },
1137
+ schema: campaignSchema,
1138
+ toOperation: (id) => ({ id, kind: "campaigns.get" }),
1139
+ what: "Campaign"
1140
+ });
1141
+ var sequenceGet = (core) => ({
1142
+ action: "sequence.get",
1143
+ prepare: () => {
1144
+ requireCapability(core.gate, "sequence", "Reading a campaign's sequence");
1145
+ },
1146
+ schema: sequenceSchema,
1147
+ toOperation: (id) => ({ id, kind: "sequence.get" }),
1148
+ what: "Sequence for campaign"
1149
+ });
1150
+ var senderList = (core) => ({
1151
+ action: "senders.list",
1152
+ keyOf: refOf2,
1153
+ prepare: (filters) => {
1154
+ if (filters.campaignId === void 0) {
1155
+ requireCapability(core.gate, "senders.list", "Listing senders");
1156
+ } else {
1157
+ requireCapability(
1158
+ core.gate,
1159
+ "senders.byCampaign",
1160
+ "Listing a campaign's senders"
1161
+ );
1162
+ }
1163
+ return { campaignId: filters.campaignId };
1164
+ },
1165
+ schema: senderSchema,
1166
+ toOperation: (filters, page) => ({
1167
+ kind: "senders.list",
1168
+ query: { ...filters, ...page }
1169
+ })
1170
+ });
1171
+ var senderGet = (core) => ({
1172
+ action: "senders.get",
1173
+ prepare: () => {
1174
+ requireCapability(core.gate, "senders.get", "Reading one sender");
1175
+ },
1176
+ schema: senderSchema,
1177
+ toOperation: (id) => ({ id, kind: "senders.get" }),
1178
+ what: "Sender"
1179
+ });
1180
+ var leadList = (core) => ({
1181
+ action: "leads.list",
1182
+ // A lookup returns one record per campaign the person is in. On a vendor
1183
+ // whose lead id is the same in every campaign those records share a ref,
1184
+ // so the campaign is part of what tells them apart.
1185
+ keyOf: (lead, filters) => filters.email === void 0 && filters.linkedinUrl === void 0 ? lead.ref : `${lead.ref} ${lead.campaignRef ?? ""}`,
1186
+ prepare: (filters) => {
1187
+ if (filters.campaignId !== void 0 && filters.listId !== void 0) {
1188
+ throw new OutboundError(
1189
+ "Invalid",
1190
+ "Leads can be listed by campaign or by list, not both at once"
1191
+ );
1192
+ }
1193
+ const lookup2 = filters.email !== void 0 || filters.linkedinUrl !== void 0;
1194
+ if (lookup2) {
1195
+ requireCapability(
1196
+ core.gate,
1197
+ "leads.lookup",
1198
+ "Finding a lead by email or LinkedIn profile"
1199
+ );
1200
+ }
1201
+ if (filters.listId !== void 0) {
1202
+ requireCapability(core.gate, "lists.leads", "Listing a list's leads");
1203
+ } else if (filters.campaignId !== void 0) {
1204
+ requireCapability(
1205
+ core.gate,
1206
+ "leads.byCampaign",
1207
+ "Listing a campaign's leads"
1208
+ );
1209
+ } else if (!lookup2) {
1210
+ requireCapability(core.gate, "leads.list", "Listing leads");
1211
+ }
1212
+ if (hasRange(filters)) {
1213
+ requireCapability(core.gate, "leads.since", "Filtering leads by date");
1214
+ }
1215
+ return {
1216
+ campaignId: filters.campaignId,
1217
+ email: filters.email?.trim().toLowerCase(),
1218
+ linkedinUrl: filters.linkedinUrl?.trim(),
1219
+ listId: filters.listId,
1220
+ ...normalizeRange(filters)
1221
+ };
1222
+ },
1223
+ schema: leadSchema,
1224
+ toOperation: (filters, page) => ({
1225
+ kind: "leads.list",
1226
+ query: { ...filters, ...page }
1227
+ })
1228
+ });
1229
+ var leadGet = (core) => ({
1230
+ action: "leads.get",
1231
+ prepare: () => {
1232
+ requireCapability(core.gate, "leads.get", "Reading one lead");
1233
+ },
1234
+ schema: leadSchema,
1235
+ toOperation: (id) => ({ id, kind: "leads.get" }),
1236
+ what: "Lead"
1237
+ });
1238
+ var messageList = (core) => ({
1239
+ action: "messages.list",
1240
+ keyOf: refOf2,
1241
+ prepare: (filters) => {
1242
+ requireCapability(core.gate, "messages.list", "Listing messages");
1243
+ if (filters.threadId !== void 0) {
1244
+ requireCapability(
1245
+ core.gate,
1246
+ "messages.byThread",
1247
+ "Reading one conversation"
1248
+ );
1249
+ }
1250
+ if (wantsBody(filters.include)) {
1251
+ requireCapability(core.gate, "messages.body", "Reading message bodies");
1252
+ }
1253
+ if (hasRange(filters)) {
1254
+ requireCapability(
1255
+ core.gate,
1256
+ "messages.since",
1257
+ "Filtering messages by date"
1258
+ );
1259
+ }
1260
+ return {
1261
+ campaignId: filters.campaignId,
1262
+ include: filters.include,
1263
+ leadId: filters.leadId,
1264
+ threadId: filters.threadId,
1265
+ ...normalizeRange(filters)
1266
+ };
1267
+ },
1268
+ schema: messageSchema,
1269
+ toOperation: (filters, page) => ({
1270
+ kind: "messages.list",
1271
+ query: {
1272
+ campaignId: filters.campaignId,
1273
+ includeBody: wantsBody(filters.include),
1274
+ leadId: filters.leadId,
1275
+ since: filters.since,
1276
+ threadId: filters.threadId,
1277
+ until: filters.until,
1278
+ ...page
1279
+ }
1280
+ })
1281
+ });
1282
+ var replyList = (core) => ({
1283
+ action: "replies.list",
1284
+ keyOf: refOf2,
1285
+ prepare: (filters) => {
1286
+ requireCapability(core.gate, "replies.list", "Listing replies");
1287
+ if (filters.category !== void 0) {
1288
+ requireCapability(
1289
+ core.gate,
1290
+ "replies.category",
1291
+ "Filtering replies by category"
1292
+ );
1293
+ }
1294
+ if (filters.unread !== void 0) {
1295
+ requireCapability(
1296
+ core.gate,
1297
+ "replies.unread",
1298
+ "Filtering replies by whether they are unread"
1299
+ );
1300
+ }
1301
+ if (wantsBody(filters.include)) {
1302
+ requireCapability(core.gate, "messages.body", "Reading reply bodies");
1303
+ }
1304
+ if (hasRange(filters)) {
1305
+ requireCapability(
1306
+ core.gate,
1307
+ "replies.since",
1308
+ "Filtering replies by date"
1309
+ );
1310
+ }
1311
+ return {
1312
+ campaignId: filters.campaignId,
1313
+ category: filters.category,
1314
+ include: filters.include,
1315
+ unread: filters.unread,
1316
+ ...normalizeRange(filters)
1317
+ };
1318
+ },
1319
+ schema: replySchema,
1320
+ toOperation: (filters, page) => ({
1321
+ kind: "replies.list",
1322
+ query: {
1323
+ campaignId: filters.campaignId,
1324
+ category: filters.category,
1325
+ includeBody: wantsBody(filters.include),
1326
+ since: filters.since,
1327
+ unread: filters.unread,
1328
+ until: filters.until,
1329
+ ...page
1330
+ }
1331
+ })
1332
+ });
1333
+ var workspaceList = (core) => ({
1334
+ action: "workspaces.list",
1335
+ keyOf: refOf2,
1336
+ prepare: () => {
1337
+ requireCapability(core.gate, "workspaces", "Listing workspaces");
1338
+ return {};
1339
+ },
1340
+ schema: workspaceSchema,
1341
+ toOperation: (_filters, page) => ({ kind: "workspaces.list", query: page })
1342
+ });
1343
+
1344
+ // src/internal/outbound/stats.ts
1345
+ var SCOPE_CAPABILITY = {
1346
+ campaign: "stats.campaign",
1347
+ sender: "stats.bySender",
1348
+ step: "stats.byStep",
1349
+ workspace: "stats.workspace"
1350
+ };
1351
+ var readStats = async (core, options = {}) => {
1352
+ const scope = options.scope ?? "workspace";
1353
+ const by = options.by ?? "total";
1354
+ const from = assertDay(options.from, "from");
1355
+ const to = assertDay(options.to, "to");
1356
+ if (from !== void 0 && to !== void 0 && from > to) {
1357
+ throw new OutboundError("Invalid", "from must not be after to");
1358
+ }
1359
+ const everyCampaign = scope === "campaign" && options.scopeId === void 0;
1360
+ if (scope !== "workspace" && options.scopeId === void 0 && !everyCampaign) {
1361
+ throw new OutboundError(
1362
+ "Invalid",
1363
+ `stats for the ${scope} scope need a scopeId`
1364
+ );
1365
+ }
1366
+ requireCapability(
1367
+ core.gate,
1368
+ everyCampaign ? "stats.allCampaigns" : SCOPE_CAPABILITY[scope],
1369
+ everyCampaign ? "Reading stats for every campaign in one call" : `Reading stats for the ${scope} scope`
1370
+ );
1371
+ if (by === "day") {
1372
+ requireCapability(core.gate, "stats.byDay", "Reading stats by day");
1373
+ }
1374
+ return await perform(core, "stats", options, async (state) => {
1375
+ const output2 = await core.run(
1376
+ {
1377
+ kind: "stats",
1378
+ query: { by, from, scope, scopeId: options.scopeId, to }
1379
+ },
1380
+ infoFor(core, state)
1381
+ );
1382
+ return {
1383
+ meta: metaFor(core, state, {
1384
+ complete: true,
1385
+ evidence: output2.evidence,
1386
+ fetchedAt: output2.fetchedAt,
1387
+ stale: output2.stale
1388
+ }),
1389
+ rows: checked(core, metricRowSchema, output2.items, "stats")
1390
+ };
1391
+ });
1392
+ };
1393
+
1394
+ // src/internal/outbound/handles.ts
1395
+ var scoped = (core, spec, fixed) => {
1396
+ const collection = makeReadCollection(core, spec);
1397
+ const withCampaign = (options) => ({ ...options, ...fixed });
1398
+ return {
1399
+ list: (options) => collection.list(withCampaign(options)),
1400
+ listAll: (options) => collection.listAll(withCampaign(options))
1401
+ };
1402
+ };
1403
+ var makeCampaignHandle = (core, id) => {
1404
+ const campaignId = assertId(id, "Campaign");
1405
+ const get = makeGetter(core, campaignGet());
1406
+ const sequence = makeGetter(core, sequenceGet(core));
1407
+ const settings = makeGetter(core, settingsGet(core));
1408
+ const progress = makeGetter(core, progressGet(core));
1409
+ const fixed = { campaignId };
1410
+ return {
1411
+ get: (options) => get(campaignId, options),
1412
+ id: campaignId,
1413
+ leads: scoped(core, leadList(core), fixed),
1414
+ messages: scoped(core, messageList(core), fixed),
1415
+ progress: (options) => progress(campaignId, options),
1416
+ replies: scoped(core, replyList(core), fixed),
1417
+ senders: scoped(core, senderList(core), fixed),
1418
+ sequence: (options) => sequence(campaignId, options),
1419
+ settings: (options) => settings(campaignId, options),
1420
+ subsequences: scoped(core, subsequenceList(core), fixed),
1421
+ webhooks: scoped(core, webhookList(core), fixed),
1422
+ stats: (options) => readStats(core, {
1423
+ ...options,
1424
+ scope: options?.scope ?? "campaign",
1425
+ scopeId: campaignId
1426
+ })
1427
+ };
1428
+ };
1429
+ var makeSenderHandle = (core, id) => {
1430
+ const senderId = assertId(id, "Sender");
1431
+ const get = makeGetter(core, senderGet(core));
1432
+ const health = makeGetter(core, healthGet(core));
1433
+ return {
1434
+ campaigns: scoped(core, campaignList(core), { senderId }),
1435
+ get: (options) => get(senderId, options),
1436
+ health: (options) => health(senderId, options),
1437
+ id: senderId,
1438
+ stats: (options) => readStats(core, { ...options, scope: "sender", scopeId: senderId }),
1439
+ warmup: async (options) => {
1440
+ requireCapability(
1441
+ core.gate,
1442
+ "senders.warmup",
1443
+ "Reading a sender's warmup"
1444
+ );
1445
+ const sender = await get(senderId, options);
1446
+ if (sender.warmup === null) {
1447
+ throw new OutboundError(
1448
+ "NotFound",
1449
+ `Sender ${senderId} has no warmup data`,
1450
+ {
1451
+ provider: core.adapter.name
1452
+ }
1453
+ );
1454
+ }
1455
+ return sender.warmup;
1456
+ }
1457
+ };
1458
+ };
1459
+ var bySentAt = (left, right) => (left.sentAt ?? "").localeCompare(right.sentAt ?? "");
1460
+ var collect = async (core, walk, what) => {
1461
+ const items = await walk.toArray();
1462
+ if (walk.meta === void 0) {
1463
+ throw new OutboundError("Provider", `The ${what} returned no page`, {
1464
+ provider: core.adapter.name
1465
+ });
1466
+ }
1467
+ return { complete: true, items: items.toSorted(bySentAt), meta: walk.meta };
1468
+ };
1469
+ var makeLeadHandle = (core, id) => {
1470
+ const leadId = assertId(id, "Lead");
1471
+ const get = makeGetter(core, leadGet(core));
1472
+ const messages = makeReadCollection(core, messageList(core));
1473
+ return {
1474
+ get: (options) => get(leadId, options),
1475
+ id: leadId,
1476
+ // Async, so a refused read rejects like every other failure of the call.
1477
+ timeline: async (options) => {
1478
+ requireCapability(
1479
+ core.gate,
1480
+ "leads.timeline",
1481
+ "Reading a lead's timeline"
1482
+ );
1483
+ return await collect(
1484
+ core,
1485
+ messages.listAll({ ...options, leadId }),
1486
+ "timeline"
1487
+ );
1488
+ }
1489
+ };
1490
+ };
1491
+ var makeListHandle = (core, id) => {
1492
+ const listId = assertId(id, "List");
1493
+ const get = makeGetter(core, listGet(core));
1494
+ return {
1495
+ get: (options) => get(listId, options),
1496
+ id: listId,
1497
+ leads: scoped(core, leadList(core), { listId })
1498
+ };
1499
+ };
1500
+ var makeThreadHandle = (core, id) => {
1501
+ const threadId = assertId(id, "Thread");
1502
+ const messages = makeReadCollection(core, messageList(core));
1503
+ return {
1504
+ id: threadId,
1505
+ // Async, so a refused read rejects like every other failure of the call.
1506
+ messages: async (options) => await collect(core, messages.listAll({ ...options, threadId }), "thread")
1507
+ };
1508
+ };
1509
+
1510
+ // src/internal/outbound/native.ts
1511
+ var invalid2 = (core, message) => new OutboundError("Invalid", message, { provider: core.adapter.name });
1512
+ var TYPE_CHECKS = {
1513
+ boolean: (value) => value === true || value === false,
1514
+ json: () => true,
1515
+ list: (value) => Array.isArray(value) && value.every((item) => !isJsonObject(item) && !Array.isArray(item)),
1516
+ number: (value) => Number.isFinite(value),
1517
+ string: (value) => String(value) === value
1518
+ };
1519
+ var scalar = (value) => isJsonObject(value) || Array.isArray(value) ? JSON.stringify(value) : value;
1520
+ var place = (built, name, param, value) => {
1521
+ if (param.in === "path") {
1522
+ return {
1523
+ ...built,
1524
+ path: built.path.replace(`{${name}}`, encodeURIComponent(String(value)))
1525
+ };
1526
+ }
1527
+ if (param.in === "query" && param.type === "list" && Array.isArray(value)) {
1528
+ return {
1529
+ ...built,
1530
+ repeated: [
1531
+ ...built.repeated,
1532
+ ...value.map((item) => [name, String(item)])
1533
+ ]
1534
+ };
1535
+ }
1536
+ return param.in === "query" ? { ...built, query: { ...built.query, [name]: scalar(value) } } : { ...built, body: { ...built.body, [name]: value } };
1537
+ };
1538
+ var withRepeated = (url, repeated) => {
1539
+ if (repeated.length === 0) {
1540
+ return url;
1541
+ }
1542
+ const parsed = new URL(url);
1543
+ for (const [name, value] of repeated) {
1544
+ parsed.searchParams.append(name, value);
1545
+ }
1546
+ return parsed.toString();
1547
+ };
1548
+ var build = (core, { name, read }, params) => {
1549
+ const declared = Object.entries(read.params ?? {});
1550
+ const known = new Set(declared.map(([param]) => param));
1551
+ const unknown = Object.keys(params).find((param) => !known.has(param));
1552
+ if (unknown !== void 0) {
1553
+ throw invalid2(
1554
+ core,
1555
+ `${name} has no parameter "${unknown}". It takes: ${[...known].join(", ") || "nothing"}`
1556
+ );
1557
+ }
1558
+ let built = {
1559
+ body: read.method === "POST" ? {} : void 0,
1560
+ path: read.path,
1561
+ query: {},
1562
+ repeated: []
1563
+ };
1564
+ for (const [param, spec] of declared) {
1565
+ const value = params[param];
1566
+ if (value === void 0 || value === null) {
1567
+ if (spec.required === true || spec.in === "path") {
1568
+ throw invalid2(core, `${name} needs "${param}"`);
1569
+ }
1570
+ continue;
1571
+ }
1572
+ if (!TYPE_CHECKS[spec.type](value)) {
1573
+ throw invalid2(core, `${name}: "${param}" must be a ${spec.type}`);
1574
+ }
1575
+ built = place(built, param, spec, value);
1576
+ }
1577
+ return built;
1578
+ };
1579
+ var makeNativeClient = (core) => {
1580
+ const { adapter } = core;
1581
+ const catalog = adapter.native ?? {};
1582
+ const read = async (name, params = {}, options = {}) => {
1583
+ if (adapter.members !== void 0) {
1584
+ throw new OutboundError(
1585
+ "Unsupported",
1586
+ `native is not available on a combined instance: it belongs to one vendor. Use outbound.workspace("provider:workspace").native, for example ${adapter.members.map((member) => `"${member.name}:${member.workspaceId}"`).join(" or ")}`,
1587
+ { provider: adapter.name }
1588
+ );
1589
+ }
1590
+ requireCapability(core.gate, "native", "Reading the vendor's own data");
1591
+ const entry = Object.hasOwn(catalog, name) ? catalog[name] : void 0;
1592
+ if (entry === void 0) {
1593
+ throw invalid2(
1594
+ core,
1595
+ `${adapter.name} has no native read "${name}". See outbound.native.catalog`
1596
+ );
1597
+ }
1598
+ const built = build(core, { name, read: entry }, params);
1599
+ return await perform(core, `native.${name}`, options, async (state) => {
1600
+ const spec = adapter.raw.authorize({
1601
+ body: built.body,
1602
+ lane: entry.lane,
1603
+ method: entry.method,
1604
+ url: withRepeated(
1605
+ buildUrl(
1606
+ entry.baseUrl ?? adapter.raw.baseUrl,
1607
+ built.path,
1608
+ built.query
1609
+ ),
1610
+ built.repeated
1611
+ )
1612
+ });
1613
+ const response = await core.engine.contextFor(adapter, state).request(spec);
1614
+ return {
1615
+ data: response.body,
1616
+ meta: metaFor(core, state, { complete: true, evidence: "exact" })
1617
+ };
1618
+ });
1619
+ };
1620
+ const reads = {};
1621
+ for (const name of Object.keys(catalog)) {
1622
+ reads[name] = (params, options) => read(name, params, options);
1623
+ }
1624
+ return {
1625
+ // SAFETY: the catalog is the adapter's own, typed by the caller as Native.
1626
+ catalog,
1627
+ provider: adapter.name,
1628
+ read,
1629
+ // SAFETY: one function per catalog name, each taking that read's parameters.
1630
+ reads
1631
+ };
1632
+ };
1633
+
1634
+ // src/internal/outbound/operation-shared.ts
1635
+ var unsupported = (adapter, kind) => new OutboundError(
1636
+ "Unsupported",
1637
+ `The ${adapter.name} adapter does not implement ${kind}`,
1638
+ {
1639
+ provider: adapter.name
1640
+ }
1641
+ );
1642
+ var idFor = (adapter, id) => (
1643
+ // A combined adapter routes by ref, so it needs the id untouched.
1644
+ adapter.members === void 0 ? sourceIdFor(id, adapter.name, adapter.workspaceId) : id
1645
+ );
1646
+ var optionalId = (adapter, id) => id === void 0 ? void 0 : idFor(adapter, id);
1647
+ var output = (page, derived = false) => ({
1648
+ evidence: derived ? "derived" : "exact",
1649
+ items: page.items,
1650
+ next: page.next
1651
+ });
1652
+ var single = (item) => ({
1653
+ evidence: "exact",
1654
+ items: [item]
1655
+ });
1656
+
1657
+ // src/internal/outbound/operations-account.ts
1658
+ var ACCOUNT_KINDS = /* @__PURE__ */ new Set([
1659
+ "blocklist.list",
1660
+ "campaigns.progress",
1661
+ "campaigns.settings",
1662
+ "lists.get",
1663
+ "lists.list",
1664
+ "placementTests.list",
1665
+ "senders.health",
1666
+ "sequence.subsequences",
1667
+ "tags.list",
1668
+ "webhooks.get",
1669
+ "webhooks.list"
1670
+ ]);
1671
+ var isAccountOperation = (operation) => ACCOUNT_KINDS.has(operation.kind);
1672
+ var lookup = async (target, operation) => {
1673
+ const { adapter, ctx } = target;
1674
+ const id = idFor(adapter, operation.id);
1675
+ const read = {
1676
+ "campaigns.progress": adapter.getCampaignProgress,
1677
+ "campaigns.settings": adapter.getCampaignSettings,
1678
+ "lists.get": adapter.getList,
1679
+ "senders.health": adapter.getSenderHealth,
1680
+ "webhooks.get": adapter.getWebhook
1681
+ }[operation.kind];
1682
+ if (read === void 0) {
1683
+ throw unsupported(adapter, operation.kind);
1684
+ }
1685
+ return single(await read(id, ctx));
1686
+ };
1687
+ var scopedList = async (target, operation) => {
1688
+ const { adapter, ctx } = target;
1689
+ if (operation.kind === "sequence.subsequences") {
1690
+ if (adapter.listSubsequences === void 0) {
1691
+ throw unsupported(adapter, operation.kind);
1692
+ }
1693
+ return output(
1694
+ await adapter.listSubsequences(
1695
+ {
1696
+ ...operation.query,
1697
+ campaignId: idFor(adapter, operation.query.campaignId)
1698
+ },
1699
+ ctx
1700
+ )
1701
+ );
1702
+ }
1703
+ if (adapter.listWebhooks === void 0) {
1704
+ throw unsupported(adapter, operation.kind);
1705
+ }
1706
+ return output(
1707
+ await adapter.listWebhooks(
1708
+ {
1709
+ ...operation.query,
1710
+ campaignId: optionalId(adapter, operation.query.campaignId)
1711
+ },
1712
+ ctx
1713
+ )
1714
+ );
1715
+ };
1716
+ var dispatchAccount = async (target, operation) => {
1717
+ const { adapter, ctx } = target;
1718
+ switch (operation.kind) {
1719
+ case "campaigns.progress":
1720
+ case "campaigns.settings":
1721
+ case "lists.get":
1722
+ case "senders.health":
1723
+ case "webhooks.get": {
1724
+ return await lookup(target, operation);
1725
+ }
1726
+ case "sequence.subsequences":
1727
+ case "webhooks.list": {
1728
+ return await scopedList(target, operation);
1729
+ }
1730
+ case "blocklist.list": {
1731
+ if (adapter.listBlocklist === void 0) {
1732
+ throw unsupported(adapter, operation.kind);
1733
+ }
1734
+ return output(await adapter.listBlocklist(operation.query, ctx));
1735
+ }
1736
+ case "lists.list": {
1737
+ if (adapter.listLists === void 0) {
1738
+ throw unsupported(adapter, operation.kind);
1739
+ }
1740
+ return output(await adapter.listLists(operation.query, ctx));
1741
+ }
1742
+ case "placementTests.list": {
1743
+ if (adapter.listPlacementTests === void 0) {
1744
+ throw unsupported(adapter, operation.kind);
1745
+ }
1746
+ return output(await adapter.listPlacementTests(operation.query, ctx));
1747
+ }
1748
+ case "tags.list": {
1749
+ if (adapter.listTags === void 0) {
1750
+ throw unsupported(adapter, operation.kind);
1751
+ }
1752
+ return output(await adapter.listTags(operation.query, ctx));
1753
+ }
1754
+ default: {
1755
+ const unreachable = operation;
1756
+ return unreachable;
1757
+ }
1758
+ }
1759
+ };
1760
+
1761
+ // src/internal/outbound/operations.ts
1762
+ var inRange = (value, range) => {
1763
+ if (range.since === void 0 && range.until === void 0) {
1764
+ return true;
1765
+ }
1766
+ if (value === null) {
1767
+ return false;
1768
+ }
1769
+ const time = Date.parse(value);
1770
+ return (range.since === void 0 || time >= Date.parse(range.since)) && (range.until === void 0 || time <= Date.parse(range.until));
1771
+ };
1772
+ var hasRange2 = (range) => range.since !== void 0 || range.until !== void 0;
1773
+ var filterByTime = (page, range, grade, timeOf) => {
1774
+ if (grade !== "client" || !hasRange2(range)) {
1775
+ return { derived: false, page };
1776
+ }
1777
+ return {
1778
+ derived: true,
1779
+ page: {
1780
+ items: page.items.filter((item) => inRange(timeOf(item), range)),
1781
+ next: page.next
1782
+ }
1783
+ };
1784
+ };
1785
+ var listCampaigns = async (target, query) => {
1786
+ const page = await target.adapter.listCampaigns(
1787
+ { ...query, senderId: optionalId(target.adapter, query.senderId) },
1788
+ target.ctx
1789
+ );
1790
+ if (target.capabilities["campaigns.status"] !== "client" || query.status === void 0) {
1791
+ return output(page);
1792
+ }
1793
+ return output(
1794
+ {
1795
+ items: page.items.filter((campaign) => campaign.status === query.status),
1796
+ next: page.next
1797
+ },
1798
+ true
1799
+ );
1800
+ };
1801
+ var listLeads = async (target, query) => {
1802
+ const { adapter, capabilities, ctx } = target;
1803
+ if (adapter.listLeads === void 0) {
1804
+ throw unsupported(adapter, "leads.list");
1805
+ }
1806
+ const page = await adapter.listLeads(
1807
+ {
1808
+ ...query,
1809
+ campaignId: optionalId(adapter, query.campaignId),
1810
+ listId: optionalId(adapter, query.listId)
1811
+ },
1812
+ ctx
1813
+ );
1814
+ const filtered = filterByTime(
1815
+ page,
1816
+ query,
1817
+ capabilities["leads.since"],
1818
+ (lead) => lead.createdAt
1819
+ );
1820
+ return output(filtered.page, filtered.derived);
1821
+ };
1822
+ var listMessages = async (target, query) => {
1823
+ const { adapter, capabilities, ctx } = target;
1824
+ if (adapter.listMessages === void 0) {
1825
+ throw unsupported(adapter, "messages.list");
1826
+ }
1827
+ const page = await adapter.listMessages(
1828
+ {
1829
+ ...query,
1830
+ campaignId: optionalId(adapter, query.campaignId),
1831
+ leadId: optionalId(adapter, query.leadId)
1832
+ },
1833
+ ctx
1834
+ );
1835
+ const filtered = filterByTime(
1836
+ page,
1837
+ query,
1838
+ capabilities["messages.since"],
1839
+ (message) => message.sentAt
1840
+ );
1841
+ return output(filtered.page, filtered.derived);
1842
+ };
1843
+ var listReplies = async (target, query) => {
1844
+ const { adapter, capabilities, ctx } = target;
1845
+ if (adapter.listReplies === void 0) {
1846
+ throw unsupported(adapter, "replies.list");
1847
+ }
1848
+ const page = await adapter.listReplies(
1849
+ { ...query, campaignId: optionalId(adapter, query.campaignId) },
1850
+ ctx
1851
+ );
1852
+ const filtered = filterByTime(
1853
+ page,
1854
+ query,
1855
+ capabilities["replies.since"],
1856
+ (reply) => reply.sentAt
1857
+ );
1858
+ if (capabilities["replies.unread"] !== "client" || query.unread === void 0) {
1859
+ return output(filtered.page, filtered.derived);
1860
+ }
1861
+ return output(
1862
+ {
1863
+ items: filtered.page.items.filter(
1864
+ (reply) => reply.unread === query.unread
1865
+ ),
1866
+ next: filtered.page.next
1867
+ },
1868
+ true
1869
+ );
1870
+ };
1871
+ var listSenders = async (target, query) => {
1872
+ const { adapter, ctx } = target;
1873
+ if (adapter.listSenders === void 0) {
1874
+ throw unsupported(adapter, "senders.list");
1875
+ }
1876
+ return output(
1877
+ await adapter.listSenders(
1878
+ { ...query, campaignId: optionalId(adapter, query.campaignId) },
1879
+ ctx
1880
+ )
1881
+ );
1882
+ };
1883
+ var stats = async (target, query) => {
1884
+ const { adapter, ctx } = target;
1885
+ if (adapter.stats === void 0) {
1886
+ throw unsupported(adapter, "stats");
1887
+ }
1888
+ const rows = await adapter.stats(
1889
+ { ...query, scopeId: optionalId(adapter, query.scopeId) },
1890
+ ctx
1891
+ );
1892
+ const derived = rows.some((row) => row.evidence !== "exact");
1893
+ return { evidence: derived ? "derived" : "exact", items: rows };
1894
+ };
1895
+ var getOne2 = async (target, operation) => {
1896
+ const { adapter, ctx } = target;
1897
+ const id = idFor(adapter, operation.id);
1898
+ switch (operation.kind) {
1899
+ case "campaigns.get": {
1900
+ return single(await adapter.getCampaign(id, ctx));
1901
+ }
1902
+ case "leads.get": {
1903
+ if (adapter.getLead === void 0) {
1904
+ throw unsupported(adapter, operation.kind);
1905
+ }
1906
+ return single(await adapter.getLead(id, ctx));
1907
+ }
1908
+ case "senders.get": {
1909
+ if (adapter.getSender === void 0) {
1910
+ throw unsupported(adapter, operation.kind);
1911
+ }
1912
+ return single(await adapter.getSender(id, ctx));
1913
+ }
1914
+ case "sequence.get": {
1915
+ if (adapter.getSequence === void 0) {
1916
+ throw unsupported(adapter, operation.kind);
1917
+ }
1918
+ return single(await adapter.getSequence(id, ctx));
1919
+ }
1920
+ default: {
1921
+ const unreachable = operation;
1922
+ return unreachable;
1923
+ }
1924
+ }
1925
+ };
1926
+ var dispatch = async (target, operation) => {
1927
+ if (isAccountOperation(operation)) {
1928
+ return await dispatchAccount(target, operation);
1929
+ }
1930
+ switch (operation.kind) {
1931
+ case "campaigns.list": {
1932
+ return await listCampaigns(target, operation.query);
1933
+ }
1934
+ case "leads.list": {
1935
+ return await listLeads(target, operation.query);
1936
+ }
1937
+ case "messages.list": {
1938
+ return await listMessages(target, operation.query);
1939
+ }
1940
+ case "replies.list": {
1941
+ return await listReplies(target, operation.query);
1942
+ }
1943
+ case "senders.list": {
1944
+ return await listSenders(target, operation.query);
1945
+ }
1946
+ case "stats": {
1947
+ return await stats(target, operation.query);
1948
+ }
1949
+ case "workspaces.list": {
1950
+ if (target.adapter.listWorkspaces === void 0) {
1951
+ throw unsupported(target.adapter, operation.kind);
1952
+ }
1953
+ return output(
1954
+ await target.adapter.listWorkspaces(operation.query, target.ctx)
1955
+ );
1956
+ }
1957
+ default: {
1958
+ return await getOne2(target, operation);
1959
+ }
1960
+ }
1961
+ };
1962
+
1963
+ // src/internal/outbound/plugins.ts
1964
+ var narrowCapabilities = (declared, plugins) => {
1965
+ const narrowedBy = /* @__PURE__ */ new Map();
1966
+ let current = declared;
1967
+ for (const plugin of plugins) {
1968
+ if (plugin.capabilities !== void 0) {
1969
+ const next = intersectCapabilities(
1970
+ current,
1971
+ plugin.capabilities({ ...current })
1972
+ );
1973
+ for (const key of CAPABILITY_KEYS) {
1974
+ if (next[key] === false && current[key] !== false) {
1975
+ narrowedBy.set(key, plugin.name);
1976
+ }
1977
+ }
1978
+ current = next;
1979
+ }
1980
+ }
1981
+ return { capabilities: current, narrowedBy };
1982
+ };
1983
+ var composeOperations = (plugins, innermost) => {
1984
+ const wraps = plugins.flatMap(
1985
+ (plugin) => plugin.wrap === void 0 ? [] : [plugin.wrap]
1986
+ );
1987
+ return (operation, info) => {
1988
+ const run = (index, current) => {
1989
+ const wrap = wraps[index];
1990
+ return wrap === void 0 ? innermost(current, info) : wrap(current, (inner) => run(index + 1, inner), info);
1991
+ };
1992
+ return run(0, operation);
1993
+ };
1994
+ };
1995
+ var assertUniquePluginNames = (plugins) => {
1996
+ const seen = /* @__PURE__ */ new Set();
1997
+ for (const plugin of plugins) {
1998
+ if (seen.has(plugin.name)) {
1999
+ throw new OutboundError(
2000
+ "Invalid",
2001
+ `The ${plugin.name} plugin is listed twice`
2002
+ );
2003
+ }
2004
+ seen.add(plugin.name);
2005
+ }
2006
+ };
2007
+ var isExtension = (value) => typeof value === "object" && value !== null;
2008
+ var installExtensions = (outbound, plugins) => {
2009
+ for (const plugin of plugins) {
2010
+ const extension = plugin.extend?.(outbound);
2011
+ for (const [name, value] of Object.entries(
2012
+ isExtension(extension) ? extension : {}
2013
+ )) {
2014
+ if (name in outbound) {
2015
+ throw new OutboundError(
2016
+ "Invalid",
2017
+ `The ${plugin.name} plugin adds "${name}", which already exists on the instance`
2018
+ );
2019
+ }
2020
+ Object.defineProperty(outbound, name, { enumerable: true, value });
2021
+ }
2022
+ }
2023
+ };
2024
+
2025
+ // src/internal/outbound/raw.ts
2026
+ var ENCODED_SEPARATOR = /%(?:2f|5c|2e)|\\/iu;
2027
+ var refuse = (core, message) => new OutboundError("Unsupported", message, {
2028
+ provider: core.adapter.name
2029
+ });
2030
+ var resolve = (core, path, query) => {
2031
+ const { baseUrl } = core.adapter.raw;
2032
+ if (ENCODED_SEPARATOR.test(path)) {
2033
+ throw new OutboundError(
2034
+ "Invalid",
2035
+ "A raw path may not contain a backslash or an encoded slash, backslash or dot",
2036
+ { provider: core.adapter.name }
2037
+ );
2038
+ }
2039
+ const base = new URL(baseUrl);
2040
+ const url = new URL(buildUrl(baseUrl, path, query));
2041
+ const root = base.pathname.replace(/\/+$/u, "");
2042
+ if (url.origin !== base.origin || !(url.pathname === root || url.pathname.startsWith(`${root}/`))) {
2043
+ throw refuse(
2044
+ core,
2045
+ `${path} leaves the ${core.adapter.name} API, so raw will not send it`
2046
+ );
2047
+ }
2048
+ const relative = `/${url.pathname.slice(root.length).split("/").filter((part) => part !== "").join("/")}`;
2049
+ url.pathname = `${root}${relative}`;
2050
+ return { path: relative, query: url.searchParams, url: url.toString() };
2051
+ };
2052
+ var makeRawClient = (core, nativeOffBy) => {
2053
+ const { adapter } = core;
2054
+ const request = async (method, path, options = {}) => {
2055
+ if (adapter.members !== void 0) {
2056
+ throw refuse(
2057
+ core,
2058
+ `raw is not available on a combined instance: it belongs to one vendor. Use outbound.workspace("provider:workspace").raw, for example ${adapter.members.map((member) => `"${member.name}:${member.workspaceId}"`).join(" or ")}`
2059
+ );
2060
+ }
2061
+ if (nativeOffBy !== void 0) {
2062
+ throw refuse(
2063
+ core,
2064
+ `raw is not available: the ${nativeOffBy} plugin turned the vendor's own reads off (native), and raw returns the same untouched payload`
2065
+ );
2066
+ }
2067
+ const target = resolve(core, path, options.query);
2068
+ if (adapter.raw.isSecret?.(target.path, target.query) === true) {
2069
+ throw refuse(
2070
+ core,
2071
+ `${method} ${target.path} returns secrets (keys or passwords) on ${adapter.name}, so raw never reads it`
2072
+ );
2073
+ }
2074
+ const isRead = adapter.raw.isRead(method, target.path);
2075
+ if (!core.allowWrites && !isRead) {
2076
+ throw refuse(
2077
+ core,
2078
+ `${method} ${target.path} is not a known read on ${adapter.name}. The SDK is read-only; pass allowWrites: true to createOutbound to permit it`
2079
+ );
2080
+ }
2081
+ const settings = isRead || options.retries !== void 0 ? options : { ...options, retries: 0 };
2082
+ return await perform(core, "raw", settings, async (state) => {
2083
+ const spec = adapter.raw.authorize({
2084
+ body: options.body,
2085
+ lane: options.lane,
2086
+ method,
2087
+ url: target.url
2088
+ });
2089
+ const response = await core.engine.contextFor(adapter, state).request(spec);
2090
+ return response.body;
2091
+ });
2092
+ };
2093
+ return {
2094
+ get: (path, options) => request("GET", path, options),
2095
+ provider: adapter.name,
2096
+ request
2097
+ };
2098
+ };
2099
+
2100
+ // src/internal/outbound/outbound.ts
2101
+ var engineFor = (options) => new RequestEngine({
2102
+ defaults: {
2103
+ deadline: options.deadline,
2104
+ maxRequests: options.maxRequests,
2105
+ retries: options.retries,
2106
+ signal: options.signal,
2107
+ timeout: options.timeout
2108
+ },
2109
+ hooks: mergeHooks([
2110
+ options.hooks,
2111
+ ...(options.plugins ?? []).map((plugin) => plugin.hooks)
2112
+ ]),
2113
+ runtime: options.fetch === void 0 ? options.runtime : { ...options.runtime, fetch: options.fetch },
2114
+ share: options.share,
2115
+ store: options.rateLimitStore
2116
+ });
2117
+ var Outbound = class _Outbound {
2118
+ #core;
2119
+ #options;
2120
+ #plugins;
2121
+ campaigns;
2122
+ senders;
2123
+ leads;
2124
+ messages;
2125
+ replies;
2126
+ workspaces;
2127
+ lists;
2128
+ blocklist;
2129
+ tags;
2130
+ placementTests;
2131
+ webhooks;
2132
+ raw;
2133
+ native;
2134
+ constructor(options, engine = engineFor(options)) {
2135
+ const { adapter } = options;
2136
+ const plugins = options.plugins ?? [];
2137
+ assertUniquePluginNames(plugins);
2138
+ const declared = resolveCapabilities(adapter.capabilities);
2139
+ const narrowed = narrowCapabilities(declared, plugins);
2140
+ const run = composeOperations(
2141
+ plugins,
2142
+ (operation, info) => dispatch(
2143
+ {
2144
+ adapter,
2145
+ capabilities: declared,
2146
+ ctx: engine.contextFor(adapter, info.state)
2147
+ },
2148
+ operation
2149
+ )
2150
+ );
2151
+ this.#options = options;
2152
+ this.#plugins = plugins;
2153
+ this.#core = {
2154
+ adapter,
2155
+ allowWrites: options.allowWrites ?? false,
2156
+ engine,
2157
+ gate: { ...narrowed, provider: adapter.name },
2158
+ run
2159
+ };
2160
+ this.campaigns = makeCollection(
2161
+ this.#core,
2162
+ campaignList(this.#core),
2163
+ campaignGet()
2164
+ );
2165
+ this.senders = makeCollection(
2166
+ this.#core,
2167
+ senderList(this.#core),
2168
+ senderGet(this.#core)
2169
+ );
2170
+ this.leads = makeCollection(
2171
+ this.#core,
2172
+ leadList(this.#core),
2173
+ leadGet(this.#core)
2174
+ );
2175
+ this.messages = makeReadCollection(this.#core, messageList(this.#core));
2176
+ this.replies = makeReadCollection(this.#core, replyList(this.#core));
2177
+ this.workspaces = makeReadCollection(this.#core, workspaceList(this.#core));
2178
+ this.lists = makeCollection(
2179
+ this.#core,
2180
+ listList(this.#core),
2181
+ listGet(this.#core)
2182
+ );
2183
+ this.blocklist = makeReadCollection(this.#core, blocklistList(this.#core));
2184
+ this.tags = makeReadCollection(this.#core, tagList(this.#core));
2185
+ this.placementTests = makeReadCollection(
2186
+ this.#core,
2187
+ placementTestList(this.#core)
2188
+ );
2189
+ this.webhooks = makeCollection(
2190
+ this.#core,
2191
+ webhookList(this.#core),
2192
+ webhookGet(this.#core)
2193
+ );
2194
+ this.raw = makeRawClient(
2195
+ this.#core,
2196
+ // Asked as if the adapter had native reads: a plugin that would turn
2197
+ // them off must stop raw on an adapter that has none, too.
2198
+ narrowCapabilities({ ...declared, native: true }, plugins).narrowedBy.get(
2199
+ "native"
2200
+ )
2201
+ );
2202
+ this.native = makeNativeClient(this.#core);
2203
+ }
2204
+ get provider() {
2205
+ return this.#core.adapter.name;
2206
+ }
2207
+ get workspaceId() {
2208
+ return this.#core.adapter.workspaceId;
2209
+ }
2210
+ get capabilities() {
2211
+ return { ...this.#core.gate.capabilities };
2212
+ }
2213
+ get maturity() {
2214
+ return this.#core.adapter.maturity;
2215
+ }
2216
+ get caveats() {
2217
+ return this.#core.adapter.caveats ?? [];
2218
+ }
2219
+ get fields() {
2220
+ const { adapter } = this.#core;
2221
+ return adapter.fieldCoverage ?? resolveFields(adapter.fields);
2222
+ }
2223
+ /** The plugins on this instance, outermost first. */
2224
+ get plugins() {
2225
+ return this.#plugins;
2226
+ }
2227
+ campaign(id) {
2228
+ return makeCampaignHandle(this.#core, id);
2229
+ }
2230
+ sender(id) {
2231
+ return makeSenderHandle(this.#core, id);
2232
+ }
2233
+ lead(id) {
2234
+ return makeLeadHandle(this.#core, id);
2235
+ }
2236
+ list(id) {
2237
+ return makeListHandle(this.#core, id);
2238
+ }
2239
+ thread(id) {
2240
+ return makeThreadHandle(this.#core, id);
2241
+ }
2242
+ /**
2243
+ * The same instance scoped to one client or workspace. It keeps the
2244
+ * plugins and what they add, so `outbound.workspace(id).insights` works.
2245
+ */
2246
+ workspace(id) {
2247
+ const { adapter, engine } = this.#core;
2248
+ if (adapter.members === void 0 && adapter.workspaceId === id) {
2249
+ return this;
2250
+ }
2251
+ const member = adapter.scope?.(id);
2252
+ if (member === void 0) {
2253
+ throw new OutboundError(
2254
+ "NotFound",
2255
+ `Workspace ${id} is not on this instance`,
2256
+ {
2257
+ provider: adapter.name
2258
+ }
2259
+ );
2260
+ }
2261
+ const scoped2 = new _Outbound({ ...this.#options, adapter: member }, engine);
2262
+ installExtensions(scoped2, this.#plugins);
2263
+ return scoped2;
2264
+ }
2265
+ stats(options) {
2266
+ return readStats(this.#core, options);
2267
+ }
2268
+ limits() {
2269
+ const { adapter, engine } = this.#core;
2270
+ return Promise.all(
2271
+ (adapter.members ?? [adapter]).map((member) => engine.limits(member))
2272
+ );
2273
+ }
2274
+ estimate(query) {
2275
+ const cost = this.#core.adapter.costs?.[query.action];
2276
+ if (cost === void 0) {
2277
+ return {
2278
+ basis: `${this.provider} declares no cost for ${query.action}`,
2279
+ requests: null
2280
+ };
2281
+ }
2282
+ const pageSize = query.limit ?? cost.pageSize;
2283
+ if (query.records === void 0 || pageSize === void 0) {
2284
+ return { basis: `${cost.perPage} request(s) per page`, requests: null };
2285
+ }
2286
+ const pages = Math.max(1, Math.ceil(query.records / pageSize));
2287
+ const requests = pages * cost.perPage + query.records * (cost.perRecord ?? 0);
2288
+ return {
2289
+ basis: `${pages} page(s) of ${pageSize} at ${cost.perPage} request(s) each, plus ${cost.perRecord ?? 0} per record`,
2290
+ requests
2291
+ };
2292
+ }
2293
+ };
2294
+
2295
+ // src/internal/outbound/create.ts
2296
+ var createOutbound = (options) => {
2297
+ const outbound = new Outbound(options);
2298
+ installExtensions(outbound, options.plugins ?? []);
2299
+ return outbound;
2300
+ };
2301
+
2302
+ export {
2303
+ DEFAULT_SHARE,
2304
+ fullJitterBackoff,
2305
+ Outbound,
2306
+ createOutbound
2307
+ };