@billionsend/cli 0.2.5 → 0.3.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 (3) hide show
  1. package/README.md +19 -14
  2. package/dist/index.js +755 -197
  3. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -89,11 +89,18 @@ var AuthError = class extends Error {
89
89
  var ApiError = class extends Error {
90
90
  status;
91
91
  body;
92
- constructor(status2, name, message, body = null) {
92
+ /**
93
+ * The request was sent once and not again because it may have written something (a POST or
94
+ * PATCH that failed with a 5xx, a timeout or a lost connection). The caller records it as a
95
+ * failure; a re-run picks it up.
96
+ */
97
+ sentOnce;
98
+ constructor(status2, name, message, body = null, sentOnce = false) {
93
99
  super(message);
94
100
  this.name = name;
95
101
  this.status = status2;
96
102
  this.body = body;
103
+ this.sentOnce = sentOnce;
97
104
  }
98
105
  };
99
106
  var PaginationError = class extends Error {
@@ -142,7 +149,32 @@ function cursorGuard(path2, maxPages = MAX_PAGES) {
142
149
  for (const row of page) seen.add(row.id);
143
150
  };
144
151
  }
152
+ var route = (strings, ...values) => strings.reduce(
153
+ (out, text, i) => out + text + (i < values.length ? encodeURIComponent(values[i] ?? "") : ""),
154
+ ""
155
+ );
156
+ function badSegment(pathname) {
157
+ for (const segment of pathname.split("/").slice(1)) {
158
+ let decoded = segment;
159
+ try {
160
+ decoded = decodeURIComponent(segment);
161
+ } catch {
162
+ }
163
+ if (decoded === "" || decoded === "." || decoded === "..")
164
+ return decoded === "" ? "an empty one" : `\`${decoded}\``;
165
+ }
166
+ return null;
167
+ }
168
+ var HEADER_VALUE = /^[\t\x20-\x7e]*$/;
169
+ var RequestError = class extends Error {
170
+ constructor(message) {
171
+ super(message);
172
+ this.name = "invalid_request";
173
+ }
174
+ };
145
175
  var MAX_WAIT_MS = 12e4;
176
+ var MAX_RETRY_AFTER_MS = 6e4;
177
+ var REPEATABLE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE"]);
146
178
  var REMAINING_RESERVE = 2;
147
179
  var clampWait = (ms) => Math.min(MAX_WAIT_MS, Math.max(0, ms));
148
180
  function headerNumber(headers, name) {
@@ -227,11 +259,18 @@ function createHttp(options) {
227
259
  holdUntil = Math.max(holdUntil, Date.now() + clampWait(reset * 1e3));
228
260
  }
229
261
  };
230
- async function request(method, path2, body, { query, headers: extraHeaders } = {}) {
262
+ async function request(method, path2, body, { query, headers: extraHeaders, idempotent = false } = {}) {
231
263
  if (options.readOnly === true && method !== "GET") {
232
264
  throw new Error(`${name} is read-only for this tool; refusing ${method} ${path2}`);
233
265
  }
234
- const url = new URL(base + (path2.startsWith("/") ? path2 : `/${path2}`));
266
+ const rawPath = path2.startsWith("/") ? path2 : `/${path2}`;
267
+ const bad = badSegment(rawPath.split("?")[0] ?? rawPath);
268
+ if (bad !== null) {
269
+ throw new RequestError(
270
+ `${name}: ${method} ${rawPath.split("?")[0]} has ${bad} as a path segment; an id is missing or not an id`
271
+ );
272
+ }
273
+ const url = new URL(base + rawPath);
235
274
  for (const [key, value] of Object.entries(query ?? {})) {
236
275
  if (value !== void 0) url.searchParams.set(key, String(value));
237
276
  }
@@ -243,11 +282,19 @@ function createHttp(options) {
243
282
  ...body === void 0 ? {} : { "content-type": "application/json" },
244
283
  ...extraHeaders
245
284
  };
285
+ for (const [header, value] of Object.entries(headers)) {
286
+ if (!HEADER_VALUE.test(value)) {
287
+ throw new RequestError(
288
+ `${name}: the ${header} header holds a character a header cannot carry (only printable ASCII is allowed)${header === "authorization" ? "; check the API key for a stray line break or non-ASCII character" : ""}`
289
+ );
290
+ }
291
+ }
246
292
  const init = {
247
293
  method,
248
294
  headers,
249
295
  ...body === void 0 ? {} : { body: JSON.stringify(body) }
250
296
  };
297
+ const repeatable = idempotent || REPEATABLE_METHODS.has(method);
251
298
  let rateLimited = 0;
252
299
  let failures = 0;
253
300
  for (; ; ) {
@@ -259,12 +306,14 @@ function createHttp(options) {
259
306
  } catch (error) {
260
307
  const reason = networkReason(error);
261
308
  failures += 1;
262
- if (failures >= maxAttempts) {
309
+ if (!repeatable || failures >= maxAttempts) {
263
310
  const hint = name === "BillionSend" ? "check --to-url / BILLIONSEND_BASE_URL" : `check your network to ${url.host}`;
264
311
  throw new ApiError(
265
312
  0,
266
313
  "network_error",
267
- `${name}: ${label} failed ${failures} times \u2014 ${reason}; ${hint}`
314
+ `${name}: ${label} failed ${failures} times \u2014 ${reason}; ${hint}`,
315
+ null,
316
+ !repeatable
268
317
  );
269
318
  }
270
319
  const wait = 1e3 * 2 ** (failures - 1);
@@ -290,6 +339,14 @@ function createHttp(options) {
290
339
  );
291
340
  }
292
341
  const wait = retryAfterMs(response.headers) ?? 2e3;
342
+ if (wait > MAX_RETRY_AFTER_MS) {
343
+ throw new ApiError(
344
+ 429,
345
+ "rate_limit_exceeded",
346
+ `${name} asks to wait ${Math.round(wait / 1e3)}s after rate limiting ${label}; not waiting more than ${MAX_RETRY_AFTER_MS / 1e3}s`,
347
+ parsed
348
+ );
349
+ }
293
350
  rps = Math.max(1, rps / 2);
294
351
  rampedAt = Date.now();
295
352
  log.warn(
@@ -300,12 +357,13 @@ function createHttp(options) {
300
357
  }
301
358
  if (status2 >= 500) {
302
359
  failures += 1;
303
- if (failures >= maxAttempts) {
360
+ if (!repeatable || failures >= maxAttempts) {
304
361
  throw new ApiError(
305
362
  status2,
306
363
  "server_error",
307
- `${name} answered ${status2} to ${label} ${failures} times`,
308
- parsed
364
+ `${name} answered ${status2} to ${label}${failures > 1 ? ` ${failures} times` : ""}${repeatable ? "" : "; it is not sent again, because it may have been written (run again to continue)"}`,
365
+ parsed,
366
+ !repeatable
309
367
  );
310
368
  }
311
369
  const wait = 1e3 * 2 ** (failures - 1);
@@ -449,26 +507,52 @@ var emptySnapshot = () => ({
449
507
  webhooks: [],
450
508
  suppressions: [],
451
509
  metrics: { emailsLast30Days: null },
452
- enriched: false
510
+ enriched: false,
511
+ segmentScope: null
453
512
  });
513
+ var SEGMENT_HINT_MAX = 30;
514
+ function selectSegments(all, selectors) {
515
+ const picked = [];
516
+ const missing = [];
517
+ for (const selector of selectors) {
518
+ const lower = selector.toLowerCase();
519
+ const matches = [
520
+ all.filter((s) => s.id === selector),
521
+ all.filter((s) => s.name === selector),
522
+ all.filter((s) => s.name.toLowerCase() === lower)
523
+ ].find((found) => found.length > 0);
524
+ if (matches === void 0) missing.push(selector);
525
+ else for (const match of matches) if (!picked.includes(match)) picked.push(match);
526
+ }
527
+ if (missing.length > 0) {
528
+ const shown = all.slice(0, SEGMENT_HINT_MAX).map((s) => ` ${s.name} (${s.id})`);
529
+ const more = all.length - shown.length;
530
+ throw new Error(
531
+ `No Resend segment named or with the id ${missing.map((m) => `\`${m}\``).join(", ")}. ${all.length === 0 ? "The account has no segments." : `Segments on the account:
532
+ ${shown.join("\n")}${more > 0 ? `
533
+ \u2026 and ${more} more` : ""}`}`
534
+ );
535
+ }
536
+ return picked;
537
+ }
454
538
  function createResendSource(http, log) {
455
539
  let requests = 0;
456
- const get = (route, options) => {
540
+ const get = (route2, options) => {
457
541
  requests += 1;
458
- return http.get(route, options);
542
+ return http.get(route2, options);
459
543
  };
460
- async function listAll(route, query = {}, label, onProgress) {
544
+ async function listAll(route2, query = {}, label, onProgress) {
461
545
  const items = [];
462
546
  let after;
463
- const guard = cursorGuard(route);
547
+ const guard = cursorGuard(route2);
464
548
  for (; ; ) {
465
- const { body } = await get(route, { query: { ...query, limit: PAGE, after } });
466
- const data = pageItems(route, body, after);
549
+ const { body } = await get(route2, { query: { ...query, limit: PAGE, after } });
550
+ const data = pageItems(route2, body, after);
467
551
  guard(data, after);
468
552
  items.push(...data);
469
553
  const hasMore = body.has_more ?? data.length === PAGE;
470
554
  if (!hasMore || data.length === 0) break;
471
- after = nextCursor(route, data, after);
555
+ after = nextCursor(route2, data, after);
472
556
  if (label !== void 0) onProgress?.({ label, n: items.length, done: false });
473
557
  }
474
558
  if (label !== void 0) {
@@ -476,8 +560,8 @@ function createResendSource(http, log) {
476
560
  }
477
561
  return items;
478
562
  }
479
- async function listWithDetails(route, label, onProgress, detail, keep = () => true) {
480
- const list = (await listAll(route)).filter(keep);
563
+ async function listWithDetails(route2, label, onProgress, detail, keep = () => true) {
564
+ const list = (await listAll(route2)).filter(keep);
481
565
  const out = [];
482
566
  for (const item of list) {
483
567
  out.push(await detail(item));
@@ -486,6 +570,23 @@ function createResendSource(http, log) {
486
570
  onProgress?.({ label, n: out.length, total: list.length, done: true });
487
571
  return out;
488
572
  }
573
+ async function readSegments(scope, onProgress, membersOf) {
574
+ const list = scope ?? await listAll("/segments");
575
+ const out = [];
576
+ for (const item of list) {
577
+ const { body } = await get(path("segments", item.id));
578
+ const members = await membersOf(item.id);
579
+ out.push({
580
+ id: item.id,
581
+ name: body.name ?? item.name,
582
+ filter: body.filter ?? null,
583
+ memberEmails: members.map((member) => member.email)
584
+ });
585
+ onProgress?.({ label: "Segments", n: out.length, total: list.length, done: false });
586
+ }
587
+ onProgress?.({ label: "Segments", n: out.length, total: list.length, done: true });
588
+ return out;
589
+ }
489
590
  return {
490
591
  get requests() {
491
592
  return requests;
@@ -495,8 +596,19 @@ function createResendSource(http, log) {
495
596
  const first = body.data?.[0];
496
597
  return first === void 0 ? { ok: true } : { ok: true, teamHint: first.name };
497
598
  },
498
- async readShallow({ include, includeSent = false, onProgress }) {
599
+ async readShallow({ include, includeSent = false, segments = [], onProgress }) {
499
600
  const snapshot = emptySnapshot();
601
+ const needsContacts = include.has("contacts") || include.has("enrichment");
602
+ const scope = segments.length === 0 ? null : selectSegments(await listAll("/segments"), segments);
603
+ if (scope !== null) snapshot.segmentScope = scope.map(({ id, name }) => ({ id, name }));
604
+ const memberLists = /* @__PURE__ */ new Map();
605
+ const membersOf = async (id) => {
606
+ const cached = memberLists.get(id);
607
+ if (cached !== void 0) return cached;
608
+ const members = await listAll(path("segments", id, "contacts"), {});
609
+ memberLists.set(id, members);
610
+ return members;
611
+ };
500
612
  if (include.has("domains")) {
501
613
  snapshot.domains = await listWithDetails(
502
614
  "/domains",
@@ -529,26 +641,30 @@ function createResendSource(http, log) {
529
641
  visibility: topic.visibility
530
642
  }));
531
643
  }
532
- if (include.has("segments")) {
533
- snapshot.segments = await listWithDetails(
534
- "/segments",
535
- "Segments",
536
- onProgress,
537
- async (item) => {
538
- const { body } = await get(path("segments", item.id));
539
- const members = await listAll(`/segments/${item.id}/contacts`, {});
540
- return {
541
- id: item.id,
542
- name: body.name ?? item.name,
543
- filter: body.filter ?? null,
544
- memberEmails: members.map((member) => member.email)
545
- };
546
- }
644
+ if (include.has("segments") || scope !== null && needsContacts) {
645
+ snapshot.segments = await readSegments(
646
+ scope,
647
+ include.has("segments") ? onProgress : void 0,
648
+ membersOf
547
649
  );
548
650
  }
549
- if (include.has("contacts") || include.has("enrichment")) {
550
- const list = await listAll("/contacts", {}, "Contacts", onProgress);
551
- snapshot.contacts = list.map(toContact);
651
+ if (needsContacts) {
652
+ if (scope === null) {
653
+ const list = await listAll("/contacts", {}, "Contacts", onProgress);
654
+ snapshot.contacts = list.map(toContact);
655
+ } else {
656
+ const seen = /* @__PURE__ */ new Set();
657
+ const members = [];
658
+ for (const segment of scope) {
659
+ for (const member of await membersOf(segment.id)) {
660
+ if (seen.has(member.id)) continue;
661
+ seen.add(member.id);
662
+ members.push(member);
663
+ }
664
+ }
665
+ onProgress?.({ label: "Contacts", n: members.length, total: members.length, done: true });
666
+ snapshot.contacts = members.map(toContact);
667
+ }
552
668
  }
553
669
  if (include.has("broadcasts")) {
554
670
  snapshot.broadcasts = await listWithDetails(
@@ -661,7 +777,7 @@ function createResendSource(http, log) {
661
777
  var pagesOf = (count) => Math.max(1, Math.ceil(count / PAGE));
662
778
  function estimateSourceRequests(snapshot) {
663
779
  const s = snapshot;
664
- const spent = pagesOf(s.domains.length) + s.domains.length + pagesOf(s.properties.length) + pagesOf(s.topics.length) + pagesOf(s.segments.length) + s.segments.reduce((sum, segment) => sum + 1 + pagesOf(segment.memberEmails.length), 0) + pagesOf(s.contacts.length) + pagesOf(s.broadcasts.length) + s.broadcasts.filter((b) => b.status !== "sent" || b.html !== null || b.text !== null).length + pagesOf(s.templates.length) + s.templates.length + pagesOf(s.webhooks.length) + s.webhooks.length + pagesOf(s.suppressions.length) + pagesOf(s.apiKeys.length);
780
+ const spent = pagesOf(s.domains.length) + s.domains.length + pagesOf(s.properties.length) + pagesOf(s.topics.length) + pagesOf(s.segments.length) + s.segments.reduce((sum, segment) => sum + 1 + pagesOf(segment.memberEmails.length), 0) + (s.segmentScope === null ? pagesOf(s.contacts.length) : 0) + pagesOf(s.broadcasts.length) + s.broadcasts.filter((b) => b.status !== "sent" || b.html !== null || b.text !== null).length + pagesOf(s.templates.length) + s.templates.length + pagesOf(s.webhooks.length) + s.webhooks.length + pagesOf(s.suppressions.length) + pagesOf(s.apiKeys.length);
665
781
  const facets = (s.properties.length > 0 ? 1 : 0) + (s.topics.length > 0 ? 1 : 0);
666
782
  return { spent, enrichment: s.contacts.length * facets };
667
783
  }
@@ -824,18 +940,13 @@ function bannerLines(tier = "full") {
824
940
  function banner(tier = "full") {
825
941
  return bannerLines(tier);
826
942
  }
827
- async function selectPrompt(rl, {
828
- label,
829
- options,
830
- initial,
831
- rail = false
832
- }) {
943
+ async function selectPrompt(rl, { label, options, initial }) {
833
944
  const fallback = initial ?? options[0]?.value ?? "";
834
945
  if (!isInteractive()) {
835
946
  const answer = (await rl.question(`${label} [${fallback}]: `)).trim();
836
947
  return answer || fallback;
837
948
  }
838
- return selectTty(label, options, fallback, rail);
949
+ return selectTty(label, options, fallback);
839
950
  }
840
951
  var isEnter = (key) => key.name === "return" || key.name === "enter";
841
952
  function readKeys(onKey, erase, stdout = process.stdout) {
@@ -883,13 +994,7 @@ function optionRow(prefix, { label, hint }, selected, columns) {
883
994
  const tail = text.slice(label.length);
884
995
  return `${(selected ? bone : dim)(`${prefix}${head}`)}${tail ? dim(tail) : ""}`;
885
996
  }
886
- function railOptionRow({ label, hint }, selected, columns) {
887
- const text = truncate(`${label}${hint ? ` ${hint}` : ""}`, columns - 6);
888
- const head = text.slice(0, label.length);
889
- const tail = text.slice(label.length);
890
- return `${dim("\u2502")} ${selected ? info("\u25CF") : dim("\u25CB")} ${selected ? bone(head) : dim(head)}${dim(tail)}`;
891
- }
892
- async function selectTty(label, options, initial, rail = false) {
997
+ async function selectTty(label, options, initial) {
893
998
  const { stdout } = process;
894
999
  let index = Math.max(
895
1000
  0,
@@ -899,11 +1004,7 @@ async function selectTty(label, options, initial, rail = false) {
899
1004
  const render = (first) => {
900
1005
  if (!first) eraseRows(height);
901
1006
  const columns = terminalColumns();
902
- const lines = rail ? [
903
- `${info("\u25C6")} ${bold(label)}`,
904
- ...options.map((o, i) => railOptionRow(o, i === index, columns)),
905
- dim("\u2502")
906
- ] : [
1007
+ const lines = [
907
1008
  label,
908
1009
  ...options.map((o, i) => optionRow(i === index ? "\u276F " : " ", o, i === index, columns))
909
1010
  ];
@@ -929,13 +1030,8 @@ async function selectTty(label, options, initial, rail = false) {
929
1030
  () => eraseRows(height)
930
1031
  );
931
1032
  const chosen = options.find((o) => o.value === value)?.label ?? value;
932
- stdout.write(
933
- rail ? `${dim("\u25C7")} ${label}
934
- ${dim("\u2502")} ${dim(chosen)}
935
- ${dim("\u2502")}
936
- ` : `${answerLine(label, chosen)}
937
- `
938
- );
1033
+ stdout.write(`${answerLine(label, chosen)}
1034
+ `);
939
1035
  return value;
940
1036
  }
941
1037
  async function multiSelectPrompt(rl, { label, options }) {
@@ -1006,7 +1102,7 @@ ${labels.map((l) => wrapIndent(l, { indent: " " })).join("\n")}
1006
1102
  function maskSecret(secret) {
1007
1103
  return secret.length >= 12 ? `${secret.slice(0, 3)}****\u2026${secret.slice(-4)}` : "****";
1008
1104
  }
1009
- async function secretPrompt(rl, { label, rail = false }) {
1105
+ async function secretPrompt(rl, { label }) {
1010
1106
  const mode2 = secretPromptMode(process.stdin.isTTY === true, process.stdout.isTTY === true);
1011
1107
  if (!mode2.masked) return (await rl.question(`${label}: `)).trim();
1012
1108
  const stdout = mode2.toStderr ? process.stderr : process.stdout;
@@ -1015,7 +1111,7 @@ async function secretPrompt(rl, { label, rail = false }) {
1015
1111
  if (ahead !== void 0) {
1016
1112
  secret = ahead.trim();
1017
1113
  } else {
1018
- stdout.write(rail ? `${dim("\u2502")} ` : `${label}: `);
1114
+ stdout.write(`${label}: `);
1019
1115
  let value = "";
1020
1116
  secret = await readKeys(
1021
1117
  (str, key) => {
@@ -1028,12 +1124,8 @@ async function secretPrompt(rl, { label, rail = false }) {
1028
1124
  stdout
1029
1125
  );
1030
1126
  }
1031
- stdout.write(
1032
- rail ? `${dim("\u2502")} ${dim(maskSecret(secret))}
1033
- ${dim("\u2502")}
1034
- ` : `${label}: ${dim(maskSecret(secret))}
1035
- `
1036
- );
1127
+ stdout.write(`${label}: ${dim(maskSecret(secret))}
1128
+ `);
1037
1129
  return secret;
1038
1130
  }
1039
1131
  async function confirmPrompt(rl, { label, initial = false }) {
@@ -1079,11 +1171,20 @@ var SYM = {
1079
1171
  skip: "\u2212"
1080
1172
  };
1081
1173
  var layoutWidth = () => Math.min(process.stdout.columns ?? 80, 100);
1174
+ var KEEP = "\u241F";
1082
1175
  function wrapIndent(text, {
1083
1176
  width = layoutWidth(),
1084
1177
  indent = "",
1085
- hanging = indent
1178
+ hanging = indent,
1179
+ keep = []
1086
1180
  } = {}) {
1181
+ if (keep.length > 0) {
1182
+ let guarded = text;
1183
+ for (const token of keep) {
1184
+ if (/\s/.test(token)) guarded = guarded.split(token).join(token.replace(/\s+/g, KEEP));
1185
+ }
1186
+ return wrapIndent(guarded, { width, indent, hanging }).split(KEEP).join(" ");
1187
+ }
1087
1188
  const lines = [];
1088
1189
  let line = indent;
1089
1190
  let empty = true;
@@ -1127,13 +1228,22 @@ var TARGET_WEBHOOK_EVENTS = [
1127
1228
  "contact.created",
1128
1229
  "contact.updated",
1129
1230
  "contact.deleted",
1231
+ "contact.topics.updated",
1130
1232
  "suppression.added",
1131
1233
  "suppression.removed",
1234
+ "domain.created",
1235
+ "domain.updated",
1236
+ "domain.deleted",
1237
+ "topic.created",
1238
+ "topic.updated",
1239
+ "topic.deleted",
1132
1240
  "inbox.created",
1133
1241
  "inbox.updated",
1134
1242
  "inbox.deleted",
1135
1243
  "inbox.thread.created",
1136
1244
  "inbox.thread.folder.updated",
1245
+ "inbox.thread.assigned",
1246
+ "inbox.thread.unassigned",
1137
1247
  "inbox.thread.labels.updated",
1138
1248
  "inbox.email.received",
1139
1249
  "inbox.email.sent",
@@ -1291,16 +1401,45 @@ function domainCreateInput(domain) {
1291
1401
  };
1292
1402
  return { input, tracking };
1293
1403
  }
1404
+ var TEMPLATE_VARIABLES_MAX = 50;
1405
+ var TEMPLATE_VARIABLE_KEY_RE = /^[A-Za-z0-9_]{1,50}$/;
1406
+ var TEMPLATE_REPLY_TO_MAX = 50;
1294
1407
  var listTokens = (tokens) => tokens.join(", ");
1295
1408
  function templateCreateInput(t) {
1296
1409
  const notes = [];
1297
- if (t.from) notes.push(`from ${t.from} is not stored on templates; pass it when sending`);
1298
- if (t.replyTo?.length)
1299
- notes.push(`reply_to ${t.replyTo.join(", ")} is not stored on templates; pass it when sending`);
1300
- if (t.variables.length > 0)
1410
+ const replyTo = t.replyTo ?? [];
1411
+ if (replyTo.length > TEMPLATE_REPLY_TO_MAX) {
1412
+ notes.push(
1413
+ `reply_to has ${replyTo.length} addresses; a template stores ${TEMPLATE_REPLY_TO_MAX}, the first ${TEMPLATE_REPLY_TO_MAX} were kept`
1414
+ );
1415
+ }
1416
+ const keyOk = (key) => TEMPLATE_VARIABLE_KEY_RE.test(key);
1417
+ const typeOk = (type) => type === "string" || type === "number";
1418
+ const badKey = t.variables.filter((v) => !keyOk(v.key));
1419
+ const badType = t.variables.filter((v) => keyOk(v.key) && !typeOk(v.type));
1420
+ const usable = t.variables.filter((v) => keyOk(v.key) && typeOk(v.type));
1421
+ if (badKey.length > 0) {
1301
1422
  notes.push(
1302
- `variables ${t.variables.map((v) => v.key).join(", ")} are not stored; merge fields resolve from contact properties`
1423
+ `variables ${badKey.map((v) => v.key).join(", ")} not stored: a key is 1\u201350 letters, digits or underscores`
1303
1424
  );
1425
+ }
1426
+ if (badType.length > 0) {
1427
+ notes.push(
1428
+ `variables ${badType.map((v) => `${v.key} (${v.type})`).join(", ")} not stored: BillionSend variables are strings or numbers`
1429
+ );
1430
+ }
1431
+ const variables = usable.slice(0, TEMPLATE_VARIABLES_MAX).map(
1432
+ (v) => ({
1433
+ key: v.key,
1434
+ type: v.type === "number" ? "number" : "string",
1435
+ ...v.fallbackValue === void 0 ? {} : { fallback_value: v.fallbackValue }
1436
+ })
1437
+ );
1438
+ if (usable.length > TEMPLATE_VARIABLES_MAX) {
1439
+ notes.push(
1440
+ `${usable.length} variables; a template stores ${TEMPLATE_VARIABLES_MAX}, the first ${TEMPLATE_VARIABLES_MAX} were kept`
1441
+ );
1442
+ }
1304
1443
  if (!t.html) return { input: null, notes, reason: "template has no html body" };
1305
1444
  const html = translateMergeTags(t.html);
1306
1445
  const subject = t.subject ? translateMergeTags(t.subject) : null;
@@ -1316,9 +1455,12 @@ function templateCreateInput(t) {
1316
1455
  const input = {
1317
1456
  name: t.name,
1318
1457
  ...t.alias ? { alias: t.alias } : {},
1458
+ ...t.from ? { from: t.from } : {},
1459
+ ...replyTo.length > 0 ? { reply_to: replyTo.slice(0, TEMPLATE_REPLY_TO_MAX) } : {},
1319
1460
  ...subject ? { subject: subject.html } : {},
1320
1461
  html: html.html,
1321
- ...text ? { text: text.html } : {}
1462
+ ...text ? { text: text.html } : {},
1463
+ ...variables.length > 0 ? { variables } : {}
1322
1464
  };
1323
1465
  return { input, notes, reason: null };
1324
1466
  }
@@ -1357,7 +1499,7 @@ function broadcastCreateInput(b, ids) {
1357
1499
  }
1358
1500
 
1359
1501
  // src/plan.ts
1360
- var PLAN_VERSION = 1;
1502
+ var PLAN_VERSION = 2;
1361
1503
  var BATCH_SIZE = 1e3;
1362
1504
  var RESOURCE_ORDER = [
1363
1505
  "properties",
@@ -1372,6 +1514,11 @@ var RESOURCE_ORDER = [
1372
1514
  "enrichment",
1373
1515
  "api-keys"
1374
1516
  ];
1517
+ function contactDiffers(source, target) {
1518
+ if (source.unsubscribed && !target.unsubscribed) return true;
1519
+ if (source.firstName !== null && source.firstName !== target.firstName) return true;
1520
+ return source.lastName !== null && source.lastName !== target.lastName;
1521
+ }
1375
1522
  function changedFields(pairs) {
1376
1523
  return pairs.filter(([, a, b]) => canonicalJson(a) !== canonicalJson(b)).map(([name]) => name);
1377
1524
  }
@@ -1389,8 +1536,19 @@ function buildPlan({
1389
1536
  const manual = (resource, key, detail) => add(resource, "manual", key, { detail });
1390
1537
  const has = (resource) => options.include.has(resource);
1391
1538
  if (has("properties")) {
1539
+ const kept = /* @__PURE__ */ new Map();
1392
1540
  for (const p of snapshot.properties) {
1393
- const existing = target.properties.find((t) => t.key === p.key);
1541
+ const lower = p.key.toLowerCase();
1542
+ const first = kept.get(lower);
1543
+ if (first !== void 0) {
1544
+ add("properties", "manual", p.key, {
1545
+ detail: `differs from \`${first}\` only in case; BillionSend property keys ignore case, so only \`${first}\` is created and no value of \`${p.key}\` is written (the contacts that have one are counted after the enrichment pass)`,
1546
+ payload: { collidesWith: first }
1547
+ });
1548
+ continue;
1549
+ }
1550
+ kept.set(lower, p.key);
1551
+ const existing = target.properties.find((t) => t.key.toLowerCase() === lower);
1394
1552
  if (!existing) {
1395
1553
  const payload = {
1396
1554
  key: p.key,
@@ -1404,6 +1562,12 @@ function buildPlan({
1404
1562
  p.key,
1405
1563
  `type differs: ${p.type} on Resend, ${existing.type} here \u2014 a property's type cannot change`
1406
1564
  );
1565
+ } else if (existing.key !== p.key) {
1566
+ add("properties", "unchanged", p.key, {
1567
+ targetId: existing.id,
1568
+ detail: `already here as \`${existing.key}\` (keys ignore case)`,
1569
+ payload: { targetKey: existing.key }
1570
+ });
1407
1571
  } else {
1408
1572
  add("properties", "unchanged", p.key, { targetId: existing.id });
1409
1573
  }
@@ -1554,14 +1718,30 @@ function buildPlan({
1554
1718
  alias: t.alias,
1555
1719
  subject: input.subject ?? null,
1556
1720
  html: input.html,
1557
- text: input.text ?? null
1721
+ text: input.text ?? null,
1722
+ ...input.from === void 0 ? {} : { from: input.from },
1723
+ ...input.reply_to === void 0 ? {} : { reply_to: input.reply_to },
1724
+ ...input.variables === void 0 ? {} : {
1725
+ variables: input.variables.map((v) => ({
1726
+ key: v.key,
1727
+ type: v.type,
1728
+ fallback_value: v.fallback_value ?? null
1729
+ }))
1730
+ }
1558
1731
  };
1559
1732
  const current = {
1560
1733
  name: existing.name,
1561
1734
  alias: existing.alias,
1562
1735
  subject: existing.subject ?? null,
1563
1736
  html: existing.html ?? null,
1564
- text: existing.text ?? null
1737
+ text: existing.text ?? null,
1738
+ from: existing.from ?? null,
1739
+ reply_to: existing.replyTo ?? null,
1740
+ variables: (existing.variables ?? []).map((v) => ({
1741
+ key: v.key,
1742
+ type: v.type,
1743
+ fallback_value: v.fallback_value
1744
+ }))
1565
1745
  };
1566
1746
  const changed = changedFields(
1567
1747
  Object.keys(desired).map((field) => [field, desired[field], current[field]])
@@ -1582,14 +1762,62 @@ function buildPlan({
1582
1762
  const contactCount = has("contacts") ? snapshot.contacts.length : 0;
1583
1763
  if (contactCount > 0) {
1584
1764
  const memberships = has("segments") ? snapshot.segments.reduce((n, s) => n + s.memberEmails.length, 0) : 0;
1585
- add("contacts", "create", "contacts", {
1586
- count: contactCount,
1587
- detail: `batch upsert, ${pluralize(memberships, "segment membership")}`
1588
- });
1765
+ const members = /* @__PURE__ */ new Set();
1766
+ if (has("segments")) {
1767
+ for (const segment of snapshot.segments) {
1768
+ for (const email of segment.memberEmails) members.add(email.toLowerCase());
1769
+ }
1770
+ }
1771
+ const fresh = [];
1772
+ const matched = { changed: 0, same: 0 };
1773
+ for (const c of snapshot.contacts) {
1774
+ const there = target.contacts.get(c.email.toLowerCase());
1775
+ if (there === void 0) fresh.push(c);
1776
+ else if (contactDiffers(c, there) || members.has(c.email.toLowerCase())) matched.changed += 1;
1777
+ else matched.same += 1;
1778
+ }
1779
+ const existing = matched.changed + matched.same;
1780
+ const batchDetail = `batch upsert, ${pluralize(memberships, "segment membership")}`;
1781
+ if (fresh.length > 0 || existing === 0) {
1782
+ add("contacts", "create", "contacts", {
1783
+ count: fresh.length,
1784
+ detail: existing === 0 ? batchDetail : `${formatNumber(fresh.length)} not on BillionSend yet; batch upsert, ${pluralize(memberships, "segment membership")} across all ${formatNumber(contactCount)} contacts`
1785
+ });
1786
+ }
1787
+ if (existing > 0) {
1788
+ const there = (n, what) => `${formatNumber(n)} already on BillionSend (matched by address); ${what}`;
1789
+ if (options.onConflict === "skip") {
1790
+ add("contacts", "skip", "existing contacts", {
1791
+ count: existing,
1792
+ detail: there(existing, "--on-conflict skip leaves them as they are")
1793
+ });
1794
+ } else if (options.onConflict === "error") {
1795
+ add("contacts", "update", "existing contacts", {
1796
+ count: existing,
1797
+ detail: there(existing, "--on-conflict error refuses them, and the run exits 3")
1798
+ });
1799
+ } else {
1800
+ if (matched.changed > 0) {
1801
+ add("contacts", "update", "existing contacts", {
1802
+ count: matched.changed,
1803
+ detail: there(
1804
+ matched.changed,
1805
+ "the upsert makes sure each is in its segment and writes a name or opt-out flag that differs"
1806
+ )
1807
+ });
1808
+ }
1809
+ if (matched.same > 0) {
1810
+ add("contacts", "unchanged", "existing contacts", {
1811
+ count: matched.same,
1812
+ detail: there(matched.same, "names and opt-out flag are the same, in no segment")
1813
+ });
1814
+ }
1815
+ }
1816
+ }
1589
1817
  const limit = target.usage.limits.contacts;
1590
- if (limit !== null && contactCount > limit) {
1818
+ if (limit !== null && fresh.length > limit) {
1591
1819
  warnings.push(
1592
- `${pluralize(contactCount, "contact")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${formatNumber(limit)}`
1820
+ `${pluralize(fresh.length, "contact")} to create; the ${capitalize(target.usage.plan ?? "current")} plan allows ${formatNumber(limit)}`
1593
1821
  );
1594
1822
  }
1595
1823
  }
@@ -1617,6 +1845,10 @@ function buildPlan({
1617
1845
  }
1618
1846
  if (has("broadcasts")) {
1619
1847
  for (const b of snapshot.broadcasts) {
1848
+ if (snapshot.segmentScope !== null && b.segmentId !== null && !snapshot.segmentScope.some((s) => s.id === b.segmentId)) {
1849
+ add("broadcasts", "skip", b.name, { detail: "sent to a segment outside --segment" });
1850
+ continue;
1851
+ }
1620
1852
  if (b.status === "sent" && !options.includeSent) {
1621
1853
  add("broadcasts", "skip", b.name, {
1622
1854
  detail: "already sent; --include-sent imports sent broadcasts as drafts"
@@ -1672,18 +1904,28 @@ function buildPlan({
1672
1904
  const rowWrites = items.filter(
1673
1905
  (i) => (i.action === "create" || i.action === "update") && i.count === void 0
1674
1906
  ).length;
1675
- const writes = rowWrites + batches(contactCount) + batches(suppressionCount) + (enrichment ? facets.length * batches(enrichCount) : 0);
1676
- const reads = enrichment ? estimateSourceRequests(snapshot).enrichment : 0;
1677
- const requests = options.sourceRequestsSpent + reads + writes;
1907
+ const writes = rowWrites + // The lookup of the source's addresses on the target, then the upsert itself.
1908
+ batches(contactCount) * 2 + batches(suppressionCount) + (enrichment ? facets.length * batches(enrichCount) : 0);
1909
+ const reads = options.sourceRequestsSpent + (enrichment ? estimateSourceRequests(snapshot).enrichment : 0);
1910
+ const requests = reads + writes;
1678
1911
  const seconds2 = Math.ceil(reads / options.rps + writes / 10);
1679
1912
  return {
1680
- version: 1,
1913
+ version: 2,
1681
1914
  createdAt: (options.now ?? /* @__PURE__ */ new Date()).toISOString(),
1682
1915
  source: snapshot.provider,
1683
1916
  target: {
1684
1917
  baseUrl: options.baseUrl,
1685
1918
  plan: target.usage.plan
1686
1919
  },
1920
+ options: {
1921
+ only: options.only,
1922
+ skip: options.skip,
1923
+ segment: options.segment,
1924
+ onConflict: options.onConflict,
1925
+ includeSent: options.includeSent,
1926
+ freshWebhookSecrets: options.freshWebhookSecrets
1927
+ },
1928
+ scope: snapshot.segmentScope === null ? null : { segments: snapshot.segmentScope },
1687
1929
  rps: options.rps,
1688
1930
  items,
1689
1931
  estimate: { requests, seconds: seconds2 },
@@ -1767,10 +2009,11 @@ function groupPlanItems(items) {
1767
2009
  });
1768
2010
  }
1769
2011
  }
1770
- const count = own[0]?.count;
2012
+ const counted = own.filter((i) => i.count !== void 0);
2013
+ const count = counted.reduce((n, i) => n + (i.count ?? 0), 0);
1771
2014
  groups.push({
1772
2015
  resource,
1773
- label: count === void 0 ? resource : `${resource} (${formatNumber(count)})`,
2016
+ label: counted.length === 0 ? resource : `${resource} (${formatNumber(count)})`,
1774
2017
  rows
1775
2018
  });
1776
2019
  }
@@ -1794,12 +2037,14 @@ function renderRow(row) {
1794
2037
  return lines;
1795
2038
  }
1796
2039
  var foldedKeysLine = (keys) => `${keys.slice(0, 2).map(stripControl).join(", ")} \u2026 and ${formatNumber(keys.length - 2)} more`;
2040
+ var scopeLine = (scope) => `Scope (--segment): only ${scope.segments.map((s) => s.name).join(", ")} and ${scope.segments.length === 1 ? "its" : "their"} members; contacts and the enrichment pass cover those contacts alone.`;
1797
2041
  function renderPlan(plan2) {
1798
2042
  const c = plan2.counts;
1799
2043
  const n = (count) => count > 0 ? bold(formatNumber(count)) : "0";
1800
2044
  const lines = [
1801
2045
  dim(ACTIONS.map((a) => `${ACTION_STYLE[a][0]} ${a}`).join(" ")),
1802
2046
  "",
2047
+ ...plan2.scope === null ? [] : [wrapIndent(dim(scopeLine(plan2.scope)), { hanging: " " }), ""],
1803
2048
  ...groupPlanItems(plan2.items).flatMap((g) => [g.label, ...g.rows.flatMap(renderRow)]),
1804
2049
  "",
1805
2050
  wrapIndent(
@@ -1838,14 +2083,38 @@ function parsePlan(text) {
1838
2083
  `plan file version ${String(plan2.version)} is not supported (expected ${PLAN_VERSION})`
1839
2084
  );
1840
2085
  }
2086
+ if (plan2.options === null || typeof plan2.options !== "object") {
2087
+ throw new Error("plan file is not a migration plan");
2088
+ }
1841
2089
  return plan2;
1842
2090
  }
2091
+ function describePlanDiff(saved, current) {
2092
+ const label = (i) => `${i.resource}/${i.key}`;
2093
+ const byLabel = (plan2) => new Map(plan2.items.map((i) => [label(i), i]));
2094
+ const before = byLabel(saved);
2095
+ const after = byLabel(current);
2096
+ const lines = [];
2097
+ for (const [name, a] of before) {
2098
+ const b = after.get(name);
2099
+ if (b === void 0) lines.push(`${name}: in the file, not in the current plan`);
2100
+ else if (canonicalJson(a) !== canonicalJson(b)) {
2101
+ const count = a.count !== b.count ? `, ${formatNumber(a.count ?? 0)} \u2192 ${formatNumber(b.count ?? 0)}` : "";
2102
+ lines.push(
2103
+ `${name}: ${a.action} \u2192 ${b.action}${a.action === b.action && count === "" ? " (details differ)" : count}`
2104
+ );
2105
+ }
2106
+ }
2107
+ for (const name of after.keys()) {
2108
+ if (!before.has(name)) lines.push(`${name}: not in the file, in the current plan`);
2109
+ }
2110
+ return lines;
2111
+ }
1843
2112
 
1844
2113
  // src/config.ts
1845
2114
  import { parseArgs } from "node:util";
1846
2115
 
1847
2116
  // src/meta.ts
1848
- var VERSION = true ? "0.2.5" : "0.0.0-dev";
2117
+ var VERSION = true ? "0.3.0" : "0.0.0-dev";
1849
2118
  var REPO_URL = "https://github.com/billionsend/billionsend-cli";
1850
2119
  var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
1851
2120
  var CLOUD_API_URL = "https://api.billionsend.com";
@@ -1869,6 +2138,14 @@ var RESOURCES = [
1869
2138
  ];
1870
2139
 
1871
2140
  // src/config.ts
2141
+ var PLAN_OPTIONS = [
2142
+ "only",
2143
+ "skip",
2144
+ "segment",
2145
+ "on-conflict",
2146
+ "include-sent",
2147
+ "fresh-webhook-secrets"
2148
+ ];
1872
2149
  var ConfigError = class extends Error {
1873
2150
  constructor(message) {
1874
2151
  super(message);
@@ -1892,6 +2169,7 @@ var OPTIONS = {
1892
2169
  rps: { type: "string" },
1893
2170
  only: { type: "string" },
1894
2171
  skip: { type: "string" },
2172
+ segment: { type: "string", multiple: true },
1895
2173
  "on-conflict": { type: "string" },
1896
2174
  yes: { type: "boolean", short: "y" },
1897
2175
  "non-interactive": { type: "boolean" },
@@ -1921,18 +2199,25 @@ function resourceList(flag, value) {
1921
2199
  }
1922
2200
  return names;
1923
2201
  }
2202
+ function segmentList(value) {
2203
+ const names = (value ?? []).flatMap((entry) => entry.split(",")).map((name) => name.trim());
2204
+ if (names.includes("")) {
2205
+ throw new ConfigError("--segment needs a segment name or id (an empty value was given).");
2206
+ }
2207
+ return [...new Set(names)];
2208
+ }
1924
2209
  function keyInput(envName, env, stdinFlag, flagValue, flagName, warnings) {
1925
2210
  if (stdinFlag && flagValue !== void 0) {
1926
2211
  throw new ConfigError(`Pass either ${flagName} or ${flagName}-stdin, not both.`);
1927
2212
  }
1928
- const fromEnv = env[envName];
2213
+ const fromEnv = env[envName]?.trim();
1929
2214
  if (fromEnv !== void 0 && fromEnv !== "") return { source: "env", value: fromEnv };
1930
2215
  if (stdinFlag) return { source: "stdin", value: null };
1931
2216
  if (flagValue !== void 0) {
1932
2217
  warnings.push(
1933
2218
  `${flagName} is visible to other users in process lists; prefer ${envName} or ${flagName}-stdin.`
1934
2219
  );
1935
- return { source: "flag", value: flagValue };
2220
+ return { source: "flag", value: flagValue.trim() };
1936
2221
  }
1937
2222
  return { source: "prompt", value: null };
1938
2223
  }
@@ -2068,6 +2353,8 @@ function parseConfig(argv, env = process.env, stdinIsTTY = process.stdin.isTTY =
2068
2353
  rpsGiven,
2069
2354
  only: resourceList("--only", values.only),
2070
2355
  skip: resourceList("--skip", values.skip) ?? [],
2356
+ segment: segmentList(values.segment),
2357
+ given: new Set(PLAN_OPTIONS.filter((name) => values[name] !== void 0)),
2071
2358
  onConflict,
2072
2359
  yes: values.yes === true,
2073
2360
  nonInteractive,
@@ -2094,6 +2381,8 @@ function minimal(command) {
2094
2381
  rpsGiven: false,
2095
2382
  only: null,
2096
2383
  skip: [],
2384
+ segment: [],
2385
+ given: /* @__PURE__ */ new Set(),
2097
2386
  onConflict: "upsert",
2098
2387
  yes: false,
2099
2388
  nonInteractive: true,
@@ -2114,7 +2403,7 @@ function helpText() {
2114
2403
  Usage
2115
2404
  billionsend migrate --from resend connect, choose resources, plan, confirm, apply, summary
2116
2405
  billionsend migrate plan --from resend [--out plan.json] read-only; exit 0 nothing to do, 2 changes, 1 error
2117
- billionsend migrate apply [plan.json] [--yes] apply a saved plan, or plan and apply in one go
2406
+ billionsend migrate apply [plan.json] [--yes] apply a saved plan (with the options it was made with), or plan and apply in one go
2118
2407
  billionsend migrate status what the last run created and what is left
2119
2408
  billionsend migrate rollback [--yes] delete only what this tool created
2120
2409
  billionsend --help | --version
@@ -2131,12 +2420,14 @@ Options
2131
2420
  Go past ${MAX_RPS} only after Resend raised your limit (up to ${RPS_CEILING})
2132
2421
  --only <a,b> migrate only these resources
2133
2422
  --skip <a,b> skip these resources; \`enrichment\` is the per-contact properties/topics pass
2423
+ --segment <name|id> only these Resend segments: the segments, their members and the members' enrichment.
2424
+ Repeat the flag or separate with commas; an unknown name or id exits 1 and lists the segments
2134
2425
  --on-conflict <mode> contacts that already exist on the target: upsert (default), skip, error
2135
2426
  --include-sent import sent broadcasts as drafts (skipped by default)
2136
2427
  --fresh-webhook-secrets mint new webhook signing secrets instead of copying them (shown once in the report)
2137
2428
  --fresh ignore resume progress; keeps what earlier runs created so rollback still works
2138
2429
  --out <file> \`migrate plan\`: write the plan as JSON
2139
- --report <file> also write the Markdown report to this path
2430
+ --report <file> also write the Markdown report to this path (\`migrate plan\`: the plan as Markdown)
2140
2431
  -y, --yes skip confirmations
2141
2432
  --non-interactive never prompt; a missing input is exit 1 (automatic when stdin is not a terminal, and with --json)
2142
2433
  --json JSON on stdout, progress on stderr
@@ -2169,16 +2460,18 @@ ${TRADEMARK_NOTICE}
2169
2460
  }
2170
2461
 
2171
2462
  // src/billionsend.ts
2463
+ var LOOKUP_EMAIL = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/;
2172
2464
  var BATCH_MAX = 1e3;
2173
2465
  var PERMISSIVE = { headers: { "x-batch-validation": "permissive" } };
2174
2466
  function writeError(error) {
2175
- if (!(error instanceof ApiError) || error.status < 400 || error.status >= 500) return null;
2467
+ if (!(error instanceof ApiError)) return null;
2468
+ if (!error.sentOnce && (error.status < 400 || error.status >= 500)) return null;
2176
2469
  const body = error.body;
2177
2470
  return {
2178
2471
  ok: false,
2179
2472
  status: error.status,
2180
2473
  name: error.name,
2181
- message: typeof body?.message === "string" ? body.message : error.message
2474
+ message: !error.sentOnce && typeof body?.message === "string" ? body.message : error.message
2182
2475
  };
2183
2476
  }
2184
2477
  function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
@@ -2210,8 +2503,8 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2210
2503
  throw error;
2211
2504
  }
2212
2505
  }
2213
- const id = async (response) => ({
2214
- id: (await response).body.id
2506
+ const id = async (response, known = "") => ({
2507
+ id: (await response).body?.id ?? known
2215
2508
  });
2216
2509
  const withRecords = async (response) => {
2217
2510
  const { body } = await response;
@@ -2252,24 +2545,15 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2252
2545
  }
2253
2546
  throw error;
2254
2547
  }
2255
- const period = body.period ?? null;
2256
2548
  return {
2257
2549
  plan: body.plan,
2258
2550
  limits: {
2259
- emailsPerDay: body.limits.emails_per_day,
2260
- emailsPerMonth: body.limits.emails_per_month ?? null,
2261
- domains: body.limits.domains,
2262
- contacts: body.limits.contacts ?? null
2551
+ emailsPerDay: body.emails.daily.limit,
2552
+ emailsPerMonth: body.emails.monthly.limit,
2553
+ domains: body.domains.limit,
2554
+ contacts: body.contacts.limit
2263
2555
  },
2264
- today: { emailsSent: body.today.emails_sent },
2265
- period: period && {
2266
- emailsSent: period.emails_sent,
2267
- included: period.included,
2268
- overageEnabled: period.overage_enabled,
2269
- startsAt: period.starts_at,
2270
- endsAt: period.ends_at
2271
- },
2272
- appUrl: body.app_url
2556
+ overageEnabled: body.emails.monthly.overage_enabled
2273
2557
  };
2274
2558
  }
2275
2559
  async function readState() {
@@ -2295,7 +2579,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2295
2579
  ]);
2296
2580
  const domains = [];
2297
2581
  for (const { id: id2 } of domainRows.filter((row) => row.shared !== true)) {
2298
- const { body } = await api.get(`/domains/${id2}`);
2582
+ const { body } = await api.get(route`/domains/${id2}`);
2299
2583
  domains.push({
2300
2584
  id: body.id,
2301
2585
  name: body.name,
@@ -2306,18 +2590,26 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2306
2590
  }
2307
2591
  const templates = [];
2308
2592
  for (const { id: id2 } of templateRows) {
2309
- const { body } = await api.get(`/templates/${id2}`);
2593
+ const { body } = await api.get(route`/templates/${id2}`);
2310
2594
  templates.push({
2311
2595
  id: body.id,
2312
2596
  name: body.name,
2313
2597
  alias: body.alias,
2598
+ from: body.from,
2599
+ replyTo: body.reply_to,
2314
2600
  subject: body.subject,
2315
2601
  html: body.html,
2316
- text: body.text
2602
+ text: body.text,
2603
+ variables: body.variables.map(({ key, type, fallback_value }) => ({
2604
+ key,
2605
+ type,
2606
+ fallback_value
2607
+ }))
2317
2608
  });
2318
2609
  }
2319
2610
  return {
2320
2611
  usage,
2612
+ contacts: /* @__PURE__ */ new Map(),
2321
2613
  domains,
2322
2614
  hasContacts: firstContact.body.data.length > 0,
2323
2615
  properties: properties.map(({ id: id2, key, type }) => ({ id: id2, key, type })),
@@ -2345,6 +2637,51 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2345
2637
  )
2346
2638
  };
2347
2639
  }
2640
+ async function lookupContacts(emails, include) {
2641
+ const rows = [];
2642
+ const ask = async (slice) => {
2643
+ try {
2644
+ const { body } = await api.post(
2645
+ "/contacts/batch/get",
2646
+ {
2647
+ contacts: slice.map((email) => ({ email })),
2648
+ ...include === null ? {} : { include: [include] }
2649
+ },
2650
+ // It only reads.
2651
+ { idempotent: true }
2652
+ );
2653
+ rows.push(...body.data);
2654
+ } catch (error) {
2655
+ if (!(error instanceof ApiError) || error.status !== 422) throw error;
2656
+ if (slice.length === 1) return;
2657
+ const half = Math.ceil(slice.length / 2);
2658
+ await ask(slice.slice(0, half));
2659
+ await ask(slice.slice(half));
2660
+ }
2661
+ };
2662
+ const askable = [...new Set(emails.filter((email) => LOOKUP_EMAIL.test(email)))];
2663
+ for (const slice of chunk(askable, BATCH_MAX)) await ask(slice);
2664
+ return rows;
2665
+ }
2666
+ async function findContacts(emails) {
2667
+ const found = /* @__PURE__ */ new Map();
2668
+ for (const row of await lookupContacts(emails, null)) {
2669
+ found.set(row.email.toLowerCase(), {
2670
+ firstName: row.first_name,
2671
+ lastName: row.last_name,
2672
+ unsubscribed: row.unsubscribed
2673
+ });
2674
+ }
2675
+ return found;
2676
+ }
2677
+ async function explicitOptOuts(emails) {
2678
+ const out = /* @__PURE__ */ new Map();
2679
+ for (const row of await lookupContacts(emails, "topics")) {
2680
+ const topics = (row.topics ?? []).filter((t) => t.explicit && t.subscription === "opt_out");
2681
+ if (topics.length > 0) out.set(row.email.toLowerCase(), new Set(topics.map((t) => t.id)));
2682
+ }
2683
+ return out;
2684
+ }
2348
2685
  async function batchContacts(items, {
2349
2686
  onConflict,
2350
2687
  permissive = true
@@ -2384,12 +2721,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2384
2721
  return out;
2385
2722
  }
2386
2723
  async function suppressionsBatch(path2, key, values, extra = {}) {
2387
- const out = { ids: [], errors: [] };
2724
+ const out = { ids: [], notRemoved: [], errors: [] };
2388
2725
  const chunks = chunk(values, BATCH_MAX);
2389
2726
  for (const [n, slice] of chunks.entries()) {
2390
- const result = await write(async () => ({
2391
- data: (await api.post(path2, { [key]: slice, ...extra })).body.data
2392
- }));
2727
+ const result = await write(async () => {
2728
+ const { body } = await api.post(path2, { [key]: slice, ...extra });
2729
+ return { data: body.data, notRemoved: body.not_removed ?? [] };
2730
+ });
2393
2731
  if (!result.ok) {
2394
2732
  log.warn(`${path2} ${n + 1}/${chunks.length} failed: ${result.message}`);
2395
2733
  for (const i of slice.keys()) {
@@ -2402,6 +2740,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2402
2740
  continue;
2403
2741
  }
2404
2742
  out.ids.push(...result.data.map((r) => r.id));
2743
+ out.notRemoved.push(...result.notRemoved);
2405
2744
  }
2406
2745
  return out;
2407
2746
  }
@@ -2421,7 +2760,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2421
2760
  })
2422
2761
  )
2423
2762
  ),
2424
- deleteProperty: (propertyId) => write(() => id(api.delete(`/contact-properties/${propertyId}`))),
2763
+ deleteProperty: (propertyId) => write(() => id(api.delete(route`/contact-properties/${propertyId}`), propertyId)),
2425
2764
  createTopic: (input) => write(
2426
2765
  () => id(
2427
2766
  api.post("/topics", {
@@ -2434,14 +2773,14 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2434
2773
  ),
2435
2774
  updateTopic: (topicId, input) => write(
2436
2775
  () => id(
2437
- api.patch(`/topics/${topicId}`, {
2776
+ api.patch(route`/topics/${topicId}`, {
2438
2777
  name: input.name,
2439
2778
  description: input.description ?? void 0,
2440
2779
  visibility: input.visibility
2441
2780
  })
2442
2781
  )
2443
2782
  ),
2444
- deleteTopic: (topicId) => write(() => id(api.delete(`/topics/${topicId}`))),
2783
+ deleteTopic: (topicId) => write(() => id(api.delete(route`/topics/${topicId}`), topicId)),
2445
2784
  createSegment: (input) => write(
2446
2785
  () => id(
2447
2786
  api.post("/segments", {
@@ -2453,13 +2792,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2453
2792
  /** `filter: null` clears the saved filter (manual membership only). */
2454
2793
  updateSegment: (segmentId, input) => write(
2455
2794
  () => id(
2456
- api.patch(`/segments/${segmentId}`, {
2795
+ api.patch(route`/segments/${segmentId}`, {
2457
2796
  name: input.name,
2458
2797
  ...input.filter !== void 0 ? { filter: input.filter } : {}
2459
2798
  })
2460
2799
  )
2461
2800
  ),
2462
- deleteSegment: (segmentId) => write(() => id(api.delete(`/segments/${segmentId}`))),
2801
+ deleteSegment: (segmentId) => write(() => id(api.delete(route`/segments/${segmentId}`), segmentId)),
2463
2802
  createDomain: (input) => write(
2464
2803
  () => withRecords(
2465
2804
  api.post("/domains", {
@@ -2470,14 +2809,14 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2470
2809
  ),
2471
2810
  updateDomainTracking: (domainId, input) => write(
2472
2811
  () => withRecords(
2473
- api.patch(`/domains/${domainId}`, {
2812
+ api.patch(route`/domains/${domainId}`, {
2474
2813
  open_tracking: input.openTracking,
2475
2814
  click_tracking: input.clickTracking,
2476
2815
  tracking_subdomain: input.trackingSubdomain
2477
2816
  })
2478
2817
  )
2479
2818
  ),
2480
- deleteDomain: (domainId) => write(() => id(api.delete(`/domains/${domainId}`))),
2819
+ deleteDomain: (domainId) => write(() => id(api.delete(route`/domains/${domainId}`), domainId)),
2481
2820
  createWebhook: (input) => write(async () => {
2482
2821
  const { body } = await api.post("/webhooks", {
2483
2822
  endpoint: input.endpoint,
@@ -2486,22 +2825,25 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2486
2825
  });
2487
2826
  return { id: body.id, signingSecret: body.signing_secret };
2488
2827
  }),
2489
- updateWebhook: (webhookId, input) => write(() => id(api.patch(`/webhooks/${webhookId}`, input))),
2490
- deleteWebhook: (webhookId) => write(() => id(api.delete(`/webhooks/${webhookId}`))),
2828
+ updateWebhook: (webhookId, input) => write(() => id(api.patch(route`/webhooks/${webhookId}`, input))),
2829
+ deleteWebhook: (webhookId) => write(() => id(api.delete(route`/webhooks/${webhookId}`), webhookId)),
2491
2830
  createTemplate: (input) => write(
2492
2831
  () => id(
2493
2832
  api.post("/templates", {
2494
2833
  name: input.name,
2495
2834
  alias: input.alias ?? void 0,
2835
+ from: input.from ?? void 0,
2836
+ reply_to: input.reply_to ?? void 0,
2496
2837
  subject: input.subject ?? void 0,
2497
2838
  html: input.html,
2498
- text: input.text ?? void 0
2839
+ text: input.text ?? void 0,
2840
+ variables: input.variables ?? void 0
2499
2841
  })
2500
2842
  )
2501
2843
  ),
2502
2844
  /** `idOrAlias`: the API resolves either. */
2503
- updateTemplate: (idOrAlias, input) => write(() => id(api.patch(`/templates/${idOrAlias}`, input))),
2504
- deleteTemplate: (idOrAlias) => write(() => id(api.delete(`/templates/${idOrAlias}`))),
2845
+ updateTemplate: (idOrAlias, input) => write(() => id(api.patch(route`/templates/${idOrAlias}`, input))),
2846
+ deleteTemplate: (idOrAlias) => write(() => id(api.delete(route`/templates/${idOrAlias}`), idOrAlias)),
2505
2847
  /** Always a draft; sending stays a deliberate act in the dashboard. */
2506
2848
  createBroadcast: (input) => write(
2507
2849
  () => id(
@@ -2518,10 +2860,12 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2518
2860
  })
2519
2861
  )
2520
2862
  ),
2521
- deleteBroadcast: (broadcastId) => write(() => id(api.delete(`/broadcasts/${broadcastId}`))),
2863
+ deleteBroadcast: (broadcastId) => write(() => id(api.delete(route`/broadcasts/${broadcastId}`), broadcastId)),
2864
+ findContacts,
2865
+ explicitOptOuts,
2522
2866
  batchContacts,
2523
2867
  deleteContact: (contactId) => write(async () => ({
2524
- id: (await api.delete(`/contacts/${contactId}`)).body.contact
2868
+ id: (await api.delete(route`/contacts/${contactId}`)).body?.contact ?? contactId
2525
2869
  })),
2526
2870
  /** Prefer inline `segments` on batch items; this is one request per contact. */
2527
2871
  addContactsToSegment: async (segmentId, contactIds) => {
@@ -2529,7 +2873,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
2529
2873
  const errors = [];
2530
2874
  for (const contactId of contactIds) {
2531
2875
  const result = await write(
2532
- () => id(api.post(`/contacts/${contactId}/segments/${segmentId}`))
2876
+ () => id(api.post(route`/contacts/${contactId}/segments/${segmentId}`))
2533
2877
  );
2534
2878
  if (result.ok) added.push(result.id);
2535
2879
  else errors.push({ id: contactId, message: result.message });
@@ -2765,10 +3109,10 @@ function buildOffer(usage, snapshot, domains, sourceLabel) {
2765
3109
  domains: usage.limits.domains,
2766
3110
  contacts: usage.limits.contacts
2767
3111
  };
2768
- const url = usage.appUrl === null ? CLOUD_BILLING_URL : `${stripTrailingSlashes(usage.appUrl)}/settings/billing`;
3112
+ const url = CLOUD_BILLING_URL;
2769
3113
  const short = [];
2770
3114
  const over = sent !== null && current.perMonth !== null && sent > current.perMonth;
2771
- const volumeShort = over && !usage.period?.overageEnabled;
3115
+ const volumeShort = over && !usage.overageEnabled;
2772
3116
  if (volumeShort) short.push(`${current.label} allows ${perMonthText(current.perMonth)}`);
2773
3117
  if (current.domains !== null && domains > current.domains) {
2774
3118
  short.push(
@@ -2824,16 +3168,22 @@ function buildReport({
2824
3168
  dns.push({ domain: domain.name, records: domain.records });
2825
3169
  }
2826
3170
  const apiKeys = plan2.items.filter((i) => i.resource === "api-keys").map((i) => i.key);
2827
- const manual = plan2.manual.filter(
2828
- (m) => !m.title.startsWith("api-keys/") && !m.detail.startsWith("add DNS records")
2829
- );
3171
+ const manual = [
3172
+ ...plan2.manual.filter(
3173
+ (m) => !m.title.startsWith("api-keys/") && !m.detail.startsWith("add DNS records")
3174
+ ),
3175
+ ...outcome.enrichment.droppedProperties.filter((d) => d.contacts > 0).map((d) => ({
3176
+ title: `properties/${d.key}`,
3177
+ detail: `${pluralize(d.contacts, "contact")} had a value for it that was not written: BillionSend property keys ignore case and \`${d.collidesWith}\` is the same key`
3178
+ }))
3179
+ ];
2830
3180
  const failures = outcome.state.failures;
2831
3181
  const retryable = failures.filter((f) => retryableStatus(f.statusCode)).length;
2832
3182
  const refused = failures.length - retryable;
2833
3183
  const done = Object.entries(outcome.counts).filter(([, c]) => c !== void 0 && c.failed === 0 && c.created + c.updated + c.unchanged > 0).map(([resource]) => resource);
2834
3184
  const left = [
2835
3185
  ...dns.map((d) => `add DNS records for ${d.domain}`),
2836
- `set ${plan2.source.toUpperCase()}_BASE_URL=${baseUrl} in your app`,
3186
+ baseUrlStep(plan2.source, baseUrl),
2837
3187
  ...apiKeys.length > 0 ? [`create API keys: ${apiKeys.join(", ")}`] : [],
2838
3188
  ...outcome.ids.length > 0 ? [`replace ${sourceLabel} topic and segment ids in your code (id map below)`] : [],
2839
3189
  ...manual.length > 0 ? [`review ${pluralize(manual.length, "manual note")}`] : [],
@@ -2847,6 +3197,7 @@ function buildReport({
2847
3197
  source: plan2.source,
2848
3198
  sourceLabel,
2849
3199
  target: { baseUrl, plan: usage.plan },
3200
+ scope: plan2.scope,
2850
3201
  counts: outcome.counts,
2851
3202
  enrichment: outcome.enrichment,
2852
3203
  sourceReadOnly: true,
@@ -2861,6 +3212,11 @@ function buildReport({
2861
3212
  trademark: TRADEMARK_NOTICE
2862
3213
  };
2863
3214
  }
3215
+ function baseUrlStep(source, baseUrl) {
3216
+ const name = `${source.toUpperCase()}_BASE_URL`;
3217
+ const step = `set ${name}=${CLOUD_API_URL} in your app, so ${capitalize(source)} SDK calls go to BillionSend`;
3218
+ return baseUrl === CLOUD_API_URL ? step : `${step} (this run used ${baseUrl}; put that address there only if your app reaches BillionSend through it)`;
3219
+ }
2864
3220
  function dnsCards(records) {
2865
3221
  return records.flatMap((r, i) => [
2866
3222
  ...i > 0 ? [""] : [],
@@ -2874,7 +3230,10 @@ function cutoverReadyLines(source, baseUrl, domainRecords) {
2874
3230
  heading("Cutover ready"),
2875
3231
  "Everything but the per-contact enrichment is on BillionSend: transactional sending can move now.",
2876
3232
  "Topic opt-outs and properties land in the enrichment passes below; hold topic sends and broadcasts until they finish.",
2877
- ` ${dim("[")} ${dim("]")} set ${source.toUpperCase()}_BASE_URL=${baseUrl} in your app`
3233
+ wrapIndent(`${dim("[")} ${dim("]")} ${baseUrlStep(source, baseUrl)}`, {
3234
+ indent: " ",
3235
+ hanging: " "
3236
+ })
2878
3237
  ];
2879
3238
  for (const [domain, records] of Object.entries(domainRecords)) {
2880
3239
  lines.push("", `DNS records for ${domain}:`, ...dnsCards(records));
@@ -2921,10 +3280,13 @@ function countRows(counts, enrichment) {
2921
3280
  if (resource === "enrichment" && enrichment !== void 0) {
2922
3281
  rows.push({ label: "with topic subscriptions", value: enrichment.withTopics });
2923
3282
  rows.push({ label: "with properties", value: enrichment.withProperties });
3283
+ const dropped = (enrichment.droppedProperties ?? []).reduce((n, d) => n + d.contacts, 0);
3284
+ if (dropped > 0) rows.push({ label: "property values not written", value: dropped });
2924
3285
  }
2925
3286
  } else {
2926
3287
  if (c.created > 0) rows.push({ label: `${resource} created`, value: c.created });
2927
3288
  if (c.updated > 0) rows.push({ label: `${resource} updated`, value: c.updated });
3289
+ if (c.matched > 0) rows.push({ label: `${resource} matched existing`, value: c.matched });
2928
3290
  if (c.unchanged > 0) rows.push({ label: `${resource} unchanged`, value: c.unchanged });
2929
3291
  }
2930
3292
  if (c.failed > 0) rows.push({ label: `${resource} failed`, value: c.failed });
@@ -2945,6 +3307,8 @@ ${heading("Done")}
2945
3307
  await countUp(countRows(report.counts, report.enrichment), { stream: out });
2946
3308
  out.write(`
2947
3309
  ${dim(`${report.sourceLabel} was only read; nothing there was changed.`)}
3310
+ `);
3311
+ if (report.scope !== null) out.write(`${dim(wrapIndent(scopeLine(report.scope)))}
2948
3312
  `);
2949
3313
  if (report.freshWebhookSecrets.length > 0) {
2950
3314
  out.write("\nWebhook signing secrets, shown once (they are not saved anywhere):\n");
@@ -2982,7 +3346,10 @@ Id map (${report.sourceLabel} \u2192 BillionSend; full pairs in migrate-report.m
2982
3346
  }
2983
3347
  if (report.failures.length > 0) {
2984
3348
  out.write("\nFailed:\n");
2985
- for (const f of report.failures) line(`${err(SYM.err)} ${f.resource}/${f.key} \u2014 ${f.message}`);
3349
+ for (const f of report.failures) {
3350
+ const head = `${err(SYM.err)} ${f.resource}/${f.key}`;
3351
+ line(`${head} \u2014 ${f.message}`, { ...ITEM, keep: [head, f.key] });
3352
+ }
2986
3353
  }
2987
3354
  out.write(`
2988
3355
  ${dim(wrapIndent(SYNC_HINT(report.source)))}
@@ -3001,12 +3368,15 @@ function renderReportMd(raw) {
3001
3368
  "",
3002
3369
  "## Numbers",
3003
3370
  "",
3004
- "| Resource | Created | Updated | Unchanged | Skipped | Manual | Failed |",
3005
- "| --- | ---: | ---: | ---: | ---: | ---: | ---: |",
3371
+ "| Resource | Created | Updated | Matched existing | Unchanged | Skipped | Manual | Failed |",
3372
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
3006
3373
  ...orderedCounts(report.counts).map(
3007
- ([resource, c]) => `| ${resource} | ${c.created} | ${c.updated} | ${c.unchanged} | ${c.skipped} | ${c.manual} | ${c.failed} |`
3374
+ ([resource, c]) => `| ${resource} | ${c.created} | ${c.updated} | ${c.matched} | ${c.unchanged} | ${c.skipped} | ${c.manual} | ${c.failed} |`
3008
3375
  ),
3009
3376
  "",
3377
+ "Matched existing: contacts the batch endpoint found already in your account. It does not say whether a matched contact changed, so these are not counted as updated or unchanged.",
3378
+ "",
3379
+ ...report.scope === null ? [] : [scopeLine(report.scope), ""],
3010
3380
  `${report.sourceLabel} was only read; nothing there was changed.`,
3011
3381
  "",
3012
3382
  "## Checklist",
@@ -3067,6 +3437,47 @@ function writeReport(paths, report, extraMd) {
3067
3437
  writePrivate(paths.reportMd, md);
3068
3438
  if (extraMd !== null) writePrivate(extraMd, md);
3069
3439
  }
3440
+ function renderPlanMd(raw, sourceLabel) {
3441
+ const plan2 = stripControlDeep(raw);
3442
+ const rows = RESOURCES.flatMap((resource) => {
3443
+ const own = plan2.items.filter((i) => i.resource === resource);
3444
+ if (own.length === 0) return [];
3445
+ const n = (action) => own.filter((i) => i.action === action).reduce((sum, i) => sum + (i.count ?? 1), 0);
3446
+ return [
3447
+ `| ${resource} | ${n("create")} | ${n("update")} | ${n("unchanged")} | ${n("manual")} | ${n("skip")} |`
3448
+ ];
3449
+ });
3450
+ const lines = [
3451
+ `# Migration plan \u2014 ${sourceLabel} \u2192 BillionSend`,
3452
+ "",
3453
+ `Planned ${plan2.createdAt} \xB7 target ${plan2.target.baseUrl}${plan2.target.plan === null ? "" : ` \xB7 plan ${capitalize(plan2.target.plan)}`}`,
3454
+ "",
3455
+ "Nothing has been written: this is what `billionsend migrate apply` would do.",
3456
+ "",
3457
+ ...plan2.scope === null ? [] : [scopeLine(plan2.scope), ""],
3458
+ "## Plan",
3459
+ "",
3460
+ "| Resource | Create | Update | Unchanged | Manual | Skipped |",
3461
+ "| --- | ---: | ---: | ---: | ---: | ---: |",
3462
+ ...rows,
3463
+ "",
3464
+ `About ${formatNumber(plan2.estimate.requests)} requests (${formatDuration(plan2.estimate.seconds)} at ${plan2.rps} req/s).`
3465
+ ];
3466
+ if (plan2.warnings.length > 0) {
3467
+ lines.push("", "## Warnings", "", ...plan2.warnings.map((w) => `- ${w}`));
3468
+ }
3469
+ if (plan2.manual.length > 0) {
3470
+ lines.push(
3471
+ "",
3472
+ "## Manual notes",
3473
+ "",
3474
+ ...plan2.manual.map(({ title, detail }) => `- ${title} \u2014 ${detail}`)
3475
+ );
3476
+ }
3477
+ lines.push("", "---", "", TRADEMARK_NOTICE, "");
3478
+ return lines.join("\n");
3479
+ }
3480
+ var writePlanReport = (path2, plan2, sourceLabel) => writePrivate(path2, renderPlanMd(plan2, sourceLabel));
3070
3481
 
3071
3482
  // src/apply.ts
3072
3483
  var ROLLBACK_ORDER = [
@@ -3101,6 +3512,7 @@ var ENRICHMENT_LABEL = {
3101
3512
  var emptyCounts = () => ({
3102
3513
  created: 0,
3103
3514
  updated: 0,
3515
+ matched: 0,
3104
3516
  unchanged: 0,
3105
3517
  skipped: 0,
3106
3518
  manual: 0,
@@ -3110,15 +3522,20 @@ var finish = (step, failed, total) => {
3110
3522
  if (failed > 0) step.fail(`${formatNumber(failed)} of ${formatNumber(total)} failed`);
3111
3523
  else step.done();
3112
3524
  };
3113
- function enrichmentItem(c, pass1Status, maps, facets = ["properties", "topics"]) {
3525
+ function enrichmentItem(c, mode2, maps, facets = ["properties", "topics"]) {
3114
3526
  const properties = facets.includes("properties") ? Object.fromEntries(
3115
- Object.entries(c.properties ?? {}).filter(([key]) => maps.propertyKeys.has(key))
3527
+ Object.entries(c.properties ?? {}).flatMap(([key, value]) => {
3528
+ const targetKey = maps.propertyKeys.get(key);
3529
+ return targetKey === void 0 ? [] : [[targetKey, value]];
3530
+ })
3116
3531
  ) : {};
3117
3532
  const topics = facets.includes("topics") ? (c.topics ?? []).flatMap((t) => {
3118
3533
  const id = maps.topicBySource.get(t.id);
3119
- if (id === void 0 || pass1Status === "updated" && t.subscription !== "opt_out")
3120
- return [];
3121
- return [{ id, subscription: t.subscription }];
3534
+ if (id === void 0) return [];
3535
+ if (t.subscription === "opt_out" || mode2 === "created") {
3536
+ return [{ id, subscription: t.subscription }];
3537
+ }
3538
+ return mode2 === "pending" && maps.optOutByDefault?.has(t.id) === true ? [{ id, subscription: t.subscription }] : [];
3122
3539
  }) : [];
3123
3540
  return {
3124
3541
  email: c.email,
@@ -3141,10 +3558,12 @@ async function applyPlan(input) {
3141
3558
  const failed = (resource, key, { message, statusCode }) => {
3142
3559
  state.failures.push({ resource, key, message, statusCode });
3143
3560
  tally(resource).failed += 1;
3144
- log.warn(`${resource}/${key}: ${message}`);
3145
3561
  };
3562
+ const pending = new Set(state.progress.pendingEnrichment ?? []);
3146
3563
  const save = () => {
3147
3564
  state.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3565
+ if (pending.size > 0) state.progress.pendingEnrichment = [...pending];
3566
+ else delete state.progress.pendingEnrichment;
3148
3567
  input.save(state);
3149
3568
  };
3150
3569
  const outcome = {
@@ -3153,13 +3572,14 @@ async function applyPlan(input) {
3153
3572
  freshSecrets: [],
3154
3573
  domainRecords: {},
3155
3574
  ids: [],
3156
- enrichment: { withProperties: 0, withTopics: 0 }
3575
+ enrichment: { withProperties: 0, withTopics: 0, droppedProperties: [] }
3157
3576
  };
3158
3577
  const topicByName = /* @__PURE__ */ new Map();
3159
3578
  const topicBySource = /* @__PURE__ */ new Map();
3160
3579
  const segmentByName = /* @__PURE__ */ new Map();
3161
3580
  const segmentBySource = /* @__PURE__ */ new Map();
3162
- const propertyKeys = /* @__PURE__ */ new Set();
3581
+ const propertyKeys = /* @__PURE__ */ new Map();
3582
+ const collidingKeys = /* @__PURE__ */ new Map();
3163
3583
  const registerTopic = (name, id) => {
3164
3584
  topicByName.set(name, id);
3165
3585
  const sourceTopic = snapshot.topics.find((t) => t.name === name);
@@ -3171,13 +3591,22 @@ async function applyPlan(input) {
3171
3591
  if (sourceSegment) segmentBySource.set(sourceSegment.id, id);
3172
3592
  };
3173
3593
  for (const item of plan2.items) {
3174
- if (item.action === "unchanged") tally(item.resource).unchanged += 1;
3175
- else if (item.action === "manual") tally(item.resource).manual += 1;
3176
- else if (item.action === "skip") tally(item.resource).skipped += 1;
3594
+ if (item.resource !== "contacts") {
3595
+ if (item.action === "unchanged") tally(item.resource).unchanged += 1;
3596
+ else if (item.action === "manual") tally(item.resource).manual += 1;
3597
+ else if (item.action === "skip") tally(item.resource).skipped += 1;
3598
+ }
3599
+ if (item.resource === "properties" && item.action === "manual") {
3600
+ const collidesWith = item.payload?.collidesWith;
3601
+ if (collidesWith !== void 0) collidingKeys.set(item.key, collidesWith);
3602
+ }
3177
3603
  if (item.targetId === void 0) continue;
3178
3604
  if (item.resource === "topics") registerTopic(item.key, item.targetId);
3179
3605
  else if (item.resource === "segments") registerSegment(item.key, item.targetId);
3180
- else if (item.resource === "properties") propertyKeys.add(item.key);
3606
+ else if (item.resource === "properties") {
3607
+ const targetKey = item.payload?.targetKey;
3608
+ propertyKeys.set(item.key, targetKey ?? item.key);
3609
+ }
3181
3610
  }
3182
3611
  async function runRows(resource, run) {
3183
3612
  const items = plan2.items.filter(
@@ -3208,7 +3637,7 @@ async function applyPlan(input) {
3208
3637
  type: p.type,
3209
3638
  fallbackValue: p.fallback_value
3210
3639
  });
3211
- if (result.ok) propertyKeys.add(p.key);
3640
+ if (result.ok) propertyKeys.set(p.key, p.key);
3212
3641
  return result;
3213
3642
  });
3214
3643
  await runRows("topics", async (item) => {
@@ -3315,8 +3744,11 @@ async function applyPlan(input) {
3315
3744
  const contact = slice[row.index];
3316
3745
  if (contact === void 0) continue;
3317
3746
  pass1.set(contact.email.toLowerCase(), row.status);
3318
- if (row.status === "created") created("contacts", row.id);
3319
- else tally("contacts")[row.status] += 1;
3747
+ if (row.status === "created") {
3748
+ created("contacts", row.id);
3749
+ pending.add(contact.email.toLowerCase());
3750
+ } else if (row.status === "updated") tally("contacts").matched += 1;
3751
+ else tally("contacts").skipped += 1;
3320
3752
  }
3321
3753
  for (const error of out.errors) {
3322
3754
  const contact = slice[error.index];
@@ -3383,6 +3815,10 @@ async function applyPlan(input) {
3383
3815
  const enrichedIds = /* @__PURE__ */ new Set();
3384
3816
  const failedIds = /* @__PURE__ */ new Set();
3385
3817
  const total = snapshot.contacts.length;
3818
+ const droppedContacts = /* @__PURE__ */ new Map();
3819
+ const optOutByDefault = new Set(
3820
+ snapshot.topics.filter((t) => t.defaultSubscription === "opt_out").map((t) => t.id)
3821
+ );
3386
3822
  const passes = [
3387
3823
  {
3388
3824
  facet: "topics",
@@ -3408,6 +3844,21 @@ async function applyPlan(input) {
3408
3844
  for (const line of lines) progress.line(line);
3409
3845
  progress.line("");
3410
3846
  }
3847
+ const keepTargetOptOuts = async (entries) => {
3848
+ const asking = entries.filter(
3849
+ (e) => !e.created && e.item.topics?.some((t) => t.subscription === "opt_in") === true
3850
+ );
3851
+ if (asking.length === 0) return;
3852
+ const optedOut = await target.explicitOptOuts(asking.map((e) => e.item.email));
3853
+ for (const e of asking) {
3854
+ const kept = optedOut.get(e.item.email.toLowerCase());
3855
+ if (kept !== void 0) {
3856
+ e.item.topics = e.item.topics?.filter(
3857
+ (t) => t.subscription !== "opt_in" || !kept.has(t.id)
3858
+ );
3859
+ }
3860
+ }
3861
+ };
3411
3862
  for (const pass of passes) {
3412
3863
  if (!pass.wanted) {
3413
3864
  progress.line(dim(`${ENRICHMENT_LABEL[pass.facet]}: skipped, ${pass.skipped}`));
@@ -3425,6 +3876,7 @@ async function applyPlan(input) {
3425
3876
  let withValues = 0;
3426
3877
  let buffer = [];
3427
3878
  const flush = async () => {
3879
+ if (pass.facet === "topics") await keepTargetOptOuts(buffer);
3428
3880
  const sendable = buffer.filter(
3429
3881
  (b) => b.item.properties !== void 0 || b.item.topics !== void 0
3430
3882
  );
@@ -3461,10 +3913,17 @@ async function applyPlan(input) {
3461
3913
  const status2 = pass1.get(contact.email.toLowerCase());
3462
3914
  if (status2 === "failed" || status2 === "skipped") return;
3463
3915
  processed += 1;
3916
+ if (pass.facet === "properties") {
3917
+ for (const [key, value] of Object.entries(contact.properties ?? {})) {
3918
+ if (collidingKeys.has(key) && String(value) !== "") {
3919
+ droppedContacts.set(key, (droppedContacts.get(key) ?? 0) + 1);
3920
+ }
3921
+ }
3922
+ }
3464
3923
  const item = enrichmentItem(
3465
3924
  contact,
3466
- status2 === "created" || !synced ? "created" : "updated",
3467
- { propertyKeys, topicBySource },
3925
+ status2 === "created" || !synced ? "created" : pending.has(contact.email.toLowerCase()) ? "pending" : "updated",
3926
+ { propertyKeys, topicBySource, optOutByDefault },
3468
3927
  [pass.facet]
3469
3928
  );
3470
3929
  if (status2 === void 0) {
@@ -3472,7 +3931,7 @@ async function applyPlan(input) {
3472
3931
  item.first_name = contact.firstName ?? void 0;
3473
3932
  item.last_name = contact.lastName ?? void 0;
3474
3933
  }
3475
- buffer.push({ id: contact.id, item });
3934
+ buffer.push({ id: contact.id, item, created: status2 === "created" });
3476
3935
  if (buffer.length >= BATCH_MAX) await flush();
3477
3936
  }
3478
3937
  });
@@ -3492,6 +3951,21 @@ async function applyPlan(input) {
3492
3951
  step.done(`${formatNumber(total)} \xB7 ${formatNumber(withValues)} with ${noun}`);
3493
3952
  }
3494
3953
  }
3954
+ outcome.enrichment.droppedProperties = [...collidingKeys].map(([key, collidesWith]) => ({
3955
+ key,
3956
+ collidesWith,
3957
+ contacts: droppedContacts.get(key) ?? 0
3958
+ }));
3959
+ if (snapshot.topics.length === 0) pending.clear();
3960
+ else if (passes.some((p) => p.facet === "topics" && p.wanted)) {
3961
+ for (const c of snapshot.contacts) {
3962
+ const email = c.email.toLowerCase();
3963
+ const status2 = pass1.get(email);
3964
+ if (status2 === "failed" || status2 === "skipped") continue;
3965
+ if (failedIds.has(c.id)) pending.add(email);
3966
+ else pending.delete(email);
3967
+ }
3968
+ }
3495
3969
  state.progress.enrichmentCompleted = true;
3496
3970
  if (tally("enrichment").failed === 0) {
3497
3971
  delete state.progress.enrichmentDone;
@@ -3536,10 +4010,7 @@ async function resolveKey(ctx, input, { label, envName, flag }) {
3536
4010
  if (line === "") throw new Error(`No ${label} arrived on stdin (${flag}-stdin).`);
3537
4011
  return line;
3538
4012
  }
3539
- if (ctx.config.nonInteractive) {
3540
- throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3541
- }
3542
- const key = await secretPrompt(ctx.rl, { label: `${label} (full access)` });
4013
+ const key = (await secretPrompt(ctx.rl, { label: `${label} (full access)` })).trim();
3543
4014
  if (key === "") throw new Error(`Missing ${label}. Set ${envName} or pass ${flag}-stdin.`);
3544
4015
  return key;
3545
4016
  }
@@ -3620,10 +4091,10 @@ async function connectTarget(ctx) {
3620
4091
  });
3621
4092
  const target = createBillionSendTarget(http, ctx.log, baseUrl);
3622
4093
  const usage = await target.probe();
3623
- ctx.out.write(
3624
- `${ok(SYM.ok)} BillionSend Cloud ${dim("\xB7")} plan ${capitalize(usage.plan ?? "unknown")}
3625
- `
3626
- );
4094
+ const where = baseUrl === CLOUD_API_URL ? "" : ` (${baseUrl})`;
4095
+ const plan2 = usage.plan === null ? "no plan limits" : `plan ${capitalize(usage.plan)}`;
4096
+ ctx.out.write(`${ok(SYM.ok)} BillionSend${where} ${dim("\xB7")} ${plan2}
4097
+ `);
3627
4098
  return { target, usage, baseUrl };
3628
4099
  }
3629
4100
  function bridgeProgress(progress) {
@@ -3724,7 +4195,7 @@ async function resolveDomainLimit(ctx, plan2, target) {
3724
4195
  );
3725
4196
  return capDomainCreates(plan2, allowed);
3726
4197
  }
3727
- async function prepare(ctx, providerId) {
4198
+ async function prepare(ctx, providerId, { pick = true } = {}) {
3728
4199
  const { config, out } = ctx;
3729
4200
  const label = providers[providerId].label;
3730
4201
  printHeader(
@@ -3741,18 +4212,30 @@ ${heading(`Reading ${label}`)}
3741
4212
  const snapshot = await source.readShallow({
3742
4213
  include,
3743
4214
  includeSent: config.includeSent,
4215
+ segments: config.segment,
3744
4216
  onProgress: bridgeProgress(ctx.progress)
3745
4217
  });
3746
4218
  snapshot.metrics = await source.readMetrics();
3747
4219
  const step = ctx.progress.step("BillionSend");
3748
- const targetState = await target.readState();
4220
+ let targetState = await target.readState();
4221
+ if (include.has("contacts") && snapshot.contacts.length > 0) {
4222
+ targetState = {
4223
+ ...targetState,
4224
+ contacts: await target.findContacts(snapshot.contacts.map((c) => c.email))
4225
+ };
4226
+ }
3749
4227
  step.done("current state read");
3750
- const chosen = config.nonInteractive || config.only !== null || config.skip.length > 0 ? include : await pickResources(ctx, snapshot, include);
4228
+ const chosen = !pick || config.nonInteractive || config.only !== null || config.skip.length > 0 ? include : await pickResources(ctx, snapshot, include);
3751
4229
  let plan2 = buildPlan({
3752
4230
  snapshot,
3753
4231
  target: targetState,
3754
4232
  options: {
3755
4233
  include: chosen,
4234
+ // What the picker left selected is recorded as `only`, so a plan file reproduces it.
4235
+ only: chosen.size === include.size ? config.only : RESOURCES.filter((r) => chosen.has(r)),
4236
+ skip: config.skip,
4237
+ segment: config.segment,
4238
+ onConflict: config.onConflict,
3756
4239
  includeSent: config.includeSent,
3757
4240
  freshWebhookSecrets: config.freshWebhookSecrets,
3758
4241
  rps: config.rps,
@@ -3803,15 +4286,17 @@ function idleOutcome(plan2, state) {
3803
4286
  const c = counts[item.resource] ?? {
3804
4287
  created: 0,
3805
4288
  updated: 0,
4289
+ matched: 0,
3806
4290
  unchanged: 0,
3807
4291
  skipped: 0,
3808
4292
  manual: 0,
3809
4293
  failed: 0
3810
4294
  };
3811
4295
  counts[item.resource] = c;
3812
- if (item.action === "unchanged") c.unchanged += 1;
3813
- else if (item.action === "manual") c.manual += 1;
3814
- else if (item.action === "skip") c.skipped += 1;
4296
+ const rows = item.count ?? 1;
4297
+ if (item.action === "unchanged") c.unchanged += rows;
4298
+ else if (item.action === "manual") c.manual += rows;
4299
+ else if (item.action === "skip") c.skipped += rows;
3815
4300
  }
3816
4301
  return {
3817
4302
  state,
@@ -3819,7 +4304,7 @@ function idleOutcome(plan2, state) {
3819
4304
  freshSecrets: [],
3820
4305
  domainRecords: {},
3821
4306
  ids: [],
3822
- enrichment: { withProperties: 0, withTopics: 0 }
4307
+ enrichment: { withProperties: 0, withTopics: 0, droppedProperties: [] }
3823
4308
  };
3824
4309
  }
3825
4310
  var runReport = (prepared, outcome) => buildReport({
@@ -3899,6 +4384,51 @@ async function migrate(ctx) {
3899
4384
 
3900
4385
  // src/commands/apply.ts
3901
4386
  var MAX_PLAN_AGE_MS = 36e5;
4387
+ var DIFF_SHOWN = 5;
4388
+ var sorted = (list) => [...list].sort();
4389
+ var show = (list) => list === null ? "(not set)" : list.length === 0 ? "(none)" : list.join(",");
4390
+ function followPlanOptions(config, file, recorded) {
4391
+ const conflicts = [];
4392
+ const conflict = (flag, given, wanted) => {
4393
+ conflicts.push(`${flag}: the command line has ${given}, the file has ${wanted}`);
4394
+ };
4395
+ const g = config.given;
4396
+ if (g.has("only") && canonicalJson(config.only && sorted(config.only)) !== canonicalJson(recorded.only && sorted(recorded.only))) {
4397
+ conflict("--only", show(config.only), show(recorded.only));
4398
+ }
4399
+ if (g.has("skip") && canonicalJson(sorted(config.skip)) !== canonicalJson(sorted(recorded.skip))) {
4400
+ conflict("--skip", show(config.skip), show(recorded.skip));
4401
+ }
4402
+ if (g.has("segment") && canonicalJson(sorted(config.segment)) !== canonicalJson(sorted(recorded.segment))) {
4403
+ conflict("--segment", show(config.segment), show(recorded.segment));
4404
+ }
4405
+ if (g.has("on-conflict") && config.onConflict !== recorded.onConflict) {
4406
+ conflict("--on-conflict", config.onConflict, recorded.onConflict);
4407
+ }
4408
+ if (g.has("include-sent") && config.includeSent !== recorded.includeSent) {
4409
+ conflict("--include-sent", String(config.includeSent), String(recorded.includeSent));
4410
+ }
4411
+ if (g.has("fresh-webhook-secrets") && config.freshWebhookSecrets !== recorded.freshWebhookSecrets) {
4412
+ conflict(
4413
+ "--fresh-webhook-secrets",
4414
+ String(config.freshWebhookSecrets),
4415
+ String(recorded.freshWebhookSecrets)
4416
+ );
4417
+ }
4418
+ if (conflicts.length > 0) {
4419
+ throw new Error(
4420
+ `${file} was made with other options than this command line asks for:
4421
+ ${conflicts.join("\n ")}
4422
+ Applying a file follows the options it was made with: leave these flags out, or run \`migrate plan --out ${file}\` again with the new ones.`
4423
+ );
4424
+ }
4425
+ config.only = recorded.only;
4426
+ config.skip = [...recorded.skip];
4427
+ config.segment = [...recorded.segment];
4428
+ config.onConflict = recorded.onConflict;
4429
+ config.includeSent = recorded.includeSent;
4430
+ config.freshWebhookSecrets = recorded.freshWebhookSecrets;
4431
+ }
3902
4432
  async function apply(ctx) {
3903
4433
  const { config, out } = ctx;
3904
4434
  if (config.planFile === null) return migrate(ctx);
@@ -3912,6 +4442,7 @@ async function apply(ctx) {
3912
4442
  );
3913
4443
  }
3914
4444
  const saved = parsePlan(text);
4445
+ followPlanOptions(config, config.planFile, saved.options);
3915
4446
  const ageMs = Date.now() - Date.parse(saved.createdAt);
3916
4447
  const stale = !(ageMs < MAX_PLAN_AGE_MS);
3917
4448
  if (stale && config.nonInteractive) {
@@ -3925,7 +4456,7 @@ async function apply(ctx) {
3925
4456
  `
3926
4457
  );
3927
4458
  }
3928
- const prepared = await prepare(ctx, config.from ?? saved.source);
4459
+ const prepared = await prepare(ctx, config.from ?? saved.source, { pick: false });
3929
4460
  if (saved.target.baseUrl !== prepared.baseUrl) {
3930
4461
  throw new Error(
3931
4462
  `${config.planFile} was made for ${saved.target.baseUrl}; connected to ${prepared.baseUrl}.`
@@ -3933,11 +4464,18 @@ async function apply(ctx) {
3933
4464
  }
3934
4465
  const reasons = [];
3935
4466
  if (stale) reasons.push(`is ${formatDuration(ageMs / 1e3)} old`);
3936
- if (planHash(saved) !== planHash(prepared.plan)) reasons.push("differs from the plan just built");
4467
+ const same = planHash(saved) === planHash(prepared.plan);
4468
+ const differing = same ? [] : describePlanDiff(saved, prepared.plan);
4469
+ if (!same) reasons.push("differs from the plan just built");
3937
4470
  if (reasons.length > 0) {
3938
- const notice = `${config.planFile} ${reasons.join(" and ")}; the plan above is current.`;
4471
+ const cause = differing.length === 0 ? "" : ` The options are the file's own, so the source or your BillionSend account changed since the file was made: ${differing.slice(0, DIFF_SHOWN).join(
4472
+ "; "
4473
+ )}${differing.length > DIFF_SHOWN ? `; \u2026 and ${differing.length - DIFF_SHOWN} more` : ""}.`;
4474
+ const notice = `${config.planFile} ${reasons.join(" and ")}; the plan above is current.${cause}`;
3939
4475
  if (config.nonInteractive) {
3940
- throw new Error(`${notice} Re-run \`migrate plan --out\`, or apply without a file.`);
4476
+ throw new Error(
4477
+ `${notice} Run \`migrate plan --out ${config.planFile}\` again to refresh the file, or apply without a file.`
4478
+ );
3941
4479
  }
3942
4480
  out.write(`${notice}
3943
4481
  `);
@@ -3957,6 +4495,11 @@ async function plan(ctx) {
3957
4495
  if (ctx.config.out !== null) {
3958
4496
  writeFileSync2(ctx.config.out, json);
3959
4497
  ctx.out.write(`Plan written to ${ctx.config.out}
4498
+ `);
4499
+ }
4500
+ if (ctx.config.report !== null) {
4501
+ writePlanReport(ctx.config.report, prepared.plan, prepared.provider.label);
4502
+ ctx.out.write(`Plan report written to ${ctx.config.report}
3960
4503
  `);
3961
4504
  }
3962
4505
  if (ctx.config.json) ctx.stdout.write(json);
@@ -3983,8 +4526,9 @@ async function rollback(ctx) {
3983
4526
  const state = readJson(paths.state);
3984
4527
  const pending = ROLLBACK_ORDER.filter((r) => (state?.created[r]?.length ?? 0) > 0);
3985
4528
  const deleted = {};
4529
+ const kept = {};
3986
4530
  const emitJson = (failures) => {
3987
- if (config.json) ctx.stdout.write(`${JSON.stringify({ deleted, failures })}
4531
+ if (config.json) ctx.stdout.write(`${JSON.stringify({ deleted, kept, failures })}
3988
4532
  `);
3989
4533
  };
3990
4534
  if (state === null || pending.length === 0) {
@@ -4025,7 +4569,6 @@ async function rollback(ctx) {
4025
4569
 
4026
4570
  `);
4027
4571
  if (!config.yes) {
4028
- if (config.nonInteractive) throw new Error("Rollback needs --yes in non-interactive mode.");
4029
4572
  if (!await confirmPrompt(ctx.rl, { label: "Delete these from your BillionSend instance?" })) {
4030
4573
  out.write("Nothing deleted.\n");
4031
4574
  emitJson([]);
@@ -4050,15 +4593,17 @@ async function rollback(ctx) {
4050
4593
  };
4051
4594
  const step = ctx.progress.step(RESOURCE_LABEL[resource]);
4052
4595
  let failed = 0;
4596
+ let permanent = 0;
4053
4597
  if (resource === "suppressions") {
4054
- const { ids: removed, errors } = await target.removeSuppressions(ids);
4055
- const kept = /* @__PURE__ */ new Set();
4598
+ const { ids: removed, notRemoved, errors } = await target.removeSuppressions(ids);
4599
+ permanent = notRemoved.length;
4600
+ const heldBack = /* @__PURE__ */ new Set();
4056
4601
  for (const error of errors) {
4057
- kept.add(error.index);
4602
+ heldBack.add(error.index);
4058
4603
  failed += 1;
4059
4604
  state.failures.push({ resource, key: ids[error.index] ?? "?", message: error.message });
4060
4605
  }
4061
- for (const [i, id] of ids.entries()) if (!kept.has(i)) remaining.delete(id);
4606
+ for (const [i, id] of ids.entries()) if (!heldBack.has(i)) remaining.delete(id);
4062
4607
  step.update(removed.length, ids.length);
4063
4608
  } else {
4064
4609
  const del = DELETE[resource];
@@ -4074,7 +4619,8 @@ async function rollback(ctx) {
4074
4619
  if ((n + 1) % SAVE_EVERY === 0) save();
4075
4620
  }
4076
4621
  }
4077
- deleted[resource] = ids.length - remaining.size;
4622
+ deleted[resource] = ids.length - remaining.size - permanent;
4623
+ if (permanent > 0) kept[resource] = permanent;
4078
4624
  if (resource === "contacts") state.progress = {};
4079
4625
  save();
4080
4626
  if (failed > 0) step.fail(`${pluralize(failed, "delete")} failed`);
@@ -4094,6 +4640,12 @@ ${pluralize(state.failures.length, "delete")} failed; the ids stay in ${paths.st
4094
4640
  return 3;
4095
4641
  }
4096
4642
  out.write("\nRolled back. Rows this tool only updated were left as they are.\n");
4643
+ if (kept.suppressions !== void 0) {
4644
+ out.write(
4645
+ `${pluralize(kept.suppressions, "suppression")} stay: a bounce or complaint entry is permanent and BillionSend does not remove it.
4646
+ `
4647
+ );
4648
+ }
4097
4649
  return 0;
4098
4650
  }
4099
4651
 
@@ -4134,14 +4686,20 @@ async function status(ctx) {
4134
4686
  bold(formatNumber(ids.length))
4135
4687
  ])
4136
4688
  );
4137
- const { contactsCursor, enrichmentDone } = state.progress;
4689
+ const { contactsCursor, enrichmentDone, pendingEnrichment } = state.progress;
4138
4690
  out.write("\nProgress\n");
4139
4691
  block([
4140
4692
  [" Contacts", contactsCursor ? `resumes after ${contactsCursor}` : "complete"],
4141
4693
  [
4142
4694
  " Enriched",
4143
4695
  enrichmentDone ? `resumes with ${formatNumber(enrichmentDone.length)} done` : "complete"
4144
- ]
4696
+ ],
4697
+ ...pendingEnrichment && pendingEnrichment.length > 0 ? [
4698
+ [
4699
+ " Waiting",
4700
+ `${pluralize(pendingEnrichment.length, "contact")} not enriched yet`
4701
+ ]
4702
+ ] : []
4145
4703
  ]);
4146
4704
  if (state.failures.length > 0) {
4147
4705
  out.write(`