| 1 |
'use strict' |
| 2 |
|
| 3 |
const { writeFile, readFile, mkdir } = require('node:fs/promises') |
| 4 |
const { dirname, resolve } = require('node:path') |
| 5 |
const { setTimeout, clearTimeout } = require('node:timers') |
| 6 |
const { InvalidArgumentError, UndiciError } = require('../core/errors') |
| 7 |
const { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require('./snapshot-utils') |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
function normalizeUrlForMatching (url, matchQuery, normalizeQuery) { |
| 93 |
if (matchQuery === false) return `${url.origin}${url.pathname}` |
| 94 |
if (normalizeQuery) { |
| 95 |
const normalized = String(normalizeQuery(url.searchParams) ?? '') |
| 96 |
return normalized ? `${url.origin}${url.pathname}?${normalized}` : `${url.origin}${url.pathname}` |
| 97 |
} |
| 98 |
return url.toString() |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
function normalizeBodyForMatching (body, matchBody, normalizeBody) { |
| 110 |
if (matchBody === false) return '' |
| 111 |
if (normalizeBody) return String(normalizeBody(body) ?? '') |
| 112 |
return body ? String(body) : '' |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
function formatRequestKey (opts, headerFilters, matchOptions = {}) { |
| 125 |
const url = new URL(opts.path, opts.origin) |
| 126 |
|
| 127 |
|
| 128 |
const normalized = opts._normalizedHeaders || normalizeHeaders(opts.headers) |
| 129 |
if (!opts._normalizedHeaders) { |
| 130 |
opts._normalizedHeaders = normalized |
| 131 |
} |
| 132 |
|
| 133 |
return { |
| 134 |
method: opts.method || 'GET', |
| 135 |
url: normalizeUrlForMatching(url, matchOptions.matchQuery, matchOptions.normalizeQuery), |
| 136 |
headers: filterHeadersForMatching(normalized, headerFilters, matchOptions), |
| 137 |
body: normalizeBodyForMatching(opts.body, matchOptions.matchBody, matchOptions.normalizeBody) |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
function filterHeadersForMatching (headers, headerFilters, matchOptions = {}) { |
| 149 |
if (!headers || typeof headers !== 'object') return {} |
| 150 |
|
| 151 |
const { |
| 152 |
caseSensitive = false |
| 153 |
} = matchOptions |
| 154 |
|
| 155 |
const filtered = {} |
| 156 |
const { ignore, exclude, match } = headerFilters |
| 157 |
|
| 158 |
for (const [key, value] of Object.entries(headers)) { |
| 159 |
const headerKey = caseSensitive ? key : key.toLowerCase() |
| 160 |
|
| 161 |
|
| 162 |
if (exclude.has(headerKey)) continue |
| 163 |
|
| 164 |
|
| 165 |
if (ignore.has(headerKey)) continue |
| 166 |
|
| 167 |
|
| 168 |
if (match.size !== 0) { |
| 169 |
if (!match.has(headerKey)) continue |
| 170 |
} |
| 171 |
|
| 172 |
filtered[headerKey] = value |
| 173 |
} |
| 174 |
|
| 175 |
return filtered |
| 176 |
} |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
function filterHeadersForStorage (headers, headerFilters, matchOptions = {}) { |
| 186 |
if (!headers || typeof headers !== 'object') return {} |
| 187 |
|
| 188 |
const { |
| 189 |
caseSensitive = false |
| 190 |
} = matchOptions |
| 191 |
|
| 192 |
const filtered = {} |
| 193 |
const { exclude: excludeSet } = headerFilters |
| 194 |
|
| 195 |
for (const [key, value] of Object.entries(headers)) { |
| 196 |
const headerKey = caseSensitive ? key : key.toLowerCase() |
| 197 |
|
| 198 |
|
| 199 |
if (excludeSet.has(headerKey)) continue |
| 200 |
|
| 201 |
filtered[headerKey] = value |
| 202 |
} |
| 203 |
|
| 204 |
return filtered |
| 205 |
} |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
function createRequestHash (formattedRequest) { |
| 215 |
const parts = [ |
| 216 |
formattedRequest.method, |
| 217 |
formattedRequest.url |
| 218 |
] |
| 219 |
|
| 220 |
|
| 221 |
if (formattedRequest.headers && typeof formattedRequest.headers === 'object') { |
| 222 |
const headerKeys = Object.keys(formattedRequest.headers).sort() |
| 223 |
for (const key of headerKeys) { |
| 224 |
const values = Array.isArray(formattedRequest.headers[key]) |
| 225 |
? formattedRequest.headers[key] |
| 226 |
: [formattedRequest.headers[key]] |
| 227 |
|
| 228 |
|
| 229 |
parts.push(key) |
| 230 |
|
| 231 |
|
| 232 |
for (const value of values.sort()) { |
| 233 |
parts.push(String(value)) |
| 234 |
} |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
|
| 239 |
parts.push(formattedRequest.body) |
| 240 |
|
| 241 |
const content = parts.join('|') |
| 242 |
|
| 243 |
return hashId(content) |
| 244 |
} |
| 245 |
|
| 246 |
class SnapshotRecorder { |
| 247 |
|
| 248 |
#flushTimeout |
| 249 |
|
| 250 |
|
| 251 |
#isUrlExcluded |
| 252 |
|
| 253 |
|
| 254 |
#snapshots = new Map() |
| 255 |
|
| 256 |
|
| 257 |
#snapshotPath |
| 258 |
|
| 259 |
|
| 260 |
#maxSnapshots = Infinity |
| 261 |
|
| 262 |
|
| 263 |
#autoFlush = false |
| 264 |
|
| 265 |
|
| 266 |
#headerFilters |
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
constructor (options = {}) { |
| 273 |
this.#snapshotPath = options.snapshotPath |
| 274 |
this.#maxSnapshots = options.maxSnapshots || Infinity |
| 275 |
this.#autoFlush = options.autoFlush || false |
| 276 |
this.flushInterval = options.flushInterval || 30000 |
| 277 |
this._flushTimer = null |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
this.matchOptions = { |
| 282 |
matchHeaders: options.matchHeaders || [], |
| 283 |
ignoreHeaders: options.ignoreHeaders || [], |
| 284 |
excludeHeaders: options.excludeHeaders || [], |
| 285 |
matchBody: options.matchBody !== false, |
| 286 |
normalizeBody: options.normalizeBody || undefined, |
| 287 |
matchQuery: options.matchQuery !== false, |
| 288 |
normalizeQuery: options.normalizeQuery || undefined, |
| 289 |
caseSensitive: options.caseSensitive || false |
| 290 |
} |
| 291 |
|
| 292 |
|
| 293 |
this.#headerFilters = createHeaderFilters(this.matchOptions) |
| 294 |
|
| 295 |
|
| 296 |
this.shouldRecord = options.shouldRecord || (() => true) |
| 297 |
this.shouldPlayback = options.shouldPlayback || (() => true) |
| 298 |
|
| 299 |
|
| 300 |
this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls) |
| 301 |
|
| 302 |
|
| 303 |
if (this.#autoFlush && this.#snapshotPath) { |
| 304 |
this.#startAutoFlush() |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
async record (requestOpts, response) { |
| 315 |
|
| 316 |
if (!this.shouldRecord(requestOpts)) { |
| 317 |
return |
| 318 |
} |
| 319 |
|
| 320 |
|
| 321 |
if (this.isUrlExcluded(requestOpts)) { |
| 322 |
return |
| 323 |
} |
| 324 |
|
| 325 |
const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) |
| 326 |
const hash = createRequestHash(request) |
| 327 |
|
| 328 |
|
| 329 |
const normalizedHeaders = normalizeHeaders(response.headers) |
| 330 |
|
| 331 |
|
| 332 |
const responseData = { |
| 333 |
statusCode: response.statusCode, |
| 334 |
headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions), |
| 335 |
body: Buffer.isBuffer(response.body) |
| 336 |
? response.body.toString('base64') |
| 337 |
: Buffer.from(String(response.body || '')).toString('base64'), |
| 338 |
trailers: response.trailers |
| 339 |
} |
| 340 |
|
| 341 |
|
| 342 |
if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash)) { |
| 343 |
const oldestKey = this.#snapshots.keys().next().value |
| 344 |
this.#snapshots.delete(oldestKey) |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
const existingSnapshot = this.#snapshots.get(hash) |
| 349 |
if (existingSnapshot && existingSnapshot.responses) { |
| 350 |
existingSnapshot.responses.push(responseData) |
| 351 |
existingSnapshot.timestamp = new Date().toISOString() |
| 352 |
} else { |
| 353 |
this.#snapshots.set(hash, { |
| 354 |
request, |
| 355 |
responses: [responseData], |
| 356 |
callCount: 0, |
| 357 |
timestamp: new Date().toISOString() |
| 358 |
}) |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
if (this.#autoFlush && this.#snapshotPath) { |
| 363 |
this.#scheduleFlush() |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
isUrlExcluded (requestOpts) { |
| 373 |
const url = new URL(requestOpts.path, requestOpts.origin).toString() |
| 374 |
return this.#isUrlExcluded(url) |
| 375 |
} |
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
findSnapshot (requestOpts) { |
| 385 |
|
| 386 |
if (!this.shouldPlayback(requestOpts)) { |
| 387 |
return undefined |
| 388 |
} |
| 389 |
|
| 390 |
|
| 391 |
if (this.isUrlExcluded(requestOpts)) { |
| 392 |
return undefined |
| 393 |
} |
| 394 |
|
| 395 |
const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) |
| 396 |
const hash = createRequestHash(request) |
| 397 |
const snapshot = this.#snapshots.get(hash) |
| 398 |
|
| 399 |
if (!snapshot) return undefined |
| 400 |
|
| 401 |
|
| 402 |
const currentCallCount = snapshot.callCount || 0 |
| 403 |
const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1) |
| 404 |
snapshot.callCount = currentCallCount + 1 |
| 405 |
|
| 406 |
return { |
| 407 |
...snapshot, |
| 408 |
response: snapshot.responses[responseIndex] |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
async loadSnapshots (filePath) { |
| 418 |
const path = filePath || this.#snapshotPath |
| 419 |
if (!path) { |
| 420 |
throw new InvalidArgumentError('Snapshot path is required') |
| 421 |
} |
| 422 |
|
| 423 |
try { |
| 424 |
const data = await readFile(resolve(path), 'utf8') |
| 425 |
const parsed = JSON.parse(data) |
| 426 |
|
| 427 |
|
| 428 |
if (Array.isArray(parsed)) { |
| 429 |
this.#snapshots.clear() |
| 430 |
for (const { hash, snapshot } of parsed) { |
| 431 |
this.#snapshots.set(hash, snapshot) |
| 432 |
} |
| 433 |
} else { |
| 434 |
|
| 435 |
this.#snapshots = new Map(Object.entries(parsed)) |
| 436 |
} |
| 437 |
} catch (error) { |
| 438 |
if (error.code === 'ENOENT') { |
| 439 |
|
| 440 |
this.#snapshots.clear() |
| 441 |
} else { |
| 442 |
throw new UndiciError(`Failed to load snapshots from ${path}`, { cause: error }) |
| 443 |
} |
| 444 |
} |
| 445 |
} |
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
async saveSnapshots (filePath) { |
| 454 |
const path = filePath || this.#snapshotPath |
| 455 |
if (!path) { |
| 456 |
throw new InvalidArgumentError('Snapshot path is required') |
| 457 |
} |
| 458 |
|
| 459 |
const resolvedPath = resolve(path) |
| 460 |
|
| 461 |
|
| 462 |
await mkdir(dirname(resolvedPath), { recursive: true }) |
| 463 |
|
| 464 |
|
| 465 |
const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({ |
| 466 |
hash, |
| 467 |
snapshot |
| 468 |
})) |
| 469 |
|
| 470 |
await writeFile(resolvedPath, JSON.stringify(data, null, 2), { flush: true }) |
| 471 |
} |
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
clear () { |
| 478 |
this.#snapshots.clear() |
| 479 |
} |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
getSnapshots () { |
| 486 |
return Array.from(this.#snapshots.values()) |
| 487 |
} |
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
size () { |
| 494 |
return this.#snapshots.size |
| 495 |
} |
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
resetCallCounts () { |
| 502 |
for (const snapshot of this.#snapshots.values()) { |
| 503 |
snapshot.callCount = 0 |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
deleteSnapshot (requestOpts) { |
| 513 |
const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) |
| 514 |
const hash = createRequestHash(request) |
| 515 |
return this.#snapshots.delete(hash) |
| 516 |
} |
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
getSnapshotInfo (requestOpts) { |
| 524 |
const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions) |
| 525 |
const hash = createRequestHash(request) |
| 526 |
const snapshot = this.#snapshots.get(hash) |
| 527 |
|
| 528 |
if (!snapshot) return null |
| 529 |
|
| 530 |
return { |
| 531 |
hash, |
| 532 |
request: snapshot.request, |
| 533 |
responseCount: snapshot.responses ? snapshot.responses.length : (snapshot.response ? 1 : 0), |
| 534 |
callCount: snapshot.callCount || 0, |
| 535 |
timestamp: snapshot.timestamp |
| 536 |
} |
| 537 |
} |
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
replaceSnapshots (snapshotData) { |
| 545 |
this.#snapshots.clear() |
| 546 |
|
| 547 |
if (Array.isArray(snapshotData)) { |
| 548 |
for (const { hash, snapshot } of snapshotData) { |
| 549 |
this.#snapshots.set(hash, snapshot) |
| 550 |
} |
| 551 |
} else if (snapshotData && typeof snapshotData === 'object') { |
| 552 |
|
| 553 |
this.#snapshots = new Map(Object.entries(snapshotData)) |
| 554 |
} |
| 555 |
} |
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
|
| 560 |
|
| 561 |
#startAutoFlush () { |
| 562 |
return this.#scheduleFlush() |
| 563 |
} |
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
#stopAutoFlush () { |
| 570 |
if (this.#flushTimeout) { |
| 571 |
clearTimeout(this.#flushTimeout) |
| 572 |
|
| 573 |
this.saveSnapshots().catch(() => { |
| 574 |
|
| 575 |
}) |
| 576 |
this.#flushTimeout = null |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
|
| 581 |
|
| 582 |
|
| 583 |
#scheduleFlush () { |
| 584 |
this.#flushTimeout = setTimeout(() => { |
| 585 |
this.saveSnapshots().catch(() => { |
| 586 |
|
| 587 |
}) |
| 588 |
if (this.#autoFlush) { |
| 589 |
this.#flushTimeout?.refresh() |
| 590 |
} else { |
| 591 |
this.#flushTimeout = null |
| 592 |
} |
| 593 |
}, 1000) |
| 594 |
} |
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
destroy () { |
| 601 |
this.#stopAutoFlush() |
| 602 |
if (this.#flushTimeout) { |
| 603 |
clearTimeout(this.#flushTimeout) |
| 604 |
this.#flushTimeout = null |
| 605 |
} |
| 606 |
} |
| 607 |
|
| 608 |
|
| 609 |
|
| 610 |
|
| 611 |
|
| 612 |
async close () { |
| 613 |
|
| 614 |
if (this.#snapshotPath && this.#snapshots.size !== 0) { |
| 615 |
await this.saveSnapshots() |
| 616 |
} |
| 617 |
|
| 618 |
|
| 619 |
this.destroy() |
| 620 |
} |
| 621 |
} |
| 622 |
|
| 623 |
module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters } |