gifted-baileys 1.5.6 → 1.5.7

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 (252) hide show
  1. package/README.md +9 -0
  2. package/WAProto/WAProto.proto +969 -88
  3. package/WAProto/index.d.ts +13199 -1260
  4. package/WAProto/index.js +124901 -74525
  5. package/lib/Defaults/baileys-version.json +3 -0
  6. package/lib/Defaults/index.d.ts +284 -0
  7. package/{src → lib}/Defaults/index.js +7 -14
  8. package/lib/Signal/libsignal.d.ts +3 -0
  9. package/lib/Signal/libsignal.js +161 -0
  10. package/lib/Socket/Client/abstract-socket-client.d.ts +15 -0
  11. package/lib/Socket/Client/index.d.ts +2 -0
  12. package/{src → lib}/Socket/Client/index.js +2 -3
  13. package/lib/Socket/Client/mobile-socket-client.d.ts +12 -0
  14. package/lib/Socket/Client/mobile-socket-client.js +65 -0
  15. package/lib/Socket/Client/types.d.ts +17 -0
  16. package/lib/Socket/Client/types.js +13 -0
  17. package/lib/Socket/Client/websocket.d.ts +12 -0
  18. package/lib/Socket/Client/websocket.js +62 -0
  19. package/lib/Socket/business.d.ts +170 -0
  20. package/{src → lib}/Socket/business.js +28 -33
  21. package/lib/Socket/chats.d.ts +81 -0
  22. package/{src → lib}/Socket/chats.js +174 -176
  23. package/lib/Socket/groups.d.ts +115 -0
  24. package/{src → lib}/Socket/groups.js +80 -68
  25. package/lib/Socket/index.d.ts +172 -0
  26. package/{src → lib}/Socket/index.js +4 -1
  27. package/lib/Socket/messages-recv.d.ts +158 -0
  28. package/{src → lib}/Socket/messages-recv.js +378 -211
  29. package/lib/Socket/messages-send.d.ts +155 -0
  30. package/{src → lib}/Socket/messages-send.js +452 -177
  31. package/lib/Socket/newsletter.d.ts +132 -0
  32. package/{src → lib}/Socket/newsletter.js +107 -98
  33. package/lib/Socket/registration.d.ts +264 -0
  34. package/{src → lib}/Socket/registration.js +56 -48
  35. package/lib/Socket/socket.d.ts +44 -0
  36. package/{src → lib}/Socket/socket.js +77 -77
  37. package/lib/Socket/usync.d.ts +37 -0
  38. package/lib/Socket/usync.js +70 -0
  39. package/lib/Store/index.d.ts +3 -0
  40. package/lib/Store/make-cache-manager-store.d.ts +14 -0
  41. package/{src → lib}/Store/make-cache-manager-store.js +25 -34
  42. package/lib/Store/make-in-memory-store.d.ts +118 -0
  43. package/{src → lib}/Store/make-in-memory-store.js +36 -32
  44. package/lib/Store/make-ordered-dictionary.d.ts +13 -0
  45. package/lib/Store/object-repository.d.ts +10 -0
  46. package/{src → lib}/Store/object-repository.js +1 -1
  47. package/lib/Types/Auth.d.ts +109 -0
  48. package/lib/Types/Call.d.ts +13 -0
  49. package/lib/Types/Chat.d.ts +107 -0
  50. package/{src/Types/Contact.ts → lib/Types/Contact.d.ts} +8 -9
  51. package/lib/Types/Events.d.ts +172 -0
  52. package/lib/Types/GroupMetadata.d.ts +56 -0
  53. package/lib/Types/Label.d.ts +46 -0
  54. package/{src/Types/LabelAssociation.ts → lib/Types/LabelAssociation.d.ts} +16 -22
  55. package/lib/Types/Message.d.ts +433 -0
  56. package/lib/Types/Newsletter.d.ts +92 -0
  57. package/lib/Types/Product.d.ts +78 -0
  58. package/lib/Types/Signal.d.ts +57 -0
  59. package/{src/Types/Socket.ts → lib/Types/Socket.d.ts} +61 -68
  60. package/lib/Types/State.d.ts +27 -0
  61. package/lib/Types/USync.d.ts +25 -0
  62. package/lib/Types/index.d.ts +66 -0
  63. package/lib/Utils/auth-utils.d.ts +18 -0
  64. package/{src → lib}/Utils/auth-utils.js +73 -90
  65. package/lib/Utils/baileys-event-stream.d.ts +16 -0
  66. package/lib/Utils/baileys-event-stream.js +63 -0
  67. package/lib/Utils/business.d.ts +22 -0
  68. package/{src → lib}/Utils/business.js +15 -43
  69. package/lib/Utils/chat-utils.d.ts +70 -0
  70. package/{src → lib}/Utils/chat-utils.js +87 -94
  71. package/lib/Utils/crypto.d.ts +40 -0
  72. package/{src → lib}/Utils/crypto.js +4 -2
  73. package/lib/Utils/decode-wa-message.d.ts +36 -0
  74. package/lib/Utils/decode-wa-message.js +226 -0
  75. package/lib/Utils/event-buffer.d.ts +35 -0
  76. package/{src → lib}/Utils/event-buffer.js +4 -13
  77. package/lib/Utils/generics.d.ts +88 -0
  78. package/{src → lib}/Utils/generics.js +67 -86
  79. package/lib/Utils/history.d.ts +19 -0
  80. package/{src → lib}/Utils/history.js +13 -39
  81. package/lib/Utils/index.d.ts +17 -0
  82. package/lib/Utils/link-preview.d.ts +21 -0
  83. package/{src → lib}/Utils/link-preview.js +17 -54
  84. package/lib/Utils/logger.d.ts +2 -0
  85. package/lib/Utils/lt-hash.d.ts +12 -0
  86. package/lib/Utils/make-mutex.d.ts +7 -0
  87. package/{src → lib}/Utils/make-mutex.js +4 -13
  88. package/lib/Utils/messages-media.d.ts +113 -0
  89. package/{src → lib}/Utils/messages-media.js +193 -255
  90. package/lib/Utils/messages.d.ts +77 -0
  91. package/{src → lib}/Utils/messages.js +588 -118
  92. package/lib/Utils/noise-handler.d.ts +20 -0
  93. package/lib/Utils/process-message.d.ts +41 -0
  94. package/{src → lib}/Utils/process-message.js +27 -30
  95. package/lib/Utils/signal.d.ts +33 -0
  96. package/{src → lib}/Utils/signal.js +25 -42
  97. package/lib/Utils/use-multi-file-auth-state.d.ts +12 -0
  98. package/{src → lib}/Utils/use-multi-file-auth-state.js +27 -28
  99. package/lib/Utils/validate-connection.d.ts +11 -0
  100. package/{src → lib}/Utils/validate-connection.js +40 -9
  101. package/lib/WABinary/constants.d.ts +27 -0
  102. package/lib/WABinary/decode.d.ts +6 -0
  103. package/lib/WABinary/encode.d.ts +2 -0
  104. package/{src → lib}/WABinary/encode.js +16 -10
  105. package/lib/WABinary/generic-utils.d.ts +14 -0
  106. package/lib/WABinary/index.d.ts +5 -0
  107. package/lib/WABinary/jid-utils.d.ts +31 -0
  108. package/lib/WABinary/types.d.ts +18 -0
  109. package/lib/WABinary/types.js +2 -0
  110. package/lib/WAM/BinaryInfo.d.ts +8 -0
  111. package/lib/WAM/constants.d.ts +38 -0
  112. package/lib/WAM/encode.d.ts +2 -0
  113. package/lib/WAM/index.d.ts +3 -0
  114. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +9 -0
  115. package/lib/WAUSync/Protocols/USyncContactProtocol.js +32 -0
  116. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +22 -0
  117. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +57 -0
  118. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +12 -0
  119. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +30 -0
  120. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +12 -0
  121. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +42 -0
  122. package/lib/WAUSync/Protocols/index.d.ts +4 -0
  123. package/lib/WAUSync/Protocols/index.js +20 -0
  124. package/lib/WAUSync/USyncQuery.d.ts +26 -0
  125. package/lib/WAUSync/USyncQuery.js +79 -0
  126. package/lib/WAUSync/USyncUser.d.ts +10 -0
  127. package/lib/WAUSync/USyncUser.js +22 -0
  128. package/lib/WAUSync/index.d.ts +3 -0
  129. package/lib/WAUSync/index.js +19 -0
  130. package/{src → lib}/index.js +1 -0
  131. package/package.json +26 -8
  132. package/LICENSE +0 -21
  133. package/src/Defaults/baileys-version.json +0 -3
  134. package/src/Defaults/index.ts +0 -131
  135. package/src/README.md +0 -1
  136. package/src/Signal/libsignal.js +0 -180
  137. package/src/Signal/libsignal.ts +0 -141
  138. package/src/Socket/Client/abstract-socket-client.ts +0 -19
  139. package/src/Socket/Client/index.ts +0 -3
  140. package/src/Socket/Client/mobile-socket-client.js +0 -78
  141. package/src/Socket/Client/mobile-socket-client.ts +0 -66
  142. package/src/Socket/Client/web-socket-client.js +0 -75
  143. package/src/Socket/Client/web-socket-client.ts +0 -57
  144. package/src/Socket/business.ts +0 -281
  145. package/src/Socket/chats.ts +0 -1030
  146. package/src/Socket/groups.ts +0 -356
  147. package/src/Socket/index.ts +0 -13
  148. package/src/Socket/messages-recv.ts +0 -985
  149. package/src/Socket/messages-send.ts +0 -871
  150. package/src/Socket/newsletter.ts +0 -282
  151. package/src/Socket/registration.ts +0 -250
  152. package/src/Socket/socket.ts +0 -777
  153. package/src/Store/index.ts +0 -3
  154. package/src/Store/make-cache-manager-store.ts +0 -100
  155. package/src/Store/make-in-memory-store.ts +0 -475
  156. package/src/Store/make-ordered-dictionary.ts +0 -86
  157. package/src/Store/object-repository.ts +0 -32
  158. package/src/Tests/test.app-state-sync.js +0 -204
  159. package/src/Tests/test.app-state-sync.ts +0 -207
  160. package/src/Tests/test.event-buffer.js +0 -270
  161. package/src/Tests/test.event-buffer.ts +0 -319
  162. package/src/Tests/test.key-store.js +0 -76
  163. package/src/Tests/test.key-store.ts +0 -92
  164. package/src/Tests/test.libsignal.js +0 -141
  165. package/src/Tests/test.libsignal.ts +0 -186
  166. package/src/Tests/test.media-download.js +0 -93
  167. package/src/Tests/test.media-download.ts +0 -76
  168. package/src/Tests/test.messages.js +0 -33
  169. package/src/Tests/test.messages.ts +0 -37
  170. package/src/Tests/utils.js +0 -34
  171. package/src/Tests/utils.ts +0 -36
  172. package/src/Types/Auth.ts +0 -113
  173. package/src/Types/Call.ts +0 -15
  174. package/src/Types/Chat.ts +0 -106
  175. package/src/Types/Events.ts +0 -93
  176. package/src/Types/GroupMetadata.ts +0 -53
  177. package/src/Types/Label.ts +0 -36
  178. package/src/Types/Message.ts +0 -288
  179. package/src/Types/Newsletter.ts +0 -98
  180. package/src/Types/Product.ts +0 -85
  181. package/src/Types/Signal.ts +0 -68
  182. package/src/Types/State.ts +0 -29
  183. package/src/Types/index.ts +0 -59
  184. package/src/Utils/auth-utils.ts +0 -222
  185. package/src/Utils/baileys-event-stream.js +0 -92
  186. package/src/Utils/baileys-event-stream.ts +0 -66
  187. package/src/Utils/business.ts +0 -275
  188. package/src/Utils/chat-utils.ts +0 -860
  189. package/src/Utils/crypto.ts +0 -131
  190. package/src/Utils/decode-wa-message.js +0 -211
  191. package/src/Utils/decode-wa-message.ts +0 -228
  192. package/src/Utils/event-buffer.ts +0 -613
  193. package/src/Utils/generics.ts +0 -434
  194. package/src/Utils/history.ts +0 -112
  195. package/src/Utils/index.ts +0 -17
  196. package/src/Utils/link-preview.ts +0 -122
  197. package/src/Utils/logger.ts +0 -3
  198. package/src/Utils/lt-hash.ts +0 -61
  199. package/src/Utils/make-mutex.ts +0 -44
  200. package/src/Utils/messages-media.ts +0 -847
  201. package/src/Utils/messages.ts +0 -956
  202. package/src/Utils/noise-handler.ts +0 -197
  203. package/src/Utils/process-message.ts +0 -414
  204. package/src/Utils/signal.ts +0 -177
  205. package/src/Utils/use-multi-file-auth-state.ts +0 -90
  206. package/src/Utils/validate-connection.ts +0 -238
  207. package/src/WABinary/constants.ts +0 -42
  208. package/src/WABinary/decode.ts +0 -265
  209. package/src/WABinary/encode.ts +0 -236
  210. package/src/WABinary/generic-utils.ts +0 -121
  211. package/src/WABinary/index.ts +0 -5
  212. package/src/WABinary/jid-utils.ts +0 -68
  213. package/src/WABinary/types.ts +0 -17
  214. package/src/WAM/BinaryInfo.ts +0 -12
  215. package/src/WAM/constants.ts +0 -15382
  216. package/src/WAM/encode.ts +0 -174
  217. package/src/WAM/index.ts +0 -3
  218. package/src/gifted +0 -1
  219. package/src/index.ts +0 -13
  220. /package/{src → lib}/Defaults/phonenumber-mcc.json +0 -0
  221. /package/{src → lib}/Socket/Client/abstract-socket-client.js +0 -0
  222. /package/{src → lib}/Store/index.js +0 -0
  223. /package/{src → lib}/Store/make-ordered-dictionary.js +0 -0
  224. /package/{src → lib}/Types/Auth.js +0 -0
  225. /package/{src → lib}/Types/Call.js +0 -0
  226. /package/{src → lib}/Types/Chat.js +0 -0
  227. /package/{src → lib}/Types/Contact.js +0 -0
  228. /package/{src → lib}/Types/Events.js +0 -0
  229. /package/{src → lib}/Types/GroupMetadata.js +0 -0
  230. /package/{src → lib}/Types/Label.js +0 -0
  231. /package/{src → lib}/Types/LabelAssociation.js +0 -0
  232. /package/{src → lib}/Types/Message.js +0 -0
  233. /package/{src → lib}/Types/Newsletter.js +0 -0
  234. /package/{src → lib}/Types/Product.js +0 -0
  235. /package/{src → lib}/Types/Signal.js +0 -0
  236. /package/{src → lib}/Types/Socket.js +0 -0
  237. /package/{src → lib}/Types/State.js +0 -0
  238. /package/{src/WABinary/types.js → lib/Types/USync.js} +0 -0
  239. /package/{src → lib}/Types/index.js +0 -0
  240. /package/{src → lib}/Utils/index.js +0 -0
  241. /package/{src → lib}/Utils/logger.js +0 -0
  242. /package/{src → lib}/Utils/lt-hash.js +0 -0
  243. /package/{src → lib}/Utils/noise-handler.js +0 -0
  244. /package/{src → lib}/WABinary/constants.js +0 -0
  245. /package/{src → lib}/WABinary/decode.js +0 -0
  246. /package/{src → lib}/WABinary/generic-utils.js +0 -0
  247. /package/{src → lib}/WABinary/index.js +0 -0
  248. /package/{src → lib}/WABinary/jid-utils.js +0 -0
  249. /package/{src → lib}/WAM/BinaryInfo.js +0 -0
  250. /package/{src → lib}/WAM/constants.js +0 -0
  251. /package/{src → lib}/WAM/encode.js +0 -0
  252. /package/{src → lib}/WAM/index.js +0 -0
@@ -1,85 +0,0 @@
1
- import { WAMediaUpload } from './Message'
2
-
3
- export type CatalogResult = {
4
- data: {
5
- paging: { cursors: { before: string, after: string } }
6
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
- data: any[]
8
- }
9
- }
10
-
11
- export type ProductCreateResult = {
12
- data: { product: {} }
13
- }
14
-
15
- export type CatalogStatus = {
16
- status: string
17
- canAppeal: boolean
18
- }
19
-
20
- export type CatalogCollection = {
21
- id: string
22
- name: string
23
- products: Product[]
24
-
25
- status: CatalogStatus
26
- }
27
-
28
- export type ProductAvailability = 'in stock'
29
-
30
- export type ProductBase = {
31
- name: string
32
- retailerId?: string
33
- url?: string
34
- description: string
35
- price: number
36
- currency: string
37
- isHidden?: boolean
38
- }
39
-
40
- export type ProductCreate = ProductBase & {
41
- /** ISO country code for product origin. Set to undefined for no country */
42
- originCountryCode: string | undefined
43
- /** images of the product */
44
- images: WAMediaUpload[]
45
- }
46
-
47
- export type ProductUpdate = Omit<ProductCreate, 'originCountryCode'>
48
-
49
- export type Product = ProductBase & {
50
- id: string
51
- imageUrls: { [_: string]: string }
52
- reviewStatus: { [_: string]: string }
53
- availability: ProductAvailability
54
- }
55
-
56
- export type OrderPrice = {
57
- currency: string
58
- total: number
59
- }
60
-
61
- export type OrderProduct = {
62
- id: string
63
- imageUrl: string
64
- name: string
65
- quantity: number
66
-
67
- currency: string
68
- price: number
69
- }
70
-
71
- export type OrderDetails = {
72
- price: OrderPrice
73
- products: OrderProduct[]
74
- }
75
-
76
- export type CatalogCursor = string
77
-
78
- export type GetCatalogOptions = {
79
- /** cursor to start from */
80
- cursor?: CatalogCursor
81
- /** number of products to fetch */
82
- limit?: number
83
-
84
- jid?: string
85
- }
@@ -1,68 +0,0 @@
1
- import { proto } from '../../WAProto'
2
-
3
- type DecryptGroupSignalOpts = {
4
- group: string
5
- authorJid: string
6
- msg: Uint8Array
7
- }
8
-
9
- type ProcessSenderKeyDistributionMessageOpts = {
10
- item: proto.Message.ISenderKeyDistributionMessage
11
- authorJid: string
12
- }
13
-
14
- type DecryptSignalProtoOpts = {
15
- jid: string
16
- type: 'pkmsg' | 'msg'
17
- ciphertext: Uint8Array
18
- }
19
-
20
- type EncryptMessageOpts = {
21
- jid: string
22
- data: Uint8Array
23
- }
24
-
25
- type EncryptGroupMessageOpts = {
26
- group: string
27
- data: Uint8Array
28
- meId: string
29
- }
30
-
31
- type PreKey = {
32
- keyId: number
33
- publicKey: Uint8Array
34
- }
35
-
36
- type SignedPreKey = PreKey & {
37
- signature: Uint8Array
38
- }
39
-
40
- type E2ESession = {
41
- registrationId: number
42
- identityKey: Uint8Array
43
- signedPreKey: SignedPreKey
44
- preKey: PreKey
45
- }
46
-
47
- type E2ESessionOpts = {
48
- jid: string
49
- session: E2ESession
50
- }
51
-
52
- export type SignalRepository = {
53
- decryptGroupMessage(opts: DecryptGroupSignalOpts): Promise<Uint8Array>
54
- processSenderKeyDistributionMessage(
55
- opts: ProcessSenderKeyDistributionMessageOpts
56
- ): Promise<void>
57
- decryptMessage(opts: DecryptSignalProtoOpts): Promise<Uint8Array>
58
- encryptMessage(opts: EncryptMessageOpts): Promise<{
59
- type: 'pkmsg' | 'msg'
60
- ciphertext: Uint8Array
61
- }>
62
- encryptGroupMessage(opts: EncryptGroupMessageOpts): Promise<{
63
- senderKeyDistributionMessage: Uint8Array
64
- ciphertext: Uint8Array
65
- }>
66
- injectE2ESession(opts: E2ESessionOpts): Promise<void>
67
- jidToSignalProtocolAddress(jid: string): string
68
- }
@@ -1,29 +0,0 @@
1
- import { Contact } from './Contact'
2
-
3
- export type WAConnectionState = 'open' | 'connecting' | 'close'
4
-
5
- export type ConnectionState = {
6
- /** connection is now open, connecting or closed */
7
- connection: WAConnectionState
8
- /** the error that caused the connection to close */
9
- lastDisconnect?: {
10
- error: Error | undefined
11
- date: Date
12
- }
13
- /** is this a new login */
14
- isNewLogin?: boolean
15
- /** the current QR code */
16
- qr?: string
17
- /** has the device received all pending notifications while it was offline */
18
- receivedPendingNotifications?: boolean
19
- /** legacy connection options */
20
- legacy?: {
21
- phoneConnected: boolean
22
- user?: Contact
23
- }
24
- /**
25
- * if the client is shown as an active, online client.
26
- * If this is false, the primary phone and other devices will receive notifs
27
- * */
28
- isOnline?: boolean
29
- }
@@ -1,59 +0,0 @@
1
- export * from './Auth'
2
- export * from './GroupMetadata'
3
- export * from './Chat'
4
- export * from './Contact'
5
- export * from './State'
6
- export * from './Message'
7
- export * from './Newsletter'
8
- export * from './Socket'
9
- export * from './Events'
10
- export * from './Product'
11
- export * from './Call'
12
- export * from './Signal'
13
-
14
- import { AuthenticationState } from './Auth'
15
- import { SocketConfig } from './Socket'
16
-
17
- export type UserFacingSocketConfig = Partial<SocketConfig> & { auth: AuthenticationState }
18
-
19
- export enum DisconnectReason {
20
- connectionClosed = 428,
21
- connectionLost = 408,
22
- connectionReplaced = 440,
23
- timedOut = 408,
24
- loggedOut = 401,
25
- badSession = 500,
26
- restartRequired = 515,
27
- multideviceMismatch = 411,
28
- forbidden = 403,
29
- unavailableService = 503
30
- }
31
-
32
- export type WAInitResponse = {
33
- ref: string
34
- ttl: number
35
- status: 200
36
- }
37
-
38
- export type WABusinessHoursConfig = {
39
- day_of_week: string
40
- mode: string
41
- open_time?: number
42
- close_time?: number
43
- }
44
-
45
- export type WABusinessProfile = {
46
- description: string
47
- email: string | undefined
48
- business_hours: {
49
- timezone?: string
50
- config?: WABusinessHoursConfig[]
51
- business_config?: WABusinessHoursConfig[]
52
- }
53
- website: string[]
54
- category?: string
55
- wid?: string
56
- address?: string
57
- }
58
-
59
- export type CurveKeyPair = { private: Uint8Array, public: Uint8Array }
@@ -1,222 +0,0 @@
1
- import { randomBytes } from 'crypto'
2
- import NodeCache from 'node-cache'
3
- import type { Logger } from 'pino'
4
- import { v4 as uuidv4 } from 'uuid'
5
- import { DEFAULT_CACHE_TTLS } from '../Defaults'
6
- import type { AuthenticationCreds, CacheStore, SignalDataSet, SignalDataTypeMap, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types'
7
- import { Curve, signedKeyPair } from './crypto'
8
- import { delay, generateRegistrationId } from './generics'
9
-
10
- /**
11
- * Adds caching capability to a SignalKeyStore
12
- * @param store the store to add caching to
13
- * @param logger to log trace events
14
- * @param _cache cache store to use
15
- */
16
- export function makeCacheableSignalKeyStore(
17
- store: SignalKeyStore,
18
- logger: Logger,
19
- _cache?: CacheStore
20
- ): SignalKeyStore {
21
- const cache = _cache || new NodeCache({
22
- stdTTL: DEFAULT_CACHE_TTLS.SIGNAL_STORE, // 5 minutes
23
- useClones: false,
24
- deleteOnExpire: true,
25
- })
26
-
27
- function getUniqueId(type: string, id: string) {
28
- return `${type}.${id}`
29
- }
30
-
31
- return {
32
- async get(type, ids) {
33
- const data: { [_: string]: SignalDataTypeMap[typeof type] } = { }
34
- const idsToFetch: string[] = []
35
- for(const id of ids) {
36
- const item = cache.get<SignalDataTypeMap[typeof type]>(getUniqueId(type, id))
37
- if(typeof item !== 'undefined') {
38
- data[id] = item
39
- } else {
40
- idsToFetch.push(id)
41
- }
42
- }
43
-
44
- if(idsToFetch.length) {
45
- logger.trace({ items: idsToFetch.length }, 'loading from store')
46
- const fetched = await store.get(type, idsToFetch)
47
- for(const id of idsToFetch) {
48
- const item = fetched[id]
49
- if(item) {
50
- data[id] = item
51
- cache.set(getUniqueId(type, id), item)
52
- }
53
- }
54
- }
55
-
56
- return data
57
- },
58
- async set(data) {
59
- let keys = 0
60
- for(const type in data) {
61
- for(const id in data[type]) {
62
- cache.set(getUniqueId(type, id), data[type][id])
63
- keys += 1
64
- }
65
- }
66
-
67
- logger.trace({ keys }, 'updated cache')
68
-
69
- await store.set(data)
70
- },
71
- async clear() {
72
- cache.flushAll()
73
- await store.clear?.()
74
- }
75
- }
76
- }
77
-
78
- /**
79
- * Adds DB like transaction capability (https://en.wikipedia.org/wiki/Database_transaction) to the SignalKeyStore,
80
- * this allows batch read & write operations & improves the performance of the lib
81
- * @param state the key store to apply this capability to
82
- * @param logger logger to log events
83
- * @returns SignalKeyStore with transaction capability
84
- */
85
- export const addTransactionCapability = (
86
- state: SignalKeyStore,
87
- logger: Logger,
88
- { maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions
89
- ): SignalKeyStoreWithTransaction => {
90
- // number of queries made to the DB during the transaction
91
- // only there for logging purposes
92
- let dbQueriesInTransaction = 0
93
- let transactionCache: SignalDataSet = { }
94
- let mutations: SignalDataSet = { }
95
-
96
- let transactionsInProgress = 0
97
-
98
- return {
99
- get: async(type, ids) => {
100
- if(isInTransaction()) {
101
- const dict = transactionCache[type]
102
- const idsRequiringFetch = dict
103
- ? ids.filter(item => typeof dict[item] === 'undefined')
104
- : ids
105
- // only fetch if there are any items to fetch
106
- if(idsRequiringFetch.length) {
107
- dbQueriesInTransaction += 1
108
- const result = await state.get(type, idsRequiringFetch)
109
-
110
- transactionCache[type] ||= {}
111
- Object.assign(
112
- transactionCache[type]!,
113
- result
114
- )
115
- }
116
-
117
- return ids.reduce(
118
- (dict, id) => {
119
- const value = transactionCache[type]?.[id]
120
- if(value) {
121
- dict[id] = value
122
- }
123
-
124
- return dict
125
- }, { }
126
- )
127
- } else {
128
- return state.get(type, ids)
129
- }
130
- },
131
- set: data => {
132
- if(isInTransaction()) {
133
- logger.trace({ types: Object.keys(data) }, 'caching in transaction')
134
- for(const key in data) {
135
- transactionCache[key] = transactionCache[key] || { }
136
- Object.assign(transactionCache[key], data[key])
137
-
138
- mutations[key] = mutations[key] || { }
139
- Object.assign(mutations[key], data[key])
140
- }
141
- } else {
142
- return state.set(data)
143
- }
144
- },
145
- isInTransaction,
146
- async transaction(work) {
147
- let result: Awaited<ReturnType<typeof work>>
148
- transactionsInProgress += 1
149
- if(transactionsInProgress === 1) {
150
- logger.trace('entering transaction')
151
- }
152
-
153
- try {
154
- result = await work()
155
- // commit if this is the outermost transaction
156
- if(transactionsInProgress === 1) {
157
- if(Object.keys(mutations).length) {
158
- logger.trace('committing transaction')
159
- // retry mechanism to ensure we've some recovery
160
- // in case a transaction fails in the first attempt
161
- let tries = maxCommitRetries
162
- while(tries) {
163
- tries -= 1
164
- try {
165
- await state.set(mutations)
166
- logger.trace({ dbQueriesInTransaction }, 'committed transaction')
167
- break
168
- } catch(error) {
169
- logger.warn(`failed to commit ${Object.keys(mutations).length} mutations, tries left=${tries}`)
170
- await delay(delayBetweenTriesMs)
171
- }
172
- }
173
- } else {
174
- logger.trace('no mutations in transaction')
175
- }
176
- }
177
- } finally {
178
- transactionsInProgress -= 1
179
- if(transactionsInProgress === 0) {
180
- transactionCache = { }
181
- mutations = { }
182
- dbQueriesInTransaction = 0
183
- }
184
- }
185
-
186
- return result
187
- }
188
- }
189
-
190
- function isInTransaction() {
191
- return transactionsInProgress > 0
192
- }
193
- }
194
-
195
- export const initAuthCreds = (): AuthenticationCreds => {
196
- const identityKey = Curve.generateKeyPair()
197
- return {
198
- noiseKey: Curve.generateKeyPair(),
199
- pairingEphemeralKeyPair: Curve.generateKeyPair(),
200
- signedIdentityKey: identityKey,
201
- signedPreKey: signedKeyPair(identityKey, 1),
202
- registrationId: generateRegistrationId(),
203
- advSecretKey: randomBytes(32).toString('base64'),
204
- processedHistoryMessages: [],
205
- nextPreKeyId: 1,
206
- firstUnuploadedPreKeyId: 1,
207
- accountSyncCounter: 0,
208
- accountSettings: {
209
- unarchiveChats: false
210
- },
211
- // mobile creds
212
- deviceId: Buffer.from(uuidv4().replace(/-/g, ''), 'hex').toString('base64url'),
213
- phoneId: uuidv4(),
214
- identityId: randomBytes(20),
215
- registered: false,
216
- backupToken: randomBytes(20),
217
- registration: {} as never,
218
- pairingCode: undefined,
219
- lastPropHash: undefined,
220
- routingInfo: undefined,
221
- }
222
- }
@@ -1,92 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __asyncValues = (this && this.__asyncValues) || function (o) {
12
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
- var m = o[Symbol.asyncIterator], i;
14
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
- };
18
- var __importDefault = (this && this.__importDefault) || function (mod) {
19
- return (mod && mod.__esModule) ? mod : { "default": mod };
20
- };
21
- Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.readAndEmitEventStream = exports.captureEventStream = void 0;
23
- const events_1 = __importDefault(require("events"));
24
- const fs_1 = require("fs");
25
- const promises_1 = require("fs/promises");
26
- const readline_1 = require("readline");
27
- const generics_1 = require("./generics");
28
- const make_mutex_1 = require("./make-mutex");
29
- /**
30
- * Captures events from a baileys event emitter & stores them in a file
31
- * @param ev The event emitter to read events from
32
- * @param filename File to save to
33
- */
34
- const captureEventStream = (ev, filename) => {
35
- const oldEmit = ev.emit;
36
- // write mutex so data is appended in order
37
- const writeMutex = (0, make_mutex_1.makeMutex)();
38
- // monkey patch eventemitter to capture all events
39
- ev.emit = function (...args) {
40
- const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
41
- const result = oldEmit.apply(ev, args);
42
- writeMutex.mutex(() => __awaiter(this, void 0, void 0, function* () {
43
- yield (0, promises_1.writeFile)(filename, content, { flag: 'a' });
44
- }));
45
- return result;
46
- };
47
- };
48
- exports.captureEventStream = captureEventStream;
49
- /**
50
- * Read event file and emit events from there
51
- * @param filename filename containing event data
52
- * @param delayIntervalMs delay between each event emit
53
- */
54
- const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
55
- const ev = new events_1.default();
56
- const fireEvents = () => __awaiter(void 0, void 0, void 0, function* () {
57
- var _a, e_1, _b, _c;
58
- // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
59
- const fileStream = (0, fs_1.createReadStream)(filename);
60
- const rl = (0, readline_1.createInterface)({
61
- input: fileStream,
62
- crlfDelay: Infinity
63
- });
64
- try {
65
- // Note: we use the crlfDelay option to recognize all instances of CR LF
66
- // ('\r\n') in input.txt as a single line break.
67
- for (var _d = true, rl_1 = __asyncValues(rl), rl_1_1; rl_1_1 = yield rl_1.next(), _a = rl_1_1.done, !_a; _d = true) {
68
- _c = rl_1_1.value;
69
- _d = false;
70
- const line = _c;
71
- if (line) {
72
- const { event, data } = JSON.parse(line);
73
- ev.emit(event, data);
74
- delayIntervalMs && (yield (0, generics_1.delay)(delayIntervalMs));
75
- }
76
- }
77
- }
78
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
79
- finally {
80
- try {
81
- if (!_d && !_a && (_b = rl_1.return)) yield _b.call(rl_1);
82
- }
83
- finally { if (e_1) throw e_1.error; }
84
- }
85
- fileStream.close();
86
- });
87
- return {
88
- ev,
89
- task: fireEvents()
90
- };
91
- };
92
- exports.readAndEmitEventStream = readAndEmitEventStream;
@@ -1,66 +0,0 @@
1
- import EventEmitter from 'events'
2
- import { createReadStream } from 'fs'
3
- import { writeFile } from 'fs/promises'
4
- import { createInterface } from 'readline'
5
- import type { BaileysEventEmitter } from '../Types'
6
- import { delay } from './generics'
7
- import { makeMutex } from './make-mutex'
8
-
9
- /**
10
- * Captures events from a baileys event emitter & stores them in a file
11
- * @param ev The event emitter to read events from
12
- * @param filename File to save to
13
- */
14
- export const captureEventStream = (ev: BaileysEventEmitter, filename: string) => {
15
- const oldEmit = ev.emit
16
- // write mutex so data is appended in order
17
- const writeMutex = makeMutex()
18
- // monkey patch eventemitter to capture all events
19
- ev.emit = function(...args: any[]) {
20
- const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n'
21
- const result = oldEmit.apply(ev, args)
22
-
23
- writeMutex.mutex(
24
- async() => {
25
- await writeFile(filename, content, { flag: 'a' })
26
- }
27
- )
28
-
29
- return result
30
- }
31
- }
32
-
33
- /**
34
- * Read event file and emit events from there
35
- * @param filename filename containing event data
36
- * @param delayIntervalMs delay between each event emit
37
- */
38
- export const readAndEmitEventStream = (filename: string, delayIntervalMs: number = 0) => {
39
- const ev = new EventEmitter() as BaileysEventEmitter
40
-
41
- const fireEvents = async() => {
42
- // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
43
- const fileStream = createReadStream(filename)
44
-
45
- const rl = createInterface({
46
- input: fileStream,
47
- crlfDelay: Infinity
48
- })
49
- // Note: we use the crlfDelay option to recognize all instances of CR LF
50
- // ('\r\n') in input.txt as a single line break.
51
- for await (const line of rl) {
52
- if(line) {
53
- const { event, data } = JSON.parse(line)
54
- ev.emit(event, data)
55
- delayIntervalMs && await delay(delayIntervalMs)
56
- }
57
- }
58
-
59
- fileStream.close()
60
- }
61
-
62
- return {
63
- ev,
64
- task: fireEvents()
65
- }
66
- }