outbound-sdk 0.1.0 → 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 (145) hide show
  1. package/README.md +0 -2
  2. package/dist/alerts/index.js +5 -1
  3. package/dist/audit/index.js +2 -2
  4. package/dist/benchmarks/index.js +5 -3
  5. package/dist/budget/index.js +31 -10
  6. package/dist/cache/index.js +2 -2
  7. package/dist/cards/index.js +1 -1
  8. package/dist/chunks/{chunk-WAM6N4OF.js → chunk-4PSO6JEK.js} +107 -19
  9. package/dist/chunks/chunk-6CVZOUHB.js +152 -0
  10. package/dist/chunks/{chunk-OCV66TS2.js → chunk-AFU5E5QB.js} +17 -8
  11. package/dist/chunks/{chunk-R6AM4GJR.js → chunk-DJ2IUQEU.js} +24 -18
  12. package/dist/chunks/{chunk-LOXBLQ3I.js → chunk-E7JHLNLG.js} +9 -2
  13. package/dist/chunks/{chunk-LNCOGBMI.js → chunk-FHKSLCVW.js} +13 -3
  14. package/dist/chunks/chunk-FKH5N47I.js +40 -0
  15. package/dist/chunks/chunk-HZCTYL22.js +29 -0
  16. package/dist/chunks/{chunk-CMQ5ZHLZ.js → chunk-IPUYZD4O.js} +1 -1
  17. package/dist/chunks/{chunk-VURTOVGI.js → chunk-IVH3NMQZ.js} +1 -1
  18. package/dist/chunks/{chunk-ZGHQYZEH.js → chunk-LVYG7XZJ.js} +1 -1
  19. package/dist/chunks/chunk-NAKXLBA6.js +30 -0
  20. package/dist/chunks/{chunk-7BCYLIDG.js → chunk-PMSSUWD7.js} +186 -33
  21. package/dist/chunks/{chunk-Q465X22Y.js → chunk-PURHK3JU.js} +93 -209
  22. package/dist/chunks/{chunk-F7MKFVIG.js → chunk-R3Y56YVF.js} +2 -2
  23. package/dist/chunks/chunk-RCZ7ZZFU.js +92 -0
  24. package/dist/chunks/chunk-SBIZDCRY.js +106 -0
  25. package/dist/chunks/{chunk-IBC52BX3.js → chunk-U2D34ARZ.js} +20 -3
  26. package/dist/chunks/chunk-UAT3JSJZ.js +331 -0
  27. package/dist/chunks/{chunk-QZNNCXXD.js → chunk-VQSCHOBV.js} +20 -1
  28. package/dist/chunks/{chunk-B7V6EOAC.js → chunk-XNFESPZH.js} +160 -126
  29. package/dist/chunks/{chunk-WW746NJF.js → chunk-YOTW5ESM.js} +25 -1
  30. package/dist/cli/bin.js +14 -13
  31. package/dist/cli/commands.d.ts +3 -0
  32. package/dist/cli/config.d.ts +22 -0
  33. package/dist/cli/index.d.ts +5 -1
  34. package/dist/cli/index.js +20 -15
  35. package/dist/cli/stdio.d.ts +9 -0
  36. package/dist/clients/index.js +13 -3
  37. package/dist/combine/account.d.ts +1 -1
  38. package/dist/combine/index.js +90 -15
  39. package/dist/combine/route.d.ts +7 -0
  40. package/dist/exporter/index.js +2 -2
  41. package/dist/failover/index.js +4 -4
  42. package/dist/fixtures/index.js +40 -21
  43. package/dist/heyreach/account.d.ts +1 -1
  44. package/dist/heyreach/adapter.d.ts +1 -1
  45. package/dist/heyreach/capabilities.d.ts +2 -0
  46. package/dist/heyreach/client.d.ts +3 -5
  47. package/dist/heyreach/index.d.ts +7 -0
  48. package/dist/heyreach/index.js +428 -205
  49. package/dist/heyreach/leads.d.ts +4 -0
  50. package/dist/heyreach/map-account.d.ts +7 -1
  51. package/dist/heyreach/map-stats.d.ts +8 -5
  52. package/dist/heyreach/map.d.ts +3 -1
  53. package/dist/heyreach/webhooks.d.ts +1 -0
  54. package/dist/identity/index.js +22 -11
  55. package/dist/index.d.ts +1 -4
  56. package/dist/index.js +29 -17
  57. package/dist/insights/copy/index.d.ts +2 -2
  58. package/dist/insights/copy/variant-test.d.ts +2 -2
  59. package/dist/insights/index.js +248 -184
  60. package/dist/insights/ops/anomalies.d.ts +3 -3
  61. package/dist/insights/ops/index.d.ts +2 -2
  62. package/dist/insights/ops/shared.d.ts +7 -1
  63. package/dist/insights/registry.d.ts +4 -4
  64. package/dist/instantly/adapter-account.d.ts +1 -1
  65. package/dist/instantly/capabilities.d.ts +2 -0
  66. package/dist/instantly/client.d.ts +4 -9
  67. package/dist/instantly/index.d.ts +7 -0
  68. package/dist/instantly/index.js +410 -155
  69. package/dist/instantly/map-account.d.ts +20 -5
  70. package/dist/instantly/map-stats.d.ts +9 -6
  71. package/dist/instantly/map.d.ts +0 -2
  72. package/dist/instantly/native-agents-sales.d.ts +41 -41
  73. package/dist/instantly/native-agents.d.ts +44 -44
  74. package/dist/instantly/native-campaigns.d.ts +21 -21
  75. package/dist/instantly/native-leads.d.ts +12 -12
  76. package/dist/instantly/native-params.d.ts +2 -19
  77. package/dist/instantly/native-search.d.ts +10 -10
  78. package/dist/instantly/native-senders.d.ts +56 -56
  79. package/dist/instantly/native-supersearch.d.ts +33 -33
  80. package/dist/instantly/native-workspace.d.ts +45 -45
  81. package/dist/instantly/native.d.ts +262 -262
  82. package/dist/instantly/webhooks.d.ts +1 -0
  83. package/dist/internal/adapter.d.ts +24 -2
  84. package/dist/internal/capabilities.d.ts +18 -0
  85. package/dist/internal/client.d.ts +15 -0
  86. package/dist/internal/concurrency.d.ts +8 -0
  87. package/dist/internal/engine/request.d.ts +7 -0
  88. package/dist/internal/entities-account.d.ts +73 -3
  89. package/dist/internal/entities.d.ts +116 -12
  90. package/dist/internal/errors.d.ts +6 -1
  91. package/dist/internal/fields.d.ts +462 -0
  92. package/dist/internal/json.d.ts +9 -0
  93. package/dist/internal/lead-fields.d.ts +21 -0
  94. package/dist/internal/lead-status.d.ts +13 -0
  95. package/dist/internal/metrics.d.ts +14 -2
  96. package/dist/internal/native.d.ts +15 -0
  97. package/dist/internal/outbound/api.d.ts +29 -4
  98. package/dist/internal/outbound/operations-account.d.ts +12 -0
  99. package/dist/internal/outbound/outbound.d.ts +6 -3
  100. package/dist/internal/outbound/specs-account.d.ts +5 -1
  101. package/dist/internal/page.d.ts +14 -0
  102. package/dist/internal/record.d.ts +17 -0
  103. package/dist/internal/records.d.ts +7 -0
  104. package/dist/internal/sequence.d.ts +14 -0
  105. package/dist/internal/sha256.d.ts +2 -0
  106. package/dist/loader/index.d.ts +14 -2
  107. package/dist/loader/index.js +8 -4
  108. package/dist/memory/account-reads.d.ts +1 -1
  109. package/dist/memory/account.d.ts +15 -1
  110. package/dist/memory/data.d.ts +17 -2
  111. package/dist/memory/index.js +110 -35
  112. package/dist/redact/index.js +11 -6
  113. package/dist/redact/plugin.d.ts +1 -1
  114. package/dist/smartlead/account.d.ts +1 -1
  115. package/dist/smartlead/adapter.d.ts +1 -1
  116. package/dist/smartlead/capabilities.d.ts +2 -0
  117. package/dist/smartlead/client.d.ts +6 -11
  118. package/dist/smartlead/hmac.d.ts +0 -2
  119. package/dist/smartlead/index.d.ts +7 -0
  120. package/dist/smartlead/index.js +731 -572
  121. package/dist/smartlead/leads.d.ts +4 -1
  122. package/dist/smartlead/map-account.d.ts +17 -5
  123. package/dist/smartlead/map-stats.d.ts +9 -10
  124. package/dist/smartlead/map.d.ts +15 -5
  125. package/dist/smartlead/native-analytics.d.ts +87 -87
  126. package/dist/smartlead/native-campaigns.d.ts +64 -64
  127. package/dist/smartlead/native-inbox.d.ts +51 -51
  128. package/dist/smartlead/native-params.d.ts +2 -23
  129. package/dist/smartlead/native-services.d.ts +34 -34
  130. package/dist/smartlead/native.d.ts +236 -236
  131. package/dist/smartlead/shared.d.ts +6 -5
  132. package/dist/smartlead/webhooks.d.ts +1 -0
  133. package/dist/sync/index.js +3 -3
  134. package/dist/tools/ai-sdk.js +7 -5
  135. package/dist/tools/campaign-tools.d.ts +1 -1
  136. package/dist/tools/claude-agent.js +7 -5
  137. package/dist/tools/index.js +8 -6
  138. package/dist/tracing/index.js +2 -2
  139. package/dist/webhooks/index.js +10 -9
  140. package/package.json +1 -1
  141. package/dist/chunks/chunk-FZF6CLPX.js +0 -232
  142. package/dist/chunks/chunk-GPEJG34O.js +0 -53
  143. package/dist/chunks/chunk-HEC7XFFH.js +0 -65
  144. package/dist/chunks/chunk-QTB747K4.js +0 -100
  145. package/dist/chunks/chunk-TIJKJJDW.js +0 -6
@@ -1,4 +1,6 @@
1
1
  import {
2
+ EVENT_TYPES,
3
+ NO_CATEGORIES,
2
4
  reputation,
3
5
  smartleadEvents,
4
6
  toCampaign,
@@ -11,43 +13,55 @@ import {
11
13
  toWorkspace,
12
14
  unwrap,
13
15
  withoutSecrets
14
- } from "../chunks/chunk-Q465X22Y.js";
16
+ } from "../chunks/chunk-PURHK3JU.js";
15
17
  import {
16
- normalizeBody
17
- } from "../chunks/chunk-GPEJG34O.js";
18
+ createVendorClient,
19
+ flatMapPage,
20
+ mapPage,
21
+ normalizeBody,
22
+ withLeadFields,
23
+ withMappedFields
24
+ } from "../chunks/chunk-6CVZOUHB.js";
18
25
  import {
19
- defineNative
20
- } from "../chunks/chunk-TIJKJJDW.js";
26
+ fromOne
27
+ } from "../chunks/chunk-FKH5N47I.js";
21
28
  import {
22
- emptyCounts
23
- } from "../chunks/chunk-WW746NJF.js";
29
+ defineNative,
30
+ inBody,
31
+ inBodyRequired,
32
+ inPath,
33
+ inQuery,
34
+ inQueryRequired
35
+ } from "../chunks/chunk-NAKXLBA6.js";
24
36
  import {
25
- buildUrl
26
- } from "../chunks/chunk-NAWZ73QS.js";
37
+ emptyCounts,
38
+ metricRow
39
+ } from "../chunks/chunk-YOTW5ESM.js";
40
+ import "../chunks/chunk-NAWZ73QS.js";
27
41
  import {
28
42
  stableId
29
- } from "../chunks/chunk-LNCOGBMI.js";
43
+ } from "../chunks/chunk-FHKSLCVW.js";
30
44
  import {
31
45
  readEnv,
32
46
  requireCredential
33
- } from "../chunks/chunk-CMQ5ZHLZ.js";
47
+ } from "../chunks/chunk-IPUYZD4O.js";
34
48
  import {
49
+ eventTypesOf,
35
50
  recordBase,
36
51
  refTo,
37
52
  refsTo
38
- } from "../chunks/chunk-IBC52BX3.js";
53
+ } from "../chunks/chunk-U2D34ARZ.js";
39
54
  import {
40
- SCHEMA_VERSION,
41
55
  replyCategorySchema
42
- } from "../chunks/chunk-WAM6N4OF.js";
56
+ } from "../chunks/chunk-4PSO6JEK.js";
43
57
  import {
44
- assertWorkspaceId,
45
- makeRef
46
- } from "../chunks/chunk-ZGHQYZEH.js";
58
+ assertWorkspaceId
59
+ } from "../chunks/chunk-LVYG7XZJ.js";
47
60
  import {
48
61
  OutboundError,
49
- makeErrorMapper
50
- } from "../chunks/chunk-LOXBLQ3I.js";
62
+ makeErrorMapper,
63
+ requireObject
64
+ } from "../chunks/chunk-E7JHLNLG.js";
51
65
  import {
52
66
  count,
53
67
  emailAddress,
@@ -62,7 +76,7 @@ import {
62
76
  stringMap,
63
77
  text,
64
78
  timestamp
65
- } from "../chunks/chunk-QZNNCXXD.js";
79
+ } from "../chunks/chunk-VQSCHOBV.js";
66
80
 
67
81
  // src/smartlead/capabilities.ts
68
82
  var BASE_URL = "https://server.smartlead.ai/api/v1";
@@ -80,6 +94,10 @@ var capabilities = {
80
94
  // GET /leads/get-domain-block-list: addresses and domains.
81
95
  blocklist: true,
82
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,
83
101
  "campaigns.settings": true,
84
102
  // GET /campaigns/ has no status filter and returns every campaign at once.
85
103
  "campaigns.status": "client",
@@ -101,6 +119,10 @@ var capabilities = {
101
119
  // sent and the wrapper filters after fetching.
102
120
  "leads.since": "client",
103
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,
104
126
  // GET /lead-list/. lists.leads is left off: no endpoint returns the leads
105
127
  // of a lead list.
106
128
  "lists.list": true,
@@ -115,6 +137,8 @@ var capabilities = {
115
137
  "replies.category": "vendor",
116
138
  "replies.list": true,
117
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",
118
142
  "replies.since": "client",
119
143
  "senders.byCampaign": true,
120
144
  "senders.get": true,
@@ -131,14 +155,49 @@ var capabilities = {
131
155
  // address. The per-campaign mailbox endpoint documents no response.
132
156
  "stats.bySender": "exact",
133
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",
134
161
  "stats.campaign": "exact",
135
162
  "stats.workspace": "exact",
136
163
  // GET /email-accounts/tags: one tag space for mailboxes, leads and campaigns.
137
164
  tags: true,
165
+ // GET /webhook/{webhook_id}.
166
+ "webhooks.get": true,
138
167
  // GET /campaigns/{id}/webhooks; there is no list of every webhook.
139
168
  "webhooks.list": true,
140
169
  workspaces: true
141
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
+ };
142
201
  var TEN_PER_MINUTE = [{ perMs: 6e4, requests: 10 }];
143
202
  var limits = {
144
203
  lanes: {
@@ -155,7 +214,8 @@ var costs = {
155
214
  // One request returns every campaign; there are no pages.
156
215
  "campaigns.list": { perPage: 1 },
157
216
  "campaigns.settings": { perPage: 1 },
158
- // The lead, then its tags.
217
+ // The lead, then its tags, then the category list when the lead has a
218
+ // category.
159
219
  "leads.get": { perPage: 2 },
160
220
  // The first page also reads the lead category list and, without a
161
221
  // campaign, the campaign list. A lookup by address is one request, two
@@ -175,6 +235,7 @@ var costs = {
175
235
  // One subsequence per page; the first page also reads the campaign list.
176
236
  "sequence.subsequences": { pageSize: 1, perPage: 1 },
177
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.
178
239
  stats: { perPage: 1 },
179
240
  "tags.list": { perPage: 1 },
180
241
  // One campaign per page; without a campaign, the first page also reads the
@@ -192,7 +253,7 @@ var caveats = [
192
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.",
193
254
  "No endpoint finds a lead by LinkedIn profile: leads.list({ linkedinUrl }) returns nothing and sends no request.",
194
255
  "A lead's status, campaign and creation time are per campaign; leads.get returns no campaign and its example looks illustrative.",
195
- "STOPPED maps to paused; lead status BLOCKED maps to bounced.",
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.",
196
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.",
197
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.",
198
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.",
@@ -200,9 +261,9 @@ var caveats = [
200
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.",
201
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.",
202
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.",
203
- "No delivered or automatic-reply count exists. A campaign's dated total uses non_ooo_reply_count for replied when present; lifetime reply_count includes out-of-office replies.",
204
- "Daily rows have sent, total opens and replies; the daily endpoint always reports 0 bounces, so bounced is null.",
205
- "Step statistics do not say whether opens and clicks are unique (mapped to openedTotal and clicked). A step with variants has a row per variant and no 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.",
206
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%.",
207
268
  "Workspaces are Smartlead clients; a client-level key may be refused.",
208
269
  "Webhook signing is off until turned on per webhook; unsigned webhooks fail verify.",
@@ -216,6 +277,7 @@ var caveats = [
216
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.",
217
278
  "Tags come from GET /email-accounts/tags; whether campaign tags share that list is unconfirmed.",
218
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.",
219
281
  "Block list entries with an @ are emails, the rest domains."
220
282
  ];
221
283
 
@@ -286,6 +348,21 @@ var toSettings = (identity, campaignId, raw) => {
286
348
  }
287
349
  };
288
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
+ };
289
366
  var connected = (account) => {
290
367
  const smtp = flag(account.is_smtp_success);
291
368
  const imap = flag(account.is_imap_success);
@@ -323,52 +400,264 @@ var toHealth = (identity, account, stats) => {
323
400
  warmup: warmupTraffic(stats, account.warmup_details)
324
401
  };
325
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
+ };
326
426
  var toList = (identity, raw) => ({
327
427
  ...recordBase(identity, text(raw.id) ?? "", raw),
328
428
  createdAt: timestamp(raw.created_at),
329
429
  kind: "leads",
330
- name: text(raw.name) ?? "",
430
+ name: text(raw.name) ?? text(raw.id) ?? "",
331
431
  size: count(raw.lead_count)
332
432
  });
333
433
  var toBlockEntry = (identity, raw) => {
334
- const value = (text(raw.email_or_domain) ?? "").toLowerCase();
335
- return {
336
- ...recordBase(identity, text(raw.id) ?? "", raw),
337
- createdAt: timestamp(raw.created_at),
338
- kind: value.includes("@") ? "email" : "domain",
339
- value
340
- };
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
+ ];
341
443
  };
342
444
  var toTag = (identity, raw) => ({
343
445
  ...recordBase(identity, text(raw.id) ?? "", raw),
344
446
  description: null,
345
- name: text(raw.name) ?? ""
447
+ name: text(raw.name) ?? text(raw.id) ?? ""
346
448
  });
347
- var toWebhook = (identity, campaignId, raw) => ({
348
- ...recordBase(identity, text(raw.id) ?? "", withoutSecrets(raw)),
349
- // Only the newer example carries is_active.
350
- active: flag(raw.is_active),
351
- campaignRefs: refsTo(identity, [text(raw.email_campaign_id) ?? campaignId]),
352
- createdAt: timestamp(raw.created_at),
353
- events: list(raw.event_types).flatMap((event) => text(event) ?? []),
354
- name: text(raw.name),
355
- url: text(raw.webhook_url) ?? ""
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)
356
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
+ };
357
651
 
358
652
  // src/smartlead/shared.ts
359
653
  var pageSize = (limit, max = PAGE_SIZE) => Math.min(limit ?? max, max);
360
654
  var segment = (id) => encodeURIComponent(id);
361
655
  var idList = (value) => list(value).flatMap((id) => text(id) ?? []);
362
- var providerError = (client, message) => new OutboundError("Provider", message, {
363
- provider: client.identity.provider
364
- });
365
- var objectOf = (client, body2, what) => {
366
- const payload = unwrap(body2);
367
- if (!isJsonObject(payload)) {
368
- throw providerError(client, `Smartlead returned no object for ${what}`);
369
- }
370
- return payload;
371
- };
656
+ var objectOf = (client, body, what) => requireObject(
657
+ unwrap(body),
658
+ client.identity.provider,
659
+ `Smartlead returned no object for ${what}`
660
+ );
372
661
  var campaignList = async (client, ctx) => objects(
373
662
  unwrap(
374
663
  await client.get(ctx, "/campaigns/", { query: { include_tags: true } })
@@ -378,34 +667,42 @@ var campaignIds = async (client, ctx) => {
378
667
  const campaigns = await campaignList(client, ctx);
379
668
  return campaigns.flatMap((campaign) => text(campaign.id) ?? []);
380
669
  };
381
- var offsetPage = async (client, ctx, path2, page) => {
382
- const rows = objects(unwrap(await client.get(ctx, path2, { query: page })));
670
+ var offsetPage = async (client, ctx, path, page) => {
671
+ const rows = objects(unwrap(await client.get(ctx, path, { query: page })));
383
672
  return {
384
- next: rows.length === page.limit ? page.offset + page.limit : void 0,
385
- rows
673
+ items: rows,
674
+ next: rows.length === page.limit ? page.offset + page.limit : void 0
386
675
  };
387
676
  };
388
- var categoryNames = async (client, ctx, next) => {
677
+ var leadCategories = async (client, ctx, next) => {
389
678
  if (isJsonObject(next)) {
390
- return stringMap(next.categories);
679
+ return {
680
+ meanings: categoriesFromJson(next.meanings),
681
+ names: stringMap(next.categories)
682
+ };
391
683
  }
392
- const categories = objects(
393
- unwrap(await client.get(ctx, "/leads/fetch-categories"))
394
- );
395
- return Object.fromEntries(
396
- categories.flatMap((category) => {
397
- const id = text(category.id);
398
- const name = text(category.name);
399
- return id === null || name === null ? [] : [[id, name]];
400
- })
401
- );
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
+ };
402
695
  };
696
+ var categoriesCursor = (categories) => ({
697
+ categories: { ...categories.names },
698
+ meanings: categoriesToJson(categories.meanings)
699
+ });
403
700
 
404
701
  // src/smartlead/account.ts
405
- var listSubsequences = async (client, ctx, query2) => {
406
- const campaigns = isJsonObject(query2.next) ? objects(query2.next.subsequences) : await campaignList(client, ctx);
702
+ var listSubsequences = async (client, ctx, query) => {
703
+ const campaigns = isJsonObject(query.next) ? objects(query.next.subsequences) : await campaignList(client, ctx);
407
704
  const children = campaigns.filter(
408
- (campaign) => text(campaign.parent_campaign_id) === query2.campaignId
705
+ (campaign) => text(campaign.parent_campaign_id) === query.campaignId
409
706
  );
410
707
  const [current, ...rest] = children;
411
708
  const id = text(current?.id);
@@ -414,23 +711,23 @@ var listSubsequences = async (client, ctx, query2) => {
414
711
  }
415
712
  const steps = await client.get(ctx, `/campaigns/${segment(id)}/sequences`);
416
713
  return {
417
- items: [toSubsequence(client.identity, query2.campaignId, current, steps)],
714
+ items: [toSubsequence(client.identity, query.campaignId, current, steps)],
418
715
  next: rest.length > 0 ? { subsequences: rest } : void 0
419
716
  };
420
717
  };
421
718
  var campaignWebhooks = async (client, ctx, campaignId) => objects(
422
719
  unwrap(await client.get(ctx, `/campaigns/${segment(campaignId)}/webhooks`))
423
720
  ).map((webhook) => toWebhook(client.identity, campaignId, webhook));
424
- var listWebhooks = async (client, ctx, query2) => {
425
- if (query2.campaignId !== void 0) {
426
- return { items: await campaignWebhooks(client, ctx, query2.campaignId) };
721
+ var listWebhooks = async (client, ctx, query) => {
722
+ if (query.campaignId !== void 0) {
723
+ return { items: await campaignWebhooks(client, ctx, query.campaignId) };
427
724
  }
428
- const campaigns = isJsonObject(query2.next) ? idList(query2.next.campaigns) : await campaignIds(client, ctx);
725
+ const campaigns = isJsonObject(query.next) ? idList(query.next.campaigns) : await campaignIds(client, ctx);
429
726
  const [current, ...rest] = campaigns;
430
727
  if (current === void 0) {
431
728
  return { items: [] };
432
729
  }
433
- const seen = new Set(idList(field(query2.next, "seen")));
730
+ const seen = new Set(idList(field(query.next, "seen")));
434
731
  const listed = await campaignWebhooks(client, ctx, current);
435
732
  const items = listed.filter((webhook) => !seen.has(webhook.sourceId));
436
733
  return {
@@ -444,6 +741,15 @@ var listWebhooks = async (client, ctx, query2) => {
444
741
  var accountReaders = (client) => {
445
742
  const { identity } = client;
446
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
+ ),
447
753
  getCampaignSettings: async (id, ctx) => toSettings(
448
754
  identity,
449
755
  id,
@@ -465,39 +771,56 @@ var accountReaders = (client) => {
465
771
  );
466
772
  return toHealth(identity, account, unwrap(stats));
467
773
  },
468
- listBlocklist: async (query2, ctx) => {
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) => {
469
792
  const page = await offsetPage(
470
793
  client,
471
794
  ctx,
472
795
  "/leads/get-domain-block-list",
473
796
  {
474
- limit: pageSize(query2.limit, BLOCKLIST_PAGE_SIZE),
475
- offset: count(query2.next) ?? 0
797
+ limit: pageSize(query.limit, BLOCKLIST_PAGE_SIZE),
798
+ offset: count(query.next) ?? 0
476
799
  }
477
800
  );
478
- return {
479
- items: page.rows.map((entry) => toBlockEntry(identity, entry)),
480
- next: page.next
481
- };
801
+ return flatMapPage(page, (entry) => toBlockEntry(identity, entry));
482
802
  },
483
- listLists: async (query2, ctx) => {
803
+ listLists: async (query, ctx) => {
484
804
  const page = await offsetPage(client, ctx, "/lead-list/", {
485
- limit: pageSize(query2.limit),
486
- offset: count(query2.next) ?? 0
805
+ limit: pageSize(query.limit),
806
+ offset: count(query.next) ?? 0
487
807
  });
488
- return {
489
- items: page.rows.map((row2) => toList(identity, row2)),
490
- next: page.next
491
- };
808
+ return mapPage(page, (row) => toList(identity, row));
492
809
  },
493
- listSubsequences: (query2, ctx) => listSubsequences(client, ctx, query2),
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),
494
817
  // One response holds every tag of the account; there are no pages.
495
818
  listTags: async (_query, ctx) => ({
496
819
  items: objects(unwrap(await client.get(ctx, "/email-accounts/tags"))).map(
497
820
  (tag) => toTag(identity, tag)
498
821
  )
499
822
  }),
500
- listWebhooks: (query2, ctx) => listWebhooks(client, ctx, query2)
823
+ listWebhooks: (query, ctx) => listWebhooks(client, ctx, query)
501
824
  };
502
825
  };
503
826
 
@@ -518,24 +841,24 @@ var memberships = async (client, ctx, lead) => {
518
841
  return campaignId === null ? [] : [{ campaignId, entry }];
519
842
  });
520
843
  };
521
- var leadsByEmail = async (client, ctx, query2) => {
522
- if (query2.email === void 0 || query2.linkedinUrl !== void 0) {
844
+ var leadsByEmail = async (client, ctx, query) => {
845
+ if (query.email === void 0 || query.linkedinUrl !== void 0) {
523
846
  return NONE;
524
847
  }
525
848
  const lead = unwrap(
526
- await client.get(ctx, "/leads/", { query: { email: query2.email } })
849
+ await client.get(ctx, "/leads/", { query: { email: query.email } })
527
850
  );
528
- if (!isJsonObject(lead) || text(lead.id) === null || emailAddress(lead.email) !== query2.email) {
851
+ if (!isJsonObject(lead) || text(lead.id) === null || emailAddress(lead.email) !== query.email) {
529
852
  return NONE;
530
853
  }
531
854
  const found = await memberships(client, ctx, lead);
532
855
  const wanted = found.filter(
533
- (membership) => query2.campaignId === void 0 || membership.campaignId === query2.campaignId
856
+ (membership) => query.campaignId === void 0 || membership.campaignId === query.campaignId
534
857
  );
535
858
  const categorized = wanted.some(
536
859
  (membership) => text(membership.entry.lead_category_id) !== null
537
860
  );
538
- const categories = categorized ? await categoryNames(client, ctx, void 0) : {};
861
+ const categories = categorized ? await leadCategories(client, ctx, void 0) : NO_CATEGORIES;
539
862
  return {
540
863
  items: wanted.map(
541
864
  (membership) => toFoundLead(client.identity, lead, { ...membership, categories })
@@ -545,64 +868,68 @@ var leadsByEmail = async (client, ctx, query2) => {
545
868
 
546
869
  // src/smartlead/leads.ts
547
870
  var campaignLeads = async (client, ctx, place) => {
548
- const body2 = await client.get(
871
+ const body = await client.get(
549
872
  ctx,
550
873
  `/campaigns/${segment(place.campaignId)}/leads`,
551
874
  { query: { limit: place.limit, offset: place.offset } }
552
875
  );
553
- const rows = objects(field(body2, "data"));
554
- const total = count(field(body2, "total_leads"));
876
+ const rows = objects(field(body, "data"));
877
+ const total = count(field(body, "total_leads"));
555
878
  const end = place.offset + rows.length;
556
879
  const more = rows.length > 0 && (total === null ? rows.length === place.limit : end < total);
557
880
  return {
558
881
  items: rows.map(
559
- (row2) => toCampaignLead(client.identity, place.campaignId, row2, place.categories)
882
+ (row) => toCampaignLead(client.identity, place.campaignId, row, place.categories)
560
883
  ),
561
884
  nextOffset: more ? end : void 0
562
885
  };
563
886
  };
564
887
  var offsetOf = (next) => count(field(next, "offset")) ?? 0;
565
- var allLeads = async (client, ctx, query2) => {
566
- const campaigns = isJsonObject(query2.next) ? idList(query2.next.campaigns) : await campaignIds(client, ctx);
888
+ var allLeads = async (client, ctx, query) => {
889
+ const campaigns = isJsonObject(query.next) ? idList(query.next.campaigns) : await campaignIds(client, ctx);
567
890
  const [current, ...rest] = campaigns;
568
891
  if (current === void 0) {
569
892
  return { items: [] };
570
893
  }
571
- const categories = await categoryNames(client, ctx, query2.next);
894
+ const categories = await leadCategories(client, ctx, query.next);
572
895
  const page = await campaignLeads(client, ctx, {
573
896
  campaignId: current,
574
897
  categories,
575
- limit: pageSize(query2.limit),
576
- offset: offsetOf(query2.next)
898
+ limit: pageSize(query.limit),
899
+ offset: offsetOf(query.next)
577
900
  });
578
901
  if (page.nextOffset !== void 0) {
579
902
  return {
580
903
  items: page.items,
581
- next: { campaigns, categories, offset: page.nextOffset }
904
+ next: {
905
+ ...categoriesCursor(categories),
906
+ campaigns,
907
+ offset: page.nextOffset
908
+ }
582
909
  };
583
910
  }
584
911
  return {
585
912
  items: page.items,
586
- next: rest.length > 0 ? { campaigns: rest, categories, offset: 0 } : void 0
913
+ next: rest.length > 0 ? { ...categoriesCursor(categories), campaigns: rest, offset: 0 } : void 0
587
914
  };
588
915
  };
589
- var listLeads = async (client, ctx, query2) => {
590
- if (query2.email !== void 0 || query2.linkedinUrl !== void 0) {
591
- return await leadsByEmail(client, ctx, query2);
916
+ var listLeads = async (client, ctx, query) => {
917
+ if (query.email !== void 0 || query.linkedinUrl !== void 0) {
918
+ return await leadsByEmail(client, ctx, query);
592
919
  }
593
- if (query2.campaignId === void 0) {
594
- return await allLeads(client, ctx, query2);
920
+ if (query.campaignId === void 0) {
921
+ return await allLeads(client, ctx, query);
595
922
  }
596
- const categories = await categoryNames(client, ctx, query2.next);
923
+ const categories = await leadCategories(client, ctx, query.next);
597
924
  const page = await campaignLeads(client, ctx, {
598
- campaignId: query2.campaignId,
925
+ campaignId: query.campaignId,
599
926
  categories,
600
- limit: pageSize(query2.limit),
601
- offset: offsetOf(query2.next)
927
+ limit: pageSize(query.limit),
928
+ offset: offsetOf(query.next)
602
929
  });
603
930
  return {
604
931
  items: page.items,
605
- next: page.nextOffset === void 0 ? void 0 : { categories, offset: page.nextOffset }
932
+ next: page.nextOffset === void 0 ? void 0 : { ...categoriesCursor(categories), offset: page.nextOffset }
606
933
  };
607
934
  };
608
935
  var getLead = async (client, ctx, id) => {
@@ -619,229 +946,52 @@ var getLead = async (client, ctx, id) => {
619
946
  const tags = await client.get(ctx, "/crm/leads/tags", {
620
947
  query: { leadId: id }
621
948
  });
949
+ const categories = text(lead.category_id) === null ? NO_CATEGORIES : await leadCategories(client, ctx, void 0);
622
950
  return toLead(
623
951
  client.identity,
624
952
  lead,
625
- objects(unwrap(tags)).flatMap((tag) => text(tag.name) ?? [])
953
+ objects(unwrap(tags)).flatMap((tag) => text(tag.name) ?? []),
954
+ categories
626
955
  );
627
956
  };
628
957
 
629
- // src/smartlead/map-messages.ts
630
- var OUT_OF_OFFICE = "out of office";
631
- var SENTIMENT = /* @__PURE__ */ new Map([
632
- ["negative", "negative"],
633
- ["positive", "positive"]
634
- ]);
635
- var categoryOf = (raw) => {
636
- if (text(raw.name)?.toLowerCase() === OUT_OF_OFFICE) {
637
- return "ooo";
638
- }
639
- const sentiment = SENTIMENT.get(text(raw.sentiment_type) ?? "");
640
- if (sentiment !== void 0) {
641
- return sentiment;
642
- }
643
- return raw.sentiment_type === null ? "neutral" : void 0;
644
- };
645
- var toCategoryMap = (body2) => new Map(
646
- objects(body2).flatMap((raw) => {
647
- const id = text(raw.id);
648
- const category = categoryOf(raw);
649
- return id === null || category === void 0 ? [] : [[id, category]];
650
- })
651
- );
652
- var categoriesToJson = (categories) => Object.fromEntries(categories);
653
- var categoriesFromJson = (value) => new Map(
654
- Object.entries(isJsonObject(value) ? value : {}).flatMap(
655
- ([id, category]) => {
656
- const parsed2 = replyCategorySchema.safeParse(category);
657
- return parsed2.success ? [[id, parsed2.data]] : [];
658
- }
659
- )
660
- );
661
- var categoryIds = (categories, category) => [...categories].flatMap(([id, mapped]) => {
662
- const number = count(id);
663
- return mapped === category && number !== null ? [number] : [];
664
- });
665
- var messageFields = (identity, place, parts, includeBody) => ({
666
- ...recordBase(identity, parts.sourceId, parts.raw),
667
- ...normalizeBody(parts.body, includeBody),
668
- campaignRef: refTo(identity, place.campaignId),
669
- channel: "email",
670
- leadRef: refTo(identity, place.leadId),
671
- senderRef: refTo(identity, place.senderId),
672
- sentAt: timestamp(parts.sentAt),
673
- stepIndex: place.stepIndex ?? null,
674
- subject: parts.subject,
675
- threadId: place.threadId ?? null,
676
- variantKey: null
677
- });
678
- var stepIndex = (value) => {
679
- const number = count(value);
680
- return number === null || number < 1 ? null : number - 1;
681
- };
682
- var activityMessages = (identity, row2, activity, includeBody) => {
683
- const place = {
684
- campaignId: text(row2.campaign_id),
685
- leadId: text(row2.lead_id),
686
- stepIndex: stepIndex(activity.email_seq_number),
687
- // The lead-in-campaign mapping id is the master inbox's thread id.
688
- threadId: text(row2.email_lead_map_id)
689
- };
690
- const sent = {
691
- ...messageFields(
692
- identity,
693
- place,
694
- {
695
- body: text(activity.email_body),
696
- raw: activity,
697
- sentAt: activity.sent_time,
698
- sourceId: text(activity.stats_id) ?? "",
699
- subject: text(activity.subject)
700
- },
701
- includeBody
702
- ),
703
- direction: "out"
704
- };
705
- const reply = activity.reply_details;
706
- if (!isJsonObject(reply)) {
707
- return [sent];
708
- }
709
- return [
710
- sent,
711
- {
712
- ...messageFields(
713
- identity,
714
- place,
715
- {
716
- body: text(reply.reply_email_body),
717
- raw: reply,
718
- sentAt: reply.time,
719
- // A reply has no id of its own beyond its Message-ID header.
720
- sourceId: text(reply.message_id) ?? stableId(sent.sourceId, text(reply.time)),
721
- subject: null
722
- },
723
- includeBody
724
- ),
725
- direction: "in"
726
- }
727
- ];
728
- };
729
- var toActivityMessages = (identity, row2, includeBody) => objects(row2.activities).flatMap(
730
- (activity) => activityMessages(identity, row2, activity, includeBody)
731
- );
732
- var toHistoryMessage = (identity, place, item, includeBody) => {
733
- const isReply = text(item.type) === "REPLY";
734
- const statsId = text(item.stats_id);
735
- const messageId = text(item.message_id);
736
- return {
737
- ...messageFields(
738
- identity,
739
- place,
740
- {
741
- body: text(item.email_body),
742
- raw: item,
743
- sentAt: item.time,
744
- // A sent email is identified by its stats_id, as in the activity feed.
745
- // A reply carries the stats_id of the email it answers.
746
- sourceId: (isReply ? messageId : statsId) ?? stableId(statsId, messageId, text(item.time)),
747
- subject: text(item.subject)
748
- },
749
- includeBody
750
- ),
751
- direction: isReply ? "in" : "out"
752
- };
753
- };
754
- var isInbound = (item) => text(item.direction) === "inbound" || text(item.type) === "REPLY";
755
- var threadParts = (threadId, item) => {
756
- const inbound = isInbound(item);
757
- const time = item.sent_at ?? item.received_at ?? item.time;
758
- return {
759
- body: text(item.body) ?? text(item.email_body),
760
- raw: item,
761
- sentAt: time,
762
- sourceId: text(item.id) ?? text(inbound ? item.message_id : item.stats_id) ?? stableId(threadId, text(item.direction), text(time), text(item.subject)),
763
- subject: text(item.subject)
764
- };
765
- };
766
- var threadPlace = (thread) => ({
767
- campaignId: text(field(thread.campaign, "id")),
768
- leadId: text(field(thread.lead, "id")) ?? text(thread.lead_id),
769
- senderId: text(field(thread.email_account, "id")),
770
- threadId: text(thread.campaign_lead_map_id)
771
- });
772
- var toThreadMessages = (identity, thread, includeBody) => {
773
- const place = threadPlace(thread);
774
- return objects(thread.message_history).map((item) => ({
775
- ...messageFields(
776
- identity,
777
- place,
778
- threadParts(place.threadId ?? null, item),
779
- includeBody
780
- ),
781
- direction: isInbound(item) ? "in" : "out"
782
- }));
783
- };
784
- var toInboxReplies = (identity, item, categories, includeBody) => {
785
- const last = item.last_message;
786
- const category = categories.get(text(field(item.category, "id")) ?? "");
787
- const place = threadPlace(item);
788
- const history = objects(item.message_history).filter(isInbound);
789
- const parts = history.length > 0 ? history.map((message) => threadParts(place.threadId ?? null, message)) : [
790
- {
791
- body: text(field(last, "body")),
792
- raw: item,
793
- sentAt: field(last, "received_at"),
794
- sourceId: text(field(last, "id")) ?? text(item.id) ?? "",
795
- subject: text(field(last, "subject"))
796
- }
797
- ];
798
- return parts.map((part) => ({
799
- ...messageFields(identity, place, part, includeBody),
800
- category: category ?? "unknown",
801
- categorySource: category === void 0 ? null : "vendor",
802
- direction: "in",
803
- // Smartlead's only automatic-reply signal is the Out Of Office category.
804
- isAuto: category === "ooo" ? true : null
805
- }));
806
- };
807
-
808
958
  // src/smartlead/mail.ts
809
959
  var DAY_MS = 864e5;
810
960
  var MAX_CATEGORY_IDS = 10;
811
961
  var EPOCH = "1970-01-01T00:00:00.000Z";
812
- var listActivities = async (client, ctx, query2) => {
813
- const offset = count(query2.next) ?? 0;
814
- const body2 = await client.get(ctx, "/campaigns/all-leads-activities", {
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", {
815
965
  lane: ACTIVITIES_LANE,
816
966
  query: {
817
967
  // Narrows the feed to leads with activity since then. `event_time_to`
818
968
  // is not sent: a lead active after the end could drop out of the feed.
819
- event_time_from: query2.since,
969
+ event_time_from: query.since,
820
970
  limit: Math.min(
821
- query2.limit ?? ACTIVITIES_PAGE_SIZE,
971
+ query.limit ?? ACTIVITIES_PAGE_SIZE,
822
972
  ACTIVITIES_MAX_PAGE_SIZE
823
973
  ),
824
974
  offset
825
975
  }
826
976
  });
827
- const rows = objects(field(body2, "data"));
828
- const more = flag(field(body2, "hasMore")) === true && rows.length > 0;
977
+ const rows = objects(field(body, "data"));
978
+ const more = flag(field(body, "hasMore")) === true && rows.length > 0;
829
979
  return {
830
980
  // The feed has no campaign filter, so one campaign's rows are picked here.
831
981
  items: rows.filter(
832
- (row2) => query2.campaignId === void 0 || text(row2.campaign_id) === query2.campaignId
982
+ (row) => query.campaignId === void 0 || text(row.campaign_id) === query.campaignId
833
983
  ).flatMap(
834
- (row2) => toActivityMessages(client.identity, row2, query2.includeBody)
984
+ (row) => toActivityMessages(client.identity, row, query.includeBody)
835
985
  ),
836
986
  next: more ? offset + rows.length : void 0
837
987
  };
838
988
  };
839
- var leadCampaigns = async (client, ctx, query2, leadId) => {
840
- if (isJsonObject(query2.next)) {
841
- return idList(query2.next.campaigns);
989
+ var leadCampaigns = async (client, ctx, query, leadId) => {
990
+ if (isJsonObject(query.next)) {
991
+ return idList(query.next.campaigns);
842
992
  }
843
- if (query2.campaignId !== void 0) {
844
- return [query2.campaignId];
993
+ if (query.campaignId !== void 0) {
994
+ return [query.campaignId];
845
995
  }
846
996
  const campaigns = await client.get(
847
997
  ctx,
@@ -851,16 +1001,16 @@ var leadCampaigns = async (client, ctx, query2, leadId) => {
851
1001
  (campaign) => text(campaign.id) ?? []
852
1002
  );
853
1003
  };
854
- var listHistory = async (client, ctx, query2, leadId) => {
855
- const [campaignId, ...rest] = await leadCampaigns(client, ctx, query2, leadId);
1004
+ var listHistory = async (client, ctx, query, leadId) => {
1005
+ const [campaignId, ...rest] = await leadCampaigns(client, ctx, query, leadId);
856
1006
  if (campaignId === void 0) {
857
1007
  return { items: [] };
858
1008
  }
859
- const body2 = await client.get(
1009
+ const body = await client.get(
860
1010
  ctx,
861
1011
  `/campaigns/${encodeURIComponent(campaignId)}/leads/${encodeURIComponent(leadId)}/message-history`
862
1012
  );
863
- const history = field(unwrap(body2), "history");
1013
+ const history = field(unwrap(body), "history");
864
1014
  if (!isJsonArray(history)) {
865
1015
  throw new OutboundError(
866
1016
  "Provider",
@@ -874,13 +1024,13 @@ var listHistory = async (client, ctx, query2, leadId) => {
874
1024
  client.identity,
875
1025
  { campaignId, leadId },
876
1026
  item,
877
- query2.includeBody
1027
+ query.includeBody
878
1028
  )
879
1029
  ),
880
1030
  next: rest.length > 0 ? { campaigns: rest } : void 0
881
1031
  };
882
1032
  };
883
- var listThread = async (client, ctx, query2, threadId) => ({
1033
+ var listThread = async (client, ctx, query, threadId) => ({
884
1034
  items: toThreadMessages(
885
1035
  client.identity,
886
1036
  {
@@ -892,81 +1042,68 @@ var listThread = async (client, ctx, query2, threadId) => ({
892
1042
  // The path id is the thread id, whatever the body says.
893
1043
  campaign_lead_map_id: threadId
894
1044
  },
895
- query2.includeBody
1045
+ query.includeBody
896
1046
  )
897
1047
  });
898
- var listMessages = (client, ctx, query2) => {
899
- if (query2.threadId !== void 0) {
900
- return listThread(client, ctx, query2, query2.threadId);
1048
+ var listMessages = (client, ctx, query) => {
1049
+ if (query.threadId !== void 0) {
1050
+ return listThread(client, ctx, query, query.threadId);
901
1051
  }
902
- return query2.leadId === void 0 ? listActivities(client, ctx, query2) : listHistory(client, ctx, query2, query2.leadId);
1052
+ return query.leadId === void 0 ? listActivities(client, ctx, query) : listHistory(client, ctx, query, query.leadId);
903
1053
  };
904
1054
  var readCategories = async (client, ctx, next) => isJsonObject(next) ? categoriesFromJson(next.categories) : toCategoryMap(unwrap(await client.get(ctx, "/leads/fetch-categories")));
905
- var inboxFilters = (query2, wanted) => {
1055
+ var inboxFilters = (query, wanted) => {
906
1056
  const filters2 = {};
907
- if (query2.campaignId !== void 0) {
908
- filters2.campaignId = count(query2.campaignId) ?? query2.campaignId;
1057
+ if (query.campaignId !== void 0) {
1058
+ filters2.campaignId = count(query.campaignId) ?? query.campaignId;
909
1059
  }
910
1060
  if (wanted.length > 0 && wanted.length <= MAX_CATEGORY_IDS) {
911
1061
  filters2.leadCategories = { categoryIdsIn: wanted };
912
1062
  }
913
- if (query2.since !== void 0 || query2.until !== void 0) {
1063
+ if (query.since !== void 0 || query.until !== void 0) {
914
1064
  filters2.replyTimeBetween = [
915
- query2.since ?? EPOCH,
916
- query2.until ?? new Date(Date.now() + DAY_MS).toISOString()
1065
+ query.since ?? EPOCH,
1066
+ query.until ?? new Date(Date.now() + DAY_MS).toISOString()
917
1067
  ];
918
1068
  }
919
1069
  return filters2;
920
1070
  };
921
- var listReplies = async (client, ctx, query2) => {
922
- const categories = await readCategories(client, ctx, query2.next);
923
- const wanted = query2.category === void 0 ? [] : categoryIds(categories, query2.category);
924
- if (query2.category !== void 0 && query2.category !== "unknown" && wanted.length === 0) {
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) {
925
1075
  return { items: [] };
926
1076
  }
927
- const offset = count(field(query2.next, "offset")) ?? 0;
928
- const limit = Math.min(query2.limit ?? INBOX_PAGE_SIZE, INBOX_PAGE_SIZE);
929
- const body2 = await client.post(
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(
930
1080
  ctx,
931
1081
  "/master-inbox/inbox-replies",
932
- { filters: inboxFilters(query2, wanted), limit, offset },
1082
+ { filters: inboxFilters(query, wanted), limit, offset },
933
1083
  // Without it a thread carries only its latest reply.
934
1084
  { query: { fetch_message_history: true } }
935
1085
  );
936
- const threads = objects(field(unwrap(body2), "messages"));
937
- const total = count(field(unwrap(body2), "total_count"));
1086
+ const threads = objects(field(unwrap(body), "messages"));
1087
+ const total = count(field(unwrap(body), "total_count"));
938
1088
  const end = offset + threads.length;
939
1089
  const more = threads.length > 0 && (total === null ? threads.length === limit : end < total);
940
1090
  const replies = threads.flatMap(
941
- (thread) => toInboxReplies(client.identity, thread, categories, query2.includeBody)
1091
+ (thread) => toInboxReplies(client.identity, thread, categories, query.includeBody)
942
1092
  );
943
1093
  return {
944
1094
  // The id filter only narrows; the category is matched on the mapped value.
945
- items: query2.category === void 0 ? replies : replies.filter((reply) => reply.category === query2.category),
1095
+ items: query.category === void 0 ? replies : replies.filter((reply) => reply.category === query.category),
946
1096
  next: more ? { categories: categoriesToJson(categories), offset: end } : void 0
947
1097
  };
948
1098
  };
949
1099
 
950
1100
  // src/smartlead/map-stats.ts
951
1101
  var TIMEZONE = "UTC";
952
- var row = (scope, counts, extra = {}) => ({
953
- ...counts,
954
- contentHash: null,
955
- date: extra.date ?? null,
956
- evidence: "exact",
957
- provider: scope.provider,
958
- schemaVersion: SCHEMA_VERSION,
959
- scope: scope.scope,
960
- scopeRef: makeRef(scope.provider, scope.workspaceId, scope.scopeId),
961
- stepIndex: extra.stepIndex ?? null,
962
- timezone: extra.timezone ?? null,
963
- variantKey: extra.variantKey ?? null,
964
- workspaceId: scope.workspaceId
965
- });
966
1102
  var campaignCounts = (raw) => ({
967
1103
  ...emptyCounts(),
968
1104
  bounced: count(raw.bounce_count),
969
1105
  clicked: count(raw.unique_click_count),
1106
+ clickedTotal: count(raw.click_count),
970
1107
  contacted: count(raw.unique_sent_count),
971
1108
  opened: count(raw.unique_open_count),
972
1109
  openedTotal: count(raw.open_count),
@@ -974,19 +1111,25 @@ var campaignCounts = (raw) => ({
974
1111
  sent: count(raw.sent_count),
975
1112
  unsubscribed: count(raw.unsubscribed_count)
976
1113
  });
977
- var lifetimeRow = (scope, raw) => row(scope, {
1114
+ var lifetimeRow = (scope, raw) => metricRow(scope, {
978
1115
  ...campaignCounts(raw),
979
1116
  positive: count(field(raw.campaign_lead_stats, "interested"))
980
1117
  });
981
- var windowRow = (scope, raw) => row(
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(
982
1124
  scope,
983
1125
  {
984
1126
  ...campaignCounts(raw),
985
- replied: count(raw.non_ooo_reply_count) ?? count(raw.reply_count)
1127
+ replied: count(raw.non_ooo_reply_count) ?? count(raw.reply_count),
1128
+ repliedAuto: outOfOffice(raw)
986
1129
  },
987
1130
  { timezone: TIMEZONE }
988
1131
  );
989
- var overallRow = (scope, raw) => row(
1132
+ var overallRow = (scope, raw) => metricRow(
990
1133
  scope,
991
1134
  {
992
1135
  ...emptyCounts(),
@@ -1000,17 +1143,18 @@ var overallRow = (scope, raw) => row(
1000
1143
  },
1001
1144
  { timezone: TIMEZONE }
1002
1145
  );
1003
- var dayRow = (scope, raw) => row(
1146
+ var dayRow = (scope, raw, positive) => metricRow(
1004
1147
  scope,
1005
1148
  {
1006
1149
  ...emptyCounts(),
1007
1150
  openedTotal: count(raw.opened),
1151
+ positive: count(positive),
1008
1152
  replied: count(raw.replied),
1009
1153
  sent: count(raw.sent)
1010
1154
  },
1011
1155
  { date: text(raw.date), timezone: TIMEZONE }
1012
1156
  );
1013
- var mailboxRow = (scope, raw) => row(
1157
+ var mailboxRow = (scope, raw) => metricRow(
1014
1158
  scope,
1015
1159
  {
1016
1160
  ...emptyCounts(),
@@ -1024,7 +1168,9 @@ var mailboxRow = (scope, raw) => row(
1024
1168
  var stepCounts = (stats) => ({
1025
1169
  ...emptyCounts(),
1026
1170
  bounced: count(field(stats, "bounce_count")),
1027
- clicked: count(field(stats, "click_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")),
1028
1174
  openedTotal: count(field(stats, "open_count")),
1029
1175
  positive: count(field(stats, "positive_reply_count")),
1030
1176
  replied: count(field(stats, "reply_count")),
@@ -1032,20 +1178,19 @@ var stepCounts = (stats) => ({
1032
1178
  unsubscribed: count(field(stats, "unsubscribed_count"))
1033
1179
  });
1034
1180
  var stepRows = (scope, step) => {
1035
- const number = count(step.seq_number);
1036
- const stepIndex2 = number === null || number < 1 ? null : number - 1;
1181
+ const stepIndex = fromOne(step.seq_number);
1037
1182
  const variants = objects(step.variants);
1038
1183
  if (variants.length === 0) {
1039
1184
  return [
1040
- row(scope, stepCounts(step.total_stats), {
1041
- stepIndex: stepIndex2,
1185
+ metricRow(scope, stepCounts(step.total_stats), {
1186
+ stepIndex,
1042
1187
  timezone: TIMEZONE
1043
1188
  })
1044
1189
  ];
1045
1190
  }
1046
1191
  return variants.map(
1047
- (variant) => row(scope, stepCounts(variant.stats), {
1048
- stepIndex: stepIndex2,
1192
+ (variant) => metricRow(scope, stepCounts(variant.stats), {
1193
+ stepIndex,
1049
1194
  timezone: TIMEZONE,
1050
1195
  variantKey: text(variant.variant_label)
1051
1196
  })
@@ -1058,10 +1203,10 @@ var LIFETIME_START = "2000-01-01";
1058
1203
  var MAX_WINDOW_DAYS = 30;
1059
1204
  var dayOf = (time) => new Date(time).toISOString().slice(0, 10);
1060
1205
  var timeOf = (day) => Date.parse(`${day}T00:00:00.000Z`);
1061
- var resolveRange = (query2, recent) => {
1062
- const to = query2.to ?? dayOf(Date.now());
1206
+ var resolveRange = (query, recent) => {
1207
+ const to = query.to ?? dayOf(Date.now());
1063
1208
  const fallback = recent ? dayOf(timeOf(to) - MAX_WINDOW_DAYS * DAY_MS2) : LIFETIME_START;
1064
- return { from: query2.from ?? fallback, to };
1209
+ return { from: query.from ?? fallback, to };
1065
1210
  };
1066
1211
  var invalid = (client, message) => new OutboundError("Invalid", message, {
1067
1212
  provider: client.identity.provider
@@ -1069,24 +1214,15 @@ var invalid = (client, message) => new OutboundError("Invalid", message, {
1069
1214
  var unsupported = (client, message) => new OutboundError("Unsupported", message, {
1070
1215
  provider: client.identity.provider
1071
1216
  });
1072
- var dataOf = (client, body2, what) => {
1073
- const data = unwrap(body2);
1074
- if (!isJsonObject(data)) {
1075
- throw new OutboundError(
1076
- "Provider",
1077
- `Smartlead returned no object for ${what}`,
1078
- { provider: client.identity.provider }
1079
- );
1080
- }
1081
- return data;
1082
- };
1083
1217
  var campaignPath = (scope, leaf) => `/campaigns/${encodeURIComponent(scope.scopeId)}/${leaf}`;
1084
- var campaignTotal = async (client, ctx, scope, query2) => {
1085
- if (query2.from === void 0 && query2.to === void 0) {
1218
+ var campaignTotal = async (client, ctx, scope, query) => {
1219
+ if (query.from === void 0 && query.to === void 0) {
1086
1220
  const lifetime = await client.get(ctx, campaignPath(scope, "analytics"));
1087
- return [lifetimeRow(scope, dataOf(client, lifetime, "campaign analytics"))];
1221
+ return [
1222
+ lifetimeRow(scope, objectOf(client, lifetime, "campaign analytics"))
1223
+ ];
1088
1224
  }
1089
- const range = resolveRange(query2, true);
1225
+ const range = resolveRange(query, true);
1090
1226
  if (timeOf(range.to) - timeOf(range.from) > MAX_WINDOW_DAYS * DAY_MS2) {
1091
1227
  throw invalid(
1092
1228
  client,
@@ -1104,33 +1240,67 @@ var campaignTotal = async (client, ctx, scope, query2) => {
1104
1240
  }
1105
1241
  }
1106
1242
  );
1107
- return [windowRow(scope, dataOf(client, window, "campaign analytics"))];
1243
+ return [windowRow(scope, objectOf(client, window, "campaign analytics"))];
1108
1244
  };
1109
- var dailyRows = async (client, ctx, scope, query2) => {
1110
- const range = resolveRange(query2, true);
1111
- const body2 = await client.get(ctx, "/analytics/day-wise-overall-stats", {
1245
+ var dailyRows = async (client, ctx, scope, query) => {
1246
+ const range = resolveRange(query, true);
1247
+ const request = {
1112
1248
  query: {
1113
1249
  campaign_ids: scope.scope === "campaign" ? scope.scopeId : void 0,
1114
1250
  end_date: range.to,
1115
1251
  start_date: range.from,
1116
1252
  timezone: TIMEZONE
1117
1253
  }
1118
- });
1119
- return objects(field(unwrap(body2), "day_wise_stats")).map(
1120
- (day) => dayRow(scope, day)
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)))
1121
1267
  );
1122
1268
  };
1123
- var workspaceTotal = async (client, ctx, scope, query2) => {
1124
- const range = resolveRange(query2, false);
1125
- const body2 = await client.get(ctx, "/analytics/overall-stats-v2", {
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", {
1126
1272
  query: { end_date: range.to, start_date: range.from, timezone: TIMEZONE }
1127
1273
  });
1128
- const stats = field(dataOf(client, body2, "overall stats"), "overall_stats");
1274
+ const stats = field(objectOf(client, body, "overall stats"), "overall_stats");
1129
1275
  return [overallRow(scope, isJsonObject(stats) ? stats : {})];
1130
1276
  };
1131
- var stepTotals = async (client, ctx, scope, query2) => {
1132
- const range = resolveRange(query2, false);
1133
- const body2 = await client.get(
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(
1134
1304
  ctx,
1135
1305
  campaignPath(scope, "sequence-analytics"),
1136
1306
  {
@@ -1141,12 +1311,12 @@ var stepTotals = async (client, ctx, scope, query2) => {
1141
1311
  }
1142
1312
  }
1143
1313
  );
1144
- return objects(field(unwrap(body2), "sequences")).flatMap(
1314
+ return objects(field(unwrap(body), "sequences")).flatMap(
1145
1315
  (step) => stepRows(scope, step)
1146
1316
  );
1147
1317
  };
1148
- var senderTotal = async (client, ctx, scope, query2) => {
1149
- const account = dataOf(
1318
+ var senderTotal = async (client, ctx, scope, query) => {
1319
+ const account = objectOf(
1150
1320
  client,
1151
1321
  await client.get(
1152
1322
  ctx,
@@ -1155,8 +1325,8 @@ var senderTotal = async (client, ctx, scope, query2) => {
1155
1325
  "the email account"
1156
1326
  );
1157
1327
  const address = emailAddress(account.from_email);
1158
- const range = resolveRange(query2, false);
1159
- const body2 = await client.get(
1328
+ const range = resolveRange(query, false);
1329
+ const body = await client.get(
1160
1330
  ctx,
1161
1331
  "/analytics/mailbox/name-wise-health-metrics",
1162
1332
  {
@@ -1166,39 +1336,48 @@ var senderTotal = async (client, ctx, scope, query2) => {
1166
1336
  return [
1167
1337
  mailboxRow(
1168
1338
  scope,
1169
- objects(field(unwrap(body2), "email_health_metrics")).find(
1339
+ objects(field(unwrap(body), "email_health_metrics")).find(
1170
1340
  (metrics) => address !== null && emailAddress(metrics.email_account) === address
1171
1341
  )
1172
1342
  )
1173
1343
  ];
1174
1344
  };
1175
- var readStats = async (client, ctx, query2) => {
1345
+ var readStats = async (client, ctx, query) => {
1176
1346
  const scope = {
1177
1347
  ...client.identity,
1178
- scope: query2.scope,
1179
- scopeId: query2.scopeId ?? client.identity.workspaceId
1348
+ scope: query.scope,
1349
+ scopeId: query.scopeId ?? client.identity.workspaceId
1180
1350
  };
1181
- if (query2.scope === "sender" || query2.scope === "step") {
1182
- if (query2.by === "day") {
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") {
1183
1362
  throw unsupported(
1184
1363
  client,
1185
1364
  "Smartlead reports step and mailbox analytics as totals only"
1186
1365
  );
1187
1366
  }
1188
- return query2.scope === "step" ? await stepTotals(client, ctx, scope, query2) : await senderTotal(client, ctx, scope, query2);
1367
+ return query.scope === "step" ? await stepTotals(client, ctx, scope, query) : await senderTotal(client, ctx, scope, query);
1189
1368
  }
1190
- if (query2.by === "day") {
1191
- return await dailyRows(client, ctx, scope, query2);
1369
+ if (query.by === "day") {
1370
+ return await dailyRows(client, ctx, scope, query);
1192
1371
  }
1193
- return query2.scope === "campaign" ? await campaignTotal(client, ctx, scope, query2) : await workspaceTotal(client, ctx, scope, query2);
1372
+ return query.scope === "campaign" ? await campaignTotal(client, ctx, scope, query) : await workspaceTotal(client, ctx, scope, query);
1194
1373
  };
1195
1374
 
1196
1375
  // src/smartlead/adapter.ts
1197
- var listSenders = async (client, ctx, query2) => {
1198
- if (query2.campaignId !== void 0) {
1376
+ var listSenders = async (client, ctx, query) => {
1377
+ if (query.campaignId !== void 0) {
1199
1378
  const attached = await client.get(
1200
1379
  ctx,
1201
- `/campaigns/${segment(query2.campaignId)}/email-accounts`
1380
+ `/campaigns/${segment(query.campaignId)}/email-accounts`
1202
1381
  );
1203
1382
  return {
1204
1383
  items: objects(unwrap(attached)).map(
@@ -1207,13 +1386,10 @@ var listSenders = async (client, ctx, query2) => {
1207
1386
  };
1208
1387
  }
1209
1388
  const page = await offsetPage(client, ctx, "/email-accounts/", {
1210
- limit: pageSize(query2.limit),
1211
- offset: count(query2.next) ?? 0
1389
+ limit: pageSize(query.limit),
1390
+ offset: count(query.next) ?? 0
1212
1391
  });
1213
- return {
1214
- items: page.rows.map((account) => toSender(client.identity, account)),
1215
- next: page.next
1216
- };
1392
+ return mapPage(page, (account) => toSender(client.identity, account));
1217
1393
  };
1218
1394
  var readers = (client) => {
1219
1395
  const { identity } = client;
@@ -1244,22 +1420,34 @@ var readers = (client) => {
1244
1420
  id,
1245
1421
  await client.get(ctx, `/campaigns/${segment(id)}/sequences`)
1246
1422
  ),
1247
- listCampaigns: async (_query, ctx) => {
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
+ );
1248
1434
  const campaigns = await campaignList(client, ctx);
1249
1435
  return {
1250
- items: campaigns.map((campaign) => toCampaign(identity, campaign))
1436
+ items: campaigns.filter(
1437
+ (campaign) => attached === void 0 || attached.includes(text(campaign.id) ?? "")
1438
+ ).map((campaign) => toCampaign(identity, campaign))
1251
1439
  };
1252
1440
  },
1253
- listLeads: (query2, ctx) => listLeads(client, ctx, query2),
1254
- listMessages: (query2, ctx) => listMessages(client, ctx, query2),
1255
- listReplies: (query2, ctx) => listReplies(client, ctx, query2),
1256
- listSenders: (query2, ctx) => listSenders(client, ctx, query2),
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),
1257
1445
  listWorkspaces: async (_query, ctx) => ({
1258
1446
  items: objects(unwrap(await client.get(ctx, "/client/"))).map(
1259
1447
  (raw) => toWorkspace(identity, raw)
1260
1448
  )
1261
1449
  }),
1262
- stats: (query2, ctx) => readStats(client, ctx, query2)
1450
+ stats: (query, ctx) => readStats(client, ctx, query)
1263
1451
  };
1264
1452
  };
1265
1453
 
@@ -1269,54 +1457,40 @@ var DELIVERY_URL = "https://smartdelivery.smartlead.ai/api/v1";
1269
1457
  var PROSPECT_URL = "https://prospect-api.smartlead.ai/api/v1";
1270
1458
  var SENDERS_URL = "https://smart-senders.smartlead.ai/api/v1";
1271
1459
  var SERVERS_URL = "https://smartservers.smartlead.ai/api/v1";
1272
- var query = (type, description) => ({ description, in: "query", type });
1273
- var queryRequired = (type, description) => ({
1274
- description,
1275
- in: "query",
1276
- required: true,
1277
- type
1278
- });
1279
- var body = (type, description) => ({ description, in: "body", type });
1280
- var bodyRequired = (type, description) => ({ description, in: "body", required: true, type });
1281
- var path = (description) => ({
1282
- description,
1283
- in: "path",
1284
- type: "string"
1285
- });
1286
1460
  var paged = (limit) => ({
1287
- limit: query("number", limit),
1288
- offset: query("number", "Rows to skip.")
1461
+ limit: inQuery("number", limit),
1462
+ offset: inQuery("number", "Rows to skip.")
1289
1463
  });
1290
1464
 
1291
1465
  // src/smartlead/native-analytics.ts
1292
1466
  var CLIENTS = {
1293
- client_ids: query("string", "Only these clients: ids separated by commas.")
1467
+ client_ids: inQuery("string", "Only these clients: ids separated by commas.")
1294
1468
  };
1295
1469
  var SCOPE = {
1296
1470
  ...CLIENTS,
1297
- campaign_ids: query(
1471
+ campaign_ids: inQuery(
1298
1472
  "string",
1299
1473
  "Only these campaigns: ids separated by commas."
1300
1474
  )
1301
1475
  };
1302
1476
  var WINDOW = {
1303
- end_date: queryRequired("string", "Last day, YYYY-MM-DD."),
1304
- start_date: queryRequired("string", "First day, YYYY-MM-DD."),
1305
- timezone: query("string", "IANA time zone, for example America/New_York.")
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.")
1306
1480
  };
1307
1481
  var ZONED_WINDOW = {
1308
1482
  ...WINDOW,
1309
- timezone: queryRequired(
1483
+ timezone: inQueryRequired(
1310
1484
  "string",
1311
1485
  "IANA time zone, for example America/New_York."
1312
1486
  )
1313
1487
  };
1314
1488
  var FULL = {
1315
- full_data: query("string", 'Set to "true" for the full data set.')
1489
+ full_data: inQuery("string", 'Set to "true" for the full data set.')
1316
1490
  };
1317
1491
  var PAGE = {
1318
- limit: query("string", "Most rows to return."),
1319
- offset: query("string", "Rows to skip.")
1492
+ limit: inQuery("string", "Most rows to return."),
1493
+ offset: inQuery("string", "Rows to skip.")
1320
1494
  };
1321
1495
  var ANALYTICS = defineNative({
1322
1496
  analyticsCampaignFollowUpReplyRate: {
@@ -1391,7 +1565,7 @@ var ANALYTICS = defineNative({
1391
1565
  ...CLIENTS,
1392
1566
  ...PAGE,
1393
1567
  ...FULL,
1394
- filter: query("string", "Filter value for the client rows.")
1568
+ filter: inQuery("string", "Filter value for the client rows.")
1395
1569
  },
1396
1570
  path: "/analytics/client/overall-stats"
1397
1571
  },
@@ -1462,7 +1636,7 @@ var ANALYTICS = defineNative({
1462
1636
  });
1463
1637
 
1464
1638
  // src/smartlead/native-campaigns.ts
1465
- var CAMPAIGN = { campaign_id: path("The campaign's id.") };
1639
+ var CAMPAIGN = { campaign_id: inPath("The campaign's id.") };
1466
1640
  var CAMPAIGN_READS = defineNative({
1467
1641
  campaignEmailStatistics: {
1468
1642
  description: "One row per email a campaign sent: the lead, the step, and when it was sent, opened, clicked, replied to or bounced.",
@@ -1471,16 +1645,16 @@ var CAMPAIGN_READS = defineNative({
1471
1645
  params: {
1472
1646
  ...CAMPAIGN,
1473
1647
  ...paged("Rows per page, at most 1000."),
1474
- email_sequence_number: query("number", "Only this step, 1 to 20."),
1475
- email_status: query(
1648
+ email_sequence_number: inQuery("number", "Only this step, 1 to 20."),
1649
+ email_status: inQuery(
1476
1650
  "string",
1477
1651
  "opened, clicked, replied, unsubscribed or bounced."
1478
1652
  ),
1479
- sent_time_end_date: query(
1653
+ sent_time_end_date: inQuery(
1480
1654
  "string",
1481
1655
  "Sent before this time, as 2023-10-16 10:33:02.000Z."
1482
1656
  ),
1483
- sent_time_start_date: query(
1657
+ sent_time_start_date: inQuery(
1484
1658
  "string",
1485
1659
  "Sent after this time, as 2023-10-16 10:33:02.000Z."
1486
1660
  )
@@ -1492,55 +1666,55 @@ var CAMPAIGN_READS = defineNative({
1492
1666
  docs: `${DOCS}/campaigns/search-leads`,
1493
1667
  method: "POST",
1494
1668
  params: {
1495
- campaignId: path("The campaign's id."),
1496
- deletedEmailAddresses: body("json", "Email addresses, as an array."),
1497
- emailAccountIds: body("json", "Mailbox ids the leads are assigned to."),
1498
- emailStatuses: body(
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(
1499
1673
  "json",
1500
1674
  "Array of is_opened, is_clicked, is_bounced, is_replied, is_unsubscribed, is_accepted, not_replied and the like."
1501
1675
  ),
1502
- espDomainTypes: body("json", "ESP domain types, integers 0 to 2."),
1503
- fieldSet: body(
1676
+ espDomainTypes: inBody("json", "ESP domain types, integers 0 to 2."),
1677
+ fieldSet: inBody(
1504
1678
  "string",
1505
1679
  "drafted_table (compact) or active_table (full)."
1506
1680
  ),
1507
- filterLeadsForManualCompletion: body(
1681
+ filterLeadsForManualCompletion: inBody(
1508
1682
  "boolean",
1509
1683
  "Only leads waiting on a manual step."
1510
1684
  ),
1511
- filterManualSeqIds: body(
1685
+ filterManualSeqIds: inBody(
1512
1686
  "json",
1513
1687
  "Manual step ids, with filterLeadsForManualCompletion."
1514
1688
  ),
1515
- includeSenderBounce: body("boolean", "Include sender-bounced leads."),
1516
- lastSeenLeadId: body(
1689
+ includeSenderBounce: inBody("boolean", "Include sender-bounced leads."),
1690
+ lastSeenLeadId: inBody(
1517
1691
  "number",
1518
1692
  "Cursor: lastSeenEclmId from the previous page."
1519
1693
  ),
1520
- lastSeenReplyTime: body(
1694
+ lastSeenReplyTime: inBody(
1521
1695
  "string",
1522
1696
  "Second half of the cursor for active_table with statusFilter replied."
1523
1697
  ),
1524
- leadCategoryIds: body(
1698
+ leadCategoryIds: inBody(
1525
1699
  "json",
1526
1700
  "Lead category ids; -1 also matches leads with none."
1527
1701
  ),
1528
- leadCategoryIsNull: body("boolean", "Only leads with no category."),
1529
- leadStatuses: body(
1702
+ leadCategoryIsNull: inBody("boolean", "Only leads with no category."),
1703
+ leadStatuses: inBody(
1530
1704
  "json",
1531
1705
  "Array of STARTED, INPROGRESS, COMPLETED, STOPPED, PAUSED, BLOCKED."
1532
1706
  ),
1533
- limit: body("number", "Leads per page, 1 to 100."),
1534
- searchText: body(
1707
+ limit: inBody("number", "Leads per page, 1 to 100."),
1708
+ searchText: inBody(
1535
1709
  "string",
1536
1710
  "Every word must match the email, first name or last name."
1537
1711
  ),
1538
- segTypes: body("json", "Segment types, integers 0 to 10."),
1539
- seqScheduleType: body("string", "MANUAL or AUTO."),
1540
- seqVariantIds: body("json", "Step variant ids."),
1541
- sequenceIds: body("json", "Step ids."),
1542
- sequenceNumbers: body("json", "Step numbers, 1 to 999."),
1543
- statusFilter: body(
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(
1544
1718
  "string",
1545
1719
  "A status tab: all, active, replied, failed, scheduled and the like."
1546
1720
  )
@@ -1555,7 +1729,7 @@ var CAMPAIGN_READS = defineNative({
1555
1729
  params: {
1556
1730
  ...CAMPAIGN,
1557
1731
  ...paged("Leads per page, at most 100."),
1558
- event_time_gt: query(
1732
+ event_time_gt: inQuery(
1559
1733
  "string",
1560
1734
  "Only leads whose last event is after this day, YYYY-MM-DD."
1561
1735
  )
@@ -1576,10 +1750,10 @@ var CAMPAIGN_READS = defineNative({
1576
1750
  params: {
1577
1751
  ...CAMPAIGN,
1578
1752
  ...paged("Rows per page, 1 to 20."),
1579
- client_id: query("number", "The client, for a client's campaign."),
1580
- end_date: query("string", "Last day, YYYY-MM-DD; needs start_date."),
1581
- start_date: query("string", "First day, YYYY-MM-DD; needs end_date."),
1582
- time_zone: query("string", "The campaign's IANA time zone.")
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.")
1583
1757
  },
1584
1758
  path: "/campaigns/{campaign_id}/mailbox-statistics"
1585
1759
  },
@@ -1589,8 +1763,8 @@ var CAMPAIGN_READS = defineNative({
1589
1763
  method: "POST",
1590
1764
  params: {
1591
1765
  ...CAMPAIGN,
1592
- event_time_gt: query("string", "Only messages after this time."),
1593
- lead_ids: body("json", "Lead ids, as an array; null for every lead.")
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.")
1594
1768
  },
1595
1769
  path: "/campaigns/{campaign_id}/message-history-for-leads/bbfbdsFGHlBr76ruhjvh6fhHL"
1596
1770
  },
@@ -1607,8 +1781,8 @@ var CAMPAIGN_READS = defineNative({
1607
1781
  method: "GET",
1608
1782
  params: {
1609
1783
  ...CAMPAIGN,
1610
- end_date: queryRequired("string", "Last day, YYYY-MM-DD."),
1611
- start_date: queryRequired("string", "First day, YYYY-MM-DD.")
1784
+ end_date: inQueryRequired("string", "Last day, YYYY-MM-DD."),
1785
+ start_date: inQueryRequired("string", "First day, YYYY-MM-DD.")
1612
1786
  },
1613
1787
  path: "/campaigns/{campaign_id}/top-level-analytics-by-date"
1614
1788
  },
@@ -1617,9 +1791,9 @@ var CAMPAIGN_READS = defineNative({
1617
1791
  docs: `${DOCS}/campaigns/get-webhook-summary`,
1618
1792
  method: "GET",
1619
1793
  params: {
1620
- campaignId: path("The campaign's id."),
1621
- fromTime: queryRequired("string", "Start, as an ISO 8601 time."),
1622
- toTime: queryRequired("string", "End, as an ISO 8601 time.")
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.")
1623
1797
  },
1624
1798
  path: "/campaigns/{campaignId}/webhooks/summary"
1625
1799
  },
@@ -1628,10 +1802,10 @@ var CAMPAIGN_READS = defineNative({
1628
1802
  docs: `${DOCS}/clients/get-by-id`,
1629
1803
  method: "GET",
1630
1804
  params: {
1631
- id: path("The client's id."),
1632
- includeCodeIntegrations: query("boolean", "Add the code snippets."),
1633
- includeCredits: query("boolean", "Add lead and email credits."),
1634
- includePermissions: query("boolean", "Add the client's permissions.")
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.")
1635
1809
  },
1636
1810
  path: "/client/{id}"
1637
1811
  },
@@ -1639,28 +1813,28 @@ var CAMPAIGN_READS = defineNative({
1639
1813
  description: "The lead with an email address and every campaign it is in. An unknown address returns an empty object.",
1640
1814
  docs: `${DOCS}/leads/get-by-email`,
1641
1815
  method: "GET",
1642
- params: { email: queryRequired("string", "The lead's email address.") },
1816
+ params: { email: inQueryRequired("string", "The lead's email address.") },
1643
1817
  path: "/leads/"
1644
1818
  },
1645
1819
  leadCampaignOverview: {
1646
1820
  description: "A lead's status, category, revenue and current step in each of its campaigns. Refuses client-level keys.",
1647
1821
  docs: `${DOCS}/leads/campaign-overview`,
1648
1822
  method: "GET",
1649
- params: { leadId: path("The lead's id.") },
1823
+ params: { leadId: inPath("The lead's id.") },
1650
1824
  path: "/leads/{leadId}/campaign-overview"
1651
1825
  },
1652
1826
  leadList: {
1653
1827
  description: "One lead list: its name, lead count and dates.",
1654
1828
  docs: `${DOCS}/lead-lists/get-by-id`,
1655
1829
  method: "GET",
1656
- params: { id: path("The lead list's id.") },
1830
+ params: { id: inPath("The lead list's id.") },
1657
1831
  path: "/lead-list/{id}"
1658
1832
  },
1659
1833
  leadNotes: {
1660
1834
  description: "The notes written on a lead.",
1661
1835
  docs: `${DOCS}/lead-notes/get-all`,
1662
1836
  method: "GET",
1663
- params: { id: path("The lead's id.") },
1837
+ params: { id: inPath("The lead's id.") },
1664
1838
  path: "/crm/leads/notes/{id}"
1665
1839
  },
1666
1840
  leadSequenceDetails: {
@@ -1668,8 +1842,8 @@ var CAMPAIGN_READS = defineNative({
1668
1842
  docs: `${DOCS}/leads/sequence-details`,
1669
1843
  method: "GET",
1670
1844
  params: {
1671
- campaignId: query("number", "Only this campaign."),
1672
- leadMapId: path("The lead-in-campaign mapping id.")
1845
+ campaignId: inQuery("number", "Only this campaign."),
1846
+ leadMapId: inPath("The lead-in-campaign mapping id.")
1673
1847
  },
1674
1848
  path: "/leads/{leadMapId}/sequence-details"
1675
1849
  },
@@ -1677,7 +1851,7 @@ var CAMPAIGN_READS = defineNative({
1677
1851
  description: "The tasks created for a lead.",
1678
1852
  docs: `${DOCS}/lead-tasks/get-all`,
1679
1853
  method: "GET",
1680
- params: { id: path("The lead's id.") },
1854
+ params: { id: inPath("The lead's id.") },
1681
1855
  path: "/crm/leads/tasks/{id}"
1682
1856
  },
1683
1857
  senderTagsByEmail: {
@@ -1685,7 +1859,7 @@ var CAMPAIGN_READS = defineNative({
1685
1859
  docs: `${DOCS}/email-account-tags/get-all`,
1686
1860
  method: "POST",
1687
1861
  params: {
1688
- email_ids: bodyRequired("json", "Mailbox addresses, as an array.")
1862
+ email_ids: inBodyRequired("json", "Mailbox addresses, as an array.")
1689
1863
  },
1690
1864
  path: "/email-accounts/tag-list"
1691
1865
  },
@@ -1693,27 +1867,27 @@ var CAMPAIGN_READS = defineNative({
1693
1867
  description: "One webhook: its URL, events, categories and campaign.",
1694
1868
  docs: `${DOCS}/webhooks/get`,
1695
1869
  method: "GET",
1696
- params: { webhook_id: path("The webhook's id.") },
1870
+ params: { webhook_id: inPath("The webhook's id.") },
1697
1871
  path: "/webhook/{webhook_id}"
1698
1872
  }
1699
1873
  });
1700
1874
 
1701
1875
  // src/smartlead/native-inbox.ts
1702
1876
  var PAGE2 = {
1703
- limit: body("number", "Threads per page, 1 to 20."),
1704
- offset: body("number", "Threads to skip.")
1877
+ limit: inBody("number", "Threads per page, 1 to 20."),
1878
+ offset: inBody("number", "Threads to skip.")
1705
1879
  };
1706
1880
  var HISTORY = {
1707
- fetch_message_history: query("boolean", "Add each thread's messages.")
1881
+ fetch_message_history: inQuery("boolean", "Add each thread's messages.")
1708
1882
  };
1709
1883
  var FILTERS = "search, leadCategories, emailStatus, campaignId, emailAccountId, campaignTeamMemberId, campaignTagId, campaignClientId and replyTimeBetween";
1710
1884
  var filters = (note) => ({
1711
- filters: body("json", `An object of ${FILTERS}. ${note}`)
1885
+ filters: inBody("json", `An object of ${FILTERS}. ${note}`)
1712
1886
  });
1713
1887
  var MANY = filters("Ids may be arrays: 5 campaigns, 10 of the others.");
1714
1888
  var SINGLE = filters("Each id is a single value.");
1715
1889
  var SORT = {
1716
- sortBy: body("string", "REPLY_TIME_DESC or SENT_TIME_DESC.")
1890
+ sortBy: inBody("string", "REPLY_TIME_DESC or SENT_TIME_DESC.")
1717
1891
  };
1718
1892
  var INBOX = defineNative({
1719
1893
  inboxArchived: {
@@ -1744,7 +1918,7 @@ var INBOX = defineNative({
1744
1918
  params: {
1745
1919
  ...PAGE2,
1746
1920
  ...MANY,
1747
- sortBy: body("string", "REMINDER_TIME_ASC or REMINDER_TIME_DESC.")
1921
+ sortBy: inBody("string", "REMINDER_TIME_ASC or REMINDER_TIME_DESC.")
1748
1922
  },
1749
1923
  path: "/master-inbox/reminders"
1750
1924
  },
@@ -1756,7 +1930,7 @@ var INBOX = defineNative({
1756
1930
  ...PAGE2,
1757
1931
  ...HISTORY,
1758
1932
  ...MANY,
1759
- sortBy: body("string", "SCHEDULED_TIME_ASC or SCHEDULED_TIME_DESC.")
1933
+ sortBy: inBody("string", "SCHEDULED_TIME_ASC or SCHEDULED_TIME_DESC.")
1760
1934
  },
1761
1935
  path: "/master-inbox/scheduled"
1762
1936
  },
@@ -1786,13 +1960,13 @@ var INBOX = defineNative({
1786
1960
  docs: `${DOCS}/inbox/get-untracked`,
1787
1961
  method: "GET",
1788
1962
  params: {
1789
- fetchAttachments: query("boolean", "Add attachment details."),
1790
- fetchBody: query("boolean", "Add each email's body."),
1791
- from_email: query("string", "Only from this address."),
1792
- limit: query("number", "Replies per page, 1 to 100."),
1793
- offset: query("number", "Replies to skip."),
1794
- subject_line: query("string", "Only subjects containing this."),
1795
- to_email: query("string", "Only to this address.")
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.")
1796
1970
  },
1797
1971
  path: "/master-inbox/untracked-replies"
1798
1972
  },
@@ -1813,7 +1987,7 @@ var INBOX = defineNative({
1813
1987
  docs: `${DOCS}/inbox/reply-status`,
1814
1988
  method: "GET",
1815
1989
  params: {
1816
- message_id: queryRequired(
1990
+ message_id: inQueryRequired(
1817
1991
  "string",
1818
1992
  "The reply's Message-ID header, angle brackets included."
1819
1993
  )
@@ -1823,7 +1997,7 @@ var INBOX = defineNative({
1823
1997
  });
1824
1998
 
1825
1999
  // src/smartlead/native-services.ts
1826
- var TEST = { spamTestId: path("The placement test's id.") };
2000
+ var TEST = { spamTestId: inPath("The placement test's id.") };
1827
2001
  var report = (leaf, page, description) => ({
1828
2002
  baseUrl: DELIVERY_URL,
1829
2003
  description,
@@ -1833,8 +2007,8 @@ var report = (leaf, page, description) => ({
1833
2007
  path: `/spam-test/report/{spamTestId}/${leaf}`
1834
2008
  });
1835
2009
  var SEARCHES = {
1836
- limit: query("string", "Searches per page; 10 by default."),
1837
- offset: query("string", "Searches to skip.")
2010
+ limit: inQuery("string", "Searches per page; 10 by default."),
2011
+ offset: inQuery("string", "Searches to skip.")
1838
2012
  };
1839
2013
  var searches = (leaf, description) => ({
1840
2014
  baseUrl: PROSPECT_URL,
@@ -1865,7 +2039,7 @@ var DELIVERY = defineNative({
1865
2039
  description: "One folder of placement tests.",
1866
2040
  docs: `${DOCS}/smart-delivery/get-folder-by-id`,
1867
2041
  method: "GET",
1868
- params: { folderId: path("The folder's id.") },
2042
+ params: { folderId: inPath("The folder's id.") },
1869
2043
  path: "/spam-test/folder/{folderId}"
1870
2044
  },
1871
2045
  deliveryFolders: {
@@ -1925,7 +2099,7 @@ var DELIVERY = defineNative({
1925
2099
  description: "The headers of one email a placement test received.",
1926
2100
  docs: `${DOCS}/smart-delivery/reply-headers`,
1927
2101
  method: "GET",
1928
- params: { ...TEST, replyId: path("The received email's reply id.") },
2102
+ params: { ...TEST, replyId: inPath("The received email's reply id.") },
1929
2103
  path: "/spam-test/report/{spamTestId}/sender-account-wise/{replyId}/email-headers"
1930
2104
  },
1931
2105
  deliveryScheduleHistory: report(
@@ -1983,16 +2157,19 @@ var SERVICES = defineNative({
1983
2157
  docs: `${DOCS}/smart-prospect/get-contacts`,
1984
2158
  method: "POST",
1985
2159
  params: {
1986
- catch_all_status: body(
2160
+ catch_all_status: inBody(
1987
2161
  "string",
1988
2162
  "catch_all_verified, catch_all_soft_bounced, catch_all_hard_bounced, catch_all_unknown or catch_all_bounced."
1989
2163
  ),
1990
- filter_id: body("number", "The search filter whose contacts to read."),
1991
- id: body("json", "Contact ids (adapt_ids), as an array of at most 200."),
1992
- limit: body("number", "Contacts per page, 1 to 1000, with filter_id."),
1993
- offset: body("number", "Contacts to skip, with filter_id."),
1994
- search: body("string", "Matches the first, last or full name."),
1995
- verification_status: body("string", "valid, catch_all or invalid.")
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.")
1996
2173
  },
1997
2174
  path: "/search-email-leads/get-contacts"
1998
2175
  },
@@ -2020,7 +2197,7 @@ var SERVICES = defineNative({
2020
2197
  description: "SmartProspect leads found, emails fetched and credits left, with the monthly trend.",
2021
2198
  docs: `${DOCS}/smart-prospect/search-analytics`,
2022
2199
  method: "GET",
2023
- params: { filter_id: query("string", "Only this search filter.") },
2200
+ params: { filter_id: inQuery("string", "Only this search filter.") },
2024
2201
  path: "/search-email-leads/search-analytics"
2025
2202
  },
2026
2203
  smartSendersDomains: {
@@ -2036,11 +2213,11 @@ var SERVICES = defineNative({
2036
2213
  docs: `${DOCS}/smart-servers/list-servers`,
2037
2214
  method: "GET",
2038
2215
  params: {
2039
- unmapped: query(
2216
+ unmapped: inQuery(
2040
2217
  "string",
2041
2218
  'Set to "true" for only servers on no campaign or client.'
2042
2219
  ),
2043
- withCampaignData: query(
2220
+ withCampaignData: inQuery(
2044
2221
  "string",
2045
2222
  `Set to "true" to add each server's campaigns, client and region.`
2046
2223
  )
@@ -2052,7 +2229,7 @@ var SERVICES = defineNative({
2052
2229
  description: "The dedicated IP attached to a campaign; only one is returned when it has several.",
2053
2230
  docs: `${DOCS}/smart-servers/get-campaign-servers`,
2054
2231
  method: "GET",
2055
- params: { campaign_id: path("The campaign's id.") },
2232
+ params: { campaign_id: inPath("The campaign's id.") },
2056
2233
  path: "/smart-server/all/campaign/{campaign_id}"
2057
2234
  }
2058
2235
  });
@@ -2077,8 +2254,8 @@ var NATIVE_READ_POSTS = Object.values(
2077
2254
 
2078
2255
  // src/smartlead/client.ts
2079
2256
  var READ_POSTS = [/^\/master-inbox\/inbox-replies$/u, ...NATIVE_READ_POSTS];
2080
- var normalizePath = (path2) => {
2081
- const [withoutQuery = ""] = path2.split("?");
2257
+ var normalizePath = (path) => {
2258
+ const [withoutQuery = ""] = path.split("?");
2082
2259
  return `/${withoutQuery.replace(/^\/+/u, "").replace(/\/+$/u, "")}`.replace(
2083
2260
  /^\/api\/v1(?=\/|$)/u,
2084
2261
  ""
@@ -2086,16 +2263,16 @@ var normalizePath = (path2) => {
2086
2263
  };
2087
2264
  var SECRET_PATH = /^\/(?:client\/api-key|email-accounts\/fetch-email-account-details|smart-senders\/(?:auth-secret|order-details))(?:\/|$)/iu;
2088
2265
  var CLIENT = /^\/client\/[^/]+$/iu;
2089
- var isSecret = (path2, query2) => {
2090
- const normalized = normalizePath(path2);
2091
- const whitelabel = query2.get("includeWhitelabel");
2266
+ var isSecret = (path, query) => {
2267
+ const normalized = normalizePath(path);
2268
+ const whitelabel = query.get("includeWhitelabel");
2092
2269
  return SECRET_PATH.test(normalized) || CLIENT.test(normalized) && whitelabel !== null && whitelabel.toLowerCase() !== "false";
2093
2270
  };
2094
- var isRead = (method, path2) => {
2271
+ var isRead = (method, path) => {
2095
2272
  if (method === "GET") {
2096
2273
  return true;
2097
2274
  }
2098
- const normalized = normalizePath(path2);
2275
+ const normalized = normalizePath(path);
2099
2276
  return method === "POST" && READ_POSTS.some((pattern2) => pattern2.test(normalized));
2100
2277
  };
2101
2278
  var createClient = (options) => {
@@ -2106,28 +2283,9 @@ var createClient = (options) => {
2106
2283
  return { ...spec, url: url.toString() };
2107
2284
  };
2108
2285
  return {
2109
- get: async (ctx, path2, request = {}) => {
2110
- const response = await ctx.request(
2111
- authorize({
2112
- lane: request.lane,
2113
- method: "GET",
2114
- url: buildUrl(baseUrl, path2, request.query)
2115
- })
2116
- );
2117
- return response.body;
2118
- },
2286
+ ...createVendorClient(baseUrl, authorize),
2287
+ delivery: createVendorClient(DELIVERY_URL, authorize),
2119
2288
  identity: options.identity,
2120
- post: async (ctx, path2, body2, request = {}) => {
2121
- const response = await ctx.request(
2122
- authorize({
2123
- body: body2,
2124
- lane: request.lane,
2125
- method: "POST",
2126
- url: buildUrl(baseUrl, path2, request.query)
2127
- })
2128
- );
2129
- return response.body;
2130
- },
2131
2289
  raw: { authorize, baseUrl, isRead, isSecret }
2132
2290
  };
2133
2291
  };
@@ -2147,11 +2305,12 @@ var smartlead = (options = {}) => {
2147
2305
  identity: { provider: PROVIDER, workspaceId }
2148
2306
  });
2149
2307
  return {
2150
- ...readers(client),
2308
+ ...withLeadFields(readers(client), options.leadFields),
2151
2309
  capabilities: { ...capabilities, ...options.capabilities },
2152
2310
  caveats,
2153
2311
  costs,
2154
2312
  events: smartleadEvents(PROVIDER),
2313
+ fields: withMappedFields(fields, options.leadFields),
2155
2314
  limits,
2156
2315
  mapError: makeErrorMapper(PROVIDER, { secrets: [apiKey] }),
2157
2316
  maturity: "unverified",