@dongdev/fca-unofficial 3.0.30 → 4.0.0

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 (104) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +224 -406
  3. package/dist/index.d.mts +1241 -0
  4. package/dist/index.d.ts +1241 -0
  5. package/dist/index.js +27749 -0
  6. package/dist/index.mjs +27713 -0
  7. package/docs/ARCHITECTURE.md +467 -0
  8. package/docs/DOCS.md +686 -0
  9. package/fca-config.example.json +33 -0
  10. package/package.json +33 -22
  11. package/test/fca.test.cjs +533 -0
  12. package/CHANGELOG.md +0 -293
  13. package/DOCS.md +0 -2712
  14. package/func/checkUpdate.js +0 -222
  15. package/func/logAdapter.js +0 -33
  16. package/func/logger.js +0 -48
  17. package/index.d.ts +0 -751
  18. package/index.js +0 -8
  19. package/module/config.js +0 -40
  20. package/module/login.js +0 -133
  21. package/module/loginHelper.js +0 -1296
  22. package/module/options.js +0 -44
  23. package/src/api/action/addExternalModule.js +0 -25
  24. package/src/api/action/changeAvatar.js +0 -137
  25. package/src/api/action/changeBio.js +0 -75
  26. package/src/api/action/enableAutoSaveAppState.js +0 -73
  27. package/src/api/action/getCurrentUserID.js +0 -7
  28. package/src/api/action/handleFriendRequest.js +0 -57
  29. package/src/api/action/logout.js +0 -76
  30. package/src/api/action/refreshFb_dtsg.js +0 -48
  31. package/src/api/action/setPostReaction.js +0 -106
  32. package/src/api/action/unfriend.js +0 -54
  33. package/src/api/http/httpGet.js +0 -46
  34. package/src/api/http/httpPost.js +0 -52
  35. package/src/api/http/postFormData.js +0 -47
  36. package/src/api/messaging/addUserToGroup.js +0 -68
  37. package/src/api/messaging/changeAdminStatus.js +0 -126
  38. package/src/api/messaging/changeArchivedStatus.js +0 -55
  39. package/src/api/messaging/changeBlockedStatus.js +0 -48
  40. package/src/api/messaging/changeGroupImage.js +0 -91
  41. package/src/api/messaging/changeNickname.js +0 -70
  42. package/src/api/messaging/changeThreadColor.js +0 -79
  43. package/src/api/messaging/changeThreadEmoji.js +0 -111
  44. package/src/api/messaging/createNewGroup.js +0 -88
  45. package/src/api/messaging/createPoll.js +0 -46
  46. package/src/api/messaging/createThemeAI.js +0 -98
  47. package/src/api/messaging/deleteMessage.js +0 -136
  48. package/src/api/messaging/deleteThread.js +0 -56
  49. package/src/api/messaging/editMessage.js +0 -68
  50. package/src/api/messaging/forwardAttachment.js +0 -57
  51. package/src/api/messaging/getEmojiUrl.js +0 -29
  52. package/src/api/messaging/getFriendsList.js +0 -82
  53. package/src/api/messaging/getMessage.js +0 -829
  54. package/src/api/messaging/getThemePictures.js +0 -62
  55. package/src/api/messaging/handleMessageRequest.js +0 -65
  56. package/src/api/messaging/markAsDelivered.js +0 -57
  57. package/src/api/messaging/markAsRead.js +0 -88
  58. package/src/api/messaging/markAsReadAll.js +0 -49
  59. package/src/api/messaging/markAsSeen.js +0 -61
  60. package/src/api/messaging/muteThread.js +0 -50
  61. package/src/api/messaging/removeUserFromGroup.js +0 -62
  62. package/src/api/messaging/resolvePhotoUrl.js +0 -43
  63. package/src/api/messaging/scheduler.js +0 -264
  64. package/src/api/messaging/searchForThread.js +0 -52
  65. package/src/api/messaging/sendMessage.js +0 -270
  66. package/src/api/messaging/sendTypingIndicator.js +0 -74
  67. package/src/api/messaging/setMessageReaction.js +0 -91
  68. package/src/api/messaging/setTitle.js +0 -124
  69. package/src/api/messaging/shareContact.js +0 -49
  70. package/src/api/messaging/threadColors.js +0 -128
  71. package/src/api/messaging/unsendMessage.js +0 -81
  72. package/src/api/messaging/uploadAttachment.js +0 -492
  73. package/src/api/socket/core/connectMqtt.js +0 -258
  74. package/src/api/socket/core/emitAuth.js +0 -103
  75. package/src/api/socket/core/getSeqID.js +0 -320
  76. package/src/api/socket/core/getTaskResponseData.js +0 -25
  77. package/src/api/socket/core/parseDelta.js +0 -377
  78. package/src/api/socket/detail/buildStream.js +0 -215
  79. package/src/api/socket/detail/constants.js +0 -28
  80. package/src/api/socket/listenMqtt.js +0 -377
  81. package/src/api/socket/middleware/index.js +0 -216
  82. package/src/api/threads/getThreadHistory.js +0 -664
  83. package/src/api/threads/getThreadInfo.js +0 -295
  84. package/src/api/threads/getThreadList.js +0 -293
  85. package/src/api/threads/getThreadPictures.js +0 -78
  86. package/src/api/users/getUserID.js +0 -65
  87. package/src/api/users/getUserInfo.js +0 -399
  88. package/src/api/users/getUserInfoV2.js +0 -134
  89. package/src/core/sendReqMqtt.js +0 -96
  90. package/src/database/models/index.js +0 -87
  91. package/src/database/models/thread.js +0 -50
  92. package/src/database/models/user.js +0 -46
  93. package/src/database/threadData.js +0 -98
  94. package/src/database/userData.js +0 -89
  95. package/src/remote/remoteClient.js +0 -123
  96. package/src/utils/broadcast.js +0 -51
  97. package/src/utils/client.js +0 -10
  98. package/src/utils/constants.js +0 -23
  99. package/src/utils/cookies.js +0 -68
  100. package/src/utils/format.js +0 -1174
  101. package/src/utils/headers.js +0 -115
  102. package/src/utils/loginParser.js +0 -365
  103. package/src/utils/messageFormat.js +0 -1173
  104. package/src/utils/request.js +0 -332
@@ -0,0 +1,467 @@
1
+ # Architecture — @dongdev/fca-unofficial (4.x)
2
+
3
+ This document describes the internal architecture of the library. The overarching goal is to **separate session management, HTTP transport, and MQTT realtime** from **business-logic domains**, while preserving full **backward compatibility** with the flat FCA API and offering a **modern event-driven bot** interface on top.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ 1. [Design Principles](#design-principles)
10
+ 2. [Bootstrap Flow](#bootstrap-flow)
11
+ 3. [Source Tree](#source-tree)
12
+ 4. [Layer Diagram](#layer-diagram)
13
+ 5. [Core Layer](#core-layer)
14
+ 6. [Transport Layer](#transport-layer)
15
+ 7. [Domain Layer](#domain-layer)
16
+ 8. [Application Layer](#application-layer)
17
+ 9. [Compatibility Layer](#compatibility-layer)
18
+ 10. [Database Layer](#database-layer)
19
+ 11. [Utilities](#utilities)
20
+ 12. [Type System](#type-system)
21
+ 13. [Realtime Subsystem (Deep Dive)](#realtime-subsystem-deep-dive)
22
+ 14. [MessengerBot (Deep Dive)](#messengerbot-deep-dive)
23
+ 15. [Thread Cache & Realtime Sync](#thread-cache--realtime-sync)
24
+ 16. [Related Documentation](#related-documentation)
25
+
26
+ ---
27
+
28
+ ## Design Principles
29
+
30
+ 1. **Domain isolation** — Each business area (messages, threads, users, account) is a self-contained domain module with its own types, commands, and queries.
31
+ 2. **Transport abstraction** — HTTP (GraphQL, Mercury, form-data) and MQTT are in the `transport/` layer, decoupled from domain logic.
32
+ 3. **Backward compatibility** — The flat `api.sendMessage(...)` surface is preserved via `attachLegacyApiSurface`. Existing bots need zero migration.
33
+ 4. **Progressive API** — New users can choose `createMessengerBot` (event-driven) or `createFcaClient` (namespaced facade) without understanding the internals.
34
+ 5. **Optional persistence** — SQLite + Sequelize for caching is opt-in. Everything works in-memory when the database is absent.
35
+
36
+ ---
37
+
38
+ ## Bootstrap Flow
39
+
40
+ After cookie parsing or credential-based authentication, the following sequence runs:
41
+
42
+ ```
43
+ 1. core/login-helper.impl.ts
44
+ └─ Completes the session, creates `ctx` (FcaContext) and base `api` facade.
45
+
46
+ 2. core/state.ts → attachThreadUpdater(ctx, models, logger)
47
+ └─ Wires DB-based message counting per thread (if Thread model exists).
48
+
49
+ 3. app/attach-legacy-api.ts → attachLegacyApiSurface(ctx, api, ...)
50
+ └─ Attaches all flat methods + domain namespace methods onto `api`.
51
+
52
+ 4. core/thread-info-realtime-sync.ts → attachThreadInfoRealtimeSync(ctx, models, logger, api)
53
+ └─ Hooks MQTT "event" deltas to invalidate / update the thread cache.
54
+ Requires `api.getUserInfo` to be present on `api`.
55
+
56
+ 5. compat/api-registry.ts → attachClientFacade(ctx)
57
+ └─ Adds `ctx.client` (the namespaced FcaClientFacade).
58
+ ```
59
+
60
+ Each step is optional when composing a custom login flow — functions are exported individually.
61
+
62
+ ---
63
+
64
+ ## Source Tree
65
+
66
+ ```
67
+ src/
68
+ ├── core/ # Session, config, state, fundamental helpers
69
+ │ ├── auth.ts # login(), loginLegacy(), loginViaAPI(), tokensViaAPI()
70
+ │ ├── auth-helpers.ts # createAuthCore() — low-level auth plumbing
71
+ │ ├── config.ts # loadConfig(), defaultConfig(), resolveConfig()
72
+ │ ├── login-helper.ts # High-level login orchestration (entry)
73
+ │ ├── login-helper.impl.ts # Login implementation: session init, ctx creation
74
+ │ ├── mqtt.ts # listenMqtt() helper
75
+ │ ├── options.ts # setOptions() — validates and applies FcaOptions
76
+ │ ├── request.ts # createRequestHelper() — authenticated HTTP
77
+ │ ├── state.ts # FcaContext, createFcaState(), attachThreadUpdater()
78
+ │ ├── thread-info-realtime-sync.ts # Cache sync from MQTT events
79
+ │ └── update-check.ts # npm version check
80
+
81
+ ├── transport/ # Protocol-level I/O
82
+ │ ├── http/
83
+ │ │ ├── facebook.ts # Core Facebook HTTP endpoints
84
+ │ │ ├── form-data.ts # Multipart form-data uploads
85
+ │ │ ├── graphql.ts # GraphQL query execution
86
+ │ │ ├── mercury.ts # Mercury endpoint (message operations)
87
+ │ │ ├── shared-photos.ts # Shared photos endpoint
88
+ │ │ ├── threads.ts # Thread-specific HTTP calls
89
+ │ │ └── upload-attachment.ts # Attachment upload transport
90
+ │ └── realtime/
91
+ │ ├── connect-mqtt.ts # WebSocket MQTT connection, subscribe, reconnect
92
+ │ ├── get-seq-id.ts # Fetch sequence ID via GraphQL
93
+ │ ├── ls-requests.ts # Lightspeed request builder
94
+ │ ├── publish.ts # MQTT publish helpers
95
+ │ ├── stream.ts # Duplex stream adapter for MQTT
96
+ │ ├── task-response.ts # Parse MQTT task response payloads
97
+ │ └── topics.ts # MQTT topic constants
98
+
99
+ ├── domains/ # Business logic grouped by concern
100
+ │ ├── messages/
101
+ │ │ ├── index.ts # createMessagesDomain()
102
+ │ │ ├── message.types.ts # Domain-specific types
103
+ │ │ ├── commands/ # sendMessage, editMessage, unsendMessage, ...
104
+ │ │ └── queries/ # getMessage, getEmojiUrl, resolvePhotoUrl, ...
105
+ │ ├── threads/
106
+ │ │ ├── index.ts # createThreadsDomain()
107
+ │ │ ├── thread.types.ts
108
+ │ │ ├── commands/ # createNewGroup, addUserToGroup, setTitle, ...
109
+ │ │ └── queries/ # getThreadInfo, getThreadList, searchForThread, ...
110
+ │ ├── users/
111
+ │ │ ├── index.ts # createUsersDomain()
112
+ │ │ ├── user.types.ts
113
+ │ │ ├── shared.ts # Shared user utilities
114
+ │ │ └── queries/ # getUserInfo, getUserInfoV2, getUserID, getFriendsList
115
+ │ ├── account/
116
+ │ │ ├── index.ts # createAccountDomain()
117
+ │ │ ├── account.types.ts
118
+ │ │ └── commands/ # changeAvatar, changeBio, logout, unfriend, ...
119
+ │ ├── realtime/
120
+ │ │ ├── index.ts # createRealtimeDomain()
121
+ │ │ ├── listener.ts # MQTT lifecycle: getSeqID → listen → retry
122
+ │ │ ├── emit-auth.ts # MQTT auth emission
123
+ │ │ ├── middleware.ts # Realtime middleware chain
124
+ │ │ └── parse-delta.ts # Delta → event transformation
125
+ │ ├── http/
126
+ │ │ ├── index.ts # createHttpDomain()
127
+ │ │ ├── commands/ # httpPost, postFormData
128
+ │ │ └── queries/ # httpGet
129
+ │ └── scheduler/
130
+ │ └── index.ts # createSchedulerDomain()
131
+
132
+ ├── app/ # High-level application constructs
133
+ │ ├── attach-legacy-api.ts # Attaches flat methods + namespaces onto api
134
+ │ ├── create-client.ts # createFcaClient() — namespaced facade factory
135
+ │ ├── messenger-bot.ts # MessengerBot class (EventEmitter + composer)
136
+ │ └── messenger-context.ts # MessengerContext — per-message context object
137
+
138
+ ├── compat/ # Backward-compatibility adapters
139
+ │ ├── api-registry.ts # attachClientFacade() — ctx.client wiring
140
+ │ ├── callbackify.ts # Promise → callback adapter
141
+ │ └── legacy-promise.ts # Legacy promise wrapper
142
+
143
+ ├── database/ # Optional SQLite + Sequelize persistence
144
+ │ ├── helpers.ts # DB initialization helpers
145
+ │ ├── models/
146
+ │ │ ├── index.ts # Model registry
147
+ │ │ ├── thread.ts # Thread model (threadID, data, messageCount)
148
+ │ │ └── user.ts # User model
149
+ │ ├── threadData.ts # Thread data access layer
150
+ │ └── userData.ts # User data access layer
151
+
152
+ ├── session/ # Session management
153
+ │ ├── capability-resolver.ts # Resolves available capabilities
154
+ │ └── session.ts # Session abstraction
155
+
156
+ ├── remote/ # Remote control
157
+ │ └── remoteClient.ts # WebSocket client for external dashboards
158
+
159
+ ├── func/ # Logging infrastructure
160
+ │ ├── logger.ts # Main logger
161
+ │ └── logAdapter.ts # Log format adapter
162
+
163
+ ├── utils/ # Shared utilities
164
+ │ ├── broadcast.ts # Broadcast helper
165
+ │ ├── client.ts # Client utilities
166
+ │ ├── constants.ts # Shared constants
167
+ │ ├── cookies.ts # Cookie manipulation
168
+ │ ├── headers.ts # HTTP header construction
169
+ │ ├── format/ # Data formatting
170
+ │ │ ├── index.ts # Format barrel export
171
+ │ │ ├── attachment.ts # Attachment formatting
172
+ │ │ ├── cookie.ts # Cookie formatting
173
+ │ │ ├── date.ts # Date formatting
174
+ │ │ ├── decode.ts # Decoding utilities
175
+ │ │ ├── delta.ts # MQTT delta formatting
176
+ │ │ ├── ids.ts # ID formatting
177
+ │ │ ├── message.ts # Message formatting
178
+ │ │ ├── presence.ts # Presence formatting
179
+ │ │ ├── readTyp.ts # Read/typing formatting
180
+ │ │ ├── thread.ts # Thread formatting
181
+ │ │ └── utils.ts # General format utilities
182
+ │ ├── loginParser/ # Login response parsing
183
+ │ │ ├── index.ts # Parser barrel export
184
+ │ │ ├── autoLogin.ts # Auto-login logic
185
+ │ │ ├── helpers.ts # Parser helpers
186
+ │ │ ├── parseAndCheckLogin.ts # Main login response parser
187
+ │ │ └── textUtils.ts # Text parsing utilities
188
+ │ └── request/ # HTTP request infrastructure
189
+ │ ├── index.ts # Request barrel export
190
+ │ ├── client.ts # HTTP client setup
191
+ │ ├── config.ts # Request configuration
192
+ │ ├── defaults.ts # Default request options
193
+ │ └── helpers.ts # Request helpers
194
+
195
+ ├── types/ # Public TypeScript types
196
+ │ ├── index.ts # Type barrel export
197
+ │ ├── client.ts # FcaClientFacade, FcaClientNamespace
198
+ │ ├── core.ts # Core types (FcaID, etc.)
199
+ │ ├── core-modules.ts # Core module types
200
+ │ ├── events.ts # MqttEvent, MessageEvent, ReactionEvent, ...
201
+ │ ├── messaging.ts # Messaging types
202
+ │ ├── threads.ts # Thread types
203
+ │ └── scheduler.ts # Scheduler types
204
+
205
+ ├── global-types.d.ts # Global type declarations (Loose, etc.)
206
+ └── index.ts # Package entry — re-exports everything public
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Layer Diagram
212
+
213
+ ```
214
+ ┌───────────────────────────────────────────────────┐
215
+ │ Consumer Code │
216
+ │ (bot scripts, integrations, etc.) │
217
+ └───────────┬──────────────┬──────────────┬─────────┘
218
+ │ │ │
219
+ ┌───────▼──────┐ ┌────▼─────┐ ┌──────▼──────┐
220
+ │ MessengerBot │ │ FcaClient│ │ Flat API │
221
+ │ (app/) │ │ Facade │ │ (legacy) │
222
+ └───────┬──────┘ └────┬─────┘ └──────┬──────┘
223
+ │ │ │
224
+ └──────────────┼──────────────┘
225
+
226
+ ┌────────────▼────────────┐
227
+ │ Domain Layer │
228
+ │ messages / threads / │
229
+ │ users / account / │
230
+ │ realtime / http / │
231
+ │ scheduler │
232
+ └────────────┬────────────┘
233
+
234
+ ┌──────────────┼──────────────┐
235
+ │ │ │
236
+ ┌───────▼──────┐ ┌────▼─────┐ ┌──────▼──────┐
237
+ │ Transport │ │ Core │ │ Database │
238
+ │ http/ │ │ auth, │ │ (optional) │
239
+ │ realtime/ │ │ state, │ │ SQLite + │
240
+ │ │ │ config │ │ Sequelize │
241
+ └──────────────┘ └──────────┘ └─────────────┘
242
+ ```
243
+
244
+ ---
245
+
246
+ ## Core Layer
247
+
248
+ **`src/core/`** manages authentication, session state, configuration, and fundamental helpers that every other layer depends on.
249
+
250
+ | File | Responsibility |
251
+ |-------------------------------|-------------------------------------------------------------------|
252
+ | `auth.ts` | Entry points: `login()`, `loginLegacy()`, `loginViaAPI()`, `tokensViaAPI()` |
253
+ | `auth-helpers.ts` | Low-level auth plumbing: cookie extraction, token refresh |
254
+ | `config.ts` | Load, merge, and write `fca-config.json` |
255
+ | `login-helper.ts` | High-level login orchestration |
256
+ | `login-helper.impl.ts` | Session initialization, `ctx` and `api` creation |
257
+ | `mqtt.ts` | `listenMqtt()` — thin wrapper that delegates to `domains/realtime` |
258
+ | `options.ts` | Validate and apply `FcaOptions` onto global state |
259
+ | `request.ts` | `createRequestHelper()` — authenticated HTTP client |
260
+ | `state.ts` | `FcaContext` type, `createFcaState()`, `createApiFacade()`, `attachThreadUpdater()` |
261
+ | `thread-info-realtime-sync.ts`| Sync thread cache from realtime MQTT events |
262
+ | `update-check.ts` | Check npm registry for newer versions |
263
+
264
+ ---
265
+
266
+ ## Transport Layer
267
+
268
+ **`src/transport/`** handles raw protocol-level communication. Domain modules call into transport functions rather than making HTTP or MQTT calls directly.
269
+
270
+ ### HTTP (`transport/http/`)
271
+
272
+ | File | Purpose |
273
+ |-----------------------|---------------------------------------------------|
274
+ | `facebook.ts` | General Facebook API endpoints |
275
+ | `graphql.ts` | Execute GraphQL queries with authenticated context |
276
+ | `mercury.ts` | Mercury endpoint for message-related operations |
277
+ | `form-data.ts` | Multipart form-data POST requests |
278
+ | `upload-attachment.ts`| Upload attachments to Facebook's CDN |
279
+ | `shared-photos.ts` | Shared photos endpoint |
280
+ | `threads.ts` | Thread-specific HTTP operations |
281
+
282
+ ### Realtime (`transport/realtime/`)
283
+
284
+ | File | Purpose |
285
+ |--------------------|--------------------------------------------------------------------|
286
+ | `connect-mqtt.ts` | Establish WebSocket connection to Facebook MQTT; subscribe to topics in batch, then publish sync; handle reconnection safely |
287
+ | `get-seq-id.ts` | Fetch the latest sequence ID via GraphQL (required before listening) |
288
+ | `publish.ts` | MQTT publish helpers |
289
+ | `stream.ts` | Duplex stream adapter for the MQTT wire protocol |
290
+ | `task-response.ts` | Parse task/response payloads from MQTT frames |
291
+ | `topics.ts` | Topic string constants (`/t_ms`, `/thread_typing`, etc.) |
292
+ | `ls-requests.ts` | Build Lightspeed request payloads |
293
+
294
+ ---
295
+
296
+ ## Domain Layer
297
+
298
+ **`src/domains/`** contains all business logic organized by concern. Each domain exports a `create*Domain()` factory that returns an object of related functions.
299
+
300
+ ### Structure pattern
301
+
302
+ ```
303
+ domains/<name>/
304
+ ├── index.ts # createXxxDomain() factory
305
+ ├── <name>.types.ts # Domain-specific TypeScript types
306
+ ├── commands/ # Write operations (mutations)
307
+ │ ├── do-something.ts
308
+ │ └── ...
309
+ └── queries/ # Read operations
310
+ ├── get-something.ts
311
+ └── ...
312
+ ```
313
+
314
+ ### Domains
315
+
316
+ | Domain | Commands | Queries |
317
+ |-------------|--------------------------------------------------------------------------------------------|------------------------------------------------------------------|
318
+ | `messages` | send, edit, unsend, delete, setReaction, sendTyping, markRead, markDelivered, markSeen, markReadAll, upload, forward, shareContact, changeColor, changeEmoji | getMessage, getEmojiUrl, resolvePhotoUrl, getThreadColors |
319
+ | `threads` | createGroup, addUser, removeUser, changeAdmin, changeImage, changeNickname, setTitle, createPoll, createThemeAI, delete, archive, mute, handleRequest | getInfo, getList, getHistory, getPictures, getThemePictures, search |
320
+ | `users` | — | getInfo, getInfoV2, getID, getFriendsList |
321
+ | `account` | changeAvatar, changeBio, changeBlocked, handleFriendReq, unfriend, setPostReaction, refreshDtsg, logout, addModule, enableAutoSave | getCurrentUserID |
322
+ | `realtime` | *(listener lifecycle, emit-auth, middleware)* | *(parse-delta)* |
323
+ | `http` | httpPost, postFormData | httpGet |
324
+ | `scheduler` | *(scheduling primitives)* | — |
325
+
326
+ ---
327
+
328
+ ## Application Layer
329
+
330
+ **`src/app/`** provides the high-level constructs that consumers interact with directly.
331
+
332
+ | File | What it does |
333
+ |-------------------------|-----------------------------------------------------------------------------|
334
+ | `attach-legacy-api.ts` | Attaches all flat methods + domain namespaces onto the `api` object |
335
+ | `create-client.ts` | `createFcaClient(api)` — wraps flat API into a `FcaClientFacade` |
336
+ | `messenger-bot.ts` | `MessengerBot` class — EventEmitter + composer middleware engine |
337
+ | `messenger-context.ts` | `MessengerContext` — per-message context with `reply()` / `replyAsync()` |
338
+
339
+ ---
340
+
341
+ ## Compatibility Layer
342
+
343
+ **`src/compat/`** ensures older code keeps working.
344
+
345
+ | File | Purpose |
346
+ |--------------------|---------------------------------------------------------------|
347
+ | `api-registry.ts` | `attachClientFacade(ctx)` — adds `ctx.client` lazily |
348
+ | `callbackify.ts` | Convert promise-returning functions to Node-style callbacks |
349
+ | `legacy-promise.ts`| Wrap callbacks in a Promise for dual-mode support |
350
+
351
+ ---
352
+
353
+ ## Database Layer
354
+
355
+ **`src/database/`** is entirely optional. When SQLite + Sequelize are available:
356
+
357
+ - **Models:** `Thread` (stores JSON thread data + `messageCount`) and `User` (stores user profile cache).
358
+ - **`threadData.ts`** / **`userData.ts`** provide a data access layer with freshness-based reads and writes.
359
+ - **`helpers.ts`** handles Sequelize initialization and model synchronization.
360
+
361
+ When the database is absent, all cache features gracefully degrade to in-memory or no-op behavior.
362
+
363
+ ---
364
+
365
+ ## Utilities
366
+
367
+ **`src/utils/`** contains cross-cutting concerns:
368
+
369
+ | Subdirectory / File | Purpose |
370
+ |---------------------|-------------------------------------------------------------|
371
+ | `format/` | Transform raw Facebook data into normalized structures (attachments, deltas, messages, threads, presence, IDs, dates) |
372
+ | `loginParser/` | Parse login HTTP responses, handle auto-login, extract tokens |
373
+ | `request/` | HTTP client setup, default headers, proxy configuration |
374
+ | `broadcast.ts` | Broadcast helper for multi-thread messaging |
375
+ | `client.ts` | Client-level utility functions |
376
+ | `constants.ts` | Shared constant values |
377
+ | `cookies.ts` | Cookie parsing and manipulation |
378
+ | `headers.ts` | HTTP header construction for Facebook API requests |
379
+
380
+ ---
381
+
382
+ ## Type System
383
+
384
+ **`src/types/`** contains all publicly exported TypeScript interfaces and type aliases:
385
+
386
+ | File | Contents |
387
+ |------------------|------------------------------------------------------------|
388
+ | `client.ts` | `FcaClientFacade`, `FcaClientNamespace`, `LegacyApiLike` |
389
+ | `core.ts` | `FcaID` and other primitive types |
390
+ | `core-modules.ts`| Core module interface types |
391
+ | `events.ts` | `MqttEvent` union, `MessageEvent`, `ReactionEvent`, `TypingEvent`, etc. |
392
+ | `messaging.ts` | Messaging-related types |
393
+ | `threads.ts` | Thread-related types |
394
+ | `scheduler.ts` | Scheduler types |
395
+
396
+ `src/global-types.d.ts` declares the global `Loose` type (alias for `any`) used throughout the codebase for dynamic Facebook API payloads.
397
+
398
+ ---
399
+
400
+ ## Realtime Subsystem (Deep Dive)
401
+
402
+ ### Connection lifecycle
403
+
404
+ 1. **`domains/realtime/listener.ts`** orchestrates the full lifecycle:
405
+ - Calls `getSeqID` (GraphQL) to obtain the latest sequence number.
406
+ - Invokes `listenMqtt` which delegates to `transport/realtime/connect-mqtt.ts`.
407
+ - Manages auto-cycle (periodic reconnection) and retry logic with debounced `getSeqID`.
408
+
409
+ 2. **`transport/realtime/connect-mqtt.ts`** handles the wire protocol:
410
+ - Opens a WebSocket to Facebook's MQTT endpoint.
411
+ - Subscribes to topics in a batch (`/t_ms`, `/thread_typing`, `/orca_presence`, etc.).
412
+ - Only after subscriptions complete does it publish the sync queue.
413
+ - On disconnect, the old client is fully cleaned up before creating a new one.
414
+
415
+ 3. **`domains/realtime/parse-delta.ts`** transforms raw MQTT deltas into typed event objects and dispatches them through the callback chain. It also fires `emitThreadInfoEvent` to trigger cache synchronization.
416
+
417
+ ### Topics
418
+
419
+ Defined in `transport/realtime/topics.ts`. Key topics include thread messages (`/t_ms`), typing indicators (`/thread_typing`), presence (`/orca_presence`), and Lightspeed requests (`/ls_req`, `/ls_resp`).
420
+
421
+ ---
422
+
423
+ ## MessengerBot (Deep Dive)
424
+
425
+ ### Event dispatch
426
+
427
+ `MessengerBot` listens on the MQTT emitter's `"message"` event and maps each `MqttEvent` to named channels:
428
+
429
+ - `message` / `messageCreate` for chat messages and replies
430
+ - `messageReactionAdd`, `messageDelete`, `typingStart`, `typingStop`, `threadUpdate`, `ready`, `shardReady`
431
+ - `raw` / `update` for every delta
432
+
433
+ The `emitIf` helper only fires `emit()` when there are active listeners, keeping overhead minimal.
434
+
435
+ ### Composer engine
436
+
437
+ The composer is a Koa-style middleware chain that runs only for `message` and `message_reply` events. Execution order:
438
+
439
+ 1. Global `use()` middlewares in registration order.
440
+ 2. `command()` handlers check for `{prefix}{name}` at the start of the message.
441
+ 3. `hears()` handlers match by regex or substring.
442
+ 4. If any middleware throws, the `catch()` handler receives the error.
443
+
444
+ Middleware is dispatched via `queueMicrotask` to avoid blocking the MQTT event loop.
445
+
446
+ ---
447
+
448
+ ## Thread Cache & Realtime Sync
449
+
450
+ **`core/thread-info-realtime-sync.ts`** subscribes to MQTT events of type `"event"` and performs:
451
+
452
+ | Log message type | Action |
453
+ |-----------------------------------|---------------------------------------------------------|
454
+ | `log:subscribe` | Add participant to cache, fetch fresh `userInfo` |
455
+ | `log:unsubscribe` | Remove participant from cache |
456
+ | Thread metadata changes | Invalidate the cached `data` (set to `null`) |
457
+ | Unknown/unhandled types | Invalidate as a safety measure |
458
+
459
+ This keeps the SQLite cache consistent with the actual thread state without requiring periodic full refetches.
460
+
461
+ ---
462
+
463
+ ## Related Documentation
464
+
465
+ - [README.md](../README.md) — Installation and quick start guide
466
+ - [DOCS.md](./DOCS.md) — Full API reference and usage guide
467
+ - Version history: [`CHANGELOG.md`](https://github.com/dongp06/fca-unofficial/blob/main/CHANGELOG.md) in the repository (not shipped in the npm tarball).