index.d.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. /**
  2. * @module LRUCache
  3. */
  4. export type Perf = {
  5. now: () => number;
  6. };
  7. declare const TYPE: unique symbol;
  8. export type PosInt = number & {
  9. [TYPE]: 'Positive Integer';
  10. };
  11. export type Index = number & {
  12. [TYPE]: 'LRUCache Index';
  13. };
  14. export type UintArray = Uint8Array | Uint16Array | Uint32Array;
  15. export type NumberArray = UintArray | number[];
  16. declare class ZeroArray extends Array<number> {
  17. constructor(size: number);
  18. }
  19. export type { ZeroArray };
  20. export type { Stack };
  21. export type StackLike = Stack | Index[];
  22. declare class Stack {
  23. #private;
  24. heap: NumberArray;
  25. length: number;
  26. static create(max: number): StackLike;
  27. constructor(max: number, HeapCls: {
  28. new (n: number): NumberArray;
  29. });
  30. push(n: Index): void;
  31. pop(): Index;
  32. }
  33. /**
  34. * Promise representing an in-progress {@link LRUCache#fetch} call
  35. */
  36. export type BackgroundFetch<V> = Promise<V | undefined> & {
  37. __returned: BackgroundFetch<V> | undefined;
  38. __abortController: AbortController;
  39. __staleWhileFetching: V | undefined;
  40. };
  41. export type DisposeTask<K, V> = [
  42. value: V,
  43. key: K,
  44. reason: LRUCache.DisposeReason
  45. ];
  46. export declare namespace LRUCache {
  47. /**
  48. * An integer greater than 0, reflecting the calculated size of items
  49. */
  50. type Size = number;
  51. /**
  52. * Integer greater than 0, representing some number of milliseconds, or the
  53. * time at which a TTL started counting from.
  54. */
  55. type Milliseconds = number;
  56. /**
  57. * An integer greater than 0, reflecting a number of items
  58. */
  59. type Count = number;
  60. /**
  61. * The reason why an item was removed from the cache, passed
  62. * to the {@link Disposer} methods.
  63. *
  64. * - `evict`: The item was evicted because it is the least recently used,
  65. * and the cache is full.
  66. * - `set`: A new value was set, overwriting the old value being disposed.
  67. * - `delete`: The item was explicitly deleted, either by calling
  68. * {@link LRUCache#delete}, {@link LRUCache#clear}, or
  69. * {@link LRUCache#set} with an undefined value.
  70. * - `expire`: The item was removed due to exceeding its TTL.
  71. * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned
  72. * `undefined` or was aborted, causing the item to be deleted.
  73. */
  74. type DisposeReason = 'evict' | 'set' | 'delete' | 'expire' | 'fetch';
  75. /**
  76. * A method called upon item removal, passed as the
  77. * {@link OptionsBase.dispose} and/or
  78. * {@link OptionsBase.disposeAfter} options.
  79. */
  80. type Disposer<K, V> = (value: V, key: K, reason: DisposeReason) => void;
  81. /**
  82. * The reason why an item was added to the cache, passed
  83. * to the {@link Inserter} methods.
  84. *
  85. * - `add`: the item was not found in the cache, and was added
  86. * - `update`: the item was in the cache, with the same value provided
  87. * - `replace`: the item was in the cache, and replaced
  88. */
  89. type InsertReason = 'add' | 'update' | 'replace';
  90. /**
  91. * A method called upon item insertion, passed as the
  92. * {@link OptionsBase.insert}
  93. */
  94. type Inserter<K, V> = (value: V, key: K, reason: InsertReason) => void;
  95. /**
  96. * A function that returns the effective calculated size
  97. * of an entry in the cache.
  98. */
  99. type SizeCalculator<K, V> = (value: V, key: K) => Size;
  100. /**
  101. * Options provided to the
  102. * {@link OptionsBase.fetchMethod} function.
  103. */
  104. interface FetcherOptions<K, V, FC = unknown> {
  105. signal: AbortSignal;
  106. options: FetcherFetchOptions<K, V, FC>;
  107. /**
  108. * Object provided in the {@link FetchOptions.context} option to
  109. * {@link LRUCache#fetch}
  110. */
  111. context: FC;
  112. }
  113. /**
  114. * Occasionally, it may be useful to track the internal behavior of the
  115. * cache, particularly for logging, debugging, or for behavior within the
  116. * `fetchMethod`. To do this, you can pass a `status` object to the
  117. * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},
  118. * {@link LRUCache#memo}, and {@link LRUCache#has} methods.
  119. *
  120. * The `status` option should be a plain JavaScript object. The following
  121. * fields will be set on it appropriately, depending on the situation.
  122. */
  123. interface Status<V> {
  124. /**
  125. * The status of a set() operation.
  126. *
  127. * - add: the item was not found in the cache, and was added
  128. * - update: the item was in the cache, with the same value provided
  129. * - replace: the item was in the cache, and replaced
  130. * - miss: the item was not added to the cache for some reason
  131. */
  132. set?: 'add' | 'update' | 'replace' | 'miss';
  133. /**
  134. * the ttl stored for the item, or undefined if ttls are not used.
  135. */
  136. ttl?: Milliseconds;
  137. /**
  138. * the start time for the item, or undefined if ttls are not used.
  139. */
  140. start?: Milliseconds;
  141. /**
  142. * The timestamp used for TTL calculation
  143. */
  144. now?: Milliseconds;
  145. /**
  146. * the remaining ttl for the item, or undefined if ttls are not used.
  147. */
  148. remainingTTL?: Milliseconds;
  149. /**
  150. * The calculated size for the item, if sizes are used.
  151. */
  152. entrySize?: Size;
  153. /**
  154. * The total calculated size of the cache, if sizes are used.
  155. */
  156. totalCalculatedSize?: Size;
  157. /**
  158. * A flag indicating that the item was not stored, due to exceeding the
  159. * {@link OptionsBase.maxEntrySize}
  160. */
  161. maxEntrySizeExceeded?: true;
  162. /**
  163. * The old value, specified in the case of `set:'update'` or
  164. * `set:'replace'`
  165. */
  166. oldValue?: V;
  167. /**
  168. * The results of a {@link LRUCache#has} operation
  169. *
  170. * - hit: the item was found in the cache
  171. * - stale: the item was found in the cache, but is stale
  172. * - miss: the item was not found in the cache
  173. */
  174. has?: 'hit' | 'stale' | 'miss';
  175. /**
  176. * The status of a {@link LRUCache#fetch} operation.
  177. * Note that this can change as the underlying fetch() moves through
  178. * various states.
  179. *
  180. * - inflight: there is another fetch() for this key which is in process
  181. * - get: there is no {@link OptionsBase.fetchMethod}, so
  182. * {@link LRUCache#get} was called.
  183. * - miss: the item is not in cache, and will be fetched.
  184. * - hit: the item is in the cache, and was resolved immediately.
  185. * - stale: the item is in the cache, but stale.
  186. * - refresh: the item is in the cache, and not stale, but
  187. * {@link FetchOptions.forceRefresh} was specified.
  188. */
  189. fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh';
  190. /**
  191. * The {@link OptionsBase.fetchMethod} was called
  192. */
  193. fetchDispatched?: true;
  194. /**
  195. * The cached value was updated after a successful call to
  196. * {@link OptionsBase.fetchMethod}
  197. */
  198. fetchUpdated?: true;
  199. /**
  200. * The reason for a fetch() rejection. Either the error raised by the
  201. * {@link OptionsBase.fetchMethod}, or the reason for an
  202. * AbortSignal.
  203. */
  204. fetchError?: Error;
  205. /**
  206. * The fetch received an abort signal
  207. */
  208. fetchAborted?: true;
  209. /**
  210. * The abort signal received was ignored, and the fetch was allowed to
  211. * continue.
  212. */
  213. fetchAbortIgnored?: true;
  214. /**
  215. * The fetchMethod promise resolved successfully
  216. */
  217. fetchResolved?: true;
  218. /**
  219. * The fetchMethod promise was rejected
  220. */
  221. fetchRejected?: true;
  222. /**
  223. * The status of a {@link LRUCache#get} operation.
  224. *
  225. * - fetching: The item is currently being fetched. If a previous value
  226. * is present and allowed, that will be returned.
  227. * - stale: The item is in the cache, and is stale.
  228. * - hit: the item is in the cache
  229. * - miss: the item is not in the cache
  230. */
  231. get?: 'stale' | 'hit' | 'miss';
  232. /**
  233. * A fetch or get operation returned a stale value.
  234. */
  235. returnedStale?: true;
  236. }
  237. /**
  238. * options which override the options set in the LRUCache constructor
  239. * when calling {@link LRUCache#fetch}.
  240. *
  241. * This is the union of {@link GetOptions} and {@link SetOptions}, plus
  242. * {@link OptionsBase.noDeleteOnFetchRejection},
  243. * {@link OptionsBase.allowStaleOnFetchRejection},
  244. * {@link FetchOptions.forceRefresh}, and
  245. * {@link FetcherOptions.context}
  246. *
  247. * Any of these may be modified in the {@link OptionsBase.fetchMethod}
  248. * function, but the {@link GetOptions} fields will of course have no
  249. * effect, as the {@link LRUCache#get} call already happened by the time
  250. * the fetchMethod is called.
  251. */
  252. interface FetcherFetchOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> {
  253. status?: Status<V>;
  254. size?: Size;
  255. }
  256. /**
  257. * Options that may be passed to the {@link LRUCache#fetch} method.
  258. */
  259. interface FetchOptions<K, V, FC> extends FetcherFetchOptions<K, V, FC> {
  260. /**
  261. * Set to true to force a re-load of the existing data, even if it
  262. * is not yet stale.
  263. */
  264. forceRefresh?: boolean;
  265. /**
  266. * Context provided to the {@link OptionsBase.fetchMethod} as
  267. * the {@link FetcherOptions.context} param.
  268. *
  269. * If the FC type is specified as unknown (the default),
  270. * undefined or void, then this is optional. Otherwise, it will
  271. * be required.
  272. */
  273. context?: FC;
  274. signal?: AbortSignal;
  275. status?: Status<V>;
  276. }
  277. /**
  278. * Options provided to {@link LRUCache#fetch} when the FC type is something
  279. * other than `unknown`, `undefined`, or `void`
  280. */
  281. interface FetchOptionsWithContext<K, V, FC> extends FetchOptions<K, V, FC> {
  282. context: FC;
  283. }
  284. /**
  285. * Options provided to {@link LRUCache#fetch} when the FC type is
  286. * `undefined` or `void`
  287. */
  288. interface FetchOptionsNoContext<K, V> extends FetchOptions<K, V, undefined> {
  289. context?: undefined;
  290. }
  291. interface MemoOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL' | 'noDeleteOnFetchRejection' | 'allowStaleOnFetchRejection' | 'ignoreFetchAbort' | 'allowStaleOnFetchAbort'> {
  292. /**
  293. * Set to true to force a re-load of the existing data, even if it
  294. * is not yet stale.
  295. */
  296. forceRefresh?: boolean;
  297. /**
  298. * Context provided to the {@link OptionsBase.memoMethod} as
  299. * the {@link MemoizerOptions.context} param.
  300. *
  301. * If the FC type is specified as unknown (the default),
  302. * undefined or void, then this is optional. Otherwise, it will
  303. * be required.
  304. */
  305. context?: FC;
  306. status?: Status<V>;
  307. }
  308. /**
  309. * Options provided to {@link LRUCache#memo} when the FC type is something
  310. * other than `unknown`, `undefined`, or `void`
  311. */
  312. interface MemoOptionsWithContext<K, V, FC> extends MemoOptions<K, V, FC> {
  313. context: FC;
  314. }
  315. /**
  316. * Options provided to {@link LRUCache#memo} when the FC type is
  317. * `undefined` or `void`
  318. */
  319. interface MemoOptionsNoContext<K, V> extends MemoOptions<K, V, undefined> {
  320. context?: undefined;
  321. }
  322. /**
  323. * Options provided to the
  324. * {@link OptionsBase.memoMethod} function.
  325. */
  326. interface MemoizerOptions<K, V, FC = unknown> {
  327. options: MemoizerMemoOptions<K, V, FC>;
  328. /**
  329. * Object provided in the {@link MemoOptions.context} option to
  330. * {@link LRUCache#memo}
  331. */
  332. context: FC;
  333. }
  334. /**
  335. * options which override the options set in the LRUCache constructor
  336. * when calling {@link LRUCache#memo}.
  337. *
  338. * This is the union of {@link GetOptions} and {@link SetOptions}, plus
  339. * {@link MemoOptions.forceRefresh}, and
  340. * {@link MemoOptions.context}
  341. *
  342. * Any of these may be modified in the {@link OptionsBase.memoMethod}
  343. * function, but the {@link GetOptions} fields will of course have no
  344. * effect, as the {@link LRUCache#get} call already happened by the time
  345. * the memoMethod is called.
  346. */
  347. interface MemoizerMemoOptions<K, V, FC = unknown> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet' | 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> {
  348. status?: Status<V>;
  349. size?: Size;
  350. start?: Milliseconds;
  351. }
  352. /**
  353. * Options that may be passed to the {@link LRUCache#has} method.
  354. */
  355. interface HasOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'updateAgeOnHas'> {
  356. status?: Status<V>;
  357. }
  358. /**
  359. * Options that may be passed to the {@link LRUCache#get} method.
  360. */
  361. interface GetOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'> {
  362. status?: Status<V>;
  363. }
  364. /**
  365. * Options that may be passed to the {@link LRUCache#peek} method.
  366. */
  367. interface PeekOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'allowStale'> {
  368. }
  369. /**
  370. * Options that may be passed to the {@link LRUCache#set} method.
  371. */
  372. interface SetOptions<K, V, FC> extends Pick<OptionsBase<K, V, FC>, 'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'> {
  373. /**
  374. * If size tracking is enabled, then setting an explicit size
  375. * in the {@link LRUCache#set} call will prevent calling the
  376. * {@link OptionsBase.sizeCalculation} function.
  377. */
  378. size?: Size;
  379. /**
  380. * If TTL tracking is enabled, then setting an explicit start
  381. * time in the {@link LRUCache#set} call will override the
  382. * default time from `performance.now()` or `Date.now()`.
  383. *
  384. * Note that it must be a valid value for whichever time-tracking
  385. * method is in use.
  386. */
  387. start?: Milliseconds;
  388. status?: Status<V>;
  389. }
  390. /**
  391. * The type signature for the {@link OptionsBase.fetchMethod} option.
  392. */
  393. type Fetcher<K, V, FC = unknown> = (key: K, staleValue: V | undefined, options: FetcherOptions<K, V, FC>) => Promise<V | undefined | void> | V | undefined | void;
  394. /**
  395. * the type signature for the {@link OptionsBase.memoMethod} option.
  396. */
  397. type Memoizer<K, V, FC = unknown> = (key: K, staleValue: V | undefined, options: MemoizerOptions<K, V, FC>) => V;
  398. /**
  399. * Options which may be passed to the {@link LRUCache} constructor.
  400. *
  401. * Most of these may be overridden in the various options that use
  402. * them.
  403. *
  404. * Despite all being technically optional, the constructor requires that
  405. * a cache is at minimum limited by one or more of {@link OptionsBase.max},
  406. * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.
  407. *
  408. * If {@link OptionsBase.ttl} is used alone, then it is strongly advised
  409. * (and in fact required by the type definitions here) that the cache
  410. * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially
  411. * unbounded storage.
  412. *
  413. * All options are also available on the {@link LRUCache} instance, making
  414. * it safe to pass an LRUCache instance as the options argumemnt to
  415. * make another empty cache of the same type.
  416. *
  417. * Some options are marked as read-only, because changing them after
  418. * instantiation is not safe. Changing any of the other options will of
  419. * course only have an effect on subsequent method calls.
  420. */
  421. interface OptionsBase<K, V, FC> {
  422. /**
  423. * The maximum number of items to store in the cache before evicting
  424. * old entries. This is read-only on the {@link LRUCache} instance,
  425. * and may not be overridden.
  426. *
  427. * If set, then storage space will be pre-allocated at construction
  428. * time, and the cache will perform significantly faster.
  429. *
  430. * Note that significantly fewer items may be stored, if
  431. * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also
  432. * set.
  433. *
  434. * **It is strongly recommended to set a `max` to prevent unbounded growth
  435. * of the cache.**
  436. */
  437. max?: Count;
  438. /**
  439. * Max time in milliseconds for items to live in cache before they are
  440. * considered stale. Note that stale items are NOT preemptively removed by
  441. * default, and MAY live in the cache, contributing to its LRU max, long
  442. * after they have expired, unless {@link OptionsBase.ttlAutopurge} is
  443. * set.
  444. *
  445. * If set to `0` (the default value), then that means "do not track
  446. * TTL", not "expire immediately".
  447. *
  448. * Also, as this cache is optimized for LRU/MRU operations, some of
  449. * the staleness/TTL checks will reduce performance, as they will incur
  450. * overhead by deleting items.
  451. *
  452. * This is not primarily a TTL cache, and does not make strong TTL
  453. * guarantees. There is no pre-emptive pruning of expired items, but you
  454. * _may_ set a TTL on the cache, and it will treat expired items as missing
  455. * when they are fetched, and delete them.
  456. *
  457. * Optional, but must be a non-negative integer in ms if specified.
  458. *
  459. * This may be overridden by passing an options object to `cache.set()`.
  460. *
  461. * At least one of `max`, `maxSize`, or `TTL` is required. This must be a
  462. * positive integer if set.
  463. *
  464. * Even if ttl tracking is enabled, **it is strongly recommended to set a
  465. * `max` to prevent unbounded growth of the cache.**
  466. *
  467. * If ttl tracking is enabled, and `max` and `maxSize` are not set,
  468. * and `ttlAutopurge` is not set, then a warning will be emitted
  469. * cautioning about the potential for unbounded memory consumption.
  470. * (The TypeScript definitions will also discourage this.)
  471. */
  472. ttl?: Milliseconds;
  473. /**
  474. * Minimum amount of time in ms in which to check for staleness.
  475. * Defaults to 1, which means that the current time is checked
  476. * at most once per millisecond.
  477. *
  478. * Set to 0 to check the current time every time staleness is tested.
  479. * (This reduces performance, and is theoretically unnecessary.)
  480. *
  481. * Setting this to a higher value will improve performance somewhat
  482. * while using ttl tracking, albeit at the expense of keeping stale
  483. * items around a bit longer than their TTLs would indicate.
  484. *
  485. * @default 1
  486. */
  487. ttlResolution?: Milliseconds;
  488. /**
  489. * Preemptively remove stale items from the cache.
  490. *
  491. * Note that this may *significantly* degrade performance, especially if
  492. * the cache is storing a large number of items. It is almost always best
  493. * to just leave the stale items in the cache, and let them fall out as new
  494. * items are added.
  495. *
  496. * Note that this means that {@link OptionsBase.allowStale} is a bit
  497. * pointless, as stale items will be deleted almost as soon as they
  498. * expire.
  499. *
  500. * Use with caution!
  501. */
  502. ttlAutopurge?: boolean;
  503. /**
  504. * When using time-expiring entries with `ttl`, setting this to `true` will
  505. * make each item's age reset to 0 whenever it is retrieved from cache with
  506. * {@link LRUCache#get}, causing it to not expire. (It can still fall out
  507. * of cache based on recency of use, of course.)
  508. *
  509. * Has no effect if {@link OptionsBase.ttl} is not set.
  510. *
  511. * This may be overridden by passing an options object to `cache.get()`.
  512. */
  513. updateAgeOnGet?: boolean;
  514. /**
  515. * When using time-expiring entries with `ttl`, setting this to `true` will
  516. * make each item's age reset to 0 whenever its presence in the cache is
  517. * checked with {@link LRUCache#has}, causing it to not expire. (It can
  518. * still fall out of cache based on recency of use, of course.)
  519. *
  520. * Has no effect if {@link OptionsBase.ttl} is not set.
  521. */
  522. updateAgeOnHas?: boolean;
  523. /**
  524. * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return
  525. * stale data, if available.
  526. *
  527. * By default, if you set `ttl`, stale items will only be deleted from the
  528. * cache when you `get(key)`. That is, it's not preemptively pruning items,
  529. * unless {@link OptionsBase.ttlAutopurge} is set.
  530. *
  531. * If you set `allowStale:true`, it'll return the stale value *as well as*
  532. * deleting it. If you don't set this, then it'll return `undefined` when
  533. * you try to get a stale entry.
  534. *
  535. * Note that when a stale entry is fetched, _even if it is returned due to
  536. * `allowStale` being set_, it is removed from the cache immediately. You
  537. * can suppress this behavior by setting
  538. * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in
  539. * the options provided to {@link LRUCache#get}.
  540. *
  541. * This may be overridden by passing an options object to `cache.get()`.
  542. * The `cache.has()` method will always return `false` for stale items.
  543. *
  544. * Only relevant if a ttl is set.
  545. */
  546. allowStale?: boolean;
  547. /**
  548. * Function that is called on items when they are dropped from the
  549. * cache, as `dispose(value, key, reason)`.
  550. *
  551. * This can be handy if you want to close file descriptors or do
  552. * other cleanup tasks when items are no longer stored in the cache.
  553. *
  554. * **NOTE**: It is called _before_ the item has been fully removed
  555. * from the cache, so if you want to put it right back in, you need
  556. * to wait until the next tick. If you try to add it back in during
  557. * the `dispose()` function call, it will break things in subtle and
  558. * weird ways.
  559. *
  560. * Unlike several other options, this may _not_ be overridden by
  561. * passing an option to `set()`, for performance reasons.
  562. *
  563. * The `reason` will be one of the following strings, corresponding
  564. * to the reason for the item's deletion:
  565. *
  566. * - `evict` Item was evicted to make space for a new addition
  567. * - `set` Item was overwritten by a new value
  568. * - `expire` Item expired its TTL
  569. * - `fetch` Item was deleted due to a failed or aborted fetch, or a
  570. * fetchMethod returning `undefined.
  571. * - `delete` Item was removed by explicit `cache.delete(key)`,
  572. * `cache.clear()`, or `cache.set(key, undefined)`.
  573. */
  574. dispose?: Disposer<K, V>;
  575. /**
  576. * Function that is called when new items are inserted into the cache,
  577. * as `onInsert(value, key, reason)`.
  578. *
  579. * This can be useful if you need to perform actions when an item is
  580. * added, such as logging or tracking insertions.
  581. *
  582. * Unlike some other options, this may _not_ be overridden by passing
  583. * an option to `set()`, for performance and consistency reasons.
  584. */
  585. onInsert?: Inserter<K, V>;
  586. /**
  587. * The same as {@link OptionsBase.dispose}, but called *after* the entry
  588. * is completely removed and the cache is once again in a clean state.
  589. *
  590. * It is safe to add an item right back into the cache at this point.
  591. * However, note that it is *very* easy to inadvertently create infinite
  592. * recursion this way.
  593. */
  594. disposeAfter?: Disposer<K, V>;
  595. /**
  596. * Set to true to suppress calling the
  597. * {@link OptionsBase.dispose} function if the entry key is
  598. * still accessible within the cache.
  599. *
  600. * This may be overridden by passing an options object to
  601. * {@link LRUCache#set}.
  602. *
  603. * Only relevant if `dispose` or `disposeAfter` are set.
  604. */
  605. noDisposeOnSet?: boolean;
  606. /**
  607. * Boolean flag to tell the cache to not update the TTL when setting a new
  608. * value for an existing key (ie, when updating a value rather than
  609. * inserting a new value). Note that the TTL value is _always_ set (if
  610. * provided) when adding a new entry into the cache.
  611. *
  612. * Has no effect if a {@link OptionsBase.ttl} is not set.
  613. *
  614. * May be passed as an option to {@link LRUCache#set}.
  615. */
  616. noUpdateTTL?: boolean;
  617. /**
  618. * Set to a positive integer to track the sizes of items added to the
  619. * cache, and automatically evict items in order to stay below this size.
  620. * Note that this may result in fewer than `max` items being stored.
  621. *
  622. * Attempting to add an item to the cache whose calculated size is greater
  623. * that this amount will be a no-op. The item will not be cached, and no
  624. * other items will be evicted.
  625. *
  626. * Optional, must be a positive integer if provided.
  627. *
  628. * Sets `maxEntrySize` to the same value, unless a different value is
  629. * provided for `maxEntrySize`.
  630. *
  631. * At least one of `max`, `maxSize`, or `TTL` is required. This must be a
  632. * positive integer if set.
  633. *
  634. * Even if size tracking is enabled, **it is strongly recommended to set a
  635. * `max` to prevent unbounded growth of the cache.**
  636. *
  637. * Note also that size tracking can negatively impact performance,
  638. * though for most cases, only minimally.
  639. */
  640. maxSize?: Size;
  641. /**
  642. * The maximum allowed size for any single item in the cache.
  643. *
  644. * If a larger item is passed to {@link LRUCache#set} or returned by a
  645. * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then
  646. * it will not be stored in the cache.
  647. *
  648. * Attempting to add an item whose calculated size is greater than
  649. * this amount will not cache the item or evict any old items, but
  650. * WILL delete an existing value if one is already present.
  651. *
  652. * Optional, must be a positive integer if provided. Defaults to
  653. * the value of `maxSize` if provided.
  654. */
  655. maxEntrySize?: Size;
  656. /**
  657. * A function that returns a number indicating the item's size.
  658. *
  659. * Requires {@link OptionsBase.maxSize} to be set.
  660. *
  661. * If not provided, and {@link OptionsBase.maxSize} or
  662. * {@link OptionsBase.maxEntrySize} are set, then all
  663. * {@link LRUCache#set} calls **must** provide an explicit
  664. * {@link SetOptions.size} or sizeCalculation param.
  665. */
  666. sizeCalculation?: SizeCalculator<K, V>;
  667. /**
  668. * Method that provides the implementation for {@link LRUCache#fetch}
  669. *
  670. * ```ts
  671. * fetchMethod(key, staleValue, { signal, options, context })
  672. * ```
  673. *
  674. * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent
  675. * to `Promise.resolve(cache.get(key))`.
  676. *
  677. * If at any time, `signal.aborted` is set to `true`, or if the
  678. * `signal.onabort` method is called, or if it emits an `'abort'` event
  679. * which you can listen to with `addEventListener`, then that means that
  680. * the fetch should be abandoned. This may be passed along to async
  681. * functions aware of AbortController/AbortSignal behavior.
  682. *
  683. * The `fetchMethod` should **only** return `undefined` or a Promise
  684. * resolving to `undefined` if the AbortController signaled an `abort`
  685. * event. In all other cases, it should return or resolve to a value
  686. * suitable for adding to the cache.
  687. *
  688. * The `options` object is a union of the options that may be provided to
  689. * `set()` and `get()`. If they are modified, then that will result in
  690. * modifying the settings to `cache.set()` when the value is resolved, and
  691. * in the case of
  692. * {@link OptionsBase.noDeleteOnFetchRejection} and
  693. * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of
  694. * `fetchMethod` failures.
  695. *
  696. * For example, a DNS cache may update the TTL based on the value returned
  697. * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.
  698. */
  699. fetchMethod?: Fetcher<K, V, FC>;
  700. /**
  701. * Method that provides the implementation for {@link LRUCache#memo}
  702. */
  703. memoMethod?: Memoizer<K, V, FC>;
  704. /**
  705. * Set to true to suppress the deletion of stale data when a
  706. * {@link OptionsBase.fetchMethod} returns a rejected promise.
  707. */
  708. noDeleteOnFetchRejection?: boolean;
  709. /**
  710. * Do not delete stale items when they are retrieved with
  711. * {@link LRUCache#get}.
  712. *
  713. * Note that the `get` return value will still be `undefined`
  714. * unless {@link OptionsBase.allowStale} is true.
  715. *
  716. * When using time-expiring entries with `ttl`, by default stale
  717. * items will be removed from the cache when the key is accessed
  718. * with `cache.get()`.
  719. *
  720. * Setting this option will cause stale items to remain in the cache, until
  721. * they are explicitly deleted with `cache.delete(key)`, or retrieved with
  722. * `noDeleteOnStaleGet` set to `false`.
  723. *
  724. * This may be overridden by passing an options object to `cache.get()`.
  725. *
  726. * Only relevant if a ttl is used.
  727. */
  728. noDeleteOnStaleGet?: boolean;
  729. /**
  730. * Set to true to allow returning stale data when a
  731. * {@link OptionsBase.fetchMethod} throws an error or returns a rejected
  732. * promise.
  733. *
  734. * This differs from using {@link OptionsBase.allowStale} in that stale
  735. * data will ONLY be returned in the case that the {@link LRUCache#fetch}
  736. * fails, not any other times.
  737. *
  738. * If a `fetchMethod` fails, and there is no stale value available, the
  739. * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are
  740. * suppressed.
  741. *
  742. * Implies `noDeleteOnFetchRejection`.
  743. *
  744. * This may be set in calls to `fetch()`, or defaulted on the constructor,
  745. * or overridden by modifying the options object in the `fetchMethod`.
  746. */
  747. allowStaleOnFetchRejection?: boolean;
  748. /**
  749. * Set to true to return a stale value from the cache when the
  750. * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches
  751. * an `'abort'` event, whether user-triggered, or due to internal cache
  752. * behavior.
  753. *
  754. * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying
  755. * {@link OptionsBase.fetchMethod} will still be considered canceled, and
  756. * any value it returns will be ignored and not cached.
  757. *
  758. * Caveat: since fetches are aborted when a new value is explicitly
  759. * set in the cache, this can lead to fetch returning a stale value,
  760. * since that was the fallback value _at the moment the `fetch()` was
  761. * initiated_, even though the new updated value is now present in
  762. * the cache.
  763. *
  764. * For example:
  765. *
  766. * ```ts
  767. * const cache = new LRUCache<string, any>({
  768. * ttl: 100,
  769. * fetchMethod: async (url, oldValue, { signal }) => {
  770. * const res = await fetch(url, { signal })
  771. * return await res.json()
  772. * }
  773. * })
  774. * cache.set('https://example.com/', { some: 'data' })
  775. * // 100ms go by...
  776. * const result = cache.fetch('https://example.com/')
  777. * cache.set('https://example.com/', { other: 'thing' })
  778. * console.log(await result) // { some: 'data' }
  779. * console.log(cache.get('https://example.com/')) // { other: 'thing' }
  780. * ```
  781. */
  782. allowStaleOnFetchAbort?: boolean;
  783. /**
  784. * Set to true to ignore the `abort` event emitted by the `AbortSignal`
  785. * object passed to {@link OptionsBase.fetchMethod}, and still cache the
  786. * resulting resolution value, as long as it is not `undefined`.
  787. *
  788. * When used on its own, this means aborted {@link LRUCache#fetch} calls
  789. * are not immediately resolved or rejected when they are aborted, and
  790. * instead take the full time to await.
  791. *
  792. * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted
  793. * {@link LRUCache#fetch} calls will resolve immediately to their stale
  794. * cached value or `undefined`, and will continue to process and eventually
  795. * update the cache when they resolve, as long as the resulting value is
  796. * not `undefined`, thus supporting a "return stale on timeout while
  797. * refreshing" mechanism by passing `AbortSignal.timeout(n)` as the signal.
  798. *
  799. * For example:
  800. *
  801. * ```ts
  802. * const c = new LRUCache({
  803. * ttl: 100,
  804. * ignoreFetchAbort: true,
  805. * allowStaleOnFetchAbort: true,
  806. * fetchMethod: async (key, oldValue, { signal }) => {
  807. * // note: do NOT pass the signal to fetch()!
  808. * // let's say this fetch can take a long time.
  809. * const res = await fetch(`https://slow-backend-server/${key}`)
  810. * return await res.json()
  811. * },
  812. * })
  813. *
  814. * // this will return the stale value after 100ms, while still
  815. * // updating in the background for next time.
  816. * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })
  817. * ```
  818. *
  819. * **Note**: regardless of this setting, an `abort` event _is still
  820. * emitted on the `AbortSignal` object_, so may result in invalid results
  821. * when passed to other underlying APIs that use AbortSignals.
  822. *
  823. * This may be overridden in the {@link OptionsBase.fetchMethod} or the
  824. * call to {@link LRUCache#fetch}.
  825. */
  826. ignoreFetchAbort?: boolean;
  827. /**
  828. * In some cases, you may want to swap out the performance/Date object
  829. * used for TTL tracking. This should almost certainly NOT be done in
  830. * production environments!
  831. *
  832. * This value defaults to `global.performance` if it has a `now()` method,
  833. * or the `global.Date` object otherwise.
  834. */
  835. perf?: Perf;
  836. }
  837. interface OptionsMaxLimit<K, V, FC> extends OptionsBase<K, V, FC> {
  838. max: Count;
  839. }
  840. interface OptionsTTLLimit<K, V, FC> extends OptionsBase<K, V, FC> {
  841. ttl: Milliseconds;
  842. ttlAutopurge: boolean;
  843. }
  844. interface OptionsSizeLimit<K, V, FC> extends OptionsBase<K, V, FC> {
  845. maxSize: Size;
  846. }
  847. /**
  848. * The valid safe options for the {@link LRUCache} constructor
  849. */
  850. type Options<K, V, FC> = OptionsMaxLimit<K, V, FC> | OptionsSizeLimit<K, V, FC> | OptionsTTLLimit<K, V, FC>;
  851. /**
  852. * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},
  853. * and returned by {@link LRUCache#info}.
  854. */
  855. interface Entry<V> {
  856. value: V;
  857. ttl?: Milliseconds;
  858. size?: Size;
  859. start?: Milliseconds;
  860. }
  861. }
  862. /**
  863. * Default export, the thing you're using this module to get.
  864. *
  865. * The `K` and `V` types define the key and value types, respectively. The
  866. * optional `FC` type defines the type of the `context` object passed to
  867. * `cache.fetch()` and `cache.memo()`.
  868. *
  869. * Keys and values **must not** be `null` or `undefined`.
  870. *
  871. * All properties from the options object (with the exception of `max`,
  872. * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
  873. * added as normal public members. (The listed options are read-only getters.)
  874. *
  875. * Changing any of these will alter the defaults for subsequent method calls.
  876. */
  877. export declare class LRUCache<K extends {}, V extends {}, FC = unknown> {
  878. #private;
  879. /**
  880. * {@link LRUCache.OptionsBase.perf}
  881. */
  882. get perf(): Perf;
  883. /**
  884. * {@link LRUCache.OptionsBase.ttl}
  885. */
  886. ttl: LRUCache.Milliseconds;
  887. /**
  888. * {@link LRUCache.OptionsBase.ttlResolution}
  889. */
  890. ttlResolution: LRUCache.Milliseconds;
  891. /**
  892. * {@link LRUCache.OptionsBase.ttlAutopurge}
  893. */
  894. ttlAutopurge: boolean;
  895. /**
  896. * {@link LRUCache.OptionsBase.updateAgeOnGet}
  897. */
  898. updateAgeOnGet: boolean;
  899. /**
  900. * {@link LRUCache.OptionsBase.updateAgeOnHas}
  901. */
  902. updateAgeOnHas: boolean;
  903. /**
  904. * {@link LRUCache.OptionsBase.allowStale}
  905. */
  906. allowStale: boolean;
  907. /**
  908. * {@link LRUCache.OptionsBase.noDisposeOnSet}
  909. */
  910. noDisposeOnSet: boolean;
  911. /**
  912. * {@link LRUCache.OptionsBase.noUpdateTTL}
  913. */
  914. noUpdateTTL: boolean;
  915. /**
  916. * {@link LRUCache.OptionsBase.maxEntrySize}
  917. */
  918. maxEntrySize: LRUCache.Size;
  919. /**
  920. * {@link LRUCache.OptionsBase.sizeCalculation}
  921. */
  922. sizeCalculation?: LRUCache.SizeCalculator<K, V>;
  923. /**
  924. * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
  925. */
  926. noDeleteOnFetchRejection: boolean;
  927. /**
  928. * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
  929. */
  930. noDeleteOnStaleGet: boolean;
  931. /**
  932. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
  933. */
  934. allowStaleOnFetchAbort: boolean;
  935. /**
  936. * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
  937. */
  938. allowStaleOnFetchRejection: boolean;
  939. /**
  940. * {@link LRUCache.OptionsBase.ignoreFetchAbort}
  941. */
  942. ignoreFetchAbort: boolean;
  943. /**
  944. * Do not call this method unless you need to inspect the
  945. * inner workings of the cache. If anything returned by this
  946. * object is modified in any way, strange breakage may occur.
  947. *
  948. * These fields are private for a reason!
  949. *
  950. * @internal
  951. */
  952. static unsafeExposeInternals<K extends {}, V extends {}, FC extends unknown = unknown>(c: LRUCache<K, V, FC>): {
  953. starts: ZeroArray | undefined;
  954. ttls: ZeroArray | undefined;
  955. autopurgeTimers: (NodeJS.Timeout | undefined)[] | undefined;
  956. sizes: ZeroArray | undefined;
  957. keyMap: Map<K, number>;
  958. keyList: (K | undefined)[];
  959. valList: (V | BackgroundFetch<V> | undefined)[];
  960. next: NumberArray;
  961. prev: NumberArray;
  962. readonly head: Index;
  963. readonly tail: Index;
  964. free: StackLike;
  965. isBackgroundFetch: (p: any) => p is BackgroundFetch<V>;
  966. backgroundFetch: (k: K, index: number | undefined, options: LRUCache.FetchOptions<K, V, FC>, context: any) => BackgroundFetch<V>;
  967. moveToTail: (index: number) => void;
  968. indexes: (options?: {
  969. allowStale: boolean;
  970. }) => Generator<Index, void, unknown>;
  971. rindexes: (options?: {
  972. allowStale: boolean;
  973. }) => Generator<Index, void, unknown>;
  974. isStale: (index: number | undefined) => boolean;
  975. };
  976. /**
  977. * {@link LRUCache.OptionsBase.max} (read-only)
  978. */
  979. get max(): LRUCache.Count;
  980. /**
  981. * {@link LRUCache.OptionsBase.maxSize} (read-only)
  982. */
  983. get maxSize(): LRUCache.Count;
  984. /**
  985. * The total computed size of items in the cache (read-only)
  986. */
  987. get calculatedSize(): LRUCache.Size;
  988. /**
  989. * The number of items stored in the cache (read-only)
  990. */
  991. get size(): LRUCache.Count;
  992. /**
  993. * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
  994. */
  995. get fetchMethod(): LRUCache.Fetcher<K, V, FC> | undefined;
  996. get memoMethod(): LRUCache.Memoizer<K, V, FC> | undefined;
  997. /**
  998. * {@link LRUCache.OptionsBase.dispose} (read-only)
  999. */
  1000. get dispose(): LRUCache.Disposer<K, V> | undefined;
  1001. /**
  1002. * {@link LRUCache.OptionsBase.onInsert} (read-only)
  1003. */
  1004. get onInsert(): LRUCache.Inserter<K, V> | undefined;
  1005. /**
  1006. * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
  1007. */
  1008. get disposeAfter(): LRUCache.Disposer<K, V> | undefined;
  1009. constructor(options: LRUCache.Options<K, V, FC> | LRUCache<K, V, FC>);
  1010. /**
  1011. * Return the number of ms left in the item's TTL. If item is not in cache,
  1012. * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
  1013. */
  1014. getRemainingTTL(key: K): number;
  1015. /**
  1016. * Return a generator yielding `[key, value]` pairs,
  1017. * in order from most recently used to least recently used.
  1018. */
  1019. entries(): Generator<[K, V], void, unknown>;
  1020. /**
  1021. * Inverse order version of {@link LRUCache.entries}
  1022. *
  1023. * Return a generator yielding `[key, value]` pairs,
  1024. * in order from least recently used to most recently used.
  1025. */
  1026. rentries(): Generator<(K | V)[], void, unknown>;
  1027. /**
  1028. * Return a generator yielding the keys in the cache,
  1029. * in order from most recently used to least recently used.
  1030. */
  1031. keys(): Generator<K, void, unknown>;
  1032. /**
  1033. * Inverse order version of {@link LRUCache.keys}
  1034. *
  1035. * Return a generator yielding the keys in the cache,
  1036. * in order from least recently used to most recently used.
  1037. */
  1038. rkeys(): Generator<K, void, unknown>;
  1039. /**
  1040. * Return a generator yielding the values in the cache,
  1041. * in order from most recently used to least recently used.
  1042. */
  1043. values(): Generator<V, void, unknown>;
  1044. /**
  1045. * Inverse order version of {@link LRUCache.values}
  1046. *
  1047. * Return a generator yielding the values in the cache,
  1048. * in order from least recently used to most recently used.
  1049. */
  1050. rvalues(): Generator<V | undefined, void, unknown>;
  1051. /**
  1052. * Iterating over the cache itself yields the same results as
  1053. * {@link LRUCache.entries}
  1054. */
  1055. [Symbol.iterator](): Generator<[K, V], void, unknown>;
  1056. /**
  1057. * A String value that is used in the creation of the default string
  1058. * description of an object. Called by the built-in method
  1059. * `Object.prototype.toString`.
  1060. */
  1061. [Symbol.toStringTag]: string;
  1062. /**
  1063. * Find a value for which the supplied fn method returns a truthy value,
  1064. * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
  1065. */
  1066. find(fn: (v: V, k: K, self: LRUCache<K, V, FC>) => boolean, getOptions?: LRUCache.GetOptions<K, V, FC>): V | undefined;
  1067. /**
  1068. * Call the supplied function on each item in the cache, in order from most
  1069. * recently used to least recently used.
  1070. *
  1071. * `fn` is called as `fn(value, key, cache)`.
  1072. *
  1073. * If `thisp` is provided, function will be called in the `this`-context of
  1074. * the provided object, or the cache if no `thisp` object is provided.
  1075. *
  1076. * Does not update age or recenty of use, or iterate over stale values.
  1077. */
  1078. forEach(fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any, thisp?: any): void;
  1079. /**
  1080. * The same as {@link LRUCache.forEach} but items are iterated over in
  1081. * reverse order. (ie, less recently used items are iterated over first.)
  1082. */
  1083. rforEach(fn: (v: V, k: K, self: LRUCache<K, V, FC>) => any, thisp?: any): void;
  1084. /**
  1085. * Delete any stale entries. Returns true if anything was removed,
  1086. * false otherwise.
  1087. */
  1088. purgeStale(): boolean;
  1089. /**
  1090. * Get the extended info about a given entry, to get its value, size, and
  1091. * TTL info simultaneously. Returns `undefined` if the key is not present.
  1092. *
  1093. * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
  1094. * serialization, the `start` value is always the current timestamp, and the
  1095. * `ttl` is a calculated remaining time to live (negative if expired).
  1096. *
  1097. * Always returns stale values, if their info is found in the cache, so be
  1098. * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
  1099. * if relevant.
  1100. */
  1101. info(key: K): LRUCache.Entry<V> | undefined;
  1102. /**
  1103. * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
  1104. * passed to {@link LRUCache#load}.
  1105. *
  1106. * The `start` fields are calculated relative to a portable `Date.now()`
  1107. * timestamp, even if `performance.now()` is available.
  1108. *
  1109. * Stale entries are always included in the `dump`, even if
  1110. * {@link LRUCache.OptionsBase.allowStale} is false.
  1111. *
  1112. * Note: this returns an actual array, not a generator, so it can be more
  1113. * easily passed around.
  1114. */
  1115. dump(): [K, LRUCache.Entry<V>][];
  1116. /**
  1117. * Reset the cache and load in the items in entries in the order listed.
  1118. *
  1119. * The shape of the resulting cache may be different if the same options are
  1120. * not used in both caches.
  1121. *
  1122. * The `start` fields are assumed to be calculated relative to a portable
  1123. * `Date.now()` timestamp, even if `performance.now()` is available.
  1124. */
  1125. load(arr: [K, LRUCache.Entry<V>][]): void;
  1126. /**
  1127. * Add a value to the cache.
  1128. *
  1129. * Note: if `undefined` is specified as a value, this is an alias for
  1130. * {@link LRUCache#delete}
  1131. *
  1132. * Fields on the {@link LRUCache.SetOptions} options param will override
  1133. * their corresponding values in the constructor options for the scope
  1134. * of this single `set()` operation.
  1135. *
  1136. * If `start` is provided, then that will set the effective start
  1137. * time for the TTL calculation. Note that this must be a previous
  1138. * value of `performance.now()` if supported, or a previous value of
  1139. * `Date.now()` if not.
  1140. *
  1141. * Options object may also include `size`, which will prevent
  1142. * calling the `sizeCalculation` function and just use the specified
  1143. * number if it is a positive integer, and `noDisposeOnSet` which
  1144. * will prevent calling a `dispose` function in the case of
  1145. * overwrites.
  1146. *
  1147. * If the `size` (or return value of `sizeCalculation`) for a given
  1148. * entry is greater than `maxEntrySize`, then the item will not be
  1149. * added to the cache.
  1150. *
  1151. * Will update the recency of the entry.
  1152. *
  1153. * If the value is `undefined`, then this is an alias for
  1154. * `cache.delete(key)`. `undefined` is never stored in the cache.
  1155. */
  1156. set(k: K, v: V | BackgroundFetch<V> | undefined, setOptions?: LRUCache.SetOptions<K, V, FC>): this;
  1157. /**
  1158. * Evict the least recently used item, returning its value or
  1159. * `undefined` if cache is empty.
  1160. */
  1161. pop(): V | undefined;
  1162. /**
  1163. * Check if a key is in the cache, without updating the recency of use.
  1164. * Will return false if the item is stale, even though it is technically
  1165. * in the cache.
  1166. *
  1167. * Check if a key is in the cache, without updating the recency of
  1168. * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
  1169. * to `true` in either the options or the constructor.
  1170. *
  1171. * Will return `false` if the item is stale, even though it is technically in
  1172. * the cache. The difference can be determined (if it matters) by using a
  1173. * `status` argument, and inspecting the `has` field.
  1174. *
  1175. * Will not update item age unless
  1176. * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
  1177. */
  1178. has(k: K, hasOptions?: LRUCache.HasOptions<K, V, FC>): boolean;
  1179. /**
  1180. * Like {@link LRUCache#get} but doesn't update recency or delete stale
  1181. * items.
  1182. *
  1183. * Returns `undefined` if the item is stale, unless
  1184. * {@link LRUCache.OptionsBase.allowStale} is set.
  1185. */
  1186. peek(k: K, peekOptions?: LRUCache.PeekOptions<K, V, FC>): V | undefined;
  1187. /**
  1188. * Make an asynchronous cached fetch using the
  1189. * {@link LRUCache.OptionsBase.fetchMethod} function.
  1190. *
  1191. * If the value is in the cache and not stale, then the returned
  1192. * Promise resolves to the value.
  1193. *
  1194. * If not in the cache, or beyond its TTL staleness, then
  1195. * `fetchMethod(key, staleValue, { options, signal, context })` is
  1196. * called, and the value returned will be added to the cache once
  1197. * resolved.
  1198. *
  1199. * If called with `allowStale`, and an asynchronous fetch is
  1200. * currently in progress to reload a stale value, then the former
  1201. * stale value will be returned.
  1202. *
  1203. * If called with `forceRefresh`, then the cached item will be
  1204. * re-fetched, even if it is not stale. However, if `allowStale` is also
  1205. * set, then the old value will still be returned. This is useful
  1206. * in cases where you want to force a reload of a cached value. If
  1207. * a background fetch is already in progress, then `forceRefresh`
  1208. * has no effect.
  1209. *
  1210. * If multiple fetches for the same key are issued, then they will all be
  1211. * coalesced into a single call to fetchMethod.
  1212. *
  1213. * Note that this means that handling options such as
  1214. * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},
  1215. * {@link LRUCache.FetchOptions.signal},
  1216. * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be
  1217. * determined by the FIRST fetch() call for a given key.
  1218. *
  1219. * This is a known (fixable) shortcoming which will be addresed on when
  1220. * someone complains about it, as the fix would involve added complexity and
  1221. * may not be worth the costs for this edge case.
  1222. *
  1223. * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is
  1224. * effectively an alias for `Promise.resolve(cache.get(key))`.
  1225. *
  1226. * When the fetch method resolves to a value, if the fetch has not
  1227. * been aborted due to deletion, eviction, or being overwritten,
  1228. * then it is added to the cache using the options provided.
  1229. *
  1230. * If the key is evicted or deleted before the `fetchMethod`
  1231. * resolves, then the AbortSignal passed to the `fetchMethod` will
  1232. * receive an `abort` event, and the promise returned by `fetch()`
  1233. * will reject with the reason for the abort.
  1234. *
  1235. * If a `signal` is passed to the `fetch()` call, then aborting the
  1236. * signal will abort the fetch and cause the `fetch()` promise to
  1237. * reject with the reason provided.
  1238. *
  1239. * **Setting `context`**
  1240. *
  1241. * If an `FC` type is set to a type other than `unknown`, `void`, or
  1242. * `undefined` in the {@link LRUCache} constructor, then all
  1243. * calls to `cache.fetch()` _must_ provide a `context` option. If
  1244. * set to `undefined` or `void`, then calls to fetch _must not_
  1245. * provide a `context` option.
  1246. *
  1247. * The `context` param allows you to provide arbitrary data that
  1248. * might be relevant in the course of fetching the data. It is only
  1249. * relevant for the course of a single `fetch()` operation, and
  1250. * discarded afterwards.
  1251. *
  1252. * **Note: `fetch()` calls are inflight-unique**
  1253. *
  1254. * If you call `fetch()` multiple times with the same key value,
  1255. * then every call after the first will resolve on the same
  1256. * promise<sup>1</sup>,
  1257. * _even if they have different settings that would otherwise change
  1258. * the behavior of the fetch_, such as `noDeleteOnFetchRejection`
  1259. * or `ignoreFetchAbort`.
  1260. *
  1261. * In most cases, this is not a problem (in fact, only fetching
  1262. * something once is what you probably want, if you're caching in
  1263. * the first place). If you are changing the fetch() options
  1264. * dramatically between runs, there's a good chance that you might
  1265. * be trying to fit divergent semantics into a single object, and
  1266. * would be better off with multiple cache instances.
  1267. *
  1268. * **1**: Ie, they're not the "same Promise", but they resolve at
  1269. * the same time, because they're both waiting on the same
  1270. * underlying fetchMethod response.
  1271. */
  1272. fetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions<K, V, FC> : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V> : LRUCache.FetchOptionsWithContext<K, V, FC>): Promise<undefined | V>;
  1273. fetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions<K, V, FC> : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V> : never): Promise<undefined | V>;
  1274. /**
  1275. * In some cases, `cache.fetch()` may resolve to `undefined`, either because
  1276. * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning
  1277. * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or
  1278. * because `ignoreFetchAbort` was specified (either to the constructor or
  1279. * in the {@link LRUCache.FetchOptions}). Also, the
  1280. * {@link LRUCache.OptionsBase.fetchMethod} may return `undefined` or `void`, making
  1281. * the test even more complicated.
  1282. *
  1283. * Because inferring the cases where `undefined` might be returned are so
  1284. * cumbersome, but testing for `undefined` can also be annoying, this method
  1285. * can be used, which will reject if `this.fetch()` resolves to undefined.
  1286. */
  1287. forceFetch(k: K, fetchOptions: unknown extends FC ? LRUCache.FetchOptions<K, V, FC> : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V> : LRUCache.FetchOptionsWithContext<K, V, FC>): Promise<V>;
  1288. forceFetch(k: unknown extends FC ? K : FC extends undefined | void ? K : never, fetchOptions?: unknown extends FC ? LRUCache.FetchOptions<K, V, FC> : FC extends undefined | void ? LRUCache.FetchOptionsNoContext<K, V> : never): Promise<V>;
  1289. /**
  1290. * If the key is found in the cache, then this is equivalent to
  1291. * {@link LRUCache#get}. If not, in the cache, then calculate the value using
  1292. * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.
  1293. *
  1294. * If an `FC` type is set to a type other than `unknown`, `void`, or
  1295. * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`
  1296. * _must_ provide a `context` option. If set to `undefined` or `void`, then
  1297. * calls to memo _must not_ provide a `context` option.
  1298. *
  1299. * The `context` param allows you to provide arbitrary data that might be
  1300. * relevant in the course of fetching the data. It is only relevant for the
  1301. * course of a single `memo()` operation, and discarded afterwards.
  1302. */
  1303. memo(k: K, memoOptions: unknown extends FC ? LRUCache.MemoOptions<K, V, FC> : FC extends undefined | void ? LRUCache.MemoOptionsNoContext<K, V> : LRUCache.MemoOptionsWithContext<K, V, FC>): V;
  1304. memo(k: unknown extends FC ? K : FC extends undefined | void ? K : never, memoOptions?: unknown extends FC ? LRUCache.MemoOptions<K, V, FC> : FC extends undefined | void ? LRUCache.MemoOptionsNoContext<K, V> : never): V;
  1305. /**
  1306. * Return a value from the cache. Will update the recency of the cache
  1307. * entry found.
  1308. *
  1309. * If the key is not found, get() will return `undefined`.
  1310. */
  1311. get(k: K, getOptions?: LRUCache.GetOptions<K, V, FC>): V | undefined;
  1312. /**
  1313. * Deletes a key out of the cache.
  1314. *
  1315. * Returns true if the key was deleted, false otherwise.
  1316. */
  1317. delete(k: K): boolean;
  1318. /**
  1319. * Clear the cache entirely, throwing away all values.
  1320. */
  1321. clear(): void;
  1322. }
  1323. //# sourceMappingURL=index.d.ts.map