diff --git a/README.md b/README.md index 0f5bac3..ab3cee6 100644 --- a/README.md +++ b/README.md @@ -198,10 +198,14 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply contact update ( \| ) --fields -` | change some fields and custom fields; null clears one → `updated` | | `reply contact delete ` | → `deleted` | | `reply contact opt-out ` | → `opted_out` | -| `reply contact send-email --email-account-id N --message -` | one email now, outside any sequence → `sent` | +| `reply contact send-email --email-account-id N --message - [--track-links] [--track-opens]` | one email outside any sequence → `sent` | | `reply contact linkedin-connect --linkedin-account-id N [--message -]` | a LinkedIn invitation, with or without a note → `sent` / `already_connected` | | `reply contact linkedin-message …` · `linkedin-inmail …` · `linkedin-voice …` | a LinkedIn message, an InMail, or an AI voice message spoken from a script → `sent` | +| any direct send `… [--send-after ] [--schedule-id N] [--idempotency-key K]` | the send held until a moment, timed by a schedule, under a key of yours → `sent`, with its `reference` and `state` | +| `reply direct-send get ` | a send as Reply holds it: whether it has gone out, when, and why it failed | +| `reply direct-send cancel ` | stop a send that has not gone out yet → `state` `cancelled` | | `reply inbox list (--contact-id \| --sequence-id) [--source] [--channel] [--category-id] [--since]` | one page of threads | +| `reply inbox changes [--cursor … \| --since …] [--top N]` | one page of the inbox feed, read forward by cursor | | `reply inbox get ` | a thread with its subject, and one page of its messages | | `reply inbox reply --message -` | reply in the thread, on its own channel → `sent` | | `reply inbox categories` | the categories a thread can be filed under | @@ -304,6 +308,79 @@ lengths Reply publishes (a LinkedIn message's 8000 characters, an InMail's 200 a 1000) are refused before anything is sent. Reply reads `{{…}}` in a LinkedIn text as its template variables, and refuses one it cannot fill with `linkedin.missing_variables`. +`contact send-email` tracks neither links nor opens unless `--track-links` or `--track-opens` asks +it to. An email Reply sends within the request adds `rendered_subject` and `rendered_body`, the text +as Reply filled it in, when Reply gives them; a send held for later has neither. A template variable +Reply cannot fill is `contact.missing_variables`, with the names under the error's +`details.missing_variables` when Reply lists them, and a template Reply cannot render is +`contact.rendering_failed`, with Reply's message as its `detail`. Neither sends anything: + +```sh +# {"error":{"code":"contact.missing_variables",…,"details":{"missing_variables":["FirstName","Company"]}}} +``` + +Every direct send also takes `--send-after `, `--schedule-id ` and `--idempotency-key +`. Reply holds the send until the moment, given with its offset (`2026-11-03T14:00:00Z`, +`2026-11-03T16:00:00+02:00`) and sent to Reply in UTC; a moment without an offset is refused +(`usage.date`). `--schedule-id` names the sending schedule Reply times the send by (see `reply +schedule list`). The answer then adds Reply's `reference`, `send_after` and `state`, each only when +Reply gives it. `status: "sent"` means Reply took the send, and `state`, when present, says whether +it has gone out: `queued` or `sending` is not yet, then `sent`, `failed` or `cancelled`. `reply +direct-send get ` reads the send later, and `reply direct-send cancel ` stops +one that has not gone out. The reference is Reply's, `email-` or `linkedin-`, the form +Reply's route takes: a reference of any other form is refused before any call (`usage.reference`, +exit 2), and nothing else is read from it. An answer without `state` comes from a Reply that does +not know these flags yet: it sent at once, as without them. + +`--idempotency-key` goes to Reply as the `Idempotency-Key` header, never in the body. A Reply that +knows the header answers a repeat with the same key with the send the key first made; while that +one is still being made the answer is `idempotency_key.in_use`, and the same key on a different +send is `idempotency_key.reused`. Neither sends anything. A repeat of a send given a person's +fields (`--contact -`) answers `contact.already_held` first, since the first one created the +contact: that is safe too, as nothing is sent twice. `idempotency_key.reused` names the send the +key was first taken for under the error's `details`: its `reference`, `state` and `send_after`, +each only when Reply gives it. Any other refusal of a send Reply already holds, an email that +failed after Reply made its row for example, names that send the same way, beside the refusal's +own details such as `missing_variables`; its code is the refusal's own. A key is 1 to 255 +printable ASCII characters; a space inside is kept, and one at either end is refused +(`usage.idempotency_key`), since a header loses it on the way out. + +```sh +echo '{"body":"Following up on my note."}' | reply contact linkedin-message --contact-id 456 --linkedin-account-id 34 --message - --send-after 2026-11-03T14:00:00Z --idempotency-key follow-up-456-1 +# {"status":"sent",…,"reference":"linkedin-1042","send_after":"2026-11-03T14:00:00Z","state":"queued"} +reply direct-send get linkedin-1042 +reply direct-send cancel linkedin-1042 +``` + +Both answer the send under the CLI's names, each null when Reply gives none: `reference`, +`channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason` and +`cancelled_at`. `failure_code`, `missing_variables`, `rendered_subject` and `rendered_body` are +added only when Reply gives them. `failure_reason` is a sentence for a person and never parsed; +`failure_code` is Reply's code for the failure, the one to branch on. `direct-send cancel` of a send already cancelled answers it +again. A send already gone out or failed is `direct_send.already_sent` or +`direct_send.already_failed`, and a reference Reply has no send for is `direct_send.not_found`. + +`reply inbox changes` reads the inbox feed forward. Each page holds the threads whose latest message, +inbound or outbound, changed, oldest first and as Reply gives them, with `has_more` and a `cursor`. +Start with `--since ` (inclusive, at most 30 days ago) or with neither flag, which reads the +last 30 days, then pass the answered cursor back with `--cursor` while `has_more` is true. Loop on +`has_more`, not on the number of items: an empty page still carries a cursor, and when `has_more` is +false that cursor is where the next read starts. A cursor or a `--since` older than the 30 days the +feed keeps is `inbox.cursor_expired`: start again with `--since`. A cursor Reply will not read +otherwise, unreadable or ahead of its clock, is `inbox.cursor_refused`, with `cursor` in +`details.fields`; start again the same way. + +```sh +reply inbox changes --since 2026-11-01T00:00:00Z --json +# {"items":[{"threadId":9876,"contactId":456,"channel":"email","lastActivityDate":"2026-11-03T14:02:11Z",…}], +# "has_more":true,"cursor":"AQjfObhYHZgAAADjVg"} +reply inbox changes --cursor AQjfObhYHZgAAADjVg --json +``` + +A Reply that does not have `direct-send get`, `direct-send cancel` or the feed yet answers +`reply.refused` with status 404 and no `reply_code`. A reference of any other form never leaves the +CLI, so on the two `direct-send` commands that 404 means this Reply has no such route. + `reply schedule list` gives every sending schedule the account can use, in one answer and in the order Reply gives them: its `time_zone_id` as Reply holds it, a Windows time zone identifier such as `Eastern Standard Time`, whether it reads its windows in each recipient's own time zone, whether it @@ -324,9 +401,12 @@ reply schedule list --json `inbox reply`, `sequence create` and the five direct sends are the work commands that are not safe to re-run. On exit 3 (outcome unknown) a reply or a send may already have gone, and running it again may -send it twice, unless the hint says nothing was sent: a send whose contact's import lost its answer -was never made, and its hint says so; run again, it answers `contact.already_held` if that import did -create the contact. +send it twice, unless the hint says nothing was sent. A direct send's exit 3 comes from a lost +answer, a 5xx, or a 400 to the send whose JSON carries neither a `code` nor `errors[]`, which is +Reply failing while it made the send; a 400 with `errors[]` is `reply.invalid_request` and sent +nothing. A send whose contact's import lost its answer was never made, and its hint says so; run +again, it answers `contact.already_held` if that import did create the contact. An `--idempotency-key` does not change this: a Reply that does not know the +header yet would make the send again. For `inbox reply`, read the thread with `reply inbox get` before trying again. For `sequence create`, Reply allows two sequences of one name, so after exit 3 look the name up with `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index bc3afec..5da9511 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -1,6 +1,7 @@ import {describe, it, expect} from 'vitest'; import type {Command} from 'commander'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from '../../operations/commands'; +import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, + direct_send_command} from '../../operations/commands'; const sub = (parent: Command, name: string): Command=>{ const found = parent.commands.find(c=>c.name() === name); @@ -23,9 +24,39 @@ describe('operations/commands', ()=>{ expect(contact_list_command.commands.map(c=>c.name())).toEqual(['add-contact']); expect(contact_command.commands.map(c=>c.name())).toEqual(['find', 'get', 'update', 'delete', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']); - expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); + expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'changes', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); expect(account_command.commands.map(c=>c.name())).toEqual(['list']); expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); + expect(direct_send_command.commands.map(c=>c.name())).toEqual(['get', 'cancel']); + }); + + it('direct-send get and cancel each take one reference and no flag, and list the refusals Reply gives each', ()=>{ + const expected: [string, string[], boolean][] = [ + ['get', ['direct_send.not_found', 'direct_send.not_owned'], false], + ['cancel', ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true], + ]; + for (const [name, codes, write] of expected) + { + const c = sub(direct_send_command, name); + expect(flags(c), name).toEqual([]); + expect(c.registeredArguments.map(a=>a.name()), name).toEqual(['reference']); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + expect(text, name).toContain(codes.map(code=>` ${code}\n`).join('')); + expect(text.includes('outcome.unknown'), name).toBe(write); + expect(flat, name).toContain('The reference is Reply\'s, from the answer of a send made with --send-after'); + expect(flat, name).toContain('state is Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled'); + expect(flat, name).toContain('A Reply without this route answers reply.refused with status 404 and no reply_code'); + expect(flat, name).toContain('email- or linkedin-, the form Reply\'s route takes'); + expect(flat, name).toContain('any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it'); + expect(flat, name).toContain('a reference of any other form never leaves the CLI, so that 404 means this Reply has no such route'); + expect(flat, name).not.toContain('step up'); + expect(c.registeredArguments[0].description, name).toContain('email- or linkedin-'); + expect(flat, name).toContain('failure_code, missing_variables, rendered_subject and rendered_body are added only when Reply gives them'); + expect(flat, name).toContain('failure_reason is a sentence for a person, never parsed; failure_code is Reply\'s code for the failure'); + } + expect(help_of(sub(direct_send_command, 'cancel')).replace(/\s+/g, ' ')) + .toContain('Cancelling a send already cancelled answers it again, so running it again is safe'); }); it('schedule list takes no flag and no id, and says how a time zone, a weekday, a time and a state are written', ()=>{ @@ -140,6 +171,26 @@ describe('operations/commands', ()=>{ expect(flags(sub(contact_command, 'delete'))).toEqual([]); }); + it('inbox changes takes --cursor, --since and --top, and says how the feed is read forward', ()=>{ + const c = sub(inbox_command, 'changes'); + expect(flags(c)).toEqual(['--cursor', '--since', '--top']); + expect(c.registeredArguments).toEqual([]); + const text = help_of(c); + const flat = text.replace(/\s+/g, ' '); + expect(flat, text).toContain('Result: {"items","has_more","cursor"}'); + expect(flat, text).toContain('the items as Reply gives them'); + expect(flat, text).toContain('Give --cursor or --since, not both; with neither, Reply reads the last 30 days'); + expect(flat, text).toContain('loop on has_more, not on the number of items'); + expect(flat, text).toContain('an empty page still carries a cursor'); + expect(flat, text).toContain('A cursor or a --since older than 30 days is inbox.cursor_expired: start again with --since'); + expect(flat, text).toContain('A cursor Reply will not read otherwise, unreadable or ahead of its clock, is inbox.cursor_refused'); + expect(text, text).toContain(' inbox.cursor_expired\n inbox.cursor_refused\n'); + expect(text, text).not.toContain('outcome.unknown'); + // The feed names the threads that changed, and its examples use the command's own name. + expect(text, text).toContain('inbox changes --since 2026-11-01T00:00:00Z'); + expect(text, text).not.toContain('events'); + }); + it('sequence list and create take the name only through --name -, and create says a repeat may make a second one', ()=>{ expect(flags(sub(sequence_command, 'list'))).toEqual(['--name']); const create = sub(sequence_command, 'create'); @@ -196,7 +247,8 @@ describe('operations/commands', ()=>{ 'linkedin.feature_disabled', 'linkedin.account_inactive', 'linkedin.invalid_cookie']; const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ - ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], + ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', + 'contact.missing_variables', 'contact.rendering_failed'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -221,7 +273,8 @@ describe('operations/commands', ()=>{ for (const [name, account_flag, codes, sent_at] of DIRECT_SENDS) { const c = sub(contact_command, name); - expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message']); + expect(flags(c), name).toEqual([...CONTACT_FLAGS, account_flag, '--message', + ...(name === 'send-email' ? ['--track-links', '--track-opens'] : []), '--send-after', '--schedule-id', '--idempotency-key']); const text = help_of(c); const flat = text.replace(/\s+/g, ' '); expect(text, text).toContain('--message -'); @@ -237,13 +290,42 @@ describe('operations/commands', ()=>{ expect(flat.includes('--email alone is refused (usage.contact)'), text).toBe(name !== 'send-email'); expect(flat, text).toContain(sent_at); expect(flat, text).toContain('read from stdin only'); + // A send for later: what status and state each say, and what an older Reply does with the flags. + expect(flat, text).toContain('status "sent" means Reply took the send; state, when Reply gives it, says whether it has gone ' + + 'out: queued or sending is not yet, then sent, failed or cancelled'); + expect(flat, text).toContain('direct-send get reads it later, and direct-send cancel stops one not yet sent'); + expect(flat, text).toContain('An answer without state comes from a Reply that does not know --send-after and --schedule-id'); + expect(flat, text).toContain('--idempotency-key goes as the Idempotency-Key header'); + expect(flat, text).toContain('A Reply that knows the header answers a repeat with the same key with the send the key first made; while that one is still ' + + 'being made the answer is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused'); + // Given a person's fields, a repeat finds the contact the first one created before it reaches the key. + expect(flat, text).toContain('A repeat of a send given a person\'s fields answers contact.already_held first, since the ' + + 'first one created the contact: that is safe too, as nothing is sent twice'); + expect(flat, text).toContain('idempotency_key.reused names the send the key was first taken for in details: reference, ' + + 'state and send_after, each only when Reply gives it'); + expect(flat, text).toContain('Any other refusal of a send Reply already holds names that send the same way, beside the ' + + 'refusal\'s own details; its code is the refusal\'s own'); + expect(flat, text).toContain('A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: ' + + 'like a 5xx or a lost answer, it is outcome.unknown (exit 3)'); // Exactly the codes its endpoint publishes, then the shared ones, as the help lists them. const listed = text.split('\nErrors')[1].split('\nExit codes')[0].split('\n').slice(1).map(l=>l.trim()); - expect(listed, name).toEqual([...codes, 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', + expect(listed, name).toEqual([...codes, 'idempotency_key.in_use', 'idempotency_key.reused', 'access.denied', 'access.feature_unavailable', 'rate_limited', 'reply.unavailable', 'reply.refused', 'reply.invalid_request', 'outcome.unknown']); } }); + it('send-email says tracking is off unless asked, where the unfilled variables go, and what a rendered answer adds', ()=>{ + const c = sub(contact_command, 'send-email'); + const flat = help_of(c).replace(/\s+/g, ' '); + const described = (flag: string)=>c.options.find(o=>o.long === flag)?.description; + expect(described('--track-links'), '--track-links').toContain('Track the links'); + expect(described('--track-opens'), '--track-opens').toContain('Track the opens'); + expect(flat, flat).toContain('Reply tracks neither links nor opens unless --track-links or --track-opens asks it to'); + expect(flat, flat).toContain('contact.missing_variables names the variables Reply could not fill in details.missing_variables'); + expect(flat, flat).toContain('contact.rendering_failed is a template Reply could not render, its message in detail'); + expect(flat, flat).toContain('An email sent within the request adds rendered_subject and rendered_body'); + }); + it('inbox reply takes its text only through --message, and says a repeat may send it twice', ()=>{ const reply = sub(inbox_command, 'reply'); expect(flags(reply)).toEqual(['--message']); diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 9f6272a..5f7bf35 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -275,6 +275,8 @@ describe('every direct send', ()=>{ const answers: [string, ()=>void][] = [ ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + // An exception escaping a send, on the email route and the LinkedIn ones alike. + ['500', ()=>answer(json({title: 'Internal Server Error', status: 500}, 500, {'Content-Type': 'application/problem+json'}))], ['uncoded 502', ()=>answer(json('bad gateway', 502))], ['201', ()=>answer(json({}, 201))], ['unreadable 200', ()=>answer(json('ok', 200))], @@ -526,6 +528,8 @@ describe('a direct send to a person given by their fields', ()=>{ 'contact.invalid_linkedin_url', 1], [[nobody(), nobody(), json({code: 'contact.limitExceeded', detail: 'Contact limit reached.'}, 400)], 'account.contact_limit_reached', 1], [[nobody(), nobody(), json({items: [{id: null, status: 'failed', error: 'Invalid data'}]})], 'reply.refused', 1], + // A 400 with neither a code nor errors[] is read as Reply's exception only on the send call, never on the import. + [[nobody(), nobody(), json({title: 'Bad Request', status: 400}, 400, {'Content-Type': 'application/problem+json'})], 'reply.refused', 1], ]; for (const [answers, code, exit_code] of cases) { @@ -620,3 +624,395 @@ describe('a direct send to a person given by their fields', ()=>{ } }); }); + +describe('a send for later', ()=>{ + const SENDS: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS], + ['linkedin-connect', {note: NOTE}, LINKEDIN_OPTS], + ['linkedin-message', {body: TEXT}, LINKEDIN_OPTS], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, LINKEDIN_OPTS], + ['linkedin-voice', {script: SCRIPT}, LINKEDIN_OPTS], + ]; + const LATER = {sendAfter: '2026-11-03T16:00:00+02:00', scheduleId: '41', idempotencyKey: 'send-456-step-2'}; + const headers_of = (i: number): Record=> + (mock_fetch.mock.calls[i] as [string, RequestInit])[1].headers as Record; + const accepted = (name: Direct_send_name, extra: Record)=> + json(name === 'send-email' ? {status: 'new', messageId: null, ...extra} : {linkedInActivityId: 1042, ...extra}); + + it('each send carries the moment in UTC, the schedule and the key only when given, the key as a header and never in the body', async()=>{ + for (const [name, message, opts] of SENDS) + { + mock_fetch.mockReset(); + answer(accepted(name, {}), accepted(name, {})); + await run(name, message, {...opts, ...LATER}); + const body = sent()[0].body as Record; + expect(body.sendAfter, name).toBe('2026-11-03T14:00:00.000Z'); + expect(body.scheduleId, name).toBe(41); + expect(JSON.stringify(body), name).not.toContain('send-456-step-2'); + expect(headers_of(0)['Idempotency-Key'], name).toBe('send-456-step-2'); + await run(name, message, opts); + const plain = sent()[1].body as Record; + expect('scheduleId' in plain, name).toBe(false); + expect('sendAfter' in plain, name).toBe(false); + expect('Idempotency-Key' in headers_of(1), name).toBe(false); + } + }); + + it('adds reference, send_after and state to the answer, each only when Reply gives it, and keeps status as sent', async()=>{ + answer(accepted('send-email', {reference: 'email-1001', sendAfter: '2026-11-03T14:00:00Z', state: 'queued'})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER})).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', + reference: 'email-1001', send_after: '2026-11-03T14:00:00Z', state: 'queued', + }); + mock_fetch.mockReset(); + answer(accepted('linkedin-message', {reference: 'linkedin-1042', state: 'sending', sendAfter: null})); + expect(await run('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: null, + reference: 'linkedin-1042', state: 'sending', + }); + }); + + it('adds the rendered subject and body of an email sent inside the request, each only when Reply gives it', async()=>{ + answer(accepted('send-email', {renderedSubject: 'Quick question, Marta', renderedBody: '

Hi Marta

', state: 'sent'})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS)).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, message_id: null, sent_at: null, reply_status: 'new', + state: 'sent', rendered_subject: 'Quick question, Marta', rendered_body: '

Hi Marta

', + }); + mock_fetch.mockReset(); + answer(accepted('send-email', {reference: 'email-1001', state: 'queued', renderedSubject: null})); + expect(await run('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER})).not.toHaveProperty('rendered_subject'); + }); + + it('an answer without them prints exactly what it prints today, even when the flags were given', async()=>{ + answer(accepted('linkedin-voice', {sentAtUtc: '2026-10-19T10:30:00Z'})); + expect(await run('linkedin-voice', {script: SCRIPT}, {...LINKEDIN_OPTS, ...LATER})).toStrictEqual({ + status: 'sent', contact_id: 456, contact_created: false, activity_id: 1042, sent_at: '2026-10-19T10:30:00Z', + }); + }); + + it('refuses a moment without its offset, a schedule id that is not one and a key Reply cannot take, before any call', async()=>{ + const cases: [Partial, string][] = [ + [{sendAfter: '2026-11-03T14:00:00'}, 'usage.date'], + [{sendAfter: '2026-11-03'}, 'usage.date'], + [{scheduleId: '0'}, 'usage.id'], + [{scheduleId: 'business'}, 'usage.id'], + [{idempotencyKey: ''}, 'usage.idempotency_key'], + [{idempotencyKey: 'k'.repeat(256)}, 'usage.idempotency_key'], + [{idempotencyKey: 'tab\there'}, 'usage.idempotency_key'], + ]; + for (const [name, message, opts] of SENDS) + { + for (const [extra, code] of cases) + { + const e = await failure(name, message, {...opts, ...extra}); + expect(e, `${name} ${JSON.stringify(extra)}`).toMatchObject({code, exit_code: 2}); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a key does not make a lost answer safe to repeat: a Reply that ignores the header would send it twice', async()=>{ + mock_fetch.mockRejectedValueOnce(lost_connection()); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...LATER}); + expect(e).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect((e as {hint?: string}).hint).toContain('may send it twice'); + }); + + it('a 404 with no code of Reply\'s own stays reply.refused, status 404 and no reply code, an empty body, a problem without one, or a page that is not JSON', async()=>{ + const bare: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], + ['html', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/html'}})], + ['text', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/plain'}})], + ]; + for (const [name, message, opts] of SENDS) + { + for (const [label, res] of bare) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, {...opts, ...LATER}); + expect(e, `${name} ${label}`).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, `${name} ${label}`).toBeUndefined(); + } + } + }); +}); + +describe('a send made with an idempotency key', ()=>{ + const KEY = {idempotencyKey: 'send-456-step-2'}; + const SENDS: [Direct_send_name, unknown, Direct_send_opts, string][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, 'contact'], + ['linkedin-connect', {note: NOTE}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ['linkedin-voice', {script: SCRIPT}, {...LINKEDIN_OPTS, ...KEY}, 'directLinkedIn'], + ]; + + it('maps the key Reply holds for a send still being made, and the key reused for another send, each definite', async()=>{ + for (const [name, message, opts, family] of SENDS) + { + for (const [reply_code, code] of [['idempotencyKeyInUse', 'idempotency_key.in_use'], ['idempotencyKeyReused', 'idempotency_key.reused']]) + { + mock_fetch.mockReset(); + answer(json({code: `${family}.${reply_code}`, detail: 'Idempotency-Key conflict.'}, 409)); + const e = await failure(name, message, opts); + expect(e, `${name} ${reply_code}`).toMatchObject({code, exit_code: 1, status: 409, reply_code: `${family}.${reply_code}`, + ids: {contact_id: 456}}); + expect(sent(), name).toHaveLength(1); + } + } + }); + + it('a reused key carries the send Reply holds under it, reference, state and send_after, each only when Reply gives it', async()=>{ + for (const [name, message, opts, family] of SENDS) + { + mock_fetch.mockReset(); + answer(json({code: `${family}.idempotencyKeyReused`, detail: 'Reused.', reference: 'email-1001', state: 'queued', + sendAfter: '2026-11-03T14:00:00Z'}, 409)); + const e = await failure(name, message, opts); + expect(e, name).toMatchObject({code: 'idempotency_key.reused', + details: {reference: 'email-1001', state: 'queued', send_after: '2026-11-03T14:00:00Z'}}); + expect((e as {to_json: () => unknown}).to_json(), name).toMatchObject({error: {details: {reference: 'email-1001'}}}); + } + mock_fetch.mockReset(); + answer(json({code: 'contact.idempotencyKeyReused', reference: 'email-1001', state: 7, sendAfter: null}, 409)); + expect((await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}) as {details?: unknown}).details) + .toStrictEqual({reference: 'email-1001'}); + }); + + it('a reused key or a key in use without the send carries no details: the output is what it was', async()=>{ + for (const reply_code of ['contact.idempotencyKeyReused', 'contact.idempotencyKeyInUse']) + { + mock_fetch.mockReset(); + answer(json({code: reply_code, detail: 'Conflict.'}, 409)); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}); + expect((e as {details?: unknown}).details, reply_code).toBeUndefined(); + expect(JSON.stringify((e as {to_json: () => unknown}).to_json()), reply_code).not.toContain('details'); + } + // A key in use names the send too when Reply gives it, as every refusal of a send does. + mock_fetch.mockReset(); + answer(json({code: 'contact.idempotencyKeyInUse', detail: 'Conflict.', reference: 'email-1001'}, 409)); + expect((await failure('send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}) as {details?: unknown}).details) + .toStrictEqual({reference: 'email-1001'}); + }); + + it('reads those codes only under 409 and only in the send route\'s own family; any other answer is mapped as before', async()=>{ + const cases: [Direct_send_name, unknown, Direct_send_opts, Response][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, json({code: 'contact.idempotencyKeyInUse'}, 400)], + ['send-email', {subject: SUBJECT, body: BODY}, {...EMAIL_OPTS, ...KEY}, json({code: 'directLinkedIn.idempotencyKeyInUse'}, 409)], + ['linkedin-message', {body: TEXT}, {...LINKEDIN_OPTS, ...KEY}, json({code: 'contact.idempotencyKeyReused'}, 409)], + ]; + for (const [name, message, opts, res] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(name, message, opts), name).toMatchObject({code: 'reply.refused', exit_code: 1}); + } + }); +}); + +describe('a direct email Reply renders', ()=>{ + const EMAIL: unknown = {subject: SUBJECT, body: BODY}; + + it('maps a variable Reply could not fill to contact.missing_variables, with the bare names under details', async()=>{ + answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.', + missingVariables: ['FirstName', 'Company']}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({code: 'contact.missing_variables', status: 400, exit_code: 1, reply_code: 'contact.missingVariables', + details: {missing_variables: ['FirstName', 'Company']}, ids: {contact_id: 456}}); + expect((e as {to_json: () => unknown}).to_json()).toMatchObject({error: {details: {missing_variables: ['FirstName', 'Company']}}}); + }); + + it('leaves missing_variables out when Reply gives no list of names, as the reused key leaves its fields out', async()=>{ + for (const missing of [undefined, null, 'FirstName', ['FirstName', 7]]) + { + mock_fetch.mockReset(); + answer(json({code: 'contact.missingVariables', detail: 'The message has variables with no value.', missingVariables: missing}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, JSON.stringify(missing)).toMatchObject({code: 'contact.missing_variables', status: 400, exit_code: 1}); + expect((e as {details?: unknown}).details, JSON.stringify(missing)).toBeUndefined(); + expect((e as {to_json: () => {error: object}}).to_json().error, JSON.stringify(missing)).not.toHaveProperty('details'); + } + }); + + it('maps a template Reply could not render to contact.rendering_failed, with Reply\'s message as the detail', async()=>{ + answer(json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}, 400)); + expect(await failure('send-email', EMAIL, EMAIL_OPTS)).toMatchObject({code: 'contact.rendering_failed', status: 400, exit_code: 1, + reply_code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}); + }); + + it('reads the two codes only under 400; Reply\'s older contact.unknown stays reply.refused', async()=>{ + const cases: [Response, string][] = [ + [json({code: 'contact.missingVariables'}, 409), 'reply.refused'], + [json({code: 'contact.renderingFailed'}, 409), 'reply.refused'], + [json({code: 'contact.unknown', detail: 'The message has variables with no value.'}, 400), 'reply.refused'], + ]; + for (const [res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure('send-email', EMAIL, EMAIL_OPTS), code).toMatchObject({code, exit_code: 1}); + } + }); + + it('reads the two codes only from the email route: a LinkedIn send answering either falls to the usual mapping', async()=>{ + const sends: [Direct_send_name, unknown][] = [['linkedin-connect', {note: NOTE}], ['linkedin-message', {body: TEXT}], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}], ['linkedin-voice', {script: SCRIPT}]]; + for (const [name, message] of sends) + { + for (const reply_code of ['contact.missingVariables', 'contact.renderingFailed']) + { + mock_fetch.mockReset(); + answer(json({code: reply_code, missingVariables: ['FirstName']}, 400)); + const e = await failure(name, message, LINKEDIN_OPTS); + expect(e, `${name} ${reply_code}`).toMatchObject({code: 'reply.refused', status: 400, reply_code, exit_code: 1}); + expect((e as {details?: unknown}).details, `${name} ${reply_code}`).toBeUndefined(); + } + } + }); + + it('sends trackLinks and trackOpens only when their flags are given, and nothing of them otherwise', async()=>{ + const cases: [Direct_send_opts, Record][] = [ + [EMAIL_OPTS, {}], + [{...EMAIL_OPTS, trackLinks: true}, {trackLinks: true}], + [{...EMAIL_OPTS, trackOpens: true}, {trackOpens: true}], + [{...EMAIL_OPTS, trackLinks: true, trackOpens: true}, {trackLinks: true, trackOpens: true}], + ]; + for (const [opts, tracking] of cases) + { + mock_fetch.mockReset(); + answer(json({status: 'new', messageId: null})); + await run('send-email', EMAIL, opts); + const body = sent()[0].body as Record; + expect({trackLinks: body.trackLinks, trackOpens: body.trackOpens}, JSON.stringify(tracking)) + .toStrictEqual({trackLinks: tracking.trackLinks, trackOpens: tracking.trackOpens}); + expect(Object.keys(body).filter(k=>k.startsWith('track')), JSON.stringify(tracking)).toEqual(Object.keys(tracking)); + } + }); +}); + +describe('a refused send that Reply holds a row for', ()=>{ + const EMAIL: unknown = {subject: SUBJECT, body: BODY}; + const HELD = {reference: 'email-1001', state: 'failed', sendAfter: '2026-11-03T14:00:00Z'}; + const details_of = (e: unknown): unknown=>(e as {details?: unknown}).details; + + it('names the send under details, reference, state and send_after, beside the refusal\'s code and class as before', async()=>{ + answer(json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.', ...HELD}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({code: 'contact.rendering_failed', status: 400, exit_code: 1, reply_code: 'contact.renderingFailed', + ids: {contact_id: 456}}); + expect(details_of(e)).toStrictEqual({reference: 'email-1001', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + expect((e as {to_json: () => unknown}).to_json()).toMatchObject({error: {details: {reference: 'email-1001', state: 'failed'}}}); + }); + + it('gives each field only when Reply gives it as a string', async()=>{ + const cases: [Record, unknown][] = [ + [{reference: 'email-1001'}, {reference: 'email-1001'}], + [{reference: 'email-1001', state: 7, sendAfter: null}, {reference: 'email-1001'}], + [{state: {failed: true}, sendAfter: ['2026-11-03T14:00:00Z']}, undefined], + ]; + for (const [held, details] of cases) + { + mock_fetch.mockReset(); + answer(json({code: 'contact.contactInBlackList', ...held}, 400)); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, JSON.stringify(held)).toMatchObject({code: 'contact.blacklisted', exit_code: 1}); + expect(details_of(e), JSON.stringify(held)).toStrictEqual(details); + } + }); + + it('names it on a LinkedIn send\'s refusal too, a known code or one mapped as everywhere else', async()=>{ + const cases: [Direct_send_name, unknown, Response, string][] = [ + ['linkedin-message', {body: TEXT}, json({code: 'directLinkedIn.notConnected', ...HELD, reference: 'linkedin-1042'}, 409), + 'linkedin.not_connected'], + ['linkedin-connect', {note: NOTE}, json({code: 'directLinkedIn.somethingNew', ...HELD, reference: 'linkedin-1042'}, 400), + 'reply.refused'], + ]; + for (const [name, message, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure(name, message, LINKEDIN_OPTS); + expect(e, name).toMatchObject({code, exit_code: 1}); + expect(details_of(e), name).toStrictEqual({reference: 'linkedin-1042', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + } + }); + + it('sits beside the details a refusal carries of its own: the unfilled names, a LinkedIn limit', async()=>{ + answer(json({code: 'contact.missingVariables', missingVariables: ['FirstName'], ...HELD}, 400)); + expect(details_of(await failure('send-email', EMAIL, EMAIL_OPTS))).toStrictEqual({missing_variables: ['FirstName'], + reference: 'email-1001', state: 'failed', send_after: '2026-11-03T14:00:00Z'}); + mock_fetch.mockReset(); + answer(json({code: 'directLinkedIn.dailyLimitReached', reference: 'linkedin-1042'}, 429, {'Retry-After': '3600'})); + expect(details_of(await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS))).toStrictEqual({limit: 'daily', + reference: 'linkedin-1042'}); + }); + + it('a refusal without them carries no details, and the output is what it was', async()=>{ + for (const res of [json({code: 'contact.renderingFailed', detail: 'Unclosed block at line 2.'}, 400), + json({code: 'contact.somethingNew'}, 400), json('Bad Request', 400)]) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(details_of(e)).toBeUndefined(); + expect(JSON.stringify((e as {to_json: () => unknown}).to_json())).not.toContain('details'); + } + }); +}); + +describe('a 400 on the send call with neither a code nor errors[]', ()=>{ + const SENDS: [Direct_send_name, unknown, Direct_send_opts][] = [ + ['send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS], + ['linkedin-connect', {note: NOTE}, LINKEDIN_OPTS], + ['linkedin-message', {body: TEXT}, LINKEDIN_OPTS], + ['linkedin-inmail', {subject: SUBJECT, body: TEXT}, LINKEDIN_OPTS], + ['linkedin-voice', {script: SCRIPT}, LINKEDIN_OPTS], + ]; + const problem = (body: unknown)=>json(body, 400, {'Content-Type': 'application/problem+json'}); + + it('is Reply\'s exception path: outcome.unknown (exit 3), made once, and a repeat may send it twice', async()=>{ + for (const [name, message, opts] of SENDS) + { + for (const [label, res] of [['problem', ()=>problem({title: 'Internal error', status: 400})], ['json', ()=>json({title: 'Internal error'}, 400)]] as const) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, opts); + expect(e, `${name} ${label}`).toMatchObject({code: 'outcome.unknown', exit_code: 3, status: 400, ids: {contact_id: 456}}); + expect((e as {reply_code?: string}).reply_code, `${name} ${label}`).toBeUndefined(); + expect((e as {hint?: string}).hint ?? '', `${name} ${label}`).toContain('may send it twice'); + expect(mock_fetch, `${name} ${label}`).toHaveBeenCalledTimes(1); + } + } + }); + + it('keeps the send it names under details, should Reply give one', async()=>{ + answer(problem({title: 'Internal error', status: 400, reference: 'email-1001', state: 'failed'})); + const e = await failure('send-email', {subject: SUBJECT, body: BODY}, EMAIL_OPTS); + expect(e).toMatchObject({code: 'outcome.unknown', exit_code: 3, details: {reference: 'email-1001', state: 'failed'}}); + }); + + it('with errors[] it is a request Reply refused as given, and a page that is not JSON maps as before', async()=>{ + for (const [name, message, opts] of SENDS) + { + const cases: [string, ()=>Response, string][] = [ + ['errors', ()=>problem({title: 'Validation failed', status: 400, errors: [{pointer: '/body', detail: 'must not be empty'}]}), + 'reply.invalid_request'], + ['empty errors', ()=>problem({title: 'Validation failed', status: 400, errors: []}), 'reply.invalid_request'], + ['html', ()=>new Response('Bad Request', {status: 400, headers: {'Content-Type': 'text/html'}}), 'reply.refused'], + ['text', ()=>new Response('Bad Request', {status: 400, headers: {'Content-Type': 'text/plain'}}), 'reply.refused'], + ['empty', ()=>new Response(null, {status: 400}), 'reply.refused'], + ]; + for (const [label, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(name, message, opts); + expect(e, `${name} ${label}`).toMatchObject({code, exit_code: 1, status: 400}); + expect(mock_fetch, `${name} ${label}`).toHaveBeenCalledTimes(1); + } + } + }); +}); diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts new file mode 100644 index 0000000..0abbd10 --- /dev/null +++ b/src/__tests__/operations/direct-sends.test.ts @@ -0,0 +1,230 @@ +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_direct_send_get, handle_direct_send_cancel} from '../../operations/direct-sends'; + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +const QUEUED = { + reference: 'email-1001', channel: 'email', contactId: 456, state: 'queued', sendAfter: '2026-11-03T14:00:00Z', + sentAt: null, messageId: null, failureReason: null, cancelledAt: null, +}; +const CANCELLED = {...QUEUED, state: 'cancelled', cancelledAt: '2026-11-02T09:15:00Z'}; + +const get = async(reference: string)=>JSON.parse((await capture(()=>handle_direct_send_get(reference, ctx(), {json: true}))).out); +const cancel = async(reference: string)=>JSON.parse((await capture(()=>handle_direct_send_cancel(reference, ctx(), {json: true}))).out); +const failure = (fn: () => Promise)=>fn().catch((x: unknown)=>x); + +const lost_connection = ()=>Object.assign(new TypeError('fetch failed'), + {cause: Object.assign(new Error('ECONNRESET'), {code: 'ECONNRESET'})}); + +// A 404 with no code of Reply's own: how a Reply without the route, or a proxy in front of it, answers. +const BARE_404: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem without a code', ()=>json({title: 'Not Found', status: 404}, 404, {'Content-Type': 'application/problem+json'})], + ['html page', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/html'}})], + ['plain text', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/plain'}})], +]; + +describe('direct-send get', ()=>{ + it('reads one send by its reference and answers Reply\'s model under the CLI\'s names', async()=>{ + answer(json(QUEUED)); + expect(await get('email-1001')).toStrictEqual({ + reference: 'email-1001', channel: 'email', contact_id: 456, state: 'queued', send_after: '2026-11-03T14:00:00Z', + sent_at: null, message_id: null, failure_reason: null, cancelled_at: null, + }); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/direct-sends/email-1001', body: undefined}]); + }); + + it('gives what Reply leaves out as null, and Reply\'s state as its own word, one the CLI does not know included', async()=>{ + answer(json({reference: 'linkedin-1042', state: 'held', sentAt: '2026-11-03T14:00:02Z', messageId: 'm-1', + failureReason: 'notConnected'})); + expect(await get('linkedin-1042')).toStrictEqual({ + reference: 'linkedin-1042', channel: null, contact_id: null, state: 'held', send_after: null, + sent_at: '2026-11-03T14:00:02Z', message_id: 'm-1', failure_reason: 'notConnected', cancelled_at: null, + }); + }); + + it('gives what Reply says of a rendered or failed send as given: the failure\'s sentence and its code, the unfilled names', async()=>{ + answer(json({...QUEUED, state: 'failed', failureReason: 'A template variable had no value for this contact.', + failureCode: 'contact.missingVariables', missingVariables: ['FirstName', 'Company'], + renderedSubject: 'Quick question, Marta', renderedBody: '

Hi Marta

'})); + expect(await get('email-1001')).toMatchObject({ + state: 'failed', failure_reason: 'A template variable had no value for this contact.', failure_code: 'contact.missingVariables', + missing_variables: ['FirstName', 'Company'], rendered_subject: 'Quick question, Marta', rendered_body: '

Hi Marta

', + }); + }); + + it('adds the rendered text, the failure\'s code and the unfilled names only when Reply gives them, a null included', async()=>{ + answer(json({...QUEUED, failureCode: null, missingVariables: null, renderedSubject: null, renderedBody: null})); + expect(await get('email-1001')).toMatchObject({failure_code: null, missing_variables: null, rendered_subject: null, rendered_body: null}); + for (const [from, to] of [['failureCode', 'failure_code'], ['missingVariables', 'missing_variables'], + ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, failureCode: 'x', missingVariables: [], renderedSubject: 's', renderedBody: 'b', [from]: undefined})); + const got = await get('email-1001'); + expect(got, from).not.toHaveProperty(to); + expect(Object.keys(got), from).toHaveLength(12); + } + }); + + it('gives missing_variables only as a list of names, and the others only as text: anything else is left out', async()=>{ + for (const missing of [[], ['FirstName']]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, missingVariables: missing})); + expect((await get('email-1001')).missing_variables, JSON.stringify(missing)).toEqual(missing); + } + for (const odd of ['FirstName', ['FirstName', 7], {name: 'FirstName'}, 7]) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, missingVariables: odd, failureCode: [odd], renderedSubject: 7, renderedBody: {odd}})); + expect(Object.keys(await get('email-1001')), JSON.stringify(odd)).toEqual(['reference', 'channel', 'contact_id', 'state', + 'send_after', 'sent_at', 'message_id', 'failure_reason', 'cancelled_at']); + } + }); + + it('sends a reference of the form Reply\'s route takes as given: email- or linkedin-, n from 1 and at most ten digits', async()=>{ + for (const reference of ['email-1', 'linkedin-42', 'email-9999999999', 'email-1001']) + { + for (const [fn, suffix] of [[get, ''], [cancel, '/cancel']] as const) + { + mock_fetch.mockReset(); + answer(json({...QUEUED, reference})); + await fn(reference); + expect(sent()[0].url, reference).toBe(`https://api/v3/direct-sends/${reference}${suffix}`); + } + } + }); + + it('refuses any other reference before any call, so a bare 404 always means the route is absent', async()=>{ + const malformed = ['email-0', 'email-01', 'email-12345678901', 'sms-1', 'email-', 'email-1a', ' email-1', 'email-1 ', 'EMAIL-1', + 'email--1', 'linkedin', '.', '..', 'a.b', '...', '.a', ' ..', 'a/b c?d', 'ds_8F2k', 'email-1/cancel', 'email-1\n']; + for (const reference of malformed) + { + for (const fn of [handle_direct_send_get, handle_direct_send_cancel]) + { + const e = await failure(()=>fn(reference, ctx(), {})); + expect(e, `${fn.name} ${JSON.stringify(reference)}`).toMatchObject({code: 'usage.reference', exit_code: 2}); + expect((e as Error).message, JSON.stringify(reference)).toContain('email- or linkedin-'); + } + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('refuses a blank reference before any call', async()=>{ + for (const blank of ['', ' ']) + { + expect(await failure(()=>handle_direct_send_get(blank, ctx(), {})), JSON.stringify(blank)) + .toMatchObject({code: 'usage.reference', exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('maps Reply\'s two refusals of a read, each under the status Reply publishes it with', async()=>{ + const cases: [Response, string, string | undefined][] = [ + [json({code: 'directSend.notFound', detail: 'Direct send not found.'}, 404), 'direct_send.not_found', 'directSend.notFound'], + [json({code: 'directSend.notOwned', detail: 'Not yours.'}, 403), 'direct_send.not_owned', 'directSend.notOwned'], + [json({code: 'directSend.notOwned'}, 404), 'reply.refused', 'directSend.notOwned'], + [json({code: 'directSend.forbidden'}, 403), 'access.feature_unavailable', 'directSend.forbidden'], + [json({code: 'directSend.somethingElse'}, 400), 'reply.refused', 'directSend.somethingElse'], + ]; + for (const [res, code, reply_code] of cases) + { + mock_fetch.mockReset(); + answer(res); + const e = await failure(()=>handle_direct_send_get('email-1001', ctx(), {})); + expect(e, code).toMatchObject({code, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, code).toBe(reply_code); + } + }); + + it('a 404 with no code of Reply\'s own is reply.refused, status 404 and no reply code', async()=>{ + for (const [label, res] of BARE_404) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(()=>handle_direct_send_get('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } + }); + + it('an answer without a reference or a state cannot be read, and the read is safe to make again', async()=>{ + for (const body of [{...QUEUED, reference: undefined}, {...QUEUED, state: ''}, [QUEUED], 'ok']) + { + mock_fetch.mockReset(); + answer(json(body)); + expect(await failure(()=>handle_direct_send_get('email-1001', ctx(), {})), JSON.stringify(body)) + .toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } + }); +}); + +describe('direct-send cancel', ()=>{ + it('cancels one send by its reference and answers the send as Reply now holds it', async()=>{ + answer(json(CANCELLED)); + expect(await cancel('email-1001')).toStrictEqual({ + reference: 'email-1001', channel: 'email', contact_id: 456, state: 'cancelled', send_after: '2026-11-03T14:00:00Z', + sent_at: null, message_id: null, failure_reason: null, cancelled_at: '2026-11-02T09:15:00Z', + }); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/direct-sends/email-1001/cancel', body: undefined}]); + }); + + it('a cancel of a send already cancelled is a success again, as Reply answers it', async()=>{ + answer(json(CANCELLED), json(CANCELLED)); + expect(await cancel('email-1001')).toMatchObject({state: 'cancelled'}); + expect(await cancel('email-1001')).toMatchObject({state: 'cancelled'}); + expect(mock_fetch).toHaveBeenCalledTimes(2); + }); + + it('maps Reply\'s four refusals of a cancel, each definite', async()=>{ + const cases: [Response, string][] = [ + [json({code: 'directSend.notFound'}, 404), 'direct_send.not_found'], + [json({code: 'directSend.notOwned'}, 403), 'direct_send.not_owned'], + [json({code: 'directSend.alreadySent'}, 409), 'direct_send.already_sent'], + [json({code: 'directSend.alreadyFailed'}, 409), 'direct_send.already_failed'], + [json({code: 'directSend.alreadySent'}, 400), 'reply.refused'], + ]; + for (const [res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})), code).toMatchObject({code, exit_code: 1}); + expect(mock_fetch, code).toHaveBeenCalledTimes(1); + } + }); + + it('a 404 with no code of Reply\'s own is reply.refused, status 404 and no reply code', async()=>{ + for (const [label, res] of BARE_404) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } + }); + + it('an answer that may hide a cancel is outcome.unknown (exit 3), made once, and says running it again is safe', async()=>{ + const answers: [string, ()=>void][] = [ + ['lost answer', ()=>{ mock_fetch.mockRejectedValueOnce(lost_connection()); }], + ['503', ()=>answer(json({title: 'Service Unavailable'}, 503))], + ['unreadable 200', ()=>answer(json('ok', 200))], + ]; + for (const [label, give] of answers) + { + mock_fetch.mockReset(); + give(); + const e = await failure(()=>handle_direct_send_cancel('email-1001', ctx(), {})); + expect(e, label).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + expect((e as {hint?: string}).hint ?? '', label).toContain('running it again is safe'); + expect(mock_fetch, label).toHaveBeenCalledTimes(1); + } + }); + + it('refuses a blank reference before any call', async()=>{ + expect(await failure(()=>handle_direct_send_cancel(' ', ctx(), {}))).toMatchObject({code: 'usage.reference', exit_code: 2}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/src/__tests__/operations/inbox-changes.test.ts b/src/__tests__/operations/inbox-changes.test.ts new file mode 100644 index 0000000..de93b83 --- /dev/null +++ b/src/__tests__/operations/inbox-changes.test.ts @@ -0,0 +1,146 @@ +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_inbox_changes} from '../../operations/inbox'; + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +const CHANGE = { + threadId: 9876, contactId: 456, channel: 'email', lastActivityDate: '2026-11-03T14:02:11Z', sequenceId: 12, + category: 'interested', hasMeetingIntent: false, newFieldReplyAdds: 'kept', + flags: {hasReply: true, hasBounce: false, hasAutoReply: false, hasOutOfOffice: false}, + lastMessage: {messageId: '', isOutbound: false, date: '2026-11-03T14:02:11Z'}, +}; + +type Opts = {cursor?: string; since?: string; top?: string}; +const changes = async(opts: Opts = {})=>JSON.parse((await capture(()=>handle_inbox_changes(opts, ctx(), {json: true}))).out); +const failure = (opts: Opts)=>handle_inbox_changes(opts, ctx(), {}).catch((x: unknown)=>x); + +// A cursor or a since older than the feed's 30 days: a business problem with a code of its own. +const WINDOW_EXPIRED = { + code: 'inboxThread.changeWindowExpired', title: 'Change window expired', status: 400, + detail: 'The feed keeps 30 days. Start again with \'since\' (at most 30 days ago) or with no parameters, which reads the last 30 days.', +}; +// How Reply's API document publishes a cursor it will not read: a validation problem with no code, pointing at /cursor. +const CURSOR_UNREADABLE = { + title: 'Validation failed', status: 400, detail: 'The request body contains validation errors.', + errors: [{pointer: '/cursor', detail: '\'cursor\' could not be read.'}], +}; +const problem = (body: unknown, status: number)=>json(body, status, {'Content-Type': 'application/problem+json'}); + +describe('inbox changes', ()=>{ + it('reads one page of the feed and passes the items on as Reply gives them, under has_more and cursor', async()=>{ + answer(json({items: [CHANGE], hasMore: true, cursor: 'AQjfObhYHZgAAADjVg'})); + expect(await changes()).toStrictEqual({items: [CHANGE], has_more: true, cursor: 'AQjfObhYHZgAAADjVg'}); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/inbox/threads/changes', body: undefined}]); + }); + + it('an empty page keeps the cursor Reply gives with it, so the next read goes on from there', async()=>{ + answer(json({items: [], hasMore: false, cursor: 'AQjfObkJcH4Af____w'})); + expect(await changes({cursor: 'AQjfObhYHZgAAADjVg'})).toStrictEqual({items: [], has_more: false, cursor: 'AQjfObkJcH4Af____w'}); + }); + + it('sends the cursor as given and encoded, --since in UTC and not shifted, and --top only when given', async()=>{ + const cases: [Opts, string][] = [ + [{cursor: 'AQjf+b/Y=='}, 'cursor=AQjf%2Bb%2FY%3D%3D'], + [{since: '2026-11-03T16:00:00+02:00'}, 'since=2026-11-03T14%3A00%3A00.000Z'], + [{since: '2026-11-03T14:00:00Z', top: '1000'}, 'since=2026-11-03T14%3A00%3A00.000Z&top=1000'], + [{top: '1'}, 'top=1'], + ]; + for (const [opts, query] of cases) + { + mock_fetch.mockReset(); + answer(json({items: [], hasMore: false, cursor: 'c'})); + await changes(opts); + expect(sent()[0].url, query).toBe(`https://api/v3/inbox/threads/changes?${query}`); + } + }); + + it('refuses --cursor with --since, a blank cursor, a moment without its offset and a --top out of range, before any call', async()=>{ + const cases: [Opts, string][] = [ + [{cursor: 'AQjfObhYHZgAAADjVg', since: '2026-11-03T14:00:00Z'}, 'usage.inbox'], + [{cursor: ' '}, 'usage.inbox'], + [{since: '2026-11-03T14:00:00'}, 'usage.date'], + [{since: '2026-11-03'}, 'usage.date'], + [{top: '0'}, 'usage.range'], + [{top: '1001'}, 'usage.range'], + ]; + for (const [opts, code] of cases) + { + expect(await failure(opts), JSON.stringify(opts)).toMatchObject({code, exit_code: 2}); + } + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('a cursor or a --since older than the feed keeps is inbox.cursor_expired, which says to start again with --since', async()=>{ + for (const opts of [{cursor: 'AQjfObhYHZgAAADjVg'}, {since: '2026-09-01T00:00:00Z'}, {}]) + { + mock_fetch.mockReset(); + answer(problem(WINDOW_EXPIRED, 400)); + const e = await failure(opts); + expect(e, JSON.stringify(opts)).toMatchObject({code: 'inbox.cursor_expired', status: 400, exit_code: 1, + reply_code: 'inboxThread.changeWindowExpired', detail: WINDOW_EXPIRED.detail}); + expect((e as {hint?: string}).hint, JSON.stringify(opts)).toContain('--since'); + } + }); + + it('the window\'s code under another status is not the window: it maps as everywhere else', async()=>{ + answer(problem({...WINDOW_EXPIRED, status: 409}, 409)); + expect(await failure({cursor: 'c'})).toMatchObject({code: 'reply.refused', reply_code: 'inboxThread.changeWindowExpired'}); + }); + + it('a cursor Reply will not read is inbox.cursor_refused, with the same hint as the expired window', async()=>{ + answer(problem(CURSOR_UNREADABLE, 400)); + const e = await failure({cursor: 'AQjfObhYHZgAAADjVg'}); + expect(e).toMatchObject({code: 'inbox.cursor_refused', status: 400, exit_code: 1, details: {fields: ['cursor']}}); + expect((e as {reply_code?: string}).reply_code).toBeUndefined(); + mock_fetch.mockReset(); + answer(problem(WINDOW_EXPIRED, 400)); + expect((e as {hint?: string}).hint).toBe((await failure({cursor: 'AQjfObhYHZgAAADjVg'}) as {hint?: string}).hint); + }); + + it('any other refusal maps as everywhere else', async()=>{ + const cases: [Opts, Response, string][] = [ + // The same pointer when no cursor was sent is not about one the caller holds. + [{since: '2026-11-03T14:00:00Z'}, problem(CURSOR_UNREADABLE, 400), 'reply.invalid_request'], + [{since: '2026-09-01T00:00:00Z'}, problem({title: 'Validation failed', status: 400, errors: [{pointer: '/since', detail: 'too old'}]}, 400), + 'reply.invalid_request'], + [{cursor: 'c'}, problem({code: 'inboxThread.invalidPagination', status: 400}, 400), 'reply.refused'], + [{}, problem({code: 'inboxThread.forbidden', status: 403}, 403), 'access.feature_unavailable'], + [{}, new Response(null, {status: 404}), 'reply.refused'], + [{}, problem({title: 'Not Found', status: 404}, 404), 'reply.refused'], + ]; + for (const [opts, res, code] of cases) + { + mock_fetch.mockReset(); + answer(res); + expect(await failure(opts), `${JSON.stringify(opts)} ${code}`).toMatchObject({code, exit_code: 1}); + } + }); + + it('a 404 with no code of Reply\'s own, from a Reply without the feed, is reply.refused with status 404 and no reply code', async()=>{ + const bare: [string, ()=>Response][] = [ + ['empty', ()=>new Response(null, {status: 404})], + ['problem without a code', ()=>problem({title: 'Not Found', status: 404}, 404)], + ['html page', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/html'}})], + ['plain text', ()=>new Response('Not Found', {status: 404, headers: {'Content-Type': 'text/plain'}})], + ]; + for (const [label, res] of bare) + { + mock_fetch.mockReset(); + answer(res()); + const e = await failure({}); + expect(e, label).toMatchObject({code: 'reply.refused', status: 404, exit_code: 1}); + expect((e as {reply_code?: string}).reply_code, label).toBeUndefined(); + } + }); + + it('a page without its items, has_more or cursor cannot be read, and the read is safe to make again', async()=>{ + for (const body of [{items: [], hasMore: false}, {items: [], cursor: 'c'}, {items: {}, hasMore: false, cursor: 'c'}, + {items: [], hasMore: 'no', cursor: 'c'}, {items: [], hasMore: false, cursor: 7}, [CHANGE]]) + { + mock_fetch.mockReset(); + answer(json(body)); + expect(await failure({}), JSON.stringify(body)).toMatchObject({code: 'reply.unavailable', exit_code: 1}); + } + }); +}); diff --git a/src/__tests__/operations/options.test.ts b/src/__tests__/operations/options.test.ts index aea2f2e..343b9f1 100644 --- a/src/__tests__/operations/options.test.ts +++ b/src/__tests__/operations/options.test.ts @@ -1,5 +1,7 @@ import {describe, it, expect} from 'vitest'; -import {parse_id, parse_int_in, parse_iso, parse_choice, LARGEST_SAFE_ID} from '../../operations/options'; +import { + parse_id, parse_int_in, parse_iso, parse_moment, parse_idempotency_key, parse_choice, LARGEST_SAFE_ID, +} from '../../operations/options'; import {UsageError} from '../../utils/errors'; const usage_code = (fn: () => unknown): string | undefined=>{ @@ -60,6 +62,35 @@ describe('operations/options', ()=>{ } }); + it('parse_moment takes a date and time with its offset, as the same instant in UTC', ()=>{ + expect(parse_moment('2026-11-03T14:00:00Z', '--send-after')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03T16:00:00+02:00', '--send-after')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03T09:00-0500', '--since')).toBe('2026-11-03T14:00:00.000Z'); + expect(parse_moment('2026-11-03t14:00:00.25z', '--since')).toBe('2026-11-03T14:00:00.250Z'); + }); + + it('parse_moment refuses a date alone and a time without its offset, which the CLI would have to place in a zone of its own', ()=>{ + for (const bad of ['2026-11-03', '2026-11-03T14:00:00', '2026-11-03 14:00:00Z', 'tomorrow', '1', '2026-13-45T00:00:00Z']) + { + expect(usage_code(()=>parse_moment(bad, '--send-after')), bad).toBe('usage.date'); + } + expect(()=>parse_moment('2026-11-03T14:00:00', '--send-after')) + .toThrow('--send-after must be a date and time with its offset, e.g. 2026-11-03T14:00:00Z.'); + }); + + it('parse_idempotency_key takes 1 to 255 characters from space to tilde, spaces inside, as given', ()=>{ + expect(parse_idempotency_key('send-456-step-2')).toBe('send-456-step-2'); + for (const good of ['a b', 'send 456 step 2', '~!"#', 'k'.repeat(255), `a${' '.repeat(253)}b`]) + { + expect(parse_idempotency_key(good), JSON.stringify(good)).toBe(good); + } + // A header value loses a space at either end on its way out, so such a key would reach Reply as another key. + for (const bad of ['', ' ', ' a', 'a ', 'k'.repeat(256), 'café', 'a\nb', 'a\tb', 'a\u007fb']) + { + expect(usage_code(()=>parse_idempotency_key(bad)), JSON.stringify(bad)).toBe('usage.idempotency_key'); + } + }); + it('parse_choice accepts only the listed values', ()=>{ expect(parse_choice('sent', '--source', ['inbox', 'sent'] as const)).toBe('sent'); expect(parse_choice(undefined, '--source', ['inbox'] as const)).toBeUndefined(); diff --git a/src/__tests__/operations/program.test.ts b/src/__tests__/operations/program.test.ts index feb4fda..8006a89 100644 --- a/src/__tests__/operations/program.test.ts +++ b/src/__tests__/operations/program.test.ts @@ -139,6 +139,28 @@ describe('the program', ()=>{ ]); }); + const LATER_SEND = ['--json', '-k', 'key-1', 'contact', 'linkedin-message', '--contact-id', '456', '--linkedin-account-id', '34', + '--message', '-']; + + it('a send for later takes --send-after, --schedule-id and --idempotency-key: the first two in the body, the key as a header', async()=>{ + pipe_stdin(JSON.stringify({body: 'Thanks for connecting.'})); + answer(json({code: 'directLinkedIn.notConnected'}, 409)); + const {code} = await run_program([...LATER_SEND, + '--send-after', '2026-11-03T14:00:00Z', '--schedule-id', '41', '--idempotency-key', 'send-456-1']); + expect(code).toBe(1); + expect(requests()).toEqual([{method: 'POST', url: 'https://api.reply.io/v3/contacts/456/send-direct-linkedin-message', + body: {linkedInAccountId: 34, message: 'Thanks for connecting.', sendAfter: '2026-11-03T14:00:00.000Z', scheduleId: 41}}]); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[1].headers).toMatchObject({'Idempotency-Key': 'send-456-1'}); + }); + + it('a send for later at a moment without its offset exits 2 before any request', async()=>{ + pipe_stdin(JSON.stringify({body: 'Thanks for connecting.'})); + const {code, err} = await run_program([...LATER_SEND, '--send-after', '2026-11-03T14:00:00']); + expect(code).toBe(2); + expect(JSON.parse(err)).toMatchObject({error: {code: 'usage.date'}}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + it('a send to a person Reply already holds exits 1, sends nothing, and names the contact', async()=>{ pipe_stdin(JSON.stringify({contact: {email: 'marta@example.com', first_name: 'Marta'}, message: {subject: 'Hi Marta', body: 'Tuesday works'}})); @@ -188,6 +210,33 @@ describe('the program', ()=>{ expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/schedules'); }); + it('direct-send is a work command of its own: no reference exits 2, a refused cancel exits 1 with its code', async()=>{ + for (const verb of ['get', 'cancel']) + { + const {code} = await run_program(['--json', '-q', '-k', 'key-1', 'direct-send', verb]); + expect(code, verb).toBe(2); + } + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({code: 'directSend.alreadySent', detail: 'Already sent.'}, 409, {'Content-Type': 'application/problem+json'})); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'direct-send', 'cancel', 'email-1001']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'direct_send.already_sent', status: 409}}); + const [url, init] = mock_fetch.mock.calls[0] as [string, RequestInit]; + expect([init.method, url]).toEqual(['POST', 'https://api.reply.io/v3/direct-sends/email-1001/cancel']); + }); + + it('inbox changes reads its flags through commander: both --cursor and --since exit 2, an expired cursor exits 1 with its code', async()=>{ + const both = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'changes', '--cursor', 'c1', '--since', '2026-11-03T14:00:00Z']); + expect(both.code).toBe(2); + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({code: 'inboxThread.changeWindowExpired', status: 400, detail: 'The feed keeps 30 days.'}, 400, + {'Content-Type': 'application/problem+json'})); + const {code, err} = await run_program(['--json', '-q', '-k', 'key-1', 'inbox', 'changes', '--cursor', 'c1', '--top', '50']); + expect(code).toBe(1); + expect(JSON.parse(err)).toMatchObject({error: {code: 'inbox.cursor_expired', status: 400, reply_code: 'inboxThread.changeWindowExpired'}}); + expect((mock_fetch.mock.calls[0] as [string, RequestInit])[0]).toBe('https://api.reply.io/v3/inbox/threads/changes?cursor=c1&top=50'); + }); + it('a usage error exits 2 before any request', async()=>{ const {code, err} = await run_program(['--json', '-k', 'key-1', 'sequence', 'stats', '123', '--from', '2026-10-02', '--to', '2026-10-01']); expect(code).toBe(2); diff --git a/src/index.ts b/src/index.ts index a874344..6598ea0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,9 @@ import {team_command} from './commands/team'; import {api_command} from './commands/api'; import {skills_command} from './commands/skills'; import {install_command} from './commands/install'; -import {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command} from './operations/commands'; +import { + sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command, +} from './operations/commands'; import {update_notice} from './selfupdate/notice'; import {CliError, format_hint} from './utils/errors'; import {info, set_quiet} from './utils/output'; @@ -46,7 +48,9 @@ const build_program = (): Command=>{ const WORK = 'Work with your Reply account:'; const SETUP = 'Setup:'; - for (const c of [sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, api_command]) + for (const c of [ + sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command, api_command, + ]) { program.addCommand(c.helpGroup(WORK)); } diff --git a/src/operations/call.ts b/src/operations/call.ts index 98c32e1..4504abd 100644 --- a/src/operations/call.ts +++ b/src/operations/call.ts @@ -37,10 +37,13 @@ const detail_of = (a: Answer): string | undefined=>{ // One call to Reply for an operation. Every HTTP status comes back as an Answer for the command // to read. If Reply can't be reached, nothing happened, so that becomes reply.unavailable. A -// write whose answer was lost passes through as outcome.unknown. -const call_reply = async(s: Op_session, method: string, path: string, kind: Call_kind, body?: unknown): Promise=>{ +// write whose answer was lost passes through as outcome.unknown. Headers given here are this call's +// own, added to the ones every call carries. +const call_reply = async( + s: Op_session, method: string, path: string, kind: Call_kind, body?: unknown, headers: Record = {}, +): Promise=>{ try { - const r = await request_raw(s.api_base, s.token, method, path, body, {headers: s.headers, kind}); + const r = await request_raw(s.api_base, s.token, method, path, body, {headers: {...s.headers, ...headers}, kind}); return {status: r.status, data: r.data, headers: r.response_headers}; } catch (e) { if (e instanceof RuntimeError) diff --git a/src/operations/commands.ts b/src/operations/commands.ts index 9f6db12..c96e5e7 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -8,7 +8,7 @@ import {handle_sequence_list, handle_sequence_create} from './sequence-by-name'; import {handle_sequence_add_contact, handle_sequence_remove_contact} from './sequence-membership'; import {handle_sequence_pause, handle_sequence_start} from './sequence-state'; import { - handle_inbox_list, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, + handle_inbox_list, handle_inbox_changes, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, } from './inbox'; import {handle_inbox_reply} from './inbox-reply'; import {handle_contact_list_add_contact} from './contact-list'; @@ -17,6 +17,7 @@ import {handle_contact_find, handle_contact_get, handle_contact_update, handle_c import {handle_direct_send, type Direct_send_name} from './direct-send'; import {handle_account_list} from './accounts'; import {handle_schedule_list} from './schedules'; +import {handle_direct_send_get, handle_direct_send_cancel} from './direct-sends'; const P = PROGRAM_NAME; const COMMON_ERRORS = [ @@ -290,26 +291,59 @@ const SENT_TO = (by: 'email' | 'linkedin', what: string): string=>CONTACT_FORMS + '--contact-id it is always false; in both cases a successful answer says the send was made.\n' + (by === 'email' ? '' : LINKEDIN_URL_NEEDED) + STDIN_PAIR('message'); +// The flags of a send for later, the same on every direct send. +const later_options = (c: Command): Command=>c + .option('--send-after ', 'Send at or after this moment, given with its offset (e.g. 2026-11-03T14:00:00Z)') + .option('--schedule-id ', 'The sending schedule Reply times the send by (see `schedule list`)') + .option('--idempotency-key ', 'Your own key for this send, sent as the Idempotency-Key header'); + +const LATER = 'With --send-after Reply holds the send until that moment, given with its offset and sent to Reply in UTC; a moment\n' + + 'without an offset is refused (usage.date). --schedule-id names the sending schedule Reply times the send by. The answer\n' + + 'then adds Reply\'s reference, send_after and state, each only when Reply gives it: status "sent" means Reply took the\n' + + 'send; state, when Reply gives it, says whether it has gone out: queued or sending is not yet, then sent, failed or\n' + + 'cancelled. direct-send get reads it later, and direct-send cancel stops one not yet sent. An\n' + + 'answer without state comes from a Reply that does not know --send-after and --schedule-id: it sent at once, as\n' + + 'without them. --idempotency-key goes as the Idempotency-Key header, never in the body. A Reply that knows the header\n' + + 'answers a repeat with the same key with the send the key first made; while that one is still being made the answer\n' + + 'is idempotency_key.in_use, and the same key on a different send is idempotency_key.reused. Neither sends anything.\n' + + 'A repeat of a send given a person\'s fields answers contact.already_held first, since the first one created the\n' + + 'contact: that is safe too, as nothing is sent twice. idempotency_key.reused names the send the key was first taken\n' + + 'for in details: reference, state and send_after, each only when Reply gives it. Any other refusal of a send Reply\n' + + 'already holds names that send the same way, beside the refusal\'s own details; its code is the refusal\'s own.\n' + + 'A 400 to the send with neither a code nor errors[] is Reply failing while it made the send: like a 5xx or a lost\n' + + 'answer, it is outcome.unknown (exit 3). A 400 with errors[] is reply.invalid_request, and nothing was sent.\n'; + +// The refusals of a send's key, the same on every direct send, after each send's own. +const KEY_CODES = ['idempotency_key.in_use', 'idempotency_key.reused']; + // One send's example with the person and the text both on stdin. const piped_send = (command: string, contact: string, message: string, flags: string): string=> `echo '{"contact":${contact},"message":${message}}' | ${P} contact ${command} --contact - ${flags} --message -`; const ANN_EMAIL = '{"email":"ann@example.com","first_name":"Ann"}'; const ANN_PROFILE = '{"linkedin_url":"https://www.linkedin.com/in/ann-example","first_name":"Ann"}'; -add_contact_options(contact_command.command('send-email'), true) +later_options(add_contact_options(contact_command.command('send-email'), true) .option('--email-account-id ', 'The mailbox to send from (see `account list`)') .option('--message ', 'Only -: the email {subject, body} as JSON on stdin') + .option('--track-links', 'Track the links in the email (off unless given)') + .option('--track-opens', 'Track the opens of the email (off unless given)')) .description('Send one email to a contact now, outside any sequence, from the mailbox you name') .addHelpText('after', help( [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12')], - ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted'], true, + ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', + 'contact.missing_variables', 'contact.rendering_failed', ...KEY_CODES], true, 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' - + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Reply sends a\n' - + 'direct email at once, outside the mailbox\'s daily limit and sending delay.\n' - + SENT_TO('email', 'email'), + + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Without\n' + + '--send-after, Reply sends a direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + 'Reply tracks neither links nor opens unless --track-links or --track-opens asks it to. An email sent within the\n' + + 'request adds rendered_subject and rendered_body, the subject and body as Reply filled them in, when Reply gives\n' + + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' + + 'details.missing_variables when Reply lists them, and contact.rendering_failed is a template Reply could not\n' + + 'render, its message in detail. Neither sends anything.\n' + + LATER + SENT_TO('email', 'email'), SEND_TWICE('email'))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -332,11 +366,12 @@ const linkedin_send = ( name: Exclude, description: string, message: string, examples: string[], codes: string[], extra: string, what: string, ): void=>{ - add_contact_options(contact_command.command(name), true) + later_options(add_contact_options(contact_command.command(name), true) .option('--linkedin-account-id ', 'The LinkedIn account to send from (see `account list`)') - .option('--message ', `Only -: the ${message} as JSON on stdin`) + .option('--message ', `Only -: the ${message} as JSON on stdin`)) .description(description) - .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes], true, extra + SENT_TO('linkedin', what), SEND_TWICE(what))) + .addHelpText('after', help(examples, [...LINKEDIN_SEND_CODES, ...codes, ...KEY_CODES], true, extra + LATER + SENT_TO('linkedin', what), + SEND_TWICE(what))) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); await handle_direct_send(name, cmd.opts(), ctx, g); @@ -406,6 +441,27 @@ inbox_command.command('list') await handle_inbox_list(cmd.opts(), ctx, g); })); +inbox_command.command('changes') + .option('--cursor ', 'Go on from the cursor a previous page answered, passed back unchanged') + .option('--since ', 'Start at this moment, inclusive, given with its offset; at most 30 days ago') + .option('--top ', 'Items per page, 1-1000 (default: Reply\'s)') + .description('One page of the inbox feed: each thread whose latest message changed, oldest first, read forward by cursor') + .addHelpText('after', help([ex('inbox changes --since 2026-11-01T00:00:00Z'), ex('inbox changes --cursor AQjfObhYHZgAAADjVg --top 200')], + ['inbox.cursor_expired', 'inbox.cursor_refused'], false, + 'Result: {"items","has_more","cursor"}, the items as Reply gives them, one per thread whose latest message, inbound\n' + + 'or outbound, changed: threadId, contactId, channel, lastActivityDate, flags (hasReply, hasBounce, hasAutoReply,\n' + + 'hasOutOfOffice) and lastMessage among them. Give --cursor or --since, not both; with neither, Reply reads the last\n' + + '30 days. Call again with the answered cursor while has_more is true, and loop on has_more, not on the number of\n' + + 'items: an empty page still carries a cursor, and when has_more is false that cursor is where the next read starts.\n' + + '--since goes to Reply in UTC; a moment without its offset is refused (usage.date). A cursor or a --since older\n' + + 'than 30 days is inbox.cursor_expired: start again with --since. A cursor Reply will not read otherwise,\n' + + 'unreadable or ahead of its clock, is inbox.cursor_refused, with cursor in details.fields; start again the same way.\n' + + 'A Reply without the feed answers reply.refused with status 404 and no reply_code.\n')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_inbox_changes(cmd.opts(), ctx, g); + })); + inbox_command.command('get') .argument('', 'Inbox thread id') .option('--limit ', 'Messages per page, 1-20 (default 20)') @@ -519,4 +575,40 @@ schedule_command.command('list') await handle_schedule_list(ctx, g); })); -export {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command}; +const direct_send_command = new Command('direct-send').description('Read or cancel a direct send Reply holds to send later'); + +const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_after","sent_at","message_id","failure_reason",\n' + + '"cancelled_at"}, Reply\'s fields under these names, each null when Reply gives none. The reference is Reply\'s, from the\n' + + 'answer of a send made with --send-after: email- or linkedin-, the form Reply\'s route takes. A reference of\n' + + 'any other form is refused before any call (usage.reference, exit 2), and nothing else is read from it. state is\n' + + 'Reply\'s own word: queued or sending is not yet sent, then sent, failed or cancelled. failure_code,\n' + + 'missing_variables, rendered_subject and rendered_body are added only when Reply gives them: failure_reason is a\n' + + 'sentence for a person, never parsed; failure_code is Reply\'s code for the failure, the one to branch on.\n' + + 'missing_variables lists the template variables Reply could not fill, and rendered_subject and rendered_body are the\n' + + 'text as Reply filled it in. A Reply without this route answers reply.refused with status 404 and no reply_code; a\n' + + 'reference of any other form never leaves the CLI, so that 404 means this Reply has no such route.\n' + + 'direct_send.not_found is a reference that Reply has no send for.\n'; + +direct_send_command.command('get') + .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') + .description('One direct send as Reply holds it: whether it has gone out, when, and why it failed') + .addHelpText('after', help([ex('direct-send get email-1001')], ['direct_send.not_found', 'direct_send.not_owned'], false, DIRECT_SEND)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_direct_send_get(cmd.args[0], ctx, g); + })); + +direct_send_command.command('cancel') + .argument('', 'The send\'s reference, email- or linkedin-, as a send made with --send-after answered it') + .description('Stop a direct send that has not gone out yet') + .addHelpText('after', help([ex('direct-send cancel email-1001')], + ['direct_send.not_found', 'direct_send.not_owned', 'direct_send.already_sent', 'direct_send.already_failed'], true, + DIRECT_SEND + 'The answer is the send as Reply now holds it, state cancelled. Cancelling a send already cancelled answers\n' + + 'it again, so running it again is safe. direct_send.already_sent and direct_send.already_failed mean the send\n' + + 'was past cancelling; nothing changed.\n')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_direct_send_cancel(cmd.args[0], ctx, g); + })); + +export {sequence_command, contact_list_command, contact_command, inbox_command, account_command, schedule_command, direct_send_command}; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index 19fe209..f88a7bb 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -1,8 +1,8 @@ import {PROGRAM_NAME} from '../config'; import {Operation_error, Unknown_outcome_error, UsageError, type Ids} from '../utils/errors'; import {parse_retry_after} from '../utils/client'; -import {call_reply, expect_object, refusal, reply_code_of, detail_of, open_session, type Answer} from './call'; -import {parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; +import {call_reply, expect_object, refusal, is_object, reply_code_of, detail_of, open_session, type Answer} from './call'; +import {parse_id, parse_moment, parse_idempotency_key, LARGEST_SAFE_ID, type Op_globals} from './options'; import {read_contact_input, type Contact_flags, type Contact_ref} from './contact-input'; import {contact_not_found, find_contact_by_address, import_contact, type Channel, type Ensured} from './contacts'; import {read_stdin_object, stdin_inputs} from './stdin-input'; @@ -10,7 +10,10 @@ import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; type Direct_send_name = 'send-email' | 'linkedin-connect' | 'linkedin-message' | 'linkedin-inmail' | 'linkedin-voice'; -type Direct_send_opts = Contact_flags & {emailAccountId?: string; linkedinAccountId?: string; message?: string}; +type Direct_send_opts = Contact_flags & { + emailAccountId?: string; linkedinAccountId?: string; message?: string; + sendAfter?: string; scheduleId?: string; idempotencyKey?: string; trackLinks?: boolean; trackOpens?: boolean; +}; type Text = Record; type Direct_send = { @@ -88,8 +91,41 @@ const read_text = (name: Direct_send_name, send: Direct_send, source: string | u return text; }; +// A refusal Reply publishes, under the status it comes with; details reads what the problem body +// carries beside its code, for the error output's details. +type Refusal = { + status: number; code: string; title: string; hint?: string; + details?: (body: Record) => Record | undefined; +}; + +// The keys a table names that hold a string in what Reply sent, under the names the CLI prints. +const picked = (keys: [string, string][], from: Record): Record=> + Object.fromEntries(keys.filter(([key])=>typeof from[key] === 'string').map(([key, to])=>[to, from[key]])); + +// A list of strings, or undefined for anything else. +const strings_of = (v: unknown): string[] | undefined=> + Array.isArray(v) && v.every(s=>typeof s === 'string') ? v : undefined; + +// The email route's refusals of the template it renders. Only that route renders one, so a LinkedIn +// send answering either code falls to the usual mapping. Each one is definite: nothing was sent. +const TEMPLATE_REFUSALS: Record> = { + email: { + 'contact.missingVariables': { + status: 400, code: 'contact.missing_variables', title: 'The email holds a template variable Reply could not fill, so nothing was sent.', + details: body=>{ + const missing = strings_of(body.missingVariables); + return missing === undefined ? undefined : {missing_variables: missing}; + }, + }, + 'contact.renderingFailed': { + status: 400, code: 'contact.rendering_failed', title: 'Reply could not render the email\'s template, so nothing was sent.', + }, + }, + linkedin: {}, +}; + // Reply's refusals of a direct send, by status and code. Each one is definite: nothing was sent. -const REFUSALS: Record = { +const REFUSALS: Record = { 'contact.emailAccountNotFound': { status: 400, code: 'email_account.not_found', title: 'Reply has no mailbox by that id that this account can send from, so nothing was sent.', }, @@ -142,7 +178,64 @@ const REFUSALS: Record = const LIMITS: Record = {'directLinkedIn.dailyLimitReached': 'daily', 'directLinkedIn.weeklyLimitReached': 'weekly'}; -const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ +// The codes of a send made for later, each Reply's code with the CLI code it maps to, here and +// nowhere else. A send route answers a refused Idempotency-Key under its own family: contact for the +// email, directLinkedIn for the LinkedIn sends. Neither sent anything. +const KEY_IN_USE: Refusal = { + status: 409, code: 'idempotency_key.in_use', title: 'Reply is still making an earlier send with this idempotency key, so this one sent nothing.', + hint: 'Run it again with the same key once that send is made: Reply answers a repeat with the send the key first made.', +}; +// Reply holds the send the key was first taken for, and may name it: a repeat built differently from +// the first attempt answers reused, so the caller still learns which send that was (send_refusal). +const KEY_REUSED: Refusal = { + status: 409, code: 'idempotency_key.reused', title: 'Reply already took this idempotency key for a different send, so nothing was sent.', + hint: 'Give each new send a key of its own.', +}; +const KEY_REFUSALS: Record> = { + email: {'contact.idempotencyKeyInUse': KEY_IN_USE, 'contact.idempotencyKeyReused': KEY_REUSED}, + linkedin: {'directLinkedIn.idempotencyKeyInUse': KEY_IN_USE, 'directLinkedIn.idempotencyKeyReused': KEY_REUSED}, +}; +// The routes that read and cancel a send by its reference answer under directSend: a reference this +// account has no send for, a send it may not act on, and, to a cancel, a send already gone out or failed. +const DIRECT_SEND_REFUSALS: Record = { + 'directSend.notFound': { + status: 404, code: 'direct_send.not_found', title: 'Reply has no direct send under that reference that this account can see.', + }, + 'directSend.notOwned': { + status: 403, code: 'direct_send.not_owned', title: 'The direct send is not one this user may act on.', + }, + 'directSend.alreadySent': { + status: 409, code: 'direct_send.already_sent', title: 'The direct send has already gone out, so it was not cancelled.', + }, + 'directSend.alreadyFailed': { + status: 409, code: 'direct_send.already_failed', title: 'The direct send has already failed, so it was not cancelled.', + }, +}; + +// The refusal a table holds for this answer, under the status Reply publishes it with, or undefined. +const known_refusal = (a: Answer, table: Record): Operation_error | undefined=>{ + const reply_code = reply_code_of(a); + const known = reply_code === undefined ? undefined : table[reply_code]; + return known !== undefined && known.status === a.status + ? new Operation_error(known.code, known.title, { + status: a.status, reply_code, detail: detail_of(a), hint: known.hint, details: known.details?.(a.data as Record), + }) + : undefined; +}; + +// An exception escaping a send reaches the caller as a 400 whose JSON carries neither a code nor +// errors[]: the send may already be made, as on a 5xx. A model validation names its fields in +// errors[], and a page that is not JSON is no exception of Reply's; both stay refusals. +const exception_of_send = (a: Answer): boolean=> + a.status === 400 && is_object(a.data) && a.data.code === undefined && a.data.errors === undefined; + +const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ + if (exception_of_send(a)) + { + return new Unknown_outcome_error('Reply failed while handling the send; it may or may not have been made.', { + status: a.status, detail: detail_of(a), + }); + } const reply_code = reply_code_of(a); if (a.status === 404 && (reply_code === 'contact.notFound' || reply_code === 'directLinkedIn.contactNotFound')) { @@ -155,22 +248,40 @@ const send_refusal = (a: Answer, contact_id: number): Operation_error=>{ retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: LIMITS[reply_code]}, }); } - const known = reply_code === undefined ? undefined : REFUSALS[reply_code]; - if (known !== undefined && known.status === a.status) + return known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, KEY_REFUSALS[by]) + ?? refusal(a, 'write'); +}; + +// A send Reply refused after its row existed, or the send a reused key was taken for, comes with +// Reply's reference, state and sendAfter: each one it gives as a string goes under details, beside +// the refusal's own. The refusal's code and class are its own either way. +const send_refusal = (a: Answer, contact_id: number, by: Channel): Operation_error=>{ + const e = refusal_of_send(a, contact_id, by); + const held = is_object(a.data) ? picked(HELD_KEYS, a.data) : {}; + if (Object.keys(held).length > 0) { - return new Operation_error(known.code, known.title, {status: a.status, reply_code, detail: detail_of(a)}); + e.details = {...e.details, ...held}; } - return refusal(a, 'write'); + return e; }; const positive_integer = (v: unknown): number | null=> typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null; +// What Reply says of the send itself, each only when it gives it: the reference that names the send +// for direct-send get and cancel, the moment it was accepted for, and whether it has gone out; and, +// for an email sent inside the request, its subject and body as Reply filled them in, before the +// signature and the tracking. An answer without them is printed as it always was. +const HELD_KEYS: [string, string][] = [['reference', 'reference'], ['sendAfter', 'send_after'], ['state', 'state']]; +const LATER_KEYS: [string, string][] = [...HELD_KEYS, ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]; + +const later_of = (sent: Record): Record=>picked(LATER_KEYS, sent); + // What the CLI answers for a send Reply took: the contact it went to, as the add commands name it, so // a caller can keep its id. Neither adds a time of its own: Reply's answer to a direct email carries // none, and a LinkedIn send's sentAtUtc is given as Reply gives it. -const result_of = (name: Direct_send_name, contact: Ensured, sent: Record): Record=> - name === 'send-email' +const result_of = (name: Direct_send_name, contact: Ensured, sent: Record): Record=>({ + ...(name === 'send-email' ? { status: 'sent', contact_id: contact.id, contact_created: contact.created, message_id: typeof sent.messageId === 'string' ? sent.messageId : null, @@ -181,7 +292,9 @@ const result_of = (name: Direct_send_name, contact: Ensured, sent: Record = {}; + if (opts.sendAfter !== undefined) + { + later.sendAfter = parse_moment(opts.sendAfter, '--send-after'); + } + if (opts.scheduleId !== undefined) + { + later.scheduleId = parse_id(opts.scheduleId, '--schedule-id'); + } + // Reply tracks neither unless asked, so each is sent only to turn it on. + if (opts.trackLinks === true) + { + later.trackLinks = true; + } + if (opts.trackOpens === true) + { + later.trackOpens = true; + } + const headers: Record = opts.idempotencyKey === undefined + ? {} : {'Idempotency-Key': parse_idempotency_key(opts.idempotencyKey)}; const s = await open_session(ctx, g); let sending = false; try { @@ -263,7 +397,8 @@ const handle_direct_send = async( ids.contact_id = ensured.id; } sending = true; - const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', send.body(account_id, text)); + const body = {...send.body(account_id, text), ...later}; + const a = await call_reply(s, 'POST', `/v3/contacts/${ensured.id}/${send.path}`, 'write', body, headers); if (name === 'linkedin-connect' && a.status === 409 && reply_code_of(a) === 'directLinkedIn.alreadyConnected') { // Nothing was sent, and nothing needs to be: the contact is already a connection. @@ -272,7 +407,7 @@ const handle_direct_send = async( } if (a.status !== 200) { - throw send_refusal(a, ensured.id); + throw send_refusal(a, ensured.id, by); } print_result(result_of(name, ensured, expect_object(a, 'write')), g); } catch (e) { @@ -289,5 +424,5 @@ const handle_direct_send = async( } }; -export {handle_direct_send}; +export {handle_direct_send, known_refusal, strings_of, DIRECT_SEND_REFUSALS}; export type {Direct_send_name, Direct_send_opts}; diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts new file mode 100644 index 0000000..188b0cd --- /dev/null +++ b/src/operations/direct-sends.ts @@ -0,0 +1,89 @@ +import {Unknown_outcome_error, UsageError} from '../utils/errors'; +import {call_reply, expect_object, refusal, unreadable, open_session, type Answer} from './call'; +import {known_refusal, strings_of, DIRECT_SEND_REFUSALS} from './direct-send'; +import {print_result} from './result'; +import type {Op_globals} from './options'; +import type {Cli_context} from '../context'; + +// Reply's route takes exactly this form and answers anything else with a bare 404, as it does when it +// has no such route at all. Checking the form here keeps that 404 meaning only the latter; nothing else +// is read from the reference, and the form leaves nothing to encode. +const REFERENCE = /^(email|linkedin)-[1-9]\d{0,9}$/; + +const path_of = (reference: string): string=>{ + if (reference.trim() === '') + { + throw new UsageError('No reference was given.', {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); + } + if (!REFERENCE.test(reference)) + { + throw new UsageError('That is not a reference Reply gives: email- or linkedin-, n from 1.', + {code: 'usage.reference', hint: 'A send made with --send-after answers its reference.'}); + } + return `/v3/direct-sends/${reference}`; +}; + +// What Reply says of the text it rendered and of a failure's code, each only when it gives it, as text +// or null, and the unfilled names as a list: an answer without them prints as it did before them. +const RENDERING_KEYS: [string, string][] = [['failureCode', 'failure_code'], ['renderedSubject', 'rendered_subject'], ['renderedBody', 'rendered_body']]; + +const rendering_of = (body: Record): Record=>{ + const given = (v: unknown): boolean=>typeof v === 'string' || v === null; + const out: Record = Object.fromEntries(RENDERING_KEYS.filter(([from])=>given(body[from])).map(([from, to])=>[to, body[from]])); + const missing = body.missingVariables === null ? null : strings_of(body.missingVariables); + if (missing !== undefined) + { + out.missing_variables = missing; + } + return out; +}; + +// A send as Reply holds it, under the CLI's names; one of its first fields that Reply leaves out is null. Its state is Reply's word, passed on as given, so a state the CLI does +// not know yet reaches the caller instead of failing the read. failure_reason is a sentence for a person and failure_code +// Reply's code for the same failure: neither is read here. +const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record=>{ + const body = expect_object(a, kind); + if (typeof body.reference !== 'string' || body.reference === '' || typeof body.state !== 'string' || body.state === '') + { + throw unreadable(a, kind); + } + const field = (name: string): unknown=>body[name] ?? null; + return { + reference: body.reference, channel: field('channel'), contact_id: field('contactId'), state: body.state, + send_after: field('sendAfter'), sent_at: field('sentAt'), message_id: field('messageId'), + failure_reason: field('failureReason'), ...rendering_of(body), cancelled_at: field('cancelledAt'), + }; +}; + +const handle_direct_send_get = async(reference: string, ctx: Cli_context, g: Op_globals): Promise=>{ + const path = path_of(reference); + const s = await open_session(ctx, g); + const a = await call_reply(s, 'GET', path, 'read'); + if (a.status !== 200) + { + throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? refusal(a, 'read'); + } + print_result(direct_send_of(a, 'read'), g); +}; + +const handle_direct_send_cancel = async(reference: string, ctx: Cli_context, g: Op_globals): Promise=>{ + const path = `${path_of(reference)}/cancel`; + const s = await open_session(ctx, g); + try { + const a = await call_reply(s, 'POST', path, 'write'); + if (a.status !== 200) + { + throw known_refusal(a, DIRECT_SEND_REFUSALS) ?? refusal(a, 'write'); + } + print_result(direct_send_of(a, 'write'), g); + } catch (e) { + // A cancel is safe to repeat: Reply answers a send already cancelled as cancelled again. + if (e instanceof Unknown_outcome_error) + { + e.hint = 'The send may or may not have been cancelled; running it again is safe, and direct-send get reads where it stands.'; + } + throw e; + } +}; + +export {handle_direct_send_get, handle_direct_send_cancel}; diff --git a/src/operations/inbox.ts b/src/operations/inbox.ts index c6392c3..962d7e1 100644 --- a/src/operations/inbox.ts +++ b/src/operations/inbox.ts @@ -1,9 +1,9 @@ import {Operation_error, UsageError} from '../utils/errors'; import { - call_reply, expect_object, read_page, refusal, reply_code_of, is_object, item_failure, unreadable, open_session, - type Answer, type Op_session, + call_reply, expect_object, read_page, refusal, reply_code_of, detail_of, invalid_fields, is_object, item_failure, unreadable, + open_session, type Answer, type Op_session, } from './call'; -import {parse_id, parse_int_in, parse_iso, parse_choice, type Op_globals} from './options'; +import {parse_id, parse_int_in, parse_iso, parse_moment, parse_choice, type Op_globals} from './options'; import {print_result, with_ids} from './result'; import type {Cli_context} from '../context'; @@ -66,6 +66,65 @@ const handle_inbox_list = async(opts: Inbox_list_opts, ctx: Cli_context, g: Op_g print_result({items: page.items, has_more: page.has_more}, g); }; +type Inbox_changes_opts = {cursor?: string; since?: string; top?: string}; + +const START_AGAIN = 'Start again with --since (at most 30 days ago), or with neither flag to read the last 30 days.'; + +// The feed keeps 30 days. Reply refuses a cursor or a since older than that under a code of its own. +const window_expired = (a: Answer): Operation_error | undefined=> + a.status === 400 && reply_code_of(a) === 'inboxThread.changeWindowExpired' + ? new Operation_error('inbox.cursor_expired', 'Reply keeps the feed for 30 days, and the cursor or --since reaches further back.', { + status: a.status, reply_code: reply_code_of(a), detail: detail_of(a), hint: START_AGAIN, + }) + : undefined; + +// Any other cursor Reply will not read (unreadable, or ahead of its clock) is a validation problem +// with no code that points at /cursor; they differ only in their text. +const cursor_refused = (a: Answer, fields: string[]): Operation_error=> + new Operation_error('inbox.cursor_refused', 'Reply would not read the cursor: unreadable, older than 30 days or ahead of its clock.', { + status: a.status, detail: detail_of(a), details: {fields}, hint: START_AGAIN, + }); + +const handle_inbox_changes = async(opts: Inbox_changes_opts, ctx: Cli_context, g: Op_globals): Promise=>{ + if (opts.cursor !== undefined && opts.since !== undefined) + { + throw new UsageError('Give --cursor or --since, not both.', {code: 'usage.inbox'}); + } + const query = new URLSearchParams(); + if (opts.cursor !== undefined) + { + // Reply's cursor is opaque: it goes back as given, never read. + if (opts.cursor.trim() === '') + { + throw new UsageError('--cursor is empty.', {code: 'usage.inbox', hint: 'Pass the cursor a previous page answered, unchanged.'}); + } + query.set('cursor', opts.cursor); + } + if (opts.since !== undefined) + { + // Reply's since is inclusive already, so the moment goes as given, in UTC. + query.set('since', parse_moment(opts.since, '--since')); + } + if (opts.top !== undefined) + { + query.set('top', String(parse_int_in(opts.top, '--top', 1, 1000, 0))); + } + const s = await open_session(ctx, g); + const q = query.toString(); + const a = await call_reply(s, 'GET', q === '' ? '/v3/inbox/threads/changes' : `/v3/inbox/threads/changes?${q}`, 'read'); + if (a.status !== 200) + { + const fields = opts.cursor !== undefined && a.status === 400 && reply_code_of(a) === undefined ? invalid_fields(a) : undefined; + throw window_expired(a) ?? (fields?.includes('cursor') ? cursor_refused(a, fields) : refusal(a, 'read')); + } + const body = expect_object(a, 'read'); + if (!Array.isArray(body.items) || typeof body.hasMore !== 'boolean' || typeof body.cursor !== 'string') + { + throw unreadable(a, 'read'); + } + print_result({items: body.items, has_more: body.hasMore, cursor: body.cursor}, g); +}; + // INTERIM (API gap): GET /v3/inbox/threads/{id} carries the thread's whole history inline, every // body included and with no limit, and the thread has no subject of its own. // Needed: a thread without its history inline, and a subject field. @@ -216,7 +275,7 @@ const handle_inbox_mark_unread = (thread_arg: string, ctx: Cli_context, g: Op_gl mark_thread(thread_arg, false, ctx, g); export { - handle_inbox_list, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, + handle_inbox_list, handle_inbox_changes, handle_inbox_get, handle_inbox_categories, handle_inbox_categorize, handle_inbox_mark_read, handle_inbox_mark_unread, thread_not_found, SOURCES, CHANNELS, }; export type {Channel}; diff --git a/src/operations/options.ts b/src/operations/options.ts index ed96167..7d6a330 100644 --- a/src/operations/options.ts +++ b/src/operations/options.ts @@ -67,7 +67,33 @@ const parse_iso = (raw: string, label: string): string=>{ return new Date(at).toISOString(); }; -const parse_choice = (raw: string | undefined, label: string, allowed: readonly T[]): T | undefined=>{ +const MOMENT = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:?\d{2})$/i; + +// A moment Reply acts at, such as a send's: a date and time with its offset, sent as the same instant +// in UTC. Without an offset the CLI would have to choose a zone for it, so one is refused. +const parse_moment = (raw: string, label: string): string=>{ + const m = MOMENT.exec(raw.trim()); + const at = m === null ? NaN : Date.parse(`${m[1]}T${m[2]}${m[3].toUpperCase().replace(/^([+-]\d{2})(\d{2})$/, '$1:$2')}`); + if (isNaN(at)) + { + throw new UsageError(`${label} must be a date and time with its offset, e.g. 2026-11-03T14:00:00Z.`, {code: 'usage.date', hint: `Got: ${raw}`}); + } + return new Date(at).toISOString(); +}; + +// An Idempotency-Key header as Reply takes one: 1 to 255 printable ASCII characters. A space at +// either end is refused rather than trimmed away by the header on its way out. +const parse_idempotency_key = (raw: string): string=>{ + if (!/^[\x21-\x7e](?:[\x20-\x7e]{0,253}[\x21-\x7e])?$/.test(raw)) + { + throw new UsageError('--idempotency-key must be 1 to 255 printable ASCII characters, with no space at either end.', { + code: 'usage.idempotency_key', + }); + } + return raw; +}; + +const parse_choice =(raw: string | undefined, label: string, allowed: readonly T[]): T | undefined=>{ if (raw === undefined) { return undefined; @@ -80,6 +106,6 @@ const parse_choice = (raw: string | undefined, label: string, }; export { - read_op_globals, parse_id, parse_int_in, parse_iso, parse_choice, LARGEST_REPLY_ID, LARGEST_SAFE_ID, + read_op_globals, parse_id, parse_int_in, parse_iso, parse_moment, parse_idempotency_key, parse_choice, LARGEST_REPLY_ID, LARGEST_SAFE_ID, }; export type {Op_globals};