@baileys-md/baileys 12.0.0 → 12.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/LICENSE +21 -13
  2. package/WAProto/WAProto.proto +769 -233
  3. package/WAProto/index.js +65813 -141372
  4. package/lib/Defaults/index.js +128 -113
  5. package/lib/KeyDB/BinarySearch.js +30 -0
  6. package/lib/KeyDB/KeyedDB.js +178 -0
  7. package/lib/KeyDB/index.js +14 -0
  8. package/lib/Signal/Group/ciphertext-message.js +22 -14
  9. package/lib/Signal/Group/group-session-builder.js +21 -42
  10. package/lib/Signal/Group/group_cipher.js +85 -87
  11. package/lib/Signal/Group/index.js +23 -57
  12. package/lib/Signal/Group/keyhelper.js +28 -52
  13. package/lib/Signal/Group/sender-chain-key.js +37 -33
  14. package/lib/Signal/Group/sender-key-distribution-message.js +73 -63
  15. package/lib/Signal/Group/sender-key-message.js +75 -66
  16. package/lib/Signal/Group/sender-key-name.js +55 -44
  17. package/lib/Signal/Group/sender-key-record.js +49 -49
  18. package/lib/Signal/Group/sender-key-state.js +90 -93
  19. package/lib/Signal/Group/sender-message-key.js +37 -28
  20. package/lib/Signal/libsignal.js +324 -163
  21. package/lib/Signal/lid-mapping.js +166 -0
  22. package/lib/Socket/Client/index.js +14 -18
  23. package/lib/Socket/Client/types.js +12 -12
  24. package/lib/Socket/Client/websocket.js +60 -109
  25. package/lib/Socket/business.js +359 -242
  26. package/lib/Socket/chats.js +857 -898
  27. package/lib/Socket/communities.js +413 -0
  28. package/lib/Socket/groups.js +304 -324
  29. package/lib/Socket/index.js +25 -9
  30. package/lib/Socket/messages-recv.js +1109 -1000
  31. package/lib/Socket/messages-send.js +615 -387
  32. package/lib/Socket/mex.js +45 -0
  33. package/lib/Socket/newsletter.js +231 -227
  34. package/lib/Socket/socket.js +803 -628
  35. package/lib/Store/index.js +18 -8
  36. package/lib/Store/make-cache-manager-store.js +75 -0
  37. package/lib/Store/make-in-memory-store.js +286 -435
  38. package/lib/Store/make-ordered-dictionary.js +77 -79
  39. package/lib/Store/object-repository.js +24 -26
  40. package/lib/Types/Auth.js +13 -2
  41. package/lib/Types/Bussines.js +13 -0
  42. package/lib/Types/Call.js +13 -2
  43. package/lib/Types/Chat.js +19 -4
  44. package/lib/Types/Contact.js +13 -2
  45. package/lib/Types/Events.js +13 -2
  46. package/lib/Types/GroupMetadata.js +13 -2
  47. package/lib/Types/Label.js +43 -26
  48. package/lib/Types/LabelAssociation.js +16 -8
  49. package/lib/Types/Message.js +22 -7
  50. package/lib/Types/Newsletter.js +42 -17
  51. package/lib/Types/Product.js +13 -2
  52. package/lib/Types/Signal.js +13 -2
  53. package/lib/Types/Socket.js +14 -2
  54. package/lib/Types/State.js +21 -2
  55. package/lib/Types/USync.js +13 -2
  56. package/lib/Types/index.js +37 -41
  57. package/lib/Utils/auth-utils.js +219 -189
  58. package/lib/Utils/baileys-event-stream.js +54 -0
  59. package/lib/Utils/browser-utils.js +21 -31
  60. package/lib/Utils/business.js +213 -214
  61. package/lib/Utils/chat-utils.js +711 -689
  62. package/lib/Utils/crypto.js +112 -175
  63. package/lib/Utils/decode-wa-message.js +254 -194
  64. package/lib/Utils/event-buffer.js +510 -500
  65. package/lib/Utils/generics.js +318 -430
  66. package/lib/Utils/history.js +83 -90
  67. package/lib/Utils/index.js +31 -35
  68. package/lib/Utils/link-preview.js +71 -116
  69. package/lib/Utils/logger.js +5 -7
  70. package/lib/Utils/lt-hash.js +40 -46
  71. package/lib/Utils/make-mutex.js +34 -41
  72. package/lib/Utils/message-retry-manager.js +33 -48
  73. package/lib/Utils/messages-media.js +516 -784
  74. package/lib/Utils/messages.js +347 -489
  75. package/lib/Utils/noise-handler.js +138 -144
  76. package/lib/Utils/pre-key-manager.js +95 -0
  77. package/lib/Utils/process-message.js +331 -384
  78. package/lib/Utils/signal.js +157 -139
  79. package/lib/Utils/use-multi-file-auth-state.js +119 -91
  80. package/lib/Utils/validate-connection.js +184 -203
  81. package/lib/WABinary/constants.js +1308 -1298
  82. package/lib/WABinary/decode.js +241 -256
  83. package/lib/WABinary/encode.js +217 -239
  84. package/lib/WABinary/generic-utils.js +131 -40
  85. package/lib/WABinary/index.js +17 -21
  86. package/lib/WABinary/jid-utils.js +97 -79
  87. package/lib/WABinary/types.js +13 -2
  88. package/lib/WAM/BinaryInfo.js +20 -12
  89. package/lib/WAM/constants.js +22863 -15348
  90. package/lib/WAM/encode.js +145 -136
  91. package/lib/WAM/index.js +15 -19
  92. package/lib/WAUSync/Protocols/USyncContactProtocol.js +39 -31
  93. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +61 -54
  94. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +39 -29
  95. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +48 -40
  96. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +62 -51
  97. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +38 -21
  98. package/lib/WAUSync/Protocols/index.js +17 -20
  99. package/lib/WAUSync/USyncQuery.js +98 -86
  100. package/lib/WAUSync/USyncUser.js +35 -26
  101. package/lib/WAUSync/index.js +16 -19
  102. package/lib/index.js +23 -41
  103. package/package.json +46 -56
  104. package/README.md +0 -113
  105. package/WAProto/GenerateStatics.sh +0 -4
  106. package/lib/Defaults/wileys-version.json +0 -3
  107. package/lib/Signal/Group/queue-job.js +0 -57
  108. package/lib/Socket/usync.js +0 -70
  109. package/lib/Utils/wileys-event-stream.js +0 -63
package/lib/index.js CHANGED
@@ -1,44 +1,26 @@
1
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
2
- if (k2 === undefined) k2 = k;
3
- var desc = Object.getOwnPropertyDescriptor(m, k);
4
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
5
- desc = { enumerable: true, get: function() { return m[k]; } };
6
- }
7
- Object.defineProperty(o, k2, desc);
8
- }) : (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- o[k2] = m[k];
11
- }));
12
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
13
- for (var p in m)
14
- if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p))
15
- __createBinding(exports, m, p);
16
- };
17
- var __importDefault = (this && this.__importDefault) || function(mod) {
18
- return (mod && mod.__esModule) ? mod : { "default": mod };
19
- };
1
+ //========================================//
2
+ /**
3
+ * @project @sixcore/baileys
4
+ * @author Sixx.js </>🌿
5
+ * @version 1.0.3
6
+ * @license MIT
7
+ * @country Mozambique 🇲🇿♥️
8
+ * @chamadas || sms +258860817689
9
+ * @whatsApp +55889616-2417 || +258851907875
10
+ * @description Biblioteca Node.js para integração e automação no WhatsApp usando Baileys
11
+ */
12
+
20
13
 
21
- Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.proto = exports.makeWASocket = void 0;
14
+ import makeWASocket from "./Socket/index.js";
15
+ export * from "./Defaults/index.js";
16
+ export * from "./WABinary/index.js";
17
+ export * from "../WAProto/index.js";
18
+ export * from "./WAUSync/index.js";
19
+ export * from "./Store/index.js";
20
+ export * from "./Utils/index.js";
21
+ export * from "./Types/index.js";
22
+ export * from "./WAM/index.js";
23
23
 
24
- const WAProto_1 = require("../WAProto");
25
- Object.defineProperty(exports, "proto", {
26
- enumerable: true,
27
- get: function() {
28
- return WAProto_1.proto;
29
- }
30
- });
31
24
 
32
- const Socket_1 = __importDefault(require("./Socket"));
33
- exports.makeWASocket = Socket_1.default;
34
-
35
- __exportStar(require("../WAProto"), exports);
36
- __exportStar(require("./Utils"), exports);
37
- __exportStar(require("./Types"), exports);
38
- __exportStar(require("./Store"), exports);
39
- __exportStar(require("./Defaults"), exports);
40
- __exportStar(require("./WABinary"), exports);
41
- __exportStar(require("./WAM"), exports);
42
- __exportStar(require("./WAUSync"), exports);
43
-
44
- exports.default = Socket_1.default;
25
+ export { makeWASocket };
26
+ export default makeWASocket;
package/package.json CHANGED
@@ -1,66 +1,53 @@
1
1
  {
2
2
  "name": "@baileys-md/baileys",
3
- "version": "12.0.0",
4
- "description": "Forked, Minimized And Stabilized From Shamika WA Custom Baileys WhatsApp API",
5
- "keywords": ["whatsapp","js-whatsapp","whatsapp-api","whatsapp-web","WhiskeySockets", "@whiskeysockets","whiskeysockets", "@whiskey", "sockets","socket","@whiskeysockets/baileys","whatsapp","whatsapp-chat","whatsapp-group","baileys","baileys-md", "newsletter","news letter" , "automation","multi-device","ttdl","tiktok","tiktok scraper","tiktok no watermark","tiktok no wm","ttnowm","ytdl","ytmp3","ytmp4","youtube","instagram","instagram-dl","igdl"],
6
- "homepage": "https://github.com/WhiskeySockets/Baileys/",
3
+ "version": "12.2.0",
4
+ "type": "module",
5
+ "description": "Forked from Baileys core adaptado para @sixcore/baileys",
6
+ "keywords": ["whatsapp","js-whatsapp","whatsapp-api","whatsapp-web","WhiskeySockets", "@whiskeysockets","whiskeysockets", "@whiskey", "sockets","socket","@whiskeysockets/baileys","whatsapp","whatsapp-chat","whatsapp-group","baileys","baileys-md", "newsletter","news letter" , "automation","multi-device","ttdl","tiktok","tiktok scraper","tiktok no watermark","tiktok no wm","ttnowm","ytdl","ytmp3","ytmp4","youtube","instagram","instagram-dl","igdl"],
7
+ "homepage": "https://github.com/Ytsixx/lena-baileys",
7
8
  "repository": {
8
- "url": "git@github.com:WhiskeySockets/Baileys.git"
9
+ "type": "git",
10
+ "url": "git+https://github.com/Ytsixx/lena-baileys.git"
9
11
  },
10
-
11
12
  "license": "MIT",
12
- "author": "MR.Shamika",
13
-
14
- "main": "lib/index.js",
15
- "types": "lib/index.d.ts",
13
+ "author": "Sixx.js </>",
14
+ "main": "./lib/index.js",
16
15
  "files": [
17
- "lib/*",
18
- "WAProto/*"
19
- ],
16
+ "lib",
17
+ "WAProto"
18
+ ],
20
19
  "dependencies": {
21
- "@adiwajshing/keyed-db": "^0.2.4",
22
- "@cacheable/node-cache": "^1.4.0",
23
- "@hapi/boom": "^9.1.3",
20
+ "@cacheable/node-cache": "^1.3.0",
21
+ "@hapi/boom": "^10.0.1",
22
+ "async-mutex": "^0.5.0",
24
23
  "axios": "1.3.2",
25
- "chalk": "2.4.2",
26
- "cache-manager": "4.0.1",
27
- "cheerio": "1.0.0-rc.10",
28
- "libphonenumber-js": "^1.10.20",
29
- "libsignal": "npm:@baileys-md/libsignal",
30
- "lodash": "^4.17.21",
31
- "lru-cache": "^11.2.5",
32
- "music-metadata": "^7.12.3",
33
- "pino": "^9.6",
34
- "protobufjs": "^6.11.3",
35
- "uuid": "^10.0.0",
36
- "ws": "^8.13.0"
24
+ "jimp": "0.16.2",
25
+ "cache-manager": "^7.2.8",
26
+ "libsignal-xeuka": "npm:@shennmine/libsignal-node@2.0.1",
27
+ "long": "^5.3.2",
28
+ "lru-cache": "^10.2.0",
29
+ "music-metadata": "^7.14.0",
30
+ "p-queue": "^8.0.1",
31
+ "pino": "^9.0.0",
32
+ "protobufjs": "^7.3.0",
33
+ "ws": "^8.17.0"
37
34
  },
38
35
  "devDependencies": {
39
- "@adiwajshing/eslint-config": "github:adiwajshing/eslint-config",
40
- "@types/got": "^9.6.11",
41
- "@types/jest": "^27.5.1",
42
- "@types/node": "^16.18.126",
43
- "@types/sharp": "^0.29.4",
44
- "@types/ws": "^8.0.0",
45
- "conventional-changelog-cli": "^2.2.2",
46
- "eslint": "^8.0.0",
47
- "jest": "^27.0.6",
48
- "jimp": "^0.16.1",
49
- "json": "^11.0.0",
36
+ "@types/jest": "^29.5.12",
37
+ "@types/node": "^20.12.0",
38
+ "@types/ws": "^8.5.10",
39
+ "conventional-changelog-cli": "^5.0.0",
40
+ "eslint": "^9.0.0",
41
+ "jest": "^29.7.0",
50
42
  "link-preview-js": "^3.0.0",
51
- "open": "^8.4.2",
52
- "qrcode-terminal": "^0.12.0",
53
- "release-it": "^15.10.3",
54
- "ts-jest": "^27.0.3",
55
- "ts-node": "^10.8.1",
56
- "typedoc": "^0.27.9",
57
- "typescript": "^5.8.2"
43
+ "open": "^10.1.0",
44
+ "protobufjs-cli": "^1.1.3",
45
+ "release-it": "^17.0.0"
58
46
  },
59
47
  "peerDependencies": {
60
- "audio-decode": "^2.1.3",
61
- "jimp": "^0.16.1",
62
- "link-preview-js": "^3.0.0",
63
- "qrcode-terminal": "^0.12.0"
48
+ "audio-decode": "*",
49
+ "jimp": ">=0.16.0",
50
+ "link-preview-js": "*"
64
51
  },
65
52
  "peerDependenciesMeta": {
66
53
  "audio-decode": {
@@ -71,13 +58,16 @@
71
58
  },
72
59
  "link-preview-js": {
73
60
  "optional": true
74
- },
75
- "qrcode-terminal": {
76
- "optional": true
77
61
  }
78
62
  },
79
- "packageManager": "yarn@1.22.19",
63
+ "packageManager": "pnpm@10.0.0",
80
64
  "engines": {
81
- "node": ">=20.0.0"
65
+ "node": ">=20"
66
+ },
67
+ "directories": {
68
+ "lib": "lib"
69
+ },
70
+ "bugs": {
71
+ "url": "https://github.com/Ytsixx/lena-baileys/issues"
82
72
  }
83
- }
73
+ }
package/README.md DELETED
@@ -1,113 +0,0 @@
1
- # <div align='center'>Typescript/Javascript WA Baileys Modification</div>
2
-
3
- <div align="center">
4
-
5
- <img src="https://i.ibb.co/93c0VgP7/shamika-wa-baileys.jpg" />
6
-
7
- </div>
8
-
9
- ## Important Note
10
-
11
- The original repository was initially removed by its creator and subsequently taken over by [WhiskeySockets](https://github.com/WhiskeySockets). Building upon this foundation, I have implemented several enhancements and introduced new features that were not present in the original repository. These improvements aim to elevate functionality and provide a more robust and versatile experience.
12
-
13
-
14
- > [!CAUTION]
15
- > NOTICE OF BREAKING CHANGE.
16
- >
17
- > As of 7.0.0, multiple breaking changes were introduced into the library.
18
- >
19
- > Please check out https://whiskey.so/migrate-latest for more information.
20
-
21
- # Important Note
22
- > [!IMPORTANT]
23
- >This is a temporary README.md, the new guide is in development and will this file will be replaced with .github/README.md (already a default on GitHub).
24
- >
25
- >New guide link: https://baileys.wiki
26
-
27
- ## Installation
28
-
29
- ### In package.json:
30
- ```json
31
- "dependencies": {
32
- "shamika-wa-baileys": "*"
33
- }
34
- ```
35
-
36
- ### Terminal Installation:
37
- ```
38
- npm install shamika-wa-baileys
39
- ```
40
-
41
- ### Use the stable version:
42
- ```
43
- yarn add shamika-wa-baileys
44
- ```
45
-
46
- ### Use the edge version (no guarantee of stability, but latest fixes + features)
47
- ```
48
- yarn add npm:shamika-wa-baileys
49
- ```
50
-
51
- ### Then import your code using:
52
- ```ts
53
- import makeWASocket from 'shamika-wa-baileys'
54
- ```
55
-
56
- ## Added Features and Improvements
57
- Here are some of the features and improvements I have added:
58
-
59
- - **Support for Sending Messages to Channels**
60
- - **Support for Button Messages and Interactive Messages**
61
- - **AI Message Icon**
62
- - **Profile Picture Settings**
63
- - **Custom Pairing Code**
64
- - **Libsignal Fixes**
65
-
66
-
67
- ### How Whatsapp Communicate With Us
68
-
69
- > [!TIP]
70
- > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
71
-
72
- - **Example:** Functionality to track the battery percentage of your phone. You enable logging and you'll see a message about your battery pop up in the console:
73
- ```
74
- {
75
- "level": 10,
76
- "fromMe": false,
77
- "frame": {
78
- "tag": "ib",
79
- "attrs": {
80
- "from": "@s.whatsapp.net"
81
- },
82
- "content": [
83
- {
84
- "tag": "edge_routing",
85
- "attrs": {},
86
- "content": [
87
- {
88
- "tag": "routing_info",
89
- "attrs": {},
90
- "content": {
91
- "type": "Buffer",
92
- "data": [8,2,8,5]
93
- }
94
- }
95
- ]
96
- }
97
- ]
98
- },
99
- "msg":"communication"
100
- }
101
- ```
102
-
103
- The `'frame'` is what the message received is, it has three components:
104
- - `tag` -- what this frame is about (eg. message will have 'message')
105
- - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
106
- - `content` -- the actual data (eg. a message node will have the actual message content in it)
107
- - read more about this format [here](/src/WABinary/readme.md)
108
- ---
109
-
110
- ## Notes
111
- Everything other than the modifications mentioned above remains the same as the original repository. You can check out the original repository at [WhiskeySockets](https://github.com/WhiskeySockets/Baileys)
112
-
113
- This was made purely for my own enjoyment and experimentation, so the original copyright belongs to the original owners.
@@ -1,4 +0,0 @@
1
- yarn pbjs -t static-module -w commonjs -o ./WAProto/index.js ./WAProto/WAProto.proto;
2
- yarn pbts -o ./WAProto/index.d.ts ./WAProto/index.js;
3
-
4
- #protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt=env=node,useOptionals=true,forceLong=long --ts_proto_out=. ./src/Binary/WAMessage.proto;
@@ -1,3 +0,0 @@
1
- {
2
- "version": [2, 3000, 1033959288]
3
- }
@@ -1,57 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = queueJob;
4
- const _queueAsyncBuckets = new Map();
5
- const _gcLimit = 10000;
6
- async function _asyncQueueExecutor(queue, cleanup) {
7
- let offt = 0;
8
- // eslint-disable-next-line no-constant-condition
9
- while (true) {
10
- const limit = Math.min(queue.length, _gcLimit);
11
- for (let i = offt; i < limit; i++) {
12
- const job = queue[i];
13
- try {
14
- job.resolve(await job.awaitable());
15
- }
16
- catch (e) {
17
- job.reject(e);
18
- }
19
- }
20
- if (limit < queue.length) {
21
- if (limit >= _gcLimit) {
22
- queue.splice(0, limit);
23
- offt = 0;
24
- }
25
- else {
26
- offt = limit;
27
- }
28
- }
29
- else {
30
- break;
31
- }
32
- }
33
- cleanup();
34
- }
35
- function queueJob(bucket, awaitable) {
36
- // Skip name assignment since it's readonly in strict mode
37
- if (typeof bucket !== 'string') {
38
- console.warn('Unhandled bucket type (for naming):', typeof bucket, bucket);
39
- }
40
- let inactive = false;
41
- if (!_queueAsyncBuckets.has(bucket)) {
42
- _queueAsyncBuckets.set(bucket, []);
43
- inactive = true;
44
- }
45
- const queue = _queueAsyncBuckets.get(bucket);
46
- const job = new Promise((resolve, reject) => {
47
- queue.push({
48
- awaitable,
49
- resolve: resolve,
50
- reject
51
- });
52
- });
53
- if (inactive) {
54
- _asyncQueueExecutor(queue, () => _queueAsyncBuckets.delete(bucket));
55
- }
56
- return job;
57
- }
@@ -1,70 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeUSyncSocket = void 0;
4
- const boom_1 = require("@hapi/boom");
5
- const WABinary_1 = require("../WABinary");
6
- const socket_1 = require("./socket");
7
- const makeUSyncSocket = (config) => {
8
- const sock = (0, socket_1.makeSocket)(config);
9
- const { generateMessageTag, query, } = sock;
10
- const executeUSyncQuery = async (usyncQuery) => {
11
- if (usyncQuery.protocols.length === 0) {
12
- throw new boom_1.Boom('USyncQuery must have at least one protocol');
13
- }
14
- // todo: validate users, throw WARNING on no valid users
15
- // variable below has only validated users
16
- const validUsers = usyncQuery.users;
17
- const userNodes = validUsers.map((user) => {
18
- return {
19
- tag: 'user',
20
- attrs: {
21
- jid: !user.phone ? user.id : undefined,
22
- },
23
- content: usyncQuery.protocols
24
- .map((a) => a.getUserElement(user))
25
- .filter(a => a !== null)
26
- };
27
- });
28
- const listNode = {
29
- tag: 'list',
30
- attrs: {},
31
- content: userNodes
32
- };
33
- const queryNode = {
34
- tag: 'query',
35
- attrs: {},
36
- content: usyncQuery.protocols.map((a) => a.getQueryElement())
37
- };
38
- const iq = {
39
- tag: 'iq',
40
- attrs: {
41
- to: WABinary_1.S_WHATSAPP_NET,
42
- type: 'get',
43
- xmlns: 'usync',
44
- },
45
- content: [
46
- {
47
- tag: 'usync',
48
- attrs: {
49
- context: usyncQuery.context,
50
- mode: usyncQuery.mode,
51
- sid: generateMessageTag(),
52
- last: 'true',
53
- index: '0',
54
- },
55
- content: [
56
- queryNode,
57
- listNode
58
- ]
59
- }
60
- ],
61
- };
62
- const result = await query(iq);
63
- return usyncQuery.parseUSyncQueryResult(result);
64
- };
65
- return {
66
- ...sock,
67
- executeUSyncQuery,
68
- };
69
- };
70
- exports.makeUSyncSocket = makeUSyncSocket;
@@ -1,63 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readAndEmitEventStream = exports.captureEventStream = void 0;
7
- const events_1 = __importDefault(require("events"));
8
- const fs_1 = require("fs");
9
- const promises_1 = require("fs/promises");
10
- const readline_1 = require("readline");
11
- const generics_1 = require("./generics");
12
- const make_mutex_1 = require("./make-mutex");
13
- /**
14
- * Captures events from a wileys event emitter & stores them in a file
15
- * @param ev The event emitter to read events from
16
- * @param filename File to save to
17
- */
18
- const captureEventStream = (ev, filename) => {
19
- const oldEmit = ev.emit;
20
- // write mutex so data is appended in order
21
- const writeMutex = (0, make_mutex_1.makeMutex)();
22
- // monkey patch eventemitter to capture all events
23
- ev.emit = function (...args) {
24
- const content = JSON.stringify({ timestamp: Date.now(), event: args[0], data: args[1] }) + '\n';
25
- const result = oldEmit.apply(ev, args);
26
- writeMutex.mutex(async () => {
27
- await (0, promises_1.writeFile)(filename, content, { flag: 'a' });
28
- });
29
- return result;
30
- };
31
- };
32
- exports.captureEventStream = captureEventStream;
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
- const readAndEmitEventStream = (filename, delayIntervalMs = 0) => {
39
- const ev = new events_1.default();
40
- const fireEvents = async () => {
41
- // from: https://stackoverflow.com/questions/6156501/read-a-file-one-line-at-a-time-in-node-js
42
- const fileStream = (0, fs_1.createReadStream)(filename);
43
- const rl = (0, readline_1.createInterface)({
44
- input: fileStream,
45
- crlfDelay: Infinity
46
- });
47
- // Note: we use the crlfDelay option to recognize all instances of CR LF
48
- // ('\r\n') in input.txt as a single line break.
49
- for await (const line of rl) {
50
- if (line) {
51
- const { event, data } = JSON.parse(line);
52
- ev.emit(event, data);
53
- delayIntervalMs && await (0, generics_1.delay)(delayIntervalMs);
54
- }
55
- }
56
- fileStream.close();
57
- };
58
- return {
59
- ev,
60
- task: fireEvents()
61
- };
62
- };
63
- exports.readAndEmitEventStream = readAndEmitEventStream;