index.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. "use strict";
  2. /**
  3. * @module LRUCache
  4. */
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.LRUCache = void 0;
  7. const perf = typeof performance === 'object' &&
  8. performance &&
  9. typeof performance.now === 'function'
  10. ? performance
  11. : Date;
  12. const warned = new Set();
  13. const emitWarning = (msg, type, code, fn) => {
  14. typeof process === 'object' &&
  15. process &&
  16. typeof process.emitWarning === 'function'
  17. ? process.emitWarning(msg, type, code, fn)
  18. : console.error(`[${code}] ${type}: ${msg}`);
  19. };
  20. const shouldWarn = (code) => !warned.has(code);
  21. const TYPE = Symbol('type');
  22. const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
  23. /* c8 ignore start */
  24. // This is a little bit ridiculous, tbh.
  25. // The maximum array length is 2^32-1 or thereabouts on most JS impls.
  26. // And well before that point, you're caching the entire world, I mean,
  27. // that's ~32GB of just integers for the next/prev links, plus whatever
  28. // else to hold that many keys and values. Just filling the memory with
  29. // zeroes at init time is brutal when you get that big.
  30. // But why not be complete?
  31. // Maybe in the future, these limits will have expanded.
  32. const getUintArray = (max) => !isPosInt(max)
  33. ? null
  34. : max <= Math.pow(2, 8)
  35. ? Uint8Array
  36. : max <= Math.pow(2, 16)
  37. ? Uint16Array
  38. : max <= Math.pow(2, 32)
  39. ? Uint32Array
  40. : max <= Number.MAX_SAFE_INTEGER
  41. ? ZeroArray
  42. : null;
  43. /* c8 ignore stop */
  44. class ZeroArray extends Array {
  45. constructor(size) {
  46. super(size);
  47. this.fill(0);
  48. }
  49. }
  50. class Stack {
  51. heap;
  52. length;
  53. // private constructor
  54. static #constructing = false;
  55. static create(max) {
  56. const HeapCls = getUintArray(max);
  57. if (!HeapCls)
  58. return [];
  59. Stack.#constructing = true;
  60. const s = new Stack(max, HeapCls);
  61. Stack.#constructing = false;
  62. return s;
  63. }
  64. constructor(max, HeapCls) {
  65. /* c8 ignore start */
  66. if (!Stack.#constructing) {
  67. throw new TypeError('instantiate Stack using Stack.create(n)');
  68. }
  69. /* c8 ignore stop */
  70. this.heap = new HeapCls(max);
  71. this.length = 0;
  72. }
  73. push(n) {
  74. this.heap[this.length++] = n;
  75. }
  76. pop() {
  77. return this.heap[--this.length];
  78. }
  79. }
  80. /**
  81. * Default export, the thing you're using this module to get.
  82. *
  83. * All properties from the options object (with the exception of
  84. * {@link OptionsBase.max} and {@link OptionsBase.maxSize}) are added as
  85. * normal public members. (`max` and `maxBase` are read-only getters.)
  86. * Changing any of these will alter the defaults for subsequent method calls,
  87. * but is otherwise safe.
  88. */
  89. class LRUCache {
  90. // properties coming in from the options of these, only max and maxSize
  91. // really *need* to be protected. The rest can be modified, as they just
  92. // set defaults for various methods.
  93. #max;
  94. #maxSize;
  95. #dispose;
  96. #disposeAfter;
  97. #fetchMethod;
  98. /**
  99. * {@link LRUCache.OptionsBase.ttl}
  100. */
  101. ttl;
  102. /**
  103. * {@link LRUCache.OptionsBase.ttlResolution}
  104. */
  105. ttlResolution;
  106. /**
  107. * {@link LRUCache.OptionsBase.ttlAutopurge}
  108. */
  109. ttlAutopurge;
  110. /**
  111. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  112. */
  113. updateAgeOnGet;
  114. /**
  115. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  116. */
  117. updateAgeOnHas;
  118. /**
  119. * {@link LRUCache.OptionsBase.allowStale}
  120. */
  121. allowStale;
  122. /**
  123. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  124. */
  125. noDisposeOnSet;
  126. /**
  127. * {@link LRUCache.OptionsBase.noUpdateTTL}
  128. */
  129. noUpdateTTL;
  130. /**
  131. * {@link LRUCache.OptionsBase.maxEntrySize}
  132. */
  133. maxEntrySize;
  134. /**
  135. * {@link LRUCache.OptionsBase.sizeCalculation}
  136. */
  137. sizeCalculation;
  138. /**
  139. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  140. */
  141. noDeleteOnFetchRejection;
  142. /**
  143. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  144. */
  145. noDeleteOnStaleGet;
  146. /**
  147. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  148. */
  149. allowStaleOnFetchAbort;
  150. /**
  151. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  152. */
  153. allowStaleOnFetchRejection;
  154. /**
  155. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  156. */
  157. ignoreFetchAbort;
  158. // computed properties
  159. #size;
  160. #calculatedSize;
  161. #keyMap;
  162. #keyList;
  163. #valList;
  164. #next;
  165. #prev;
  166. #head;
  167. #tail;
  168. #free;
  169. #disposed;
  170. #sizes;
  171. #starts;
  172. #ttls;
  173. #hasDispose;
  174. #hasFetchMethod;
  175. #hasDisposeAfter;
  176. /**
  177. * Do not call this method unless you need to inspect the
  178. * inner workings of the cache. If anything returned by this
  179. * object is modified in any way, strange breakage may occur.
  180. *
  181. * These fields are private for a reason!
  182. *
  183. * @internal
  184. */
  185. static unsafeExposeInternals(c) {
  186. return {
  187. // properties
  188. starts: c.#starts,
  189. ttls: c.#ttls,
  190. sizes: c.#sizes,
  191. keyMap: c.#keyMap,
  192. keyList: c.#keyList,
  193. valList: c.#valList,
  194. next: c.#next,
  195. prev: c.#prev,
  196. get head() {
  197. return c.#head;
  198. },
  199. get tail() {
  200. return c.#tail;
  201. },
  202. free: c.#free,
  203. // methods
  204. isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
  205. backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
  206. moveToTail: (index) => c.#moveToTail(index),
  207. indexes: (options) => c.#indexes(options),
  208. rindexes: (options) => c.#rindexes(options),
  209. isStale: (index) => c.#isStale(index),
  210. };
  211. }
  212. // Protected read-only members
  213. /**
  214. * {@link LRUCache.OptionsBase.max} (read-only)
  215. */
  216. get max() {
  217. return this.#max;
  218. }
  219. /**
  220. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  221. */
  222. get maxSize() {
  223. return this.#maxSize;
  224. }
  225. /**
  226. * The total computed size of items in the cache (read-only)
  227. */
  228. get calculatedSize() {
  229. return this.#calculatedSize;
  230. }
  231. /**
  232. * The number of items stored in the cache (read-only)
  233. */
  234. get size() {
  235. return this.#size;
  236. }
  237. /**
  238. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  239. */
  240. get fetchMethod() {
  241. return this.#fetchMethod;
  242. }
  243. /**
  244. * {@link LRUCache.OptionsBase.dispose} (read-only)
  245. */
  246. get dispose() {
  247. return this.#dispose;
  248. }
  249. /**
  250. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  251. */
  252. get disposeAfter() {
  253. return this.#disposeAfter;
  254. }
  255. constructor(options) {
  256. const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, } = options;
  257. if (max !== 0 && !isPosInt(max)) {
  258. throw new TypeError('max option must be a nonnegative integer');
  259. }
  260. const UintArray = max ? getUintArray(max) : Array;
  261. if (!UintArray) {
  262. throw new Error('invalid max value: ' + max);
  263. }
  264. this.#max = max;
  265. this.#maxSize = maxSize;
  266. this.maxEntrySize = maxEntrySize || this.#maxSize;
  267. this.sizeCalculation = sizeCalculation;
  268. if (this.sizeCalculation) {
  269. if (!this.#maxSize && !this.maxEntrySize) {
  270. throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
  271. }
  272. if (typeof this.sizeCalculation !== 'function') {
  273. throw new TypeError('sizeCalculation set to non-function');
  274. }
  275. }
  276. if (fetchMethod !== undefined &&
  277. typeof fetchMethod !== 'function') {
  278. throw new TypeError('fetchMethod must be a function if specified');
  279. }
  280. this.#fetchMethod = fetchMethod;
  281. this.#hasFetchMethod = !!fetchMethod;
  282. this.#keyMap = new Map();
  283. this.#keyList = new Array(max).fill(undefined);
  284. this.#valList = new Array(max).fill(undefined);
  285. this.#next = new UintArray(max);
  286. this.#prev = new UintArray(max);
  287. this.#head = 0;
  288. this.#tail = 0;
  289. this.#free = Stack.create(max);
  290. this.#size = 0;
  291. this.#calculatedSize = 0;
  292. if (typeof dispose === 'function') {
  293. this.#dispose = dispose;
  294. }
  295. if (typeof disposeAfter === 'function') {
  296. this.#disposeAfter = disposeAfter;
  297. this.#disposed = [];
  298. }
  299. else {
  300. this.#disposeAfter = undefined;
  301. this.#disposed = undefined;
  302. }
  303. this.#hasDispose = !!this.#dispose;
  304. this.#hasDisposeAfter = !!this.#disposeAfter;
  305. this.noDisposeOnSet = !!noDisposeOnSet;
  306. this.noUpdateTTL = !!noUpdateTTL;
  307. this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
  308. this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
  309. this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
  310. this.ignoreFetchAbort = !!ignoreFetchAbort;
  311. // NB: maxEntrySize is set to maxSize if it's set
  312. if (this.maxEntrySize !== 0) {
  313. if (this.#maxSize !== 0) {
  314. if (!isPosInt(this.#maxSize)) {
  315. throw new TypeError('maxSize must be a positive integer if specified');
  316. }
  317. }
  318. if (!isPosInt(this.maxEntrySize)) {
  319. throw new TypeError('maxEntrySize must be a positive integer if specified');
  320. }
  321. this.#initializeSizeTracking();
  322. }
  323. this.allowStale = !!allowStale;
  324. this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
  325. this.updateAgeOnGet = !!updateAgeOnGet;
  326. this.updateAgeOnHas = !!updateAgeOnHas;
  327. this.ttlResolution =
  328. isPosInt(ttlResolution) || ttlResolution === 0
  329. ? ttlResolution
  330. : 1;
  331. this.ttlAutopurge = !!ttlAutopurge;
  332. this.ttl = ttl || 0;
  333. if (this.ttl) {
  334. if (!isPosInt(this.ttl)) {
  335. throw new TypeError('ttl must be a positive integer if specified');
  336. }
  337. this.#initializeTTLTracking();
  338. }
  339. // do not allow completely unbounded caches
  340. if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
  341. throw new TypeError('At least one of max, maxSize, or ttl is required');
  342. }
  343. if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
  344. const code = 'LRU_CACHE_UNBOUNDED';
  345. if (shouldWarn(code)) {
  346. warned.add(code);
  347. const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
  348. 'result in unbounded memory consumption.';
  349. emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
  350. }
  351. }
  352. }
  353. /**
  354. * Return the remaining TTL time for a given entry key
  355. */
  356. getRemainingTTL(key) {
  357. return this.#keyMap.has(key) ? Infinity : 0;
  358. }
  359. #initializeTTLTracking() {
  360. const ttls = new ZeroArray(this.#max);
  361. const starts = new ZeroArray(this.#max);
  362. this.#ttls = ttls;
  363. this.#starts = starts;
  364. this.#setItemTTL = (index, ttl, start = perf.now()) => {
  365. starts[index] = ttl !== 0 ? start : 0;
  366. ttls[index] = ttl;
  367. if (ttl !== 0 && this.ttlAutopurge) {
  368. const t = setTimeout(() => {
  369. if (this.#isStale(index)) {
  370. this.delete(this.#keyList[index]);
  371. }
  372. }, ttl + 1);
  373. // unref() not supported on all platforms
  374. /* c8 ignore start */
  375. if (t.unref) {
  376. t.unref();
  377. }
  378. /* c8 ignore stop */
  379. }
  380. };
  381. this.#updateItemAge = index => {
  382. starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  383. };
  384. this.#statusTTL = (status, index) => {
  385. if (ttls[index]) {
  386. const ttl = ttls[index];
  387. const start = starts[index];
  388. status.ttl = ttl;
  389. status.start = start;
  390. status.now = cachedNow || getNow();
  391. status.remainingTTL = status.now + ttl - start;
  392. }
  393. };
  394. // debounce calls to perf.now() to 1s so we're not hitting
  395. // that costly call repeatedly.
  396. let cachedNow = 0;
  397. const getNow = () => {
  398. const n = perf.now();
  399. if (this.ttlResolution > 0) {
  400. cachedNow = n;
  401. const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
  402. // not available on all platforms
  403. /* c8 ignore start */
  404. if (t.unref) {
  405. t.unref();
  406. }
  407. /* c8 ignore stop */
  408. }
  409. return n;
  410. };
  411. this.getRemainingTTL = key => {
  412. const index = this.#keyMap.get(key);
  413. if (index === undefined) {
  414. return 0;
  415. }
  416. return ttls[index] === 0 || starts[index] === 0
  417. ? Infinity
  418. : starts[index] + ttls[index] - (cachedNow || getNow());
  419. };
  420. this.#isStale = index => {
  421. return (ttls[index] !== 0 &&
  422. starts[index] !== 0 &&
  423. (cachedNow || getNow()) - starts[index] > ttls[index]);
  424. };
  425. }
  426. // conditionally set private methods related to TTL
  427. #updateItemAge = () => { };
  428. #statusTTL = () => { };
  429. #setItemTTL = () => { };
  430. /* c8 ignore stop */
  431. #isStale = () => false;
  432. #initializeSizeTracking() {
  433. const sizes = new ZeroArray(this.#max);
  434. this.#calculatedSize = 0;
  435. this.#sizes = sizes;
  436. this.#removeItemSize = index => {
  437. this.#calculatedSize -= sizes[index];
  438. sizes[index] = 0;
  439. };
  440. this.#requireSize = (k, v, size, sizeCalculation) => {
  441. // provisionally accept background fetches.
  442. // actual value size will be checked when they return.
  443. if (this.#isBackgroundFetch(v)) {
  444. return 0;
  445. }
  446. if (!isPosInt(size)) {
  447. if (sizeCalculation) {
  448. if (typeof sizeCalculation !== 'function') {
  449. throw new TypeError('sizeCalculation must be a function');
  450. }
  451. size = sizeCalculation(v, k);
  452. if (!isPosInt(size)) {
  453. throw new TypeError('sizeCalculation return invalid (expect positive integer)');
  454. }
  455. }
  456. else {
  457. throw new TypeError('invalid size value (must be positive integer). ' +
  458. 'When maxSize or maxEntrySize is used, sizeCalculation ' +
  459. 'or size must be set.');
  460. }
  461. }
  462. return size;
  463. };
  464. this.#addItemSize = (index, size, status) => {
  465. sizes[index] = size;
  466. if (this.#maxSize) {
  467. const maxSize = this.#maxSize - sizes[index];
  468. while (this.#calculatedSize > maxSize) {
  469. this.#evict(true);
  470. }
  471. }
  472. this.#calculatedSize += sizes[index];
  473. if (status) {
  474. status.entrySize = size;
  475. status.totalCalculatedSize = this.#calculatedSize;
  476. }
  477. };
  478. }
  479. #removeItemSize = _i => { };
  480. #addItemSize = (_i, _s, _st) => { };
  481. #requireSize = (_k, _v, size, sizeCalculation) => {
  482. if (size || sizeCalculation) {
  483. throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
  484. }
  485. return 0;
  486. };
  487. *#indexes({ allowStale = this.allowStale } = {}) {
  488. if (this.#size) {
  489. for (let i = this.#tail; true;) {
  490. if (!this.#isValidIndex(i)) {
  491. break;
  492. }
  493. if (allowStale || !this.#isStale(i)) {
  494. yield i;
  495. }
  496. if (i === this.#head) {
  497. break;
  498. }
  499. else {
  500. i = this.#prev[i];
  501. }
  502. }
  503. }
  504. }
  505. *#rindexes({ allowStale = this.allowStale } = {}) {
  506. if (this.#size) {
  507. for (let i = this.#head; true;) {
  508. if (!this.#isValidIndex(i)) {
  509. break;
  510. }
  511. if (allowStale || !this.#isStale(i)) {
  512. yield i;
  513. }
  514. if (i === this.#tail) {
  515. break;
  516. }
  517. else {
  518. i = this.#next[i];
  519. }
  520. }
  521. }
  522. }
  523. #isValidIndex(index) {
  524. return (index !== undefined &&
  525. this.#keyMap.get(this.#keyList[index]) === index);
  526. }
  527. /**
  528. * Return a generator yielding `[key, value]` pairs,
  529. * in order from most recently used to least recently used.
  530. */
  531. *entries() {
  532. for (const i of this.#indexes()) {
  533. if (this.#valList[i] !== undefined &&
  534. this.#keyList[i] !== undefined &&
  535. !this.#isBackgroundFetch(this.#valList[i])) {
  536. yield [this.#keyList[i], this.#valList[i]];
  537. }
  538. }
  539. }
  540. /**
  541. * Inverse order version of {@link LRUCache.entries}
  542. *
  543. * Return a generator yielding `[key, value]` pairs,
  544. * in order from least recently used to most recently used.
  545. */
  546. *rentries() {
  547. for (const i of this.#rindexes()) {
  548. if (this.#valList[i] !== undefined &&
  549. this.#keyList[i] !== undefined &&
  550. !this.#isBackgroundFetch(this.#valList[i])) {
  551. yield [this.#keyList[i], this.#valList[i]];
  552. }
  553. }
  554. }
  555. /**
  556. * Return a generator yielding the keys in the cache,
  557. * in order from most recently used to least recently used.
  558. */
  559. *keys() {
  560. for (const i of this.#indexes()) {
  561. const k = this.#keyList[i];
  562. if (k !== undefined &&
  563. !this.#isBackgroundFetch(this.#valList[i])) {
  564. yield k;
  565. }
  566. }
  567. }
  568. /**
  569. * Inverse order version of {@link LRUCache.keys}
  570. *
  571. * Return a generator yielding the keys in the cache,
  572. * in order from least recently used to most recently used.
  573. */
  574. *rkeys() {
  575. for (const i of this.#rindexes()) {
  576. const k = this.#keyList[i];
  577. if (k !== undefined &&
  578. !this.#isBackgroundFetch(this.#valList[i])) {
  579. yield k;
  580. }
  581. }
  582. }
  583. /**
  584. * Return a generator yielding the values in the cache,
  585. * in order from most recently used to least recently used.
  586. */
  587. *values() {
  588. for (const i of this.#indexes()) {
  589. const v = this.#valList[i];
  590. if (v !== undefined &&
  591. !this.#isBackgroundFetch(this.#valList[i])) {
  592. yield this.#valList[i];
  593. }
  594. }
  595. }
  596. /**
  597. * Inverse order version of {@link LRUCache.values}
  598. *
  599. * Return a generator yielding the values in the cache,
  600. * in order from least recently used to most recently used.
  601. */
  602. *rvalues() {
  603. for (const i of this.#rindexes()) {
  604. const v = this.#valList[i];
  605. if (v !== undefined &&
  606. !this.#isBackgroundFetch(this.#valList[i])) {
  607. yield this.#valList[i];
  608. }
  609. }
  610. }
  611. /**
  612. * Iterating over the cache itself yields the same results as
  613. * {@link LRUCache.entries}
  614. */
  615. [Symbol.iterator]() {
  616. return this.entries();
  617. }
  618. /**
  619. * Find a value for which the supplied fn method returns a truthy value,
  620. * similar to Array.find(). fn is called as fn(value, key, cache).
  621. */
  622. find(fn, getOptions = {}) {
  623. for (const i of this.#indexes()) {
  624. const v = this.#valList[i];
  625. const value = this.#isBackgroundFetch(v)
  626. ? v.__staleWhileFetching
  627. : v;
  628. if (value === undefined)
  629. continue;
  630. if (fn(value, this.#keyList[i], this)) {
  631. return this.get(this.#keyList[i], getOptions);
  632. }
  633. }
  634. }
  635. /**
  636. * Call the supplied function on each item in the cache, in order from
  637. * most recently used to least recently used. fn is called as
  638. * fn(value, key, cache). Does not update age or recenty of use.
  639. * Does not iterate over stale values.
  640. */
  641. forEach(fn, thisp = this) {
  642. for (const i of this.#indexes()) {
  643. const v = this.#valList[i];
  644. const value = this.#isBackgroundFetch(v)
  645. ? v.__staleWhileFetching
  646. : v;
  647. if (value === undefined)
  648. continue;
  649. fn.call(thisp, value, this.#keyList[i], this);
  650. }
  651. }
  652. /**
  653. * The same as {@link LRUCache.forEach} but items are iterated over in
  654. * reverse order. (ie, less recently used items are iterated over first.)
  655. */
  656. rforEach(fn, thisp = this) {
  657. for (const i of this.#rindexes()) {
  658. const v = this.#valList[i];
  659. const value = this.#isBackgroundFetch(v)
  660. ? v.__staleWhileFetching
  661. : v;
  662. if (value === undefined)
  663. continue;
  664. fn.call(thisp, value, this.#keyList[i], this);
  665. }
  666. }
  667. /**
  668. * Delete any stale entries. Returns true if anything was removed,
  669. * false otherwise.
  670. */
  671. purgeStale() {
  672. let deleted = false;
  673. for (const i of this.#rindexes({ allowStale: true })) {
  674. if (this.#isStale(i)) {
  675. this.delete(this.#keyList[i]);
  676. deleted = true;
  677. }
  678. }
  679. return deleted;
  680. }
  681. /**
  682. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  683. * passed to cache.load()
  684. */
  685. dump() {
  686. const arr = [];
  687. for (const i of this.#indexes({ allowStale: true })) {
  688. const key = this.#keyList[i];
  689. const v = this.#valList[i];
  690. const value = this.#isBackgroundFetch(v)
  691. ? v.__staleWhileFetching
  692. : v;
  693. if (value === undefined || key === undefined)
  694. continue;
  695. const entry = { value };
  696. if (this.#ttls && this.#starts) {
  697. entry.ttl = this.#ttls[i];
  698. // always dump the start relative to a portable timestamp
  699. // it's ok for this to be a bit slow, it's a rare operation.
  700. const age = perf.now() - this.#starts[i];
  701. entry.start = Math.floor(Date.now() - age);
  702. }
  703. if (this.#sizes) {
  704. entry.size = this.#sizes[i];
  705. }
  706. arr.unshift([key, entry]);
  707. }
  708. return arr;
  709. }
  710. /**
  711. * Reset the cache and load in the items in entries in the order listed.
  712. * Note that the shape of the resulting cache may be different if the
  713. * same options are not used in both caches.
  714. */
  715. load(arr) {
  716. this.clear();
  717. for (const [key, entry] of arr) {
  718. if (entry.start) {
  719. // entry.start is a portable timestamp, but we may be using
  720. // node's performance.now(), so calculate the offset, so that
  721. // we get the intended remaining TTL, no matter how long it's
  722. // been on ice.
  723. //
  724. // it's ok for this to be a bit slow, it's a rare operation.
  725. const age = Date.now() - entry.start;
  726. entry.start = perf.now() - age;
  727. }
  728. this.set(key, entry.value, entry);
  729. }
  730. }
  731. /**
  732. * Add a value to the cache.
  733. */
  734. set(k, v, setOptions = {}) {
  735. const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
  736. let { noUpdateTTL = this.noUpdateTTL } = setOptions;
  737. const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
  738. // if the item doesn't fit, don't do anything
  739. // NB: maxEntrySize set to maxSize by default
  740. if (this.maxEntrySize && size > this.maxEntrySize) {
  741. if (status) {
  742. status.set = 'miss';
  743. status.maxEntrySizeExceeded = true;
  744. }
  745. // have to delete, in case something is there already.
  746. this.delete(k);
  747. return this;
  748. }
  749. let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
  750. if (index === undefined) {
  751. // addition
  752. index = (this.#size === 0
  753. ? this.#tail
  754. : this.#free.length !== 0
  755. ? this.#free.pop()
  756. : this.#size === this.#max
  757. ? this.#evict(false)
  758. : this.#size);
  759. this.#keyList[index] = k;
  760. this.#valList[index] = v;
  761. this.#keyMap.set(k, index);
  762. this.#next[this.#tail] = index;
  763. this.#prev[index] = this.#tail;
  764. this.#tail = index;
  765. this.#size++;
  766. this.#addItemSize(index, size, status);
  767. if (status)
  768. status.set = 'add';
  769. noUpdateTTL = false;
  770. }
  771. else {
  772. // update
  773. this.#moveToTail(index);
  774. const oldVal = this.#valList[index];
  775. if (v !== oldVal) {
  776. if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
  777. oldVal.__abortController.abort(new Error('replaced'));
  778. }
  779. else if (!noDisposeOnSet) {
  780. if (this.#hasDispose) {
  781. this.#dispose?.(oldVal, k, 'set');
  782. }
  783. if (this.#hasDisposeAfter) {
  784. this.#disposed?.push([oldVal, k, 'set']);
  785. }
  786. }
  787. this.#removeItemSize(index);
  788. this.#addItemSize(index, size, status);
  789. this.#valList[index] = v;
  790. if (status) {
  791. status.set = 'replace';
  792. const oldValue = oldVal && this.#isBackgroundFetch(oldVal)
  793. ? oldVal.__staleWhileFetching
  794. : oldVal;
  795. if (oldValue !== undefined)
  796. status.oldValue = oldValue;
  797. }
  798. }
  799. else if (status) {
  800. status.set = 'update';
  801. }
  802. }
  803. if (ttl !== 0 && !this.#ttls) {
  804. this.#initializeTTLTracking();
  805. }
  806. if (this.#ttls) {
  807. if (!noUpdateTTL) {
  808. this.#setItemTTL(index, ttl, start);
  809. }
  810. if (status)
  811. this.#statusTTL(status, index);
  812. }
  813. if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
  814. const dt = this.#disposed;
  815. let task;
  816. while ((task = dt?.shift())) {
  817. this.#disposeAfter?.(...task);
  818. }
  819. }
  820. return this;
  821. }
  822. /**
  823. * Evict the least recently used item, returning its value or
  824. * `undefined` if cache is empty.
  825. */
  826. pop() {
  827. try {
  828. while (this.#size) {
  829. const val = this.#valList[this.#head];
  830. this.#evict(true);
  831. if (this.#isBackgroundFetch(val)) {
  832. if (val.__staleWhileFetching) {
  833. return val.__staleWhileFetching;
  834. }
  835. }
  836. else if (val !== undefined) {
  837. return val;
  838. }
  839. }
  840. }
  841. finally {
  842. if (this.#hasDisposeAfter && this.#disposed) {
  843. const dt = this.#disposed;
  844. let task;
  845. while ((task = dt?.shift())) {
  846. this.#disposeAfter?.(...task);
  847. }
  848. }
  849. }
  850. }
  851. #evict(free) {
  852. const head = this.#head;
  853. const k = this.#keyList[head];
  854. const v = this.#valList[head];
  855. if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
  856. v.__abortController.abort(new Error('evicted'));
  857. }
  858. else if (this.#hasDispose || this.#hasDisposeAfter) {
  859. if (this.#hasDispose) {
  860. this.#dispose?.(v, k, 'evict');
  861. }
  862. if (this.#hasDisposeAfter) {
  863. this.#disposed?.push([v, k, 'evict']);
  864. }
  865. }
  866. this.#removeItemSize(head);
  867. // if we aren't about to use the index, then null these out
  868. if (free) {
  869. this.#keyList[head] = undefined;
  870. this.#valList[head] = undefined;
  871. this.#free.push(head);
  872. }
  873. if (this.#size === 1) {
  874. this.#head = this.#tail = 0;
  875. this.#free.length = 0;
  876. }
  877. else {
  878. this.#head = this.#next[head];
  879. }
  880. this.#keyMap.delete(k);
  881. this.#size--;
  882. return head;
  883. }
  884. /**
  885. * Check if a key is in the cache, without updating the recency of use.
  886. * Will return false if the item is stale, even though it is technically
  887. * in the cache.
  888. *
  889. * Will not update item age unless
  890. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  891. */
  892. has(k, hasOptions = {}) {
  893. const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
  894. const index = this.#keyMap.get(k);
  895. if (index !== undefined) {
  896. const v = this.#valList[index];
  897. if (this.#isBackgroundFetch(v) &&
  898. v.__staleWhileFetching === undefined) {
  899. return false;
  900. }
  901. if (!this.#isStale(index)) {
  902. if (updateAgeOnHas) {
  903. this.#updateItemAge(index);
  904. }
  905. if (status) {
  906. status.has = 'hit';
  907. this.#statusTTL(status, index);
  908. }
  909. return true;
  910. }
  911. else if (status) {
  912. status.has = 'stale';
  913. this.#statusTTL(status, index);
  914. }
  915. }
  916. else if (status) {
  917. status.has = 'miss';
  918. }
  919. return false;
  920. }
  921. /**
  922. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  923. * items.
  924. *
  925. * Returns `undefined` if the item is stale, unless
  926. * {@link LRUCache.OptionsBase.allowStale} is set.
  927. */
  928. peek(k, peekOptions = {}) {
  929. const { allowStale = this.allowStale } = peekOptions;
  930. const index = this.#keyMap.get(k);
  931. if (index !== undefined &&
  932. (allowStale || !this.#isStale(index))) {
  933. const v = this.#valList[index];
  934. // either stale and allowed, or forcing a refresh of non-stale value
  935. return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
  936. }
  937. }
  938. #backgroundFetch(k, index, options, context) {
  939. const v = index === undefined ? undefined : this.#valList[index];
  940. if (this.#isBackgroundFetch(v)) {
  941. return v;
  942. }
  943. const ac = new AbortController();
  944. const { signal } = options;
  945. // when/if our AC signals, then stop listening to theirs.
  946. signal?.addEventListener('abort', () => ac.abort(signal.reason), {
  947. signal: ac.signal,
  948. });
  949. const fetchOpts = {
  950. signal: ac.signal,
  951. options,
  952. context,
  953. };
  954. const cb = (v, updateCache = false) => {
  955. const { aborted } = ac.signal;
  956. const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
  957. if (options.status) {
  958. if (aborted && !updateCache) {
  959. options.status.fetchAborted = true;
  960. options.status.fetchError = ac.signal.reason;
  961. if (ignoreAbort)
  962. options.status.fetchAbortIgnored = true;
  963. }
  964. else {
  965. options.status.fetchResolved = true;
  966. }
  967. }
  968. if (aborted && !ignoreAbort && !updateCache) {
  969. return fetchFail(ac.signal.reason);
  970. }
  971. // either we didn't abort, and are still here, or we did, and ignored
  972. const bf = p;
  973. if (this.#valList[index] === p) {
  974. if (v === undefined) {
  975. if (bf.__staleWhileFetching) {
  976. this.#valList[index] = bf.__staleWhileFetching;
  977. }
  978. else {
  979. this.delete(k);
  980. }
  981. }
  982. else {
  983. if (options.status)
  984. options.status.fetchUpdated = true;
  985. this.set(k, v, fetchOpts.options);
  986. }
  987. }
  988. return v;
  989. };
  990. const eb = (er) => {
  991. if (options.status) {
  992. options.status.fetchRejected = true;
  993. options.status.fetchError = er;
  994. }
  995. return fetchFail(er);
  996. };
  997. const fetchFail = (er) => {
  998. const { aborted } = ac.signal;
  999. const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
  1000. const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
  1001. const noDelete = allowStale || options.noDeleteOnFetchRejection;
  1002. const bf = p;
  1003. if (this.#valList[index] === p) {
  1004. // if we allow stale on fetch rejections, then we need to ensure that
  1005. // the stale value is not removed from the cache when the fetch fails.
  1006. const del = !noDelete || bf.__staleWhileFetching === undefined;
  1007. if (del) {
  1008. this.delete(k);
  1009. }
  1010. else if (!allowStaleAborted) {
  1011. // still replace the *promise* with the stale value,
  1012. // since we are done with the promise at this point.
  1013. // leave it untouched if we're still waiting for an
  1014. // aborted background fetch that hasn't yet returned.
  1015. this.#valList[index] = bf.__staleWhileFetching;
  1016. }
  1017. }
  1018. if (allowStale) {
  1019. if (options.status && bf.__staleWhileFetching !== undefined) {
  1020. options.status.returnedStale = true;
  1021. }
  1022. return bf.__staleWhileFetching;
  1023. }
  1024. else if (bf.__returned === bf) {
  1025. throw er;
  1026. }
  1027. };
  1028. const pcall = (res, rej) => {
  1029. const fmp = this.#fetchMethod?.(k, v, fetchOpts);
  1030. if (fmp && fmp instanceof Promise) {
  1031. fmp.then(v => res(v), rej);
  1032. }
  1033. // ignored, we go until we finish, regardless.
  1034. // defer check until we are actually aborting,
  1035. // so fetchMethod can override.
  1036. ac.signal.addEventListener('abort', () => {
  1037. if (!options.ignoreFetchAbort ||
  1038. options.allowStaleOnFetchAbort) {
  1039. res();
  1040. // when it eventually resolves, update the cache.
  1041. if (options.allowStaleOnFetchAbort) {
  1042. res = v => cb(v, true);
  1043. }
  1044. }
  1045. });
  1046. };
  1047. if (options.status)
  1048. options.status.fetchDispatched = true;
  1049. const p = new Promise(pcall).then(cb, eb);
  1050. const bf = Object.assign(p, {
  1051. __abortController: ac,
  1052. __staleWhileFetching: v,
  1053. __returned: undefined,
  1054. });
  1055. if (index === undefined) {
  1056. // internal, don't expose status.
  1057. this.set(k, bf, { ...fetchOpts.options, status: undefined });
  1058. index = this.#keyMap.get(k);
  1059. }
  1060. else {
  1061. this.#valList[index] = bf;
  1062. }
  1063. return bf;
  1064. }
  1065. #isBackgroundFetch(p) {
  1066. if (!this.#hasFetchMethod)
  1067. return false;
  1068. const b = p;
  1069. return (!!b &&
  1070. b instanceof Promise &&
  1071. b.hasOwnProperty('__staleWhileFetching') &&
  1072. b.__abortController instanceof AbortController);
  1073. }
  1074. async fetch(k, fetchOptions = {}) {
  1075. const {
  1076. // get options
  1077. allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
  1078. // set options
  1079. ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
  1080. // fetch exclusive options
  1081. noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
  1082. if (!this.#hasFetchMethod) {
  1083. if (status)
  1084. status.fetch = 'get';
  1085. return this.get(k, {
  1086. allowStale,
  1087. updateAgeOnGet,
  1088. noDeleteOnStaleGet,
  1089. status,
  1090. });
  1091. }
  1092. const options = {
  1093. allowStale,
  1094. updateAgeOnGet,
  1095. noDeleteOnStaleGet,
  1096. ttl,
  1097. noDisposeOnSet,
  1098. size,
  1099. sizeCalculation,
  1100. noUpdateTTL,
  1101. noDeleteOnFetchRejection,
  1102. allowStaleOnFetchRejection,
  1103. allowStaleOnFetchAbort,
  1104. ignoreFetchAbort,
  1105. status,
  1106. signal,
  1107. };
  1108. let index = this.#keyMap.get(k);
  1109. if (index === undefined) {
  1110. if (status)
  1111. status.fetch = 'miss';
  1112. const p = this.#backgroundFetch(k, index, options, context);
  1113. return (p.__returned = p);
  1114. }
  1115. else {
  1116. // in cache, maybe already fetching
  1117. const v = this.#valList[index];
  1118. if (this.#isBackgroundFetch(v)) {
  1119. const stale = allowStale && v.__staleWhileFetching !== undefined;
  1120. if (status) {
  1121. status.fetch = 'inflight';
  1122. if (stale)
  1123. status.returnedStale = true;
  1124. }
  1125. return stale ? v.__staleWhileFetching : (v.__returned = v);
  1126. }
  1127. // if we force a refresh, that means do NOT serve the cached value,
  1128. // unless we are already in the process of refreshing the cache.
  1129. const isStale = this.#isStale(index);
  1130. if (!forceRefresh && !isStale) {
  1131. if (status)
  1132. status.fetch = 'hit';
  1133. this.#moveToTail(index);
  1134. if (updateAgeOnGet) {
  1135. this.#updateItemAge(index);
  1136. }
  1137. if (status)
  1138. this.#statusTTL(status, index);
  1139. return v;
  1140. }
  1141. // ok, it is stale or a forced refresh, and not already fetching.
  1142. // refresh the cache.
  1143. const p = this.#backgroundFetch(k, index, options, context);
  1144. const hasStale = p.__staleWhileFetching !== undefined;
  1145. const staleVal = hasStale && allowStale;
  1146. if (status) {
  1147. status.fetch = isStale ? 'stale' : 'refresh';
  1148. if (staleVal && isStale)
  1149. status.returnedStale = true;
  1150. }
  1151. return staleVal ? p.__staleWhileFetching : (p.__returned = p);
  1152. }
  1153. }
  1154. /**
  1155. * Return a value from the cache. Will update the recency of the cache
  1156. * entry found.
  1157. *
  1158. * If the key is not found, get() will return `undefined`.
  1159. */
  1160. get(k, getOptions = {}) {
  1161. const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
  1162. const index = this.#keyMap.get(k);
  1163. if (index !== undefined) {
  1164. const value = this.#valList[index];
  1165. const fetching = this.#isBackgroundFetch(value);
  1166. if (status)
  1167. this.#statusTTL(status, index);
  1168. if (this.#isStale(index)) {
  1169. if (status)
  1170. status.get = 'stale';
  1171. // delete only if not an in-flight background fetch
  1172. if (!fetching) {
  1173. if (!noDeleteOnStaleGet) {
  1174. this.delete(k);
  1175. }
  1176. if (status && allowStale)
  1177. status.returnedStale = true;
  1178. return allowStale ? value : undefined;
  1179. }
  1180. else {
  1181. if (status &&
  1182. allowStale &&
  1183. value.__staleWhileFetching !== undefined) {
  1184. status.returnedStale = true;
  1185. }
  1186. return allowStale ? value.__staleWhileFetching : undefined;
  1187. }
  1188. }
  1189. else {
  1190. if (status)
  1191. status.get = 'hit';
  1192. // if we're currently fetching it, we don't actually have it yet
  1193. // it's not stale, which means this isn't a staleWhileRefetching.
  1194. // If it's not stale, and fetching, AND has a __staleWhileFetching
  1195. // value, then that means the user fetched with {forceRefresh:true},
  1196. // so it's safe to return that value.
  1197. if (fetching) {
  1198. return value.__staleWhileFetching;
  1199. }
  1200. this.#moveToTail(index);
  1201. if (updateAgeOnGet) {
  1202. this.#updateItemAge(index);
  1203. }
  1204. return value;
  1205. }
  1206. }
  1207. else if (status) {
  1208. status.get = 'miss';
  1209. }
  1210. }
  1211. #connect(p, n) {
  1212. this.#prev[n] = p;
  1213. this.#next[p] = n;
  1214. }
  1215. #moveToTail(index) {
  1216. // if tail already, nothing to do
  1217. // if head, move head to next[index]
  1218. // else
  1219. // move next[prev[index]] to next[index] (head has no prev)
  1220. // move prev[next[index]] to prev[index]
  1221. // prev[index] = tail
  1222. // next[tail] = index
  1223. // tail = index
  1224. if (index !== this.#tail) {
  1225. if (index === this.#head) {
  1226. this.#head = this.#next[index];
  1227. }
  1228. else {
  1229. this.#connect(this.#prev[index], this.#next[index]);
  1230. }
  1231. this.#connect(this.#tail, index);
  1232. this.#tail = index;
  1233. }
  1234. }
  1235. /**
  1236. * Deletes a key out of the cache.
  1237. * Returns true if the key was deleted, false otherwise.
  1238. */
  1239. delete(k) {
  1240. let deleted = false;
  1241. if (this.#size !== 0) {
  1242. const index = this.#keyMap.get(k);
  1243. if (index !== undefined) {
  1244. deleted = true;
  1245. if (this.#size === 1) {
  1246. this.clear();
  1247. }
  1248. else {
  1249. this.#removeItemSize(index);
  1250. const v = this.#valList[index];
  1251. if (this.#isBackgroundFetch(v)) {
  1252. v.__abortController.abort(new Error('deleted'));
  1253. }
  1254. else if (this.#hasDispose || this.#hasDisposeAfter) {
  1255. if (this.#hasDispose) {
  1256. this.#dispose?.(v, k, 'delete');
  1257. }
  1258. if (this.#hasDisposeAfter) {
  1259. this.#disposed?.push([v, k, 'delete']);
  1260. }
  1261. }
  1262. this.#keyMap.delete(k);
  1263. this.#keyList[index] = undefined;
  1264. this.#valList[index] = undefined;
  1265. if (index === this.#tail) {
  1266. this.#tail = this.#prev[index];
  1267. }
  1268. else if (index === this.#head) {
  1269. this.#head = this.#next[index];
  1270. }
  1271. else {
  1272. this.#next[this.#prev[index]] = this.#next[index];
  1273. this.#prev[this.#next[index]] = this.#prev[index];
  1274. }
  1275. this.#size--;
  1276. this.#free.push(index);
  1277. }
  1278. }
  1279. }
  1280. if (this.#hasDisposeAfter && this.#disposed?.length) {
  1281. const dt = this.#disposed;
  1282. let task;
  1283. while ((task = dt?.shift())) {
  1284. this.#disposeAfter?.(...task);
  1285. }
  1286. }
  1287. return deleted;
  1288. }
  1289. /**
  1290. * Clear the cache entirely, throwing away all values.
  1291. */
  1292. clear() {
  1293. for (const index of this.#rindexes({ allowStale: true })) {
  1294. const v = this.#valList[index];
  1295. if (this.#isBackgroundFetch(v)) {
  1296. v.__abortController.abort(new Error('deleted'));
  1297. }
  1298. else {
  1299. const k = this.#keyList[index];
  1300. if (this.#hasDispose) {
  1301. this.#dispose?.(v, k, 'delete');
  1302. }
  1303. if (this.#hasDisposeAfter) {
  1304. this.#disposed?.push([v, k, 'delete']);
  1305. }
  1306. }
  1307. }
  1308. this.#keyMap.clear();
  1309. this.#valList.fill(undefined);
  1310. this.#keyList.fill(undefined);
  1311. if (this.#ttls && this.#starts) {
  1312. this.#ttls.fill(0);
  1313. this.#starts.fill(0);
  1314. }
  1315. if (this.#sizes) {
  1316. this.#sizes.fill(0);
  1317. }
  1318. this.#head = 0;
  1319. this.#tail = 0;
  1320. this.#free.length = 0;
  1321. this.#calculatedSize = 0;
  1322. this.#size = 0;
  1323. if (this.#hasDisposeAfter && this.#disposed) {
  1324. const dt = this.#disposed;
  1325. let task;
  1326. while ((task = dt?.shift())) {
  1327. this.#disposeAfter?.(...task);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. exports.LRUCache = LRUCache;
  1333. exports.default = LRUCache;
  1334. //# sourceMappingURL=index.js.map