domma-cms 1.28.4 → 1.29.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 (98) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/admin/js/lib/contacts-arrange.js +1 -1
  3. package/docs/DommaFeatures.md +5 -3
  4. package/package.json +4 -1
  5. package/plugins/_lib/admin/mail/body-menu.js +2 -0
  6. package/plugins/_lib/admin/mail/cms-host.js +22 -0
  7. package/plugins/_lib/admin/mail/compose-window.js +1027 -1021
  8. package/plugins/_lib/admin/mail/contacts.js +10 -8
  9. package/plugins/_lib/admin/mail/diagnostics-section.js +2 -0
  10. package/plugins/_lib/admin/mail/drag-drop.js +46 -0
  11. package/plugins/_lib/admin/mail/folder-tree.js +2 -0
  12. package/plugins/_lib/admin/mail/font-controls.js +6 -4
  13. package/plugins/_lib/admin/mail/fonts.js +1 -1
  14. package/plugins/_lib/admin/mail/host-context.js +87 -0
  15. package/plugins/_lib/admin/mail/identity.js +2 -0
  16. package/plugins/_lib/admin/mail/image-senders-section.js +2 -0
  17. package/plugins/_lib/admin/mail/keyboard.js +2 -0
  18. package/plugins/_lib/admin/mail/mail.css +1 -1
  19. package/plugins/_lib/admin/mail/mail.html +4 -0
  20. package/plugins/_lib/admin/mail/message-actions.js +2 -0
  21. package/plugins/_lib/admin/mail/oauth-panel.js +2 -0
  22. package/plugins/_lib/admin/mail/panes.js +2 -0
  23. package/plugins/_lib/admin/mail/reader-kit.js +2 -0
  24. package/plugins/_lib/admin/mail/reader-runtime.js +6534 -0
  25. package/plugins/_lib/admin/mail/reader-view.js +9 -6380
  26. package/plugins/_lib/admin/mail/resizable.js +2 -0
  27. package/plugins/_lib/admin/mail/restore-spam.js +13 -0
  28. package/plugins/_lib/admin/mail/rules.js +14 -0
  29. package/plugins/_lib/admin/mail/scheduling.js +4 -1
  30. package/plugins/_lib/admin/mail/section-kit.js +4 -1
  31. package/plugins/_lib/admin/mail/security-note.js +2 -0
  32. package/plugins/_lib/admin/mail/settings-section.js +11 -10
  33. package/plugins/_lib/admin/mail/templates.js +5 -2
  34. package/plugins/_lib/admin/mail/threads.js +2 -0
  35. package/plugins/_lib/admin/mail/vacation.js +16 -2
  36. package/plugins/_lib/admin/mail/when-closed.js +24 -2
  37. package/plugins/_lib/admin/ui/dates.js +2 -0
  38. package/plugins/_lib/admin/ui/resizable.js +7 -5
  39. package/plugins/_lib/contacts/mailContact.js +69 -0
  40. package/plugins/_lib/contacts/model.js +199 -0
  41. package/plugins/_lib/domma-mail-contacts.lock.json +10 -0
  42. package/plugins/_lib/domma-mail.lock.json +85 -0
  43. package/plugins/_lib/mail/accountFileStore.js +66 -0
  44. package/plugins/_lib/mail/accountRepository.js +617 -0
  45. package/plugins/_lib/mail/accountRoutes.js +130 -0
  46. package/plugins/_lib/mail/accounts.js +66 -940
  47. package/plugins/_lib/mail/automationLock.js +10 -0
  48. package/plugins/_lib/mail/bodyTokenProvider.js +36 -0
  49. package/plugins/_lib/mail/bodyTokens.js +5 -99
  50. package/plugins/_lib/mail/compose.js +5 -3
  51. package/plugins/_lib/mail/defaults.js +2 -0
  52. package/plugins/_lib/mail/envelope.js +3 -1
  53. package/plugins/_lib/mail/folderActions.js +83 -0
  54. package/plugins/_lib/mail/folderRuntime.js +109 -0
  55. package/plugins/_lib/mail/folders.js +4 -9
  56. package/plugins/_lib/mail/imapPool.js +11 -389
  57. package/plugins/_lib/mail/imapPoolRuntime.js +396 -0
  58. package/plugins/_lib/mail/mbox.js +2 -0
  59. package/plugins/_lib/mail/message-action.js +2 -0
  60. package/plugins/_lib/mail/messageSecurity.js +4 -111
  61. package/plugins/_lib/mail/messageSecurityProvider.js +116 -0
  62. package/plugins/_lib/mail/networkAddresses.js +77 -0
  63. package/plugins/_lib/mail/networkPolicy.js +62 -0
  64. package/plugins/_lib/mail/oauth.js +3 -451
  65. package/plugins/_lib/mail/oauthAccounts.js +178 -0
  66. package/plugins/_lib/mail/oauthRouteRuntime.js +282 -0
  67. package/plugins/_lib/mail/oauthRoutes.js +7 -289
  68. package/plugins/_lib/mail/oauthRuntime.js +456 -0
  69. package/plugins/_lib/mail/pollSchedule.js +2 -0
  70. package/plugins/_lib/mail/poller.js +4 -136
  71. package/plugins/_lib/mail/pollerRuntime.js +150 -0
  72. package/plugins/_lib/mail/priority.js +2 -0
  73. package/plugins/_lib/mail/publicMailbox.js +27 -0
  74. package/plugins/_lib/mail/readRoutes.js +14 -827
  75. package/plugins/_lib/mail/readRuntime.js +701 -0
  76. package/plugins/_lib/mail/render.js +2 -0
  77. package/plugins/_lib/mail/ruleRunner.js +27 -10
  78. package/plugins/_lib/mail/scheduler.js +11 -279
  79. package/plugins/_lib/mail/schedulerRuntime.js +259 -0
  80. package/plugins/_lib/mail/secretProvider.js +112 -0
  81. package/plugins/_lib/mail/secretbox.js +12 -225
  82. package/plugins/_lib/mail/send.js +21 -537
  83. package/plugins/_lib/mail/sieve.js +211 -0
  84. package/plugins/_lib/mail/sieveHost.js +24 -0
  85. package/plugins/_lib/mail/smtpService.js +553 -0
  86. package/plugins/_lib/mail/snoozeRuntime.js +60 -0
  87. package/plugins/_lib/mail/store.js +122 -64
  88. package/plugins/_lib/mail/subscriptions.js +11 -0
  89. package/plugins/_lib/mail/sync.js +64 -290
  90. package/plugins/_lib/mail/syncPlan.js +2 -0
  91. package/plugins/_lib/mail/syncRuntime.js +255 -0
  92. package/plugins/_lib/mail/syncSelection.js +2 -0
  93. package/plugins/_lib/mail/unreadBadge.js +2 -0
  94. package/plugins/_lib/mail/unsubscribe.js +2 -0
  95. package/plugins/_lib/mail/vacationRunner.js +3 -116
  96. package/plugins/_lib/mail/vacationRuntime.js +70 -0
  97. package/plugins/_lib/mail/write.js +44 -13
  98. package/server/routes/api/contacts.js +2 -196
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/resizable.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * The mail reader's resizable slideovers.
3
5
  *
@@ -0,0 +1,13 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/restore-spam.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ /** Undo restores both junk status and the original folder, following each UID remap. */
4
+ export async function restoreSpam({api, base, account, from, destination, uids, spam}) {
5
+ const query = new URLSearchParams({account, folder: from});
6
+ const result = await api(`${base}/messages/spam?${query}`, 'POST', {uids, spam});
7
+ const folder = result.movedTo || from;
8
+ if (folder === destination) return result;
9
+ const current = result.movedTo ? Object.values(result.uidMap ?? {}) : uids;
10
+ if (!current.length) throw new Error('The junk status was restored, but the server did not return the message IDs needed to restore their folder. Refresh the mailbox.');
11
+ const back = new URLSearchParams({account, folder});
12
+ return api(`${base}/messages/move?${back}`, 'POST', {uids: current, destination});
13
+ }
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/rules.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Filing rules.
3
5
  *
@@ -89,6 +91,18 @@ export const RULE_ACTIONS = [
89
91
  {type: 'stop', label: 'Stop processing further rules', needs: null}
90
92
  ];
91
93
 
94
+ /** Source and destination folders are disjoint so automatic filing cannot loop. */
95
+ export function validateRuleFolders(rules, sources, folders, mirrored = null) {
96
+ const badSourceUses = new Set(['\\Sent', '\\Drafts', '\\Trash', '\\Junk', '\\Archive', '\\All', '\\Flagged']);
97
+ if (!Array.isArray(sources) || sources.length > 100 || sources.some(path => typeof path !== 'string' || !path || path.length > 500 || /[\x00-\x1f\x7f]/.test(path))) return {ok: false, error: 'Choose valid source folders.'};
98
+ if (sources.some(path => (mirrored && !mirrored.has(path)) || !folders.some(box => box.path === path && !box.flags?.has('\\Noselect') && !badSourceUses.has(box.specialUse)))) return {ok: false, error: 'Rule sources must be mirrored incoming folders. Sent, Drafts, Trash, Junk and archive views cannot be sources.'};
99
+ for (const rule of (rules ?? []).filter(rule => rule?.enabled !== false)) for (const action of rule.actions ?? []) {
100
+ if (action?.folder && (!folders.some(box => box.path === action.folder && !box.flags?.has('\\Noselect')) || sources.includes(action.folder))) return {ok: false, error: 'Choose an existing destination outside the rule source folders.'};
101
+ if (action?.type === 'delete' && !folders.some(box => box.specialUse === '\\Trash')) return {ok: false, error: 'This mailbox needs a Trash folder for a delete rule.'};
102
+ }
103
+ return {ok: true};
104
+ }
105
+
92
106
  /** The field kinds, by field name, for validating an op against a field. */
93
107
  const KIND_OF = Object.fromEntries(RULE_FIELDS.map(f => [f.field, f.kind]));
94
108
 
@@ -1,3 +1,6 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/scheduling.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ const MAIL_MODULE_VERSION = new URL(import.meta.url).searchParams.get('v') ?? '1';
1
4
  /**
2
5
  * When something should happen.
3
6
  *
@@ -20,7 +23,7 @@
20
23
  * @module _lib/admin/mail/scheduling
21
24
  */
22
25
 
23
- import {fmtDate, fmtTime} from '../ui/dates.js';
26
+ const {fmtDate, fmtTime} = await import(new URL(`../ui/dates.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
24
27
 
25
28
  /** How long a sent message may be held back so it can be recalled. */
26
29
  export const UNDO_SECONDS = [0, 5, 10, 20, 30];
@@ -1,3 +1,6 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/section-kit.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ const MAIL_MODULE_VERSION = new URL(import.meta.url).searchParams.get('v') ?? '1';
1
4
  /**
2
5
  * Building a settings section out of Domma rather than out of `createElement`.
3
6
  *
@@ -22,7 +25,7 @@
22
25
  *
23
26
  * @module _lib/admin/mail/section-kit
24
27
  */
25
- import {installFontControls} from './font-controls.js';
28
+ const {installFontControls} = await import(new URL(`./font-controls.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
26
29
 
27
30
  /**
28
31
  * A `<div>` with Domma classes on it, appended to a parent.
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/security-note.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * What the reader says about a signed or encrypted (S/MIME) message.
3
5
  *
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/settings-section.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /** Browser preferences for the shared mail reader. */
2
4
  export const READ_DELAY_KEY = 'domma-mail.mark-read-seconds';
3
5
  /** Compose preferences - this browser's, like the rest of this tab. */
@@ -126,19 +128,16 @@ export function permissionWords(permission) {
126
128
  * notifications hang off (admin/js/lib/sidebar-notify.js).
127
129
  * @returns {object}
128
130
  */
129
- export function createSettingsSection({canWrite, canSend = false, load, save, sidebarUrl = null, userId = null}) {
131
+ export function createSettingsSection({canWrite, canSend = false, load, save, sidebarUrl = null, userId = null, host = null}) {
132
+ const S = host?.storage ?? globalThis.S;
130
133
  return {
131
134
  id: 'settings',
132
135
  label: 'Settings',
133
136
  help: 'Preferences for reading and writing email in this browser.',
134
137
  async render(container, ctx) {
135
138
  const kit = await import(new URL(`./section-kit.js?v=${ctx.assetVersion ?? '1'}`, import.meta.url).href);
136
- // Optional: a core older than the notifications leaves that part out.
137
- const notify = sidebarUrl
138
- ? await import('/admin/js/lib/sidebar-notify.js').catch(() => null)
139
- : null;
140
- // The same user id the sidebar keys its notifications by.
141
- const who = userId ?? (await import('/admin/js/api.js').catch(() => null))?.getUser?.()?.id ?? null;
139
+ const notify = sidebarUrl ? (host?.helpers.notifications ?? null) : null;
140
+ const who = userId ?? host?.getUser()?.id ?? null;
142
141
  kit.note(container, 'Settings are saved in this browser and apply to all your mailboxes.');
143
142
 
144
143
  const saveSteps = [];
@@ -197,7 +196,9 @@ export function createSettingsSection({canWrite, canSend = false, load, save, si
197
196
  S.set(AUTOSAVE_KEY, autosaveMinutes(state.autosave));
198
197
  S.set(SPELLCHECK_KEY, state.spellcheck !== false);
199
198
  });
200
- kit.note(container, 'Receipts, signing, encryption and where replies are filed belong to each mailbox: see the Composing and Security tabs.');
199
+ if (host?.capabilities?.mailboxComposeSettings !== false) {
200
+ kit.note(container, 'Receipts, signing, encryption and where replies are filed belong to each mailbox: see the Composing and Security tabs.');
201
+ }
201
202
  }
202
203
 
203
204
  // ---- Notifications -------------------------------------------
@@ -236,14 +237,14 @@ export function createSettingsSection({canWrite, canSend = false, load, save, si
236
237
  }
237
238
 
238
239
  // ---- Email links ---------------------------------------------
239
- if (canSend && typeof navigator?.registerProtocolHandler === 'function') {
240
+ if (canSend && host?.helpers.mailCompose?.mailtoHandlerUrl && typeof navigator?.registerProtocolHandler === 'function') {
240
241
  kit.heading(container, 'Email links');
241
242
  kit.note(container, 'Make this browser open mailto: links - on any website - in a new message here, instead of in a mail program on this computer. The browser asks you to confirm. To undo it, use the browser\u2019s settings (in Chrome: Settings > Privacy and security > Site settings > Protocol handlers).');
242
243
  const linkRow = kit.box(container, 'flex gap-2 items-center mb-2');
243
244
  const linkStatus = kit.box(linkRow, 'flex-1 text-sm mail-status text-muted', 'span');
244
245
  kit.button(linkRow, 'Register as the mailto: links handler', async () => {
245
246
  try {
246
- const mail = await import('/admin/js/lib/mail-compose.js');
247
+ const mail = host.helpers.mailCompose;
247
248
  navigator.registerProtocolHandler('mailto', mail.mailtoHandlerUrl(`${location.origin}${location.pathname}`));
248
249
  linkStatus.textContent = 'Asked. If the browser showed a question, answer it to finish.';
249
250
  } catch (err) {
@@ -1,3 +1,6 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/templates.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
3
+ const MAIL_MODULE_VERSION = new URL(import.meta.url).searchParams.get('v') ?? '1';
1
4
  /**
2
5
  * Canned responses.
3
6
  *
@@ -25,8 +28,8 @@
25
28
  *
26
29
  * @module _lib/admin/mail/templates
27
30
  */
28
- import {signatureToText, textToHtml} from './identity.js';
29
- import {fmtDate, fmtTime} from '../ui/dates.js';
31
+ const {signatureToText, textToHtml} = await import(new URL(`./identity.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
32
+ const {fmtDate, fmtTime} = await import(new URL(`../ui/dates.js?v=${MAIL_MODULE_VERSION}`, import.meta.url).href);
30
33
 
31
34
  /** How many templates one mailbox may hold. */
32
35
  export const MAX_TEMPLATES = 50;
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/threads.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Grouping messages into conversations.
3
5
  *
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/vacation.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * The automatic reply, and everything that must stop it.
3
5
  *
@@ -142,6 +144,7 @@ export function looksAutomated(headers) {
142
144
  if (submitted && submitted !== 'no') return true;
143
145
 
144
146
  if (/^(bulk|list|junk|auto_reply)$/i.test(read('precedence').trim())) return true;
147
+ if (/\b(all|autoreply|oof)\b/i.test(read('x-auto-response-suppress'))) return true;
145
148
 
146
149
  // Any List-* header at all. A mailing list is never expecting a personal
147
150
  // reply, and answering one posts to every subscriber.
@@ -193,10 +196,12 @@ export function shouldAutoReply({
193
196
  if (!sender) return {reply: false, reason: 'The message has no sender address.'};
194
197
 
195
198
  // 1. Machines, lists and anything that announced itself as automatic.
196
- if (message?.automated === true) {
199
+ if (message?.automated === true || message?.listId) {
197
200
  return {reply: false, reason: 'It was sent automatically, or to a mailing list.'};
198
201
  }
199
202
 
203
+ if ((message?.flags ?? []).some(flag => ['$junk', '\\junk', '\\deleted'].includes(String(flag).toLowerCase()))) return {reply: false, reason: 'This message is marked as junk or deleted.'};
204
+ if (!/^[^\s<>@]+@[^\s<>@]+\.[^\s<>@]+$/.test(sender)) return {reply: false, reason: 'The sender address is invalid.'};
200
205
  // 2. Bounces and addresses that exist to send rather than receive.
201
206
  if (isNoReplyAddress(sender)) {
202
207
  return {reply: false, reason: `${sender} is not an address that accepts replies.`};
@@ -212,7 +217,7 @@ export function shouldAutoReply({
212
217
  // we were Bcc'd on, and a blast must not be answered.
213
218
  const recipients = [...(message?.to ?? []), ...(message?.cc ?? [])]
214
219
  .map(entry => String(entry?.address ?? '').toLowerCase());
215
- if (mine.size && !recipients.some(address => mine.has(address))) {
220
+ if (!mine.size || !recipients.some(address => mine.has(address))) {
216
221
  return {reply: false, reason: 'This mailbox was not in the To or Cc - it looks like a bulk send.'};
217
222
  }
218
223
 
@@ -231,6 +236,15 @@ export function shouldAutoReply({
231
236
  return {reply: true, reason: `Replying to ${sender}.`};
232
237
  }
233
238
 
239
+ /** Claims with an uncertain outcome remain blocked until a new absence. */
240
+ export function replyHistory(row, vacation, now = new Date()) {
241
+ if (!row) return {blocked: false, lastRepliedAt: null};
242
+ if (['sending', 'unknown'].includes(row.status)) return {blocked: true, reason: 'A previous automatic reply has an unconfirmed outcome. Check it manually.'};
243
+ const recent = new Date(row.at).getTime() > now.getTime() - normaliseVacation({vacation}).intervalDays * 86400000;
244
+ if (row.status === 'failed' && recent) return {blocked: true, reason: 'An automatic reply was already attempted for this sender during this interval.'};
245
+ return {blocked: false, lastRepliedAt: row.at ?? null};
246
+ }
247
+
234
248
  /**
235
249
  * The headers an automatic reply must carry.
236
250
  *
@@ -1,11 +1,13 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/mail/when-closed.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Run code when a Domma modal or slideover actually closes.
3
5
  *
4
- * Both are Domma components (0.55+), so `component.on('close', fn)` is the
6
+ * Current Domma modals and slideovers are components, so `component.on('close', fn)` is the
5
7
  * hook: it fires once per close - the X, the backdrop, Escape and close()
6
8
  * alike - after any "discard changes?" guard has let it through, and a modal
7
9
  * opened inside this one closing does not count. The modal's unprefixed
8
- * `close` DOM event this used to listen for is gone in domma-js 0.58.
10
+ * `close` DOM event remains supported for older CMS component handles.
9
11
  *
10
12
  * Anything without on() (a plain object, an older handle) falls back to
11
13
  * chaining `options.onClose`.
@@ -24,6 +26,26 @@ export function whenClosed(component, fn) {
24
26
  return;
25
27
  }
26
28
  const opts = component?.options;
29
+ const el = component?.element;
30
+ // The web component (`<domma-modal>` - a custom element's tag has a
31
+ // hyphen). Its handle's `options` is the element's `_options`, which is
32
+ // often not even set, so it cannot be what decides.
33
+ const custom = typeof el?.tagName === 'string' && el.tagName.includes('-');
34
+ if (el && typeof el.addEventListener === 'function' && (custom || !opts || el._options === opts)) {
35
+ // Once per close: the X sits in the modal's shadow root, so its click
36
+ // also reaches the host's backdrop handler and close() emits twice.
37
+ // Re-armed when the modal opens again.
38
+ let fired = false;
39
+ el.addEventListener('open', (event) => { if (event.target === el) fired = false; });
40
+ el.addEventListener('close', (event) => {
41
+ // `close` bubbles and is composed: a modal opened INSIDE this one
42
+ // closing must not count as this one closing.
43
+ if (event.target !== el || fired) return;
44
+ fired = true;
45
+ try { fn(component); } catch { /* one cleanup failing must not stop the next */ }
46
+ });
47
+ return;
48
+ }
27
49
  if (!opts) return;
28
50
  const previous = opts.onClose;
29
51
  opts.onClose = (instance) => {
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/ui/dates.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Dates as a plugin shows them to a person: dd/mm/yyyy, and dd/mm/yyyy HH:mm
3
5
  * where a time matters. The engine's twins are admin/js/lib/dates.js and
@@ -1,3 +1,5 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/admin/ui/resizable.js.
2
+ // Update with domma-mail/scripts/sync-cms.mjs; edit the shared source.
1
3
  /**
2
4
  * Making a slideover resizable.
3
5
  *
@@ -24,7 +26,7 @@ const MIN_WIDTH = 360;
24
26
  * @param {{storageKey: string, defaultWidth?: number, handleClass?: string}} options
25
27
  * @returns {() => void} a teardown for the listeners this adds
26
28
  */
27
- export function makeResizable(slideover, {storageKey, defaultWidth = 640, handleClass = 'dm-ui-resizer'}) {
29
+ export function makeResizable(slideover, {storageKey, defaultWidth = 640, handleClass = 'dm-ui-resizer', storage = globalThis.S}) {
28
30
  const panel = slideover?.element;
29
31
  if (!panel) return () => {};
30
32
 
@@ -45,7 +47,7 @@ export function makeResizable(slideover, {storageKey, defaultWidth = 640, handle
45
47
  central.defaultWidth = defaultWidth;
46
48
  let width = defaultWidth;
47
49
  try {
48
- const stored = Number(S.get(storageKey));
50
+ const stored = Number(storage.get(storageKey));
49
51
  if (Number.isFinite(stored) && stored >= MIN_WIDTH) width = stored;
50
52
  } catch { /* Storage unavailable; the default is serviceable. */ }
51
53
  central.width = width;
@@ -59,7 +61,7 @@ export function makeResizable(slideover, {storageKey, defaultWidth = 640, handle
59
61
  // leftwards makes it wider - the delta is inverted against the pointer.
60
62
  let width = defaultWidth;
61
63
  try {
62
- const stored = Number(S.get(storageKey));
64
+ const stored = Number(storage.get(storageKey));
63
65
  if (Number.isFinite(stored) && stored >= MIN_WIDTH) width = stored;
64
66
  } catch {
65
67
  // Storage unavailable; the default is serviceable.
@@ -110,7 +112,7 @@ export function makeResizable(slideover, {storageKey, defaultWidth = 640, handle
110
112
  handle.removeEventListener('pointercancel', end);
111
113
  panel.classList.remove('is-resizing');
112
114
  try {
113
- S.set(storageKey, width);
115
+ storage.set(storageKey, width);
114
116
  } catch {
115
117
  // The drag still applies for this panel.
116
118
  }
@@ -125,7 +127,7 @@ export function makeResizable(slideover, {storageKey, defaultWidth = 640, handle
125
127
  width = defaultWidth;
126
128
  apply();
127
129
  try {
128
- S.set(storageKey, width);
130
+ storage.set(storageKey, width);
129
131
  } catch { /* nothing to do */ }
130
132
  };
131
133
 
@@ -0,0 +1,69 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/contacts/mailContact.js.
2
+ // Update with domma-mail/scripts/sync-contacts.mjs; edit the shared source.
3
+ import {buildContact} from './model.js';
4
+
5
+ /** The standalone mail policy is intentionally stricter than the CMS general address book. */
6
+ export const contactsError = (message, statusCode = 400) => Object.assign(new Error(message), {statusCode, publicContactsError: true});
7
+ const fail = contactsError;
8
+ export const DETAIL_LIMITS = Object.freeze({phone: 100, company: 200, jobTitle: 200, website: 500});
9
+ const MAIL_FIELDS = ['name', 'email', 'favourite', 'groups', ...Object.keys(DETAIL_LIMITS), 'notes', 'emails', 'phones'];
10
+
11
+ export function normaliseMailContact(input, {allowJsonLists = false} = {}) {
12
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw fail('Provide a contact.');
13
+ const text = (value, max, label) => {
14
+ if (typeof value !== 'string' || value.length > max || /[\x00-\x1f\x7f]/.test(value)) throw fail(`Choose a valid ${label}.`);
15
+ return value.trim();
16
+ };
17
+ const email = text(input.email, 254, 'email address').toLowerCase();
18
+ if (!/^[^\s@<>,;:"\\]+@[^\s@<>,;:"\\]+\.[^\s@<>,;:"\\]+$/.test(email)) throw fail('Enter one email address.');
19
+ const name = text(input.name ?? '', 200, 'name') || email;
20
+ if (input.favourite !== undefined && typeof input.favourite !== 'boolean') throw fail('Choose whether this contact is a favourite.');
21
+ if (input.groups !== undefined && (!Array.isArray(input.groups) || input.groups.length > 10)) throw fail('Use at most ten groups.');
22
+ const groups = [...new Set((input.groups ?? []).map(value => text(value, 40, 'group name')).filter(Boolean))];
23
+ if (groups.some(group => group.includes(','))) throw fail('Use group names without commas.');
24
+ const details = Object.fromEntries(Object.entries(DETAIL_LIMITS).map(([key, limit]) => [key, text(input[key] ?? '', limit, key)]));
25
+ if (details.website) {
26
+ let url;
27
+ try { url = new URL(details.website); } catch { throw fail('Use an absolute HTTP or HTTPS website address.'); }
28
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw fail('Use an HTTP or HTTPS website without embedded credentials.');
29
+ }
30
+ const notes = input.notes ?? '';
31
+ if (typeof notes !== 'string' || notes.length > 2000 || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(notes)) throw fail('Use plain-text notes of at most 2,000 characters.');
32
+ const seen = new Set([email]);
33
+ const lists = {};
34
+ for (const [field, key, limit] of [['emails', 'address', 254], ['phones', 'number', 100]]) {
35
+ let rows = input[field] === undefined ? [] : input[field];
36
+ if (allowJsonLists && typeof rows === 'string') {
37
+ try { rows = rows.trim() ? JSON.parse(rows) : []; } catch { throw fail(`Provide additional ${field} as a JSON array.`); }
38
+ }
39
+ if (!Array.isArray(rows) || rows.length > 10) throw fail(`Use at most ten additional ${field}.`);
40
+ lists[field] = rows.flatMap(row => {
41
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw fail(`Provide a valid additional ${field} row.`);
42
+ const label = text(row.label ?? '', 40, 'label');
43
+ let value = text(row[key] ?? '', limit, field === 'emails' ? 'email address' : 'phone number');
44
+ if (!label && !value) return [];
45
+ if (!value) throw fail(`Enter the additional ${field === 'emails' ? 'email address' : 'phone number'}.`);
46
+ if (field === 'emails') {
47
+ value = value.toLowerCase();
48
+ if (!/^[^\s@<>,;:"\\]+@[^\s@<>,;:"\\]+\.[^\s@<>,;:"\\]+$/.test(value)) throw fail('Enter one additional email address.');
49
+ if (seen.has(value)) throw fail('Use each email address only once per contact.');
50
+ seen.add(value);
51
+ }
52
+ return [{label, [key]: value}];
53
+ });
54
+ }
55
+ const record = buildContact({name, email, favourite: input.favourite === true, groups, ...details, ...lists, notes: notes.replace(/\r\n?/g, '\n').trim()});
56
+ return Object.fromEntries(MAIL_FIELDS.map(field => [field, record[field]]));
57
+ }
58
+
59
+ /** Normalised contacts only. Additional addresses are suggestions, not extra group members. */
60
+ export function contactEmails(contact) {
61
+ return [contact.email, ...(contact.emails ?? []).map(row => row.address)];
62
+ }
63
+
64
+ export function contactRecipients(contacts) {
65
+ return contacts.flatMap(contact => [
66
+ {name: contact.name, email: contact.email, favourite: contact.favourite, groups: contact.groups},
67
+ ...(contact.emails ?? []).map(row => ({name: `${contact.name} (${row.label})`, email: row.address, favourite: contact.favourite, groups: []}))
68
+ ]);
69
+ }
@@ -0,0 +1,199 @@
1
+ // Source: @domma-mail/core 0.18.0, packages/core/src/contacts/model.js.
2
+ // Update with domma-mail/scripts/sync-contacts.mjs; edit the shared source.
3
+ /** Portable CMS contact records. Storage, access checks and identity belong to the host. */
4
+ /**
5
+ * The fields a contact carries beyond a name and a phone number.
6
+ *
7
+ * Kept as one list so the create, update and import paths cannot drift apart -
8
+ * they each used to spell the field set out by hand, which is how a field gets
9
+ * added to two of the three and quietly dropped by the other.
10
+ */
11
+ export const TEXT_FIELDS = [
12
+ 'name', 'email', 'phone', 'notes',
13
+ 'company', 'jobTitle', 'website',
14
+ 'vatNumber', 'companyNumber', 'reference', 'billingEmail', 'currency',
15
+ 'accountName', 'bankName', 'sortCode', 'accountNumber', 'iban', 'bic'
16
+ ];
17
+
18
+ /** Repeatable lists, each a array of small objects. */
19
+ export const LIST_FIELDS = ['addresses', 'emails', 'phones'];
20
+
21
+ /** Parse a value that may have been stored as JSON text by an import or the API. */
22
+ function toArray(value) {
23
+ if (Array.isArray(value)) return value;
24
+ if (typeof value === 'string' && value.trim()) {
25
+ try {
26
+ const parsed = JSON.parse(value);
27
+ return Array.isArray(parsed) ? parsed : [];
28
+ } catch {
29
+ return [];
30
+ }
31
+ }
32
+ return [];
33
+ }
34
+
35
+ const str = (v) => (typeof v === 'string' ? v.trim() : (v === undefined || v === null ? '' : String(v)));
36
+
37
+ /**
38
+ * One address, with every part named.
39
+ *
40
+ * Stored as parts rather than a blob because an invoice, a letter and a
41
+ * delivery note each want them arranged differently - and because a postcode
42
+ * you cannot read out separately is not much use for anything.
43
+ */
44
+ function cleanAddress(raw) {
45
+ return {
46
+ label: str(raw?.label) || 'Address',
47
+ line1: str(raw?.line1),
48
+ line2: str(raw?.line2),
49
+ city: str(raw?.city),
50
+ region: str(raw?.region),
51
+ postcode: str(raw?.postcode),
52
+ country: str(raw?.country),
53
+ isBilling: raw?.isBilling === true || raw?.isBilling === 'true'
54
+ };
55
+ }
56
+
57
+ function cleanEmail(raw) {
58
+ return { label: str(raw?.label) || 'Email', address: str(raw?.address) };
59
+ }
60
+
61
+ function cleanPhone(raw) {
62
+ return { label: str(raw?.label) || 'Phone', number: str(raw?.number) };
63
+ }
64
+
65
+ const CLEANERS = { addresses: cleanAddress, emails: cleanEmail, phones: cleanPhone };
66
+
67
+ /** Coerce a repeatable list, dropping rows with nothing in them. */
68
+ export function cleanList(field, value) {
69
+ const clean = CLEANERS[field];
70
+ return toArray(value)
71
+ .map(clean)
72
+ .filter((row) => Object.entries(row).some(([k, v]) => k !== 'label' && v !== '' && v !== false));
73
+ }
74
+
75
+ /**
76
+ * An address as an invoice prints it: one line per part, blanks omitted.
77
+ *
78
+ * @param {object} address
79
+ * @returns {string}
80
+ */
81
+ export function formatAddress(address) {
82
+ if (!address) return '';
83
+ return [address.line1, address.line2, address.city, address.region, address.postcode, address.country]
84
+ .map(str)
85
+ .filter(Boolean)
86
+ .join('\n');
87
+ }
88
+
89
+ /**
90
+ * The address to bill to: the one marked for billing, else the first.
91
+ *
92
+ * @param {object[]} addresses
93
+ * @returns {object|null}
94
+ */
95
+ export function billingAddress(addresses) {
96
+ const list = toArray(addresses);
97
+ return list.find((a) => a?.isBilling) ?? list[0] ?? null;
98
+ }
99
+
100
+ /**
101
+ * A contact projected into the shape the Invoice plugin's receivers use.
102
+ *
103
+ * This is the join between the two plugins: the field names are Invoice's, not
104
+ * Contacts', so the caller can post it straight at `/api/plugins/invoice/receivers`.
105
+ *
106
+ * @param {object} contact as returned by toContact()
107
+ * @returns {object}
108
+ */
109
+ export function toBillingProfile(contact) {
110
+ const address = billingAddress(contact.addresses);
111
+ return {
112
+ name: contact.name,
113
+ company: contact.company,
114
+ // The billing address wins over the personal one, which is the whole
115
+ // point of having both - invoices go to accounts, not to a mobile.
116
+ email: contact.billingEmail || contact.email,
117
+ phone: contact.phone,
118
+ address: formatAddress(address),
119
+ vatNumber: contact.vatNumber,
120
+ reference: contact.reference,
121
+ // An issuer prints these so the invoice can be paid; a receiver simply
122
+ // has none, and an empty string is what the Invoice plugin stores anyway.
123
+ bankDetails: formatBankDetails(contact)
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Bank details as an invoice prints them: label and value, one per line,
129
+ * blanks omitted. Sort code and account number ride together on one line
130
+ * because that is how anyone reads them off a page.
131
+ *
132
+ * @param {object} contact
133
+ * @returns {string}
134
+ */
135
+ export function formatBankDetails(contact) {
136
+ const lines = [];
137
+ if (contact.accountName) lines.push(contact.accountName);
138
+ if (contact.bankName) lines.push(contact.bankName);
139
+
140
+ const sort = str(contact.sortCode);
141
+ const acct = str(contact.accountNumber);
142
+ if (sort && acct) lines.push(`Sort ${sort} Acc ${acct}`);
143
+ else if (sort) lines.push(`Sort ${sort}`);
144
+ else if (acct) lines.push(`Acc ${acct}`);
145
+
146
+ if (contact.iban) lines.push(`IBAN ${str(contact.iban)}`);
147
+ if (contact.bic) lines.push(`BIC ${str(contact.bic)}`);
148
+ return lines.join('\n');
149
+ }
150
+
151
+ /** Map a collection entry to the shape the admin view expects. */
152
+ export function toContact(entry) {
153
+ let groups = entry.data.groups;
154
+ if (typeof groups === 'string') {
155
+ try {
156
+ groups = JSON.parse(groups);
157
+ } catch {
158
+ groups = [];
159
+ }
160
+ }
161
+ const contact = {
162
+ id: entry.id,
163
+ groups: Array.isArray(groups) ? groups : [],
164
+ favourite: entry.data.favourite === true || entry.data.favourite === 'true',
165
+ paymentTerms: entry.data.paymentTerms === '' || entry.data.paymentTerms === undefined || entry.data.paymentTerms === null
166
+ ? null
167
+ : Number(entry.data.paymentTerms),
168
+ userId: entry.data.userId ?? null,
169
+ createdAt: entry.meta.createdAt,
170
+ updatedAt: entry.meta.updatedAt
171
+ };
172
+ for (const field of TEXT_FIELDS) contact[field] = entry.data[field] ?? '';
173
+ for (const field of LIST_FIELDS) contact[field] = toArray(entry.data[field]);
174
+ return contact;
175
+ }
176
+
177
+ /**
178
+ * Build the stored shape from whatever a caller sent.
179
+ *
180
+ * Used by create AND import so the two cannot drift - a field added to one
181
+ * and forgotten in the other is the bug this exists to prevent.
182
+ *
183
+ * @param {object} raw
184
+ * @param {string|null} uid
185
+ * @returns {object}
186
+ */
187
+ export function buildContact(raw, uid) {
188
+ const data = {
189
+ groups: Array.isArray(raw.groups) ? raw.groups : [],
190
+ favourite: raw.favourite === true || raw.favourite === 'true',
191
+ paymentTerms: raw.paymentTerms === '' || raw.paymentTerms === undefined || raw.paymentTerms === null
192
+ ? ''
193
+ : (Number(raw.paymentTerms) || 0),
194
+ userId: uid ?? null
195
+ };
196
+ for (const field of TEXT_FIELDS) data[field] = str(raw[field]);
197
+ for (const field of LIST_FIELDS) data[field] = cleanList(field, raw[field]);
198
+ return data;
199
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "package": "@domma-mail/core",
4
+ "version": "0.18.0",
5
+ "files": {
6
+ "admin/js/lib/contacts-arrange.js": "0cb3b65de7305ae62b38eca4df8e44f397f4a799312bf04091e26171041b21ee",
7
+ "plugins/_lib/contacts/model.js": "a0fa7fd0439e5651f66cbfaa1bf7f78972832edba5f789f8426ee35f3c9a377d",
8
+ "plugins/_lib/contacts/mailContact.js": "497f1014449eb14bd1a7794dd09fd3d3ec2dca5af1fb29e5f6a97878bfa00168"
9
+ }
10
+ }