1+ import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js" ;
2+ import type { CodePatcher } from "@opennextjs/aws/build/patch/codePatcher" ;
3+ import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js" ;
4+
5+ const inlineChunksRule = `
6+ rule:
7+ kind: call_expression
8+ pattern: require(resolved)
9+ fix:
10+ requireChunk(chunkPath)
11+ ` ;
12+
13+ export const inlineChunksPatch : CodePatcher = {
14+ name : "inline-turbopack-chunks" ,
15+ patches : [
16+ {
17+ versions : ">=16.0.0" ,
18+ pathFilter : getCrossPlatformPathRegex (
19+ String . raw `\[turbopack\]_runtime\.js$` ,
20+ {
21+ escape : false ,
22+ }
23+ ) ,
24+ contentFilter : / l o a d R u n t i m e C h u n k P a t h / ,
25+ patchCode : async ( { code, tracedFiles } ) => {
26+ const patched = patchCode ( code , inlineChunksRule ) ;
27+
28+ return `${ patched } \n${ inlineChunksFn ( tracedFiles ) } ` ;
29+ } ,
30+ } ,
31+ ] ,
32+ } ;
33+
34+ function getInlinableChunks ( tracedFiles : string [ ] ) {
35+ const chunks = new Set < string > ( ) ;
36+ for ( const file of tracedFiles ) {
37+ if ( file . includes ( ".next/server/chunks/" ) && ! file . includes ( "[turbopack]_runtime.js" ) ) {
38+ chunks . add ( file ) ;
39+ }
40+ }
41+ return chunks ;
42+ }
43+
44+ function inlineChunksFn ( tracedFiles : string [ ] ) {
45+ // From the outputs, we extract every chunks
46+ const chunks = getInlinableChunks ( tracedFiles ) ;
47+ return `
48+ function requireChunk(chunkPath) {
49+ switch(chunkPath) {
50+ ${ Array . from ( chunks ) . map ( chunk => ` case "${
51+ // we only want the path after /path/to/.next/
52+ chunk . replace ( / .* \. n e x t \/ / , "" )
53+ } ": return require("${ chunk } ");`) . join ( "\n" ) }
54+ default:
55+ throw new Error(\`Not found \${chunkPath}\`);
56+ }
57+ }
58+ ` ;
59+ }
0 commit comments