Skip to content

Commit 78e260e

Browse files
owjs3901devfive
andauthored
fix: route Pages navigation to static RSC files (#30)
Co-authored-by: devfive <devfive@devfive.kr>
1 parent 5b59593 commit 78e260e

1 file changed

Lines changed: 39 additions & 3 deletions

File tree

packages/app/src/lib/mock-api.ts

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -658,10 +658,41 @@ function mockResponse(url: URL, method: string, init?: RequestInit): Response {
658658
)
659659
}
660660

661-
function normalizeStaticRscResponse(url: URL, response: Response): Response {
661+
function staticRscRequestUrl(
662+
input: RequestInfo | URL,
663+
init: RequestInit | undefined,
664+
url: URL,
665+
): URL | null {
666+
if (
667+
url.origin !== window.location.origin ||
668+
(DEMO_BASE_PATH !== '' &&
669+
url.pathname !== DEMO_BASE_PATH &&
670+
!url.pathname.startsWith(`${DEMO_BASE_PATH}/`))
671+
) {
672+
return null
673+
}
674+
675+
const headers = new Headers(input instanceof Request ? input.headers : {})
676+
new Headers(init?.headers).forEach((value, name) => headers.set(name, value))
677+
if (
678+
headers.get('RSC') !== '1' &&
679+
!headers.get('Accept')?.includes('text/x-component')
680+
) {
681+
return null
682+
}
683+
684+
const staticUrl = new URL(url)
685+
if (!staticUrl.pathname.endsWith('.rsc')) {
686+
staticUrl.pathname = staticUrl.pathname.endsWith('/')
687+
? `${staticUrl.pathname}index.rsc`
688+
: `${staticUrl.pathname}.rsc`
689+
}
690+
return staticUrl
691+
}
692+
693+
function normalizeStaticRscResponse(response: Response): Response {
662694
if (
663695
!response.ok ||
664-
!url.pathname.endsWith('.rsc') ||
665696
response.headers.get('Content-Type')?.startsWith('text/x-component')
666697
) {
667698
return response
@@ -698,7 +729,12 @@ export function installMockApi(): void {
698729
) {
699730
return mockResponse(url, method, init)
700731
}
701-
return normalizeStaticRscResponse(url, await nativeFetch(input, init))
732+
const staticRscUrl = staticRscRequestUrl(input, init, url)
733+
if (staticRscUrl === null) return nativeFetch(input, init)
734+
735+
const staticInput =
736+
input instanceof Request ? new Request(staticRscUrl, input) : staticRscUrl
737+
return normalizeStaticRscResponse(await nativeFetch(staticInput, init))
702738
}
703739
}
704740

0 commit comments

Comments
 (0)