File size: 7,132 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
import { webpack, sources } from 'next/dist/compiled/webpack/webpack'
import getRouteFromEntrypoint from '../../../server/get-route-from-entrypoint'
import { NEXT_FONT_MANIFEST } from '../../../shared/lib/constants'
import { traverseModules } from '../utils'
import path from 'path'

export type NextFontManifest = {
  pages: {
    [path: string]: string[]
  }
  app: {
    [entry: string]: string[]
  }
  appUsingSizeAdjust: boolean
  pagesUsingSizeAdjust: boolean
}
const PLUGIN_NAME = 'NextFontManifestPlugin'

/**
 * When calling font functions with next/font, you can specify if you'd like the font to be preloaded (true by default).
 * e.g.: const inter = Inter({ subsets: ['latin'], preload: true })
 *
 * In that case, next-font-loader will emit the font file as [name].p.[ext] instead of [name].[ext]
 * This function returns those files from an array that can include both preloaded and non-preloaded files.
 */
function getPreloadedFontFiles(fontFiles: string[]) {
  return fontFiles.filter((file: string) =>
    /\.p\.(woff|woff2|eot|ttf|otf)$/.test(file)
  )
}

/**
 * Similarly to getPreloadedFontFiles, but returns true if some of the files includes -s in the name.
 * This means that a font is using size adjust in its fallback font.
 * This was added to enable adding data-size-adjust="true" to the dom, used by the Google Aurora team to collect statistics.
 */
function getPageIsUsingSizeAdjust(fontFiles: string[]) {
  return fontFiles.some((file) => file.includes('-s'))
}

/**
 * The NextFontManifestPlugin collects all font files emitted by next-font-loader and creates a manifest file.
 * The manifest file is used in the Next.js render functions (_document.tsx for pages/ and app-render for app/) to add preload tags for the font files.
 * We only want to att preload fonts that are used by the current route.
 *
 * For pages/ the plugin finds the fonts imported in the entrypoint chunks and creates a map:
 * { [route]: fontFile[] }
 * When rendering the app in _document.tsx, it gets the font files to preload: manifest.pages[currentRouteBeingRendered].
 *
 * For app/, the manifest is a bit different.
 * Instead of creating a map of route to font files, it creates a map of the webpack module request to font files.
 * { [webpackModuleRequest]: fontFile[]]}
 * When creating the component tree in app-render it looks for font files to preload: manifest.app[moduleBeingRendered]
 */
export class NextFontManifestPlugin {
  private appDir: undefined | string

  constructor(options: { appDir: undefined | string }) {
    this.appDir = options.appDir
  }

  apply(compiler: webpack.Compiler) {
    compiler.hooks.make.tap(PLUGIN_NAME, (compilation) => {
      // In this stage the font files are emitted and we can collect all files emitted by each chunkGroup (entry).
      compilation.hooks.processAssets.tap(
        {
          name: PLUGIN_NAME,
          stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
        },
        () => {
          const nextFontManifest: NextFontManifest = {
            pages: {},
            app: {},
            appUsingSizeAdjust: false,
            pagesUsingSizeAdjust: false,
          }

          if (this.appDir) {
            const appDirBase = path.dirname(this.appDir) + path.sep

            // After all modules are created, we collect the modules that was created by next-font-loader.
            traverseModules(
              compilation,
              (mod, _chunk, chunkGroup) => {
                if (mod?.request?.includes('/next-font-loader/index.js?')) {
                  if (!mod.buildInfo?.assets) return

                  const chunkEntryName = (appDirBase + chunkGroup.name).replace(
                    /[\\/]/g,
                    path.sep
                  )

                  const modAssets = Object.keys(mod.buildInfo.assets)
                  const fontFiles: string[] = modAssets.filter((file: string) =>
                    /\.(woff|woff2|eot|ttf|otf)$/.test(file)
                  )

                  // Look if size-adjust fallback font is being used
                  if (!nextFontManifest.appUsingSizeAdjust) {
                    nextFontManifest.appUsingSizeAdjust =
                      getPageIsUsingSizeAdjust(fontFiles)
                  }

                  const preloadedFontFiles = getPreloadedFontFiles(fontFiles)

                  // Add an entry of the module's font files in the manifest.
                  // We'll add an entry even if no files should preload.
                  // When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
                  if (fontFiles.length > 0) {
                    if (!nextFontManifest.app[chunkEntryName]) {
                      nextFontManifest.app[chunkEntryName] = []
                    }
                    nextFontManifest.app[chunkEntryName].push(
                      ...preloadedFontFiles
                    )
                  }
                }
              },
              (chunkGroup) => {
                // Only loop through entrypoints that are under app/.
                return !!chunkGroup.name?.startsWith('app/')
              }
            )
          }

          // Look at all the entrypoints created for pages/.
          for (const entrypoint of compilation.entrypoints.values()) {
            const pagePath = getRouteFromEntrypoint(entrypoint.name!)

            if (!pagePath) {
              continue
            }

            // Get font files from the chunks included in the entrypoint.
            const fontFiles: string[] = entrypoint.chunks
              .flatMap((chunk: any) => [...chunk.auxiliaryFiles])
              .filter((file: string) =>
                /\.(woff|woff2|eot|ttf|otf)$/.test(file)
              )

            // Look if size-adjust fallback font is being used
            if (!nextFontManifest.pagesUsingSizeAdjust) {
              nextFontManifest.pagesUsingSizeAdjust =
                getPageIsUsingSizeAdjust(fontFiles)
            }

            const preloadedFontFiles = getPreloadedFontFiles(fontFiles)

            // Add an entry of the route's font files in the manifest.
            // We'll add an entry even if no files should preload.
            // When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
            if (fontFiles.length > 0) {
              nextFontManifest.pages[pagePath] = preloadedFontFiles
            }
          }

          const manifest = JSON.stringify(nextFontManifest, null)
          // Create manifest for edge
          compilation.emitAsset(
            `server/${NEXT_FONT_MANIFEST}.js`,
            new sources.RawSource(
              `self.__NEXT_FONT_MANIFEST=${JSON.stringify(manifest)}`
            ) as unknown as webpack.sources.RawSource
          )

          // Create manifest for server
          compilation.emitAsset(
            `server/${NEXT_FONT_MANIFEST}.json`,
            new sources.RawSource(
              manifest
            ) as unknown as webpack.sources.RawSource
          )
        }
      )
    })
    return
  }
}