feat: add Webpack and Rspack browser plugins #143
Mergedtannerlinsleymerged 3 commits into
main fromtaren/bundler-selection-current-0173merged by tannerlinsley - @@ -0,0 +53,21 @@53+ dir = parent54+ }55+}56+57+function resolveExport(packageDir: string, sub: string): string | null {58+ const pkgJsonPath = resolvePath(packageDir, 'package.json')59+ let pkg: any60+ try {61+ pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8'))62+ } catch {63+ return null64+ }65+ const key = sub ? './' + sub : '.'66+ const exp = pkg.exports?.[key]67+ // Prefer published JavaScript over TypeScript sources. Dist preserves one68+ // file per module, so subpath imports share state and feature boundaries.69+ const pick = (v: any): string | null => {70+ if (typeof v === 'string') return v71+ if (v && typeof v === 'object') {72+ return pick(v.import ?? v.module ?? v.source ?? v.default ?? null)73+ }packages/redact/src/bundler-core/resolution.ts lines 101 to 102OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ return null83+}84+85+// When installed from npm, `@tanstack/redact` is declared as a `dependency`86+// of consumer apps. Under pnpm's strict mode it ends up nested under the87+// plugin's own `.pnpm/@tanstack+redact@.../node_modules/` rather than88+// hoisted to the consumer's root, so a `findPackageDir` walk starting at89+// the Vite project root won't always find it. Search from the plugin's own90+// directory first (which walks into its nested node_modules), then fall91+// back to the consumer root for hoisted installs.92+const pluginDir = dirname(fileURLToPath(import.meta.url))93+94+export function resolveSpecifier(95+ specifier: string,96+ fromDir: string,97+ packageRoots: Record<string, string>,98+): string | null {99+ const { pkg, sub } = splitSpecifier(specifier)100+ const packageDir =101+ packageRoots[pkg] ??102+ findPackageDir(pkg, pluginDir) ??@@ -0,0 +46,21 @@46+ const feature = directory && directories[directory]47+ if (!feature || features[feature]) return null48+ const stub = resolve(dirname(canonical), 'stub.js')49+ if (!existsSync(stub)) throw new Error(`Redact feature stub is missing: ${stub}`)50+ return stub + resource.slice(path.length)51+}52+53+/** Webpack 5 and Rspack 2 integration for browser SPAs. */54+export function redact(options: RedactOptions = {}) {55+ const features = resolveFeatures(options.preset ?? 'full', options.features ?? {})56+ return {57+ apply(compiler: Compiler): void {58+ const target = compiler.options.target59+ if (target !== undefined && target !== 'web' && !(Array.isArray(target) && target.includes('web') && target.every(value => value === 'web' || /^es\d+$/.test(value)))) {60+ throw new Error('The Redact Webpack/Rspack plugin supports browser SPA targets only. Use target: "web".')61+ }62+ const from = options.resolveFrom ?? compiler.context63+ const roots = options.packageRoots ?? {}64+ const entry = resolveSpecifier('@tanstack/redact', from, roots)65+ if (!entry) throw new Error('Cannot find the built @tanstack/redact package. Install it before configuring the plugin.')66+ const root = realpathSync(resolve(dirname(entry), '../..'))packages/redact/src/webpack/index.ts line 78OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +58,21 @@58+ const target = compiler.options.target59+ if (target !== undefined && target !== 'web' && !(Array.isArray(target) && target.includes('web') && target.every(value => value === 'web' || /^es\d+$/.test(value)))) {60+ throw new Error('The Redact Webpack/Rspack plugin supports browser SPA targets only. Use target: "web".')61+ }62+ const from = options.resolveFrom ?? compiler.context63+ const roots = options.packageRoots ?? {}64+ const entry = resolveSpecifier('@tanstack/redact', from, roots)65+ if (!entry) throw new Error('Cannot find the built @tanstack/redact package. Install it before configuring the plugin.')66+ const root = realpathSync(resolve(dirname(entry), '../..'))67+ const aliases: Array<{ name: string; alias: string; onlyModule: true }> = []68+ for (const [name, specifier] of Object.entries(ALIASES)) {69+ if (options.skip?.includes(name)) continue70+ const alias = resolveSpecifier(specifier, from, roots)71+ if (!alias) throw new Error(`Cannot resolve Redact alias: ${specifier}`)72+ aliases.push({ name, alias, onlyModule: true })73+ }74+ const previous = compiler.options.resolve.alias || {}75+ compiler.options.resolve.alias = Array.isArray(previous)76+ ? [...aliases, ...previous]77+ : Object.fromEntries([78+ ...aliases.map(({ name, alias }) => [name + '$', alias]),@@ -0,0 +66,21 @@66+ const root = realpathSync(resolve(dirname(entry), '../..'))67+ const aliases: Array<{ name: string; alias: string; onlyModule: true }> = []68+ for (const [name, specifier] of Object.entries(ALIASES)) {69+ if (options.skip?.includes(name)) continue70+ const alias = resolveSpecifier(specifier, from, roots)71+ if (!alias) throw new Error(`Cannot resolve Redact alias: ${specifier}`)72+ aliases.push({ name, alias, onlyModule: true })73+ }74+ const previous = compiler.options.resolve.alias || {}75+ compiler.options.resolve.alias = Array.isArray(previous)76+ ? [...aliases, ...previous]77+ : Object.fromEntries([78+ ...aliases.map(({ name, alias }) => [name + '$', alias]),79+ ...Object.entries(previous).filter(([name]) => !aliases.some(alias => alias.name + '$' === name)),80+ ])81+ const reactDir = findPackageDir('react', from)82+ const version = reactDir && JSON.parse(readFileSync(resolve(reactDir, 'package.json'), 'utf8')).version83+ if (typeof version === 'string' && /^18\./.test(version)) {84+ compiler.options.module.rules.push({85+ test: /\.js$/,86+ include: (file: string) => realpathSync(file).replaceAll('\\', '/').startsWith(root.replaceAll('\\', '/') + '/dist/'),@@ -0,0 +1,18 @@1+const { realpathSync } = require('node:fs')2+const { relative, resolve } = require('node:path')3+const { pathToFileURL } = require('node:url')4+const { parse } = require('acorn')5+6+module.exports = function(source, inputMap) {7+ const done = this.async()8+ const { packageRoot, version } = this.getOptions()9+ const root = realpathSync(resolve(packageRoot, 'dist'))10+ const resource = realpathSync(this.resourcePath)11+ const moduleName = relative(root, resource).replaceAll('\\', '/').replace(/\.js$/, '')12+ if (!/^18\./.test(version) || moduleName.startsWith('../') || moduleName === '..') {13+ done(null, source, inputMap)14+ return15+ }16+ import(pathToFileURL(resolve(root, 'vite/react18.js')).href).then(({ adaptReact18 }) => {17+ const result = adaptReact18(source, this.resourcePath, moduleName, version,18+ code => parse(code, { ecmaVersion: 'latest', sourceType: 'module' }))
- @@ -0,0 +82,21 @@82+ return null83+}84+85+// When installed from npm, `@tanstack/redact` is declared as a `dependency`86+// of consumer apps. Under pnpm's strict mode it ends up nested under the87+// plugin's own `.pnpm/@tanstack+redact@.../node_modules/` rather than88+// hoisted to the consumer's root, so a `findPackageDir` walk starting at89+// the Vite project root won't always find it. Search from the plugin's own90+// directory first (which walks into its nested node_modules), then fall91+// back to the consumer root for hoisted installs.92+const pluginDir = dirname(fileURLToPath(import.meta.url))93+94+export function resolvePackageDir(95+ pkg: string,96+ fromDir: string,97+ packageRoots: Record<string, string>,98+ preferFrom = false,99+): string | null {100+ return packageRoots[pkg] ?? (preferFrom101+ ? findPackageDir(pkg, fromDir) ?? findPackageDir(pkg, pluginDir)102+ : findPackageDir(pkg, pluginDir) ?? findPackageDir(pkg, fromDir))
tannerlinsley merged this3f222d3
tannerlinsley closed this
Sign in to join this conversation.
🦋 Changeset detected#
Latest commit: 989fc2fac9df0860089e6521c266c11a3ce742aa
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR