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