@lazyneoaz/metachat 5.1.1 → 6.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.
package/dist/index.d.mts CHANGED
@@ -831,6 +831,63 @@ declare function retryDelay(attempt: number, baseMs?: number, capMs?: number): n
831
831
  /** Mark a heavy action so the next request gets a longer pause. */
832
832
  declare function noteAction(ctx: any, weight?: "light" | "normal" | "heavy"): void;
833
833
 
834
+ /**
835
+ * Realtime event middleware system (reference `api.useMiddleware` etc.).
836
+ *
837
+ * A middleware is `(event, next) => void | Promise<void>`. Middleware run in
838
+ * registration order; call `next()` to continue, `next(err)` to abort with an
839
+ * error, or `next(false)` to drop the event. Returning false/null from a
840
+ * middleware drops the event.
841
+ */
842
+ type MiddlewareCallback = (err: any, event: any) => void;
843
+ type NextFunction = (arg?: any) => void;
844
+ type MiddlewareFunction = (event: any, next: NextFunction) => any;
845
+ interface RealtimeMiddlewareSystem {
846
+ use: (middleware: string | MiddlewareFunction, fn?: MiddlewareFunction) => () => void;
847
+ remove: (identifier: string | MiddlewareFunction) => boolean;
848
+ clear: () => void;
849
+ list: () => string[];
850
+ setEnabled: (name: string, enabled: boolean) => boolean;
851
+ process: (event: any, finalCallback: MiddlewareCallback) => void;
852
+ wrapCallback: (callback: MiddlewareCallback) => MiddlewareCallback;
853
+ readonly count: number;
854
+ }
855
+ declare function createRealtimeMiddlewareSystem(logger?: (text: string, type?: string) => void): RealtimeMiddlewareSystem;
856
+
857
+ declare function createScheduler(sendMessage: (...args: any[]) => any, logger?: (m: string, l?: string) => void): {
858
+ scheduleMessage: (message: any, threadID: any, when: Date | number | string, options?: any) => string;
859
+ cancelScheduledMessage: (id: string) => boolean;
860
+ getScheduledMessage: (id: string) => {
861
+ id: string;
862
+ message: any;
863
+ threadID: any;
864
+ timestamp: number;
865
+ createdAt: number;
866
+ options: {
867
+ replyMessageID?: string;
868
+ isGroup?: boolean;
869
+ callback?: any;
870
+ };
871
+ timeUntilSend: number;
872
+ };
873
+ listScheduledMessages: () => {
874
+ id: string;
875
+ message: any;
876
+ threadID: any;
877
+ timestamp: number;
878
+ createdAt: number;
879
+ options: {
880
+ replyMessageID?: string;
881
+ isGroup?: boolean;
882
+ callback?: any;
883
+ };
884
+ timeUntilSend: number;
885
+ }[];
886
+ cancelAllScheduledMessages: () => number;
887
+ getScheduledCount: () => number;
888
+ destroy: () => number;
889
+ };
890
+
834
891
  /**
835
892
  * Account safety: a per-session request budget and circuit breaker.
836
893
  *
@@ -1154,7 +1211,7 @@ interface RealtimeHealthState {
1154
1211
  */
1155
1212
  declare class RealtimeHealth {
1156
1213
  private now;
1157
- private frames;
1214
+ private frameCount;
1158
1215
  private lastFrameAt;
1159
1216
  private connectedAt;
1160
1217
  private probes;
@@ -1175,15 +1232,19 @@ declare class RealtimeHealth {
1175
1232
  /** Record an active ping being sent. */
1176
1233
  notePing(): void;
1177
1234
  sinceLastFrame(): number;
1235
+ /** Total inbound packets observed on this connection generation. */
1236
+ get frames(): number;
1178
1237
  /**
1179
1238
  * Decide what to do about the current socket.
1180
1239
  *
1181
1240
  * - `disconnected` — the transport already knows it is down; reconnect.
1182
- * - `dead` — connected on paper, silent well past the window, and repeated
1183
- * pings raised no traffic at all; reconnect.
1184
- * - `suspect` — silent past the window but a ping was only just sent; wait.
1241
+ * - `dead` — connected on paper and silent past the window; the supervisor
1242
+ * runs a round-trip probe and recycles it only if the probe fails.
1185
1243
  * - `quiet` — silent but inside the window; normal.
1186
1244
  * - `healthy` — recent traffic.
1245
+ *
1246
+ * Silence alone is never proof of death: an idle-but-healthy socket is
1247
+ * frame-silent for hours. The probe is what distinguishes the two.
1187
1248
  */
1188
1249
  verdict(connected: boolean): RealtimeHealthState["verdict"];
1189
1250
  /** A snapshot for diagnostics. */
@@ -1196,8 +1257,12 @@ interface RealtimeSupervisorOptions {
1196
1257
  intervalMs?: number;
1197
1258
  /** Ask the transport to reconnect (fresh socket) — must be idempotent. */
1198
1259
  reconnect: (reason: string) => void;
1199
- /** Send an MQTT ping. Return false if it could not be sent. */
1200
- ping?: () => boolean;
1260
+ /**
1261
+ * Active liveness probe. Resolve true only when the broker's reply was
1262
+ * observed (e.g. a PINGRESP or app-level round-trip). Returning true marks
1263
+ * the socket alive; false allows it to be recycled.
1264
+ */
1265
+ ping?: () => boolean | Promise<boolean>;
1201
1266
  /** Whether the transport currently reports connected. */
1202
1267
  isConnected: () => boolean;
1203
1268
  /** Observe verdict changes (logging). */
@@ -1216,7 +1281,7 @@ interface RealtimeSupervisorOptions {
1216
1281
  declare function startRealtimeSupervisor(options: RealtimeSupervisorOptions): {
1217
1282
  health: RealtimeHealth;
1218
1283
  stop: () => void;
1219
- checkNow: () => RealtimeHealthState;
1284
+ checkNow: () => Promise<RealtimeHealthState>;
1220
1285
  };
1221
1286
 
1222
1287
  /** Extract the `CurrentUserInitialData` object from a profile HTML document. */
@@ -1241,13 +1306,7 @@ interface AcquireResult {
1241
1306
  /** Number of cookies written into the jar. */
1242
1307
  loaded: number;
1243
1308
  }
1244
- /**
1245
- * Acquire session cookies into `jar`.
1246
- *
1247
- * Accepts an appState array, a `;`-joined cookie string, or email+password
1248
- * credentials. Throws only when *no* usable source was provided — an individual
1249
- * bad cookie never fails the whole load.
1250
- */
1309
+
1251
1310
  declare function acquireCookies(jar: any, credentials: LoginCredentials$1, globalOptions: LoginOptions$1): Promise<AcquireResult>;
1252
1311
 
1253
1312
  interface UploadedAttachment {
@@ -1276,6 +1335,11 @@ declare function normalizeReaction(value: unknown, options?: {
1276
1335
  /**
1277
1336
  * Facebook "non-critical" errors (e.g. 1357004) are retryable and must not be
1278
1337
  * treated as auth failures or checkpoints.
1338
+ *
1339
+ * `1357001` ("Facebook blocked the login") and `1357031` (document token
1340
+ * invalid) are deliberately excluded: they mean the session is dead or the
1341
+ * tokens are stale, so retrying the same call hides a real problem instead of
1342
+ * repairing it.
1279
1343
  */
1280
1344
  declare function isNonCriticalError(value: any): boolean;
1281
1345
  declare function retryOnNonCritical<T = any>(operation: () => Promise<T>, refresh: () => void | Promise<void>): Promise<T>;
@@ -1290,4 +1354,4 @@ declare const _default: typeof login$1 & {
1290
1354
  default: typeof login$1;
1291
1355
  };
1292
1356
 
1293
- export { type API, type AddedStickerPackInfo, type AiTheme, type AnyAttachment, type ApiContext, type ApiInternal, type Attachment, type AudioAttachment, type BrowserProfile, CORE_REACTIONS, type Callback, type CommentMessage, type CommentResult, type Coordinates, type DefaultFuncs, type EmojiEvent, type Event, type FileAttachment, type GroupNameEvent, type ListenEvent, type LivenessHandle, type LivenessState, type LoginCredentials, type LoginOptions, type Mention, type Message, type MessageID, type MessageObject, type MessageReply, type MusicTag, type MusicTrack, type NicknameEvent, PING_GRACE_MS, type PhotoAttachment, REACTION_ALIASES, type Reaction, RealtimeHealth, type RealtimeHealthState, type RecoveryEvent, type RecoveryOptions, type RecoveryRuntime, type RecoveryState, RecoverySupervisor, SILENT_WINDOW_MS, type SearchMusicOptions, type SearchMusicResult, type ShareAttachment, type ShareResult, type StickerAttachment, type StickerInfo, type StickerPackInfo, type ThreadID, type ThreadInfo, type ThreadThemeEvent, type TypingIndicator, type UnsendMessageEvent, type UserID, type UserInfo, type VideoAttachment, type WarmUpResult, acquireCookies, applySetCookie, awaitProactiveSlot, canActProactively, cleanJsonResponse, collectSessionCookies, _default as default, defaultBrowserProfile, ensureCometTokens, extractCookies, extractCookiesFromBody, extractCookiesFromJar, extractCookiesFromSetCookie, extractCurrentUser, getFingerprintParams, getHeaders, getWebSocketHeaders, hasAuthenticatedSession, humanDelay, invalidateCometTokens, isAuthFailure, isBreakerOpen, isLoggedOutDocument, isNonCriticalError, isReactionEmoji, isStaleTokenError, login$1 as login, missingSessionCookies, normalizeBrowserProfile, normalizeReaction, noteAction, noteAuthFailure, noteCheckpoint, noteRateLimit, paceRequest, publicTypes, randomUserAgent, refreshSessionCookies, repairSession, reserveRequest, resetBreaker, resolveProfile, retryDelay, retryOnNonCritical, safetySnapshot, sleep, startLiveness, startRealtimeSupervisor, startRecovery, tripBreaker, uploadGroupImage, uploadMercuryAttachment, warmUpSession, withCometTokens, withSessionRetry };
1357
+ export { type API, type AddedStickerPackInfo, type AiTheme, type AnyAttachment, type ApiContext, type ApiInternal, type Attachment, type AudioAttachment, type BrowserProfile, CORE_REACTIONS, type Callback, type CommentMessage, type CommentResult, type Coordinates, type DefaultFuncs, type EmojiEvent, type Event, type FileAttachment, type GroupNameEvent, type ListenEvent, type LivenessHandle, type LivenessState, type LoginCredentials, type LoginOptions, type Mention, type Message, type MessageID, type MessageObject, type MessageReply, type MusicTag, type MusicTrack, type NicknameEvent, PING_GRACE_MS, type PhotoAttachment, REACTION_ALIASES, type Reaction, RealtimeHealth, type RealtimeHealthState, type RecoveryEvent, type RecoveryOptions, type RecoveryRuntime, type RecoveryState, RecoverySupervisor, SILENT_WINDOW_MS, type SearchMusicOptions, type SearchMusicResult, type ShareAttachment, type ShareResult, type StickerAttachment, type StickerInfo, type StickerPackInfo, type ThreadID, type ThreadInfo, type ThreadThemeEvent, type TypingIndicator, type UnsendMessageEvent, type UserID, type UserInfo, type VideoAttachment, type WarmUpResult, acquireCookies, applySetCookie, awaitProactiveSlot, canActProactively, cleanJsonResponse, collectSessionCookies, createRealtimeMiddlewareSystem, createScheduler, _default as default, defaultBrowserProfile, ensureCometTokens, extractCookies, extractCookiesFromBody, extractCookiesFromJar, extractCookiesFromSetCookie, extractCurrentUser, getFingerprintParams, getHeaders, getWebSocketHeaders, hasAuthenticatedSession, humanDelay, invalidateCometTokens, isAuthFailure, isBreakerOpen, isLoggedOutDocument, isNonCriticalError, isReactionEmoji, isStaleTokenError, login$1 as login, missingSessionCookies, normalizeBrowserProfile, normalizeReaction, noteAction, noteAuthFailure, noteCheckpoint, noteRateLimit, paceRequest, publicTypes, randomUserAgent, refreshSessionCookies, repairSession, reserveRequest, resetBreaker, resolveProfile, retryDelay, retryOnNonCritical, safetySnapshot, sleep, startLiveness, startRealtimeSupervisor, startRecovery, tripBreaker, uploadGroupImage, uploadMercuryAttachment, warmUpSession, withCometTokens, withSessionRetry };
package/dist/index.d.ts CHANGED
@@ -831,6 +831,63 @@ declare function retryDelay(attempt: number, baseMs?: number, capMs?: number): n
831
831
  /** Mark a heavy action so the next request gets a longer pause. */
832
832
  declare function noteAction(ctx: any, weight?: "light" | "normal" | "heavy"): void;
833
833
 
834
+ /**
835
+ * Realtime event middleware system (reference `api.useMiddleware` etc.).
836
+ *
837
+ * A middleware is `(event, next) => void | Promise<void>`. Middleware run in
838
+ * registration order; call `next()` to continue, `next(err)` to abort with an
839
+ * error, or `next(false)` to drop the event. Returning false/null from a
840
+ * middleware drops the event.
841
+ */
842
+ type MiddlewareCallback = (err: any, event: any) => void;
843
+ type NextFunction = (arg?: any) => void;
844
+ type MiddlewareFunction = (event: any, next: NextFunction) => any;
845
+ interface RealtimeMiddlewareSystem {
846
+ use: (middleware: string | MiddlewareFunction, fn?: MiddlewareFunction) => () => void;
847
+ remove: (identifier: string | MiddlewareFunction) => boolean;
848
+ clear: () => void;
849
+ list: () => string[];
850
+ setEnabled: (name: string, enabled: boolean) => boolean;
851
+ process: (event: any, finalCallback: MiddlewareCallback) => void;
852
+ wrapCallback: (callback: MiddlewareCallback) => MiddlewareCallback;
853
+ readonly count: number;
854
+ }
855
+ declare function createRealtimeMiddlewareSystem(logger?: (text: string, type?: string) => void): RealtimeMiddlewareSystem;
856
+
857
+ declare function createScheduler(sendMessage: (...args: any[]) => any, logger?: (m: string, l?: string) => void): {
858
+ scheduleMessage: (message: any, threadID: any, when: Date | number | string, options?: any) => string;
859
+ cancelScheduledMessage: (id: string) => boolean;
860
+ getScheduledMessage: (id: string) => {
861
+ id: string;
862
+ message: any;
863
+ threadID: any;
864
+ timestamp: number;
865
+ createdAt: number;
866
+ options: {
867
+ replyMessageID?: string;
868
+ isGroup?: boolean;
869
+ callback?: any;
870
+ };
871
+ timeUntilSend: number;
872
+ };
873
+ listScheduledMessages: () => {
874
+ id: string;
875
+ message: any;
876
+ threadID: any;
877
+ timestamp: number;
878
+ createdAt: number;
879
+ options: {
880
+ replyMessageID?: string;
881
+ isGroup?: boolean;
882
+ callback?: any;
883
+ };
884
+ timeUntilSend: number;
885
+ }[];
886
+ cancelAllScheduledMessages: () => number;
887
+ getScheduledCount: () => number;
888
+ destroy: () => number;
889
+ };
890
+
834
891
  /**
835
892
  * Account safety: a per-session request budget and circuit breaker.
836
893
  *
@@ -1154,7 +1211,7 @@ interface RealtimeHealthState {
1154
1211
  */
1155
1212
  declare class RealtimeHealth {
1156
1213
  private now;
1157
- private frames;
1214
+ private frameCount;
1158
1215
  private lastFrameAt;
1159
1216
  private connectedAt;
1160
1217
  private probes;
@@ -1175,15 +1232,19 @@ declare class RealtimeHealth {
1175
1232
  /** Record an active ping being sent. */
1176
1233
  notePing(): void;
1177
1234
  sinceLastFrame(): number;
1235
+ /** Total inbound packets observed on this connection generation. */
1236
+ get frames(): number;
1178
1237
  /**
1179
1238
  * Decide what to do about the current socket.
1180
1239
  *
1181
1240
  * - `disconnected` — the transport already knows it is down; reconnect.
1182
- * - `dead` — connected on paper, silent well past the window, and repeated
1183
- * pings raised no traffic at all; reconnect.
1184
- * - `suspect` — silent past the window but a ping was only just sent; wait.
1241
+ * - `dead` — connected on paper and silent past the window; the supervisor
1242
+ * runs a round-trip probe and recycles it only if the probe fails.
1185
1243
  * - `quiet` — silent but inside the window; normal.
1186
1244
  * - `healthy` — recent traffic.
1245
+ *
1246
+ * Silence alone is never proof of death: an idle-but-healthy socket is
1247
+ * frame-silent for hours. The probe is what distinguishes the two.
1187
1248
  */
1188
1249
  verdict(connected: boolean): RealtimeHealthState["verdict"];
1189
1250
  /** A snapshot for diagnostics. */
@@ -1196,8 +1257,12 @@ interface RealtimeSupervisorOptions {
1196
1257
  intervalMs?: number;
1197
1258
  /** Ask the transport to reconnect (fresh socket) — must be idempotent. */
1198
1259
  reconnect: (reason: string) => void;
1199
- /** Send an MQTT ping. Return false if it could not be sent. */
1200
- ping?: () => boolean;
1260
+ /**
1261
+ * Active liveness probe. Resolve true only when the broker's reply was
1262
+ * observed (e.g. a PINGRESP or app-level round-trip). Returning true marks
1263
+ * the socket alive; false allows it to be recycled.
1264
+ */
1265
+ ping?: () => boolean | Promise<boolean>;
1201
1266
  /** Whether the transport currently reports connected. */
1202
1267
  isConnected: () => boolean;
1203
1268
  /** Observe verdict changes (logging). */
@@ -1216,7 +1281,7 @@ interface RealtimeSupervisorOptions {
1216
1281
  declare function startRealtimeSupervisor(options: RealtimeSupervisorOptions): {
1217
1282
  health: RealtimeHealth;
1218
1283
  stop: () => void;
1219
- checkNow: () => RealtimeHealthState;
1284
+ checkNow: () => Promise<RealtimeHealthState>;
1220
1285
  };
1221
1286
 
1222
1287
  /** Extract the `CurrentUserInitialData` object from a profile HTML document. */
@@ -1241,13 +1306,7 @@ interface AcquireResult {
1241
1306
  /** Number of cookies written into the jar. */
1242
1307
  loaded: number;
1243
1308
  }
1244
- /**
1245
- * Acquire session cookies into `jar`.
1246
- *
1247
- * Accepts an appState array, a `;`-joined cookie string, or email+password
1248
- * credentials. Throws only when *no* usable source was provided — an individual
1249
- * bad cookie never fails the whole load.
1250
- */
1309
+
1251
1310
  declare function acquireCookies(jar: any, credentials: LoginCredentials$1, globalOptions: LoginOptions$1): Promise<AcquireResult>;
1252
1311
 
1253
1312
  interface UploadedAttachment {
@@ -1276,6 +1335,11 @@ declare function normalizeReaction(value: unknown, options?: {
1276
1335
  /**
1277
1336
  * Facebook "non-critical" errors (e.g. 1357004) are retryable and must not be
1278
1337
  * treated as auth failures or checkpoints.
1338
+ *
1339
+ * `1357001` ("Facebook blocked the login") and `1357031` (document token
1340
+ * invalid) are deliberately excluded: they mean the session is dead or the
1341
+ * tokens are stale, so retrying the same call hides a real problem instead of
1342
+ * repairing it.
1279
1343
  */
1280
1344
  declare function isNonCriticalError(value: any): boolean;
1281
1345
  declare function retryOnNonCritical<T = any>(operation: () => Promise<T>, refresh: () => void | Promise<void>): Promise<T>;
@@ -1290,4 +1354,4 @@ declare const _default: typeof login$1 & {
1290
1354
  default: typeof login$1;
1291
1355
  };
1292
1356
 
1293
- export { type API, type AddedStickerPackInfo, type AiTheme, type AnyAttachment, type ApiContext, type ApiInternal, type Attachment, type AudioAttachment, type BrowserProfile, CORE_REACTIONS, type Callback, type CommentMessage, type CommentResult, type Coordinates, type DefaultFuncs, type EmojiEvent, type Event, type FileAttachment, type GroupNameEvent, type ListenEvent, type LivenessHandle, type LivenessState, type LoginCredentials, type LoginOptions, type Mention, type Message, type MessageID, type MessageObject, type MessageReply, type MusicTag, type MusicTrack, type NicknameEvent, PING_GRACE_MS, type PhotoAttachment, REACTION_ALIASES, type Reaction, RealtimeHealth, type RealtimeHealthState, type RecoveryEvent, type RecoveryOptions, type RecoveryRuntime, type RecoveryState, RecoverySupervisor, SILENT_WINDOW_MS, type SearchMusicOptions, type SearchMusicResult, type ShareAttachment, type ShareResult, type StickerAttachment, type StickerInfo, type StickerPackInfo, type ThreadID, type ThreadInfo, type ThreadThemeEvent, type TypingIndicator, type UnsendMessageEvent, type UserID, type UserInfo, type VideoAttachment, type WarmUpResult, acquireCookies, applySetCookie, awaitProactiveSlot, canActProactively, cleanJsonResponse, collectSessionCookies, _default as default, defaultBrowserProfile, ensureCometTokens, extractCookies, extractCookiesFromBody, extractCookiesFromJar, extractCookiesFromSetCookie, extractCurrentUser, getFingerprintParams, getHeaders, getWebSocketHeaders, hasAuthenticatedSession, humanDelay, invalidateCometTokens, isAuthFailure, isBreakerOpen, isLoggedOutDocument, isNonCriticalError, isReactionEmoji, isStaleTokenError, login$1 as login, missingSessionCookies, normalizeBrowserProfile, normalizeReaction, noteAction, noteAuthFailure, noteCheckpoint, noteRateLimit, paceRequest, publicTypes, randomUserAgent, refreshSessionCookies, repairSession, reserveRequest, resetBreaker, resolveProfile, retryDelay, retryOnNonCritical, safetySnapshot, sleep, startLiveness, startRealtimeSupervisor, startRecovery, tripBreaker, uploadGroupImage, uploadMercuryAttachment, warmUpSession, withCometTokens, withSessionRetry };
1357
+ export { type API, type AddedStickerPackInfo, type AiTheme, type AnyAttachment, type ApiContext, type ApiInternal, type Attachment, type AudioAttachment, type BrowserProfile, CORE_REACTIONS, type Callback, type CommentMessage, type CommentResult, type Coordinates, type DefaultFuncs, type EmojiEvent, type Event, type FileAttachment, type GroupNameEvent, type ListenEvent, type LivenessHandle, type LivenessState, type LoginCredentials, type LoginOptions, type Mention, type Message, type MessageID, type MessageObject, type MessageReply, type MusicTag, type MusicTrack, type NicknameEvent, PING_GRACE_MS, type PhotoAttachment, REACTION_ALIASES, type Reaction, RealtimeHealth, type RealtimeHealthState, type RecoveryEvent, type RecoveryOptions, type RecoveryRuntime, type RecoveryState, RecoverySupervisor, SILENT_WINDOW_MS, type SearchMusicOptions, type SearchMusicResult, type ShareAttachment, type ShareResult, type StickerAttachment, type StickerInfo, type StickerPackInfo, type ThreadID, type ThreadInfo, type ThreadThemeEvent, type TypingIndicator, type UnsendMessageEvent, type UserID, type UserInfo, type VideoAttachment, type WarmUpResult, acquireCookies, applySetCookie, awaitProactiveSlot, canActProactively, cleanJsonResponse, collectSessionCookies, createRealtimeMiddlewareSystem, createScheduler, _default as default, defaultBrowserProfile, ensureCometTokens, extractCookies, extractCookiesFromBody, extractCookiesFromJar, extractCookiesFromSetCookie, extractCurrentUser, getFingerprintParams, getHeaders, getWebSocketHeaders, hasAuthenticatedSession, humanDelay, invalidateCometTokens, isAuthFailure, isBreakerOpen, isLoggedOutDocument, isNonCriticalError, isReactionEmoji, isStaleTokenError, login$1 as login, missingSessionCookies, normalizeBrowserProfile, normalizeReaction, noteAction, noteAuthFailure, noteCheckpoint, noteRateLimit, paceRequest, publicTypes, randomUserAgent, refreshSessionCookies, repairSession, reserveRequest, resetBreaker, resolveProfile, retryDelay, retryOnNonCritical, safetySnapshot, sleep, startLiveness, startRealtimeSupervisor, startRecovery, tripBreaker, uploadGroupImage, uploadMercuryAttachment, warmUpSession, withCometTokens, withSessionRetry };