outbound-sdk 0.4.0 → 0.5.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 (90) hide show
  1. package/README.md +2 -2
  2. package/dist/alerts/check-evaluate.d.ts +53 -0
  3. package/dist/alerts/check-measure.d.ts +100 -0
  4. package/dist/alerts/check-schema.d.ts +184 -0
  5. package/dist/alerts/check-validate.d.ts +18 -0
  6. package/dist/alerts/index.d.ts +7 -0
  7. package/dist/alerts/index.js +635 -2
  8. package/dist/budget/index.d.ts +2 -0
  9. package/dist/budget/index.js +1 -0
  10. package/dist/cards/index.js +2 -1
  11. package/dist/chunks/{chunk-5CFO3CXG.js → chunk-3S32R2MH.js} +33 -67
  12. package/dist/chunks/{chunk-ZFVHM5JI.js → chunk-5J7GGV62.js} +11 -4
  13. package/dist/chunks/chunk-6TKFISG4.js +676 -0
  14. package/dist/chunks/{chunk-E6DSDCPI.js → chunk-BK5SLY32.js} +92 -101
  15. package/dist/chunks/{chunk-A6WVOCA4.js → chunk-BN6WCAWX.js} +4 -4
  16. package/dist/chunks/{chunk-IZFTTMJP.js → chunk-EHSJGQ5K.js} +5 -5
  17. package/dist/chunks/chunk-HPNGSG5E.js +51 -0
  18. package/dist/chunks/chunk-HWHI4LFY.js +102 -0
  19. package/dist/chunks/{chunk-Y5RAJ6PZ.js → chunk-OLPMBRXM.js} +3 -2
  20. package/dist/chunks/chunk-WGW3ROLY.js +18 -0
  21. package/dist/chunks/{chunk-7ZDS6SZD.js → chunk-WH6V3YNN.js} +25 -0
  22. package/dist/chunks/{chunk-7LNJJ2RO.js → chunk-X4RDBD4J.js} +102 -11
  23. package/dist/chunks/chunk-XL6LJVHJ.js +71 -0
  24. package/dist/chunks/{chunk-5FVKRIEJ.js → chunk-YYCT3NGV.js} +35 -11
  25. package/dist/cli/bin.js +13 -28
  26. package/dist/cli/index.d.ts +3 -0
  27. package/dist/cli/index.js +12 -11
  28. package/dist/cli/update.d.ts +15 -0
  29. package/dist/emailbison/account.d.ts +7 -0
  30. package/dist/emailbison/adapter.d.ts +5 -0
  31. package/dist/emailbison/capabilities.d.ts +78 -0
  32. package/dist/emailbison/client.d.ts +29 -0
  33. package/dist/emailbison/index.d.ts +30 -0
  34. package/dist/emailbison/index.js +1017 -0
  35. package/dist/emailbison/mail.d.ts +5 -0
  36. package/dist/emailbison/map-mail.d.ts +13 -0
  37. package/dist/emailbison/map-sequence.d.ts +12 -0
  38. package/dist/emailbison/map-stats.d.ts +47 -0
  39. package/dist/emailbison/map.d.ts +24 -0
  40. package/dist/emailbison/native-params.d.ts +5 -0
  41. package/dist/emailbison/native-workspace.d.ts +167 -0
  42. package/dist/emailbison/native.d.ts +327 -0
  43. package/dist/emailbison/stats.d.ts +4 -0
  44. package/dist/emailbison/webhooks.d.ts +2 -0
  45. package/dist/fixtures/index.js +6 -6
  46. package/dist/heyreach/capabilities.d.ts +3 -0
  47. package/dist/heyreach/index.js +20 -20
  48. package/dist/index.js +19 -18
  49. package/dist/insights/copy/copy-reuse.d.ts +6 -6
  50. package/dist/insights/copy/shared.d.ts +2 -2
  51. package/dist/insights/copy/step-funnel.d.ts +5 -5
  52. package/dist/insights/copy/variant-test.d.ts +2 -2
  53. package/dist/insights/cost.d.ts +91 -0
  54. package/dist/insights/define.d.ts +22 -1
  55. package/dist/insights/index.d.ts +4 -3
  56. package/dist/insights/index.js +331 -27
  57. package/dist/insights/inputs.generated.d.ts +4 -4
  58. package/dist/insights/ops/campaign-ranking.d.ts +3 -3
  59. package/dist/insights/ops/index.d.ts +2 -2
  60. package/dist/insights/ops/shared.d.ts +11 -1
  61. package/dist/insights/plugin.d.ts +19 -0
  62. package/dist/insights/registry.d.ts +2 -2
  63. package/dist/insights/run-cap.d.ts +35 -0
  64. package/dist/insights/senders/bounce-watch.d.ts +4 -4
  65. package/dist/insights/senders/domain-health.d.ts +2 -2
  66. package/dist/insights/senders/sender-load.d.ts +1 -1
  67. package/dist/insights/tools.d.ts +10 -0
  68. package/dist/instantly/capabilities.d.ts +13 -0
  69. package/dist/instantly/index.js +41 -28
  70. package/dist/internal/adapter.d.ts +12 -0
  71. package/dist/internal/outbound/outbound.d.ts +5 -1
  72. package/dist/internal/request-cap.d.ts +35 -0
  73. package/dist/loader/index.js +2 -2
  74. package/dist/memory/index.js +10 -10
  75. package/dist/providers/index.d.ts +21 -1
  76. package/dist/providers/index.js +1 -1
  77. package/dist/redact/index.js +4 -4
  78. package/dist/smartlead/capabilities.d.ts +5 -0
  79. package/dist/smartlead/index.js +24 -24
  80. package/dist/tools/ai-sdk.js +5 -3
  81. package/dist/tools/claude-agent.js +5 -3
  82. package/dist/tools/index.d.ts +2 -2
  83. package/dist/tools/index.js +11 -6
  84. package/dist/tools/registry.d.ts +20 -1
  85. package/dist/tools/shared.d.ts +20 -1
  86. package/dist/webhooks/index.js +16 -7
  87. package/package.json +8 -2
  88. package/dist/chunks/chunk-K4USHN4C.js +0 -40
  89. package/dist/chunks/chunk-LVQUSKEX.js +0 -17
  90. package/dist/chunks/{chunk-C4LS2HNV.js → chunk-JWGSB7PT.js} +3 -3
@@ -0,0 +1,676 @@
1
+ import {
2
+ createVendorClient,
3
+ leadStanding,
4
+ listIn,
5
+ normalizeBody
6
+ } from "./chunk-3S32R2MH.js";
7
+ import {
8
+ eventData,
9
+ eventTypesOf,
10
+ recordBase,
11
+ refTo
12
+ } from "./chunk-2D42TQFU.js";
13
+ import {
14
+ SCHEMA_VERSION
15
+ } from "./chunk-QGRZDTX4.js";
16
+ import {
17
+ stableId
18
+ } from "./chunk-FHKSLCVW.js";
19
+ import {
20
+ requireObject
21
+ } from "./chunk-J7DDZ4C2.js";
22
+ import {
23
+ count,
24
+ emailAddress,
25
+ field,
26
+ flag,
27
+ fullName,
28
+ isJsonObject,
29
+ isString,
30
+ list,
31
+ objects,
32
+ text,
33
+ timestamp,
34
+ withoutKeys
35
+ } from "./chunk-BLCJHP5H.js";
36
+
37
+ // src/emailbison/capabilities.ts
38
+ var BASE_URL = "https://dedi.emailbison.com";
39
+ var API_KEY_ENV = "EMAILBISON_API_KEY";
40
+ var BASE_URL_ENV = "EMAILBISON_BASE_URL";
41
+ var WORKSPACE_ENV = "EMAILBISON_WORKSPACE_ID";
42
+ var PAGE_SIZE = 15;
43
+ var capabilities = {
44
+ // GET /api/blacklisted-emails, then GET /api/blacklisted-domains.
45
+ blocklist: true,
46
+ // GET /api/sender-emails/{id}/campaigns.
47
+ "campaigns.bySender": true,
48
+ // GET /api/campaigns/{id} for the caps and tracking, then
49
+ // GET /api/campaigns/{id}/schedule for the sending window.
50
+ "campaigns.settings": true,
51
+ // The status filter takes 11 vendor values and one SDK status covers
52
+ // several of them, so the wrapper filters after fetching.
53
+ "campaigns.status": "client",
54
+ "events.parse": true,
55
+ // The workspace has a webhook secret, but no page says how a delivery is
56
+ // signed. A secret in the URL is what can be checked.
57
+ "events.verify": "secret",
58
+ "leads.byCampaign": true,
59
+ // overall_stats on every lead.
60
+ "leads.engagement": true,
61
+ "leads.get": true,
62
+ "leads.list": true,
63
+ // GET /api/leads/{lead_id} takes an email in place of the id.
64
+ "leads.lookup": true,
65
+ // filters.created_at compares whole days, so the wrapper filters on the
66
+ // creation time after fetching.
67
+ "leads.since": "client",
68
+ // A lead's sent emails, then its replies.
69
+ "leads.timeline": true,
70
+ // GET /api/lead-lists/{id}. No read returns the leads of a list.
71
+ "lists.get": true,
72
+ "lists.list": true,
73
+ "messages.body": "full",
74
+ // GET /api/replies/{id}/conversation-thread: the thread around one reply.
75
+ "messages.byThread": true,
76
+ // Sent campaign emails: GET /api/scheduled-emails?status=sent.
77
+ "messages.list": true,
78
+ "messages.since": "client",
79
+ native: true,
80
+ // `interested` and `automated_reply` on each reply.
81
+ "replies.category": "vendor",
82
+ "replies.list": true,
83
+ // The inbox has no dated filter.
84
+ "replies.since": "client",
85
+ "replies.unread": "server",
86
+ "senders.byCampaign": true,
87
+ "senders.get": true,
88
+ // The sender's connection state and GET /api/warmup/sender-emails/{id}.
89
+ "senders.health": true,
90
+ "senders.list": true,
91
+ "senders.warmup": true,
92
+ // GET /api/campaigns/v1.1/{id}/sequence-steps.
93
+ sequence: true,
94
+ // The line-area series of the workspace or a campaign, and
95
+ // GET /api/campaign-events/stats for one sender.
96
+ "stats.byDay": "exact",
97
+ // A sender's lifetime counts, or its daily events summed over a range.
98
+ "stats.bySender": "exact",
99
+ // sequence_step_stats of POST /api/campaigns/{id}/stats.
100
+ "stats.byStep": "exact",
101
+ "stats.campaign": "exact",
102
+ "stats.workspace": "exact",
103
+ tags: true,
104
+ "webhooks.get": true,
105
+ "webhooks.list": true,
106
+ workspaces: true
107
+ };
108
+ var fields = {
109
+ // Nothing reports leads by where they are in the sequence.
110
+ campaignProgress: false,
111
+ campaignSettings: {
112
+ endDate: false,
113
+ gapMinutes: false,
114
+ startDate: false,
115
+ stopOnAutoReply: false,
116
+ stopOnReply: false
117
+ },
118
+ lead: {
119
+ companyLinkedinUrl: false,
120
+ // `interested` on a campaign's lead.
121
+ interest: "derived",
122
+ interestCategory: "derived",
123
+ linkedinUrl: false,
124
+ location: false,
125
+ phone: false,
126
+ tags: false,
127
+ website: false
128
+ },
129
+ // A sent email names its step by id, not by place.
130
+ message: { stepIndex: false, variantKey: false },
131
+ metricRow: {
132
+ clicked: false,
133
+ clickedTotal: false,
134
+ connectionsAccepted: false,
135
+ connectionsSent: false,
136
+ contentHash: false,
137
+ delivered: false,
138
+ inmailsSent: false,
139
+ repliedAuto: false,
140
+ // No read says which timezone its days are in.
141
+ timezone: false
142
+ },
143
+ placementTest: false,
144
+ reply: { stepIndex: false, variantKey: false },
145
+ sender: { linkedinUrl: false },
146
+ // Only the main sequence is read, and it has no name.
147
+ sequence: { name: false },
148
+ senderHealth: {
149
+ blacklisted: false,
150
+ checkedAt: false,
151
+ dns: false,
152
+ issues: false
153
+ },
154
+ tag: { description: false },
155
+ // A webhook is workspace-wide and has no on or off state.
156
+ webhook: { active: false, campaignRefs: false }
157
+ };
158
+ var limits = {
159
+ source: 'https://emailbison.com/blogs/emailbison-vs-salesloft ("up to 3,000 requests per minute"; the API reference at https://dedi.emailbison.com/api/reference documents no limit) and https://emailbison.com/developers (limits are per key; 429 carries retry_after); read 2026-11-15, not confirmed live',
160
+ windows: [{ perMs: 6e4, requests: 3e3 }]
161
+ };
162
+ var costs = {
163
+ // Emails first, then domains.
164
+ "blocklist.list": { pageSize: PAGE_SIZE, perPage: 1 },
165
+ "campaigns.get": { perPage: 1 },
166
+ "campaigns.list": { pageSize: PAGE_SIZE, perPage: 1 },
167
+ // The campaign, then its schedule.
168
+ "campaigns.settings": { perPage: 2 },
169
+ "leads.get": { perPage: 1 },
170
+ // A lookup by address is one request and never walks leads.
171
+ "leads.list": { pageSize: PAGE_SIZE, perPage: 1 },
172
+ "lists.list": { pageSize: PAGE_SIZE, perPage: 1 },
173
+ // A lead's timeline is its sent emails, then its replies 15 at a time. A
174
+ // thread is one request.
175
+ "messages.list": { pageSize: PAGE_SIZE, perPage: 1 },
176
+ "replies.list": { pageSize: PAGE_SIZE, perPage: 1 },
177
+ "senders.get": { perPage: 1 },
178
+ // The sender, then its warmup.
179
+ "senders.health": { perPage: 2 },
180
+ "senders.list": { pageSize: PAGE_SIZE, perPage: 1 },
181
+ "sequence.get": { perPage: 1 },
182
+ // Step rows cost two: the campaign's stats, then its steps.
183
+ stats: { perPage: 1 },
184
+ "tags.list": { perPage: 1 },
185
+ "webhooks.list": { pageSize: PAGE_SIZE, perPage: 1 },
186
+ "workspaces.list": { perPage: 1 }
187
+ };
188
+ var caveats = [
189
+ "Nothing is checked against a live account: no EmailBison workspace or key was available. Mappings follow the API reference read on 2026-11-15, whose response examples are hand-written and often not valid JSON.",
190
+ "Each customer has their own instance: pass baseUrl (or set EMAILBISON_BASE_URL) to the URL you log in with. The default is https://dedi.emailbison.com, the reference's server.",
191
+ "The rate limit is undocumented in the reference. The adapter assumes 3,000 requests per minute per key, from a marketing page, and uses half of it.",
192
+ "Every list returns 15 records per page and cannot be asked for more. Lists that document cursor pagination are read by cursor, so the 1,000-page cap of page numbers does not apply to them.",
193
+ "outbound.raw refuses the workspace reads (they carry webhooks_secret_key) and a mailbox's OAuth access token; normalized records drop webhooks_secret_key from raw.",
194
+ "Campaign status: active, launching and queued are active; stopped and completed are completed; failed, pending deletion and deleted are unknown.",
195
+ "A lead's status is its email verification status: bounced sets bounced, unsubscribed sets unsubscribed. replied is overall_stats.replies above 0. progress comes from lead_campaign_data.status, documented only as stopped (read as paused), so it is unknown on a lead read outside a campaign.",
196
+ "Lead engagement is overall_stats across every campaign: opens and replies as total counts, no clicks and no dates.",
197
+ "interest is Interested when a campaign's lead is marked interested; EmailBison's lead tags are not in any lead payload.",
198
+ "messages.list reads sent campaign emails (GET /api/scheduled-emails?status=sent), whose ids are prefixed scheduled- to keep them apart from replies. A lead's timeline adds its master inbox messages (folder all).",
199
+ "threadId is a reply id: GET /api/replies/{id}/conversation-thread returns the messages before and after it. A message in folder Sent is outgoing.",
200
+ "The unread filter is sent as read=0 or read=1, assuming the API takes booleans the way a Laravel app does; the reference does not say.",
201
+ "Replies are the master inbox's inbox folder. category is positive when interested, ooo when automated_reply, otherwise unknown; only positive and ooo are filtered by EmailBison.",
202
+ "Dated statistics need both dates: a missing end is today (UTC), a missing start 2000-01-01 for totals and 30 days before the end for daily rows. No read says which timezone its days are in.",
203
+ "Workspace and campaign totals: opened is unique opens per contact and openedTotal total opens, replied unique replies per contact, positive interested. No clicks and no automatic-reply count are reported.",
204
+ "A sender's totals without dates are its lifetime counts; with dates they are its daily events summed (derived). Step rows come from sequence_step_stats, one per step and variant.",
205
+ "Sequence variants are steps with variant true, placed under variant_from_step_id or, when that is null, the step with the same order.",
206
+ "Settings: dailyLimit is max_emails_per_day, dailyNewLeads max_new_leads_per_day, one sending window from the campaign schedule. Stop rules, dates and send gaps are not reported.",
207
+ "Sender health: connected from the sender status, warmup from GET /api/warmup/sender-emails/{id} over the last 7 days. No DNS records or block list state are reported.",
208
+ "Webhooks: only EMAIL_SENT, MANUAL_EMAIL_SENT and TAG_ATTACHED have documented payloads. The others are read with the same data keys. Payloads carry no event id, so the id is derived from the event type and the ids in data.",
209
+ "Webhook signatures are not verified: the signing scheme behind webhooks_secret_key is undocumented. Put a secret in the webhook URL.",
210
+ "Block list entries come from two lists: emails first, then domains.",
211
+ "A lead list's size is leads_succeeded."
212
+ ];
213
+
214
+ // src/emailbison/client.ts
215
+ var READ_POST = /^\/api\/campaigns\/[^/]+\/stats$/u;
216
+ var SECRET_PATH = /^\/api\/(?:sender-emails\/[^/]+\/oauth-access-token|workspaces(?:\/v1\.1)?(?:\/(?!stats$|line-area-chart-stats$|master-inbox-settings$)[^/]+)?)$/iu;
217
+ var normalizePath = (path) => {
218
+ const [withoutQuery = ""] = path.split("?");
219
+ return `/${withoutQuery.replace(/^\/+/u, "").replace(/\/+$/u, "")}`;
220
+ };
221
+ var isSecret = (path) => SECRET_PATH.test(normalizePath(path));
222
+ var isRead = (method, path) => method === "GET" || method === "POST" && READ_POST.test(normalizePath(path));
223
+ var SECRET_KEYS = /secret|token|password/iu;
224
+ var nextOf = (body) => {
225
+ const meta = field(body, "meta");
226
+ const cursor = field(meta, "next_cursor");
227
+ if (isString(cursor) && cursor !== "") {
228
+ return { cursor };
229
+ }
230
+ const current = count(field(meta, "current_page"));
231
+ const last = count(field(meta, "last_page"));
232
+ return current !== null && last !== null && current < last ? { page: current + 1 } : void 0;
233
+ };
234
+ var pageQuery = (next, cursor) => ({
235
+ cursor: text(field(next, "cursor")) ?? void 0,
236
+ page: count(field(next, "page")) ?? void 0,
237
+ pagination_type: cursor ? "cursor" : void 0
238
+ });
239
+ var createClient = (options) => {
240
+ const baseUrl = (options.baseUrl ?? BASE_URL).replace(/\/+$/u, "");
241
+ const { provider } = options.identity;
242
+ const authorize = (spec) => ({
243
+ ...spec,
244
+ headers: {
245
+ ...spec.headers,
246
+ Accept: "application/json",
247
+ Authorization: `Bearer ${options.apiKey}`
248
+ }
249
+ });
250
+ const vendor = createVendorClient(baseUrl, authorize);
251
+ const rows = (body, path) => objects(
252
+ listIn(body, { key: "data", path, provider, vendor: "EmailBison" })
253
+ );
254
+ return {
255
+ ...vendor,
256
+ identity: options.identity,
257
+ one: (body, path) => requireObject(
258
+ field(body, "data"),
259
+ provider,
260
+ `EmailBison returned no object for ${path}`
261
+ ),
262
+ page: async (ctx, path, next, pageOptions = {}) => {
263
+ const body = await vendor.get(ctx, path, {
264
+ lane: pageOptions.lane,
265
+ query: {
266
+ ...pageOptions.query,
267
+ ...pageQuery(next, pageOptions.cursor === true)
268
+ }
269
+ });
270
+ return { items: rows(body, path), next: nextOf(body) };
271
+ },
272
+ raw: { authorize, baseUrl, isRead, isSecret },
273
+ rows
274
+ };
275
+ };
276
+
277
+ // src/emailbison/map-mail.ts
278
+ var SENT_PREFIX = "scheduled-";
279
+ var idOf = (raw) => text(raw.id) ?? "";
280
+ var linked = (raw, nested, key) => text(raw[key]) ?? text(field(raw[nested], "id"));
281
+ var toSentMessage = (identity, raw, includeBody) => ({
282
+ ...recordBase(identity, `${SENT_PREFIX}${idOf(raw)}`, raw),
283
+ ...normalizeBody(text(raw.email_body), includeBody),
284
+ campaignRef: refTo(identity, linked(raw, "campaign", "campaign_id")),
285
+ channel: "email",
286
+ direction: "out",
287
+ leadRef: refTo(identity, linked(raw, "lead", "lead_id")),
288
+ senderRef: refTo(identity, linked(raw, "sender_email", "sender_email_id")),
289
+ sentAt: timestamp(raw.sent_at),
290
+ stepIndex: null,
291
+ subject: text(raw.email_subject),
292
+ // A campaign email is not in the master inbox, so it has no thread there.
293
+ threadId: null,
294
+ variantKey: null
295
+ });
296
+ var isOutgoing = (raw) => (text(raw.folder) ?? "").toLowerCase() === "sent";
297
+ var bodyOf = (raw) => text(raw.html_body) ?? text(raw.text_body);
298
+ var inboxFields = (identity, raw, includeBody) => ({
299
+ ...recordBase(identity, idOf(raw), raw),
300
+ ...normalizeBody(bodyOf(raw), includeBody),
301
+ campaignRef: refTo(identity, linked(raw, "campaign", "campaign_id")),
302
+ channel: "email",
303
+ leadRef: refTo(identity, linked(raw, "lead", "lead_id")),
304
+ senderRef: refTo(identity, linked(raw, "sender_email", "sender_email_id")),
305
+ sentAt: timestamp(raw.date_received),
306
+ stepIndex: null,
307
+ subject: text(raw.subject) ?? text(raw.email_subject),
308
+ // Any reply in a conversation reads the whole conversation.
309
+ threadId: text(raw.id),
310
+ variantKey: null
311
+ });
312
+ var toInboxMessage = (identity, raw, includeBody) => ({
313
+ ...inboxFields(identity, raw, includeBody),
314
+ direction: isOutgoing(raw) ? "out" : "in"
315
+ });
316
+ var categoryOf = (raw) => {
317
+ if (raw.interested === true) {
318
+ return "positive";
319
+ }
320
+ return raw.automated_reply === true ? "ooo" : "unknown";
321
+ };
322
+ var toReply = (identity, raw, includeBody) => {
323
+ const category = categoryOf(raw);
324
+ const read = flag(raw.read);
325
+ return {
326
+ ...inboxFields(identity, raw, includeBody),
327
+ category,
328
+ categorySource: category === "unknown" ? null : "vendor",
329
+ direction: "in",
330
+ isAuto: flag(raw.automated_reply),
331
+ unread: read === null ? null : !read
332
+ };
333
+ };
334
+
335
+ // src/emailbison/map.ts
336
+ var CAMPAIGN_STATUSES = /* @__PURE__ */ new Map([
337
+ ["active", "active"],
338
+ ["archived", "archived"],
339
+ ["completed", "completed"],
340
+ ["deleted", "unknown"],
341
+ ["draft", "draft"],
342
+ ["failed", "unknown"],
343
+ ["launching", "active"],
344
+ ["paused", "paused"],
345
+ ["pending deletion", "unknown"],
346
+ ["queued", "active"],
347
+ ["stopped", "completed"]
348
+ ]);
349
+ var lower = (value) => (text(value) ?? "").toLowerCase();
350
+ var tagNames = (value) => objects(value).flatMap((tag) => text(tag.name) ?? []);
351
+ var idOf2 = (raw) => text(raw.id) ?? "";
352
+ var toCampaign = (identity, raw) => ({
353
+ ...recordBase(identity, idOf2(raw), raw),
354
+ channel: "email",
355
+ createdAt: timestamp(raw.created_at),
356
+ name: text(raw.name) ?? idOf2(raw),
357
+ status: CAMPAIGN_STATUSES.get(lower(raw.status)) ?? "unknown",
358
+ tags: tagNames(raw.tags)
359
+ });
360
+ var DAYS = [
361
+ "sunday",
362
+ "monday",
363
+ "tuesday",
364
+ "wednesday",
365
+ "thursday",
366
+ "friday",
367
+ "saturday"
368
+ ];
369
+ var clock = (value) => {
370
+ const time = text(value);
371
+ return time !== null && /^\d{2}:\d{2}$/u.test(time) ? time : null;
372
+ };
373
+ var toWindow = (schedule) => ({
374
+ days: DAYS.flatMap((day, index) => schedule[day] === true ? [index] : []),
375
+ from: clock(schedule.start_time),
376
+ name: text(schedule.type),
377
+ timezone: text(schedule.timezone),
378
+ to: clock(schedule.end_time)
379
+ });
380
+ var toSettings = (identity, campaign, schedule) => ({
381
+ ...recordBase(identity, idOf2(campaign), { campaign, schedule }),
382
+ campaignRef: refTo(identity, idOf2(campaign)) ?? "",
383
+ dailyLimit: count(campaign.max_emails_per_day),
384
+ dailyNewLeads: count(campaign.max_new_leads_per_day),
385
+ endDate: null,
386
+ gapMinutes: null,
387
+ plainText: flag(campaign.plain_text),
388
+ schedule: schedule === null ? [] : [toWindow(schedule)],
389
+ startDate: null,
390
+ stopOnAutoReply: null,
391
+ stopOnReply: null,
392
+ // Only open tracking is a campaign setting.
393
+ tracking: { clicks: null, opens: flag(campaign.open_tracking) }
394
+ });
395
+ var SENDER_STATUSES = /* @__PURE__ */ new Map([
396
+ ["connected", "active"],
397
+ ["not_connected", "disconnected"],
398
+ ["not connected", "disconnected"],
399
+ ["disconnected", "disconnected"]
400
+ ]);
401
+ var senderStatus = (raw) => SENDER_STATUSES.get(lower(raw.status)) ?? "unknown";
402
+ var mailProvider = (value) => {
403
+ const type = lower(value);
404
+ if (type.startsWith("google")) {
405
+ return "google";
406
+ }
407
+ if (type.startsWith("microsoft") || type.startsWith("outlook")) {
408
+ return "microsoft";
409
+ }
410
+ return type === "custom" || type.includes("imap") || type.includes("smtp") ? "smtp" : null;
411
+ };
412
+ var toSender = (identity, raw) => {
413
+ const enabled = flag(raw.warmup_enabled);
414
+ return {
415
+ ...recordBase(identity, idOf2(raw), raw),
416
+ address: emailAddress(raw.email),
417
+ dailyLimit: count(raw.daily_limit),
418
+ kind: "mailbox",
419
+ linkedinUrl: null,
420
+ mailProvider: mailProvider(raw.type),
421
+ name: text(raw.name),
422
+ status: senderStatus(raw),
423
+ tags: tagNames(raw.tags),
424
+ // The sender reads report whether warmup is on; its score is on the
425
+ // warmup reads, which sender health reads.
426
+ warmup: enabled === null ? null : { enabled, score: null }
427
+ };
428
+ };
429
+ var PROGRESS = /* @__PURE__ */ new Map([
430
+ ["active", "active"],
431
+ ["completed", "completed"],
432
+ ["finished", "completed"],
433
+ ["in_sequence", "active"],
434
+ ["never_contacted", "active"],
435
+ ["not_contacted", "active"],
436
+ ["paused", "paused"],
437
+ ["sequence_finished", "completed"],
438
+ ["sequence_stopped", "paused"],
439
+ ["stopped", "paused"]
440
+ ]);
441
+ var customOf = (value) => Object.fromEntries(
442
+ objects(value).flatMap((variable) => {
443
+ const name = text(variable.name);
444
+ const content = variable.value;
445
+ return name === null || content === null || content === void 0 ? [] : [[name, isString(content) ? content : String(text(content) ?? "")]];
446
+ })
447
+ );
448
+ var engagementOf = (stats) => {
449
+ if (stats === void 0 || stats === null) {
450
+ return null;
451
+ }
452
+ return {
453
+ clicks: null,
454
+ lastContactedAt: null,
455
+ lastOpenedAt: null,
456
+ lastRepliedAt: null,
457
+ opens: count(field(stats, "opens")),
458
+ replies: count(field(stats, "replies")),
459
+ repliedStepIndex: null,
460
+ stepIndex: null
461
+ };
462
+ };
463
+ var repliedOf = (stats) => {
464
+ const replies = count(field(stats, "replies"));
465
+ return replies === null ? null : replies > 0;
466
+ };
467
+ var toLead = (identity, raw, campaignId = null) => {
468
+ const verification = lower(raw.status);
469
+ const inCampaign = field(raw, "lead_campaign_data");
470
+ const interested = flag(field(inCampaign, "interested"));
471
+ return {
472
+ ...recordBase(identity, idOf2(raw), raw),
473
+ ...leadStanding(
474
+ PROGRESS.get(lower(field(inCampaign, "status"))) ?? "unknown",
475
+ {
476
+ bounced: verification === "bounced" ? true : null,
477
+ replied: repliedOf(raw.overall_stats),
478
+ unsubscribed: verification === "unsubscribed" ? true : null
479
+ }
480
+ ),
481
+ campaignRef: refTo(identity, campaignId),
482
+ company: text(raw.company),
483
+ companyLinkedinUrl: null,
484
+ createdAt: timestamp(raw.created_at),
485
+ custom: customOf(raw.custom_variables),
486
+ email: emailAddress(raw.email),
487
+ engagement: engagementOf(raw.overall_stats),
488
+ firstName: text(raw.first_name),
489
+ interest: interested === true ? "Interested" : null,
490
+ interestCategory: interested === true ? "positive" : null,
491
+ lastName: text(raw.last_name),
492
+ linkedinUrl: null,
493
+ location: null,
494
+ phone: null,
495
+ tags: [],
496
+ title: text(raw.title),
497
+ website: null
498
+ };
499
+ };
500
+ var toLeadList = (identity, raw) => ({
501
+ ...recordBase(identity, idOf2(raw), raw),
502
+ createdAt: timestamp(raw.created_at),
503
+ kind: "leads",
504
+ name: text(raw.name) ?? idOf2(raw),
505
+ size: count(raw.leads_succeeded)
506
+ });
507
+ var toBlockEntry = (identity, raw, kind) => {
508
+ const value = text(kind === "email" ? raw.email : raw.domain)?.toLowerCase();
509
+ return value === void 0 ? [] : [
510
+ {
511
+ ...recordBase(identity, `${kind}-${idOf2(raw)}`, raw),
512
+ createdAt: timestamp(raw.created_at),
513
+ kind,
514
+ value
515
+ }
516
+ ];
517
+ };
518
+ var toTag = (identity, raw) => {
519
+ const name = text(raw.name);
520
+ return name === null ? [] : [{ ...recordBase(identity, idOf2(raw), raw), description: null, name }];
521
+ };
522
+ var EVENT_TYPES = /* @__PURE__ */ new Map([
523
+ ["blacklisted_domain_added", "unknown"],
524
+ ["blacklisted_domain_removed", "unknown"],
525
+ ["blacklisted_email_added", "unknown"],
526
+ ["blacklisted_email_removed", "unknown"],
527
+ ["email_account_added", "sender.status_changed"],
528
+ ["email_account_disconnected", "sender.status_changed"],
529
+ ["email_account_reconnected", "sender.status_changed"],
530
+ ["email_account_removed", "sender.status_changed"],
531
+ ["email_bounced", "message.bounced"],
532
+ ["email_opened", "message.opened"],
533
+ ["email_send_failed", "unknown"],
534
+ ["email_sent", "message.sent"],
535
+ ["lead_first_contacted", "message.sent"],
536
+ ["lead_interested", "reply.categorized"],
537
+ ["lead_replied", "reply.received"],
538
+ ["lead_unsubscribed", "lead.unsubscribed"],
539
+ ["manual_email_send_failed", "unknown"],
540
+ ["manual_email_sent", "message.sent"],
541
+ ["tag_attached", "unknown"],
542
+ ["tag_removed", "unknown"],
543
+ ["untracked_reply_received", "reply.received"],
544
+ ["warmup_disabled_causing_bounces", "sender.status_changed"],
545
+ ["warmup_disabled_receiving_bounces", "sender.status_changed"]
546
+ ]);
547
+ var toWebhook = (identity, raw) => {
548
+ const events = list(raw.events).flatMap((name) => text(name) ?? []);
549
+ return {
550
+ ...recordBase(identity, idOf2(raw), raw),
551
+ active: null,
552
+ campaignRefs: [],
553
+ createdAt: timestamp(raw.created_at),
554
+ eventTypes: eventTypesOf(
555
+ events.map((name) => name.toLowerCase()),
556
+ EVENT_TYPES
557
+ ),
558
+ events,
559
+ name: text(raw.name),
560
+ url: text(raw.url) ?? ""
561
+ };
562
+ };
563
+ var toWorkspace = (identity, raw) => ({
564
+ // A workspace carries its webhook signing secret, which no record keeps.
565
+ ...recordBase(identity, idOf2(raw), withoutKeys(raw, SECRET_KEYS)),
566
+ name: text(raw.name) ?? idOf2(raw)
567
+ });
568
+
569
+ // src/emailbison/webhooks.ts
570
+ var objectAt = (value, key) => {
571
+ const found = field(value, key);
572
+ return isJsonObject(found) ? found : null;
573
+ };
574
+ var idAt = (data, key) => text(field(data[key], "id"));
575
+ var messageId = (data) => {
576
+ const reply = idAt(data, "reply");
577
+ if (reply !== null) {
578
+ return reply;
579
+ }
580
+ const scheduled = idAt(data, "scheduled_email");
581
+ return scheduled === null ? null : `${SENT_PREFIX}${scheduled}`;
582
+ };
583
+ var occurredAt = (data) => timestamp(field(data.campaign_event, "created_at")) ?? timestamp(field(data.reply, "date_received")) ?? timestamp(field(data.scheduled_email, "sent_at"));
584
+ var dataOf = (name, event, data) => {
585
+ const lead = objectAt(data, "lead");
586
+ const reply = objectAt(data, "reply");
587
+ const scheduled = objectAt(data, "scheduled_email");
588
+ const lowered = name.toLowerCase();
589
+ return eventData(
590
+ {
591
+ campaignName: text(field(data.campaign, "name")),
592
+ category: lowered === "lead_interested" ? "positive" : void 0,
593
+ isAuto: flag(field(reply, "automated_reply")) ?? void 0,
594
+ isFirst: lowered === "lead_first_contacted" ? true : void 0,
595
+ leadEmail: emailAddress(field(lead, "email")),
596
+ leadName: fullName(field(lead, "first_name"), field(lead, "last_name")),
597
+ senderEmail: emailAddress(field(data.sender_email, "email")),
598
+ subject: text(field(reply, "email_subject")) ?? text(field(reply, "subject")) ?? text(field(scheduled, "email_subject")),
599
+ text: text(field(reply, "text_body")),
600
+ untracked: lowered === "untracked_reply_received" ? true : void 0,
601
+ vendorEvent: name
602
+ },
603
+ {
604
+ tagName: text(data.tag_name),
605
+ taggableId: text(data.taggable_id),
606
+ taggableType: text(data.taggable_type),
607
+ vendorWorkspaceId: text(event.workspace_id),
608
+ vendorWorkspaceName: text(event.workspace_name)
609
+ }
610
+ );
611
+ };
612
+ var toEvent = (identity, body) => {
613
+ const event = objectAt(body, "event") ?? {};
614
+ const data = objectAt(body, "data") ?? {};
615
+ const name = text(event.type) ?? "";
616
+ const message = messageId(data);
617
+ const time = occurredAt(data);
618
+ return {
619
+ campaignRef: refTo(identity, idAt(data, "campaign")),
620
+ data: dataOf(name, event, data),
621
+ // No event id is sent. The type and the ids it names are the same on
622
+ // every delivery of one event.
623
+ id: stableId(
624
+ identity.provider,
625
+ name,
626
+ text(event.workspace_id),
627
+ message,
628
+ idAt(data, "lead"),
629
+ idAt(data, "sender_email"),
630
+ text(data.tag_id),
631
+ text(data.taggable_id),
632
+ text(field(data.campaign_event, "id")),
633
+ time
634
+ ),
635
+ leadRef: refTo(identity, idAt(data, "lead")),
636
+ messageRef: refTo(identity, message),
637
+ occurredAt: time,
638
+ provider: identity.provider,
639
+ raw: body,
640
+ schemaVersion: SCHEMA_VERSION,
641
+ senderRef: refTo(identity, idAt(data, "sender_email")),
642
+ type: EVENT_TYPES.get(name.toLowerCase()) ?? "unknown",
643
+ workspaceId: identity.workspaceId
644
+ };
645
+ };
646
+ var detect = (request) => isJsonObject(request.body) && isJsonObject(request.body.event) && isString(request.body.event.type) && isJsonObject(request.body.data);
647
+ var emailbisonEvents = (provider) => ({
648
+ detect,
649
+ parse: (request, workspaceId) => isJsonObject(request.body) ? [toEvent({ provider, workspaceId }, request.body)] : []
650
+ });
651
+
652
+ export {
653
+ API_KEY_ENV,
654
+ BASE_URL_ENV,
655
+ WORKSPACE_ENV,
656
+ capabilities,
657
+ fields,
658
+ limits,
659
+ costs,
660
+ caveats,
661
+ createClient,
662
+ toCampaign,
663
+ toSettings,
664
+ senderStatus,
665
+ toSender,
666
+ toLead,
667
+ toLeadList,
668
+ toBlockEntry,
669
+ toTag,
670
+ toWebhook,
671
+ toWorkspace,
672
+ toSentMessage,
673
+ toInboxMessage,
674
+ toReply,
675
+ emailbisonEvents
676
+ };