clavarium 0.2.471-next.1 → 0.2.473-next.1
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.
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/api.mjs +12 -2
- package/server/contactview.mjs +121 -0
- package/server/mailview.mjs +203 -0
- package/server/mcpoauth.mjs +118 -33
- package/server/mcpx.mjs +7 -2
- package/server/settingswords.mjs +19 -1
- package/server/tethers.mjs +5 -4
- package/web/app.js +296 -31
- package/web/kit.js +4 -1
- package/web/style.css +37 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.473-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.473-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"clavarium-binder": "0.1.63-next.1",
|
|
15
15
|
"clavarium-docket": "0.1.2-next.2",
|
|
16
16
|
"clavarium-parley": "0.17.95-next.1",
|
|
17
|
-
"clavarium-tether": "0.1.0-next.
|
|
17
|
+
"clavarium-tether": "0.1.0-next.70",
|
|
18
18
|
"mammoth": "1.13.0",
|
|
19
19
|
"mermaid": "11.17.2",
|
|
20
20
|
"node-pty": "^1.1.0",
|
|
@@ -800,9 +800,9 @@
|
|
|
800
800
|
}
|
|
801
801
|
},
|
|
802
802
|
"node_modules/clavarium-tether": {
|
|
803
|
-
"version": "0.1.0-next.
|
|
804
|
-
"resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.
|
|
805
|
-
"integrity": "sha512-
|
|
803
|
+
"version": "0.1.0-next.70",
|
|
804
|
+
"resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.70.tgz",
|
|
805
|
+
"integrity": "sha512-W8lJN/xNh3az7tc9c8OImvkBD7FWogxqiFJcLDqk+ZzrQoxTyGbj40s+tZ4Z+QSwn9wuItfLy22n0EPIvQqhog==",
|
|
806
806
|
"license": "MIT",
|
|
807
807
|
"bin": {
|
|
808
808
|
"tether": "bin/cli.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.473-next.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"clavarium-binder": "0.1.63-next.1",
|
|
49
49
|
"clavarium-docket": "0.1.2-next.2",
|
|
50
50
|
"clavarium-parley": "0.17.95-next.1",
|
|
51
|
-
"clavarium-tether": "0.1.0-next.
|
|
51
|
+
"clavarium-tether": "0.1.0-next.70",
|
|
52
52
|
"mammoth": "1.13.0",
|
|
53
53
|
"mermaid": "11.17.2",
|
|
54
54
|
"node-pty": "^1.1.0",
|
package/server/api.mjs
CHANGED
|
@@ -173,6 +173,8 @@
|
|
|
173
173
|
* GET /api/files/download?c=...&r=...&p=<path> one file
|
|
174
174
|
* GET /api/mail/open?ref=mail:...&c= GET /api/mail/page?ref=... a mail cited by its reference, read now (mailref.mjs)
|
|
175
175
|
* POST /api/tether/agenda {target, from?, to?}: a calendar's events of a window, read now (agenda.mjs)
|
|
176
|
+
* POST /api/tether/mail-list|mail-read {target, folder?, text?} | {target, id, folder?}: a mailbox's latest messages, one as text (mailview.mjs)
|
|
177
|
+
* POST /api/tether/contacts|contact {target, text?} | {target, id}: an address book's contacts, one (contactview.mjs)
|
|
176
178
|
* POST /api/files/import?c=...&r=...&p=<folder>&name=<file name>[&dir=<subfolders>&exists=keep|replace|skip&batch=<id>] the body IS the file
|
|
177
179
|
* GET /api/files/thumb|text POST /api/files/save|make|rename|move|remove|taken ?c=...&r=...&p=... (see files.mjs)
|
|
178
180
|
*
|
|
@@ -190,6 +192,8 @@ import { VmUnknown } from './vm.mjs';
|
|
|
190
192
|
import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
|
|
191
193
|
import { mailRoute } from './mailref.mjs';
|
|
192
194
|
import { readAgenda } from './agenda.mjs';
|
|
195
|
+
import { readMailList, readMail } from './mailview.mjs';
|
|
196
|
+
import { readContacts, readContact } from './contactview.mjs';
|
|
193
197
|
import { WORK_TAB } from './resources.mjs';
|
|
194
198
|
import { transcribe, AUDIO_MAX } from './voice.mjs';
|
|
195
199
|
import { FILE_MAX } from './setup.mjs';
|
|
@@ -541,8 +545,10 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
541
545
|
provider. A page, not JSON; its state is the proof it was started from this page. */
|
|
542
546
|
if (pathname === BACK_PATH && tethers?.oauth) {
|
|
543
547
|
let page;
|
|
544
|
-
|
|
545
|
-
|
|
548
|
+
/* Said in the language of the page that started it; one never started here, in the browser's. */
|
|
549
|
+
const lang = String(request.headers['accept-language'] ?? '').slice(0, 2);
|
|
550
|
+
try { const done = await tethers.oauth.finish({ tethers }, { code: query.get('code'), state: query.get('state'), error: query.get('error') }); page = backPage({ ok: true, title: done.title, lang: done.lang, back: done.back, sameTab: done.sameTab }); }
|
|
551
|
+
catch (error) { page = backPage({ ok: false, message: error instanceof Refusal ? error.message : '', why: error?.why ?? 'failed', lang: error?.lang ?? lang, back: error?.back }); }
|
|
546
552
|
response.writeHead(200, { ...headers, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }).end(page);
|
|
547
553
|
return true;
|
|
548
554
|
}
|
|
@@ -726,6 +732,10 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
726
732
|
/* A calendar's agenda, read now through Tether as the owner's own read (agenda.mjs, 16-11): seen in its asset
|
|
727
733
|
panel, so the calendar need not stay open elsewhere. A POST, for this site's own pages only (checked above). */
|
|
728
734
|
if (pathname === '/api/tether/agenda' && tethers) return send(200, await readAgenda(tethers, body ?? {}, { who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' } })), true;
|
|
735
|
+
/* A mailbox's latest messages and one as text, an address book's contacts and one, read the same way (16-11:
|
|
736
|
+
mailview.mjs, contactview.mjs): never marked read, nothing changed. */
|
|
737
|
+
const peek = { '/api/tether/mail-list': readMailList, '/api/tether/mail-read': readMail, '/api/tether/contacts': readContacts, '/api/tether/contact': readContact }[pathname];
|
|
738
|
+
if (peek && tethers) return send(200, await peek(tethers, body ?? {}, { who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' } })), true;
|
|
729
739
|
/* A mailbox's signature (Markdown), added under what the agent sends from it. */
|
|
730
740
|
if (pathname === '/api/tether/signature' && tethers) {
|
|
731
741
|
const t = tethers.store().target(String(body.target ?? ''));
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/* AN ADDRESS BOOK, SEEN BY ITS OWNER (16-11): the contacts of a contacts asset (a Tether target of kind contacts:
|
|
2
|
+
* Microsoft over Graph, Google or a classic book over CardDAV), shown in its asset panel, as the agenda is (agenda.mjs).
|
|
3
|
+
*
|
|
4
|
+
* POST /api/tether/contacts {target, text?} the contacts, or those whose name or email matches (Tether's
|
|
5
|
+
* contacts.search). -> { target, title, text, contacts: [{id, name, emails, phones,
|
|
6
|
+
* company}], more, partial }
|
|
7
|
+
* POST /api/tether/contact {target, id} one contact. -> { target, id, name, emails, phones, company,
|
|
8
|
+
* facts: [[word, value]], notes, partial }
|
|
9
|
+
*
|
|
10
|
+
* READ THROUGH TETHER, as an agent's contacts-list is: the sign-in stays in this server, never in the answer, never
|
|
11
|
+
* in the browser; the read is the owner's own in Tether's journal, never an agent's. READ ONLY. Nothing is kept here.
|
|
12
|
+
*
|
|
13
|
+
* A Tether that hands its contacts as data (`data.contacts`, `data.contact`: the fields below) gives them all; one that
|
|
14
|
+
* gives only its text lines (0.1.0-next.69) gives name, emails and phones in one line, no company: `partial`. */
|
|
15
|
+
import { Refusal } from './conversations.mjs';
|
|
16
|
+
import { READ_MS } from './mailview.mjs';
|
|
17
|
+
|
|
18
|
+
export const CONTACTS_MAX = 200;
|
|
19
|
+
export const SEARCH_MAX = 200;
|
|
20
|
+
export const NOTES_MAX = 4000;
|
|
21
|
+
const LINE_MAX = 400;
|
|
22
|
+
const refused = (status, kind, message) => Object.assign(new Refusal(status, message), { kind });
|
|
23
|
+
const line = (v, max = LINE_MAX) => String(v ?? '').replace(/[\u0000-\u001f\u007f]+/g, ' ').trim().slice(0, max);
|
|
24
|
+
const lines = (v, max = 20) => (Array.isArray(v) ? v : v ? [v] : []).map((x) => line(x)).filter(Boolean).slice(0, max);
|
|
25
|
+
|
|
26
|
+
function bookOf(tethers, target) {
|
|
27
|
+
if (!tethers) throw refused(503, 'unreachable', 'Address books are not reached from this server.');
|
|
28
|
+
const t = tethers.store().target(String(target ?? ''));
|
|
29
|
+
if (!t || t.kind !== 'contacts') throw refused(404, 'gone', 'No such address book.');
|
|
30
|
+
return t;
|
|
31
|
+
}
|
|
32
|
+
async function asked(tethers, t, verb, args, who, wait) {
|
|
33
|
+
let timer;
|
|
34
|
+
const late = new Promise((resolve) => { timer = setTimeout(() => resolve(null), wait); timer.unref?.(); });
|
|
35
|
+
let got;
|
|
36
|
+
try { got = await Promise.race([tethers.read(verb, { target: t.id, ...args }, who), late]); }
|
|
37
|
+
finally { clearTimeout(timer); }
|
|
38
|
+
if (got === null) throw refused(504, 'late', `${t.title} did not answer in time. Try again.`);
|
|
39
|
+
if (!got?.ok) throw refused(/no such contact/.test(String(got?.text)) ? 404 : 502, 'unreachable', `${t.title} could not be read: ${line(got?.text, 300) || 'no answer'}.`);
|
|
40
|
+
return got;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/* One contact Tether handed as data, kept to what the list shows. */
|
|
44
|
+
export function contactOf(c) {
|
|
45
|
+
const id = line(c?.id, 2048);
|
|
46
|
+
if (!id) return null;
|
|
47
|
+
return { id, name: line(c.name) || '(no name)', emails: lines(c.emails ?? c.email), phones: lines(c.phones ?? c.phone), company: line(c.company) || null };
|
|
48
|
+
}
|
|
49
|
+
/* The text lines Tether's contacts-list and contacts-search say ("ID", then " Name <a, b> tel 1 2"), read back.
|
|
50
|
+
Its phones are joined by spaces, which a phone has too: they stay one line. */
|
|
51
|
+
export function contactsOfText(text) {
|
|
52
|
+
const out = [];
|
|
53
|
+
const all = String(text ?? '').split('\n');
|
|
54
|
+
for (let i = 0; i < all.length; i++) {
|
|
55
|
+
const head = all[i];
|
|
56
|
+
if (!head || head.startsWith(' ') || head.startsWith('(') || /^No contact/.test(head)) continue;
|
|
57
|
+
const next = all[i + 1] ?? '';
|
|
58
|
+
if (!next.startsWith(' ') || next.startsWith(' ')) continue;
|
|
59
|
+
i++;
|
|
60
|
+
const m = /^ {2}(.*?)(?: {2}<([^>]*)>)?(?: {2}tel (.*))?$/.exec(next);
|
|
61
|
+
out.push(contactOf({ id: head, name: m[1] === '(no name)' ? '' : m[1], emails: (m[2] ?? '').split(', '), phones: m[3] ? [m[3]] : [] }));
|
|
62
|
+
}
|
|
63
|
+
return out.filter(Boolean);
|
|
64
|
+
}
|
|
65
|
+
const cutSaid = (text) => /\((Showing the first|Looked at the first) \d+/.test(String(text ?? ''));
|
|
66
|
+
|
|
67
|
+
/* THE CONTACTS OF AN ADDRESS BOOK TARGET, or those matching `text`, read now. */
|
|
68
|
+
export async function readContacts(tethers, { target, text } = {}, { who, wait = READ_MS } = {}) {
|
|
69
|
+
const t = bookOf(tethers, target);
|
|
70
|
+
const q = line(text, SEARCH_MAX);
|
|
71
|
+
const got = await asked(tethers, t, q ? 'contacts.search' : 'contacts.list', q ? { text: q } : {}, who, wait);
|
|
72
|
+
const given = Array.isArray(got.data?.contacts);
|
|
73
|
+
const all = (given ? got.data.contacts.map(contactOf).filter(Boolean) : contactsOfText(got.text))
|
|
74
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
75
|
+
const more = all.length > CONTACTS_MAX || got.data?.more === true || cutSaid(got.text);
|
|
76
|
+
return { target: t.id, title: t.title, text: q, contacts: all.slice(0, CONTACTS_MAX), more, partial: !given };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/* ---------- one contact ---------- */
|
|
80
|
+
const notesOf = (v) => String(v ?? '').replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').replace(/\n{3,}/g, '\n\n').trim().slice(0, NOTES_MAX);
|
|
81
|
+
const vcardValue = (v) => v.replace(/\\n/gi, '\n').replace(/\\([,;\\])/g, '$1');
|
|
82
|
+
/* The text Tether's contacts-read says, read back: the name, then " email: x", " tel (mobile): x", " company: X, T",
|
|
83
|
+
" address (work): ...", " birthday: ..."; then (Microsoft) its notes and "id: ..."; (CardDAV) its vCard, of
|
|
84
|
+
which only the company, title and note are kept. */
|
|
85
|
+
export function contactOfText(text, id) {
|
|
86
|
+
const all = String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
|
|
87
|
+
const c = { id, name: all[0] === '(no name)' ? '' : all[0] ?? '', emails: [], phones: [], company: '', facts: [], notes: '' };
|
|
88
|
+
let i = 1;
|
|
89
|
+
for (; i < all.length && all[i].startsWith(' '); i++) {
|
|
90
|
+
const kv = /^ {2}([a-z]+)(?: \(([^)]*)\))?: (.*)$/.exec(all[i]);
|
|
91
|
+
if (!kv) continue;
|
|
92
|
+
const [, k, kind, v] = kv;
|
|
93
|
+
if (k === 'email') c.emails.push(v);
|
|
94
|
+
else if (k === 'tel') c.phones.push(kind ? `${v} (${kind})` : v);
|
|
95
|
+
else if (k === 'company') c.company = v;
|
|
96
|
+
else c.facts.push([kind ? `${k} (${kind})` : k, v]);
|
|
97
|
+
}
|
|
98
|
+
const rest = all.slice(i).join('\n').trim();
|
|
99
|
+
if (/^BEGIN:VCARD/i.test(rest)) {
|
|
100
|
+
const card = rest.replace(/\n[ \t]/g, '');
|
|
101
|
+
const one = (name) => { const m = new RegExp(`^${name}[^:\\n]*:(.*)$`, 'im').exec(card); return m ? vcardValue(m[1].trim()) : ''; };
|
|
102
|
+
const org = one('ORG').split(';').filter(Boolean).join(', ');
|
|
103
|
+
if (org) c.company = org;
|
|
104
|
+
const title = one('TITLE'); if (title) c.facts.push(['title', title]);
|
|
105
|
+
c.notes = one('NOTE');
|
|
106
|
+
} else c.notes = rest.replace(/\n*id: \S+$/, '');
|
|
107
|
+
return c;
|
|
108
|
+
}
|
|
109
|
+
/* ONE CONTACT OF AN ADDRESS BOOK TARGET, read now: its fields as text. */
|
|
110
|
+
export async function readContact(tethers, { target, id } = {}, { who, wait = READ_MS } = {}) {
|
|
111
|
+
const t = bookOf(tethers, target);
|
|
112
|
+
const cid = String(id ?? '').trim();
|
|
113
|
+
if (!cid || cid.length > 2048 || /[\s\0]/.test(cid)) throw refused(400, 'bad-contact', 'No such contact.');
|
|
114
|
+
const got = await asked(tethers, t, 'contacts.read', { id: cid }, who, wait);
|
|
115
|
+
const given = got.data?.contact && typeof got.data.contact === 'object';
|
|
116
|
+
const c = given ? got.data.contact : contactOfText(got.text, cid);
|
|
117
|
+
const facts = (Array.isArray(c.facts) ? c.facts : []).filter((f) => Array.isArray(f) && f[1]).map(([k, v]) => [line(k, 60), line(v, 1000)]).slice(0, 40);
|
|
118
|
+
if (given) for (const k of ['title', 'birthday']) if (c[k]) facts.push([k, line(c[k], 1000)]);
|
|
119
|
+
if (given) for (const a of lines(c.addresses, 5)) facts.push(['address', a]);
|
|
120
|
+
return { target: t.id, id: cid, name: line(c.name) || '(no name)', emails: lines(c.emails), phones: lines(c.phones), company: line(c.company) || null, facts, notes: notesOf(c.notes), partial: !given };
|
|
121
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/* A MAILBOX, SEEN BY ITS OWNER (16-11): the latest messages of a mailbox asset (a Tether target of kind mail:
|
|
2
|
+
* Microsoft over Graph, Google or a classic box over IMAP), shown in its asset panel, as the agenda is (agenda.mjs).
|
|
3
|
+
*
|
|
4
|
+
* POST /api/tether/mail-list {target, folder?, text?} the newest messages of a folder (inbox by default), or
|
|
5
|
+
* those whose text matches (Tether's mail.search). -> { target, title, folder, text,
|
|
6
|
+
* folders, messages: [...], more, partial }
|
|
7
|
+
* POST /api/tether/mail-read {target, id, folder?} one message, as text. -> { target, id, ref, from, to, cc,
|
|
8
|
+
* date, subject, text, attachments: [{name, type, size}], cut, partial }
|
|
9
|
+
*
|
|
10
|
+
* READ THROUGH TETHER, as an agent's mail-list is: the same connector, the same sign-in -- which stays in this server,
|
|
11
|
+
* never in the answer, never in the browser. The read is the owner's own in Tether's journal, never an agent's, never
|
|
12
|
+
* asked of anyone. Nothing is kept here.
|
|
13
|
+
*
|
|
14
|
+
* NEVER MARKED READ: Tether reads with EXAMINE and BODY.PEEK over IMAP, a GET over Graph -- as the mail viewer's
|
|
15
|
+
* mail.open (mailref.mjs). READ ONLY: nothing is moved, flagged or sent.
|
|
16
|
+
*
|
|
17
|
+
* TEXT ONLY: a message's words come as text from Tether (its HTML made text there); one still in HTML here is made
|
|
18
|
+
* text again. Attachments are named with their size, never opened. Pictures are never loaded.
|
|
19
|
+
*
|
|
20
|
+
* A Tether that hands its messages as data (`data.messages`, `data.message`: the fields below) gives them all; one
|
|
21
|
+
* that gives only its text lines (0.1.0-next.69) gives who, subject, date, and no unread or attachment mark: the
|
|
22
|
+
* answer says `partial`. */
|
|
23
|
+
import { Refusal } from './conversations.mjs';
|
|
24
|
+
|
|
25
|
+
export const MESSAGES_MAX = 25;
|
|
26
|
+
export const READ_MS = 30_000;
|
|
27
|
+
export const TEXT_MAX = 100_000; /* a message's words shown at most */
|
|
28
|
+
export const SEARCH_MAX = 200;
|
|
29
|
+
/* The folders offered: Graph knows them by these words; an IMAP box names its own, so only its inbox is offered. */
|
|
30
|
+
export const FOLDERS = ['inbox', 'sent', 'drafts', 'archive', 'junk', 'trash'];
|
|
31
|
+
const LINE_MAX = 400;
|
|
32
|
+
const refused = (status, kind, message) => Object.assign(new Refusal(status, message), { kind });
|
|
33
|
+
const line = (v, max = LINE_MAX) => String(v ?? '').replace(/[\u0000-\u001f\u007f]+/g, ' ').trim().slice(0, max);
|
|
34
|
+
|
|
35
|
+
/* ---------- a target, a folder ---------- */
|
|
36
|
+
export function boxOf(tethers, target) {
|
|
37
|
+
if (!tethers) throw refused(503, 'unreachable', 'Mailboxes are not reached from this server.');
|
|
38
|
+
const t = tethers.store().target(String(target ?? ''));
|
|
39
|
+
if (!t || t.kind !== 'mail') throw refused(404, 'gone', 'No such mailbox.');
|
|
40
|
+
return t;
|
|
41
|
+
}
|
|
42
|
+
/* Microsoft over Graph: the folders by their common words. Else (IMAP): the inbox alone. */
|
|
43
|
+
export const foldersOf = (t) => (String(t?.config?.provider ?? '') === 'microsoft' ? FOLDERS : ['inbox']);
|
|
44
|
+
export function folderOf(t, folder) {
|
|
45
|
+
const f = String(folder ?? '').trim().toLowerCase() || 'inbox';
|
|
46
|
+
if (!foldersOf(t).includes(f)) throw refused(400, 'bad-folder', 'No such folder here.');
|
|
47
|
+
return f;
|
|
48
|
+
}
|
|
49
|
+
/* What Tether is given: the inbox is the mailbox's own (its config may name another); Graph takes the other words. */
|
|
50
|
+
const mailboxArg = (f) => (f === 'inbox' ? {} : { mailbox: f });
|
|
51
|
+
|
|
52
|
+
/* ---------- times ---------- */
|
|
53
|
+
const MONTHS = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
|
|
54
|
+
/* An instant as ISO (UTC): Graph's ISO times, IMAP's INTERNALDATE ("16-Nov-2026 09:30:00 +0100"), a Date header. */
|
|
55
|
+
export function dateOf(v) {
|
|
56
|
+
const s = String(v ?? '').trim();
|
|
57
|
+
if (!s) return null;
|
|
58
|
+
const imap = /^(\d{1,2})-([A-Za-z]{3})-(\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-])(\d{2})(\d{2})$/.exec(s);
|
|
59
|
+
if (imap) {
|
|
60
|
+
const [, d, mon, y, h, mi, se, sign, oh, om] = imap;
|
|
61
|
+
const m = MONTHS[mon.toLowerCase()];
|
|
62
|
+
if (!m) return null;
|
|
63
|
+
const off = (sign === '-' ? -1 : 1) * (Number(oh) * 60 + Number(om));
|
|
64
|
+
return new Date(Date.UTC(Number(y), m - 1, Number(d), Number(h), Number(mi), Number(se)) - off * 60_000).toISOString();
|
|
65
|
+
}
|
|
66
|
+
const ms = Date.parse(s);
|
|
67
|
+
return Number.isNaN(ms) ? null : new Date(ms).toISOString();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* ---------- words, as text ---------- */
|
|
71
|
+
const ENTITIES = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'" };
|
|
72
|
+
/* HTML made text: what runs or draws dropped, line breaks kept, the rest of the tags taken away, entities read. */
|
|
73
|
+
export function textOfHtml(html) {
|
|
74
|
+
return String(html ?? '')
|
|
75
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
76
|
+
.replace(/<\s*(script|style|head|title|template|svg|object|iframe)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, ' ')
|
|
77
|
+
.replace(/<\s*br\s*\/?\s*>/gi, '\n').replace(/<\s*\/\s*(p|div|li|tr|h[1-6]|table|blockquote)\s*>/gi, '\n')
|
|
78
|
+
.replace(/<[^>]*>/g, '')
|
|
79
|
+
.replace(/&(nbsp|amp|lt|gt|quot|apos|#39);/gi, (_, e) => ENTITIES[e.toLowerCase()])
|
|
80
|
+
.replace(/&#(\d{1,6});/g, (_, n) => { const c = Number(n); return c > 31 && c < 0x110000 ? String.fromCodePoint(c) : ''; })
|
|
81
|
+
.replace(/[ \t\u00a0]{2,}/g, ' ').replace(/[ \t]+\n/g, '\n').replace(/\n[ \t]+/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
82
|
+
}
|
|
83
|
+
const looksHtml = (s) => /<\s*(html|body|div|table|p|br|span|img|a)\b[^>]*>/i.test(s);
|
|
84
|
+
/* A message's words: text, control characters dropped, lines kept, short enough. Still HTML: made text. */
|
|
85
|
+
export function wordsOf(v) {
|
|
86
|
+
let s = String(v ?? '').replace(/\r\n?/g, '\n');
|
|
87
|
+
if (looksHtml(s)) s = textOfHtml(s);
|
|
88
|
+
s = s.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').replace(/\n{3,}/g, '\n\n').trim();
|
|
89
|
+
return { text: s.slice(0, TEXT_MAX), cut: s.length > TEXT_MAX };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/* ---------- a list ---------- */
|
|
93
|
+
const markOf = (v) => (v === true || v === false ? v : null);
|
|
94
|
+
/* One message Tether handed as data, kept to what the page shows. */
|
|
95
|
+
export function messageOf(m) {
|
|
96
|
+
const id = line(m?.id ?? m?.uid, 2048);
|
|
97
|
+
if (!id) return null;
|
|
98
|
+
const n = Number(m.attachments);
|
|
99
|
+
return {
|
|
100
|
+
id, ref: line(m.ref, 2048) || null, from: line(m.from), subject: line(m.subject) || '(no subject)', date: dateOf(m.date),
|
|
101
|
+
unread: markOf(m.unread), attachments: Array.isArray(m.attachments) ? m.attachments.length > 0 : m.attachments === true || m.attachments === false ? m.attachments : Number.isInteger(n) ? n > 0 : null,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/* The text lines Tether's mail-list and mail-search say, read back. IMAP: "#uid date" then " From:", " Subject:",
|
|
105
|
+
" ref:"; Graph: "#id", then " date", " From:", " Subject:", " ref:". */
|
|
106
|
+
export function messagesOfText(text) {
|
|
107
|
+
const out = [];
|
|
108
|
+
let at = null;
|
|
109
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
110
|
+
const head = /^#(\S+)(?: {2}(.*))?$/.exec(raw);
|
|
111
|
+
if (head) { at = { id: head[1], date: head[2] ?? '' }; out.push(at); continue; }
|
|
112
|
+
if (!at || !raw.startsWith(' ')) { if (raw.trim()) at = null; continue; }
|
|
113
|
+
const l = raw.slice(2);
|
|
114
|
+
const kv = /^(From|Subject|ref): ?(.*)$/.exec(l);
|
|
115
|
+
if (kv) at[kv[1].toLowerCase()] = kv[2];
|
|
116
|
+
else if (!at.date) at.date = l;
|
|
117
|
+
}
|
|
118
|
+
return out.map(messageOf).filter(Boolean);
|
|
119
|
+
}
|
|
120
|
+
const said = (text) => String(text ?? '');
|
|
121
|
+
const cutSaid = (text) => /\(Showing the (first )?\d+ most recent/.test(said(text));
|
|
122
|
+
|
|
123
|
+
/* Tether asked, waited for at most `wait`: its answer, or a refusal in plain words. */
|
|
124
|
+
async function asked(tethers, t, verb, args, who, wait) {
|
|
125
|
+
let timer;
|
|
126
|
+
const late = new Promise((resolve) => { timer = setTimeout(() => resolve(null), wait); timer.unref?.(); });
|
|
127
|
+
let got;
|
|
128
|
+
try { got = await Promise.race([tethers.read(verb, { target: t.id, ...args }, who), late]); }
|
|
129
|
+
finally { clearTimeout(timer); }
|
|
130
|
+
if (got === null) throw refused(504, 'late', `${t.title} did not answer in time. Try again.`);
|
|
131
|
+
if (!got?.ok) throw refused(got?.code === 'gone' ? 404 : 502, got?.code === 'gone' ? 'gone' : 'unreachable', `${t.title} could not be read: ${line(got?.text, 300) || 'no answer'}.`);
|
|
132
|
+
return got;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/* THE LATEST MESSAGES OF A MAILBOX TARGET, or those matching `text`, read now. `who`: { id, name }, said in Tether's
|
|
136
|
+
journal. */
|
|
137
|
+
export async function readMailList(tethers, { target, folder, text } = {}, { who, wait = READ_MS } = {}) {
|
|
138
|
+
const t = boxOf(tethers, target);
|
|
139
|
+
const f = folderOf(t, folder);
|
|
140
|
+
const q = line(text, SEARCH_MAX);
|
|
141
|
+
const got = await asked(tethers, t, q ? 'mail.search' : 'mail.list', q ? { text: q, ...mailboxArg(f) } : mailboxArg(f), who, wait);
|
|
142
|
+
const given = Array.isArray(got.data?.messages);
|
|
143
|
+
const all = (given ? got.data.messages.map(messageOf).filter(Boolean) : messagesOfText(got.text))
|
|
144
|
+
.sort((a, b) => String(b.date ?? '').localeCompare(String(a.date ?? '')));
|
|
145
|
+
const more = all.length > MESSAGES_MAX || got.data?.more === true || cutSaid(got.text);
|
|
146
|
+
return { target: t.id, title: t.title, folder: f, text: q, folders: foldersOf(t), messages: all.slice(0, MESSAGES_MAX), more, partial: !given };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/* ---------- one message ---------- */
|
|
150
|
+
const attachmentOf = (a) => {
|
|
151
|
+
const name = line(a?.name, 300);
|
|
152
|
+
if (!name) return null;
|
|
153
|
+
const n = Number(a.size);
|
|
154
|
+
return { name, type: line(a.type, 100) || null, size: Number.isFinite(n) && n >= 0 ? Math.round(n) : null };
|
|
155
|
+
};
|
|
156
|
+
/* "name (type, N KB)" or "name (type, ~N KB)", as Tether's mail-read lists them. */
|
|
157
|
+
const attachmentOfText = (l) => {
|
|
158
|
+
const m = /^\s*(?:- )?(.*?) \(([^,()]*), ~?(\d+) KB\)\s*$/.exec(l);
|
|
159
|
+
return m ? attachmentOf({ name: m[1], type: m[2], size: Number(m[3]) * 1024 }) : null;
|
|
160
|
+
};
|
|
161
|
+
/* The text Tether's mail-read says, read back: "ref:", the head (From, To, Cc, Date, Subject), a blank line, the words,
|
|
162
|
+
then an invitation, then "Attachments:" (Graph) or "--- Attachments (n) ---" (IMAP), then a cut said last. */
|
|
163
|
+
export function messageOfText(text) {
|
|
164
|
+
const lines = String(text ?? '').replace(/\r\n?/g, '\n').split('\n');
|
|
165
|
+
const head = {};
|
|
166
|
+
let i = 0;
|
|
167
|
+
for (; i < lines.length; i++) {
|
|
168
|
+
const kv = /^(ref|From|To|Cc|Date|Subject): ?(.*)$/.exec(lines[i]);
|
|
169
|
+
if (!kv) break;
|
|
170
|
+
head[kv[1].toLowerCase()] = kv[2];
|
|
171
|
+
}
|
|
172
|
+
if (lines[i] === '') i++;
|
|
173
|
+
let body = lines.slice(i);
|
|
174
|
+
let cut = false;
|
|
175
|
+
while (body.length && !body.at(-1).trim()) body.pop();
|
|
176
|
+
if (/^\(Large message/.test(body.at(-1) ?? '')) { cut = true; body.pop(); }
|
|
177
|
+
const attachments = [];
|
|
178
|
+
const mark = body.findIndex((l) => /^(Attachments:|--- Attachments \(\d+\) ---)$/.test(l));
|
|
179
|
+
if (mark >= 0) {
|
|
180
|
+
for (const l of body.slice(mark + 1)) { const a = attachmentOfText(l); if (a) attachments.push(a); }
|
|
181
|
+
body = body.slice(0, mark);
|
|
182
|
+
while (body.length && !body.at(-1).trim()) body.pop();
|
|
183
|
+
}
|
|
184
|
+
return { ...head, text: body.join('\n'), attachments, cut };
|
|
185
|
+
}
|
|
186
|
+
/* ONE MESSAGE OF A MAILBOX TARGET, read now, as text. `id`: its number (IMAP uid) or Graph's id, as the list gave it;
|
|
187
|
+
`folder`: the one it was listed in. */
|
|
188
|
+
export async function readMail(tethers, { target, id, folder } = {}, { who, wait = READ_MS } = {}) {
|
|
189
|
+
const t = boxOf(tethers, target);
|
|
190
|
+
const f = folderOf(t, folder);
|
|
191
|
+
const uid = String(id ?? '').trim();
|
|
192
|
+
if (!uid || uid.length > 1024 || /[\s\0]/.test(uid)) throw refused(400, 'bad-message', 'No such message.');
|
|
193
|
+
const got = await asked(tethers, t, 'mail.read', { uid, ...mailboxArg(f) }, who, wait);
|
|
194
|
+
const given = got.data?.message && typeof got.data.message === 'object';
|
|
195
|
+
const m = given ? got.data.message : messageOfText(got.text);
|
|
196
|
+
const words = wordsOf(m.text ?? m.body);
|
|
197
|
+
return {
|
|
198
|
+
target: t.id, id: uid, ref: line(m.ref, 2048) || null, from: line(m.from), to: line(m.to, 2000), cc: line(m.cc, 2000),
|
|
199
|
+
date: dateOf(m.date), subject: line(m.subject) || '(no subject)', text: words.text,
|
|
200
|
+
attachments: (Array.isArray(m.attachments) ? m.attachments : []).map(attachmentOf).filter(Boolean).slice(0, 100),
|
|
201
|
+
cut: words.cut || m.cut === true, partial: !given,
|
|
202
|
+
};
|
|
203
|
+
}
|