inboxer 0.4.11 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +40 -20
  2. package/dist/app.js +4 -3
  3. package/dist/config.d.ts +2 -4
  4. package/dist/config.js +13 -4
  5. package/dist/core/address.d.ts +5 -1
  6. package/dist/core/address.js +11 -1
  7. package/dist/core/mail.d.ts +24 -13
  8. package/dist/core/mail.js +158 -85
  9. package/dist/core/sync.d.ts +6 -0
  10. package/dist/core/sync.js +22 -7
  11. package/dist/core/threads.d.ts +2 -0
  12. package/dist/core/threads.js +12 -1
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +5 -5
  15. package/dist/mcp.js +8 -8
  16. package/dist/provider/index.d.ts +2 -1
  17. package/dist/provider/index.js +10 -6
  18. package/dist/provider/kapso.d.ts +8 -0
  19. package/dist/provider/kapso.js +198 -0
  20. package/dist/provider/resend.d.ts +1 -1
  21. package/dist/provider/resend.js +14 -10
  22. package/dist/provider/types.d.ts +35 -16
  23. package/dist/store.d.ts +2 -2
  24. package/dist/store.js +4 -4
  25. package/dist/types.d.ts +10 -2
  26. package/dist/ui/routes.js +15 -11
  27. package/dist/ui/static/style.css +5 -0
  28. package/dist/ui/views.d.ts +7 -5
  29. package/dist/ui/views.js +18 -16
  30. package/package.json +1 -1
  31. package/skills/inboxer/SKILL.md +15 -8
  32. package/src/app.ts +4 -3
  33. package/src/config.ts +10 -3
  34. package/src/core/address.ts +13 -1
  35. package/src/core/mail.ts +162 -89
  36. package/src/core/sync.ts +23 -7
  37. package/src/core/threads.ts +12 -1
  38. package/src/index.ts +10 -8
  39. package/src/mcp.ts +8 -8
  40. package/src/provider/index.ts +9 -5
  41. package/src/provider/kapso.ts +251 -0
  42. package/src/provider/resend.ts +15 -11
  43. package/src/provider/types.ts +38 -14
  44. package/src/store.ts +4 -4
  45. package/src/types.ts +10 -2
  46. package/src/ui/routes.ts +16 -11
  47. package/src/ui/static/style.css +5 -0
  48. package/src/ui/views.ts +20 -17
@@ -40,16 +40,16 @@ export interface ContextView {
40
40
  context: Context | null;
41
41
  contacts: Contact[];
42
42
  }
43
- /** A draft for review, on our side of its thread. */
44
- export declare function draftCard(d: Message): View;
43
+ /** A draft for review, on our side of its thread; without actions where the session can only read. */
44
+ export declare function draftCard(d: Message, canAct: boolean): View;
45
45
  export interface DraftForm {
46
46
  to: string;
47
47
  cc: string;
48
48
  subject: string;
49
49
  text: string;
50
50
  }
51
- /** The edit sheet's content; one draft is edited at a time. */
52
- export declare function draftEditor(d: Message, form: DraftForm, conflict: Message | null): View;
51
+ /** The edit sheet's content; one draft is edited at a time. A chat message has a recipient and a body only. */
52
+ export declare function draftEditor(d: Message, form: DraftForm, conflict: Message | null, chat: boolean): View;
53
53
  /** The editor's attachment list with remove buttons, and the picker that drag and drop also feeds. */
54
54
  export declare function draftFiles(d: Message, error: string | null): View;
55
55
  export declare function draftDone(id: string, text: string): View;
@@ -71,6 +71,7 @@ interface ThreadListOptions {
71
71
  addressOf: (account: string) => string;
72
72
  filter: InboxFilter;
73
73
  own: (address: string) => boolean;
74
+ isChat: (mailbox: string) => boolean;
74
75
  current: string | null;
75
76
  }
76
77
  /** The thread list and the open thread side by side; a phone shows one of the two. */
@@ -79,12 +80,13 @@ export interface ThreadEntry {
79
80
  at: string;
80
81
  view: View;
81
82
  }
82
- /** The conversation, oldest first, with day separators, a reply box and the context panel. */
83
+ /** The conversation, oldest first, with day separators, a reply box and the context panel. A chat is titled by who it is with. */
83
84
  export declare function threadView(thread: Thread, entries: ThreadEntry[], ctx: ContextView, opts: {
84
85
  back: string;
85
86
  filter: InboxFilter;
86
87
  own: (address: string) => boolean;
87
88
  account: string;
89
+ chat: boolean;
88
90
  reply: {
89
91
  allowed: boolean;
90
92
  replyAll: boolean;
package/dist/ui/views.js CHANGED
@@ -60,7 +60,7 @@ function displayName(address) {
60
60
  return match ? match[1] : bareAddress(address);
61
61
  }
62
62
  function initials(address) {
63
- const name = displayName(address);
63
+ const name = displayName(address).replace(/^\+/, "");
64
64
  const words = (name.includes("@") ? name.split("@")[0] : name).split(/[\s._-]+/).filter(Boolean);
65
65
  return (words.length > 1 ? words[0][0] + words[1][0] : (words[0] ?? "?").slice(0, 2)).toUpperCase();
66
66
  }
@@ -248,8 +248,8 @@ function pendingCard(d) {
248
248
  <i class="countdown" style="animation-duration: ${left}ms"></i>
249
249
  </article>`;
250
250
  }
251
- /** A draft for review, on our side of its thread. */
252
- export function draftCard(d) {
251
+ /** A draft for review, on our side of its thread; without actions where the session can only read. */
252
+ export function draftCard(d, canAct) {
253
253
  if (d.pending)
254
254
  return pendingCard(d);
255
255
  return h `<article class="card draft" id="draft-${d.id}">
@@ -260,20 +260,20 @@ export function draftCard(d) {
260
260
  </div>
261
261
  <div class="draft-head">
262
262
  <div class="meta"><span>${S.to}: <strong>${d.to.join(", ")}</strong></span>${when(d.cc.length, () => h `<span>${S.cc}: ${d.cc.join(", ")}</span>`)}</div>
263
- <div class="subject">${d.subject}</div>
263
+ ${when(d.subject, () => h `<div class="subject">${d.subject}</div>`)}
264
264
  </div>
265
265
  ${when(d.note, () => h `<div class="note">${d.note}</div>`)}
266
266
  <pre class="body">${d.text}</pre>
267
267
  ${attachments(d)}
268
- <div class="actions">
268
+ ${when(canAct, () => h `<div class="actions">
269
269
  <button class="danger" hx-post="/drafts/${d.id}/discard" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.discard}</button>
270
270
  <button hx-get="/drafts/${d.id}/edit" hx-target="#edit-sheet" hx-swap="innerHTML">${S.edit}</button>
271
271
  <button class="primary" hx-post="/drafts/${d.id}/send" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.send}</button>
272
- </div>
272
+ </div>`)}
273
273
  </article>`;
274
274
  }
275
- /** The edit sheet's content; one draft is edited at a time. */
276
- export function draftEditor(d, form, conflict) {
275
+ /** The edit sheet's content; one draft is edited at a time. A chat message has a recipient and a body only. */
276
+ export function draftEditor(d, form, conflict, chat) {
277
277
  const version = conflict ? conflict.version : d.version;
278
278
  return h `<form class="${conflict ? "conflict" : ""}" hx-post="/drafts/${d.id}/save" hx-target="#edit-sheet" hx-swap="innerHTML" data-drop>
279
279
  <div class="grabber" aria-hidden="true"></div>
@@ -294,16 +294,16 @@ export function draftEditor(d, form, conflict) {
294
294
  <div class="field">
295
295
  <label for="to-${d.id}">${S.to}</label>
296
296
  <input id="to-${d.id}" name="to" value="${form.to}" autocomplete="off" required>
297
- ${when(!form.cc, () => h `<button type="button" class="link" onclick="this.remove();var r=document.getElementById('cc-row-${d.id}');r.hidden=false;r.querySelector('input').focus()">${S.cc}</button>`)}
297
+ ${when(!chat && !form.cc, () => h `<button type="button" class="link" onclick="this.remove();var r=document.getElementById('cc-row-${d.id}');r.hidden=false;r.querySelector('input').focus()">${S.cc}</button>`)}
298
298
  </div>
299
- <div class="field" id="cc-row-${d.id}" ${raw(form.cc ? "" : "hidden")}>
299
+ ${when(!chat, () => h `<div class="field" id="cc-row-${d.id}" ${raw(form.cc ? "" : "hidden")}>
300
300
  <label for="cc-${d.id}">${S.cc}</label>
301
301
  <input id="cc-${d.id}" name="cc" value="${form.cc}" autocomplete="off">
302
302
  </div>
303
303
  <div class="field">
304
304
  <label for="subject-${d.id}">${S.subject}</label>
305
305
  <input id="subject-${d.id}" name="subject" value="${form.subject}" required>
306
- </div>
306
+ </div>`)}
307
307
  <textarea id="text-${d.id}" name="text" aria-label="${S.body}" required>${form.text}</textarea>
308
308
  <div class="sheet-actions">
309
309
  ${draftFiles(d, null)}
@@ -371,12 +371,13 @@ export function threadList(threads, opts) {
371
371
  </section>`;
372
372
  }
373
373
  function threadRow(t, opts) {
374
- const people = t.participants.filter(p => !opts.own(p));
374
+ const chat = opts.isChat(t.mailbox);
375
+ const people = t.participants.filter(p => !opts.own(p)).map(p => (chat && t.names[p]) || p);
375
376
  return h `<a class="row ${t.unread ? "unread" : ""}" href="/threads/${t.id}?${inboxQuery(opts.filter)}" ${raw(t.id === opts.current ? 'aria-current="page"' : "")}>
376
377
  <span class="avatar" aria-hidden="true">${initials(people[0] ?? t.mailbox)}</span>
377
378
  <span class="row-main">
378
379
  <span class="row-top"><span class="who">${people.join(", ") || t.mailbox}</span><time datetime="${t.last_at}">${formatDate(t.last_at)}</time></span>
379
- <span class="row-subject">${t.subject || "—"}</span>
380
+ ${when(!chat, () => h `<span class="row-subject">${t.subject || "—"}</span>`)}
380
381
  ${when(t.has_draft || opts.accounts.length > 1 || t.unread, () => h `<span class="row-tags">
381
382
  ${when(t.has_draft, () => h `<span class="badge draft">${S.hasDraft}</span>`)}
382
383
  ${when(opts.accounts.length > 1, () => mailboxBadge(opts.addressOf(opts.accountOf(t))))}
@@ -389,12 +390,13 @@ function threadRow(t, opts) {
389
390
  export function inboxPage(list, thread) {
390
391
  return h `<div class="split ${thread ? "has-thread" : ""}">${list}<section class="pane">${thread ?? ""}</section></div>`;
391
392
  }
392
- /** The conversation, oldest first, with day separators, a reply box and the context panel. */
393
+ /** The conversation, oldest first, with day separators, a reply box and the context panel. A chat is titled by who it is with. */
393
394
  export function threadView(thread, entries, ctx, opts) {
394
395
  const query = inboxQuery(opts.filter);
395
396
  const rows = contextRows(ctx);
396
397
  const people = thread.participants.filter(p => !opts.own(p));
397
- const title = h `<span class="thread-subject">${thread.subject || "—"}</span><span class="thread-meta">${[...people, opts.account].join(" · ")}</span>`;
398
+ const heading = opts.chat ? people.map(p => thread.names[p] ?? p).join(", ") : thread.subject;
399
+ const title = h `<span class="thread-subject">${heading || "—"}</span><span class="thread-meta">${[...people, opts.account].join(" · ")}</span>`;
398
400
  const items = [];
399
401
  let day = "";
400
402
  for (const entry of entries) {
@@ -416,7 +418,7 @@ export function threadView(thread, entries, ctx, opts) {
416
418
  <div class="messages" id="messages" data-live data-scroll-end>${join(items)}</div>
417
419
  ${when(opts.reply.allowed, () => h `<form class="composer" method="post" action="/threads/${thread.id}/reply?${query}">
418
420
  ${when(opts.reply.replyAll, () => h `<label class="reply-all"><input type="checkbox" name="reply_all" value="1">${S.replyAll}</label>`)}
419
- <button type="button" class="icon-btn" aria-label="${S.fullReply}" title="${S.fullReply}" hx-get="/threads/${thread.id}/reply/full?${query}" hx-include="closest form" hx-target="#edit-sheet" hx-swap="innerHTML">${icon("plus")}</button>
421
+ ${when(!opts.chat, () => h `<button type="button" class="icon-btn" aria-label="${S.fullReply}" title="${S.fullReply}" hx-get="/threads/${thread.id}/reply/full?${query}" hx-include="closest form" hx-target="#edit-sheet" hx-swap="innerHTML">${icon("plus")}</button>`)}
420
422
  <textarea name="text" rows="1" aria-label="${S.reply}" placeholder="${S.reply}…" required></textarea>
421
423
  <button type="submit" name="action" value="save" class="icon-btn" aria-label="${S.saveDraft}" title="${S.saveDraft}">${icon("drafts")}</button>
422
424
  <button type="submit" name="action" value="send" class="primary send" aria-label="${S.send}" title="${S.send}">${icon("send")}</button>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inboxer",
3
- "version": "0.4.11",
3
+ "version": "0.5.0",
4
4
  "description": "A self-hosted mail layer for agents: persists every inbound and outbound email, exposes an MCP server, and ships a minimal UI to review drafts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,23 +21,25 @@ const config = {
21
21
  syncIntervalMin: 10,
22
22
  threadWindowDays: 30,
23
23
  mailboxes: {
24
- support: { address: "support@example.com", name: "Example Support",
24
+ support: { address: "support@example.com", name: "Example Support", provider: "resend",
25
25
  signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>",
26
26
  tokens: { "support-schedule": "<openssl rand -hex 32>" } } // support only
27
27
  },
28
- provider: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." },
28
+ providers: { resend: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." } },
29
29
  mcp: { tokens: { "admin": "<openssl rand -hex 32>" }, maxAttachmentMb: 10 }, // every mailbox
30
30
  ui: { cookieSecret: "<openssl rand -hex 32>", loginLinkTtlMin: 10, undoSec: 10, maxUploadMb: 20 }
31
31
  };
32
32
  ```
33
33
 
34
- - Every key above is required except the mailbox signatures and mailbox tokens; `createInboxer` throws on a missing or invalid one. There are no defaults.
34
+ - Every key above is required except the mailbox signatures, mailbox tokens and `uiReadOnly`; `createInboxer` throws on a missing or invalid one. There are no defaults.
35
35
  - `mailboxes` is an object keyed by id. `catchall` is reserved: unknown recipients land there, grouped by the address they were written to. It answers as that address, with the name and signature of a mailbox on the same domain, and cannot start new mail.
36
- - `provider.apiKey`, `provider.webhookSecret`, every token and `ui.cookieSecret` are secrets: keep them out of Git and out of logs.
36
+ - Each mailbox names its `provider`, a key of `providers`. That key is the webhook route (`/webhooks/<name>`) and is stored on every message: do not rename it once there is data.
37
+ - `uiReadOnly: true` on a mailbox lets browser sessions read and organize it but not draft or send; MCP tokens still can.
38
+ - Every provider `apiKey` and `webhookSecret`, every token and `ui.cookieSecret` are secrets: keep them out of Git and out of logs.
37
39
 
38
40
  ## Serve
39
41
 
40
- `createInboxer(cfg, { provider? })` is synchronous, does not listen, and returns `{ fetch, handler, ready, close }`. Requests wait for `ready`.
42
+ `createInboxer(cfg, { providers? })` is synchronous, does not listen, and returns `{ fetch, handler, ready, close }`. Requests wait for `ready`.
41
43
 
42
44
  ```typescript
43
45
  import { createInboxer } from "inboxer";
@@ -60,16 +62,20 @@ Keep two domains apart: the app runs on its own host, e.g. `inboxer.example.com`
60
62
  2. MX and TXT — `send` (bounces and SPF): MX `send` → `feedback-smtp.us-east-1.amazonses.com`, priority `10`; TXT `send` → `v=spf1 include:amazonses.com ~all`.
61
63
  3. TXT — DMARC: `_dmarc` → `v=DMARC1; p=none; rua=mailto:dmarc@example.com`.
62
64
  4. MX — receiving: `@` → `inbound-smtp.us-east-1.amazonaws.com`, priority `10`. This moves the whole domain's mail to Resend; unknown addresses land in `catchall`. To keep the root elsewhere, put the addresses and this MX on a subdomain. Wait until Resend shows the domain verified.
63
- 5. Create a full-access API key (Inboxer reads emails, not only sends) → `provider.apiKey`.
65
+ 5. Create a full-access API key (Inboxer reads emails, not only sends) → the provider's `apiKey`.
64
66
  6. Deploy Inboxer over HTTPS at `publicUrl`.
65
- 7. Create a webhook at `<publicUrl>/webhooks/resend` for `email.received`, `email.sent`, `email.delivered`, `email.bounced`, `email.failed`, `email.suppressed` → its signing secret is `provider.webhookSecret`.
67
+ 7. Create a webhook at `<publicUrl>/webhooks/resend` for `email.received`, `email.sent`, `email.delivered`, `email.bounced`, `email.failed`, `email.suppressed` → its signing secret is the provider's `webhookSecret`.
66
68
  8. Restart and send a test email from outside. A webhook `401` means a wrong signing secret.
67
69
 
68
70
  Missed webhooks are recovered by the periodic sync.
69
71
 
72
+ ## WhatsApp through Kapso
73
+
74
+ A WhatsApp number is a mailbox of kind `chat`: `mailboxes: { whatsapp: { address: "+12025550100", name: "Example", provider: "whatsapp" } }` with `providers: { whatsapp: { type: "kapso", apiKey, webhookSecret, phoneNumberId } }`. In Kapso, add a webhook of kind `kapso` on the number at `<publicUrl>/webhooks/whatsapp` for `whatsapp.message.received`, `.sent`, `.delivered`, `.read` and `.failed`; its secret is `webhookSecret`. A number takes several webhooks, so an existing bot keeps its own. Inboxer mirrors everything on the line, including what a bot sends through Kapso directly, and its first sync reads the whole history.
75
+
70
76
  ## Another provider
71
77
 
72
- Implement `MailProvider` (exported types) and pass it as `createInboxer(cfg, { provider })`; `cfg.provider.type` is then not required. `send()` must not deliver twice for the same `idempotencyKey` (Inboxer passes the draft id). `parseWebhook()` throws `WebhookSignatureError` on a bad signature.
78
+ Implement `MailProvider` (exported types) and pass it as `createInboxer(cfg, { providers: { <name>: instance } })`; `cfg.providers` is then not read. `send()` must not deliver twice for the same `idempotencyKey` (Inboxer passes the draft id). `parseWebhook()` throws `WebhookSignatureError` on a bad signature.
73
79
 
74
80
  ## Connect an MCP client
75
81
 
@@ -97,6 +103,7 @@ Rules for agents:
97
103
  - Pass a **message id** as `reply_to_id` or `message_id`. Recipients, `Re:` subject, `In-Reply-To` and `References` are derived; do not set them by hand. `reply_all` adds the original To/Cc minus the mailbox itself.
98
104
  - Put what the reviewer must do or check in `note`, not in the body. The note is never sent.
99
105
  - A new conversation needs `mailbox`, `to` and `subject`.
106
+ - `list_mailboxes` gives each mailbox's `kind`. In a `chat` mailbox (a phone line) addresses are phone numbers, a thread is the whole conversation with one number, and a message is plain text: no `subject`, `cc`, `bcc` or `html`. `send({ mailbox, to: ["+5491155550000"], text })` joins that number's thread. Messages with status `read` were seen by the recipient. WhatsApp only delivers free text within 24 hours of the person's last message; a later send fails.
100
107
  - `update_draft` needs the draft's current `version`. On a conflict the error includes `current`; re-read it before retrying.
101
108
  - A draft whose `pending` is set is in the reviewer's undo window and is about to be sent or discarded; `update_draft` fails until it ends.
102
109
  - Never `force` an update of a draft with `edited_by_human: true` unless the user explicitly asks; the human's edit wins.
package/src/app.ts CHANGED
@@ -33,15 +33,16 @@ export function buildApp(mail: Mail, access: Access, cfg: InboxerConfig, ready:
33
33
 
34
34
  // A failure answers 500 so the provider retries; ingest is idempotent.
35
35
  app.post("/webhooks/:provider", async c => {
36
- if (c.req.param("provider") !== mail.provider.name) return c.notFound();
36
+ const name = c.req.param("provider");
37
+ if (!Object.hasOwn(mail.providers, name)) return c.notFound();
37
38
  let events;
38
39
  try {
39
- events = mail.provider.parseWebhook({ headers: c.req.raw.headers, body: await c.req.text() });
40
+ events = mail.providers[name]!.parseWebhook({ headers: c.req.raw.headers, body: await c.req.text() });
40
41
  } catch (err) {
41
42
  if (err instanceof WebhookSignatureError) return c.text("Invalid signature", 401);
42
43
  throw err;
43
44
  }
44
- for (const event of events) await mail.applyEvent(event);
45
+ for (const event of events) await mail.applyEvent(name, event);
45
46
  return c.json({ ok: true });
46
47
  });
47
48
 
package/src/config.ts CHANGED
@@ -23,23 +23,30 @@ function requirePositive(value: unknown, path: string): void {
23
23
  if (typeof value !== "number" || !(value > 0)) fail(path, "a positive number");
24
24
  }
25
25
 
26
- /** Asserts the shape `createInboxer` relies on. */
27
- export function assertConfig(cfg: InboxerConfig, { requireProvider }: { requireProvider: boolean }): void {
26
+ /** Asserts the shape `createInboxer` relies on. `injectedProviders` names provider instances passed in place of `cfg.providers`. */
27
+ export function assertConfig(cfg: InboxerConfig, injectedProviders?: string[]): void {
28
28
  requireString(cfg.publicUrl, "publicUrl");
29
29
  requireString(cfg.dataDir, "dataDir");
30
30
  if (!isAbsolute(cfg.dataDir)) fail("dataDir", "an absolute path");
31
31
  requirePositive(cfg.syncIntervalMin, "syncIntervalMin");
32
32
  requirePositive(cfg.threadWindowDays, "threadWindowDays");
33
33
 
34
+ if (!injectedProviders) {
35
+ if (!cfg.providers || typeof cfg.providers !== "object") fail("providers", "an object keyed by provider name");
36
+ for (const [name, provider] of Object.entries(cfg.providers)) requireString(provider?.type, `providers.${name}.type`);
37
+ }
38
+ const providers = injectedProviders ?? Object.keys(cfg.providers);
39
+
34
40
  if (!cfg.mailboxes || typeof cfg.mailboxes !== "object") fail("mailboxes", "an object keyed by mailbox id");
35
41
  if (CATCHALL in cfg.mailboxes) fail(`mailboxes.${CATCHALL}`, "absent (the id is reserved)");
36
42
  for (const [id, mailbox] of Object.entries(cfg.mailboxes)) {
37
43
  requireString(mailbox.address, `mailboxes.${id}.address`);
38
44
  requireString(mailbox.name, `mailboxes.${id}.name`);
45
+ if (!providers.includes(mailbox.provider)) fail(`mailboxes.${id}.provider`, `one of: ${providers.join(", ")}`);
46
+ if (mailbox.uiReadOnly !== undefined && mailbox.uiReadOnly !== true) fail(`mailboxes.${id}.uiReadOnly`, "true or absent");
39
47
  if (mailbox.tokens !== undefined && (!mailbox.tokens || typeof mailbox.tokens !== "object")) fail(`mailboxes.${id}.tokens`, "an object of named tokens");
40
48
  }
41
49
 
42
- if (requireProvider) requireString(cfg.provider?.type, "provider.type");
43
50
  if (!cfg.mcp?.tokens || typeof cfg.mcp.tokens !== "object") fail("mcp.tokens", "an object of named tokens");
44
51
  for (const [name, token] of Object.entries(cfg.mcp.tokens)) requireString(token, `mcp.tokens.${name}`);
45
52
  mcpTokens(cfg);
@@ -1,9 +1,21 @@
1
- /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. */
1
+ /** Bare, lowercased address from `Name <a@b.com>` or `a@b.com`. A chat address is a phone number: `+5491155550000`. */
2
2
  export function bareAddress(value: string): string {
3
3
  const match = /<([^<>]+)>\s*$/.exec(value);
4
4
  return (match ? match[1]! : value).trim().toLowerCase();
5
5
  }
6
6
 
7
+ /** Display name from `Name <address>`, or null when there is none. */
8
+ export function nameOf(value: string): string | null {
9
+ const match = /^\s*"?([^"<]+?)"?\s*</.exec(value);
10
+ return match ? match[1]! : null;
11
+ }
12
+
13
+ /** The E.164 address of a phone number written with or without the plus, spaces or dashes; null when it is not one. */
14
+ export function phoneAddress(value: string): string | null {
15
+ const digits = bareAddress(value).replace(/[\s().-]/g, "").replace(/^\+/, "");
16
+ return /^[1-9]\d{6,14}$/.test(digits) ? `+${digits}` : null;
17
+ }
18
+
7
19
  export function formatAddress(name: string, address: string): string {
8
20
  return `"${name.replace(/["\\]/g, "\\$&")}" <${address}>`;
9
21
  }