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,2329 @@
1
+ import {
2
+ EVENT_TYPES,
3
+ NO_CATEGORIES,
4
+ reputation,
5
+ smartleadEvents,
6
+ toCampaign,
7
+ toCampaignLead,
8
+ toFoundLead,
9
+ toLead,
10
+ toSender,
11
+ toSequence,
12
+ toSubsequence,
13
+ toWorkspace,
14
+ unwrap,
15
+ withoutSecrets
16
+ } from "../chunks/chunk-PURHK3JU.js";
17
+ import {
18
+ createVendorClient,
19
+ flatMapPage,
20
+ mapPage,
21
+ normalizeBody,
22
+ withLeadFields,
23
+ withMappedFields
24
+ } from "../chunks/chunk-6CVZOUHB.js";
25
+ import {
26
+ fromOne
27
+ } from "../chunks/chunk-FKH5N47I.js";
28
+ import {
29
+ defineNative,
30
+ inBody,
31
+ inBodyRequired,
32
+ inPath,
33
+ inQuery,
34
+ inQueryRequired
35
+ } from "../chunks/chunk-NAKXLBA6.js";
36
+ import {
37
+ emptyCounts,
38
+ metricRow
39
+ } from "../chunks/chunk-YOTW5ESM.js";
40
+ import "../chunks/chunk-NAWZ73QS.js";
41
+ import {
42
+ stableId
43
+ } from "../chunks/chunk-FHKSLCVW.js";
44
+ import {
45
+ readEnv,
46
+ requireCredential
47
+ } from "../chunks/chunk-IPUYZD4O.js";
48
+ import {
49
+ eventTypesOf,
50
+ recordBase,
51
+ refTo,
52
+ refsTo
53
+ } from "../chunks/chunk-U2D34ARZ.js";
54
+ import {
55
+ replyCategorySchema
56
+ } from "../chunks/chunk-4PSO6JEK.js";
57
+ import {
58
+ assertWorkspaceId
59
+ } from "../chunks/chunk-LVYG7XZJ.js";
60
+ import {
61
+ OutboundError,
62
+ makeErrorMapper,
63
+ requireObject
64
+ } from "../chunks/chunk-E7JHLNLG.js";
65
+ import {
66
+ count,
67
+ emailAddress,
68
+ field,
69
+ flag,
70
+ isJsonArray,
71
+ isJsonObject,
72
+ isString,
73
+ list,
74
+ objects,
75
+ parseJson,
76
+ stringMap,
77
+ text,
78
+ timestamp
79
+ } from "../chunks/chunk-VQSCHOBV.js";
80
+
81
+ // src/smartlead/capabilities.ts
82
+ var BASE_URL = "https://server.smartlead.ai/api/v1";
83
+ var API_KEY_ENV = "SMARTLEAD_API_KEY";
84
+ var WORKSPACE_ENV = "SMARTLEAD_WORKSPACE_ID";
85
+ var ACTIVITIES_LANE = "all-leads-activities";
86
+ var LEAD_STATISTICS_LANE = "leads-statistics";
87
+ var DOMAIN_HEALTH_LANE = "domain-wise-health";
88
+ var PAGE_SIZE = 100;
89
+ var ACTIVITIES_PAGE_SIZE = 100;
90
+ var ACTIVITIES_MAX_PAGE_SIZE = 1e3;
91
+ var BLOCKLIST_PAGE_SIZE = 1e3;
92
+ var INBOX_PAGE_SIZE = 20;
93
+ var capabilities = {
94
+ // GET /leads/get-domain-block-list: addresses and domains.
95
+ blocklist: true,
96
+ // GET /campaigns/{id}: schedule, caps, tracking and stop rules.
97
+ // GET /email-accounts/{id}/?fetch_campaigns=true names the campaign ids.
98
+ "campaigns.bySender": true,
99
+ // GET /campaigns/{id}/analytics carries campaign_lead_stats.
100
+ "campaigns.progress": true,
101
+ "campaigns.settings": true,
102
+ // GET /campaigns/ has no status filter and returns every campaign at once.
103
+ "campaigns.status": "client",
104
+ "events.parse": true,
105
+ // Standard Webhooks signing, which the customer turns on per webhook.
106
+ "events.verify": "signature",
107
+ "leads.byCampaign": true,
108
+ // leads.engagement is left off: the only per-lead counts are in
109
+ // GET /campaigns/{id}/leads-statistics, whose response is documented
110
+ // nowhere, and in a CSV export.
111
+ "leads.get": true,
112
+ // Smartlead has no list of all leads. Without a campaign the adapter walks
113
+ // every campaign's leads; see the caveats.
114
+ "leads.list": true,
115
+ // GET /leads/?email= returns the lead and its campaigns. Nothing finds a
116
+ // lead by its LinkedIn profile, so that filter matches no lead.
117
+ "leads.lookup": true,
118
+ // created_at_gt does not say which created_at it compares, so it is not
119
+ // sent and the wrapper filters after fetching.
120
+ "leads.since": "client",
121
+ "leads.timeline": true,
122
+ // SmartDelivery's POST /spam-test/report, on its own host.
123
+ "placementTests.list": true,
124
+ // GET /lead-list/{id}.
125
+ "lists.get": true,
126
+ // GET /lead-list/. lists.leads is left off: no endpoint returns the leads
127
+ // of a lead list.
128
+ "lists.list": true,
129
+ "messages.body": "full",
130
+ // GET /master-inbox/{id}: the id is the lead-in-campaign mapping id.
131
+ "messages.byThread": true,
132
+ "messages.list": true,
133
+ // event_time_from narrows the feed; the wrapper filters on the send time.
134
+ "messages.since": "client",
135
+ // The reads with no normalized form, by name: see native.ts.
136
+ native: true,
137
+ "replies.category": "vendor",
138
+ "replies.list": true,
139
+ // replyTimeBetween narrows the inbox; the wrapper filters on the reply time.
140
+ // A thread carries is_read, and the inbox has no filter for it.
141
+ "replies.unread": "client",
142
+ "replies.since": "client",
143
+ "senders.byCampaign": true,
144
+ "senders.get": true,
145
+ // The mailbox and its warmup statistics; no DNS records are reported.
146
+ "senders.health": true,
147
+ "senders.list": true,
148
+ "senders.warmup": true,
149
+ sequence: true,
150
+ // Child campaigns of the campaign list, each with its own steps.
151
+ "sequence.subsequences": true,
152
+ // GET /analytics/day-wise-overall-stats returns one row per day.
153
+ "stats.byDay": "exact",
154
+ // GET /analytics/mailbox/name-wise-health-metrics, one row per mailbox
155
+ // address. The per-campaign mailbox endpoint documents no response.
156
+ "stats.bySender": "exact",
157
+ "stats.byStep": "exact",
158
+ // GET /analytics/campaign/overall-stats: a row per campaign, totals only.
159
+ // Partial: it has no clicks and no unsubscribes.
160
+ "stats.allCampaigns": "partial",
161
+ "stats.campaign": "exact",
162
+ "stats.workspace": "exact",
163
+ // GET /email-accounts/tags: one tag space for mailboxes, leads and campaigns.
164
+ tags: true,
165
+ // GET /webhook/{webhook_id}.
166
+ "webhooks.get": true,
167
+ // GET /campaigns/{id}/webhooks; there is no list of every webhook.
168
+ "webhooks.list": true,
169
+ workspaces: true
170
+ };
171
+ var fields = {
172
+ campaignProgress: { failed: false },
173
+ campaignSettings: { endDate: false },
174
+ lead: { companyLinkedinUrl: false, engagement: false, title: false },
175
+ message: { variantKey: false },
176
+ metricRow: {
177
+ connectionsAccepted: false,
178
+ connectionsSent: false,
179
+ contentHash: false,
180
+ delivered: false,
181
+ inmailsSent: false,
182
+ // total_reply_count less non_ooo_reply_count.
183
+ repliedAuto: "derived"
184
+ },
185
+ // SmartDelivery's list gives a test's schedule and nothing else about it.
186
+ placementTest: { campaignRef: false, createdAt: false, nextRunAt: false },
187
+ reply: {
188
+ // The lead's category, not a label on the message.
189
+ category: "derived",
190
+ categorySource: "derived",
191
+ // Only an Out Of Office category says a reply was automatic.
192
+ isAuto: "derived",
193
+ // The master inbox does not say which step a reply answers.
194
+ stepIndex: false,
195
+ variantKey: false
196
+ },
197
+ sender: { linkedinUrl: false },
198
+ senderHealth: { blacklisted: false, checkedAt: false, dns: false },
199
+ tag: { description: false }
200
+ };
201
+ var TEN_PER_MINUTE = [{ perMs: 6e4, requests: 10 }];
202
+ var limits = {
203
+ lanes: {
204
+ [ACTIVITIES_LANE]: TEN_PER_MINUTE,
205
+ [DOMAIN_HEALTH_LANE]: TEN_PER_MINUTE,
206
+ [LEAD_STATISTICS_LANE]: TEN_PER_MINUTE
207
+ },
208
+ source: "https://helpcenter.smartlead.ai/en/articles/68-how-to-get-started-with-the-smartlead-api (200/min shared by an account's admin keys), https://helpcenter.smartlead.ai/en/articles/430-how-client-level-api-keys-work-in-smartlead (60/min per client key) and https://api.smartlead.ai/guides/rate-limits (10 per 60 s on three endpoints); read 2026-11-14, not confirmed live. The key type cannot be detected, so every key gets the 60/min limit",
209
+ windows: [{ perMs: 6e4, requests: 60 }]
210
+ };
211
+ var costs = {
212
+ "blocklist.list": { pageSize: BLOCKLIST_PAGE_SIZE, perPage: 1 },
213
+ "campaigns.get": { perPage: 1 },
214
+ // One request returns every campaign; there are no pages.
215
+ "campaigns.list": { perPage: 1 },
216
+ "campaigns.settings": { perPage: 1 },
217
+ // The lead, then its tags, then the category list when the lead has a
218
+ // category.
219
+ "leads.get": { perPage: 2 },
220
+ // The first page also reads the lead category list and, without a
221
+ // campaign, the campaign list. A lookup by address is one request, two
222
+ // when a campaign gives a lead category, and never walks leads.
223
+ "leads.list": { pageSize: PAGE_SIZE, perPage: 1 },
224
+ "lists.list": { pageSize: PAGE_SIZE, perPage: 1 },
225
+ // A lead's timeline costs one request per campaign the lead is in, plus one
226
+ // to find those campaigns. A thread is one request.
227
+ "messages.list": { pageSize: ACTIVITIES_PAGE_SIZE, perPage: 1 },
228
+ // The first page of a walk also reads the lead category list.
229
+ "replies.list": { pageSize: INBOX_PAGE_SIZE, perPage: 1 },
230
+ "senders.get": { perPage: 1 },
231
+ // The mailbox, then its warmup statistics.
232
+ "senders.health": { perPage: 2 },
233
+ "senders.list": { pageSize: PAGE_SIZE, perPage: 1 },
234
+ "sequence.get": { perPage: 1 },
235
+ // One subsequence per page; the first page also reads the campaign list.
236
+ "sequence.subsequences": { pageSize: 1, perPage: 1 },
237
+ // A mailbox's totals cost two: the mailbox for its address, then the list.
238
+ // Daily rows cost two: the day-wise counts, then the positive replies.
239
+ stats: { perPage: 1 },
240
+ "tags.list": { perPage: 1 },
241
+ // One campaign per page; without a campaign, the first page also reads the
242
+ // campaign list.
243
+ "webhooks.list": { perPage: 1 },
244
+ "workspaces.list": { perPage: 1 }
245
+ };
246
+ var caveats = [
247
+ "outbound.raw returns responses unchanged: GET /email-accounts includes SMTP and IMAP passwords, which only normalized records drop.",
248
+ "outbound.native returns each payload as Smartlead sent it. Its catalog leaves out the reads that return secrets: client API keys, a mailbox looked up by address, SmartSenders orders and one-time passwords, and a client's whitelabel credentials.",
249
+ "Native reads of SmartDelivery, SmartProspect, SmartSenders and SmartServers call other hosts with the same key; an account without the product is refused. Their parameters and responses follow the reference alone.",
250
+ "Nothing is checked against a live account; mappings follow the documentation read on 2026-11-14, whose three sources disagree, also on envelopes (bare or { ok | success, data }; both are accepted).",
251
+ "The API key travels in the URL (api_key): the SDK redacts it, but a proxy or server log can record it.",
252
+ "leads.list without a campaign walks every campaign: a lead in no campaign is never returned, and one in several is returned once by listAll.",
253
+ "leads.list({ email }) reads GET /leads/?email=: one record per campaign, all with the lead's id (listAll keeps one), status unknown unless unsubscribed, createdAt the lead's own. Address matching is undocumented; other addresses are dropped.",
254
+ "No endpoint finds a lead by LinkedIn profile: leads.list({ linkedinUrl }) returns nothing and sends no request.",
255
+ "A lead's status, campaign and creation time are per campaign; leads.get returns no campaign and its example looks illustrative.",
256
+ "STOPPED maps to paused. A lead's status BLOCKED, which Smartlead describes as bounced or on the block list, sets bounced and leaves progress unknown. unsubscribed is is_unsubscribed. replied is email_stats.is_replied, which only leads.get carries, so a listed lead's replied is null.",
257
+ "Messages come from GET /campaigns/all-leads-activities (10 requests per 60 s, no campaign filter, pages of leads): campaign(id).messages reads the whole feed, and thread_replies is not read.",
258
+ "senderRef is null on feed and history messages (mailbox named by address). leadRef on replies and thread messages needs lead.id or lead_id on the thread; documented examples show an address only.",
259
+ "threadId is the lead-in-campaign mapping id; history messages have none. GET /master-inbox/{id} is documented without message ids or bodies; older history items are accepted too.",
260
+ "A lead's timeline follows the older documentation's { history, from, to } shape.",
261
+ "Replies come from POST /master-inbox/inbox-replies (illustrative item shape), 20 threads per page: each inbound history message is a reply, or only the latest without a history, and all share the lead's current category.",
262
+ "Reply categories come from GET /leads/fetch-categories: sentiment_type gives positive or negative, null neutral, the name Out Of Office ooo; a list without sentiment_type leaves the rest unknown.",
263
+ "Dated statistics need both dates: a missing end is today (UTC), a missing start 2000-01-01 for totals, or 30 days before the end for daily rows and a campaign's dated total.",
264
+ "No delivered count exists. A campaign's dated total uses non_ooo_reply_count for replied and total_reply_count less non_ooo_reply_count for repliedAuto, which is out-of-office replies only; lifetime reply_count includes out-of-office replies and has no automatic-reply count.",
265
+ "Daily rows have sent, total opens and replies, plus positive replies from a second request (GET /analytics/day-wise-positive-reply-stats); the daily endpoint always reports 0 bounces, so bounced is null.",
266
+ "Step statistics do not say whether opens and clicks are unique (mapped to openedTotal and clickedTotal). A step with variants has a row per variant and no total.",
267
+ "A sender is disconnected when is_smtp_success or is_imap_success is false, active when both are true, else unknown. warmup_reputation may be a number or a string such as 95%.",
268
+ "Workspaces are Smartlead clients; a client-level key may be refused.",
269
+ "Webhook signing is off until turned on per webhook; unsigned webhooks fail verify.",
270
+ "Webhook examples omit lead ids, so leadRef needs sl_email_lead_id or lead_id.",
271
+ "Settings: dailyNewLeads is max_leads_per_day, gapMinutes min_time_btwn_emails, dailyLimit sending_limit (newer example only), startDate the UTC day of schedule_start_time. One sending window, no end date.",
272
+ "stopOnReply is true for REPLY_TO_AN_EMAIL, false for NEVER, else null. stopOnAutoReply needs out_of_office_detection_settings.ignoreOOOasReply, documented on the settings update only.",
273
+ "Subsequences are campaigns whose parent_campaign_id is the campaign, one per page; that GET /campaigns/ lists them is implied, not confirmed. Trigger conditions cannot be read, so branch is null.",
274
+ "Sender health reads the mailbox and its 7-day warmup-stats (both documented shapes). DNS records, block list state and check time are not reported.",
275
+ "A mailbox's statistics are its row, by address, of GET /analytics/mailbox/name-wise-health-metrics (totals only, no filter, undocumented paging): a mailbox it leaves out gets null counts. opened is taken as total opens.",
276
+ "interest is the lead category's name, resolved through GET /leads/fetch-categories; leads.get reads category_name, shown only in an illustrative example.",
277
+ "Lead tags cost a request per lead (GET /crm/leads/tags), so only leads.get fills them. engagement is null: no JSON response documents per-lead counts.",
278
+ "Tags come from GET /email-accounts/tags; whether campaign tags share that list is unconfirmed.",
279
+ "Webhooks are listed per campaign; without one the adapter walks the campaigns and returns each once. User-level or client-level webhooks may appear under none.",
280
+ "Placement tests are read from SmartDelivery (smartdelivery.smartlead.ai) with the same key: an account without the product is refused. The list is documented without pages, and manual is read as a one-time test. A test's results stay native, because SmartDelivery reports them as rates.",
281
+ "Block list entries with an @ are emails, the rest domains."
282
+ ];
283
+
284
+ // src/smartlead/map-account.ts
285
+ var parsed = (value) => isString(value) ? parseJson(value) : value;
286
+ var CLOCK = /^(?<hour>\d{1,2}):(?<minute>\d{2})/u;
287
+ var clock = (value) => {
288
+ const match = CLOCK.exec(text(value) ?? "");
289
+ const hour = match?.groups?.hour;
290
+ const minute = match?.groups?.minute;
291
+ return hour === void 0 || minute === void 0 ? null : `${hour.padStart(2, "0")}:${minute}`;
292
+ };
293
+ var weekdays = (value) => list(value).flatMap((day) => {
294
+ const number = count(day);
295
+ return number !== null && Number.isInteger(number) && number >= 0 && number <= 6 ? [number] : [];
296
+ });
297
+ var schedule = (value) => {
298
+ const cron = parsed(value);
299
+ if (!isJsonObject(cron)) {
300
+ return [];
301
+ }
302
+ return [
303
+ {
304
+ days: weekdays(cron.days),
305
+ from: clock(cron.startHour),
306
+ name: null,
307
+ timezone: text(cron.tz),
308
+ to: clock(cron.endHour)
309
+ }
310
+ ];
311
+ };
312
+ var tracked = (value, off) => {
313
+ const settings = parsed(value);
314
+ return isJsonArray(settings) ? !settings.some((setting) => isString(setting) && setting.endsWith(off)) : null;
315
+ };
316
+ var STOP_ON_REPLY = /* @__PURE__ */ new Map([
317
+ ["NEVER", false],
318
+ ["REPLY_TO_AN_EMAIL", true]
319
+ ]);
320
+ var stopOnAutoReply = (raw, stopOnReply) => {
321
+ const ignored = flag(
322
+ field(raw.out_of_office_detection_settings, "ignoreOOOasReply")
323
+ );
324
+ if (ignored === null) {
325
+ return null;
326
+ }
327
+ return ignored ? false : stopOnReply;
328
+ };
329
+ var toSettings = (identity, campaignId, raw) => {
330
+ const stopOnReply = STOP_ON_REPLY.get(text(raw.stop_lead_settings) ?? "") ?? null;
331
+ return {
332
+ ...recordBase(identity, campaignId, raw),
333
+ campaignRef: refTo(identity, campaignId) ?? "",
334
+ // Named only in the newer example and the settings guide; a mailbox's own
335
+ // daily limit is on the sender.
336
+ dailyLimit: count(raw.sending_limit),
337
+ dailyNewLeads: count(raw.max_leads_per_day),
338
+ endDate: null,
339
+ gapMinutes: count(raw.min_time_btwn_emails),
340
+ plainText: flag(raw.send_as_plain_text),
341
+ schedule: schedule(raw.scheduler_cron_value),
342
+ startDate: timestamp(raw.schedule_start_time)?.slice(0, 10) ?? null,
343
+ stopOnAutoReply: stopOnAutoReply(raw, stopOnReply),
344
+ stopOnReply,
345
+ tracking: {
346
+ clicks: tracked(raw.track_settings, "LINK_CLICK"),
347
+ opens: tracked(raw.track_settings, "EMAIL_OPEN")
348
+ }
349
+ };
350
+ };
351
+ var toCampaignProgress = (identity, campaignId, raw) => {
352
+ const stats = raw.campaign_lead_stats;
353
+ return {
354
+ ...recordBase(identity, campaignId, raw),
355
+ blocked: count(field(stats, "blocked")),
356
+ campaignRef: refTo(identity, campaignId) ?? "",
357
+ completed: count(field(stats, "completed")),
358
+ // Smartlead has no count of leads a campaign failed for.
359
+ failed: null,
360
+ inProgress: count(field(stats, "inprogress")),
361
+ leads: count(field(stats, "total")),
362
+ notStarted: count(field(stats, "notStarted")),
363
+ stopped: count(field(stats, "stopped"))
364
+ };
365
+ };
366
+ var connected = (account) => {
367
+ const smtp = flag(account.is_smtp_success);
368
+ const imap = flag(account.is_imap_success);
369
+ if (smtp === false || imap === false) {
370
+ return false;
371
+ }
372
+ return smtp === true && imap === true ? true : null;
373
+ };
374
+ var warmupTraffic = (stats, details) => isJsonObject(stats) ? {
375
+ inbox: count(stats.inbox_count),
376
+ received: count(stats.warmup_email_received_count),
377
+ score: reputation(stats.reputation_score) ?? reputation(field(details, "warmup_reputation")),
378
+ sent: count(stats.sent_count) ?? count(stats.total_sent),
379
+ spam: count(stats.spam_count)
380
+ } : null;
381
+ var toHealth = (identity, account, stats) => {
382
+ const id = text(account.id) ?? "";
383
+ const address = emailAddress(account.from_email);
384
+ return {
385
+ ...recordBase(identity, id, {
386
+ account: withoutSecrets(account),
387
+ warmup_stats: stats ?? null
388
+ }),
389
+ blacklisted: null,
390
+ checkedAt: null,
391
+ connected: connected(account),
392
+ dns: { dkim: null, dmarc: null, mx: null, spf: null },
393
+ domain: address?.split("@")[1] ?? null,
394
+ issues: [
395
+ account.smtp_failure_error,
396
+ account.imap_failure_error,
397
+ field(account.warmup_details, "blocked_reason")
398
+ ].flatMap((issue) => text(issue) ?? []),
399
+ senderRef: refTo(identity, id) ?? "",
400
+ warmup: warmupTraffic(stats, account.warmup_details)
401
+ };
402
+ };
403
+ var TEST_STATUS = /* @__PURE__ */ new Map([
404
+ ["active", "active"],
405
+ ["completed", "completed"],
406
+ ["paused", "paused"]
407
+ ]);
408
+ var TEST_KIND = /* @__PURE__ */ new Map([
409
+ ["automated", "automated"],
410
+ ["manual", "one_time"]
411
+ ]);
412
+ var toPlacementTest = (identity, raw) => {
413
+ const id = text(raw.spam_test_id) ?? text(raw.id) ?? "";
414
+ return {
415
+ ...recordBase(identity, id, raw),
416
+ campaignRef: null,
417
+ createdAt: null,
418
+ endsAt: timestamp(raw.test_end_date),
419
+ kind: TEST_KIND.get(text(raw.test_type)?.toLowerCase() ?? "") ?? null,
420
+ name: text(raw.test_name) ?? id,
421
+ nextRunAt: null,
422
+ startsAt: timestamp(raw.schedule_start_time),
423
+ status: TEST_STATUS.get(text(raw.status)?.toLowerCase() ?? "") ?? "unknown"
424
+ };
425
+ };
426
+ var toList = (identity, raw) => ({
427
+ ...recordBase(identity, text(raw.id) ?? "", raw),
428
+ createdAt: timestamp(raw.created_at),
429
+ kind: "leads",
430
+ name: text(raw.name) ?? text(raw.id) ?? "",
431
+ size: count(raw.lead_count)
432
+ });
433
+ var toBlockEntry = (identity, raw) => {
434
+ const value = text(raw.email_or_domain)?.toLowerCase();
435
+ return value === void 0 ? [] : [
436
+ {
437
+ ...recordBase(identity, text(raw.id) ?? "", raw),
438
+ createdAt: timestamp(raw.created_at),
439
+ kind: value.includes("@") ? "email" : "domain",
440
+ value
441
+ }
442
+ ];
443
+ };
444
+ var toTag = (identity, raw) => ({
445
+ ...recordBase(identity, text(raw.id) ?? "", raw),
446
+ description: null,
447
+ name: text(raw.name) ?? text(raw.id) ?? ""
448
+ });
449
+ var eventNames = (raw) => {
450
+ const listed = list(raw.event_types).flatMap((event) => text(event) ?? []);
451
+ if (listed.length > 0 || !isJsonObject(raw.event_type_map)) {
452
+ return listed;
453
+ }
454
+ return Object.entries(raw.event_type_map).flatMap(
455
+ ([name, on]) => on === true ? [name] : []
456
+ );
457
+ };
458
+ var toWebhook = (identity, campaignId, raw) => {
459
+ const events = eventNames(raw);
460
+ return {
461
+ ...recordBase(identity, text(raw.id) ?? "", withoutSecrets(raw)),
462
+ // Only the newer example carries is_active.
463
+ active: flag(raw.is_active),
464
+ campaignRefs: refsTo(identity, [text(raw.email_campaign_id) ?? campaignId]),
465
+ createdAt: timestamp(raw.created_at),
466
+ eventTypes: eventTypesOf(events, EVENT_TYPES),
467
+ events,
468
+ name: text(raw.name),
469
+ url: text(raw.webhook_url) ?? ""
470
+ };
471
+ };
472
+
473
+ // src/smartlead/map-messages.ts
474
+ var OUT_OF_OFFICE = "out of office";
475
+ var SENTIMENT = /* @__PURE__ */ new Map([
476
+ ["negative", "negative"],
477
+ ["positive", "positive"]
478
+ ]);
479
+ var categoryOf = (raw) => {
480
+ if (text(raw.name)?.toLowerCase() === OUT_OF_OFFICE) {
481
+ return "ooo";
482
+ }
483
+ const sentiment = SENTIMENT.get(text(raw.sentiment_type) ?? "");
484
+ if (sentiment !== void 0) {
485
+ return sentiment;
486
+ }
487
+ return raw.sentiment_type === null ? "neutral" : void 0;
488
+ };
489
+ var toCategoryMap = (body) => new Map(
490
+ objects(body).flatMap((raw) => {
491
+ const id = text(raw.id);
492
+ const category = categoryOf(raw);
493
+ return id === null || category === void 0 ? [] : [[id, category]];
494
+ })
495
+ );
496
+ var categoriesToJson = (categories) => Object.fromEntries(categories);
497
+ var categoriesFromJson = (value) => new Map(
498
+ Object.entries(isJsonObject(value) ? value : {}).flatMap(
499
+ ([id, category]) => {
500
+ const parsed2 = replyCategorySchema.safeParse(category);
501
+ return parsed2.success ? [[id, parsed2.data]] : [];
502
+ }
503
+ )
504
+ );
505
+ var categoryIds = (categories, category) => [...categories].flatMap(([id, mapped]) => {
506
+ const number = count(id);
507
+ return mapped === category && number !== null ? [number] : [];
508
+ });
509
+ var messageFields = (identity, place, parts, includeBody) => ({
510
+ ...recordBase(identity, parts.sourceId, parts.raw),
511
+ ...normalizeBody(parts.body, includeBody),
512
+ campaignRef: refTo(identity, place.campaignId),
513
+ channel: "email",
514
+ leadRef: refTo(identity, place.leadId),
515
+ senderRef: refTo(identity, place.senderId),
516
+ sentAt: timestamp(parts.sentAt),
517
+ stepIndex: place.stepIndex ?? null,
518
+ subject: parts.subject,
519
+ threadId: place.threadId ?? null,
520
+ variantKey: null
521
+ });
522
+ var activityMessages = (identity, row, activity, includeBody) => {
523
+ const place = {
524
+ campaignId: text(row.campaign_id),
525
+ leadId: text(row.lead_id),
526
+ stepIndex: fromOne(activity.email_seq_number),
527
+ // The lead-in-campaign mapping id is the master inbox's thread id.
528
+ threadId: text(row.email_lead_map_id)
529
+ };
530
+ const sent = {
531
+ ...messageFields(
532
+ identity,
533
+ place,
534
+ {
535
+ body: text(activity.email_body),
536
+ raw: activity,
537
+ sentAt: activity.sent_time,
538
+ sourceId: text(activity.stats_id) ?? "",
539
+ subject: text(activity.subject)
540
+ },
541
+ includeBody
542
+ ),
543
+ direction: "out"
544
+ };
545
+ const reply = activity.reply_details;
546
+ if (!isJsonObject(reply)) {
547
+ return [sent];
548
+ }
549
+ return [
550
+ sent,
551
+ {
552
+ ...messageFields(
553
+ identity,
554
+ place,
555
+ {
556
+ body: text(reply.reply_email_body),
557
+ raw: reply,
558
+ sentAt: reply.time,
559
+ // A reply has no id of its own beyond its Message-ID header.
560
+ sourceId: text(reply.message_id) ?? stableId(sent.sourceId, text(reply.time)),
561
+ subject: null
562
+ },
563
+ includeBody
564
+ ),
565
+ direction: "in"
566
+ }
567
+ ];
568
+ };
569
+ var toActivityMessages = (identity, row, includeBody) => objects(row.activities).flatMap(
570
+ (activity) => activityMessages(identity, row, activity, includeBody)
571
+ );
572
+ var toHistoryMessage = (identity, place, item, includeBody) => {
573
+ const isReply = text(item.type) === "REPLY";
574
+ const statsId = text(item.stats_id);
575
+ const messageId = text(item.message_id);
576
+ return {
577
+ ...messageFields(
578
+ identity,
579
+ place,
580
+ {
581
+ body: text(item.email_body),
582
+ raw: item,
583
+ sentAt: item.time,
584
+ // A sent email is identified by its stats_id, as in the activity feed.
585
+ // A reply carries the stats_id of the email it answers.
586
+ sourceId: (isReply ? messageId : statsId) ?? stableId(statsId, messageId, text(item.time)),
587
+ subject: text(item.subject)
588
+ },
589
+ includeBody
590
+ ),
591
+ direction: isReply ? "in" : "out"
592
+ };
593
+ };
594
+ var isInbound = (item) => text(item.direction) === "inbound" || text(item.type) === "REPLY";
595
+ var threadParts = (threadId, item) => {
596
+ const inbound = isInbound(item);
597
+ const time = item.sent_at ?? item.received_at ?? item.time;
598
+ return {
599
+ body: text(item.body) ?? text(item.email_body),
600
+ raw: item,
601
+ sentAt: time,
602
+ sourceId: text(item.id) ?? text(inbound ? item.message_id : item.stats_id) ?? stableId(threadId, text(item.direction), text(time), text(item.subject)),
603
+ subject: text(item.subject)
604
+ };
605
+ };
606
+ var threadPlace = (thread) => ({
607
+ campaignId: text(field(thread.campaign, "id")),
608
+ leadId: text(field(thread.lead, "id")) ?? text(thread.lead_id),
609
+ senderId: text(field(thread.email_account, "id")),
610
+ threadId: text(thread.campaign_lead_map_id)
611
+ });
612
+ var toThreadMessages = (identity, thread, includeBody) => {
613
+ const place = threadPlace(thread);
614
+ return objects(thread.message_history).map((item) => ({
615
+ ...messageFields(
616
+ identity,
617
+ place,
618
+ threadParts(place.threadId ?? null, item),
619
+ includeBody
620
+ ),
621
+ direction: isInbound(item) ? "in" : "out"
622
+ }));
623
+ };
624
+ var toInboxReplies = (identity, item, categories, includeBody) => {
625
+ const last = item.last_message;
626
+ const category = categories.get(text(field(item.category, "id")) ?? "");
627
+ const place = threadPlace(item);
628
+ const history = objects(item.message_history).filter(isInbound);
629
+ const parts = history.length > 0 ? history.map((message) => threadParts(place.threadId ?? null, message)) : [
630
+ {
631
+ body: text(field(last, "body")),
632
+ raw: item,
633
+ sentAt: field(last, "received_at"),
634
+ sourceId: text(field(last, "id")) ?? text(item.id) ?? "",
635
+ subject: text(field(last, "subject"))
636
+ }
637
+ ];
638
+ const read = flag(item.is_read);
639
+ return parts.map((part) => ({
640
+ ...messageFields(identity, place, part, includeBody),
641
+ category: category ?? "unknown",
642
+ // The category is the lead's, not one message's.
643
+ categorySource: category === void 0 ? null : "lead",
644
+ direction: "in",
645
+ // Smartlead's only automatic-reply signal is the Out Of Office category.
646
+ isAuto: category === "ooo" ? true : null,
647
+ // `is_read` is the thread's.
648
+ unread: read === null ? null : !read
649
+ }));
650
+ };
651
+
652
+ // src/smartlead/shared.ts
653
+ var pageSize = (limit, max = PAGE_SIZE) => Math.min(limit ?? max, max);
654
+ var segment = (id) => encodeURIComponent(id);
655
+ var idList = (value) => list(value).flatMap((id) => text(id) ?? []);
656
+ var objectOf = (client, body, what) => requireObject(
657
+ unwrap(body),
658
+ client.identity.provider,
659
+ `Smartlead returned no object for ${what}`
660
+ );
661
+ var campaignList = async (client, ctx) => objects(
662
+ unwrap(
663
+ await client.get(ctx, "/campaigns/", { query: { include_tags: true } })
664
+ )
665
+ );
666
+ var campaignIds = async (client, ctx) => {
667
+ const campaigns = await campaignList(client, ctx);
668
+ return campaigns.flatMap((campaign) => text(campaign.id) ?? []);
669
+ };
670
+ var offsetPage = async (client, ctx, path, page) => {
671
+ const rows = objects(unwrap(await client.get(ctx, path, { query: page })));
672
+ return {
673
+ items: rows,
674
+ next: rows.length === page.limit ? page.offset + page.limit : void 0
675
+ };
676
+ };
677
+ var leadCategories = async (client, ctx, next) => {
678
+ if (isJsonObject(next)) {
679
+ return {
680
+ meanings: categoriesFromJson(next.meanings),
681
+ names: stringMap(next.categories)
682
+ };
683
+ }
684
+ const body = unwrap(await client.get(ctx, "/leads/fetch-categories"));
685
+ return {
686
+ meanings: toCategoryMap(body),
687
+ names: Object.fromEntries(
688
+ objects(body).flatMap((category) => {
689
+ const id = text(category.id);
690
+ const name = text(category.name);
691
+ return id === null || name === null ? [] : [[id, name]];
692
+ })
693
+ )
694
+ };
695
+ };
696
+ var categoriesCursor = (categories) => ({
697
+ categories: { ...categories.names },
698
+ meanings: categoriesToJson(categories.meanings)
699
+ });
700
+
701
+ // src/smartlead/account.ts
702
+ var listSubsequences = async (client, ctx, query) => {
703
+ const campaigns = isJsonObject(query.next) ? objects(query.next.subsequences) : await campaignList(client, ctx);
704
+ const children = campaigns.filter(
705
+ (campaign) => text(campaign.parent_campaign_id) === query.campaignId
706
+ );
707
+ const [current, ...rest] = children;
708
+ const id = text(current?.id);
709
+ if (current === void 0 || id === null) {
710
+ return { items: [] };
711
+ }
712
+ const steps = await client.get(ctx, `/campaigns/${segment(id)}/sequences`);
713
+ return {
714
+ items: [toSubsequence(client.identity, query.campaignId, current, steps)],
715
+ next: rest.length > 0 ? { subsequences: rest } : void 0
716
+ };
717
+ };
718
+ var campaignWebhooks = async (client, ctx, campaignId) => objects(
719
+ unwrap(await client.get(ctx, `/campaigns/${segment(campaignId)}/webhooks`))
720
+ ).map((webhook) => toWebhook(client.identity, campaignId, webhook));
721
+ var listWebhooks = async (client, ctx, query) => {
722
+ if (query.campaignId !== void 0) {
723
+ return { items: await campaignWebhooks(client, ctx, query.campaignId) };
724
+ }
725
+ const campaigns = isJsonObject(query.next) ? idList(query.next.campaigns) : await campaignIds(client, ctx);
726
+ const [current, ...rest] = campaigns;
727
+ if (current === void 0) {
728
+ return { items: [] };
729
+ }
730
+ const seen = new Set(idList(field(query.next, "seen")));
731
+ const listed = await campaignWebhooks(client, ctx, current);
732
+ const items = listed.filter((webhook) => !seen.has(webhook.sourceId));
733
+ return {
734
+ items,
735
+ next: rest.length > 0 ? {
736
+ campaigns: rest,
737
+ seen: [...seen, ...items.map((webhook) => webhook.sourceId)]
738
+ } : void 0
739
+ };
740
+ };
741
+ var accountReaders = (client) => {
742
+ const { identity } = client;
743
+ return {
744
+ getCampaignProgress: async (id, ctx) => toCampaignProgress(
745
+ identity,
746
+ id,
747
+ objectOf(
748
+ client,
749
+ await client.get(ctx, `/campaigns/${segment(id)}/analytics`),
750
+ "campaign analytics"
751
+ )
752
+ ),
753
+ getCampaignSettings: async (id, ctx) => toSettings(
754
+ identity,
755
+ id,
756
+ objectOf(
757
+ client,
758
+ await client.get(ctx, `/campaigns/${segment(id)}`),
759
+ "the campaign"
760
+ )
761
+ ),
762
+ getSenderHealth: async (id, ctx) => {
763
+ const account = objectOf(
764
+ client,
765
+ await client.get(ctx, `/email-accounts/${segment(id)}/`),
766
+ "the email account"
767
+ );
768
+ const stats = await client.get(
769
+ ctx,
770
+ `/email-accounts/${segment(id)}/warmup-stats`
771
+ );
772
+ return toHealth(identity, account, unwrap(stats));
773
+ },
774
+ getList: async (id, ctx) => toList(
775
+ identity,
776
+ objectOf(
777
+ client,
778
+ await client.get(ctx, `/lead-list/${segment(id)}`),
779
+ "the lead list"
780
+ )
781
+ ),
782
+ getWebhook: async (id, ctx) => toWebhook(
783
+ identity,
784
+ null,
785
+ objectOf(
786
+ client,
787
+ await client.get(ctx, `/webhook/${segment(id)}`),
788
+ "the webhook"
789
+ )
790
+ ),
791
+ listBlocklist: async (query, ctx) => {
792
+ const page = await offsetPage(
793
+ client,
794
+ ctx,
795
+ "/leads/get-domain-block-list",
796
+ {
797
+ limit: pageSize(query.limit, BLOCKLIST_PAGE_SIZE),
798
+ offset: count(query.next) ?? 0
799
+ }
800
+ );
801
+ return flatMapPage(page, (entry) => toBlockEntry(identity, entry));
802
+ },
803
+ listLists: async (query, ctx) => {
804
+ const page = await offsetPage(client, ctx, "/lead-list/", {
805
+ limit: pageSize(query.limit),
806
+ offset: count(query.next) ?? 0
807
+ });
808
+ return mapPage(page, (row) => toList(identity, row));
809
+ },
810
+ // SmartDelivery answers with every test at once: no pages are documented.
811
+ listPlacementTests: async (_query, ctx) => ({
812
+ items: objects(
813
+ unwrap(await client.delivery.post(ctx, "/spam-test/report", {}))
814
+ ).map((test) => toPlacementTest(identity, test))
815
+ }),
816
+ listSubsequences: (query, ctx) => listSubsequences(client, ctx, query),
817
+ // One response holds every tag of the account; there are no pages.
818
+ listTags: async (_query, ctx) => ({
819
+ items: objects(unwrap(await client.get(ctx, "/email-accounts/tags"))).map(
820
+ (tag) => toTag(identity, tag)
821
+ )
822
+ }),
823
+ listWebhooks: (query, ctx) => listWebhooks(client, ctx, query)
824
+ };
825
+ };
826
+
827
+ // src/smartlead/lookup.ts
828
+ var NONE = { items: [] };
829
+ var memberships = async (client, ctx, lead) => {
830
+ const listed = lead.lead_campaign_data;
831
+ const entries = isJsonArray(listed) ? objects(listed) : objects(
832
+ unwrap(
833
+ await client.get(
834
+ ctx,
835
+ `/leads/${segment(text(lead.id) ?? "")}/campaigns`
836
+ )
837
+ )
838
+ );
839
+ return entries.flatMap((entry) => {
840
+ const campaignId = text(entry.campaign_id) ?? text(entry.id);
841
+ return campaignId === null ? [] : [{ campaignId, entry }];
842
+ });
843
+ };
844
+ var leadsByEmail = async (client, ctx, query) => {
845
+ if (query.email === void 0 || query.linkedinUrl !== void 0) {
846
+ return NONE;
847
+ }
848
+ const lead = unwrap(
849
+ await client.get(ctx, "/leads/", { query: { email: query.email } })
850
+ );
851
+ if (!isJsonObject(lead) || text(lead.id) === null || emailAddress(lead.email) !== query.email) {
852
+ return NONE;
853
+ }
854
+ const found = await memberships(client, ctx, lead);
855
+ const wanted = found.filter(
856
+ (membership) => query.campaignId === void 0 || membership.campaignId === query.campaignId
857
+ );
858
+ const categorized = wanted.some(
859
+ (membership) => text(membership.entry.lead_category_id) !== null
860
+ );
861
+ const categories = categorized ? await leadCategories(client, ctx, void 0) : NO_CATEGORIES;
862
+ return {
863
+ items: wanted.map(
864
+ (membership) => toFoundLead(client.identity, lead, { ...membership, categories })
865
+ )
866
+ };
867
+ };
868
+
869
+ // src/smartlead/leads.ts
870
+ var campaignLeads = async (client, ctx, place) => {
871
+ const body = await client.get(
872
+ ctx,
873
+ `/campaigns/${segment(place.campaignId)}/leads`,
874
+ { query: { limit: place.limit, offset: place.offset } }
875
+ );
876
+ const rows = objects(field(body, "data"));
877
+ const total = count(field(body, "total_leads"));
878
+ const end = place.offset + rows.length;
879
+ const more = rows.length > 0 && (total === null ? rows.length === place.limit : end < total);
880
+ return {
881
+ items: rows.map(
882
+ (row) => toCampaignLead(client.identity, place.campaignId, row, place.categories)
883
+ ),
884
+ nextOffset: more ? end : void 0
885
+ };
886
+ };
887
+ var offsetOf = (next) => count(field(next, "offset")) ?? 0;
888
+ var allLeads = async (client, ctx, query) => {
889
+ const campaigns = isJsonObject(query.next) ? idList(query.next.campaigns) : await campaignIds(client, ctx);
890
+ const [current, ...rest] = campaigns;
891
+ if (current === void 0) {
892
+ return { items: [] };
893
+ }
894
+ const categories = await leadCategories(client, ctx, query.next);
895
+ const page = await campaignLeads(client, ctx, {
896
+ campaignId: current,
897
+ categories,
898
+ limit: pageSize(query.limit),
899
+ offset: offsetOf(query.next)
900
+ });
901
+ if (page.nextOffset !== void 0) {
902
+ return {
903
+ items: page.items,
904
+ next: {
905
+ ...categoriesCursor(categories),
906
+ campaigns,
907
+ offset: page.nextOffset
908
+ }
909
+ };
910
+ }
911
+ return {
912
+ items: page.items,
913
+ next: rest.length > 0 ? { ...categoriesCursor(categories), campaigns: rest, offset: 0 } : void 0
914
+ };
915
+ };
916
+ var listLeads = async (client, ctx, query) => {
917
+ if (query.email !== void 0 || query.linkedinUrl !== void 0) {
918
+ return await leadsByEmail(client, ctx, query);
919
+ }
920
+ if (query.campaignId === void 0) {
921
+ return await allLeads(client, ctx, query);
922
+ }
923
+ const categories = await leadCategories(client, ctx, query.next);
924
+ const page = await campaignLeads(client, ctx, {
925
+ campaignId: query.campaignId,
926
+ categories,
927
+ limit: pageSize(query.limit),
928
+ offset: offsetOf(query.next)
929
+ });
930
+ return {
931
+ items: page.items,
932
+ next: page.nextOffset === void 0 ? void 0 : { ...categoriesCursor(categories), offset: page.nextOffset }
933
+ };
934
+ };
935
+ var getLead = async (client, ctx, id) => {
936
+ const lead = objectOf(
937
+ client,
938
+ await client.get(ctx, `/leads/${segment(id)}`),
939
+ "the lead"
940
+ );
941
+ if (text(lead.id) === null) {
942
+ throw new OutboundError("NotFound", `Lead ${id} was not found`, {
943
+ provider: client.identity.provider
944
+ });
945
+ }
946
+ const tags = await client.get(ctx, "/crm/leads/tags", {
947
+ query: { leadId: id }
948
+ });
949
+ const categories = text(lead.category_id) === null ? NO_CATEGORIES : await leadCategories(client, ctx, void 0);
950
+ return toLead(
951
+ client.identity,
952
+ lead,
953
+ objects(unwrap(tags)).flatMap((tag) => text(tag.name) ?? []),
954
+ categories
955
+ );
956
+ };
957
+
958
+ // src/smartlead/mail.ts
959
+ var DAY_MS = 864e5;
960
+ var MAX_CATEGORY_IDS = 10;
961
+ var EPOCH = "1970-01-01T00:00:00.000Z";
962
+ var listActivities = async (client, ctx, query) => {
963
+ const offset = count(query.next) ?? 0;
964
+ const body = await client.get(ctx, "/campaigns/all-leads-activities", {
965
+ lane: ACTIVITIES_LANE,
966
+ query: {
967
+ // Narrows the feed to leads with activity since then. `event_time_to`
968
+ // is not sent: a lead active after the end could drop out of the feed.
969
+ event_time_from: query.since,
970
+ limit: Math.min(
971
+ query.limit ?? ACTIVITIES_PAGE_SIZE,
972
+ ACTIVITIES_MAX_PAGE_SIZE
973
+ ),
974
+ offset
975
+ }
976
+ });
977
+ const rows = objects(field(body, "data"));
978
+ const more = flag(field(body, "hasMore")) === true && rows.length > 0;
979
+ return {
980
+ // The feed has no campaign filter, so one campaign's rows are picked here.
981
+ items: rows.filter(
982
+ (row) => query.campaignId === void 0 || text(row.campaign_id) === query.campaignId
983
+ ).flatMap(
984
+ (row) => toActivityMessages(client.identity, row, query.includeBody)
985
+ ),
986
+ next: more ? offset + rows.length : void 0
987
+ };
988
+ };
989
+ var leadCampaigns = async (client, ctx, query, leadId) => {
990
+ if (isJsonObject(query.next)) {
991
+ return idList(query.next.campaigns);
992
+ }
993
+ if (query.campaignId !== void 0) {
994
+ return [query.campaignId];
995
+ }
996
+ const campaigns = await client.get(
997
+ ctx,
998
+ `/leads/${encodeURIComponent(leadId)}/campaigns`
999
+ );
1000
+ return objects(unwrap(campaigns)).flatMap(
1001
+ (campaign) => text(campaign.id) ?? []
1002
+ );
1003
+ };
1004
+ var listHistory = async (client, ctx, query, leadId) => {
1005
+ const [campaignId, ...rest] = await leadCampaigns(client, ctx, query, leadId);
1006
+ if (campaignId === void 0) {
1007
+ return { items: [] };
1008
+ }
1009
+ const body = await client.get(
1010
+ ctx,
1011
+ `/campaigns/${encodeURIComponent(campaignId)}/leads/${encodeURIComponent(leadId)}/message-history`
1012
+ );
1013
+ const history = field(unwrap(body), "history");
1014
+ if (!isJsonArray(history)) {
1015
+ throw new OutboundError(
1016
+ "Provider",
1017
+ "Smartlead returned a message history without a history list",
1018
+ { provider: client.identity.provider }
1019
+ );
1020
+ }
1021
+ return {
1022
+ items: objects(history).map(
1023
+ (item) => toHistoryMessage(
1024
+ client.identity,
1025
+ { campaignId, leadId },
1026
+ item,
1027
+ query.includeBody
1028
+ )
1029
+ ),
1030
+ next: rest.length > 0 ? { campaigns: rest } : void 0
1031
+ };
1032
+ };
1033
+ var listThread = async (client, ctx, query, threadId) => ({
1034
+ items: toThreadMessages(
1035
+ client.identity,
1036
+ {
1037
+ ...objectOf(
1038
+ client,
1039
+ await client.get(ctx, `/master-inbox/${segment(threadId)}`),
1040
+ "the inbox thread"
1041
+ ),
1042
+ // The path id is the thread id, whatever the body says.
1043
+ campaign_lead_map_id: threadId
1044
+ },
1045
+ query.includeBody
1046
+ )
1047
+ });
1048
+ var listMessages = (client, ctx, query) => {
1049
+ if (query.threadId !== void 0) {
1050
+ return listThread(client, ctx, query, query.threadId);
1051
+ }
1052
+ return query.leadId === void 0 ? listActivities(client, ctx, query) : listHistory(client, ctx, query, query.leadId);
1053
+ };
1054
+ var readCategories = async (client, ctx, next) => isJsonObject(next) ? categoriesFromJson(next.categories) : toCategoryMap(unwrap(await client.get(ctx, "/leads/fetch-categories")));
1055
+ var inboxFilters = (query, wanted) => {
1056
+ const filters2 = {};
1057
+ if (query.campaignId !== void 0) {
1058
+ filters2.campaignId = count(query.campaignId) ?? query.campaignId;
1059
+ }
1060
+ if (wanted.length > 0 && wanted.length <= MAX_CATEGORY_IDS) {
1061
+ filters2.leadCategories = { categoryIdsIn: wanted };
1062
+ }
1063
+ if (query.since !== void 0 || query.until !== void 0) {
1064
+ filters2.replyTimeBetween = [
1065
+ query.since ?? EPOCH,
1066
+ query.until ?? new Date(Date.now() + DAY_MS).toISOString()
1067
+ ];
1068
+ }
1069
+ return filters2;
1070
+ };
1071
+ var listReplies = async (client, ctx, query) => {
1072
+ const categories = await readCategories(client, ctx, query.next);
1073
+ const wanted = query.category === void 0 ? [] : categoryIds(categories, query.category);
1074
+ if (query.category !== void 0 && query.category !== "unknown" && wanted.length === 0) {
1075
+ return { items: [] };
1076
+ }
1077
+ const offset = count(field(query.next, "offset")) ?? 0;
1078
+ const limit = Math.min(query.limit ?? INBOX_PAGE_SIZE, INBOX_PAGE_SIZE);
1079
+ const body = await client.post(
1080
+ ctx,
1081
+ "/master-inbox/inbox-replies",
1082
+ { filters: inboxFilters(query, wanted), limit, offset },
1083
+ // Without it a thread carries only its latest reply.
1084
+ { query: { fetch_message_history: true } }
1085
+ );
1086
+ const threads = objects(field(unwrap(body), "messages"));
1087
+ const total = count(field(unwrap(body), "total_count"));
1088
+ const end = offset + threads.length;
1089
+ const more = threads.length > 0 && (total === null ? threads.length === limit : end < total);
1090
+ const replies = threads.flatMap(
1091
+ (thread) => toInboxReplies(client.identity, thread, categories, query.includeBody)
1092
+ );
1093
+ return {
1094
+ // The id filter only narrows; the category is matched on the mapped value.
1095
+ items: query.category === void 0 ? replies : replies.filter((reply) => reply.category === query.category),
1096
+ next: more ? { categories: categoriesToJson(categories), offset: end } : void 0
1097
+ };
1098
+ };
1099
+
1100
+ // src/smartlead/map-stats.ts
1101
+ var TIMEZONE = "UTC";
1102
+ var campaignCounts = (raw) => ({
1103
+ ...emptyCounts(),
1104
+ bounced: count(raw.bounce_count),
1105
+ clicked: count(raw.unique_click_count),
1106
+ clickedTotal: count(raw.click_count),
1107
+ contacted: count(raw.unique_sent_count),
1108
+ opened: count(raw.unique_open_count),
1109
+ openedTotal: count(raw.open_count),
1110
+ replied: count(raw.reply_count),
1111
+ sent: count(raw.sent_count),
1112
+ unsubscribed: count(raw.unsubscribed_count)
1113
+ });
1114
+ var lifetimeRow = (scope, raw) => metricRow(scope, {
1115
+ ...campaignCounts(raw),
1116
+ positive: count(field(raw.campaign_lead_stats, "interested"))
1117
+ });
1118
+ var outOfOffice = (raw) => {
1119
+ const total = count(raw.total_reply_count);
1120
+ const people = count(raw.non_ooo_reply_count);
1121
+ return total === null || people === null || total < people ? null : total - people;
1122
+ };
1123
+ var windowRow = (scope, raw) => metricRow(
1124
+ scope,
1125
+ {
1126
+ ...campaignCounts(raw),
1127
+ replied: count(raw.non_ooo_reply_count) ?? count(raw.reply_count),
1128
+ repliedAuto: outOfOffice(raw)
1129
+ },
1130
+ { timezone: TIMEZONE }
1131
+ );
1132
+ var overallRow = (scope, raw) => metricRow(
1133
+ scope,
1134
+ {
1135
+ ...emptyCounts(),
1136
+ bounced: count(raw.bounced),
1137
+ contacted: count(raw.unique_lead_count),
1138
+ opened: count(raw.unique_open_count),
1139
+ openedTotal: count(raw.opened),
1140
+ positive: count(raw.positive_replied),
1141
+ replied: count(raw.replied),
1142
+ sent: count(raw.sent)
1143
+ },
1144
+ { timezone: TIMEZONE }
1145
+ );
1146
+ var dayRow = (scope, raw, positive) => metricRow(
1147
+ scope,
1148
+ {
1149
+ ...emptyCounts(),
1150
+ openedTotal: count(raw.opened),
1151
+ positive: count(positive),
1152
+ replied: count(raw.replied),
1153
+ sent: count(raw.sent)
1154
+ },
1155
+ { date: text(raw.date), timezone: TIMEZONE }
1156
+ );
1157
+ var mailboxRow = (scope, raw) => metricRow(
1158
+ scope,
1159
+ {
1160
+ ...emptyCounts(),
1161
+ bounced: count(raw?.bounced),
1162
+ openedTotal: count(raw?.opened),
1163
+ replied: count(raw?.replied),
1164
+ sent: count(raw?.sent)
1165
+ },
1166
+ { timezone: TIMEZONE }
1167
+ );
1168
+ var stepCounts = (stats) => ({
1169
+ ...emptyCounts(),
1170
+ bounced: count(field(stats, "bounce_count")),
1171
+ // The step report has one click count and one open count and does not call
1172
+ // either unique, so both are read as totals.
1173
+ clickedTotal: count(field(stats, "click_count")),
1174
+ openedTotal: count(field(stats, "open_count")),
1175
+ positive: count(field(stats, "positive_reply_count")),
1176
+ replied: count(field(stats, "reply_count")),
1177
+ sent: count(field(stats, "sent_count")),
1178
+ unsubscribed: count(field(stats, "unsubscribed_count"))
1179
+ });
1180
+ var stepRows = (scope, step) => {
1181
+ const stepIndex = fromOne(step.seq_number);
1182
+ const variants = objects(step.variants);
1183
+ if (variants.length === 0) {
1184
+ return [
1185
+ metricRow(scope, stepCounts(step.total_stats), {
1186
+ stepIndex,
1187
+ timezone: TIMEZONE
1188
+ })
1189
+ ];
1190
+ }
1191
+ return variants.map(
1192
+ (variant) => metricRow(scope, stepCounts(variant.stats), {
1193
+ stepIndex,
1194
+ timezone: TIMEZONE,
1195
+ variantKey: text(variant.variant_label)
1196
+ })
1197
+ );
1198
+ };
1199
+
1200
+ // src/smartlead/stats.ts
1201
+ var DAY_MS2 = 864e5;
1202
+ var LIFETIME_START = "2000-01-01";
1203
+ var MAX_WINDOW_DAYS = 30;
1204
+ var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1205
+ var timeOf = (day) => Date.parse(`${day}T00:00:00.000Z`);
1206
+ var resolveRange = (query, recent) => {
1207
+ const to = query.to ?? dayOf(Date.now());
1208
+ const fallback = recent ? dayOf(timeOf(to) - MAX_WINDOW_DAYS * DAY_MS2) : LIFETIME_START;
1209
+ return { from: query.from ?? fallback, to };
1210
+ };
1211
+ var invalid = (client, message) => new OutboundError("Invalid", message, {
1212
+ provider: client.identity.provider
1213
+ });
1214
+ var unsupported = (client, message) => new OutboundError("Unsupported", message, {
1215
+ provider: client.identity.provider
1216
+ });
1217
+ var campaignPath = (scope, leaf) => `/campaigns/${encodeURIComponent(scope.scopeId)}/${leaf}`;
1218
+ var campaignTotal = async (client, ctx, scope, query) => {
1219
+ if (query.from === void 0 && query.to === void 0) {
1220
+ const lifetime = await client.get(ctx, campaignPath(scope, "analytics"));
1221
+ return [
1222
+ lifetimeRow(scope, objectOf(client, lifetime, "campaign analytics"))
1223
+ ];
1224
+ }
1225
+ const range = resolveRange(query, true);
1226
+ if (timeOf(range.to) - timeOf(range.from) > MAX_WINDOW_DAYS * DAY_MS2) {
1227
+ throw invalid(
1228
+ client,
1229
+ `Smartlead reports a campaign's dated totals for at most ${MAX_WINDOW_DAYS} days; ${range.from} to ${range.to} is longer`
1230
+ );
1231
+ }
1232
+ const window = await client.get(
1233
+ ctx,
1234
+ campaignPath(scope, "analytics-by-date"),
1235
+ {
1236
+ query: {
1237
+ end_date: range.to,
1238
+ start_date: range.from,
1239
+ time_zone: TIMEZONE
1240
+ }
1241
+ }
1242
+ );
1243
+ return [windowRow(scope, objectOf(client, window, "campaign analytics"))];
1244
+ };
1245
+ var dailyRows = async (client, ctx, scope, query) => {
1246
+ const range = resolveRange(query, true);
1247
+ const request = {
1248
+ query: {
1249
+ campaign_ids: scope.scope === "campaign" ? scope.scopeId : void 0,
1250
+ end_date: range.to,
1251
+ start_date: range.from,
1252
+ timezone: TIMEZONE
1253
+ }
1254
+ };
1255
+ const [body, positive] = await Promise.all([
1256
+ client.get(ctx, "/analytics/day-wise-overall-stats", request),
1257
+ client.get(ctx, "/analytics/day-wise-positive-reply-stats", request)
1258
+ ]);
1259
+ const positiveByDay = new Map(
1260
+ objects(field(unwrap(positive), "day_wise_stats")).map((day) => [
1261
+ text(day.date),
1262
+ day.positive_replied
1263
+ ])
1264
+ );
1265
+ return objects(field(unwrap(body), "day_wise_stats")).map(
1266
+ (day) => dayRow(scope, day, positiveByDay.get(text(day.date)))
1267
+ );
1268
+ };
1269
+ var workspaceTotal = async (client, ctx, scope, query) => {
1270
+ const range = resolveRange(query, false);
1271
+ const body = await client.get(ctx, "/analytics/overall-stats-v2", {
1272
+ query: { end_date: range.to, start_date: range.from, timezone: TIMEZONE }
1273
+ });
1274
+ const stats = field(objectOf(client, body, "overall stats"), "overall_stats");
1275
+ return [overallRow(scope, isJsonObject(stats) ? stats : {})];
1276
+ };
1277
+ var everyCampaign = async (client, ctx, query) => {
1278
+ const range = resolveRange(query, false);
1279
+ const body = await client.get(ctx, "/analytics/campaign/overall-stats", {
1280
+ query: {
1281
+ end_date: range.to,
1282
+ full_data: true,
1283
+ start_date: range.from,
1284
+ timezone: TIMEZONE
1285
+ }
1286
+ });
1287
+ const campaigns = field(
1288
+ objectOf(client, body, "campaign performance"),
1289
+ "campaign_wise_performance"
1290
+ );
1291
+ return objects(campaigns).flatMap((campaign) => {
1292
+ const scopeId = text(campaign.id);
1293
+ return scopeId === null ? [] : [
1294
+ overallRow(
1295
+ { ...client.identity, scope: "campaign", scopeId },
1296
+ campaign
1297
+ )
1298
+ ];
1299
+ });
1300
+ };
1301
+ var stepTotals = async (client, ctx, scope, query) => {
1302
+ const range = resolveRange(query, false);
1303
+ const body = await client.get(
1304
+ ctx,
1305
+ campaignPath(scope, "sequence-analytics"),
1306
+ {
1307
+ query: {
1308
+ end_date: `${range.to}T23:59:59.999Z`,
1309
+ start_date: `${range.from}T00:00:00.000Z`,
1310
+ time_zone: TIMEZONE
1311
+ }
1312
+ }
1313
+ );
1314
+ return objects(field(unwrap(body), "sequences")).flatMap(
1315
+ (step) => stepRows(scope, step)
1316
+ );
1317
+ };
1318
+ var senderTotal = async (client, ctx, scope, query) => {
1319
+ const account = objectOf(
1320
+ client,
1321
+ await client.get(
1322
+ ctx,
1323
+ `/email-accounts/${encodeURIComponent(scope.scopeId)}/`
1324
+ ),
1325
+ "the email account"
1326
+ );
1327
+ const address = emailAddress(account.from_email);
1328
+ const range = resolveRange(query, false);
1329
+ const body = await client.get(
1330
+ ctx,
1331
+ "/analytics/mailbox/name-wise-health-metrics",
1332
+ {
1333
+ query: { end_date: range.to, start_date: range.from, timezone: TIMEZONE }
1334
+ }
1335
+ );
1336
+ return [
1337
+ mailboxRow(
1338
+ scope,
1339
+ objects(field(unwrap(body), "email_health_metrics")).find(
1340
+ (metrics) => address !== null && emailAddress(metrics.email_account) === address
1341
+ )
1342
+ )
1343
+ ];
1344
+ };
1345
+ var readStats = async (client, ctx, query) => {
1346
+ const scope = {
1347
+ ...client.identity,
1348
+ scope: query.scope,
1349
+ scopeId: query.scopeId ?? client.identity.workspaceId
1350
+ };
1351
+ if (query.scope === "campaign" && query.scopeId === void 0) {
1352
+ if (query.by === "day") {
1353
+ throw unsupported(
1354
+ client,
1355
+ "Smartlead reports every campaign in one call as totals only; read one campaign for its days"
1356
+ );
1357
+ }
1358
+ return await everyCampaign(client, ctx, query);
1359
+ }
1360
+ if (query.scope === "sender" || query.scope === "step") {
1361
+ if (query.by === "day") {
1362
+ throw unsupported(
1363
+ client,
1364
+ "Smartlead reports step and mailbox analytics as totals only"
1365
+ );
1366
+ }
1367
+ return query.scope === "step" ? await stepTotals(client, ctx, scope, query) : await senderTotal(client, ctx, scope, query);
1368
+ }
1369
+ if (query.by === "day") {
1370
+ return await dailyRows(client, ctx, scope, query);
1371
+ }
1372
+ return query.scope === "campaign" ? await campaignTotal(client, ctx, scope, query) : await workspaceTotal(client, ctx, scope, query);
1373
+ };
1374
+
1375
+ // src/smartlead/adapter.ts
1376
+ var listSenders = async (client, ctx, query) => {
1377
+ if (query.campaignId !== void 0) {
1378
+ const attached = await client.get(
1379
+ ctx,
1380
+ `/campaigns/${segment(query.campaignId)}/email-accounts`
1381
+ );
1382
+ return {
1383
+ items: objects(unwrap(attached)).map(
1384
+ (account) => toSender(client.identity, account)
1385
+ )
1386
+ };
1387
+ }
1388
+ const page = await offsetPage(client, ctx, "/email-accounts/", {
1389
+ limit: pageSize(query.limit),
1390
+ offset: count(query.next) ?? 0
1391
+ });
1392
+ return mapPage(page, (account) => toSender(client.identity, account));
1393
+ };
1394
+ var readers = (client) => {
1395
+ const { identity } = client;
1396
+ return {
1397
+ ...accountReaders(client),
1398
+ getCampaign: async (id, ctx) => toCampaign(
1399
+ identity,
1400
+ objectOf(
1401
+ client,
1402
+ await client.get(ctx, `/campaigns/${segment(id)}`, {
1403
+ query: { include_tags: true }
1404
+ }),
1405
+ "the campaign"
1406
+ )
1407
+ ),
1408
+ getLead: (id, ctx) => getLead(client, ctx, id),
1409
+ getSender: async (id, ctx) => toSender(
1410
+ identity,
1411
+ objectOf(
1412
+ client,
1413
+ // The documented path ends with a slash.
1414
+ await client.get(ctx, `/email-accounts/${segment(id)}/`),
1415
+ "the email account"
1416
+ )
1417
+ ),
1418
+ getSequence: async (id, ctx) => toSequence(
1419
+ identity,
1420
+ id,
1421
+ await client.get(ctx, `/campaigns/${segment(id)}/sequences`)
1422
+ ),
1423
+ listCampaigns: async (query, ctx) => {
1424
+ const { senderId } = query;
1425
+ const attached = senderId === void 0 ? void 0 : idList(
1426
+ objectOf(
1427
+ client,
1428
+ await client.get(ctx, `/email-accounts/${segment(senderId)}/`, {
1429
+ query: { fetch_campaigns: true }
1430
+ }),
1431
+ "the email account"
1432
+ ).campaign_ids
1433
+ );
1434
+ const campaigns = await campaignList(client, ctx);
1435
+ return {
1436
+ items: campaigns.filter(
1437
+ (campaign) => attached === void 0 || attached.includes(text(campaign.id) ?? "")
1438
+ ).map((campaign) => toCampaign(identity, campaign))
1439
+ };
1440
+ },
1441
+ listLeads: (query, ctx) => listLeads(client, ctx, query),
1442
+ listMessages: (query, ctx) => listMessages(client, ctx, query),
1443
+ listReplies: (query, ctx) => listReplies(client, ctx, query),
1444
+ listSenders: (query, ctx) => listSenders(client, ctx, query),
1445
+ listWorkspaces: async (_query, ctx) => ({
1446
+ items: objects(unwrap(await client.get(ctx, "/client/"))).map(
1447
+ (raw) => toWorkspace(identity, raw)
1448
+ )
1449
+ }),
1450
+ stats: (query, ctx) => readStats(client, ctx, query)
1451
+ };
1452
+ };
1453
+
1454
+ // src/smartlead/native-params.ts
1455
+ var DOCS = "https://api.smartlead.ai/api-reference";
1456
+ var DELIVERY_URL = "https://smartdelivery.smartlead.ai/api/v1";
1457
+ var PROSPECT_URL = "https://prospect-api.smartlead.ai/api/v1";
1458
+ var SENDERS_URL = "https://smart-senders.smartlead.ai/api/v1";
1459
+ var SERVERS_URL = "https://smartservers.smartlead.ai/api/v1";
1460
+ var paged = (limit) => ({
1461
+ limit: inQuery("number", limit),
1462
+ offset: inQuery("number", "Rows to skip.")
1463
+ });
1464
+
1465
+ // src/smartlead/native-analytics.ts
1466
+ var CLIENTS = {
1467
+ client_ids: inQuery("string", "Only these clients: ids separated by commas.")
1468
+ };
1469
+ var SCOPE = {
1470
+ ...CLIENTS,
1471
+ campaign_ids: inQuery(
1472
+ "string",
1473
+ "Only these campaigns: ids separated by commas."
1474
+ )
1475
+ };
1476
+ var WINDOW = {
1477
+ end_date: inQueryRequired("string", "Last day, YYYY-MM-DD."),
1478
+ start_date: inQueryRequired("string", "First day, YYYY-MM-DD."),
1479
+ timezone: inQuery("string", "IANA time zone, for example America/New_York.")
1480
+ };
1481
+ var ZONED_WINDOW = {
1482
+ ...WINDOW,
1483
+ timezone: inQueryRequired(
1484
+ "string",
1485
+ "IANA time zone, for example America/New_York."
1486
+ )
1487
+ };
1488
+ var FULL = {
1489
+ full_data: inQuery("string", 'Set to "true" for the full data set.')
1490
+ };
1491
+ var PAGE = {
1492
+ limit: inQuery("string", "Most rows to return."),
1493
+ offset: inQuery("string", "Rows to skip.")
1494
+ };
1495
+ var ANALYTICS = defineNative({
1496
+ analyticsCampaignFollowUpReplyRate: {
1497
+ description: "The reply rate of follow-up steps (second email onwards).",
1498
+ docs: `${DOCS}/analytics/followup-reply-rate`,
1499
+ method: "GET",
1500
+ params: { ...WINDOW, ...SCOPE },
1501
+ path: "/analytics/campaign/follow-up-reply-rate"
1502
+ },
1503
+ analyticsCampaignLeadToReplyTime: {
1504
+ description: "The average time from a lead's first email to its reply.",
1505
+ docs: `${DOCS}/analytics/lead-to-reply-time`,
1506
+ method: "GET",
1507
+ params: { ...WINDOW, ...SCOPE },
1508
+ path: "/analytics/campaign/lead-to-reply-time"
1509
+ },
1510
+ analyticsCampaignLeadsForFirstReply: {
1511
+ description: "How many leads are contacted, on average, per first reply.",
1512
+ docs: `${DOCS}/analytics/leads-for-first-reply`,
1513
+ method: "GET",
1514
+ params: { ...WINDOW, ...SCOPE },
1515
+ path: "/analytics/campaign/leads-take-for-first-reply"
1516
+ },
1517
+ analyticsCampaignList: {
1518
+ description: "The id and name of every campaign, for analytics filters.",
1519
+ docs: `${DOCS}/analytics/campaign-list`,
1520
+ method: "GET",
1521
+ params: CLIENTS,
1522
+ path: "/analytics/campaign/list"
1523
+ },
1524
+ analyticsCampaignPerformance: {
1525
+ description: "One row per campaign in a date window: counts, rates and lead totals.",
1526
+ docs: `${DOCS}/analytics/campaign-performance`,
1527
+ method: "GET",
1528
+ params: { ...WINDOW, ...SCOPE, ...PAGE, ...FULL },
1529
+ path: "/analytics/campaign/overall-stats"
1530
+ },
1531
+ analyticsCampaignResponseStats: {
1532
+ description: "Replies per campaign in a date window, split by reply sentiment.",
1533
+ docs: `${DOCS}/analytics/campaign-response-stats`,
1534
+ method: "GET",
1535
+ params: { ...WINDOW, ...SCOPE, ...FULL },
1536
+ path: "/analytics/campaign/response-stats"
1537
+ },
1538
+ analyticsCampaignStatusStats: {
1539
+ description: "How many campaigns are in each status.",
1540
+ docs: `${DOCS}/analytics/campaign-status-stats`,
1541
+ method: "GET",
1542
+ params: CLIENTS,
1543
+ path: "/analytics/campaign/status-stats"
1544
+ },
1545
+ analyticsClientList: {
1546
+ description: "The id and name of every client, for analytics filters.",
1547
+ docs: `${DOCS}/analytics/client-list`,
1548
+ method: "GET",
1549
+ params: CLIENTS,
1550
+ path: "/analytics/client/list"
1551
+ },
1552
+ analyticsClientMonthlyCount: {
1553
+ description: "How many clients the account had, month by month.",
1554
+ docs: `${DOCS}/analytics/month-wise-client-count`,
1555
+ method: "GET",
1556
+ params: CLIENTS,
1557
+ path: "/analytics/client/month-wise-count"
1558
+ },
1559
+ analyticsClientPerformance: {
1560
+ description: "One row per client in a date window, with that client's campaign totals.",
1561
+ docs: `${DOCS}/analytics/client-performance`,
1562
+ method: "GET",
1563
+ params: {
1564
+ ...WINDOW,
1565
+ ...CLIENTS,
1566
+ ...PAGE,
1567
+ ...FULL,
1568
+ filter: inQuery("string", "Filter value for the client rows.")
1569
+ },
1570
+ path: "/analytics/client/overall-stats"
1571
+ },
1572
+ analyticsDailyBySentTime: {
1573
+ description: "Daily sent, opened, replied and bounced counts, each counted on the day its email was sent. The only daily read that reports bounces.",
1574
+ docs: `${DOCS}/analytics/day-wise-sent-time`,
1575
+ method: "GET",
1576
+ params: { ...ZONED_WINDOW, ...SCOPE },
1577
+ path: "/analytics/day-wise-overall-stats-by-sent-time"
1578
+ },
1579
+ analyticsDailyPositiveReplies: {
1580
+ description: "Positive replies per day, counted on the day of the reply.",
1581
+ docs: `${DOCS}/analytics/day-wise-positive-reply`,
1582
+ method: "GET",
1583
+ params: { ...WINDOW, ...SCOPE },
1584
+ path: "/analytics/day-wise-positive-reply-stats"
1585
+ },
1586
+ analyticsDailyPositiveRepliesBySentTime: {
1587
+ description: "Positive replies per day, counted on the day the replied-to email was sent.",
1588
+ docs: `${DOCS}/analytics/day-wise-positive-sent-time`,
1589
+ method: "GET",
1590
+ params: { ...ZONED_WINDOW, ...SCOPE },
1591
+ path: "/analytics/day-wise-positive-reply-stats-by-sent-time"
1592
+ },
1593
+ analyticsLeadCategoryResponses: {
1594
+ description: "Replies in a date window by lead category, with each one's share.",
1595
+ docs: `${DOCS}/analytics/lead-category-response`,
1596
+ method: "GET",
1597
+ params: { ...WINDOW, ...SCOPE },
1598
+ path: "/analytics/lead/category-wise-response"
1599
+ },
1600
+ analyticsLeadStats: {
1601
+ description: "Leads reached in a date window: the total, new leads and follow-ups.",
1602
+ docs: `${DOCS}/analytics/lead-stats`,
1603
+ method: "GET",
1604
+ params: { ...WINDOW, ...SCOPE },
1605
+ path: "/analytics/lead/overall-stats"
1606
+ },
1607
+ analyticsMailboxDomainHealth: {
1608
+ description: "Sent, opened, replied and bounced counts per sending domain in a date window.",
1609
+ docs: `${DOCS}/analytics/domain-wise-health`,
1610
+ lane: DOMAIN_HEALTH_LANE,
1611
+ method: "GET",
1612
+ params: { ...WINDOW, ...SCOPE, ...PAGE, ...FULL },
1613
+ path: "/analytics/mailbox/domain-wise-health-metrics"
1614
+ },
1615
+ analyticsMailboxOverall: {
1616
+ description: "How many mailboxes are connected, in use, disconnected, or enabled without warmup.",
1617
+ docs: `${DOCS}/analytics/mailbox-health`,
1618
+ method: "GET",
1619
+ params: CLIENTS,
1620
+ path: "/analytics/mailbox/overall-stats"
1621
+ },
1622
+ analyticsMailboxProviderPerformance: {
1623
+ description: "Counts and rates in a date window per mailbox provider (Gmail, Outlook, SMTP).",
1624
+ docs: `${DOCS}/analytics/provider-performance`,
1625
+ method: "GET",
1626
+ params: { ...WINDOW, ...SCOPE, ...FULL },
1627
+ path: "/analytics/mailbox/provider-wise-overall-performance"
1628
+ },
1629
+ analyticsTeamBoard: {
1630
+ description: "Results in a date window per team member.",
1631
+ docs: `${DOCS}/analytics/team-board-stats`,
1632
+ method: "GET",
1633
+ params: { ...WINDOW, ...SCOPE, ...FULL },
1634
+ path: "/analytics/team-board/overall-stats"
1635
+ }
1636
+ });
1637
+
1638
+ // src/smartlead/native-campaigns.ts
1639
+ var CAMPAIGN = { campaign_id: inPath("The campaign's id.") };
1640
+ var CAMPAIGN_READS = defineNative({
1641
+ campaignEmailStatistics: {
1642
+ description: "One row per email a campaign sent: the lead, the step, and when it was sent, opened, clicked, replied to or bounced.",
1643
+ docs: `${DOCS}/campaign-statistics/get-by-id`,
1644
+ method: "GET",
1645
+ params: {
1646
+ ...CAMPAIGN,
1647
+ ...paged("Rows per page, at most 1000."),
1648
+ email_sequence_number: inQuery("number", "Only this step, 1 to 20."),
1649
+ email_status: inQuery(
1650
+ "string",
1651
+ "opened, clicked, replied, unsubscribed or bounced."
1652
+ ),
1653
+ sent_time_end_date: inQuery(
1654
+ "string",
1655
+ "Sent before this time, as 2023-10-16 10:33:02.000Z."
1656
+ ),
1657
+ sent_time_start_date: inQuery(
1658
+ "string",
1659
+ "Sent after this time, as 2023-10-16 10:33:02.000Z."
1660
+ )
1661
+ },
1662
+ path: "/campaigns/{campaign_id}/statistics"
1663
+ },
1664
+ campaignLeadSearch: {
1665
+ description: "A campaign's leads filtered by text, status, category, mailbox or step. Refuses client-level keys.",
1666
+ docs: `${DOCS}/campaigns/search-leads`,
1667
+ method: "POST",
1668
+ params: {
1669
+ campaignId: inPath("The campaign's id."),
1670
+ deletedEmailAddresses: inBody("json", "Email addresses, as an array."),
1671
+ emailAccountIds: inBody("json", "Mailbox ids the leads are assigned to."),
1672
+ emailStatuses: inBody(
1673
+ "json",
1674
+ "Array of is_opened, is_clicked, is_bounced, is_replied, is_unsubscribed, is_accepted, not_replied and the like."
1675
+ ),
1676
+ espDomainTypes: inBody("json", "ESP domain types, integers 0 to 2."),
1677
+ fieldSet: inBody(
1678
+ "string",
1679
+ "drafted_table (compact) or active_table (full)."
1680
+ ),
1681
+ filterLeadsForManualCompletion: inBody(
1682
+ "boolean",
1683
+ "Only leads waiting on a manual step."
1684
+ ),
1685
+ filterManualSeqIds: inBody(
1686
+ "json",
1687
+ "Manual step ids, with filterLeadsForManualCompletion."
1688
+ ),
1689
+ includeSenderBounce: inBody("boolean", "Include sender-bounced leads."),
1690
+ lastSeenLeadId: inBody(
1691
+ "number",
1692
+ "Cursor: lastSeenEclmId from the previous page."
1693
+ ),
1694
+ lastSeenReplyTime: inBody(
1695
+ "string",
1696
+ "Second half of the cursor for active_table with statusFilter replied."
1697
+ ),
1698
+ leadCategoryIds: inBody(
1699
+ "json",
1700
+ "Lead category ids; -1 also matches leads with none."
1701
+ ),
1702
+ leadCategoryIsNull: inBody("boolean", "Only leads with no category."),
1703
+ leadStatuses: inBody(
1704
+ "json",
1705
+ "Array of STARTED, INPROGRESS, COMPLETED, STOPPED, PAUSED, BLOCKED."
1706
+ ),
1707
+ limit: inBody("number", "Leads per page, 1 to 100."),
1708
+ searchText: inBody(
1709
+ "string",
1710
+ "Every word must match the email, first name or last name."
1711
+ ),
1712
+ segTypes: inBody("json", "Segment types, integers 0 to 10."),
1713
+ seqScheduleType: inBody("string", "MANUAL or AUTO."),
1714
+ seqVariantIds: inBody("json", "Step variant ids."),
1715
+ sequenceIds: inBody("json", "Step ids."),
1716
+ sequenceNumbers: inBody("json", "Step numbers, 1 to 999."),
1717
+ statusFilter: inBody(
1718
+ "string",
1719
+ "A status tab: all, active, replied, failed, scheduled and the like."
1720
+ )
1721
+ },
1722
+ path: "/campaigns/{campaignId}/leads/filter"
1723
+ },
1724
+ campaignLeadStatistics: {
1725
+ description: "Per-lead statistics of a campaign. The response is documented nowhere.",
1726
+ docs: `${DOCS}/campaign-statistics/lead-statistics`,
1727
+ lane: LEAD_STATISTICS_LANE,
1728
+ method: "GET",
1729
+ params: {
1730
+ ...CAMPAIGN,
1731
+ ...paged("Leads per page, at most 100."),
1732
+ event_time_gt: inQuery(
1733
+ "string",
1734
+ "Only leads whose last event is after this day, YYYY-MM-DD."
1735
+ )
1736
+ },
1737
+ path: "/campaigns/{campaign_id}/leads-statistics"
1738
+ },
1739
+ campaignLeadsExport: {
1740
+ description: "Every lead of a campaign as CSV text, with open, click and reply counts per lead.",
1741
+ docs: `${DOCS}/leads/export`,
1742
+ method: "GET",
1743
+ params: CAMPAIGN,
1744
+ path: "/campaigns/{campaign_id}/leads-export"
1745
+ },
1746
+ campaignMailboxStatistics: {
1747
+ description: "A campaign's results per mailbox. The response is documented nowhere.",
1748
+ docs: `${DOCS}/campaign-statistics/mailbox-statistics`,
1749
+ method: "GET",
1750
+ params: {
1751
+ ...CAMPAIGN,
1752
+ ...paged("Rows per page, 1 to 20."),
1753
+ client_id: inQuery("number", "The client, for a client's campaign."),
1754
+ end_date: inQuery("string", "Last day, YYYY-MM-DD; needs start_date."),
1755
+ start_date: inQuery("string", "First day, YYYY-MM-DD; needs end_date."),
1756
+ time_zone: inQuery("string", "The campaign's IANA time zone.")
1757
+ },
1758
+ path: "/campaigns/{campaign_id}/mailbox-statistics"
1759
+ },
1760
+ campaignMessageHistoryBulk: {
1761
+ description: "The message history of many of a campaign's leads at once.",
1762
+ docs: `${DOCS}/campaigns/get-leads-history-bulk`,
1763
+ method: "POST",
1764
+ params: {
1765
+ ...CAMPAIGN,
1766
+ event_time_gt: inQuery("string", "Only messages after this time."),
1767
+ lead_ids: inBody("json", "Lead ids, as an array; null for every lead.")
1768
+ },
1769
+ path: "/campaigns/{campaign_id}/message-history-for-leads/bbfbdsFGHlBr76ruhjvh6fhHL"
1770
+ },
1771
+ campaignPromptTemplate: {
1772
+ description: "The AI prompt that categorises a campaign's replies, and the categories it may assign.",
1773
+ docs: `${DOCS}/campaigns/get-prompt-template`,
1774
+ method: "GET",
1775
+ params: CAMPAIGN,
1776
+ path: "/campaigns/{campaign_id}/prompt-template"
1777
+ },
1778
+ campaignTopLevelAnalyticsByDate: {
1779
+ description: "A campaign's top-level totals and rates in a date window, as the vendor computes them.",
1780
+ docs: `${DOCS}/campaign-statistics/top-level-by-date`,
1781
+ method: "GET",
1782
+ params: {
1783
+ ...CAMPAIGN,
1784
+ end_date: inQueryRequired("string", "Last day, YYYY-MM-DD."),
1785
+ start_date: inQueryRequired("string", "First day, YYYY-MM-DD.")
1786
+ },
1787
+ path: "/campaigns/{campaign_id}/top-level-analytics-by-date"
1788
+ },
1789
+ campaignWebhookSummary: {
1790
+ description: "How many webhook calls a campaign made in a time window, and how many failed.",
1791
+ docs: `${DOCS}/campaigns/get-webhook-summary`,
1792
+ method: "GET",
1793
+ params: {
1794
+ campaignId: inPath("The campaign's id."),
1795
+ fromTime: inQueryRequired("string", "Start, as an ISO 8601 time."),
1796
+ toTime: inQueryRequired("string", "End, as an ISO 8601 time.")
1797
+ },
1798
+ path: "/campaigns/{campaignId}/webhooks/summary"
1799
+ },
1800
+ client: {
1801
+ description: "One client, with its permissions, credits and code snippets on request. Refuses client-level keys.",
1802
+ docs: `${DOCS}/clients/get-by-id`,
1803
+ method: "GET",
1804
+ params: {
1805
+ id: inPath("The client's id."),
1806
+ includeCodeIntegrations: inQuery("boolean", "Add the code snippets."),
1807
+ includeCredits: inQuery("boolean", "Add lead and email credits."),
1808
+ includePermissions: inQuery("boolean", "Add the client's permissions.")
1809
+ },
1810
+ path: "/client/{id}"
1811
+ },
1812
+ leadByEmail: {
1813
+ description: "The lead with an email address and every campaign it is in. An unknown address returns an empty object.",
1814
+ docs: `${DOCS}/leads/get-by-email`,
1815
+ method: "GET",
1816
+ params: { email: inQueryRequired("string", "The lead's email address.") },
1817
+ path: "/leads/"
1818
+ },
1819
+ leadCampaignOverview: {
1820
+ description: "A lead's status, category, revenue and current step in each of its campaigns. Refuses client-level keys.",
1821
+ docs: `${DOCS}/leads/campaign-overview`,
1822
+ method: "GET",
1823
+ params: { leadId: inPath("The lead's id.") },
1824
+ path: "/leads/{leadId}/campaign-overview"
1825
+ },
1826
+ leadList: {
1827
+ description: "One lead list: its name, lead count and dates.",
1828
+ docs: `${DOCS}/lead-lists/get-by-id`,
1829
+ method: "GET",
1830
+ params: { id: inPath("The lead list's id.") },
1831
+ path: "/lead-list/{id}"
1832
+ },
1833
+ leadNotes: {
1834
+ description: "The notes written on a lead.",
1835
+ docs: `${DOCS}/lead-notes/get-all`,
1836
+ method: "GET",
1837
+ params: { id: inPath("The lead's id.") },
1838
+ path: "/crm/leads/notes/{id}"
1839
+ },
1840
+ leadSequenceDetails: {
1841
+ description: "The send status of every step for a lead in a campaign. Refuses client-level keys.",
1842
+ docs: `${DOCS}/leads/sequence-details`,
1843
+ method: "GET",
1844
+ params: {
1845
+ campaignId: inQuery("number", "Only this campaign."),
1846
+ leadMapId: inPath("The lead-in-campaign mapping id.")
1847
+ },
1848
+ path: "/leads/{leadMapId}/sequence-details"
1849
+ },
1850
+ leadTasks: {
1851
+ description: "The tasks created for a lead.",
1852
+ docs: `${DOCS}/lead-tasks/get-all`,
1853
+ method: "GET",
1854
+ params: { id: inPath("The lead's id.") },
1855
+ path: "/crm/leads/tasks/{id}"
1856
+ },
1857
+ senderTagsByEmail: {
1858
+ description: "The tags of the mailboxes with the given addresses.",
1859
+ docs: `${DOCS}/email-account-tags/get-all`,
1860
+ method: "POST",
1861
+ params: {
1862
+ email_ids: inBodyRequired("json", "Mailbox addresses, as an array.")
1863
+ },
1864
+ path: "/email-accounts/tag-list"
1865
+ },
1866
+ webhook: {
1867
+ description: "One webhook: its URL, events, categories and campaign.",
1868
+ docs: `${DOCS}/webhooks/get`,
1869
+ method: "GET",
1870
+ params: { webhook_id: inPath("The webhook's id.") },
1871
+ path: "/webhook/{webhook_id}"
1872
+ }
1873
+ });
1874
+
1875
+ // src/smartlead/native-inbox.ts
1876
+ var PAGE2 = {
1877
+ limit: inBody("number", "Threads per page, 1 to 20."),
1878
+ offset: inBody("number", "Threads to skip.")
1879
+ };
1880
+ var HISTORY = {
1881
+ fetch_message_history: inQuery("boolean", "Add each thread's messages.")
1882
+ };
1883
+ var FILTERS = "search, leadCategories, emailStatus, campaignId, emailAccountId, campaignTeamMemberId, campaignTagId, campaignClientId and replyTimeBetween";
1884
+ var filters = (note) => ({
1885
+ filters: inBody("json", `An object of ${FILTERS}. ${note}`)
1886
+ });
1887
+ var MANY = filters("Ids may be arrays: 5 campaigns, 10 of the others.");
1888
+ var SINGLE = filters("Each id is a single value.");
1889
+ var SORT = {
1890
+ sortBy: inBody("string", "REPLY_TIME_DESC or SENT_TIME_DESC.")
1891
+ };
1892
+ var INBOX = defineNative({
1893
+ inboxArchived: {
1894
+ description: "Archived threads of the master inbox.",
1895
+ docs: `${DOCS}/inbox/get-archived`,
1896
+ method: "POST",
1897
+ params: { ...PAGE2, ...HISTORY, ...MANY, ...SORT },
1898
+ path: "/master-inbox/archived"
1899
+ },
1900
+ inboxAssignedToMe: {
1901
+ description: "Threads assigned to the key's own user.",
1902
+ docs: `${DOCS}/inbox/get-assigned`,
1903
+ method: "POST",
1904
+ params: { ...PAGE2, ...HISTORY, ...SINGLE, ...SORT },
1905
+ path: "/master-inbox/assigned-me"
1906
+ },
1907
+ inboxImportant: {
1908
+ description: "Threads marked as important.",
1909
+ docs: `${DOCS}/inbox/get-important`,
1910
+ method: "POST",
1911
+ params: { ...PAGE2, ...HISTORY, ...MANY, ...SORT },
1912
+ path: "/master-inbox/important"
1913
+ },
1914
+ inboxReminders: {
1915
+ description: "Threads with a reminder, with its time and message.",
1916
+ docs: `${DOCS}/inbox/get-reminders`,
1917
+ method: "POST",
1918
+ params: {
1919
+ ...PAGE2,
1920
+ ...MANY,
1921
+ sortBy: inBody("string", "REMINDER_TIME_ASC or REMINDER_TIME_DESC.")
1922
+ },
1923
+ path: "/master-inbox/reminders"
1924
+ },
1925
+ inboxScheduled: {
1926
+ description: "Emails queued to be sent later, with their scheduled time.",
1927
+ docs: `${DOCS}/inbox/get-scheduled`,
1928
+ method: "POST",
1929
+ params: {
1930
+ ...PAGE2,
1931
+ ...HISTORY,
1932
+ ...MANY,
1933
+ sortBy: inBody("string", "SCHEDULED_TIME_ASC or SCHEDULED_TIME_DESC.")
1934
+ },
1935
+ path: "/master-inbox/scheduled"
1936
+ },
1937
+ inboxSent: {
1938
+ description: "Sent emails across every campaign, one thread per row.",
1939
+ docs: `${DOCS}/inbox/get-sent`,
1940
+ method: "POST",
1941
+ params: { ...PAGE2, ...MANY, ...SORT },
1942
+ path: "/master-inbox/sent"
1943
+ },
1944
+ inboxSnoozed: {
1945
+ description: "Threads snoozed for later.",
1946
+ docs: `${DOCS}/inbox/get-snoozed`,
1947
+ method: "POST",
1948
+ params: { ...PAGE2, ...HISTORY, ...MANY, ...SORT },
1949
+ path: "/master-inbox/snoozed"
1950
+ },
1951
+ inboxUnread: {
1952
+ description: "Threads with an unread reply.",
1953
+ docs: `${DOCS}/inbox/get-unread`,
1954
+ method: "POST",
1955
+ params: { ...PAGE2, ...HISTORY, ...MANY, ...SORT },
1956
+ path: "/master-inbox/unread-replies"
1957
+ },
1958
+ inboxUntrackedReplies: {
1959
+ description: "Replies that reached a connected mailbox but belong to no campaign.",
1960
+ docs: `${DOCS}/inbox/get-untracked`,
1961
+ method: "GET",
1962
+ params: {
1963
+ fetchAttachments: inQuery("boolean", "Add attachment details."),
1964
+ fetchBody: inQuery("boolean", "Add each email's body."),
1965
+ from_email: inQuery("string", "Only from this address."),
1966
+ limit: inQuery("number", "Replies per page, 1 to 100."),
1967
+ offset: inQuery("number", "Replies to skip."),
1968
+ subject_line: inQuery("string", "Only subjects containing this."),
1969
+ to_email: inQuery("string", "Only to this address.")
1970
+ },
1971
+ path: "/master-inbox/untracked-replies"
1972
+ },
1973
+ inboxView: {
1974
+ description: "Threads matching a custom view: the inbox filters plus a subsequence.",
1975
+ docs: `${DOCS}/inbox/get-views`,
1976
+ method: "POST",
1977
+ params: {
1978
+ ...PAGE2,
1979
+ ...HISTORY,
1980
+ ...filters("Each id is a single value; subSequenceId is also taken."),
1981
+ ...SORT
1982
+ },
1983
+ path: "/master-inbox/views"
1984
+ },
1985
+ replyStatus: {
1986
+ description: "Whether a reply sent from the master inbox was delivered, and when.",
1987
+ docs: `${DOCS}/inbox/reply-status`,
1988
+ method: "GET",
1989
+ params: {
1990
+ message_id: inQueryRequired(
1991
+ "string",
1992
+ "The reply's Message-ID header, angle brackets included."
1993
+ )
1994
+ },
1995
+ path: "/master-inbox/reply-status"
1996
+ }
1997
+ });
1998
+
1999
+ // src/smartlead/native-services.ts
2000
+ var TEST = { spamTestId: inPath("The placement test's id.") };
2001
+ var report = (leaf, page, description) => ({
2002
+ baseUrl: DELIVERY_URL,
2003
+ description,
2004
+ docs: `${DOCS}/smart-delivery/${page}`,
2005
+ method: "GET",
2006
+ params: TEST,
2007
+ path: `/spam-test/report/{spamTestId}/${leaf}`
2008
+ });
2009
+ var SEARCHES = {
2010
+ limit: inQuery("string", "Searches per page; 10 by default."),
2011
+ offset: inQuery("string", "Searches to skip.")
2012
+ };
2013
+ var searches = (leaf, description) => ({
2014
+ baseUrl: PROSPECT_URL,
2015
+ description,
2016
+ docs: `${DOCS}/smart-prospect/${leaf}`,
2017
+ method: "GET",
2018
+ params: SEARCHES,
2019
+ path: `/search-email-leads/search-filters/${leaf}`
2020
+ });
2021
+ var DELIVERY = defineNative({
2022
+ deliveryDkimDetails: report(
2023
+ "dkim-details",
2024
+ "dkim-details",
2025
+ "The DKIM result of each sender in a placement test."
2026
+ ),
2027
+ deliveryDomainBlacklist: report(
2028
+ "domain-blacklist",
2029
+ "domain-blacklist",
2030
+ "Whether a placement test's sending domains are on a block list."
2031
+ ),
2032
+ deliveryEmailContent: report(
2033
+ "email-content",
2034
+ "test-email-content",
2035
+ "The email a placement test sent."
2036
+ ),
2037
+ deliveryFolder: {
2038
+ baseUrl: DELIVERY_URL,
2039
+ description: "One folder of placement tests.",
2040
+ docs: `${DOCS}/smart-delivery/get-folder-by-id`,
2041
+ method: "GET",
2042
+ params: { folderId: inPath("The folder's id.") },
2043
+ path: "/spam-test/folder/{folderId}"
2044
+ },
2045
+ deliveryFolders: {
2046
+ baseUrl: DELIVERY_URL,
2047
+ description: "The folders that organize placement tests.",
2048
+ docs: `${DOCS}/smart-delivery/get-folders`,
2049
+ method: "GET",
2050
+ path: "/spam-test/folder"
2051
+ },
2052
+ deliveryGeoReport: {
2053
+ baseUrl: DELIVERY_URL,
2054
+ description: "A placement test's inbox and spam rates per region.",
2055
+ docs: `${DOCS}/smart-delivery/geo-report`,
2056
+ method: "POST",
2057
+ params: TEST,
2058
+ path: "/spam-test/report/{spamTestId}/groupwise"
2059
+ },
2060
+ deliveryIpBlacklist: report(
2061
+ "blacklist",
2062
+ "blacklists",
2063
+ "Whether a placement test's sending IPs are on a block list, per seed mailbox."
2064
+ ),
2065
+ deliveryIpDetails: report(
2066
+ "ip-analytics",
2067
+ "ip-details",
2068
+ "The sending IP addresses a placement test saw."
2069
+ ),
2070
+ deliveryMailboxCount: {
2071
+ baseUrl: DELIVERY_URL,
2072
+ description: "How many test mailboxes there are per provider.",
2073
+ docs: `${DOCS}/smart-delivery/mailbox-count`,
2074
+ method: "GET",
2075
+ path: "/spam-test/report/mailboxes-count"
2076
+ },
2077
+ deliveryMailboxSummary: {
2078
+ baseUrl: DELIVERY_URL,
2079
+ description: "A summary of every test mailbox.",
2080
+ docs: `${DOCS}/smart-delivery/mailbox-summary`,
2081
+ method: "GET",
2082
+ path: "/spam-test/report/mailboxes-summary"
2083
+ },
2084
+ deliveryProviderReport: {
2085
+ baseUrl: DELIVERY_URL,
2086
+ description: "A placement test's inbox, spam and bounce rates per mailbox provider.",
2087
+ docs: `${DOCS}/smart-delivery/provider-report`,
2088
+ method: "POST",
2089
+ params: TEST,
2090
+ path: "/spam-test/report/{spamTestId}/providerwise"
2091
+ },
2092
+ deliveryRdnsDetails: report(
2093
+ "rdns-details",
2094
+ "rdns-report",
2095
+ "The reverse DNS of a placement test's sending IPs."
2096
+ ),
2097
+ deliveryReplyHeaders: {
2098
+ baseUrl: DELIVERY_URL,
2099
+ description: "The headers of one email a placement test received.",
2100
+ docs: `${DOCS}/smart-delivery/reply-headers`,
2101
+ method: "GET",
2102
+ params: { ...TEST, replyId: inPath("The received email's reply id.") },
2103
+ path: "/spam-test/report/{spamTestId}/sender-account-wise/{replyId}/email-headers"
2104
+ },
2105
+ deliveryScheduleHistory: report(
2106
+ "schedule-history",
2107
+ "schedule-history",
2108
+ "The runs of an automated placement test."
2109
+ ),
2110
+ deliverySeedProviders: {
2111
+ baseUrl: DELIVERY_URL,
2112
+ description: "The mailbox provider ids per region that placement tests refer to.",
2113
+ docs: `${DOCS}/smart-delivery/provider-ids`,
2114
+ method: "GET",
2115
+ path: "/spam-test/seed/providers"
2116
+ },
2117
+ deliverySenderAccounts: report(
2118
+ "sender-accounts",
2119
+ "sender-list",
2120
+ "The sender mailboxes of a placement test."
2121
+ ),
2122
+ deliverySenderReport: report(
2123
+ "sender-account-wise",
2124
+ "sender-report",
2125
+ "A placement test's results per sender mailbox."
2126
+ ),
2127
+ deliverySpamFilterDetails: report(
2128
+ "spam-filter-details",
2129
+ "spam-filter-report",
2130
+ "Which spam filters a placement test's emails triggered, and why."
2131
+ ),
2132
+ deliverySpfDetails: report(
2133
+ "spf-details",
2134
+ "spf-details",
2135
+ "The SPF result of each sender in a placement test."
2136
+ ),
2137
+ deliveryTest: {
2138
+ baseUrl: DELIVERY_URL,
2139
+ description: "One placement test: its type, campaign, step and provider.",
2140
+ docs: `${DOCS}/smart-delivery/test-details`,
2141
+ method: "GET",
2142
+ params: TEST,
2143
+ path: "/spam-test/{spamTestId}"
2144
+ },
2145
+ deliveryTests: {
2146
+ baseUrl: DELIVERY_URL,
2147
+ description: "Every placement test, with its status and schedule.",
2148
+ docs: `${DOCS}/smart-delivery/list-tests`,
2149
+ method: "POST",
2150
+ path: "/spam-test/report"
2151
+ }
2152
+ });
2153
+ var SERVICES = defineNative({
2154
+ prospectContacts: {
2155
+ baseUrl: PROSPECT_URL,
2156
+ description: "Contacts already saved from SmartProspect, by search filter or by id. Takes filter_id or id, not both.",
2157
+ docs: `${DOCS}/smart-prospect/get-contacts`,
2158
+ method: "POST",
2159
+ params: {
2160
+ catch_all_status: inBody(
2161
+ "string",
2162
+ "catch_all_verified, catch_all_soft_bounced, catch_all_hard_bounced, catch_all_unknown or catch_all_bounced."
2163
+ ),
2164
+ filter_id: inBody("number", "The search filter whose contacts to read."),
2165
+ id: inBody(
2166
+ "json",
2167
+ "Contact ids (adapt_ids), as an array of at most 200."
2168
+ ),
2169
+ limit: inBody("number", "Contacts per page, 1 to 1000, with filter_id."),
2170
+ offset: inBody("number", "Contacts to skip, with filter_id."),
2171
+ search: inBody("string", "Matches the first, last or full name."),
2172
+ verification_status: inBody("string", "valid, catch_all or invalid.")
2173
+ },
2174
+ path: "/search-email-leads/get-contacts"
2175
+ },
2176
+ prospectFetchedSearches: searches(
2177
+ "fetched-searches",
2178
+ "SmartProspect searches whose contacts were fetched, with their email counts."
2179
+ ),
2180
+ prospectRecentSearches: searches(
2181
+ "recent-searches",
2182
+ "The most recent SmartProspect searches."
2183
+ ),
2184
+ prospectReplyAnalytics: {
2185
+ baseUrl: PROSPECT_URL,
2186
+ description: "Replies from SmartProspect contacts this month against last month.",
2187
+ docs: `${DOCS}/smart-prospect/reply-analytics`,
2188
+ method: "GET",
2189
+ path: "/search-email-leads/reply-analytics"
2190
+ },
2191
+ prospectSavedSearches: searches(
2192
+ "saved-searches",
2193
+ "The saved SmartProspect searches."
2194
+ ),
2195
+ prospectSearchAnalytics: {
2196
+ baseUrl: PROSPECT_URL,
2197
+ description: "SmartProspect leads found, emails fetched and credits left, with the monthly trend.",
2198
+ docs: `${DOCS}/smart-prospect/search-analytics`,
2199
+ method: "GET",
2200
+ params: { filter_id: inQuery("string", "Only this search filter.") },
2201
+ path: "/search-email-leads/search-analytics"
2202
+ },
2203
+ smartSendersDomains: {
2204
+ baseUrl: SENDERS_URL,
2205
+ description: "The sending domains bought through SmartSenders.",
2206
+ docs: `${DOCS}/smart-senders/domain-list`,
2207
+ method: "GET",
2208
+ path: "/smart-senders/get-domain-list"
2209
+ },
2210
+ smartServers: {
2211
+ baseUrl: SERVERS_URL,
2212
+ description: "The account's dedicated sending IPs, with the campaigns on each on request.",
2213
+ docs: `${DOCS}/smart-servers/list-servers`,
2214
+ method: "GET",
2215
+ params: {
2216
+ unmapped: inQuery(
2217
+ "string",
2218
+ 'Set to "true" for only servers on no campaign or client.'
2219
+ ),
2220
+ withCampaignData: inQuery(
2221
+ "string",
2222
+ `Set to "true" to add each server's campaigns, client and region.`
2223
+ )
2224
+ },
2225
+ path: "/smart-server/"
2226
+ },
2227
+ smartServersForCampaign: {
2228
+ baseUrl: SERVERS_URL,
2229
+ description: "The dedicated IP attached to a campaign; only one is returned when it has several.",
2230
+ docs: `${DOCS}/smart-servers/get-campaign-servers`,
2231
+ method: "GET",
2232
+ params: { campaign_id: inPath("The campaign's id.") },
2233
+ path: "/smart-server/all/campaign/{campaign_id}"
2234
+ }
2235
+ });
2236
+
2237
+ // src/smartlead/native.ts
2238
+ var NATIVE = defineNative({
2239
+ ...ANALYTICS,
2240
+ ...CAMPAIGN_READS,
2241
+ ...INBOX,
2242
+ ...DELIVERY,
2243
+ ...SERVICES
2244
+ });
2245
+ var escaped = (part) => part.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
2246
+ var pattern = (read) => {
2247
+ const id = read.baseUrl === void 0 ? String.raw`\d+` : "[^/]+";
2248
+ const route = read.path.split(/\{[^}]+\}/u).map(escaped).join(id).replace(/\/$/u, "");
2249
+ return new RegExp(`^${route}$`, "u");
2250
+ };
2251
+ var NATIVE_READ_POSTS = Object.values(
2252
+ NATIVE
2253
+ ).filter((read) => read.method === "POST").map(pattern);
2254
+
2255
+ // src/smartlead/client.ts
2256
+ var READ_POSTS = [/^\/master-inbox\/inbox-replies$/u, ...NATIVE_READ_POSTS];
2257
+ var normalizePath = (path) => {
2258
+ const [withoutQuery = ""] = path.split("?");
2259
+ return `/${withoutQuery.replace(/^\/+/u, "").replace(/\/+$/u, "")}`.replace(
2260
+ /^\/api\/v1(?=\/|$)/u,
2261
+ ""
2262
+ );
2263
+ };
2264
+ var SECRET_PATH = /^\/(?:client\/api-key|email-accounts\/fetch-email-account-details|smart-senders\/(?:auth-secret|order-details))(?:\/|$)/iu;
2265
+ var CLIENT = /^\/client\/[^/]+$/iu;
2266
+ var isSecret = (path, query) => {
2267
+ const normalized = normalizePath(path);
2268
+ const whitelabel = query.get("includeWhitelabel");
2269
+ return SECRET_PATH.test(normalized) || CLIENT.test(normalized) && whitelabel !== null && whitelabel.toLowerCase() !== "false";
2270
+ };
2271
+ var isRead = (method, path) => {
2272
+ if (method === "GET") {
2273
+ return true;
2274
+ }
2275
+ const normalized = normalizePath(path);
2276
+ return method === "POST" && READ_POSTS.some((pattern2) => pattern2.test(normalized));
2277
+ };
2278
+ var createClient = (options) => {
2279
+ const baseUrl = options.baseUrl ?? BASE_URL;
2280
+ const authorize = (spec) => {
2281
+ const url = new URL(spec.url);
2282
+ url.searchParams.set("api_key", options.apiKey);
2283
+ return { ...spec, url: url.toString() };
2284
+ };
2285
+ return {
2286
+ ...createVendorClient(baseUrl, authorize),
2287
+ delivery: createVendorClient(DELIVERY_URL, authorize),
2288
+ identity: options.identity,
2289
+ raw: { authorize, baseUrl, isRead, isSecret }
2290
+ };
2291
+ };
2292
+
2293
+ // src/smartlead/index.ts
2294
+ var PROVIDER = "smartlead";
2295
+ var envVars = [API_KEY_ENV, WORKSPACE_ENV];
2296
+ var smartlead = (options = {}) => {
2297
+ const apiKey = requireCredential(options.apiKey, API_KEY_ENV, PROVIDER);
2298
+ const workspaceId = assertWorkspaceId(
2299
+ options.workspaceId ?? readEnv(WORKSPACE_ENV) ?? "default",
2300
+ PROVIDER
2301
+ );
2302
+ const client = createClient({
2303
+ apiKey,
2304
+ baseUrl: options.baseUrl,
2305
+ identity: { provider: PROVIDER, workspaceId }
2306
+ });
2307
+ return {
2308
+ ...withLeadFields(readers(client), options.leadFields),
2309
+ capabilities: { ...capabilities, ...options.capabilities },
2310
+ caveats,
2311
+ costs,
2312
+ events: smartleadEvents(PROVIDER),
2313
+ fields: withMappedFields(fields, options.leadFields),
2314
+ limits,
2315
+ mapError: makeErrorMapper(PROVIDER, { secrets: [apiKey] }),
2316
+ maturity: "unverified",
2317
+ name: PROVIDER,
2318
+ native: NATIVE,
2319
+ raw: client.raw,
2320
+ // The key is in every URL, so the engine must redact it everywhere.
2321
+ secrets: [apiKey],
2322
+ workspaceId
2323
+ };
2324
+ };
2325
+ export {
2326
+ PROVIDER,
2327
+ envVars,
2328
+ smartlead
2329
+ };