diff --git a/packages/start-plugin-core/src/compiler/scope.ts b/packages/start-plugin-core/src/compiler/scope.ts index 5a164394d1..7089141a55 100644 --- a/packages/start-plugin-core/src/compiler/scope.ts +++ b/packages/start-plugin-core/src/compiler/scope.ts @@ -3,6 +3,7 @@ * transform, the Rsbuild loader). */ import { HYDRATE_COMPONENT } from '../planners/hydrate' +import { isInsideDirectory } from '../import-protection/utils' import { startRecognizer } from './recognizer' import type { ImportProtection } from '../import-protection/session' @@ -32,6 +33,29 @@ export function startCompileScope( startText.test(code) } +/** + * The text test a host may run on dependency modules before handing them to + * the compiler (a transform hook's code filter): the text side of + * `startCompileScope`. Null when import protection's scope may reach a + * dependency by its path (an `include`, or a source directory holding the + * root's `node_modules`), which no text test sees. + */ +export function dependencyTextFilter( + ip: ImportProtection | null, +): RegExp | null { + if ( + ip && + (ip.config.include.length > 0 || + isInsideDirectory( + `${ip.config.root}/node_modules/_`, + ip.config.srcDirectory, + )) + ) { + return null + } + return startTextTest(ip) +} + /** Whether a text names what the planners recognise (see `startCompileScope`). */ function startTextTest(ip: ImportProtection | null): RegExp { const names = new Set( diff --git a/packages/start-plugin-core/src/vite/compiler-plugin.ts b/packages/start-plugin-core/src/vite/compiler-plugin.ts index ec26d0657b..26f8c46faa 100644 --- a/packages/start-plugin-core/src/vite/compiler-plugin.ts +++ b/packages/start-plugin-core/src/vite/compiler-plugin.ts @@ -43,7 +43,7 @@ import { TRANSFORM_ID_REGEX, VITE_ENVIRONMENT_NAMES, } from '../constants' -import { NODE_MODULES_RE } from '../compiler/scope' +import { NODE_MODULES_RE, dependencyTextFilter } from '../compiler/scope' import { StartCompilerSession } from '../compiler/session' import { decodeDevFunctionId } from '../server-fns/ids' import { providerModuleId } from '../server-fns/registry' @@ -91,6 +91,12 @@ import type { ViteDevServer, } from 'vite' +/** A transform hook's handler (shared by the compiler's two transform hooks of an environment). */ +type TransformHandler = Extract< + NonNullable, + { handler: unknown } +>['handler'] + interface StartCompilerEnvironment { name: string type: 'client' | 'server' @@ -124,6 +130,13 @@ const SERVER_FN_FORWARD_VIRTUAL_ID = 'virtual:tanstack-start-server-fn-forward' /** A module naming no server-fn factory nor `.handler(` defines no server function (a text gate before any analysis). */ const SERVER_FN_TEXT_RE = /createServerFn|\.handler\s*\(/ +/** A dependency module: `node_modules` in its path (not its query). */ +const DEPENDENCY_ID_RE = /^[^?]*[\\/]node_modules[\\/]/ + +/** A dependency's script module (the `TRANSFORM_ID_REGEX` of `DEPENDENCY_ID_RE`). */ +const DEPENDENCY_SCRIPT_RE = + /^[^?]*[\\/]node_modules[\\/].*\.[cm]?[tj]sx?(?:$|\?)/ + /** Specifiers of import protection's edge modules. */ const IP_SPECIFIER_RE = /tanstack-start-ip:/ @@ -620,11 +633,64 @@ export function startCompilerPlugin( ): InvalidateChange['kind'] => event === 'delete' ? 'unlink' : event === 'create' ? 'add' : 'change' + /** + * The transform filter of dependency scripts. Its text test is set with + * the session (it depends on import protection's configuration); without + * one, every dependency script reaches the compiler, whose scope decides. + */ + const dependencyFilter: { + id: { include: Array; exclude: Array } + code?: RegExp + } = { id: { include: [DEPENDENCY_SCRIPT_RE], exclude: [ASSET_QUERY_RE] } } + /** The environment whose plugin runs `watchChange` (bundled dev): one invalidation per change, applied to every environment. */ const watchingEnv = opts.environments[0]?.name - function perEnvPlugin(env: StartCompilerEnvironment): Plugin { + function perEnvPlugins(env: StartCompilerEnvironment): Array { const watches = env.name === watchingEnv - return { + const compileTransform: TransformHandler = async function (code, id) { + const identity = identify(id) + const s = requireSession() + if (identity.lang === null || !s.start.compiles(identity.path, code)) { + return null + } + const environment = this.environment + const out = await s.start.compile( + { + id, + code, + env, + inputMap: () => inputMapOf(this, code, identity.path), + wantMap: + s.start.opts.mode === 'dev' || + environment.config.build.sourcemap !== false, + }, + hostFor(s, this.environment, (source, imp, options) => + this.resolve(source, imp, options), + ), + ) + if (!out) { + return null + } + reportDiagnostics(s, this, out, identity.path, id, code, env.type) + const decided = afterCompile(s, env, id, out, (error) => + this.error(error), + ) + if (decided) { + await decided + } + if (s.start.opts.mode === 'dev') { + outputDigests.set(`${environment.name}\0${id}`, revision(out.code)) + } + if (identity.derived === null && out.code === code) { + return null + } + return { + code: out.code, + map: out.map as never, + moduleSideEffects: out.sideEffectFree ? false : undefined, + } + } + const plugin: Plugin = { name: `tanstack-start:compiler:${env.name}`, enforce: 'pre', perEnvironmentWatchChangeDuringDev: watches, @@ -638,6 +704,10 @@ export function startCompilerPlugin( command: config.command, bundledDev: !!config.experimental.bundledDev, }) + const text = dependencyTextFilter(session.start.ip) + if (text) { + dependencyFilter.code = text + } unsubscribeRoutes?.() unsubscribeRoutes = onRoutesChanged( opts.routerPluginContext, @@ -782,54 +852,12 @@ export function startCompilerPlugin( }, transform: { filter: { - id: { include: TRANSFORM_ID_REGEX, exclude: ASSET_QUERY_RE }, - }, - async handler(code, id) { - const identity = identify(id) - const s = requireSession() - if ( - identity.lang === null || - !s.start.compiles(identity.path, code) - ) { - return null - } - const environment = this.environment - const out = await s.start.compile( - { - id, - code, - env, - inputMap: () => inputMapOf(this, code, identity.path), - wantMap: - s.start.opts.mode === 'dev' || - environment.config.build.sourcemap !== false, - }, - hostFor(s, this.environment, (source, imp, options) => - this.resolve(source, imp, options), - ), - ) - if (!out) { - return null - } - reportDiagnostics(s, this, out, identity.path, id, code, env.type) - const decided = afterCompile(s, env, id, out, (error) => - this.error(error), - ) - if (decided) { - await decided - } - if (s.start.opts.mode === 'dev') { - outputDigests.set(`${environment.name}\0${id}`, revision(out.code)) - } - if (identity.derived === null && out.code === code) { - return null - } - return { - code: out.code, - map: out.map as never, - moduleSideEffects: out.sideEffectFree ? false : undefined, - } + id: { + include: TRANSFORM_ID_REGEX, + exclude: [ASSET_QUERY_RE, DEPENDENCY_ID_RE], + }, }, + handler: compileTransform, }, async hotUpdate(ctx) { const s = requireSession() @@ -998,6 +1026,20 @@ export function startCompilerPlugin( } }, } + return [ + plugin, + { + // dependency scripts: only those whose text names what the compiler + // recognises reach the compiler (most of a dependency graph never + // crosses into JavaScript) + name: `tanstack-start:compiler:${env.name}:dependencies`, + enforce: 'pre', + applyToEnvironment(e) { + return e.name === env.name + }, + transform: { filter: dependencyFilter, handler: compileTransform }, + }, + ] } /** @@ -1216,7 +1258,7 @@ export function startCompilerPlugin( }) return [ - ...opts.environments.map(perEnvPlugin), + ...opts.environments.flatMap(perEnvPlugins), buildLoopPlugin, latePassPlugin, devLookupPlugin, diff --git a/packages/start-plugin-core/tests/integration/importProtection/build.test.ts b/packages/start-plugin-core/tests/integration/importProtection/build.test.ts index f7f5f0351b..1437d8167f 100644 --- a/packages/start-plugin-core/tests/integration/importProtection/build.test.ts +++ b/packages/start-plugin-core/tests/integration/importProtection/build.test.ts @@ -142,6 +142,40 @@ describe.each(startBundlers)('%s build', (bundler) => { timeout, ) + // Import protection's `include` may reach a dependency: it is judged like + // a module of the app, though its text names no Start API. + test( + 'a dependency import protection includes fails the build with the denied import it uses', + async () => { + const report = await failureReport( + buildStart({ + bundler, + files: { + 'node_modules/lib/package.json': JSON.stringify({ + name: 'lib', + type: 'module', + exports: './index.js', + }), + 'node_modules/lib/index.js': `import { secret } from './secret.js'\nexport const read = () => secret()\n`, + 'node_modules/lib/secret.js': `export const secret = () => 'MARK_SECRET' + Math.random()\n`, + 'src/entry.ts': `export { read } from 'lib'\n`, + }, + entry: 'src/entry.ts', + start: { + importProtection: { + behavior: 'error', + include: ['src/**', 'node_modules/lib/**'], + client: { files: ['**/lib/secret.js'], excludeFiles: [] }, + }, + }, + }), + ) + expect(report.environment).toBe('client') + expect(report.importer).toMatch(/^node_modules\/lib\/index\.js/) + }, + timeout, + ) + test( 'a file with both a server-only and a client-only marker fails the build, naming the file', async () => {