gifted-baileys 1.5.0 → 1.5.5

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 (222) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1429 -684
  3. package/package.json +11 -26
  4. package/src/Defaults/baileys-version.json +3 -0
  5. package/{lib → src}/Defaults/index.js +16 -8
  6. package/src/Defaults/index.ts +131 -0
  7. package/src/Defaults/phonenumber-mcc.json +223 -0
  8. package/src/Signal/libsignal.js +180 -0
  9. package/src/Signal/libsignal.ts +141 -0
  10. package/src/Socket/Client/abstract-socket-client.ts +19 -0
  11. package/src/Socket/Client/index.ts +3 -0
  12. package/src/Socket/Client/mobile-socket-client.js +78 -0
  13. package/src/Socket/Client/mobile-socket-client.ts +66 -0
  14. package/src/Socket/Client/web-socket-client.js +75 -0
  15. package/src/Socket/Client/web-socket-client.ts +57 -0
  16. package/{lib → src}/Socket/business.js +33 -27
  17. package/src/Socket/business.ts +281 -0
  18. package/{lib → src}/Socket/chats.js +197 -178
  19. package/src/Socket/chats.ts +1030 -0
  20. package/{lib → src}/Socket/groups.js +69 -79
  21. package/src/Socket/groups.ts +356 -0
  22. package/{lib → src}/Socket/index.js +1 -4
  23. package/src/Socket/index.ts +13 -0
  24. package/{lib → src}/Socket/messages-recv.js +160 -108
  25. package/src/Socket/messages-recv.ts +985 -0
  26. package/{lib → src}/Socket/messages-send.js +183 -100
  27. package/src/Socket/messages-send.ts +871 -0
  28. package/src/Socket/newsletter.js +227 -0
  29. package/src/Socket/newsletter.ts +282 -0
  30. package/{lib → src}/Socket/registration.js +55 -63
  31. package/src/Socket/registration.ts +250 -0
  32. package/{lib → src}/Socket/socket.js +107 -66
  33. package/src/Socket/socket.ts +777 -0
  34. package/src/Store/index.ts +3 -0
  35. package/{lib → src}/Store/make-cache-manager-store.js +34 -25
  36. package/src/Store/make-cache-manager-store.ts +100 -0
  37. package/{lib → src}/Store/make-in-memory-store.js +51 -61
  38. package/src/Store/make-in-memory-store.ts +475 -0
  39. package/src/Store/make-ordered-dictionary.ts +86 -0
  40. package/{lib → src}/Store/object-repository.js +1 -1
  41. package/src/Store/object-repository.ts +32 -0
  42. package/src/Tests/test.app-state-sync.js +204 -0
  43. package/src/Tests/test.app-state-sync.ts +207 -0
  44. package/src/Tests/test.event-buffer.js +270 -0
  45. package/src/Tests/test.event-buffer.ts +319 -0
  46. package/src/Tests/test.key-store.js +76 -0
  47. package/src/Tests/test.key-store.ts +92 -0
  48. package/src/Tests/test.libsignal.js +141 -0
  49. package/src/Tests/test.libsignal.ts +186 -0
  50. package/src/Tests/test.media-download.js +93 -0
  51. package/src/Tests/test.media-download.ts +76 -0
  52. package/src/Tests/test.messages.js +33 -0
  53. package/src/Tests/test.messages.ts +37 -0
  54. package/src/Tests/utils.js +34 -0
  55. package/src/Tests/utils.ts +36 -0
  56. package/src/Types/Auth.ts +113 -0
  57. package/src/Types/Call.ts +15 -0
  58. package/src/Types/Chat.ts +106 -0
  59. package/{lib/Types/Contact.d.ts → src/Types/Contact.ts} +9 -8
  60. package/src/Types/Events.ts +93 -0
  61. package/src/Types/GroupMetadata.ts +53 -0
  62. package/{lib → src}/Types/Label.js +1 -1
  63. package/src/Types/Label.ts +36 -0
  64. package/{lib → src}/Types/LabelAssociation.js +1 -1
  65. package/{lib/Types/LabelAssociation.d.ts → src/Types/LabelAssociation.ts} +22 -16
  66. package/src/Types/Message.ts +288 -0
  67. package/src/Types/Newsletter.js +32 -0
  68. package/src/Types/Newsletter.ts +98 -0
  69. package/src/Types/Product.ts +85 -0
  70. package/src/Types/Signal.ts +68 -0
  71. package/{lib/Types/Socket.d.ts → src/Types/Socket.ts} +68 -56
  72. package/src/Types/State.ts +29 -0
  73. package/{lib → src}/Types/index.js +2 -1
  74. package/src/Types/index.ts +59 -0
  75. package/{lib → src}/Utils/auth-utils.js +95 -76
  76. package/src/Utils/auth-utils.ts +222 -0
  77. package/src/Utils/baileys-event-stream.js +92 -0
  78. package/src/Utils/baileys-event-stream.ts +66 -0
  79. package/{lib → src}/Utils/business.js +45 -17
  80. package/src/Utils/business.ts +275 -0
  81. package/{lib → src}/Utils/chat-utils.js +74 -46
  82. package/src/Utils/chat-utils.ts +860 -0
  83. package/{lib → src}/Utils/crypto.js +31 -21
  84. package/src/Utils/crypto.ts +131 -0
  85. package/src/Utils/decode-wa-message.js +211 -0
  86. package/src/Utils/decode-wa-message.ts +228 -0
  87. package/{lib → src}/Utils/event-buffer.js +13 -4
  88. package/src/Utils/event-buffer.ts +613 -0
  89. package/{lib → src}/Utils/generics.js +98 -45
  90. package/src/Utils/generics.ts +434 -0
  91. package/{lib → src}/Utils/history.js +39 -10
  92. package/src/Utils/history.ts +112 -0
  93. package/src/Utils/index.ts +17 -0
  94. package/{lib → src}/Utils/link-preview.js +54 -17
  95. package/src/Utils/link-preview.ts +122 -0
  96. package/src/Utils/logger.ts +3 -0
  97. package/src/Utils/lt-hash.ts +61 -0
  98. package/{lib → src}/Utils/make-mutex.js +13 -4
  99. package/src/Utils/make-mutex.ts +44 -0
  100. package/{lib → src}/Utils/messages-media.js +296 -192
  101. package/src/Utils/messages-media.ts +847 -0
  102. package/{lib → src}/Utils/messages.js +124 -113
  103. package/src/Utils/messages.ts +956 -0
  104. package/{lib → src}/Utils/noise-handler.js +16 -3
  105. package/src/Utils/noise-handler.ts +197 -0
  106. package/{lib → src}/Utils/process-message.js +33 -29
  107. package/src/Utils/process-message.ts +414 -0
  108. package/{lib → src}/Utils/signal.js +23 -14
  109. package/src/Utils/signal.ts +177 -0
  110. package/{lib → src}/Utils/use-multi-file-auth-state.js +28 -19
  111. package/src/Utils/use-multi-file-auth-state.ts +90 -0
  112. package/{lib → src}/Utils/validate-connection.js +25 -42
  113. package/src/Utils/validate-connection.ts +238 -0
  114. package/src/WABinary/constants.ts +42 -0
  115. package/{lib → src}/WABinary/decode.js +17 -7
  116. package/src/WABinary/decode.ts +265 -0
  117. package/{lib → src}/WABinary/encode.js +17 -7
  118. package/src/WABinary/encode.ts +236 -0
  119. package/{lib → src}/WABinary/generic-utils.js +2 -2
  120. package/src/WABinary/generic-utils.ts +121 -0
  121. package/src/WABinary/index.ts +5 -0
  122. package/{lib → src}/WABinary/jid-utils.js +4 -1
  123. package/src/WABinary/jid-utils.ts +68 -0
  124. package/src/WABinary/types.ts +17 -0
  125. package/src/WAM/BinaryInfo.js +13 -0
  126. package/src/WAM/BinaryInfo.ts +12 -0
  127. package/src/WAM/constants.js +15350 -0
  128. package/src/WAM/constants.ts +15382 -0
  129. package/src/WAM/encode.js +155 -0
  130. package/src/WAM/encode.ts +174 -0
  131. package/src/WAM/index.js +19 -0
  132. package/src/WAM/index.ts +3 -0
  133. package/src/gifted +1 -0
  134. package/{lib → src}/index.js +1 -0
  135. package/src/index.ts +13 -0
  136. package/lib/Defaults/baileys-version.json +0 -3
  137. package/lib/Defaults/index.d.ts +0 -284
  138. package/lib/Defaults/phonenumber-mcc.json +0 -223
  139. package/lib/Signal/libsignal.d.ts +0 -3
  140. package/lib/Signal/libsignal.js +0 -152
  141. package/lib/Socket/Client/abstract-socket-client.d.ts +0 -17
  142. package/lib/Socket/Client/index.d.ts +0 -3
  143. package/lib/Socket/Client/mobile-socket-client.d.ts +0 -13
  144. package/lib/Socket/Client/mobile-socket-client.js +0 -65
  145. package/lib/Socket/Client/web-socket-client.d.ts +0 -12
  146. package/lib/Socket/Client/web-socket-client.js +0 -62
  147. package/lib/Socket/business.d.ts +0 -135
  148. package/lib/Socket/chats.d.ts +0 -79
  149. package/lib/Socket/groups.d.ts +0 -113
  150. package/lib/Socket/index.d.ts +0 -137
  151. package/lib/Socket/messages-recv.d.ts +0 -124
  152. package/lib/Socket/messages-send.d.ts +0 -119
  153. package/lib/Socket/registration.d.ts +0 -232
  154. package/lib/Socket/socket.d.ts +0 -42
  155. package/lib/Store/index.d.ts +0 -3
  156. package/lib/Store/make-cache-manager-store.d.ts +0 -13
  157. package/lib/Store/make-in-memory-store.d.ts +0 -117
  158. package/lib/Store/make-ordered-dictionary.d.ts +0 -13
  159. package/lib/Store/object-repository.d.ts +0 -10
  160. package/lib/Types/Auth.d.ts +0 -108
  161. package/lib/Types/Call.d.ts +0 -13
  162. package/lib/Types/Chat.d.ts +0 -102
  163. package/lib/Types/Events.d.ts +0 -157
  164. package/lib/Types/GroupMetadata.d.ts +0 -52
  165. package/lib/Types/Label.d.ts +0 -35
  166. package/lib/Types/Message.d.ts +0 -261
  167. package/lib/Types/Product.d.ts +0 -78
  168. package/lib/Types/Signal.d.ts +0 -57
  169. package/lib/Types/State.d.ts +0 -27
  170. package/lib/Types/index.d.ts +0 -56
  171. package/lib/Utils/auth-utils.d.ts +0 -18
  172. package/lib/Utils/baileys-event-stream.d.ts +0 -16
  173. package/lib/Utils/baileys-event-stream.js +0 -63
  174. package/lib/Utils/business.d.ts +0 -22
  175. package/lib/Utils/chat-utils.d.ts +0 -71
  176. package/lib/Utils/crypto.d.ts +0 -41
  177. package/lib/Utils/decode-wa-message.d.ts +0 -19
  178. package/lib/Utils/decode-wa-message.js +0 -174
  179. package/lib/Utils/event-buffer.d.ts +0 -35
  180. package/lib/Utils/generics.d.ts +0 -94
  181. package/lib/Utils/history.d.ts +0 -15
  182. package/lib/Utils/index.d.ts +0 -17
  183. package/lib/Utils/link-preview.d.ts +0 -21
  184. package/lib/Utils/logger.d.ts +0 -4
  185. package/lib/Utils/lt-hash.d.ts +0 -12
  186. package/lib/Utils/make-mutex.d.ts +0 -7
  187. package/lib/Utils/messages-media.d.ts +0 -107
  188. package/lib/Utils/messages.d.ts +0 -76
  189. package/lib/Utils/noise-handler.d.ts +0 -20
  190. package/lib/Utils/process-message.d.ts +0 -41
  191. package/lib/Utils/signal.d.ts +0 -32
  192. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -12
  193. package/lib/Utils/validate-connection.d.ts +0 -11
  194. package/lib/WABinary/constants.d.ts +0 -27
  195. package/lib/WABinary/decode.d.ts +0 -7
  196. package/lib/WABinary/encode.d.ts +0 -3
  197. package/lib/WABinary/generic-utils.d.ts +0 -15
  198. package/lib/WABinary/index.d.ts +0 -5
  199. package/lib/WABinary/jid-utils.d.ts +0 -29
  200. package/lib/WABinary/types.d.ts +0 -18
  201. package/lib/index.d.ts +0 -10
  202. /package/{lib → src}/Socket/Client/abstract-socket-client.js +0 -0
  203. /package/{lib → src}/Socket/Client/index.js +0 -0
  204. /package/{lib → src}/Store/index.js +0 -0
  205. /package/{lib → src}/Store/make-ordered-dictionary.js +0 -0
  206. /package/{lib → src}/Types/Auth.js +0 -0
  207. /package/{lib → src}/Types/Call.js +0 -0
  208. /package/{lib → src}/Types/Chat.js +0 -0
  209. /package/{lib → src}/Types/Contact.js +0 -0
  210. /package/{lib → src}/Types/Events.js +0 -0
  211. /package/{lib → src}/Types/GroupMetadata.js +0 -0
  212. /package/{lib → src}/Types/Message.js +0 -0
  213. /package/{lib → src}/Types/Product.js +0 -0
  214. /package/{lib → src}/Types/Signal.js +0 -0
  215. /package/{lib → src}/Types/Socket.js +0 -0
  216. /package/{lib → src}/Types/State.js +0 -0
  217. /package/{lib → src}/Utils/index.js +0 -0
  218. /package/{lib → src}/Utils/logger.js +0 -0
  219. /package/{lib → src}/Utils/lt-hash.js +0 -0
  220. /package/{lib → src}/WABinary/constants.js +0 -0
  221. /package/{lib → src}/WABinary/index.js +0 -0
  222. /package/{lib → src}/WABinary/types.js +0 -0
@@ -0,0 +1,141 @@
1
+ import * as libsignal from 'libsignal'
2
+ import { GroupCipher, GroupSessionBuilder, SenderKeyDistributionMessage, SenderKeyName, SenderKeyRecord } from '../../WASignalGroup'
3
+ import { SignalAuthState } from '../Types'
4
+ import { SignalRepository } from '../Types/Signal'
5
+ import { generateSignalPubKey } from '../Utils'
6
+ import { jidDecode } from '../WABinary'
7
+
8
+ export function makeLibSignalRepository(auth: SignalAuthState): SignalRepository {
9
+ const storage = signalStorage(auth)
10
+ return {
11
+ decryptGroupMessage({ group, authorJid, msg }) {
12
+ const senderName = jidToSignalSenderKeyName(group, authorJid)
13
+ const cipher = new GroupCipher(storage, senderName)
14
+
15
+ return cipher.decrypt(msg)
16
+ },
17
+ async processSenderKeyDistributionMessage({ item, authorJid }) {
18
+ const builder = new GroupSessionBuilder(storage)
19
+ const senderName = jidToSignalSenderKeyName(item.groupId!, authorJid)
20
+
21
+ const senderMsg = new SenderKeyDistributionMessage(null, null, null, null, item.axolotlSenderKeyDistributionMessage)
22
+ const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
23
+ if(!senderKey) {
24
+ await storage.storeSenderKey(senderName, new SenderKeyRecord())
25
+ }
26
+
27
+ await builder.process(senderName, senderMsg)
28
+ },
29
+ async decryptMessage({ jid, type, ciphertext }) {
30
+ const addr = jidToSignalProtocolAddress(jid)
31
+ const session = new libsignal.SessionCipher(storage, addr)
32
+ let result: Buffer
33
+ switch (type) {
34
+ case 'pkmsg':
35
+ result = await session.decryptPreKeyWhisperMessage(ciphertext)
36
+ break
37
+ case 'msg':
38
+ result = await session.decryptWhisperMessage(ciphertext)
39
+ break
40
+ }
41
+
42
+ return result
43
+ },
44
+ async encryptMessage({ jid, data }) {
45
+ const addr = jidToSignalProtocolAddress(jid)
46
+ const cipher = new libsignal.SessionCipher(storage, addr)
47
+
48
+ const { type: sigType, body } = await cipher.encrypt(data)
49
+ const type = sigType === 3 ? 'pkmsg' : 'msg'
50
+ return { type, ciphertext: Buffer.from(body, 'binary') }
51
+ },
52
+ async encryptGroupMessage({ group, meId, data }) {
53
+ const senderName = jidToSignalSenderKeyName(group, meId)
54
+ const builder = new GroupSessionBuilder(storage)
55
+
56
+ const { [senderName]: senderKey } = await auth.keys.get('sender-key', [senderName])
57
+ if(!senderKey) {
58
+ await storage.storeSenderKey(senderName, new SenderKeyRecord())
59
+ }
60
+
61
+ const senderKeyDistributionMessage = await builder.create(senderName)
62
+ const session = new GroupCipher(storage, senderName)
63
+ const ciphertext = await session.encrypt(data)
64
+
65
+ return {
66
+ ciphertext,
67
+ senderKeyDistributionMessage: senderKeyDistributionMessage.serialize(),
68
+ }
69
+ },
70
+ async injectE2ESession({ jid, session }) {
71
+ const cipher = new libsignal.SessionBuilder(storage, jidToSignalProtocolAddress(jid))
72
+ await cipher.initOutgoing(session)
73
+ },
74
+ jidToSignalProtocolAddress(jid) {
75
+ return jidToSignalProtocolAddress(jid).toString()
76
+ },
77
+ }
78
+ }
79
+
80
+ const jidToSignalProtocolAddress = (jid: string) => {
81
+ const { user, device } = jidDecode(jid)!
82
+ return new libsignal.ProtocolAddress(user, device || 0)
83
+ }
84
+
85
+ const jidToSignalSenderKeyName = (group: string, user: string): string => {
86
+ return new SenderKeyName(group, jidToSignalProtocolAddress(user)).toString()
87
+ }
88
+
89
+ function signalStorage({ creds, keys }: SignalAuthState) {
90
+ return {
91
+ loadSession: async(id: string) => {
92
+ const { [id]: sess } = await keys.get('session', [id])
93
+ if(sess) {
94
+ return libsignal.SessionRecord.deserialize(sess)
95
+ }
96
+ },
97
+ storeSession: async(id, session) => {
98
+ await keys.set({ 'session': { [id]: session.serialize() } })
99
+ },
100
+ isTrustedIdentity: () => {
101
+ return true
102
+ },
103
+ loadPreKey: async(id: number | string) => {
104
+ const keyId = id.toString()
105
+ const { [keyId]: key } = await keys.get('pre-key', [keyId])
106
+ if(key) {
107
+ return {
108
+ privKey: Buffer.from(key.private),
109
+ pubKey: Buffer.from(key.public)
110
+ }
111
+ }
112
+ },
113
+ removePreKey: (id: number) => keys.set({ 'pre-key': { [id]: null } }),
114
+ loadSignedPreKey: () => {
115
+ const key = creds.signedPreKey
116
+ return {
117
+ privKey: Buffer.from(key.keyPair.private),
118
+ pubKey: Buffer.from(key.keyPair.public)
119
+ }
120
+ },
121
+ loadSenderKey: async(keyId: string) => {
122
+ const { [keyId]: key } = await keys.get('sender-key', [keyId])
123
+ if(key) {
124
+ return new SenderKeyRecord(key)
125
+ }
126
+ },
127
+ storeSenderKey: async(keyId, key) => {
128
+ await keys.set({ 'sender-key': { [keyId]: key.serialize() } })
129
+ },
130
+ getOurRegistrationId: () => (
131
+ creds.registrationId
132
+ ),
133
+ getOurIdentity: () => {
134
+ const { signedIdentityKey } = creds
135
+ return {
136
+ privKey: Buffer.from(signedIdentityKey.private),
137
+ pubKey: generateSignalPubKey(signedIdentityKey.public),
138
+ }
139
+ }
140
+ }
141
+ }
@@ -0,0 +1,19 @@
1
+ import { EventEmitter } from 'events'
2
+ import { URL } from 'url'
3
+ import { SocketConfig } from '../../Types'
4
+
5
+ export abstract class AbstractSocketClient extends EventEmitter {
6
+ abstract get isOpen(): boolean
7
+ abstract get isClosed(): boolean
8
+ abstract get isClosing(): boolean
9
+ abstract get isConnecting(): boolean
10
+
11
+ constructor(public url: URL, public config: SocketConfig) {
12
+ super()
13
+ this.setMaxListeners(0)
14
+ }
15
+
16
+ abstract connect(): Promise<void>
17
+ abstract close(): Promise<void>
18
+ abstract send(str: Uint8Array | string, cb?: (err?: Error) => void): boolean;
19
+ }
@@ -0,0 +1,3 @@
1
+ export * from './abstract-socket-client'
2
+ export * from './mobile-socket-client'
3
+ export * from './web-socket-client'
@@ -0,0 +1,78 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MobileSocketClient = void 0;
13
+ const net_1 = require("net");
14
+ const abstract_socket_client_1 = require("./abstract-socket-client");
15
+ class MobileSocketClient extends abstract_socket_client_1.AbstractSocketClient {
16
+ constructor() {
17
+ super(...arguments);
18
+ this.socket = null;
19
+ }
20
+ get isOpen() {
21
+ var _a;
22
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'open';
23
+ }
24
+ get isClosed() {
25
+ var _a;
26
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
27
+ }
28
+ get isClosing() {
29
+ var _a;
30
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'closed';
31
+ }
32
+ get isConnecting() {
33
+ var _a;
34
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === 'opening';
35
+ }
36
+ connect() {
37
+ return __awaiter(this, void 0, void 0, function* () {
38
+ var _a;
39
+ if (this.socket) {
40
+ return;
41
+ }
42
+ if (this.config.agent) {
43
+ throw new Error('There are not support for proxy agent for mobile connection');
44
+ }
45
+ else {
46
+ this.socket = (0, net_1.connect)({
47
+ host: this.url.hostname,
48
+ port: Number(this.url.port) || 443
49
+ });
50
+ }
51
+ this.socket.setMaxListeners(0);
52
+ const events = ['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'ready', 'timeout'];
53
+ for (const event of events) {
54
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.on(event, (...args) => this.emit(event, ...args));
55
+ }
56
+ this.socket.on('data', (...args) => this.emit('message', ...args));
57
+ this.socket.on('ready', (...args) => this.emit('open', ...args));
58
+ });
59
+ }
60
+ close() {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ if (!this.socket) {
63
+ return;
64
+ }
65
+ return new Promise(resolve => {
66
+ this.socket.end(resolve);
67
+ this.socket = null;
68
+ });
69
+ });
70
+ }
71
+ send(str, cb) {
72
+ if (this.socket === null) {
73
+ return false;
74
+ }
75
+ return this.socket.write(str, undefined, cb);
76
+ }
77
+ }
78
+ exports.MobileSocketClient = MobileSocketClient;
@@ -0,0 +1,66 @@
1
+ import { connect, Socket } from 'net'
2
+ import { AbstractSocketClient } from './abstract-socket-client'
3
+
4
+ export class MobileSocketClient extends AbstractSocketClient {
5
+ protected socket: Socket | null = null
6
+
7
+ get isOpen(): boolean {
8
+ return this.socket?.readyState === 'open'
9
+ }
10
+ get isClosed(): boolean {
11
+ return this.socket === null || this.socket?.readyState === 'closed'
12
+ }
13
+ get isClosing(): boolean {
14
+ return this.socket === null || this.socket?.readyState === 'closed'
15
+ }
16
+ get isConnecting(): boolean {
17
+ return this.socket?.readyState === 'opening'
18
+ }
19
+
20
+ async connect(): Promise<void> {
21
+ if(this.socket) {
22
+ return
23
+ }
24
+
25
+ if(this.config.agent) {
26
+
27
+ throw new Error('There are not support for proxy agent for mobile connection')
28
+ } else {
29
+ this.socket = connect({
30
+ host: this.url.hostname,
31
+ port: Number(this.url.port) || 443
32
+ })
33
+ }
34
+
35
+ this.socket.setMaxListeners(0)
36
+
37
+ const events = ['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'ready', 'timeout']
38
+
39
+ for(const event of events) {
40
+ this.socket?.on(event, (...args: any[]) => this.emit(event, ...args))
41
+ }
42
+
43
+ this.socket.on('data', (...args: any[]) => this.emit('message', ...args))
44
+ this.socket.on('ready', (...args: any[]) => this.emit('open', ...args))
45
+ }
46
+
47
+ async close(): Promise<void> {
48
+ if(!this.socket) {
49
+ return
50
+ }
51
+
52
+ return new Promise<void>(resolve => {
53
+ this.socket!.end(resolve)
54
+ this.socket = null
55
+ })
56
+ }
57
+
58
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean {
59
+ if(this.socket === null) {
60
+ return false
61
+ }
62
+
63
+ return this.socket.write(str, undefined, cb)
64
+ }
65
+
66
+ }
@@ -0,0 +1,75 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.WebSocketClient = void 0;
16
+ const ws_1 = __importDefault(require("ws"));
17
+ const Defaults_1 = require("../../Defaults");
18
+ const abstract_socket_client_1 = require("./abstract-socket-client");
19
+ class WebSocketClient extends abstract_socket_client_1.AbstractSocketClient {
20
+ constructor() {
21
+ super(...arguments);
22
+ this.socket = null;
23
+ }
24
+ get isOpen() {
25
+ var _a;
26
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.OPEN;
27
+ }
28
+ get isClosed() {
29
+ var _a;
30
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CLOSED;
31
+ }
32
+ get isClosing() {
33
+ var _a;
34
+ return this.socket === null || ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CLOSING;
35
+ }
36
+ get isConnecting() {
37
+ var _a;
38
+ return ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.readyState) === ws_1.default.CONNECTING;
39
+ }
40
+ connect() {
41
+ return __awaiter(this, void 0, void 0, function* () {
42
+ var _a, _b;
43
+ if (this.socket) {
44
+ return;
45
+ }
46
+ this.socket = new ws_1.default(this.url, {
47
+ origin: Defaults_1.DEFAULT_ORIGIN,
48
+ headers: (_a = this.config.options) === null || _a === void 0 ? void 0 : _a.headers,
49
+ handshakeTimeout: this.config.connectTimeoutMs,
50
+ timeout: this.config.connectTimeoutMs,
51
+ agent: this.config.agent,
52
+ });
53
+ this.socket.setMaxListeners(0);
54
+ const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response'];
55
+ for (const event of events) {
56
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.on(event, (...args) => this.emit(event, ...args));
57
+ }
58
+ });
59
+ }
60
+ close() {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ if (!this.socket) {
63
+ return;
64
+ }
65
+ this.socket.close();
66
+ this.socket = null;
67
+ });
68
+ }
69
+ send(str, cb) {
70
+ var _a;
71
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.send(str, cb);
72
+ return Boolean(this.socket);
73
+ }
74
+ }
75
+ exports.WebSocketClient = WebSocketClient;
@@ -0,0 +1,57 @@
1
+ import WebSocket from 'ws'
2
+ import { DEFAULT_ORIGIN } from '../../Defaults'
3
+ import { AbstractSocketClient } from './abstract-socket-client'
4
+
5
+ export class WebSocketClient extends AbstractSocketClient {
6
+
7
+ protected socket: WebSocket | null = null
8
+
9
+ get isOpen(): boolean {
10
+ return this.socket?.readyState === WebSocket.OPEN
11
+ }
12
+ get isClosed(): boolean {
13
+ return this.socket === null || this.socket?.readyState === WebSocket.CLOSED
14
+ }
15
+ get isClosing(): boolean {
16
+ return this.socket === null || this.socket?.readyState === WebSocket.CLOSING
17
+ }
18
+ get isConnecting(): boolean {
19
+ return this.socket?.readyState === WebSocket.CONNECTING
20
+ }
21
+
22
+ async connect(): Promise<void> {
23
+ if(this.socket) {
24
+ return
25
+ }
26
+
27
+ this.socket = new WebSocket(this.url, {
28
+ origin: DEFAULT_ORIGIN,
29
+ headers: this.config.options?.headers as {},
30
+ handshakeTimeout: this.config.connectTimeoutMs,
31
+ timeout: this.config.connectTimeoutMs,
32
+ agent: this.config.agent,
33
+ })
34
+
35
+ this.socket.setMaxListeners(0)
36
+
37
+ const events = ['close', 'error', 'upgrade', 'message', 'open', 'ping', 'pong', 'unexpected-response']
38
+
39
+ for(const event of events) {
40
+ this.socket?.on(event, (...args: any[]) => this.emit(event, ...args))
41
+ }
42
+ }
43
+
44
+ async close(): Promise<void> {
45
+ if(!this.socket) {
46
+ return
47
+ }
48
+
49
+ this.socket.close()
50
+ this.socket = null
51
+ }
52
+ send(str: string | Uint8Array, cb?: (err?: Error) => void): boolean {
53
+ this.socket?.send(str, cb)
54
+
55
+ return Boolean(this.socket)
56
+ }
57
+ }
@@ -1,4 +1,13 @@
1
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
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
12
  exports.makeBusinessSocket = void 0;
4
13
  const business_1 = require("../Utils/business");
@@ -8,9 +17,9 @@ const messages_recv_1 = require("./messages-recv");
8
17
  const makeBusinessSocket = (config) => {
9
18
  const sock = (0, messages_recv_1.makeMessagesRecvSocket)(config);
10
19
  const { authState, query, waUploadToServer } = sock;
11
- const getCatalog = async ({ jid, limit, cursor }) => {
12
- var _a;
13
- jid = jid || ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id);
20
+ const getCatalog = (_a) => __awaiter(void 0, [_a], void 0, function* ({ jid, limit, cursor }) {
21
+ var _b;
22
+ jid = jid || ((_b = authState.creds.me) === null || _b === void 0 ? void 0 : _b.id);
14
23
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
15
24
  const queryParamNodes = [
16
25
  {
@@ -36,7 +45,7 @@ const makeBusinessSocket = (config) => {
36
45
  content: cursor
37
46
  });
38
47
  }
39
- const result = await query({
48
+ const result = yield query({
40
49
  tag: 'iq',
41
50
  attrs: {
42
51
  to: WABinary_1.S_WHATSAPP_NET,
@@ -55,12 +64,12 @@ const makeBusinessSocket = (config) => {
55
64
  ]
56
65
  });
57
66
  return (0, business_1.parseCatalogNode)(result);
58
- };
59
- const getCollections = async (jid, limit = 51) => {
67
+ });
68
+ const getCollections = (jid_1, ...args_1) => __awaiter(void 0, [jid_1, ...args_1], void 0, function* (jid, limit = 51) {
60
69
  var _a;
61
70
  jid = jid || ((_a = authState.creds.me) === null || _a === void 0 ? void 0 : _a.id);
62
71
  jid = (0, WABinary_1.jidNormalizedUser)(jid);
63
- const result = await query({
72
+ const result = yield query({
64
73
  tag: 'iq',
65
74
  attrs: {
66
75
  to: WABinary_1.S_WHATSAPP_NET,
@@ -100,9 +109,9 @@ const makeBusinessSocket = (config) => {
100
109
  ]
101
110
  });
102
111
  return (0, business_1.parseCollectionsNode)(result);
103
- };
104
- const getOrderDetails = async (orderId, tokenBase64) => {
105
- const result = await query({
112
+ });
113
+ const getOrderDetails = (orderId, tokenBase64) => __awaiter(void 0, void 0, void 0, function* () {
114
+ const result = yield query({
106
115
  tag: 'iq',
107
116
  attrs: {
108
117
  to: WABinary_1.S_WHATSAPP_NET,
@@ -144,11 +153,11 @@ const makeBusinessSocket = (config) => {
144
153
  ]
145
154
  });
146
155
  return (0, business_1.parseOrderDetailsNode)(result);
147
- };
148
- const productUpdate = async (productId, update) => {
149
- update = await (0, business_1.uploadingNecessaryImagesOfProduct)(update, waUploadToServer);
156
+ });
157
+ const productUpdate = (productId, update) => __awaiter(void 0, void 0, void 0, function* () {
158
+ update = yield (0, business_1.uploadingNecessaryImagesOfProduct)(update, waUploadToServer);
150
159
  const editNode = (0, business_1.toProductNode)(productId, update);
151
- const result = await query({
160
+ const result = yield query({
152
161
  tag: 'iq',
153
162
  attrs: {
154
163
  to: WABinary_1.S_WHATSAPP_NET,
@@ -178,13 +187,13 @@ const makeBusinessSocket = (config) => {
178
187
  const productCatalogEditNode = (0, generic_utils_1.getBinaryNodeChild)(result, 'product_catalog_edit');
179
188
  const productNode = (0, generic_utils_1.getBinaryNodeChild)(productCatalogEditNode, 'product');
180
189
  return (0, business_1.parseProductNode)(productNode);
181
- };
182
- const productCreate = async (create) => {
190
+ });
191
+ const productCreate = (create) => __awaiter(void 0, void 0, void 0, function* () {
183
192
  // ensure isHidden is defined
184
193
  create.isHidden = !!create.isHidden;
185
- create = await (0, business_1.uploadingNecessaryImagesOfProduct)(create, waUploadToServer);
194
+ create = yield (0, business_1.uploadingNecessaryImagesOfProduct)(create, waUploadToServer);
186
195
  const createNode = (0, business_1.toProductNode)(undefined, create);
187
- const result = await query({
196
+ const result = yield query({
188
197
  tag: 'iq',
189
198
  attrs: {
190
199
  to: WABinary_1.S_WHATSAPP_NET,
@@ -214,9 +223,9 @@ const makeBusinessSocket = (config) => {
214
223
  const productCatalogAddNode = (0, generic_utils_1.getBinaryNodeChild)(result, 'product_catalog_add');
215
224
  const productNode = (0, generic_utils_1.getBinaryNodeChild)(productCatalogAddNode, 'product');
216
225
  return (0, business_1.parseProductNode)(productNode);
217
- };
218
- const productDelete = async (productIds) => {
219
- const result = await query({
226
+ });
227
+ const productDelete = (productIds) => __awaiter(void 0, void 0, void 0, function* () {
228
+ const result = yield query({
220
229
  tag: 'iq',
221
230
  attrs: {
222
231
  to: WABinary_1.S_WHATSAPP_NET,
@@ -245,15 +254,12 @@ const makeBusinessSocket = (config) => {
245
254
  return {
246
255
  deleted: +((productCatalogDelNode === null || productCatalogDelNode === void 0 ? void 0 : productCatalogDelNode.attrs.deleted_count) || 0)
247
256
  };
248
- };
249
- return {
250
- ...sock,
251
- getOrderDetails,
257
+ });
258
+ return Object.assign(Object.assign({}, sock), { logger: config.logger, getOrderDetails,
252
259
  getCatalog,
253
260
  getCollections,
254
261
  productCreate,
255
262
  productDelete,
256
- productUpdate
257
- };
263
+ productUpdate });
258
264
  };
259
265
  exports.makeBusinessSocket = makeBusinessSocket;