File size: 8,796 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
Copyright (c) 2017 The swc Project Developers

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

import type { NextConfig } from '../../../types'
import { type WebpackLayerName, WEBPACK_LAYERS } from '../../../lib/constants'
import { isWasm, transform } from '../../swc'
import { getLoaderSWCOptions } from '../../swc/options'
import path, { isAbsolute } from 'path'
import { babelIncludeRegexes } from '../../webpack-config'
import { isResourceInPackages } from '../../handle-externals'
import type { TelemetryLoaderContext } from '../plugins/telemetry-plugin/telemetry-plugin'
import {
  updateTelemetryLoaderCtxFromTransformOutput,
  type SwcTransformTelemetryOutput,
} from '../plugins/telemetry-plugin/update-telemetry-loader-context-from-swc'
import type { LoaderContext } from 'webpack'
import {
  COMPILER_NAMES,
  type CompilerNameValues,
} from '../../../shared/lib/constants'

const maybeExclude = (
  excludePath: string,
  transpilePackages: string[]
): boolean => {
  if (babelIncludeRegexes.some((r) => r.test(excludePath))) {
    return false
  }

  const shouldBeBundled = isResourceInPackages(excludePath, transpilePackages)
  if (shouldBeBundled) return false

  return excludePath.includes('node_modules')
}

export interface SWCLoaderOptions {
  rootDir: string
  isServer: boolean
  compilerType: CompilerNameValues
  pagesDir?: string
  appDir?: string
  hasReactRefresh: boolean
  optimizeServerReact?: boolean
  nextConfig: NextConfig
  jsConfig: any
  supportedBrowsers: string[] | undefined
  swcCacheDir: string
  serverComponents?: boolean
  serverReferenceHashSalt: string
  bundleLayer?: WebpackLayerName
  esm?: boolean
  transpilePackages?: string[]
}

// these are exact code conditions checked
// for to force transpiling a `node_module`
const FORCE_TRANSPILE_CONDITIONS =
  /next\/font|next\/dynamic|use server|use client|use cache/
// same as above, but including `import(...)`.
// (note the optional whitespace: `import  (...)` is also syntactically valid)
const FORCE_TRANSPILE_CONDITIONS_WITH_IMPORT = new RegExp(
  String.raw`(?:${FORCE_TRANSPILE_CONDITIONS.source})|import\s*\(`
)

async function loaderTransform(
  this: LoaderContext<SWCLoaderOptions> & TelemetryLoaderContext,
  source?: string,
  inputSourceMap?: any
) {
  // Make the loader async
  const filename = this.resourcePath

  // Ensure `.d.ts` are not processed.
  if (filename.endsWith('.d.ts')) {
    return [source, inputSourceMap]
  }

  let loaderOptions: SWCLoaderOptions = this.getOptions() || {}
  const shouldMaybeExclude = maybeExclude(
    filename,
    loaderOptions.transpilePackages || []
  )

  const trackDynamicImports = shouldTrackDynamicImports(loaderOptions)

  if (shouldMaybeExclude) {
    if (!source) {
      throw new Error(`Invariant might be excluded but missing source`)
    }

    const forceTranspileConditions = trackDynamicImports
      ? FORCE_TRANSPILE_CONDITIONS_WITH_IMPORT
      : FORCE_TRANSPILE_CONDITIONS

    if (!forceTranspileConditions.test(source)) {
      return [source, inputSourceMap]
    }
  }

  const {
    isServer,
    rootDir,
    pagesDir,
    appDir,
    hasReactRefresh,
    nextConfig,
    jsConfig,
    supportedBrowsers,
    swcCacheDir,
    serverComponents,
    serverReferenceHashSalt,
    bundleLayer,
    esm,
  } = loaderOptions
  const isPageFile = pagesDir ? filename.startsWith(pagesDir) : false
  const relativeFilePathFromRoot = path.relative(rootDir, filename)

  const swcOptions = getLoaderSWCOptions({
    pagesDir,
    appDir,
    filename,
    isServer,
    isPageFile,
    development:
      this.mode === 'development' ||
      !!nextConfig.experimental?.allowDevelopmentBuild,
    isCacheComponents: nextConfig.experimental?.cacheComponents,
    hasReactRefresh,
    modularizeImports: nextConfig?.modularizeImports,
    optimizePackageImports: nextConfig?.experimental?.optimizePackageImports,
    swcPlugins: nextConfig?.experimental?.swcPlugins,
    compilerOptions: nextConfig?.compiler,
    optimizeServerReact: nextConfig?.experimental?.optimizeServerReact,
    jsConfig,
    supportedBrowsers,
    swcCacheDir,
    relativeFilePathFromRoot,
    serverComponents,
    serverReferenceHashSalt,
    bundleLayer,
    esm,
    cacheHandlers: nextConfig.experimental?.cacheHandlers,
    useCacheEnabled: nextConfig.experimental?.useCache,
    trackDynamicImports,
  })

  const programmaticOptions = {
    ...swcOptions,
    filename,
    inputSourceMap: inputSourceMap ? JSON.stringify(inputSourceMap) : undefined,

    // Set the default sourcemap behavior based on Webpack's mapping flag,
    sourceMaps: this.sourceMap,
    inlineSourcesContent: this.sourceMap,

    // Ensure that Webpack will get a full absolute path in the sourcemap
    // so that it can properly map the module back to its internal cached
    // modules.
    sourceFileName: filename,
  }

  if (!programmaticOptions.inputSourceMap) {
    delete programmaticOptions.inputSourceMap
  }

  // auto detect development mode
  if (
    this.mode &&
    programmaticOptions.jsc &&
    programmaticOptions.jsc.transform &&
    programmaticOptions.jsc.transform.react &&
    !Object.prototype.hasOwnProperty.call(
      programmaticOptions.jsc.transform.react,
      'development'
    )
  ) {
    programmaticOptions.jsc.transform.react.development =
      this.mode === 'development'
  }

  return transform(source as any, programmaticOptions).then(
    (
      output: {
        code: string
        map?: string
      } & SwcTransformTelemetryOutput
    ) => {
      updateTelemetryLoaderCtxFromTransformOutput(this, output)
      return [output.code, output.map ? JSON.parse(output.map) : undefined]
    }
  )
}

function shouldTrackDynamicImports(loaderOptions: SWCLoaderOptions): boolean {
  // we only need to track `import()` 1. in cacheComponents, 2. on the server (RSC and SSR)
  // (Note: logic duplicated in crates/next-core/src/next_server/transforms.rs)
  const { nextConfig, bundleLayer, compilerType } = loaderOptions
  return (
    !!nextConfig.experimental?.cacheComponents &&
    // NOTE: `server` means nodejs. `cacheComponents` is not supported in the edge runtime, so we want to exclude it.
    // (also, the code generated by the dynamic imports transform relies on `CacheSignal`, which uses nodejs-specific APIs)
    compilerType === COMPILER_NAMES.server &&
    (bundleLayer === WEBPACK_LAYERS.reactServerComponents ||
      bundleLayer === WEBPACK_LAYERS.serverSideRendering)
  )
}

const EXCLUDED_PATHS =
  /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|__virtual__)[\\/]/g

export function pitch(this: any) {
  const callback = this.async()
  let loaderOptions: SWCLoaderOptions = this.getOptions() || {}

  const shouldMaybeExclude = maybeExclude(
    this.resourcePath,
    loaderOptions.transpilePackages || []
  )

  ;(async () => {
    if (
      // if it might be excluded/no-op we can't use pitch loader
      !shouldMaybeExclude &&
      // TODO: investigate swc file reading in PnP mode?
      !process.versions.pnp &&
      !EXCLUDED_PATHS.test(this.resourcePath) &&
      this.loaders.length - 1 === this.loaderIndex &&
      isAbsolute(this.resourcePath) &&
      !(await isWasm())
    ) {
      this.addDependency(this.resourcePath)
      return loaderTransform.call(this)
    }
  })().then((r) => {
    if (r) return callback(null, ...r)
    callback()
  }, callback)
}

export default function swcLoader(
  this: any,
  inputSource: string,
  inputSourceMap: any
) {
  const callback = this.async()
  loaderTransform.call(this, inputSource, inputSourceMap).then(
    ([transformedSource, outputSourceMap]: any) => {
      callback(null, transformedSource, outputSourceMap || inputSourceMap)
    },
    (err: Error) => {
      callback(err)
    }
  )
}

// accept Buffers instead of strings
export const raw = true