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,46 @@
1
+ 'use strict';
2
+
3
+ const { clean, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const audiences = group('audiences', 'Manage audiences');
7
+
8
+ act(
9
+ leaf(audiences, 'create', 'Create an audience').requiredOption('--name <name>', 'audience name'),
10
+ ({ client, opts }) => client.audiences.create({ name: opts.name }),
11
+ );
12
+
13
+ act(withPagination(leaf(audiences, 'list', 'List audiences')), ({ client, opts }) =>
14
+ client.audiences.list(pagination(opts)),
15
+ );
16
+
17
+ act(leaf(audiences, 'get <id>', 'Retrieve an audience'), ({ client, args: [id] }) =>
18
+ client.audiences.get(id),
19
+ );
20
+
21
+ act(
22
+ leaf(audiences, 'update <id>', 'Rename an audience').requiredOption('--name <name>', 'new name'),
23
+ ({ client, opts, args: [id] }) => client.audiences.update(id, { name: opts.name }),
24
+ );
25
+
26
+ act(leaf(audiences, 'delete <id>', 'Delete an audience'), ({ client, args: [id] }) =>
27
+ client.audiences.remove(id),
28
+ );
29
+
30
+ act(
31
+ leaf(
32
+ audiences,
33
+ 'import-sheet <audienceId>',
34
+ 'Import contacts from a link-shared Google Sheet (rows land in a fresh segment)',
35
+ )
36
+ .requiredOption('--url <url>', 'link-shared Google Sheet URL')
37
+ .option('--segment-name <name>', 'name for the created segment'),
38
+ ({ client, opts, args: [audienceId] }) =>
39
+ client.audiences.importSheet(
40
+ audienceId,
41
+ clean({ url: opts.url, segment_name: opts.segmentName }),
42
+ ),
43
+ );
44
+ }
45
+
46
+ module.exports = { register };
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ const { collect, parseJson, clean, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const automations = group('automations', 'Manage automations (scoped to a sending domain)');
7
+
8
+ act(
9
+ leaf(automations, 'create', 'Create an automation')
10
+ .requiredOption('--name <name>', 'automation name')
11
+ .requiredOption('--domain <domain>', 'the sending domain this automation belongs to')
12
+ .option(
13
+ '--trigger <event>',
14
+ "trigger event, e.g. 'contact.created', 'senddart:schedule' (requires --trigger-at/--trigger-timezone), or a custom event name",
15
+ )
16
+ .option('--trigger-at <iso>', "ISO 8601 instant the 'senddart:schedule' trigger fires (with --trigger-timezone)")
17
+ .option('--trigger-timezone <tz>', "IANA timezone the schedule was picked in, e.g. 'America/New_York'")
18
+ .option('--status <status>', "'enabled' | 'disabled' (default: disabled)"),
19
+ ({ client, opts }) =>
20
+ client.automations.create(
21
+ clean({
22
+ name: opts.name,
23
+ domain: opts.domain,
24
+ trigger: opts.trigger,
25
+ trigger_config:
26
+ opts.triggerAt || opts.triggerTimezone
27
+ ? clean({ at: opts.triggerAt, timezone: opts.triggerTimezone })
28
+ : undefined,
29
+ status: opts.status,
30
+ }),
31
+ ),
32
+ );
33
+
34
+ act(leaf(automations, 'get <id>', 'Retrieve an automation'), ({ client, args: [id] }) =>
35
+ client.automations.get(id),
36
+ );
37
+
38
+ act(withPagination(leaf(automations, 'list', 'List automations')), ({ client, opts }) =>
39
+ client.automations.list(pagination(opts)),
40
+ );
41
+
42
+ act(
43
+ leaf(automations, 'update <id>', 'Update an automation')
44
+ .option('--name <name>', 'new name')
45
+ .option('--status <status>', "'enabled' | 'disabled'")
46
+ .option('--trigger-at <iso>', "update the 'senddart:schedule' trigger's ISO 8601 fire time (with --trigger-timezone)")
47
+ .option('--trigger-timezone <tz>', "IANA timezone the schedule was picked in, e.g. 'America/New_York'"),
48
+ ({ client, opts, args: [id] }) =>
49
+ client.automations.update(
50
+ id,
51
+ clean({
52
+ name: opts.name,
53
+ status: opts.status,
54
+ trigger_config:
55
+ opts.triggerAt || opts.triggerTimezone
56
+ ? clean({ at: opts.triggerAt, timezone: opts.triggerTimezone })
57
+ : undefined,
58
+ }),
59
+ ),
60
+ );
61
+
62
+ act(
63
+ leaf(automations, 'add-step <id>', 'Append a step to an automation')
64
+ .requiredOption(
65
+ '--type <type>',
66
+ "step type: 'send_email' | 'wait_for_event' | 'delay' | 'condition' | 'split' | 'add_to_segment' | 'contact_update' | 'contact_delete'",
67
+ )
68
+ .option('--config <json>', "step config as JSON, e.g. '{\"template_id\":\"tmpl_x\"}'")
69
+ .option('--key <key>', 'step key (for connections)'),
70
+ ({ client, opts, args: [id] }) =>
71
+ client.automations.addStep(
72
+ id,
73
+ clean({ type: opts.type, config: parseJson(opts.config, '--config'), key: opts.key }),
74
+ ),
75
+ );
76
+
77
+ // PATCH /automations/:id/steps/:stepId re-validates the WHOLE step through the
78
+ // same validateStep the create path uses, so `--type` is required here too: a
79
+ // body without it fails `type must be one of: …` (422) before the config is
80
+ // ever looked at. It was optional, which made `update-step … --config …` — the
81
+ // form the docs showed — a request that could never succeed.
82
+ //
83
+ // `--key` is deliberately absent: the server updates a step's type and config
84
+ // only (the graph key and position are stable), so a `key` in the body was
85
+ // accepted and silently dropped, leaving the caller believing the step had
86
+ // been re-keyed and its connections re-pointed. Delete and re-add the step
87
+ // with `add-step --key` to change its key.
88
+ act(
89
+ leaf(automations, 'update-step <id> <stepId>', 'Update a step of an automation')
90
+ .requiredOption(
91
+ '--type <type>',
92
+ "step type: 'send_email' | 'wait_for_event' | 'delay' | 'condition' | 'split' | 'add_to_segment' | 'contact_update' | 'contact_delete'",
93
+ )
94
+ .option('--config <json>', 'new step config as JSON (replaces the stored config)'),
95
+ ({ client, opts, args: [id, stepId] }) =>
96
+ client.automations.updateStep(
97
+ id,
98
+ stepId,
99
+ clean({ type: opts.type, config: parseJson(opts.config, '--config') }),
100
+ ),
101
+ );
102
+
103
+ act(
104
+ leaf(automations, 'delete-step <id> <stepId>', 'Delete a step from an automation'),
105
+ ({ client, args: [id, stepId] }) => client.automations.deleteStep(id, stepId),
106
+ );
107
+
108
+ act(
109
+ withPagination(leaf(automations, 'runs <id>', "List an automation's runs, newest first")).option(
110
+ '--status <status>',
111
+ "keep only runs in these statuses: 'running' | 'completed' | 'failed' | 'skipped' (repeatable or comma-separated); filtering happens before paging",
112
+ collect,
113
+ ),
114
+ ({ client, opts, args: [id] }) =>
115
+ client.automations.runs(id, clean({ ...pagination(opts), status: opts.status })),
116
+ );
117
+
118
+ act(
119
+ leaf(automations, 'run <id> <runId>', 'Retrieve a single automation run'),
120
+ ({ client, args: [id, runId] }) => client.automations.getRun(id, runId),
121
+ );
122
+
123
+ act(
124
+ leaf(automations, 'stop <id>', 'Stop an automation (in-progress runs finish)'),
125
+ ({ client, args: [id] }) => client.automations.stop(id),
126
+ );
127
+
128
+ act(
129
+ leaf(automations, 'ai <id>', 'Author (or extend) the step graph from a natural-language prompt')
130
+ .requiredOption('--prompt <text>', 'what the automation should do (max 2000 characters)')
131
+ .option('--template-id <id>', 'a template the plan may send (repeatable or comma-separated; first 10 used)', collect)
132
+ .option('--event <name>', 'an event name the plan may wait on (repeatable or comma-separated; first 10 used)', collect)
133
+ .option('--attach-from <key>', 'extend an existing graph from this trigger key or step key instead of authoring a whole workflow')
134
+ .option('--attach-type <type>', "connection type: 'default' (default) | 'condition_met' | 'condition_not_met' | 'event_received' | 'timeout'")
135
+ .option('--attach-before <key>', 'insert before this existing step key'),
136
+ ({ client, opts, args: [id] }) =>
137
+ client.automations.createWithAi(
138
+ id,
139
+ clean({
140
+ prompt: opts.prompt,
141
+ template_ids: opts.templateId,
142
+ events: opts.event,
143
+ // Presence of `attach` is what switches the API from workflow mode to
144
+ // append mode, so only build it when the user named a source step.
145
+ attach: opts.attachFrom
146
+ ? clean({ from: opts.attachFrom, type: opts.attachType, before: opts.attachBefore })
147
+ : undefined,
148
+ }),
149
+ ),
150
+ );
151
+
152
+ act(leaf(automations, 'delete <id>', 'Delete an automation'), ({ client, args: [id] }) =>
153
+ client.automations.remove(id),
154
+ );
155
+ }
156
+
157
+ module.exports = { register };
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+
3
+ const { collect, parseJson, clean, toInt, withPagination, pagination } = require('../helpers');
4
+
5
+ /** Flags shared by `campaigns create` and `campaigns update`. */
6
+ function withCampaignBodyFlags(cmd) {
7
+ return cmd
8
+ .option('--reply-to <address>', 'reply-to address (repeatable or comma-separated)', collect)
9
+ .option('--preview-text <text>', 'inbox preview text (max 150 characters)')
10
+ .option('--schedule-timezone <tz>', "IANA timezone the schedule + daily batching are evaluated in, e.g. 'America/New_York'")
11
+ .option('--daily-batch-size <n>', 'max recipients fanned out per batch-day (1-100000)')
12
+ .option('--unsubscribe-policy <policy>', "'account' (default) | 'domain' | 'ignore'")
13
+ .option('--list-to', 'show a generated mailing-list address as the visible To')
14
+ .option('--recurrence <interval>', "'daily' | 'weekly' | 'monthly'")
15
+ .option('--recurrence-every <n>', 'periods between recurring sends (1-365, default 1)')
16
+ .option('--ab-test <json>', 'A/B config as JSON, e.g. \'{"enabled":true,"subject_b":"B"}\'')
17
+ .option('--followups <json>', 'follow-ups as a JSON array (max 5) of {condition,delay,html,subject?}');
18
+ }
19
+
20
+ /** Map the shared body flags onto the API field names. */
21
+ function campaignBody(opts) {
22
+ return {
23
+ reply_to: opts.replyTo,
24
+ preview_text: opts.previewText,
25
+ schedule_timezone: opts.scheduleTimezone,
26
+ daily_batch_size: toInt(opts.dailyBatchSize, '--daily-batch-size'),
27
+ unsubscribe_policy: opts.unsubscribePolicy,
28
+ list_to: opts.listTo,
29
+ recurrence: opts.recurrence,
30
+ recurrence_every: toInt(opts.recurrenceEvery, '--recurrence-every'),
31
+ ab_test: parseJson(opts.abTest, '--ab-test'),
32
+ followups: parseJson(opts.followups, '--followups'),
33
+ };
34
+ }
35
+
36
+ function register({ group, leaf, act }) {
37
+ const campaigns = group('campaigns', "Manage campaigns (bulk sends to a domain's contact pool)");
38
+
39
+ act(
40
+ withCampaignBodyFlags(
41
+ leaf(campaigns, 'create', 'Create a draft campaign')
42
+ .requiredOption('--domain <domain>', 'the sending domain whose contact pool this campaign targets')
43
+ .requiredOption('--from <from>', "sender, e.g. 'Acme <hi@yourdomain.com>'")
44
+ .requiredOption('--subject <subject>', 'subject line')
45
+ .option('--html <html>', 'HTML body')
46
+ .option('--text <text>', 'plain-text body')
47
+ .option('--name <name>', 'internal campaign name')
48
+ .option('--segment-id <id>', 'target a segment instead of the whole pool')
49
+ .option('--topic-id <id>', 'gate recipients by a topic subscription'),
50
+ )
51
+ .option('--send', 'send (or schedule) the campaign immediately on create')
52
+ .option('--scheduled-at <when>', "with --send: ISO 8601 or a phrase like 'in 1 min' (max 30 days ahead)"),
53
+ ({ client, opts }) =>
54
+ client.campaigns.create(
55
+ clean({
56
+ domain: opts.domain,
57
+ from: opts.from,
58
+ subject: opts.subject,
59
+ html: opts.html,
60
+ text: opts.text,
61
+ name: opts.name,
62
+ segment_id: opts.segmentId,
63
+ topic_id: opts.topicId,
64
+ send: opts.send,
65
+ scheduled_at: opts.scheduledAt,
66
+ ...campaignBody(opts),
67
+ }),
68
+ ),
69
+ );
70
+
71
+ act(
72
+ leaf(campaigns, 'send <id>', 'Send a campaign now, or schedule it')
73
+ .option('--scheduled-at <when>', "ISO 8601 timestamp, or a phrase like 'in 1 min' (max 30 days ahead)")
74
+ .option('--schedule-timezone <tz>', 'IANA timezone daily batching evaluates batch-days in'),
75
+ ({ client, opts, args: [id] }) => {
76
+ const payload = clean({
77
+ scheduled_at: opts.scheduledAt,
78
+ schedule_timezone: opts.scheduleTimezone,
79
+ });
80
+ return client.campaigns.send(id, Object.keys(payload).length ? payload : undefined);
81
+ },
82
+ );
83
+
84
+ act(leaf(campaigns, 'get <id>', 'Retrieve a campaign'), ({ client, args: [id] }) =>
85
+ client.campaigns.get(id),
86
+ );
87
+
88
+ act(withPagination(leaf(campaigns, 'list', 'List campaigns')), ({ client, opts }) =>
89
+ client.campaigns.list(pagination(opts)),
90
+ );
91
+
92
+ act(
93
+ withCampaignBodyFlags(
94
+ leaf(campaigns, 'update <id>', 'Update a draft campaign')
95
+ .option('--domain <domain>', 're-target another sending domain (clears segment and topic)')
96
+ .option('--from <from>', 'sender')
97
+ .option('--subject <subject>', 'subject line')
98
+ .option('--html <html>', 'HTML body')
99
+ .option('--text <text>', 'plain-text body')
100
+ .option('--name <name>', 'internal campaign name')
101
+ .option('--segment-id <id>', 're-target a segment')
102
+ .option('--topic-id <id>', 're-target a topic gate'),
103
+ ),
104
+ ({ client, opts, args: [id] }) =>
105
+ client.campaigns.update(
106
+ id,
107
+ clean({
108
+ domain: opts.domain,
109
+ from: opts.from,
110
+ subject: opts.subject,
111
+ html: opts.html,
112
+ text: opts.text,
113
+ name: opts.name,
114
+ segment_id: opts.segmentId,
115
+ topic_id: opts.topicId,
116
+ ...campaignBody(opts),
117
+ }),
118
+ ),
119
+ );
120
+
121
+ act(
122
+ leaf(
123
+ campaigns,
124
+ 'cancel <id>',
125
+ 'Stop a campaign (back to draft, or terminal canceled if it is already queued)',
126
+ ),
127
+ ({ client, args: [id] }) => client.campaigns.cancel(id),
128
+ );
129
+
130
+ act(leaf(campaigns, 'stats <id>', 'Per-campaign analytics'), ({ client, args: [id] }) =>
131
+ client.campaigns.stats(id),
132
+ );
133
+
134
+ act(
135
+ leaf(
136
+ campaigns,
137
+ 'engagement <id>',
138
+ 'Who opened, clicked and replied (not paginated; each list is capped at 500 rows)',
139
+ ),
140
+ ({ client, args: [id] }) => client.campaigns.engagement(id),
141
+ );
142
+
143
+ act(
144
+ leaf(campaigns, 'ab <id>', 'A/B winner evaluation for an A/B campaign'),
145
+ ({ client, args: [id] }) => client.campaigns.ab(id),
146
+ );
147
+
148
+ act(leaf(campaigns, 'delete <id>', 'Delete a campaign'), ({ client, args: [id] }) =>
149
+ client.campaigns.remove(id),
150
+ );
151
+ }
152
+
153
+ module.exports = { register };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const { CliError, clean, withPagination, pagination } = require('../helpers');
4
+
5
+ function register({ group, leaf, act }) {
6
+ const props = group('contact-properties', 'Manage custom contact properties (merge-tag keys)');
7
+
8
+ act(
9
+ leaf(props, 'create', 'Create a contact property')
10
+ .requiredOption('--key <key>', "canonical merge-tag key, e.g. 'company'")
11
+ .requiredOption('--type <type>', "value type: 'string' | 'number'")
12
+ .option('--fallback-value <value>', 'value used when a contact has none'),
13
+ ({ client, opts }) =>
14
+ client.contactProperties.create(
15
+ clean({ key: opts.key, type: opts.type, fallback_value: opts.fallbackValue }),
16
+ ),
17
+ );
18
+
19
+ act(withPagination(leaf(props, 'list', 'List contact properties')), ({ client, opts }) =>
20
+ client.contactProperties.list(pagination(opts)),
21
+ );
22
+
23
+ act(leaf(props, 'get <id>', 'Retrieve a contact property'), ({ client, args: [id] }) =>
24
+ client.contactProperties.get(id),
25
+ );
26
+
27
+ act(
28
+ leaf(props, 'update <id>', 'Update a contact property (only the fallback is mutable)')
29
+ .option('--fallback-value <value>', 'new fallback value')
30
+ .option('--clear-fallback', 'clear the fallback (sets it to null)'),
31
+ ({ client, opts, args: [id] }) => {
32
+ if (opts.clearFallback && opts.fallbackValue !== undefined) {
33
+ throw new CliError('Provide only one of --fallback-value or --clear-fallback.');
34
+ }
35
+ if (!opts.clearFallback && opts.fallbackValue === undefined) {
36
+ throw new CliError('Provide --fallback-value <value> or --clear-fallback.');
37
+ }
38
+ return client.contactProperties.update(id, {
39
+ fallback_value: opts.clearFallback ? null : opts.fallbackValue,
40
+ });
41
+ },
42
+ );
43
+
44
+ act(leaf(props, 'delete <id>', 'Delete a contact property'), ({ client, args: [id] }) =>
45
+ client.contactProperties.remove(id),
46
+ );
47
+ }
48
+
49
+ module.exports = { register };
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { CliError, parseJson, clean, withPagination, pagination } = require('../helpers');
6
+
7
+ /**
8
+ * A contact lives either in a sending domain's pool (`--domain`, the
9
+ * domain-first default) or in a plain audience (`--audience-id`, the nested
10
+ * `/audiences/:id/contacts` API). Exactly one of the two names the container.
11
+ */
12
+ function requireContainer(opts) {
13
+ if (opts.domain && opts.audienceId) {
14
+ throw new CliError('Provide only one of --domain or --audience-id.');
15
+ }
16
+ if (!opts.domain && !opts.audienceId) {
17
+ throw new CliError('Provide --domain <domain> (or --audience-id <id> to target an audience).');
18
+ }
19
+ }
20
+
21
+ function register({ group, leaf, act }) {
22
+ const contacts = group('contacts', 'Manage contacts (domain-first: each sending domain has its own pool)');
23
+
24
+ act(
25
+ leaf(contacts, 'create', "Create a contact in a domain's pool")
26
+ .option('--domain <domain>', 'the sending domain whose contact pool to use')
27
+ .option('--audience-id <id>', 'create in this audience instead of a domain pool')
28
+ .requiredOption('--email <email>', "the contact's email address")
29
+ .option('--first-name <name>', 'first name')
30
+ .option('--last-name <name>', 'last name')
31
+ .option('--unsubscribed', 'create as unsubscribed')
32
+ .option('--properties <json>', 'custom property values as a JSON object'),
33
+ ({ client, opts }) => {
34
+ requireContainer(opts);
35
+ return client.contacts.create(
36
+ clean({
37
+ domain: opts.domain,
38
+ audienceId: opts.audienceId,
39
+ email: opts.email,
40
+ first_name: opts.firstName,
41
+ last_name: opts.lastName,
42
+ unsubscribed: opts.unsubscribed,
43
+ properties: parseJson(opts.properties, '--properties'),
44
+ }),
45
+ );
46
+ },
47
+ );
48
+
49
+ act(
50
+ withPagination(
51
+ leaf(contacts, 'list', "List a domain's contacts")
52
+ .option('--domain <domain>', 'the sending domain whose contact pool to list')
53
+ .option('--audience-id <id>', 'list this audience instead of a domain pool')
54
+ .option('--segment-id <id>', 'only contacts in this segment'),
55
+ ),
56
+ ({ client, opts }) => {
57
+ requireContainer(opts);
58
+ return client.contacts.list(
59
+ clean({
60
+ domain: opts.domain,
61
+ audienceId: opts.audienceId,
62
+ segment_id: opts.segmentId,
63
+ ...pagination(opts),
64
+ }),
65
+ );
66
+ },
67
+ );
68
+
69
+ act(
70
+ leaf(contacts, 'get <id>', 'Retrieve a contact by id or email').option(
71
+ '--domain <domain>',
72
+ 'disambiguates an email id across domain pools',
73
+ ),
74
+ ({ client, opts, args: [id] }) => client.contacts.get(clean({ id, domain: opts.domain })),
75
+ );
76
+
77
+ act(
78
+ leaf(contacts, 'update <id>', 'Update a contact (id or email)')
79
+ .option('--domain <domain>', 'disambiguates an email id across domain pools')
80
+ .option('--first-name <name>', 'first name')
81
+ .option('--last-name <name>', 'last name')
82
+ .option('--unsubscribed', 'mark unsubscribed')
83
+ .option('--subscribed', 'mark subscribed again')
84
+ .option('--properties <json>', 'custom property values as a JSON object'),
85
+ ({ client, opts, args: [id] }) => {
86
+ // Contradictory consent flags used to resolve silently in favour of
87
+ // --unsubscribed, which could write the OPPOSITE of what the operator
88
+ // meant onto a subscription state. Refuse, like every other mutually
89
+ // exclusive pair in this CLI.
90
+ if (opts.unsubscribed && opts.subscribed) {
91
+ throw new CliError('Provide only one of --unsubscribed or --subscribed.');
92
+ }
93
+ return client.contacts.update(
94
+ clean({
95
+ id,
96
+ domain: opts.domain,
97
+ first_name: opts.firstName,
98
+ last_name: opts.lastName,
99
+ unsubscribed: opts.unsubscribed ? true : opts.subscribed ? false : undefined,
100
+ properties: parseJson(opts.properties, '--properties'),
101
+ }),
102
+ );
103
+ },
104
+ );
105
+
106
+ act(
107
+ leaf(contacts, 'delete <id>', 'Delete a contact (id or email)').option(
108
+ '--domain <domain>',
109
+ 'disambiguates an email id across domain pools',
110
+ ),
111
+ ({ client, opts, args: [id] }) => client.contacts.remove(clean({ id, domain: opts.domain })),
112
+ );
113
+
114
+ act(
115
+ leaf(contacts, 'add-to-segment <id> <segmentId>', 'Add a contact to a segment'),
116
+ ({ client, args: [id, segmentId] }) => client.contacts.addToSegment(id, segmentId),
117
+ );
118
+
119
+ act(
120
+ withPagination(leaf(contacts, 'segments <id>', 'List the segments a contact belongs to')),
121
+ ({ client, opts, args: [id] }) => client.contacts.listSegments(id, pagination(opts)),
122
+ );
123
+
124
+ act(
125
+ leaf(contacts, 'remove-from-segment <id> <segmentId>', 'Remove a contact from a segment'),
126
+ ({ client, args: [id, segmentId] }) => client.contacts.removeFromSegment(id, segmentId),
127
+ );
128
+
129
+ act(
130
+ withPagination(leaf(contacts, 'topics <id>', "Get a contact's topic subscriptions")),
131
+ ({ client, opts, args: [id] }) => client.contacts.getTopics(id, pagination(opts)),
132
+ );
133
+
134
+ act(
135
+ leaf(contacts, 'set-topics <id>', "Update a contact's topic subscriptions").requiredOption(
136
+ '--topics <json>',
137
+ 'JSON array of {"id","subscription"} objects, e.g. \'[{"id":"top_1","subscription":"opt_in"}]\'',
138
+ ),
139
+ ({ client, opts, args: [id] }) =>
140
+ client.contacts.updateTopics(id, { topics: parseJson(opts.topics, '--topics') }),
141
+ );
142
+
143
+ // Bulk import — from a JSON array of contacts, or a CSV file (SDK-3).
144
+ act(
145
+ leaf(contacts, 'batch [audienceId]', 'Bulk-import contacts from a JSON array (upsert by email; max 10,000)')
146
+ .option('--domain <domain>', "the sending domain whose contact pool to import into (instead of an audience)")
147
+ .option('--audience-id <id>', 'target this audience instead of a domain pool (same as the positional)')
148
+ .option('--file <path>', 'path to a JSON file containing an array of contact objects')
149
+ .option('--data <json>', 'inline JSON array of contact objects')
150
+ .option('--on-conflict <mode>', "how to resolve an existing email: 'upsert' (default) or 'skip'"),
151
+ ({ client, opts, args: [audienceId] }) => {
152
+ // The audience arrives as a positional (backwards compatibility) or as
153
+ // the --audience-id flag every sibling command carries — and which this
154
+ // command's own missing-target error suggests, so it must exist here.
155
+ requireContainer({ domain: opts.domain, audienceId: audienceId || opts.audienceId });
156
+ if (opts.file && opts.data) throw new CliError('Provide only one of --file or --data.');
157
+ if (!opts.file && !opts.data) throw new CliError('Provide --file <path> or --data <json array>.');
158
+ let contactsArr;
159
+ if (opts.file) {
160
+ let raw;
161
+ try { raw = fs.readFileSync(opts.file, 'utf8'); }
162
+ catch (err) { throw new CliError(`Cannot read --file ${opts.file}: ${err.message}`); }
163
+ contactsArr = parseJson(raw, `--file ${opts.file}`);
164
+ } else {
165
+ contactsArr = parseJson(opts.data, '--data');
166
+ }
167
+ if (!Array.isArray(contactsArr)) throw new CliError('The contacts payload must be a JSON array.');
168
+ return client.contacts.batch(clean({
169
+ domain: opts.domain,
170
+ audienceId: audienceId || opts.audienceId,
171
+ contacts: contactsArr,
172
+ on_conflict: opts.onConflict,
173
+ }));
174
+ },
175
+ );
176
+
177
+ act(
178
+ leaf(contacts, 'import <audienceId>', 'Bulk-import contacts from a CSV file (email column required; header row optional)')
179
+ .option('--csv <path>', 'path to a CSV file to send inline (max 5 MB / 10,000 rows)')
180
+ .option('--storage-key <key>', 'key from `contacts import-upload`, once the file has been PUT to its upload URL')
181
+ .option('--file-name <name>', 'name recorded for the archived source file (inline --csv mode)')
182
+ .option('--segment-id <id>', 'also add every imported email to this segment (must belong to the audience)')
183
+ .option('--on-conflict <mode>', "how to resolve an existing email: 'upsert' (default) or 'skip'")
184
+ .option('--no-create-properties', 'strict mode: keep only columns matching a registered property'),
185
+ ({ client, opts, args: [audienceId] }) => {
186
+ if (opts.csv && opts.storageKey) {
187
+ throw new CliError('Provide only one of --csv or --storage-key.');
188
+ }
189
+ if (!opts.csv && !opts.storageKey) {
190
+ throw new CliError('Provide --csv <path> (or --storage-key <key> for an already-uploaded file).');
191
+ }
192
+ let csv;
193
+ if (opts.csv) {
194
+ try { csv = fs.readFileSync(opts.csv, 'utf8'); }
195
+ catch (err) { throw new CliError(`Cannot read --csv ${opts.csv}: ${err.message}`); }
196
+ }
197
+ // commander sets opts.createProperties=false for --no-create-properties (default true).
198
+ return client.contacts.import(clean({
199
+ audienceId, csv, storage_key: opts.storageKey, file_name: opts.fileName,
200
+ segment_id: opts.segmentId, on_conflict: opts.onConflict,
201
+ create_properties: opts.createProperties === false ? false : undefined,
202
+ }));
203
+ },
204
+ );
205
+
206
+ act(
207
+ leaf(
208
+ contacts,
209
+ 'import-upload <audienceId>',
210
+ 'Mint a presigned upload URL for a CSV too large to send inline (up to 256 MB)',
211
+ ).requiredOption('--csv <path>', 'path to the CSV file to upload (its name and size are sent, not its contents)'),
212
+ ({ client, opts, args: [audienceId] }) => {
213
+ let stat;
214
+ try { stat = fs.statSync(opts.csv); }
215
+ catch (err) { throw new CliError(`Cannot read --csv ${opts.csv}: ${err.message}`); }
216
+ // PUT the file to the returned `upload_url`, then finish the import with
217
+ // `contacts import <audienceId> --storage-key <storage_key>`.
218
+ return client.contacts.createImportUpload({
219
+ audienceId,
220
+ filename: path.basename(opts.csv),
221
+ size: stat.size,
222
+ });
223
+ },
224
+ );
225
+ }
226
+
227
+ module.exports = { register };