| |
| import path from 'path' |
| import { pathToFileURL } from 'url' |
| import { arch, platform } from 'os' |
| import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples' |
| import * as Log from '../output/log' |
| import { getParserOptions } from './options' |
| import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure' |
| import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile' |
| import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc' |
| import type { |
| NextConfigComplete, |
| TurbopackLoaderItem, |
| TurbopackRuleConfigItem, |
| TurbopackRuleConfigItemOptions, |
| TurbopackRuleConfigItemOrShortcut, |
| } from '../../server/config-shared' |
| import { isDeepStrictEqual } from 'util' |
| import { type DefineEnvOptions, getDefineEnv } from '../define-env' |
| import { getReactCompilerLoader } from '../get-babel-loader-config' |
| import type { |
| NapiModuleGraphSnapshot, |
| NapiModuleGraphSnapshots, |
| NapiPartialProjectOptions, |
| NapiProjectOptions, |
| NapiSourceDiagnostic, |
| } from './generated-native' |
| import type { |
| Binding, |
| CompilationEvent, |
| DefineEnv, |
| Endpoint, |
| HmrIdentifiers, |
| Project, |
| ProjectOptions, |
| RawEntrypoints, |
| Route, |
| TurboEngineOptions, |
| TurbopackResult, |
| TurbopackStackFrame, |
| Update, |
| UpdateMessage, |
| WrittenEndpoint, |
| } from './types' |
| import { throwTurbopackInternalError } from '../../shared/lib/turbopack/internal-error' |
|
|
| type RawBindings = typeof import('./generated-native') |
| type RawWasmBindings = typeof import('./generated-wasm') & { |
| default?(): Promise<typeof import('./generated-wasm')> |
| } |
|
|
| const nextVersion = process.env.__NEXT_VERSION as string |
|
|
| const ArchName = arch() |
| const PlatformName = platform() |
|
|
| function infoLog(...args: any[]) { |
| if (process.env.NEXT_PRIVATE_BUILD_WORKER) { |
| return |
| } |
| if (process.env.DEBUG) { |
| Log.info(...args) |
| } |
| } |
|
|
| |
| |
| |
| export function getSupportedArchTriples(): Record<string, any> { |
| const { darwin, win32, linux, freebsd, android } = platformArchTriples |
|
|
| return { |
| darwin, |
| win32: { |
| arm64: win32.arm64, |
| ia32: win32.ia32.filter((triple) => triple.abi === 'msvc'), |
| x64: win32.x64.filter((triple) => triple.abi === 'msvc'), |
| }, |
| linux: { |
| |
| x64: linux.x64.filter((triple) => triple.abi !== 'gnux32'), |
| arm64: linux.arm64, |
| |
| arm: linux.arm, |
| }, |
| |
| freebsd: { |
| x64: freebsd.x64, |
| }, |
| android: { |
| arm64: android.arm64, |
| arm: android.arm, |
| }, |
| } |
| } |
|
|
| const triples = (() => { |
| const supportedArchTriples = getSupportedArchTriples() |
| const targetTriple = supportedArchTriples[PlatformName]?.[ArchName] |
|
|
| |
| if (targetTriple) { |
| return targetTriple |
| } |
|
|
| |
| |
| let rawTargetTriple = platformArchTriples[PlatformName]?.[ArchName] |
|
|
| if (rawTargetTriple) { |
| Log.warn( |
| `Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support` |
| ) |
| } else { |
| Log.warn( |
| `Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}` |
| ) |
| } |
|
|
| return [] |
| })() |
|
|
| |
| |
| |
| |
| |
| |
| const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS = |
| process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS |
|
|
| function checkVersionMismatch(pkgData: any) { |
| const version = pkgData.version |
|
|
| if (version && version !== nextVersion) { |
| Log.warn( |
| `Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match` |
| ) |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| const knownDefaultWasmFallbackTriples = [ |
| 'x86_64-unknown-freebsd', |
| 'aarch64-linux-android', |
| 'arm-linux-androideabi', |
| 'armv7-unknown-linux-gnueabihf', |
| 'i686-pc-windows-msvc', |
| |
| |
| ] |
|
|
| |
| |
| |
| let lastNativeBindingsLoadErrorCode: |
| | 'unknown' |
| | 'unsupported_target' |
| | string |
| | undefined = undefined |
| |
| let pendingBindings: Promise<Binding> |
| |
| |
| let nativeBindings: Binding |
| |
| let wasmBindings: Binding |
| let downloadWasmPromise: any |
| let swcTraceFlushGuard: any |
| let downloadNativeBindingsPromise: Promise<void> | undefined = undefined |
|
|
| export const lockfilePatchPromise: { cur?: Promise<void> } = {} |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| export async function loadBindings( |
| useWasmBinary: boolean = false |
| ): Promise<Binding> { |
| |
| if (!process.env.RUST_MIN_STACK) { |
| process.env.RUST_MIN_STACK = '8388608' |
| } |
|
|
| if (pendingBindings) { |
| return pendingBindings |
| } |
|
|
| if (process.env.NEXT_TEST_WASM) { |
| useWasmBinary = true |
| } |
|
|
| |
| |
| |
| if (process.stdout._handle != null) { |
| |
| process.stdout._handle.setBlocking?.(true) |
| } |
| if (process.stderr._handle != null) { |
| |
| process.stderr._handle.setBlocking?.(true) |
| } |
|
|
| pendingBindings = new Promise(async (resolve, _reject) => { |
| if (!lockfilePatchPromise.cur) { |
| |
| |
| lockfilePatchPromise.cur = patchIncorrectLockfile(process.cwd()).catch( |
| console.error |
| ) |
| } |
|
|
| let attempts: any[] = [] |
| const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM |
| const unsupportedPlatform = triples.some( |
| (triple: any) => |
| !!triple?.raw && knownDefaultWasmFallbackTriples.includes(triple.raw) |
| ) |
| const isWebContainer = process.versions.webcontainer |
| |
| |
| const shouldLoadWasmFallbackFirst = |
| (!disableWasmFallback && useWasmBinary) || |
| unsupportedPlatform || |
| isWebContainer |
|
|
| if (!unsupportedPlatform && useWasmBinary) { |
| Log.warn( |
| `experimental.useWasmBinary is not an option for supported platform ${PlatformName}/${ArchName} and will be ignored.` |
| ) |
| } |
|
|
| if (shouldLoadWasmFallbackFirst) { |
| lastNativeBindingsLoadErrorCode = 'unsupported_target' |
| const fallbackBindings = await tryLoadWasmWithFallback(attempts) |
| if (fallbackBindings) { |
| return resolve(fallbackBindings) |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| try { |
| return resolve(loadNative()) |
| } catch (a) { |
| if ( |
| Array.isArray(a) && |
| a.every((m) => m.includes('it was not installed')) |
| ) { |
| let fallbackBindings = await tryLoadNativeWithFallback(attempts) |
|
|
| if (fallbackBindings) { |
| return resolve(fallbackBindings) |
| } |
| } |
|
|
| attempts = attempts.concat(a) |
| } |
|
|
| |
| if (!shouldLoadWasmFallbackFirst && !disableWasmFallback) { |
| const fallbackBindings = await tryLoadWasmWithFallback(attempts) |
| if (fallbackBindings) { |
| return resolve(fallbackBindings) |
| } |
| } |
|
|
| logLoadFailure(attempts, true) |
| }) |
| return pendingBindings |
| } |
|
|
| async function tryLoadNativeWithFallback(attempts: Array<string>) { |
| const nativeBindingsDirectory = path.join( |
| path.dirname(require.resolve('next/package.json')), |
| 'next-swc-fallback' |
| ) |
|
|
| if (!downloadNativeBindingsPromise) { |
| downloadNativeBindingsPromise = downloadNativeNextSwc( |
| nextVersion, |
| nativeBindingsDirectory, |
| triples.map((triple: any) => triple.platformArchABI) |
| ) |
| } |
| await downloadNativeBindingsPromise |
|
|
| try { |
| return loadNative(nativeBindingsDirectory) |
| } catch (a: any) { |
| attempts.push(...[].concat(a)) |
| } |
|
|
| return undefined |
| } |
|
|
| |
| async function tryLoadWasmWithFallback( |
| attempts: any[] |
| ): Promise<Binding | undefined> { |
| try { |
| let bindings = await loadWasm('') |
| |
| eventSwcLoadFailure({ |
| wasm: 'enabled', |
| nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, |
| }) |
| return bindings |
| } catch (a: any) { |
| attempts.push(...[].concat(a)) |
| } |
|
|
| try { |
| |
| |
| |
| |
| const wasmDirectory = path.join( |
| path.dirname(require.resolve('next/package.json')), |
| 'wasm' |
| ) |
| if (!downloadWasmPromise) { |
| downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory) |
| } |
| await downloadWasmPromise |
| let bindings = await loadWasm(wasmDirectory) |
| |
| eventSwcLoadFailure({ |
| wasm: 'fallback', |
| nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, |
| }) |
|
|
| |
| |
| for (const attempt of attempts) { |
| Log.warn(attempt) |
| } |
| return bindings |
| } catch (a: any) { |
| attempts.push(...[].concat(a)) |
| } |
| } |
|
|
| function loadBindingsSync() { |
| let attempts: any[] = [] |
| try { |
| return loadNative() |
| } catch (a) { |
| attempts = attempts.concat(a) |
| } |
|
|
| |
| |
| if (wasmBindings) { |
| return wasmBindings |
| } |
|
|
| logLoadFailure(attempts) |
| throw new Error('Failed to load bindings', { cause: attempts }) |
| } |
|
|
| let loggingLoadFailure = false |
|
|
| function logLoadFailure(attempts: any, triedWasm = false) { |
| |
| if (loggingLoadFailure) return |
| loggingLoadFailure = true |
|
|
| for (let attempt of attempts) { |
| Log.warn(attempt) |
| } |
|
|
| |
| eventSwcLoadFailure({ |
| wasm: triedWasm ? 'failed' : undefined, |
| nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode, |
| }) |
| .then(() => lockfilePatchPromise.cur || Promise.resolve()) |
| .finally(() => { |
| Log.error( |
| `Failed to load SWC binary for ${PlatformName}/${ArchName}, see more info here: https://nextjs.org/docs/messages/failed-loading-swc` |
| ) |
| process.exit(1) |
| }) |
| } |
|
|
| type RustifiedEnv = { name: string; value: string }[] |
| type RustifiedOptionEnv = { name: string; value: string | undefined }[] |
|
|
| export function createDefineEnv({ |
| isTurbopack, |
| clientRouterFilters, |
| config, |
| dev, |
| distDir, |
| projectPath, |
| fetchCacheKeyPrefix, |
| hasRewrites, |
| middlewareMatchers, |
| rewrites, |
| }: Omit< |
| DefineEnvOptions, |
| 'isClient' | 'isNodeOrEdgeCompilation' | 'isEdgeServer' | 'isNodeServer' |
| >): DefineEnv { |
| let defineEnv: DefineEnv = { |
| client: [], |
| edge: [], |
| nodejs: [], |
| } |
|
|
| for (const variant of Object.keys(defineEnv) as (keyof typeof defineEnv)[]) { |
| defineEnv[variant] = rustifyOptionEnv( |
| getDefineEnv({ |
| isTurbopack, |
| clientRouterFilters, |
| config, |
| dev, |
| distDir, |
| projectPath, |
| fetchCacheKeyPrefix, |
| hasRewrites, |
| isClient: variant === 'client', |
| isEdgeServer: variant === 'edge', |
| isNodeServer: variant === 'nodejs', |
| middlewareMatchers, |
| rewrites, |
| }) |
| ) |
| } |
|
|
| return defineEnv |
| } |
|
|
| function rustifyEnv(env: Record<string, string>): RustifiedEnv { |
| return Object.entries(env) |
| .filter(([_, value]) => value != null) |
| .map(([name, value]) => ({ |
| name, |
| value, |
| })) |
| } |
|
|
| function rustifyOptionEnv( |
| env: Record<string, string | undefined> |
| ): RustifiedOptionEnv { |
| return Object.entries(env).map(([name, value]) => ({ |
| name, |
| value, |
| })) |
| } |
|
|
| |
| function bindingToApi( |
| binding: RawBindings, |
| _wasm: boolean |
| ): Binding['turbo']['createProject'] { |
| type NativeFunction<T> = ( |
| callback: (err: Error, value: T) => void |
| ) => Promise<{ __napiType: 'RootTask' }> |
|
|
| type NapiEndpoint = { __napiType: 'Endpoint' } |
|
|
| type NapiEntrypoints = { |
| routes: NapiRoute[] |
| middleware?: NapiMiddleware |
| instrumentation?: NapiInstrumentation |
| pagesDocumentEndpoint: NapiEndpoint |
| pagesAppEndpoint: NapiEndpoint |
| pagesErrorEndpoint: NapiEndpoint |
| } |
|
|
| type NapiMiddleware = { |
| endpoint: NapiEndpoint |
| runtime: 'nodejs' | 'edge' |
| matcher?: string[] |
| } |
|
|
| type NapiInstrumentation = { |
| nodeJs: NapiEndpoint |
| edge: NapiEndpoint |
| } |
|
|
| type NapiRoute = { |
| pathname: string |
| } & ( |
| | { |
| type: 'page' |
| htmlEndpoint: NapiEndpoint |
| dataEndpoint: NapiEndpoint |
| } |
| | { |
| type: 'page-api' |
| endpoint: NapiEndpoint |
| } |
| | { |
| type: 'app-page' |
| pages: { |
| originalName: string |
| htmlEndpoint: NapiEndpoint |
| rscEndpoint: NapiEndpoint |
| }[] |
| } |
| | { |
| type: 'app-route' |
| originalName: string |
| endpoint: NapiEndpoint |
| } |
| | { |
| type: 'conflict' |
| } |
| ) |
|
|
| const cancel = new (class Cancel extends Error {})() |
|
|
| |
| |
| |
| function invariant( |
| never: never, |
| computeMessage: (arg: any) => string |
| ): never { |
| throw new Error(`Invariant: ${computeMessage(never)}`) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function subscribe<T>( |
| useBuffer: boolean, |
| nativeFunction: |
| | NativeFunction<T> |
| | ((callback: (err: Error, value: T) => void) => Promise<void>) |
| ): AsyncIterableIterator<T> { |
| type BufferItem = |
| | { err: Error; value: undefined } |
| | { err: undefined; value: T } |
| |
| |
| let buffer: BufferItem[] = [] |
| |
| |
| let waiting: |
| | { |
| resolve: (value: T) => void |
| reject: (error: Error) => void |
| } |
| | undefined |
| let canceled = false |
|
|
| |
| |
| |
| function emitResult(err: Error | undefined, value: T | undefined) { |
| if (waiting) { |
| let { resolve, reject } = waiting |
| waiting = undefined |
| if (err) reject(err) |
| else resolve(value!) |
| } else { |
| const item = { err, value } as BufferItem |
| if (useBuffer) buffer.push(item) |
| else buffer[0] = item |
| } |
| } |
|
|
| async function* createIterator() { |
| const task = await nativeFunction(emitResult) |
| try { |
| while (!canceled) { |
| if (buffer.length > 0) { |
| const item = buffer.shift()! |
| if (item.err) throw item.err |
| yield item.value |
| } else { |
| |
| yield new Promise<T>((resolve, reject) => { |
| waiting = { resolve, reject } |
| }) |
| } |
| } |
| } catch (e) { |
| if (e === cancel) return |
| throw e |
| } finally { |
| if (task) { |
| binding.rootTaskDispose(task) |
| } |
| } |
| } |
|
|
| const iterator = createIterator() |
| iterator.return = async () => { |
| canceled = true |
| if (waiting) waiting.reject(cancel) |
| return { value: undefined, done: true } as IteratorReturnResult<never> |
| } |
| return iterator |
| } |
|
|
| async function rustifyProjectOptions( |
| options: ProjectOptions |
| ): Promise<NapiProjectOptions> { |
| return { |
| ...options, |
| nextConfig: await serializeNextConfig( |
| options.nextConfig, |
| path.join(options.rootPath, options.projectPath) |
| ), |
| jsConfig: JSON.stringify(options.jsConfig), |
| env: rustifyEnv(options.env), |
| } |
| } |
|
|
| async function rustifyPartialProjectOptions( |
| options: Partial<ProjectOptions> |
| ): Promise<NapiPartialProjectOptions> { |
| return { |
| ...options, |
| nextConfig: |
| options.nextConfig && |
| (await serializeNextConfig( |
| options.nextConfig, |
| path.join(options.rootPath!, options.projectPath!) |
| )), |
| jsConfig: options.jsConfig && JSON.stringify(options.jsConfig), |
| env: options.env && rustifyEnv(options.env), |
| } |
| } |
|
|
| class ProjectImpl implements Project { |
| private readonly _nativeProject: { __napiType: 'Project' } |
|
|
| constructor(nativeProject: { __napiType: 'Project' }) { |
| this._nativeProject = nativeProject |
| } |
|
|
| async update(options: Partial<ProjectOptions>) { |
| await binding.projectUpdate( |
| this._nativeProject, |
| await rustifyPartialProjectOptions(options) |
| ) |
| } |
|
|
| async writeAllEntrypointsToDisk( |
| appDirOnly: boolean |
| ): Promise<TurbopackResult<RawEntrypoints>> { |
| const napiEndpoints = (await binding.projectWriteAllEntrypointsToDisk( |
| this._nativeProject, |
| appDirOnly |
| )) as TurbopackResult<NapiEntrypoints> |
|
|
| return napiEntrypointsToRawEntrypoints(napiEndpoints) |
| } |
|
|
| async getEntrypoints() { |
| const napiEndpoints = (await binding.projectEntrypoints( |
| this._nativeProject |
| )) as TurbopackResult<NapiEntrypoints> |
|
|
| return napiEntrypointsToRawEntrypoints(napiEndpoints) |
| } |
|
|
| entrypointsSubscribe() { |
| const subscription = subscribe<TurbopackResult<NapiEntrypoints>>( |
| false, |
| async (callback) => |
| binding.projectEntrypointsSubscribe(this._nativeProject, callback) |
| ) |
| return (async function* () { |
| for await (const entrypoints of subscription) { |
| yield napiEntrypointsToRawEntrypoints(entrypoints) |
| } |
| })() |
| } |
|
|
| hmrEvents(identifier: string) { |
| return subscribe<TurbopackResult<Update>>(true, async (callback) => |
| binding.projectHmrEvents(this._nativeProject, identifier, callback) |
| ) |
| } |
|
|
| hmrIdentifiersSubscribe() { |
| return subscribe<TurbopackResult<HmrIdentifiers>>( |
| false, |
| async (callback) => |
| binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback) |
| ) |
| } |
|
|
| traceSource( |
| stackFrame: TurbopackStackFrame, |
| currentDirectoryFileUrl: string |
| ): Promise<TurbopackStackFrame | null> { |
| return binding.projectTraceSource( |
| this._nativeProject, |
| stackFrame, |
| currentDirectoryFileUrl |
| ) |
| } |
|
|
| getSourceForAsset(filePath: string): Promise<string | null> { |
| return binding.projectGetSourceForAsset(this._nativeProject, filePath) |
| } |
|
|
| getSourceMap(filePath: string): Promise<string | null> { |
| return binding.projectGetSourceMap(this._nativeProject, filePath) |
| } |
|
|
| getSourceMapSync(filePath: string): string | null { |
| return binding.projectGetSourceMapSync(this._nativeProject, filePath) |
| } |
|
|
| updateInfoSubscribe(aggregationMs: number) { |
| return subscribe<TurbopackResult<UpdateMessage>>(true, async (callback) => |
| binding.projectUpdateInfoSubscribe( |
| this._nativeProject, |
| aggregationMs, |
| callback |
| ) |
| ) |
| } |
|
|
| compilationEventsSubscribe(eventTypes?: string[]) { |
| return subscribe<TurbopackResult<CompilationEvent>>( |
| true, |
| async (callback) => { |
| binding.projectCompilationEventsSubscribe( |
| this._nativeProject, |
| callback, |
| eventTypes |
| ) |
| } |
| ) |
| } |
|
|
| moduleGraph(): Promise<TurbopackResult<NapiModuleGraphSnapshot>> { |
| return binding.projectModuleGraph(this._nativeProject) as Promise< |
| TurbopackResult<NapiModuleGraphSnapshot> |
| > |
| } |
|
|
| invalidatePersistentCache(): Promise<void> { |
| return binding.projectInvalidatePersistentCache(this._nativeProject) |
| } |
|
|
| shutdown(): Promise<void> { |
| return binding.projectShutdown(this._nativeProject) |
| } |
|
|
| onExit(): Promise<void> { |
| return binding.projectOnExit(this._nativeProject) |
| } |
| } |
|
|
| class EndpointImpl implements Endpoint { |
| private readonly _nativeEndpoint: { __napiType: 'Endpoint' } |
|
|
| constructor(nativeEndpoint: { __napiType: 'Endpoint' }) { |
| this._nativeEndpoint = nativeEndpoint |
| } |
|
|
| async writeToDisk(): Promise<TurbopackResult<WrittenEndpoint>> { |
| return (await binding.endpointWriteToDisk( |
| this._nativeEndpoint |
| )) as TurbopackResult<WrittenEndpoint> |
| } |
|
|
| async clientChanged(): Promise<AsyncIterableIterator<TurbopackResult<{}>>> { |
| const clientSubscription = subscribe<TurbopackResult>( |
| false, |
| async (callback) => |
| binding.endpointClientChangedSubscribe(this._nativeEndpoint, callback) |
| ) |
| await clientSubscription.next() |
| return clientSubscription |
| } |
|
|
| async serverChanged( |
| includeIssues: boolean |
| ): Promise<AsyncIterableIterator<TurbopackResult<{}>>> { |
| const serverSubscription = subscribe<TurbopackResult>( |
| false, |
| async (callback) => |
| binding.endpointServerChangedSubscribe( |
| this._nativeEndpoint, |
| includeIssues, |
| callback |
| ) |
| ) |
| await serverSubscription.next() |
| return serverSubscription |
| } |
|
|
| async moduleGraphs(): Promise<TurbopackResult<NapiModuleGraphSnapshots>> { |
| return binding.endpointModuleGraphs(this._nativeEndpoint) as Promise< |
| TurbopackResult<NapiModuleGraphSnapshots> |
| > |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| function augmentNextConfig( |
| originalNextConfig: NextConfigComplete, |
| projectPath: string |
| ): Record<string, any> { |
| let nextConfig = { ...(originalNextConfig as any) } |
|
|
| const reactCompilerOptions = nextConfig.experimental?.reactCompiler |
|
|
| |
| |
| if (reactCompilerOptions) { |
| const ruleKeys = ['*.ts', '*.js', '*.jsx', '*.tsx'] |
| if ( |
| Object.keys(nextConfig?.turbopack?.rules ?? []).some((key) => |
| ruleKeys.includes(key) |
| ) |
| ) { |
| Log.warn( |
| `The React Compiler cannot be enabled automatically because 'turbopack.rules' contains a rule for '*.ts', '*.js', '*.jsx', and '*.tsx'. Remove this rule, or add 'babel-loader' and 'babel-plugin-react-compiler' to the Turbopack configuration manually.` |
| ) |
| } else { |
| if (!nextConfig.turbopack) { |
| nextConfig.turbopack = {} |
| } |
|
|
| if (!nextConfig.turbopack.rules) { |
| nextConfig.turbopack.rules = {} |
| } |
|
|
| for (const key of ['*.ts', '*.js', '*.jsx', '*.tsx']) { |
| nextConfig.turbopack.rules[key] = { |
| browser: { |
| foreign: false, |
| loaders: [ |
| getReactCompilerLoader( |
| originalNextConfig.experimental.reactCompiler, |
| projectPath, |
| nextConfig.dev, |
| false, |
| undefined |
| ), |
| ], |
| }, |
| } |
| } |
| } |
| } |
|
|
| return nextConfig |
| } |
|
|
| async function serializeNextConfig( |
| nextConfig: NextConfigComplete, |
| projectPath: string |
| ): Promise<string> { |
| |
| let nextConfigSerializable = augmentNextConfig(nextConfig, projectPath) |
|
|
| nextConfigSerializable.generateBuildId = |
| await nextConfig.generateBuildId?.() |
|
|
| |
| nextConfigSerializable.exportPathMap = {} |
| nextConfigSerializable.webpack = nextConfig.webpack && {} |
|
|
| if (nextConfigSerializable.experimental?.turbo?.rules) { |
| ensureLoadersHaveSerializableOptions( |
| nextConfigSerializable.turbopack?.rules |
| ) |
| } |
|
|
| nextConfigSerializable.modularizeImports = |
| nextConfigSerializable.modularizeImports |
| ? Object.fromEntries( |
| Object.entries<any>(nextConfigSerializable.modularizeImports).map( |
| ([mod, config]) => [ |
| mod, |
| { |
| ...config, |
| transform: |
| typeof config.transform === 'string' |
| ? config.transform |
| : Object.entries(config.transform).map(([key, value]) => [ |
| key, |
| value, |
| ]), |
| }, |
| ] |
| ) |
| ) |
| : undefined |
|
|
| |
| if (nextConfigSerializable.images.loaderFile) { |
| nextConfigSerializable.images = { |
| ...nextConfig.images, |
| loaderFile: |
| './' + path.relative(projectPath, nextConfig.images.loaderFile), |
| } |
| } |
|
|
| const conditions: (typeof nextConfig)['turbopack']['conditions'] = |
| nextConfigSerializable.turbopack?.conditions |
| if (conditions) { |
| type SerializedConditions = { |
| [key: string]: { |
| path: |
| | { type: 'regex'; value: { source: string; flags: string } } |
| | { type: 'glob'; value: string } |
| } |
| } |
|
|
| const serializedConditions: SerializedConditions = {} |
| for (const [key, value] of Object.entries(conditions)) { |
| serializedConditions[key] = { |
| ...value, |
| path: |
| value.path instanceof RegExp |
| ? { |
| type: 'regex', |
| value: { source: value.path.source, flags: value.path.flags }, |
| } |
| : { type: 'glob', value: value.path }, |
| } |
| } |
| nextConfigSerializable.turbopack.conditions = serializedConditions |
| } |
|
|
| return JSON.stringify(nextConfigSerializable, null, 2) |
| } |
|
|
| function ensureLoadersHaveSerializableOptions( |
| turbopackRules: Record<string, TurbopackRuleConfigItemOrShortcut> |
| ) { |
| for (const [glob, rule] of Object.entries(turbopackRules)) { |
| if (Array.isArray(rule)) { |
| checkLoaderItems(rule, glob) |
| } else { |
| checkConfigItem(rule, glob) |
| } |
| } |
|
|
| function checkConfigItem(rule: TurbopackRuleConfigItem, glob: string) { |
| if (!rule) return |
| if ('loaders' in rule) { |
| checkLoaderItems((rule as TurbopackRuleConfigItemOptions).loaders, glob) |
| } else { |
| for (const key in rule) { |
| const inner = rule[key] |
| if (typeof inner === 'object' && inner) { |
| checkConfigItem(inner, glob) |
| } |
| } |
| } |
| } |
|
|
| function checkLoaderItems( |
| loaderItems: TurbopackLoaderItem[], |
| glob: string |
| ) { |
| for (const loaderItem of loaderItems) { |
| if ( |
| typeof loaderItem !== 'string' && |
| !isDeepStrictEqual(loaderItem, JSON.parse(JSON.stringify(loaderItem))) |
| ) { |
| throw new Error( |
| `loader ${loaderItem.loader} for match "${glob}" does not have serializable options. Ensure that options passed are plain JavaScript objects and values.` |
| ) |
| } |
| } |
| } |
| } |
|
|
| function napiEntrypointsToRawEntrypoints( |
| entrypoints: TurbopackResult<NapiEntrypoints> |
| ): TurbopackResult<RawEntrypoints> { |
| const routes = new Map() |
| for (const { pathname, ...nativeRoute } of entrypoints.routes) { |
| let route: Route |
| const routeType = nativeRoute.type |
| switch (routeType) { |
| case 'page': |
| route = { |
| type: 'page', |
| htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint), |
| dataEndpoint: new EndpointImpl(nativeRoute.dataEndpoint), |
| } |
| break |
| case 'page-api': |
| route = { |
| type: 'page-api', |
| endpoint: new EndpointImpl(nativeRoute.endpoint), |
| } |
| break |
| case 'app-page': |
| route = { |
| type: 'app-page', |
| pages: nativeRoute.pages.map((page) => ({ |
| originalName: page.originalName, |
| htmlEndpoint: new EndpointImpl(page.htmlEndpoint), |
| rscEndpoint: new EndpointImpl(page.rscEndpoint), |
| })), |
| } |
| break |
| case 'app-route': |
| route = { |
| type: 'app-route', |
| originalName: nativeRoute.originalName, |
| endpoint: new EndpointImpl(nativeRoute.endpoint), |
| } |
| break |
| case 'conflict': |
| route = { |
| type: 'conflict', |
| } |
| break |
| default: |
| const _exhaustiveCheck: never = routeType |
| invariant( |
| nativeRoute, |
| () => `Unknown route type: ${_exhaustiveCheck}` |
| ) |
| } |
| routes.set(pathname, route) |
| } |
| const napiMiddlewareToMiddleware = (middleware: NapiMiddleware) => ({ |
| endpoint: new EndpointImpl(middleware.endpoint), |
| runtime: middleware.runtime, |
| matcher: middleware.matcher, |
| }) |
| const middleware = entrypoints.middleware |
| ? napiMiddlewareToMiddleware(entrypoints.middleware) |
| : undefined |
| const napiInstrumentationToInstrumentation = ( |
| instrumentation: NapiInstrumentation |
| ) => ({ |
| nodeJs: new EndpointImpl(instrumentation.nodeJs), |
| edge: new EndpointImpl(instrumentation.edge), |
| }) |
| const instrumentation = entrypoints.instrumentation |
| ? napiInstrumentationToInstrumentation(entrypoints.instrumentation) |
| : undefined |
|
|
| return { |
| routes, |
| middleware, |
| instrumentation, |
| pagesDocumentEndpoint: new EndpointImpl( |
| entrypoints.pagesDocumentEndpoint |
| ), |
| pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint), |
| pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint), |
| issues: entrypoints.issues, |
| diagnostics: entrypoints.diagnostics, |
| } |
| } |
|
|
| return async function createProject( |
| options: ProjectOptions, |
| turboEngineOptions |
| ) { |
| return new ProjectImpl( |
| await binding.projectNew( |
| await rustifyProjectOptions(options), |
| turboEngineOptions || {}, |
| { |
| throwTurbopackInternalError, |
| } |
| ) |
| ) |
| } |
| } |
|
|
| |
| async function loadWasmRawBindings(importPath = ''): Promise<RawWasmBindings> { |
| let attempts = [] |
|
|
| |
| |
| const testWasmDir = process.env.NEXT_TEST_WASM_DIR |
|
|
| if (testWasmDir) { |
| |
| const rawBindings = await import( |
| pathToFileURL(path.join(testWasmDir, 'wasm.js')).toString() |
| ) |
| infoLog(`next-swc build: wasm build ${testWasmDir}`) |
| return rawBindings |
| } else { |
| for (let pkg of ['@next/swc-wasm-nodejs', '@next/swc-wasm-web']) { |
| try { |
| let pkgPath = pkg |
|
|
| if (importPath) { |
| |
| pkgPath = path.join(importPath, pkg, 'wasm.js') |
| } |
| const importedRawBindings = await import( |
| pathToFileURL(pkgPath).toString() |
| ) |
| let rawBindings |
| if (pkg === '@next/swc-wasm-web') { |
| |
| |
| rawBindings = await importedRawBindings.default!() |
| } else { |
| rawBindings = importedRawBindings |
| } |
| infoLog(`next-swc build: wasm build ${pkg}`) |
| return rawBindings |
| } catch (e: any) { |
| |
| if (importPath) { |
| if (e?.code === 'ERR_MODULE_NOT_FOUND') { |
| attempts.push(`Attempted to load ${pkg}, but it was not installed`) |
| } else { |
| attempts.push( |
| `Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}` |
| ) |
| } |
| } |
| } |
| } |
| } |
|
|
| throw attempts |
| } |
|
|
| |
| async function loadWasm(importPath = '') { |
| const rawBindings = await loadWasmRawBindings(importPath) |
|
|
| function removeUndefined(obj: any): any { |
| |
| |
| |
| |
| if (typeof obj !== 'object' || obj === null) { |
| return obj |
| } |
| if (Array.isArray(obj)) { |
| return obj.map(removeUndefined) |
| } |
| const newObj: { [key: string]: any } = {} |
| for (const [k, v] of Object.entries(obj)) { |
| if (typeof v !== 'undefined') { |
| newObj[k] = removeUndefined(v) |
| } |
| } |
| return newObj |
| } |
|
|
| |
| |
| wasmBindings = { |
| css: { |
| lightning: { |
| transform: function (_options: any) { |
| throw new Error( |
| '`css.lightning.transform` is not supported by the wasm bindings.' |
| ) |
| }, |
| transformStyleAttr: function (_options: any) { |
| throw new Error( |
| '`css.lightning.transformStyleAttr` is not supported by the wasm bindings.' |
| ) |
| }, |
| }, |
| }, |
| isWasm: true, |
| transform(src: string, options: any): Promise<any> { |
| return rawBindings.transform(src.toString(), removeUndefined(options)) |
| }, |
| transformSync(src: string, options: any) { |
| return rawBindings.transformSync(src.toString(), removeUndefined(options)) |
| }, |
| minify(src: string, options: any): Promise<any> { |
| return rawBindings.minify(src.toString(), removeUndefined(options)) |
| }, |
| minifySync(src: string, options: any) { |
| return rawBindings.minifySync(src.toString(), removeUndefined(options)) |
| }, |
| parse(src: string, options: any): Promise<any> { |
| return rawBindings.parse(src.toString(), removeUndefined(options)) |
| }, |
| getTargetTriple() { |
| return undefined |
| }, |
| turbo: { |
| createProject( |
| _options: ProjectOptions, |
| _turboEngineOptions?: TurboEngineOptions | undefined |
| ): Promise<Project> { |
| throw new Error( |
| '`turbo.createProject` is not supported by the wasm bindings.' |
| ) |
| }, |
| startTurbopackTraceServer(_traceFilePath: string): void { |
| throw new Error( |
| '`turbo.startTurbopackTraceServer` is not supported by the wasm bindings.' |
| ) |
| }, |
| }, |
| mdx: { |
| compile(src: string, options: any) { |
| return rawBindings.mdxCompile( |
| src, |
| removeUndefined(getMdxOptions(options)) |
| ) |
| }, |
| compileSync(src: string, options: any) { |
| return rawBindings.mdxCompileSync( |
| src, |
| removeUndefined(getMdxOptions(options)) |
| ) |
| }, |
| }, |
| reactCompiler: { |
| isReactCompilerRequired(_filename: string) { |
| return Promise.resolve(true) |
| }, |
| }, |
| rspack: { |
| getModuleNamedExports(_resourcePath: string): Promise<string[]> { |
| throw new Error( |
| '`rspack.getModuleNamedExports` is not supported by the wasm bindings.' |
| ) |
| }, |
| warnForEdgeRuntime( |
| _source: string, |
| _isProduction: boolean |
| ): Promise<NapiSourceDiagnostic[]> { |
| throw new Error( |
| '`rspack.warnForEdgeRuntime` is not supported by the wasm bindings.' |
| ) |
| }, |
| }, |
| } |
| return wasmBindings |
| } |
|
|
| |
| |
| |
| |
| function loadNative(importPath?: string) { |
| if (nativeBindings) { |
| return nativeBindings |
| } |
|
|
| if (process.env.NEXT_TEST_WASM) { |
| throw new Error('cannot run loadNative when `NEXT_TEST_WASM` is set') |
| } |
|
|
| const customBindings: RawBindings = !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS |
| ? require(__INTERNAL_CUSTOM_TURBOPACK_BINDINGS) |
| : null |
| let bindings: RawBindings = customBindings |
| let attempts: any[] = [] |
|
|
| const NEXT_TEST_NATIVE_DIR = process.env.NEXT_TEST_NATIVE_DIR |
| for (const triple of triples) { |
| if (NEXT_TEST_NATIVE_DIR) { |
| try { |
| |
| bindings = require( |
| `${NEXT_TEST_NATIVE_DIR}/next-swc.${triple.platformArchABI}.node` |
| ) |
| infoLog( |
| 'next-swc build: local built @next/swc from NEXT_TEST_NATIVE_DIR' |
| ) |
| break |
| } catch (e) {} |
| } else { |
| try { |
| bindings = require( |
| `@next/swc/native/next-swc.${triple.platformArchABI}.node` |
| ) |
| infoLog('next-swc build: local built @next/swc') |
| break |
| } catch (e) {} |
| } |
| } |
|
|
| if (!bindings) { |
| for (const triple of triples) { |
| let pkg = importPath |
| ? path.join( |
| importPath, |
| `@next/swc-${triple.platformArchABI}`, |
| `next-swc.${triple.platformArchABI}.node` |
| ) |
| : `@next/swc-${triple.platformArchABI}` |
| try { |
| bindings = require(pkg) |
| if (!importPath) { |
| checkVersionMismatch(require(`${pkg}/package.json`)) |
| } |
| break |
| } catch (e: any) { |
| if (e?.code === 'MODULE_NOT_FOUND') { |
| attempts.push(`Attempted to load ${pkg}, but it was not installed`) |
| } else { |
| attempts.push( |
| `Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}` |
| ) |
| } |
| lastNativeBindingsLoadErrorCode = e?.code ?? 'unknown' |
| } |
| } |
| } |
|
|
| if (bindings) { |
| nativeBindings = { |
| isWasm: false, |
| transform(src: string, options: any) { |
| const isModule = |
| typeof src !== 'undefined' && |
| typeof src !== 'string' && |
| !Buffer.isBuffer(src) |
| options = options || {} |
|
|
| if (options?.jsc?.parser) { |
| options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript' |
| } |
|
|
| return bindings.transform( |
| isModule ? JSON.stringify(src) : src, |
| isModule, |
| toBuffer(options) |
| ) |
| }, |
|
|
| transformSync(src: string, options: any) { |
| if (typeof src === 'undefined') { |
| throw new Error( |
| "transformSync doesn't implement reading the file from filesystem" |
| ) |
| } else if (Buffer.isBuffer(src)) { |
| throw new Error( |
| "transformSync doesn't implement taking the source code as Buffer" |
| ) |
| } |
| const isModule = typeof src !== 'string' |
| options = options || {} |
|
|
| if (options?.jsc?.parser) { |
| options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript' |
| } |
|
|
| return bindings.transformSync( |
| isModule ? JSON.stringify(src) : src, |
| isModule, |
| toBuffer(options) |
| ) |
| }, |
|
|
| minify(src: string, options: any) { |
| return bindings.minify(Buffer.from(src), toBuffer(options ?? {})) |
| }, |
|
|
| minifySync(src: string, options: any) { |
| return bindings.minifySync(Buffer.from(src), toBuffer(options ?? {})) |
| }, |
|
|
| parse(src: string, options: any) { |
| return bindings.parse(src, toBuffer(options ?? {})) |
| }, |
|
|
| getTargetTriple: bindings.getTargetTriple, |
| initCustomTraceSubscriber: bindings.initCustomTraceSubscriber, |
| teardownTraceSubscriber: bindings.teardownTraceSubscriber, |
| turbo: { |
| createProject: bindingToApi(customBindings ?? bindings, false), |
| startTurbopackTraceServer(traceFilePath) { |
| Log.warn( |
| 'Turbopack trace server started. View trace at https://trace.nextjs.org' |
| ) |
| ;(customBindings ?? bindings).startTurbopackTraceServer(traceFilePath) |
| }, |
| }, |
| mdx: { |
| compile(src: string, options: any) { |
| return bindings.mdxCompile(src, toBuffer(getMdxOptions(options))) |
| }, |
| compileSync(src: string, options: any) { |
| bindings.mdxCompileSync(src, toBuffer(getMdxOptions(options))) |
| }, |
| }, |
| css: { |
| lightning: { |
| transform(transformOptions: any) { |
| return bindings.lightningCssTransform(transformOptions) |
| }, |
| transformStyleAttr(transformAttrOptions: any) { |
| return bindings.lightningCssTransformStyleAttribute( |
| transformAttrOptions |
| ) |
| }, |
| }, |
| }, |
| reactCompiler: { |
| isReactCompilerRequired: (filename: string) => { |
| return bindings.isReactCompilerRequired(filename) |
| }, |
| }, |
| rspack: { |
| getModuleNamedExports: function ( |
| resourcePath: string |
| ): Promise<string[]> { |
| return bindings.getModuleNamedExports(resourcePath) |
| }, |
| warnForEdgeRuntime: function ( |
| source: string, |
| isProduction: boolean |
| ): Promise<NapiSourceDiagnostic[]> { |
| return bindings.warnForEdgeRuntime(source, isProduction) |
| }, |
| }, |
| } |
| return nativeBindings |
| } |
|
|
| throw attempts |
| } |
|
|
| |
| |
| function getMdxOptions(options: any = {}) { |
| return { |
| ...options, |
| development: options.development ?? false, |
| jsx: options.jsx ?? false, |
| mdxType: options.mdxType ?? 'commonMark', |
| } |
| } |
|
|
| function toBuffer(t: any) { |
| return Buffer.from(JSON.stringify(t)) |
| } |
|
|
| export async function isWasm(): Promise<boolean> { |
| let bindings = await loadBindings() |
| return bindings.isWasm |
| } |
|
|
| export async function transform(src: string, options?: any): Promise<any> { |
| let bindings = await loadBindings() |
| return bindings.transform(src, options) |
| } |
|
|
| export function transformSync(src: string, options?: any): any { |
| let bindings = loadBindingsSync() |
| return bindings.transformSync(src, options) |
| } |
|
|
| export async function minify( |
| src: string, |
| options: any |
| ): Promise<{ code: string; map: any }> { |
| let bindings = await loadBindings() |
| return bindings.minify(src, options) |
| } |
|
|
| export async function isReactCompilerRequired( |
| filename: string |
| ): Promise<boolean> { |
| let bindings = await loadBindings() |
| return bindings.reactCompiler.isReactCompilerRequired(filename) |
| } |
|
|
| export async function parse(src: string, options: any): Promise<any> { |
| let bindings = await loadBindings() |
| let parserOptions = getParserOptions(options) |
| return bindings |
| .parse(src, parserOptions) |
| .then((astStr: any) => JSON.parse(astStr)) |
| } |
|
|
| export function getBinaryMetadata() { |
| let bindings |
| try { |
| bindings = loadNative() |
| } catch (e) { |
| |
| } |
|
|
| return { |
| target: bindings?.getTargetTriple?.(), |
| } |
| } |
|
|
| |
| |
| |
| |
| export function initCustomTraceSubscriber(traceFileName?: string) { |
| if (swcTraceFlushGuard) { |
| |
| let bindings = loadNative() |
| swcTraceFlushGuard = bindings.initCustomTraceSubscriber?.(traceFileName) |
| } |
| } |
|
|
| function once(fn: () => void): () => void { |
| let executed = false |
|
|
| return function (): void { |
| if (!executed) { |
| executed = true |
|
|
| fn() |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export const teardownTraceSubscriber = once(() => { |
| try { |
| let bindings = loadNative() |
| if (swcTraceFlushGuard) { |
| bindings.teardownTraceSubscriber?.(swcTraceFlushGuard) |
| } |
| } catch (e) { |
| |
| } |
| }) |
|
|
| export async function getModuleNamedExports( |
| resourcePath: string |
| ): Promise<string[]> { |
| const bindings = await loadBindings() |
| return bindings.rspack.getModuleNamedExports(resourcePath) |
| } |
|
|
| export async function warnForEdgeRuntime( |
| source: string, |
| isProduction: boolean |
| ): Promise<NapiSourceDiagnostic[]> { |
| const bindings = await loadBindings() |
| return bindings.rspack.warnForEdgeRuntime(source, isProduction) |
| } |
|
|