@bobfrankston/rmfmail 1.0.467

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 (330) hide show
  1. package/README.md +429 -0
  2. package/bin/build-icon-ico.js +283 -0
  3. package/bin/lean-accounts.js +172 -0
  4. package/bin/mailx.js +1580 -0
  5. package/bin/mailx.js.map +1 -0
  6. package/bin/mailx.ts +1549 -0
  7. package/bin/postinstall.js +39 -0
  8. package/bin/postinstall.js.map +1 -0
  9. package/bin/postinstall.ts +41 -0
  10. package/bin/tsconfig.json +10 -0
  11. package/client/.gitattributes +10 -0
  12. package/client/.msger-window.json +1 -0
  13. package/client/android.html +226 -0
  14. package/client/app.js +3400 -0
  15. package/client/app.js.map +1 -0
  16. package/client/app.ts +3190 -0
  17. package/client/components/address-book.js +199 -0
  18. package/client/components/address-book.js.map +1 -0
  19. package/client/components/address-book.ts +204 -0
  20. package/client/components/alarms.js +299 -0
  21. package/client/components/alarms.js.map +1 -0
  22. package/client/components/alarms.ts +276 -0
  23. package/client/components/calendar-sidebar.js +508 -0
  24. package/client/components/calendar-sidebar.js.map +1 -0
  25. package/client/components/calendar-sidebar.ts +474 -0
  26. package/client/components/calendar.js +217 -0
  27. package/client/components/calendar.js.map +1 -0
  28. package/client/components/calendar.ts +211 -0
  29. package/client/components/context-menu.js +80 -0
  30. package/client/components/context-menu.js.map +1 -0
  31. package/client/components/context-menu.ts +95 -0
  32. package/client/components/folder-picker.js +119 -0
  33. package/client/components/folder-picker.js.map +1 -0
  34. package/client/components/folder-picker.ts +127 -0
  35. package/client/components/folder-tree.js +1093 -0
  36. package/client/components/folder-tree.js.map +1 -0
  37. package/client/components/folder-tree.ts +1069 -0
  38. package/client/components/message-list.js +1140 -0
  39. package/client/components/message-list.js.map +1 -0
  40. package/client/components/message-list.ts +1129 -0
  41. package/client/components/message-viewer.js +1291 -0
  42. package/client/components/message-viewer.js.map +1 -0
  43. package/client/components/message-viewer.ts +1257 -0
  44. package/client/components/outbox-view.js +104 -0
  45. package/client/components/outbox-view.js.map +1 -0
  46. package/client/components/outbox-view.ts +102 -0
  47. package/client/components/tasks.js +261 -0
  48. package/client/components/tasks.js.map +1 -0
  49. package/client/components/tasks.ts +234 -0
  50. package/client/compose/compose.css +560 -0
  51. package/client/compose/compose.html +52 -0
  52. package/client/compose/compose.js +1289 -0
  53. package/client/compose/compose.js.map +1 -0
  54. package/client/compose/compose.ts +1231 -0
  55. package/client/compose/editor.js +616 -0
  56. package/client/compose/editor.js.map +1 -0
  57. package/client/compose/editor.ts +599 -0
  58. package/client/compose/ghost-text.js +122 -0
  59. package/client/compose/ghost-text.js.map +1 -0
  60. package/client/compose/ghost-text.ts +140 -0
  61. package/client/favicon.svg +11 -0
  62. package/client/icon.ico +0 -0
  63. package/client/icon.png +0 -0
  64. package/client/index.html +230 -0
  65. package/client/lib/android-bootstrap.js +9 -0
  66. package/client/lib/android-bootstrap.js.map +1 -0
  67. package/client/lib/android-bootstrap.ts +9 -0
  68. package/client/lib/api-client.js +378 -0
  69. package/client/lib/api-client.js.map +1 -0
  70. package/client/lib/api-client.ts +439 -0
  71. package/client/lib/local-service.js +603 -0
  72. package/client/lib/local-service.js.map +1 -0
  73. package/client/lib/local-service.ts +646 -0
  74. package/client/lib/local-store.js +214 -0
  75. package/client/lib/local-store.js.map +1 -0
  76. package/client/lib/local-store.ts +283 -0
  77. package/client/lib/mailxapi.js +304 -0
  78. package/client/lib/message-state.js +132 -0
  79. package/client/lib/message-state.js.map +1 -0
  80. package/client/lib/message-state.ts +160 -0
  81. package/client/package.json +16 -0
  82. package/client/styles/components.css +2049 -0
  83. package/client/styles/layout.css +332 -0
  84. package/client/styles/variables.css +85 -0
  85. package/client/tsconfig.json +19 -0
  86. package/package.json +124 -0
  87. package/packages/mailx-api/.gitattributes +10 -0
  88. package/packages/mailx-api/index.d.ts +10 -0
  89. package/packages/mailx-api/index.d.ts.map +1 -0
  90. package/packages/mailx-api/index.js +322 -0
  91. package/packages/mailx-api/index.js.map +1 -0
  92. package/packages/mailx-api/index.ts +283 -0
  93. package/packages/mailx-api/package.json +27 -0
  94. package/packages/mailx-api/tsconfig.json +9 -0
  95. package/packages/mailx-api/tsconfig.tsbuildinfo +1 -0
  96. package/packages/mailx-compose/.gitattributes +10 -0
  97. package/packages/mailx-compose/index.d.ts +21 -0
  98. package/packages/mailx-compose/index.d.ts.map +1 -0
  99. package/packages/mailx-compose/index.js +61 -0
  100. package/packages/mailx-compose/index.js.map +1 -0
  101. package/packages/mailx-compose/index.ts +85 -0
  102. package/packages/mailx-compose/package.json +18 -0
  103. package/packages/mailx-compose/tsconfig.json +9 -0
  104. package/packages/mailx-core/index.d.ts +139 -0
  105. package/packages/mailx-core/index.d.ts.map +1 -0
  106. package/packages/mailx-core/index.js +403 -0
  107. package/packages/mailx-core/index.js.map +1 -0
  108. package/packages/mailx-core/index.ts +424 -0
  109. package/packages/mailx-core/ipc.d.ts +13 -0
  110. package/packages/mailx-core/ipc.d.ts.map +1 -0
  111. package/packages/mailx-core/ipc.js +56 -0
  112. package/packages/mailx-core/ipc.js.map +1 -0
  113. package/packages/mailx-core/ipc.ts +62 -0
  114. package/packages/mailx-core/package.json +18 -0
  115. package/packages/mailx-core/tsconfig.json +9 -0
  116. package/packages/mailx-host/.gitattributes +10 -0
  117. package/packages/mailx-host/index.d.ts +21 -0
  118. package/packages/mailx-host/index.d.ts.map +1 -0
  119. package/packages/mailx-host/index.js +29 -0
  120. package/packages/mailx-host/index.js.map +1 -0
  121. package/packages/mailx-host/index.ts +38 -0
  122. package/packages/mailx-host/package.json +23 -0
  123. package/packages/mailx-host/tsconfig.json +9 -0
  124. package/packages/mailx-host/types-shim.d.ts +14 -0
  125. package/packages/mailx-imap/.gitattributes +10 -0
  126. package/packages/mailx-imap/index.d.ts +442 -0
  127. package/packages/mailx-imap/index.d.ts.map +1 -0
  128. package/packages/mailx-imap/index.js +3684 -0
  129. package/packages/mailx-imap/index.js.map +1 -0
  130. package/packages/mailx-imap/index.ts +3652 -0
  131. package/packages/mailx-imap/package-lock.json +131 -0
  132. package/packages/mailx-imap/package.json +28 -0
  133. package/packages/mailx-imap/providers/gmail-api.d.ts +8 -0
  134. package/packages/mailx-imap/providers/gmail-api.d.ts.map +1 -0
  135. package/packages/mailx-imap/providers/gmail-api.js +8 -0
  136. package/packages/mailx-imap/providers/gmail-api.js.map +1 -0
  137. package/packages/mailx-imap/providers/gmail-api.ts +8 -0
  138. package/packages/mailx-imap/providers/outlook-api.ts +7 -0
  139. package/packages/mailx-imap/providers/types.d.ts +9 -0
  140. package/packages/mailx-imap/providers/types.d.ts.map +1 -0
  141. package/packages/mailx-imap/providers/types.js +9 -0
  142. package/packages/mailx-imap/providers/types.js.map +1 -0
  143. package/packages/mailx-imap/providers/types.ts +9 -0
  144. package/packages/mailx-imap/tsconfig.json +9 -0
  145. package/packages/mailx-imap/tsconfig.tsbuildinfo +1 -0
  146. package/packages/mailx-send/.gitattributes +10 -0
  147. package/packages/mailx-send/README.md +217 -0
  148. package/packages/mailx-send/cli-queue.d.ts +11 -0
  149. package/packages/mailx-send/cli-queue.d.ts.map +1 -0
  150. package/packages/mailx-send/cli-queue.js +59 -0
  151. package/packages/mailx-send/cli-queue.js.map +1 -0
  152. package/packages/mailx-send/cli-queue.ts +62 -0
  153. package/packages/mailx-send/cli-send.d.ts +17 -0
  154. package/packages/mailx-send/cli-send.d.ts.map +1 -0
  155. package/packages/mailx-send/cli-send.js +75 -0
  156. package/packages/mailx-send/cli-send.js.map +1 -0
  157. package/packages/mailx-send/cli-send.ts +83 -0
  158. package/packages/mailx-send/cli.d.ts +22 -0
  159. package/packages/mailx-send/cli.d.ts.map +1 -0
  160. package/packages/mailx-send/cli.js +115 -0
  161. package/packages/mailx-send/cli.js.map +1 -0
  162. package/packages/mailx-send/cli.ts +126 -0
  163. package/packages/mailx-send/index.d.ts +77 -0
  164. package/packages/mailx-send/index.d.ts.map +1 -0
  165. package/packages/mailx-send/index.js +264 -0
  166. package/packages/mailx-send/index.js.map +1 -0
  167. package/packages/mailx-send/index.ts +333 -0
  168. package/packages/mailx-send/mailsend/README.md +133 -0
  169. package/packages/mailx-send/mailsend/cli.d.ts +12 -0
  170. package/packages/mailx-send/mailsend/cli.d.ts.map +1 -0
  171. package/packages/mailx-send/mailsend/cli.js +70 -0
  172. package/packages/mailx-send/mailsend/cli.js.map +1 -0
  173. package/packages/mailx-send/mailsend/cli.ts +81 -0
  174. package/packages/mailx-send/mailsend/index.d.ts +77 -0
  175. package/packages/mailx-send/mailsend/index.d.ts.map +1 -0
  176. package/packages/mailx-send/mailsend/index.js +264 -0
  177. package/packages/mailx-send/mailsend/index.js.map +1 -0
  178. package/packages/mailx-send/mailsend/index.ts +333 -0
  179. package/packages/mailx-send/mailsend/package-lock.json +65 -0
  180. package/packages/mailx-send/mailsend/package.json +26 -0
  181. package/packages/mailx-send/mailsend/tsconfig.json +21 -0
  182. package/packages/mailx-send/package-lock.json +65 -0
  183. package/packages/mailx-send/package.json +37 -0
  184. package/packages/mailx-send/tsconfig.json +21 -0
  185. package/packages/mailx-server/.gitattributes +10 -0
  186. package/packages/mailx-server/index.d.ts +8 -0
  187. package/packages/mailx-server/index.d.ts.map +1 -0
  188. package/packages/mailx-server/index.js +397 -0
  189. package/packages/mailx-server/index.js.map +1 -0
  190. package/packages/mailx-server/index.ts +429 -0
  191. package/packages/mailx-server/package.json +28 -0
  192. package/packages/mailx-server/tsconfig.json +9 -0
  193. package/packages/mailx-server/tsconfig.tsbuildinfo +1 -0
  194. package/packages/mailx-service/google-sync.d.ts +96 -0
  195. package/packages/mailx-service/google-sync.d.ts.map +1 -0
  196. package/packages/mailx-service/google-sync.js +153 -0
  197. package/packages/mailx-service/google-sync.js.map +1 -0
  198. package/packages/mailx-service/google-sync.ts +238 -0
  199. package/packages/mailx-service/index.d.ts +366 -0
  200. package/packages/mailx-service/index.d.ts.map +1 -0
  201. package/packages/mailx-service/index.js +2589 -0
  202. package/packages/mailx-service/index.js.map +1 -0
  203. package/packages/mailx-service/index.ts +2512 -0
  204. package/packages/mailx-service/jsonrpc.d.ts +25 -0
  205. package/packages/mailx-service/jsonrpc.d.ts.map +1 -0
  206. package/packages/mailx-service/jsonrpc.js +238 -0
  207. package/packages/mailx-service/jsonrpc.js.map +1 -0
  208. package/packages/mailx-service/jsonrpc.ts +268 -0
  209. package/packages/mailx-service/package.json +22 -0
  210. package/packages/mailx-service/tsconfig.json +9 -0
  211. package/packages/mailx-settings/.gitattributes +10 -0
  212. package/packages/mailx-settings/cloud.d.ts +47 -0
  213. package/packages/mailx-settings/cloud.d.ts.map +1 -0
  214. package/packages/mailx-settings/cloud.js +408 -0
  215. package/packages/mailx-settings/cloud.js.map +1 -0
  216. package/packages/mailx-settings/cloud.ts +393 -0
  217. package/packages/mailx-settings/index.d.ts +140 -0
  218. package/packages/mailx-settings/index.d.ts.map +1 -0
  219. package/packages/mailx-settings/index.js +872 -0
  220. package/packages/mailx-settings/index.js.map +1 -0
  221. package/packages/mailx-settings/index.ts +908 -0
  222. package/packages/mailx-settings/package.json +20 -0
  223. package/packages/mailx-settings/tsconfig.json +9 -0
  224. package/packages/mailx-settings/tsconfig.tsbuildinfo +1 -0
  225. package/packages/mailx-store/.gitattributes +10 -0
  226. package/packages/mailx-store/db.d.ts +346 -0
  227. package/packages/mailx-store/db.d.ts.map +1 -0
  228. package/packages/mailx-store/db.js +1796 -0
  229. package/packages/mailx-store/db.js.map +1 -0
  230. package/packages/mailx-store/db.ts +2007 -0
  231. package/packages/mailx-store/file-store.d.ts +36 -0
  232. package/packages/mailx-store/file-store.d.ts.map +1 -0
  233. package/packages/mailx-store/file-store.js +80 -0
  234. package/packages/mailx-store/file-store.js.map +1 -0
  235. package/packages/mailx-store/file-store.ts +82 -0
  236. package/packages/mailx-store/index.d.ts +7 -0
  237. package/packages/mailx-store/index.d.ts.map +1 -0
  238. package/packages/mailx-store/index.js +7 -0
  239. package/packages/mailx-store/index.js.map +1 -0
  240. package/packages/mailx-store/index.ts +7 -0
  241. package/packages/mailx-store/package.json +19 -0
  242. package/packages/mailx-store/tsconfig.json +9 -0
  243. package/packages/mailx-store/tsconfig.tsbuildinfo +1 -0
  244. package/packages/mailx-store-web/android-bootstrap.d.ts +16 -0
  245. package/packages/mailx-store-web/android-bootstrap.d.ts.map +1 -0
  246. package/packages/mailx-store-web/android-bootstrap.js +1247 -0
  247. package/packages/mailx-store-web/android-bootstrap.js.map +1 -0
  248. package/packages/mailx-store-web/android-bootstrap.ts +1262 -0
  249. package/packages/mailx-store-web/db.d.ts +132 -0
  250. package/packages/mailx-store-web/db.d.ts.map +1 -0
  251. package/packages/mailx-store-web/db.js +642 -0
  252. package/packages/mailx-store-web/db.js.map +1 -0
  253. package/packages/mailx-store-web/db.ts +756 -0
  254. package/packages/mailx-store-web/gmail-api-web.d.ts +11 -0
  255. package/packages/mailx-store-web/gmail-api-web.d.ts.map +1 -0
  256. package/packages/mailx-store-web/gmail-api-web.js +11 -0
  257. package/packages/mailx-store-web/gmail-api-web.js.map +1 -0
  258. package/packages/mailx-store-web/gmail-api-web.ts +11 -0
  259. package/packages/mailx-store-web/imap-web-provider.d.ts +33 -0
  260. package/packages/mailx-store-web/imap-web-provider.d.ts.map +1 -0
  261. package/packages/mailx-store-web/imap-web-provider.js +140 -0
  262. package/packages/mailx-store-web/imap-web-provider.js.map +1 -0
  263. package/packages/mailx-store-web/imap-web-provider.ts +156 -0
  264. package/packages/mailx-store-web/index.d.ts +10 -0
  265. package/packages/mailx-store-web/index.d.ts.map +1 -0
  266. package/packages/mailx-store-web/index.js +10 -0
  267. package/packages/mailx-store-web/index.js.map +1 -0
  268. package/packages/mailx-store-web/index.ts +10 -0
  269. package/packages/mailx-store-web/main-thread-host.d.ts +15 -0
  270. package/packages/mailx-store-web/main-thread-host.d.ts.map +1 -0
  271. package/packages/mailx-store-web/main-thread-host.js +292 -0
  272. package/packages/mailx-store-web/main-thread-host.js.map +1 -0
  273. package/packages/mailx-store-web/main-thread-host.ts +322 -0
  274. package/packages/mailx-store-web/package.json +23 -0
  275. package/packages/mailx-store-web/provider-types.d.ts +7 -0
  276. package/packages/mailx-store-web/provider-types.d.ts.map +1 -0
  277. package/packages/mailx-store-web/provider-types.js +7 -0
  278. package/packages/mailx-store-web/provider-types.js.map +1 -0
  279. package/packages/mailx-store-web/provider-types.ts +7 -0
  280. package/packages/mailx-store-web/sql-wasm-esm.js +10 -0
  281. package/packages/mailx-store-web/sql.js.d.ts +29 -0
  282. package/packages/mailx-store-web/sync-manager.d.ts +68 -0
  283. package/packages/mailx-store-web/sync-manager.d.ts.map +1 -0
  284. package/packages/mailx-store-web/sync-manager.js +506 -0
  285. package/packages/mailx-store-web/sync-manager.js.map +1 -0
  286. package/packages/mailx-store-web/sync-manager.ts +508 -0
  287. package/packages/mailx-store-web/tsconfig.json +10 -0
  288. package/packages/mailx-store-web/web-jsonrpc.d.ts +20 -0
  289. package/packages/mailx-store-web/web-jsonrpc.d.ts.map +1 -0
  290. package/packages/mailx-store-web/web-jsonrpc.js +102 -0
  291. package/packages/mailx-store-web/web-jsonrpc.js.map +1 -0
  292. package/packages/mailx-store-web/web-jsonrpc.ts +116 -0
  293. package/packages/mailx-store-web/web-message-store.d.ts +16 -0
  294. package/packages/mailx-store-web/web-message-store.d.ts.map +1 -0
  295. package/packages/mailx-store-web/web-message-store.js +89 -0
  296. package/packages/mailx-store-web/web-message-store.js.map +1 -0
  297. package/packages/mailx-store-web/web-message-store.ts +97 -0
  298. package/packages/mailx-store-web/web-service.d.ts +111 -0
  299. package/packages/mailx-store-web/web-service.d.ts.map +1 -0
  300. package/packages/mailx-store-web/web-service.js +542 -0
  301. package/packages/mailx-store-web/web-service.js.map +1 -0
  302. package/packages/mailx-store-web/web-service.ts +616 -0
  303. package/packages/mailx-store-web/web-settings.d.ts +83 -0
  304. package/packages/mailx-store-web/web-settings.d.ts.map +1 -0
  305. package/packages/mailx-store-web/web-settings.js +491 -0
  306. package/packages/mailx-store-web/web-settings.js.map +1 -0
  307. package/packages/mailx-store-web/web-settings.ts +522 -0
  308. package/packages/mailx-store-web/worker-bundle.js +6838 -0
  309. package/packages/mailx-store-web/worker-entry.d.ts +8 -0
  310. package/packages/mailx-store-web/worker-entry.d.ts.map +1 -0
  311. package/packages/mailx-store-web/worker-entry.js +187 -0
  312. package/packages/mailx-store-web/worker-entry.js.map +1 -0
  313. package/packages/mailx-store-web/worker-entry.ts +215 -0
  314. package/packages/mailx-store-web/worker-tcp-transport.d.ts +28 -0
  315. package/packages/mailx-store-web/worker-tcp-transport.d.ts.map +1 -0
  316. package/packages/mailx-store-web/worker-tcp-transport.js +98 -0
  317. package/packages/mailx-store-web/worker-tcp-transport.js.map +1 -0
  318. package/packages/mailx-store-web/worker-tcp-transport.ts +101 -0
  319. package/packages/mailx-types/.gitattributes +10 -0
  320. package/packages/mailx-types/index.d.ts +319 -0
  321. package/packages/mailx-types/index.d.ts.map +1 -0
  322. package/packages/mailx-types/index.js +243 -0
  323. package/packages/mailx-types/index.js.map +1 -0
  324. package/packages/mailx-types/index.ts +498 -0
  325. package/packages/mailx-types/package.json +16 -0
  326. package/packages/mailx-types/tsconfig.json +9 -0
  327. package/packages/mailx-types/tsconfig.tsbuildinfo +1 -0
  328. package/todo.json +13 -0
  329. package/tsconfig.base.json +31 -0
  330. package/tsconfig.json +9 -0
@@ -0,0 +1,908 @@
1
+ /**
2
+ * @bobfrankston/mailx-settings
3
+ * Settings management with shared/local split.
4
+ *
5
+ * Files (shared — on OneDrive or similar):
6
+ * accounts.jsonc — IMAP/SMTP account configs
7
+ * preferences.jsonc — UI, sync, font settings
8
+ * allowlist.jsonc — remote content allow-list
9
+ *
10
+ * Local overrides (~/.mailx/):
11
+ * config.jsonc — pointer to shared dir + local-only settings (storePath, historyDays)
12
+ * accounts.jsonc — cached copy, fallback when shared unavailable
13
+ * preferences.jsonc — local overrides merged on top of shared
14
+ * allowlist.jsonc — cached copy
15
+ *
16
+ * The old settings.jsonc is still supported for backward compatibility.
17
+ */
18
+
19
+ import * as fs from "node:fs";
20
+ import * as path from "node:path";
21
+ import { parse as parseJsonc } from "jsonc-parser";
22
+ import type { MailxSettings, AccountConfig, AutocompleteSettings } from "@bobfrankston/mailx-types";
23
+ import { getCloudProvider, gDriveFindOrCreateFolder, type CloudProvider } from "./cloud.js";
24
+
25
+ // ── Paths ──
26
+
27
+ // REMOVE 2026-05-15 — one-shot migration of legacy ~/.mailx → ~/.rmfmail.
28
+ // Runs at module load before any consumer touches LOCAL_DIR. Idempotent
29
+ // (no-op if newDir already exists or oldDir is missing). The cloud-side
30
+ // rename (the "mailx" folder on Google Drive) is handled separately by
31
+ // the user via the Drive web UI — folderId in config.jsonc still resolves
32
+ // regardless of the display name, so this is cosmetic rather than load-
33
+ // bearing for cloud auth.
34
+ {
35
+ const home = process.env.USERPROFILE || process.env.HOME || ".";
36
+ const oldDir = path.join(home, ".mailx");
37
+ const newDir = path.join(home, ".rmfmail");
38
+ if (!fs.existsSync(newDir) && fs.existsSync(oldDir)) {
39
+ try { fs.renameSync(oldDir, newDir); console.log("[migrate] ~/.mailx → ~/.rmfmail"); }
40
+ catch (e: any) { console.error(`[migrate] rename failed: ${e?.message || e}`); }
41
+ }
42
+ }
43
+ const LOCAL_DIR = path.join(process.env.USERPROFILE || process.env.HOME || ".", ".rmfmail");
44
+ const LOCAL_CONFIG_PATH = path.join(LOCAL_DIR, "config.jsonc");
45
+ const LEGACY_CONFIG_PATH = path.join(LOCAL_DIR, "config.json");
46
+ const DEFAULT_STORE_PATH = path.join(LOCAL_DIR, "mailxstore");
47
+
48
+ interface SharedDirConfig {
49
+ provider: "gdrive" | "google" | "local";
50
+ path: string;
51
+ /** Google Drive folder ID — cached locally, avoids name-based search */
52
+ folderId?: string;
53
+ }
54
+
55
+ interface AccountOverride {
56
+ enabled?: boolean;
57
+ historyDays?: number;
58
+ }
59
+
60
+ interface LocalConfig {
61
+ /** Directory containing shared settings — string, { provider, path }, or array to try in order */
62
+ sharedDir?: string | SharedDirConfig | (string | SharedDirConfig)[];
63
+ /** Legacy: single settings file path */
64
+ settingsPath?: string;
65
+ /** Local message store path */
66
+ storePath?: string;
67
+ /** Per-machine: days of history to sync (overrides shared) */
68
+ historyDays?: number;
69
+ /** Per-account overrides on this machine (enabled, historyDays) */
70
+ accountOverrides?: Record<string, AccountOverride>;
71
+ }
72
+
73
+ /** Resolve a path from config — relative to ~/.mailx/, ~ expands to home */
74
+ function resolvePath(p: string): string {
75
+ if (!p) return p;
76
+ const home = process.env.USERPROFILE || process.env.HOME || ".";
77
+ // Expand ~ to home directory
78
+ if (p.startsWith("~/") || p.startsWith("~\\")) return path.join(home, p.slice(2));
79
+ if (p === "~") return home;
80
+ // Absolute path — use as-is
81
+ if (path.isAbsolute(p)) return p;
82
+ // Relative — resolve from config directory (~/.mailx/)
83
+ return path.resolve(LOCAL_DIR, p);
84
+ }
85
+
86
+ function readLocalConfig(): LocalConfig {
87
+ // Migrate config.json → config.jsonc
88
+ if (!fs.existsSync(LOCAL_CONFIG_PATH) && fs.existsSync(LEGACY_CONFIG_PATH)) {
89
+ fs.renameSync(LEGACY_CONFIG_PATH, LOCAL_CONFIG_PATH);
90
+ }
91
+ if (!fs.existsSync(LOCAL_CONFIG_PATH)) return {};
92
+ return readJsonc(LOCAL_CONFIG_PATH) || {};
93
+ }
94
+
95
+ /** Resolve provider config to a filesystem path (checks for local Google Drive mount) */
96
+ function resolveProvider(cfg: SharedDirConfig): string | undefined {
97
+ // Cloud providers use API only — no filesystem mount scanning
98
+ if (cfg.provider === "gdrive" || cfg.provider === "google") return undefined;
99
+ if (cfg.provider === "local") return resolvePath(cfg.path);
100
+ return undefined;
101
+ }
102
+
103
+ /** Pending cloud config for API fallback (set when mount not found) */
104
+ let pendingCloudConfig: SharedDirConfig | null = null;
105
+ /** Last cloud API error (for UI display) */
106
+ let lastCloudError: string | null = null;
107
+
108
+ /** Subscribers notified whenever lastCloudError changes (push to UI immediately). */
109
+ type CloudErrorListener = (error: string | null, context?: { op: "read" | "write"; filename: string }) => void;
110
+ const cloudErrorListeners: CloudErrorListener[] = [];
111
+ export function onCloudError(cb: CloudErrorListener): () => void {
112
+ cloudErrorListeners.push(cb);
113
+ return () => {
114
+ const i = cloudErrorListeners.indexOf(cb);
115
+ if (i >= 0) cloudErrorListeners.splice(i, 1);
116
+ };
117
+ }
118
+ function setCloudError(error: string | null, context?: { op: "read" | "write"; filename: string }): void {
119
+ lastCloudError = error;
120
+ for (const cb of cloudErrorListeners) {
121
+ try { cb(error, context); } catch { /* listener faults shouldn't break writes */ }
122
+ }
123
+ }
124
+ export function getLastCloudError(): string | null { return lastCloudError; }
125
+
126
+ function resolveSharedEntry(entry: string | SharedDirConfig): string | undefined {
127
+ if (typeof entry === "string") {
128
+ const p = resolvePath(entry);
129
+ return fs.existsSync(p) ? p : undefined;
130
+ }
131
+ return resolveProvider(entry);
132
+ }
133
+
134
+ function getSharedDir(): string {
135
+ const config = readLocalConfig();
136
+ if (config.sharedDir) {
137
+ const entries = Array.isArray(config.sharedDir) ? config.sharedDir : [config.sharedDir];
138
+ for (const entry of entries) {
139
+ const resolved = resolveSharedEntry(entry);
140
+ if (resolved) return resolved;
141
+ }
142
+ // Set pending cloud config for API access
143
+ if (!pendingCloudConfig) {
144
+ const lastProvider = [...entries].reverse().find(e => typeof e !== "string") as SharedDirConfig | undefined;
145
+ if (lastProvider) pendingCloudConfig = lastProvider;
146
+ }
147
+ }
148
+ // Legacy settingsPath no longer used for shared dir — use loadLegacySettings() for reading only.
149
+ return LOCAL_DIR;
150
+ }
151
+
152
+ /** Read a file via cloud API (when filesystem mount not available) */
153
+ export async function cloudRead(filename: string): Promise<string | null> {
154
+ if (!pendingCloudConfig) return null;
155
+ // Ensure we have a folder ID
156
+ if (!pendingCloudConfig.folderId) {
157
+ pendingCloudConfig.folderId = await gDriveFindOrCreateFolder() || undefined;
158
+ if (pendingCloudConfig.folderId) saveFolderIdToConfig(pendingCloudConfig.folderId);
159
+ if (!pendingCloudConfig.folderId) {
160
+ setCloudError(`Cannot read ${filename}: Google Drive folder unavailable (OAuth not granted?)`, { op: "read", filename });
161
+ return null;
162
+ }
163
+ }
164
+ const provider = getCloudProvider(pendingCloudConfig.provider as string, pendingCloudConfig.folderId);
165
+ if (!provider) { setCloudError(`No cloud provider for ${pendingCloudConfig.provider}`, { op: "read", filename }); return null; }
166
+ console.log(` [cloud] Reading ${filename} via ${pendingCloudConfig.provider} API...`);
167
+ const content = await provider.read(filename);
168
+ if (content) {
169
+ setCloudError(null);
170
+ // Cache locally
171
+ try {
172
+ fs.mkdirSync(LOCAL_DIR, { recursive: true });
173
+ fs.writeFileSync(path.join(LOCAL_DIR, filename), content);
174
+ } catch { /* ignore cache write failure */ }
175
+ }
176
+ // Don't set error for missing files — they may not exist yet (e.g., clients.jsonc on first run)
177
+ return content;
178
+ }
179
+
180
+ /** Write a file via cloud API. Throws on failure with a descriptive error,
181
+ * and updates lastCloudError so UI banners pick it up via getStorageInfo()
182
+ * and the onCloudError listener. */
183
+ export async function cloudWrite(filename: string, content: string): Promise<void> {
184
+ if (!pendingCloudConfig) {
185
+ const err = `Cloud not initialized yet — cannot save ${filename} (pendingCloudConfig is null; loadSettings may not have run, or config.jsonc has no sharedDir)`;
186
+ console.error(` [cloud] cloudWrite: ${err}`);
187
+ setCloudError(err, { op: "write", filename });
188
+ throw new Error(err);
189
+ }
190
+ // Ensure we have a folder ID
191
+ if (!pendingCloudConfig.folderId) {
192
+ pendingCloudConfig.folderId = await gDriveFindOrCreateFolder() || undefined;
193
+ if (pendingCloudConfig.folderId) saveFolderIdToConfig(pendingCloudConfig.folderId);
194
+ if (!pendingCloudConfig.folderId) {
195
+ const err = `Cannot save ${filename}: Google Drive folder unavailable (OAuth not granted or token expired)`;
196
+ setCloudError(err, { op: "write", filename });
197
+ throw new Error(err);
198
+ }
199
+ }
200
+ const provider = getCloudProvider(pendingCloudConfig.provider as string, pendingCloudConfig.folderId);
201
+ if (!provider) {
202
+ const err = `No cloud provider for ${pendingCloudConfig.provider}`;
203
+ setCloudError(err, { op: "write", filename });
204
+ throw new Error(err);
205
+ }
206
+ try {
207
+ await provider.write(filename, content);
208
+ setCloudError(null);
209
+ } catch (e: any) {
210
+ setCloudError(e.message, { op: "write", filename });
211
+ throw e;
212
+ }
213
+ }
214
+
215
+ /** Persist the discovered folder ID back to config.jsonc so we don't search again */
216
+ function saveFolderIdToConfig(folderId: string): void {
217
+ try {
218
+ const config = readLocalConfig();
219
+ if (config.sharedDir && typeof config.sharedDir === "object" && !Array.isArray(config.sharedDir)) {
220
+ (config.sharedDir as SharedDirConfig).folderId = folderId;
221
+ atomicWrite(LOCAL_CONFIG_PATH, config);
222
+ }
223
+ } catch { /* non-critical */ }
224
+ }
225
+
226
+ /** Whether cloud API fallback is active */
227
+ export function isCloudMode(): boolean {
228
+ return pendingCloudConfig !== null;
229
+ }
230
+
231
+ /** Get storage provider info for display */
232
+ export function getStorageInfo(): { provider: string; mode: "mount" | "api" | "local"; cloudPath?: string; cloudError?: string } {
233
+ const config = readLocalConfig();
234
+ if (config.sharedDir) {
235
+ const entries = Array.isArray(config.sharedDir) ? config.sharedDir : [config.sharedDir];
236
+ for (const entry of entries) {
237
+ if (typeof entry === "string") {
238
+ const resolved = resolveSharedEntry(entry);
239
+ if (resolved && resolved !== LOCAL_DIR) {
240
+ return { provider: "local", mode: "local", cloudPath: resolved };
241
+ }
242
+ continue;
243
+ }
244
+ // Provider-based entry — check for API mode (folderId) first, then mount
245
+ const name = (entry.provider === "gdrive" || entry.provider === "google") ? "gdrive" : entry.provider;
246
+ if (entry.folderId) {
247
+ // Has folder ID → API mode (don't scan filesystem for mounts)
248
+ return { provider: name, mode: "api", cloudPath: entry.path, cloudError: lastCloudError || undefined };
249
+ }
250
+ const resolved = resolveSharedEntry(entry);
251
+ if (resolved && resolved !== LOCAL_DIR) {
252
+ return { provider: name, mode: "mount", cloudPath: entry.path };
253
+ }
254
+ }
255
+ // Not mounted and no folderId — check pendingCloudConfig from initCloudConfig()
256
+ if (pendingCloudConfig) {
257
+ const name = (pendingCloudConfig.provider === "gdrive" || pendingCloudConfig.provider === "google") ? "gdrive" : pendingCloudConfig.provider;
258
+ return { provider: name, mode: "api", cloudPath: pendingCloudConfig.path, cloudError: lastCloudError || undefined };
259
+ }
260
+ }
261
+ return { provider: "local", mode: "local" };
262
+ }
263
+
264
+ // ── File helpers ──
265
+
266
+ /** Read JSON or JSONC file. If exact path not found, tries .json/.jsonc variant. */
267
+ function readJsonc(filePath: string): any {
268
+ let actual = filePath;
269
+ if (!fs.existsSync(actual)) {
270
+ // Try alternate extension
271
+ if (actual.endsWith(".jsonc")) actual = actual.replace(/\.jsonc$/, ".json");
272
+ else if (actual.endsWith(".json")) actual = actual.replace(/\.json$/, ".jsonc");
273
+ if (!fs.existsSync(actual)) return null;
274
+ }
275
+ try {
276
+ return parseJsonc(fs.readFileSync(actual, "utf-8").replace(/\r/g, ""));
277
+ } catch (e: any) {
278
+ console.error(`Failed to read ${actual}: ${e.message}`);
279
+ return null;
280
+ }
281
+ }
282
+
283
+ function atomicWrite(filePath: string, data: any): void {
284
+ const dir = path.dirname(filePath);
285
+ fs.mkdirSync(dir, { recursive: true });
286
+ const tmp = filePath + ".tmp";
287
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
288
+ fs.renameSync(tmp, filePath);
289
+ }
290
+
291
+ /** Read a config file: shared first, local fallback, merge local overrides */
292
+ function loadFile<T>(filename: string, defaults: T): T {
293
+ const sharedDir = getSharedDir();
294
+ const sharedPath = path.join(sharedDir, filename);
295
+ const localPath = path.join(LOCAL_DIR, filename);
296
+
297
+ // Read shared version
298
+ let data = readJsonc(sharedPath);
299
+
300
+ // If no shared, try local
301
+ if (!data) data = readJsonc(localPath);
302
+
303
+ // If neither exists, use defaults
304
+ if (!data) return defaults;
305
+
306
+ // Cache shared → local (for offline fallback)
307
+ if (sharedDir !== LOCAL_DIR && fs.existsSync(sharedPath)) {
308
+ try {
309
+ const shared = fs.readFileSync(sharedPath, "utf-8");
310
+ fs.mkdirSync(LOCAL_DIR, { recursive: true });
311
+ fs.writeFileSync(localPath, shared);
312
+ } catch { /* ignore cache failures */ }
313
+ }
314
+
315
+ return { ...defaults, ...data };
316
+ }
317
+
318
+ /** Save a config file to the shared directory (and cloud API if active).
319
+ * Always writes the local copy first so the data is never lost.
320
+ * If a cloud provider is configured, also writes there — failures set
321
+ * lastCloudError and notify onCloudError listeners so the UI can show
322
+ * a banner. The cloud write is fire-and-forget at this layer; callers
323
+ * who need the result should use the typed save* helpers below. */
324
+ function saveFile(filename: string, data: any): void {
325
+ const sharedDir = getSharedDir();
326
+ atomicWrite(path.join(sharedDir, filename), data);
327
+ // Also update local cache
328
+ if (sharedDir !== LOCAL_DIR) {
329
+ try { atomicWrite(path.join(LOCAL_DIR, filename), data); } catch { /* ignore */ }
330
+ }
331
+ // Write to cloud API if filesystem mount unavailable (creates app-owned file for drive.file scope)
332
+ if (pendingCloudConfig) {
333
+ cloudWrite(filename, JSON.stringify(data, null, 2))
334
+ .then(() => console.log(` [cloud] Saved ${filename} via ${pendingCloudConfig!.provider} API`))
335
+ .catch(e => console.error(` [cloud] Failed to save ${filename}: ${e.message}`));
336
+ // Note: we don't await — saveFile is sync. cloudWrite() already calls
337
+ // setCloudError(), which fires onCloudError listeners synchronously
338
+ // when the promise rejects, so the UI gets the failure even though
339
+ // we don't propagate it back through the call chain here.
340
+ }
341
+ }
342
+
343
+ // ── Provider defaults ──
344
+
345
+ interface ProviderDefaults {
346
+ label: string;
347
+ imap: { host: string; port: number; tls: boolean; auth: "password" | "oauth2" };
348
+ smtp: { host: string; port: number; tls: boolean; auth: "password" | "oauth2" };
349
+ // The former per-provider `spam` path field was removed 2026-04-22 —
350
+ // markAsSpamMessages now finds the junk folder via `specialUse === "junk"`
351
+ // on the DB-stored folder record, populated by mailx-imap from iflow's
352
+ // getSpecialFolders() (RFC 6154 flags with sensible defaults for servers
353
+ // that don't advertise them). The provider-default path was never
354
+ // authoritative anyway — servers don't agree ("Junk Email" vs "Junk"
355
+ // vs "SPAM" vs "_Spam" vs "Bulk Mail") and we already have the right
356
+ // answer from the server.
357
+ }
358
+
359
+ const PROVIDERS: Record<string, ProviderDefaults> = {
360
+ "gmail.com": {
361
+ label: "Gmail",
362
+ imap: { host: "imap.gmail.com", port: 993, tls: true, auth: "oauth2" },
363
+ smtp: { host: "smtp.gmail.com", port: 587, tls: true, auth: "oauth2" },
364
+ },
365
+ "googlemail.com": {
366
+ label: "Gmail",
367
+ imap: { host: "imap.gmail.com", port: 993, tls: true, auth: "oauth2" },
368
+ smtp: { host: "smtp.gmail.com", port: 587, tls: true, auth: "oauth2" },
369
+ },
370
+ "outlook.com": {
371
+ label: "Outlook",
372
+ imap: { host: "outlook.office365.com", port: 993, tls: true, auth: "oauth2" },
373
+ smtp: { host: "smtp.office365.com", port: 587, tls: true, auth: "oauth2" },
374
+ },
375
+ "hotmail.com": {
376
+ label: "Hotmail",
377
+ imap: { host: "outlook.office365.com", port: 993, tls: true, auth: "oauth2" },
378
+ smtp: { host: "smtp.office365.com", port: 587, tls: true, auth: "oauth2" },
379
+ },
380
+ "yahoo.com": {
381
+ label: "Yahoo",
382
+ imap: { host: "imap.mail.yahoo.com", port: 993, tls: true, auth: "password" },
383
+ smtp: { host: "smtp.mail.yahoo.com", port: 587, tls: true, auth: "password" },
384
+ },
385
+ "aol.com": {
386
+ label: "AOL",
387
+ imap: { host: "imap.aol.com", port: 993, tls: true, auth: "password" },
388
+ smtp: { host: "smtp.aol.com", port: 587, tls: true, auth: "password" },
389
+ },
390
+ "icloud.com": {
391
+ label: "iCloud",
392
+ imap: { host: "imap.mail.me.com", port: 993, tls: true, auth: "password" },
393
+ smtp: { host: "smtp.mail.me.com", port: 587, tls: true, auth: "password" },
394
+ },
395
+ };
396
+
397
+ /** Fill in provider defaults for an account based on email domain.
398
+ * Exported so mailx-service's leanAccountsJsonc helper can reuse the same
399
+ * canonicalization rules that loadAccounts uses. */
400
+ export function normalizeAccount(acct: any, globalName?: string): AccountConfig {
401
+ const email = acct.email || "";
402
+ const localPart = email.split("@")[0]?.toLowerCase() || "";
403
+ const domain = email.split("@")[1]?.toLowerCase() || "";
404
+ const provider = PROVIDERS[domain];
405
+ const user = acct.imap?.user || acct.user || email;
406
+
407
+ // P14: auto-derive id and label so a known-provider account works with just
408
+ // { email, password? } in accounts.jsonc. id defaults to local-part (most
409
+ // accounts have a unique local-part); label defaults to provider name or id.
410
+ // Generic local-parts (info, admin, support, no-reply, ...) fall back to
411
+ // the domain stem to avoid collisions across accounts.
412
+ const GENERIC_LOCALS = new Set(["info", "admin", "support", "no-reply", "noreply", "contact", "hello", "mail", "office"]);
413
+ const domainStem = domain.split(".")[0] || "";
414
+ const autoId = (localPart && !GENERIC_LOCALS.has(localPart)) ? localPart : (domainStem || "account");
415
+
416
+ return {
417
+ id: acct.id || autoId,
418
+ name: acct.name || globalName || localPart,
419
+ label: acct.label || provider?.label || acct.id || autoId,
420
+ email,
421
+ imap: {
422
+ host: acct.imap?.host || provider?.imap.host || `imap.${domain}`,
423
+ port: acct.imap?.port || provider?.imap.port || 993,
424
+ tls: acct.imap?.tls ?? provider?.imap.tls ?? true,
425
+ auth: acct.imap?.auth || provider?.imap.auth || "password",
426
+ user: acct.imap?.user || user,
427
+ password: acct.imap?.password || acct.password,
428
+ },
429
+ smtp: {
430
+ host: acct.smtp?.host || provider?.smtp.host || `smtp.${domain}`,
431
+ port: acct.smtp?.port || provider?.smtp.port || 587,
432
+ tls: acct.smtp?.tls ?? provider?.smtp.tls ?? true,
433
+ auth: acct.smtp?.auth || provider?.smtp.auth || "password",
434
+ user: acct.smtp?.user || user,
435
+ password: acct.smtp?.password || acct.password,
436
+ },
437
+ enabled: acct.enabled ?? true,
438
+ primary: acct.primary,
439
+ primaryCalendar: (acct as any).primaryCalendar,
440
+ primaryTasks: (acct as any).primaryTasks,
441
+ primaryContacts: (acct as any).primaryContacts,
442
+ defaultSend: acct.defaultSend,
443
+ syncContacts: acct.syncContacts ?? (provider?.imap.auth === "oauth2"),
444
+ relayDomains: acct.relayDomains,
445
+ deliveredToPrefix: acct.deliveredToPrefix,
446
+ identityDomains: acct.identityDomains,
447
+ // `spam` passthrough retired 2026-04-22 — markAsSpamMessages now finds
448
+ // the junk folder via `specialUse === "junk"` on the DB folder record
449
+ // (populated by mailx-imap from iflow's getSpecialFolders()). Authoritative
450
+ // per-server info beats per-domain guesses.
451
+ // `signature` is on AccountConfig in mailx-types but the workspace
452
+ // build order sometimes leaves a stale .d.ts for type-check; using
453
+ // `as any` is the minimum-blast-radius way to add the field without
454
+ // blocking the build. Once mailx-types has rebuilt once (post-field)
455
+ // this cast can be removed.
456
+ ...(acct.signature ? { signature: acct.signature } : {}),
457
+ ...(acct.sig && typeof acct.sig === "object" && typeof acct.sig.text === "string"
458
+ ? { sig: { text: acct.sig.text, html: !!acct.sig.html } } : {}),
459
+ } as AccountConfig;
460
+ }
461
+
462
+ // ── Defaults ──
463
+
464
+ const DEFAULT_ACCOUNTS: AccountConfig[] = [];
465
+
466
+ const DEFAULT_PREFERENCES = {
467
+ ui: {
468
+ theme: "system" as "system" | "dark" | "light",
469
+ editor: "quill" as "quill" | "tiptap",
470
+ folderWidth: 220,
471
+ listViewerSplit: 40,
472
+ fontSize: 15,
473
+ },
474
+ sync: {
475
+ intervalMinutes: 5,
476
+ historyDays: 30,
477
+ prefetch: true,
478
+ },
479
+ autocomplete: {
480
+ enabled: false,
481
+ provider: "ollama" as const,
482
+ ollamaUrl: "http://localhost:11434",
483
+ ollamaModel: "qwen2.5-coder:1.5b",
484
+ cloudApiKey: "",
485
+ cloudModel: "claude-sonnet-4-20250514",
486
+ debounceMs: 600,
487
+ maxTokens: 60,
488
+ },
489
+ };
490
+
491
+ const DEFAULT_AUTOCOMPLETE: AutocompleteSettings = {
492
+ enabled: false,
493
+ provider: "ollama",
494
+ ollamaUrl: "http://localhost:11434",
495
+ ollamaModel: "qwen2.5-coder:1.5b",
496
+ cloudApiKey: "",
497
+ cloudModel: "claude-sonnet-4-20250514",
498
+ debounceMs: 600,
499
+ maxTokens: 60,
500
+ };
501
+
502
+ const DEFAULT_ALLOWLIST = {
503
+ senders: [] as string[],
504
+ domains: [] as string[],
505
+ recipients: [] as string[],
506
+ // Flagged senders/domains — surfaced as a red warning on the
507
+ // remote-content banner. Distinct from the positive lists above:
508
+ // these don't auto-allow anything, they make the banner louder when
509
+ // a known-suspicious correspondent's mail shows up. Future: a shared
510
+ // GitHub list users can opt in to (community-flagged phishing /
511
+ // tracker-heavy senders) — see TODO.md.
512
+ flaggedSenders: [] as string[],
513
+ flaggedDomains: [] as string[],
514
+ };
515
+
516
+ // ── Public API ──
517
+
518
+ /** Load account configs */
519
+ export function loadAccounts(): AccountConfig[] {
520
+ const sharedDir = getSharedDir();
521
+ const sharedPath = path.join(sharedDir, "accounts.jsonc");
522
+ const localPath = path.join(LOCAL_DIR, "accounts.jsonc");
523
+
524
+ // Try shared first, then local cache
525
+ let accounts = readJsonc(sharedPath);
526
+ if (!accounts) accounts = readJsonc(localPath);
527
+
528
+ if (accounts?.accounts || Array.isArray(accounts)) {
529
+ // Cache shared to local for offline fallback — but ONLY if the
530
+ // content actually differs. Unconditionally writing on every load
531
+ // retriggers fs.watch on the local copy, which fires the config-
532
+ // changed banner and cloud-poll cycle even when nothing changed.
533
+ // Result: "accounts.jsonc changed" notification firing constantly.
534
+ if (sharedDir !== LOCAL_DIR && fs.existsSync(sharedPath)) {
535
+ try {
536
+ const sharedContent = fs.readFileSync(sharedPath, "utf-8");
537
+ let localContent = "";
538
+ try { localContent = fs.readFileSync(localPath, "utf-8"); } catch { /* missing */ }
539
+ // Normalize before comparing — GDrive-mounted copies often
540
+ // differ in BOM / line endings / trailing newline without any
541
+ // semantic change, and that triggered the spurious banner.
542
+ const norm = (s: string): string =>
543
+ s.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n").replace(/[ \t\r\n]+$/, "");
544
+ if (norm(sharedContent) !== norm(localContent)) {
545
+ fs.mkdirSync(LOCAL_DIR, { recursive: true });
546
+ fs.writeFileSync(localPath, sharedContent);
547
+ }
548
+ } catch { /* ignore */ }
549
+ }
550
+ const raw: any[] = accounts.accounts || accounts;
551
+ const globalName: string = accounts.name || "";
552
+ const result = deduplicateAccounts(raw.map((a: any) => normalizeAccount(a, globalName)));
553
+ return applyAccountOverrides(result);
554
+ }
555
+
556
+ // Legacy: read from settings.jsonc
557
+ const legacy = loadLegacySettings();
558
+ if (legacy?.accounts) return applyAccountOverrides(legacy.accounts.map((a: any) => normalizeAccount(a, legacy.name)));
559
+
560
+ return DEFAULT_ACCOUNTS;
561
+ }
562
+
563
+ /** Normalize email for dedup — Gmail ignores dots before @ */
564
+ function normalizeEmail(email: string): string {
565
+ const [local, domain] = email.toLowerCase().split("@");
566
+ if (!domain) return email.toLowerCase();
567
+ if (domain === "gmail.com" || domain === "googlemail.com") {
568
+ return local.replace(/\./g, "") + "@gmail.com";
569
+ }
570
+ return `${local}@${domain}`;
571
+ }
572
+
573
+ /** Remove duplicate accounts (same email after normalization) */
574
+ function deduplicateAccounts(accounts: AccountConfig[]): AccountConfig[] {
575
+ const seen = new Set<string>();
576
+ return accounts.filter(a => {
577
+ const key = normalizeEmail(a.email);
578
+ if (seen.has(key)) return false;
579
+ seen.add(key);
580
+ return true;
581
+ });
582
+ }
583
+
584
+ /** Apply local per-account overrides (enabled, etc.) */
585
+ function applyAccountOverrides(accounts: AccountConfig[]): AccountConfig[] {
586
+ const localConfig = readLocalConfig();
587
+ const overrides = localConfig.accountOverrides;
588
+ if (!overrides) return accounts;
589
+ for (const acct of accounts) {
590
+ const ov = overrides[acct.id];
591
+ if (!ov) continue;
592
+ if (ov.enabled !== undefined) acct.enabled = ov.enabled;
593
+ }
594
+ return accounts;
595
+ }
596
+
597
+ /** Load accounts with cloud API fallback (async — use when cloud settings may not be mounted) */
598
+ export async function loadAccountsAsync(): Promise<AccountConfig[]> {
599
+ // Try sync first (filesystem)
600
+ const accounts = loadAccounts();
601
+ if (accounts.length > 0) return accounts;
602
+
603
+ // Try cloud API fallback
604
+ if (pendingCloudConfig) {
605
+ console.log(" [cloud] Trying cloud API for accounts...");
606
+ const content = await cloudRead("accounts.jsonc");
607
+ if (content) {
608
+ const data = parseJsonc(content);
609
+ if (data?.accounts || Array.isArray(data)) {
610
+ const raw: any[] = data.accounts || data;
611
+ const globalName: string = data.name || "";
612
+ return applyAccountOverrides(raw.map((a: any) => normalizeAccount(a, globalName)));
613
+ }
614
+ }
615
+ // Legacy settings.jsonc is no longer read — use accounts.jsonc only
616
+ }
617
+ return [];
618
+ }
619
+
620
+ /** Strip default-valued fields from a normalized AccountConfig so the
621
+ * serialized JSONC stays compact and human-editable. The previous version
622
+ * was round-tripping every defaulted field (port: 993, tls: true, auth:
623
+ * "password", enabled: true, etc.), which bloated a 10-line accounts.jsonc
624
+ * to 60+ lines and embedded unnecessary "knowledge" about defaults.
625
+ *
626
+ * Rules:
627
+ * - Drop fields that match the provider default (host/port/tls/auth derived
628
+ * from email domain via PROVIDERS).
629
+ * - Drop `enabled: true` (default).
630
+ * - Drop `name` if equal to the file-level `globalName`.
631
+ * - Drop `imap.user` / `smtp.user` if they equal the email.
632
+ * - Drop `sig.html: false` (default; only keep when user enabled HTML sigs).
633
+ * - Keep field order: id → label → email → primary* → imap → smtp → defaultSend
634
+ * → relayDomains → deliveredToPrefix → identityDomains → syncContacts → sig.
635
+ * Curated for readability, not alphabetic. */
636
+ export function denormalizeAccount(acct: AccountConfig, globalName?: string): any {
637
+ const domain = (acct.email || "").split("@")[1]?.toLowerCase() || "";
638
+ const provider = PROVIDERS[domain];
639
+ const out: any = {};
640
+ out.id = acct.id;
641
+ if (acct.label && acct.label !== provider?.label && acct.label !== acct.id) out.label = acct.label;
642
+ out.email = acct.email;
643
+ if (acct.name && acct.name !== globalName) out.name = acct.name;
644
+ if (acct.primary) out.primary = true;
645
+ if ((acct as any).primaryCalendar !== undefined) out.primaryCalendar = (acct as any).primaryCalendar;
646
+ if ((acct as any).primaryTasks !== undefined) out.primaryTasks = (acct as any).primaryTasks;
647
+ if ((acct as any).primaryContacts !== undefined) out.primaryContacts = (acct as any).primaryContacts;
648
+ // imap — keep only fields that differ from provider defaults.
649
+ const imapOut: any = {};
650
+ if (acct.imap?.host && acct.imap.host !== provider?.imap.host) imapOut.host = acct.imap.host;
651
+ if (acct.imap?.user && acct.imap.user !== acct.email) imapOut.user = acct.imap.user;
652
+ if (acct.imap?.password) imapOut.password = acct.imap.password;
653
+ if (acct.imap?.port && acct.imap.port !== (provider?.imap.port ?? 993)) imapOut.port = acct.imap.port;
654
+ if (acct.imap?.tls !== undefined && acct.imap.tls !== (provider?.imap.tls ?? true)) imapOut.tls = acct.imap.tls;
655
+ if (acct.imap?.auth && acct.imap.auth !== (provider?.imap.auth ?? "password")) imapOut.auth = acct.imap.auth;
656
+ if (Object.keys(imapOut).length > 0) out.imap = imapOut;
657
+ // smtp — same treatment.
658
+ const smtpOut: any = {};
659
+ if (acct.smtp?.host && acct.smtp.host !== provider?.smtp.host) smtpOut.host = acct.smtp.host;
660
+ if (acct.smtp?.user && acct.smtp.user !== acct.email && acct.smtp.user !== acct.imap?.user) smtpOut.user = acct.smtp.user;
661
+ if (acct.smtp?.password) smtpOut.password = acct.smtp.password;
662
+ if (acct.smtp?.port && acct.smtp.port !== (provider?.smtp.port ?? 587)) smtpOut.port = acct.smtp.port;
663
+ if (acct.smtp?.tls !== undefined && acct.smtp.tls !== (provider?.smtp.tls ?? true)) smtpOut.tls = acct.smtp.tls;
664
+ if (acct.smtp?.auth && acct.smtp.auth !== (provider?.smtp.auth ?? "password")) smtpOut.auth = acct.smtp.auth;
665
+ if (Object.keys(smtpOut).length > 0) out.smtp = smtpOut;
666
+ if (acct.defaultSend) out.defaultSend = true;
667
+ if (acct.enabled === false) out.enabled = false; // default true → omit
668
+ if (acct.relayDomains && acct.relayDomains.length > 0) out.relayDomains = acct.relayDomains;
669
+ if (acct.deliveredToPrefix && acct.deliveredToPrefix.length > 0) out.deliveredToPrefix = acct.deliveredToPrefix;
670
+ if (acct.identityDomains && acct.identityDomains.length > 0) out.identityDomains = acct.identityDomains;
671
+ // syncContacts default: true for OAuth, false otherwise. Only emit when
672
+ // the user overrode the default.
673
+ const syncContactsDefault = provider?.imap.auth === "oauth2";
674
+ if (acct.syncContacts !== undefined && acct.syncContacts !== syncContactsDefault) {
675
+ out.syncContacts = acct.syncContacts;
676
+ }
677
+ if ((acct as any).signature) out.signature = (acct as any).signature;
678
+ if (acct.sig?.text) {
679
+ // html: false is default; only keep the html flag when explicitly true.
680
+ out.sig = (acct.sig as any).html ? { text: acct.sig.text, html: true } : { text: acct.sig.text };
681
+ }
682
+ return out;
683
+ }
684
+
685
+ /** Save account configs */
686
+ /** Save accounts — merges with cloud copy by email (multi-client safe).
687
+ * Writes the lean form via denormalizeAccount so accounts.jsonc stays
688
+ * compact and human-editable. */
689
+ export async function saveAccounts(accounts: AccountConfig[]): Promise<void> {
690
+ // Merge with cloud: keep all accounts, deduplicate by normalized email
691
+ try {
692
+ const cloudContent = await cloudRead("accounts.jsonc");
693
+ if (cloudContent) {
694
+ const cloud = parseJsonc(cloudContent);
695
+ const cloudAccts: any[] = cloud?.accounts || (Array.isArray(cloud) ? cloud : []);
696
+ if (cloudAccts.length > 0) {
697
+ const seen = new Set(accounts.map(a => normalizeEmail(a.email)));
698
+ for (const ca of cloudAccts) {
699
+ if (ca.email && !seen.has(normalizeEmail(ca.email))) {
700
+ // Cloud entries are already lean — feed through
701
+ // normalizeAccount to coerce to AccountConfig shape.
702
+ accounts.push(normalizeAccount(ca));
703
+ seen.add(normalizeEmail(ca.email));
704
+ }
705
+ }
706
+ }
707
+ }
708
+ } catch { /* cloud read failed — save local version */ }
709
+ // Promote a shared "name" to file level when every account has the same
710
+ // name — keeps the JSONC tidy ({ "name": "Bob Frankston", "accounts": [...] }
711
+ // instead of repeating "name" on each entry).
712
+ const names = new Set(accounts.map(a => a.name).filter(Boolean));
713
+ const globalName = names.size === 1 ? [...names][0] : undefined;
714
+ const lean = accounts.map(a => denormalizeAccount(a, globalName));
715
+ const payload: any = globalName ? { name: globalName, accounts: lean } : { accounts: lean };
716
+ saveFile("accounts.jsonc", payload);
717
+ }
718
+
719
+ /** Load preferences (shared + local overrides, with legacy fallback) */
720
+ export function loadPreferences(): typeof DEFAULT_PREFERENCES {
721
+ let shared = loadFile("preferences.jsonc", DEFAULT_PREFERENCES);
722
+
723
+ // Legacy fallback: read ui/sync from settings.jsonc if preferences.jsonc had only defaults
724
+ const legacy = loadLegacySettings();
725
+ if (legacy?.ui) shared = { ...shared, ui: { ...shared.ui, ...legacy.ui } };
726
+ if (legacy?.sync) shared = { ...shared, sync: { ...shared.sync, ...legacy.sync } };
727
+
728
+ const localConfig = readLocalConfig();
729
+
730
+ // Local overrides
731
+ if (localConfig.historyDays !== undefined) {
732
+ shared.sync.historyDays = localConfig.historyDays;
733
+ }
734
+
735
+ return {
736
+ ui: { ...DEFAULT_PREFERENCES.ui, ...shared.ui },
737
+ sync: { ...DEFAULT_PREFERENCES.sync, ...shared.sync },
738
+ autocomplete: { ...DEFAULT_AUTOCOMPLETE, ...shared.autocomplete },
739
+ };
740
+ }
741
+
742
+ /** Save preferences */
743
+ export function savePreferences(prefs: any): void {
744
+ saveFile("preferences.jsonc", prefs);
745
+ }
746
+
747
+ /** Load autocomplete settings */
748
+ export function loadAutocomplete(): AutocompleteSettings {
749
+ const prefs = loadPreferences();
750
+ return prefs.autocomplete;
751
+ }
752
+
753
+ /** Save autocomplete settings */
754
+ export function saveAutocomplete(settings: AutocompleteSettings): void {
755
+ const prefs = loadPreferences() as any;
756
+ prefs.autocomplete = settings;
757
+ savePreferences(prefs);
758
+ }
759
+
760
+ /** Load remote content allow-list */
761
+ export function loadAllowlist(): typeof DEFAULT_ALLOWLIST {
762
+ return loadFile("allowlist.jsonc", DEFAULT_ALLOWLIST);
763
+ }
764
+
765
+ /** Save allow-list — merges with existing cloud copy (multi-client safe) */
766
+ export async function saveAllowlist(list: typeof DEFAULT_ALLOWLIST): Promise<void> {
767
+ // Read current cloud version and merge (other clients may have added entries)
768
+ let merged = { ...list };
769
+ try {
770
+ const cloudContent = await cloudRead("allowlist.jsonc");
771
+ if (cloudContent) {
772
+ const cloud = parseJsonc(cloudContent);
773
+ if (cloud) {
774
+ const mergeArrays = (local: string[], remote: string[]): string[] =>
775
+ [...new Set([...local, ...remote])];
776
+ merged = {
777
+ senders: mergeArrays(list.senders || [], cloud.senders || []),
778
+ domains: mergeArrays(list.domains || [], cloud.domains || []),
779
+ recipients: mergeArrays(list.recipients || [], cloud.recipients || []),
780
+ flaggedSenders: mergeArrays(list.flaggedSenders || [], cloud.flaggedSenders || []),
781
+ flaggedDomains: mergeArrays(list.flaggedDomains || [], cloud.flaggedDomains || []),
782
+ };
783
+ }
784
+ }
785
+ } catch { /* cloud read failed — save local version */ }
786
+ saveFile("allowlist.jsonc", merged);
787
+ }
788
+
789
+ // ── Legacy compatibility ──
790
+
791
+ function loadLegacySettings(): any {
792
+ const config = readLocalConfig();
793
+ if (config.settingsPath) return readJsonc(resolvePath(config.settingsPath));
794
+ // Try shared dir first, then local
795
+ const sharedDir = getSharedDir();
796
+ const shared = readJsonc(path.join(sharedDir, "settings.jsonc"));
797
+ if (shared) return shared;
798
+ return readJsonc(path.join(LOCAL_DIR, "settings.jsonc"));
799
+ }
800
+
801
+ /** Load settings — unified view combining all files (backward compatible) */
802
+ export function loadSettings(): MailxSettings {
803
+ const accounts = loadAccounts();
804
+ const prefs = loadPreferences();
805
+ const localConfig = readLocalConfig();
806
+
807
+ return {
808
+ accounts,
809
+ ui: prefs.ui,
810
+ sync: prefs.sync,
811
+ autocomplete: prefs.autocomplete,
812
+ store: {
813
+ basePath: localConfig.storePath || DEFAULT_STORE_PATH,
814
+ compressionBoundaryDays: 365,
815
+ },
816
+ };
817
+ }
818
+
819
+ /** Save settings — writes to split files */
820
+ export async function saveSettings(settings: MailxSettings): Promise<void> {
821
+ await saveAccounts(settings.accounts);
822
+ savePreferences({ ui: settings.ui, sync: settings.sync });
823
+ }
824
+
825
+ /** Get the local store base path */
826
+ export function getStorePath(): string {
827
+ const config = readLocalConfig();
828
+ return config.storePath ? resolvePath(config.storePath) : DEFAULT_STORE_PATH;
829
+ }
830
+
831
+ /** Get the local data directory (DB, store, etc.) */
832
+ export function getConfigDir(): string {
833
+ return LOCAL_DIR;
834
+ }
835
+
836
+ /** Get the shared settings directory */
837
+ export { getSharedDir };
838
+
839
+ // detectSharedDir() removed — cloud storage is configured via API (gdrive/onedrive),
840
+ // not auto-detected from filesystem mounts. Setup form triggers initCloudConfig().
841
+
842
+ /** Initialize local config if it doesn't exist */
843
+ export function initLocalConfig(sharedDir?: string, storePath?: string): void {
844
+ if (fs.existsSync(LOCAL_CONFIG_PATH) && !sharedDir && !storePath) return;
845
+ const existing = readLocalConfig();
846
+
847
+ // Use explicit sharedDir or preserve existing — no auto-detection.
848
+ // Cloud storage is configured when user adds an account (initCloudConfig).
849
+ const resolvedSharedDir: LocalConfig["sharedDir"] = sharedDir || existing.sharedDir;
850
+
851
+ const config: LocalConfig = {
852
+ ...existing,
853
+ sharedDir: resolvedSharedDir,
854
+ storePath: storePath || existing.storePath || DEFAULT_STORE_PATH,
855
+ };
856
+
857
+ fs.mkdirSync(LOCAL_DIR, { recursive: true });
858
+ atomicWrite(LOCAL_CONFIG_PATH, config);
859
+ }
860
+
861
+ /** Initialize config with Google Drive cloud storage.
862
+ * Finds or creates the app-owned "mailx" folder via Drive API and stores its ID.
863
+ * No mount scanning — API only. Existing settings at other paths (e.g., home/.mailx
864
+ * from Desktop sync) must be migrated manually or via config.jsonc importPath. */
865
+ export async function initCloudConfig(provider: "gdrive" = "gdrive"): Promise<void> {
866
+ const existing = readLocalConfig();
867
+ if (existing.sharedDir) return; // Already configured
868
+ // Find or create the settings folder via Drive API — tries "home/.mailx"
869
+ // first (family convention), then "mailx" (default). The found path gets
870
+ // saved so future lookups don't re-scan.
871
+ const folderId = await gDriveFindOrCreateFolder();
872
+ // Detect which path was actually found by reading back from the API
873
+ // (gDriveFindOrCreateFolder logs it). For now use "mailx" as default
874
+ // label — the folderId is what matters for subsequent reads/writes.
875
+ const sharedDir: SharedDirConfig = { provider, path: "home/.mailx", folderId: folderId || undefined };
876
+ const config: LocalConfig = { ...existing, sharedDir, storePath: existing.storePath || DEFAULT_STORE_PATH };
877
+ fs.mkdirSync(LOCAL_DIR, { recursive: true });
878
+ atomicWrite(LOCAL_CONFIG_PATH, config);
879
+ pendingCloudConfig = sharedDir;
880
+ console.log(` Initialized cloud config: ${provider} (folder ID: ${folderId || "pending"})`);
881
+ }
882
+
883
+ const DEFAULT_SETTINGS: MailxSettings = {
884
+ accounts: [],
885
+ ui: DEFAULT_PREFERENCES.ui,
886
+ sync: DEFAULT_PREFERENCES.sync,
887
+ autocomplete: DEFAULT_AUTOCOMPLETE,
888
+ store: { basePath: DEFAULT_STORE_PATH, compressionBoundaryDays: 365 },
889
+ };
890
+
891
+ /** Get historyDays for an account: per-account override > system override > shared default */
892
+ export function getHistoryDays(accountId?: string): number {
893
+ const localConfig = readLocalConfig();
894
+ if (accountId && localConfig.accountOverrides?.[accountId]?.historyDays !== undefined) {
895
+ return localConfig.accountOverrides[accountId].historyDays!;
896
+ }
897
+ if (localConfig.historyDays !== undefined) return localConfig.historyDays;
898
+ const prefs = loadPreferences();
899
+ return prefs.sync.historyDays || 0;
900
+ }
901
+
902
+ /** Get prefetch setting: download bodies during sync (default true) */
903
+ export function getPrefetch(): boolean {
904
+ const prefs = loadPreferences();
905
+ return prefs.sync.prefetch !== false;
906
+ }
907
+
908
+ export { DEFAULT_SETTINGS, DEFAULT_ALLOWLIST, DEFAULT_PREFERENCES, DEFAULT_AUTOCOMPLETE, LOCAL_DIR };