@hiroosy/baileys-lite 0.0.1

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 (63) hide show
  1. package/README.md +25 -0
  2. package/WAProto/index.d.ts +15932 -0
  3. package/WAProto/index.js +115856 -0
  4. package/engine-requirements.js +11 -0
  5. package/package.json +27 -0
  6. package/src/binary/wa-binary-constants.js +1300 -0
  7. package/src/binary/wa-binary.js +649 -0
  8. package/src/constants.js +143 -0
  9. package/src/defaults.js +102 -0
  10. package/src/foundation/audio-duration.js +530 -0
  11. package/src/foundation/audio-samples.js +268 -0
  12. package/src/foundation/boom.js +46 -0
  13. package/src/foundation/cache.js +142 -0
  14. package/src/foundation/concurrency.js +87 -0
  15. package/src/foundation/curve25519.js +221 -0
  16. package/src/foundation/link-preview.js +320 -0
  17. package/src/foundation/logger.js +69 -0
  18. package/src/foundation/long.js +140 -0
  19. package/src/foundation/protobuf-minimal.js +619 -0
  20. package/src/foundation/wa-crypto.js +76 -0
  21. package/src/foundation/zip.js +124 -0
  22. package/src/index.js +48 -0
  23. package/src/signal/libsignal.js +1051 -0
  24. package/src/signal/signal-group.js +487 -0
  25. package/src/signal/signal-repository.js +646 -0
  26. package/src/socket/business-communities.js +830 -0
  27. package/src/socket/chats.js +674 -0
  28. package/src/socket/groups-newsletter.js +342 -0
  29. package/src/socket/messages-recv.js +1835 -0
  30. package/src/socket/messages-send.js +1202 -0
  31. package/src/socket/socket-core.js +833 -0
  32. package/src/socket/usync.js +291 -0
  33. package/src/socket-client/websocket-client.js +124 -0
  34. package/src/utils/auth-state-core.js +764 -0
  35. package/src/utils/auth-state-storage.js +316 -0
  36. package/src/utils/chat-sync.js +1045 -0
  37. package/src/utils/media.js +841 -0
  38. package/src/utils/message-compose.js +1609 -0
  39. package/src/utils/message-processing.js +958 -0
  40. package/src/utils/wa-protocol-core.js +1283 -0
  41. package/src/vendor/jpeg-js/LICENSE +25 -0
  42. package/src/vendor/jpeg-js/decoder.js +1152 -0
  43. package/src/vendor/jpeg-js/encoder.js +824 -0
  44. package/src/vendor/pngjs/LICENSE +20 -0
  45. package/src/vendor/pngjs/bitmapper.js +273 -0
  46. package/src/vendor/pngjs/bitpacker.js +167 -0
  47. package/src/vendor/pngjs/constants.js +38 -0
  48. package/src/vendor/pngjs/crc.js +47 -0
  49. package/src/vendor/pngjs/filter-pack.js +179 -0
  50. package/src/vendor/pngjs/filter-parse-sync.js +27 -0
  51. package/src/vendor/pngjs/filter-parse.js +185 -0
  52. package/src/vendor/pngjs/format-normaliser.js +101 -0
  53. package/src/vendor/pngjs/interlace.js +101 -0
  54. package/src/vendor/pngjs/packer-sync.js +65 -0
  55. package/src/vendor/pngjs/packer.js +138 -0
  56. package/src/vendor/pngjs/paeth-predictor.js +22 -0
  57. package/src/vendor/pngjs/parser-sync.js +121 -0
  58. package/src/vendor/pngjs/parser.js +299 -0
  59. package/src/vendor/pngjs/png-sync.js +19 -0
  60. package/src/vendor/pngjs/sync-inflate.js +174 -0
  61. package/src/vendor/pngjs/sync-reader.js +54 -0
  62. package/src/wam/wam-constants.js +22853 -0
  63. package/src/wam/wam.js +151 -0
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Auth-state persistence adapters. Combines what used to be:
3
+ * use-multi-file-auth-state.js, use-single-file-auth-state.js, use-sqlite-auth-state.js
4
+ *
5
+ * SQLite backend is `node:sqlite` (built into Node, stable release-candidate as of Node 24; no
6
+ * install needed). `opts.database` still accepts any object shaped like `better-sqlite3` (or
7
+ * `node:sqlite`'s own DatabaseSync) if the app wants to bring its own connection/driver — see
8
+ * DB_ADAPTER below for the two shims that bridge the small API differences.
9
+ */
10
+ import { DatabaseSync } from 'node:sqlite'
11
+ import { mkdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises'
12
+ import { join } from 'node:path'
13
+ import { proto } from '../../WAProto/index.js'
14
+ import { initAuthCreds } from './auth-state-core.js'
15
+ import { BufferJSON } from './wa-protocol-core.js'
16
+ import { Cache } from '../foundation/cache.js'
17
+ import { makeKeyedMutex } from '../foundation/concurrency.js'
18
+
19
+ /* ------------------------------------------------------------------ */
20
+ /* Multi-file auth state (one JSON file per key) */
21
+ /* ------------------------------------------------------------------ */
22
+
23
+ /**
24
+ * stores the full authentication state in a single folder.
25
+ * Far more efficient than singlefileauthstate.
26
+ *
27
+ * Wouldn't endorse this for anything beyond a bot; use a proper DB for production.
28
+ */
29
+ export const useMultiFileAuthState = async folder => {
30
+ const fileLock = makeKeyedMutex() // guards concurrent read/write of the same file path
31
+
32
+ const fixFileName = file => file?.replace(/\//g, '__')?.replace(/:/g, '-')
33
+
34
+ const writeData = async (data, file) => {
35
+ const filePath = join(folder, fixFileName(file))
36
+ return fileLock.mutex(filePath, () => writeFile(filePath, JSON.stringify(data, BufferJSON.replacer)))
37
+ }
38
+ const readData = async file => {
39
+ try {
40
+ const filePath = join(folder, fixFileName(file))
41
+ return await fileLock.mutex(filePath, async () => {
42
+ const data = await readFile(filePath, { encoding: 'utf-8' })
43
+ return JSON.parse(data, BufferJSON.reviver)
44
+ })
45
+ } catch {
46
+ return null
47
+ }
48
+ }
49
+ const removeData = async file => {
50
+ try {
51
+ const filePath = join(folder, fixFileName(file))
52
+ await fileLock.mutex(filePath, async () => {
53
+ try {
54
+ await unlink(filePath)
55
+ } catch {
56
+ // ignore
57
+ }
58
+ })
59
+ } catch {
60
+ // ignore
61
+ }
62
+ }
63
+
64
+ const folderInfo = await stat(folder).catch(() => {})
65
+ if (folderInfo) {
66
+ if (!folderInfo.isDirectory()) {
67
+ throw new Error(`found something that is not a directory at ${folder}, either delete it or specify a different location`)
68
+ }
69
+ } else {
70
+ await mkdir(folder, { recursive: true })
71
+ }
72
+
73
+ const creds = (await readData('creds.json')) || initAuthCreds()
74
+
75
+ return {
76
+ state: {
77
+ creds,
78
+ keys: {
79
+ get: async (type, ids) => {
80
+ const data = {}
81
+ await Promise.all(
82
+ ids.map(async id => {
83
+ let value = await readData(`${type}-${id}.json`)
84
+ if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
85
+ data[id] = value
86
+ })
87
+ )
88
+ return data
89
+ },
90
+ set: async data => {
91
+ const tasks = []
92
+ for (const category in data) {
93
+ for (const id in data[category]) {
94
+ const value = data[category][id]
95
+ const file = `${category}-${id}.json`
96
+ tasks.push(value ? writeData(value, file) : removeData(file))
97
+ }
98
+ }
99
+ await Promise.all(tasks)
100
+ }
101
+ }
102
+ },
103
+ saveCreds: async () => writeData(creds, 'creds.json')
104
+ }
105
+ }
106
+
107
+ /* ------------------------------------------------------------------ */
108
+ /* Single-file auth state (one JSON file, in-memory cached) */
109
+ /* ------------------------------------------------------------------ */
110
+
111
+ const SIGNAL_STORE_TTL_MS = 5 * 60 * 1000
112
+ const FLUSH_TIMEOUT_MS = 3000
113
+
114
+ export const useSingleFileAuthState = async fileName => {
115
+ const cache = new Cache({ max: 20000, ttl: SIGNAL_STORE_TTL_MS })
116
+ const mutex = makeKeyedMutex()
117
+ let fileData = {}
118
+ let isLoaded = false
119
+ let flushTimeout = null
120
+
121
+ const loadKey = () =>
122
+ mutex.mutex('__file__', async () => {
123
+ if (isLoaded) return
124
+ try {
125
+ const data = JSON.parse(await readFile(fileName, 'utf-8'), BufferJSON.reviver)
126
+ fileData = data || {}
127
+ for (const [keyName, value] of Object.entries(fileData)) cache.set(keyName, value)
128
+ } catch {
129
+ fileData = {}
130
+ }
131
+ isLoaded = true
132
+ })
133
+
134
+ const flushKey = () => {
135
+ if (flushTimeout) return
136
+ flushTimeout = setTimeout(async () => {
137
+ flushTimeout = null
138
+ await mutex.mutex('__file__', async () => {
139
+ try {
140
+ const tempFile = fileName + '.temp'
141
+ await writeFile(tempFile, JSON.stringify(fileData, BufferJSON.replacer))
142
+ await rename(tempFile, fileName)
143
+ } catch {
144
+ // ignore
145
+ }
146
+ })
147
+ }, FLUSH_TIMEOUT_MS)
148
+ }
149
+
150
+ const writeKey = (keyName, value) => {
151
+ cache.set(keyName, value)
152
+ fileData[keyName] = value
153
+ flushKey()
154
+ }
155
+ const removeKey = keyName => {
156
+ cache.delete(keyName)
157
+ delete fileData[keyName]
158
+ flushKey()
159
+ }
160
+
161
+ const fileInfo = await stat(fileName).catch(() => null)
162
+ if (!fileInfo) {
163
+ await writeFile(fileName, '{}')
164
+ } else if (!fileInfo.isFile()) {
165
+ throw new Error(`found something that is not a file at ${fileName}, either delete it or specify a different location`)
166
+ }
167
+
168
+ await loadKey()
169
+ const creds = fileData['creds'] || initAuthCreds()
170
+
171
+ return {
172
+ state: {
173
+ creds,
174
+ keys: {
175
+ get: (type, ids) => {
176
+ const data = {}
177
+ for (const id of ids) {
178
+ const keyName = type + id
179
+ let value = cache.get(keyName)
180
+ if (value === undefined && fileData[keyName] !== undefined) {
181
+ value = fileData[keyName]
182
+ cache.set(keyName, value)
183
+ }
184
+ if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
185
+ data[id] = value
186
+ }
187
+ return data
188
+ },
189
+ set: data => {
190
+ for (const category in data) {
191
+ for (const id in data[category]) {
192
+ const keyName = category + id
193
+ const value = data[category][id]
194
+ value ? writeKey(keyName, value) : removeKey(keyName)
195
+ }
196
+ }
197
+ }
198
+ }
199
+ },
200
+ saveCreds: () => writeKey('creds', creds)
201
+ }
202
+ }
203
+
204
+ /* ------------------------------------------------------------------ */
205
+ /* SQLite auth state (built-in `node:sqlite`, no install required) */
206
+ /* ------------------------------------------------------------------ */
207
+
208
+ /**
209
+ * `node:sqlite`'s DatabaseSync has no `.pragma()` and no `.transaction()` (the two things
210
+ * `better-sqlite3` offers beyond plain `.exec()`/`.prepare()`). This adapter fills both in with
211
+ * the same net effect, and passes through untouched when `opts.database` is a `better-sqlite3`
212
+ * instance (or anything else that already has real `.pragma`/`.transaction` methods) so bring-
213
+ * your-own-driver keeps working exactly as before.
214
+ */
215
+ function adaptDb(db) {
216
+ const pragma = typeof db.pragma === 'function' ? stmt => db.pragma(stmt) : stmt => db.exec(`PRAGMA ${stmt}`)
217
+ const transaction =
218
+ typeof db.transaction === 'function'
219
+ ? fn => db.transaction(fn)
220
+ : fn =>
221
+ (...args) => {
222
+ db.exec('BEGIN')
223
+ try {
224
+ const result = fn(...args)
225
+ db.exec('COMMIT')
226
+ return result
227
+ } catch (err) {
228
+ db.exec('ROLLBACK')
229
+ throw err
230
+ }
231
+ }
232
+ return { db, pragma, transaction }
233
+ }
234
+
235
+ const CREDS_ROW_KEY = '__creds__'
236
+ const CREATE_SCHEMA_SQL = `
237
+ CREATE TABLE IF NOT EXISTS creds (
238
+ key TEXT PRIMARY KEY,
239
+ value TEXT NOT NULL
240
+ );
241
+ CREATE TABLE IF NOT EXISTS signal_keys (
242
+ type TEXT NOT NULL,
243
+ id TEXT NOT NULL,
244
+ value TEXT NOT NULL,
245
+ PRIMARY KEY (type, id)
246
+ );
247
+ CREATE INDEX IF NOT EXISTS signal_keys_type_idx ON signal_keys(type);
248
+ `
249
+
250
+ export async function useSqliteAuthState(opts) {
251
+ const rawDb = opts.database ?? new DatabaseSync(opts.dbPath)
252
+ const { db, pragma, transaction } = adaptDb(rawDb)
253
+ // WAL mode allows concurrent reads alongside a single writer; matches
254
+ // what SQLite recommends for read-heavy workloads with sporadic writes.
255
+ pragma('journal_mode = WAL')
256
+ pragma('synchronous = NORMAL')
257
+ db.exec(CREATE_SCHEMA_SQL)
258
+
259
+ const stmts = {
260
+ credsSelect: db.prepare('SELECT value FROM creds WHERE key = ?'),
261
+ credsUpsert: db.prepare('INSERT INTO creds (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
262
+ keySelect: db.prepare('SELECT value FROM signal_keys WHERE type = ? AND id = ?'),
263
+ keyUpsert: db.prepare('INSERT INTO signal_keys (type, id, value) VALUES (?, ?, ?) ON CONFLICT(type, id) DO UPDATE SET value = excluded.value'),
264
+ keyDelete: db.prepare('DELETE FROM signal_keys WHERE type = ? AND id = ?'),
265
+ keyListIds: db.prepare('SELECT id FROM signal_keys WHERE type = ?'),
266
+ keyList: db.prepare('SELECT id, value FROM signal_keys WHERE type = ?'),
267
+ clearKeys: db.prepare('DELETE FROM signal_keys')
268
+ }
269
+
270
+ const loadCreds = () => {
271
+ const row = stmts.credsSelect.get(CREDS_ROW_KEY)
272
+ if (!row) return initAuthCreds()
273
+ return JSON.parse(row.value, BufferJSON.reviver)
274
+ }
275
+ const persistCreds = creds => {
276
+ stmts.credsUpsert.run(CREDS_ROW_KEY, JSON.stringify(creds, BufferJSON.replacer))
277
+ }
278
+
279
+ const creds = loadCreds()
280
+
281
+ return {
282
+ state: {
283
+ creds,
284
+ keys: {
285
+ get: async (type, ids) => {
286
+ const data = {}
287
+ for (const id of ids) {
288
+ const row = stmts.keySelect.get(type, id)
289
+ if (row) {
290
+ let value = JSON.parse(row.value, BufferJSON.reviver)
291
+ if (type === 'app-state-sync-key' && value) value = proto.Message.AppStateSyncKeyData.fromObject(value)
292
+ data[id] = value
293
+ }
294
+ }
295
+ return data
296
+ },
297
+ set: async data => {
298
+ const writeTx = transaction(() => {
299
+ for (const category in data) {
300
+ for (const id in data[category]) {
301
+ const value = data[category][id]
302
+ if (value) {
303
+ stmts.keyUpsert.run(category, id, JSON.stringify(value, BufferJSON.replacer))
304
+ } else {
305
+ stmts.keyDelete.run(category, id)
306
+ }
307
+ }
308
+ }
309
+ })
310
+ writeTx()
311
+ }
312
+ }
313
+ },
314
+ saveCreds: async () => persistCreds(creds)
315
+ }
316
+ }