diff --git a/.changeset/start-rsbuild-diagnostic-locations.md b/.changeset/start-rsbuild-diagnostic-locations.md new file mode 100644 index 0000000000..a4876f953d --- /dev/null +++ b/.changeset/start-rsbuild-diagnostic-locations.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: a Start compile error or warning names its position as the compilation's own location, so Rsbuild's terminal output and error overlay point at it (`File: ./src/fns.ts:3:28`) instead of `:1:1`. diff --git a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts index ca6f52d41d..9df1654ad6 100644 --- a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts +++ b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts @@ -350,6 +350,9 @@ test.use({ 'SyntaxError', 'Syntax Error', 'Expression expected', + // the Start compiler's own error for the route file it cannot parse, + // reported at its position (Rspack's `Module build failed` no longer wraps it) + 'The compiler cannot parse', ], }) diff --git a/packages/start-plugin-core/src/rsbuild/compiler-session.ts b/packages/start-plugin-core/src/rsbuild/compiler-session.ts index de6dc77f47..acedb47460 100644 --- a/packages/start-plugin-core/src/rsbuild/compiler-session.ts +++ b/packages/start-plugin-core/src/rsbuild/compiler-session.ts @@ -57,6 +57,23 @@ export const SERVER_FN_BUILD_INFO_FIELD = 'tanstack.start.serverFns' /** The `buildInfo` field holding the key and dependencies of a module's plan, as JSON (persisted by Rspack's cache; checked at a compiler's first `finishMake`). */ export const PLAN_BUILD_INFO_FIELD = 'tanstack.start.plan' +/** + * The `buildInfo` field holding a compile's diagnostics with their positions + * (`LocatedDiagnostic`), in the order they were reported: Rspack keeps no + * location of a loader's warning or error, so the host plugin gives them + * one after the seal (`locateDiagnostics`). + */ +export const DIAGNOSTICS_BUILD_INFO_FIELD = 'tanstack.start.diagnostics' + +export interface LocatedDiagnostic { + severity: 'error' | 'warning' + /** The reported message (with the position, in the Vite host's form). */ + message: string + /** 1-based line and column. */ + line?: number + column?: number +} + export interface ServerFnBuildInfo { version: 3 canonicalId: string @@ -654,7 +671,11 @@ export class StartRsbuildCompilerSession { return { code: mock.code, map: null } } - /** Reports a compile's diagnostics: warnings to the loader context, the errors thrown together (the module fails). */ + /** + * Reports a compile's diagnostics: warnings to the loader context, the + * errors thrown together (the module fails), and all of them with their + * positions in the module's `buildInfo` (`DIAGNOSTICS_BUILD_INFO_FIELD`). + */ private reportDiagnostics( ctx: LoaderContextLike, out: CompileOutput, @@ -663,9 +684,23 @@ export class StartRsbuildCompilerSession { envType: 'client' | 'server', lateInputMap?: () => InputSourceMap | null, ): void { - // the position in the Vite host's form, `message (file:line:col)` - const where = (at: DiagnosticPosition | undefined) => - at ? ` (${file}:${at.line}:${at.column + 1})` : '' + const located: Array = [] + const locate = ( + severity: LocatedDiagnostic['severity'], + message: string, + at: DiagnosticPosition | undefined, + ) => { + // the position in the Vite host's form, `message (file:line:col)` + const text = at + ? `${message} (${file}:${at.line}:${at.column + 1})` + : message + located.push( + at + ? { severity, message: text, line: at.line, column: at.column + 1 } + : { severity, message: text }, + ) + return text + } const errors: Array = [] this.start.report( out, @@ -673,15 +708,19 @@ export class StartRsbuildCompilerSession { code, envType, { - error: (d, at) => errors.push(`${d.message}${where(at)}`), + error: (d, at) => errors.push(locate('error', d.message, at)), warn: (d, at) => { - const warning = new Error(`${d.message}${where(at)}`) + const warning = new Error(locate('warning', d.message, at)) warning.name = 'TanStackStartCompilerWarning' ctx.emitWarning(warning) }, }, lateInputMap, ) + const buildInfo = ctx._module?.buildInfo + if (located.length > 0 && buildInfo) { + buildInfo[DIAGNOSTICS_BUILD_INFO_FIELD] = located + } if (errors.length > 0) { const error = new Error(errors.join('\n')) error.name = 'TanStackStartCompilerError' diff --git a/packages/start-plugin-core/src/rsbuild/host-plugin.ts b/packages/start-plugin-core/src/rsbuild/host-plugin.ts index a91656105d..3d9c10e4ac 100644 --- a/packages/start-plugin-core/src/rsbuild/host-plugin.ts +++ b/packages/start-plugin-core/src/rsbuild/host-plugin.ts @@ -28,6 +28,7 @@ import { rspackGraphView, } from '../import-protection/witness' import { + DIAGNOSTICS_BUILD_INFO_FIELD, PLAN_BUILD_INFO_FIELD, SERVER_FN_BUILD_INFO_FIELD, canonicalResource, @@ -35,6 +36,7 @@ import { import { LOADER_REGISTRY } from './loader-registry' import type { LoaderImpl } from './compiler-loader' import type { + LocatedDiagnostic, ServerFnBuildInfo, StartRsbuildCompilerSession, } from './compiler-session' @@ -98,6 +100,82 @@ interface ModuleLike { identifier: () => string } +/** + * Start's compile diagnostics of the compilation's modules as errors and + * warnings located at their positions (`DIAGNOSTICS_BUILD_INFO_FIELD`): + * Rsbuild prints a diagnostic's file and `loc` (`File: ./src/fns.ts:3:5`, + * terminal and overlay), and Rspack keeps no location of a loader's thrown + * error or emitted warning. A module's failure (one error for every error + * its compile reported) and each of its warnings are replaced in place. + */ +function locateDiagnostics( + compilation: Rspack.Compilation, + WebpackError: typeof Rspack.WebpackError, +): void { + /** The warnings of each module not yet located, in the order reported. */ + const pending = new Map>() + for (const severity of ['error', 'warning'] as const) { + const list = + severity === 'error' ? compilation.errors : compilation.warnings + for (let i = list.length - 1; i >= 0; i--) { + const reported = list[i]! + const module = reported.module as unknown as ModuleLike | undefined + const records = module?.buildInfo?.[DIAGNOSTICS_BUILD_INFO_FIELD] as + | Array + | undefined + if (!records) { + continue + } + if (severity === 'error') { + const errors = records.filter((d) => d.severity === 'error') + if ( + errors.length > 0 && + reported.message.includes('TanStackStartCompilerError') + ) { + list.splice( + i, + 1, + ...errors.map((d) => locatedError(WebpackError, module!, d)), + ) + } + continue + } + const id = module!.identifier() + let warnings = pending.get(id) + if (!warnings) { + warnings = records.filter((d) => d.severity === 'warning') + pending.set(id, warnings) + } + // walking backwards: the module's last warning not yet located + const last = warnings.at(-1) + if (last && reported.message.includes(firstLine(last.message))) { + list.splice(i, 1, locatedError(WebpackError, module!, warnings.pop()!)) + } + } + } +} + +/** A compile diagnostic of `module` as an Rspack error or warning at its position. */ +function locatedError( + WebpackError: typeof Rspack.WebpackError, + module: ModuleLike, + d: LocatedDiagnostic, +): Rspack.RspackError { + const error: Rspack.RspackError = new WebpackError(d.message) + error.name = + d.severity === 'error' + ? 'TanStackStartCompilerError' + : 'TanStackStartCompilerWarning' + error.module = module as never + if (d.line !== undefined) { + error.loc = { start: { line: d.line, column: d.column } } + } + return error +} + +/** The start of a message's first line, as a native message quotes it. */ +const firstLine = (message: string) => message.split('\n', 1)[0]!.slice(0, 60) + /** * Whether Rspack's native `file` is a `package.json`: its edit re-resolves * what it may redirect, asked once Rspack's resolver forgot the old file @@ -338,6 +416,9 @@ export function createStartHostPlugin(opts: StartHostPluginOptions): { compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { currentCompilation = compilation env.compiled.clear() + compilation.hooks.afterSeal.tap(PLUGIN_NAME, () => + locateDiagnostics(compilation, WebpackError), + ) if (compiler.watchMode) { // Rspack watches the files the plans of the compilation's modules read (no // module depends on them: whether a change makes a module stale is the diff --git a/packages/start-plugin-core/tests/integration/rsbuild/diagnostic-location.test.ts b/packages/start-plugin-core/tests/integration/rsbuild/diagnostic-location.test.ts new file mode 100644 index 0000000000..91895aa0bb --- /dev/null +++ b/packages/start-plugin-core/tests/integration/rsbuild/diagnostic-location.test.ts @@ -0,0 +1,172 @@ +/** + * A Start compile error or warning on Rsbuild names its position as the + * compilation's own location (SPEC G5, ยง5.7): Rsbuild prints the file and + * the location of a compilation error or warning (`File: ./src/fns.ts:3:5`, + * in the terminal and the overlay) from its stats' `moduleName` and `loc`, + * and `:1:1` when there is no `loc`. Columns are 1-based, as in the message. + */ +import { describe, expect, test } from 'vitest' +import { diagnosticPosition } from '@tanstack/compiler-test-utils/diagnostics' +import { StartBuildError, buildStart } from '../../build-harness' +import { startRsbuildStartDevServer } from '../../rsbuild-dev-server' +import type { RsbuildPlugin } from '@rsbuild/core' + +const timeout = 60_000 + +interface Located { + severity: 'error' | 'warning' + moduleName?: string + loc?: string + message: string +} + +/** Every compilation's errors and warnings, as Rsbuild reads them to print them. */ +function recordLocations(): { plugin: RsbuildPlugin; seen: Array } { + const seen: Array = [] + return { + seen, + plugin: { + name: 'test:diagnostic-locations', + setup(api) { + api.onAfterEnvironmentCompile(({ stats }) => { + const json = stats?.toJson({ + all: false, + errors: true, + warnings: true, + }) + for (const severity of ['error', 'warning'] as const) { + for (const entry of json?.[`${severity}s`] ?? []) { + seen.push({ + severity, + moduleName: entry.moduleName, + loc: entry.loc, + message: entry.message, + }) + } + } + }) + }, + }, + } +} + +/** The location Rsbuild would print for `file`'s Start diagnostics. */ +function locationsOf(seen: Array, file: string, marker: RegExp) { + return seen + .filter( + (entry) => + entry.moduleName?.replace(/^\.\//, '') === file && + marker.test(entry.message), + ) + .map(({ severity, loc }) => ({ severity, loc })) +} + +const escapingSource = `import { createServerFn } from '@tanstack/react-start' +import { wrap } from './wrap' +export const reveal = wrap(createServerFn()).handler(async () => 'MARK_SERVER_SECRET') +` +const wrapSource = `export function wrap(builder: any) { + return Object.assign(builder, {}) +} +` +const serverParamSource = `import { createMiddleware } from '@tanstack/react-start' +export const requireRole = (role: string) => + createMiddleware().server(async ({ next }) => { + if (role === 'none') { + throw new Error('no') + } + return next() + }) +` + +const at = (source: string, needle: string) => { + const { line, column } = diagnosticPosition(source, needle) + return `${line}:${column}` +} + +describe('rsbuild build', () => { + test( + 'a compile error is located at its position', + async () => { + const { plugin, seen } = recordLocations() + await expect( + buildStart({ + bundler: 'rsbuild', + files: { + 'src/wrap.ts': wrapSource, + 'src/fns.ts': escapingSource, + 'src/entry.ts': `export { reveal } from './fns'\n`, + }, + entry: 'src/entry.ts', + rsbuildConfig: { plugins: [plugin] }, + }), + ).rejects.toBeInstanceOf(StartBuildError) + expect(locationsOf(seen, 'src/fns.ts', /createServerFn|builder/)).toEqual( + [{ severity: 'error', loc: at(escapingSource, 'createServerFn())') }], + ) + }, + timeout, + ) + + test( + 'a compile warning is located at its position', + async () => { + const { plugin, seen } = recordLocations() + await buildStart({ + bundler: 'rsbuild', + files: { + 'src/role.ts': serverParamSource, + 'src/entry.ts': `export { requireRole } from './role'\n`, + }, + entry: 'src/entry.ts', + rsbuildConfig: { plugins: [plugin] }, + }) + const located = locationsOf(seen, 'src/role.ts', /`role`/) + expect(located).not.toEqual([]) + expect(located).toEqual( + located.map(() => ({ + severity: 'warning', + loc: at(serverParamSource, 'role: string'), + })), + ) + }, + timeout, + ) +}) + +describe('rsbuild dev', () => { + test( + 'a compile error and a warning are located at their positions', + async () => { + const { plugin, seen } = recordLocations() + await startRsbuildStartDevServer({ + files: { + 'src/wrap.ts': wrapSource, + 'src/fns.ts': escapingSource, + 'src/role.ts': serverParamSource, + 'src/entry.ts': `export { reveal } from './fns' +export { requireRole } from './role' +`, + }, + config: { plugins: [plugin] }, + }) + expect( + locationsOf(seen, 'src/fns.ts', /createServerFn|builder/).filter( + ({ severity }) => severity === 'error', + ), + ).toContainEqual({ + severity: 'error', + loc: at(escapingSource, 'createServerFn())'), + }) + const warnings = locationsOf(seen, 'src/role.ts', /`role`/) + expect(warnings).not.toEqual([]) + expect(warnings).toEqual( + warnings.map(() => ({ + severity: 'warning', + loc: at(serverParamSource, 'role: string'), + })), + ) + }, + timeout, + ) +})