diff --git a/docs/4.configuration.md b/docs/4.configuration.md index 52369111..a2f0ffcb 100644 --- a/docs/4.configuration.md +++ b/docs/4.configuration.md @@ -59,7 +59,7 @@ An entry is either bundled into one file, like `src/module.ts`, or transpiled fi The build writes each bundled entry to `dist/.mjs`, with its declarations in `dist/.d.mts`. The entries in the example above produce `dist/utils.mjs` and `dist/kit.mjs`. Add each one to the `exports` of `package.json`, as described in [Exports](/docs/api/module-builder/exports#bundled-entries). -Relative imports in a bundled entry carry the imported file's extension, as in module code. [Source exports](/docs/api/module-builder/develop-and-publish#source-exports) point at the entry as it is, so the entry has to load as written: +Relative imports in a bundled entry carry the imported file's extension, as in module code. [Source exports](/docs/api/module-builder/develop-and-publish#source-exports) point at the entry as it is, so when `exports` or `imports` point at it, the entry and the files that it imports follow every rule of [module code](/docs/api/module-builder/typescript#module-code): ```ts [src/utils.ts] import { normalizeOptions } from './options.ts' diff --git a/docs/5.typescript.md b/docs/5.typescript.md index 15296f3c..b90bda25 100644 --- a/docs/5.typescript.md +++ b/docs/5.typescript.md @@ -165,8 +165,9 @@ Each part is type-checked on its own, with the files that it imports and the typ - `src/module.ts`. - Every file that `src/module.ts` imports by value, including runtime files. - `tsdown.config.ts`. +- With [source exports](/docs/api/module-builder/develop-and-publish#source-exports), each [bundled entry](/docs/api/module-builder/configuration#bundled-entries) that `exports` or `imports` points at, and every file that it imports by value. -Node strips types and resolves imports as written. Module code therefore follows the rules in the following sections. `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and every piece of syntax that breaks them. Each entry has its file, line, column, and fix, and an entry in a runtime file also names the module code that imports it. An import that the check can't follow, such as one of a file that doesn't exist yet, ends the list: the files behind it are checked once it resolves. Until the list is empty, `prepare` doesn't generate `.nuxt`. +Node strips types and resolves imports as written. Module code therefore follows the rules in the following sections. `prepare`, `tsdown`, and `nuxt-module-build build` stop with a list of every import and every piece of syntax that breaks them. Each entry has its file, line, column, and fix, and an entry in a runtime file also names the module code that imports it. A problem in a bundled entry, or in a file that it imports, names the key of `exports` or `imports` that points at the bundled entry. An import that the check can't follow, such as one of a file that doesn't exist yet, ends the list: the files behind it are checked once it resolves. Until the list is empty, `prepare` doesn't generate `.nuxt`. ### Relative imports carry their extension diff --git a/docs/upgrade-v2.md b/docs/upgrade-v2.md index 79e5eb52..781363e1 100644 --- a/docs/upgrade-v2.md +++ b/docs/upgrade-v2.md @@ -141,7 +141,7 @@ After each build, a warning lists any other path in these fields that the build ### Step 4: Make module code load with Node -`nuxt-module-build prepare` and the build load module code with Node, as Nuxt 5 does. Module code is `src/module.ts`, every file that it imports by value (runtime files included), and `tsdown.config.ts`. In these files: +`nuxt-module-build prepare` and the build load module code with Node, as Nuxt 5 does. Module code is `src/module.ts`, every file that it imports by value (runtime files included), and `tsdown.config.ts`. With the source exports of step 6, it also includes each bundled entry that `exports` or `imports` points at, and the files that it imports by value. In these files: - Add the file's extension to every relative import, type-only imports included: `./utils` becomes `./utils.ts`, and `./dir` becomes `./dir/index.ts`. - Replace imports through tsconfig `paths` aliases with relative imports, or with entries in the `imports` field of `package.json`. diff --git a/src/build/build.ts b/src/build/build.ts index 13148e9c..c9bd7650 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -140,7 +140,7 @@ function reportReplacedPaths(cwd: string, tsconfigs: TsconfigResolver) { export async function prepareBuild(plan: BuildPlan, { keepOutput }: { keepOutput: boolean }): Promise { const { cwd, outDir, entries, runtimeDirs } = plan await plan.config.callHook?.('build:before', plan) - assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries)) + assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, { entries, pkg: plan.pkg, outDir }) if (!keepOutput) { await rm(outDir, { recursive: true, force: true }) } diff --git a/src/build/loader.ts b/src/build/loader.ts index 30c0bc93..1e42618f 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' import { registerHooks } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' -import { dirname, join, relative, resolve } from 'pathe' +import { basename, dirname, join, relative, resolve } from 'pathe' import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type { Diagnostic } from 'nostics' import type { Expression, ImportDeclaration, ObjectExpression, TSGlobalDeclaration, TSModuleDeclaration } from '@oxc-project/types' @@ -12,7 +12,7 @@ import { packageName } from '../transpile/tsconfig.ts' import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { errors } from '../diagnostics.ts' -import { importsKeyFor } from './package.ts' +import { importsKeyFor, sourceLoadedEntries } from './package.ts' const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/ const PATH_ALIAS_RE = /^(?:~|@\/)/ @@ -71,6 +71,8 @@ export interface ModuleCodeIssue { column: number /** For a file in a runtime directory, the module code that imports it, as `file:line`. */ importedBy?: string + /** For a bundled entry loaded from source and the files it imports, the key of `package.json` that loads it, such as `` `./utils` in `exports` ``. */ + loadedBy?: string /** What Node cannot load, and what to write instead. */ message: string /** Whether the issue is an import that the check cannot follow, so the files it imports are not checked. */ @@ -87,6 +89,14 @@ const NON_ERASABLE: Array<[message: string, matches: (node: Node, parent: Node | ['decorator (call the decorator as a function)', node => node.type === 'Decorator'], ] +export interface BundledEntries { + /** Bundled entries keyed by output name, as paths relative to the module root. */ + entries: Record + /** `package.json` as it is on disk. */ + pkg: PackageJson + outDir: string +} + /** * Everything in `entries` and the sources they import by value, which Node loads with * them, that Node cannot load as written: TypeScript syntax that stripping types does not @@ -94,16 +104,16 @@ const NON_ERASABLE: Array<[message: string, matches: (node: Node, parent: Node | * the aliases only a Nuxt app provides. Type-only imports are erased before Node sees * them. Files in `runtimeDirs` that are not imported this way are left to the build. * - * `otherEntries`, bundled entries that source exports point at as they are, only need the - * extensions of their relative imports outside `runtimeDirs`. + * The `bundled` entries that `exports` or `imports` load from source are checked in the same + * way, and an entry that is itself a `.tsx` or `.vue` file is reported, as Node loads neither. The others are loaded from `outDir`, once built, so they only need the extensions of + * their relative imports outside `runtimeDirs`. */ -export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs: string[], otherEntries: string[] = []): ModuleCodeIssue[] { +export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs: string[], bundled?: BundledEntries): ModuleCodeIssue[] { const found: ModuleCodeIssue[] = [] - const checked = new Set() - walkSources(cwd, entries, (file, analysis, importer) => { - checked.add(file) + const visit = (loadedBy?: string) => (file: string, analysis: SourceAnalysis, importer?: Importer) => { const importedBy = importer && runtimeDirs.some(dir => isInside(dir, file)) ? `${relative(cwd, importer.file)}:${importer.line}` : undefined - const issue = (location: { line: number, column: number }, message: string) => found.push({ file: relative(cwd, file), ...location, ...importedBy && { importedBy }, message }) + const context = { ...importedBy && { importedBy }, ...loadedBy && { loadedBy } } + const issue = (location: { line: number, column: number }, message: string) => found.push({ file: relative(cwd, file), ...location, ...context, message }) for (const { message, ...location } of analysis.nonErasable) { issue(location, message) } @@ -112,14 +122,16 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs continue } if (typeof resolution === 'string' && resolution !== EXTERNAL) { - found.push({ file: relative(cwd, file), ...location, ...importedBy && { importedBy }, message: `\`${specifier}\` ${resolution}`, unfollowed: true }) + found.push({ file: relative(cwd, file), ...location, ...context, message: `\`${specifier}\` ${resolution}`, unfollowed: true }) continue } if (VIRTUAL_ALIAS_RE.test(specifier)) { issue(location, `\`${specifier}\` only exists in a Nuxt app (move the code that uses it into a runtime file the module adds, or import types only)`) } - if (JSON_RE.test(typeof resolution === 'object' ? resolution.file : specifier) && !json) { - issue(location, `\`${specifier}\` is JSON (use \`import pkg from '${specifier}' with { type: 'json' }\` and read \`pkg.version\`; destructuring \`pkg\` bundles the whole file)`) + const target = typeof resolution === 'object' ? resolution.file : specifier + if (JSON_RE.test(target) && !json) { + const [name, read] = basename(target) === 'package.json' ? ['pkg', '`pkg.version`'] : ['data', 'properties from `data`'] + issue(location, `\`${specifier}\` is JSON (use \`import ${name} from '${specifier}' with { type: 'json' }\` and read ${read}; destructuring \`${name}\` bundles the whole file)`) } if (typeof resolution !== 'object') { continue @@ -136,9 +148,29 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs issue(location, `\`${specifier}\` is a tsconfig \`paths\` alias (use \`${suggestion}\`, or an entry in the \`imports\` of \`package.json\`)`) } } - }) + } + const walked = walkState(cwd) + const roots = new Set() + const reportUnloadableRoot = (file: string, loadedBy?: string) => { + if (roots.has(file) || !UNLOADABLE_RE.test(file) || !existsSync(file)) { + return + } + roots.add(file) + const kind = file.endsWith('.vue') ? 'a single-file component' : 'JSX' + found.push({ file: relative(cwd, file), line: 1, column: 1, ...loadedBy && { loadedBy }, message: `\`${relative(cwd, file)}\` is ${kind}, which Node cannot load (write it as \`.ts\`)` }) + } + for (const entry of entries) { + reportUnloadableRoot(resolve(cwd, entry)) + } + walkSources(cwd, entries, visit(), walked) + const otherEntries = Object.values(bundled?.entries ?? {}) + const sourceLoaded = bundled ? sourceLoadedEntries(cwd, bundled.pkg, bundled.outDir, bundled.entries) : new Map() + for (const [file, loadedBy] of sourceLoaded) { + reportUnloadableRoot(file, loadedBy) + walkSources(cwd, [file], visit(loadedBy), walked) + } walkSources(cwd, otherEntries, (file, analysis) => { - if (checked.has(file) || runtimeDirs.some(dir => isInside(dir, file))) { + if (runtimeDirs.some(dir => isInside(dir, file))) { return } for (const { specifier, typeOnly, json: _, resolution, ...location } of analysis.imports) { @@ -146,7 +178,7 @@ export function findModuleCodeIssues(cwd: string, entries: string[], runtimeDirs found.push({ file: relative(cwd, file), ...location, message: `\`${specifier}\` (use \`${relativeSpecifier(file, resolution.file)}\`)` }) } } - }) + }, walked) return found.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column) } @@ -156,8 +188,8 @@ export function hasLoadIssues(found: ModuleCodeIssue[]): boolean { } /** Fails for {@link findModuleCodeIssues} findings. */ -export function assertLoadableModuleCode(cwd: string, entries: string[], runtimeDirs: string[], otherEntries: string[] = []): void { - const found = findModuleCodeIssues(cwd, entries, runtimeDirs, otherEntries) +export function assertLoadableModuleCode(cwd: string, entries: string[], runtimeDirs: string[], bundled?: BundledEntries): void { + const found = findModuleCodeIssues(cwd, entries, runtimeDirs, bundled) if (hasLoadIssues(found)) { throw moduleCodeError(cwd, found) } @@ -191,9 +223,17 @@ interface Importer { line: number } -function walkSources(cwd: string, entries: string[], visit: (file: string, analysis: SourceAnalysis, importer?: Importer) => void) { - const paths = pathsMatcher(cwd) - const seen = new Set() +/** What every walk of these sources shares, so that a file reached from several entries is analysed once. */ +interface WalkState { + seen: Set + paths: PathsMatcher +} + +function walkState(cwd: string): WalkState { + return { seen: new Set(), paths: pathsMatcher(cwd) } +} + +function walkSources(cwd: string, entries: string[], visit: (file: string, analysis: SourceAnalysis, importer?: Importer) => void, { seen, paths }: WalkState = walkState(cwd)) { const queue: Array<{ file: string, importer?: Importer }> = entries.map(entry => ({ file: resolve(cwd, entry) })) while (queue.length) { const { file, importer } = queue.shift()! diff --git a/src/build/package.ts b/src/build/package.ts index f9bfcfef..ac3f4df2 100644 --- a/src/build/package.ts +++ b/src/build/package.ts @@ -3,7 +3,7 @@ import { basename, join, relative, resolve } from 'pathe' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts' import type { Diagnostic } from 'nostics' import { errors, warnings } from '../diagnostics.ts' -import { DECLARATION_RE, isFile, isInside, readPackageJson, TYPESCRIPT_RE } from '../utils.ts' +import { DECLARATION_RE, escapeRegExp, isFile, isInside, isPlainObject, probe, readPackageJson, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' import type { PackageJson } from '../utils.ts' /** The fields of `package.json` whose paths are checked for whether they can be published. */ @@ -239,6 +239,145 @@ export function selfReferencePaths(cwd: string, pkg: PackageJson, outDir: string return paths } +/** + * The bundled entries of `entries`, keyed by output name, that the `exports` or `imports` of + * `pkg`, as it is on disk, load from source. Each file maps to the key that loads it, such as + * `` `./utils` in `exports` ``. A key loads an entry when Node picks it for the subpath that + * reaches the entry, and one of its targets other than `types` resolves to the entry's file or + * its directory, or becomes the entry's output in `publishConfig`. + */ +export function sourceLoadedEntries(cwd: string, pkg: PackageJson, outDir: string, entries: Record): Map { + const found = new Map() + const published = publishedPackage(pkg) + for (const field of ['exports', 'imports'] as const) { + const targets = keyedTargets(field, pkg[field]) + const keys = [...targets.keys()] + const swapped = keyedTargets(field, published[field]) + for (const [key, values] of targets) { + const sources = values.filter(target => target.startsWith('./') && !DECLARATION_RE.test(target) && !isInside(outDir, resolve(cwd, target))) + if (!sources.length) { + continue + } + for (const [name, entry] of Object.entries(entries)) { + const file = resolve(cwd, entry) + if (found.has(file)) { + continue + } + const { subpaths, anySubpath } = loadedSubpaths(key, sources, cwd, file) + const paths = [...subpaths, ...outputSubpaths(key, swapped.get(key) ?? [], cwd, outDir, name)] + if (anySubpath || paths.some(path => importsKeyFor(keys, path) === key)) { + found.set(file, `\`${key}\` in \`${field}\``) + } + } + } + } + return found +} + +/** The subpaths of `key` whose targets in `outDir` produce the output named `name`. */ +function outputSubpaths(key: string, targets: string[], cwd: string, outDir: string, name: string): string[] { + const subpaths = new Set() + for (const target of targets) { + const file = resolve(cwd, target) + if (!isInside(outDir, file)) { + continue + } + const output = `./${relative(outDir, file).replace(/(?:\.d)?\.[cm]?[jt]s$/, '')}` + if (output === `./${name}`) { + subpaths.add(key) + continue + } + const value = starValue(output, `./${name}`) + if (value !== undefined) { + subpaths.add(key.replaceAll('*', value)) + } + } + return [...subpaths] +} + +/** The subpaths of `key` whose source targets reach `file`, and whether a target reaches it at every subpath. */ +function loadedSubpaths(key: string, targets: string[], cwd: string, file: string): { subpaths: string[], anySubpath: boolean } { + const subpaths = new Set() + for (const target of targets) { + if (!targetReaches(cwd, target, file)) { + continue + } + if (!key.includes('*')) { + subpaths.add(key) + continue + } + const values = starValues(cwd, target, file) + if (!values.length) { + return { subpaths: [], anySubpath: true } + } + for (const value of values) { + subpaths.add(key.replaceAll('*', value)) + } + } + return { subpaths: [...subpaths], anySubpath: false } +} + +/** + * Whether `target` reaches `file`, after Node replaces each `*` of the target with the same + * subpath and resolves the result as an import. + */ +function targetReaches(cwd: string, target: string, file: string): boolean { + if (target.includes('*')) { + return starValues(cwd, target, file).length > 0 + } + if (target.endsWith('/')) { + const dir = target.slice(0, -1) + return entryCandidates(cwd, file).some(candidate => `${candidate}/`.startsWith(`${dir}/`)) + } + return probe(resolve(cwd, target)) === file +} + +/** The values of `*`, each substituted for every `*` of `target`, that resolve to `file`. */ +function starValues(cwd: string, target: string, file: string): string[] { + const values = new Set() + for (const candidate of entryCandidates(cwd, file)) { + const value = starValue(target, candidate) + if (value !== undefined && probe(resolve(cwd, target.replaceAll('*', value))) === file) { + values.add(value) + } + } + return [...values] +} + +/** The value every `*` of `target` needs for it to produce `candidate`. As in Node, a `*` matches at least one character. */ +function starValue(target: string, candidate: string): string | undefined { + const [first, ...rest] = target.split('*') + if (!rest.length) { + return undefined + } + const source = `${escapeRegExp(first!)}(.*)${rest.map((part, index) => `${index ? '\\1' : ''}${escapeRegExp(part)}`).join('')}` + return new RegExp(`^${source}$`).exec(candidate)?.[1] || undefined +} + +/** The ways `package.json` can write the path of `file`: as it is, with `js` for `ts`, and without its extension. */ +function entryCandidates(cwd: string, file: string): string[] { + const path = `./${relative(cwd, file)}` + return [path, path.replace(/\.([cm]?)ts(x?)$/, '.$1js$2'), path.replace(SCRIPT_RE, '')] +} + +function keyedTargets(field: 'exports' | 'imports', value: unknown): Map { + const keyed = isPlainObject(value) ? Object.entries(value).filter(([key]) => key.startsWith(field === 'exports' ? '.' : '#')) : [] + if (field === 'exports' && !keyed.length && value !== undefined) { + return new Map([['.', runtimeTargets(value)]]) + } + return new Map(keyed.map(([key, target]) => [key, runtimeTargets(target)])) +} + +function runtimeTargets(value: unknown): string[] { + if (typeof value === 'string') { + return [value] + } + if (Array.isArray(value)) { + return value.flatMap(runtimeTargets) + } + return isPlainObject(value) ? Object.entries(value).flatMap(([condition, target]) => condition === 'types' ? [] : runtimeTargets(target)) : [] +} + function exportTarget(target: unknown): string | undefined { if (typeof target === 'string') { return target diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 3aa93073..41679b17 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -105,7 +105,7 @@ export async function prepareModule(cwd: string, prepareConfig?: PrepareConfig, const { config, outDir, pkg } = prepareConfig ?? await loadPrepareConfig(cwd) const runtimeDirs = [resolve(cwd, 'src/runtime'), ...config.directories.map(directory => directory.srcDir)] const entries = bundledEntries(cwd, config) - assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, Object.values(entries)) + assertLoadableModuleCode(cwd, [entries.module], runtimeDirs, { entries, pkg, outDir }) const entryPath = resolve(cwd, entries.module) const moduleExports = await importModule(entryPath, { cwd }) const nuxtModule = (moduleExports.default ?? moduleExports) as NuxtModule diff --git a/src/diagnostics.ts b/src/diagnostics.ts index dac60779..87ce1c6f 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -47,10 +47,15 @@ export interface BundledPackage { export const errorCodes = { NUXT_MB_B0001: { why: (p: { issues: ModuleCodeIssue[] }): string => { - const line = ({ file, line, column, importedBy, message }: ModuleCodeIssue) => ` - ${file}:${line}:${column}${importedBy ? ` (imported by ${importedBy})` : ''}: ${message}` + const line = ({ file, line, column, importedBy, loadedBy, message }: ModuleCodeIssue) => { + const context = [...importedBy ? [`imported by ${importedBy}`] : [], ...loadedBy ? [`loaded from source through ${loadedBy}`] : []] + return ` - ${file}:${line}:${column}${context.length ? ` (${context.join(', ')})` : ''}: ${message}` + } const unfollowed = p.issues.filter(issue => issue.unfollowed) return [ - 'Module code has to load with Node, which strips types and resolves imports as written:', + p.issues.some(issue => issue.loadedBy) + ? 'Module code, and the bundled entries that `package.json` points at as source, have to load with Node, which strips types and resolves imports as written:' + : 'Module code has to load with Node, which strips types and resolves imports as written:', ...new Set(p.issues.filter(issue => !issue.unfollowed).map(line)), ...unfollowed.length ? ['The check stopped at these imports, so the files they import may have more of these problems:', ...new Set(unfollowed.map(line))] : [], ].join('\n') diff --git a/src/legacy/build-config.ts b/src/legacy/build-config.ts index f4c3cddc..cfedabfb 100644 --- a/src/legacy/build-config.ts +++ b/src/legacy/build-config.ts @@ -218,7 +218,7 @@ export async function loadBuildConfig(cwd: string, pkg: PackageJson, outDir: str const withoutFile = translateBuildConfig(fieldSource, { cwd, outDir }) const runtimeDirs = [resolve(cwd, 'src/runtime'), ...withoutFile.directories.map(directory => directory.srcDir)] const entries = bundledEntries(cwd, withoutFile) - unresolvable.push(...findModuleCodeIssues(cwd, [entries.module], runtimeDirs, Object.values(entries))) + unresolvable.push(...findModuleCodeIssues(cwd, [entries.module], runtimeDirs, { entries, pkg, outDir })) throw moduleCodeError(cwd, unresolvable) } const { default: config } = await importModule(resolve(cwd, file), { cwd, stubs }) diff --git a/test/cli.spec.ts b/test/cli.spec.ts index 45aea15c..161acc93 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -335,6 +335,25 @@ export type { Kit } from './kit' }, }) + dirs.sourceEntries = await fixture('.temp-cli/source-entries', { + from, + config: `export default {\n plugins: [builder({ entries: ['./src/utils', './src/stats', './src/vite'] })],\n}\n`, + pkg: ({ typesVersions: _, ...pkg }) => ({ + ...pkg, + exports: { '.': { types: './.nuxt/module-builder/types.d.mts', default: './src/module.ts' }, './utils': './src/utils.ts', './stats': './src/stats.ts', './vite': './dist/vite.mjs' }, + main: './src/module.ts', + publishConfig: { + exports: { '.': { types: './dist/types.d.mts', default: './dist/module.mjs' }, './utils': './dist/utils.mjs', './stats': './dist/stats.mjs', './vite': './dist/vite.mjs' }, + main: './dist/module.mjs', + }, + }), + files: { + 'src/registry.json': `{ "scripts": [] }\n`, + 'src/stats.ts': `import registry from './registry.json'\n\nexport const stats = (): number => registry.scripts.length\n`, + 'src/vite.ts': `import registry from './registry.json'\nimport { stats } from './stats'\n\nexport const vite = (): number => registry.scripts.length + stats()\n`, + }, + }) + dirs.unloadableDist = await fixture('.temp-cli/unloadable-dist', { from, module: source => `${source}\nif (new URL(import.meta.url).pathname.endsWith('.mjs')) {\n throw new Error('fails once built')\n}\n`, @@ -670,6 +689,8 @@ export type { Kit } from './kit' step('unloadable', cli(['build', dirs.unloadable])), step('unloadable:prepare', cli(['prepare', dirs.unloadable])), step('unloadableDist', cli(['build', dirs.unloadableDist])), + step('sourceEntries', cli(['build', dirs.sourceEntries])), + step('sourceEntries:prepare', cli(['prepare', dirs.sourceEntries])), step('isolatedError', cli(['build', dirs.isolatedError])), step('typeError', cli(['build', dirs.typeError])), step('vueError', cli(['build', dirs.vueError])), @@ -1248,6 +1269,19 @@ describe('a module whose code Node cannot load', () => { expect(exists(dirs.unloadable!, 'dist')).toBe(false) }) + it('should fail to build and prepare when a bundled entry that `exports` loads from source imports JSON without an import attribute', () => { + for (const name of ['sourceEntries', 'sourceEntries:prepare']) { + const output = withoutGuide(expectFailed(name)) + expect(output, name).toContain('Module code, and the bundled entries that `package.json` points at as source, have to load with Node') + expect(output, name).toContain([ + ' - src/stats.ts:1:22 (loaded from source through `./stats` in `exports`): `./registry.json` is JSON (use `import data from \'./registry.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + ' - src/vite.ts:2:23: `./stats` (use `./stats.ts`)', + ].join('\n')) + expect(output, name).not.toContain('src/vite.ts:1:') + } + expect(exists(dirs.sourceEntries!, 'dist')).toBe(false) + }) + it('should fail and remove the output when the built module cannot be loaded', () => { expect(expectFailed('unloadableDist')).toContain('[NUXT_MB_B0002] Cannot load `dist/module.mjs` to write `module.json`: fails once built') expect(exists(dirs.unloadableDist!, 'dist')).toBe(false) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 8b729c1c..abc3b9ba 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -8,7 +8,7 @@ import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { satisfies } from 'verkit' import { version as nuxtVersion } from 'nuxt/package.json' import { version } from '../package.json' -import { basename, dirname, join, resolve } from 'pathe' +import { basename, dirname, join, relative, resolve } from 'pathe' import { parseTsconfig } from 'get-tsconfig' import { analyseSources, finishBuild, hashGeneratedTypes, moduleTsconfigs, onBuildError } from '../src/build/build.ts' import type { BuildPlan } from '../src/build/build.ts' @@ -33,7 +33,7 @@ import { findTypescript, loadTypescript } from '../src/transpile/typescript.ts' import { assertSupportedTypescript, loadDeclarationEngine } from '../src/build/engine.ts' import { declarationTargets, rewriteRuntimeDeclarations } from '../src/build/aliases.ts' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths } from '../src/legacy/package-paths.ts' -import { checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField, importsKeyFor, publishedPackage, selfReferencePaths, sourcePathsPackError, unpublishableImportsError, unpublishablePathsError } from '../src/build/package.ts' +import { checkMissingPaths, checkNode10DeclarationPaths, checkStaleTypesField, importsKeyFor, publishedPackage, selfReferencePaths, sourceLoadedEntries, sourcePathsPackError, unpublishableImportsError, unpublishablePathsError } from '../src/build/package.ts' import { augmentsNuxtTypes, writeSourceTypes, writeTypes } from '../src/build/types.ts' import ts from 'typescript' import { errorCodes, errors, GUIDE_URL, unwrapBuildError, useBuildLogger, warningCodes, warnings } from '../src/diagnostics.ts' @@ -376,7 +376,10 @@ describe('hints', () => { }) describe('findModuleCodeIssues', () => { - const list = (found: ModuleCodeIssue[]) => found.map(({ file, line, column, importedBy, message }) => `${file}:${line}:${column}${importedBy ? ` (imported by ${importedBy})` : ''}: ${message}`) + const list = (found: ModuleCodeIssue[]) => found.map(({ file, line, column, importedBy, loadedBy, message }) => { + const context = [...importedBy ? [`imported by ${importedBy}`] : [], ...loadedBy ? [`loaded from source through ${loadedBy}`] : []] + return `${file}:${line}:${column}${context.length ? ` (${context.join(', ')})` : ''}: ${message}` + }) it('should only list namespaces that contain runtime code', async () => { const dir = await mkdtemp(join(tmpdir(), 'module-builder-namespaces-')) @@ -545,9 +548,9 @@ describe('findModuleCodeIssues', () => { expect(list(findModuleCodeIssues(dir, ['./src/module.ts'], [join(dir, 'src/runtime')]))).toEqual([ 'src/module.ts:1:18: `./runtime/Card.vue` is a single-file component, which Node cannot load (move the value the module needs into a `.ts` file, or use `import type`)', 'src/module.ts:3:23: `./runtime/label` is JSX, which Node cannot load (move the value the module needs into a `.ts` file, or use `import type`)', - 'src/module.ts:4:18: `./data.json` is JSON (use `import pkg from \'./data.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)', - 'src/module.ts:6:28: `./data.json` is JSON (use `import pkg from \'./data.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)', - 'src/module.ts:12:33: `./data.json` is JSON (use `import pkg from \'./data.json\' with { type: \'json\' }` and read `pkg.version`; destructuring `pkg` bundles the whole file)', + 'src/module.ts:4:18: `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + 'src/module.ts:6:28: `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + 'src/module.ts:12:33: `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', ]) } finally { @@ -684,6 +687,304 @@ describe('findModuleCodeIssues', () => { await rm(dir, { recursive: true, force: true }) } }) + + it('should check the bundled entries that `package.json` loads from source as module code, and only the extensions of the others', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-source-entries-')) + try { + await mkdir(join(dir, 'src/kit'), { recursive: true }) + await mkdir(join(dir, 'src/runtime'), { recursive: true }) + await writeFile(join(dir, 'package.json'), JSON.stringify({ + name: 'fixture', + type: 'module', + exports: { + '.': './src/module.ts', + './stats': './src/stats.ts', + './kit/*': './src/kit/*', + './vite': { types: './src/vite.ts', import: './src/vite.ts' }, + './built': { types: './src/built.ts', import: './dist/built.mjs' }, + './ok': './src/ok.ts', + './view': './src/view.tsx', + './built-jsx': { types: './src/built-jsx.tsx', import: './dist/built-jsx.mjs' }, + }, + publishConfig: { + exports: { '.': './dist/module.mjs', './stats': './dist/stats.mjs', './kit/*': './dist/kit/*', './vite': './dist/vite.mjs', './built': './dist/built.mjs', './ok': './dist/ok.mjs', './view': './dist/view.mjs', './built-jsx': './dist/built-jsx.mjs' }, + }, + })) + await writeFile(join(dir, 'src/module.ts'), `export default {}\n`) + await writeFile(join(dir, 'src/data.json'), `{}\n`) + await writeFile(join(dir, 'src/stats.ts'), `import data from './data.json'\nimport { helper } from './helper'\nimport { plugin } from './runtime/plugin.ts'\nexport default [data, helper, plugin]\n`) + await writeFile(join(dir, 'src/helper.ts'), `export enum Helper { On }\n`) + await writeFile(join(dir, 'src/runtime/plugin.ts'), `import { useNuxtApp } from '#app'\nexport const plugin = useNuxtApp\n`) + await writeFile(join(dir, 'src/kit/index.ts'), `import data from '../data.json'\nexport const kit = data\n`) + await writeFile(join(dir, 'src/vite.ts'), `export namespace Vite { export const value = 1 }\nexport class Plugin { constructor(private name: string) {} }\n`) + await writeFile(join(dir, 'src/built.ts'), `import data from './data.json'\nimport { helper } from './helper'\nexport enum Built { On }\nexport default [data, helper]\n`) + await writeFile(join(dir, 'src/ok.ts'), `import data from './data.json' with { type: 'json' }\nimport { tail } from './tail.ts'\nexport default [data, tail]\n`) + await writeFile(join(dir, 'src/tail.ts'), `export const tail = 1\n`) + await writeFile(join(dir, 'src/unexported.ts'), `import data from './data.json'\nexport default data\n`) + await writeFile(join(dir, 'src/view.tsx'), `export const value = 1\n`) + await writeFile(join(dir, 'src/built-jsx.tsx'), `export const value = 1\n`) + const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) + const entries = { module: './src/module.ts', stats: './src/stats.ts', kit: './src/kit/index.ts', vite: './src/vite.ts', built: './src/built.ts', ok: './src/ok.ts', unexported: './src/unexported.ts', view: './src/view.tsx', builtJsx: './src/built-jsx.tsx' } + expect(list(findModuleCodeIssues(dir, ['./src/module.ts'], [join(dir, 'src/runtime')], { entries, pkg, outDir: join(dir, 'dist') }))).toEqual([ + 'src/built.ts:2:24: `./helper` (use `./helper.ts`)', + 'src/helper.ts:1:1 (loaded from source through `./stats` in `exports`): `enum` (use an `as const` object and a union type of its values)', + 'src/kit/index.ts:1:18 (loaded from source through `./kit/*` in `exports`): `../data.json` is JSON (use `import data from \'../data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + 'src/runtime/plugin.ts:1:28 (imported by src/stats.ts:3, loaded from source through `./stats` in `exports`): `#app` only exists in a Nuxt app (move the code that uses it into a runtime file the module adds, or import types only)', + 'src/stats.ts:1:18 (loaded from source through `./stats` in `exports`): `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + 'src/stats.ts:2:24 (loaded from source through `./stats` in `exports`): `./helper` (use `./helper.ts`)', + 'src/view.tsx:1:1 (loaded from source through `./view` in `exports`): `src/view.tsx` is JSX, which Node cannot load (write it as `.ts`)', + 'src/vite.ts:1:1 (loaded from source through `./vite` in `exports`): `namespace` (use plain exports or an object)', + 'src/vite.ts:2:35 (loaded from source through `./vite` in `exports`): parameter property (declare the field and assign it in the constructor)', + ]) + + const message = moduleCodeError(dir, findModuleCodeIssues(dir, ['./src/module.ts'], [], { entries: { stats: './src/stats.ts' }, pkg, outDir: join(dir, 'dist') })).message.split('\n') + expect(message[0]).toContain('Module code, and the bundled entries that `package.json` points at as source, have to load with Node, which strips types and resolves imports as written:') + expect(message).toContain(' - src/stats.ts:1:18 (loaded from source through `./stats` in `exports`): `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)') + + expect(list(findModuleCodeIssues(dir, ['./src/module.ts'], [], { entries, pkg: { ...pkg, exports: pkg.publishConfig.exports, publishConfig: undefined }, outDir: join(dir, 'dist') }))).toEqual([ + 'src/built.ts:2:24: `./helper` (use `./helper.ts`)', + 'src/stats.ts:2:24: `./helper` (use `./helper.ts`)', + ]) + + await writeFile(join(dir, 'src/module.ts'), `export enum Module { On }\n`) + await writeFile(join(dir, 'src/stats.ts'), `import data from './data.json'\nimport './missing.ts'\nexport default data\n`) + expect(moduleCodeError(dir, findModuleCodeIssues(dir, ['./src/module.ts'], [], { entries: { module: './src/module.ts', stats: './src/stats.ts' }, pkg, outDir: join(dir, 'dist') })).message.split('\n').slice(1)).toEqual([ + ' - src/module.ts:1:1: `enum` (use an `as const` object and a union type of its values)', + ' - src/stats.ts:1:18 (loaded from source through `./stats` in `exports`): `./data.json` is JSON (use `import data from \'./data.json\' with { type: \'json\' }` and read properties from `data`; destructuring `data` bundles the whole file)', + 'The check stopped at these imports, so the files they import may have more of these problems:', + ' - src/stats.ts:2:8 (loaded from source through `./stats` in `exports`): `./missing.ts` resolves to no file', + ]) + + await writeFile(join(dir, 'src/Card.vue'), `\n`) + expect(list(findModuleCodeIssues(dir, ['./src/Card.vue'], []))).toEqual([ + 'src/Card.vue:1:1: `src/Card.vue` is a single-file component, which Node cannot load (write it as `.ts`)', + ]) + expect(list(findModuleCodeIssues(dir, ['./src/view.tsx'], [], { entries: { view: './src/view.tsx' }, pkg, outDir: join(dir, 'dist') }))).toEqual([ + 'src/view.tsx:1:1: `src/view.tsx` is JSX, which Node cannot load (write it as `.ts`)', + ]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should report a file that module code and a bundled entry both import once, as module code', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-shared-source-')) + try { + await mkdir(join(dir, 'src')) + await writeFile(join(dir, 'package.json'), JSON.stringify({ name: 'fixture', type: 'module', exports: { '.': './src/module.ts', './stats': './src/stats.ts' } })) + await writeFile(join(dir, 'src/module.ts'), `import { shared } from './shared.ts'\nexport default shared\n`) + await writeFile(join(dir, 'src/shared.ts'), `export enum Shared { On }\n`) + await writeFile(join(dir, 'src/stats.ts'), `import { shared } from './shared.ts'\nimport { helper } from './helper'\nexport default [shared, helper]\n`) + await writeFile(join(dir, 'src/helper.ts'), `export const helper = 1\n`) + const pkg = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) + const bundled = { entries: { module: './src/module.ts', stats: './src/stats.ts' }, pkg, outDir: join(dir, 'dist') } + expect(list(findModuleCodeIssues(dir, ['./src/module.ts'], [], bundled))).toEqual([ + 'src/shared.ts:1:1: `enum` (use an `as const` object and a union type of its values)', + 'src/stats.ts:2:24 (loaded from source through `./stats` in `exports`): `./helper` (use `./helper.ts`)', + ]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}) + +describe('sourceLoadedEntries', () => { + it('should find the bundled entries that a target of `exports` or `imports` other than `types` can load from source', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-source-loaded-')) + try { + const names = ['exact', 'conditional', 'typesOnly', 'wildcard', 'folder', 'directory', 'js', 'swapped', 'imported', 'dist', 'unexported'] + await mkdir(join(dir, 'src/folder'), { recursive: true }) + await mkdir(join(dir, 'src/directory'), { recursive: true }) + await mkdir(join(dir, 'src/wild'), { recursive: true }) + const entries: Record = Object.fromEntries(names.map(name => [name, name === 'folder' || name === 'directory' ? `./src/${name}/index.ts` : name === 'wildcard' ? './src/wild/entry.ts' : `./src/${name}.ts`])) + for (const entry of Object.values(entries)) { + await writeFile(join(dir, entry), `export {}\n`) + } + await writeFile(join(dir, 'src/other.ts'), `export {}\n`) + const pkg = { + exports: { + './exact': './src/exact.ts', + './conditional': { types: './src/conditional.ts', node: { development: './src/conditional.ts' }, default: './dist/conditional.mjs' }, + './types-only': { types: './src/typesOnly.ts', default: './dist/typesOnly.mjs' }, + './wild/*': './src/wild/*.ts', + './folder/': './src/folder/', + './directory': './src/directory', + './js': './src/js.js', + './swapped': './src/other.ts', + './dist': './dist/dist.mjs', + }, + imports: { '#imported': { import: './src/imported.ts' } }, + publishConfig: { exports: { './swapped': './dist/swapped.mjs' } }, + } + const found = sourceLoadedEntries(dir, pkg, join(dir, 'dist'), entries) + expect(Object.fromEntries([...found].map(([file, key]) => [relative(dir, file), key]))).toEqual({ + 'src/exact.ts': '`./exact` in `exports`', + 'src/conditional.ts': '`./conditional` in `exports`', + 'src/wild/entry.ts': '`./wild/*` in `exports`', + 'src/folder/index.ts': '`./folder/` in `exports`', + 'src/directory/index.ts': '`./directory` in `exports`', + 'src/js.ts': '`./js` in `exports`', + 'src/swapped.ts': '`./swapped` in `exports`', + 'src/imported.ts': '`#imported` in `imports`', + }) + expect(sourceLoadedEntries(dir, { exports: ['./src/exact.ts', './dist/exact.mjs'] }, join(dir, 'dist'), entries)).toEqual(new Map([[join(dir, 'src/exact.ts'), '`.` in `exports`']])) + expect(sourceLoadedEntries(dir, { exports: { './wild/*': './src/wild/*.js', './index/*': './src/*/index' } }, join(dir, 'dist'), entries)).toEqual(new Map([ + [join(dir, 'src/wild/entry.ts'), '`./wild/*` in `exports`'], + [join(dir, 'src/folder/index.ts'), '`./index/*` in `exports`'], + [join(dir, 'src/directory/index.ts'), '`./index/*` in `exports`'], + ])) + expect(sourceLoadedEntries(dir, { exports: { '.': './dist/module.mjs', './*': './dist/*.mjs' } }, join(dir, 'dist'), entries).size).toBe(0) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should follow the key that Node picks for a subpath', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-shadowed-exports-')) + try { + const files = { + 'src/shadowed/file.ts': 'shadowed/file', + 'src/shadowed/vite.ts': 'vite', + 'src/blocked/none.ts': 'blocked/none', + 'src/blocked/open.ts': 'blocked/open', + } + for (const file of Object.keys(files)) { + await mkdir(dirname(join(dir, file)), { recursive: true }) + await writeFile(join(dir, file), `export {}\n`) + } + const entries = Object.fromEntries(Object.entries(files).map(([file, name]) => [name, `./${file}`])) + const pkg = { + exports: { + './shadowed/*': './src/shadowed/*.ts', + './shadowed/vite': './dist/vite.mjs', + './blocked/*': './src/blocked/*.ts', + './blocked/none': null, + }, + } + expect(Object.fromEntries([...sourceLoadedEntries(dir, pkg, join(dir, 'dist'), entries)].map(([file, key]) => [relative(dir, file), key]))).toEqual({ + 'src/shadowed/file.ts': '`./shadowed/*` in `exports`', + 'src/blocked/open.ts': '`./blocked/*` in `exports`', + }) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should find an entry that `publishConfig` loads from source at a subpath other than its output name', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-swapped-subpath-')) + try { + const files = { 'src/thing.ts': 'thing', 'src/other.ts': 'other' } + for (const file of Object.keys(files)) { + await mkdir(dirname(join(dir, file)), { recursive: true }) + await writeFile(join(dir, file), `export {}\n`) + } + const entries = Object.fromEntries(Object.entries(files).map(([file, name]) => [name, `./${file}`])) + const pkg = { + exports: { './deep/thing': './src/absent.ts' }, + imports: { '#other': './src/absent.ts' }, + publishConfig: { exports: { './deep/thing': './dist/thing.mjs' }, imports: { '#other': './dist/other.mjs' } }, + } + expect(Object.fromEntries([...sourceLoadedEntries(dir, pkg, join(dir, 'dist'), entries)].map(([file, key]) => [relative(dir, file), key]))).toEqual({ + 'src/thing.ts': '`./deep/thing` in `exports`', + 'src/other.ts': '`#other` in `imports`', + }) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should find an entry that a wildcard target without a `*` loads from source', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-starless-target-')) + try { + await mkdir(join(dir, 'src'), { recursive: true }) + await writeFile(join(dir, 'src/starless.ts'), `export {}\n`) + expect([...sourceLoadedEntries(dir, { exports: { './starless/*': './src/starless.ts' } }, join(dir, 'dist'), { starless: './src/starless.ts' })]).toEqual([[join(dir, 'src/starless.ts'), '`./starless/*` in `exports`']]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should find an entry that `publishConfig` publishes under another output path', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-flattened-output-')) + try { + await mkdir(join(dir, 'src'), { recursive: true }) + await writeFile(join(dir, 'src/thing.ts'), `export {}\n`) + const pkg = { exports: { './kit/*': './src/absent/*.ts' }, publishConfig: { exports: { './kit/*': './dist/*.mjs' } } } + expect([...sourceLoadedEntries(dir, pkg, join(dir, 'dist'), { thing: './src/thing.ts' })]).toEqual([[join(dir, 'src/thing.ts'), '`./kit/*` in `exports`']]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should not follow a wildcard target that would capture nothing', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-empty-star-')) + try { + await mkdir(join(dir, 'src'), { recursive: true }) + await writeFile(join(dir, 'src/stats.ts'), `export {}\n`) + await writeFile(join(dir, 'src/stats-extra.ts'), `export {}\n`) + const entries = { stats: './src/stats.ts', extra: './src/stats-extra.ts' } + expect([...sourceLoadedEntries(dir, { exports: { './stats*': './src/stats*.ts' } }, join(dir, 'dist'), entries)]).toEqual([[join(dir, 'src/stats-extra.ts'), '`./stats*` in `exports`']]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should follow a directory target into the files of the directory', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-directory-target-')) + try { + await mkdir(join(dir, 'src/runtime'), { recursive: true }) + await writeFile(join(dir, 'src/runtime/plugin.ts'), `export {}\n`) + expect([...sourceLoadedEntries(dir, { exports: { './runtime/': './src/runtime/' } }, join(dir, 'dist'), { plugin: './src/runtime/plugin.ts' })]).toEqual([[join(dir, 'src/runtime/plugin.ts'), '`./runtime/` in `exports`']]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should follow a wildcard target to the file it resolves, not to its spelling', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-resolved-wildcard-')) + try { + await mkdir(join(dir, 'src/wild'), { recursive: true }) + await writeFile(join(dir, 'src/wild/a.ts'), `export {}\n`) + await writeFile(join(dir, 'src/wild/b.js'), `export {}\n`) + await writeFile(join(dir, 'src/wild/b.ts'), `export {}\n`) + const entries = { a: './src/wild/a.ts', b: './src/wild/b.ts' } + const pkg = { exports: { './wild/*': './src/wild/*.js' } } + expect(Object.fromEntries([...sourceLoadedEntries(dir, pkg, join(dir, 'dist'), entries)].map(([file, key]) => [relative(dir, file), key]))).toEqual({ + 'src/wild/a.ts': '`./wild/*` in `exports`', + }) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('should share one value between every `*` of a target', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-shared-star-')) + try { + const files = { 'src/copies/a/copy-a.ts': 'copies/a', 'src/copies/a/copy-b.ts': 'copies/b' } + for (const file of Object.keys(files)) { + await mkdir(dirname(join(dir, file)), { recursive: true }) + await writeFile(join(dir, file), `export {}\n`) + } + const entries = Object.fromEntries(Object.entries(files).map(([file, name]) => [name, `./${file}`])) + const pkg = { exports: { './copies/*': './src/copies/*/copy-*.ts' } } + expect(Object.fromEntries([...sourceLoadedEntries(dir, pkg, join(dir, 'dist'), entries)].map(([file, key]) => [relative(dir, file), key]))).toEqual({ + 'src/copies/a/copy-a.ts': '`./copies/*` in `exports`', + }) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) }) describe('deprecation checks', () => {