@billionsend/cli 0.3.3 → 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.
- package/README.md +44 -17
- package/dist/index.js +647 -69
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,28 +14,55 @@ Node 18 or newer; no dependencies.
|
|
|
14
14
|
|
|
15
15
|
## What moves
|
|
16
16
|
|
|
17
|
-
| Resource | How
|
|
18
|
-
| ---------------------------- |
|
|
19
|
-
| Contacts | Upserted by email through the batch endpoint; `unsubscribed` and topic opt-outs are preserved, never re-subscribed. Resend's `unsubscribed` is global, so it lands as BillionSend's team-wide `unsubscribed: true`; no per-domain unsubscribe is created. Topic subscriptions and properties follow in two per-contact passes that run after everything else, so the account is sendable before they finish. The batch endpoint answers created, updated or skipped but never whether a matched contact changed, so the summary reports those as `matched existing`, not as updated or unchanged.
|
|
20
|
-
| Segments, topics, properties | Matched by name / name / key: created when missing, updated when different, left alone when equal. Segment memberships follow the contacts. BillionSend property keys ignore case, Resend's do not: when Resend has both `plan` and `PLAN`, only the first is created, the other is listed as a manual note, and the report counts the contacts whose value for it was not written. A key that differs only in case from one already on BillionSend is the same property, and values are written under the spelling it has.
|
|
21
|
-
| Templates | Name, alias, subject, html, text, default from, reply-to and variables (up to 50 reply-to addresses and 50 variables; what does not fit is listed as a manual note).
|
|
22
|
-
| Webhooks | Endpoint and events. Signing secrets are copied so receivers keep verifying (`--fresh-webhook-secrets` mints new ones, shown once). Events BillionSend also emits carry over (`email.*`, `contact.created`, `contact.updated`, `contact.deleted`, `contact.topics.updated`, `suppression.added`, `suppression.removed`, `domain.created`, `domain.updated`, `domain.deleted`, `topic.created`, `topic.updated`, `topic.deleted` and `inbox.*`); the rest are dropped per webhook and listed.
|
|
23
|
-
| Suppressions | Bounces, complaints and manual entries, with their origin.
|
|
24
|
-
| Domains | Created with return path and tracking settings, in the
|
|
25
|
-
| Broadcasts | Drafts and scheduled ones import as drafts; sent ones are skipped unless `--include-sent`.
|
|
26
|
-
| API keys | Not recreated (the source only exposes names); the report lists them as a to-do.
|
|
17
|
+
| Resource | How |
|
|
18
|
+
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
19
|
+
| Contacts | Upserted by email through the batch endpoint; `unsubscribed` and topic opt-outs are preserved, never re-subscribed. Resend's `unsubscribed` is global, so it lands as BillionSend's team-wide `unsubscribed: true`; no per-domain unsubscribe is created. Topic subscriptions and properties follow in two per-contact passes that run after everything else, so the account is sendable before they finish. The batch endpoint answers created, updated or skipped but never whether a matched contact changed, so the summary reports those as `matched existing`, not as updated or unchanged. |
|
|
20
|
+
| Segments, topics, properties | Matched by name / name / key: created when missing, updated when different, left alone when equal. Segment memberships follow the contacts. BillionSend property keys ignore case, Resend's do not: when Resend has both `plan` and `PLAN`, only the first is created, the other is listed as a manual note, and the report counts the contacts whose value for it was not written. A key that differs only in case from one already on BillionSend is the same property, and values are written under the spelling it has. |
|
|
21
|
+
| Templates | Name, alias, subject, html, text, default from, reply-to and variables (up to 50 reply-to addresses and 50 variables; what does not fit is listed as a manual note). |
|
|
22
|
+
| Webhooks | Endpoint and events. Signing secrets are copied so receivers keep verifying (`--fresh-webhook-secrets` mints new ones, shown once). Events BillionSend also emits carry over (`email.*`, `contact.created`, `contact.updated`, `contact.deleted`, `contact.topics.updated`, `suppression.added`, `suppression.removed`, `domain.created`, `domain.updated`, `domain.deleted`, `topic.created`, `topic.updated`, `topic.deleted` and `inbox.*`); the rest are dropped per webhook and listed. |
|
|
23
|
+
| Suppressions | Bounces, complaints and manual entries, with their origin. |
|
|
24
|
+
| Domains | Created with return path and tracking settings, in the SES region BillionSend serves (`us-east-2`) — the Resend region does not carry over. The return path is always set explicitly and is never the label the domain has on Resend (`send` unless Resend names another): BillionSend gets `bounce`, or `bounces` when Resend's is already `bounce`, so the bounce MX record on Resend's side is not touched and both providers run in parallel until cutover; the plan and the report state both labels. BillionSend fixes the label at creation (changing it later means deleting the domain and creating it again). A domain that already exists on BillionSend is left as it is. DNS records must be added again (DKIM keys are per provider); the report prints a copy-ready table. Both providers can stay verified side by side. Resend has no unsubscribe subdomain or page, so those are left unset. |
|
|
25
|
+
| Broadcasts | Drafts and scheduled ones import as drafts; sent ones are skipped unless `--include-sent`. |
|
|
26
|
+
| API keys | Not recreated (the source only exposes names); the report lists them as a to-do. |
|
|
27
27
|
|
|
28
28
|
Audiences (deprecated in Resend) are skipped — segments cover them.
|
|
29
29
|
|
|
30
|
+
## Sending
|
|
31
|
+
|
|
32
|
+
The same `BILLIONSEND_API_KEY` sends from the command line. A broadcast goes to a segment, and to a topic's subscribers only when `--topic` is given; segments and topics are named by name or id.
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
export BILLIONSEND_API_KEY=bs_...
|
|
36
|
+
|
|
37
|
+
# Test first: the same broadcast, to these addresses only
|
|
38
|
+
billionsend broadcasts send --from "Leo <leo@mail.example.com>" --subject "Black Friday" \
|
|
39
|
+
--html-file black-friday.html --segment Customers --topic Newsletter \
|
|
40
|
+
--test you@example.com,colleague@example.com --yes
|
|
41
|
+
|
|
42
|
+
# Then the real send: shows the segment's contact count and asks before sending (--yes skips the question)
|
|
43
|
+
billionsend broadcasts send --from "Leo <leo@mail.example.com>" --subject "Black Friday" \
|
|
44
|
+
--html-file black-friday.html --segment Customers --topic Newsletter --wait
|
|
45
|
+
|
|
46
|
+
billionsend broadcasts list # newest first, with ids
|
|
47
|
+
billionsend broadcasts get <id>
|
|
48
|
+
billionsend broadcasts recipients <id> --type opened --all > opened.csv # or --format json
|
|
49
|
+
billionsend segments create --name "Black Friday last call"
|
|
50
|
+
billionsend segments get "Black Friday last call" # its contact count
|
|
51
|
+
billionsend contacts import --file buyers.csv --segment "Black Friday last call"
|
|
52
|
+
billionsend emails send --from "Leo <leo@mail.example.com>" --to you@example.com --subject "Hi" --text-file hi.txt --yes
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`--test` puts the test addresses in a segment named "CLI test recipients" that holds exactly them (contacts that do not exist yet are created; an existing contact's name, topics and unsubscribe state are left as they are) and sends the broadcast there with `[TEST]` before the subject, so a test goes through the real broadcast path: merge tags such as `{{{FIRST_NAME|there}}}` are filled per recipient and the unsubscribe link is the recipient's own. Without a terminal, sending needs `--yes`. `--wait` follows the broadcast until it is sent, failed or canceled, for 30 minutes unless `--wait-timeout <minutes>` says otherwise; a small broadcast reads as sent within about five minutes of its last email, and a first send to contacts the team never mailed is released in steps over about an hour, so give that one `--wait-timeout 90` or more. `contacts import` uploads a CSV (a header row with an email column, at most 20 MiB), follows the import to its end and prints the counts; contacts who unsubscribed stay unsubscribed, and it exits 3 when some rows failed. Contacts the team already has are updated from the file and join `--segment` (a column the file lacks keeps its value); `--on-conflict skip` leaves them out entirely, segment included. By default a contact who got 8 or more of your broadcasts and automation emails with no open or click for 120 days gets a short "still want these?" email instead of the broadcast (only where the sending domain tracks opens or clicks); `--no-dormant-check` sends the content to everyone, and `--include-dormant` also reaches contacts who never answered that email. `broadcasts list` shows each broadcast's id, time, status and name, newest first. `broadcasts recipients` lists who was sent, delivered, opened, clicked, bounced, complained, unsubscribed or suppressed, as CSV or JSON, one page of 100 or every page with `--all`. `billionsend broadcasts --help` lists every option.
|
|
56
|
+
|
|
30
57
|
## Environment
|
|
31
58
|
|
|
32
|
-
| Variable | Meaning
|
|
33
|
-
| ---------------------- |
|
|
34
|
-
| `RESEND_API_KEY` | Source key (full access; the tool only ever reads). Alternatives: `--from-key-stdin`, or a masked prompt in a terminal.
|
|
35
|
-
| `BILLIONSEND_API_KEY` | BillionSend key (full access). Alternatives: `--to-key-stdin`, or a masked prompt.
|
|
36
|
-
| `BILLIONSEND_BASE_URL` | BillionSend API URL. Same as `--to-url`. Unset, the target is
|
|
37
|
-
| `NO_COLOR` | Disables ANSI colors.
|
|
38
|
-
| `DO_NOT_TRACK` | Honored as a no-op: the tool sends no telemetry, never phones home and never checks for updates.
|
|
59
|
+
| Variable | Meaning |
|
|
60
|
+
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
61
|
+
| `RESEND_API_KEY` | Source key (full access; the tool only ever reads). Alternatives: `--from-key-stdin`, or a masked prompt in a terminal. |
|
|
62
|
+
| `BILLIONSEND_API_KEY` | BillionSend key (full access). Alternatives: `--to-key-stdin`, or a masked prompt. |
|
|
63
|
+
| `BILLIONSEND_BASE_URL` | BillionSend API URL. Same as `--to-url`. Unset, the target is `https://api.billionsend.com`, like the SDKs. |
|
|
64
|
+
| `NO_COLOR` | Disables ANSI colors. |
|
|
65
|
+
| `DO_NOT_TRACK` | Honored as a no-op: the tool sends no telemetry, never phones home and never checks for updates. |
|
|
39
66
|
|
|
40
67
|
## Flags
|
|
41
68
|
|
package/dist/index.js
CHANGED
|
@@ -5,13 +5,13 @@ import { realpathSync } from "node:fs";
|
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
|
|
7
7
|
// src/commands/apply.ts
|
|
8
|
-
import { readFileSync as
|
|
8
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
9
9
|
|
|
10
10
|
// src/plan.ts
|
|
11
11
|
import { createHash } from "node:crypto";
|
|
12
12
|
|
|
13
13
|
// src/utils.ts
|
|
14
|
-
var sleep = (ms) => new Promise((
|
|
14
|
+
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
15
15
|
var numberFormat = new Intl.NumberFormat("en-US");
|
|
16
16
|
var formatNumber = (n) => numberFormat.format(n);
|
|
17
17
|
function chunk(items, size) {
|
|
@@ -279,7 +279,8 @@ function createHttp(options) {
|
|
|
279
279
|
authorization: `Bearer ${options.token}`,
|
|
280
280
|
"user-agent": options.userAgent,
|
|
281
281
|
accept: "application/json",
|
|
282
|
-
|
|
282
|
+
// A FormData body sets its own multipart content type, boundary included.
|
|
283
|
+
...body === void 0 || body instanceof FormData ? {} : { "content-type": "application/json" },
|
|
283
284
|
...extraHeaders
|
|
284
285
|
};
|
|
285
286
|
for (const [header, value] of Object.entries(headers)) {
|
|
@@ -292,7 +293,7 @@ function createHttp(options) {
|
|
|
292
293
|
const init = {
|
|
293
294
|
method,
|
|
294
295
|
headers,
|
|
295
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
296
|
+
...body === void 0 ? {} : { body: body instanceof FormData ? body : JSON.stringify(body) }
|
|
296
297
|
};
|
|
297
298
|
const repeatable = idempotent || REPEATABLE_METHODS.has(method);
|
|
298
299
|
let rateLimited = 0;
|
|
@@ -541,7 +542,7 @@ function createResendSource(http, log) {
|
|
|
541
542
|
requests += 1;
|
|
542
543
|
return http.get(route2, options);
|
|
543
544
|
};
|
|
544
|
-
async function
|
|
545
|
+
async function listAll2(route2, query = {}, label, onProgress) {
|
|
545
546
|
const items = [];
|
|
546
547
|
let after;
|
|
547
548
|
const guard = cursorGuard(route2);
|
|
@@ -561,7 +562,7 @@ function createResendSource(http, log) {
|
|
|
561
562
|
return items;
|
|
562
563
|
}
|
|
563
564
|
async function listWithDetails(route2, label, onProgress, detail, keep = () => true) {
|
|
564
|
-
const list = (await
|
|
565
|
+
const list = (await listAll2(route2)).filter(keep);
|
|
565
566
|
const out = [];
|
|
566
567
|
for (const item of list) {
|
|
567
568
|
out.push(await detail(item));
|
|
@@ -571,7 +572,7 @@ function createResendSource(http, log) {
|
|
|
571
572
|
return out;
|
|
572
573
|
}
|
|
573
574
|
async function readSegments(scope, onProgress, membersOf) {
|
|
574
|
-
const list = scope ?? await
|
|
575
|
+
const list = scope ?? await listAll2("/segments");
|
|
575
576
|
const out = [];
|
|
576
577
|
for (const item of list) {
|
|
577
578
|
const { body } = await get(path("segments", item.id));
|
|
@@ -599,13 +600,13 @@ function createResendSource(http, log) {
|
|
|
599
600
|
async readShallow({ include, includeSent = false, segments = [], onProgress }) {
|
|
600
601
|
const snapshot = emptySnapshot();
|
|
601
602
|
const needsContacts = include.has("contacts") || include.has("enrichment");
|
|
602
|
-
const scope = segments.length === 0 ? null : selectSegments(await
|
|
603
|
+
const scope = segments.length === 0 ? null : selectSegments(await listAll2("/segments"), segments);
|
|
603
604
|
if (scope !== null) snapshot.segmentScope = scope.map(({ id, name }) => ({ id, name }));
|
|
604
605
|
const memberLists = /* @__PURE__ */ new Map();
|
|
605
606
|
const membersOf = async (id) => {
|
|
606
607
|
const cached = memberLists.get(id);
|
|
607
608
|
if (cached !== void 0) return cached;
|
|
608
|
-
const members = await
|
|
609
|
+
const members = await listAll2(path("segments", id, "contacts"), {});
|
|
609
610
|
memberLists.set(id, members);
|
|
610
611
|
return members;
|
|
611
612
|
};
|
|
@@ -619,7 +620,7 @@ function createResendSource(http, log) {
|
|
|
619
620
|
);
|
|
620
621
|
}
|
|
621
622
|
if (include.has("properties") || include.has("enrichment")) {
|
|
622
|
-
const list = await
|
|
623
|
+
const list = await listAll2(
|
|
623
624
|
"/contact-properties",
|
|
624
625
|
{},
|
|
625
626
|
"Contact properties",
|
|
@@ -632,7 +633,7 @@ function createResendSource(http, log) {
|
|
|
632
633
|
}));
|
|
633
634
|
}
|
|
634
635
|
if (include.has("topics") || include.has("enrichment")) {
|
|
635
|
-
const list = await
|
|
636
|
+
const list = await listAll2("/topics", {}, "Topics", onProgress);
|
|
636
637
|
snapshot.topics = list.map((topic) => ({
|
|
637
638
|
id: topic.id,
|
|
638
639
|
name: topic.name,
|
|
@@ -650,7 +651,7 @@ function createResendSource(http, log) {
|
|
|
650
651
|
}
|
|
651
652
|
if (needsContacts) {
|
|
652
653
|
if (scope === null) {
|
|
653
|
-
const list = await
|
|
654
|
+
const list = await listAll2("/contacts", {}, "Contacts", onProgress);
|
|
654
655
|
snapshot.contacts = list.map(toContact);
|
|
655
656
|
} else {
|
|
656
657
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -700,7 +701,7 @@ function createResendSource(http, log) {
|
|
|
700
701
|
);
|
|
701
702
|
}
|
|
702
703
|
if (include.has("suppressions")) {
|
|
703
|
-
const list = await
|
|
704
|
+
const list = await listAll2(
|
|
704
705
|
"/suppressions",
|
|
705
706
|
{},
|
|
706
707
|
"Suppressions",
|
|
@@ -713,7 +714,7 @@ function createResendSource(http, log) {
|
|
|
713
714
|
}));
|
|
714
715
|
}
|
|
715
716
|
if (include.has("api-keys")) {
|
|
716
|
-
const list = await
|
|
717
|
+
const list = await listAll2("/api-keys", {}, "API keys", onProgress);
|
|
717
718
|
snapshot.apiKeys = list.map((key) => ({ name: key.name, createdAt: key.created_at }));
|
|
718
719
|
}
|
|
719
720
|
return snapshot;
|
|
@@ -737,7 +738,7 @@ function createResendSource(http, log) {
|
|
|
737
738
|
enriched.properties = toProperties(body.properties);
|
|
738
739
|
}
|
|
739
740
|
if (wantTopics) {
|
|
740
|
-
const topics = await
|
|
741
|
+
const topics = await listAll2(path("contacts", contact.id, "topics"));
|
|
741
742
|
enriched.topics = topics.map((topic) => ({
|
|
742
743
|
id: topic.id,
|
|
743
744
|
subscription: topic.subscription ?? "opt_in"
|
|
@@ -857,10 +858,10 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
857
858
|
rl.on("line", (line) => {
|
|
858
859
|
if (!terminal && input.isRaw === true) return;
|
|
859
860
|
if (waiting) {
|
|
860
|
-
const
|
|
861
|
+
const resolve2 = waiting;
|
|
861
862
|
waiting = void 0;
|
|
862
863
|
if (!terminal) endRow();
|
|
863
|
-
|
|
864
|
+
resolve2(line);
|
|
864
865
|
} else {
|
|
865
866
|
queue.push(line);
|
|
866
867
|
}
|
|
@@ -868,10 +869,10 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
868
869
|
rl.on("close", () => {
|
|
869
870
|
ended = true;
|
|
870
871
|
if (waiting) {
|
|
871
|
-
const
|
|
872
|
+
const resolve2 = waiting;
|
|
872
873
|
waiting = void 0;
|
|
873
874
|
endRow();
|
|
874
|
-
|
|
875
|
+
resolve2("");
|
|
875
876
|
}
|
|
876
877
|
});
|
|
877
878
|
rl.on("SIGINT", () => {
|
|
@@ -894,8 +895,8 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
894
895
|
endRow();
|
|
895
896
|
return Promise.resolve(line);
|
|
896
897
|
}
|
|
897
|
-
return new Promise((
|
|
898
|
-
waiting =
|
|
898
|
+
return new Promise((resolve2) => {
|
|
899
|
+
waiting = resolve2;
|
|
899
900
|
});
|
|
900
901
|
},
|
|
901
902
|
take() {
|
|
@@ -957,7 +958,7 @@ function readKeys(onKey, erase, stdout = process.stdout) {
|
|
|
957
958
|
const wasRaw = stdin.isRaw === true;
|
|
958
959
|
stdin.setRawMode(true);
|
|
959
960
|
stdin.resume();
|
|
960
|
-
return new Promise((
|
|
961
|
+
return new Promise((resolve2) => {
|
|
961
962
|
const done = (value) => {
|
|
962
963
|
stdin.removeListener("keypress", listener);
|
|
963
964
|
process.removeListener("SIGINT", onSigint);
|
|
@@ -970,7 +971,7 @@ function readKeys(onKey, erase, stdout = process.stdout) {
|
|
|
970
971
|
stdout.write("\n");
|
|
971
972
|
process.exit(130);
|
|
972
973
|
}
|
|
973
|
-
|
|
974
|
+
resolve2(value);
|
|
974
975
|
};
|
|
975
976
|
const onSigint = () => done(void 0);
|
|
976
977
|
process.once("SIGINT", onSigint);
|
|
@@ -2119,10 +2120,10 @@ function describePlanDiff(saved, current) {
|
|
|
2119
2120
|
}
|
|
2120
2121
|
|
|
2121
2122
|
// src/config.ts
|
|
2122
|
-
import { parseArgs } from "node:util";
|
|
2123
|
+
import { parseArgs as parseArgs2 } from "node:util";
|
|
2123
2124
|
|
|
2124
2125
|
// src/meta.ts
|
|
2125
|
-
var VERSION = true ? "0.
|
|
2126
|
+
var VERSION = true ? "0.5.0" : "0.0.0-dev";
|
|
2126
2127
|
var REPO_URL = "https://github.com/billionsend/billionsend-cli";
|
|
2127
2128
|
var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
|
|
2128
2129
|
var CLOUD_API_URL = "https://api.billionsend.com";
|
|
@@ -2145,6 +2146,604 @@ var RESOURCES = [
|
|
|
2145
2146
|
"api-keys"
|
|
2146
2147
|
];
|
|
2147
2148
|
|
|
2149
|
+
// src/send.ts
|
|
2150
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2151
|
+
import { basename, resolve } from "node:path";
|
|
2152
|
+
import { parseArgs } from "node:util";
|
|
2153
|
+
|
|
2154
|
+
// src/log.ts
|
|
2155
|
+
var RANK = { error: 0, warn: 1, info: 2, debug: 3 };
|
|
2156
|
+
var TOKEN_RE = /\b(?:re|bs|whsec)_[A-Za-z0-9+/=_-]+/g;
|
|
2157
|
+
var AUTHORIZATION_RE = /(authorization["']?\s*[:=]\s*["']?)(?:bearer\s+)?[^\s"',}]+/gi;
|
|
2158
|
+
function redact(text) {
|
|
2159
|
+
return text.replace(AUTHORIZATION_RE, "$1***").replace(TOKEN_RE, "***");
|
|
2160
|
+
}
|
|
2161
|
+
function createLogger({
|
|
2162
|
+
level = "info",
|
|
2163
|
+
stream = process.stderr
|
|
2164
|
+
} = {}) {
|
|
2165
|
+
const write = (at, prefix, message) => {
|
|
2166
|
+
if (RANK[at] <= RANK[level]) stream.write(`${prefix}${stripControl(redact(message))}
|
|
2167
|
+
`);
|
|
2168
|
+
};
|
|
2169
|
+
return {
|
|
2170
|
+
level,
|
|
2171
|
+
error: (message) => write("error", `${err("error:")} `, message),
|
|
2172
|
+
warn: (message) => write("warn", `${warn("warning:")} `, message),
|
|
2173
|
+
info: (message) => write("info", "", message),
|
|
2174
|
+
debug: (message) => write("debug", "", message)
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
// src/send.ts
|
|
2179
|
+
var SEND_COMMANDS = ["broadcasts", "emails", "segments", "contacts"];
|
|
2180
|
+
var TEST_SEGMENT_NAME = "CLI test recipients";
|
|
2181
|
+
var SEND_RPS = 5;
|
|
2182
|
+
var WAIT_POLL_MS = 5e3;
|
|
2183
|
+
var DEFAULT_WAIT_MINUTES = 30;
|
|
2184
|
+
var MAX_WAIT_MINUTES = 24 * 60;
|
|
2185
|
+
var IMPORT_POLL_MS = 2e3;
|
|
2186
|
+
var IMPORT_MAX_BYTES = 20 * 1024 * 1024;
|
|
2187
|
+
var RECIPIENT_TYPES = [
|
|
2188
|
+
"sent",
|
|
2189
|
+
"delivered",
|
|
2190
|
+
"opened",
|
|
2191
|
+
"clicked",
|
|
2192
|
+
"bounced",
|
|
2193
|
+
"complained",
|
|
2194
|
+
"unsubscribed",
|
|
2195
|
+
"suppressed"
|
|
2196
|
+
];
|
|
2197
|
+
var SYSTEM_CLOCK = {
|
|
2198
|
+
now: () => Date.now(),
|
|
2199
|
+
sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms))
|
|
2200
|
+
};
|
|
2201
|
+
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["sent", "failed", "canceled", "cancelled"]);
|
|
2202
|
+
var sendHelpText = () => `Sending and the account
|
|
2203
|
+
billionsend broadcasts send --from <addr> --subject <s> --html-file <f> --segment <name|id> [options]
|
|
2204
|
+
billionsend broadcasts send ... --test <email> [--test <email>] the same broadcast, to these addresses only
|
|
2205
|
+
billionsend broadcasts list [--limit <n>] [--all] newest first, with each broadcast's id
|
|
2206
|
+
billionsend broadcasts get <id>
|
|
2207
|
+
billionsend broadcasts recipients <id> --type <type> [--all] [--format csv|json]
|
|
2208
|
+
billionsend emails send --from <addr> --to <email> --subject <s> (--html-file <f> | --text-file <f>) [options]
|
|
2209
|
+
billionsend segments create --name <name>
|
|
2210
|
+
billionsend segments get <name|id>
|
|
2211
|
+
billionsend contacts import --file <contacts.csv> [--segment <name|id>] [--on-conflict upsert|skip]
|
|
2212
|
+
|
|
2213
|
+
Sending options
|
|
2214
|
+
--from <address> sender, "Name <user@your-domain>"; the domain must be verified on BillionSend
|
|
2215
|
+
--subject <text> subject line
|
|
2216
|
+
--html-file <path> HTML body; broadcast merge tags ({{{FIRST_NAME|there}}}, {{{RESEND_UNSUBSCRIBE_URL}}}) are filled per recipient
|
|
2217
|
+
--text-file <path> plain-text body (with or instead of --html-file)
|
|
2218
|
+
--segment <name|id> broadcasts: who it goes to
|
|
2219
|
+
--topic <name|id> broadcasts: only contacts subscribed to this topic
|
|
2220
|
+
--name <text> broadcasts: internal name (default: the subject)
|
|
2221
|
+
--preview-text <text> broadcasts: inbox preview line
|
|
2222
|
+
--reply-to <address> repeatable
|
|
2223
|
+
--to <email> emails: repeatable
|
|
2224
|
+
--no-dormant-check broadcasts: send the content to every contact. By default a contact who got 8 or more
|
|
2225
|
+
of your broadcasts and automation emails with no open or click for 120 days gets a short
|
|
2226
|
+
"still want these?" email instead (only where the domain tracks opens or clicks)
|
|
2227
|
+
--include-dormant broadcasts: also send to contacts marked dormant (they never answered that email)
|
|
2228
|
+
--test <email> broadcasts: send to these addresses instead of the segment (repeatable or comma-separated).
|
|
2229
|
+
They are put in a segment named "${TEST_SEGMENT_NAME}" holding exactly them, so the test
|
|
2230
|
+
goes through the real broadcast path: names and unsubscribe links are each recipient's own
|
|
2231
|
+
--wait broadcasts: follow the broadcast until it is sent, failed or canceled
|
|
2232
|
+
--wait-timeout <minutes> how long --wait and contacts import follow before giving up (default ${DEFAULT_WAIT_MINUTES}).
|
|
2233
|
+
A first send to new contacts is released in steps over about an hour: give it 90 or more
|
|
2234
|
+
--idempotency-key <key> emails: a retry with the same key sends once
|
|
2235
|
+
--type <type> recipients: ${RECIPIENT_TYPES.join(", ")}
|
|
2236
|
+
--all recipients, list: every page (default: one page)
|
|
2237
|
+
--limit <n> list: how many per page, 1-100 (default 20)
|
|
2238
|
+
--format csv|json recipients: output format (default csv; --json is the same as --format json)
|
|
2239
|
+
--file <path> contacts import: a CSV with a header row and an email column, at most 20 MiB;
|
|
2240
|
+
contacts who unsubscribed stay unsubscribed
|
|
2241
|
+
--on-conflict upsert|skip contacts import: update contacts the team already has from the file and add them to
|
|
2242
|
+
--segment (default; a column the file lacks keeps its value), or skip them entirely,
|
|
2243
|
+
segment included
|
|
2244
|
+
--key-stdin read the BillionSend API key from stdin instead of BILLIONSEND_API_KEY
|
|
2245
|
+
-y, --yes send without asking; required when stdin is not a terminal
|
|
2246
|
+
--json JSON on stdout
|
|
2247
|
+
`;
|
|
2248
|
+
var UsageError = class extends Error {
|
|
2249
|
+
};
|
|
2250
|
+
var OPTIONS = {
|
|
2251
|
+
from: { type: "string" },
|
|
2252
|
+
subject: { type: "string" },
|
|
2253
|
+
"html-file": { type: "string" },
|
|
2254
|
+
"text-file": { type: "string" },
|
|
2255
|
+
segment: { type: "string" },
|
|
2256
|
+
topic: { type: "string" },
|
|
2257
|
+
name: { type: "string" },
|
|
2258
|
+
"preview-text": { type: "string" },
|
|
2259
|
+
"reply-to": { type: "string", multiple: true },
|
|
2260
|
+
to: { type: "string", multiple: true },
|
|
2261
|
+
test: { type: "string", multiple: true },
|
|
2262
|
+
wait: { type: "boolean" },
|
|
2263
|
+
"no-dormant-check": { type: "boolean" },
|
|
2264
|
+
"include-dormant": { type: "boolean" },
|
|
2265
|
+
limit: { type: "string" },
|
|
2266
|
+
"wait-timeout": { type: "string" },
|
|
2267
|
+
type: { type: "string" },
|
|
2268
|
+
all: { type: "boolean" },
|
|
2269
|
+
format: { type: "string" },
|
|
2270
|
+
file: { type: "string" },
|
|
2271
|
+
"on-conflict": { type: "string" },
|
|
2272
|
+
"idempotency-key": { type: "string" },
|
|
2273
|
+
"key-stdin": { type: "boolean" },
|
|
2274
|
+
"to-url": { type: "string" },
|
|
2275
|
+
yes: { type: "boolean", short: "y" },
|
|
2276
|
+
json: { type: "boolean" },
|
|
2277
|
+
help: { type: "boolean", short: "h" }
|
|
2278
|
+
};
|
|
2279
|
+
var EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
2280
|
+
function splitAddresses(values) {
|
|
2281
|
+
const out = [];
|
|
2282
|
+
for (const value of values ?? []) {
|
|
2283
|
+
for (const part of value.split(",")) {
|
|
2284
|
+
const email = part.trim().toLowerCase();
|
|
2285
|
+
if (email === "") continue;
|
|
2286
|
+
if (!EMAIL.test(email)) throw new UsageError(`Not an email address: ${part.trim()}`);
|
|
2287
|
+
if (!out.includes(email)) out.push(email);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
return out;
|
|
2291
|
+
}
|
|
2292
|
+
function required(values, name) {
|
|
2293
|
+
const value = values[name]?.trim();
|
|
2294
|
+
if (!value) throw new UsageError(`--${name} is required.`);
|
|
2295
|
+
return value;
|
|
2296
|
+
}
|
|
2297
|
+
function readBody(io, values) {
|
|
2298
|
+
const read = (flag) => {
|
|
2299
|
+
const path2 = values[flag];
|
|
2300
|
+
if (path2 === void 0) return void 0;
|
|
2301
|
+
try {
|
|
2302
|
+
return readFileSync(resolve(io.cwd, path2), "utf8");
|
|
2303
|
+
} catch {
|
|
2304
|
+
throw new UsageError(`Cannot read --${flag} ${path2}`);
|
|
2305
|
+
}
|
|
2306
|
+
};
|
|
2307
|
+
const html = read("html-file");
|
|
2308
|
+
const text = read("text-file");
|
|
2309
|
+
if (html === void 0 && text === void 0)
|
|
2310
|
+
throw new UsageError("--html-file or --text-file is required.");
|
|
2311
|
+
if (`${html ?? ""}${text ?? ""}`.trim() === "")
|
|
2312
|
+
throw new UsageError("The message body is empty.");
|
|
2313
|
+
return { ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } };
|
|
2314
|
+
}
|
|
2315
|
+
async function listAll(http, path2) {
|
|
2316
|
+
const rows = [];
|
|
2317
|
+
const guard = cursorGuard(path2);
|
|
2318
|
+
let after;
|
|
2319
|
+
for (; ; ) {
|
|
2320
|
+
const { body } = await http.get(path2, { query: { limit: 100, after } });
|
|
2321
|
+
const page = pageItems(path2, body, after);
|
|
2322
|
+
guard(page, after);
|
|
2323
|
+
rows.push(...page);
|
|
2324
|
+
if (body.has_more !== true) return rows;
|
|
2325
|
+
after = nextCursor(path2, page, after);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
async function resolveNamed(http, path2, kind, ref) {
|
|
2329
|
+
const rows = await listAll(http, path2);
|
|
2330
|
+
const byId = rows.find((r) => r.id === ref);
|
|
2331
|
+
if (byId) return byId;
|
|
2332
|
+
const byName = rows.filter((r) => r.name === ref);
|
|
2333
|
+
if (byName.length === 1 && byName[0]) return byName[0];
|
|
2334
|
+
const choices = rows.map((r) => ` ${r.name} ${r.id}`).join("\n") || " (none)";
|
|
2335
|
+
if (byName.length > 1)
|
|
2336
|
+
throw new UsageError(`${byName.length} ${kind}s are named "${ref}"; pass the id:
|
|
2337
|
+
${choices}`);
|
|
2338
|
+
throw new UsageError(`No ${kind} "${ref}". Existing ${kind}s:
|
|
2339
|
+
${choices}`);
|
|
2340
|
+
}
|
|
2341
|
+
async function prepareTestSegment(http, emails) {
|
|
2342
|
+
const segments = await listAll(http, "/segments");
|
|
2343
|
+
const existing = segments.find((s) => s.name === TEST_SEGMENT_NAME);
|
|
2344
|
+
const segment = existing ?? (await http.post("/segments", { name: TEST_SEGMENT_NAME }, { idempotent: false })).body;
|
|
2345
|
+
const members = await listAll(
|
|
2346
|
+
http,
|
|
2347
|
+
route`/segments/${segment.id}/contacts`
|
|
2348
|
+
);
|
|
2349
|
+
for (const member of members) {
|
|
2350
|
+
if (!emails.includes(member.email.toLowerCase()))
|
|
2351
|
+
await http.delete(route`/contacts/${member.id}/segments/${segment.id}`);
|
|
2352
|
+
}
|
|
2353
|
+
const found = await http.post(
|
|
2354
|
+
"/contacts/batch/get",
|
|
2355
|
+
{ contacts: emails.map((email) => ({ email })) },
|
|
2356
|
+
{ idempotent: true }
|
|
2357
|
+
);
|
|
2358
|
+
const idByEmail = new Map(found.body.data.map((c) => [c.email.toLowerCase(), c.id]));
|
|
2359
|
+
const missing = emails.filter((e) => !idByEmail.has(e));
|
|
2360
|
+
if (missing.length > 0) {
|
|
2361
|
+
const created = await http.post(
|
|
2362
|
+
"/contacts/batch",
|
|
2363
|
+
missing.map((email) => ({ email })),
|
|
2364
|
+
{ query: { on_conflict: "skip" }, idempotent: true }
|
|
2365
|
+
);
|
|
2366
|
+
for (const row of created.body.data) idByEmail.set(missing[row.index], row.id);
|
|
2367
|
+
}
|
|
2368
|
+
for (const email of emails) {
|
|
2369
|
+
const id = idByEmail.get(email);
|
|
2370
|
+
if (!members.some((m) => m.id === id))
|
|
2371
|
+
await http.post(route`/contacts/${id}/segments/${segment.id}`, void 0, {
|
|
2372
|
+
idempotent: true
|
|
2373
|
+
});
|
|
2374
|
+
}
|
|
2375
|
+
return segment;
|
|
2376
|
+
}
|
|
2377
|
+
async function confirm(io, values, question) {
|
|
2378
|
+
if (values.yes) return true;
|
|
2379
|
+
if (io.stdin.isTTY !== true)
|
|
2380
|
+
throw new UsageError(
|
|
2381
|
+
"Refusing to send without confirmation: pass --yes (stdin is not a terminal)."
|
|
2382
|
+
);
|
|
2383
|
+
const rl = lineReader(io.stdin, io.stderr);
|
|
2384
|
+
try {
|
|
2385
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
2386
|
+
return answer === "y" || answer === "yes";
|
|
2387
|
+
} finally {
|
|
2388
|
+
rl.close();
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
var describe = (b) => `status ${b.status}${b.sent_count === null ? "" : ` \xB7 sent ${b.sent_count}`}${b.failure_reason ? ` \xB7 ${b.failure_reason}` : ""}`;
|
|
2392
|
+
function waitMinutes(values) {
|
|
2393
|
+
const raw = values["wait-timeout"];
|
|
2394
|
+
if (raw === void 0) return DEFAULT_WAIT_MINUTES;
|
|
2395
|
+
const minutes = Number(raw);
|
|
2396
|
+
if (!(minutes > 0 && minutes <= MAX_WAIT_MINUTES))
|
|
2397
|
+
throw new UsageError(
|
|
2398
|
+
`--wait-timeout takes minutes, more than 0 and at most ${MAX_WAIT_MINUTES}.`
|
|
2399
|
+
);
|
|
2400
|
+
return minutes;
|
|
2401
|
+
}
|
|
2402
|
+
async function waitFor(http, id, say, clock, minutes) {
|
|
2403
|
+
const deadline = clock.now() + minutes * 6e4;
|
|
2404
|
+
let last = "";
|
|
2405
|
+
for (; ; ) {
|
|
2406
|
+
const { body } = await http.get(route`/broadcasts/${id}`);
|
|
2407
|
+
const line = describe(body);
|
|
2408
|
+
if (line !== last) say(` ${line}`);
|
|
2409
|
+
last = line;
|
|
2410
|
+
const ended = TERMINAL_STATUSES.has(body.status);
|
|
2411
|
+
if (ended || clock.now() >= deadline) return { broadcast: body, ended };
|
|
2412
|
+
await clock.sleep(WAIT_POLL_MS);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
async function broadcastsSend(io, http, values, clock) {
|
|
2416
|
+
const from = required(values, "from");
|
|
2417
|
+
const subject = required(values, "subject");
|
|
2418
|
+
const body = readBody(io, values);
|
|
2419
|
+
const minutes = waitMinutes(values);
|
|
2420
|
+
const test = splitAddresses(values.test);
|
|
2421
|
+
const segmentRef = values.segment;
|
|
2422
|
+
if (test.length === 0 && !segmentRef)
|
|
2423
|
+
throw new UsageError("--segment is required (or --test <email> for a test send).");
|
|
2424
|
+
const say = (line) => (values.json ? io.stderr : io.stdout).write(`${line}
|
|
2425
|
+
`);
|
|
2426
|
+
const topic = values.topic ? await resolveNamed(http, "/topics", "topic", values.topic) : null;
|
|
2427
|
+
const named = segmentRef ? await resolveNamed(http, "/segments", "segment", segmentRef) : null;
|
|
2428
|
+
let segment;
|
|
2429
|
+
let question;
|
|
2430
|
+
if (test.length > 0) {
|
|
2431
|
+
segment = await prepareTestSegment(http, test);
|
|
2432
|
+
question = `Send a test to ${test.join(", ")}?`;
|
|
2433
|
+
} else {
|
|
2434
|
+
segment = named;
|
|
2435
|
+
const { body: detail } = await http.get(
|
|
2436
|
+
route`/segments/${segment.id}`
|
|
2437
|
+
);
|
|
2438
|
+
say(
|
|
2439
|
+
`Segment ${segment.name} (${segment.id}) \xB7 ${detail.contact_count} contacts${topic ? ` \xB7 topic ${topic.name}: only its subscribers receive it` : ""}`
|
|
2440
|
+
);
|
|
2441
|
+
question = `Send "${subject}" to segment ${segment.name} (${detail.contact_count} contacts)?`;
|
|
2442
|
+
}
|
|
2443
|
+
if (!await confirm(io, values, question)) {
|
|
2444
|
+
say("Not sent.");
|
|
2445
|
+
return 1;
|
|
2446
|
+
}
|
|
2447
|
+
const prefix = test.length > 0 ? "[TEST] " : "";
|
|
2448
|
+
const created = await http.post(
|
|
2449
|
+
"/broadcasts",
|
|
2450
|
+
{
|
|
2451
|
+
name: `${prefix}${values.name?.trim() || subject}`,
|
|
2452
|
+
from,
|
|
2453
|
+
subject: `${prefix}${subject}`,
|
|
2454
|
+
segment_id: segment.id,
|
|
2455
|
+
...topic ? { topic_id: topic.id } : {},
|
|
2456
|
+
...values["reply-to"]?.length ? { reply_to: values["reply-to"] } : {},
|
|
2457
|
+
...values["preview-text"] ? { preview_text: values["preview-text"] } : {},
|
|
2458
|
+
...values["no-dormant-check"] ? { dormant_check: false } : {},
|
|
2459
|
+
...values["include-dormant"] ? { include_dormant: true } : {},
|
|
2460
|
+
...body,
|
|
2461
|
+
send: true
|
|
2462
|
+
},
|
|
2463
|
+
{ idempotent: false }
|
|
2464
|
+
);
|
|
2465
|
+
const id = created.body.id;
|
|
2466
|
+
say(`Broadcast ${id} queued${test.length > 0 ? ` (test to ${test.join(", ")})` : ""}.`);
|
|
2467
|
+
let result;
|
|
2468
|
+
let gaveUp = false;
|
|
2469
|
+
if (values.wait) {
|
|
2470
|
+
const waited = await waitFor(http, id, say, clock, minutes);
|
|
2471
|
+
result = waited.broadcast;
|
|
2472
|
+
gaveUp = !waited.ended;
|
|
2473
|
+
if (gaveUp)
|
|
2474
|
+
say(
|
|
2475
|
+
`Still ${result.status} after ${minutes} minutes; follow it with: billionsend broadcasts get ${id}`
|
|
2476
|
+
);
|
|
2477
|
+
} else {
|
|
2478
|
+
result = (await http.get(route`/broadcasts/${id}`)).body;
|
|
2479
|
+
say(` ${describe(result)}`);
|
|
2480
|
+
}
|
|
2481
|
+
if (values.json) io.stdout.write(`${JSON.stringify(result)}
|
|
2482
|
+
`);
|
|
2483
|
+
return result.status === "failed" || gaveUp ? 1 : 0;
|
|
2484
|
+
}
|
|
2485
|
+
async function broadcastsGet(io, http, values, id) {
|
|
2486
|
+
if (!id) throw new UsageError("Usage: billionsend broadcasts get <id>");
|
|
2487
|
+
const { body } = await http.get(route`/broadcasts/${id}`);
|
|
2488
|
+
if (values.json) io.stdout.write(`${JSON.stringify(body)}
|
|
2489
|
+
`);
|
|
2490
|
+
else io.stdout.write(`${body.id}${body.name ? ` \xB7 ${body.name}` : ""} \xB7 ${describe(body)}
|
|
2491
|
+
`);
|
|
2492
|
+
return 0;
|
|
2493
|
+
}
|
|
2494
|
+
async function emailsSend(io, http, values) {
|
|
2495
|
+
const from = required(values, "from");
|
|
2496
|
+
const subject = required(values, "subject");
|
|
2497
|
+
const to = splitAddresses(values.to);
|
|
2498
|
+
if (to.length === 0) throw new UsageError("--to is required.");
|
|
2499
|
+
const body = readBody(io, values);
|
|
2500
|
+
if (!await confirm(io, values, `Send "${subject}" to ${to.join(", ")}?`)) {
|
|
2501
|
+
io.stderr.write("Not sent.\n");
|
|
2502
|
+
return 1;
|
|
2503
|
+
}
|
|
2504
|
+
const key = values["idempotency-key"];
|
|
2505
|
+
const { body: sent } = await http.post(
|
|
2506
|
+
"/emails",
|
|
2507
|
+
{
|
|
2508
|
+
from,
|
|
2509
|
+
to,
|
|
2510
|
+
subject,
|
|
2511
|
+
...values["reply-to"]?.length ? { reply_to: values["reply-to"] } : {},
|
|
2512
|
+
...body
|
|
2513
|
+
},
|
|
2514
|
+
// With a key the API answers a repeat with the first email, so a retry is safe.
|
|
2515
|
+
key ? { headers: { "Idempotency-Key": key }, idempotent: true } : { idempotent: false }
|
|
2516
|
+
);
|
|
2517
|
+
if (values.json) io.stdout.write(`${JSON.stringify(sent)}
|
|
2518
|
+
`);
|
|
2519
|
+
else io.stdout.write(`Email ${sent.id} accepted.
|
|
2520
|
+
`);
|
|
2521
|
+
return 0;
|
|
2522
|
+
}
|
|
2523
|
+
async function broadcastsList(io, http, values) {
|
|
2524
|
+
const limit = values.limit === void 0 ? 20 : Number(values.limit);
|
|
2525
|
+
if (!(Number.isInteger(limit) && limit >= 1 && limit <= 100))
|
|
2526
|
+
throw new UsageError("--limit takes a whole number from 1 to 100.");
|
|
2527
|
+
const path2 = "/broadcasts";
|
|
2528
|
+
const rows = [];
|
|
2529
|
+
const guard = cursorGuard(path2);
|
|
2530
|
+
let after;
|
|
2531
|
+
let more = false;
|
|
2532
|
+
for (; ; ) {
|
|
2533
|
+
const { body } = await http.get(path2, { query: { limit, after } });
|
|
2534
|
+
const page = pageItems(path2, body, after);
|
|
2535
|
+
guard(page, after);
|
|
2536
|
+
rows.push(...page);
|
|
2537
|
+
more = body.has_more === true;
|
|
2538
|
+
if (!more || !values.all) break;
|
|
2539
|
+
after = nextCursor(path2, page, after);
|
|
2540
|
+
}
|
|
2541
|
+
if (values.json) io.stdout.write(`${JSON.stringify(rows)}
|
|
2542
|
+
`);
|
|
2543
|
+
else
|
|
2544
|
+
for (const b of rows)
|
|
2545
|
+
io.stdout.write(
|
|
2546
|
+
`${b.id} \xB7 ${b.created_at.slice(0, 16).replace("T", " ")} \xB7 ${describe(b)}${b.name ? ` \xB7 ${b.name}` : ""}
|
|
2547
|
+
`
|
|
2548
|
+
);
|
|
2549
|
+
if (more) io.stderr.write("More broadcasts remain; pass --all for every page.\n");
|
|
2550
|
+
return 0;
|
|
2551
|
+
}
|
|
2552
|
+
async function segmentsCreate(io, http, values) {
|
|
2553
|
+
const name = values.name?.trim();
|
|
2554
|
+
if (!name) throw new UsageError("--name is required.");
|
|
2555
|
+
const { body } = await http.post("/segments", { name }, { idempotent: false });
|
|
2556
|
+
if (values.json) io.stdout.write(`${JSON.stringify(body)}
|
|
2557
|
+
`);
|
|
2558
|
+
else io.stdout.write(`Segment ${body.id} created (${body.name}).
|
|
2559
|
+
`);
|
|
2560
|
+
return 0;
|
|
2561
|
+
}
|
|
2562
|
+
async function segmentsGet(io, http, values, ref) {
|
|
2563
|
+
if (!ref) throw new UsageError("Usage: billionsend segments get <name|id>");
|
|
2564
|
+
const segment = await resolveNamed(http, "/segments", "segment", ref);
|
|
2565
|
+
const { body } = await http.get(route`/segments/${segment.id}`);
|
|
2566
|
+
if (values.json) io.stdout.write(`${JSON.stringify(body)}
|
|
2567
|
+
`);
|
|
2568
|
+
else io.stdout.write(`${body.name} \xB7 ${body.id} \xB7 ${body.contact_count} contacts
|
|
2569
|
+
`);
|
|
2570
|
+
return 0;
|
|
2571
|
+
}
|
|
2572
|
+
async function contactsImport(io, http, values, clock) {
|
|
2573
|
+
const path2 = values.file;
|
|
2574
|
+
if (!path2) throw new UsageError("--file is required.");
|
|
2575
|
+
const onConflict = values["on-conflict"];
|
|
2576
|
+
if (onConflict !== void 0 && onConflict !== "upsert" && onConflict !== "skip")
|
|
2577
|
+
throw new UsageError("--on-conflict takes upsert or skip.");
|
|
2578
|
+
const minutes = waitMinutes(values);
|
|
2579
|
+
const full = resolve(io.cwd, path2);
|
|
2580
|
+
let csv;
|
|
2581
|
+
try {
|
|
2582
|
+
if (statSync(full).size > IMPORT_MAX_BYTES)
|
|
2583
|
+
throw new UsageError(`${path2} is larger than 20 MiB, the most one import takes.`);
|
|
2584
|
+
csv = readFileSync(full);
|
|
2585
|
+
} catch (error) {
|
|
2586
|
+
if (error instanceof UsageError) throw error;
|
|
2587
|
+
throw new UsageError(`Cannot read --file ${path2}`);
|
|
2588
|
+
}
|
|
2589
|
+
const segment = values.segment ? await resolveNamed(http, "/segments", "segment", values.segment) : null;
|
|
2590
|
+
const form = new FormData();
|
|
2591
|
+
form.set("file", new Blob([csv], { type: "text/csv" }), basename(full));
|
|
2592
|
+
if (segment) form.set("segments", JSON.stringify([{ id: segment.id }]));
|
|
2593
|
+
if (onConflict) form.set("on_conflict", onConflict);
|
|
2594
|
+
const say = (line) => (values.json ? io.stderr : io.stdout).write(`${line}
|
|
2595
|
+
`);
|
|
2596
|
+
const { body: started } = await http.post("/contacts/imports", form, {
|
|
2597
|
+
idempotent: false
|
|
2598
|
+
});
|
|
2599
|
+
say(`Import ${started.id} started${segment ? ` into segment ${segment.name}` : ""}.`);
|
|
2600
|
+
const deadline = clock.now() + minutes * 6e4;
|
|
2601
|
+
let job;
|
|
2602
|
+
for (; ; ) {
|
|
2603
|
+
job = (await http.get(route`/contacts/imports/${started.id}`)).body;
|
|
2604
|
+
if (job.status === "completed" || job.status === "failed" || clock.now() >= deadline) break;
|
|
2605
|
+
await clock.sleep(IMPORT_POLL_MS);
|
|
2606
|
+
}
|
|
2607
|
+
const { total, created, updated, skipped, failed } = job.counts;
|
|
2608
|
+
say(
|
|
2609
|
+
` status ${job.status} \xB7 ${total} rows \xB7 ${created} created \xB7 ${updated} updated \xB7 ${skipped} skipped \xB7 ${failed} failed`
|
|
2610
|
+
);
|
|
2611
|
+
if (values.json) io.stdout.write(`${JSON.stringify(job)}
|
|
2612
|
+
`);
|
|
2613
|
+
if (job.status === "completed") return failed > 0 ? 3 : 0;
|
|
2614
|
+
if (job.status !== "failed") say(`Still ${job.status} after ${minutes} minutes.`);
|
|
2615
|
+
return 1;
|
|
2616
|
+
}
|
|
2617
|
+
var csvField = (value) => /[",\r\n]/.test(value) ? `"${value.replaceAll('"', '""')}"` : value;
|
|
2618
|
+
function recipientsCsv(rows) {
|
|
2619
|
+
const lines = ["email,contact_id,email_id,count,clicked_links,bounce_type"];
|
|
2620
|
+
for (const r of rows) {
|
|
2621
|
+
lines.push(
|
|
2622
|
+
[
|
|
2623
|
+
r.email,
|
|
2624
|
+
r.contact_id ?? "",
|
|
2625
|
+
r.id,
|
|
2626
|
+
r.count === void 0 ? "" : String(r.count),
|
|
2627
|
+
(r.clicked_links ?? []).map((l) => `${l.url} (${l.clicks})`).join("; "),
|
|
2628
|
+
r.bounce_type ?? ""
|
|
2629
|
+
].map(csvField).join(",")
|
|
2630
|
+
);
|
|
2631
|
+
}
|
|
2632
|
+
return `${lines.join("\n")}
|
|
2633
|
+
`;
|
|
2634
|
+
}
|
|
2635
|
+
async function broadcastsRecipients(io, http, values, id) {
|
|
2636
|
+
if (!id) throw new UsageError("Usage: billionsend broadcasts recipients <id> --type <type>");
|
|
2637
|
+
const type = values.type;
|
|
2638
|
+
if (!type || !RECIPIENT_TYPES.includes(type))
|
|
2639
|
+
throw new UsageError(`--type is one of: ${RECIPIENT_TYPES.join(", ")}`);
|
|
2640
|
+
const format = values.json ? "json" : values.format ?? "csv";
|
|
2641
|
+
if (format !== "csv" && format !== "json") throw new UsageError("--format takes csv or json.");
|
|
2642
|
+
const path2 = route`/broadcasts/${id}/recipients`;
|
|
2643
|
+
const rows = [];
|
|
2644
|
+
const guard = cursorGuard(path2);
|
|
2645
|
+
let after;
|
|
2646
|
+
let more = false;
|
|
2647
|
+
for (; ; ) {
|
|
2648
|
+
const { body } = await http.get(path2, {
|
|
2649
|
+
query: { type, limit: 100, after }
|
|
2650
|
+
});
|
|
2651
|
+
const page = pageItems(path2, body, after);
|
|
2652
|
+
guard(page, after);
|
|
2653
|
+
rows.push(...page);
|
|
2654
|
+
more = body.has_more === true;
|
|
2655
|
+
if (!more || !values.all) break;
|
|
2656
|
+
after = nextCursor(path2, page, after);
|
|
2657
|
+
}
|
|
2658
|
+
io.stdout.write(format === "json" ? `${JSON.stringify(rows)}
|
|
2659
|
+
` : recipientsCsv(rows));
|
|
2660
|
+
io.stderr.write(
|
|
2661
|
+
`${rows.length} ${type} recipient${rows.length === 1 ? "" : "s"}${more ? "; more remain, pass --all for every page" : ""}.
|
|
2662
|
+
`
|
|
2663
|
+
);
|
|
2664
|
+
return 0;
|
|
2665
|
+
}
|
|
2666
|
+
async function readKey(io, values) {
|
|
2667
|
+
if (values["key-stdin"]) {
|
|
2668
|
+
const rl = lineReader(io.stdin, io.stderr);
|
|
2669
|
+
try {
|
|
2670
|
+
const line = (await rl.question("")).trim();
|
|
2671
|
+
if (line === "")
|
|
2672
|
+
throw new UsageError("No BillionSend API key arrived on stdin (--key-stdin).");
|
|
2673
|
+
return line;
|
|
2674
|
+
} finally {
|
|
2675
|
+
rl.close();
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
const key = io.env.BILLIONSEND_API_KEY?.trim();
|
|
2679
|
+
if (!key) throw new UsageError("Set BILLIONSEND_API_KEY or pass --key-stdin.");
|
|
2680
|
+
return key;
|
|
2681
|
+
}
|
|
2682
|
+
var COMMANDS = {
|
|
2683
|
+
"broadcasts send": ({ io, http, values, clock }) => broadcastsSend(io, http, values, clock),
|
|
2684
|
+
"broadcasts get": ({ io, http, values, id }) => broadcastsGet(io, http, values, id),
|
|
2685
|
+
"broadcasts list": ({ io, http, values }) => broadcastsList(io, http, values),
|
|
2686
|
+
"broadcasts recipients": ({ io, http, values, id }) => broadcastsRecipients(io, http, values, id),
|
|
2687
|
+
"emails send": ({ io, http, values }) => emailsSend(io, http, values),
|
|
2688
|
+
"segments create": ({ io, http, values }) => segmentsCreate(io, http, values),
|
|
2689
|
+
"segments get": ({ io, http, values, id }) => segmentsGet(io, http, values, id),
|
|
2690
|
+
"contacts import": ({ io, http, values, clock }) => contactsImport(io, http, values, clock)
|
|
2691
|
+
};
|
|
2692
|
+
var TAKES_ID = /* @__PURE__ */ new Set(["broadcasts get", "broadcasts recipients", "segments get"]);
|
|
2693
|
+
async function runSend(argv, ioIn = {}, clock = SYSTEM_CLOCK) {
|
|
2694
|
+
const io = {
|
|
2695
|
+
stdout: ioIn.stdout ?? process.stdout,
|
|
2696
|
+
stderr: ioIn.stderr ?? process.stderr,
|
|
2697
|
+
env: ioIn.env ?? process.env,
|
|
2698
|
+
stdin: ioIn.stdin ?? process.stdin,
|
|
2699
|
+
fetch: ioIn.fetch ?? globalThis.fetch,
|
|
2700
|
+
cwd: ioIn.cwd ?? process.cwd()
|
|
2701
|
+
};
|
|
2702
|
+
const log = createLogger({ level: "info", stream: io.stderr });
|
|
2703
|
+
try {
|
|
2704
|
+
const { values, positionals } = parseArgs({
|
|
2705
|
+
args: [...argv],
|
|
2706
|
+
options: OPTIONS,
|
|
2707
|
+
allowPositionals: true,
|
|
2708
|
+
strict: true
|
|
2709
|
+
});
|
|
2710
|
+
const [command, sub, id, ...rest] = positionals;
|
|
2711
|
+
if (values.help || sub === void 0) {
|
|
2712
|
+
io.stdout.write(sendHelpText());
|
|
2713
|
+
return values.help ? 0 : 1;
|
|
2714
|
+
}
|
|
2715
|
+
const name = `${command} ${sub}`;
|
|
2716
|
+
const run = COMMANDS[name];
|
|
2717
|
+
if (!run) throw new UsageError(`Unknown command: ${name}`);
|
|
2718
|
+
if (rest.length > 0 || id !== void 0 && !TAKES_ID.has(name))
|
|
2719
|
+
throw new UsageError(`Unexpected argument: ${[id, ...rest].filter(Boolean).join(" ")}`);
|
|
2720
|
+
const token = await readKey(io, values);
|
|
2721
|
+
const baseUrl = stripTrailingSlashes(
|
|
2722
|
+
values["to-url"] ?? io.env.BILLIONSEND_BASE_URL ?? CLOUD_API_URL
|
|
2723
|
+
);
|
|
2724
|
+
const http = createHttp({
|
|
2725
|
+
baseUrl,
|
|
2726
|
+
token,
|
|
2727
|
+
userAgent: USER_AGENT,
|
|
2728
|
+
rps: SEND_RPS,
|
|
2729
|
+
log,
|
|
2730
|
+
name: "BillionSend",
|
|
2731
|
+
fetch: io.fetch
|
|
2732
|
+
});
|
|
2733
|
+
return await run({ io, http, values, id, clock });
|
|
2734
|
+
} catch (error) {
|
|
2735
|
+
if (error instanceof UsageError || error instanceof AuthError || error instanceof ApiError) {
|
|
2736
|
+
log.error(error.message);
|
|
2737
|
+
return 1;
|
|
2738
|
+
}
|
|
2739
|
+
if (error instanceof TypeError && "code" in error && String(error.code).startsWith("ERR_PARSE_ARGS")) {
|
|
2740
|
+
log.error(error.message);
|
|
2741
|
+
return 1;
|
|
2742
|
+
}
|
|
2743
|
+
throw error;
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2148
2747
|
// src/config.ts
|
|
2149
2748
|
var PLAN_OPTIONS = [
|
|
2150
2749
|
"only",
|
|
@@ -2167,7 +2766,7 @@ var RPS_HEADROOM = 2;
|
|
|
2167
2766
|
var TARGET_KEY_ENV = "BILLIONSEND_API_KEY";
|
|
2168
2767
|
var TARGET_URL_ENV = "BILLIONSEND_BASE_URL";
|
|
2169
2768
|
var sourceKeyEnv = (provider) => `${provider.toUpperCase()}_API_KEY`;
|
|
2170
|
-
var
|
|
2769
|
+
var OPTIONS2 = {
|
|
2171
2770
|
from: { type: "string" },
|
|
2172
2771
|
"from-key": { type: "string" },
|
|
2173
2772
|
"from-key-stdin": { type: "boolean" },
|
|
@@ -2245,9 +2844,9 @@ function parseConfig(argv, env = process.env, stdinIsTTY = process.stdin.isTTY =
|
|
|
2245
2844
|
let values;
|
|
2246
2845
|
let positionals;
|
|
2247
2846
|
try {
|
|
2248
|
-
({ values, positionals } =
|
|
2847
|
+
({ values, positionals } = parseArgs2({
|
|
2249
2848
|
args: argv,
|
|
2250
|
-
options:
|
|
2849
|
+
options: OPTIONS2,
|
|
2251
2850
|
strict: true,
|
|
2252
2851
|
allowPositionals: true
|
|
2253
2852
|
}));
|
|
@@ -2414,6 +3013,7 @@ Usage
|
|
|
2414
3013
|
billionsend migrate apply [plan.json] [--yes] apply a saved plan (with the options it was made with), or plan and apply in one go
|
|
2415
3014
|
billionsend migrate status what the last run created and what is left
|
|
2416
3015
|
billionsend migrate rollback [--yes] delete only what this tool created
|
|
3016
|
+
billionsend broadcasts send | broadcasts get | emails send send from the command line (see Sending below)
|
|
2417
3017
|
billionsend --help | --version
|
|
2418
3018
|
|
|
2419
3019
|
Options
|
|
@@ -2448,6 +3048,7 @@ Options
|
|
|
2448
3048
|
Resources
|
|
2449
3049
|
${RESOURCES.join(", ")}
|
|
2450
3050
|
|
|
3051
|
+
${sendHelpText()}
|
|
2451
3052
|
Environment
|
|
2452
3053
|
RESEND_API_KEY source API key (full access; the tool only reads from Resend)
|
|
2453
3054
|
${TARGET_KEY_ENV} BillionSend API key (full access)
|
|
@@ -2518,7 +3119,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2518
3119
|
const { body } = await response;
|
|
2519
3120
|
return { id: body.id, records: body.records };
|
|
2520
3121
|
};
|
|
2521
|
-
async function
|
|
3122
|
+
async function listAll2(path2, { paged = true } = {}) {
|
|
2522
3123
|
const rows = [];
|
|
2523
3124
|
let after;
|
|
2524
3125
|
const guard = cursorGuard(path2);
|
|
@@ -2576,13 +3177,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2576
3177
|
broadcasts,
|
|
2577
3178
|
firstContact
|
|
2578
3179
|
] = await Promise.all([
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
3180
|
+
listAll2("/domains"),
|
|
3181
|
+
listAll2("/contact-properties"),
|
|
3182
|
+
listAll2("/topics", { paged: false }),
|
|
3183
|
+
listAll2("/segments"),
|
|
3184
|
+
listAll2("/webhooks"),
|
|
3185
|
+
listAll2("/templates"),
|
|
3186
|
+
listAll2("/broadcasts"),
|
|
2586
3187
|
api.get("/contacts", { query: { limit: 1 } })
|
|
2587
3188
|
]);
|
|
2588
3189
|
const domains = [];
|
|
@@ -2889,7 +3490,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2889
3490
|
return { added, errors };
|
|
2890
3491
|
},
|
|
2891
3492
|
/** Every suppression id on the target; apply diffs against it so rollback deletes only rows it added. */
|
|
2892
|
-
listSuppressionIds: async () => (await
|
|
3493
|
+
listSuppressionIds: async () => (await listAll2("/suppressions")).map((s) => s.id),
|
|
2893
3494
|
addSuppressions: (emails, origin) => suppressionsBatch("/suppressions/batch/add", "emails", emails, { origin }),
|
|
2894
3495
|
removeSuppressions: (ids) => suppressionsBatch("/suppressions/batch/remove", "ids", ids)
|
|
2895
3496
|
};
|
|
@@ -2902,12 +3503,12 @@ import {
|
|
|
2902
3503
|
existsSync,
|
|
2903
3504
|
lstatSync,
|
|
2904
3505
|
mkdirSync,
|
|
2905
|
-
readFileSync,
|
|
3506
|
+
readFileSync as readFileSync2,
|
|
2906
3507
|
renameSync,
|
|
2907
3508
|
unlinkSync,
|
|
2908
3509
|
writeFileSync
|
|
2909
3510
|
} from "node:fs";
|
|
2910
|
-
import { basename, dirname, join } from "node:path";
|
|
3511
|
+
import { basename as basename2, dirname, join } from "node:path";
|
|
2911
3512
|
var STATE_DIR = ".billionsend";
|
|
2912
3513
|
function migratePaths(cwd = process.cwd()) {
|
|
2913
3514
|
const dir = join(cwd, STATE_DIR);
|
|
@@ -2921,7 +3522,7 @@ function migratePaths(cwd = process.cwd()) {
|
|
|
2921
3522
|
function writePrivate(path2, content) {
|
|
2922
3523
|
const dir = dirname(path2);
|
|
2923
3524
|
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2924
|
-
if (
|
|
3525
|
+
if (basename2(dir) === STATE_DIR && lstatSync(dir).isSymbolicLink()) {
|
|
2925
3526
|
throw new Error(`${dir} is a symbolic link; remove it and run again.`);
|
|
2926
3527
|
}
|
|
2927
3528
|
const tmp = `${path2}.tmp`;
|
|
@@ -2942,7 +3543,7 @@ function writePrivateJson(path2, value) {
|
|
|
2942
3543
|
}
|
|
2943
3544
|
function readJson(path2) {
|
|
2944
3545
|
if (!existsSync(path2)) return null;
|
|
2945
|
-
const content =
|
|
3546
|
+
const content = readFileSync2(path2, "utf8");
|
|
2946
3547
|
try {
|
|
2947
3548
|
return JSON.parse(content);
|
|
2948
3549
|
} catch {
|
|
@@ -2952,7 +3553,7 @@ function readJson(path2) {
|
|
|
2952
3553
|
function ensureGitignored(cwd = process.cwd()) {
|
|
2953
3554
|
const path2 = join(cwd, ".gitignore");
|
|
2954
3555
|
if (!existsSync(path2)) return false;
|
|
2955
|
-
const content =
|
|
3556
|
+
const content = readFileSync2(path2, "utf8");
|
|
2956
3557
|
const listed = content.split(/\r?\n/).some((line) => line.trim().replace(/^\/|\/$/g, "") === STATE_DIR);
|
|
2957
3558
|
if (listed) return false;
|
|
2958
3559
|
const separator = content === "" || content.endsWith("\n") ? "" : "\n";
|
|
@@ -4470,7 +5071,7 @@ async function apply(ctx) {
|
|
|
4470
5071
|
if (config.planFile === null) return migrate(ctx);
|
|
4471
5072
|
let text;
|
|
4472
5073
|
try {
|
|
4473
|
-
text =
|
|
5074
|
+
text = readFileSync3(config.planFile, "utf8");
|
|
4474
5075
|
} catch (error) {
|
|
4475
5076
|
if (error.code !== "ENOENT") throw error;
|
|
4476
5077
|
throw new Error(
|
|
@@ -4748,30 +5349,6 @@ ${pluralize(state.failures.length, "failure")} in the last run
|
|
|
4748
5349
|
return 0;
|
|
4749
5350
|
}
|
|
4750
5351
|
|
|
4751
|
-
// src/log.ts
|
|
4752
|
-
var RANK = { error: 0, warn: 1, info: 2, debug: 3 };
|
|
4753
|
-
var TOKEN_RE = /\b(?:re|bs|whsec)_[A-Za-z0-9+/=_-]+/g;
|
|
4754
|
-
var AUTHORIZATION_RE = /(authorization["']?\s*[:=]\s*["']?)(?:bearer\s+)?[^\s"',}]+/gi;
|
|
4755
|
-
function redact(text) {
|
|
4756
|
-
return text.replace(AUTHORIZATION_RE, "$1***").replace(TOKEN_RE, "***");
|
|
4757
|
-
}
|
|
4758
|
-
function createLogger({
|
|
4759
|
-
level = "info",
|
|
4760
|
-
stream = process.stderr
|
|
4761
|
-
} = {}) {
|
|
4762
|
-
const write = (at, prefix, message) => {
|
|
4763
|
-
if (RANK[at] <= RANK[level]) stream.write(`${prefix}${stripControl(redact(message))}
|
|
4764
|
-
`);
|
|
4765
|
-
};
|
|
4766
|
-
return {
|
|
4767
|
-
level,
|
|
4768
|
-
error: (message) => write("error", `${err("error:")} `, message),
|
|
4769
|
-
warn: (message) => write("warn", `${warn("warning:")} `, message),
|
|
4770
|
-
info: (message) => write("info", "", message),
|
|
4771
|
-
debug: (message) => write("debug", "", message)
|
|
4772
|
-
};
|
|
4773
|
-
}
|
|
4774
|
-
|
|
4775
5352
|
// src/context.ts
|
|
4776
5353
|
function createContext(config, io = {}) {
|
|
4777
5354
|
const stdout = io.stdout ?? process.stdout;
|
|
@@ -4794,8 +5371,9 @@ function createContext(config, io = {}) {
|
|
|
4794
5371
|
}
|
|
4795
5372
|
|
|
4796
5373
|
// src/index.ts
|
|
4797
|
-
var
|
|
5374
|
+
var COMMANDS2 = { migrate, plan, apply, status, rollback };
|
|
4798
5375
|
async function main(argv = process.argv.slice(2), io = {}) {
|
|
5376
|
+
if (SEND_COMMANDS.includes(argv[0] ?? "")) return runSend(argv, io);
|
|
4799
5377
|
const stdout = io.stdout ?? process.stdout;
|
|
4800
5378
|
const stderr = io.stderr ?? process.stderr;
|
|
4801
5379
|
let config;
|
|
@@ -4819,7 +5397,7 @@ async function main(argv = process.argv.slice(2), io = {}) {
|
|
|
4819
5397
|
const ctx = createContext(config, io);
|
|
4820
5398
|
for (const warning of config.warnings) ctx.log.warn(warning);
|
|
4821
5399
|
try {
|
|
4822
|
-
return await
|
|
5400
|
+
return await COMMANDS2[config.command](ctx);
|
|
4823
5401
|
} catch (error) {
|
|
4824
5402
|
ctx.progress.clear();
|
|
4825
5403
|
ctx.log.error(error instanceof Error ? error.message : String(error));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@billionsend/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Migrate an email account to BillionSend: contacts, segments, topics, templates, webhooks, domains and suppressions — read from the source provider, written to your BillionSend account, re-run safe",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|