-
Notifications
You must be signed in to change notification settings - Fork 27k
/
patch-fetch.ts
796 lines (712 loc) · 27.3 KB
/
patch-fetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
import type {
StaticGenerationAsyncStorage,
StaticGenerationStore,
} from '../../client/components/static-generation-async-storage.external'
import { AppRenderSpan, NextNodeServerSpan } from './trace/constants'
import { getTracer, SpanKind } from './trace/tracer'
import {
CACHE_ONE_YEAR,
NEXT_CACHE_IMPLICIT_TAG_ID,
NEXT_CACHE_TAG_MAX_ITEMS,
NEXT_CACHE_TAG_MAX_LENGTH,
} from '../../lib/constants'
import * as Log from '../../build/output/log'
import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'
import type { FetchMetric } from '../base-http'
import { createDedupeFetch } from './dedupe-fetch'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
type Fetcher = typeof fetch
type PatchedFetcher = Fetcher & {
readonly __nextPatched: true
readonly __nextGetStaticStore: () => StaticGenerationAsyncStorage
readonly _nextOriginalFetch: Fetcher
}
function isPatchedFetch(
fetch: Fetcher | PatchedFetcher
): fetch is PatchedFetcher {
return '__nextPatched' in fetch && fetch.__nextPatched === true
}
export function validateRevalidate(
revalidateVal: unknown,
pathname: string
): undefined | number | false {
try {
let normalizedRevalidate: false | number | undefined = undefined
if (revalidateVal === false) {
normalizedRevalidate = revalidateVal
} else if (
typeof revalidateVal === 'number' &&
!isNaN(revalidateVal) &&
revalidateVal > -1
) {
normalizedRevalidate = revalidateVal
} else if (typeof revalidateVal !== 'undefined') {
throw new Error(
`Invalid revalidate value "${revalidateVal}" on "${pathname}", must be a non-negative number or "false"`
)
}
return normalizedRevalidate
} catch (err: any) {
// handle client component error from attempting to check revalidate value
if (err instanceof Error && err.message.includes('Invalid revalidate')) {
throw err
}
return undefined
}
}
export function validateTags(tags: any[], description: string) {
const validTags: string[] = []
const invalidTags: Array<{
tag: any
reason: string
}> = []
for (let i = 0; i < tags.length; i++) {
const tag = tags[i]
if (typeof tag !== 'string') {
invalidTags.push({ tag, reason: 'invalid type, must be a string' })
} else if (tag.length > NEXT_CACHE_TAG_MAX_LENGTH) {
invalidTags.push({
tag,
reason: `exceeded max length of ${NEXT_CACHE_TAG_MAX_LENGTH}`,
})
} else {
validTags.push(tag)
}
if (validTags.length > NEXT_CACHE_TAG_MAX_ITEMS) {
console.warn(
`Warning: exceeded max tag count for ${description}, dropped tags:`,
tags.slice(i).join(', ')
)
break
}
}
if (invalidTags.length > 0) {
console.warn(`Warning: invalid tags passed to ${description}: `)
for (const { tag, reason } of invalidTags) {
console.log(`tag: "${tag}" ${reason}`)
}
}
return validTags
}
const getDerivedTags = (pathname: string): string[] => {
const derivedTags: string[] = [`/layout`]
// we automatically add the current path segments as tags
// for revalidatePath handling
if (pathname.startsWith('/')) {
const pathnameParts = pathname.split('/')
for (let i = 1; i < pathnameParts.length + 1; i++) {
let curPathname = pathnameParts.slice(0, i).join('/')
if (curPathname) {
// all derived tags other than the page are layout tags
if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {
curPathname = `${curPathname}${
!curPathname.endsWith('/') ? '/' : ''
}layout`
}
derivedTags.push(curPathname)
}
}
}
return derivedTags
}
export function addImplicitTags(staticGenerationStore: StaticGenerationStore) {
const newTags: string[] = []
const { pagePath, urlPathname } = staticGenerationStore
if (!Array.isArray(staticGenerationStore.tags)) {
staticGenerationStore.tags = []
}
if (pagePath) {
const derivedTags = getDerivedTags(pagePath)
for (let tag of derivedTags) {
tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`
if (!staticGenerationStore.tags?.includes(tag)) {
staticGenerationStore.tags.push(tag)
}
newTags.push(tag)
}
}
if (urlPathname) {
const parsedPathname = new URL(urlPathname, 'http://n').pathname
const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${parsedPathname}`
if (!staticGenerationStore.tags?.includes(tag)) {
staticGenerationStore.tags.push(tag)
}
newTags.push(tag)
}
return newTags
}
function trackFetchMetric(
staticGenerationStore: StaticGenerationStore,
ctx: Omit<FetchMetric, 'end' | 'idx'>
) {
if (
!staticGenerationStore ||
staticGenerationStore.requestEndedState?.ended ||
process.env.NODE_ENV !== 'development'
) {
return
}
staticGenerationStore.fetchMetrics ??= []
const dedupeFields = ['url', 'status', 'method'] as const
// don't add metric if one already exists for the fetch
if (
staticGenerationStore.fetchMetrics.some((metric) =>
dedupeFields.every((field) => metric[field] === ctx[field])
)
) {
return
}
staticGenerationStore.fetchMetrics.push({
...ctx,
end: Date.now(),
idx: staticGenerationStore.nextFetchId || 0,
})
// only store top 10 metrics to avoid storing too many
if (staticGenerationStore.fetchMetrics.length > 10) {
// sort slowest first as these should be highlighted
staticGenerationStore.fetchMetrics.sort((a, b) => {
const aDur = a.end - a.start
const bDur = b.end - b.start
if (aDur < bDur) {
return 1
} else if (aDur > bDur) {
return -1
}
return 0
})
// now grab top 10
staticGenerationStore.fetchMetrics =
staticGenerationStore.fetchMetrics.slice(0, 10)
}
}
interface PatchableModule {
staticGenerationAsyncStorage: StaticGenerationAsyncStorage
}
function createPatchedFetcher(
originFetch: Fetcher,
{ staticGenerationAsyncStorage }: PatchableModule
): PatchedFetcher {
// Create the patched fetch function. We don't set the type here, as it's
// verified as the return value of this function.
const patched = async (
input: RequestInfo | URL,
init: RequestInit | undefined
) => {
let url: URL | undefined
try {
url = new URL(input instanceof Request ? input.url : input)
url.username = ''
url.password = ''
} catch {
// Error caused by malformed URL should be handled by native fetch
url = undefined
}
const fetchUrl = url?.href ?? ''
const fetchStart = Date.now()
const method = init?.method?.toUpperCase() || 'GET'
// Do create a new span trace for internal fetches in the
// non-verbose mode.
const isInternal = (init?.next as any)?.internal === true
const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === '1'
return getTracer().trace(
isInternal ? NextNodeServerSpan.internalFetch : AppRenderSpan.fetch,
{
hideSpan,
kind: SpanKind.CLIENT,
spanName: ['fetch', method, fetchUrl].filter(Boolean).join(' '),
attributes: {
'http.url': fetchUrl,
'http.method': method,
'net.peer.name': url?.hostname,
'net.peer.port': url?.port || undefined,
},
},
async () => {
// If this is an internal fetch, we should not do any special treatment.
if (isInternal) {
return originFetch(input, init)
}
const staticGenerationStore = staticGenerationAsyncStorage.getStore()
// If the staticGenerationStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original
// fetch implementation.
if (!staticGenerationStore) {
return originFetch(input, init)
}
// We should also fallback to the original fetch implementation if we
// are in draft mode, it does not constitute a static generation.
if (staticGenerationStore.isDraftMode) {
return originFetch(input, init)
}
const isRequestInput =
input &&
typeof input === 'object' &&
typeof (input as Request).method === 'string'
const getRequestMeta = (field: string) => {
// If request input is present but init is not, retrieve from input first.
const value = (init as any)?.[field]
return value || (isRequestInput ? (input as any)[field] : null)
}
let finalRevalidate: number | undefined | false = undefined
const getNextField = (field: 'revalidate' | 'tags') => {
return typeof init?.next?.[field] !== 'undefined'
? init?.next?.[field]
: isRequestInput
? (input as any).next?.[field]
: undefined
}
// RequestInit doesn't keep extra fields e.g. next so it's
// only available if init is used separate
let currentFetchRevalidate = getNextField('revalidate')
const tags: string[] = validateTags(
getNextField('tags') || [],
`fetch ${input.toString()}`
)
if (Array.isArray(tags)) {
if (!staticGenerationStore.tags) {
staticGenerationStore.tags = []
}
for (const tag of tags) {
if (!staticGenerationStore.tags.includes(tag)) {
staticGenerationStore.tags.push(tag)
}
}
}
const implicitTags = addImplicitTags(staticGenerationStore)
const pageFetchCacheMode = staticGenerationStore.fetchCache
const isUsingNoStore = !!staticGenerationStore.isUnstableNoStore
let currentFetchCacheConfig = getRequestMeta('cache')
let cacheReason = ''
if (
typeof currentFetchCacheConfig === 'string' &&
typeof currentFetchRevalidate !== 'undefined'
) {
// when providing fetch with a Request input, it'll automatically set a cache value of 'default'
// we only want to warn if the user is explicitly setting a cache value
if (!(isRequestInput && currentFetchCacheConfig === 'default')) {
Log.warn(
`fetch for ${fetchUrl} on ${staticGenerationStore.urlPathname} specified "cache: ${currentFetchCacheConfig}" and "revalidate: ${currentFetchRevalidate}", only one should be specified.`
)
}
currentFetchCacheConfig = undefined
}
if (currentFetchCacheConfig === 'force-cache') {
currentFetchRevalidate = false
} else if (
currentFetchCacheConfig === 'no-cache' ||
currentFetchCacheConfig === 'no-store' ||
pageFetchCacheMode === 'force-no-store' ||
pageFetchCacheMode === 'only-no-store' ||
// If no explicit fetch cache mode is set, but dynamic = `force-dynamic` is set,
// we shouldn't consider caching the fetch. This is because the `dynamic` cache
// is considered a "top-level" cache mode, whereas something like `fetchCache` is more
// fine-grained. Top-level modes are responsible for setting reasonable defaults for the
// other configurations.
(!pageFetchCacheMode && staticGenerationStore.forceDynamic)
) {
currentFetchRevalidate = 0
}
if (
currentFetchCacheConfig === 'no-cache' ||
currentFetchCacheConfig === 'no-store'
) {
cacheReason = `cache: ${currentFetchCacheConfig}`
}
finalRevalidate = validateRevalidate(
currentFetchRevalidate,
staticGenerationStore.urlPathname
)
const _headers = getRequestMeta('headers')
const initHeaders: Headers =
typeof _headers?.get === 'function'
? _headers
: new Headers(_headers || {})
const hasUnCacheableHeader =
initHeaders.get('authorization') || initHeaders.get('cookie')
const isUnCacheableMethod = !['get', 'head'].includes(
getRequestMeta('method')?.toLowerCase() || 'get'
)
/**
* We automatically disable fetch caching under the following conditions:
* - Fetch cache configs are not set. Specifically:
* - A page fetch cache mode is not set (export const fetchCache=...)
* - A fetch cache mode is not set in the fetch call (fetch(url, { cache: ... }))
* - A fetch revalidate value is not set in the fetch call (fetch(url, { revalidate: ... }))
* - OR the fetch comes after a configuration that triggered dynamic rendering (e.g., reading cookies())
* and the fetch was considered uncacheable (e.g., POST method or has authorization headers)
*/
const autoNoCache =
// this condition is hit for null/undefined
// eslint-disable-next-line eqeqeq
(pageFetchCacheMode == undefined &&
// eslint-disable-next-line eqeqeq
currentFetchCacheConfig == undefined &&
// eslint-disable-next-line eqeqeq
currentFetchRevalidate == undefined) ||
((hasUnCacheableHeader || isUnCacheableMethod) &&
staticGenerationStore.revalidate === 0)
switch (pageFetchCacheMode) {
case 'force-no-store': {
cacheReason = 'fetchCache = force-no-store'
break
}
case 'only-no-store': {
if (
currentFetchCacheConfig === 'force-cache' ||
(typeof finalRevalidate !== 'undefined' &&
(finalRevalidate === false || finalRevalidate > 0))
) {
throw new Error(
`cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`
)
}
cacheReason = 'fetchCache = only-no-store'
break
}
case 'only-cache': {
if (currentFetchCacheConfig === 'no-store') {
throw new Error(
`cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`
)
}
break
}
case 'force-cache': {
if (
typeof currentFetchRevalidate === 'undefined' ||
currentFetchRevalidate === 0
) {
cacheReason = 'fetchCache = force-cache'
finalRevalidate = false
}
break
}
default:
// sometimes we won't match the above cases. the reason we don't move
// everything to this switch is the use of autoNoCache which is not a fetchCacheMode
// I suspect this could be unified with fetchCacheMode however in which case we could
// simplify the switch case and ensure we have an exhaustive switch handling all modes
}
if (typeof finalRevalidate === 'undefined') {
if (pageFetchCacheMode === 'default-cache' && !isUsingNoStore) {
finalRevalidate = false
cacheReason = 'fetchCache = default-cache'
} else if (pageFetchCacheMode === 'default-no-store') {
finalRevalidate = 0
cacheReason = 'fetchCache = default-no-store'
} else if (isUsingNoStore) {
finalRevalidate = 0
cacheReason = 'noStore call'
} else if (autoNoCache) {
finalRevalidate = 0
cacheReason = 'auto no cache'
} else {
// TODO: should we consider this case an invariant?
cacheReason = 'auto cache'
finalRevalidate =
typeof staticGenerationStore.revalidate === 'boolean' ||
typeof staticGenerationStore.revalidate === 'undefined'
? false
: staticGenerationStore.revalidate
}
} else if (!cacheReason) {
cacheReason = `revalidate: ${finalRevalidate}`
}
if (
// when force static is configured we don't bail from
// `revalidate: 0` values
!(staticGenerationStore.forceStatic && finalRevalidate === 0) &&
// we don't consider autoNoCache to switch to dynamic for ISR
!autoNoCache &&
// If the revalidate value isn't currently set or the value is less
// than the current revalidate value, we should update the revalidate
// value.
(typeof staticGenerationStore.revalidate === 'undefined' ||
(typeof finalRevalidate === 'number' &&
(staticGenerationStore.revalidate === false ||
(typeof staticGenerationStore.revalidate === 'number' &&
finalRevalidate < staticGenerationStore.revalidate))))
) {
// If we were setting the revalidate value to 0, we should try to
// postpone instead first.
if (finalRevalidate === 0) {
markCurrentScopeAsDynamic(
staticGenerationStore,
`revalidate: 0 fetch ${input}${
staticGenerationStore.urlPathname
? ` ${staticGenerationStore.urlPathname}`
: ''
}`
)
}
staticGenerationStore.revalidate = finalRevalidate
}
const isCacheableRevalidate =
(typeof finalRevalidate === 'number' && finalRevalidate > 0) ||
finalRevalidate === false
let cacheKey: string | undefined
if (staticGenerationStore.incrementalCache && isCacheableRevalidate) {
try {
cacheKey =
await staticGenerationStore.incrementalCache.fetchCacheKey(
fetchUrl,
isRequestInput ? (input as RequestInit) : init
)
} catch (err) {
console.error(`Failed to generate cache key for`, input)
}
}
const fetchIdx = staticGenerationStore.nextFetchId ?? 1
staticGenerationStore.nextFetchId = fetchIdx + 1
const normalizedRevalidate =
typeof finalRevalidate !== 'number' ? CACHE_ONE_YEAR : finalRevalidate
const doOriginalFetch = async (
isStale?: boolean,
cacheReasonOverride?: string
) => {
const requestInputFields = [
'cache',
'credentials',
'headers',
'integrity',
'keepalive',
'method',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'window',
'duplex',
// don't pass through signal when revalidating
...(isStale ? [] : ['signal']),
]
if (isRequestInput) {
const reqInput: Request = input as any
const reqOptions: RequestInit = {
body: (reqInput as any)._ogBody || reqInput.body,
}
for (const field of requestInputFields) {
// @ts-expect-error custom fields
reqOptions[field] = reqInput[field]
}
input = new Request(reqInput.url, reqOptions)
} else if (init) {
const { _ogBody, body, signal, ...otherInput } =
init as RequestInit & { _ogBody?: any }
init = {
...otherInput,
body: _ogBody || body,
signal: isStale ? undefined : signal,
}
}
// add metadata to init without editing the original
const clonedInit = {
...init,
next: { ...init?.next, fetchType: 'origin', fetchIdx },
}
return originFetch(input, clonedInit).then(async (res) => {
if (!isStale) {
trackFetchMetric(staticGenerationStore, {
start: fetchStart,
url: fetchUrl,
cacheReason: cacheReasonOverride || cacheReason,
cacheStatus:
finalRevalidate === 0 || cacheReasonOverride
? 'skip'
: 'miss',
status: res.status,
method: clonedInit.method || 'GET',
})
}
if (
res.status === 200 &&
staticGenerationStore.incrementalCache &&
cacheKey &&
isCacheableRevalidate
) {
const bodyBuffer = Buffer.from(await res.arrayBuffer())
try {
await staticGenerationStore.incrementalCache.set(
cacheKey,
{
kind: 'FETCH',
data: {
headers: Object.fromEntries(res.headers.entries()),
body: bodyBuffer.toString('base64'),
status: res.status,
url: res.url,
},
revalidate: normalizedRevalidate,
},
{
fetchCache: true,
revalidate: finalRevalidate,
fetchUrl,
fetchIdx,
tags,
}
)
} catch (err) {
console.warn(`Failed to set fetch cache`, input, err)
}
const response = new Response(bodyBuffer, {
headers: new Headers(res.headers),
status: res.status,
})
Object.defineProperty(response, 'url', { value: res.url })
return response
}
return res
})
}
let handleUnlock = () => Promise.resolve()
let cacheReasonOverride
let isForegroundRevalidate = false
if (cacheKey && staticGenerationStore.incrementalCache) {
handleUnlock =
await staticGenerationStore.incrementalCache.lock(cacheKey)
const entry = staticGenerationStore.isOnDemandRevalidate
? null
: await staticGenerationStore.incrementalCache.get(cacheKey, {
kindHint: 'fetch',
revalidate: finalRevalidate,
fetchUrl,
fetchIdx,
tags,
softTags: implicitTags,
})
if (entry) {
await handleUnlock()
} else {
// in dev, incremental cache response will be null in case the browser adds `cache-control: no-cache` in the request headers
cacheReasonOverride = 'cache-control: no-cache (hard refresh)'
}
if (entry?.value && entry.value.kind === 'FETCH') {
// when stale and is revalidating we wait for fresh data
// so the revalidated entry has the updated data
if (staticGenerationStore.isRevalidate && entry.isStale) {
isForegroundRevalidate = true
} else {
if (entry.isStale) {
staticGenerationStore.pendingRevalidates ??= {}
if (!staticGenerationStore.pendingRevalidates[cacheKey]) {
staticGenerationStore.pendingRevalidates[cacheKey] =
doOriginalFetch(true)
.catch(console.error)
.finally(() => {
staticGenerationStore.pendingRevalidates ??= {}
delete staticGenerationStore.pendingRevalidates[
cacheKey || ''
]
})
}
}
const resData = entry.value.data
trackFetchMetric(staticGenerationStore, {
start: fetchStart,
url: fetchUrl,
cacheReason,
cacheStatus: 'hit',
status: resData.status || 200,
method: init?.method || 'GET',
})
const response = new Response(
Buffer.from(resData.body, 'base64'),
{
headers: resData.headers,
status: resData.status,
}
)
Object.defineProperty(response, 'url', {
value: entry.value.data.url,
})
return response
}
}
}
if (
staticGenerationStore.isStaticGeneration &&
init &&
typeof init === 'object'
) {
const { cache } = init
// Delete `cache` property as Cloudflare Workers will throw an error
if (isEdgeRuntime) delete init.cache
if (cache === 'no-store') {
// If enabled, we should bail out of static generation.
markCurrentScopeAsDynamic(
staticGenerationStore,
`no-store fetch ${input}${
staticGenerationStore.urlPathname
? ` ${staticGenerationStore.urlPathname}`
: ''
}`
)
}
const hasNextConfig = 'next' in init
const { next = {} } = init
if (
typeof next.revalidate === 'number' &&
(typeof staticGenerationStore.revalidate === 'undefined' ||
(typeof staticGenerationStore.revalidate === 'number' &&
next.revalidate < staticGenerationStore.revalidate))
) {
if (next.revalidate === 0) {
// If enabled, we should bail out of static generation.
markCurrentScopeAsDynamic(
staticGenerationStore,
`revalidate: 0 fetch ${input}${
staticGenerationStore.urlPathname
? ` ${staticGenerationStore.urlPathname}`
: ''
}`
)
}
if (!staticGenerationStore.forceStatic || next.revalidate !== 0) {
staticGenerationStore.revalidate = next.revalidate
}
}
if (hasNextConfig) delete init.next
}
// if we are revalidating the whole page via time or on-demand and
// the fetch cache entry is stale we should still de-dupe the
// origin hit if it's a cache-able entry
if (cacheKey && isForegroundRevalidate) {
staticGenerationStore.pendingRevalidates ??= {}
const pendingRevalidate =
staticGenerationStore.pendingRevalidates[cacheKey]
if (pendingRevalidate) {
const res: Response = await pendingRevalidate
return res.clone()
}
return (staticGenerationStore.pendingRevalidates[cacheKey] =
doOriginalFetch(true, cacheReasonOverride).finally(async () => {
staticGenerationStore.pendingRevalidates ??= {}
delete staticGenerationStore.pendingRevalidates[cacheKey || '']
await handleUnlock()
}))
} else {
return doOriginalFetch(false, cacheReasonOverride).finally(
handleUnlock
)
}
}
)
}
// Attach the necessary properties to the patched fetch function.
patched.__nextPatched = true as const
patched.__nextGetStaticStore = () => staticGenerationAsyncStorage
patched._nextOriginalFetch = originFetch
return patched
}
// we patch fetch to collect cache information used for
// determining if a page is static or not
export function patchFetch(options: PatchableModule) {
// If we've already patched fetch, we should not patch it again.
if (isPatchedFetch(globalThis.fetch)) return
// Grab the original fetch function. We'll attach this so we can use it in
// the patched fetch function.
const original = createDedupeFetch(globalThis.fetch)
// Set the global fetch to the patched fetch.
globalThis.fetch = createPatchedFetcher(original, options)
}