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.
Files changed (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
@@ -0,0 +1,315 @@
1
+ // Google contacts: the contacts (and "other contacts") of every account whose
2
+ // Google sign-in allows reading them, for People, the composer's suggestions,
3
+ // the assistant's look-ups and sender pictures.
4
+ //
5
+ // mailcore reads them (People API, core.google.contacts); this keeps them:
6
+ // in the core's encrypted database (src/core-db.js), in memory
7
+ // when there is none, never in a plain file. They are asked of Google at most
8
+ // every half hour per account, and again soon after a new sign-in (its time is
9
+ // kept beside them). A list Google refuses for good (contacts not allowed, the
10
+ // API off, the sign-in refused) is let go; one it fails to give for a while
11
+ // (rate limits, no network, a 5xx) keeps what was read before. An account
12
+ // whose sign-in no longer allows contacts, or that is gone, has what was kept
13
+ // of it let go, its contacts' photos too; a Keychain that cannot be read for a
14
+ // moment is not taken for that. A read that ends after such a change keeps
15
+ // nothing. They go nowhere but Google (asked) and this Mac (kept); nothing of
16
+ // them is logged — a failure is logged by its code alone, and `doctor` says it.
17
+
18
+ import { calendarProvider } from './config.js';
19
+
20
+ export const REFRESH_MS = 30 * 60e3;
21
+ /** After a failure that may pass (no network, a 5xx, rate limits): asked again this soon. */
22
+ export const RETRY_MS = 5 * 60e3;
23
+ /** How often which accounts may be read (the Keychain) is looked at again. */
24
+ const ACCESS_MS = 60e3;
25
+ const KNOWN_CODES = new Set(['GOOGLE_SCOPE', 'GOOGLE_API_DISABLED', 'GOOGLE_RATE', 'GOOGLE_API', 'MAIL_AUTH']);
26
+ /** A failure that may pass (rate limits, a 5xx or a timeout, no network): what was read before is kept. Anything else is Google saying no. */
27
+ export const transient = (f) => f.code === 'GOOGLE_RATE' || (f.code === 'GOOGLE_API' && (!f.status || f.status >= 500 || f.status === 408)) || !KNOWN_CODES.has(f.code);
28
+
29
+ /** What a record holds: read again, at once, when it is of an older shape (one with fewer fields of each contact). */
30
+ const SHAPE = 2;
31
+ const SCHEMA = 'CREATE TABLE IF NOT EXISTS mw_google_contacts (account TEXT PRIMARY KEY, at INTEGER NOT NULL, data BLOB NOT NULL)';
32
+
33
+ /**
34
+ * Where each account's contacts are kept: the database `open()` returns (the
35
+ * encrypted cache), else memory. get(account) → record | null; put(account, record); drop(account).
36
+ * record: { at, tried, signedInAt?, saved: [] | null, other: [] | null, error?: { code, message, list?, at } }
37
+ */
38
+ export function contactsStore({ open = () => null, now = Date.now } = {}) {
39
+ const mem = new Map();
40
+ const parsed = new Map(); // account → { stamp, rec }: a record read once until it changes
41
+ const ready = new WeakSet();
42
+ let seq = 0;
43
+ const db = () => {
44
+ try {
45
+ const d = open();
46
+ if (d && !ready.has(d)) { d.exec(SCHEMA); ready.add(d); }
47
+ return d || null;
48
+ } catch { return null; }
49
+ };
50
+ return {
51
+ get(account) {
52
+ const d = db();
53
+ if (!d) return mem.get(account) ?? null;
54
+ try {
55
+ // the stamp first (a number): the record itself is parsed again only when another write came
56
+ const s = d.prepare('SELECT at FROM mw_google_contacts WHERE account = ?').get(account);
57
+ if (!s) return mem.get(account) ?? null;
58
+ const kept = parsed.get(account);
59
+ if (kept && kept.stamp === s.at) return kept.rec;
60
+ const r = d.prepare('SELECT at, data FROM mw_google_contacts WHERE account = ?').get(account);
61
+ const rec = JSON.parse(Buffer.from(r.data).toString('utf8'));
62
+ parsed.set(account, { stamp: r.at, rec });
63
+ return rec;
64
+ } catch { return mem.get(account) ?? null; }
65
+ },
66
+ put(account, record) {
67
+ const d = db();
68
+ if (!d) { mem.set(account, record); return; }
69
+ try {
70
+ // the stamp of this write: later than any before it, from this process or another
71
+ const stamp = Math.max(now() * 1000 + (++seq % 1000), (d.prepare('SELECT at FROM mw_google_contacts WHERE account = ?').get(account)?.at || 0) + 1);
72
+ d.prepare('INSERT INTO mw_google_contacts (account, at, data) VALUES (?, ?, ?) ON CONFLICT(account) DO UPDATE SET at = excluded.at, data = excluded.data')
73
+ .run(account, stamp, Buffer.from(JSON.stringify(record), 'utf8'));
74
+ parsed.set(account, { stamp, rec: record });
75
+ mem.delete(account);
76
+ } catch { mem.set(account, record); }
77
+ },
78
+ drop(account) {
79
+ mem.delete(account);
80
+ parsed.delete(account);
81
+ const d = db();
82
+ if (d) { try { d.prepare('DELETE FROM mw_google_contacts WHERE account = ?').run(account); } catch { /* next time */ } }
83
+ },
84
+ accounts() {
85
+ const d = db();
86
+ const out = new Set(mem.keys());
87
+ if (d) { try { for (const r of d.prepare('SELECT account FROM mw_google_contacts').all()) out.add(r.account); } catch { /* the memory's */ } }
88
+ return [...out];
89
+ }
90
+ };
91
+ }
92
+
93
+ const short = (e) => ({ code: String(e?.code || 'NETWORK'), ...(e?.status ? { status: e.status } : {}), message: String(e?.message || e).split('\n')[0].slice(0, 300) });
94
+ const photosOf = (rec) => [...(rec?.saved || []), ...(rec?.other || [])].map((c) => c.photo).filter(Boolean);
95
+
96
+ /**
97
+ * The contacts over their dependencies (injected, for tests):
98
+ * accounts() [{ name, contacts: boolean, signedInAt?, unknown? }]: the accounts with a Google sign-in, whether it
99
+ * allows contacts, and `unknown` when the Keychain could not be read (signedInAccounts)
100
+ * read(account) mailcore's google.contacts(account) → { saved, other, errors }
101
+ * store contactsStore()
102
+ * forgetPhotos(urls) the photos of contacts let go (pictures.js forgetContactPhotos)
103
+ * now(), log(msg)
104
+ */
105
+ export function createGoogleContacts({ accounts, read, store, forgetPhotos = () => {}, now = Date.now, log = () => {} }) {
106
+ let accessAt = -Infinity;
107
+ let accessKept = [];
108
+ /** The accounts with a Google sign-in, read now; on a failure (config.json unreadable), the last ones. */
109
+ const readAccess = () => {
110
+ try { accessKept = accounts() || []; } catch { /* the last ones */ }
111
+ accessAt = now();
112
+ return accessKept;
113
+ };
114
+ /** The same, looked at again once a minute (at once after invalidate). */
115
+ const signedIn = () => (now() - accessAt > ACCESS_MS ? readAccess() : accessKept);
116
+ const running = new Map(); // account → { gen, p }: the read under way
117
+ const generation = new Map(); // account → n: a removal, a change of what it allows or a sign-in moves it on
118
+ const genOf = (name) => generation.get(name) || 0;
119
+ const bump = (name) => generation.set(name, genOf(name) + 1);
120
+ const indexes = new Map(); // account (or '*') → { records, byEmail, list, people }: rebuilt when a record changes
121
+
122
+ /** Whether an account's record is worth asking Google again. */
123
+ const stale = (rec, acct) => {
124
+ if (!rec || rec.shape !== SHAPE) return true;
125
+ if ((acct.signedInAt || '') !== (rec.signedInAt || '')) return true; // a sign-in since: read again now
126
+ const since = now() - (rec.tried || 0);
127
+ return since >= (rec.error?.transient ? RETRY_MS : REFRESH_MS);
128
+ };
129
+
130
+ /** What was let go between two records of an account: those photos go too. */
131
+ const letGo = (before, after) => {
132
+ const kept = new Set(photosOf(after));
133
+ const gone = photosOf(before).filter((u) => !kept.has(u));
134
+ if (gone.length) { try { forgetPhotos(gone); } catch { /* pruned later, at worst */ } }
135
+ };
136
+
137
+ /** Let an account's contacts go (and their photos); a read of it under way keeps nothing. */
138
+ function dropAccount(name) {
139
+ bump(name);
140
+ const before = store.get(name);
141
+ store.drop(name);
142
+ letGo(before, null);
143
+ indexes.clear();
144
+ }
145
+
146
+ /** Whether an account may still be read, asked again now (a Keychain that cannot be read: not known to be otherwise). */
147
+ const stillAllowed = (name) => {
148
+ const a = readAccess().find((x) => x.name === name);
149
+ return !!a && (a.contacts || !!a.unknown);
150
+ };
151
+
152
+ /**
153
+ * Read one account's contacts from Google and keep them. → the record kept, or null when what was read is not
154
+ * kept (the account was removed, signed in again or its contacts no longer allowed meanwhile).
155
+ */
156
+ function refreshOne(acct) {
157
+ const gen = genOf(acct.name);
158
+ const run = running.get(acct.name);
159
+ if (run && run.gen === gen) return run.p;
160
+ const p = (async () => {
161
+ const before = store.get(acct.name);
162
+ const rec = { shape: SHAPE, at: before?.at || 0, tried: now(), signedInAt: acct.signedInAt || '', saved: before?.saved ?? null, other: before?.other ?? null, groups: before?.groups ?? {} };
163
+ const failures = [];
164
+ try {
165
+ const r = await read(acct.name);
166
+ if (r.saved) rec.saved = r.saved;
167
+ if (r.other) rec.other = r.other;
168
+ if (r.saved && r.groups && typeof r.groups === 'object') rec.groups = r.groups;
169
+ failures.push(...(r.errors || []));
170
+ } catch (e) {
171
+ failures.push(...(e?.errors?.length ? e.errors : [{ list: '*', ...short(e) }]));
172
+ }
173
+ // Google saying no to a list lets it go; a failure that may pass keeps what was read before
174
+ for (const f of failures) if (!transient(f)) for (const list of f.list === 'saved' || f.list === 'other' ? [f.list] : ['saved', 'other']) rec[list] = null;
175
+ if (failures.length < 2 && !failures.some((f) => f.list === '*')) rec.at = now();
176
+ const first = failures.find((f) => f.list === 'saved') || failures[0];
177
+ if (first) {
178
+ rec.error = { code: first.code, message: first.message, ...(first.list === 'saved' || first.list === 'other' ? { list: first.list } : {}), transient: transient(first), at: now() };
179
+ log(`google contacts: ${acct.name}: ${rec.error.list ? `${rec.error.list} ` : ''}not read (${rec.error.code})`);
180
+ }
181
+ // kept only if nothing changed meanwhile: the same generation, and the account still allowed now
182
+ if (genOf(acct.name) !== gen || !stillAllowed(acct.name)) return null;
183
+ store.put(acct.name, rec);
184
+ letGo(before, rec);
185
+ indexes.clear();
186
+ return rec;
187
+ })();
188
+ running.set(acct.name, { gen, p });
189
+ p.finally(() => { if (running.get(acct.name)?.p === p) running.delete(acct.name); }).catch(() => {});
190
+ return p;
191
+ }
192
+
193
+ /**
194
+ * The accounts whose contacts are used: allowed, or not known now (the Keychain unreadable: what is kept stays).
195
+ * What is kept of any other one (gone from config.json, not signed in, contacts not allowed, expired) is let go.
196
+ */
197
+ function usable() {
198
+ const all = signedIn();
199
+ const ok = all.filter((a) => a.contacts || a.unknown);
200
+ for (const name of store.accounts()) if (!ok.some((a) => a.name === name)) dropAccount(name);
201
+ return ok;
202
+ }
203
+
204
+ /**
205
+ * Refresh what is due (in the background), then the contacts kept, merged:
206
+ * { people: [contact], list: [entry], byEmail: Map<lower email, entry>, cards: [saved contact, whole] }, a
207
+ * contact being { name, email (its first address), emails, kind: 'saved'|'other', photo?, company?, title?, account }
208
+ * and an entry the same under one of its addresses (`list`: one per address).
209
+ * An address belongs to one contact: a saved one before an other one, an
210
+ * account before the next. `account`: that account's alone (every account's
211
+ * without). `wait` (ms): when an account has nothing kept yet, how long to
212
+ * wait for its first reading.
213
+ */
214
+ async function contacts({ wait = 0, account } = {}) {
215
+ const ok = usable().filter((a) => !account || a.name === account);
216
+ const firsts = [];
217
+ for (const acct of ok) {
218
+ if (!acct.contacts) continue; // not known now: nothing to read it with
219
+ const rec = store.get(acct.name);
220
+ if (!stale(rec, acct)) continue;
221
+ const p = refreshOne(acct);
222
+ if (!rec || (rec.saved === null && rec.other === null)) firsts.push(p);
223
+ }
224
+ if (firsts.length && wait > 0) {
225
+ let timer;
226
+ await Promise.race([Promise.allSettled(firsts), new Promise((r) => { timer = setTimeout(r, wait); })]);
227
+ clearTimeout(timer);
228
+ }
229
+ return merged(ok, account || '*');
230
+ }
231
+
232
+ function merged(ok, key) {
233
+ const records = ok.map((a) => [a.name, store.get(a.name)]);
234
+ const index = indexes.get(key);
235
+ if (index && index.records.length === records.length && index.records.every(([n, r], i) => n === records[i][0] && r === records[i][1])) return index;
236
+ const byEmail = new Map();
237
+ const people = [];
238
+ for (const kind of ['saved', 'other']) {
239
+ for (const [account, rec] of records) {
240
+ for (const c of rec?.[kind] || []) {
241
+ const emails = (c.emails?.length ? c.emails : [c.email]).filter((e) => typeof e === 'string' && e.includes('@') && !byEmail.has(e.toLowerCase()));
242
+ if (!emails.length) continue; // every address of it is another contact's already (a saved one, or of an account before)
243
+ const one = { name: c.name || '', email: emails[0], emails, kind, account, ...(c.photo ? { photo: c.photo } : {}), ...(c.company ? { company: c.company } : {}), ...(c.title ? { title: c.title } : {}) };
244
+ people.push(one);
245
+ for (const e of emails) byEmail.set(e.toLowerCase(), { ...one, email: e });
246
+ }
247
+ }
248
+ }
249
+ // the saved contacts whole, those without an address too, each with its account and its groups by name
250
+ const cards = [];
251
+ for (const [account, rec] of records) {
252
+ for (const c of rec?.saved || []) {
253
+ const groups = (c.groups || []).map((g) => rec.groups?.[g]).filter(Boolean);
254
+ cards.push({ ...c, account, ...(groups.length ? { groups } : { groups: undefined }) });
255
+ }
256
+ }
257
+ const built = { records, byEmail, list: [...byEmail.values()], people, cards };
258
+ indexes.set(key, built);
259
+ return built;
260
+ }
261
+
262
+ /**
263
+ * Which accounts may be read is looked at again at the next use. With `account` (a sign-in, an account removed or
264
+ * added under that name): a read of it under way keeps nothing, and it is read again at its next use.
265
+ */
266
+ function invalidate(account) {
267
+ accessAt = -Infinity;
268
+ if (account) {
269
+ bump(account);
270
+ const rec = store.get(account);
271
+ if (rec) store.put(account, { ...rec, tried: 0 });
272
+ }
273
+ indexes.clear();
274
+ }
275
+
276
+ return { contacts, invalidate, refresh: refreshOne };
277
+ }
278
+
279
+ /**
280
+ * The accounts with a Google sign-in, from config.json and the Keychain (read only), as createGoogleContacts asks for
281
+ * them. `accessOf` is googleAccessKnown: a Keychain that could not be read gives { unknown: true }, not "signed out".
282
+ */
283
+ export function signedInAccounts(config, accessOf) {
284
+ return Object.values(config?.accounts || {})
285
+ .filter((a) => calendarProvider(a) === 'google')
286
+ .map((a) => {
287
+ const g = accessOf(a.name);
288
+ if (g.state === 'unknown') return { name: a.name, contacts: false, unknown: true, signedInAt: '' };
289
+ if (g.state === 'not-signed-in') return null;
290
+ return { name: a.name, contacts: !!g.contacts && g.state !== 'expired', signedInAt: g.signedInAt || '' };
291
+ })
292
+ .filter(Boolean);
293
+ }
294
+
295
+ // --- the instance Sideora uses ------------------------------------------------------
296
+
297
+ let instance = null;
298
+ /** The contacts over Sideora's own config, Keychain and cache (built on first use). */
299
+ export async function googleContacts() {
300
+ if (instance) return instance;
301
+ const [{ loadConfig }, core, { googleAccessKnown }, coreDb] = await Promise.all([import('./config.js'), import('./core.js'), import('./google-signin.js'), import('./core-db.js').then((m) => m.theCoreDb())]);
302
+ instance = createGoogleContacts({
303
+ accounts: () => signedInAccounts(loadConfig(), googleAccessKnown),
304
+ read: (account) => core.core.google.contacts(account),
305
+ store: contactsStore({ open: () => coreDb.open() }),
306
+ forgetPhotos: (urls) => { import('./pictures.js').then((m) => m.pictures()).then((p) => p.forgetContactPhotos(urls), () => {}); },
307
+ log: (m) => console.error(m)
308
+ });
309
+ return instance;
310
+ }
311
+
312
+ /** After a sign-in (an account) or an account removed (none): see invalidate. Nothing is built for it when nothing was asked yet. */
313
+ export function contactsChanged(account) {
314
+ if (instance) instance.invalidate(account);
315
+ }
@@ -0,0 +1,306 @@
1
+ // Google sign-in from the side panel, and what an account's Google sign-in
2
+ // allows (calendar, contacts) as the panel, `status` and `doctor` say it.
3
+ //
4
+ // The bridge runs the sign-in (mailcore's beginLogin: PKCE S256, a loopback
5
+ // server on 127.0.0.1 at a port of the system's choosing, the state checked,
6
+ // one answer, closed after it or after five minutes) and hands the panel only
7
+ // the consent page's address, which the panel opens in a tab. The panel names
8
+ // an account and nothing else: the OAuth client, the scopes and the redirect
9
+ // are this side's. It may start a sign-in only for an account that has a
10
+ // Google calendar, or for a Gmail mailbox that has no calendar yet and is
11
+ // getting one (`connect`): the calendar is added to it once Google allowed it.
12
+ // The tokens go to the Keychain (google:<account>) and never to the panel,
13
+ // which asks how the sign-in went (pending, done with what was allowed,
14
+ // failed, expired, cancelled).
15
+
16
+ import { GOOGLE_SCOPES, GOOGLE_CONTACTS_WRITE_SCOPES, contactsAllowed, grantedScopes, googleAccountAddress } from 'mailcore';
17
+ import { loadConfig, updateConfig, normalizeConfig, calendarProvider, keychainGet, keychainGetStrict, keychainDelete, KEYCHAIN_SERVICE } from './config.js';
18
+ import { contactsChanged } from './google-contacts.js';
19
+
20
+ /** What Sideora asks Google for: the calendar, and the contacts: read (People, suggestions, sender pictures) and added (the assistant's, at a press). */
21
+ export const SIGN_IN_SCOPES = [...GOOGLE_SCOPES, ...GOOGLE_CONTACTS_WRITE_SCOPES];
22
+ /** How long a sign-in started from the panel waits for Google. */
23
+ export const SIGN_IN_WINDOW_MS = 5 * 60e3;
24
+ /** How long an ended sign-in's outcome is kept for the panel to ask. */
25
+ const KEEP_MS = 10 * 60e3;
26
+ const EMAIL = /^[^\s@<>"]{1,64}@[^\s@<>"]{1,253}$/;
27
+ /** A scope by its short name: "calendar.events", "contacts.other.readonly". */
28
+ const short = (scope) => scope.replace('https://www.googleapis.com/auth/', '');
29
+
30
+ /**
31
+ * What stored Google tokens allow: { state, calendar, contacts, addContacts?, missing?, email?, signedInAt? }.
32
+ * The calendar counts only with every calendar scope (events, the calendar
33
+ * list, the calendars — which also say which account signed in — and
34
+ * free/busy); contacts (reading them) with the contacts, read only or not, and
35
+ * the other contacts; addContacts (true, else left out) with the contacts
36
+ * scope that is not read only (a sign-in from before asked for reading). `missing`: the scopes
37
+ * asked for and not granted (short names). state: 'signed-in' (both),
38
+ * 'calendar-only', 'no-calendar' (the calendar not fully allowed), 'expired'
39
+ * (Google refused to renew it), 'not-signed-in'. Tokens from before scopes
40
+ * were kept are the calendar's (what was asked for then). `email`: the Google
41
+ * address it signed in as, when it was read.
42
+ */
43
+ export function googleAccess(tokens) {
44
+ if (!tokens?.refresh_token) return { state: 'not-signed-in', calendar: false, contacts: false };
45
+ const scopes = grantedScopes(tokens);
46
+ const known = scopes.length > 0;
47
+ const has = (s) => scopes.includes(s);
48
+ const calendar = known ? GOOGLE_SCOPES.every(has) : true;
49
+ const allowed = contactsAllowed(scopes);
50
+ const contacts = known && allowed.read;
51
+ const missing = (known ? SIGN_IN_SCOPES.filter((s) => !has(s)) : GOOGLE_CONTACTS_WRITE_SCOPES).map(short);
52
+ const more = {
53
+ ...(allowed.write ? { addContacts: true } : {}),
54
+ ...(missing.length ? { missing } : {}),
55
+ ...(typeof tokens.email === 'string' && EMAIL.test(tokens.email) ? { email: tokens.email } : {}),
56
+ ...(typeof tokens.signed_in_at === 'string' ? { signedInAt: tokens.signed_in_at } : {})
57
+ };
58
+ if (tokens.refused_at) return { state: 'expired', calendar, contacts, ...more };
59
+ return { state: calendar ? (contacts ? 'signed-in' : 'calendar-only') : 'no-calendar', calendar, contacts, ...more };
60
+ }
61
+
62
+ /** An account's Google access, read from the Keychain (no secret leaves here). */
63
+ export function googleAccessOf(account) {
64
+ let tokens = null;
65
+ try { tokens = JSON.parse(keychainGet(`google:${account}`) || 'null'); } catch { tokens = null; }
66
+ return googleAccess(tokens);
67
+ }
68
+
69
+ /**
70
+ * An account's Google access, or { state: 'unknown' } when the Keychain could not be read (locked, access
71
+ * refused): not the same as not signed in. Tokens that do not parse are none.
72
+ */
73
+ export function googleAccessKnown(account) {
74
+ let raw;
75
+ try { raw = keychainGetStrict(`google:${account}`); } catch { return { state: 'unknown', calendar: false, contacts: false }; }
76
+ let tokens = null;
77
+ try { tokens = JSON.parse(raw || 'null'); } catch { tokens = null; }
78
+ return googleAccess(tokens);
79
+ }
80
+
81
+ /** What an account's Google access says, in a few words: "calendar, contacts", "calendar only", … */
82
+ export function accessWords(access) {
83
+ const not = access.missing?.length ? ` (not allowed: ${access.missing.join(', ')})` : '';
84
+ return {
85
+ 'signed-in': access.addContacts ? 'calendar, contacts' : 'calendar, contacts (read only: sign in again to add contacts)',
86
+ 'calendar-only': `calendar only${not}`,
87
+ 'no-calendar': `calendar not fully allowed${not}`,
88
+ expired: 'sign-in expired',
89
+ 'not-signed-in': 'not signed in'
90
+ }[access.state];
91
+ }
92
+
93
+ /** A Gmail (or Google Workspace) mailbox: IMAP at imap.gmail.com. */
94
+ export const isGmail = (a) => !!a && a.provider === 'imap' && String(a.imap?.host || '').toLowerCase() === 'imap.gmail.com';
95
+ /** A Gmail mailbox with no calendar: one the panel may connect to its Google calendar. */
96
+ export const canConnectGoogle = (a) => isGmail(a) && !calendarProvider(a);
97
+
98
+ // --- sign-ins started from the panel ------------------------------------------
99
+
100
+ /** account → { flow, startedAt, expiresAt, connect, result?, endedAt? } */
101
+ const flows = new Map();
102
+
103
+ const text = (v, max = 64) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
104
+
105
+ /** Why a sign-in failed, in the panel's words (never more than a line). */
106
+ function reasonOf(e) {
107
+ const m = String(e?.message || e || '').split('\n')[0];
108
+ if (/access_denied/.test(m)) return 'Google was not allowed to give access (the sign-in was declined).';
109
+ if (/refresh token/.test(m)) return m;
110
+ return m.replace(/^Google refused: /, 'Google said: ').slice(0, 300) || 'the sign-in did not complete';
111
+ }
112
+
113
+ /** The calendar block added to a Gmail mailbox (the config's lock held: called inside updateConfig). → added */
114
+ function addCalendarIn(raw, name) {
115
+ const a = raw.accounts[name];
116
+ const now = normalizeConfig({ accounts: { [name]: structuredClone(a) } }).accounts[name];
117
+ if (!canConnectGoogle(now)) return false;
118
+ a.calendar = { provider: 'google' };
119
+ return true;
120
+ }
121
+
122
+ const lower = (v) => String(v || '').trim().toLowerCase();
123
+ /** The address an account is known by here ('' for none): what its Google sign-in must be. */
124
+ export const addressOf = (a) => (EMAIL.test(String(a?.email || '').trim()) ? String(a.email).trim() : '');
125
+
126
+ /**
127
+ * Which Google account a sign-in is for, before its tokens are kept: the
128
+ * address of its primary calendar, which must be the account's own address
129
+ * (`expected`, any case) when it has one. → { email } (null when unknown and
130
+ * none expected), or why not (a string).
131
+ */
132
+ export async function identity(tokens, expected, { signal } = {}) {
133
+ const signedInAs = await googleAccountAddress(tokens.access_token, { signal });
134
+ if (expected) {
135
+ if (!signedInAs) return `Google did not say which account signed in (the calendar was not fully allowed). Sign in with ${expected} and tick all calendar permissions.`;
136
+ if (lower(signedInAs) !== lower(expected)) return `You signed in to Google as ${signedInAs}; this account is ${expected}. Sign in with ${expected}.`;
137
+ }
138
+ return { email: signedInAs };
139
+ }
140
+
141
+ /** The accept of a sign-in from the command line: the identity check alone; the Google address kept beside the tokens. */
142
+ export function acceptFor(expected) {
143
+ return async (tokens, ctx) => {
144
+ const who = await identity(tokens, expected, ctx);
145
+ return typeof who === 'string' ? who : who.email ? { email: who.email } : true;
146
+ };
147
+ }
148
+
149
+ /** Tokens a sign-in stored, taken back out, unless a newer sign-in has replaced them since. */
150
+ function dropIfOurs(name, tokens) {
151
+ try {
152
+ const now = JSON.parse(keychainGet(`google:${name}`) || 'null');
153
+ if (now?.refresh_token && now.refresh_token === tokens?.refresh_token) keychainDelete(KEYCHAIN_SERVICE, `google:${name}`);
154
+ } catch { /* nothing there, or the Keychain said no: the status says the account changed */ }
155
+ }
156
+
157
+ // Each start of a sign-in, and each add or removal of an account, takes the account's next generation: only the
158
+ // sign-in of the current one may keep anything (tokens, a calendar added, a restart). Removal or a new add also
159
+ // marks what came before as forgotten: tokens such a sign-in stored are taken out again.
160
+ let serial = 0;
161
+ const generation = new Map();
162
+ const forgotten = new Map();
163
+ const current = (name, gen) => generation.get(name) === gen;
164
+ const isForgotten = (name, gen) => gen <= (forgotten.get(name) ?? 0);
165
+
166
+ /** Stop an entry still waiting; true when it ended (false: its tokens are being stored, its outcome follows). */
167
+ function stop(entry) {
168
+ if (!entry || entry.result) return true;
169
+ const stopped = entry.flow ? entry.flow.cancel() !== false : true;
170
+ if (stopped) { entry.result = { state: 'cancelled' }; entry.endedAt = Date.now(); }
171
+ return stopped;
172
+ }
173
+
174
+ /**
175
+ * Start a sign-in for an account: one with a Google calendar, or (`connect`)
176
+ * a Gmail mailbox without a calendar, which gets one once Google allowed it.
177
+ * A sign-in of that account still waiting is ended first. The Google account
178
+ * signed in must be the account's own address (when it has one): another is
179
+ * refused before anything is kept.
180
+ * → { url, expiresAt }: the consent page for the panel to open.
181
+ * `opts` are this side's (tests): timeoutMs, begin(account, opts), restart().
182
+ */
183
+ export async function startSignIn({ account, connect } = {}, opts = {}) {
184
+ const name = text(account);
185
+ const accounts = loadConfig().accounts;
186
+ if (!name || !Object.hasOwn(accounts, name)) throw new Error(`there is no account named "${name}"`);
187
+ const a = accounts[name];
188
+ const joining = connect === true && canConnectGoogle(a);
189
+ if (calendarProvider(a) !== 'google' && !joining) {
190
+ throw new Error(isGmail(a) && calendarProvider(a) ? `${name} has a calendar of another kind: it is changed with the command line (sideora setup)` : `${name} has no Google calendar to sign in to`);
191
+ }
192
+ const timeoutMs = opts.timeoutMs ?? SIGN_IN_WINDOW_MS;
193
+ const begin = opts.begin ?? (async (acct, o) => (await import('./core.js')).core.google.beginLogin(acct, o));
194
+ const restart = opts.restart ?? (async () => (await import('./accounts.js')).restartDaemon());
195
+
196
+ // this one's generation, taken before anything is awaited: a start after it ends this one
197
+ const gen = ++serial;
198
+ generation.set(name, gen);
199
+ stop(flows.get(name));
200
+ const email = addressOf(a);
201
+ const startedAt = Date.now();
202
+ const entry = { gen, flow: null, startedAt, expiresAt: startedAt + timeoutMs, connect: joining, email: lower(email) };
203
+ flows.set(name, entry);
204
+ const end = (result) => { if (!entry.result) { entry.result = result; entry.endedAt = Date.now(); } };
205
+ /** The account as it was when this started: same name, same address. */
206
+ const unchanged = (acct) => !!acct && lower(addressOf(acct)) === entry.email;
207
+
208
+ // called by mailcore after the code exchange, before anything is stored
209
+ const accept = async (tokens, { signal }) => {
210
+ if (!current(name, gen)) return 'a newer sign-in of this account was started';
211
+ const who = await identity(tokens, email, { signal });
212
+ if (typeof who === 'string') return who;
213
+ const signedInAs = who.email;
214
+ let now = null;
215
+ try { now = loadConfig().accounts[name]; } catch { /* unreadable: as if changed */ }
216
+ if (!Object.hasOwn(loadConfig().accounts, name) || !unchanged(now)) return 'the account was removed or changed meanwhile';
217
+ if (!current(name, gen)) return 'a newer sign-in of this account was started';
218
+ return signedInAs ? { email: signedInAs } : true;
219
+ };
220
+
221
+ let flow;
222
+ try {
223
+ flow = await begin(name, { scopes: SIGN_IN_SCOPES, timeoutMs, appName: 'Sideora', accept, ...(email ? { loginHint: email } : {}) });
224
+ } catch (e) {
225
+ end({ state: 'failed', reason: reasonOf(e) });
226
+ throw e;
227
+ }
228
+ if (!current(name, gen) || entry.result) {
229
+ // a newer start, a cancel or the account's removal came meanwhile: this one's server is not left running
230
+ flow.cancel();
231
+ end({ state: 'cancelled' });
232
+ throw new Error('the sign-in was ended meanwhile (another was started, or the account changed)');
233
+ }
234
+ entry.flow = flow;
235
+ flow.done.then(async (tokens) => {
236
+ const access = googleAccess(tokens);
237
+ let gone = false;
238
+ let added = false;
239
+ try {
240
+ // under the config's lock: the account still the one this started for, and this sign-in still its current one
241
+ updateConfig((raw) => {
242
+ const has = raw.accounts && Object.hasOwn(raw.accounts, name) && raw.accounts[name] && typeof raw.accounts[name] === 'object';
243
+ if (!has || !unchanged(normalizeConfig({ accounts: { [name]: structuredClone(raw.accounts[name]) } }).accounts[name]) || isForgotten(name, gen)) { gone = true; return; }
244
+ if (current(name, gen) && joining && access.calendar) added = addCalendarIn(raw, name);
245
+ });
246
+ } catch (e) {
247
+ return end({ state: 'failed', reason: `signed in, but the calendar could not be added: ${reasonOf(e)}` });
248
+ }
249
+ if (gone) {
250
+ dropIfOurs(name, tokens);
251
+ return end({ state: 'failed', reason: 'the account was removed or changed meanwhile: nothing was kept' });
252
+ }
253
+ if (!current(name, gen)) return end({ state: 'cancelled' }); // a newer sign-in is the account's now
254
+ // its Google contacts are read again at their next use (what it allows may have changed)
255
+ contactsChanged(name);
256
+ // the daemon starts again: a calendar added is watched, one that was refused is asked again now
257
+ let restarted = false;
258
+ try { restarted = !!(await restart()); } catch { restarted = false; }
259
+ const { state: _access, ...allowed } = access;
260
+ end({ state: 'done', ...allowed, ...(joining ? { added } : {}), restarted });
261
+ }, (e) => {
262
+ end(e?.code === 'SIGN_IN_TIMEOUT' ? { state: 'expired' } : e?.code === 'SIGN_IN_CANCELLED' ? { state: 'cancelled' } : { state: 'failed', reason: reasonOf(e) });
263
+ });
264
+ return { url: flow.url, expiresAt: new Date(entry.expiresAt).toISOString() };
265
+ }
266
+
267
+ /**
268
+ * How the account's last sign-in from the panel went: { state: 'none' } (none
269
+ * started, or long ended), 'pending' (with expiresAt), 'done' (what was
270
+ * allowed: calendar, contacts, missing; email: the Google address; added: the
271
+ * calendar added to a Gmail mailbox; restarted), 'failed' (reason), 'expired'
272
+ * (five minutes passed), 'cancelled'.
273
+ */
274
+ export function signInStatus({ account } = {}) {
275
+ const name = text(account);
276
+ const entry = flows.get(name);
277
+ if (!entry) return { state: 'none' };
278
+ if (entry.result) {
279
+ if (Date.now() - entry.endedAt > KEEP_MS) { flows.delete(name); return { state: 'none' }; }
280
+ return entry.result;
281
+ }
282
+ return { state: 'pending', expiresAt: new Date(entry.expiresAt).toISOString() };
283
+ }
284
+
285
+ /**
286
+ * End the account's sign-in still waiting (its port closes); what was signed
287
+ * in before stays. Once its tokens are being stored it can no longer be
288
+ * stopped: it stays pending and its outcome follows.
289
+ */
290
+ export function cancelSignIn({ account } = {}) {
291
+ const name = text(account);
292
+ const entry = flows.get(name);
293
+ if (entry && !entry.result && !entry.flow) generation.set(name, ++serial); // still starting: its flow is ended when it comes
294
+ stop(entry);
295
+ return signInStatus({ account: name });
296
+ }
297
+
298
+ /** An account removed, or added under a name: a sign-in of that name under way ends, and keeps nothing it stores late. */
299
+ export function forgetSignIn(account) {
300
+ const name = text(account);
301
+ const gen = ++serial;
302
+ generation.set(name, gen);
303
+ forgotten.set(name, gen);
304
+ stop(flows.get(name));
305
+ contactsChanged(name); // which accounts may be read is looked at again, and a read of its contacts under way keeps nothing
306
+ }
@@ -0,0 +1,44 @@
1
+ // HTML for the assistant (src/core/assistant.js), read with htmlparser2 (a dependency already, through html-to-text):
2
+ // a draft's body made of what a draft may hold and nothing else, and a note's words.
3
+
4
+ import { parseDocument } from 'htmlparser2';
5
+
6
+ const DRAFT_TAGS = new Set(['p', 'br', 'ul', 'ol', 'li', 'strong', 'b', 'em', 'i', 'a', 'blockquote']);
7
+ const DROPPED = new Set(['script', 'style', 'iframe', 'object', 'embed', 'svg', 'img', 'video', 'audio', 'link', 'meta', 'head', 'title', 'template', 'noscript']);
8
+ const esc = (t) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
9
+
10
+ /**
11
+ * The body of a mail as the model wrote it, made of what a draft may hold and nothing else: paragraphs, lists,
12
+ * bold, italic, quotes, and links to http(s) and mailto addresses. No picture, nothing that loads from elsewhere
13
+ * (opening the draft would fetch it, and say what its address says), no style, no script: their text stays.
14
+ */
15
+ export function draftHtml(html) {
16
+ const walk = (node) => {
17
+ if (node.type === 'text') return esc(node.data ?? '');
18
+ if (node.type !== 'tag' && node.type !== 'script' && node.type !== 'style') return '';
19
+ const tag = String(node.name).toLowerCase();
20
+ if (DROPPED.has(tag) || node.type !== 'tag') return '';
21
+ const inner = (node.children ?? []).map(walk).join('');
22
+ if (!DRAFT_TAGS.has(tag)) return /^(div|h[1-6]|tr|table|section|article)$/.test(tag) && inner.trim() ? `<p>${inner}</p>` : inner;
23
+ if (tag === 'br') return '<br>';
24
+ if (tag === 'a') {
25
+ const href = node.attribs?.href ?? '';
26
+ return /^(https?:\/\/|mailto:)/i.test(href.trim()) ? `<a href="${esc(href.trim()).replace(/"/g, '&quot;')}">${inner}</a>` : inner;
27
+ }
28
+ const name = tag === 'b' ? 'strong' : tag === 'i' ? 'em' : tag;
29
+ return `<${name}>${inner}</${name}>`;
30
+ };
31
+ return (parseDocument(String(html ?? '')).children ?? []).map(walk).join('').trim();
32
+ }
33
+
34
+ const BLOCK = new Set(['p', 'li', 'h1', 'h2', 'h3', 'h4', 'tr', 'br', 'blockquote', 'div']);
35
+ /** The words of some HTML (a note), a line for each paragraph, item or row. */
36
+ export function htmlText(html) {
37
+ const walk = (node) => {
38
+ if (node.type === 'text') return node.data ?? '';
39
+ if (node.type !== 'tag') return '';
40
+ const inner = (node.children ?? []).map(walk).join('');
41
+ return BLOCK.has(String(node.name).toLowerCase()) ? `${inner}\n` : inner;
42
+ };
43
+ return (parseDocument(String(html ?? '')).children ?? []).map(walk).join('').replace(/\n{3,}/g, '\n\n').trim();
44
+ }