diff --git a/packages/start-plugin-core/src/import-protection/locate.ts b/packages/start-plugin-core/src/import-protection/locate.ts index 899487b5be..3484cc2498 100644 --- a/packages/start-plugin-core/src/import-protection/locate.ts +++ b/packages/start-plugin-core/src/import-protection/locate.ts @@ -190,4 +190,63 @@ export class Locator { const { line, column } = this.lf.locate(offset) return originalPositionFor(map, line, column, this.file) } + + /** The code frame of an original location `at` gave (null without the original text). */ + frame(loc: OriginalLocation): CodeFrame | null { + const map = this.inputMap() + let text: string | null = null + if (map === null) { + text = loc.file === this.file ? this.code : null + } else { + const root = map.sourceRoot ?? '' + const index = map.sources.findIndex( + (s) => + typeof s === 'string' && + resolveSource(this.file, root, s) === loc.file, + ) + text = index < 0 ? null : (map.sourcesContent?.[index] ?? null) + } + // (lines counted like `at` counts them: the input by every ECMAScript + // terminator, a map's sources by LF) + return text === null + ? null + : codeFrame(text, loc, map === null ? /\r\n|[\n\r\u2028\u2029]/ : /\r?\n/) + } +} + +/** Vitest-style lines of the original source around a location (`ViolationInfo.snippet`). */ +export interface CodeFrame { + lines: Array + highlightLine: number + /** `file:line:column`. */ + location: string +} + +const CONTEXT_LINES = 2 + +function codeFrame( + text: string, + loc: OriginalLocation, + lineBreaks: RegExp, +): CodeFrame | null { + const all = text.split(lineBreaks) + if (loc.line > all.length) { + return null + } + const first = Math.max(1, loc.line - CONTEXT_LINES) + const last = Math.min(all.length, loc.line + CONTEXT_LINES) + const gutter = String(last).length + const lines: Array = [] + for (let n = first; n <= last; n++) { + const marker = n === loc.line ? '>' : ' ' + lines.push(` ${marker} ${String(n).padStart(gutter)} | ${all[n - 1]}`) + if (n === loc.line) { + lines.push(` ${' '.repeat(gutter)} | ${' '.repeat(loc.column - 1)}^`) + } + } + return { + lines, + highlightLine: loc.line, + location: `${loc.file}:${loc.line}:${loc.column}`, + } } diff --git a/packages/start-plugin-core/src/import-protection/violations.ts b/packages/start-plugin-core/src/import-protection/violations.ts index 3856334339..1e4ff3738c 100644 --- a/packages/start-plugin-core/src/import-protection/violations.ts +++ b/packages/start-plugin-core/src/import-protection/violations.ts @@ -8,7 +8,7 @@ import { patternOf, rulesFor } from './rules' import type { EdgeModuleContent } from './edge-modules' import type { ImportProtectionConfig } from './config' import type { EnvType, RuleRef } from './rules' -import type { OriginalLocation } from './locate' +import type { CodeFrame, OriginalLocation } from './locate' import type { TraceStep, ViolationInfo } from './trace' export const IMPORT_EDGES_PLANNER = 'import-edges' @@ -29,6 +29,8 @@ export interface EdgeViolation { resolved: string | null /** Where the import is, in the original source. */ loc: OriginalLocation | null + /** The original source around `loc`, when the original text is known. */ + snippet: CodeFrame | null behavior: 'error' | 'mock' /** The edge module the specifier was substituted with (null: not substituted, dev `error`). */ module: { key: string; content: EdgeModuleContent } | null @@ -89,6 +91,9 @@ export function violationInfo( specifier: v.specifier, importer: v.importer, ...(v.loc && { importerLoc: { ...v.loc } }), + ...(v.snippet && { + snippet: { ...v.snippet, lines: [...v.snippet.lines] }, + }), ...(v.resolved !== null && { resolved: identify(v.resolved).path }), } as ViolationInfo & { freezeTrace: () => Array } Object.defineProperty(info, 'trace', { diff --git a/packages/start-plugin-core/src/planners/edges.ts b/packages/start-plugin-core/src/planners/edges.ts index 21c4df714b..915e507eb9 100644 --- a/packages/start-plugin-core/src/planners/edges.ts +++ b/packages/start-plugin-core/src/planners/edges.ts @@ -246,6 +246,7 @@ export function importEdgesPlanner(ip: ImportProtection): Planner { importerId, resolved: j.resolved, loc: j.loc, + snippet: j.loc && locator.frame(j.loc), behavior, module: null, } diff --git a/packages/start-plugin-core/tests/integration/importProtection/reported-location-trace.test.ts b/packages/start-plugin-core/tests/integration/importProtection/reported-location-trace.test.ts index 589d94d32a..bab366d17a 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/reported-location-trace.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/reported-location-trace.test.ts @@ -31,7 +31,19 @@ async function buildReport( viteConfig, }: Pick = {}, ): Promise { - const error = await rejection( + return reportOf(await buildFailure(bundler, files, { sourcemap, viteConfig })) +} + +/** The failed build of `files` (client entry `src/entry.ts`, default rules). */ +function buildFailure( + bundler: StartBundler, + files: Record, + { + sourcemap = false, + viteConfig, + }: Pick = {}, +) { + return rejection( buildStart({ bundler, files, @@ -40,6 +52,10 @@ async function buildReport( viteConfig, }), ) +} + +/** The report of the one violation of a failed build. */ +function reportOf(error: Awaited>): Violation { const [report, ...others] = violationsOf(error) expect(others).toEqual([]) return report! @@ -118,10 +134,11 @@ export const leak = () => secret() describe.each(startBundlers)( '%s build: the report of a violation', (bundler) => { - let chainReport: Promise | undefined - /** The report of the `chain` build, built once. */ - const reportOfChain = () => - (chainReport ??= buildReport(bundler, chain, {})) + let chainFailure: ReturnType | undefined + /** The failed `chain` build, built once. */ + const failureOfChain = () => (chainFailure ??= buildFailure(bundler, chain)) + /** The report of the `chain` build. */ + const reportOfChain = async () => reportOf(await failureOfChain()) // The middle steps are located on the line of their import (which // column of the import statement is not specified). @@ -149,6 +166,27 @@ describe.each(startBundlers)( timeout, ) + // The printed report shows the user's source where it locates the + // importer (SPEC J6.5 "a code frame"): read as the original text of that + // line in the build's error, not as wording. `src/b.ts` starts with a + // comment that compiling drops, so a frame of compiled code shows other + // lines. + test( + "the printed report shows the importer's original source at its location", + async () => { + const error = await failureOfChain() + const { importer } = reportOf(error) + expect(atChainImporter(importer), importer).toBe(true) + const line = Number(/^src\/b\.ts:(\d+)/.exec(importer)![1]) + const original = chain['src/b.ts'].split('\n')[line - 1]! + expect( + error.errors.some((message) => message.includes(original)), + error.errors.join('\n'), + ).toBe(true) + }, + timeout, + ) + // Any real chain from the entry to the importer will do, not // necessarily the shortest (SPEC J6.5): `src/a.ts` imports // `src/s.ts` directly and through `src/c.ts`.