@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
package/README.md CHANGED
@@ -60,6 +60,35 @@ both directions, for fields nested at any depth. An own public property wins ove
60
60
  bridge name, including an explicit `null` or `undefined`, and inputs are never
61
61
  mutated. The bridge keeps its own names.
62
62
 
63
+ ### Bridge 0.25 compatibility
64
+
65
+ The runtime dependency is pinned to `@oxidezap/whatsapp-rust-bridge@0.25.0`.
66
+ The public API still targets `baileys@7.0.0-rc14`.
67
+
68
+ - `groupFetchAllParticipating()` and `communityFetchAllParticipating()` fetch full
69
+ metadata for each slim bridge listing entry. This adds one metadata request per
70
+ group, preserves participants and settings, and rejects on any failed fetch
71
+ before emitting `groups.update`.
72
+ - Reachout pushes use the typed bridge event once, ignoring its raw MEX twin.
73
+ `connection.update.reachoutTimeLock` preserves unknown enforcement names at
74
+ runtime; a missing `isActive` means unknown, not a lifted restriction. This
75
+ reports server state and does not prevent device removal or impose send policy.
76
+ - A terminal `device_removed` or unknown conflict reports `loggedOut` rather than
77
+ `connectionReplaced`, including when run completion arrives before the event.
78
+ - `newsletterMute()` and `newsletterUnmute()` change channel-update notifications.
79
+ Metadata exposes that setting as `mute_state`, independently of admin-facing
80
+ follower-activity notifications. Reactions still resolve to `undefined`.
81
+ History results may omit `messageId`; `serverId` and large counters remain
82
+ strings. The bridge's packed live-message format does not carry the new
83
+ newsletter server ID; only object events and history results expose it.
84
+ - A failed community configuration can reject after creation succeeded. Preserve
85
+ the error's `createdJid`, `step`, `kind` and `cause`, then resume configuration on
86
+ that JID instead of repeating `communityCreate()`.
87
+ - Synced status privacy reaches `settings.update`; the unarchive setting reaches
88
+ `creds.update`. Historical calls, favorite chats and sticker-list updates have
89
+ no corresponding event in the pinned Baileys API and are acknowledged without
90
+ emitting unrelated live-call or message events.
91
+
63
92
  ## Documentation
64
93
 
65
94
  The full API reference and guides live in the
@@ -22,6 +22,7 @@
22
22
  * `asNumber`, `asString`) at those leak points only — not boilerplate
23
23
  * everywhere.
24
24
  */
25
+ import { mapReachoutTimelock } from '../Compatibility/reachout.js';
25
26
  import { processHistoryMessage } from '../Utils/process-history-message-core.js';
26
27
  import { isJidGroup } from '../WABinary/jid-utils.js';
27
28
  import { absoluteFromDuration, asBool, asBoolOr, asStringArray, asDurationSeconds, asInt64, asJidAddressString, asJidString, asNumber, asString, asUnixSeconds, isObject, normalizeDiscriminator } from './primitives.js';
@@ -215,10 +216,12 @@ const ADAPTERS = {
215
216
  const from = asJidString(data?.from);
216
217
  if (!from)
217
218
  return null;
219
+ if (data?.status !== 'available' && data?.status !== 'unavailable')
220
+ return null;
218
221
  return {
219
222
  type: 'presence',
220
223
  from,
221
- unavailable: asBoolOr(data?.unavailable, false),
224
+ unavailable: data?.status === 'unavailable',
222
225
  lastSeen: asUnixSeconds(data?.last_seen)
223
226
  };
224
227
  },
@@ -230,21 +233,15 @@ const ADAPTERS = {
230
233
  const sender = asJidString(src.sender);
231
234
  if (!chat || !sender)
232
235
  return null;
233
- // Bridge sends `media: ''` for "no media" — normalize to undefined
234
- // so consumers can rely on field omission as the absence signal.
235
- const media = asString(data?.media);
236
- // Bridge `state` MUST be one of the two canonical values; defaulting
237
- // to 'composing' on an unknown/missing value would synthesize a
238
- // false typing indicator. Drop the event instead.
239
236
  const rawState = asString(data?.state);
240
- if (rawState !== 'composing' && rawState !== 'paused')
237
+ if (rawState !== 'typing' && rawState !== 'recording_audio' && rawState !== 'idle')
241
238
  return null;
242
239
  return {
243
240
  type: 'chatPresence',
244
241
  chatJid: chat,
245
242
  senderJid: sender,
246
- state: rawState,
247
- media: media === 'audio' ? 'audio' : undefined
243
+ state: rawState === 'idle' ? 'paused' : 'composing',
244
+ media: rawState === 'recording_audio' ? 'audio' : undefined
248
245
  };
249
246
  },
250
247
  // ── Groups ──
@@ -293,7 +290,29 @@ const ADAPTERS = {
293
290
  return null;
294
291
  return { type: 'lockChatUpdate', jid, locked: asBoolOr(extractAction(data)?.locked, true) };
295
292
  },
293
+ label_sublist_update: data => {
294
+ const actionTimestamp = asString(data?.action_timestamp);
295
+ const chatJid = asJidString(data?.chat_jid);
296
+ const predefinedId = asNumber(data?.predefined_id);
297
+ const change = data?.change;
298
+ const subListId = isObject(change) && isObject(change.Upsert) ? asNumber(change.Upsert.sub_list_id) : undefined;
299
+ if (!chatJid ||
300
+ predefinedId === undefined ||
301
+ !Number.isInteger(predefinedId) ||
302
+ (change !== 'Remove' && (subListId === undefined || !Number.isInteger(subListId))))
303
+ return null;
304
+ return {
305
+ type: 'labelSublist',
306
+ predefinedId,
307
+ chatJid,
308
+ change: change === 'Remove' ? 'remove' : 'upsert',
309
+ ...(change === 'Remove' ? {} : { subListId }),
310
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
311
+ fromFullSync: asBoolOr(data?.from_full_sync, false)
312
+ };
313
+ },
296
314
  label_edit_update: data => {
315
+ const actionTimestamp = asString(data?.action_timestamp);
297
316
  const labelId = asString(data?.label_id);
298
317
  if (!labelId)
299
318
  return { type: 'noop', bridgeType: 'label_edit_update' };
@@ -303,6 +322,7 @@ const ADAPTERS = {
303
322
  const predefined = asNumber(action?.predefinedId) ?? asNumber(action?.predefined_id);
304
323
  return {
305
324
  type: 'labelEdit',
325
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
306
326
  labelId,
307
327
  name: asString(action?.name) ?? '',
308
328
  color: asNumber(action?.color) ?? 0,
@@ -311,18 +331,26 @@ const ADAPTERS = {
311
331
  };
312
332
  },
313
333
  label_association_update: data => {
334
+ const actionTimestamp = asString(data?.action_timestamp);
314
335
  const labelId = asString(data?.label_id);
315
336
  const chatJid = asJidString(data?.chat_jid);
316
337
  if (!labelId || !chatJid)
317
338
  return { type: 'noop', bridgeType: 'label_association_update' };
318
339
  // `action.labeled === true` → label added to the chat, else removed.
319
- return { type: 'labelAssociation', labelId, chatJid, labeled: asBoolOr(extractAction(data)?.labeled, true) };
340
+ return {
341
+ type: 'labelAssociation',
342
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
343
+ labelId,
344
+ chatJid,
345
+ labeled: asBoolOr(extractAction(data)?.labeled, true)
346
+ };
320
347
  },
321
348
  /**
322
349
  * The per-message half of `labels.association`, which used to have no path.
323
350
  * Same canonical event as the chat one, told apart by carrying a message.
324
351
  */
325
352
  message_label_association_update: data => {
353
+ const actionTimestamp = asString(data?.action_timestamp);
326
354
  const labelId = asString(data?.label_id);
327
355
  const chatJid = asJidString(data?.chat_jid);
328
356
  const messageId = asString(data?.message_id);
@@ -331,6 +359,7 @@ const ADAPTERS = {
331
359
  }
332
360
  return {
333
361
  type: 'labelAssociation',
362
+ ...(actionTimestamp !== undefined ? { actionTimestamp } : {}),
334
363
  labelId,
335
364
  chatJid,
336
365
  messageId,
@@ -407,6 +436,19 @@ const ADAPTERS = {
407
436
  contact_removed: () => ({ type: 'noop', bridgeType: 'contact_removed' }),
408
437
  quick_reply_update: () => ({ type: 'noop', bridgeType: 'quick_reply_update' }),
409
438
  call_log_sync: () => ({ type: 'noop', bridgeType: 'call_log_sync' }),
439
+ // Baileys rc14 has no events for historical calls, favorites or stickers.
440
+ call_log_history: () => ({ type: 'noop', bridgeType: 'call_log_history' }),
441
+ favorite_sticker_update: () => ({ type: 'noop', bridgeType: 'favorite_sticker_update' }),
442
+ remove_recent_sticker_update: () => ({ type: 'noop', bridgeType: 'remove_recent_sticker_update' }),
443
+ favorites_update: () => ({ type: 'noop', bridgeType: 'favorites_update' }),
444
+ status_privacy_update: data => isObject(data?.action) ? { type: 'settingUpdate', setting: 'statusPrivacy', value: data.action } : null,
445
+ unarchive_chats_setting_update: data => typeof data?.unarchive_chats === 'boolean'
446
+ ? { type: 'unarchiveChatsSetting', unarchiveChats: data.unarchive_chats }
447
+ : null,
448
+ reachout_timelock_update: data => {
449
+ const state = mapReachoutTimelock(data?.state);
450
+ return state ? { type: 'reachoutTimelock', state } : null;
451
+ },
410
452
  // ── Calls ──
411
453
  incoming_call: (data, logger) => adaptIncomingCall(data, logger),
412
454
  missed_call: (data, logger) => {
@@ -767,6 +809,7 @@ const adaptMessageParts = (info, messageProto, logger) => {
767
809
  isFromMe,
768
810
  id,
769
811
  timestamp,
812
+ serverId: asString(info.newsletter_server_id) ?? asNumber(info.newsletter_server_id)?.toString(),
770
813
  pushName: asString(info.push_name),
771
814
  participantAlt: resolveParticipantAlt(senderAlt, isGroup),
772
815
  remoteJidAlt: resolveRemoteJidAlt(senderAlt, recipientAlt, isGroup, isFromMe),
@@ -931,13 +974,11 @@ const adaptIncomingCall = (data, logger) => {
931
974
  logger?.debug({ data }, 'incoming_call adapter: missing action.type/call_id');
932
975
  return null;
933
976
  }
934
- // The call offer is timeline-ordered by its timestamp downstream; an
935
- // unparseable one drops the event rather than dating it at the epoch.
977
+ // Core can omit timestamps on call control stanzas. Preserve the action;
978
+ // a present malformed timestamp remains invalid input.
936
979
  const timestamp = asUnixSeconds(data.timestamp);
937
- if (timestamp === undefined) {
938
- logger?.debug(invalidTimestampDetail('incoming_call', data.timestamp), 'incoming_call adapter: missing or invalid timestamp');
980
+ if (data.timestamp != null && timestamp === undefined)
939
981
  return null;
940
- }
941
982
  const canonicalAction = {
942
983
  type: actionType,
943
984
  callId,
@@ -14,6 +14,8 @@
14
14
  * - Optional fields use `?` (omitted) rather than `null`.
15
15
  */
16
16
  import type { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
17
+ import type { ReachoutTimelockState } from '../Types/Reachout.js';
18
+ import type { BaileysEventMap } from '../Types/Events.js';
17
19
  import type { Chat, Contact, LIDMapping, WAMessage } from '../Types/index.js';
18
20
  import type { BinaryNode, WAProto } from '../Types/index.js';
19
21
  export interface CanonicalConnected {
@@ -116,6 +118,8 @@ export interface CanonicalQrScannedWithoutMultidevice {
116
118
  */
117
119
  export interface CanonicalMessage {
118
120
  type: 'message';
121
+ /** Exact newsletter server ID when the bridge object envelope carries it. */
122
+ serverId?: string;
119
123
  chatJid: string;
120
124
  senderJid?: string;
121
125
  isGroup: boolean;
@@ -451,8 +455,18 @@ export interface CanonicalMarkChatAsReadUpdate {
451
455
  * A label was created, renamed/recolored, or deleted on a linked device
452
456
  * (bridge `label_edit_update`). Maps to upstream `labels.edit` (`Label`).
453
457
  */
458
+ export interface CanonicalLabelSublist {
459
+ type: 'labelSublist';
460
+ predefinedId: number;
461
+ chatJid: string;
462
+ change: 'upsert' | 'remove';
463
+ subListId?: number;
464
+ actionTimestamp?: string;
465
+ fromFullSync: boolean;
466
+ }
454
467
  export interface CanonicalLabelEdit {
455
468
  type: 'labelEdit';
469
+ actionTimestamp?: string;
456
470
  labelId: string;
457
471
  name: string;
458
472
  color: number;
@@ -466,6 +480,7 @@ export interface CanonicalLabelEdit {
466
480
  */
467
481
  export interface CanonicalLabelAssociation {
468
482
  type: 'labelAssociation';
483
+ actionTimestamp?: string;
469
484
  labelId: string;
470
485
  chatJid: string;
471
486
  /**
@@ -514,10 +529,16 @@ export interface CanonicalAppStateSyncFailed {
514
529
  * new contract. The shape is the event's rather than one setting's: another
515
530
  * setting the bridge starts reporting is a new arm here, not a new event.
516
531
  */
517
- export interface CanonicalSettingUpdate {
532
+ export type CanonicalSettingUpdate = {
518
533
  type: 'settingUpdate';
519
- setting: 'disableLinkPreviews';
520
- value: proto.SyncActionValue.IPrivacySettingDisableLinkPreviewsAction;
534
+ } & BaileysEventMap['settings.update'];
535
+ export interface CanonicalReachoutTimelock {
536
+ type: 'reachoutTimelock';
537
+ state: ReachoutTimelockState;
538
+ }
539
+ export interface CanonicalUnarchiveChatsSetting {
540
+ type: 'unarchiveChatsSetting';
541
+ unarchiveChats: boolean;
521
542
  }
522
543
  export type CanonicalCallActionType = 'offer' | 'preaccept' | 'transport' | 'relaylatency' | 'accept' | 'reject' | 'terminate' | 'timeout';
523
544
  export interface CanonicalCallAction {
@@ -545,7 +566,7 @@ export interface CanonicalCallAction {
545
566
  export interface CanonicalIncomingCall {
546
567
  type: 'incomingCall';
547
568
  from: string;
548
- timestamp: number;
569
+ timestamp?: number;
549
570
  offline: boolean;
550
571
  /** Stanza-level `id` (distinct from `action.callId`). */
551
572
  stanzaId?: string;
@@ -732,5 +753,5 @@ export interface CanonicalServerAck {
732
753
  timestamp?: number;
733
754
  error?: string;
734
755
  }
735
- export type CanonicalEvent = CanonicalConnected | CanonicalDisconnected | CanonicalQR | CanonicalPairSuccess | CanonicalPairError | CanonicalLoggedOut | CanonicalConnectFailure | CanonicalStreamError | CanonicalStreamReplaced | CanonicalClientOutdated | CanonicalTemporaryBan | CanonicalQrScannedWithoutMultidevice | CanonicalMessage | CanonicalReceipt | CanonicalContactUpdate | CanonicalPictureUpdate | CanonicalPresence | CanonicalChatPresence | CanonicalGroupUpdate | CanonicalArchiveUpdate | CanonicalPinUpdate | CanonicalMuteUpdate | CanonicalStarUpdate | CanonicalMarkChatAsReadUpdate | CanonicalLockChatUpdate | CanonicalLabelEdit | CanonicalLabelAssociation | CanonicalAppStateSyncFailed | CanonicalQrCodesExhausted | CanonicalSettingUpdate | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
756
+ export type CanonicalEvent = CanonicalConnected | CanonicalDisconnected | CanonicalQR | CanonicalPairSuccess | CanonicalPairError | CanonicalLoggedOut | CanonicalConnectFailure | CanonicalStreamError | CanonicalStreamReplaced | CanonicalClientOutdated | CanonicalTemporaryBan | CanonicalQrScannedWithoutMultidevice | CanonicalMessage | CanonicalReceipt | CanonicalContactUpdate | CanonicalPictureUpdate | CanonicalPresence | CanonicalChatPresence | CanonicalGroupUpdate | CanonicalArchiveUpdate | CanonicalPinUpdate | CanonicalMuteUpdate | CanonicalStarUpdate | CanonicalMarkChatAsReadUpdate | CanonicalLockChatUpdate | CanonicalLabelSublist | CanonicalLabelEdit | CanonicalLabelAssociation | CanonicalAppStateSyncFailed | CanonicalQrCodesExhausted | CanonicalSettingUpdate | CanonicalReachoutTimelock | CanonicalUnarchiveChatsSetting | CanonicalIncomingCall | CanonicalUndecryptableMessage | CanonicalLidMappingUpdate | CanonicalNewsletterLiveUpdate | CanonicalChatDelete | CanonicalChatClear | CanonicalMessageDelete | CanonicalDisappearingModeChanged | CanonicalHistorySync | CanonicalOfflineSyncCompleted | CanonicalDirtyState | CanonicalRawNode | CanonicalNotification | CanonicalMexNotification | CanonicalServerAck | CanonicalNoop;
736
757
  //# sourceMappingURL=types.d.ts.map
@@ -1,14 +1,4 @@
1
- /**
2
- * Host-neutral credential seeding + store hydration for `auth: { store }`.
3
- *
4
- * `createAuthenticationState(store)` builds the public auth view the socket
5
- * consumes — `initAuthCreds()` for the credential mirror, the native store
6
- * projection for the key facade — and hydrates the mirror from the device
7
- * the engine persisted, so a restarted session reports `registered: true`
8
- * instead of a fresh placeholder. Key generation goes through the bridge
9
- * (`/host` entrypoint, already initialized by the caller), never
10
- * `node:crypto`; byte helpers come from `Runtime/bytes.ts`, never Buffer.
11
- */
1
+ import { assertStoreCallbacks } from '../Utils/atomic-store.js';
12
2
  import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
13
3
  import { concatBytes } from '../Runtime/bytes.js';
14
4
  import { createDeviceProjection } from './legacy-store/device.js';
@@ -84,6 +74,7 @@ const hydrateFromStore = async (store, creds) => {
84
74
  * wrap, no `Buffer`.
85
75
  */
86
76
  export const createAuthenticationState = async (store, keys) => {
77
+ assertStoreCallbacks(store);
87
78
  const creds = initHostAuthCreds();
88
79
  await hydrateFromStore(store, creds);
89
80
  const { projectNativeStore } = await import('./legacy-store/native-projection.js');
@@ -39,12 +39,12 @@ export const bridgeGroupMetadataToBaileys = (group) => {
39
39
  id: group.id.includes('@') ? group.id : jidEncode(group.id, 'g.us'),
40
40
  notify: group.notify,
41
41
  addressingMode: group.addressingMode === WAMessageAddressingMode.LID ? WAMessageAddressingMode.LID : WAMessageAddressingMode.PN,
42
- subject: group.subject,
42
+ subject: group.subject ?? '',
43
43
  subjectOwner: group.subjectOwner,
44
44
  subjectOwnerPn: group.subjectOwnerPn,
45
45
  subjectOwnerUsername: group.subjectOwnerUsername,
46
46
  subjectTime: group.subjectTime ?? Number.NaN,
47
- size: group.size ?? participants.length,
47
+ size: group.participantCount ?? participants.length,
48
48
  creation: group.creationTime ?? Number.NaN,
49
49
  owner: normalizeOptionalUserJid(group.creator),
50
50
  ownerPn: normalizeOptionalUserJid(group.creatorPn),
@@ -1,3 +1,4 @@
1
+ import { assertStoreCallbacks } from '../Utils/atomic-store.js';
1
2
  /** Host-only auth bootstrap. It deliberately does not import legacy-store codecs. */
2
3
  import { calculateSignature, generateKeyPair } from '@oxidezap/whatsapp-rust-bridge/host';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
@@ -155,6 +156,7 @@ export const hydrateHostAuthCreds = async (store, creds) => {
155
156
  };
156
157
  /** Build host auth from the caller-owned native byte store. Rust remains the Signal authority. */
157
158
  export const createAuthenticationState = async (store) => {
159
+ assertStoreCallbacks(store);
158
160
  const creds = initHostAuthCreds();
159
161
  await hydrateHostAuthCreds(store, creds);
160
162
  return { creds: creds, store };
@@ -1,3 +1,4 @@
1
+ import { assertStoreCallbacks } from '../../Utils/atomic-store.js';
1
2
  import { Buffer } from 'node:buffer';
2
3
  import { initAuthCreds } from '../../Utils/generics.js';
3
4
  import { hydrateHostAuthCreds } from '../host-auth-state.js';
@@ -35,6 +36,11 @@ export const normalizeSocketAuthenticationState = (input) => {
35
36
  throw new TypeError('auth must provide either { creds, keys } or a native store');
36
37
  }
37
38
  const store = input.store;
39
+ if (store)
40
+ assertStoreCallbacks(store);
41
+ else if (input.keys && typeof input.keys.bridgeTransaction !== 'function') {
42
+ throw new TypeError('legacy auth requires keys.bridgeTransaction with backend-wide atomicity; stop old writers and load file auth with useLegacyMultiFileAuthState(folder, { migrate: true })');
43
+ }
38
44
  const creds = input.creds ?? (store ? initAuthCreds() : undefined);
39
45
  const keys = input.keys ?? (store && creds ? projectNativeStore(store, creds) : undefined);
40
46
  if (!creds || !keys) {
@@ -1,7 +1,10 @@
1
+ import { assertStoreCallbacks } from '../../Utils/atomic-store.js';
1
2
  /** Host normalization: native stores remain Rust-owned and expose no legacy key facade. */
2
3
  export const normalizeHostAuthenticationState = (input) => {
3
4
  if (!input || typeof input !== 'object')
4
5
  throw new TypeError('auth must provide either { creds, keys } or a native store');
6
+ if (input.store)
7
+ assertStoreCallbacks(input.store);
5
8
  if (input.creds && input.keys)
6
9
  return input;
7
10
  if (input.store && input.creds)
@@ -1,3 +1,5 @@
1
+ import { settleBeforeFlushDeadline, flushDeadlineError, settledFlushError } from '../../Utils/flush-deadline.js';
2
+ import { atomicCallbacks, rowKey } from '../../Utils/atomic-store.js';
1
3
  // Baileys legacy auth-state projection onto the bridge's neutral byte store.
2
4
  import { Buffer } from 'node:buffer';
3
5
  import { NativeStore, RouteKind } from './constants.js';
@@ -19,6 +21,47 @@ function uniqueKeys(keys, label) {
19
21
  function createWarn(logger) {
20
22
  return logger ? (message, error) => logger.warn({ err: error }, message) : () => { };
21
23
  }
24
+ // Track complete callbacks, including backend commit barriers. A socket flush
25
+ // must join work already admitted even when its caller has not awaited it yet.
26
+ function withPendingCallbacks(store) {
27
+ const pending = new Set();
28
+ const track = (operation) => {
29
+ pending.add(operation);
30
+ void operation.then(() => pending.delete(operation), () => { } // Retain failure until a flush observes it.
31
+ );
32
+ return operation;
33
+ };
34
+ return {
35
+ ...store,
36
+ get: (...args) => track(Promise.resolve(store.get(...args))),
37
+ getMany: (...args) => track(Promise.resolve(store.getMany(...args))),
38
+ set: (...args) => track(Promise.resolve(store.set(...args))),
39
+ setMany: (...args) => track(Promise.resolve(store.setMany(...args))),
40
+ delete: (...args) => track(Promise.resolve(store.delete(...args))),
41
+ deleteMany: (...args) => track(Promise.resolve(store.deleteMany(...args))),
42
+ commitPatch: (...args) => track(Promise.resolve(store.commitPatch(...args))),
43
+ storeReceivedTcToken: (...args) => track(Promise.resolve(store.storeReceivedTcToken(...args))),
44
+ touchTcTokenSenderTimestamp: (...args) => track(Promise.resolve(store.touchTcTokenSenderTimestamp(...args))),
45
+ async flush() {
46
+ const deadline = Date.now() + 30000;
47
+ const errors = new Map();
48
+ for (;;) {
49
+ const admitted = [...pending];
50
+ await settleBeforeFlushDeadline(admitted, deadline, 'legacy store flush', errors);
51
+ for (const operation of admitted)
52
+ pending.delete(operation);
53
+ await new Promise(resolve => setImmediate(resolve));
54
+ if (pending.size === 0) {
55
+ if (errors.size)
56
+ throw settledFlushError('legacy store flush failed', errors.values());
57
+ return;
58
+ }
59
+ if (Date.now() >= deadline)
60
+ throw flushDeadlineError('legacy store flush', errors);
61
+ }
62
+ }
63
+ };
64
+ }
22
65
  export async function wrapLegacyStore(state, saveCreds, logger) {
23
66
  if (!state.creds || !state.keys) {
24
67
  throw new TypeError('wrapLegacyStore requires legacy creds and keys');
@@ -78,7 +121,11 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
78
121
  }
79
122
  const nativeValue = legacyValue == null ? null : codecs[store].fromLegacy(nativeKey, legacyValue);
80
123
  imported.set(nativeKey, nativeValue);
81
- mirrorUpdates[nativeKey] = nativeValue == null ? null : encodeNativeEnvelope(nativeValue, legacyValue);
124
+ // A negative lookup has nothing to persist when neither side exists.
125
+ // Retain deletion when a stale native mirror actually needs removing.
126
+ if (nativeValue != null || ownValue(nativeBucket, nativeKey) != null) {
127
+ mirrorUpdates[nativeKey] = nativeValue == null ? null : encodeNativeEnvelope(nativeValue, legacyValue);
128
+ }
82
129
  }
83
130
  if (Object.keys(mirrorUpdates).length > 0)
84
131
  await persist({ [route.nativeType]: mirrorUpdates });
@@ -104,7 +151,9 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
104
151
  continue;
105
152
  }
106
153
  imported.set(rawKey, legacyValue);
107
- mirrorUpdates[rawKey] = legacyValue ? encodeNativeEnvelope(legacyValue, legacyValue) : null;
154
+ if (legacyValue != null || ownValue(nativeBucket, rawKey) != null) {
155
+ mirrorUpdates[rawKey] = legacyValue ? encodeNativeEnvelope(legacyValue, legacyValue) : null;
156
+ }
108
157
  }
109
158
  if (Object.keys(mirrorUpdates).length > 0)
110
159
  await persist({ [route.nativeType]: mirrorUpdates });
@@ -238,7 +287,62 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
238
287
  throw new TypeError(`${store} has no projected codec`);
239
288
  return deleteProjected(store, requested);
240
289
  }
241
- return {
290
+ const atomic = async (stores, change) => {
291
+ if (!keys.bridgeTransaction)
292
+ throw new TypeError('legacy storage requires bridgeTransaction with backend-wide isolation and atomic durable commit');
293
+ await keys
294
+ .bridgeTransaction(async (transactionalKeys) => {
295
+ const adapter = await wrapLegacyStore({
296
+ ...state,
297
+ keys: {
298
+ get: (type, ids) => transactionalKeys.get(type, ids),
299
+ set: data => transactionalKeys.set(data)
300
+ }
301
+ }, saveCreds, logger);
302
+ const rows = new Map();
303
+ for (const { store, keys: requested } of stores) {
304
+ for (const [key, value] of await adapter.getMany(store, requested))
305
+ rows.set(rowKey(store, key), value);
306
+ }
307
+ const before = new Map(rows);
308
+ change(rows);
309
+ for (const key of before.keys())
310
+ if (!rows.has(key)) {
311
+ const [store, id] = JSON.parse(key);
312
+ await adapter.delete(store, id);
313
+ }
314
+ for (const [key, value] of rows)
315
+ if (before.get(key) !== value) {
316
+ const [store, id] = JSON.parse(key);
317
+ await adapter.set(store, id, value);
318
+ }
319
+ })
320
+ .catch(error => {
321
+ warn('atomic legacy transaction failed', error);
322
+ throw error;
323
+ });
324
+ };
325
+ const atomicMethods = (stores) => atomicCallbacks(change => atomic(stores, change));
326
+ const result = {
327
+ commitPatch(name, stateBytes, removed, added, maintainIndex) {
328
+ return atomicMethods([
329
+ { store: 'sync_version', keys: [name] },
330
+ { store: 'mutation_mac', keys: [...new Set([...removed, ...added.map(([key]) => key)])] },
331
+ { store: 'meta', keys: maintainIndex ? ['mutation_mac_keys'] : [] }
332
+ ]).commitPatch(name, stateBytes, removed, added, maintainIndex);
333
+ },
334
+ touchTcTokenSenderTimestamp(jid, timestamp) {
335
+ return atomicMethods([
336
+ { store: 'tc_token', keys: [jid] },
337
+ { store: 'meta', keys: ['tc_token_jids'] }
338
+ ]).touchTcTokenSenderTimestamp(jid, timestamp);
339
+ },
340
+ storeReceivedTcToken(jid, token, timestamp) {
341
+ return atomicMethods([
342
+ { store: 'tc_token', keys: [jid] },
343
+ { store: 'meta', keys: ['tc_token_jids'] }
344
+ ]).storeReceivedTcToken(jid, token, timestamp);
345
+ },
242
346
  async get(store, key) {
243
347
  try {
244
348
  return (await readMany(store, [key]))[0]?.[1] ?? null;
@@ -297,5 +401,35 @@ export async function wrapLegacyStore(state, saveCreds, logger) {
297
401
  async flush() { },
298
402
  dispose() { }
299
403
  };
404
+ if (!keys.bridgeTransaction)
405
+ return withPendingCallbacks(result);
406
+ const transaction = (work) => keys.bridgeTransaction(async (transactionalKeys) => work(await wrapLegacyStore({
407
+ ...state,
408
+ keys: {
409
+ get: (type, ids) => transactionalKeys.get(type, ids),
410
+ set: data => transactionalKeys.set(data)
411
+ }
412
+ }, saveCreds, logger)));
413
+ return withPendingCallbacks({
414
+ ...result,
415
+ get: (store, key) => transaction(adapter => adapter.get(store, key)),
416
+ getMany: (store, requested) => {
417
+ const snapshot = [...requested];
418
+ return transaction(adapter => adapter.getMany(store, snapshot));
419
+ },
420
+ set: (store, key, value) => {
421
+ const snapshot = Uint8Array.from(value);
422
+ return transaction(adapter => adapter.set(store, key, snapshot));
423
+ },
424
+ setMany: (store, entries) => {
425
+ const snapshot = entries.map(([key, value]) => [key, Uint8Array.from(value)]);
426
+ return transaction(adapter => adapter.setMany(store, snapshot));
427
+ },
428
+ delete: (store, key) => transaction(adapter => adapter.delete(store, key)),
429
+ deleteMany: (store, requested) => {
430
+ const snapshot = [...requested];
431
+ return transaction(adapter => adapter.deleteMany(store, snapshot));
432
+ }
433
+ });
300
434
  }
301
435
  //# sourceMappingURL=adapter.js.map
@@ -1,3 +1,4 @@
1
+ import { decodeTokenRow, encodeTokenRow, signedTimestamp } from '../../../Utils/atomic-store.js';
1
2
  // Basic value codecs for the Baileys legacy-store projection.
2
3
  import { Buffer } from 'node:buffer';
3
4
  import { proto } from '@oxidezap/whatsapp-rust-bridge/proto-types';
@@ -90,18 +91,14 @@ function tcTokenCodec() {
90
91
  return {
91
92
  fromLegacy(_key, value) {
92
93
  const token = value;
93
- return toJsonBytes({
94
+ return encodeTokenRow({
94
95
  token: bytesToNumbers(requireBytes(token.token, 'TC token')),
95
- token_timestamp: token.timestamp
96
- ? parseUnsignedDecimal(token.timestamp, 'TC token timestamp')
97
- : TimeValue.UNKNOWN_SECONDS,
98
- sender_timestamp: token.senderTimestamp
99
- ? parseUnsignedDecimal(token.senderTimestamp, 'TC token sender timestamp')
100
- : null
96
+ token_timestamp: signedTimestamp(token.timestamp ?? '0'),
97
+ sender_timestamp: token.senderTimestamp == null ? null : signedTimestamp(token.senderTimestamp)
101
98
  });
102
99
  },
103
100
  toLegacy(_key, value) {
104
- const native = fromJsonBytes(value);
101
+ const native = decodeTokenRow(value);
105
102
  // Added rather than set to `undefined`, matching upstream, which
106
103
  // only carries the field when it has a value. An undefined-valued
107
104
  // key survives in memory but not through a store, and the mirror
@@ -1,5 +1,16 @@
1
+ import type { StoreMigrationOptions } from '../../Utils/store-migration.js';
1
2
  import type { AuthenticationState } from '../../Types/index.js';
2
- export declare function useLegacyMultiFileAuthState(folder: string): Promise<{
3
+ /** Load an upstream JSON auth directory using durable backend-wide transactions.
4
+ * Existing key records require an explicit offline migration:
5
+ *
6
+ * await useLegacyMultiFileAuthState(folder, { migrate: true })
7
+ *
8
+ * Stop every old writer and back up the entire directory before opting in.
9
+ * The new snapshot becomes authoritative; retained JSON files are backups.
10
+ * To hand the directory back to upstream, stop all writers and first call
11
+ * prepareLegacyAuthRollback(folder, { offline: true }).
12
+ */
13
+ export declare function useLegacyMultiFileAuthState(folder: string, options?: StoreMigrationOptions): Promise<{
3
14
  state: AuthenticationState;
4
15
  saveCreds: () => Promise<void>;
5
16
  }>;