@oxidezap/baileyrs 0.3.9 → 0.3.11

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 (68) hide show
  1. package/README.md +29 -0
  2. package/lib/Bridge/schema.js +57 -16
  3. package/lib/Bridge/types.d.ts +26 -5
  4. package/lib/Compatibility/auth-state.js +2 -11
  5. package/lib/Compatibility/group-metadata.js +2 -2
  6. package/lib/Compatibility/host-auth-state.js +2 -0
  7. package/lib/Compatibility/internal/auth-state.js +6 -0
  8. package/lib/Compatibility/internal/host-auth-state.js +3 -0
  9. package/lib/Compatibility/legacy-store/adapter.js +137 -3
  10. package/lib/Compatibility/legacy-store/codecs/basic.js +5 -8
  11. package/lib/Compatibility/legacy-store/multi-file.d.ts +12 -1
  12. package/lib/Compatibility/legacy-store/multi-file.js +37 -25
  13. package/lib/Compatibility/legacy-store/record-files.d.ts +3 -0
  14. package/lib/Compatibility/legacy-store/record-files.js +5 -0
  15. package/lib/Compatibility/legacy-store/rollback.d.ts +8 -0
  16. package/lib/Compatibility/legacy-store/rollback.js +16 -0
  17. package/lib/Compatibility/legacy-store/snapshot.d.ts +7 -0
  18. package/lib/Compatibility/legacy-store/snapshot.js +53 -0
  19. package/lib/Compatibility/legacy-store/types.d.ts +4 -1
  20. package/lib/Compatibility/newsletter-results.d.ts +2 -3
  21. package/lib/Compatibility/newsletter-results.js +3 -3
  22. package/lib/Compatibility/reachout.d.ts +17 -0
  23. package/lib/Compatibility/reachout.js +47 -0
  24. package/lib/Socket/chat-actions.js +1 -1
  25. package/lib/Socket/communities.js +10 -5
  26. package/lib/Socket/core.js +10 -3
  27. package/lib/Socket/events-core.js +19 -10
  28. package/lib/Socket/groups.js +10 -5
  29. package/lib/Socket/index.d.ts +3 -717
  30. package/lib/Socket/newsletter.d.ts +3 -3
  31. package/lib/Socket/newsletter.js +5 -5
  32. package/lib/Socket/reachout.d.ts +1 -21
  33. package/lib/Socket/reachout.js +1 -49
  34. package/lib/Types/Auth.d.ts +5 -0
  35. package/lib/Types/Events.d.ts +6 -1
  36. package/lib/Utils/atomic-store.d.ts +20 -0
  37. package/lib/Utils/atomic-store.js +116 -0
  38. package/lib/Utils/durable-directory.d.ts +3 -0
  39. package/lib/Utils/durable-directory.js +35 -0
  40. package/lib/Utils/flush-deadline.d.ts +19 -0
  41. package/lib/Utils/flush-deadline.js +97 -0
  42. package/lib/Utils/index.d.ts +1 -0
  43. package/lib/Utils/index.js +1 -0
  44. package/lib/Utils/native-auth-rollback.d.ts +14 -0
  45. package/lib/Utils/native-auth-rollback.js +17 -0
  46. package/lib/Utils/process-file-lock.d.ts +6 -0
  47. package/lib/Utils/process-file-lock.js +38 -0
  48. package/lib/Utils/snapshot-rollback-proof.d.ts +9 -0
  49. package/lib/Utils/snapshot-rollback-proof.js +43 -0
  50. package/lib/Utils/snapshot-rollback.d.ts +5 -0
  51. package/lib/Utils/snapshot-rollback.js +69 -0
  52. package/lib/Utils/snapshot-transactions.d.ts +10 -0
  53. package/lib/Utils/snapshot-transactions.js +108 -0
  54. package/lib/Utils/store-migration.d.ts +10 -0
  55. package/lib/Utils/store-migration.js +16 -0
  56. package/lib/Utils/transactional-file-store.d.ts +7 -0
  57. package/lib/Utils/transactional-file-store.js +157 -0
  58. package/lib/Utils/use-bridge-store.d.ts +3 -49
  59. package/lib/Utils/use-bridge-store.js +121 -109
  60. package/lib/Utils/use-memory-store.js +17 -4
  61. package/lib/Utils/use-multi-file-auth-state.d.ts +2 -1
  62. package/lib/Utils/use-multi-file-auth-state.js +2 -2
  63. package/lib/Utils/wrap-legacy-store.d.ts +1 -0
  64. package/lib/Utils/wrap-legacy-store.js +1 -0
  65. package/lib/host-types.d.ts +1 -15
  66. package/lib/node-surface.d.ts +2 -1
  67. package/lib/node-surface.js +2 -1
  68. package/package.json +10 -8
@@ -1,4 +1,5 @@
1
- import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';
1
+ import { legacySnapshotKeys } from './snapshot.js';
2
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
2
3
  import { join } from 'node:path';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
4
5
  import { BufferJSON } from '../../Utils/generics.js';
@@ -14,7 +15,17 @@ function safeLegacyFileName(file) {
14
15
  }
15
16
  const keyFile = (type, id) => `${type}${LegacyMultiFile.TYPE_SEPARATOR}${id}${LegacyMultiFile.EXTENSION}`;
16
17
  const isMissingFile = (error) => error instanceof Error && 'code' in error && error.code === 'ENOENT';
17
- export async function useLegacyMultiFileAuthState(folder) {
18
+ /** Load an upstream JSON auth directory using durable backend-wide transactions.
19
+ * Existing key records require an explicit offline migration:
20
+ *
21
+ * await useLegacyMultiFileAuthState(folder, { migrate: true })
22
+ *
23
+ * Stop every old writer and back up the entire directory before opting in.
24
+ * The new snapshot becomes authoritative; retained JSON files are backups.
25
+ * To hand the directory back to upstream, stop all writers and first call
26
+ * prepareLegacyAuthRollback(folder, { offline: true }).
27
+ */
28
+ export async function useLegacyMultiFileAuthState(folder, options = {}) {
18
29
  const folderInfo = await stat(folder).catch(error => {
19
30
  if (isMissingFile(error))
20
31
  return null;
@@ -39,43 +50,44 @@ export async function useLegacyMultiFileAuthState(folder) {
39
50
  const writeData = async (data, file) => {
40
51
  await writeFile(join(folder, safeLegacyFileName(file)), JSON.stringify(data, BufferJSON.replacer));
41
52
  };
42
- const removeData = async (file) => {
43
- try {
44
- await unlink(join(folder, safeLegacyFileName(file)));
45
- }
46
- catch (error) {
47
- if (!isMissingFile(error))
48
- throw error;
49
- }
50
- };
51
53
  const creds = (await readData(LegacyMultiFile.CREDS_FILE));
52
54
  if (!creds) {
53
55
  throw new Error(`no ${LegacyMultiFile.CREDS_FILE} found in legacy auth directory: ${folder}`);
54
56
  }
57
+ const rawSnapshot = await legacySnapshotKeys(folder, (type, id) => safeLegacyFileName(keyFile(type, id)), options);
58
+ // The transaction view must use the same protobuf revival as ordinary
59
+ // reads. Persisted protobuf toJSON bytes are base64 strings, not Buffers.
60
+ const normalizeKeys = (backend) => ({
61
+ get: async (type, ids) => {
62
+ const values = await backend.get(type, ids);
63
+ if (type !== LegacyStore.SYNC_KEY)
64
+ return values;
65
+ return Object.fromEntries(Object.entries(values).map(([id, value]) => [
66
+ id,
67
+ value ? proto.Message.AppStateSyncKeyData.fromObject(value) : value
68
+ ]));
69
+ },
70
+ set: data => backend.set(data),
71
+ ...(backend.bridgeTransaction
72
+ ? {
73
+ bridgeTransaction: (work) => backend.bridgeTransaction(keys => work(normalizeKeys(keys)))
74
+ }
75
+ : {})
76
+ });
77
+ const snapshot = normalizeKeys(rawSnapshot);
55
78
  return {
56
79
  state: {
57
80
  creds,
58
81
  keys: {
59
82
  get: async (type, ids) => {
60
83
  const entries = await Promise.all(ids.map(async (id) => {
61
- let value = await readData(keyFile(type, id));
62
- if (type === LegacyStore.SYNC_KEY && value) {
63
- value = proto.Message.AppStateSyncKeyData.fromObject(value);
64
- }
84
+ const value = (await snapshot.get(type, [id]))[id];
65
85
  return [id, value];
66
86
  }));
67
87
  return Object.fromEntries(entries);
68
88
  },
69
- set: async (data) => {
70
- const writes = [];
71
- for (const [type, values] of Object.entries(data)) {
72
- for (const [id, value] of Object.entries(values ?? {})) {
73
- const file = keyFile(type, id);
74
- writes.push(value == null ? removeData(file) : writeData(value, file));
75
- }
76
- }
77
- await Promise.all(writes);
78
- }
89
+ set: async (data) => await snapshot.set(data),
90
+ bridgeTransaction: snapshot.bridgeTransaction
79
91
  }
80
92
  },
81
93
  saveCreds: () => writeData(creds, LegacyMultiFile.CREDS_FILE)
@@ -0,0 +1,3 @@
1
+ /** Only reserved auth-record filenames belong to the snapshot or its rollback. */
2
+ export declare const isLegacyAuthRecordFile: (name: string) => boolean;
3
+ //# sourceMappingURL=record-files.d.ts.map
@@ -0,0 +1,5 @@
1
+ import { LegacyStore, MirrorStore, RawStore } from './constants.js';
2
+ const prefixes = [...Object.values(LegacyStore), ...Object.values(MirrorStore), ...Object.values(RawStore)].map(type => `${type}-`);
3
+ /** Only reserved auth-record filenames belong to the snapshot or its rollback. */
4
+ export const isLegacyAuthRecordFile = (name) => !/[\\/\0]/.test(name) && name.endsWith('.json') && prefixes.some(prefix => name.startsWith(prefix));
5
+ //# sourceMappingURL=record-files.js.map
@@ -0,0 +1,8 @@
1
+ /** Offline rollback only. Stop every writer first. A rejection means upstream
2
+ * must not open this directory yet. The snapshot remains authoritative until
3
+ * every legacy record/deletion is durable, then is archived for recovery.
4
+ */
5
+ export declare function prepareLegacyAuthRollback(folder: string, options: {
6
+ offline: true;
7
+ }): Promise<void>;
8
+ //# sourceMappingURL=rollback.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { exportAuthSnapshot } from '../../Utils/snapshot-rollback.js';
2
+ import { isLegacyAuthRecordFile } from './record-files.js';
3
+ /** Offline rollback only. Stop every writer first. A rejection means upstream
4
+ * must not open this directory yet. The snapshot remains authoritative until
5
+ * every legacy record/deletion is durable, then is archived for recovery.
6
+ */
7
+ export async function prepareLegacyAuthRollback(folder, options) {
8
+ if (options?.offline !== true)
9
+ throw new TypeError('legacy rollback requires { offline: true } after stopping every auth writer');
10
+ await exportAuthSnapshot(folder, 'bridge-legacy-v1.json', new Set(['legacy']), (_namespace, name) => {
11
+ if (/[\\/\0]/.test(name))
12
+ throw new Error('invalid legacy rollback filename');
13
+ return isLegacyAuthRecordFile(name) ? name : undefined;
14
+ }, isLegacyAuthRecordFile);
15
+ }
16
+ //# sourceMappingURL=rollback.js.map
@@ -0,0 +1,7 @@
1
+ import { type StoreMigrationOptions } from '../../Utils/store-migration.js';
2
+ import type { LegacyKeysStore } from './types.js';
3
+ /** All legacy and native-mirror writes share the same persistent snapshot.
4
+ * The original JSON files are migration backups after the first commit.
5
+ */
6
+ export declare const legacySnapshotKeys: (folder: string, fileName: (type: string, id: string) => string, options?: StoreMigrationOptions) => Promise<LegacyKeysStore>;
7
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1,53 @@
1
+ import { isLegacyAuthRecordFile } from './record-files.js';
2
+ import { requireOfflineMigration } from '../../Utils/store-migration.js';
3
+ import { readFile, readdir } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { createSnapshotTransactions } from '../../Utils/snapshot-transactions.js';
6
+ import { defaultSyncDir } from '../../Utils/durable-directory.js';
7
+ import { rowKey } from '../../Utils/atomic-store.js';
8
+ import { BufferJSON } from '../../Utils/generics.js';
9
+ /** All legacy and native-mirror writes share the same persistent snapshot.
10
+ * The original JSON files are migration backups after the first commit.
11
+ */
12
+ export const legacySnapshotKeys = async (folder, fileName, options = {}) => {
13
+ await requireOfflineMigration(folder, 'bridge-legacy-v1.json', isLegacyAuthRecordFile, options);
14
+ const store = createSnapshotTransactions(folder, 'bridge-legacy-v1.json', new Set(['legacy']), async () => {
15
+ await requireOfflineMigration(folder, 'bridge-legacy-v1.json', isLegacyAuthRecordFile, options);
16
+ const rows = new Map();
17
+ for (const name of await readdir(folder)) {
18
+ if (!isLegacyAuthRecordFile(name))
19
+ continue;
20
+ rows.set(rowKey('legacy', name), await readFile(join(folder, name)));
21
+ }
22
+ return rows;
23
+ }, defaultSyncDir);
24
+ const decode = (bytes) => bytes ? JSON.parse(Buffer.from(bytes).toString(), BufferJSON.reviver) : null;
25
+ const transactionView = (rows, mutated) => ({
26
+ get: async (type, ids) => Object.fromEntries(ids.map(id => [id, decode(rows.get(rowKey('legacy', fileName(type, id))))])),
27
+ set: async (data) => {
28
+ for (const [type, values] of Object.entries(data))
29
+ for (const [id, value] of Object.entries(values ?? {})) {
30
+ const key = rowKey('legacy', fileName(type, id));
31
+ mutated();
32
+ if (value == null)
33
+ rows.delete(key);
34
+ else
35
+ rows.set(key, Buffer.from(JSON.stringify(value, BufferJSON.replacer)));
36
+ }
37
+ }
38
+ });
39
+ const transaction = (work) => {
40
+ let dirty = false;
41
+ return store.transaction(rows => work(transactionView(rows, () => {
42
+ dirty = true;
43
+ })), () => dirty);
44
+ };
45
+ return {
46
+ get: async (type, ids) => Object.fromEntries(await Promise.all(ids.map(async (id) => [id, decode(await store.read(rows => rows.get(rowKey('legacy', fileName(type, id)))))]))),
47
+ set: data => transaction(async (keys) => {
48
+ await keys.set(data);
49
+ }),
50
+ bridgeTransaction: transaction
51
+ };
52
+ };
53
+ //# sourceMappingURL=snapshot.js.map
@@ -11,9 +11,12 @@ type Awaitable<T> = T | PromiseLike<T>;
11
11
  export type LegacyKeysStore = {
12
12
  get(type: string, ids: string[]): Awaitable<Record<string, unknown>>;
13
13
  set(data: Record<string, Record<string, unknown>>): Awaitable<void>;
14
+ bridgeTransaction?<T>(work: (keys: LegacyKeysStore) => Promise<T>): Promise<T>;
14
15
  };
15
16
  export interface WrappedLegacyStore extends JsStoreCallbacks {
16
- /** Kept for socket lifecycle compatibility. All key writes are already durable. */
17
+ /** Drain admitted callbacks and their durable commit barriers. A 30s timeout
18
+ * leaves backend operations pending. Await a later successful flush before
19
+ * deleting auth state or starting an older writer. */
17
20
  flush(): Promise<void>;
18
21
  /** Kept for socket lifecycle compatibility. The adapter owns no background resources. */
19
22
  dispose(): void;
@@ -5,10 +5,9 @@ export declare const bridgeNewsletterRoleToBaileys: (role: string | undefined) =
5
5
  /**
6
6
  * Neutral newsletter metadata in upstream's shape.
7
7
  *
8
- * Four upstream fields have no source in the bridge result and stay absent
8
+ * Three upstream fields have no source in the bridge result and stay absent
9
9
  * rather than being invented: `owner` (the result carries the viewer's role,
10
- * not the owner's jid), `mute_state` (the result's `state` is the newsletter's
11
- * lifecycle, Active/Suspended, not a mute), `reaction_codes`, and
10
+ * not the owner's jid), `reaction_codes`, and
12
11
  * `thread_metadata`.
13
12
  */
14
13
  export declare const bridgeNewsletterMetadataToBaileys: (result: NewsletterMetadataResult) => NewsletterMetadata;
@@ -19,14 +19,14 @@ export const bridgeNewsletterRoleToBaileys = (role) => role === undefined ? unde
19
19
  /**
20
20
  * Neutral newsletter metadata in upstream's shape.
21
21
  *
22
- * Four upstream fields have no source in the bridge result and stay absent
22
+ * Three upstream fields have no source in the bridge result and stay absent
23
23
  * rather than being invented: `owner` (the result carries the viewer's role,
24
- * not the owner's jid), `mute_state` (the result's `state` is the newsletter's
25
- * lifecycle, Active/Suspended, not a mute), `reaction_codes`, and
24
+ * not the owner's jid), `reaction_codes`, and
26
25
  * `thread_metadata`.
27
26
  */
28
27
  export const bridgeNewsletterMetadataToBaileys = (result) => ({
29
28
  id: result.jid,
29
+ ...(result.muted !== undefined ? { mute_state: result.muted ? 'ON' : 'OFF' } : {}),
30
30
  name: result.name,
31
31
  ...(result.description !== undefined ? { description: result.description } : {}),
32
32
  ...(result.inviteCode !== undefined ? { invite: result.inviteCode } : {}),
@@ -0,0 +1,17 @@
1
+ /** Shared mapping for typed reachout pushes and on-demand query responses. */
2
+ import { type ReachoutTimelockState } from '../Types/Reachout.js';
3
+ /** Wire shape from `xwa2_fetch_account_reachout_timelock`. */
4
+ export interface ReachoutTimelockWire {
5
+ is_active?: boolean;
6
+ /** Unix seconds as string. `"0"` or absent → cooldown not set. */
7
+ time_enforcement_ends?: string;
8
+ enforcement_type?: string;
9
+ }
10
+ /** Locate the timelock object inside an arbitrary payload — the bridge
11
+ * hands us either the raw `xwa2_…` body (from `fetchReachoutTimelock`)
12
+ * or a wrapping MEX response (from the push notification). */
13
+ export declare function extractReachoutPayload(value: unknown): ReachoutTimelockWire | null;
14
+ /** Map wire payload → public state. Returns `null` when the payload is
15
+ * empty or unparseable so callers can skip the emit. */
16
+ export declare function mapReachoutTimelock(value: unknown): ReachoutTimelockState | null;
17
+ //# sourceMappingURL=reachout.d.ts.map
@@ -0,0 +1,47 @@
1
+ /** Shared mapping for typed reachout pushes and on-demand query responses. */
2
+ import {} from '../Types/Reachout.js';
3
+ /** Locate the timelock object inside an arbitrary payload — the bridge
4
+ * hands us either the raw `xwa2_…` body (from `fetchReachoutTimelock`)
5
+ * or a wrapping MEX response (from the push notification). */
6
+ export function extractReachoutPayload(value) {
7
+ if (!value || typeof value !== 'object')
8
+ return null;
9
+ const v = value;
10
+ for (const key of ['xwa2_fetch_account_reachout_timelock', 'xwa2_notify_account_reachout_timelock']) {
11
+ const nested = v[key];
12
+ if (nested && typeof nested === 'object')
13
+ return nested;
14
+ const data = v['data'];
15
+ if (data && typeof data === 'object') {
16
+ const inner = data[key];
17
+ if (inner && typeof inner === 'object')
18
+ return inner;
19
+ }
20
+ }
21
+ // Caller already extracted — treat the value itself as the payload.
22
+ if ('is_active' in v || 'time_enforcement_ends' in v || 'enforcement_type' in v) {
23
+ return v;
24
+ }
25
+ return null;
26
+ }
27
+ /** Map wire payload → public state. Returns `null` when the payload is
28
+ * empty or unparseable so callers can skip the emit. */
29
+ export function mapReachoutTimelock(value) {
30
+ const wire = extractReachoutPayload(value);
31
+ if (!wire)
32
+ return null;
33
+ const state = {};
34
+ if (typeof wire.is_active === 'boolean')
35
+ state.isActive = wire.is_active;
36
+ if (typeof wire.time_enforcement_ends === 'string' && /^\d+$/.test(wire.time_enforcement_ends)) {
37
+ const seconds = Number(wire.time_enforcement_ends);
38
+ const date = new Date(seconds * 1000);
39
+ if (seconds > 0 && Number.isFinite(date.getTime()))
40
+ state.timeEnforcementEnds = date;
41
+ }
42
+ if (typeof wire.enforcement_type === 'string' && wire.enforcement_type) {
43
+ state.enforcementType = wire.enforcement_type;
44
+ }
45
+ return state;
46
+ }
47
+ //# sourceMappingURL=reachout.js.map
@@ -58,7 +58,7 @@ export const makeChatActionMethods = (ctx) => {
58
58
  await client.deleteChat(jid);
59
59
  }
60
60
  else if ('deleteForMe' in mod) {
61
- await client.deleteMessageForMe(jid, mod.deleteForMe.key.id, !!mod.deleteForMe.key.fromMe);
61
+ await client.deleteMessageForMe(jid, mod.deleteForMe.key.id, !!mod.deleteForMe.key.fromMe, mod.deleteForMe.key.participant);
62
62
  }
63
63
  else if ('pushNameSetting' in mod) {
64
64
  await client.setPushName(mod.pushNameSetting);
@@ -6,11 +6,16 @@ import { GROUP_REQUEST_ACTIONS, GROUP_SETTINGS, JOIN_APPROVAL_MODES, makeGroupMe
6
6
  export const makeCommunityMethods = (ctx, groups = makeGroupMethods(ctx)) => {
7
7
  const communityMetadata = async (jid) => groups.groupMetadata(jid);
8
8
  const communityFetchAllParticipating = async () => {
9
- const bridgeCommunities = await ctx.withClient(client => client.communityFetchAllParticipating());
10
- const result = {};
11
- for (const [communityJid, metadata] of Object.entries(bridgeCommunities)) {
12
- result[communityJid] = bridgeGroupMetadataToBaileys(metadata);
13
- }
9
+ // The bridge listing contains only overviews. Fetch the full records
10
+ // while holding one client lease; never publish a partial roster.
11
+ const result = await ctx.withClient(async (client) => {
12
+ const overviews = await client.communityFetchAllParticipating();
13
+ const metadata = {};
14
+ for (const jid of Object.keys(overviews)) {
15
+ metadata[jid] = bridgeGroupMetadataToBaileys(await client.getGroupMetadata(jid));
16
+ }
17
+ return metadata;
18
+ });
14
19
  ctx.ev.emit('groups.update', Object.values(result));
15
20
  return result;
16
21
  };
@@ -139,7 +139,14 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
139
139
  // Upstream mutates authState.creds before notifying user listeners. Register
140
140
  // this first so `ev.on('creds.update', saveCreds)` persists the merged state
141
141
  // rather than the pre-pair placeholder.
142
- ev.on('creds.update', update => Object.assign(auth.creds, update));
142
+ ev.on('creds.update', update => {
143
+ // App-state emits partial account settings. Preserve sibling settings
144
+ // before saveCreds listeners read the updated credentials.
145
+ const merged = update.accountSettings
146
+ ? { ...update, accountSettings: { ...auth.creds.accountSettings, ...update.accountSettings } }
147
+ : update;
148
+ Object.assign(auth.creds, merged);
149
+ });
143
150
  let user;
144
151
  /** True once `init()` has finished wiring the client and started its read loop. */
145
152
  let initialized = false;
@@ -355,8 +362,8 @@ const createWASocketFactoryInner = (runtime, config, claimEngineInitialization,
355
362
  else if (completion.reason === 'auto-reconnect-disabled') {
356
363
  const protocol = completion.protocolError;
357
364
  if (protocol?.kind === 'conflict') {
358
- statusCode = DisconnectReason.connectionReplaced;
359
- message = 'Connection replaced';
365
+ statusCode = protocol.cause === 'replaced' ? DisconnectReason.connectionReplaced : DisconnectReason.loggedOut;
366
+ message = protocol.cause === 'replaced' ? 'Connection replaced' : `Logged out: ${protocol.cause}`;
360
367
  }
361
368
  else if (protocol?.kind === 'stream-error') {
362
369
  statusCode = mapConnectFailureToDisconnect(protocol.code);
@@ -21,7 +21,6 @@ import { isJidBroadcast, isJidGroup } from '../WABinary/jid-utils.js';
21
21
  import { buildGroupCreateStubMessage, buildGroupJoinRequestEvents, buildGroupNotificationChatUpdates, buildGroupNotificationDomainEvent, buildGroupNotificationStubMessages } from '../Compatibility/group-notifications.js';
22
22
  import { emitMessageUpsert } from '../Compatibility/message-upsert.js';
23
23
  import { extractMessageCappingPayload } from './message-capping.js';
24
- import { mapReachoutTimelock } from './reachout.js';
25
24
  import { isReconnectableConnectFailure, mapConnectFailureToDisconnect } from './terminal-close.js';
26
25
  const CANONICAL_MESSAGE_EVENT = 'message';
27
26
  const MESSAGE_UPSERT_APPEND = 'append';
@@ -77,6 +76,8 @@ const canonicalMessageToWAMessage = (m, Long) => {
77
76
  key.remoteJid = m.chatJid;
78
77
  key.fromMe = m.isFromMe;
79
78
  key.id = m.id;
79
+ if (m.serverId !== undefined)
80
+ key.server_id = m.serverId;
80
81
  if (m.senderJid !== undefined)
81
82
  key.participant = m.senderJid;
82
83
  const wm = new WAProto.WebMessageInfo();
@@ -629,17 +630,23 @@ const DISPATCHERS = {
629
630
  ctx.ev.emit('chats.update', [{ id: evt.jid, unreadCount: evt.read ? 0 : -1 }]),
630
631
  // Upstream `chat-utils.ts:819` emits `chats.lock` from `lockChatAction.locked`.
631
632
  lockChatUpdate: (evt, { ctx }) => ctx.ev.emit('chats.lock', { id: evt.jid, locked: evt.locked }),
633
+ labelSublist: (evt, { ctx }) => {
634
+ const { type: _type, ...update } = evt;
635
+ ctx.ev.emit('labels.sublist', update);
636
+ },
632
637
  labelEdit: (evt, { ctx }) =>
633
638
  // Upstream `labels.edit` carries a `Label`. A delete arrives with
634
639
  // `deleted: true` (consumers remove it from their store).
635
640
  ctx.ev.emit('labels.edit', {
636
641
  id: evt.labelId,
642
+ ...(evt.actionTimestamp !== undefined ? { actionTimestamp: evt.actionTimestamp } : {}),
637
643
  name: evt.name,
638
644
  color: evt.color,
639
645
  deleted: evt.deleted,
640
646
  predefinedId: evt.predefinedId
641
647
  }),
642
648
  labelAssociation: (evt, { ctx }) => ctx.ev.emit('labels.association', {
649
+ ...(evt.actionTimestamp !== undefined ? { actionTimestamp: evt.actionTimestamp } : {}),
643
650
  // The two halves arrive on separate bridge events and upstream tells
644
651
  // them apart by the association's own type, so a message id is what
645
652
  // decides which of the two shapes this is.
@@ -674,7 +681,12 @@ const DISPATCHERS = {
674
681
  // Straight onto upstream's own channel for this: `settings.update` already
675
682
  // declares the `disableLinkPreviews` arm, and a consumer that reads it is
676
683
  // reading the account-wide setting whichever device changed it.
677
- settingUpdate: (evt, { ctx }) => ctx.ev.emit('settings.update', { setting: evt.setting, value: evt.value }),
684
+ settingUpdate: (evt, { ctx }) => {
685
+ const { type: _type, ...update } = evt;
686
+ ctx.ev.emit('settings.update', update);
687
+ },
688
+ unarchiveChatsSetting: (evt, { ctx }) => ctx.ev.emit('creds.update', { accountSettings: { unarchiveChats: evt.unarchiveChats } }),
689
+ reachoutTimelock: (evt, { ctx }) => emitConnectionUpdate(ctx, { reachoutTimeLock: evt.state }),
678
690
  // ── Calls ──
679
691
  incomingCall: (evt, { ctx, callbacks }) => {
680
692
  callbacks?.onIncomingCall?.(evt);
@@ -687,7 +699,9 @@ const DISPATCHERS = {
687
699
  from: evt.action.callCreator ?? evt.from,
688
700
  ...(evt.action.callCreator ? { callCreator: evt.action.callCreator } : {}),
689
701
  id: evt.action.callId,
690
- date: new Date(evt.timestamp * 1000),
702
+ // Upstream uses new Date(+attrs.t * 1000), including Invalid Date
703
+ // when t is absent. Preserve that contract without inventing a time.
704
+ date: new Date((evt.timestamp ?? Number.NaN) * 1000),
691
705
  status,
692
706
  offline: evt.offline,
693
707
  isGroup,
@@ -719,14 +733,9 @@ const DISPATCHERS = {
719
733
  mexNotification: (evt, { ctx }) => {
720
734
  // Route by op_name. Adding a new MEX-driven event means a new entry
721
735
  // here — no per-op_name plumbing in the Bridge layer.
722
- if (evt.opName === 'NotificationUserReachoutTimelockUpdate') {
723
- const state = mapReachoutTimelock(evt.payload);
724
- if (state)
725
- emitConnectionUpdate(ctx, { reachoutTimeLock: state });
726
- else
727
- ctx.logger.warn({ payload: evt.payload }, 'reachout-timelock push: payload missing expected fields');
736
+ // Bridge 0.25 emits the typed update before this raw twin.
737
+ if (evt.opName === 'NotificationUserReachoutTimelockUpdate')
728
738
  return;
729
- }
730
739
  if (evt.opName === 'MessageCappingInfoNotification') {
731
740
  const payload = extractMessageCappingPayload(evt.payload);
732
741
  if (payload)
@@ -124,11 +124,16 @@ export const makeGroupMethods = (ctx) => {
124
124
  await ctx.withClient(client => client.groupSettingUpdate(jid, 'membership_approval', mode === 'on'));
125
125
  },
126
126
  groupFetchAllParticipating: async () => {
127
- const bridgeGroups = await ctx.withClient(client => client.groupFetchAllParticipating());
128
- const result = {};
129
- for (const [groupJid, metadata] of Object.entries(bridgeGroups)) {
130
- result[groupJid] = bridgeGroupMetadataToBaileys(metadata);
131
- }
127
+ // The bridge listing contains only overviews. Fetch the full records
128
+ // while holding one client lease; never publish a partial roster.
129
+ const result = await ctx.withClient(async (client) => {
130
+ const overviews = await client.groupFetchAllParticipating();
131
+ const metadata = {};
132
+ for (const jid of Object.keys(overviews)) {
133
+ metadata[jid] = bridgeGroupMetadataToBaileys(await client.getGroupMetadata(jid));
134
+ }
135
+ return metadata;
136
+ });
132
137
  ctx.ev.emit('groups.update', Object.values(result));
133
138
  return result;
134
139
  },