senddart-cli 1.0.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.
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+
3
+ const { clean, withPagination, pagination, saveFile } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const domains = group('domains', 'Manage sending domains');
7
+ act(leaf(domains, 'tracking-health <id>', 'Check tracking HTTPS readiness and schedule repair when unavailable'),
8
+ ({ client, args: [id] }) => client.domains.trackingHealth(id));
9
+
10
+ act(
11
+ leaf(domains, 'add <name>', 'Add a sending domain')
12
+ .option('--region <region>', 'sending region')
13
+ .option('--custom-return-path <label>', "MAIL FROM subdomain (default 'send')")
14
+ .option('--tracking-subdomain <label>', "custom tracking host label, e.g. 'email'")
15
+ .option('--tls <policy>', "outbound TLS policy: 'opportunistic' | 'enforced'")
16
+ .option('--open-tracking', 'enable open tracking')
17
+ .option('--no-open-tracking', 'disable open tracking')
18
+ .option('--click-tracking', 'enable click tracking')
19
+ .option('--no-click-tracking', 'disable click tracking')
20
+ .option('--receiving', 'enable inbound email receiving')
21
+ .option('--no-receiving', 'disable inbound email receiving'),
22
+ ({ client, opts, args: [name] }) =>
23
+ client.domains.create(
24
+ clean({
25
+ name,
26
+ region: opts.region,
27
+ custom_return_path: opts.customReturnPath,
28
+ tracking_subdomain: opts.trackingSubdomain,
29
+ tls: opts.tls,
30
+ // Only send the booleans the user explicitly set.
31
+ open_tracking: 'openTracking' in opts ? opts.openTracking : undefined,
32
+ click_tracking: 'clickTracking' in opts ? opts.clickTracking : undefined,
33
+ capabilities:
34
+ 'receiving' in opts
35
+ ? { receiving: opts.receiving ? 'enabled' : 'disabled' }
36
+ : undefined,
37
+ }),
38
+ ),
39
+ );
40
+
41
+ act(leaf(domains, 'get <id>', 'Retrieve a domain and its DNS records'), ({ client, args: [id] }) =>
42
+ client.domains.get(id),
43
+ );
44
+
45
+ act(withPagination(leaf(domains, 'list', 'List your domains')), ({ client, opts }) =>
46
+ client.domains.list(pagination(opts)),
47
+ );
48
+
49
+ act(leaf(domains, 'verify <id>', 'Trigger DNS verification for a domain'), ({ client, args: [id] }) =>
50
+ client.domains.verify(id),
51
+ );
52
+
53
+ act(
54
+ leaf(domains, 'update <id>', "Update a domain's tracking/TLS settings")
55
+ .option('--open-tracking', 'enable open tracking')
56
+ .option('--no-open-tracking', 'disable open tracking')
57
+ .option('--click-tracking', 'enable click tracking')
58
+ .option('--no-click-tracking', 'disable click tracking')
59
+ .option('--tracking-subdomain <label>', 'custom tracking host label')
60
+ .option('--custom-tracking', 'serve tracking links from the custom tracking host')
61
+ .option('--no-custom-tracking', 'serve tracking links from the SendDart host')
62
+ .option('--custom-return-path <label>', 'MAIL FROM subdomain (Return-Path) DNS label')
63
+ .option('--receiving', 'enable inbound email receiving')
64
+ .option('--no-receiving', 'disable inbound email receiving')
65
+ .option('--tls <policy>', "outbound TLS policy: 'opportunistic' | 'enforced'"),
66
+ ({ client, opts, args: [id] }) =>
67
+ client.domains.update(
68
+ id,
69
+ clean({
70
+ open_tracking: 'openTracking' in opts ? opts.openTracking : undefined,
71
+ click_tracking: 'clickTracking' in opts ? opts.clickTracking : undefined,
72
+ custom_tracking: 'customTracking' in opts ? opts.customTracking : undefined,
73
+ tracking_subdomain: opts.trackingSubdomain,
74
+ custom_return_path: opts.customReturnPath,
75
+ capabilities:
76
+ 'receiving' in opts
77
+ ? { receiving: opts.receiving ? 'enabled' : 'disabled' }
78
+ : undefined,
79
+ tls: opts.tls,
80
+ }),
81
+ ),
82
+ );
83
+
84
+ act(
85
+ leaf(domains, 'mx-check <name>', 'Check whether a domain already has MX records pointed at us'),
86
+ ({ client, args: [name] }) => client.domains.mxCheck(name),
87
+ );
88
+
89
+ act(
90
+ leaf(
91
+ domains,
92
+ 'records-csv <id>',
93
+ "Download this domain's DNS records as CSV, ready to hand to a registrar",
94
+ ).option('--output <path>', 'file to write (default: <id>-dns-records.csv)'),
95
+ async ({ client, opts, args: [id] }) => {
96
+ // The endpoint answers text/csv, not JSON — write it out and print where
97
+ // it landed, the same way the binary download commands do.
98
+ const result = await client.domains.recordsCsv(id);
99
+ if (result.error) return result;
100
+ return saveFile(opts.output || `${id}-dns-records.csv`, result.data);
101
+ },
102
+ );
103
+
104
+ act(leaf(domains, 'delete <id>', 'Delete a domain'), ({ client, args: [id] }) =>
105
+ client.domains.remove(id),
106
+ );
107
+
108
+ // ---- one-click DNS ----
109
+
110
+ const dns = domains
111
+ .command('dns')
112
+ .description("Detect a domain's DNS provider and apply its records via provider APIs");
113
+
114
+ act(
115
+ leaf(dns, 'detect <id>', 'Detect the DNS provider and available one-click apply methods'),
116
+ ({ client, args: [id] }) => client.domains.detectDns(id),
117
+ );
118
+
119
+ act(
120
+ leaf(dns, 'cloudflare <id>', 'Apply DNS records via the Cloudflare API, then auto-verify').requiredOption(
121
+ '--token <token>',
122
+ 'Cloudflare API token with DNS edit access',
123
+ ),
124
+ ({ client, opts, args: [id] }) => client.domains.applyCloudflareDns(id, { token: opts.token }),
125
+ );
126
+
127
+ act(
128
+ leaf(dns, 'godaddy <id>', 'Apply DNS records via the GoDaddy API, then auto-verify')
129
+ .requiredOption('--key <key>', 'GoDaddy API key')
130
+ .requiredOption('--secret <secret>', 'GoDaddy API secret'),
131
+ ({ client, opts, args: [id] }) =>
132
+ client.domains.applyGoDaddyDns(id, { key: opts.key, secret: opts.secret }),
133
+ );
134
+
135
+ act(
136
+ leaf(dns, 'namecheap <id>', 'Apply DNS records via the Namecheap API, then auto-verify')
137
+ .requiredOption('--api-user <user>', 'Namecheap API user')
138
+ .requiredOption('--key <key>', 'Namecheap API key')
139
+ .option('--user-name <name>', 'Namecheap account user name (default: the API user)'),
140
+ ({ client, opts, args: [id] }) =>
141
+ client.domains.applyNamecheapDns(
142
+ id,
143
+ clean({ apiUser: opts.apiUser, apiKey: opts.key, userName: opts.userName }),
144
+ ),
145
+ );
146
+
147
+ // ---- domain claims ----
148
+ // `claim` is a subgroup (start/get/verify) so the takeover flow reads
149
+ // unambiguously: `claim start <name>` begins a claim, then `claim get <id>`
150
+ // and `claim verify <id>` operate on the domain id it returns.
151
+
152
+ const claim = domains
153
+ .command('claim')
154
+ .description('Claim a domain already verified by another account (start, then verify)');
155
+
156
+ act(
157
+ leaf(claim, 'start <name>', 'Start a claim for a domain name').option(
158
+ '--region <region>',
159
+ 'sending region',
160
+ ),
161
+ ({ client, opts, args: [name] }) => client.domains.claim(clean({ name, region: opts.region })),
162
+ );
163
+
164
+ act(
165
+ leaf(claim, 'get <id>', "Retrieve a domain's claim record"),
166
+ ({ client, args: [id] }) => client.domains.getClaim(id),
167
+ );
168
+
169
+ act(
170
+ leaf(claim, 'verify <id>', 'Verify a domain claim (completes the takeover)'),
171
+ ({ client, args: [id] }) => client.domains.verifyClaim(id),
172
+ );
173
+ }
174
+
175
+ module.exports = { register };
@@ -0,0 +1,330 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const { CliError, collect, append, parseJson, clean, withPagination, pagination, saveFile } = require('../helpers');
7
+
8
+ /** Server-side attachment caps (decoded bytes) — mirrored so we fail before uploading. */
9
+ const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024;
10
+ const MAX_ATTACHMENTS_TOTAL = 40 * 1024 * 1024;
11
+
12
+ /**
13
+ * Accepted `Idempotency-Key` length, 1-<max> characters measured after the
14
+ * server trims the value (the storage column is VARCHAR(255)) — not 256.
15
+ * Mirrored from `IDEMPOTENCY_KEY_MAX_LENGTH` in the senddart SDK so the
16
+ * `--idempotency-key` help text cannot drift from the documented rule.
17
+ *
18
+ * Unlike the attachment caps above this is NOT pre-checked: the key is sent as
19
+ * given and the server is the authority (400 invalid_idempotency_key). Only
20
+ * `emails send` and `emails batch` honour the header at all.
21
+ */
22
+ const IDEMPOTENCY_KEY_MAX_LENGTH = 255;
23
+ const IDEMPOTENCY_KEY_HELP = `idempotency key for safe retries (1-${IDEMPOTENCY_KEY_MAX_LENGTH} characters)`;
24
+
25
+ /**
26
+ * Build the `attachments` array from `--attachment <path>` (read + base64) and
27
+ * `--attachment-url <url>` (fetched server-side). Local files are size-checked
28
+ * against the same caps the API enforces so an oversized send fails instantly.
29
+ */
30
+ function readAttachments(opts) {
31
+ const files = opts.attachment || [];
32
+ const urls = opts.attachmentUrl || [];
33
+ if (!files.length && !urls.length) return undefined;
34
+
35
+ let total = 0;
36
+ const attachments = files.map((filePath) => {
37
+ let buf;
38
+ try {
39
+ buf = fs.readFileSync(filePath);
40
+ } catch (err) {
41
+ throw new CliError(`Cannot read --attachment ${filePath}: ${err.message}`);
42
+ }
43
+ if (buf.length > MAX_ATTACHMENT_BYTES) {
44
+ throw new CliError(
45
+ `Attachment ${path.basename(filePath)} is ${buf.length} bytes; the limit is 25 MB per file.`,
46
+ );
47
+ }
48
+ total += buf.length;
49
+ return { filename: path.basename(filePath), content: buf.toString('base64') };
50
+ });
51
+ if (total > MAX_ATTACHMENTS_TOTAL) {
52
+ throw new CliError(`Attachments total ${total} bytes; the limit is 40 MB per message.`);
53
+ }
54
+ for (const url of urls) {
55
+ let parsed;
56
+ try {
57
+ parsed = new URL(url);
58
+ } catch {
59
+ throw new CliError(`Invalid URL for --attachment-url: ${url}`);
60
+ }
61
+ attachments.push({ filename: path.basename(parsed.pathname) || 'attachment', path: url });
62
+ }
63
+ return attachments;
64
+ }
65
+
66
+ /** Resolve the batch payload array from --file or --data, with friendly errors. */
67
+ function readBatchPayloads(opts) {
68
+ if (opts.file && opts.data) throw new CliError('Provide only one of --file or --data.');
69
+ if (!opts.file && !opts.data) throw new CliError('Provide --file <path> or --data <json array>.');
70
+ let payloads;
71
+ if (opts.data) {
72
+ payloads = parseJson(opts.data, '--data');
73
+ } else {
74
+ let raw;
75
+ try {
76
+ raw = fs.readFileSync(opts.file, 'utf8');
77
+ } catch (err) {
78
+ throw new CliError(`Cannot read --file ${opts.file}: ${err.message}`);
79
+ }
80
+ try {
81
+ payloads = JSON.parse(raw);
82
+ } catch {
83
+ throw new CliError(`Invalid JSON in --file ${opts.file}`);
84
+ }
85
+ }
86
+ if (!Array.isArray(payloads)) {
87
+ throw new CliError('Batch payload must be a JSON array of send objects.');
88
+ }
89
+ return payloads;
90
+ }
91
+
92
+ function register({ group, leaf, act }) {
93
+ const emails = group('emails', 'Send and manage emails');
94
+
95
+ act(
96
+ leaf(emails, 'send', 'Send an email')
97
+ .option('--from <from>', "sender, e.g. 'Acme <hi@yourdomain.com>' — omit to use the template's own from")
98
+ .requiredOption('--to <address>', 'recipient (repeatable or comma-separated)', collect)
99
+ .option('--subject <subject>', "subject line — omit to use the template's own subject")
100
+ .option('--html <html>', 'HTML body')
101
+ .option('--text <text>', 'plain-text body')
102
+ .option('--cc <address>', 'cc recipient (repeatable or comma-separated)', collect)
103
+ .option('--bcc <address>', 'bcc recipient (repeatable or comma-separated)', collect)
104
+ .option('--reply-to <address>', 'reply-to address (repeatable or comma-separated)', collect)
105
+ .option('--preview-text <text>', 'inbox preview text (preheader)')
106
+ .option('--template-id <id>', 'send using a saved template')
107
+ .option('--template-alias <alias>', "send using a saved template by its alias")
108
+ .option('--variables <json>', 'template variables as a JSON object')
109
+ .option('--headers <json>', 'custom headers as a JSON object')
110
+ .option('--attachment <path>', 'file to attach (repeatable; max 25 MB each, 40 MB total)', append)
111
+ .option('--attachment-url <url>', 'hosted file to attach by URL (repeatable)', append)
112
+ .option('--scheduled-at <when>', "ISO 8601 timestamp, or a phrase like 'in 1 min' (max 30 days ahead)")
113
+ .option('--topic-id <id>', 'drop recipients unsubscribed from this topic')
114
+ .option('--idempotency-key <key>', IDEMPOTENCY_KEY_HELP),
115
+ ({ client, opts }) => {
116
+ if (opts.templateId && opts.templateAlias) {
117
+ throw new CliError('Provide only one of --template-id or --template-alias.');
118
+ }
119
+ // `from`/`subject` are required only when no template supplies them, so
120
+ // they cannot be parser-level required options: declaring them so made the
121
+ // documented template one-liner unrunnable, and retyping the values the
122
+ // template already stores then overrides those two fields on every send
123
+ // (republishing the template no longer changes the from and subject,
124
+ // though the body still re-renders from it).
125
+ // The server falls back per field on `!= null`, so an ABSENT key takes the
126
+ // template's value while a key present as '' wins — which is why this
127
+ // tests `=== undefined` and not falsiness: `--subject ''` is a legitimate
128
+ // blank subject line, and `--from ''` must keep earning its 422 rather
129
+ // than being silently rewritten here. `clean()` drops only `undefined`,
130
+ // so an omitted flag never reaches the wire at all.
131
+ if (!opts.templateId && !opts.templateAlias
132
+ && (opts.from === undefined || opts.subject === undefined)) {
133
+ throw new CliError('--from and --subject are required unless you pass --template-id or --template-alias.');
134
+ }
135
+ const variables = parseJson(opts.variables, '--variables');
136
+ return client.emails.send(
137
+ clean({
138
+ from: opts.from,
139
+ to: opts.to,
140
+ subject: opts.subject,
141
+ html: opts.html,
142
+ text: opts.text,
143
+ cc: opts.cc,
144
+ bcc: opts.bcc,
145
+ reply_to: opts.replyTo,
146
+ preview_text: opts.previewText,
147
+ template_id: opts.templateId,
148
+ // An alias goes through the nested `template` form, which carries its
149
+ // own variables; the flat form keeps them top-level.
150
+ template: opts.templateAlias
151
+ ? clean({ alias: opts.templateAlias, variables })
152
+ : undefined,
153
+ variables: opts.templateAlias ? undefined : variables,
154
+ headers: parseJson(opts.headers, '--headers'),
155
+ attachments: readAttachments(opts),
156
+ scheduled_at: opts.scheduledAt,
157
+ topic_id: opts.topicId,
158
+ }),
159
+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,
160
+ );
161
+ },
162
+ );
163
+
164
+ act(
165
+ leaf(
166
+ emails,
167
+ 'batch',
168
+ 'Send up to 100 emails in one request (no attachments and no scheduled_at — the API 422s on either; send those individually)',
169
+ )
170
+ .option('--file <path>', 'path to a JSON file containing an array of send payloads')
171
+ .option('--data <json>', 'inline JSON array of send payloads')
172
+ .option('--idempotency-key <key>', IDEMPOTENCY_KEY_HELP),
173
+ ({ client, opts }) =>
174
+ client.batch.send(
175
+ readBatchPayloads(opts),
176
+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,
177
+ ),
178
+ );
179
+
180
+ act(leaf(emails, 'get <id>', 'Retrieve a sent email and its events'), ({ client, args: [id] }) =>
181
+ client.emails.get(id),
182
+ );
183
+
184
+ act(
185
+ withPagination(leaf(emails, 'list', 'List sent emails'))
186
+ .option('--campaign-id <id>', 'only emails sent by this campaign')
187
+ .option('--automation-id <id>', 'only emails sent by this automation')
188
+ .option(
189
+ '--source <source>',
190
+ "'individual' restricts to all one-off sends, 'api' to API-key sends, 'dashboard' to dashboard-composed mail",
191
+ )
192
+ .option('--domain-id <id>', 'only emails sent from this sending domain')
193
+ .option('--status <status>', "only emails whose last event matches, e.g. 'delivered'")
194
+ .option('--search <text>', 'match recipients, subject or sender')
195
+ .option('--folder <folder>', "mailbox folder: outbox | sent | scheduled | failed"),
196
+ ({ client, opts }) =>
197
+ client.emails.list(
198
+ clean({
199
+ ...pagination(opts),
200
+ campaign_id: opts.campaignId,
201
+ automation_id: opts.automationId,
202
+ source: opts.source,
203
+ domain_id: opts.domainId,
204
+ status: opts.status,
205
+ search: opts.search,
206
+ folder: opts.folder,
207
+ }),
208
+ ),
209
+ );
210
+
211
+ act(
212
+ leaf(emails, 'update <id>', 'Reschedule a scheduled email').requiredOption(
213
+ '--scheduled-at <when>',
214
+ "new send time: ISO 8601 or a phrase like 'in 1 min' (max 30 days ahead)",
215
+ ),
216
+ ({ client, opts, args: [id] }) => client.emails.update(id, { scheduled_at: opts.scheduledAt }),
217
+ );
218
+
219
+ act(leaf(emails, 'cancel <id>', 'Cancel a scheduled email'), ({ client, args: [id] }) =>
220
+ client.emails.cancel(id),
221
+ );
222
+
223
+ act(
224
+ leaf(emails, 'sources', 'Per-source send metrics: one row per campaign and automation, plus api and individual one-off roll-ups'),
225
+ ({ client }) => client.emails.sources(),
226
+ );
227
+
228
+ act(
229
+ leaf(emails, 'attachments <emailId>', "List a sent email's attachments"),
230
+ ({ client, args: [emailId] }) => client.emails.listAttachments(emailId),
231
+ );
232
+
233
+ act(
234
+ leaf(emails, 'attachment <emailId> <attachmentId>', 'Retrieve one attachment of a sent email'),
235
+ ({ client, args: [emailId, attachmentId] }) => client.emails.getAttachment(emailId, attachmentId),
236
+ );
237
+
238
+ // ---- inbound (received) email ----
239
+
240
+ const receiving = emails.command('receiving').description('Manage inbound (received) email');
241
+
242
+ act(
243
+ withPagination(leaf(receiving, 'list', 'List received emails')).option(
244
+ '--received-for <address>',
245
+ 'only messages received for this address',
246
+ ),
247
+ ({ client, opts }) =>
248
+ client.emails.receiving.list(
249
+ clean({ ...pagination(opts), received_for: opts.receivedFor }),
250
+ ),
251
+ );
252
+
253
+ act(
254
+ leaf(receiving, 'addresses', 'Per-address inbound stats: one row per address you receive mail for'),
255
+ ({ client }) => client.emails.receiving.listAddresses(),
256
+ );
257
+
258
+ act(leaf(receiving, 'get <id>', 'Retrieve a received email'), ({ client, args: [id] }) =>
259
+ client.emails.receiving.get(id),
260
+ );
261
+
262
+ act(
263
+ withPagination(leaf(receiving, 'attachments <id>', "List a received email's attachments")),
264
+ ({ client, opts, args: [id] }) => client.emails.receiving.listAttachments(id, pagination(opts)),
265
+ );
266
+
267
+ act(
268
+ leaf(
269
+ receiving,
270
+ 'attachment <id> <attachmentId>',
271
+ 'Download one attachment of a received email to a file',
272
+ ).option('--output <path>', 'file to write (default: the attachment id)'),
273
+ async ({ client, opts, args: [id, attachmentId] }) => {
274
+ const result = await client.emails.receiving.getAttachment(id, attachmentId);
275
+ if (result.error) return result;
276
+ return saveFile(opts.output || attachmentId, result.data);
277
+ },
278
+ );
279
+
280
+ act(
281
+ leaf(receiving, 'raw <id>', 'Download the original RFC822/MIME message to a file').option(
282
+ '--output <path>',
283
+ 'file to write (default: <id>.eml)',
284
+ ),
285
+ async ({ client, opts, args: [id] }) => {
286
+ const result = await client.emails.receiving.getRaw(id);
287
+ if (result.error) return result;
288
+ return saveFile(opts.output || `${id}.eml`, result.data);
289
+ },
290
+ );
291
+
292
+ act(
293
+ leaf(receiving, 'forward <id>', 'Forward a received email')
294
+ .requiredOption('--from <from>', 'a verified sending address to forward from')
295
+ .requiredOption('--to <address>', 'recipient (repeatable or comma-separated)', collect)
296
+ .option('--subject <subject>', 'override the subject line')
297
+ .option('--idempotency-key <key>', IDEMPOTENCY_KEY_HELP),
298
+ ({ client, opts, args: [id] }) =>
299
+ client.emails.receiving.forward(
300
+ id,
301
+ clean({ from: opts.from, to: opts.to, subject: opts.subject }),
302
+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,
303
+ ),
304
+ );
305
+
306
+ act(
307
+ leaf(receiving, 'reply <id>', "Reply to a received email's sender (threaded)")
308
+ .requiredOption('--from <from>', 'a verified sending address to reply from')
309
+ .option('--html <html>', 'HTML body')
310
+ .option('--text <text>', 'plain-text body')
311
+ .option('--subject <subject>', "override the subject (default: 'Re: …')")
312
+ .option('--idempotency-key <key>', IDEMPOTENCY_KEY_HELP),
313
+ ({ client, opts, args: [id] }) => {
314
+ if (opts.html === undefined && opts.text === undefined) {
315
+ throw new CliError('Provide at least one of --html or --text.');
316
+ }
317
+ return client.emails.receiving.reply(
318
+ id,
319
+ clean({ from: opts.from, html: opts.html, text: opts.text, subject: opts.subject }),
320
+ opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : undefined,
321
+ );
322
+ },
323
+ );
324
+
325
+ act(leaf(receiving, 'delete <id>', 'Delete a received email'), ({ client, args: [id] }) =>
326
+ client.emails.receiving.remove(id),
327
+ );
328
+ }
329
+
330
+ module.exports = { register };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+
3
+ const { CliError, parseJson, clean, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const events = group('events', 'Send custom events and manage event definitions');
7
+
8
+ act(
9
+ leaf(events, 'send', "Send a custom event to trigger a domain's automations")
10
+ .requiredOption('--domain <domain>', 'the sending domain this event belongs to')
11
+ .requiredOption('--name <name>', "event name, e.g. 'signup.completed'")
12
+ .option('--email <email>', 'identify the contact by email')
13
+ .option('--contact-id <id>', 'identify the contact by id')
14
+ .option('--data <json>', "event payload as JSON, e.g. '{\"plan\":\"pro\"}'"),
15
+ ({ client, opts }) =>
16
+ client.events.send(
17
+ clean({
18
+ name: opts.name,
19
+ domain: opts.domain,
20
+ email: opts.email,
21
+ contact_id: opts.contactId,
22
+ data: parseJson(opts.data, '--data'),
23
+ }),
24
+ ),
25
+ );
26
+
27
+ act(
28
+ leaf(events, 'create', 'Create a custom-event definition')
29
+ .requiredOption('--name <name>', 'event name')
30
+ .option('--schema <json>', "flat key→type schema as JSON, e.g. '{\"plan\":\"string\"}'"),
31
+ ({ client, opts }) =>
32
+ client.events.create(clean({ name: opts.name, schema: parseJson(opts.schema, '--schema') })),
33
+ );
34
+
35
+ act(withPagination(leaf(events, 'list', 'List custom-event definitions')), ({ client, opts }) =>
36
+ client.events.list(pagination(opts)),
37
+ );
38
+
39
+ // The event name is immutable (automations reference it) — only the payload
40
+ // schema can be updated, or cleared with --clear-schema.
41
+ act(
42
+ leaf(events, 'update <id>', "Update a custom-event definition's payload schema")
43
+ .option('--schema <json>', "flat key→type schema as JSON, e.g. '{\"plan\":\"string\"}'")
44
+ .option('--clear-schema', 'remove the schema (stops validating payloads)'),
45
+ ({ client, opts, args: [id] }) => {
46
+ if (opts.clearSchema && opts.schema !== undefined) {
47
+ throw new CliError('Provide only one of --schema or --clear-schema.');
48
+ }
49
+ if (!opts.clearSchema && opts.schema === undefined) {
50
+ throw new CliError('Provide --schema <json> or --clear-schema.');
51
+ }
52
+ return client.events.update(id, {
53
+ schema: opts.clearSchema ? null : parseJson(opts.schema, '--schema'),
54
+ });
55
+ },
56
+ );
57
+
58
+ act(leaf(events, 'delete <id>', 'Delete a custom-event definition'), ({ client, args: [id] }) =>
59
+ client.events.remove(id),
60
+ );
61
+ }
62
+
63
+ module.exports = { register };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ const { clean, toInt, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const logs = group('logs', 'Inspect API request logs');
7
+
8
+ act(
9
+ withPagination(
10
+ leaf(logs, 'list', 'List API request logs')
11
+ .option('--method <method>', "filter by HTTP method, e.g. 'POST'")
12
+ .option('--status <status>', 'filter by response status, e.g. 429'),
13
+ ),
14
+ ({ client, opts }) =>
15
+ client.logs.list(
16
+ clean({ ...pagination(opts), method: opts.method, status: toInt(opts.status, '--status') }),
17
+ ),
18
+ );
19
+
20
+ act(leaf(logs, 'get <id>', 'Retrieve a log entry'), ({ client, args: [id] }) => client.logs.get(id));
21
+ }
22
+
23
+ module.exports = { register };
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ const { withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const polls = group('polls', 'Read in-email poll results');
7
+
8
+ act(
9
+ withPagination(leaf(polls, 'list', 'One summary row per email with poll responses')),
10
+ ({ client, opts }) => client.polls.list(pagination(opts)),
11
+ );
12
+
13
+ act(
14
+ leaf(polls, 'get <emailId>', 'Aggregated answer breakdown for one email'),
15
+ ({ client, args: [emailId] }) => client.polls.get(emailId),
16
+ );
17
+ }
18
+
19
+ module.exports = { register };
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ const { parseJson, clean, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const segments = group('segments', 'Manage contact segments (scoped to a sending domain)');
7
+
8
+ act(
9
+ leaf(segments, 'create', 'Create a segment on a sending domain')
10
+ .requiredOption('--domain <domain>', 'the sending domain this segment belongs to')
11
+ .requiredOption('--name <name>', 'segment name (unique within the domain)')
12
+ .option('--filter <json>', "filter as JSON, e.g. '{\"status\":\"subscribed\"}'"),
13
+ ({ client, opts }) =>
14
+ client.segments.create(
15
+ clean({ domain: opts.domain, name: opts.name, filter: parseJson(opts.filter, '--filter') }),
16
+ ),
17
+ );
18
+
19
+ act(
20
+ withPagination(
21
+ leaf(segments, 'list', "List a domain's segments").requiredOption(
22
+ '--domain <domain>',
23
+ 'the sending domain whose segments to list',
24
+ ),
25
+ ),
26
+ ({ client, opts }) => client.segments.list({ domain: opts.domain, ...pagination(opts) }),
27
+ );
28
+
29
+ act(leaf(segments, 'get <id>', 'Retrieve a segment'), ({ client, args: [id] }) =>
30
+ client.segments.get(id),
31
+ );
32
+
33
+ act(
34
+ withPagination(leaf(segments, 'contacts <id>', 'Preview the contacts a segment currently resolves to')),
35
+ ({ client, opts, args: [id] }) => client.segments.contacts(id, pagination(opts)),
36
+ );
37
+
38
+ act(
39
+ leaf(segments, 'update <id>', 'Update a segment')
40
+ .option('--name <name>', 'new name')
41
+ .option('--filter <json>', 'new filter as JSON'),
42
+ ({ client, opts, args: [id] }) =>
43
+ client.segments.update(id, clean({ name: opts.name, filter: parseJson(opts.filter, '--filter') })),
44
+ );
45
+
46
+ act(leaf(segments, 'delete <id>', 'Delete a segment'), ({ client, args: [id] }) =>
47
+ client.segments.remove(id),
48
+ );
49
+ }
50
+
51
+ module.exports = { register };