sideora 0.0.1-alpha.0 → 0.1.0-alpha.2
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/LICENSE.md +9 -0
- package/README.md +57 -6
- package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
- package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
- package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
- package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
- package/assets/sounds/nice-chime.mp3 +0 -0
- package/bin/sideora.js +2430 -12
- package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
- package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
- package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
- package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
- package/extension/dist/assets/shell-82MNMljp.css +1 -0
- package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
- package/extension/dist/icons/icon-128.png +0 -0
- package/extension/dist/icons/icon-16.png +0 -0
- package/extension/dist/icons/icon-32.png +0 -0
- package/extension/dist/icons/icon-48.png +0 -0
- package/extension/dist/manifest.json +40 -0
- package/extension/dist/service-worker-loader.js +1 -0
- package/extension/dist/src/newtab/index.html +14 -0
- package/extension/dist/src/panel/index.html +15 -0
- package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
- package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
- package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
- package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
- package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
- package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
- package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
- package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
- package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
- package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
- package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
- package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
- package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
- package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
- package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
- package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
- package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
- package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
- package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
- package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
- package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
- package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
- package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
- package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
- package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
- package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
- package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
- package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
- package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
- package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
- package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
- package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
- package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
- package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
- package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
- package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
- package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
- package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
- package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
- package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
- package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
- package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
- package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
- package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
- package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
- package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
- package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
- package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
- package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
- package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
- package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
- package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
- package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
- package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
- package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
- package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
- package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
- package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
- package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
- package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
- package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
- package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
- package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
- package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
- package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
- package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
- package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
- package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
- package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
- package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
- package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
- package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
- package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
- package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
- package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
- package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
- package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
- package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
- package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
- package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
- package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
- package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
- package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
- package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
- package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
- package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
- package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
- package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
- package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
- package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
- package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
- package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
- package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
- package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
- package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
- package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
- package/extension/dist-web/icon-192.png +0 -0
- package/extension/dist-web/icon-512.png +0 -0
- package/extension/dist-web/index.html +25 -0
- package/extension/dist-web/manifest.webmanifest +14 -0
- package/package.json +64 -12
- package/plugin/.claude-plugin/icon.png +0 -0
- package/plugin/.claude-plugin/plugin.json +6 -0
- package/plugin/.mcp.json +8 -0
- package/plugin/README.md +72 -0
- package/plugin/mcp-launcher.mjs +48 -0
- package/src/account-probe.js +45 -0
- package/src/accounts.js +687 -0
- package/src/ai.js +269 -0
- package/src/assistant-runs.js +32 -0
- package/src/attached-mail.js +76 -0
- package/src/auth-gate.js +70 -0
- package/src/backup-cli.js +158 -0
- package/src/backup.js +329 -0
- package/src/bimi.js +233 -0
- package/src/bridge.js +101 -0
- package/src/calendar-alerts.js +56 -0
- package/src/chats.js +27 -0
- package/src/compose-editor.js +58 -0
- package/src/config.js +420 -0
- package/src/connections.d.ts +24 -0
- package/src/connections.js +37 -0
- package/src/core/agent.js +92 -0
- package/src/core/assistant.d.ts +13 -0
- package/src/core/assistant.js +790 -0
- package/src/core/chats.js +323 -0
- package/src/core/markdown.d.ts +8 -0
- package/src/core/markdown.js +239 -0
- package/src/core/notes.js +445 -0
- package/src/core/otp.js +152 -0
- package/src/core/rules.js +196 -0
- package/src/core/runs.d.ts +9 -0
- package/src/core/runs.js +211 -0
- package/src/core/thread.js +526 -0
- package/src/core/write.js +247 -0
- package/src/core-db.js +131 -0
- package/src/core.js +174 -0
- package/src/credentials.js +320 -0
- package/src/daemon.js +564 -0
- package/src/events.js +213 -0
- package/src/extension-id.d.ts +2 -0
- package/src/extension-id.js +5 -0
- package/src/file-lock.js +27 -0
- package/src/files-index.js +154 -0
- package/src/google-contacts.js +315 -0
- package/src/google-signin.js +306 -0
- package/src/host/assistant-html.js +44 -0
- package/src/host/chats-files.js +137 -0
- package/src/host/file-prep.js +122 -0
- package/src/host/notes-files.js +158 -0
- package/src/host/office-text.js +224 -0
- package/src/host/office-worker.js +8 -0
- package/src/host/rules-file.js +20 -0
- package/src/host/secrets-file.js +91 -0
- package/src/host/systemd.js +90 -0
- package/src/hub.js +245 -0
- package/src/identity.js +316 -0
- package/src/labels.js +5 -0
- package/src/mail-port.d.ts +79 -0
- package/src/mail-port.js +148 -0
- package/src/mcp-server.js +747 -0
- package/src/microsoft-app.js +20 -0
- package/src/microsoft-signin.js +194 -0
- package/src/migrate.js +327 -0
- package/src/notes-html.js +450 -0
- package/src/notes.js +19 -0
- package/src/notify.js +105 -0
- package/src/onepassword.js +223 -0
- package/src/op-registry.d.ts +14 -0
- package/src/op-registry.js +150 -0
- package/src/ops.js +1251 -0
- package/src/otp.js +6 -0
- package/src/panel-ops.js +273 -0
- package/src/pictures.js +735 -0
- package/src/postinstall.js +25 -0
- package/src/relay-passkey.js +122 -0
- package/src/relay-request.js +155 -0
- package/src/relay-seal.js +56 -0
- package/src/relay-settings.js +139 -0
- package/src/relay.js +876 -0
- package/src/render.js +82 -0
- package/src/rules-store.js +8 -0
- package/src/safe-fetch.js +215 -0
- package/src/sender-auth.js +270 -0
- package/src/site-match.js +77 -0
- package/src/tui-agenda.js +266 -0
- package/src/tui.js +670 -0
- package/src/vmc.js +376 -0
- package/src/wake.js +96 -0
- package/src/web-access.js +185 -0
- package/src/web-server.js +241 -0
- package/src/web-service.js +152 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// The assistant's chats, in the core: what a chat is and how it is kept, over a store the host gives (makeChats,
|
|
2
|
+
// makeChatFiles): on this Mac, one file a chat (src/host/chats-files.js). This module touches no file and no setting.
|
|
3
|
+
//
|
|
4
|
+
// a chat { id, title, created, updated, rev, model, turns }
|
|
5
|
+
// the trash a chat removed (moved there: the last TRASH_KEPT removed are kept, older ones go)
|
|
6
|
+
// a file one the person attached to a question, named by what it holds (one no chat names any more, the
|
|
7
|
+
// trash's included, is let go when room is needed)
|
|
8
|
+
//
|
|
9
|
+
// A chat is what was said, not what was read to say it: `turns` are the person's questions and the assistant's
|
|
10
|
+
// answers (with the model that wrote each, what it did, and what it referred to: a mail, a note, an event, by id).
|
|
11
|
+
// What a tool read of the mail to answer is not kept: asked again, the assistant reads it again. A note the
|
|
12
|
+
// assistant prepared is kept with its answer (`notes`), with what became of it: waiting for the person's press,
|
|
13
|
+
// saved, or dropped; so is a contact it prepared (`contacts`: added to the person's Google contacts at a press).
|
|
14
|
+
//
|
|
15
|
+
// `model`: the connection and the model this chat is asked with, when not the one chosen in the settings
|
|
16
|
+
// ({ connection, label, model }): the connection is named by its id where it is kept (the web app's are this
|
|
17
|
+
// Mac's, the extension's its own).
|
|
18
|
+
//
|
|
19
|
+
// A file attached to a question is not in the chat's text: the question names it ({ id, name, kind, size, thumb })
|
|
20
|
+
// and its bytes are a file of their own, once however many chats hold it. Only what the assistant can be handed:
|
|
21
|
+
// a picture (PNG, JPEG, GIF, WebP), a PDF, or text; known by how the file starts, never by what it is called.
|
|
22
|
+
// `thumb` is a small picture of it for the page to show at once (a data: address of an image, nothing else).
|
|
23
|
+
//
|
|
24
|
+
// The whole chat is saved at once, by the page that holds it, saying which revision it started from: when the chat
|
|
25
|
+
// moved on since (the same chat in another tab), nothing is written (CHANGED). A save is read, checked and written
|
|
26
|
+
// while the store has it as its only writer (store.locked), one at a time.
|
|
27
|
+
|
|
28
|
+
import crypto from 'node:crypto';
|
|
29
|
+
|
|
30
|
+
export const CHANGED = 'the chat was changed elsewhere';
|
|
31
|
+
export const GONE = 'that chat is no longer there';
|
|
32
|
+
const ID = /^[a-z0-9]{6,24}$/;
|
|
33
|
+
const MAX_TURNS = 400;
|
|
34
|
+
const MAX_TEXT = 200_000; // characters of one question or answer
|
|
35
|
+
const MAX_CHAT = 2 * 1024 * 1024; // bytes of one chat
|
|
36
|
+
const MAX_CHATS = 300; // listed: the ones written in last
|
|
37
|
+
const MAX_KEPT = 2000; // chats kept (the trash not counted): past that, a new one waits for some to be removed
|
|
38
|
+
const TRASH_KEPT = 200; // removed chats kept in the trash: the last ones removed
|
|
39
|
+
|
|
40
|
+
const str = (v, max = 400) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
41
|
+
|
|
42
|
+
/** A reference an answer gives (a mail, a note, an event): what it is, its id, and the few words it is shown by. */
|
|
43
|
+
function refOf(r) {
|
|
44
|
+
if (!r || typeof r !== 'object' || !['mail', 'note', 'event'].includes(r.kind) || typeof r.id !== 'string' || !r.id || r.id.length > 2000) return null;
|
|
45
|
+
return { kind: r.kind, id: r.id, label: str(r.label, 300), ...(str(r.sub, 300) ? { sub: str(r.sub, 300) } : {}), ...(str(r.account, 200) ? { account: str(r.account, 200) } : {}), ...(str(r.at, 40) ? { at: str(r.at, 40) } : {}) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** An event the assistant prepared, kept with its answer until the person adds it to the calendar, opens it there, or discards it. */
|
|
49
|
+
function eventOf(e) {
|
|
50
|
+
if (!e || typeof e !== 'object' || !str(e.subject, 255).trim()) return null;
|
|
51
|
+
// a day that is one (not the 30th of February), with a time that is one
|
|
52
|
+
const at = (v) => {
|
|
53
|
+
const m = typeof v === 'string' ? /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::\d{2})?)?$/.exec(v) : null;
|
|
54
|
+
if (!m) return undefined;
|
|
55
|
+
const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
|
|
56
|
+
if (d.getUTCMonth() !== +m[2] - 1 || d.getUTCDate() !== +m[3] || (m[4] !== undefined && (+m[4] > 23 || +m[5] > 59))) return undefined;
|
|
57
|
+
return v;
|
|
58
|
+
};
|
|
59
|
+
const start = at(e.start);
|
|
60
|
+
const end = at(e.end);
|
|
61
|
+
const state = ['saved', 'dropped', 'opened'].includes(e.state) ? e.state : 'waiting';
|
|
62
|
+
let zone = '';
|
|
63
|
+
try { if (typeof e.zone === 'string' && e.zone.length <= 64) { new Intl.DateTimeFormat('en-US', { timeZone: e.zone }); zone = e.zone; } } catch { zone = ''; }
|
|
64
|
+
return {
|
|
65
|
+
subject: str(e.subject, 255), allDay: e.allDay === true,
|
|
66
|
+
...(start ? { start } : {}), ...(end && (!start || end >= start) ? { end } : {}), ...(zone ? { zone } : {}),
|
|
67
|
+
...(str(e.location, 255) ? { location: str(e.location, 255) } : {}), ...(str(e.attendees, 2000) ? { attendees: str(e.attendees, 2000) } : {}), ...(str(e.body, 2000) ? { body: str(e.body, 2000) } : {}),
|
|
68
|
+
state, ...(state === 'saved' && typeof e.id === 'string' && e.id.length <= 600 ? { id: e.id } : {})
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A note the assistant prepared, for the person to save: a new one (`title`), or something added to one of theirs (`to`). */
|
|
73
|
+
function noteOf(n) {
|
|
74
|
+
if (!n || typeof n !== 'object') return null;
|
|
75
|
+
const to = n.to && typeof n.to === 'object' && typeof n.to.id === 'string' && /^[a-z0-9]{6,24}$/.test(n.to.id) ? { id: n.to.id, label: str(n.to.label, 300) } : null;
|
|
76
|
+
const text = str(n.text, 6000);
|
|
77
|
+
const todos = Array.isArray(n.todos) ? n.todos.filter((t) => typeof t === 'string' && t.trim()).slice(0, 30).map((t) => str(t, 300)) : [];
|
|
78
|
+
if (!to && !str(n.title, 200)) return null;
|
|
79
|
+
if (!text && !todos.length) return null;
|
|
80
|
+
const state = n.state === 'saved' || n.state === 'dropped' ? n.state : 'waiting';
|
|
81
|
+
return { ...(to ? { to } : { title: str(n.title, 200) }), text, todos, state, ...(state === 'saved' && typeof n.id === 'string' && /^[a-z0-9]{6,24}$/.test(n.id) ? { id: n.id } : {}) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A contact the assistant prepared, for the person to add to their Google contacts: what it says, and where it went once added. */
|
|
85
|
+
function contactOf(c) {
|
|
86
|
+
const tstr = (v, max) => str(v, max).trim(); // (a name of spaces is no name)
|
|
87
|
+
if (!c || typeof c !== 'object') return null;
|
|
88
|
+
const list = (v, n, f) => (Array.isArray(v) ? v.slice(0, n).map(f).filter(Boolean) : []);
|
|
89
|
+
const kind = (x) => (tstr(x?.kind, 40) ? { kind: tstr(x.kind, 40) } : {});
|
|
90
|
+
const out = {
|
|
91
|
+
...(tstr(c.name, 200) ? { name: tstr(c.name, 200) } : {}),
|
|
92
|
+
emails: list(c.emails, 10, (e) => tstr(e, 320) || null),
|
|
93
|
+
phones: list(c.phones, 10, (p) => (tstr(p?.number, 60) ? { number: tstr(p.number, 60), ...kind(p) } : null)),
|
|
94
|
+
addresses: list(c.addresses, 6, (a) => (tstr(a?.text, 600) ? { text: tstr(a.text, 600), ...kind(a) } : null)),
|
|
95
|
+
...(tstr(c.company, 200) ? { company: tstr(c.company, 200) } : {}),
|
|
96
|
+
...(tstr(c.title, 200) ? { title: tstr(c.title, 200) } : {}),
|
|
97
|
+
...(tstr(c.note, 4000) ? { note: tstr(c.note, 4000) } : {}),
|
|
98
|
+
urls: list(c.urls, 6, (u) => (typeof u === 'string' && /^https?:\/\/\S+$/i.test(u) && u.length <= 500 ? u : null))
|
|
99
|
+
};
|
|
100
|
+
if (!out.name && !out.emails.length && !out.phones.length && !out.company) return null;
|
|
101
|
+
const state = c.state === 'saved' || c.state === 'dropped' ? c.state : 'waiting';
|
|
102
|
+
return { ...out, state, ...(state === 'saved' && tstr(c.account, 200) ? { account: tstr(c.account, 200) } : {}), ...(state === 'saved' && typeof c.id === 'string' && /^people\/[\w-]{1,200}$/.test(c.id) ? { id: c.id } : {}) };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const FILE_ID = /^[0-9a-f]{32}$/;
|
|
106
|
+
const THUMB = /^data:image\/(?:jpeg|png|webp);base64,[A-Za-z0-9+/]+={0,2}$/;
|
|
107
|
+
/** A file a question names: its id here, its name, what it is, and a small picture of it. */
|
|
108
|
+
function fileOfTurn(f) {
|
|
109
|
+
if (!f || typeof f !== 'object' || typeof f.id !== 'string' || !FILE_ID.test(f.id) || !['image', 'pdf', 'text'].includes(f.kind)) return null;
|
|
110
|
+
return { id: f.id, name: str(f.name, 200) || 'file', kind: f.kind, size: Number.isFinite(f.size) && f.size >= 0 ? Math.round(f.size) : 0, ...(typeof f.thumb === 'string' && f.thumb.length <= 40_000 && THUMB.test(f.thumb) ? { thumb: f.thumb } : {}) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A page of the web an answer read (its web search): an http(s) address, and its title. */
|
|
114
|
+
function sourceOf(s) {
|
|
115
|
+
if (!s || typeof s !== 'object' || typeof s.url !== 'string' || s.url.length > 2000 || !/^https?:\/\/[^\s]+$/i.test(s.url)) return null;
|
|
116
|
+
return { url: s.url, ...(str(s.title, 300) ? { title: str(s.title, 300) } : {}) };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** One turn as it is kept: only what a turn holds, each part bounded. Throws on what is not one. */
|
|
120
|
+
function turnOf(t) {
|
|
121
|
+
if (!t || typeof t !== 'object' || (t.role !== 'user' && t.role !== 'assistant') || typeof t.text !== 'string') throw new Error('a chat is made of questions and answers');
|
|
122
|
+
if (t.text.length > MAX_TEXT) throw new Error('that is too long for one message of a chat');
|
|
123
|
+
const at = Number.isFinite(t.at) ? t.at : Date.now();
|
|
124
|
+
if (t.role === 'user') return { role: 'user', text: t.text, at, ...(Array.isArray(t.files) && t.files.length ? { files: t.files.slice(0, 8).map(fileOfTurn).filter(Boolean) } : {}) };
|
|
125
|
+
return {
|
|
126
|
+
role: 'assistant', text: t.text, at,
|
|
127
|
+
...(str(t.model, 200) ? { model: str(t.model, 200) } : {}),
|
|
128
|
+
...(Array.isArray(t.steps) && t.steps.length ? { steps: t.steps.slice(0, 60).filter((s) => s && typeof s.name === 'string').map((s) => ({ name: str(s.name, 80), ok: s.ok !== false, ...(str(s.label, 200) ? { label: str(s.label, 200) } : {}) })) } : {}),
|
|
129
|
+
...(Array.isArray(t.refs) && t.refs.length ? { refs: t.refs.slice(0, 40).map(refOf).filter(Boolean) } : {}),
|
|
130
|
+
...(Array.isArray(t.notes) && t.notes.length ? { notes: t.notes.slice(0, 10).map(noteOf).filter(Boolean) } : {}),
|
|
131
|
+
...(Array.isArray(t.contacts) && t.contacts.length ? { contacts: t.contacts.slice(0, 10).map(contactOf).filter(Boolean) } : {}),
|
|
132
|
+
...(Array.isArray(t.events) && t.events.length ? { events: t.events.slice(0, 10).map(eventOf).filter(Boolean) } : {}),
|
|
133
|
+
...(Array.isArray(t.sources) && t.sources.length ? { sources: t.sources.slice(0, 20).map(sourceOf).filter(Boolean) } : {}),
|
|
134
|
+
// the drafts it kept in the Drafts folder (what it was asked to write again revises the same one)
|
|
135
|
+
...(Array.isArray(t.drafts) && t.drafts.length ? { drafts: t.drafts.slice(0, 10).filter((d) => d && typeof d.draftId === 'string' && d.draftId && d.draftId.length <= 600 && typeof d.key === 'string').map((d) => ({ draftId: d.draftId, key: str(d.key, 700), ...(str(d.subject, 300) ? { subject: str(d.subject, 300) } : {}) })) } : {}),
|
|
136
|
+
...(t.failed === true ? { failed: true } : {})
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function modelOf(m) {
|
|
141
|
+
if (!m || typeof m !== 'object' || typeof m.connection !== 'string' || !m.connection) return null;
|
|
142
|
+
return { connection: str(m.connection, 200), label: str(m.label, 200), model: str(m.model, 200) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The chats over `store` (src/host/chats-files.js is this Mac's):
|
|
147
|
+
* locked(fn) fn's result, run as the only writer (sync)
|
|
148
|
+
* count() how many chats are kept (the trash not counted)
|
|
149
|
+
* list() [{ id, at }]: the chats kept, with when each was last written
|
|
150
|
+
* read(id) a chat's text as written; null when there is none
|
|
151
|
+
* write(id, text) the text, whole
|
|
152
|
+
* trash(id, keep) moved to the trash, where the last `keep` removed are kept
|
|
153
|
+
*/
|
|
154
|
+
export function makeChats({ store }) {
|
|
155
|
+
const read = (id) => {
|
|
156
|
+
if (typeof id !== 'string' || !ID.test(id)) throw new Error('a chat is named by its id');
|
|
157
|
+
const raw = store.read(id);
|
|
158
|
+
if (raw == null) throw new Error(GONE);
|
|
159
|
+
const c = JSON.parse(raw);
|
|
160
|
+
return { id, title: str(c.title, 300), created: Number(c.created) || 0, updated: Number(c.updated) || 0, rev: Number(c.rev) || 0, model: modelOf(c.model), ...(c.web === true ? { web: true } : {}), turns: Array.isArray(c.turns) ? c.turns : [] };
|
|
161
|
+
};
|
|
162
|
+
const write = (c) => {
|
|
163
|
+
const text = JSON.stringify(c);
|
|
164
|
+
if (Buffer.byteLength(text) > MAX_CHAT) throw new Error('this chat has grown too long: start a new one');
|
|
165
|
+
store.write(c.id, text);
|
|
166
|
+
};
|
|
167
|
+
const rowOf = (c) => ({ id: c.id, title: c.title, updated: c.updated, rev: c.rev, n: c.turns.length, ...(c.model ? { model: c.model } : {}) });
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
/** The chats, the one written in last first: their names, not what they say. (Only the newest are read: by when they were written.) */
|
|
171
|
+
list() {
|
|
172
|
+
const rows = [];
|
|
173
|
+
for (const { id } of store.list().sort((a, b) => b.at - a.at).slice(0, MAX_CHATS)) {
|
|
174
|
+
try { rows.push(rowOf(read(id))); } catch { /* not one, or gone as it was read: not listed */ }
|
|
175
|
+
}
|
|
176
|
+
return { chats: rows.sort((a, b) => b.updated - a.updated) };
|
|
177
|
+
},
|
|
178
|
+
read({ id } = {}) { return read(id); },
|
|
179
|
+
/**
|
|
180
|
+
* The whole chat, as the page holds it. No `id`: a new one. `rev`: the revision it started from; the chat having
|
|
181
|
+
* moved on since, nothing is written (CHANGED). Gives its row (its new revision).
|
|
182
|
+
*/
|
|
183
|
+
save(a = {}) {
|
|
184
|
+
if (!Array.isArray(a.turns)) throw new Error('saveChat needs the turns of the chat');
|
|
185
|
+
if (a.turns.length > MAX_TURNS) throw new Error('this chat has grown too long: start a new one');
|
|
186
|
+
const turns = a.turns.map(turnOf);
|
|
187
|
+
return store.locked(() => this.saveLocked(a, turns));
|
|
188
|
+
},
|
|
189
|
+
saveLocked(a, turns) {
|
|
190
|
+
const now = Date.now();
|
|
191
|
+
let was = null;
|
|
192
|
+
if (a.id !== undefined) {
|
|
193
|
+
try { was = read(a.id); } catch (e) { if (e.message !== GONE || a.rev) throw e; } // (an id of the page's own making, not kept yet: a new chat under it)
|
|
194
|
+
if (was && Number(a.rev) !== was.rev) throw new Error(CHANGED);
|
|
195
|
+
}
|
|
196
|
+
if (!was && store.count() >= MAX_KEPT) throw new Error('there are too many chats kept: remove some before starting another');
|
|
197
|
+
const id = was?.id ?? (typeof a.id === 'string' && ID.test(a.id) ? a.id : `c${crypto.randomBytes(6).toString('hex')}`);
|
|
198
|
+
const asked = turns.find((t) => t.role === 'user');
|
|
199
|
+
const title = str(a.title, 300).replace(/\s+/g, ' ').trim() || was?.title || str(asked?.text ?? '', 80).replace(/\s+/g, ' ').trim() || str(asked?.files?.[0]?.name ?? '', 80) || 'New chat';
|
|
200
|
+
const web = a.web === undefined ? !!was?.web : a.web === true; // (whether this chat may search the web: the person's choice, kept with it)
|
|
201
|
+
const c = { id, title, created: was?.created || now, updated: now, rev: (was?.rev ?? 0) + 1, model: a.model === undefined ? was?.model ?? null : modelOf(a.model), ...(web ? { web: true } : {}), turns };
|
|
202
|
+
write(c);
|
|
203
|
+
return rowOf(c);
|
|
204
|
+
},
|
|
205
|
+
/** Removed: moved to the trash, where the last TRASH_KEPT removed are kept (the ones before go for good). */
|
|
206
|
+
remove({ id } = {}) {
|
|
207
|
+
return store.locked(() => {
|
|
208
|
+
read(id);
|
|
209
|
+
store.trash(id, TRASH_KEPT);
|
|
210
|
+
return { ok: true };
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// --- files attached to a question -------------------------------------------------
|
|
217
|
+
|
|
218
|
+
export const MAX_FILE = 8 * 1024 * 1024; // bytes, one file
|
|
219
|
+
const MAX_TEXT_FILE = 400 * 1024;
|
|
220
|
+
const MAX_FILES_KEPT = 5000;
|
|
221
|
+
const MAX_FILES_BYTES = 2 * 1024 * 1024 * 1024; // of all the files kept
|
|
222
|
+
const UNNAMED_MS = 24 * 3600e3; // a file no chat names is kept this long at least since it was last attached (its question may not be sent yet)
|
|
223
|
+
/** How much of the chats' files one turn may bring to the model: as many, and as heavy. */
|
|
224
|
+
const MAX_TURN_FILES = 24;
|
|
225
|
+
const MAX_TURN_FILE_BYTES = 14 * 1024 * 1024;
|
|
226
|
+
const starts = (b, ...bytes) => bytes.every((x, i) => b[i] === x);
|
|
227
|
+
/** What a file is, by how it starts: a picture a model takes, a PDF, or text (valid UTF-8, nothing a text has not). null: none of these. */
|
|
228
|
+
export function kindOf(bytes) {
|
|
229
|
+
if (starts(bytes, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return { kind: 'image', mediaType: 'image/png' };
|
|
230
|
+
if (starts(bytes, 0xff, 0xd8, 0xff)) return { kind: 'image', mediaType: 'image/jpeg' };
|
|
231
|
+
if (/^GIF8[79]a$/.test(bytes.toString('latin1', 0, 6))) return { kind: 'image', mediaType: 'image/gif' };
|
|
232
|
+
if (bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP') return { kind: 'image', mediaType: 'image/webp' };
|
|
233
|
+
if (bytes.toString('latin1', 0, 5) === '%PDF-') return { kind: 'pdf', mediaType: 'application/pdf' };
|
|
234
|
+
if (bytes.length <= MAX_TEXT_FILE) {
|
|
235
|
+
// (valid UTF-8, with none of the control characters a text has none of: a tab, a new line and an escape are of text)
|
|
236
|
+
try { if (!/[\u0000-\u0008\u000e-\u001a\u001c-\u001f]/.test(new TextDecoder('utf-8', { fatal: true }).decode(bytes))) return { kind: 'text', mediaType: 'text/plain' }; } catch { /* not text */ }
|
|
237
|
+
}
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The files of the chats over `store` (the chats' own: its `locked` and `eachText`, and its `files`):
|
|
243
|
+
* files.list() [{ id, size, at }]: the files kept
|
|
244
|
+
* files.read(id) the bytes (a Buffer); null when it is not kept
|
|
245
|
+
* files.size(id) -1 when it is not kept
|
|
246
|
+
* files.put(id, bytes) kept, whole or not at all
|
|
247
|
+
* files.touch(id) its time starts again
|
|
248
|
+
* files.remove(id)
|
|
249
|
+
* eachText(visit) visit(text) for every chat, the trash's included, one at a time; false when one could not be read
|
|
250
|
+
*/
|
|
251
|
+
export function makeChatFiles({ store }) {
|
|
252
|
+
const files = store.files;
|
|
253
|
+
const read = (id) => {
|
|
254
|
+
if (typeof id !== 'string' || !FILE_ID.test(id)) throw new Error('a file of a chat is named by its id');
|
|
255
|
+
const bytes = files.read(id);
|
|
256
|
+
if (bytes == null) throw new Error('that file is no longer kept');
|
|
257
|
+
const kind = kindOf(bytes);
|
|
258
|
+
if (!kind) throw new Error('that file is not one the assistant can be handed');
|
|
259
|
+
return { bytes, ...kind };
|
|
260
|
+
};
|
|
261
|
+
let collectedAt = 0;
|
|
262
|
+
/** The files no chat names any more (the trash's included), kept longer than UNNAMED_MS: let go. Under the chats' lock: no chat is saved while it looks. */
|
|
263
|
+
const collect = () => store.locked(() => {
|
|
264
|
+
const named = new Set();
|
|
265
|
+
// (one not read: nothing is let go on its account)
|
|
266
|
+
if (!store.eachText((text) => { for (const m of text.matchAll(/"id":"([0-9a-f]{32})"/g)) named.add(m[1]); })) return;
|
|
267
|
+
for (const f of files.list()) if (!named.has(f.id) && Date.now() - f.at > UNNAMED_MS) files.remove(f.id);
|
|
268
|
+
});
|
|
269
|
+
return {
|
|
270
|
+
collect,
|
|
271
|
+
/** Keep a file: `data`, its bytes in base64. Named by what it holds: the same file kept twice is one. { id, kind, mediaType, size }. */
|
|
272
|
+
add({ data } = {}) {
|
|
273
|
+
if (typeof data !== 'string' || !data || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error('a file is its bytes, in base64');
|
|
274
|
+
if (data.length > Math.ceil(MAX_FILE / 3) * 4 + 4) throw new Error(`that file is more than ${Math.round(MAX_FILE / 1024 / 1024)} MB`);
|
|
275
|
+
const bytes = Buffer.from(data, 'base64');
|
|
276
|
+
const kind = kindOf(bytes);
|
|
277
|
+
if (!kind) throw new Error('only a picture (PNG, JPEG, GIF, WebP), a PDF or a text file can be attached');
|
|
278
|
+
const id = crypto.createHash('sha256').update(bytes).digest('hex').slice(0, 32);
|
|
279
|
+
if (files.size(id) !== bytes.length) {
|
|
280
|
+
const room = () => { const all = files.list(); return all.length < MAX_FILES_KEPT && all.reduce((n, f) => n + f.size, 0) + bytes.length <= MAX_FILES_BYTES; };
|
|
281
|
+
// (looked through once in a while at most: it reads every chat)
|
|
282
|
+
if (!room()) { if (Date.now() - collectedAt > 10 * 60_000) { collectedAt = Date.now(); collect(); } if (!room()) throw new Error('too many files are kept with the chats: remove some chats that have files'); }
|
|
283
|
+
files.put(id, bytes);
|
|
284
|
+
} else {
|
|
285
|
+
// (attached again: its time starts again, so that it is not let go as unnamed while its question is written)
|
|
286
|
+
files.touch(id);
|
|
287
|
+
}
|
|
288
|
+
return { id, ...kind, size: bytes.length };
|
|
289
|
+
},
|
|
290
|
+
/** Its bytes, in base64, with what it is. */
|
|
291
|
+
get({ id } = {}) { const f = read(id); return { data: f.bytes.toString('base64'), kind: f.kind, mediaType: f.mediaType, size: f.bytes.length }; },
|
|
292
|
+
/**
|
|
293
|
+
* The messages of a turn, with the files they name (`{ type: 'file', id, name }` among a message's parts) as
|
|
294
|
+
* the model takes them: a picture, a PDF as a document, a text file as its text. (The page names them; their
|
|
295
|
+
* bytes do not travel with each turn.)
|
|
296
|
+
*/
|
|
297
|
+
expand(messages) {
|
|
298
|
+
if (!Array.isArray(messages)) return messages;
|
|
299
|
+
// (counted and weighed before anything is read: a turn naming a file a thousand times is refused, not loaded)
|
|
300
|
+
const asked = messages.flatMap((m) => (Array.isArray(m?.content) ? m.content.filter((p) => p && p.type === 'file') : []));
|
|
301
|
+
if (asked.length > MAX_TURN_FILES) throw new Error('too many files for one turn');
|
|
302
|
+
let weight = 0;
|
|
303
|
+
for (const p of asked) {
|
|
304
|
+
if (typeof p.id !== 'string' || !FILE_ID.test(p.id)) throw new Error('a file of a chat is named by its id');
|
|
305
|
+
const size = files.size(p.id);
|
|
306
|
+
if (size < 0) throw new Error('that file is no longer kept');
|
|
307
|
+
weight += size;
|
|
308
|
+
}
|
|
309
|
+
if (weight > MAX_TURN_FILE_BYTES) throw new Error('the files of this chat are too much to hand to a model at once');
|
|
310
|
+
return messages.map((m) => {
|
|
311
|
+
if (!m || !Array.isArray(m.content) || !m.content.some((p) => p && p.type === 'file')) return m;
|
|
312
|
+
return { ...m, content: m.content.map((p) => {
|
|
313
|
+
if (!p || p.type !== 'file') return p;
|
|
314
|
+
const f = read(p.id);
|
|
315
|
+
const name = str(p.name, 200).replace(/[\r\n"]/g, ' ') || 'file';
|
|
316
|
+
if (f.kind === 'image') return { type: 'image', mediaType: f.mediaType, data: f.bytes.toString('base64') };
|
|
317
|
+
if (f.kind === 'pdf') return { type: 'document', mediaType: 'application/pdf', data: f.bytes.toString('base64'), name };
|
|
318
|
+
return { type: 'text', text: `<attachment name="${name}">\n${f.bytes.toString('utf8')}\n</attachment>` };
|
|
319
|
+
}) };
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Types of src/core/markdown.js, for the page (extension/src/panel/lib/markdown.ts gives it out).
|
|
2
|
+
export function looksLikeMarkdown(text: string): boolean;
|
|
3
|
+
export function markdownToEditorHtml(md: string, notes?: boolean, pictures?: boolean): string;
|
|
4
|
+
export const MAX_VIEW: number;
|
|
5
|
+
export function markdownToViewHtml(md: string): string;
|
|
6
|
+
export function withTodoIds(html: string): string;
|
|
7
|
+
export function todoListHtml(todos: string[]): string;
|
|
8
|
+
export function noteHtmlOf(md: string): string;
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// The core's, and the page's (extension/src/panel/lib/markdown.ts gives it out there): one way to read Markdown.
|
|
2
|
+
//
|
|
3
|
+
// Markdown pasted into the editor, as the editor's own HTML: what a chat
|
|
4
|
+
// answer, a README or a note app copied as plain text looks like once
|
|
5
|
+
// written. What the editor has no place for becomes the nearest it has: a
|
|
6
|
+
// heading is a bold line, a rule an empty line.
|
|
7
|
+
//
|
|
8
|
+
// Every pattern here is tried on one line at a time, with bounded repeats: a
|
|
9
|
+
// paste of any size or shape is read in time proportional to its length (a
|
|
10
|
+
// run of blank lines or of brackets must not hold the panel).
|
|
11
|
+
|
|
12
|
+
const MAX = 50_000; // longer than that, a paste is taken as it is
|
|
13
|
+
|
|
14
|
+
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
15
|
+
|
|
16
|
+
const HEADING = /^(#{1,6}) +(\S.*?)(?: +#+)? *$/; // a closing run of # only after a space: C# stays C#
|
|
17
|
+
const ITEM = /^([ \t]{0,16})([-*+]|\d{1,9}[.)]) +(\S.*)$/;
|
|
18
|
+
const QUOTE = /^[ \t]{0,8}> ?/;
|
|
19
|
+
const FENCE = /^[ \t]{0,3}```/;
|
|
20
|
+
const RULE = /^[ \t]{0,3}(?:-{3,}|\*{3,}|_{3,})[ \t]*$/;
|
|
21
|
+
/** The line under a table's header: dashes between pipes (a single column needs its pipes on both sides). */
|
|
22
|
+
function isTableRule(line) {
|
|
23
|
+
if (line.length > 2000 || !line.includes('|') || !line.includes('-')) return false;
|
|
24
|
+
const parts = cells(line);
|
|
25
|
+
return parts.length > 0 && parts.every((p) => /^:?-+:?$/.test(p)) && (parts.length > 1 || /^[ \t]*\|.*\|[ \t]*$/.test(line));
|
|
26
|
+
}
|
|
27
|
+
const INLINE = /\*\*[^*\n]{1,200}\*\*|__[^_\n]{1,200}__|`[^`\n]{1,200}`|\[[^\]\n]{1,200}\]\((?:https?:|mailto:)[^)\s]{1,2000}\)|~~[^~\n]{1,200}~~/g;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Does this plain text read as Markdown? A table, a fence, a heading, or a
|
|
31
|
+
* list or quote of two lines or more; or inline marks used twice (once, with
|
|
32
|
+
* a block mark beside it). A sentence with one "**" or a lone "- " is left as
|
|
33
|
+
* it is.
|
|
34
|
+
*/
|
|
35
|
+
export function looksLikeMarkdown(text) {
|
|
36
|
+
if (!text || text.length > MAX) return false;
|
|
37
|
+
const lines = text.split(/\r?\n/);
|
|
38
|
+
let listed = 0;
|
|
39
|
+
let quoted = 0;
|
|
40
|
+
let block = false;
|
|
41
|
+
let headings = 0; // set apart from what follows, as a heading is (a shell comment or a YAML key is not)
|
|
42
|
+
for (let i = 0; i < lines.length; i++) {
|
|
43
|
+
const l = lines[i];
|
|
44
|
+
if (i > 0 && lines[i - 1].includes('|') && isTableRule(l)) return true;
|
|
45
|
+
if (FENCE.test(l)) return true;
|
|
46
|
+
if (HEADING.test(l)) { block = true; if (i + 1 >= lines.length || !lines[i + 1].trim()) headings++; }
|
|
47
|
+
if (ITEM.test(l)) { listed++; block = true; }
|
|
48
|
+
if (QUOTE.test(l) && l.trim().length > 1) { quoted++; block = true; }
|
|
49
|
+
}
|
|
50
|
+
if (listed >= 2 || quoted >= 2) return true;
|
|
51
|
+
const marks = (text.match(INLINE) ?? []).length;
|
|
52
|
+
// a heading alone ("# install" over a command) is not enough: with a list, a mark or another heading it is
|
|
53
|
+
return marks >= 2 || (block && marks >= 1) || (headings >= 1 && (listed >= 1 || headings >= 2));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// (set for the time of one call: a note that brings pictures in, see markdownToEditorHtml)
|
|
57
|
+
let bringPictures = false;
|
|
58
|
+
|
|
59
|
+
function inline(text) {
|
|
60
|
+
// code and addresses first, set aside: nothing inside code is a mark, and an address is never rewritten by one
|
|
61
|
+
const kept= [];
|
|
62
|
+
const keep = (html) => `\u0000${kept.push(html) - 1}\u0000`;
|
|
63
|
+
let s = text.replace(/[\u0000-\u0003]/g, '');
|
|
64
|
+
s = s.replace(/`([^`\n]{1,2000})`/g, (_, c) => keep(`<code>${esc(c)}</code>`));
|
|
65
|
+
// : a picture is not held here, so it is a link to it, named by what it shows
|
|
66
|
+
s = s.replace(/!\[([^\]\n]{0,500})\]\((https?:\/\/[^)\s]{1,2000})(?:\s+(?:"[^"\n]{0,300}"|'[^'\n]{0,300}'))?\)/g, (_, alt, href) => keep(bringPictures && /^https:\/\//i.test(href) ? `<img data-import="${esc(href)}" alt="${esc(alt.trim())}">` : `<a href="${esc(href)}">${esc(alt.trim() || href)}</a>`));
|
|
67
|
+
// [label](address), with or without a title after the address: the label is written like any text, the address is kept whole
|
|
68
|
+
s = s.replace(/\[([^\]\n]{1,500})\]\(((?:https?:\/\/|mailto:)[^)\s]{1,2000})(?:\s+(?:"[^"\n]{0,300}"|'[^'\n]{0,300}'))?\)/g, (_, label, href) => `${keep(`<a href="${esc(href)}">`)}\u0001${label}\u0002`);
|
|
69
|
+
// a bare address is a link too
|
|
70
|
+
s = s.replace(/(^|[\s("'<])(https?:\/\/[^\s<)]{0,2000}[^\s<).,;:!?'"])/g, (_, before, href) => `${before}${keep(`<a href="${esc(href)}">${esc(href)}</a>`)}`);
|
|
71
|
+
s = esc(s);
|
|
72
|
+
// three stars: bold and italic at once
|
|
73
|
+
s = s.replace(/(^|[^\w*])\*\*\*(?=\S)([^*]{0,2000}?\S)\*\*\*(?!\w)/g, '$1<strong><em>$2</em></strong>');
|
|
74
|
+
s = s.replace(/(^|[^\w*])\*\*(?=\S)([^*]{1,2000}?)\*\*(?!\w)/g, '$1<strong>$2</strong>');
|
|
75
|
+
s = s.replace(/(^|[^\w_])__(?=\S)([^_]{1,2000}?)__(?!\w)/g, '$1<strong>$2</strong>');
|
|
76
|
+
// a closing mark follows a letter, not a space: "*.js and *.ts" is not emphasis
|
|
77
|
+
s = s.replace(/(^|[^\w*])\*(?=\S)([^*]{0,2000}?\S)\*(?!\w)/g, '$1<em>$2</em>');
|
|
78
|
+
s = s.replace(/(^|[^\w_])_(?=\S)([^_]{0,2000}?\S)_(?!\w)/g, '$1<em>$2</em>');
|
|
79
|
+
s = s.replace(/~~([^~]{1,2000})~~/g, '<s>$1</s>');
|
|
80
|
+
s = s.replace(/\u0001/g, '').replace(/\u0002/g, '</a>');
|
|
81
|
+
return s.replace(/\u0000(\d+)\u0000/g, (_, k) => kept[Number(k)] ?? '');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The cells of a table's line: split at pipes that are not escaped; a pipe at either end only bounds the row. */
|
|
85
|
+
function cells(row) {
|
|
86
|
+
const out= [];
|
|
87
|
+
let cur = '';
|
|
88
|
+
for (let i = 0; i < row.length; i++) {
|
|
89
|
+
const ch = row[i];
|
|
90
|
+
if (ch === '\\' && row[i + 1] === '|') { cur += '|'; i++; continue; }
|
|
91
|
+
if (ch === '|') { out.push(cur); cur = ''; continue; }
|
|
92
|
+
cur += ch;
|
|
93
|
+
}
|
|
94
|
+
out.push(cur);
|
|
95
|
+
if (out.length > 1 && !out[0].trim()) out.shift();
|
|
96
|
+
if (out.length > 1 && !out[out.length - 1].trim()) out.pop();
|
|
97
|
+
return out.map((c) => c.trim());
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Markdown to the editor's HTML (paragraphs, lists, quotes, code, tables, links, bold, italic, strike).
|
|
102
|
+
* `notes`: for a note, which a mail is not: a heading is one (of three sizes), and `- [ ]` is a to-do to tick.
|
|
103
|
+
* `pictures`: `` is a picture to bring in (`<img data-import>`, which the note's editor fetches once
|
|
104
|
+
* and keeps), not a link to it: only where what is written is the person's own paste.
|
|
105
|
+
*/
|
|
106
|
+
export function markdownToEditorHtml(md, notes = false, pictures = false) {
|
|
107
|
+
const was = bringPictures;
|
|
108
|
+
bringPictures = pictures;
|
|
109
|
+
try { return convert(md, { headings: notes, tasks: notes }); } finally { bringPictures = was; }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A file this long is not laid out (shown as the text it is). */
|
|
113
|
+
export const MAX_VIEW = 1024 * 1024;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Markdown to HTML for reading (a .md file shown, not written in): headings are headings, a rule is a rule, a to-do
|
|
117
|
+
* is a box drawn ticked or not, links open in a tab of their own. The same reading as the editor's: every piece of
|
|
118
|
+
* text is escaped, and only the tags written here come out (a file's own HTML is shown as the text it is; an
|
|
119
|
+
* address is a link only when it is http(s) or mailto).
|
|
120
|
+
*/
|
|
121
|
+
export function markdownToViewHtml(md) {
|
|
122
|
+
const was = bringPictures;
|
|
123
|
+
bringPictures = false;
|
|
124
|
+
try { return convert(md, { headings: true, tasks: false, rule: '<hr>', max: MAX_VIEW }).replace(/<a href="/g, '<a target="_blank" rel="noopener noreferrer" href="'); } finally { bringPictures = was; }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Quotes inside quotes, this deep at most: deeper, the rest is the text it is (a file of nothing but ">" must not hold the page, or run it out of room). */
|
|
128
|
+
const MAX_DEPTH = 12;
|
|
129
|
+
|
|
130
|
+
function convert(md, how, depth = 0) {
|
|
131
|
+
const notes = how.tasks;
|
|
132
|
+
if (md.length > (how.max ?? MAX) || depth > MAX_DEPTH) return `<p>${esc(md)}</p>`;
|
|
133
|
+
const lines = md.replace(/\r\n?/g, '\n').split('\n');
|
|
134
|
+
const out= [];
|
|
135
|
+
const para= [];
|
|
136
|
+
const flush = () => { if (para.length) { out.push(`<p>${para.map(inline).join('<br>')}</p>`); para.length = 0; } };
|
|
137
|
+
let i = 0;
|
|
138
|
+
while (i < lines.length) {
|
|
139
|
+
const line = lines[i];
|
|
140
|
+
if (!line.trim()) { flush(); i++; continue; }
|
|
141
|
+
if (FENCE.test(line)) {
|
|
142
|
+
flush();
|
|
143
|
+
const lang = /^[ \t]{0,3}```[ \t]*([A-Za-z0-9_+-]{1,30})/.exec(line)?.[1]?.toLowerCase();
|
|
144
|
+
const buf= [];
|
|
145
|
+
i++;
|
|
146
|
+
while (i < lines.length && !FENCE.test(lines[i])) buf.push(lines[i++]);
|
|
147
|
+
i++;
|
|
148
|
+
// (its language kept as the editor reads one: a `mermaid` block is drawn)
|
|
149
|
+
out.push(`<pre><code${lang ? ` class="language-${lang}"` : ''}>${esc(buf.join('\n'))}</code></pre>`);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const h = HEADING.exec(line);
|
|
153
|
+
if (h) {
|
|
154
|
+
flush();
|
|
155
|
+
const level = Math.min(3, h[1].length);
|
|
156
|
+
out.push(how.headings ? `<h${level}>${inline(h[2])}</h${level}>` : `<p><strong>${inline(h[2])}</strong></p>`);
|
|
157
|
+
i++;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (RULE.test(line)) { flush(); out.push(how.rule ?? '<p></p>'); i++; continue; }
|
|
161
|
+
if (line.includes('|') && i + 1 < lines.length && isTableRule(lines[i + 1])) {
|
|
162
|
+
flush();
|
|
163
|
+
const head = cells(line);
|
|
164
|
+
i += 2;
|
|
165
|
+
const rows= [];
|
|
166
|
+
while (i < lines.length && lines[i].includes('|') && lines[i].trim()) rows.push(cells(lines[i++]));
|
|
167
|
+
const row = (r, tag) => `<tr>${head.map((_, k) => `<${tag}><p>${inline(r[k] ?? '')}</p></${tag}>`).join('')}</tr>`;
|
|
168
|
+
out.push(`<table><tbody>${row(head, 'th')}${rows.map((r) => row(r, 'td')).join('')}</tbody></table>`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (ITEM.test(line)) {
|
|
172
|
+
flush();
|
|
173
|
+
// a list, one level deeper for each step of indent
|
|
174
|
+
const html= [];
|
|
175
|
+
const open= [];
|
|
176
|
+
while (i < lines.length) {
|
|
177
|
+
// a blank line between items (as chat answers write them) does not end the list
|
|
178
|
+
if (!lines[i].trim()) {
|
|
179
|
+
let j = i;
|
|
180
|
+
while (j < lines.length && !lines[j].trim()) j++;
|
|
181
|
+
if (j < lines.length && (ITEM.test(lines[j]) || /^[ \t]{2,}\S/.test(lines[j]))) { i = j; continue; }
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
const m = ITEM.exec(lines[i]);
|
|
185
|
+
if (!m) {
|
|
186
|
+
// a line that goes on the item above
|
|
187
|
+
if (lines[i].trim() && /^[ \t]{2,}\S/.test(lines[i]) && html.length) { html[html.length - 1] = html[html.length - 1].replace(/<\/p>$/, `<br>${inline(lines[i].trim())}</p>`); i++; continue; }
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
const indent = m[1].replace(/\t/g, ' ').length;
|
|
191
|
+
const task = /^\[( |x|X)\] +(.*)$/.exec(m[3]);
|
|
192
|
+
// in a note, to-dos are a list of their own kind (ticked in place)
|
|
193
|
+
const tag = notes && task ? 'task' : /\d/.test(m[2]) ? 'ol' : 'ul';
|
|
194
|
+
const end = (t) => `</li></${t === 'task' ? 'ul' : t}>`;
|
|
195
|
+
while (open.length > 1 && indent < open[open.length - 1].indent) html.push(end(open.pop() .tag));
|
|
196
|
+
// the other kind of list at the same level: this one ends and that one begins
|
|
197
|
+
if (open.length && indent === open[open.length - 1].indent && open[open.length - 1].tag !== tag) {
|
|
198
|
+
html.push(end(open.pop() .tag));
|
|
199
|
+
if (open.length) html.push('</li>');
|
|
200
|
+
}
|
|
201
|
+
if (!open.length || indent > open[open.length - 1].indent) {
|
|
202
|
+
// a numbered list keeps the number it starts at (a part of a procedure, copied)
|
|
203
|
+
const start = tag === 'ol' ? parseInt(m[2], 10) : 1;
|
|
204
|
+
html.push(tag === 'task' ? '<ul data-type="taskList">' : start > 1 ? `<ol start="${start}">` : `<${tag}>`);
|
|
205
|
+
open.push({ tag, indent });
|
|
206
|
+
} else html.push('</li>');
|
|
207
|
+
if (tag === 'task') html.push(`<li data-type="taskItem" data-checked="${task [1] === ' ' ? 'false' : 'true'}"><p>${inline(task [2])}</p>`);
|
|
208
|
+
else html.push(`<li><p>${task ? `${task[1] === ' ' ? '☐' : '☑'} ${inline(task[2])}` : inline(m[3])}</p>`);
|
|
209
|
+
i++;
|
|
210
|
+
}
|
|
211
|
+
while (open.length) { const t = open.pop() .tag; html.push(`</li></${t === 'task' ? 'ul' : t}>`); }
|
|
212
|
+
out.push(html.join(''));
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (QUOTE.test(line)) {
|
|
216
|
+
flush();
|
|
217
|
+
const buf= [];
|
|
218
|
+
while (i < lines.length && QUOTE.test(lines[i])) buf.push(lines[i++].replace(QUOTE, ''));
|
|
219
|
+
out.push(`<blockquote>${convert(buf.join('\n'), how, depth + 1)}</blockquote>`);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
para.push(line.trim());
|
|
223
|
+
i++;
|
|
224
|
+
}
|
|
225
|
+
flush();
|
|
226
|
+
return out.join('');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// --- a note's own HTML -------------------------------------------------------------------------------------------
|
|
230
|
+
|
|
231
|
+
const escAttr = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
232
|
+
const newTodoId = () => [...globalThis.crypto.getRandomValues(new Uint8Array(4))].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
233
|
+
const todoHtml = (id, text) => `<li data-type="taskItem" data-checked="false" data-id="${escAttr(id)}"><label><input type="checkbox"><span></span></label><div><p>${escAttr(text)}</p></div></li>`;
|
|
234
|
+
/** HTML written from Markdown, its to-dos each given an id of its own (the store lists, and Home ticks, those that have one). */
|
|
235
|
+
export const withTodoIds = (html) => html.replace(/<li data-type="taskItem"(?![^>]*\sdata-id=)/g, () => `<li data-type="taskItem" data-id="${newTodoId()}"`);
|
|
236
|
+
/** To-dos as the editor writes them, each with an id of its own: what a new note begins with ('' for none). */
|
|
237
|
+
export const todoListHtml = (todos) => (todos.length ? `<ul data-type="taskList">${todos.map((t) => todoHtml(newTodoId(), t)).join('')}</ul>` : '');
|
|
238
|
+
/** What is written in a note from Markdown (headings, lists, to-dos with their ids). */
|
|
239
|
+
export const noteHtmlOf = (md) => withTodoIds(markdownToEditorHtml(md, true));
|