@billionsend/cli 0.3.2 → 0.4.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 +22 -0
- package/dist/index.js +433 -63
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,6 +27,28 @@ Node 18 or newer; no dependencies.
|
|
|
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 get <id>
|
|
47
|
+
billionsend emails send --from "Leo <leo@mail.example.com>" --to you@example.com --subject "Hi" --text-file hi.txt --yes
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`--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; a small broadcast reads as sent within about five minutes of its last email. `billionsend broadcasts --help` lists every option.
|
|
51
|
+
|
|
30
52
|
## Environment
|
|
31
53
|
|
|
32
54
|
| Variable | Meaning |
|
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) {
|
|
@@ -541,7 +541,7 @@ function createResendSource(http, log) {
|
|
|
541
541
|
requests += 1;
|
|
542
542
|
return http.get(route2, options);
|
|
543
543
|
};
|
|
544
|
-
async function
|
|
544
|
+
async function listAll2(route2, query = {}, label, onProgress) {
|
|
545
545
|
const items = [];
|
|
546
546
|
let after;
|
|
547
547
|
const guard = cursorGuard(route2);
|
|
@@ -561,7 +561,7 @@ function createResendSource(http, log) {
|
|
|
561
561
|
return items;
|
|
562
562
|
}
|
|
563
563
|
async function listWithDetails(route2, label, onProgress, detail, keep = () => true) {
|
|
564
|
-
const list = (await
|
|
564
|
+
const list = (await listAll2(route2)).filter(keep);
|
|
565
565
|
const out = [];
|
|
566
566
|
for (const item of list) {
|
|
567
567
|
out.push(await detail(item));
|
|
@@ -571,7 +571,7 @@ function createResendSource(http, log) {
|
|
|
571
571
|
return out;
|
|
572
572
|
}
|
|
573
573
|
async function readSegments(scope, onProgress, membersOf) {
|
|
574
|
-
const list = scope ?? await
|
|
574
|
+
const list = scope ?? await listAll2("/segments");
|
|
575
575
|
const out = [];
|
|
576
576
|
for (const item of list) {
|
|
577
577
|
const { body } = await get(path("segments", item.id));
|
|
@@ -599,13 +599,13 @@ function createResendSource(http, log) {
|
|
|
599
599
|
async readShallow({ include, includeSent = false, segments = [], onProgress }) {
|
|
600
600
|
const snapshot = emptySnapshot();
|
|
601
601
|
const needsContacts = include.has("contacts") || include.has("enrichment");
|
|
602
|
-
const scope = segments.length === 0 ? null : selectSegments(await
|
|
602
|
+
const scope = segments.length === 0 ? null : selectSegments(await listAll2("/segments"), segments);
|
|
603
603
|
if (scope !== null) snapshot.segmentScope = scope.map(({ id, name }) => ({ id, name }));
|
|
604
604
|
const memberLists = /* @__PURE__ */ new Map();
|
|
605
605
|
const membersOf = async (id) => {
|
|
606
606
|
const cached = memberLists.get(id);
|
|
607
607
|
if (cached !== void 0) return cached;
|
|
608
|
-
const members = await
|
|
608
|
+
const members = await listAll2(path("segments", id, "contacts"), {});
|
|
609
609
|
memberLists.set(id, members);
|
|
610
610
|
return members;
|
|
611
611
|
};
|
|
@@ -619,7 +619,7 @@ function createResendSource(http, log) {
|
|
|
619
619
|
);
|
|
620
620
|
}
|
|
621
621
|
if (include.has("properties") || include.has("enrichment")) {
|
|
622
|
-
const list = await
|
|
622
|
+
const list = await listAll2(
|
|
623
623
|
"/contact-properties",
|
|
624
624
|
{},
|
|
625
625
|
"Contact properties",
|
|
@@ -632,7 +632,7 @@ function createResendSource(http, log) {
|
|
|
632
632
|
}));
|
|
633
633
|
}
|
|
634
634
|
if (include.has("topics") || include.has("enrichment")) {
|
|
635
|
-
const list = await
|
|
635
|
+
const list = await listAll2("/topics", {}, "Topics", onProgress);
|
|
636
636
|
snapshot.topics = list.map((topic) => ({
|
|
637
637
|
id: topic.id,
|
|
638
638
|
name: topic.name,
|
|
@@ -650,7 +650,7 @@ function createResendSource(http, log) {
|
|
|
650
650
|
}
|
|
651
651
|
if (needsContacts) {
|
|
652
652
|
if (scope === null) {
|
|
653
|
-
const list = await
|
|
653
|
+
const list = await listAll2("/contacts", {}, "Contacts", onProgress);
|
|
654
654
|
snapshot.contacts = list.map(toContact);
|
|
655
655
|
} else {
|
|
656
656
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -700,7 +700,7 @@ function createResendSource(http, log) {
|
|
|
700
700
|
);
|
|
701
701
|
}
|
|
702
702
|
if (include.has("suppressions")) {
|
|
703
|
-
const list = await
|
|
703
|
+
const list = await listAll2(
|
|
704
704
|
"/suppressions",
|
|
705
705
|
{},
|
|
706
706
|
"Suppressions",
|
|
@@ -713,7 +713,7 @@ function createResendSource(http, log) {
|
|
|
713
713
|
}));
|
|
714
714
|
}
|
|
715
715
|
if (include.has("api-keys")) {
|
|
716
|
-
const list = await
|
|
716
|
+
const list = await listAll2("/api-keys", {}, "API keys", onProgress);
|
|
717
717
|
snapshot.apiKeys = list.map((key) => ({ name: key.name, createdAt: key.created_at }));
|
|
718
718
|
}
|
|
719
719
|
return snapshot;
|
|
@@ -737,7 +737,7 @@ function createResendSource(http, log) {
|
|
|
737
737
|
enriched.properties = toProperties(body.properties);
|
|
738
738
|
}
|
|
739
739
|
if (wantTopics) {
|
|
740
|
-
const topics = await
|
|
740
|
+
const topics = await listAll2(path("contacts", contact.id, "topics"));
|
|
741
741
|
enriched.topics = topics.map((topic) => ({
|
|
742
742
|
id: topic.id,
|
|
743
743
|
subscription: topic.subscription ?? "opt_in"
|
|
@@ -857,10 +857,10 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
857
857
|
rl.on("line", (line) => {
|
|
858
858
|
if (!terminal && input.isRaw === true) return;
|
|
859
859
|
if (waiting) {
|
|
860
|
-
const
|
|
860
|
+
const resolve2 = waiting;
|
|
861
861
|
waiting = void 0;
|
|
862
862
|
if (!terminal) endRow();
|
|
863
|
-
|
|
863
|
+
resolve2(line);
|
|
864
864
|
} else {
|
|
865
865
|
queue.push(line);
|
|
866
866
|
}
|
|
@@ -868,10 +868,10 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
868
868
|
rl.on("close", () => {
|
|
869
869
|
ended = true;
|
|
870
870
|
if (waiting) {
|
|
871
|
-
const
|
|
871
|
+
const resolve2 = waiting;
|
|
872
872
|
waiting = void 0;
|
|
873
873
|
endRow();
|
|
874
|
-
|
|
874
|
+
resolve2("");
|
|
875
875
|
}
|
|
876
876
|
});
|
|
877
877
|
rl.on("SIGINT", () => {
|
|
@@ -894,8 +894,8 @@ function lineReader(input = process.stdin, output = process.stdout) {
|
|
|
894
894
|
endRow();
|
|
895
895
|
return Promise.resolve(line);
|
|
896
896
|
}
|
|
897
|
-
return new Promise((
|
|
898
|
-
waiting =
|
|
897
|
+
return new Promise((resolve2) => {
|
|
898
|
+
waiting = resolve2;
|
|
899
899
|
});
|
|
900
900
|
},
|
|
901
901
|
take() {
|
|
@@ -957,7 +957,7 @@ function readKeys(onKey, erase, stdout = process.stdout) {
|
|
|
957
957
|
const wasRaw = stdin.isRaw === true;
|
|
958
958
|
stdin.setRawMode(true);
|
|
959
959
|
stdin.resume();
|
|
960
|
-
return new Promise((
|
|
960
|
+
return new Promise((resolve2) => {
|
|
961
961
|
const done = (value) => {
|
|
962
962
|
stdin.removeListener("keypress", listener);
|
|
963
963
|
process.removeListener("SIGINT", onSigint);
|
|
@@ -970,7 +970,7 @@ function readKeys(onKey, erase, stdout = process.stdout) {
|
|
|
970
970
|
stdout.write("\n");
|
|
971
971
|
process.exit(130);
|
|
972
972
|
}
|
|
973
|
-
|
|
973
|
+
resolve2(value);
|
|
974
974
|
};
|
|
975
975
|
const onSigint = () => done(void 0);
|
|
976
976
|
process.once("SIGINT", onSigint);
|
|
@@ -2119,10 +2119,10 @@ function describePlanDiff(saved, current) {
|
|
|
2119
2119
|
}
|
|
2120
2120
|
|
|
2121
2121
|
// src/config.ts
|
|
2122
|
-
import { parseArgs } from "node:util";
|
|
2122
|
+
import { parseArgs as parseArgs2 } from "node:util";
|
|
2123
2123
|
|
|
2124
2124
|
// src/meta.ts
|
|
2125
|
-
var VERSION = true ? "0.
|
|
2125
|
+
var VERSION = true ? "0.4.0" : "0.0.0-dev";
|
|
2126
2126
|
var REPO_URL = "https://github.com/billionsend/billionsend-cli";
|
|
2127
2127
|
var USER_AGENT = `billionsend-cli/${VERSION} (+${REPO_URL})`;
|
|
2128
2128
|
var CLOUD_API_URL = "https://api.billionsend.com";
|
|
@@ -2145,6 +2145,397 @@ var RESOURCES = [
|
|
|
2145
2145
|
"api-keys"
|
|
2146
2146
|
];
|
|
2147
2147
|
|
|
2148
|
+
// src/send.ts
|
|
2149
|
+
import { readFileSync } from "node:fs";
|
|
2150
|
+
import { resolve } from "node:path";
|
|
2151
|
+
import { parseArgs } from "node:util";
|
|
2152
|
+
|
|
2153
|
+
// src/log.ts
|
|
2154
|
+
var RANK = { error: 0, warn: 1, info: 2, debug: 3 };
|
|
2155
|
+
var TOKEN_RE = /\b(?:re|bs|whsec)_[A-Za-z0-9+/=_-]+/g;
|
|
2156
|
+
var AUTHORIZATION_RE = /(authorization["']?\s*[:=]\s*["']?)(?:bearer\s+)?[^\s"',}]+/gi;
|
|
2157
|
+
function redact(text) {
|
|
2158
|
+
return text.replace(AUTHORIZATION_RE, "$1***").replace(TOKEN_RE, "***");
|
|
2159
|
+
}
|
|
2160
|
+
function createLogger({
|
|
2161
|
+
level = "info",
|
|
2162
|
+
stream = process.stderr
|
|
2163
|
+
} = {}) {
|
|
2164
|
+
const write = (at, prefix, message) => {
|
|
2165
|
+
if (RANK[at] <= RANK[level]) stream.write(`${prefix}${stripControl(redact(message))}
|
|
2166
|
+
`);
|
|
2167
|
+
};
|
|
2168
|
+
return {
|
|
2169
|
+
level,
|
|
2170
|
+
error: (message) => write("error", `${err("error:")} `, message),
|
|
2171
|
+
warn: (message) => write("warn", `${warn("warning:")} `, message),
|
|
2172
|
+
info: (message) => write("info", "", message),
|
|
2173
|
+
debug: (message) => write("debug", "", message)
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
// src/send.ts
|
|
2178
|
+
var SEND_COMMANDS = ["broadcasts", "emails"];
|
|
2179
|
+
var TEST_SEGMENT_NAME = "CLI test recipients";
|
|
2180
|
+
var SEND_RPS = 5;
|
|
2181
|
+
var WAIT_POLL_MS = 5e3;
|
|
2182
|
+
var WAIT_LIMIT_MS = 30 * 6e4;
|
|
2183
|
+
var SYSTEM_CLOCK = {
|
|
2184
|
+
now: () => Date.now(),
|
|
2185
|
+
sleep: (ms) => new Promise((resolve2) => setTimeout(resolve2, ms))
|
|
2186
|
+
};
|
|
2187
|
+
var TERMINAL_STATUSES = /* @__PURE__ */ new Set(["sent", "failed", "canceled", "cancelled"]);
|
|
2188
|
+
var sendHelpText = () => `Sending
|
|
2189
|
+
billionsend broadcasts send --from <addr> --subject <s> --html-file <f> --segment <name|id> [options]
|
|
2190
|
+
billionsend broadcasts send ... --test <email> [--test <email>] the same broadcast, to these addresses only
|
|
2191
|
+
billionsend broadcasts get <id>
|
|
2192
|
+
billionsend emails send --from <addr> --to <email> --subject <s> (--html-file <f> | --text-file <f>) [options]
|
|
2193
|
+
|
|
2194
|
+
Sending options
|
|
2195
|
+
--from <address> sender, "Name <user@your-domain>"; the domain must be verified on BillionSend
|
|
2196
|
+
--subject <text> subject line
|
|
2197
|
+
--html-file <path> HTML body; broadcast merge tags ({{{FIRST_NAME|there}}}, {{{RESEND_UNSUBSCRIBE_URL}}}) are filled per recipient
|
|
2198
|
+
--text-file <path> plain-text body (with or instead of --html-file)
|
|
2199
|
+
--segment <name|id> broadcasts: who it goes to
|
|
2200
|
+
--topic <name|id> broadcasts: only contacts subscribed to this topic
|
|
2201
|
+
--name <text> broadcasts: internal name (default: the subject)
|
|
2202
|
+
--preview-text <text> broadcasts: inbox preview line
|
|
2203
|
+
--reply-to <address> repeatable
|
|
2204
|
+
--to <email> emails: repeatable
|
|
2205
|
+
--test <email> broadcasts: send to these addresses instead of the segment (repeatable or comma-separated).
|
|
2206
|
+
They are put in a segment named "${TEST_SEGMENT_NAME}" holding exactly them, so the test
|
|
2207
|
+
goes through the real broadcast path: names and unsubscribe links are each recipient's own
|
|
2208
|
+
--wait broadcasts: follow the broadcast until it is sent, failed or canceled (30 min at most)
|
|
2209
|
+
--idempotency-key <key> emails: a retry with the same key sends once
|
|
2210
|
+
--key-stdin read the BillionSend API key from stdin instead of BILLIONSEND_API_KEY
|
|
2211
|
+
-y, --yes send without asking; required when stdin is not a terminal
|
|
2212
|
+
--json JSON on stdout
|
|
2213
|
+
`;
|
|
2214
|
+
var UsageError = class extends Error {
|
|
2215
|
+
};
|
|
2216
|
+
var OPTIONS = {
|
|
2217
|
+
from: { type: "string" },
|
|
2218
|
+
subject: { type: "string" },
|
|
2219
|
+
"html-file": { type: "string" },
|
|
2220
|
+
"text-file": { type: "string" },
|
|
2221
|
+
segment: { type: "string" },
|
|
2222
|
+
topic: { type: "string" },
|
|
2223
|
+
name: { type: "string" },
|
|
2224
|
+
"preview-text": { type: "string" },
|
|
2225
|
+
"reply-to": { type: "string", multiple: true },
|
|
2226
|
+
to: { type: "string", multiple: true },
|
|
2227
|
+
test: { type: "string", multiple: true },
|
|
2228
|
+
wait: { type: "boolean" },
|
|
2229
|
+
"idempotency-key": { type: "string" },
|
|
2230
|
+
"key-stdin": { type: "boolean" },
|
|
2231
|
+
"to-url": { type: "string" },
|
|
2232
|
+
yes: { type: "boolean", short: "y" },
|
|
2233
|
+
json: { type: "boolean" },
|
|
2234
|
+
help: { type: "boolean", short: "h" }
|
|
2235
|
+
};
|
|
2236
|
+
var EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
2237
|
+
function splitAddresses(values) {
|
|
2238
|
+
const out = [];
|
|
2239
|
+
for (const value of values ?? []) {
|
|
2240
|
+
for (const part of value.split(",")) {
|
|
2241
|
+
const email = part.trim().toLowerCase();
|
|
2242
|
+
if (email === "") continue;
|
|
2243
|
+
if (!EMAIL.test(email)) throw new UsageError(`Not an email address: ${part.trim()}`);
|
|
2244
|
+
if (!out.includes(email)) out.push(email);
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
return out;
|
|
2248
|
+
}
|
|
2249
|
+
function required(values, name) {
|
|
2250
|
+
const value = values[name]?.trim();
|
|
2251
|
+
if (!value) throw new UsageError(`--${name} is required.`);
|
|
2252
|
+
return value;
|
|
2253
|
+
}
|
|
2254
|
+
function readBody(io, values) {
|
|
2255
|
+
const read = (flag) => {
|
|
2256
|
+
const path2 = values[flag];
|
|
2257
|
+
if (path2 === void 0) return void 0;
|
|
2258
|
+
try {
|
|
2259
|
+
return readFileSync(resolve(io.cwd, path2), "utf8");
|
|
2260
|
+
} catch {
|
|
2261
|
+
throw new UsageError(`Cannot read --${flag} ${path2}`);
|
|
2262
|
+
}
|
|
2263
|
+
};
|
|
2264
|
+
const html = read("html-file");
|
|
2265
|
+
const text = read("text-file");
|
|
2266
|
+
if (html === void 0 && text === void 0)
|
|
2267
|
+
throw new UsageError("--html-file or --text-file is required.");
|
|
2268
|
+
if (`${html ?? ""}${text ?? ""}`.trim() === "")
|
|
2269
|
+
throw new UsageError("The message body is empty.");
|
|
2270
|
+
return { ...html === void 0 ? {} : { html }, ...text === void 0 ? {} : { text } };
|
|
2271
|
+
}
|
|
2272
|
+
async function listAll(http, path2) {
|
|
2273
|
+
const rows = [];
|
|
2274
|
+
const guard = cursorGuard(path2);
|
|
2275
|
+
let after;
|
|
2276
|
+
for (; ; ) {
|
|
2277
|
+
const { body } = await http.get(path2, { query: { limit: 100, after } });
|
|
2278
|
+
const page = pageItems(path2, body, after);
|
|
2279
|
+
guard(page, after);
|
|
2280
|
+
rows.push(...page);
|
|
2281
|
+
if (body.has_more !== true) return rows;
|
|
2282
|
+
after = nextCursor(path2, page, after);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
async function resolveNamed(http, path2, kind, ref) {
|
|
2286
|
+
const rows = await listAll(http, path2);
|
|
2287
|
+
const byId = rows.find((r) => r.id === ref);
|
|
2288
|
+
if (byId) return byId;
|
|
2289
|
+
const byName = rows.filter((r) => r.name === ref);
|
|
2290
|
+
if (byName.length === 1 && byName[0]) return byName[0];
|
|
2291
|
+
const choices = rows.map((r) => ` ${r.name} ${r.id}`).join("\n") || " (none)";
|
|
2292
|
+
if (byName.length > 1)
|
|
2293
|
+
throw new UsageError(`${byName.length} ${kind}s are named "${ref}"; pass the id:
|
|
2294
|
+
${choices}`);
|
|
2295
|
+
throw new UsageError(`No ${kind} "${ref}". Existing ${kind}s:
|
|
2296
|
+
${choices}`);
|
|
2297
|
+
}
|
|
2298
|
+
async function prepareTestSegment(http, emails) {
|
|
2299
|
+
const segments = await listAll(http, "/segments");
|
|
2300
|
+
const existing = segments.find((s) => s.name === TEST_SEGMENT_NAME);
|
|
2301
|
+
const segment = existing ?? (await http.post("/segments", { name: TEST_SEGMENT_NAME }, { idempotent: false })).body;
|
|
2302
|
+
const members = await listAll(
|
|
2303
|
+
http,
|
|
2304
|
+
route`/segments/${segment.id}/contacts`
|
|
2305
|
+
);
|
|
2306
|
+
for (const member of members) {
|
|
2307
|
+
if (!emails.includes(member.email.toLowerCase()))
|
|
2308
|
+
await http.delete(route`/contacts/${member.id}/segments/${segment.id}`);
|
|
2309
|
+
}
|
|
2310
|
+
const found = await http.post(
|
|
2311
|
+
"/contacts/batch/get",
|
|
2312
|
+
{ contacts: emails.map((email) => ({ email })) },
|
|
2313
|
+
{ idempotent: true }
|
|
2314
|
+
);
|
|
2315
|
+
const idByEmail = new Map(found.body.data.map((c) => [c.email.toLowerCase(), c.id]));
|
|
2316
|
+
const missing = emails.filter((e) => !idByEmail.has(e));
|
|
2317
|
+
if (missing.length > 0) {
|
|
2318
|
+
const created = await http.post(
|
|
2319
|
+
"/contacts/batch",
|
|
2320
|
+
missing.map((email) => ({ email })),
|
|
2321
|
+
{ query: { on_conflict: "skip" }, idempotent: true }
|
|
2322
|
+
);
|
|
2323
|
+
for (const row of created.body.data) idByEmail.set(missing[row.index], row.id);
|
|
2324
|
+
}
|
|
2325
|
+
for (const email of emails) {
|
|
2326
|
+
const id = idByEmail.get(email);
|
|
2327
|
+
if (!members.some((m) => m.id === id))
|
|
2328
|
+
await http.post(route`/contacts/${id}/segments/${segment.id}`, void 0, {
|
|
2329
|
+
idempotent: true
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
return segment;
|
|
2333
|
+
}
|
|
2334
|
+
async function confirm(io, values, question) {
|
|
2335
|
+
if (values.yes) return true;
|
|
2336
|
+
if (io.stdin.isTTY !== true)
|
|
2337
|
+
throw new UsageError(
|
|
2338
|
+
"Refusing to send without confirmation: pass --yes (stdin is not a terminal)."
|
|
2339
|
+
);
|
|
2340
|
+
const rl = lineReader(io.stdin, io.stderr);
|
|
2341
|
+
try {
|
|
2342
|
+
const answer = (await rl.question(`${question} [y/N] `)).trim().toLowerCase();
|
|
2343
|
+
return answer === "y" || answer === "yes";
|
|
2344
|
+
} finally {
|
|
2345
|
+
rl.close();
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
var describe = (b) => `status ${b.status}${b.sent_count === null ? "" : ` \xB7 sent ${b.sent_count}`}${b.failure_reason ? ` \xB7 ${b.failure_reason}` : ""}`;
|
|
2349
|
+
async function waitFor(http, id, say, clock) {
|
|
2350
|
+
const deadline = clock.now() + WAIT_LIMIT_MS;
|
|
2351
|
+
let last = "";
|
|
2352
|
+
for (; ; ) {
|
|
2353
|
+
const { body } = await http.get(route`/broadcasts/${id}`);
|
|
2354
|
+
const line = describe(body);
|
|
2355
|
+
if (line !== last) say(` ${line}`);
|
|
2356
|
+
last = line;
|
|
2357
|
+
const ended = TERMINAL_STATUSES.has(body.status);
|
|
2358
|
+
if (ended || clock.now() >= deadline) return { broadcast: body, ended };
|
|
2359
|
+
await clock.sleep(WAIT_POLL_MS);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
async function broadcastsSend(io, http, values, clock) {
|
|
2363
|
+
const from = required(values, "from");
|
|
2364
|
+
const subject = required(values, "subject");
|
|
2365
|
+
const body = readBody(io, values);
|
|
2366
|
+
const test = splitAddresses(values.test);
|
|
2367
|
+
const segmentRef = values.segment;
|
|
2368
|
+
if (test.length === 0 && !segmentRef)
|
|
2369
|
+
throw new UsageError("--segment is required (or --test <email> for a test send).");
|
|
2370
|
+
const say = (line) => (values.json ? io.stderr : io.stdout).write(`${line}
|
|
2371
|
+
`);
|
|
2372
|
+
const topic = values.topic ? await resolveNamed(http, "/topics", "topic", values.topic) : null;
|
|
2373
|
+
const named = segmentRef ? await resolveNamed(http, "/segments", "segment", segmentRef) : null;
|
|
2374
|
+
let segment;
|
|
2375
|
+
let question;
|
|
2376
|
+
if (test.length > 0) {
|
|
2377
|
+
segment = await prepareTestSegment(http, test);
|
|
2378
|
+
question = `Send a test to ${test.join(", ")}?`;
|
|
2379
|
+
} else {
|
|
2380
|
+
segment = named;
|
|
2381
|
+
const { body: detail } = await http.get(
|
|
2382
|
+
route`/segments/${segment.id}`
|
|
2383
|
+
);
|
|
2384
|
+
say(
|
|
2385
|
+
`Segment ${segment.name} (${segment.id}) \xB7 ${detail.contact_count} contacts${topic ? ` \xB7 topic ${topic.name}: only its subscribers receive it` : ""}`
|
|
2386
|
+
);
|
|
2387
|
+
question = `Send "${subject}" to segment ${segment.name} (${detail.contact_count} contacts)?`;
|
|
2388
|
+
}
|
|
2389
|
+
if (!await confirm(io, values, question)) {
|
|
2390
|
+
say("Not sent.");
|
|
2391
|
+
return 1;
|
|
2392
|
+
}
|
|
2393
|
+
const prefix = test.length > 0 ? "[TEST] " : "";
|
|
2394
|
+
const created = await http.post(
|
|
2395
|
+
"/broadcasts",
|
|
2396
|
+
{
|
|
2397
|
+
name: `${prefix}${values.name?.trim() || subject}`,
|
|
2398
|
+
from,
|
|
2399
|
+
subject: `${prefix}${subject}`,
|
|
2400
|
+
segment_id: segment.id,
|
|
2401
|
+
...topic ? { topic_id: topic.id } : {},
|
|
2402
|
+
...values["reply-to"]?.length ? { reply_to: values["reply-to"] } : {},
|
|
2403
|
+
...values["preview-text"] ? { preview_text: values["preview-text"] } : {},
|
|
2404
|
+
...body,
|
|
2405
|
+
send: true
|
|
2406
|
+
},
|
|
2407
|
+
{ idempotent: false }
|
|
2408
|
+
);
|
|
2409
|
+
const id = created.body.id;
|
|
2410
|
+
say(`Broadcast ${id} queued${test.length > 0 ? ` (test to ${test.join(", ")})` : ""}.`);
|
|
2411
|
+
let result;
|
|
2412
|
+
let gaveUp = false;
|
|
2413
|
+
if (values.wait) {
|
|
2414
|
+
const waited = await waitFor(http, id, say, clock);
|
|
2415
|
+
result = waited.broadcast;
|
|
2416
|
+
gaveUp = !waited.ended;
|
|
2417
|
+
if (gaveUp)
|
|
2418
|
+
say(
|
|
2419
|
+
`Still ${result.status} after 30 minutes; follow it with: billionsend broadcasts get ${id}`
|
|
2420
|
+
);
|
|
2421
|
+
} else {
|
|
2422
|
+
result = (await http.get(route`/broadcasts/${id}`)).body;
|
|
2423
|
+
say(` ${describe(result)}`);
|
|
2424
|
+
}
|
|
2425
|
+
if (values.json)
|
|
2426
|
+
io.stdout.write(`${JSON.stringify(result)}
|
|
2427
|
+
`);
|
|
2428
|
+
return result.status === "failed" || gaveUp ? 1 : 0;
|
|
2429
|
+
}
|
|
2430
|
+
async function broadcastsGet(io, http, values, id) {
|
|
2431
|
+
if (!id) throw new UsageError("Usage: billionsend broadcasts get <id>");
|
|
2432
|
+
const { body } = await http.get(route`/broadcasts/${id}`);
|
|
2433
|
+
if (values.json) io.stdout.write(`${JSON.stringify(body)}
|
|
2434
|
+
`);
|
|
2435
|
+
else io.stdout.write(`${body.id}${body.name ? ` \xB7 ${body.name}` : ""} \xB7 ${describe(body)}
|
|
2436
|
+
`);
|
|
2437
|
+
return 0;
|
|
2438
|
+
}
|
|
2439
|
+
async function emailsSend(io, http, values) {
|
|
2440
|
+
const from = required(values, "from");
|
|
2441
|
+
const subject = required(values, "subject");
|
|
2442
|
+
const to = splitAddresses(values.to);
|
|
2443
|
+
if (to.length === 0) throw new UsageError("--to is required.");
|
|
2444
|
+
const body = readBody(io, values);
|
|
2445
|
+
if (!await confirm(io, values, `Send "${subject}" to ${to.join(", ")}?`)) {
|
|
2446
|
+
io.stderr.write("Not sent.\n");
|
|
2447
|
+
return 1;
|
|
2448
|
+
}
|
|
2449
|
+
const key = values["idempotency-key"];
|
|
2450
|
+
const { body: sent } = await http.post(
|
|
2451
|
+
"/emails",
|
|
2452
|
+
{
|
|
2453
|
+
from,
|
|
2454
|
+
to,
|
|
2455
|
+
subject,
|
|
2456
|
+
...values["reply-to"]?.length ? { reply_to: values["reply-to"] } : {},
|
|
2457
|
+
...body
|
|
2458
|
+
},
|
|
2459
|
+
// With a key the API answers a repeat with the first email, so a retry is safe.
|
|
2460
|
+
key ? { headers: { "Idempotency-Key": key }, idempotent: true } : { idempotent: false }
|
|
2461
|
+
);
|
|
2462
|
+
if (values.json) io.stdout.write(`${JSON.stringify(sent)}
|
|
2463
|
+
`);
|
|
2464
|
+
else io.stdout.write(`Email ${sent.id} accepted.
|
|
2465
|
+
`);
|
|
2466
|
+
return 0;
|
|
2467
|
+
}
|
|
2468
|
+
async function readKey(io, values) {
|
|
2469
|
+
if (values["key-stdin"]) {
|
|
2470
|
+
const rl = lineReader(io.stdin, io.stderr);
|
|
2471
|
+
try {
|
|
2472
|
+
const line = (await rl.question("")).trim();
|
|
2473
|
+
if (line === "")
|
|
2474
|
+
throw new UsageError("No BillionSend API key arrived on stdin (--key-stdin).");
|
|
2475
|
+
return line;
|
|
2476
|
+
} finally {
|
|
2477
|
+
rl.close();
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
const key = io.env.BILLIONSEND_API_KEY?.trim();
|
|
2481
|
+
if (!key) throw new UsageError("Set BILLIONSEND_API_KEY or pass --key-stdin.");
|
|
2482
|
+
return key;
|
|
2483
|
+
}
|
|
2484
|
+
async function runSend(argv, ioIn = {}, clock = SYSTEM_CLOCK) {
|
|
2485
|
+
const io = {
|
|
2486
|
+
stdout: ioIn.stdout ?? process.stdout,
|
|
2487
|
+
stderr: ioIn.stderr ?? process.stderr,
|
|
2488
|
+
env: ioIn.env ?? process.env,
|
|
2489
|
+
stdin: ioIn.stdin ?? process.stdin,
|
|
2490
|
+
fetch: ioIn.fetch ?? globalThis.fetch,
|
|
2491
|
+
cwd: ioIn.cwd ?? process.cwd()
|
|
2492
|
+
};
|
|
2493
|
+
const log = createLogger({ level: "info", stream: io.stderr });
|
|
2494
|
+
try {
|
|
2495
|
+
const { values, positionals } = parseArgs({
|
|
2496
|
+
args: [...argv],
|
|
2497
|
+
options: OPTIONS,
|
|
2498
|
+
allowPositionals: true,
|
|
2499
|
+
strict: true
|
|
2500
|
+
});
|
|
2501
|
+
const [command, sub, id, ...rest] = positionals;
|
|
2502
|
+
if (values.help || sub === void 0) {
|
|
2503
|
+
io.stdout.write(sendHelpText());
|
|
2504
|
+
return values.help ? 0 : 1;
|
|
2505
|
+
}
|
|
2506
|
+
const known = command === "broadcasts" && (sub === "send" || sub === "get") || command === "emails" && sub === "send";
|
|
2507
|
+
if (!known) throw new UsageError(`Unknown command: ${command} ${sub}`);
|
|
2508
|
+
if (rest.length > 0 || id !== void 0 && sub !== "get")
|
|
2509
|
+
throw new UsageError(`Unexpected argument: ${[id, ...rest].filter(Boolean).join(" ")}`);
|
|
2510
|
+
const token = await readKey(io, values);
|
|
2511
|
+
const baseUrl = stripTrailingSlashes(
|
|
2512
|
+
values["to-url"] ?? io.env.BILLIONSEND_BASE_URL ?? CLOUD_API_URL
|
|
2513
|
+
);
|
|
2514
|
+
const http = createHttp({
|
|
2515
|
+
baseUrl,
|
|
2516
|
+
token,
|
|
2517
|
+
userAgent: USER_AGENT,
|
|
2518
|
+
rps: SEND_RPS,
|
|
2519
|
+
log,
|
|
2520
|
+
name: "BillionSend",
|
|
2521
|
+
fetch: io.fetch
|
|
2522
|
+
});
|
|
2523
|
+
if (command === "emails") return await emailsSend(io, http, values);
|
|
2524
|
+
if (sub === "get") return await broadcastsGet(io, http, values, id);
|
|
2525
|
+
return await broadcastsSend(io, http, values, clock);
|
|
2526
|
+
} catch (error) {
|
|
2527
|
+
if (error instanceof UsageError || error instanceof AuthError || error instanceof ApiError) {
|
|
2528
|
+
log.error(error.message);
|
|
2529
|
+
return 1;
|
|
2530
|
+
}
|
|
2531
|
+
if (error instanceof TypeError && "code" in error && String(error.code).startsWith("ERR_PARSE_ARGS")) {
|
|
2532
|
+
log.error(error.message);
|
|
2533
|
+
return 1;
|
|
2534
|
+
}
|
|
2535
|
+
throw error;
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2148
2539
|
// src/config.ts
|
|
2149
2540
|
var PLAN_OPTIONS = [
|
|
2150
2541
|
"only",
|
|
@@ -2167,7 +2558,7 @@ var RPS_HEADROOM = 2;
|
|
|
2167
2558
|
var TARGET_KEY_ENV = "BILLIONSEND_API_KEY";
|
|
2168
2559
|
var TARGET_URL_ENV = "BILLIONSEND_BASE_URL";
|
|
2169
2560
|
var sourceKeyEnv = (provider) => `${provider.toUpperCase()}_API_KEY`;
|
|
2170
|
-
var
|
|
2561
|
+
var OPTIONS2 = {
|
|
2171
2562
|
from: { type: "string" },
|
|
2172
2563
|
"from-key": { type: "string" },
|
|
2173
2564
|
"from-key-stdin": { type: "boolean" },
|
|
@@ -2245,9 +2636,9 @@ function parseConfig(argv, env = process.env, stdinIsTTY = process.stdin.isTTY =
|
|
|
2245
2636
|
let values;
|
|
2246
2637
|
let positionals;
|
|
2247
2638
|
try {
|
|
2248
|
-
({ values, positionals } =
|
|
2639
|
+
({ values, positionals } = parseArgs2({
|
|
2249
2640
|
args: argv,
|
|
2250
|
-
options:
|
|
2641
|
+
options: OPTIONS2,
|
|
2251
2642
|
strict: true,
|
|
2252
2643
|
allowPositionals: true
|
|
2253
2644
|
}));
|
|
@@ -2414,6 +2805,7 @@ Usage
|
|
|
2414
2805
|
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
2806
|
billionsend migrate status what the last run created and what is left
|
|
2416
2807
|
billionsend migrate rollback [--yes] delete only what this tool created
|
|
2808
|
+
billionsend broadcasts send | broadcasts get | emails send send from the command line (see Sending below)
|
|
2417
2809
|
billionsend --help | --version
|
|
2418
2810
|
|
|
2419
2811
|
Options
|
|
@@ -2448,6 +2840,7 @@ Options
|
|
|
2448
2840
|
Resources
|
|
2449
2841
|
${RESOURCES.join(", ")}
|
|
2450
2842
|
|
|
2843
|
+
${sendHelpText()}
|
|
2451
2844
|
Environment
|
|
2452
2845
|
RESEND_API_KEY source API key (full access; the tool only reads from Resend)
|
|
2453
2846
|
${TARGET_KEY_ENV} BillionSend API key (full access)
|
|
@@ -2518,7 +2911,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2518
2911
|
const { body } = await response;
|
|
2519
2912
|
return { id: body.id, records: body.records };
|
|
2520
2913
|
};
|
|
2521
|
-
async function
|
|
2914
|
+
async function listAll2(path2, { paged = true } = {}) {
|
|
2522
2915
|
const rows = [];
|
|
2523
2916
|
let after;
|
|
2524
2917
|
const guard = cursorGuard(path2);
|
|
@@ -2576,13 +2969,13 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2576
2969
|
broadcasts,
|
|
2577
2970
|
firstContact
|
|
2578
2971
|
] = await Promise.all([
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2972
|
+
listAll2("/domains"),
|
|
2973
|
+
listAll2("/contact-properties"),
|
|
2974
|
+
listAll2("/topics", { paged: false }),
|
|
2975
|
+
listAll2("/segments"),
|
|
2976
|
+
listAll2("/webhooks"),
|
|
2977
|
+
listAll2("/templates"),
|
|
2978
|
+
listAll2("/broadcasts"),
|
|
2586
2979
|
api.get("/contacts", { query: { limit: 1 } })
|
|
2587
2980
|
]);
|
|
2588
2981
|
const domains = [];
|
|
@@ -2889,7 +3282,7 @@ function createBillionSendTarget(http, log, baseUrl = "the BillionSend URL") {
|
|
|
2889
3282
|
return { added, errors };
|
|
2890
3283
|
},
|
|
2891
3284
|
/** Every suppression id on the target; apply diffs against it so rollback deletes only rows it added. */
|
|
2892
|
-
listSuppressionIds: async () => (await
|
|
3285
|
+
listSuppressionIds: async () => (await listAll2("/suppressions")).map((s) => s.id),
|
|
2893
3286
|
addSuppressions: (emails, origin) => suppressionsBatch("/suppressions/batch/add", "emails", emails, { origin }),
|
|
2894
3287
|
removeSuppressions: (ids) => suppressionsBatch("/suppressions/batch/remove", "ids", ids)
|
|
2895
3288
|
};
|
|
@@ -2902,7 +3295,7 @@ import {
|
|
|
2902
3295
|
existsSync,
|
|
2903
3296
|
lstatSync,
|
|
2904
3297
|
mkdirSync,
|
|
2905
|
-
readFileSync,
|
|
3298
|
+
readFileSync as readFileSync2,
|
|
2906
3299
|
renameSync,
|
|
2907
3300
|
unlinkSync,
|
|
2908
3301
|
writeFileSync
|
|
@@ -2942,7 +3335,7 @@ function writePrivateJson(path2, value) {
|
|
|
2942
3335
|
}
|
|
2943
3336
|
function readJson(path2) {
|
|
2944
3337
|
if (!existsSync(path2)) return null;
|
|
2945
|
-
const content =
|
|
3338
|
+
const content = readFileSync2(path2, "utf8");
|
|
2946
3339
|
try {
|
|
2947
3340
|
return JSON.parse(content);
|
|
2948
3341
|
} catch {
|
|
@@ -2952,7 +3345,7 @@ function readJson(path2) {
|
|
|
2952
3345
|
function ensureGitignored(cwd = process.cwd()) {
|
|
2953
3346
|
const path2 = join(cwd, ".gitignore");
|
|
2954
3347
|
if (!existsSync(path2)) return false;
|
|
2955
|
-
const content =
|
|
3348
|
+
const content = readFileSync2(path2, "utf8");
|
|
2956
3349
|
const listed = content.split(/\r?\n/).some((line) => line.trim().replace(/^\/|\/$/g, "") === STATE_DIR);
|
|
2957
3350
|
if (listed) return false;
|
|
2958
3351
|
const separator = content === "" || content.endsWith("\n") ? "" : "\n";
|
|
@@ -4470,7 +4863,7 @@ async function apply(ctx) {
|
|
|
4470
4863
|
if (config.planFile === null) return migrate(ctx);
|
|
4471
4864
|
let text;
|
|
4472
4865
|
try {
|
|
4473
|
-
text =
|
|
4866
|
+
text = readFileSync3(config.planFile, "utf8");
|
|
4474
4867
|
} catch (error) {
|
|
4475
4868
|
if (error.code !== "ENOENT") throw error;
|
|
4476
4869
|
throw new Error(
|
|
@@ -4748,30 +5141,6 @@ ${pluralize(state.failures.length, "failure")} in the last run
|
|
|
4748
5141
|
return 0;
|
|
4749
5142
|
}
|
|
4750
5143
|
|
|
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
5144
|
// src/context.ts
|
|
4776
5145
|
function createContext(config, io = {}) {
|
|
4777
5146
|
const stdout = io.stdout ?? process.stdout;
|
|
@@ -4796,6 +5165,7 @@ function createContext(config, io = {}) {
|
|
|
4796
5165
|
// src/index.ts
|
|
4797
5166
|
var COMMANDS = { migrate, plan, apply, status, rollback };
|
|
4798
5167
|
async function main(argv = process.argv.slice(2), io = {}) {
|
|
5168
|
+
if (SEND_COMMANDS.includes(argv[0] ?? "")) return runSend(argv, io);
|
|
4799
5169
|
const stdout = io.stdout ?? process.stdout;
|
|
4800
5170
|
const stderr = io.stderr ?? process.stderr;
|
|
4801
5171
|
let config;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@billionsend/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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",
|