@hiroosy/baileys-lite 0.0.3 → 0.3.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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,702 @@
1
+ import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+
3
+ const MAGIC = '{"nsql":1}'
4
+ const COMPACT_MIN_BYTES = 1024 * 1024
5
+ const CONTROL = new Set(['begin', 'commit', 'rollback'])
6
+ const TOKEN = /\s+|'((?:[^']|'')*)'|"([^"]*)"|`([^`]*)`|\[([^\]]*)\]|(\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?)|([A-Za-z_]\w*)|([(),;=?*.-])/y
7
+
8
+ class SqlError extends Error {
9
+ constructor(message) {
10
+ super(message)
11
+ this.name = 'SqlError'
12
+ }
13
+ }
14
+
15
+ const lower = name => name.toLowerCase()
16
+
17
+ const keyOf = (table, row) => JSON.stringify(table.pk.map(i => row[i]))
18
+
19
+ const bind = (count, params) => {
20
+ if (params.length !== count) throw new SqlError(`expected ${count} parameters, got ${params.length}`)
21
+ return params.map(value => {
22
+ if (value === null || typeof value === 'string') return value
23
+ if (typeof value === 'boolean') return Number(value)
24
+ if (typeof value === 'number' && Number.isFinite(value)) return value
25
+ throw new SqlError(`unsupported parameter type: ${typeof value}`)
26
+ })
27
+ }
28
+
29
+ const tokenize = sql => {
30
+ const tokens = []
31
+ TOKEN.lastIndex = 0
32
+ while (TOKEN.lastIndex < sql.length) {
33
+ const at = TOKEN.lastIndex
34
+ const m = TOKEN.exec(sql)
35
+ if (!m) throw new SqlError(`unexpected character at offset ${at}`)
36
+ const end = TOKEN.lastIndex
37
+ let token = null
38
+ if (m[1] !== undefined) token = { k: 'str', v: m[1].replace(/''/g, "'") }
39
+ else if (m[5] !== undefined) token = { k: 'num', v: Number(m[5]) }
40
+ else if (m[6] !== undefined) token = { k: 'id', v: m[6] }
41
+ else if (m[7] !== undefined) token = { k: 'p', v: m[7] }
42
+ else if (m[2] !== undefined || m[3] !== undefined || m[4] !== undefined) token = { k: 'id', v: m[2] ?? m[3] ?? m[4] }
43
+ if (token) tokens.push({ ...token, at, end })
44
+ }
45
+ tokens.push({ k: 'eof', at: sql.length, end: sql.length })
46
+ return tokens
47
+ }
48
+
49
+ class Parser {
50
+ constructor(tokens) {
51
+ this.tokens = tokens
52
+ this.pos = 0
53
+ this.params = 0
54
+ }
55
+
56
+ peek() {
57
+ return this.tokens[this.pos]
58
+ }
59
+
60
+ next() {
61
+ return this.tokens[this.pos++]
62
+ }
63
+
64
+ isKw(word) {
65
+ const t = this.peek()
66
+ return t.k === 'id' && t.v.toUpperCase() === word
67
+ }
68
+
69
+ eatKw(word) {
70
+ if (!this.isKw(word)) return false
71
+ this.pos++
72
+ return true
73
+ }
74
+
75
+ expectKw(word) {
76
+ if (!this.eatKw(word)) throw new SqlError(`expected ${word}`)
77
+ }
78
+
79
+ isP(ch) {
80
+ const t = this.peek()
81
+ return t.k === 'p' && t.v === ch
82
+ }
83
+
84
+ eatP(ch) {
85
+ if (!this.isP(ch)) return false
86
+ this.pos++
87
+ return true
88
+ }
89
+
90
+ expectP(ch) {
91
+ if (!this.eatP(ch)) throw new SqlError(`expected '${ch}'`)
92
+ }
93
+
94
+ ident() {
95
+ const t = this.next()
96
+ if (t.k !== 'id') throw new SqlError('expected identifier')
97
+ return t.v
98
+ }
99
+
100
+ identList() {
101
+ this.expectP('(')
102
+ const names = [this.ident()]
103
+ while (this.eatP(',')) names.push(this.ident())
104
+ this.expectP(')')
105
+ return names
106
+ }
107
+
108
+ operand() {
109
+ const t = this.next()
110
+ if (t.k === 'str' || t.k === 'num') return { kind: 'lit', value: t.v }
111
+ if (t.k === 'p' && t.v === '?') return { kind: 'param', index: this.params++ }
112
+ if (t.k === 'p' && t.v === '-' && this.peek().k === 'num') return { kind: 'lit', value: -this.next().v }
113
+ if (t.k === 'id' && t.v.toUpperCase() === 'NULL') return { kind: 'lit', value: null }
114
+ if (t.k === 'id' && t.v.toUpperCase() === 'EXCLUDED' && this.eatP('.')) return { kind: 'excluded', column: this.ident() }
115
+ throw new SqlError('unsupported expression')
116
+ }
117
+
118
+ statement() {
119
+ const t = this.peek()
120
+ const word = t.k === 'id' ? t.v.toUpperCase() : ''
121
+ switch (word) {
122
+ case 'CREATE':
123
+ return this.create()
124
+ case 'INSERT':
125
+ return this.insert()
126
+ case 'SELECT':
127
+ return this.select()
128
+ case 'DELETE':
129
+ return this.remove()
130
+ case 'PRAGMA':
131
+ return this.skip()
132
+ case 'BEGIN':
133
+ return this.control('begin')
134
+ case 'COMMIT':
135
+ case 'END':
136
+ return this.control('commit')
137
+ case 'ROLLBACK':
138
+ return this.control('rollback')
139
+ default:
140
+ throw new SqlError(`unsupported statement${word ? ` ${word}` : ''}`)
141
+ }
142
+ }
143
+
144
+ control(type) {
145
+ this.next()
146
+ this.eatKw('TRANSACTION')
147
+ return { type, write: false }
148
+ }
149
+
150
+ skip() {
151
+ this.next()
152
+ while (!this.isP(';') && this.peek().k !== 'eof') this.next()
153
+ return { type: 'noop', write: false }
154
+ }
155
+
156
+ create() {
157
+ this.next()
158
+ if (this.isKw('UNIQUE')) throw new SqlError('unique indexes are not supported')
159
+ if (this.eatKw('TABLE')) return this.createTable()
160
+ if (this.eatKw('INDEX')) return this.createIndex()
161
+ throw new SqlError('unsupported CREATE statement')
162
+ }
163
+
164
+ ifNotExists() {
165
+ if (!this.eatKw('IF')) return false
166
+ this.expectKw('NOT')
167
+ this.expectKw('EXISTS')
168
+ return true
169
+ }
170
+
171
+ createTable() {
172
+ const ifNotExists = this.ifNotExists()
173
+ const name = this.ident()
174
+ this.expectP('(')
175
+ const columns = []
176
+ let primaryKey = null
177
+ do {
178
+ if (this.eatKw('PRIMARY')) {
179
+ this.expectKw('KEY')
180
+ primaryKey = this.identList()
181
+ } else {
182
+ columns.push(this.columnDef())
183
+ }
184
+ } while (this.eatP(','))
185
+ this.expectP(')')
186
+ const key = primaryKey ?? columns.filter(c => c.primary).map(c => c.name)
187
+ if (!key.length) throw new SqlError(`table ${name} needs a PRIMARY KEY`)
188
+ return { type: 'create_table', name, ifNotExists, columns, primaryKey: key, write: true }
189
+ }
190
+
191
+ columnDef() {
192
+ const column = { name: this.ident(), notNull: false, primary: false }
193
+ if (this.peek().k === 'id' && !this.isKw('NOT') && !this.isKw('PRIMARY')) this.next()
194
+ for (;;) {
195
+ if (this.eatKw('NOT')) {
196
+ this.expectKw('NULL')
197
+ column.notNull = true
198
+ } else if (this.eatKw('PRIMARY')) {
199
+ this.expectKw('KEY')
200
+ column.primary = true
201
+ } else {
202
+ return column
203
+ }
204
+ }
205
+ }
206
+
207
+ createIndex() {
208
+ const ifNotExists = this.ifNotExists()
209
+ const name = this.ident()
210
+ this.expectKw('ON')
211
+ const table = this.ident()
212
+ const columns = this.identList()
213
+ return { type: 'create_index', name, table, columns, ifNotExists, write: true }
214
+ }
215
+
216
+ insert() {
217
+ this.next()
218
+ let replace = false
219
+ if (this.eatKw('OR')) {
220
+ this.expectKw('REPLACE')
221
+ replace = true
222
+ }
223
+ this.expectKw('INTO')
224
+ const table = this.ident()
225
+ const columns = this.isP('(') ? this.identList() : null
226
+ this.expectKw('VALUES')
227
+ this.expectP('(')
228
+ const values = [this.operand()]
229
+ while (this.eatP(',')) values.push(this.operand())
230
+ this.expectP(')')
231
+ let onConflict = null
232
+ if (this.eatKw('ON')) {
233
+ this.expectKw('CONFLICT')
234
+ const target = this.identList()
235
+ this.expectKw('DO')
236
+ if (this.eatKw('NOTHING')) {
237
+ onConflict = { target, action: 'nothing' }
238
+ } else {
239
+ this.expectKw('UPDATE')
240
+ this.expectKw('SET')
241
+ const sets = []
242
+ do {
243
+ const column = this.ident()
244
+ this.expectP('=')
245
+ sets.push({ column, operand: this.operand() })
246
+ } while (this.eatP(','))
247
+ onConflict = { target, action: 'update', sets }
248
+ }
249
+ }
250
+ return { type: 'insert', table, columns, values, replace, onConflict, write: true }
251
+ }
252
+
253
+ select() {
254
+ this.next()
255
+ let columns = '*'
256
+ if (!this.eatP('*')) {
257
+ columns = [this.ident()]
258
+ while (this.eatP(',')) columns.push(this.ident())
259
+ }
260
+ this.expectKw('FROM')
261
+ const table = this.ident()
262
+ return { type: 'select', table, columns, where: this.where(), write: false }
263
+ }
264
+
265
+ remove() {
266
+ this.next()
267
+ this.expectKw('FROM')
268
+ const table = this.ident()
269
+ return { type: 'delete', table, where: this.where(), write: true }
270
+ }
271
+
272
+ where() {
273
+ const conditions = []
274
+ if (!this.eatKw('WHERE')) return conditions
275
+ do {
276
+ const column = this.ident()
277
+ this.expectP('=')
278
+ conditions.push({ column, operand: this.operand() })
279
+ } while (this.eatKw('AND'))
280
+ return conditions
281
+ }
282
+ }
283
+
284
+ const parseStatements = sql => {
285
+ const parser = new Parser(tokenize(sql))
286
+ const statements = []
287
+ while (parser.peek().k !== 'eof') {
288
+ if (parser.eatP(';')) continue
289
+ const start = parser.peek().at
290
+ parser.params = 0
291
+ const stmt = parser.statement()
292
+ const end = parser.tokens[parser.pos - 1].end
293
+ if (!parser.eatP(';') && parser.peek().k !== 'eof') throw new SqlError('expected ;')
294
+ stmt.text = sql.slice(start, end)
295
+ stmt.paramCount = parser.params
296
+ statements.push(stmt)
297
+ }
298
+ return statements
299
+ }
300
+
301
+ export class SqlDatabase {
302
+ #tables = new Map()
303
+ #indexes = new Map()
304
+ #undo = []
305
+ #pending = []
306
+ #inTxn = false
307
+ #path = null
308
+ #logBytes = 0
309
+ #baseBytes = 0
310
+ #closed = false
311
+
312
+ constructor(path = ':memory:') {
313
+ if (path !== ':memory:') this.#open(path)
314
+ }
315
+
316
+ exec(sql) {
317
+ this.#assertOpen()
318
+ for (const stmt of parseStatements(sql)) this.#invoke(stmt, [])
319
+ }
320
+
321
+ prepare(sql) {
322
+ this.#assertOpen()
323
+ const statements = parseStatements(sql)
324
+ if (statements.length !== 1) throw new SqlError('prepare expects exactly one statement')
325
+ const [stmt] = statements
326
+ return {
327
+ run: (...params) => ({ changes: this.#invoke(stmt, params).changes }),
328
+ get: (...params) => this.#invoke(stmt, params).rows[0],
329
+ all: (...params) => this.#invoke(stmt, params).rows
330
+ }
331
+ }
332
+
333
+ transaction(fn) {
334
+ return (...args) => {
335
+ this.#assertOpen()
336
+ if (this.#inTxn) return fn(...args)
337
+ this.#control('begin')
338
+ try {
339
+ const result = fn(...args)
340
+ this.#commit()
341
+ return result
342
+ } catch (err) {
343
+ this.#rollback()
344
+ throw err
345
+ }
346
+ }
347
+ }
348
+
349
+ close() {
350
+ this.#rollback()
351
+ this.#closed = true
352
+ }
353
+
354
+ #assertOpen() {
355
+ if (this.#closed) throw new SqlError('database is closed')
356
+ }
357
+
358
+ #invoke(stmt, params) {
359
+ this.#assertOpen()
360
+ if (CONTROL.has(stmt.type)) return this.#control(stmt.type)
361
+ const values = bind(stmt.paramCount, params)
362
+ return this.#statement(() => {
363
+ const result = this.#execute(stmt, values)
364
+ if (stmt.write && result.changes) this.#pending.push([stmt.text, values])
365
+ return result
366
+ })
367
+ }
368
+
369
+ #control(type) {
370
+ if (type === 'begin') {
371
+ if (this.#inTxn) throw new SqlError('cannot start a transaction within a transaction')
372
+ this.#inTxn = true
373
+ } else if (!this.#inTxn) {
374
+ throw new SqlError('no transaction is active')
375
+ } else if (type === 'commit') {
376
+ this.#commit()
377
+ } else {
378
+ this.#rollback()
379
+ }
380
+ return { changes: 0, rows: [] }
381
+ }
382
+
383
+ #statement(fn) {
384
+ const auto = !this.#inTxn
385
+ if (auto) this.#inTxn = true
386
+ const mark = this.#undo.length
387
+ const pmark = this.#pending.length
388
+ let result
389
+ try {
390
+ result = fn()
391
+ } catch (err) {
392
+ this.#undoTo(mark)
393
+ this.#pending.length = pmark
394
+ if (auto) this.#end()
395
+ throw err
396
+ }
397
+ if (auto) this.#commit()
398
+ return result
399
+ }
400
+
401
+ #commit() {
402
+ try {
403
+ if (this.#path !== null && this.#pending.length) this.#append(this.#pending)
404
+ } catch (err) {
405
+ this.#rollback()
406
+ throw err
407
+ }
408
+ this.#end()
409
+ this.#maybeCompact()
410
+ }
411
+
412
+ #rollback() {
413
+ this.#undoTo(0)
414
+ this.#end()
415
+ }
416
+
417
+ #undoTo(mark) {
418
+ while (this.#undo.length > mark) this.#undo.pop()()
419
+ }
420
+
421
+ #end() {
422
+ this.#undo = []
423
+ this.#pending = []
424
+ this.#inTxn = false
425
+ }
426
+
427
+ #execute(stmt, params) {
428
+ switch (stmt.type) {
429
+ case 'create_table':
430
+ return this.#createTable(stmt)
431
+ case 'create_index':
432
+ return this.#createIndex(stmt)
433
+ case 'insert':
434
+ return this.#insert(stmt, params)
435
+ case 'delete':
436
+ return this.#deleteRows(stmt, params)
437
+ case 'select':
438
+ return this.#selectRows(stmt, params)
439
+ default:
440
+ return { changes: 0, rows: [] }
441
+ }
442
+ }
443
+
444
+ #table(name) {
445
+ const table = this.#tables.get(lower(name))
446
+ if (!table) throw new SqlError(`no such table: ${name}`)
447
+ return table
448
+ }
449
+
450
+ #column(table, name) {
451
+ const i = table.colIndex.get(lower(name))
452
+ if (i === undefined) throw new SqlError(`no such column: ${name}`)
453
+ return i
454
+ }
455
+
456
+ #isPrimaryKey(table, names) {
457
+ const cols = names.map(n => this.#column(table, n))
458
+ return cols.length === table.pk.length && cols.every(i => table.pk.includes(i))
459
+ }
460
+
461
+ #value(operand, params) {
462
+ if (operand.kind === 'param') return params[operand.index]
463
+ if (operand.kind === 'lit') return operand.value
464
+ throw new SqlError('excluded is only valid in ON CONFLICT ... DO UPDATE SET')
465
+ }
466
+
467
+ #checkNotNull(table, row) {
468
+ table.columns.forEach((c, i) => {
469
+ if (c.notNull && row[i] === null) throw new SqlError(`NOT NULL constraint failed: ${table.name}.${c.name}`)
470
+ })
471
+ }
472
+
473
+ #createTable(stmt) {
474
+ const key = lower(stmt.name)
475
+ if (this.#tables.has(key)) {
476
+ if (stmt.ifNotExists) return { changes: 0, rows: [] }
477
+ throw new SqlError(`table ${stmt.name} already exists`)
478
+ }
479
+ const pkNames = stmt.primaryKey.map(lower)
480
+ const columns = stmt.columns.map(c => ({ name: c.name, notNull: c.notNull || pkNames.includes(lower(c.name)) }))
481
+ const colIndex = new Map(columns.map((c, i) => [lower(c.name), i]))
482
+ const pk = stmt.primaryKey.map(name => {
483
+ const i = colIndex.get(lower(name))
484
+ if (i === undefined) throw new SqlError(`no such column: ${name}`)
485
+ return i
486
+ })
487
+ const table = { name: stmt.name, sql: stmt.text, columns, colIndex, pk, rows: new Map(), indexes: [] }
488
+ this.#tables.set(key, table)
489
+ this.#undo.push(() => this.#tables.delete(key))
490
+ return { changes: 1, rows: [] }
491
+ }
492
+
493
+ #createIndex(stmt) {
494
+ const key = lower(stmt.name)
495
+ if (this.#indexes.has(key)) {
496
+ if (stmt.ifNotExists) return { changes: 0, rows: [] }
497
+ throw new SqlError(`index ${stmt.name} already exists`)
498
+ }
499
+ const table = this.#table(stmt.table)
500
+ const index = {
501
+ name: stmt.name,
502
+ sql: stmt.text,
503
+ columns: stmt.columns.map(c => this.#column(table, c)),
504
+ entries: new Map()
505
+ }
506
+ for (const [rowKey, row] of table.rows) this.#addEntry(index, rowKey, row)
507
+ table.indexes.push(index)
508
+ this.#indexes.set(key, index)
509
+ this.#undo.push(() => {
510
+ table.indexes.splice(table.indexes.indexOf(index), 1)
511
+ this.#indexes.delete(key)
512
+ })
513
+ return { changes: 1, rows: [] }
514
+ }
515
+
516
+ #insert(stmt, params) {
517
+ const table = this.#table(stmt.table)
518
+ const names = stmt.columns ?? table.columns.map(c => c.name)
519
+ if (names.length !== stmt.values.length) throw new SqlError(`${names.length} columns but ${stmt.values.length} values supplied`)
520
+ if (stmt.onConflict && !this.#isPrimaryKey(table, stmt.onConflict.target)) throw new SqlError('ON CONFLICT target must be the primary key')
521
+ const row = table.columns.map(() => null)
522
+ names.forEach((name, i) => {
523
+ row[this.#column(table, name)] = this.#value(stmt.values[i], params)
524
+ })
525
+ this.#checkNotNull(table, row)
526
+ const rowKey = keyOf(table, row)
527
+ const existing = table.rows.get(rowKey)
528
+ if (!existing) {
529
+ this.#storeRow(table, rowKey, row)
530
+ return { changes: 1, rows: [] }
531
+ }
532
+ const action = stmt.onConflict?.action
533
+ if (action === 'nothing') return { changes: 0, rows: [] }
534
+ if (action === 'update') return this.#upsertConflict(table, rowKey, existing, stmt.onConflict.sets, row, params)
535
+ if (stmt.replace) {
536
+ this.#storeRow(table, rowKey, row)
537
+ return { changes: 1, rows: [] }
538
+ }
539
+ throw new SqlError(`UNIQUE constraint failed: ${table.pk.map(i => `${table.name}.${table.columns[i].name}`).join(', ')}`)
540
+ }
541
+
542
+ #upsertConflict(table, rowKey, existing, sets, incoming, params) {
543
+ const next = existing.slice()
544
+ for (const { column, operand } of sets) {
545
+ next[this.#column(table, column)] = operand.kind === 'excluded'
546
+ ? incoming[this.#column(table, operand.column)]
547
+ : this.#value(operand, params)
548
+ }
549
+ if (table.pk.some(i => next[i] !== existing[i])) throw new SqlError('primary key cannot be changed on conflict')
550
+ this.#checkNotNull(table, next)
551
+ this.#storeRow(table, rowKey, next)
552
+ return { changes: 1, rows: [] }
553
+ }
554
+
555
+ #deleteRows(stmt, params) {
556
+ const table = this.#table(stmt.table)
557
+ let changes = 0
558
+ for (const row of this.#match(table, stmt.where, params)) {
559
+ if (this.#removeRow(table, keyOf(table, row))) changes++
560
+ }
561
+ return { changes, rows: [] }
562
+ }
563
+
564
+ #selectRows(stmt, params) {
565
+ const table = this.#table(stmt.table)
566
+ const names = stmt.columns === '*' ? table.columns.map(c => c.name) : stmt.columns
567
+ const picks = names.map(n => this.#column(table, n))
568
+ const rows = this.#match(table, stmt.where, params).map(row => Object.fromEntries(names.map((n, i) => [n, row[picks[i]]])))
569
+ return { changes: 0, rows }
570
+ }
571
+
572
+ #match(table, where, params) {
573
+ const bound = where.map(({ column, operand }) => ({ index: this.#column(table, column), value: this.#value(operand, params) }))
574
+ const wanted = new Map(bound.map(({ index, value }) => [index, value]))
575
+ return this.#candidates(table, wanted).filter(row => bound.every(({ index, value }) => value !== null && row[index] === value))
576
+ }
577
+
578
+ #candidates(table, wanted) {
579
+ if (table.pk.every(i => wanted.has(i))) {
580
+ const row = table.rows.get(JSON.stringify(table.pk.map(i => wanted.get(i))))
581
+ return row ? [row] : []
582
+ }
583
+ for (const index of table.indexes) {
584
+ if (index.columns.every(i => wanted.has(i))) {
585
+ const keys = index.entries.get(JSON.stringify(index.columns.map(i => wanted.get(i))))
586
+ return keys ? [...keys].map(k => table.rows.get(k)) : []
587
+ }
588
+ }
589
+ return [...table.rows.values()]
590
+ }
591
+
592
+ #addEntry(index, rowKey, row) {
593
+ const k = JSON.stringify(index.columns.map(i => row[i]))
594
+ let set = index.entries.get(k)
595
+ if (!set) {
596
+ set = new Set()
597
+ index.entries.set(k, set)
598
+ }
599
+ set.add(rowKey)
600
+ }
601
+
602
+ #removeEntry(index, rowKey, row) {
603
+ const k = JSON.stringify(index.columns.map(i => row[i]))
604
+ const set = index.entries.get(k)
605
+ if (!set) return
606
+ set.delete(rowKey)
607
+ if (!set.size) index.entries.delete(k)
608
+ }
609
+
610
+ #indexRow(table, rowKey, row) {
611
+ for (const index of table.indexes) this.#addEntry(index, rowKey, row)
612
+ }
613
+
614
+ #unindexRow(table, rowKey, row) {
615
+ for (const index of table.indexes) this.#removeEntry(index, rowKey, row)
616
+ }
617
+
618
+ #storeRow(table, rowKey, row) {
619
+ const prev = table.rows.get(rowKey)
620
+ if (prev) this.#unindexRow(table, rowKey, prev)
621
+ table.rows.set(rowKey, row)
622
+ this.#indexRow(table, rowKey, row)
623
+ this.#undo.push(() => this.#restoreRow(table, rowKey, prev))
624
+ }
625
+
626
+ #removeRow(table, rowKey) {
627
+ const prev = table.rows.get(rowKey)
628
+ if (!prev) return false
629
+ this.#unindexRow(table, rowKey, prev)
630
+ table.rows.delete(rowKey)
631
+ this.#undo.push(() => this.#restoreRow(table, rowKey, prev))
632
+ return true
633
+ }
634
+
635
+ #restoreRow(table, rowKey, prev) {
636
+ const current = table.rows.get(rowKey)
637
+ if (current) this.#unindexRow(table, rowKey, current)
638
+ if (prev) {
639
+ table.rows.set(rowKey, prev)
640
+ this.#indexRow(table, rowKey, prev)
641
+ } else {
642
+ table.rows.delete(rowKey)
643
+ }
644
+ }
645
+
646
+ #open(path) {
647
+ let text = existsSync(path) ? readFileSync(path, 'utf8') : ''
648
+ const fresh = text === ''
649
+ if (fresh) text = `${MAGIC}\n`
650
+ const lines = text.split('\n')
651
+ const tail = lines.pop()
652
+ if (lines[0] !== MAGIC) throw new SqlError(`${path} is not a native sql database file`)
653
+ for (const line of lines.slice(1)) this.#replay(line)
654
+ this.#path = path
655
+ this.#logBytes = this.#baseBytes = Buffer.byteLength(text)
656
+ if (fresh) writeFileSync(path, text)
657
+ else if (tail !== '') this.#compact()
658
+ }
659
+
660
+ #replay(line) {
661
+ if (line === '') return
662
+ let entries
663
+ try {
664
+ entries = JSON.parse(line)
665
+ } catch {
666
+ throw new SqlError('corrupted sql log entry')
667
+ }
668
+ for (const [sql, params] of entries) {
669
+ const [stmt] = parseStatements(sql)
670
+ this.#invoke(stmt, params)
671
+ }
672
+ }
673
+
674
+ #append(entries) {
675
+ const line = `${JSON.stringify(entries)}\n`
676
+ appendFileSync(this.#path, line)
677
+ this.#logBytes += Buffer.byteLength(line)
678
+ }
679
+
680
+ #maybeCompact() {
681
+ if (this.#path === null || this.#logBytes < COMPACT_MIN_BYTES || this.#logBytes < 2 * this.#baseBytes) return
682
+ try {
683
+ this.#compact()
684
+ } catch {}
685
+ }
686
+
687
+ #compact() {
688
+ const entries = []
689
+ for (const table of this.#tables.values()) entries.push([table.sql, []])
690
+ for (const index of this.#indexes.values()) entries.push([index.sql, []])
691
+ for (const table of this.#tables.values()) {
692
+ const names = table.columns.map(c => `"${c.name}"`).join(', ')
693
+ const sql = `INSERT INTO "${table.name}" (${names}) VALUES (${table.columns.map(() => '?').join(', ')})`
694
+ for (const row of table.rows.values()) entries.push([sql, row])
695
+ }
696
+ const text = `${MAGIC}\n${JSON.stringify(entries)}\n`
697
+ const tmp = `${this.#path}.tmp`
698
+ writeFileSync(tmp, text)
699
+ renameSync(tmp, this.#path)
700
+ this.#logBytes = this.#baseBytes = Buffer.byteLength(text)
701
+ }
702
+ }