Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/typed-vite-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/redact': patch
---

Return typed Vite plugins from `redact()` instead of `any`.
16 changes: 10 additions & 6 deletions packages/redact/src/vite/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { readFileSync, realpathSync } from 'node:fs'
import { dirname, resolve as resolvePath } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Plugin } from 'vite'
import { adaptReact18 } from './react18'

import { ALIASES, resolveFeatures, isOwnedRuntimeFeature } from '../bundler-core/selection'
Expand Down Expand Up @@ -32,7 +33,7 @@ function pruneOptimizeDepsInclude(
})
}

export function redact(options: RedactOptions = {}): any {
export function redact(options: RedactOptions = {}) {
const skip = new Set(options.skip ?? [])
const entries = Object.entries(ALIASES).filter(([k]) => !skip.has(k))
const excludeList = entries.map(([k]) => k)
Expand Down Expand Up @@ -72,9 +73,11 @@ export function redact(options: RedactOptions = {}): any {
done = true
}

return [{
// Check the common Vite contract without erasing newer environment hooks
// or making optional Vite declarations part of the public return type.
const plugins = [{
name: 'redact',
enforce: 'pre',
enforce: 'pre' as const,

config() {
// Single package — only one name to dedupe / no-external.
Expand Down Expand Up @@ -188,7 +191,7 @@ export function redact(options: RedactOptions = {}): any {
name: 'redact:canonical-imports',
applyToEnvironment: (environment: any) => active(environment),
resolveId: {
order: 'pre',
order: 'pre' as const,
filter: { id: aliasFilter },
handler(this: any, id: string, _importer?: string, opts?: any) {
if (!active(this.environment, opts?.ssr)) return null
Expand All @@ -198,7 +201,7 @@ export function redact(options: RedactOptions = {}): any {
}, {
name: 'redact:react18',
applyToEnvironment: (environment: any) => !!react18Version && !!runtimeRoot && active(environment),
enforce: 'post',
enforce: 'post' as const,
transform(this: any, code: string, id: string, opts?: any) {
if (!react18Version || !runtimeRoot || !active(this?.environment, opts?.ssr)) return null
const path = id.split('?')[0]!.replaceAll('\\', '/')
Expand All @@ -208,7 +211,7 @@ export function redact(options: RedactOptions = {}): any {
},
}, {
name: 'redact:optimize-deps-guard',
enforce: 'post',
enforce: 'post' as const,

configResolved(config: any) {
// `optimizeDeps.exclude` loses when another plugin force-adds the same
Expand All @@ -223,6 +226,7 @@ export function redact(options: RedactOptions = {}): any {
// Leave `environments.rsc` untouched. RSC depends on real React internals.
},
}]
return plugins satisfies Array<Plugin>
}

export default redact
6 changes: 5 additions & 1 deletion tests/fixtures/react-router-framework/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { reactRouter } from '@react-router/dev/vite'
import { redact } from '@tanstack/redact/vite'
export default {
server: { host: '127.0.0.1' },
server: {
host: '127.0.0.1',
// HMR must read a completed module, not a file while it is being rewritten.
watch: { awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 10 } },
},
cacheDir: process.env.ROUTER_REFERENCE ? '.vite-native' : '.vite-redact',
plugins: [
...(process.env.ROUTER_REFERENCE
Expand Down
22 changes: 15 additions & 7 deletions tests/vite-environments.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,19 @@ import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { execFileSync } from 'node:child_process'
import { build } from 'vite'
import type { Plugin } from 'vite'
import { redact } from '@tanstack/redact/vite'

// These unit fixtures supply only the Vite context fields used by each hook.
function findPlugin(plugins: Array<Plugin>, name: string): any {
const plugin = plugins.find(item => item.name === name)
expect(plugin).toBeDefined()
return plugin
}

it.each(['client', 'ssr'] as const)('only substitutes React in the selected %s environment', async selected => {
const plugins = redact({ environments: [selected], preset: 'nano', packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } })
const plugin = plugins.find((item: { name: string }) => item.name === 'redact')
const plugin = findPlugin(plugins, 'redact')
plugin.configResolved({ root: resolve(import.meta.dirname, '..') })
const config = plugin.config()
expect(Object.keys(config.environments)).toEqual([selected])
Expand All @@ -26,7 +34,7 @@ it.each(['client', 'ssr'] as const)('only substitutes React in the selected %s e

it('keeps native SSR optimizer includes when only the browser uses Redact', () => {
const plugins = redact({ environments: ['client'] })
const guard = plugins.find((item: { name: string }) => item.name === 'redact:optimize-deps-guard')
const guard = findPlugin(plugins, 'redact:optimize-deps-guard')
const config = {
optimizeDeps: { include: ['react', 'other'] },
environments: {
Expand All @@ -43,7 +51,7 @@ it('keeps native SSR optimizer includes when only the browser uses Redact', () =
})

it('does not swap feature modules in an unselected SSR environment', async () => {
const plugin = redact({ environments: ['client'], preset: 'nano' }).find((item: { name: string }) => item.name === 'redact')
const plugin = findPlugin(redact({ environments: ['client'], preset: 'nano' }), 'redact')
const context = { environment: { name: 'ssr' }, resolve() { throw new Error('Native SSR must not be rewritten') } }
expect(await plugin.resolveId.handler.call(context, './portal', '/package/src/dom/features/index.ts')).toBeNull()
})
Expand Down Expand Up @@ -79,8 +87,8 @@ it('leaves the native SSR protocol untouched when adapting a React 18 browser',
mkdirSync(resolve(root, 'node_modules/react'), { recursive: true })
writeFileSync(resolve(root, 'node_modules/react/package.json'), JSON.stringify({ version: '18.3.1' }))
const plugins = redact({ environments: ['client'], resolveFrom: root, packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } })
const main = plugins.find((item: { name: string }) => item.name === 'redact')
const compiler = plugins.find((item: { name: string }) => item.name === 'redact:react18')
const main = findPlugin(plugins, 'redact')
const compiler = findPlugin(plugins, 'redact:react18')
main.configResolved({ root })
const id = await main.resolveId.handler.call({}, 'react')
const code = "export const version = '19.2.3'; export default { version: '19.2.3' };"
Expand All @@ -94,8 +102,8 @@ it('leaves the native SSR protocol untouched when adapting a React 18 browser',

it.each(['client', 'ssr'] as const)('keeps canonical imports in the selected %s environment only', async selected => {
const plugins = redact({ environments: [selected], packageRoots: { '@tanstack/redact': resolve(import.meta.dirname, '../packages/redact') } })
plugins.find((p: any) => p.name === 'redact').configResolved({ root: resolve(import.meta.dirname, '..') })
const hook = plugins.find((p: any) => p.name === 'redact:canonical-imports').resolveId.handler
findPlugin(plugins, 'redact').configResolved({ root: resolve(import.meta.dirname, '..') })
const hook = findPlugin(plugins, 'redact:canonical-imports').resolveId.handler
for (const name of ['client', 'ssr', 'rsc']) expect((await hook.call({ environment: { name } }, 'react')) !== null).toBe(name === selected)
expect(await hook.call({}, 'react', undefined, { ssr: true }) !== null).toBe(selected === 'ssr')
})
43 changes: 43 additions & 0 deletions tests/vite-plugin-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// @vitest-environment node
import { expect, it } from 'vitest'
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { resolve } from 'node:path'
import ts from 'typescript'

it('publishes typed Vite plugins for both exports', () => {
const root = mkdtempSync(resolve(tmpdir(), 'redact-vite-types-'))
try {
symlinkSync(resolve(import.meta.dirname, '../node_modules'), resolve(root, 'node_modules'), 'dir')
const declaration = resolve(import.meta.dirname, '../packages/redact/dist/vite/index.js')
const fixture = (entry: string) => `
import defaultRedact, { redact } from ${JSON.stringify(entry)};
import { defineConfig, type Plugin } from 'vite';
type IsAny<T> = 0 extends (1 & T) ? true : false;
type AssertFalse<T extends false> = T;
export type NamedReturn = AssertFalse<IsAny<ReturnType<typeof redact>>>;
export type DefaultReturn = AssertFalse<IsAny<ReturnType<typeof defaultRedact>>>;
const plugins: Plugin[] = redact();
defineConfig({ plugins: [redact(), ...defaultRedact(), ...plugins] });
`
const check = (entry: string) => {
const file = resolve(root, 'consumer.mts')
writeFileSync(file, fixture(entry))
const program = ts.createProgram([file], {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.NodeNext,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
strict: true, skipLibCheck: true, noEmit: true, types: [],
})
return ts.getPreEmitDiagnostics(program).map(diagnostic => ({
code: diagnostic.code,
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
}))
}
// Prove the same consumer rejects the original public any return type.
const control = resolve(root, 'untyped.d.mts')
writeFileSync(control, 'export declare function redact(): any;\nexport default redact;\n')
expect(check(resolve(root, 'untyped.mjs')).map(diagnostic => diagnostic.code)).toEqual([2344, 2344])
expect(check(declaration)).toEqual([])
} finally { rmSync(root, { recursive: true, force: true }) }
})
Loading