File size: 2,039 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
import type webpack from 'webpack'
import { getModuleBuildInfo } from './get-module-build-info'
import { stringifyRequest } from '../stringify-request'
import type { MiddlewareConfig } from '../../analysis/get-page-static-info'

export type EdgeFunctionLoaderOptions = {
  absolutePagePath: string
  page: string
  rootDir: string
  preferredRegion: string | string[] | undefined
  middlewareConfig: string
}

const nextEdgeFunctionLoader: webpack.LoaderDefinitionFunction<EdgeFunctionLoaderOptions> =
  function nextEdgeFunctionLoader(this) {
    const {
      absolutePagePath,
      page,
      rootDir,
      preferredRegion,
      middlewareConfig: middlewareConfigBase64,
    }: EdgeFunctionLoaderOptions = this.getOptions()
    const stringifiedPagePath = stringifyRequest(this, absolutePagePath)
    const buildInfo = getModuleBuildInfo(this._module as any)
    const middlewareConfig: MiddlewareConfig = JSON.parse(
      Buffer.from(middlewareConfigBase64, 'base64').toString()
    )
    buildInfo.route = {
      page: page || '/',
      absolutePagePath,
      preferredRegion,
      middlewareConfig,
    }
    buildInfo.nextEdgeApiFunction = {
      page: page || '/',
    }
    buildInfo.rootDir = rootDir

    return `
        import 'next/dist/esm/server/web/globals'
        import { adapter } from 'next/dist/esm/server/web/adapter'
        import { IncrementalCache } from 'next/dist/esm/server/lib/incremental-cache'
        import { wrapApiHandler } from 'next/dist/esm/server/api-utils'

        import handler from ${stringifiedPagePath}

        if (typeof handler !== 'function') {
          throw new Error('The Edge Function "pages${page}" must export a \`default\` function');
        }

        export default function nHandler (opts) {
          return adapter({
              ...opts,
              IncrementalCache,
              page: ${JSON.stringify(page)},
              handler: wrapApiHandler(${JSON.stringify(page)}, handler),
          })
        }
    `
  }

export default nextEdgeFunctionLoader