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
50 changes: 45 additions & 5 deletions src/build/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,65 @@ import { resolve } from 'pathe'
import { findExports, findTypeExports } from 'mlly'
import type { ESMExport } from 'mlly'

const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type'])
const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function|const\s+enum|const|let|var|class|enum)\s+([$\w]+)/g

export async function writeTypes(distDir: string, isStub: boolean): Promise<void> {
const dtsFile = resolve(distDir, 'types.d.mts')
if (existsSync(dtsFile)) {
return
}

const moduleReExports: ESMExport[] = []
const typeOnlyExports = new Set<string>()
if (!isStub) {
// Read generated module types
const moduleTypesFile = resolve(distDir, 'module.d.mts')
const moduleTypes = await fsp.readFile(moduleTypesFile, 'utf8').catch(() => '')
const normalisedModuleTypes = moduleTypes
// Replace `export { type Foo }` with `export { Foo }`
.replace(/export\s*\{.*?\}/gs, match => match.replace(/\b(type|interface)\b/g, ''))
for (const e of findExports(normalisedModuleTypes)) {
moduleReExports.push(e)
const exports = findExports(normalisedModuleTypes)
const typeExports = findTypeExports(moduleTypes)
moduleReExports.push(...exports, ...typeExports)

const valueExports = new Set<string>()
for (const e of findExports(moduleTypes)) {
if (e.type === 'named' || e.type === 'default') {
for (const name of e.names) {
valueExports.add(name)
}
}
}
for (const e of typeExports) {
const isTypeOnly = e.type === 'named' || (e.type === 'declaration' && e.declarationType !== undefined && TYPE_ONLY_DECLARATIONS.has(e.declarationType))
const target = isTypeOnly ? typeOnlyExports : valueExports
for (const name of e.names) {
target.add(name)
}
}

// `findTypeExports` drops a value declaration that shares its name with a type
// export, so read those names from the generated declarations too.
for (const match of moduleTypes.matchAll(VALUE_DECLARATION_RE)) {
valueExports.add(match[1]!)
}

// `findExports` only reports `export { type Foo }` after the `type` keyword is removed,
// so names it finds only in the normalised types are type-only.
for (const e of exports) {
if (e.type !== 'named' && e.type !== 'default') {
continue
}
for (const name of e.names) {
if (!valueExports.has(name)) {
typeOnlyExports.add(name)
}
}
}
for (const i of findTypeExports(normalisedModuleTypes)) {
moduleReExports.push(i)

for (const name of valueExports) {
typeOnlyExports.delete(name)
}
}

Expand Down Expand Up @@ -67,7 +107,7 @@ ${appShims.length ? `declare module '#app' {\n${appShims.join('\n')}\n}\n` : ''}
${schemaShims.length ? `declare module '@nuxt/schema' {\n${schemaShims.join('\n')}\n}\n` : ''}
${moduleExports.length ? `\n${moduleExports.join('\n')}` : ''}
${isStub ? 'export * from "./module.mjs"\nexport { default } from "./module.mjs"' : ''}
${[...groupNamedReExports(moduleReExports)].map(([specifier, names]) => `\nexport { ${names.map(n => (n === 'default' ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')}
${[...groupNamedReExports(moduleReExports)].map(([specifier, names]) => `\nexport { ${names.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')}
${moduleReExports.filter(e => e.type === 'star').map(e => `\nexport * from '${e.specifier || './module.mjs'}'`).join('\n')}
`.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n'

Expand Down
76 changes: 76 additions & 0 deletions test/build.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ describe('module builder', () => {
const solutionRootDir = rootDir.replace('example', '.temp-example-solution-tsconfig')
const parentTsconfigRootDir = rootDir.replace('example', '.temp-example-parent-tsconfig')
const portableRootDir = rootDir.replace('example', '.temp-example-portable-types')
const valueExportsRootDir = rootDir.replace('example', '.temp-example-value-exports')
const valueExportsIsolatedRootDir = rootDir.replace('example', '.temp-example-value-exports-isolated')
const isolatedRootDir = rootDir.replace('example', '.temp-example-isolated-declarations')
const typeErrorRootDir = rootDir.replace('example', '.temp-example-type-error')
const semanticErrorRootDir = rootDir.replace('example', '.temp-example-semantic-error')
Expand Down Expand Up @@ -125,6 +127,51 @@ export default defineNuxtModule({
await copyExample(isolatedRootDir, contents => contents)
await enableIsolatedDeclarations(isolatedRootDir)

const valueExports = `export function defineMyModuleConfig(): void {}
export const myModuleVersion = '1.0.0'
export const Mode = { Light: 0, Dark: 1 } as const
export type Mode = typeof Mode[keyof typeof Mode]`
const valueExportsConsumer = `import { Mode, defineMyModuleConfig, myModuleVersion } from 'my-module'
import type { ModuleOptions } from 'my-module'

defineMyModuleConfig()
const options: ModuleOptions = { apiKey: myModuleVersion }
const light: number = Mode.Light
const dark: Mode = Mode.Dark
void [light, dark, options]
`
const valueExportsConsumerConfig = JSON.stringify({
compilerOptions: {
moduleResolution: 'bundler',
module: 'ESNext',
target: 'ESNext',
lib: ['ESNext'],
strict: true,
noEmit: true,
skipLibCheck: true,
},
include: ['consumer.ts'],
}, null, 2)
const prepareValueExportsConsumer = async (target: string) => {
await rm(join(target, 'playground/node_modules/my-module'), { force: true })
await symlink(target, join(target, 'playground/node_modules/my-module'))
await writeFile(join(target, 'playground/consumer.ts'), valueExportsConsumer)
await writeFile(join(target, 'playground/consumer.tsconfig.json'), valueExportsConsumerConfig)
}

await copyExample(valueExportsRootDir, contents => `${contents}\n${valueExports}\n`)
await prepareValueExportsConsumer(valueExportsRootDir)

await copyExample(valueExportsIsolatedRootDir, contents => [
`import type { NuxtModule } from '@nuxt/schema'`,
contents.replace('export default defineNuxtModule<ModuleOptions>({', 'const module: NuxtModule<ModuleOptions> = defineNuxtModule<ModuleOptions>({'),
'export default module',
valueExports,
].join('\n'))
await prepareValueExportsConsumer(valueExportsIsolatedRootDir)
await writeFile(join(valueExportsIsolatedRootDir, 'src/utils.ts'), 'export const myModuleUtils = (): void => {}\n')
await enableIsolatedDeclarations(valueExportsIsolatedRootDir)

await copyExample(stubSyntaxRootDir, contents => `import { name as packageName } from '../package.json'
import { Level } from './levels.ts'

Expand Down Expand Up @@ -598,6 +645,8 @@ export const defineOptions = (options: Options) => ({ options, helper })
exec('pnpm', ['nuxt-module-build', 'build', solutionRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
exec('pnpm', ['nuxt-module-build', 'build', join(parentTsconfigRootDir, 'packages/mod')], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
exec('pnpm', ['nuxt-module-build', 'build', portableRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
exec('pnpm', ['nuxt-module-build', 'build', valueExportsRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
exec('pnpm', ['nuxt-module-build', 'build', valueExportsIsolatedRootDir], { nodeOptions: { cwd: repoRoot }, throwOnError: true }),
])
}, 180 * 1000)

Expand Down Expand Up @@ -1246,6 +1295,33 @@ export const defineOptions = (options: Options) => ({ options, helper })
`)
})

it('should keep value exports as values in `types.d.mts`', async () => {
const types = await readFile(join(valueExportsRootDir, 'dist/types.d.mts'), 'utf-8')
expect(types).toMatchInlineSnapshot(`
"import type { ModuleHooks, ModuleRuntimeHooks, ModuleRuntimeConfig, ModulePublicRuntimeConfig } from './module.mjs'

declare module '#app' {
interface RuntimeNuxtHooks extends ModuleRuntimeHooks {}
}

declare module '@nuxt/schema' {
interface NuxtHooks extends ModuleHooks {}
interface RuntimeConfig extends ModuleRuntimeConfig {}
interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
}

export { defineMyModuleConfig, Mode, type ModuleHooks, type ModuleOptions, type ModulePublicRuntimeConfig, type ModuleRuntimeConfig, type ModuleRuntimeHooks, myModuleVersion, default } from './module.mjs'
"
`)
expect(await readFile(join(valueExportsIsolatedRootDir, 'dist/types.d.mts'), 'utf-8')).toBe(types)

for (const root of [valueExportsRootDir, valueExportsIsolatedRootDir]) {
const { stdout, stderr, exitCode } = await exec('pnpm', ['exec', 'tsc', '--noEmit', '-p', join(root, 'playground/consumer.tsconfig.json')], { nodeOptions: { cwd: repoRoot } })
expect(stdout + stderr, root).toBe('')
expect(exitCode).toBe(0)
}
}, 60 * 1000)

it('should generate types when no ModuleOptions are exported', async () => {
const types = await readFile(join(secondDistDir, 'types.d.mts'), 'utf-8')
expect(types).toMatchInlineSnapshot(`
Expand Down
Loading