File size: 5,155 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import path from 'path'
import fs from 'fs/promises'
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import {
  PAGES_MANIFEST,
  APP_PATHS_MANIFEST,
} from '../../../shared/lib/constants'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'

export type PagesManifest = { [page: string]: string }

export let edgeServerPages = {}
export let nodeServerPages = {}
export let edgeServerAppPaths = {}
export let nodeServerAppPaths = {}

// This plugin creates a pages-manifest.json from page entrypoints.
// This is used for mapping paths like `/` to `.next/server/static/<buildid>/pages/index.js` when doing SSR
// It's also used by next export to provide defaultPathMap
export default class PagesManifestPlugin
  implements webpack.WebpackPluginInstance
{
  dev: boolean
  distDir?: string
  isEdgeRuntime: boolean
  appDirEnabled: boolean

  constructor({
    dev,
    distDir,
    isEdgeRuntime,
    appDirEnabled,
  }: {
    dev: boolean
    distDir?: string
    isEdgeRuntime: boolean
    appDirEnabled: boolean
  }) {
    this.dev = dev
    this.distDir = distDir
    this.isEdgeRuntime = isEdgeRuntime
    this.appDirEnabled = appDirEnabled
  }

  async createAssets(compilation: any) {
    const entrypoints = compilation.entrypoints
    const pages: PagesManifest = {}
    const appPaths: PagesManifest = {}

    for (const entrypoint of entrypoints.values()) {
      const pagePath = getRouteFromEntrypoint(
        entrypoint.name,
        this.appDirEnabled
      )

      if (!pagePath) {
        continue
      }

      const files = entrypoint
        .getFiles()
        .filter(
          (file: string) =>
            !file.includes('webpack-runtime') &&
            !file.includes('webpack-api-runtime') &&
            file.endsWith('.js')
        )

      // Skip entries which are empty
      if (!files.length) {
        continue
      }
      // Write filename, replace any backslashes in path (on windows) with forwardslashes for cross-platform consistency.
      let file = files[files.length - 1]

      if (!this.dev) {
        if (!this.isEdgeRuntime) {
          file = file.slice(3)
        }
      }
      file = normalizePathSep(file)

      if (entrypoint.name.startsWith('app/')) {
        appPaths[pagePath] = file
      } else {
        pages[pagePath] = file
      }
    }

    // This plugin is used by both the Node server and Edge server compilers,
    // we need to merge both pages to generate the full manifest.
    if (this.isEdgeRuntime) {
      edgeServerPages = pages
      edgeServerAppPaths = appPaths
    } else {
      nodeServerPages = pages
      nodeServerAppPaths = appPaths
    }

    // handle parallel compilers writing to the same
    // manifest path by merging existing manifest with new
    const writeMergedManifest = async (
      manifestPath: string,
      entries: Record<string, string>
    ) => {
      await fs.mkdir(path.dirname(manifestPath), { recursive: true })
      await fs.writeFile(
        manifestPath,
        JSON.stringify(
          {
            ...(await fs
              .readFile(manifestPath, 'utf8')
              .then((res) => JSON.parse(res))
              .catch(() => ({}))),
            ...entries,
          },
          null,
          2
        )
      )
    }

    if (this.distDir) {
      const pagesManifestPath = path.join(
        this.distDir,
        'server',
        PAGES_MANIFEST
      )
      await writeMergedManifest(pagesManifestPath, {
        ...edgeServerPages,
        ...nodeServerPages,
      })
    } else {
      const pagesManifestPath =
        (!this.dev && !this.isEdgeRuntime ? '../' : '') + PAGES_MANIFEST
      compilation.emitAsset(
        pagesManifestPath,
        new sources.RawSource(
          JSON.stringify(
            {
              ...edgeServerPages,
              ...nodeServerPages,
            },
            null,
            2
          )
        )
      )
    }

    if (this.appDirEnabled) {
      if (this.distDir) {
        const appPathsManifestPath = path.join(
          this.distDir,
          'server',
          APP_PATHS_MANIFEST
        )
        await writeMergedManifest(appPathsManifestPath, {
          ...edgeServerAppPaths,
          ...nodeServerAppPaths,
        })
      } else {
        compilation.emitAsset(
          (!this.dev && !this.isEdgeRuntime ? '../' : '') + APP_PATHS_MANIFEST,
          new sources.RawSource(
            JSON.stringify(
              {
                ...edgeServerAppPaths,
                ...nodeServerAppPaths,
              },
              null,
              2
            )
          ) as unknown as webpack.sources.RawSource
        )
      }
    }
  }

  apply(compiler: webpack.Compiler): void {
    compiler.hooks.make.tap('NextJsPagesManifest', (compilation) => {
      compilation.hooks.processAssets.tapPromise(
        {
          name: 'NextJsPagesManifest',
          stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
        },
        () => this.createAssets(compilation)
      )
    })
  }
}