// `withBugsee(nextConfig, options)` — the Next.js build integration that makes `next build` upload source maps. // // webpack (`next build --webpack`; the default up to Next 15): a Bugsee plugin on each of the client, server and // edge compilations stamps the debug-IDs inside the build and uploads that compilation's own maps. // Turbopack (the default in Next 16; `next build --turbopack` before): no plugin API, so Next's // `compiler.runAfterProductionCompile` hook runs the stamp + upload over the written `.next`. // // The result composes with what the app already has: a config object, a (phase) function or an async one; the // app's own `webpack` function, `compiler.runAfterProductionCompile`, `compiler.define` and // `productionBrowserSourceMaps` are called, kept or extended, never replaced. Nothing runs for `next dev`. import { createRequire } from 'node:module'; import { join, resolve } from 'node:path'; import { APP_BUILD_DEFINE, APP_VERSION_DEFINE } from '@bugsee/bundler-plugin-core'; import { type BugseeNextContext, createBugseeContext, type WithBugseeOptions } from './context'; import { type PostBuildMetadata, runPostBuild } from './post-build'; import { NO_HOOK_NOTICE, TURBOPACK_SRI_NOTICE } from './sri'; import { createNextWebpackPlugin, type NextCompilationKind } from './webpack-plugin'; /** The Next config shapes this accepts. Structural: `next` is not a dependency. */ // biome-ignore lint/suspicious/noExplicitAny: a user's Next config is open-ended; only the keys read below matter. export type NextConfigObject = Record; export type NextConfigFunction = ( phase: string, context: { defaultConfig: NextConfigObject }, ) => C | Promise; export type NextConfigInput = C | Promise | NextConfigFunction; /** Next's `PHASE_PRODUCTION_BUILD`. The only phase that builds anything we touch. */ const PHASE_PRODUCTION_BUILD = 'phase-production-build'; /** The first Next with `compiler.runAfterProductionCompile` (in the 15.4.0 types, schema and build; absent in 15.3.x). */ const MIN_TURBOPACK_HOOK = [15, 4, 0] as const; /** The first Next whose config schema has `compiler.define` (15.1.0; 15.0.x rejects it as an unknown key). */ const MIN_COMPILER_DEFINE = [15, 1, 0] as const; /** Configs this has already extended, so applying `withBugsee` twice (a shared base config) adds nothing twice. */ const WRAPPED = new WeakSet(); /** Seams for tests. */ export interface WithBugseeDeps { cwd?: () => string; env?: Record; /** The installed `next` version, or `undefined` when unknown. */ nextVersion?: (projectDir: string) => string | undefined; createContext?: typeof createBugseeContext; } function isThenable(value: unknown): value is PromiseLike { return ( typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function' ); } /** Whether `version` (`16.4.6`, `15.4.0-canary.12`) is at least `min`. Unparseable counts as new enough. */ export function versionAtLeast(version: string, min: readonly [number, number, number]): boolean { const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version); if (match === null) { return true; } const parts = [Number(match[1]), Number(match[2]), Number(match[3])]; for (let i = 0; i < 3; i++) { if ((parts[i] as number) !== min[i]) { return (parts[i] as number) > (min[i] as number); } } return true; } /** A JSON string literal as the string it denotes; anything else as written. */ function unquote(value: string): string { try { const parsed: unknown = JSON.parse(value); return typeof parsed === 'string' ? parsed : value; } catch { return value; } } /** The `version` of the `next` installed for `projectDir`. */ function installedNextVersion(projectDir: string): string | undefined { try { const require = createRequire(join(projectDir, 'package.json')); return (require('next/package.json') as { version?: string }).version; } catch { return undefined; } } function compilationKind(next: { isServer?: boolean; nextRuntime?: string }): NextCompilationKind { if (next.isServer !== true) { return 'client'; } return next.nextRuntime === 'edge' ? 'edge' : 'server'; } /** Build the extended config for one resolved context. */ function extendConfig( config: C, baseContext: BugseeNextContext, turbopack: boolean, nextVersion: string | undefined, projectDir: string, development: boolean, ): C { const sri = Boolean(config.experimental?.sri); const next: NextConfigObject = { ...config }; // Whether this build has a way to upload at all: webpack always does (it stamps inside the build, SRI included); // Turbopack needs the post-build hook (Next >= 15.4.0) and cannot stamp an SRI build. const noHook = turbopack && nextVersion !== undefined && !versionAtLeast(nextVersion, MIN_TURBOPACK_HOOK); const uploadAvailable = !turbopack || (!noHook && !sri); // Bugsee turns browser maps on only when the app said nothing AND an upload is possible. // A dry run uploads and deletes nothing, so it would leave the forced maps public: not forced then. const forced = baseContext.resolved.enabled && !baseContext.resolved.dryRun && config.productionBrowserSourceMaps === undefined && uploadAvailable; // The version and build the app's OWN `compiler.define` bakes into the bundle are what the runtime SDK reports, // so they are what the upload and the build registration are labelled with (a string value; anything else keeps // the resolved identity). const userDefine = (config.compiler?.define ?? {}) as Record; const definedVersion = userDefine[APP_VERSION_DEFINE]; const definedBuild = userDefine[APP_BUILD_DEFINE]; const context: BugseeNextContext = { ...baseContext, resolved: { ...baseContext.resolved, ...(typeof definedVersion === 'string' ? { appVersion: definedVersion } : {}), ...(typeof definedBuild === 'string' ? { appBuild: definedBuild } : {}), }, ...(sri ? { sri: true } : {}), ...(forced ? { forcedMaps: true } : {}), browserMaps: forced || config.productionBrowserSourceMaps === true, }; const { resolved } = context; // The app's version and build, baked into every bundle (browser, node, edge) for the runtime SDK to read. // `compiler.define` applies to all three; `defineServer` must NOT repeat the keys (measured, Next 15.5: it // throws "already configured"). A constant the app defined itself wins. // Only with a token: without one the integration changes nothing Next emits. if (!resolved.enabled) { return next as C; } const identity = resolved.identityDefines; if ( Object.keys(identity).length > 0 && (nextVersion === undefined || versionAtLeast(nextVersion, MIN_COMPILER_DEFINE)) ) { const compiler: NextConfigObject = { ...(config.compiler ?? {}) }; // The core hands over JSON string literals (`"1.2.3"`, what a bundler's DefinePlugin takes). Next JSON-encodes // every `compiler.define` value itself (define-env.js serializeDefineEnv), so a JSON string would reach the // bundle quoted twice: the raw value is what it wants (measured: `v"9.8.7"` in a real build). const raw = Object.fromEntries( Object.entries(identity).map(([key, value]) => [key, unquote(value)]), ); compiler.define = { ...raw, ...(config.compiler?.define ?? {}) }; next.compiler = compiler; } // Browser maps are what Bugsee symbolicates browser crashes with. Forced on only when nothing says otherwise AND // an upload is possible for this build: they are written to `.next/static`, which is served publicly, and only a // confirmed upload removes them. If the upload cannot happen, the app's own setting stands. if (forced) { next.productionBrowserSourceMaps = true; } // webpack builds only. A `webpack` function on a Turbopack build is an ERROR in Next 16 ("a `webpack` config and // no `turbopack` config", measured) and a warning in 15.5, so Turbopack builds never get one from us. if (!turbopack) { const userWebpack = config.webpack as | ((webpackConfig: NextConfigObject, options: NextConfigObject) => unknown) | undefined; next.webpack = (webpackConfig: NextConfigObject, options: NextConfigObject) => { const result = userWebpack === undefined ? webpackConfig : userWebpack(webpackConfig, options); const finish = (value: unknown): NextConfigObject => { const out = (value ?? webpackConfig) as NextConfigObject; if (options.dev === true) { return out; } const kind = compilationKind(options); if (kind !== 'client' && context.serverSourceMaps && !out.devtool) { out.devtool = 'source-map'; } out.plugins = [...(out.plugins ?? []), createNextWebpackPlugin(context, kind)]; return out; }; return isThenable(result) ? result.then(finish) : finish(result); }; } if (turbopack) { if (noHook) { // Config-time notices are about a BUILD; `next dev` loads the same config and must stay quiet. if (!development) { context.say(NO_HOOK_NOTICE(nextVersion as string)); } } else if (sri) { if (!development) { context.say(TURBOPACK_SRI_NOTICE); } } else { const userHook = config.compiler?.runAfterProductionCompile as | ((metadata: PostBuildMetadata) => Promise) | undefined; next.compiler = { ...(next.compiler ?? config.compiler ?? {}), runAfterProductionCompile: async (metadata: PostBuildMetadata) => { await userHook?.(metadata); // The config (token file, version, installed Next) was resolved for the working directory at load time; // Next says which project it is building. They differ for `next build ` from a monorepo root. if (resolve(metadata.projectDir) !== resolve(projectDir)) { context.say( `the config was resolved for ${projectDir} but Next is building ${metadata.projectDir}: the token file, app version and Next version were looked up in the former. Run \`next build\` from the project directory.`, ); } await runPostBuild(context, metadata); }, }; } } return next as C; } /** * Wrap a Next config so `next build` stamps debug-IDs and uploads source maps to Bugsee. * * ```js * // next.config.mjs * import { withBugsee } from '@bugsee/nextjs/config'; * export default withBugsee({ /* your config *\/ }, { appToken: process.env.BUGSEE_APP_TOKEN }); * ``` */ export function withBugsee( nextConfig: NextConfigInput = {} as C, options: WithBugseeOptions = {}, deps: WithBugseeDeps = {}, ): NextConfigInput { if (options.disabled === true) { return nextConfig; } const env = deps.env ?? process.env; const turbopack = Boolean(env.TURBOPACK); const apply = (config: C, phase: string | undefined): C => { // `next dev`, `next start` and `next export` build nothing this touches. An object config has no phase; // there the webpack function is gated on `dev` and the post-build hook only exists in a production build. if (phase !== undefined && phase !== PHASE_PRODUCTION_BUILD) { return config; } if (WRAPPED.has(config)) { return config; } const projectDir = (deps.cwd ?? process.cwd)(); const context = (deps.createContext ?? createBugseeContext)(options, projectDir, { env }); const extended = extendConfig( config, context, turbopack, (deps.nextVersion ?? installedNextVersion)(projectDir), projectDir, env.NODE_ENV === 'development', ); WRAPPED.add(extended); return extended; }; if (typeof nextConfig === 'function') { return async (phase, context) => apply(await nextConfig(phase, context), phase); } if (isThenable(nextConfig)) { return Promise.resolve(nextConfig).then((config) => apply(config, undefined)); } return apply(nextConfig, undefined); }