@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
package/bin/mailx.js ADDED
@@ -0,0 +1,1580 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * rmfmail -- email client
4
+ *
5
+ * Usage:
6
+ * rmfmail Start service + open in msger (IPC, no TCP)
7
+ * rmfmail --server Start Express HTTP server (dev/remote)
8
+ * rmfmail --no-browser Start server only (headless)
9
+ * rmfmail --verbose Show console output (default: log file only)
10
+ * rmfmail --email <addr> First-time setup with email (skips prompt)
11
+ * rmfmail --import <file> Import accounts.jsonc into GDrive and merge
12
+ * rmfmail -v / --version Show version and exit
13
+ * rmfmail -kill Kill running rmfmail processes
14
+ * rmfmail -setup Interactive first-time setup (CLI)
15
+ * rmfmail -test Test IMAP/SMTP connectivity
16
+ * rmfmail -rebuild Wipe local cache, re-sync from IMAP
17
+ * rmfmail -repair Re-sync metadata (fix corrupt subjects) keeping .eml files
18
+ * rmfmail -reauth Clear cached OAuth tokens; next start re-consents
19
+ * (use when new Google scopes have been added)
20
+ */
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import os from "node:os";
24
+ import net from "node:net";
25
+ import { ports } from "@bobfrankston/miscinfo";
26
+ import { showMessageBox, showService, setAppName, setAppIcon } from "@bobfrankston/mailx-host";
27
+ setAppName("rmfmail");
28
+ // Prefer the .ico (Windows Explorer / taskbar-pin shortcut uses the embedded
29
+ // icon resource of the pinned exe, or a Windows icon resource referenced
30
+ // via PKEY_AppUserModel_RelaunchIconResource — PNG can't play either role).
31
+ // Fall back to PNG for the in-window / tao-level icon on non-Windows.
32
+ {
33
+ const icoPath = path.resolve(import.meta.dirname, "..", "client", "icon.ico");
34
+ const pngPath = path.resolve(import.meta.dirname, "..", "client", "icon.png");
35
+ setAppIcon(fs.existsSync(icoPath) ? icoPath : pngPath);
36
+ }
37
+ const PORT = ports.mailx;
38
+ const args = process.argv.slice(2);
39
+ // Normalize: accept both -flag and --flag
40
+ function hasFlag(name) { return args.includes(`-${name}`) || args.includes(`--${name}`); }
41
+ const verbose = hasFlag("verbose");
42
+ const isDaemon = hasFlag("daemon"); // internal: re-spawned detached process
43
+ // Read our own version once — used for the instance file + upgrade check below.
44
+ const __selfRoot = path.join(import.meta.dirname, "..");
45
+ const __selfVersion = (() => {
46
+ try {
47
+ return JSON.parse(fs.readFileSync(path.join(__selfRoot, "package.json"), "utf-8")).version || "unknown";
48
+ }
49
+ catch {
50
+ return "unknown";
51
+ }
52
+ })();
53
+ const __instanceFile = path.join(process.env.USERPROFILE || process.env.HOME || ".", ".rmfmail", "instance.json");
54
+ function readInstanceFile() {
55
+ try {
56
+ const raw = fs.readFileSync(__instanceFile, "utf-8");
57
+ const inst = JSON.parse(raw);
58
+ if (typeof inst.pid === "number" && typeof inst.version === "string")
59
+ return inst;
60
+ }
61
+ catch { /* missing or unreadable — treated as no instance */ }
62
+ return null;
63
+ }
64
+ function writeInstanceFile(pid) {
65
+ try {
66
+ fs.mkdirSync(path.dirname(__instanceFile), { recursive: true });
67
+ fs.writeFileSync(__instanceFile, JSON.stringify({ pid, version: __selfVersion, startedAt: Date.now() }, null, 2));
68
+ }
69
+ catch { /* non-fatal */ }
70
+ }
71
+ function clearInstanceFile() {
72
+ try {
73
+ fs.unlinkSync(__instanceFile);
74
+ }
75
+ catch { /* ignore */ }
76
+ }
77
+ function pidAlive(pid) {
78
+ try {
79
+ process.kill(pid, 0);
80
+ return true;
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /** True only if `pid` is alive AND its command line looks like a rmfmail node
87
+ * process. Windows reuses PIDs aggressively — a rmfmail that exited without
88
+ * running its cleanup handler can leave behind an instance.json whose PID
89
+ * has since been recycled by some other app (e.g. Creative Cloud UI Helper),
90
+ * making bare pidAlive() return true and wedging every subsequent `mailx`
91
+ * with "already running". Verify it's actually us. Non-Windows: fall back
92
+ * to pidAlive — POSIX PID reuse is rare enough that we don't bother. */
93
+ function pidIsMailx(pid) {
94
+ if (!pidAlive(pid))
95
+ return false;
96
+ if (process.platform !== "win32")
97
+ return true;
98
+ try {
99
+ const { execSync } = require("node:child_process");
100
+ const out = execSync(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId=${pid}\\").CommandLine"`, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true }).toString();
101
+ return /(?:rmfmail|mailx)[\\\/](?:bin|packages|app)|mailx-server/i.test(out);
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ }
107
+ // Version-mismatch upgrade: if a daemon from an older version is running when
108
+ // the user types `mailx`, kill it so the new one can take over. Without this,
109
+ // a second invocation would silently no-op (daemon exists), leaving the user
110
+ // on an old UI with no indication that the install has been upgraded.
111
+ // Skip this logic for command-only flags (kill, rebuild, setup, ...) and for
112
+ // the internal --daemon respawn.
113
+ const __commandFlags = ["kill", "v", "version", "setup", "add", "test", "rebuild", "repair", "import", "log", "reauth"];
114
+ const __isCommandInvocation = process.argv.slice(2).some(a => __commandFlags.includes(a.replace(/^--?/, "")));
115
+ if (!isDaemon && !__isCommandInvocation) {
116
+ const inst = readInstanceFile();
117
+ if (inst && pidIsMailx(inst.pid)) {
118
+ if (inst.version !== __selfVersion) {
119
+ console.log(`rmfmail: upgrading running daemon (PID ${inst.pid}) from v${inst.version} → v${__selfVersion}`);
120
+ try {
121
+ process.kill(inst.pid, "SIGTERM");
122
+ }
123
+ catch { /* already gone */ }
124
+ // Give it ~1.5s to exit gracefully, then verify
125
+ const deadline = Date.now() + 2000;
126
+ while (Date.now() < deadline && pidAlive(inst.pid)) {
127
+ const sab = new SharedArrayBuffer(4);
128
+ Atomics.wait(new Int32Array(sab), 0, 0, 100); // 100ms nap
129
+ }
130
+ if (pidAlive(inst.pid)) {
131
+ try {
132
+ process.kill(inst.pid, "SIGKILL");
133
+ }
134
+ catch { /* */ }
135
+ }
136
+ clearInstanceFile();
137
+ }
138
+ else {
139
+ // Same version already running — nothing to do. Print so the user
140
+ // knows why `mailx` seems to have done nothing.
141
+ console.log(`rmfmail v${__selfVersion} is already running (PID ${inst.pid}). Use rmfmail -kill to stop it.`);
142
+ process.exit(0);
143
+ }
144
+ }
145
+ else if (inst) {
146
+ // Stale instance file — PID is dead. Clean up.
147
+ clearInstanceFile();
148
+ }
149
+ }
150
+ // Auto-detach: re-spawn as background process so terminal returns immediately
151
+ // Skip for: --verbose (want console), --daemon (already detached),
152
+ // and any command flags (setup, kill, test, etc.)
153
+ if (!verbose && !isDaemon && !process.argv.slice(2).some(a => /^-/.test(a))) {
154
+ const { spawn } = await import("node:child_process");
155
+ const child = spawn(process.execPath, [...process.argv.slice(1), "--daemon"], {
156
+ // windowsHide on the spawn options below — prevents the brief
157
+ // console-window flash when the daemon launches.
158
+ detached: true,
159
+ stdio: "ignore",
160
+ windowsHide: true,
161
+ });
162
+ child.unref();
163
+ process.exit(0);
164
+ }
165
+ const setupMode = hasFlag("setup");
166
+ const addMode = hasFlag("add");
167
+ const testMode = hasFlag("test");
168
+ const rebuildMode = hasFlag("rebuild");
169
+ const repairMode = hasFlag("repair");
170
+ const importMode = hasFlag("import");
171
+ // Validate arguments
172
+ const knownFlags = ["verbose", "kill", "v", "version", "setup", "add", "test", "rebuild", "repair", "log", "import", "email", "mail", "daemon"];
173
+ for (const arg of args) {
174
+ const flag = arg.replace(/^--?/, "");
175
+ if (arg.startsWith("-") && !knownFlags.includes(flag)) {
176
+ console.error(`Unknown option: ${arg}`);
177
+ console.error("Usage: rmfmail [-verbose] [-kill] [-rebuild] [-v] [-setup]");
178
+ process.exit(1);
179
+ }
180
+ }
181
+ function log(...msg) { if (verbose)
182
+ console.log("[rmfmail]", ...msg); }
183
+ /** Detect whether we're running with administrator / root privileges.
184
+ * Windows: `net session` requires admin — succeeds silently when elevated,
185
+ * errors "Access is denied" otherwise. Linux/Mac: check process uid.
186
+ * Returns true only when positively detected as elevated; on ambiguity
187
+ * (e.g. child_process spawn failed for non-privilege reasons), returns
188
+ * false so we don't block users on false positives. */
189
+ function isElevated() {
190
+ try {
191
+ if (process.platform === "win32") {
192
+ const { execSync } = require("node:child_process");
193
+ execSync("net session >nul 2>&1", { stdio: "ignore", windowsHide: true });
194
+ return true;
195
+ }
196
+ if (typeof process.getuid === "function") {
197
+ return process.getuid() === 0;
198
+ }
199
+ }
200
+ catch { /* non-admin → net session fails */ }
201
+ return false;
202
+ }
203
+ /** Put up a blocking warning dialog via showMessageBox. Returns the label
204
+ * the user clicked. The default (Quit) is first so Enter dismisses to
205
+ * safety. Caller decides what to do with "Continue anyway". */
206
+ async function warnElevated() {
207
+ const res = await showMessageBox({
208
+ title: "rmfmail — elevated run not recommended",
209
+ message: "rmfmail is running with Administrator privileges.\n\n" +
210
+ "This can corrupt the per-user WebView2 profile at\n" +
211
+ "%LOCALAPPDATA%\\msger\\webview2\\ and create admin-owned files\n" +
212
+ "under ~/.rmfmail/ that later non-admin runs can't write to\n" +
213
+ "(SQLite db, tokens, config).\n\n" +
214
+ "Quit, relaunch from a normal shell, and only use admin if\n" +
215
+ "you specifically know you need it. To bypass this warning\n" +
216
+ "(for scripted admin use), pass --allow-elevated.",
217
+ buttons: ["Quit", "Continue anyway"],
218
+ size: { width: 540, height: 340 },
219
+ escapeCloses: true,
220
+ });
221
+ return res.button;
222
+ }
223
+ // Kill any running rmfmail server
224
+ if (hasFlag("kill")) {
225
+ log("Killing rmfmail processes...");
226
+ const { execSync } = await import("node:child_process");
227
+ let killed = 0;
228
+ // Try graceful exit first
229
+ try {
230
+ execSync(`curl -s -m 2 http://localhost:${PORT}/api/exit`, { stdio: "pipe" });
231
+ log("Sent graceful exit");
232
+ execSync("timeout /t 1 /nobreak", { stdio: "pipe" });
233
+ }
234
+ catch { /* server may not be responding */ }
235
+ if (process.platform === "win32") {
236
+ // Kill by port
237
+ try {
238
+ const out = execSync(`netstat -ano | findstr :${PORT} | findstr LISTENING`, { encoding: "utf-8" }).trim();
239
+ const pids = [...new Set(out.split("\n").map(l => l.trim().split(/\s+/).pop()).filter(Boolean))];
240
+ for (const pid of pids) {
241
+ try {
242
+ execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" });
243
+ console.log(`Killed PID ${pid} (port ${PORT})`);
244
+ killed++;
245
+ }
246
+ catch { /* */ }
247
+ }
248
+ }
249
+ catch { /* no process on port */ }
250
+ // Kill any node.exe running rmfmail (server or IPC service). Match
251
+ // the legacy `mailx` path too — source tree dir is still
252
+ // `Y:\dev\email\mailx\` and per-app exes from older installs are
253
+ // under `%LOCALAPPDATA%\mailx\` until those get cleaned up.
254
+ try {
255
+ const ps = execSync(`powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='node.exe'\\" | Where-Object { $_.CommandLine -match '(rmfmail|mailx)-server|(rmfmail|mailx)\\\\packages|(rmfmail|mailx)\\\\bin' } | Select-Object -ExpandProperty ProcessId"`, { encoding: "utf-8" }).trim();
256
+ for (const pid of ps.split("\n").map(s => s.trim()).filter(s => /^\d+$/.test(s))) {
257
+ try {
258
+ execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" });
259
+ console.log(`Killed PID ${pid} (rmfmail node process)`);
260
+ killed++;
261
+ }
262
+ catch { /* */ }
263
+ }
264
+ }
265
+ catch { /* */ }
266
+ // Kill orphaned msgernative.exe windows. When the node process dies
267
+ // without cascade-killing its WebView child (old crash, forced
268
+ // taskkill, etc.), the msgernative.exe stays on screen and looks
269
+ // like a live rmfmail. rmfmail -kill should leave no trace.
270
+ // Scoped to exes launched for rmfmail by filtering CommandLine —
271
+ // don't touch msger windows started by other apps (msga, bbs, etc.).
272
+ try {
273
+ const ps = execSync(`powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"name='msgernative.exe'\\" | Where-Object { $_.CommandLine -match 'rmfmail|mailx' -or $_.Path -match 'rmfmail|mailx' } | Select-Object -ExpandProperty ProcessId"`, { encoding: "utf-8" }).trim();
274
+ for (const pid of ps.split("\n").map(s => s.trim()).filter(s => /^\d+$/.test(s))) {
275
+ try {
276
+ execSync(`taskkill /F /PID ${pid}`, { stdio: "pipe" });
277
+ console.log(`Killed PID ${pid} (rmfmail msgernative/WebView)`);
278
+ killed++;
279
+ }
280
+ catch { /* */ }
281
+ }
282
+ }
283
+ catch { /* */ }
284
+ }
285
+ else {
286
+ try {
287
+ execSync(`fuser -k ${PORT}/tcp`, { stdio: "pipe" });
288
+ console.log(`Killed process on port ${PORT}`);
289
+ killed++;
290
+ }
291
+ catch { /* */ }
292
+ }
293
+ // Clean up stale SQLite WAL/SHM files
294
+ const mailxDir = path.join(process.env.USERPROFILE || process.env.HOME || ".", ".rmfmail");
295
+ for (const ext of ["mailx.db-shm", "mailx.db-wal"]) {
296
+ const p = path.join(mailxDir, ext);
297
+ try {
298
+ fs.unlinkSync(p);
299
+ log(`Cleaned ${ext}`);
300
+ }
301
+ catch { /* */ }
302
+ }
303
+ // Always clear instance.json — the daemon's exit handler does this on a
304
+ // clean shutdown, but if it crashed (or was force-killed before the
305
+ // handler ran) the file lingers and wedges every future `mailx` with
306
+ // "already running" because Windows recycles PIDs aggressively. -kill
307
+ // is the user's escape hatch; leave no lock behind.
308
+ clearInstanceFile();
309
+ if (killed === 0)
310
+ console.log("No rmfmail processes found");
311
+ process.exit(0);
312
+ }
313
+ // Re-auth: clear cached OAuth tokens so the next start forces a fresh
314
+ // consent flow. Needed when scopes change (e.g. Google Tasks was added
315
+ // 2026-04-23 but existing tokens were issued against the older scope
316
+ // set, so tasks API calls 403ed with "insufficient authentication
317
+ // scopes"). Safe — tokens are only a cache; fresh consent re-issues.
318
+ if (hasFlag("reauth")) {
319
+ const { getConfigDir } = await import("@bobfrankston/mailx-settings");
320
+ const tokensDir = path.join(getConfigDir(), "tokens");
321
+ if (!fs.existsSync(tokensDir)) {
322
+ console.log("No tokens directory — nothing to clear.");
323
+ process.exit(0);
324
+ }
325
+ let cleared = 0;
326
+ for (const entry of fs.readdirSync(tokensDir)) {
327
+ const userDir = path.join(tokensDir, entry);
328
+ try {
329
+ const stat = fs.statSync(userDir);
330
+ if (!stat.isDirectory())
331
+ continue;
332
+ const tokenFile = path.join(userDir, "oauth-token.json");
333
+ if (fs.existsSync(tokenFile)) {
334
+ fs.unlinkSync(tokenFile);
335
+ console.log(` Cleared token for ${entry}`);
336
+ cleared++;
337
+ }
338
+ }
339
+ catch { /* skip */ }
340
+ }
341
+ console.log(cleared === 0
342
+ ? "No cached tokens found."
343
+ : `Cleared ${cleared} cached token(s). Next 'rmfmail' start will open a browser OAuth consent so the new scopes (tasks, full contacts) get granted.`);
344
+ process.exit(0);
345
+ }
346
+ // Rebuild: wipe DB + message store, keep accounts/settings
347
+ if (rebuildMode) {
348
+ const { getConfigDir, getStorePath } = await import("@bobfrankston/mailx-settings");
349
+ const dbDir = getConfigDir();
350
+ const storePath = getStorePath();
351
+ console.log("Rebuilding rmfmail local cache...");
352
+ console.log(" Accounts and settings will be preserved.");
353
+ // Remove DB files
354
+ for (const f of ["mailx.db", "mailx.db-wal", "mailx.db-shm"]) {
355
+ const p = path.join(dbDir, f);
356
+ if (fs.existsSync(p)) {
357
+ fs.unlinkSync(p);
358
+ console.log(` Deleted ${f}`);
359
+ }
360
+ }
361
+ // Remove message store
362
+ if (fs.existsSync(storePath)) {
363
+ fs.rmSync(storePath, { recursive: true });
364
+ console.log(` Deleted message store`);
365
+ }
366
+ console.log(" Rebuild complete. Run 'rmfmail' to start fresh.");
367
+ process.exit(0);
368
+ }
369
+ // Repair: re-sync metadata (subjects, flags, envelopes) without deleting stored .eml files
370
+ if (repairMode) {
371
+ const { getConfigDir } = await import("@bobfrankston/mailx-settings");
372
+ const dbDir = getConfigDir();
373
+ const dbPath = path.join(dbDir, "mailx.db");
374
+ if (!fs.existsSync(dbPath)) {
375
+ console.error("No database found. Run 'rmfmail' first to create one.");
376
+ process.exit(1);
377
+ }
378
+ console.log("Repairing rmfmail metadata...");
379
+ console.log(" Message bodies (.eml files) will be preserved.");
380
+ console.log(" Clearing message metadata for re-sync...");
381
+ // Dynamic require — better-sqlite3 is a native module, not typed in bin/
382
+ const mod = "better-sqlite3";
383
+ const Database = (await import(/* webpackIgnore: true */ mod)).default;
384
+ const db = Database(dbPath);
385
+ db.pragma("journal_mode = WAL");
386
+ const count = db.prepare("SELECT COUNT(*) as cnt FROM messages").get().cnt;
387
+ db.exec("DELETE FROM messages");
388
+ db.exec("DELETE FROM messages_fts");
389
+ // Reset folder sync state so IMAP re-syncs all envelopes
390
+ db.exec("UPDATE folders SET total = 0, unread = 0");
391
+ db.close();
392
+ console.log(` Cleared ${count} message entries. Folder sync state reset.`);
393
+ console.log(" Run 'rmfmail' to re-sync from IMAP with correct encoding.");
394
+ process.exit(0);
395
+ }
396
+ // Import accounts from a local file into GDrive
397
+ if (importMode) {
398
+ const importPath = args.find(a => !a.startsWith("-"));
399
+ if (!importPath) {
400
+ console.error("Usage: rmfmail --import <path-to-accounts.jsonc>");
401
+ console.error(" Reads accounts from a local file and saves to Google Drive.");
402
+ console.error(" Example: rmfmail --import ~/OneDrive/home/.rmfmail/accounts.jsonc");
403
+ process.exit(1);
404
+ }
405
+ const { parse: parseJsonc } = await import("jsonc-parser");
406
+ const absPath = path.resolve(importPath);
407
+ if (!fs.existsSync(absPath)) {
408
+ console.error(`File not found: ${absPath}`);
409
+ process.exit(1);
410
+ }
411
+ const content = fs.readFileSync(absPath, "utf-8").replace(/\r/g, "");
412
+ const data = parseJsonc(content);
413
+ const accounts = data?.accounts || (Array.isArray(data) ? data : null);
414
+ if (!accounts || accounts.length === 0) {
415
+ console.error("No accounts found in file. Expected { accounts: [...] } or [...]");
416
+ process.exit(1);
417
+ }
418
+ console.log(`Found ${accounts.length} account(s) in ${absPath}`);
419
+ // Initialize cloud config (GDrive) and save
420
+ const { initCloudConfig, loadAccounts, saveAccounts } = await import("@bobfrankston/mailx-settings");
421
+ await initCloudConfig("gdrive");
422
+ // Merge: existing cloud accounts + imported, deduplicate by email
423
+ const existing = loadAccounts();
424
+ const merged = [...existing];
425
+ for (const acct of accounts) {
426
+ if (!merged.some(e => e.email === acct.email)) {
427
+ merged.push(acct);
428
+ console.log(` + ${acct.label || acct.email}`);
429
+ }
430
+ else {
431
+ console.log(` = ${acct.label || acct.email} (already exists)`);
432
+ }
433
+ }
434
+ // Wrap with name if the source had one
435
+ const wrapper = { accounts: merged };
436
+ if (data?.name)
437
+ wrapper.name = data.name;
438
+ await saveAccounts(merged);
439
+ console.log(`Saved ${merged.length} account(s). Run 'rmfmail' to start.`);
440
+ process.exit(0);
441
+ }
442
+ // Version
443
+ if (hasFlag("v") || hasFlag("version")) {
444
+ const root = path.join(import.meta.dirname, "..");
445
+ const ver = (pkg) => {
446
+ for (const dir of [`${root}/node_modules/${pkg}`, `${root}/node_modules/@bobfrankston/${pkg.replace("@bobfrankston/", "")}`]) {
447
+ try {
448
+ return JSON.parse(fs.readFileSync(`${dir}/package.json`, "utf-8")).version;
449
+ }
450
+ catch { /* */ }
451
+ }
452
+ // Check workspace packages
453
+ const short = pkg.replace("@bobfrankston/", "");
454
+ try {
455
+ return JSON.parse(fs.readFileSync(`${root}/packages/${short}/package.json`, "utf-8")).version;
456
+ }
457
+ catch { /* */ }
458
+ return "not found";
459
+ };
460
+ try {
461
+ const pkg = JSON.parse(fs.readFileSync(`${root}/package.json`, "utf-8"));
462
+ console.log(`\x1b[1;97;44m rmfmail v${pkg.version} \x1b[0m`);
463
+ }
464
+ catch {
465
+ console.log("rmfmail (version unknown)");
466
+ }
467
+ console.log(` node ${process.version}`);
468
+ console.log(` iflow-direct ${ver("@bobfrankston/iflow-direct")}`);
469
+ console.log(` miscinfo ${ver("@bobfrankston/miscinfo")}`);
470
+ console.log(` oauth ${ver("@bobfrankston/oauthsupport")}`);
471
+ console.log(` store ${ver("@bobfrankston/mailx-store")}`);
472
+ console.log(` server ${ver("@bobfrankston/mailx-server")}`);
473
+ console.log(` api ${ver("@bobfrankston/mailx-api")}`);
474
+ console.log(` platform ${process.platform} ${process.arch}`);
475
+ process.exit(0);
476
+ }
477
+ function isPortInUse(port) {
478
+ return new Promise((resolve) => {
479
+ const socket = net.createConnection({ port, host: "127.0.0.1" });
480
+ socket.once("connect", () => { socket.destroy(); resolve(true); });
481
+ socket.once("error", () => resolve(false));
482
+ });
483
+ }
484
+ /** Launch msger pointing at the server URL */
485
+ function launchMsger(url) {
486
+ showMessageBox({ url, detach: true, size: { width: 1400, height: 900 } });
487
+ }
488
+ async function prompt(question) {
489
+ const readline = await import("readline");
490
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
491
+ return new Promise(resolve => rl.question(question, (ans) => { rl.close(); resolve(ans.trim()); }));
492
+ }
493
+ /** Check if rmfmail is configured (has local config or accounts) */
494
+ function hasConfig() {
495
+ const home = process.env.USERPROFILE || process.env.HOME || "";
496
+ const mailxDir = path.join(home, ".rmfmail");
497
+ for (const f of ["config.jsonc", "accounts.jsonc", "settings.jsonc"]) {
498
+ if (fs.existsSync(path.join(mailxDir, f)))
499
+ return true;
500
+ }
501
+ return false;
502
+ }
503
+ /** Try to auto-discover mail server settings from email domain */
504
+ async function autoDiscover(domain) {
505
+ // 1. Try Thunderbird ISPDB
506
+ try {
507
+ const res = await fetch(`https://autoconfig.thunderbird.net/v1.1/${domain}`, { signal: AbortSignal.timeout(5000) });
508
+ if (res.ok) {
509
+ const xml = await res.text();
510
+ const imap = xml.match(/<incomingServer type="imap">[\s\S]*?<hostname>(.*?)<\/hostname>[\s\S]*?<port>(\d+)<\/port>[\s\S]*?<authentication>(.*?)<\/authentication>/);
511
+ const smtp = xml.match(/<outgoingServer type="smtp">[\s\S]*?<hostname>(.*?)<\/hostname>[\s\S]*?<port>(\d+)<\/port>[\s\S]*?<authentication>(.*?)<\/authentication>/);
512
+ if (imap && smtp) {
513
+ return {
514
+ imap: { host: imap[1], port: parseInt(imap[2]), auth: imap[3].includes("OAuth2") ? "oauth2" : "password" },
515
+ smtp: { host: smtp[1], port: parseInt(smtp[2]), auth: smtp[3].includes("OAuth2") ? "oauth2" : "password" },
516
+ source: "ISPDB",
517
+ };
518
+ }
519
+ }
520
+ }
521
+ catch { /* timeout or not found */ }
522
+ // 2. Try DNS SRV records
523
+ try {
524
+ const dns = await import("node:dns/promises");
525
+ const imapSrv = await dns.resolveSrv(`_imaps._tcp.${domain}`).catch(() => null);
526
+ const smtpSrv = await dns.resolveSrv(`_submission._tcp.${domain}`).catch(() => null);
527
+ if (imapSrv?.[0] && smtpSrv?.[0]) {
528
+ return {
529
+ imap: { host: imapSrv[0].name, port: imapSrv[0].port, auth: "password" },
530
+ smtp: { host: smtpSrv[0].name, port: smtpSrv[0].port, auth: "password" },
531
+ source: "DNS SRV",
532
+ };
533
+ }
534
+ }
535
+ catch { /* DNS failed */ }
536
+ // 3. Try MX-based detection (Google Workspace, Microsoft 365)
537
+ try {
538
+ const dns = await import("node:dns/promises");
539
+ const records = await dns.resolveMx(domain);
540
+ for (const mx of records) {
541
+ const host = mx.exchange.toLowerCase();
542
+ if (host.endsWith(".google.com") || host.endsWith(".googlemail.com")) {
543
+ return {
544
+ imap: { host: "imap.gmail.com", port: 993, auth: "oauth2" },
545
+ smtp: { host: "smtp.gmail.com", port: 587, auth: "oauth2" },
546
+ source: `MX → Google (${host})`,
547
+ };
548
+ }
549
+ if (host.endsWith(".outlook.com") || host.endsWith(".protection.outlook.com")) {
550
+ return {
551
+ imap: { host: "outlook.office365.com", port: 993, auth: "oauth2" },
552
+ smtp: { host: "smtp.office365.com", port: 587, auth: "oauth2" },
553
+ source: `MX → Microsoft (${host})`,
554
+ };
555
+ }
556
+ }
557
+ }
558
+ catch { /* DNS failed */ }
559
+ return null;
560
+ }
561
+ /** Prompt user for account details, auto-discover where possible */
562
+ async function promptForAccount(intro) {
563
+ if (intro)
564
+ console.log(intro);
565
+ const email = await prompt("Email address (or 'skip'): ");
566
+ if (!email || email.toLowerCase() === "skip")
567
+ return null;
568
+ const domain = email.split("@")[1]?.toLowerCase() || "";
569
+ const knownOAuth = ["gmail.com", "googlemail.com", "outlook.com", "hotmail.com"];
570
+ if (knownOAuth.includes(domain)) {
571
+ console.log(` ${domain}: OAuth2 — no password needed. Browser will prompt for authorization.`);
572
+ return { email };
573
+ }
574
+ // Try auto-discovery
575
+ console.log(` Looking up mail servers for ${domain}...`);
576
+ const discovered = await autoDiscover(domain);
577
+ if (discovered) {
578
+ console.log(` Found via ${discovered.source}: IMAP ${discovered.imap.host}:${discovered.imap.port}, SMTP ${discovered.smtp.host}:${discovered.smtp.port}`);
579
+ if (discovered.imap.auth === "oauth2") {
580
+ console.log(" OAuth2 authentication — browser will prompt for authorization.");
581
+ return { email };
582
+ }
583
+ const password = await prompt("Password: ");
584
+ return {
585
+ email, password,
586
+ imap: { host: discovered.imap.host, port: discovered.imap.port },
587
+ smtp: { host: discovered.smtp.host, port: discovered.smtp.port },
588
+ };
589
+ }
590
+ // Manual fallback
591
+ console.log(" Could not auto-detect servers. Enter manually:");
592
+ const password = await prompt("Password: ");
593
+ const imapHost = await prompt(`IMAP host [imap.${domain}]: `) || `imap.${domain}`;
594
+ const smtpHost = await prompt(`SMTP host [smtp.${domain}]: `) || `smtp.${domain}`;
595
+ return {
596
+ email, password,
597
+ imap: { host: imapHost },
598
+ smtp: { host: smtpHost },
599
+ };
600
+ }
601
+ /** Interactive first-time setup — GDrive API for cloud storage.
602
+ * Returns true if an account was added (caller should proceed to launch UI),
603
+ * false if the user skipped (UI's in-browser setup form will take over). */
604
+ async function runSetup(providedEmail) {
605
+ console.log("\nrmfmail— first-time setup\n");
606
+ const home = process.env.USERPROFILE || process.env.HOME || "";
607
+ const mailxDir = path.join(home, ".rmfmail");
608
+ fs.mkdirSync(mailxDir, { recursive: true });
609
+ // Use --email flag or prompt interactively
610
+ const email = providedEmail || await prompt("Email address (Gmail recommended): ");
611
+ if (!email || !email.includes("@")) {
612
+ console.log(`\nNo account added. The UI will show a setup form.`);
613
+ return false;
614
+ }
615
+ if (providedEmail)
616
+ console.log(`Using email: ${email}`);
617
+ const domain = email.split("@")[1]?.toLowerCase() || "";
618
+ let isGoogle = ["gmail.com", "googlemail.com"].includes(domain);
619
+ if (!isGoogle) {
620
+ try {
621
+ const dnsmod = await import("node:dns/promises");
622
+ const records = await dnsmod.resolveMx(domain);
623
+ isGoogle = records.some(mx => {
624
+ const host = mx.exchange.toLowerCase();
625
+ return host.endsWith(".google.com") || host.endsWith(".googlemail.com");
626
+ });
627
+ if (isGoogle)
628
+ console.log(` ${domain} is hosted on Google (detected via MX)`);
629
+ }
630
+ catch { /* DNS lookup failed */ }
631
+ }
632
+ // For Google-hosted accounts, check Drive for existing settings first
633
+ let driveFolderId = null;
634
+ if (isGoogle) {
635
+ console.log("\nChecking Google Drive for existing rmfmail settings...");
636
+ try {
637
+ const { gDriveFindOrCreateFolder, getCloudProvider } = await import("@bobfrankston/mailx-settings/cloud.js");
638
+ driveFolderId = await gDriveFindOrCreateFolder();
639
+ if (driveFolderId) {
640
+ console.log(` Drive folder: My Drive/rmfmail/ (${driveFolderId})`);
641
+ const gdrive = getCloudProvider("gdrive", driveFolderId);
642
+ if (gdrive) {
643
+ // Read accounts.jsonc (canonical) — ignore legacy settings.jsonc
644
+ const existing = await gdrive.read("accounts.jsonc");
645
+ if (existing) {
646
+ const { parse: parseJsonc } = await import("jsonc-parser");
647
+ const data = parseJsonc(existing);
648
+ const accts = data?.accounts || (Array.isArray(data) ? data : []);
649
+ if (accts.length > 0) {
650
+ console.log(`\nFound ${accts.length} existing account(s) on Google Drive (My Drive/rmfmail/accounts.jsonc):`);
651
+ for (const a of accts)
652
+ console.log(` • ${a.label || a.name || a.email}`);
653
+ // Save config pointing to Drive — no prompts needed
654
+ const config = { sharedDir: { provider: "gdrive", path: "rmfmail", folderId: driveFolderId } };
655
+ fs.writeFileSync(path.join(mailxDir, "config.jsonc"), JSON.stringify(config, null, 2));
656
+ console.log("Local config created. Starting rmfmail...\n");
657
+ return true;
658
+ }
659
+ }
660
+ }
661
+ // No existing accounts — save Drive config for later
662
+ const config = { sharedDir: { provider: "gdrive", path: "rmfmail", folderId: driveFolderId } };
663
+ fs.writeFileSync(path.join(mailxDir, "config.jsonc"), JSON.stringify(config, null, 2));
664
+ }
665
+ else {
666
+ console.log(" Could not access Google Drive (OAuth not granted or token expired).");
667
+ console.log(" Account will be saved locally; the UI will retry the cloud sync when you fix Drive access.");
668
+ }
669
+ }
670
+ catch (e) {
671
+ console.log(` Drive check failed: ${e.message} — will save locally and retry from UI.`);
672
+ }
673
+ }
674
+ // No existing accounts found — build a new account
675
+ const account = { email };
676
+ const isOAuth = ["gmail.com", "googlemail.com", "outlook.com", "hotmail.com", "live.com"].includes(domain);
677
+ if (!isOAuth) {
678
+ account.password = await prompt("Password (app password for Yahoo/AOL/iCloud): ");
679
+ }
680
+ // Display name: leave empty for Google accounts so MailxService.setupAccount
681
+ // (or the next launch's IMAP auth) can resolve it from the People API once
682
+ // the Gmail OAuth token exists. The Drive token alone doesn't have the
683
+ // contacts.readonly scope, so we can't fetch it here at CLI-prompt time.
684
+ const defaultName = email.split("@")[0];
685
+ const name = await prompt(`Your name (for From: header) [auto-detect from Google, or '${defaultName}']: `) || (isGoogle ? "" : defaultName);
686
+ // ALWAYS write a local copy first so the data is never lost. The cloud
687
+ // write below is the sync, not the source of truth on this machine.
688
+ const accountsData = { name, accounts: [account] };
689
+ const localAccountsPath = path.join(mailxDir, "accounts.jsonc");
690
+ fs.writeFileSync(localAccountsPath, JSON.stringify(accountsData, null, 2));
691
+ if (isGoogle && driveFolderId) {
692
+ // Save to Google Drive via API
693
+ console.log("\nSaving account to Google Drive...");
694
+ try {
695
+ const { getCloudProvider } = await import("@bobfrankston/mailx-settings/cloud.js");
696
+ const gdrive = getCloudProvider("gdrive", driveFolderId);
697
+ if (!gdrive)
698
+ throw new Error("getCloudProvider returned null");
699
+ await gdrive.write("accounts.jsonc", JSON.stringify(accountsData, null, 2));
700
+ console.log(" Account saved to Google Drive.");
701
+ }
702
+ catch (e) {
703
+ console.log(` Drive write failed: ${e.message}`);
704
+ console.log(` Local copy saved at ${localAccountsPath} — UI will retry cloud sync.`);
705
+ }
706
+ }
707
+ else if (isGoogle && !driveFolderId) {
708
+ console.log(` Skipping Drive sync (no folder ID). Local copy at ${localAccountsPath}.`);
709
+ }
710
+ console.log("Setup complete. Starting rmfmail...\n");
711
+ return true;
712
+ }
713
+ /** Test account connectivity — IMAP connect, SMTP send, sync round-trip */
714
+ async function runTest() {
715
+ console.log("\nrmfmail— connection test\n");
716
+ // Start server in-process to access settings
717
+ console.log("Loading settings...");
718
+ const { loadSettings, getSharedDir, initLocalConfig } = await import("@bobfrankston/mailx-settings");
719
+ initLocalConfig();
720
+ const settings = loadSettings();
721
+ if (settings.accounts.length === 0) {
722
+ console.log("No accounts configured. Run: rmfmail -setup");
723
+ process.exit(1);
724
+ }
725
+ console.log(`Shared dir: ${getSharedDir()}`);
726
+ console.log(`Accounts: ${settings.accounts.map((a) => `${a.label || a.name} <${a.email}>`).join(", ")}\n`);
727
+ for (const account of settings.accounts) {
728
+ if (!account.enabled) {
729
+ console.log(` ${account.label || account.id}: SKIPPED (disabled)\n`);
730
+ continue;
731
+ }
732
+ console.log(`Testing ${account.label || account.id} (${account.email}):`);
733
+ // Test IMAP
734
+ try {
735
+ const { createAutoImapConfig, CompatImapClient } = await import("@bobfrankston/iflow-direct");
736
+ const { NodeTcpTransport } = await import("@bobfrankston/node-tcp-transport");
737
+ const config = createAutoImapConfig({
738
+ server: account.imap.host,
739
+ port: account.imap.port,
740
+ username: account.imap.user,
741
+ password: account.imap.password
742
+ });
743
+ const client = new CompatImapClient(config, () => new NodeTcpTransport());
744
+ const folders = await client.getFolderList();
745
+ await client.logout();
746
+ console.log(` IMAP: OK (${folders.length} folders)`);
747
+ }
748
+ catch (e) {
749
+ console.log(` IMAP: FAILED — ${e.message}`);
750
+ }
751
+ // Test SMTP
752
+ try {
753
+ const { createTransport } = await import("nodemailer");
754
+ let smtpAuth;
755
+ if (account.smtp.auth === "password") {
756
+ smtpAuth = { user: account.smtp.user, pass: account.smtp.password };
757
+ }
758
+ else if (account.smtp.auth === "oauth2") {
759
+ // Try to get OAuth token
760
+ const { createAutoImapConfig } = await import("@bobfrankston/iflow-direct");
761
+ const config = createAutoImapConfig({
762
+ server: account.imap.host,
763
+ port: account.imap.port,
764
+ username: account.imap.user,
765
+ });
766
+ if (config.tokenProvider) {
767
+ const accessToken = await config.tokenProvider();
768
+ smtpAuth = { type: "OAuth2", user: account.smtp.user, accessToken };
769
+ }
770
+ }
771
+ const transport = createTransport({
772
+ host: account.smtp.host,
773
+ port: account.smtp.port,
774
+ secure: account.smtp.port === 465,
775
+ auth: smtpAuth,
776
+ tls: { rejectUnauthorized: false },
777
+ });
778
+ await transport.verify();
779
+ console.log(` SMTP: OK`);
780
+ // Send test message to self
781
+ const testSubject = `rmfmail test — ${new Date().toLocaleString()}`;
782
+ await transport.sendMail({
783
+ from: `${account.name} <${account.email}>`,
784
+ to: account.email,
785
+ subject: testSubject,
786
+ text: `This is a test message from rmfmail -test.\nSent: ${new Date().toISOString()}\nAccount: ${account.id}`,
787
+ });
788
+ console.log(` SEND: OK — test message sent to ${account.email}`);
789
+ console.log(` Subject: "${testSubject}"`);
790
+ }
791
+ catch (e) {
792
+ console.log(` SMTP: FAILED — ${e.message}`);
793
+ }
794
+ console.log();
795
+ }
796
+ console.log("Test complete. Check your inbox for the test message(s).");
797
+ process.exit(0);
798
+ }
799
+ /** Register this client on GDrive — writes/updates clients.jsonc with device info.
800
+ * Best-effort: silently skips when cloud isn't ready (fresh install, expired
801
+ * token). The scary "No cloud configured" banner must NOT fire for this. */
802
+ async function registerClient(settings) {
803
+ const { cloudRead, cloudWrite, getStorageInfo } = await import("@bobfrankston/mailx-settings");
804
+ // Check if cloud is actually ready before attempting a write — cloudWrite
805
+ // calls setCloudError which pushes an error banner to the UI. We'd rather
806
+ // silently skip than show "No cloud configured" at startup.
807
+ const info = getStorageInfo();
808
+ if (info.mode === "local" || !info.provider || info.provider === "local")
809
+ return;
810
+ // Device ID: stable per machine, stored locally
811
+ const deviceIdPath = path.join(os.homedir(), ".rmfmail", "device-id");
812
+ let deviceId;
813
+ if (fs.existsSync(deviceIdPath)) {
814
+ deviceId = fs.readFileSync(deviceIdPath, "utf-8").trim();
815
+ }
816
+ else {
817
+ deviceId = `${os.hostname()}-${Date.now().toString(36)}`;
818
+ fs.mkdirSync(path.dirname(deviceIdPath), { recursive: true });
819
+ fs.writeFileSync(deviceIdPath, deviceId);
820
+ }
821
+ // Get local IP
822
+ let localIp = "";
823
+ try {
824
+ const nets = os.networkInterfaces();
825
+ for (const addrs of Object.values(nets)) {
826
+ for (const addr of addrs || []) {
827
+ if (addr.family === "IPv4" && !addr.internal) {
828
+ localIp = addr.address;
829
+ break;
830
+ }
831
+ }
832
+ if (localIp)
833
+ break;
834
+ }
835
+ }
836
+ catch { /* ignore */ }
837
+ // Read existing clients.jsonc from cloud (may not exist yet — that's fine)
838
+ let clients = {};
839
+ try {
840
+ const content = await cloudRead("clients.jsonc");
841
+ if (content)
842
+ clients = JSON.parse(content);
843
+ }
844
+ catch { /* start fresh */ }
845
+ // Update this device's entry
846
+ clients[deviceId] = {
847
+ hostname: os.hostname(),
848
+ platform: `${process.platform} ${process.arch}`,
849
+ accounts: settings.accounts.map((a) => a.id),
850
+ lastSeen: new Date().toISOString(),
851
+ ip: localIp,
852
+ version: JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8")).version,
853
+ };
854
+ // Write back. cloudWrite now throws on failure (and sets lastCloudError),
855
+ // so swallow here — registerClient is fire-and-forget from the caller.
856
+ try {
857
+ await cloudWrite("clients.jsonc", JSON.stringify(clients, null, 2));
858
+ console.log(` [client] Registered device: ${deviceId}`);
859
+ }
860
+ catch (e) {
861
+ console.error(` [client] Failed to register device: ${e.message}`);
862
+ }
863
+ }
864
+ async function main() {
865
+ log(`Platform: ${process.platform} ${process.arch}`);
866
+ log(`Node: ${process.version}`);
867
+ log(`Mode: ${setupMode ? "setup" : "auto"}`);
868
+ // Refuse to run elevated unless explicitly opted in. An elevated mailx
869
+ // can poison %LOCALAPPDATA%\msger\webview2\ (see msger/notes.md WebView2
870
+ // profile playbook) and create admin-owned files under ~/.rmfmail/ that
871
+ // later non-admin runs can't write to. `net session` requires admin on
872
+ // Windows; succeeds → admin, fails → non-admin. Linux/Mac use process
873
+ // uid (0 = root). --allow-elevated bypasses for scripted admin use.
874
+ if (!hasFlag("allow-elevated") && !isDaemon && isElevated()) {
875
+ const button = await warnElevated();
876
+ if (button !== "Continue anyway") {
877
+ log("User chose Quit on elevated-run warning. Exiting.");
878
+ process.exit(0);
879
+ }
880
+ log("User chose Continue anyway on elevated-run warning. Proceeding (will likely poison local state).");
881
+ }
882
+ // Test connectivity
883
+ if (testMode) {
884
+ await runTest();
885
+ return;
886
+ }
887
+ // Add account to existing config
888
+ if (addMode) {
889
+ const account = await promptForAccount();
890
+ if (account) {
891
+ const home = process.env.USERPROFILE || process.env.HOME || "";
892
+ const mailxDir = path.join(home, ".rmfmail");
893
+ const settingsPath = path.join(mailxDir, "settings.jsonc");
894
+ let settings;
895
+ try {
896
+ settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8").replace(/\r/g, "").replace(/\/\/.*/g, ""));
897
+ }
898
+ catch {
899
+ settings = { accounts: [] };
900
+ }
901
+ if (!settings.accounts)
902
+ settings.accounts = [];
903
+ settings.accounts.push(account);
904
+ fs.mkdirSync(mailxDir, { recursive: true });
905
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
906
+ console.log(`Added ${account.email} to settings. Restart rmfmail to connect.`);
907
+ }
908
+ process.exit(0);
909
+ }
910
+ // Auto-detect first run — enter setup if no config exists.
911
+ // Skip CLI prompts entirely when stdin isn't a TTY (auto-detached daemon
912
+ // has stdio:"ignore", so prompt() returns "" instantly and the user never
913
+ // gets to type their email — silent no-setup). The in-browser setup form
914
+ // takes over in that case.
915
+ const hasTty = setupMode ? !!process.stdin.isTTY : (process.stdin.isTTY === true);
916
+ if (setupMode || !hasConfig()) {
917
+ if (!setupMode)
918
+ console.log("No rmfmail configuration found.");
919
+ // -email or -mail flag skips the interactive prompt
920
+ const emailFlag = args.findIndex(a => a === "-email" || a === "--email" || a === "-mail" || a === "--mail");
921
+ const emailArg = args.find(a => a.startsWith("-email=") || a.startsWith("--email=") || a.startsWith("-mail=") || a.startsWith("--mail="))?.split("=")[1]
922
+ || (emailFlag >= 0 ? args[emailFlag + 1] : undefined);
923
+ if (hasTty || emailArg) {
924
+ await runSetup(emailArg);
925
+ }
926
+ else {
927
+ console.log("No TTY and no -email flag — skipping CLI setup; in-browser setup form will appear.");
928
+ // Ensure the data dir exists so the UI can write its config.
929
+ const home = process.env.USERPROFILE || process.env.HOME || "";
930
+ fs.mkdirSync(path.join(home, ".rmfmail"), { recursive: true });
931
+ }
932
+ }
933
+ // Redirect console to log file — keep terminal clean
934
+ if (!verbose) {
935
+ const home = process.env.USERPROFILE || process.env.HOME || ".";
936
+ const logDir = path.join(home, ".rmfmail", "logs");
937
+ fs.mkdirSync(logDir, { recursive: true });
938
+ // Prune logs older than LOG_RETENTION_DAYS on startup. Keep it simple:
939
+ // scan the dir, stat, delete. Cheap even with years of history.
940
+ // Bumped 7 → 30 days so "where did my letter go?" reports can still
941
+ // reach the `[reconcile-delete]` log entry weeks after the fact.
942
+ const LOG_RETENTION_DAYS = 30;
943
+ const cutoff = Date.now() - LOG_RETENTION_DAYS * 86400000;
944
+ try {
945
+ for (const name of fs.readdirSync(logDir)) {
946
+ if (!/^mailx-\d{4}-\d{2}-\d{2}\.log$/.test(name))
947
+ continue;
948
+ const full = path.join(logDir, name);
949
+ try {
950
+ const st = fs.statSync(full);
951
+ if (st.mtimeMs < cutoff)
952
+ fs.unlinkSync(full);
953
+ }
954
+ catch { /* ignore per-file error */ }
955
+ }
956
+ }
957
+ catch { /* ignore — log pruning is best-effort */ }
958
+ const logDate = new Date().toISOString().slice(0, 10);
959
+ const logPath = path.join(logDir, `mailx-${logDate}.log`);
960
+ const logStream = fs.createWriteStream(logPath, { flags: "a" });
961
+ const ts = () => new Date().toISOString().slice(11, 23);
962
+ console.log = (...a) => { logStream.write(`${ts()} ${a.join(" ")}\n`); };
963
+ console.error = (...a) => { logStream.write(`${ts()} ERROR ${a.join(" ")}\n`); };
964
+ // Redirect daemon's process.stderr to the log too. msger forwards its
965
+ // Rust child's stderr to our process.stderr; in daemon mode that's
966
+ // stdio:"ignore" → /dev/null, which buries diagnostics like
967
+ // "Failed to load icon ..." that we need to debug taskbar-icon
968
+ // problems. Wire it through here.
969
+ const origStderrWrite = process.stderr.write.bind(process.stderr);
970
+ process.stderr.write = ((chunk, ...rest) => {
971
+ try {
972
+ const s = typeof chunk === "string" ? chunk : chunk.toString();
973
+ logStream.write(`${ts()} STDERR ${s}${s.endsWith("\n") ? "" : "\n"}`);
974
+ }
975
+ catch { /* ignore — best-effort logging */ }
976
+ return origStderrWrite(chunk, ...rest);
977
+ });
978
+ }
979
+ // IPC service mode — no HTTP server
980
+ console.log("Starting rmfmail service...");
981
+ const { MailxDB } = await import("@bobfrankston/mailx-store");
982
+ const { ImapManager } = await import("@bobfrankston/mailx-imap");
983
+ const { MailxService } = await import("@bobfrankston/mailx-service");
984
+ const { dispatch } = await import("@bobfrankston/mailx-service/jsonrpc.js");
985
+ const { loadSettings, loadAccountsAsync, getConfigDir, getStorageInfo } = await import("@bobfrankston/mailx-settings");
986
+ let settings = loadSettings();
987
+ if (settings.accounts.length === 0) {
988
+ const cloudAccounts = await loadAccountsAsync();
989
+ if (cloudAccounts.length > 0) {
990
+ settings = { ...settings, accounts: cloudAccounts };
991
+ console.log(` Loaded ${cloudAccounts.length} account(s) from cloud`);
992
+ }
993
+ }
994
+ const db = new MailxDB(getConfigDir());
995
+ // Auto-create the sending/ recovery README on every startup. Stays in
996
+ // sync with the running version of mailx; user can ignore once the
997
+ // disk-staging fallback is no longer needed.
998
+ try {
999
+ const sendingDir = path.join(getConfigDir(), "sending");
1000
+ fs.mkdirSync(sendingDir, { recursive: true });
1001
+ const readmePath = path.join(sendingDir, "README.md");
1002
+ const readmeBody = `# \`~/.rmfmail/sending/\` and \`~/.rmfmail/outbox/\` — outgoing-mail staging
1003
+
1004
+ Auto-generated by rmfmail on startup. Manual recovery reference for when rmfmail is broken or you need to feed an outgoing message into another mail program.
1005
+
1006
+ ## Layout
1007
+
1008
+ \`\`\`
1009
+ ~/.rmfmail/
1010
+ ├── outbox/<account>/
1011
+ │ └── *.ltr ← THE QUEUE. Worker scans every 10s, sends, deletes on success.
1012
+ └── sending/<account>/
1013
+ ├── editing/ ← Last 3 draft autosaves while composing.
1014
+ ├── queued/ ← Manual drop-in / crash-recovery copies.
1015
+ └── sent/ ← Audit trail of successfully sent messages.
1016
+ \`\`\`
1017
+
1018
+ In-flight files are atomically renamed to \`<file>.sending-<host>-<pid>\` while the worker is processing them — same-machine claim so two rmfmail instances don't double-send. Stale claims (dead PIDs on this host) are recovered on the next tick.
1019
+
1020
+ ## Manual fallback
1021
+
1022
+ - **rmfmail is dead, need to send a draft** — most recent file in \`sending/<account>/editing/\` is a complete RFC 822 message; copy the body into another mail client and resend.
1023
+ - **Feed a raw .eml to mailx** — drop into \`sending/<account>/queued/\`. Picked up within 10s.
1024
+ - **rmfmail says queued but server doesn't have it** — look in \`outbox/<account>/\`. \`.ltr\` still there → worker hasn't sent yet (check \`~/.rmfmail/logs/\`). \`.sending-<host>-<pid>\` → in flight. Gone → success.
1025
+
1026
+ ## Format
1027
+
1028
+ RFC 5322 with CRLF line endings. Bodies are quoted-printable encoded (readable in a text editor). Every message carries \`Message-ID:\` for cross-device dedup; \`X-Mailx-Retry\` marks retry attempts.
1029
+ `;
1030
+ // Only rewrite if content drifted (avoids gratuitous mtime updates).
1031
+ let existing = "";
1032
+ try {
1033
+ existing = fs.readFileSync(readmePath, "utf-8");
1034
+ }
1035
+ catch { /* missing */ }
1036
+ if (existing !== readmeBody)
1037
+ fs.writeFileSync(readmePath, readmeBody);
1038
+ }
1039
+ catch (e) {
1040
+ console.error(` [readme] Could not write sending README: ${e?.message || e}`);
1041
+ }
1042
+ // `--server` mode — hand off to the Express HTTP server package (self-
1043
+ // contained; initializes its own DB / IMAP manager / MailxService). No
1044
+ // WebView2, no IPC bridge. Useful for remote access (phone before MAUI
1045
+ // was a thing) and for JSON-RPC debugging from devtools. Loopback by
1046
+ // default; passes --external through if the user asked for it. See C34.
1047
+ if (hasFlag("server")) {
1048
+ writeInstanceFile(process.pid);
1049
+ await import("@bobfrankston/mailx-server");
1050
+ // mailx-server's index.ts self-invokes `start()` — once imported,
1051
+ // Express owns the event loop. Don't fall through to showService.
1052
+ return;
1053
+ }
1054
+ const { NodeTcpTransport } = await import("@bobfrankston/node-tcp-transport");
1055
+ const imapManager = new ImapManager(db, () => new NodeTcpTransport());
1056
+ // Native client is the only option (iflow-direct)
1057
+ const svc = new MailxService(db, imapManager);
1058
+ // Open msger in service mode — custom protocol serves files from client dir
1059
+ const clientDir = path.join(import.meta.dirname, "..", "client");
1060
+ const mailxapiPath = path.join(clientDir, "lib", "mailxapi.js");
1061
+ const mailxapiScript = fs.readFileSync(mailxapiPath, "utf-8");
1062
+ // Restore saved window geometry (position + size) from previous session
1063
+ const windowJsonPath = path.join(getConfigDir(), "window.json");
1064
+ let savedGeometry = null;
1065
+ try {
1066
+ const raw = JSON.parse(fs.readFileSync(windowJsonPath, "utf-8"));
1067
+ if (typeof raw.width === "number" && raw.width > 200 &&
1068
+ typeof raw.height === "number" && raw.height > 200) {
1069
+ savedGeometry = raw;
1070
+ }
1071
+ }
1072
+ catch { /* no saved geometry — use defaults */ }
1073
+ const rootPkgVersion = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8")).version;
1074
+ // Pass the .png as the window-decode icon: msger uses the `image` crate
1075
+ // to decode `options.icon` for the Tao window icon, and PNG-in-ICO files
1076
+ // round-trip unreliably through the image-0.24 ICO decoder, which leaves
1077
+ // the taskbar entry showing the empty msgernative.exe default. PNG always
1078
+ // decodes cleanly. The .ico path is forwarded separately as
1079
+ // `relaunchIcon`, which msger uses for `PKEY_AppUserModel_RelaunchIconResource`
1080
+ // (the path is consumed verbatim — no decode — so PNG-in-ICO is fine
1081
+ // there). Falls back if either file is missing.
1082
+ const __iconIco = path.join(clientDir, "icon.ico");
1083
+ const __iconPng = path.join(clientDir, "icon.png");
1084
+ const __iconPathRuntime = fs.existsSync(__iconPng) ? __iconPng : __iconIco;
1085
+ const __iconPathPin = fs.existsSync(__iconIco) ? __iconIco : undefined;
1086
+ console.log(`[icon] runtime=${__iconPathRuntime} (exists=${fs.existsSync(__iconPathRuntime)}) pin=${__iconPathPin ?? "none"} (exists=${__iconPathPin ? fs.existsSync(__iconPathPin) : false})`);
1087
+ // Pinned-shortcut launch command. Windows captures the running exe at
1088
+ // pin time by default, but the running exe is `mailx.exe` — actually
1089
+ // msgernative.exe expecting JSON options on stdin. Click that bare and
1090
+ // it dies on `serde_json::from_str("")`. Override with an explicit
1091
+ // node + script invocation so the pin re-enters through bin/mailx.js
1092
+ // the same way the `mailx` CLI does.
1093
+ const __mailxJs = path.join(import.meta.dirname, "mailx.js");
1094
+ const __relaunchCommand = `"${process.execPath}" "${__mailxJs}"`;
1095
+ const handle = showService({
1096
+ title: `rmfmail v${rootPkgVersion}`,
1097
+ url: "index.html",
1098
+ contentDir: clientDir,
1099
+ initScript: mailxapiScript,
1100
+ icon: __iconPathRuntime,
1101
+ relaunchIcon: __iconPathPin,
1102
+ relaunchCommand: __relaunchCommand,
1103
+ relaunchDisplayName: "rmfmail",
1104
+ aumid: "com.frankston.rmfmail",
1105
+ size: savedGeometry
1106
+ ? { width: savedGeometry.width, height: savedGeometry.height }
1107
+ : { width: 1400, height: 900 },
1108
+ pos: savedGeometry
1109
+ ? { x: savedGeometry.x, y: savedGeometry.y }
1110
+ : undefined,
1111
+ escapeCloses: false,
1112
+ });
1113
+ // Register ourselves as the live instance so subsequent `mailx` invocations
1114
+ // can detect version-mismatch and upgrade us (see top of file). Clear on
1115
+ // any of: SIGINT, SIGTERM, normal exit.
1116
+ //
1117
+ // Critical: the SIGTERM handler must *close the WebView child process*
1118
+ // (handle.close() → kills msgernative.exe) before Node exits. Without
1119
+ // this, the auto-upgrade leaves the old WebView orphaned on screen and
1120
+ // the user sees an apparently frozen "old mailx" while the new Node is
1121
+ // trying to spawn a second one. Cascade-killing the child makes the
1122
+ // version-mismatch auto-upgrade actually transparent to the user.
1123
+ writeInstanceFile(process.pid);
1124
+ const __cleanupInstance = () => {
1125
+ // Only clear if WE are still the registered instance. Prevents the
1126
+ // restart-daemon sequence (clear → spawn → new daemon writes its
1127
+ // own entry → we exit) from deleting the replacement's claim on
1128
+ // the way out.
1129
+ const inst = readInstanceFile();
1130
+ if (inst && inst.pid === process.pid)
1131
+ clearInstanceFile();
1132
+ try {
1133
+ handle.close();
1134
+ }
1135
+ catch { /* already gone */ }
1136
+ };
1137
+ process.once("exit", __cleanupInstance);
1138
+ process.once("SIGINT", () => { __cleanupInstance(); process.exit(0); });
1139
+ process.once("SIGTERM", () => { __cleanupInstance(); process.exit(0); });
1140
+ // Handle requests from WebView → dispatch to MailxService
1141
+ // Pass server version to dispatch so getVersion returns it
1142
+ const rootPkg = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "..", "package.json"), "utf-8"));
1143
+ handle.onRequest(async (req) => {
1144
+ if (!req._action) {
1145
+ // msger sends {"button":"OK","closed":true} on navigation — ignore it, don't exit
1146
+ if (req.closed || req.button) {
1147
+ console.log(`[ipc] ← ignored close signal during navigation: ${JSON.stringify(req).substring(0, 100)}`);
1148
+ return;
1149
+ }
1150
+ console.log(`[ipc] ← ignored (no _action): ${JSON.stringify(req).substring(0, 100)}`);
1151
+ return;
1152
+ }
1153
+ console.log(`[ipc] ← ${req._action} (${req._cbid})`);
1154
+ // Save window position+size for next launch (handled here, not in MailxService)
1155
+ if (req._action === "saveWindowGeometry") {
1156
+ try {
1157
+ const geom = {
1158
+ x: Number(req.x) || 0,
1159
+ y: Number(req.y) || 0,
1160
+ width: Math.max(400, Number(req.width) || 1400),
1161
+ height: Math.max(300, Number(req.height) || 900),
1162
+ };
1163
+ fs.writeFileSync(windowJsonPath, JSON.stringify(geom, null, 2));
1164
+ }
1165
+ catch (e) {
1166
+ console.error(`[window] Failed to save geometry: ${e.message}`);
1167
+ }
1168
+ handle.send({ _cbid: req._cbid, result: { ok: true } });
1169
+ return;
1170
+ }
1171
+ // Restart the daemon in-place without npm install. Subtle: the new
1172
+ // mailx's startup-time instance check sees the instance.json we
1173
+ // wrote and bails with "already running" if versions match —
1174
+ // skipping the new process entirely. Clear the instance file
1175
+ // FIRST so the replacement can claim the slot, THEN spawn, THEN
1176
+ // gracefully shut this process down. The exit handler guards
1177
+ // against clobbering the replacement's entry (see __cleanupInstance
1178
+ // below — only clears if instance.json's PID still matches ours).
1179
+ if (req._action === "restartDaemon") {
1180
+ handle.send({ _cbid: req._cbid, ok: true, status: "restarting" });
1181
+ try {
1182
+ clearInstanceFile();
1183
+ const { spawn: spawnChild } = await import("child_process");
1184
+ const child = spawnChild("rmfmail", [], { detached: true, stdio: "ignore", shell: true, windowsHide: true });
1185
+ child.unref();
1186
+ console.log(" [restart] Spawned fresh daemon; shutting down current");
1187
+ // Give the spawn a moment to take hold before we start
1188
+ // tearing things down — otherwise IMAP disconnects could
1189
+ // race with the new process's startup handshake.
1190
+ await new Promise(r => setTimeout(r, 800));
1191
+ }
1192
+ catch (e) {
1193
+ console.error(` [restart] Spawn failed: ${e.message}`);
1194
+ }
1195
+ gracefulShutdown("User requested restart");
1196
+ return;
1197
+ }
1198
+ // Auto-update action: run npm install then restart
1199
+ if (req._action === "performUpdate") {
1200
+ handle.send({ _cbid: req._cbid, ok: true, status: "updating" });
1201
+ try {
1202
+ const { execSync, spawn: spawnChild } = await import("child_process");
1203
+ console.log(" [update] Installing latest version...");
1204
+ execSync("npm install -g @bobfrankston/rmfmail", { encoding: "utf-8", timeout: 120_000, stdio: "inherit", windowsHide: true });
1205
+ console.log(" [update] Install complete — relaunching");
1206
+ // Spawn the new version detached so it outlives this process
1207
+ const child = spawnChild("rmfmail", [], { detached: true, stdio: "ignore", shell: true, windowsHide: true });
1208
+ child.unref();
1209
+ gracefulShutdown("Update applied");
1210
+ }
1211
+ catch (e) {
1212
+ // Don't shut down on a failed install — the user is still in
1213
+ // the middle of a session, an offline-time "Update now" tap
1214
+ // shouldn't kill the running app. Surface the failure so the
1215
+ // banner can offer a retry instead of leaving "Updating..."
1216
+ // pinned forever.
1217
+ const msg = e?.message || String(e);
1218
+ console.error(` [update] Install failed: ${msg}`);
1219
+ const offline = /ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|getaddrinfo|network|registry/i.test(msg);
1220
+ handle.send({ _event: "updateFailed", type: "updateFailed", offline, message: msg });
1221
+ }
1222
+ return;
1223
+ }
1224
+ // Per-action wall-clock timing so a "took N seconds" report tells us
1225
+ // where between Rust→stdin→dispatch→service the time actually went.
1226
+ const ipcT0 = Date.now();
1227
+ try {
1228
+ const response = await dispatch(svc, req);
1229
+ const elapsed = Date.now() - ipcT0;
1230
+ console.log(`[ipc] → ${req._action} (${req._cbid}) ok in ${elapsed}ms`);
1231
+ handle.send(response);
1232
+ }
1233
+ catch (e) {
1234
+ const elapsed = Date.now() - ipcT0;
1235
+ console.error(`[ipc] → ${req._action} (${req._cbid}) error in ${elapsed}ms: ${e.message}`);
1236
+ handle.send({ _cbid: req._cbid, error: e.message });
1237
+ }
1238
+ });
1239
+ // Wire IMAP events → push to WebView (throttled to avoid flooding stdin)
1240
+ let pendingSyncProgress = {};
1241
+ let syncProgressTimer = null;
1242
+ imapManager.on("syncProgress", (accountId, phase, progress) => {
1243
+ pendingSyncProgress[accountId] = { phase, progress };
1244
+ if (!syncProgressTimer) {
1245
+ syncProgressTimer = setTimeout(() => {
1246
+ syncProgressTimer = null;
1247
+ for (const [id, p] of Object.entries(pendingSyncProgress)) {
1248
+ handle.send({ _event: "syncProgress", type: "syncProgress", accountId: id, phase: p.phase, progress: p.progress });
1249
+ }
1250
+ pendingSyncProgress = {};
1251
+ }, 500); // batch sync events every 500ms
1252
+ }
1253
+ });
1254
+ let pendingCounts = {};
1255
+ let countsTimer = null;
1256
+ imapManager.on("folderCountsChanged", (accountId, counts) => {
1257
+ pendingCounts[accountId] = counts;
1258
+ if (!countsTimer) {
1259
+ countsTimer = setTimeout(() => {
1260
+ countsTimer = null;
1261
+ for (const [id, c] of Object.entries(pendingCounts)) {
1262
+ handle.send({ _event: "folderCountsChanged", type: "folderCountsChanged", accountId: id, ...c });
1263
+ }
1264
+ pendingCounts = {};
1265
+ }, 1000); // batch count updates every 1s
1266
+ }
1267
+ });
1268
+ // Batch folderSynced events (same cadence as counts) so a sync-all burst
1269
+ // doesn't flood the WebView with one stdin write per folder.
1270
+ let pendingSynced = {};
1271
+ let syncedTimer = null;
1272
+ imapManager.on("folderSynced", (accountId, folderId, syncedAt) => {
1273
+ (pendingSynced[accountId] ||= []).push({ folderId, syncedAt });
1274
+ if (!syncedTimer) {
1275
+ syncedTimer = setTimeout(() => {
1276
+ syncedTimer = null;
1277
+ for (const [id, entries] of Object.entries(pendingSynced)) {
1278
+ handle.send({ _event: "folderSynced", type: "folderSynced", accountId: id, entries });
1279
+ }
1280
+ pendingSynced = {};
1281
+ }, 1000);
1282
+ }
1283
+ });
1284
+ imapManager.on("syncError", (accountId, error) => {
1285
+ handle.send({ _event: "error", type: "error", message: `${accountId}: ${error}` });
1286
+ });
1287
+ imapManager.on("accountError", (accountId, error, hint, isOAuth) => {
1288
+ handle.send({ _event: "accountError", type: "accountError", accountId, error, hint, isOAuth });
1289
+ });
1290
+ imapManager.on("configChanged", (filename) => {
1291
+ handle.send({ _event: "configChanged", type: "configChanged", filename });
1292
+ });
1293
+ imapManager.on("outboxStatus", (status) => {
1294
+ handle.send({ _event: "outboxStatus", type: "outboxStatus", ...status });
1295
+ });
1296
+ // syncComplete drives the folder-tree refresh that picks up newly-discovered
1297
+ // folders on first run (Gmail accounts have no folders in the DB until the
1298
+ // first sync fetches the labels). Without this forward, the UI shows the
1299
+ // account but no folders, and never auto-selects the inbox.
1300
+ imapManager.on("syncComplete", (accountId) => {
1301
+ handle.send({ _event: "syncComplete", type: "syncComplete", accountId });
1302
+ });
1303
+ imapManager.on("syncActionFailed", (accountId, action, uid, error) => {
1304
+ handle.send({ _event: "syncActionFailed", type: "syncActionFailed", accountId, action, uid, error });
1305
+ });
1306
+ // External-edit (Word) save events. The service watches the temp file
1307
+ // and emits this when Word writes; compose.ts listens and reloads Quill.
1308
+ imapManager.on("wordEditUpdated", (payload) => {
1309
+ handle.send({ _event: "wordEditUpdated", type: "wordEditUpdated", ...payload });
1310
+ });
1311
+ // Cloud-write/read failures from mailx-settings → push to UI as a banner so
1312
+ // silent fall-back-to-local can no longer swallow Drive errors.
1313
+ const { onCloudError } = await import("@bobfrankston/mailx-settings");
1314
+ onCloudError((error, ctx) => {
1315
+ if (error) {
1316
+ handle.send({ _event: "cloudError", type: "cloudError", error, op: ctx?.op, filename: ctx?.filename });
1317
+ }
1318
+ else {
1319
+ handle.send({ _event: "cloudError", type: "cloudError", error: null });
1320
+ }
1321
+ });
1322
+ // Coalesce bodyCached into batches so a prefetch storm doesn't flood stdin
1323
+ // with one IPC write per message — lets the UI flip many rows at once.
1324
+ let pendingCached = [];
1325
+ let cachedTimer = null;
1326
+ // Calendar/tasks refresh completion — service emits when a pull merged
1327
+ // new rows or reconciled a server-side delete. Client re-renders its
1328
+ // sidebar on receipt. No payload beyond accountId.
1329
+ imapManager.on("calendarUpdated", (payload) => {
1330
+ handle.send({ _event: "calendarUpdated", type: "calendarUpdated", ...payload });
1331
+ });
1332
+ imapManager.on("tasksUpdated", (payload) => {
1333
+ handle.send({ _event: "tasksUpdated", type: "tasksUpdated", ...payload });
1334
+ });
1335
+ imapManager.on("authScopeError", (payload) => {
1336
+ handle.send({ _event: "authScopeError", type: "authScopeError", ...payload });
1337
+ });
1338
+ imapManager.on("bodyCached", (accountId, uid) => {
1339
+ pendingCached.push({ accountId, uid });
1340
+ if (!cachedTimer) {
1341
+ cachedTimer = setTimeout(() => {
1342
+ cachedTimer = null;
1343
+ const batch = pendingCached;
1344
+ pendingCached = [];
1345
+ handle.send({ _event: "bodyCached", type: "bodyCached", items: batch });
1346
+ }, 500);
1347
+ }
1348
+ });
1349
+ // Brief pause for WebView2 to initialize before starting IMAP (avoids stdin writes during init)
1350
+ await new Promise(r => setTimeout(r, 500));
1351
+ // Register all accounts (OAuth may open browser for Gmail — event loop stays free for IPC)
1352
+ for (const account of settings.accounts) {
1353
+ if (!account.enabled)
1354
+ continue;
1355
+ try {
1356
+ await imapManager.addAccount(account);
1357
+ console.log(` Account: ${account.label || account.name} (${account.id})`);
1358
+ }
1359
+ catch (e) {
1360
+ console.error(` Failed: ${account.id}: ${e.message}`);
1361
+ }
1362
+ }
1363
+ // After OAuth has completed, resolve missing display names for Google
1364
+ // accounts via the People API (contacts.readonly is in the Gmail scope).
1365
+ // "Missing" = empty or matches the email local-part default.
1366
+ try {
1367
+ const { getGoogleProfile } = await import("@bobfrankston/mailx-settings/cloud.js");
1368
+ const { saveAccounts } = await import("@bobfrankston/mailx-settings");
1369
+ let updated = false;
1370
+ for (const acct of settings.accounts) {
1371
+ if (!acct.enabled)
1372
+ continue;
1373
+ const isGoogle = acct.email.endsWith("@gmail.com")
1374
+ || acct.email.endsWith("@googlemail.com")
1375
+ || acct.imap?.host?.includes("gmail");
1376
+ if (!isGoogle)
1377
+ continue;
1378
+ const local = acct.email.split("@")[0];
1379
+ const looksDefault = !acct.name || acct.name === local;
1380
+ if (!looksDefault)
1381
+ continue;
1382
+ try {
1383
+ const tok = await imapManager.getOAuthToken(acct.id);
1384
+ if (!tok)
1385
+ continue;
1386
+ const profile = await getGoogleProfile(tok);
1387
+ if (profile?.name && profile.name !== acct.name) {
1388
+ console.log(` [name-resolve] ${acct.id}: '${acct.name || "(empty)"}' → '${profile.name}'`);
1389
+ acct.name = profile.name;
1390
+ updated = true;
1391
+ }
1392
+ }
1393
+ catch (e) {
1394
+ console.error(` [name-resolve] ${acct.id}: ${e.message}`);
1395
+ }
1396
+ }
1397
+ if (updated) {
1398
+ try {
1399
+ await saveAccounts(settings.accounts);
1400
+ }
1401
+ catch (e) {
1402
+ console.error(` [name-resolve] saveAccounts failed: ${e.message}`);
1403
+ }
1404
+ }
1405
+ }
1406
+ catch (e) {
1407
+ console.error(` [name-resolve] init failed: ${e.message}`);
1408
+ }
1409
+ // Register this client device on GDrive (fire-and-forget).
1410
+ // Skip when no accounts — cloud isn't configured yet on fresh installs,
1411
+ // so the write fails with "No cloud configured" and flashes a scary banner.
1412
+ if (settings.accounts.length > 0) {
1413
+ registerClient(settings).catch(() => { });
1414
+ }
1415
+ // Start sync in background — don't block. Kick off IDLE watchers once the
1416
+ // initial sync finishes so IMAP accounts get instant-push new-mail (the
1417
+ // 5-min STATUS poll is only a safety net).
1418
+ if (settings.accounts.some(a => a.enabled)) {
1419
+ // Fast-path: fire a quick INBOX check on every account IMMEDIATELY,
1420
+ // parallel to the full syncAll. quickInboxCheckAccount uses a fresh
1421
+ // client + a cached folder list from the DB, so it skips the
1422
+ // folder-list fetch that syncAll's step 1 does. On a cold Dovecot
1423
+ // session that folder LIST can take several seconds on big trees
1424
+ // (bobma = ~105 folders) — no reason the user should wait for it
1425
+ // before seeing mail that arrived overnight in INBOX.
1426
+ for (const acct of settings.accounts) {
1427
+ if (!acct.enabled)
1428
+ continue;
1429
+ imapManager.quickInboxCheckAccount(acct.id).catch(e => console.error(` [startup-check] ${acct.id}: ${e?.message || e}`));
1430
+ }
1431
+ imapManager.syncAll()
1432
+ .then(() => imapManager.startWatching())
1433
+ .then(() => {
1434
+ // Seed the contacts table from received messages so address
1435
+ // autocomplete works on the first compose without waiting for
1436
+ // the user to manually trigger it. Cheap — one grouped SELECT
1437
+ // + one INSERT per new sender. No-op if contact already exists.
1438
+ const added = db.seedContactsFromMessages();
1439
+ if (added > 0)
1440
+ console.log(` [contacts] seeded ${added} from message senders`);
1441
+ })
1442
+ .catch(e => console.error(` Sync error: ${e.message}`));
1443
+ }
1444
+ imapManager.startPeriodicSync(settings.sync.intervalMinutes);
1445
+ imapManager.startOutboxWorker();
1446
+ imapManager.watchConfigFiles();
1447
+ // Re-seed contacts every 30 min so newly-received senders surface in
1448
+ // autocomplete without restarting mailx. Cheap; idempotent.
1449
+ setInterval(() => {
1450
+ try {
1451
+ const added = db.seedContactsFromMessages();
1452
+ if (added > 0)
1453
+ console.log(` [contacts] periodic seed added ${added} new senders`);
1454
+ }
1455
+ catch (e) {
1456
+ console.error(` [contacts] periodic seed error: ${e.message}`);
1457
+ }
1458
+ }, 30 * 60_000);
1459
+ // Drain store_sync (calendar / tasks / contacts two-way pushes) every
1460
+ // 30s. Local edits also drain immediately; this picks up rows that
1461
+ // failed their first attempt (network blip, token refresh, 5xx).
1462
+ setInterval(() => {
1463
+ svc.drainStoreSync().catch((e) => console.error(` [store_sync] periodic drain error: ${e?.message || e}`));
1464
+ }, 30_000);
1465
+ // Calendar + Tasks poll — pulls server-side changes so the sidebar
1466
+ // reflects events added/edited/deleted on another device without
1467
+ // needing a sidebar nav click. 5-minute cadence is well under the
1468
+ // per-user rate limit and the 1M/day project quota. Webhooks would
1469
+ // be cheaper in theory but need a public HTTPS endpoint; poll is
1470
+ // the pragmatic choice (confirmed 2026-04-23). getCalendarEvents /
1471
+ // getTasks emit the refresh event via imapManager, so the sidebar
1472
+ // re-renders automatically.
1473
+ const CAL_POLL_MS = 5 * 60_000;
1474
+ const horizonDays = 90; // larger than sidebar's default so background
1475
+ // poll catches upcoming-week events the sidebar hasn't asked for yet.
1476
+ setInterval(() => {
1477
+ const now = Date.now();
1478
+ svc.getCalendarEvents(now, now + horizonDays * 86400_000)
1479
+ .catch((e) => console.error(` [calendar] poll error: ${e?.message || e}`));
1480
+ svc.getTasks(false)
1481
+ .catch((e) => console.error(` [tasks] poll error: ${e?.message || e}`));
1482
+ }, CAL_POLL_MS);
1483
+ // Contacts poll — incremental sync via People API syncToken (persisted
1484
+ // per-account in the kv table). Cheap after the first run because only
1485
+ // changed/deleted contacts come back. 15-minute cadence picks up new
1486
+ // contacts added on phone / web without restart while staying well
1487
+ // under the People API rate limit.
1488
+ const CONTACTS_POLL_MS = 15 * 60_000;
1489
+ setInterval(() => {
1490
+ svc.syncGoogleContacts()
1491
+ .catch((e) => console.error(` [contacts] poll error: ${e?.message || e}`));
1492
+ }, CONTACTS_POLL_MS);
1493
+ // Auto-update: periodically check npm for a newer version and push a
1494
+ // notification to the WebView so the user can update with one click.
1495
+ const UPDATE_CHECK_MS = 30 * 60_000; // 30 minutes
1496
+ async function checkForUpdate() {
1497
+ try {
1498
+ // spawn with windowsHide:true — execSync briefly flashes a cmd
1499
+ // window on Windows every time the periodic check fires.
1500
+ const { spawn } = await import("child_process");
1501
+ const latest = await new Promise((resolve, reject) => {
1502
+ const child = spawn("npm", ["view", "@bobfrankston/mailx", "version"], {
1503
+ windowsHide: true,
1504
+ shell: true,
1505
+ });
1506
+ let out = "";
1507
+ let err = "";
1508
+ child.stdout.on("data", (d) => { out += d.toString(); });
1509
+ child.stderr.on("data", (d) => { err += d.toString(); });
1510
+ const killer = setTimeout(() => { try {
1511
+ child.kill();
1512
+ }
1513
+ catch { /* */ } reject(new Error("npm view timed out")); }, 15_000);
1514
+ child.on("error", (e) => { clearTimeout(killer); reject(e); });
1515
+ child.on("exit", (code) => {
1516
+ clearTimeout(killer);
1517
+ if (code === 0)
1518
+ resolve(out.trim());
1519
+ else
1520
+ reject(new Error(err.trim() || `npm view exit ${code}`));
1521
+ });
1522
+ });
1523
+ const current = rootPkgVersion;
1524
+ if (latest && latest !== current) {
1525
+ console.log(` [update] New version available: ${current} → ${latest}`);
1526
+ handle.send({ _event: "updateAvailable", type: "updateAvailable", current, latest });
1527
+ }
1528
+ }
1529
+ catch (e) {
1530
+ // Silent — network down, npm not reachable, etc.
1531
+ console.log(` [update] Check failed: ${e.message}`);
1532
+ }
1533
+ }
1534
+ // First check after 2 minutes (don't slow down startup), then every 30 min
1535
+ setTimeout(() => {
1536
+ checkForUpdate();
1537
+ setInterval(checkForUpdate, UPDATE_CHECK_MS);
1538
+ }, 120_000);
1539
+ // Graceful shutdown — close IMAP connections, stop timers, close DB
1540
+ let shuttingDown = false;
1541
+ async function gracefulShutdown(reason) {
1542
+ if (shuttingDown)
1543
+ return;
1544
+ shuttingDown = true;
1545
+ console.log(`${reason} — shutting down`);
1546
+ imapManager.stopPeriodicSync();
1547
+ imapManager.stopOutboxWorker();
1548
+ // 3s hard timeout — don't hang on broken IMAP connections
1549
+ const forceExit = setTimeout(() => { console.log("Forced exit"); process.exit(0); }, 3000);
1550
+ try {
1551
+ await imapManager.shutdown();
1552
+ }
1553
+ catch { /* proceed */ }
1554
+ clearTimeout(forceExit);
1555
+ db.close();
1556
+ process.exit(0);
1557
+ }
1558
+ process.on("SIGINT", () => gracefulShutdown("SIGINT"));
1559
+ process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
1560
+ process.on("uncaughtException", (err) => {
1561
+ console.error(`UNCAUGHT EXCEPTION: ${err.stack || err.message}`);
1562
+ gracefulShutdown("uncaughtException");
1563
+ });
1564
+ process.on("unhandledRejection", (reason) => {
1565
+ console.error(`UNHANDLED REJECTION: ${reason?.stack || reason?.message || reason}`);
1566
+ });
1567
+ process.on("exit", (code) => {
1568
+ console.log(`Process exit (code ${code})`);
1569
+ if (!shuttingDown) {
1570
+ imapManager.stopPeriodicSync();
1571
+ imapManager.stopOutboxWorker();
1572
+ db.close();
1573
+ }
1574
+ });
1575
+ // Wait for window close, then shut down
1576
+ await handle.closed;
1577
+ await gracefulShutdown("Window closed");
1578
+ }
1579
+ main().catch(console.error);
1580
+ //# sourceMappingURL=mailx.js.map