@netlify/plugin-nextjs 5.10.7 → 5.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/build/advanced-api-routes.js +1 -1
  2. package/dist/build/cache.js +1 -1
  3. package/dist/build/content/prerendered.js +47 -21
  4. package/dist/build/content/server.js +22 -15
  5. package/dist/build/content/static.js +4 -8
  6. package/dist/build/functions/edge.js +2 -2
  7. package/dist/build/functions/server.js +4 -8
  8. package/dist/build/image-cdn.js +1 -1
  9. package/dist/build/plugin-context.js +2 -2
  10. package/dist/build/templates/handler-monorepo.tmpl.js +0 -5
  11. package/dist/build/templates/handler.tmpl.js +0 -4
  12. package/dist/build/verification.js +3 -3
  13. package/dist/esm-chunks/{chunk-OEQOKJGE.js → chunk-6BT4RYQJ.js} +1 -12
  14. package/dist/esm-chunks/{chunk-APO262HE.js → chunk-F7NTXMLE.js} +26 -10
  15. package/dist/esm-chunks/chunk-FKDTZJRV.js +832 -0
  16. package/dist/esm-chunks/{chunk-NFOLXH6F.js → chunk-YUXQHOYO.js} +1 -1
  17. package/dist/index.js +3 -7
  18. package/dist/run/config.js +3 -3
  19. package/dist/run/constants.js +3 -3
  20. package/dist/run/handlers/cache.cjs +24 -234
  21. package/dist/run/handlers/request-context.cjs +63 -88
  22. package/dist/run/handlers/server.js +9 -6
  23. package/dist/run/handlers/tags-handler.cjs +192 -0
  24. package/dist/run/handlers/tracer.cjs +4 -4
  25. package/dist/run/handlers/use-cache-handler.js +1553 -0
  26. package/dist/run/headers.js +1 -1
  27. package/dist/run/revalidate.js +1 -1
  28. package/dist/shared/blobkey.js +1 -1
  29. package/edge-runtime/lib/routing.ts +12 -2
  30. package/package.json +1 -1
  31. package/dist/esm-chunks/chunk-5QSXBV7L.js +0 -89
  32. package/dist/esm-chunks/chunk-GNGHTHMQ.js +0 -1624
  33. package/dist/esm-chunks/package-SGSU42JZ.js +0 -148
  34. package/dist/run/handlers/tracing.js +0 -68968
@@ -0,0 +1,1553 @@
1
+
2
+ var require = await (async () => {
3
+ var { createRequire } = await import("node:module");
4
+ return createRequire(import.meta.url);
5
+ })();
6
+
7
+ import "../../esm-chunks/chunk-6BT4RYQJ.js";
8
+
9
+ // src/run/handlers/use-cache-handler.ts
10
+ import { Buffer } from "node:buffer";
11
+
12
+ // node_modules/lru-cache/dist/esm/index.js
13
+ var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
14
+ var warned = /* @__PURE__ */ new Set();
15
+ var PROCESS = typeof process === "object" && !!process ? process : {};
16
+ var emitWarning = (msg, type, code, fn) => {
17
+ typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
18
+ };
19
+ var AC = globalThis.AbortController;
20
+ var AS = globalThis.AbortSignal;
21
+ if (typeof AC === "undefined") {
22
+ AS = class AbortSignal {
23
+ onabort;
24
+ _onabort = [];
25
+ reason;
26
+ aborted = false;
27
+ addEventListener(_, fn) {
28
+ this._onabort.push(fn);
29
+ }
30
+ };
31
+ AC = class AbortController {
32
+ constructor() {
33
+ warnACPolyfill();
34
+ }
35
+ signal = new AS();
36
+ abort(reason) {
37
+ if (this.signal.aborted)
38
+ return;
39
+ this.signal.reason = reason;
40
+ this.signal.aborted = true;
41
+ for (const fn of this.signal._onabort) {
42
+ fn(reason);
43
+ }
44
+ this.signal.onabort?.(reason);
45
+ }
46
+ };
47
+ let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
48
+ const warnACPolyfill = () => {
49
+ if (!printACPolyfillWarning)
50
+ return;
51
+ printACPolyfillWarning = false;
52
+ emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
53
+ };
54
+ }
55
+ var shouldWarn = (code) => !warned.has(code);
56
+ var TYPE = Symbol("type");
57
+ var isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
58
+ var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
59
+ var ZeroArray = class extends Array {
60
+ constructor(size) {
61
+ super(size);
62
+ this.fill(0);
63
+ }
64
+ };
65
+ var Stack = class _Stack {
66
+ heap;
67
+ length;
68
+ // private constructor
69
+ static #constructing = false;
70
+ static create(max) {
71
+ const HeapCls = getUintArray(max);
72
+ if (!HeapCls)
73
+ return [];
74
+ _Stack.#constructing = true;
75
+ const s = new _Stack(max, HeapCls);
76
+ _Stack.#constructing = false;
77
+ return s;
78
+ }
79
+ constructor(max, HeapCls) {
80
+ if (!_Stack.#constructing) {
81
+ throw new TypeError("instantiate Stack using Stack.create(n)");
82
+ }
83
+ this.heap = new HeapCls(max);
84
+ this.length = 0;
85
+ }
86
+ push(n) {
87
+ this.heap[this.length++] = n;
88
+ }
89
+ pop() {
90
+ return this.heap[--this.length];
91
+ }
92
+ };
93
+ var LRUCache = class _LRUCache {
94
+ // options that cannot be changed without disaster
95
+ #max;
96
+ #maxSize;
97
+ #dispose;
98
+ #disposeAfter;
99
+ #fetchMethod;
100
+ #memoMethod;
101
+ /**
102
+ * {@link LRUCache.OptionsBase.ttl}
103
+ */
104
+ ttl;
105
+ /**
106
+ * {@link LRUCache.OptionsBase.ttlResolution}
107
+ */
108
+ ttlResolution;
109
+ /**
110
+ * {@link LRUCache.OptionsBase.ttlAutopurge}
111
+ */
112
+ ttlAutopurge;
113
+ /**
114
+ * {@link LRUCache.OptionsBase.updateAgeOnGet}
115
+ */
116
+ updateAgeOnGet;
117
+ /**
118
+ * {@link LRUCache.OptionsBase.updateAgeOnHas}
119
+ */
120
+ updateAgeOnHas;
121
+ /**
122
+ * {@link LRUCache.OptionsBase.allowStale}
123
+ */
124
+ allowStale;
125
+ /**
126
+ * {@link LRUCache.OptionsBase.noDisposeOnSet}
127
+ */
128
+ noDisposeOnSet;
129
+ /**
130
+ * {@link LRUCache.OptionsBase.noUpdateTTL}
131
+ */
132
+ noUpdateTTL;
133
+ /**
134
+ * {@link LRUCache.OptionsBase.maxEntrySize}
135
+ */
136
+ maxEntrySize;
137
+ /**
138
+ * {@link LRUCache.OptionsBase.sizeCalculation}
139
+ */
140
+ sizeCalculation;
141
+ /**
142
+ * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
143
+ */
144
+ noDeleteOnFetchRejection;
145
+ /**
146
+ * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
147
+ */
148
+ noDeleteOnStaleGet;
149
+ /**
150
+ * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
151
+ */
152
+ allowStaleOnFetchAbort;
153
+ /**
154
+ * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
155
+ */
156
+ allowStaleOnFetchRejection;
157
+ /**
158
+ * {@link LRUCache.OptionsBase.ignoreFetchAbort}
159
+ */
160
+ ignoreFetchAbort;
161
+ // computed properties
162
+ #size;
163
+ #calculatedSize;
164
+ #keyMap;
165
+ #keyList;
166
+ #valList;
167
+ #next;
168
+ #prev;
169
+ #head;
170
+ #tail;
171
+ #free;
172
+ #disposed;
173
+ #sizes;
174
+ #starts;
175
+ #ttls;
176
+ #hasDispose;
177
+ #hasFetchMethod;
178
+ #hasDisposeAfter;
179
+ /**
180
+ * Do not call this method unless you need to inspect the
181
+ * inner workings of the cache. If anything returned by this
182
+ * object is modified in any way, strange breakage may occur.
183
+ *
184
+ * These fields are private for a reason!
185
+ *
186
+ * @internal
187
+ */
188
+ static unsafeExposeInternals(c) {
189
+ return {
190
+ // properties
191
+ starts: c.#starts,
192
+ ttls: c.#ttls,
193
+ sizes: c.#sizes,
194
+ keyMap: c.#keyMap,
195
+ keyList: c.#keyList,
196
+ valList: c.#valList,
197
+ next: c.#next,
198
+ prev: c.#prev,
199
+ get head() {
200
+ return c.#head;
201
+ },
202
+ get tail() {
203
+ return c.#tail;
204
+ },
205
+ free: c.#free,
206
+ // methods
207
+ isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
208
+ backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
209
+ moveToTail: (index) => c.#moveToTail(index),
210
+ indexes: (options) => c.#indexes(options),
211
+ rindexes: (options) => c.#rindexes(options),
212
+ isStale: (index) => c.#isStale(index)
213
+ };
214
+ }
215
+ // Protected read-only members
216
+ /**
217
+ * {@link LRUCache.OptionsBase.max} (read-only)
218
+ */
219
+ get max() {
220
+ return this.#max;
221
+ }
222
+ /**
223
+ * {@link LRUCache.OptionsBase.maxSize} (read-only)
224
+ */
225
+ get maxSize() {
226
+ return this.#maxSize;
227
+ }
228
+ /**
229
+ * The total computed size of items in the cache (read-only)
230
+ */
231
+ get calculatedSize() {
232
+ return this.#calculatedSize;
233
+ }
234
+ /**
235
+ * The number of items stored in the cache (read-only)
236
+ */
237
+ get size() {
238
+ return this.#size;
239
+ }
240
+ /**
241
+ * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
242
+ */
243
+ get fetchMethod() {
244
+ return this.#fetchMethod;
245
+ }
246
+ get memoMethod() {
247
+ return this.#memoMethod;
248
+ }
249
+ /**
250
+ * {@link LRUCache.OptionsBase.dispose} (read-only)
251
+ */
252
+ get dispose() {
253
+ return this.#dispose;
254
+ }
255
+ /**
256
+ * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
257
+ */
258
+ get disposeAfter() {
259
+ return this.#disposeAfter;
260
+ }
261
+ constructor(options) {
262
+ const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
263
+ if (max !== 0 && !isPosInt(max)) {
264
+ throw new TypeError("max option must be a nonnegative integer");
265
+ }
266
+ const UintArray = max ? getUintArray(max) : Array;
267
+ if (!UintArray) {
268
+ throw new Error("invalid max value: " + max);
269
+ }
270
+ this.#max = max;
271
+ this.#maxSize = maxSize;
272
+ this.maxEntrySize = maxEntrySize || this.#maxSize;
273
+ this.sizeCalculation = sizeCalculation;
274
+ if (this.sizeCalculation) {
275
+ if (!this.#maxSize && !this.maxEntrySize) {
276
+ throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
277
+ }
278
+ if (typeof this.sizeCalculation !== "function") {
279
+ throw new TypeError("sizeCalculation set to non-function");
280
+ }
281
+ }
282
+ if (memoMethod !== void 0 && typeof memoMethod !== "function") {
283
+ throw new TypeError("memoMethod must be a function if defined");
284
+ }
285
+ this.#memoMethod = memoMethod;
286
+ if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
287
+ throw new TypeError("fetchMethod must be a function if specified");
288
+ }
289
+ this.#fetchMethod = fetchMethod;
290
+ this.#hasFetchMethod = !!fetchMethod;
291
+ this.#keyMap = /* @__PURE__ */ new Map();
292
+ this.#keyList = new Array(max).fill(void 0);
293
+ this.#valList = new Array(max).fill(void 0);
294
+ this.#next = new UintArray(max);
295
+ this.#prev = new UintArray(max);
296
+ this.#head = 0;
297
+ this.#tail = 0;
298
+ this.#free = Stack.create(max);
299
+ this.#size = 0;
300
+ this.#calculatedSize = 0;
301
+ if (typeof dispose === "function") {
302
+ this.#dispose = dispose;
303
+ }
304
+ if (typeof disposeAfter === "function") {
305
+ this.#disposeAfter = disposeAfter;
306
+ this.#disposed = [];
307
+ } else {
308
+ this.#disposeAfter = void 0;
309
+ this.#disposed = void 0;
310
+ }
311
+ this.#hasDispose = !!this.#dispose;
312
+ this.#hasDisposeAfter = !!this.#disposeAfter;
313
+ this.noDisposeOnSet = !!noDisposeOnSet;
314
+ this.noUpdateTTL = !!noUpdateTTL;
315
+ this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
316
+ this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
317
+ this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
318
+ this.ignoreFetchAbort = !!ignoreFetchAbort;
319
+ if (this.maxEntrySize !== 0) {
320
+ if (this.#maxSize !== 0) {
321
+ if (!isPosInt(this.#maxSize)) {
322
+ throw new TypeError("maxSize must be a positive integer if specified");
323
+ }
324
+ }
325
+ if (!isPosInt(this.maxEntrySize)) {
326
+ throw new TypeError("maxEntrySize must be a positive integer if specified");
327
+ }
328
+ this.#initializeSizeTracking();
329
+ }
330
+ this.allowStale = !!allowStale;
331
+ this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
332
+ this.updateAgeOnGet = !!updateAgeOnGet;
333
+ this.updateAgeOnHas = !!updateAgeOnHas;
334
+ this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
335
+ this.ttlAutopurge = !!ttlAutopurge;
336
+ this.ttl = ttl || 0;
337
+ if (this.ttl) {
338
+ if (!isPosInt(this.ttl)) {
339
+ throw new TypeError("ttl must be a positive integer if specified");
340
+ }
341
+ this.#initializeTTLTracking();
342
+ }
343
+ if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
344
+ throw new TypeError("At least one of max, maxSize, or ttl is required");
345
+ }
346
+ if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
347
+ const code = "LRU_CACHE_UNBOUNDED";
348
+ if (shouldWarn(code)) {
349
+ warned.add(code);
350
+ const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
351
+ emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
352
+ }
353
+ }
354
+ }
355
+ /**
356
+ * Return the number of ms left in the item's TTL. If item is not in cache,
357
+ * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
358
+ */
359
+ getRemainingTTL(key) {
360
+ return this.#keyMap.has(key) ? Infinity : 0;
361
+ }
362
+ #initializeTTLTracking() {
363
+ const ttls = new ZeroArray(this.#max);
364
+ const starts = new ZeroArray(this.#max);
365
+ this.#ttls = ttls;
366
+ this.#starts = starts;
367
+ this.#setItemTTL = (index, ttl, start = perf.now()) => {
368
+ starts[index] = ttl !== 0 ? start : 0;
369
+ ttls[index] = ttl;
370
+ if (ttl !== 0 && this.ttlAutopurge) {
371
+ const t = setTimeout(() => {
372
+ if (this.#isStale(index)) {
373
+ this.#delete(this.#keyList[index], "expire");
374
+ }
375
+ }, ttl + 1);
376
+ if (t.unref) {
377
+ t.unref();
378
+ }
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
+ if (!ttl || !start)
389
+ return;
390
+ status.ttl = ttl;
391
+ status.start = start;
392
+ status.now = cachedNow || getNow();
393
+ const age = status.now - start;
394
+ status.remainingTTL = ttl - age;
395
+ }
396
+ };
397
+ let cachedNow = 0;
398
+ const getNow = () => {
399
+ const n = perf.now();
400
+ if (this.ttlResolution > 0) {
401
+ cachedNow = n;
402
+ const t = setTimeout(() => cachedNow = 0, this.ttlResolution);
403
+ if (t.unref) {
404
+ t.unref();
405
+ }
406
+ }
407
+ return n;
408
+ };
409
+ this.getRemainingTTL = (key) => {
410
+ const index = this.#keyMap.get(key);
411
+ if (index === void 0) {
412
+ return 0;
413
+ }
414
+ const ttl = ttls[index];
415
+ const start = starts[index];
416
+ if (!ttl || !start) {
417
+ return Infinity;
418
+ }
419
+ const age = (cachedNow || getNow()) - start;
420
+ return ttl - age;
421
+ };
422
+ this.#isStale = (index) => {
423
+ const s = starts[index];
424
+ const t = ttls[index];
425
+ return !!t && !!s && (cachedNow || getNow()) - s > t;
426
+ };
427
+ }
428
+ // conditionally set private methods related to TTL
429
+ #updateItemAge = () => {
430
+ };
431
+ #statusTTL = () => {
432
+ };
433
+ #setItemTTL = () => {
434
+ };
435
+ /* c8 ignore stop */
436
+ #isStale = () => false;
437
+ #initializeSizeTracking() {
438
+ const sizes = new ZeroArray(this.#max);
439
+ this.#calculatedSize = 0;
440
+ this.#sizes = sizes;
441
+ this.#removeItemSize = (index) => {
442
+ this.#calculatedSize -= sizes[index];
443
+ sizes[index] = 0;
444
+ };
445
+ this.#requireSize = (k, v, size, sizeCalculation) => {
446
+ if (this.#isBackgroundFetch(v)) {
447
+ return 0;
448
+ }
449
+ if (!isPosInt(size)) {
450
+ if (sizeCalculation) {
451
+ if (typeof sizeCalculation !== "function") {
452
+ throw new TypeError("sizeCalculation must be a function");
453
+ }
454
+ size = sizeCalculation(v, k);
455
+ if (!isPosInt(size)) {
456
+ throw new TypeError("sizeCalculation return invalid (expect positive integer)");
457
+ }
458
+ } else {
459
+ throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation 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
+ };
481
+ #addItemSize = (_i, _s, _st) => {
482
+ };
483
+ #requireSize = (_k, _v, size, sizeCalculation) => {
484
+ if (size || sizeCalculation) {
485
+ throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
486
+ }
487
+ return 0;
488
+ };
489
+ *#indexes({ allowStale = this.allowStale } = {}) {
490
+ if (this.#size) {
491
+ for (let i = this.#tail; true; ) {
492
+ if (!this.#isValidIndex(i)) {
493
+ break;
494
+ }
495
+ if (allowStale || !this.#isStale(i)) {
496
+ yield i;
497
+ }
498
+ if (i === this.#head) {
499
+ break;
500
+ } else {
501
+ i = this.#prev[i];
502
+ }
503
+ }
504
+ }
505
+ }
506
+ *#rindexes({ allowStale = this.allowStale } = {}) {
507
+ if (this.#size) {
508
+ for (let i = this.#head; true; ) {
509
+ if (!this.#isValidIndex(i)) {
510
+ break;
511
+ }
512
+ if (allowStale || !this.#isStale(i)) {
513
+ yield i;
514
+ }
515
+ if (i === this.#tail) {
516
+ break;
517
+ } else {
518
+ i = this.#next[i];
519
+ }
520
+ }
521
+ }
522
+ }
523
+ #isValidIndex(index) {
524
+ return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
525
+ }
526
+ /**
527
+ * Return a generator yielding `[key, value]` pairs,
528
+ * in order from most recently used to least recently used.
529
+ */
530
+ *entries() {
531
+ for (const i of this.#indexes()) {
532
+ if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
533
+ yield [this.#keyList[i], this.#valList[i]];
534
+ }
535
+ }
536
+ }
537
+ /**
538
+ * Inverse order version of {@link LRUCache.entries}
539
+ *
540
+ * Return a generator yielding `[key, value]` pairs,
541
+ * in order from least recently used to most recently used.
542
+ */
543
+ *rentries() {
544
+ for (const i of this.#rindexes()) {
545
+ if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
546
+ yield [this.#keyList[i], this.#valList[i]];
547
+ }
548
+ }
549
+ }
550
+ /**
551
+ * Return a generator yielding the keys in the cache,
552
+ * in order from most recently used to least recently used.
553
+ */
554
+ *keys() {
555
+ for (const i of this.#indexes()) {
556
+ const k = this.#keyList[i];
557
+ if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
558
+ yield k;
559
+ }
560
+ }
561
+ }
562
+ /**
563
+ * Inverse order version of {@link LRUCache.keys}
564
+ *
565
+ * Return a generator yielding the keys in the cache,
566
+ * in order from least recently used to most recently used.
567
+ */
568
+ *rkeys() {
569
+ for (const i of this.#rindexes()) {
570
+ const k = this.#keyList[i];
571
+ if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
572
+ yield k;
573
+ }
574
+ }
575
+ }
576
+ /**
577
+ * Return a generator yielding the values in the cache,
578
+ * in order from most recently used to least recently used.
579
+ */
580
+ *values() {
581
+ for (const i of this.#indexes()) {
582
+ const v = this.#valList[i];
583
+ if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
584
+ yield this.#valList[i];
585
+ }
586
+ }
587
+ }
588
+ /**
589
+ * Inverse order version of {@link LRUCache.values}
590
+ *
591
+ * Return a generator yielding the values in the cache,
592
+ * in order from least recently used to most recently used.
593
+ */
594
+ *rvalues() {
595
+ for (const i of this.#rindexes()) {
596
+ const v = this.#valList[i];
597
+ if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
598
+ yield this.#valList[i];
599
+ }
600
+ }
601
+ }
602
+ /**
603
+ * Iterating over the cache itself yields the same results as
604
+ * {@link LRUCache.entries}
605
+ */
606
+ [Symbol.iterator]() {
607
+ return this.entries();
608
+ }
609
+ /**
610
+ * A String value that is used in the creation of the default string
611
+ * description of an object. Called by the built-in method
612
+ * `Object.prototype.toString`.
613
+ */
614
+ [Symbol.toStringTag] = "LRUCache";
615
+ /**
616
+ * Find a value for which the supplied fn method returns a truthy value,
617
+ * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
618
+ */
619
+ find(fn, getOptions = {}) {
620
+ for (const i of this.#indexes()) {
621
+ const v = this.#valList[i];
622
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
623
+ if (value === void 0)
624
+ continue;
625
+ if (fn(value, this.#keyList[i], this)) {
626
+ return this.get(this.#keyList[i], getOptions);
627
+ }
628
+ }
629
+ }
630
+ /**
631
+ * Call the supplied function on each item in the cache, in order from most
632
+ * recently used to least recently used.
633
+ *
634
+ * `fn` is called as `fn(value, key, cache)`.
635
+ *
636
+ * If `thisp` is provided, function will be called in the `this`-context of
637
+ * the provided object, or the cache if no `thisp` object is provided.
638
+ *
639
+ * Does not update age or recenty of use, or 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) ? v.__staleWhileFetching : v;
645
+ if (value === void 0)
646
+ continue;
647
+ fn.call(thisp, value, this.#keyList[i], this);
648
+ }
649
+ }
650
+ /**
651
+ * The same as {@link LRUCache.forEach} but items are iterated over in
652
+ * reverse order. (ie, less recently used items are iterated over first.)
653
+ */
654
+ rforEach(fn, thisp = this) {
655
+ for (const i of this.#rindexes()) {
656
+ const v = this.#valList[i];
657
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
658
+ if (value === void 0)
659
+ continue;
660
+ fn.call(thisp, value, this.#keyList[i], this);
661
+ }
662
+ }
663
+ /**
664
+ * Delete any stale entries. Returns true if anything was removed,
665
+ * false otherwise.
666
+ */
667
+ purgeStale() {
668
+ let deleted = false;
669
+ for (const i of this.#rindexes({ allowStale: true })) {
670
+ if (this.#isStale(i)) {
671
+ this.#delete(this.#keyList[i], "expire");
672
+ deleted = true;
673
+ }
674
+ }
675
+ return deleted;
676
+ }
677
+ /**
678
+ * Get the extended info about a given entry, to get its value, size, and
679
+ * TTL info simultaneously. Returns `undefined` if the key is not present.
680
+ *
681
+ * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
682
+ * serialization, the `start` value is always the current timestamp, and the
683
+ * `ttl` is a calculated remaining time to live (negative if expired).
684
+ *
685
+ * Always returns stale values, if their info is found in the cache, so be
686
+ * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
687
+ * if relevant.
688
+ */
689
+ info(key) {
690
+ const i = this.#keyMap.get(key);
691
+ if (i === void 0)
692
+ return void 0;
693
+ const v = this.#valList[i];
694
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
695
+ if (value === void 0)
696
+ return void 0;
697
+ const entry = { value };
698
+ if (this.#ttls && this.#starts) {
699
+ const ttl = this.#ttls[i];
700
+ const start = this.#starts[i];
701
+ if (ttl && start) {
702
+ const remain = ttl - (perf.now() - start);
703
+ entry.ttl = remain;
704
+ entry.start = Date.now();
705
+ }
706
+ }
707
+ if (this.#sizes) {
708
+ entry.size = this.#sizes[i];
709
+ }
710
+ return entry;
711
+ }
712
+ /**
713
+ * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
714
+ * passed to {@link LRLUCache#load}.
715
+ *
716
+ * The `start` fields are calculated relative to a portable `Date.now()`
717
+ * timestamp, even if `performance.now()` is available.
718
+ *
719
+ * Stale entries are always included in the `dump`, even if
720
+ * {@link LRUCache.OptionsBase.allowStale} is false.
721
+ *
722
+ * Note: this returns an actual array, not a generator, so it can be more
723
+ * easily passed around.
724
+ */
725
+ dump() {
726
+ const arr = [];
727
+ for (const i of this.#indexes({ allowStale: true })) {
728
+ const key = this.#keyList[i];
729
+ const v = this.#valList[i];
730
+ const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
731
+ if (value === void 0 || key === void 0)
732
+ continue;
733
+ const entry = { value };
734
+ if (this.#ttls && this.#starts) {
735
+ entry.ttl = this.#ttls[i];
736
+ const age = perf.now() - this.#starts[i];
737
+ entry.start = Math.floor(Date.now() - age);
738
+ }
739
+ if (this.#sizes) {
740
+ entry.size = this.#sizes[i];
741
+ }
742
+ arr.unshift([key, entry]);
743
+ }
744
+ return arr;
745
+ }
746
+ /**
747
+ * Reset the cache and load in the items in entries in the order listed.
748
+ *
749
+ * The shape of the resulting cache may be different if the same options are
750
+ * not used in both caches.
751
+ *
752
+ * The `start` fields are assumed to be calculated relative to a portable
753
+ * `Date.now()` timestamp, even if `performance.now()` is available.
754
+ */
755
+ load(arr) {
756
+ this.clear();
757
+ for (const [key, entry] of arr) {
758
+ if (entry.start) {
759
+ const age = Date.now() - entry.start;
760
+ entry.start = perf.now() - age;
761
+ }
762
+ this.set(key, entry.value, entry);
763
+ }
764
+ }
765
+ /**
766
+ * Add a value to the cache.
767
+ *
768
+ * Note: if `undefined` is specified as a value, this is an alias for
769
+ * {@link LRUCache#delete}
770
+ *
771
+ * Fields on the {@link LRUCache.SetOptions} options param will override
772
+ * their corresponding values in the constructor options for the scope
773
+ * of this single `set()` operation.
774
+ *
775
+ * If `start` is provided, then that will set the effective start
776
+ * time for the TTL calculation. Note that this must be a previous
777
+ * value of `performance.now()` if supported, or a previous value of
778
+ * `Date.now()` if not.
779
+ *
780
+ * Options object may also include `size`, which will prevent
781
+ * calling the `sizeCalculation` function and just use the specified
782
+ * number if it is a positive integer, and `noDisposeOnSet` which
783
+ * will prevent calling a `dispose` function in the case of
784
+ * overwrites.
785
+ *
786
+ * If the `size` (or return value of `sizeCalculation`) for a given
787
+ * entry is greater than `maxEntrySize`, then the item will not be
788
+ * added to the cache.
789
+ *
790
+ * Will update the recency of the entry.
791
+ *
792
+ * If the value is `undefined`, then this is an alias for
793
+ * `cache.delete(key)`. `undefined` is never stored in the cache.
794
+ */
795
+ set(k, v, setOptions = {}) {
796
+ if (v === void 0) {
797
+ this.delete(k);
798
+ return this;
799
+ }
800
+ const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
801
+ let { noUpdateTTL = this.noUpdateTTL } = setOptions;
802
+ const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
803
+ if (this.maxEntrySize && size > this.maxEntrySize) {
804
+ if (status) {
805
+ status.set = "miss";
806
+ status.maxEntrySizeExceeded = true;
807
+ }
808
+ this.#delete(k, "set");
809
+ return this;
810
+ }
811
+ let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
812
+ if (index === void 0) {
813
+ index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
814
+ this.#keyList[index] = k;
815
+ this.#valList[index] = v;
816
+ this.#keyMap.set(k, index);
817
+ this.#next[this.#tail] = index;
818
+ this.#prev[index] = this.#tail;
819
+ this.#tail = index;
820
+ this.#size++;
821
+ this.#addItemSize(index, size, status);
822
+ if (status)
823
+ status.set = "add";
824
+ noUpdateTTL = false;
825
+ } else {
826
+ this.#moveToTail(index);
827
+ const oldVal = this.#valList[index];
828
+ if (v !== oldVal) {
829
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
830
+ oldVal.__abortController.abort(new Error("replaced"));
831
+ const { __staleWhileFetching: s } = oldVal;
832
+ if (s !== void 0 && !noDisposeOnSet) {
833
+ if (this.#hasDispose) {
834
+ this.#dispose?.(s, k, "set");
835
+ }
836
+ if (this.#hasDisposeAfter) {
837
+ this.#disposed?.push([s, k, "set"]);
838
+ }
839
+ }
840
+ } else if (!noDisposeOnSet) {
841
+ if (this.#hasDispose) {
842
+ this.#dispose?.(oldVal, k, "set");
843
+ }
844
+ if (this.#hasDisposeAfter) {
845
+ this.#disposed?.push([oldVal, k, "set"]);
846
+ }
847
+ }
848
+ this.#removeItemSize(index);
849
+ this.#addItemSize(index, size, status);
850
+ this.#valList[index] = v;
851
+ if (status) {
852
+ status.set = "replace";
853
+ const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
854
+ if (oldValue !== void 0)
855
+ status.oldValue = oldValue;
856
+ }
857
+ } else if (status) {
858
+ status.set = "update";
859
+ }
860
+ }
861
+ if (ttl !== 0 && !this.#ttls) {
862
+ this.#initializeTTLTracking();
863
+ }
864
+ if (this.#ttls) {
865
+ if (!noUpdateTTL) {
866
+ this.#setItemTTL(index, ttl, start);
867
+ }
868
+ if (status)
869
+ this.#statusTTL(status, index);
870
+ }
871
+ if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
872
+ const dt = this.#disposed;
873
+ let task;
874
+ while (task = dt?.shift()) {
875
+ this.#disposeAfter?.(...task);
876
+ }
877
+ }
878
+ return this;
879
+ }
880
+ /**
881
+ * Evict the least recently used item, returning its value or
882
+ * `undefined` if cache is empty.
883
+ */
884
+ pop() {
885
+ try {
886
+ while (this.#size) {
887
+ const val = this.#valList[this.#head];
888
+ this.#evict(true);
889
+ if (this.#isBackgroundFetch(val)) {
890
+ if (val.__staleWhileFetching) {
891
+ return val.__staleWhileFetching;
892
+ }
893
+ } else if (val !== void 0) {
894
+ return val;
895
+ }
896
+ }
897
+ } finally {
898
+ if (this.#hasDisposeAfter && this.#disposed) {
899
+ const dt = this.#disposed;
900
+ let task;
901
+ while (task = dt?.shift()) {
902
+ this.#disposeAfter?.(...task);
903
+ }
904
+ }
905
+ }
906
+ }
907
+ #evict(free) {
908
+ const head = this.#head;
909
+ const k = this.#keyList[head];
910
+ const v = this.#valList[head];
911
+ if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
912
+ v.__abortController.abort(new Error("evicted"));
913
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
914
+ if (this.#hasDispose) {
915
+ this.#dispose?.(v, k, "evict");
916
+ }
917
+ if (this.#hasDisposeAfter) {
918
+ this.#disposed?.push([v, k, "evict"]);
919
+ }
920
+ }
921
+ this.#removeItemSize(head);
922
+ if (free) {
923
+ this.#keyList[head] = void 0;
924
+ this.#valList[head] = void 0;
925
+ this.#free.push(head);
926
+ }
927
+ if (this.#size === 1) {
928
+ this.#head = this.#tail = 0;
929
+ this.#free.length = 0;
930
+ } else {
931
+ this.#head = this.#next[head];
932
+ }
933
+ this.#keyMap.delete(k);
934
+ this.#size--;
935
+ return head;
936
+ }
937
+ /**
938
+ * Check if a key is in the cache, without updating the recency of use.
939
+ * Will return false if the item is stale, even though it is technically
940
+ * in the cache.
941
+ *
942
+ * Check if a key is in the cache, without updating the recency of
943
+ * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
944
+ * to `true` in either the options or the constructor.
945
+ *
946
+ * Will return `false` if the item is stale, even though it is technically in
947
+ * the cache. The difference can be determined (if it matters) by using a
948
+ * `status` argument, and inspecting the `has` field.
949
+ *
950
+ * Will not update item age unless
951
+ * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
952
+ */
953
+ has(k, hasOptions = {}) {
954
+ const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
955
+ const index = this.#keyMap.get(k);
956
+ if (index !== void 0) {
957
+ const v = this.#valList[index];
958
+ if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
959
+ return false;
960
+ }
961
+ if (!this.#isStale(index)) {
962
+ if (updateAgeOnHas) {
963
+ this.#updateItemAge(index);
964
+ }
965
+ if (status) {
966
+ status.has = "hit";
967
+ this.#statusTTL(status, index);
968
+ }
969
+ return true;
970
+ } else if (status) {
971
+ status.has = "stale";
972
+ this.#statusTTL(status, index);
973
+ }
974
+ } else if (status) {
975
+ status.has = "miss";
976
+ }
977
+ return false;
978
+ }
979
+ /**
980
+ * Like {@link LRUCache#get} but doesn't update recency or delete stale
981
+ * items.
982
+ *
983
+ * Returns `undefined` if the item is stale, unless
984
+ * {@link LRUCache.OptionsBase.allowStale} is set.
985
+ */
986
+ peek(k, peekOptions = {}) {
987
+ const { allowStale = this.allowStale } = peekOptions;
988
+ const index = this.#keyMap.get(k);
989
+ if (index === void 0 || !allowStale && this.#isStale(index)) {
990
+ return;
991
+ }
992
+ const v = this.#valList[index];
993
+ return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
994
+ }
995
+ #backgroundFetch(k, index, options, context) {
996
+ const v = index === void 0 ? void 0 : this.#valList[index];
997
+ if (this.#isBackgroundFetch(v)) {
998
+ return v;
999
+ }
1000
+ const ac = new AC();
1001
+ const { signal } = options;
1002
+ signal?.addEventListener("abort", () => ac.abort(signal.reason), {
1003
+ signal: ac.signal
1004
+ });
1005
+ const fetchOpts = {
1006
+ signal: ac.signal,
1007
+ options,
1008
+ context
1009
+ };
1010
+ const cb = (v2, updateCache = false) => {
1011
+ const { aborted } = ac.signal;
1012
+ const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
1013
+ if (options.status) {
1014
+ if (aborted && !updateCache) {
1015
+ options.status.fetchAborted = true;
1016
+ options.status.fetchError = ac.signal.reason;
1017
+ if (ignoreAbort)
1018
+ options.status.fetchAbortIgnored = true;
1019
+ } else {
1020
+ options.status.fetchResolved = true;
1021
+ }
1022
+ }
1023
+ if (aborted && !ignoreAbort && !updateCache) {
1024
+ return fetchFail(ac.signal.reason);
1025
+ }
1026
+ const bf2 = p;
1027
+ if (this.#valList[index] === p) {
1028
+ if (v2 === void 0) {
1029
+ if (bf2.__staleWhileFetching) {
1030
+ this.#valList[index] = bf2.__staleWhileFetching;
1031
+ } else {
1032
+ this.#delete(k, "fetch");
1033
+ }
1034
+ } else {
1035
+ if (options.status)
1036
+ options.status.fetchUpdated = true;
1037
+ this.set(k, v2, fetchOpts.options);
1038
+ }
1039
+ }
1040
+ return v2;
1041
+ };
1042
+ const eb = (er) => {
1043
+ if (options.status) {
1044
+ options.status.fetchRejected = true;
1045
+ options.status.fetchError = er;
1046
+ }
1047
+ return fetchFail(er);
1048
+ };
1049
+ const fetchFail = (er) => {
1050
+ const { aborted } = ac.signal;
1051
+ const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
1052
+ const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
1053
+ const noDelete = allowStale || options.noDeleteOnFetchRejection;
1054
+ const bf2 = p;
1055
+ if (this.#valList[index] === p) {
1056
+ const del = !noDelete || bf2.__staleWhileFetching === void 0;
1057
+ if (del) {
1058
+ this.#delete(k, "fetch");
1059
+ } else if (!allowStaleAborted) {
1060
+ this.#valList[index] = bf2.__staleWhileFetching;
1061
+ }
1062
+ }
1063
+ if (allowStale) {
1064
+ if (options.status && bf2.__staleWhileFetching !== void 0) {
1065
+ options.status.returnedStale = true;
1066
+ }
1067
+ return bf2.__staleWhileFetching;
1068
+ } else if (bf2.__returned === bf2) {
1069
+ throw er;
1070
+ }
1071
+ };
1072
+ const pcall = (res, rej) => {
1073
+ const fmp = this.#fetchMethod?.(k, v, fetchOpts);
1074
+ if (fmp && fmp instanceof Promise) {
1075
+ fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
1076
+ }
1077
+ ac.signal.addEventListener("abort", () => {
1078
+ if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
1079
+ res(void 0);
1080
+ if (options.allowStaleOnFetchAbort) {
1081
+ res = (v2) => cb(v2, true);
1082
+ }
1083
+ }
1084
+ });
1085
+ };
1086
+ if (options.status)
1087
+ options.status.fetchDispatched = true;
1088
+ const p = new Promise(pcall).then(cb, eb);
1089
+ const bf = Object.assign(p, {
1090
+ __abortController: ac,
1091
+ __staleWhileFetching: v,
1092
+ __returned: void 0
1093
+ });
1094
+ if (index === void 0) {
1095
+ this.set(k, bf, { ...fetchOpts.options, status: void 0 });
1096
+ index = this.#keyMap.get(k);
1097
+ } else {
1098
+ this.#valList[index] = bf;
1099
+ }
1100
+ return bf;
1101
+ }
1102
+ #isBackgroundFetch(p) {
1103
+ if (!this.#hasFetchMethod)
1104
+ return false;
1105
+ const b = p;
1106
+ return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
1107
+ }
1108
+ async fetch(k, fetchOptions = {}) {
1109
+ const {
1110
+ // get options
1111
+ allowStale = this.allowStale,
1112
+ updateAgeOnGet = this.updateAgeOnGet,
1113
+ noDeleteOnStaleGet = this.noDeleteOnStaleGet,
1114
+ // set options
1115
+ ttl = this.ttl,
1116
+ noDisposeOnSet = this.noDisposeOnSet,
1117
+ size = 0,
1118
+ sizeCalculation = this.sizeCalculation,
1119
+ noUpdateTTL = this.noUpdateTTL,
1120
+ // fetch exclusive options
1121
+ noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
1122
+ allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
1123
+ ignoreFetchAbort = this.ignoreFetchAbort,
1124
+ allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
1125
+ context,
1126
+ forceRefresh = false,
1127
+ status,
1128
+ signal
1129
+ } = fetchOptions;
1130
+ if (!this.#hasFetchMethod) {
1131
+ if (status)
1132
+ status.fetch = "get";
1133
+ return this.get(k, {
1134
+ allowStale,
1135
+ updateAgeOnGet,
1136
+ noDeleteOnStaleGet,
1137
+ status
1138
+ });
1139
+ }
1140
+ const options = {
1141
+ allowStale,
1142
+ updateAgeOnGet,
1143
+ noDeleteOnStaleGet,
1144
+ ttl,
1145
+ noDisposeOnSet,
1146
+ size,
1147
+ sizeCalculation,
1148
+ noUpdateTTL,
1149
+ noDeleteOnFetchRejection,
1150
+ allowStaleOnFetchRejection,
1151
+ allowStaleOnFetchAbort,
1152
+ ignoreFetchAbort,
1153
+ status,
1154
+ signal
1155
+ };
1156
+ let index = this.#keyMap.get(k);
1157
+ if (index === void 0) {
1158
+ if (status)
1159
+ status.fetch = "miss";
1160
+ const p = this.#backgroundFetch(k, index, options, context);
1161
+ return p.__returned = p;
1162
+ } else {
1163
+ const v = this.#valList[index];
1164
+ if (this.#isBackgroundFetch(v)) {
1165
+ const stale = allowStale && v.__staleWhileFetching !== void 0;
1166
+ if (status) {
1167
+ status.fetch = "inflight";
1168
+ if (stale)
1169
+ status.returnedStale = true;
1170
+ }
1171
+ return stale ? v.__staleWhileFetching : v.__returned = v;
1172
+ }
1173
+ const isStale = this.#isStale(index);
1174
+ if (!forceRefresh && !isStale) {
1175
+ if (status)
1176
+ status.fetch = "hit";
1177
+ this.#moveToTail(index);
1178
+ if (updateAgeOnGet) {
1179
+ this.#updateItemAge(index);
1180
+ }
1181
+ if (status)
1182
+ this.#statusTTL(status, index);
1183
+ return v;
1184
+ }
1185
+ const p = this.#backgroundFetch(k, index, options, context);
1186
+ const hasStale = p.__staleWhileFetching !== void 0;
1187
+ const staleVal = hasStale && allowStale;
1188
+ if (status) {
1189
+ status.fetch = isStale ? "stale" : "refresh";
1190
+ if (staleVal && isStale)
1191
+ status.returnedStale = true;
1192
+ }
1193
+ return staleVal ? p.__staleWhileFetching : p.__returned = p;
1194
+ }
1195
+ }
1196
+ async forceFetch(k, fetchOptions = {}) {
1197
+ const v = await this.fetch(k, fetchOptions);
1198
+ if (v === void 0)
1199
+ throw new Error("fetch() returned undefined");
1200
+ return v;
1201
+ }
1202
+ memo(k, memoOptions = {}) {
1203
+ const memoMethod = this.#memoMethod;
1204
+ if (!memoMethod) {
1205
+ throw new Error("no memoMethod provided to constructor");
1206
+ }
1207
+ const { context, forceRefresh, ...options } = memoOptions;
1208
+ const v = this.get(k, options);
1209
+ if (!forceRefresh && v !== void 0)
1210
+ return v;
1211
+ const vv = memoMethod(k, v, {
1212
+ options,
1213
+ context
1214
+ });
1215
+ this.set(k, vv, options);
1216
+ return vv;
1217
+ }
1218
+ /**
1219
+ * Return a value from the cache. Will update the recency of the cache
1220
+ * entry found.
1221
+ *
1222
+ * If the key is not found, get() will return `undefined`.
1223
+ */
1224
+ get(k, getOptions = {}) {
1225
+ const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
1226
+ const index = this.#keyMap.get(k);
1227
+ if (index !== void 0) {
1228
+ const value = this.#valList[index];
1229
+ const fetching = this.#isBackgroundFetch(value);
1230
+ if (status)
1231
+ this.#statusTTL(status, index);
1232
+ if (this.#isStale(index)) {
1233
+ if (status)
1234
+ status.get = "stale";
1235
+ if (!fetching) {
1236
+ if (!noDeleteOnStaleGet) {
1237
+ this.#delete(k, "expire");
1238
+ }
1239
+ if (status && allowStale)
1240
+ status.returnedStale = true;
1241
+ return allowStale ? value : void 0;
1242
+ } else {
1243
+ if (status && allowStale && value.__staleWhileFetching !== void 0) {
1244
+ status.returnedStale = true;
1245
+ }
1246
+ return allowStale ? value.__staleWhileFetching : void 0;
1247
+ }
1248
+ } else {
1249
+ if (status)
1250
+ status.get = "hit";
1251
+ if (fetching) {
1252
+ return value.__staleWhileFetching;
1253
+ }
1254
+ this.#moveToTail(index);
1255
+ if (updateAgeOnGet) {
1256
+ this.#updateItemAge(index);
1257
+ }
1258
+ return value;
1259
+ }
1260
+ } else if (status) {
1261
+ status.get = "miss";
1262
+ }
1263
+ }
1264
+ #connect(p, n) {
1265
+ this.#prev[n] = p;
1266
+ this.#next[p] = n;
1267
+ }
1268
+ #moveToTail(index) {
1269
+ if (index !== this.#tail) {
1270
+ if (index === this.#head) {
1271
+ this.#head = this.#next[index];
1272
+ } else {
1273
+ this.#connect(this.#prev[index], this.#next[index]);
1274
+ }
1275
+ this.#connect(this.#tail, index);
1276
+ this.#tail = index;
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Deletes a key out of the cache.
1281
+ *
1282
+ * Returns true if the key was deleted, false otherwise.
1283
+ */
1284
+ delete(k) {
1285
+ return this.#delete(k, "delete");
1286
+ }
1287
+ #delete(k, reason) {
1288
+ let deleted = false;
1289
+ if (this.#size !== 0) {
1290
+ const index = this.#keyMap.get(k);
1291
+ if (index !== void 0) {
1292
+ deleted = true;
1293
+ if (this.#size === 1) {
1294
+ this.#clear(reason);
1295
+ } else {
1296
+ this.#removeItemSize(index);
1297
+ const v = this.#valList[index];
1298
+ if (this.#isBackgroundFetch(v)) {
1299
+ v.__abortController.abort(new Error("deleted"));
1300
+ } else if (this.#hasDispose || this.#hasDisposeAfter) {
1301
+ if (this.#hasDispose) {
1302
+ this.#dispose?.(v, k, reason);
1303
+ }
1304
+ if (this.#hasDisposeAfter) {
1305
+ this.#disposed?.push([v, k, reason]);
1306
+ }
1307
+ }
1308
+ this.#keyMap.delete(k);
1309
+ this.#keyList[index] = void 0;
1310
+ this.#valList[index] = void 0;
1311
+ if (index === this.#tail) {
1312
+ this.#tail = this.#prev[index];
1313
+ } else if (index === this.#head) {
1314
+ this.#head = this.#next[index];
1315
+ } else {
1316
+ const pi = this.#prev[index];
1317
+ this.#next[pi] = this.#next[index];
1318
+ const ni = this.#next[index];
1319
+ this.#prev[ni] = this.#prev[index];
1320
+ }
1321
+ this.#size--;
1322
+ this.#free.push(index);
1323
+ }
1324
+ }
1325
+ }
1326
+ if (this.#hasDisposeAfter && this.#disposed?.length) {
1327
+ const dt = this.#disposed;
1328
+ let task;
1329
+ while (task = dt?.shift()) {
1330
+ this.#disposeAfter?.(...task);
1331
+ }
1332
+ }
1333
+ return deleted;
1334
+ }
1335
+ /**
1336
+ * Clear the cache entirely, throwing away all values.
1337
+ */
1338
+ clear() {
1339
+ return this.#clear("delete");
1340
+ }
1341
+ #clear(reason) {
1342
+ for (const index of this.#rindexes({ allowStale: true })) {
1343
+ const v = this.#valList[index];
1344
+ if (this.#isBackgroundFetch(v)) {
1345
+ v.__abortController.abort(new Error("deleted"));
1346
+ } else {
1347
+ const k = this.#keyList[index];
1348
+ if (this.#hasDispose) {
1349
+ this.#dispose?.(v, k, reason);
1350
+ }
1351
+ if (this.#hasDisposeAfter) {
1352
+ this.#disposed?.push([v, k, reason]);
1353
+ }
1354
+ }
1355
+ }
1356
+ this.#keyMap.clear();
1357
+ this.#valList.fill(void 0);
1358
+ this.#keyList.fill(void 0);
1359
+ if (this.#ttls && this.#starts) {
1360
+ this.#ttls.fill(0);
1361
+ this.#starts.fill(0);
1362
+ }
1363
+ if (this.#sizes) {
1364
+ this.#sizes.fill(0);
1365
+ }
1366
+ this.#head = 0;
1367
+ this.#tail = 0;
1368
+ this.#free.length = 0;
1369
+ this.#calculatedSize = 0;
1370
+ this.#size = 0;
1371
+ if (this.#hasDisposeAfter && this.#disposed) {
1372
+ const dt = this.#disposed;
1373
+ let task;
1374
+ while (task = dt?.shift()) {
1375
+ this.#disposeAfter?.(...task);
1376
+ }
1377
+ }
1378
+ }
1379
+ };
1380
+
1381
+ // src/run/handlers/use-cache-handler.ts
1382
+ import { getLogger } from "./request-context.cjs";
1383
+ import {
1384
+ getMostRecentTagRevalidationTimestamp,
1385
+ isAnyTagStale,
1386
+ markTagsAsStaleAndPurgeEdgeCache
1387
+ } from "./tags-handler.cjs";
1388
+ import { getTracer } from "./tracer.cjs";
1389
+ var LRU_CACHE_GLOBAL_KEY = Symbol.for("nf-use-cache-handler-lru-cache");
1390
+ var PENDING_SETS_GLOBAL_KEY = Symbol.for("nf-use-cache-handler-pending-sets");
1391
+ var cacheHandlersSymbol = Symbol.for("@next/cache-handlers");
1392
+ var extendedGlobalThis = globalThis;
1393
+ function getLRUCache() {
1394
+ if (extendedGlobalThis[LRU_CACHE_GLOBAL_KEY]) {
1395
+ return extendedGlobalThis[LRU_CACHE_GLOBAL_KEY];
1396
+ }
1397
+ const lruCache = new LRUCache({
1398
+ max: 1e3,
1399
+ maxSize: 50 * 1024 * 1024,
1400
+ // same as hardcoded default in Next.js
1401
+ sizeCalculation: (value) => value.size
1402
+ });
1403
+ extendedGlobalThis[LRU_CACHE_GLOBAL_KEY] = lruCache;
1404
+ return lruCache;
1405
+ }
1406
+ function getPendingSets() {
1407
+ if (extendedGlobalThis[PENDING_SETS_GLOBAL_KEY]) {
1408
+ return extendedGlobalThis[PENDING_SETS_GLOBAL_KEY];
1409
+ }
1410
+ const pendingSets = /* @__PURE__ */ new Map();
1411
+ extendedGlobalThis[PENDING_SETS_GLOBAL_KEY] = pendingSets;
1412
+ return pendingSets;
1413
+ }
1414
+ var tmpResolvePendingBeforeCreatingAPromise = () => {
1415
+ };
1416
+ var NetlifyDefaultUseCacheHandler = {
1417
+ get(cacheKey) {
1418
+ return getTracer().withActiveSpan(
1419
+ "DefaultUseCacheHandler.get",
1420
+ async (span) => {
1421
+ getLogger().withFields({ cacheKey }).debug(`[NetlifyDefaultUseCacheHandler] get`);
1422
+ span.setAttributes({
1423
+ cacheKey
1424
+ });
1425
+ const pendingPromise = getPendingSets().get(cacheKey);
1426
+ if (pendingPromise) {
1427
+ await pendingPromise;
1428
+ }
1429
+ const privateEntry = getLRUCache().get(cacheKey);
1430
+ if (!privateEntry) {
1431
+ getLogger().withFields({ cacheKey, status: "MISS" }).debug(`[NetlifyDefaultUseCacheHandler] get result`);
1432
+ span.setAttributes({
1433
+ cacheStatus: "miss"
1434
+ });
1435
+ return void 0;
1436
+ }
1437
+ const { entry } = privateEntry;
1438
+ const ttl = (entry.timestamp + entry.revalidate * 1e3 - Date.now()) / 1e3;
1439
+ if (ttl < 0) {
1440
+ getLogger().withFields({ cacheKey, ttl, status: "STALE" }).debug(`[NetlifyDefaultUseCacheHandler] get result`);
1441
+ span.setAttributes({
1442
+ cacheStatus: "expired, discarded",
1443
+ ttl
1444
+ });
1445
+ return void 0;
1446
+ }
1447
+ if (await isAnyTagStale(entry.tags, entry.timestamp)) {
1448
+ getLogger().withFields({ cacheKey, ttl, status: "STALE BY TAG" }).debug(`[NetlifyDefaultUseCacheHandler] get result`);
1449
+ span.setAttributes({
1450
+ cacheStatus: "stale tag, discarded",
1451
+ ttl
1452
+ });
1453
+ return void 0;
1454
+ }
1455
+ const [returnStream, newSaved] = entry.value.tee();
1456
+ entry.value = newSaved;
1457
+ getLogger().withFields({ cacheKey, ttl, status: "HIT" }).debug(`[NetlifyDefaultUseCacheHandler] get result`);
1458
+ span.setAttributes({
1459
+ cacheStatus: "hit",
1460
+ ttl
1461
+ });
1462
+ return {
1463
+ ...entry,
1464
+ value: returnStream
1465
+ };
1466
+ }
1467
+ );
1468
+ },
1469
+ set(cacheKey, pendingEntry) {
1470
+ return getTracer().withActiveSpan(
1471
+ "DefaultUseCacheHandler.set",
1472
+ async (span) => {
1473
+ getLogger().withFields({ cacheKey }).debug(`[NetlifyDefaultUseCacheHandler]: set`);
1474
+ span.setAttributes({
1475
+ cacheKey
1476
+ });
1477
+ let resolvePending = tmpResolvePendingBeforeCreatingAPromise;
1478
+ const pendingPromise = new Promise((resolve) => {
1479
+ resolvePending = resolve;
1480
+ });
1481
+ const pendingSets = getPendingSets();
1482
+ pendingSets.set(cacheKey, pendingPromise);
1483
+ const entry = await pendingEntry;
1484
+ span.setAttributes({
1485
+ cacheKey
1486
+ });
1487
+ let size = 0;
1488
+ try {
1489
+ const [value, clonedValue] = entry.value.tee();
1490
+ entry.value = value;
1491
+ const reader = clonedValue.getReader();
1492
+ for (let chunk; !(chunk = await reader.read()).done; ) {
1493
+ size += Buffer.from(chunk.value).byteLength;
1494
+ }
1495
+ span.setAttributes({
1496
+ tags: entry.tags,
1497
+ timestamp: entry.timestamp,
1498
+ revalidate: entry.revalidate,
1499
+ expire: entry.expire
1500
+ });
1501
+ getLRUCache().set(cacheKey, {
1502
+ entry,
1503
+ size
1504
+ });
1505
+ } catch (error) {
1506
+ getLogger().withError(error).error("[NetlifyDefaultUseCacheHandler.set] error");
1507
+ } finally {
1508
+ resolvePending();
1509
+ pendingSets.delete(cacheKey);
1510
+ }
1511
+ }
1512
+ );
1513
+ },
1514
+ async refreshTags() {
1515
+ },
1516
+ getExpiration: function(...tags) {
1517
+ return getTracer().withActiveSpan(
1518
+ "DefaultUseCacheHandler.getExpiration",
1519
+ async (span) => {
1520
+ span.setAttributes({
1521
+ tags
1522
+ });
1523
+ const expiration = await getMostRecentTagRevalidationTimestamp(tags);
1524
+ getLogger().withFields({ tags, expiration }).debug(`[NetlifyDefaultUseCacheHandler] getExpiration`);
1525
+ span.setAttributes({
1526
+ expiration
1527
+ });
1528
+ return expiration;
1529
+ }
1530
+ );
1531
+ },
1532
+ expireTags(...tags) {
1533
+ return getTracer().withActiveSpan(
1534
+ "DefaultUseCacheHandler.expireTags",
1535
+ async (span) => {
1536
+ getLogger().withFields({ tags }).debug(`[NetlifyDefaultUseCacheHandler] expireTags`);
1537
+ span.setAttributes({
1538
+ tags
1539
+ });
1540
+ await markTagsAsStaleAndPurgeEdgeCache(tags);
1541
+ }
1542
+ );
1543
+ }
1544
+ };
1545
+ function configureUseCacheHandlers() {
1546
+ extendedGlobalThis[cacheHandlersSymbol] = {
1547
+ DefaultCache: NetlifyDefaultUseCacheHandler
1548
+ };
1549
+ }
1550
+ export {
1551
+ NetlifyDefaultUseCacheHandler,
1552
+ configureUseCacheHandlers
1553
+ };