@itznomo/baileys 0.0.0-stage → 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.
- package/BUTTONS.md +153 -0
- package/Example/call-bot.mjs +38 -0
- package/Example/example.mjs +36 -0
- package/Example/full-bot-commands.mjs +319 -0
- package/Example/full-bot.mjs +77 -0
- package/LICENSE +21 -0
- package/README.md +543 -2
- package/WAProto/@dnuzi +1 -0
- package/WAProto/index.d.ts +15932 -0
- package/WAProto/index.js +113300 -0
- package/assets/banner.svg +17 -0
- package/assets/devider.svg +1 -0
- package/assets/features.svg +21 -0
- package/docs/CALLS.md +106 -0
- package/docs/FEATURES.md +1152 -0
- package/engine-requirements.js +19 -0
- package/index.d.ts +815 -0
- package/package.json +51 -4
- package/src/binary/wa-binary-constants.js +1300 -0
- package/src/binary/wa-binary.js +627 -0
- package/src/constants.js +147 -0
- package/src/defaults.js +106 -0
- package/src/foundation/ai-rich.js +654 -0
- package/src/foundation/audio-duration.js +470 -0
- package/src/foundation/audio-samples.js +250 -0
- package/src/foundation/boom.js +39 -0
- package/src/foundation/builders.js +851 -0
- package/src/foundation/cache.js +134 -0
- package/src/foundation/concurrency.js +69 -0
- package/src/foundation/curve25519.js +189 -0
- package/src/foundation/image-thumb.js +65 -0
- package/src/foundation/link-preview.js +278 -0
- package/src/foundation/logger.js +78 -0
- package/src/foundation/long.js +130 -0
- package/src/foundation/performance.js +385 -0
- package/src/foundation/protobuf-minimal.js +587 -0
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +47 -0
- package/src/foundation/zip.js +108 -0
- package/src/index.js +67 -0
- package/src/signal/libsignal.js +996 -0
- package/src/signal/signal-group.js +455 -0
- package/src/signal/signal-repository.js +635 -0
- package/src/socket/business-communities.js +811 -0
- package/src/socket/chats.js +702 -0
- package/src/socket/groups-newsletter.js +524 -0
- package/src/socket/messages-recv.js +1815 -0
- package/src/socket/messages-send.js +1526 -0
- package/src/socket/socket-builder.js +131 -0
- package/src/socket/socket-core.js +913 -0
- package/src/socket/usync.js +287 -0
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +170 -0
- package/src/utils/auth-state-core.js +731 -0
- package/src/utils/auth-state-storage.js +594 -0
- package/src/utils/chat-sync.js +1046 -0
- package/src/utils/check-status.js +159 -0
- package/src/utils/cstoken.js +17 -0
- package/src/utils/media.js +807 -0
- package/src/utils/message-compose.js +1747 -0
- package/src/utils/message-processing.js +912 -0
- package/src/utils/modern-messages.js +435 -0
- package/src/utils/nomo-buttons.js +138 -0
- package/src/utils/nomo-commands.js +168 -0
- package/src/utils/spam-report-utils.js +136 -0
- package/src/utils/use-keyv-auth-state.js +307 -0
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +1227 -0
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/auto.js +139 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1727 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +730 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +22852 -0
- package/src/wam/wam.js +146 -0
- package/voip.d.ts +144 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* nomo-baileys – Performance Utilities
|
|
3
|
+
*
|
|
4
|
+
* Provides:
|
|
5
|
+
* - performanceModeDefaults → cache & pipeline tunables per mode
|
|
6
|
+
* - MessageDeduplicator → compact, bounded, TTL-based dedup
|
|
7
|
+
* - RequestCoalescer → in-flight promise reuse (prevents N duplicate fetches)
|
|
8
|
+
* - lazyLogger → zero-cost guard helper for expensive log args
|
|
9
|
+
* - applyPerformanceMode → merges mode defaults into a config object
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// ─── Performance mode presets ────────────────────────────────────────────────
|
|
13
|
+
|
|
14
|
+
/** @type {Record<string, object>} */
|
|
15
|
+
export const PERFORMANCE_MODE_DEFAULTS = {
|
|
16
|
+
/**
|
|
17
|
+
* balanced (default) — safe, backward-compatible.
|
|
18
|
+
* Identical to what Baileys has always done, just with caching on.
|
|
19
|
+
*/
|
|
20
|
+
balanced: {
|
|
21
|
+
groupMetadataCacheTTL: 5 * 60 * 1000, // 5 min
|
|
22
|
+
groupMetadataCacheMax: 500,
|
|
23
|
+
contactCacheTTL: 10 * 60 * 1000, // 10 min
|
|
24
|
+
contactCacheMax: 2000,
|
|
25
|
+
dedupTTL: 30 * 1000, // 30 s
|
|
26
|
+
dedupMax: 2000,
|
|
27
|
+
coalescingEnabled: true,
|
|
28
|
+
lazyLogging: true,
|
|
29
|
+
signalCacheMax: 1000,
|
|
30
|
+
signalCacheTTL: 5 * 60 * 1000
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* high — more aggressive caching & coalescing.
|
|
35
|
+
* Latency-focused; still bounded in RAM.
|
|
36
|
+
*/
|
|
37
|
+
high: {
|
|
38
|
+
groupMetadataCacheTTL: 15 * 60 * 1000, // 15 min
|
|
39
|
+
groupMetadataCacheMax: 2000,
|
|
40
|
+
contactCacheTTL: 30 * 60 * 1000, // 30 min
|
|
41
|
+
contactCacheMax: 10_000,
|
|
42
|
+
dedupTTL: 60 * 1000, // 60 s
|
|
43
|
+
dedupMax: 8000,
|
|
44
|
+
coalescingEnabled: true,
|
|
45
|
+
lazyLogging: true,
|
|
46
|
+
signalCacheMax: 4096,
|
|
47
|
+
signalCacheTTL: 10 * 60 * 1000
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* low-memory — smaller caches, more frequent eviction.
|
|
52
|
+
* Suitable for devices with limited RAM.
|
|
53
|
+
*/
|
|
54
|
+
'low-memory': {
|
|
55
|
+
groupMetadataCacheTTL: 2 * 60 * 1000, // 2 min
|
|
56
|
+
groupMetadataCacheMax: 100,
|
|
57
|
+
contactCacheTTL: 5 * 60 * 1000,
|
|
58
|
+
contactCacheMax: 500,
|
|
59
|
+
dedupTTL: 15 * 1000,
|
|
60
|
+
dedupMax: 500,
|
|
61
|
+
coalescingEnabled: true,
|
|
62
|
+
lazyLogging: true,
|
|
63
|
+
signalCacheMax: 256,
|
|
64
|
+
signalCacheTTL: 2 * 60 * 1000
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Returns the performance preset for a given mode, falling back to 'balanced'.
|
|
70
|
+
* @param {'balanced'|'high'|'low-memory'|string} mode
|
|
71
|
+
* @returns {object}
|
|
72
|
+
*/
|
|
73
|
+
export function getPerformanceModeDefaults(mode) {
|
|
74
|
+
return PERFORMANCE_MODE_DEFAULTS[mode] ?? PERFORMANCE_MODE_DEFAULTS.balanced
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Merges performance-mode defaults into the config passed to makeWASocket.
|
|
79
|
+
* Only fills in keys that are NOT already explicitly set by the caller.
|
|
80
|
+
*
|
|
81
|
+
* @param {object} config - raw makeWASocket config
|
|
82
|
+
* @returns {object} - enriched config (same reference, mutated in place)
|
|
83
|
+
*/
|
|
84
|
+
export function applyPerformanceMode(config) {
|
|
85
|
+
const mode = config.performanceMode ?? 'balanced'
|
|
86
|
+
const defaults = getPerformanceModeDefaults(mode)
|
|
87
|
+
config._perfMode = mode
|
|
88
|
+
config._perfDefaults = defaults
|
|
89
|
+
return config
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ─── MessageDeduplicator ─────────────────────────────────────────────────────
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Lightweight duplicate-message detector.
|
|
96
|
+
*
|
|
97
|
+
* Uses a fixed-size circular buffer keyed by a compact string derived from
|
|
98
|
+
* (messageId, remoteJid). Entries expire after `ttlMs`. The buffer never
|
|
99
|
+
* grows beyond `max` entries — oldest entries are evicted first.
|
|
100
|
+
*
|
|
101
|
+
* Overhead per message: one Map lookup + one string concat (~1–2 µs).
|
|
102
|
+
*/
|
|
103
|
+
export class MessageDeduplicator {
|
|
104
|
+
/**
|
|
105
|
+
* @param {{ max?: number, ttlMs?: number }} opts
|
|
106
|
+
*/
|
|
107
|
+
constructor({ max = 2000, ttlMs = 30_000 } = {}) {
|
|
108
|
+
this._max = max
|
|
109
|
+
this._ttl = ttlMs
|
|
110
|
+
/** @type {Map<string, number>} key → expiresAt */
|
|
111
|
+
this._seen = new Map()
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Builds the dedup key. Kept deliberately minimal for speed.
|
|
116
|
+
* @param {string} id
|
|
117
|
+
* @param {string} remoteJid
|
|
118
|
+
* @param {string} [participant]
|
|
119
|
+
* @returns {string}
|
|
120
|
+
*/
|
|
121
|
+
static key(id, remoteJid, participant) {
|
|
122
|
+
return participant ? `${id}\x00${remoteJid}\x00${participant}` : `${id}\x00${remoteJid}`
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Returns true if this message is a duplicate (seen recently).
|
|
127
|
+
* If not a duplicate, registers it.
|
|
128
|
+
* @param {string} id
|
|
129
|
+
* @param {string} remoteJid
|
|
130
|
+
* @param {string} [participant]
|
|
131
|
+
* @returns {boolean}
|
|
132
|
+
*/
|
|
133
|
+
isDuplicate(id, remoteJid, participant) {
|
|
134
|
+
const k = MessageDeduplicator.key(id, remoteJid, participant)
|
|
135
|
+
const now = Date.now()
|
|
136
|
+
const exp = this._seen.get(k)
|
|
137
|
+
if (exp !== undefined && exp > now) return true
|
|
138
|
+
|
|
139
|
+
// Evict oldest when at capacity
|
|
140
|
+
if (this._seen.size >= this._max) {
|
|
141
|
+
const oldest = this._seen.keys().next().value
|
|
142
|
+
this._seen.delete(oldest)
|
|
143
|
+
}
|
|
144
|
+
this._seen.set(k, now + this._ttl)
|
|
145
|
+
return false
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Explicitly mark a message as seen (without checking first). */
|
|
149
|
+
markSeen(id, remoteJid, participant) {
|
|
150
|
+
const k = MessageDeduplicator.key(id, remoteJid, participant)
|
|
151
|
+
if (this._seen.size >= this._max) {
|
|
152
|
+
const oldest = this._seen.keys().next().value
|
|
153
|
+
this._seen.delete(oldest)
|
|
154
|
+
}
|
|
155
|
+
this._seen.set(k, Date.now() + this._ttl)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Remove a message from the dedup cache (e.g. to allow legitimate re-delivery). */
|
|
159
|
+
forget(id, remoteJid, participant) {
|
|
160
|
+
this._seen.delete(MessageDeduplicator.key(id, remoteJid, participant))
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Number of currently tracked entries. */
|
|
164
|
+
get size() {
|
|
165
|
+
return this._seen.size
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Clear all tracked entries. */
|
|
169
|
+
clear() {
|
|
170
|
+
this._seen.clear()
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ─── RequestCoalescer ────────────────────────────────────────────────────────
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Prevents duplicate concurrent async requests for the same key.
|
|
178
|
+
*
|
|
179
|
+
* If requests A, B, C all call `coalescer.get('group@g.us', fetchFn)` at the
|
|
180
|
+
* same time, only ONE network call is made. A, B and C all resolve from the
|
|
181
|
+
* same Promise. Results are NOT cached beyond the duration of the in-flight
|
|
182
|
+
* request — use the `Cache` class for persistent caching.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* const coalescer = new RequestCoalescer()
|
|
186
|
+
* const meta = await coalescer.get(jid, () => groupQuery(jid))
|
|
187
|
+
*/
|
|
188
|
+
export class RequestCoalescer {
|
|
189
|
+
constructor() {
|
|
190
|
+
/** @type {Map<string, Promise<any>>} */
|
|
191
|
+
this._inflight = new Map()
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* @template T
|
|
196
|
+
* @param {string} key - unique string key for this request
|
|
197
|
+
* @param {() => Promise<T>} fn - factory that initiates the request
|
|
198
|
+
* @returns {Promise<T>}
|
|
199
|
+
*/
|
|
200
|
+
async get(key, fn) {
|
|
201
|
+
const existing = this._inflight.get(key)
|
|
202
|
+
if (existing) return existing
|
|
203
|
+
|
|
204
|
+
const promise = fn().finally(() => {
|
|
205
|
+
// Only delete if this promise is still registered
|
|
206
|
+
// (another call may have replaced it)
|
|
207
|
+
if (this._inflight.get(key) === promise) {
|
|
208
|
+
this._inflight.delete(key)
|
|
209
|
+
}
|
|
210
|
+
})
|
|
211
|
+
this._inflight.set(key, promise)
|
|
212
|
+
return promise
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Number of currently in-flight requests. */
|
|
216
|
+
get size() {
|
|
217
|
+
return this._inflight.size
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Cancel / drop a tracked key (does NOT abort the in-flight request). */
|
|
221
|
+
drop(key) {
|
|
222
|
+
this._inflight.delete(key)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ─── Lazy logging helper ─────────────────────────────────────────────────────
|
|
227
|
+
|
|
228
|
+
const LEVEL_VALUES = { trace: 10, debug: 20, info: 30, warn: 40, error: 50, fatal: 60 }
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Returns true when the logger would actually emit at `level`.
|
|
232
|
+
* Use this guard before constructing expensive log arguments.
|
|
233
|
+
*
|
|
234
|
+
* @param {object} logger - Baileys logger (or any pino-compatible logger)
|
|
235
|
+
* @param {'trace'|'debug'|'info'|'warn'|'error'|'fatal'} level
|
|
236
|
+
* @returns {boolean}
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* if (isLogEnabled(logger, 'debug')) {
|
|
240
|
+
* logger.debug({ expensiveDump: computeDump() }, 'big object')
|
|
241
|
+
* }
|
|
242
|
+
*/
|
|
243
|
+
export function isLogEnabled(logger, level) {
|
|
244
|
+
try {
|
|
245
|
+
const loggerLevel = logger?.level ?? 'info'
|
|
246
|
+
const current = LEVEL_VALUES[loggerLevel] ?? LEVEL_VALUES.info
|
|
247
|
+
const target = LEVEL_VALUES[level] ?? LEVEL_VALUES.debug
|
|
248
|
+
return target >= current
|
|
249
|
+
} catch {
|
|
250
|
+
return false
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Calls `fn` only if the logger is at or below `level`.
|
|
256
|
+
* fn should return [obj, msg] or [msg] — the args passed to logger[level]().
|
|
257
|
+
*
|
|
258
|
+
* @param {object} logger
|
|
259
|
+
* @param {'trace'|'debug'|'info'} level
|
|
260
|
+
* @param {() => [object, string] | [string]} fn - lazy arg factory
|
|
261
|
+
*/
|
|
262
|
+
export function lazyLog(logger, level, fn) {
|
|
263
|
+
if (!isLogEnabled(logger, level)) return
|
|
264
|
+
try {
|
|
265
|
+
const args = fn()
|
|
266
|
+
logger[level](...args)
|
|
267
|
+
} catch { /* never crash because of logging */ }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ─── Safe async executor ─────────────────────────────────────────────────────
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Runs `fn()` in the background (next microtask). Errors are caught and
|
|
274
|
+
* forwarded to `onError` (or swallowed if no handler provided).
|
|
275
|
+
*
|
|
276
|
+
* Use this to move non-critical work off the critical event path.
|
|
277
|
+
*
|
|
278
|
+
* @param {() => Promise<void>} fn
|
|
279
|
+
* @param {(err: Error) => void} [onError]
|
|
280
|
+
*/
|
|
281
|
+
export function runBackground(fn, onError) {
|
|
282
|
+
Promise.resolve().then(fn).catch(err => {
|
|
283
|
+
if (onError) {
|
|
284
|
+
try { onError(err) } catch { /* ignore */ }
|
|
285
|
+
}
|
|
286
|
+
})
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Wraps an async function so that it never throws — errors are forwarded to
|
|
291
|
+
* `onError` and the wrapper returns `undefined`.
|
|
292
|
+
*
|
|
293
|
+
* @template T
|
|
294
|
+
* @param {(...args: any[]) => Promise<T>} fn
|
|
295
|
+
* @param {(err: Error) => void} [onError]
|
|
296
|
+
* @returns {(...args: any[]) => Promise<T | undefined>}
|
|
297
|
+
*/
|
|
298
|
+
export function safeAsync(fn, onError) {
|
|
299
|
+
return async (...args) => {
|
|
300
|
+
try {
|
|
301
|
+
return await fn(...args)
|
|
302
|
+
} catch (err) {
|
|
303
|
+
if (onError) {
|
|
304
|
+
try { onError(err) } catch { /* ignore */ }
|
|
305
|
+
}
|
|
306
|
+
return undefined
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// ─── Concurrency limiter ─────────────────────────────────────────────────────
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Simple semaphore-style concurrency limiter.
|
|
315
|
+
* Ensures at most `limit` async tasks run concurrently.
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* const limit = createConcurrencyLimit(4)
|
|
319
|
+
* await Promise.all(items.map(item => limit(() => processItem(item))))
|
|
320
|
+
*/
|
|
321
|
+
export function createConcurrencyLimit(limit = 8) {
|
|
322
|
+
let active = 0
|
|
323
|
+
const queue = []
|
|
324
|
+
|
|
325
|
+
function next() {
|
|
326
|
+
if (queue.length === 0 || active >= limit) return
|
|
327
|
+
active++
|
|
328
|
+
const { fn, resolve, reject } = queue.shift()
|
|
329
|
+
Promise.resolve().then(fn).then(
|
|
330
|
+
v => { active--; resolve(v); next() },
|
|
331
|
+
e => { active--; reject(e); next() }
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* @template T
|
|
337
|
+
* @param {() => Promise<T>} fn
|
|
338
|
+
* @returns {Promise<T>}
|
|
339
|
+
*/
|
|
340
|
+
return function limited(fn) {
|
|
341
|
+
return new Promise((resolve, reject) => {
|
|
342
|
+
queue.push({ fn, resolve, reject })
|
|
343
|
+
next()
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ─── Memoize with TTL ────────────────────────────────────────────────────────
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Creates a memoized version of `fn` with a TTL-based cache.
|
|
352
|
+
* Combines RequestCoalescer (in-flight dedup) + Map cache (result reuse).
|
|
353
|
+
*
|
|
354
|
+
* @template T
|
|
355
|
+
* @param {(key: string) => Promise<T>} fn
|
|
356
|
+
* @param {{ ttlMs?: number, max?: number }} opts
|
|
357
|
+
* @returns {(key: string) => Promise<T>}
|
|
358
|
+
*/
|
|
359
|
+
export function memoizeAsync(fn, { ttlMs = 60_000, max = 1000 } = {}) {
|
|
360
|
+
/** @type {Map<string, { value: T, expiresAt: number }>} */
|
|
361
|
+
const cache = new Map()
|
|
362
|
+
const coalescer = new RequestCoalescer()
|
|
363
|
+
|
|
364
|
+
return function memoized(key) {
|
|
365
|
+
// Check cache first (synchronous, zero-cost on hit)
|
|
366
|
+
const cached = cache.get(key)
|
|
367
|
+
if (cached && cached.expiresAt > Date.now()) return Promise.resolve(cached.value)
|
|
368
|
+
|
|
369
|
+
// Coalesce in-flight requests for the same key
|
|
370
|
+
return coalescer.get(key, async () => {
|
|
371
|
+
// Double-check cache after acquiring (another call may have filled it)
|
|
372
|
+
const fresh = cache.get(key)
|
|
373
|
+
if (fresh && fresh.expiresAt > Date.now()) return fresh.value
|
|
374
|
+
|
|
375
|
+
const value = await fn(key)
|
|
376
|
+
|
|
377
|
+
// Evict LRU if at capacity
|
|
378
|
+
if (cache.size >= max) {
|
|
379
|
+
cache.delete(cache.keys().next().value)
|
|
380
|
+
}
|
|
381
|
+
cache.set(key, { value, expiresAt: Date.now() + ttlMs })
|
|
382
|
+
return value
|
|
383
|
+
})
|
|
384
|
+
}
|
|
385
|
+
}
|