From 6ea1a9735df7e630ce985c262247e01c70f174c6 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 11:56:56 +0000 Subject: [PATCH 01/12] refactor: replace `consola` with `@clack/prompts` logs --- CONTRIBUTING.md | 2 +- package.json | 2 +- pnpm-lock.yaml | 6 +++--- src/build/build.ts | 11 +++++------ src/build/module-declarations.ts | 5 ++--- src/build/package.ts | 5 ++--- src/commands/build.ts | 4 ++-- src/legacy/build-config.ts | 9 ++++----- src/tsdown/setup.ts | 5 ++--- src/utils.ts | 7 +++++++ test/builder.spec.ts | 2 +- test/cli.spec.ts | 8 ++++---- test/legacy.spec.ts | 8 ++++---- test/unit.spec.ts | 15 +++++++-------- 14 files changed, 45 insertions(+), 44 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e535a648..4e2acc44 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,7 +38,7 @@ The package has three entry points: | `src/build/` | The build itself, independent of tsdown's plugin API:
`options.ts` resolves `builder()` options.
`build.ts` resolves a `BuildPlan` and runs the steps before and after the bundle.
`loader.ts` imports module code and checks that Node can load it.
`package.ts` holds the `package.json` checks.
`types.ts` and `module-declarations.ts` write `types.d.mts` and the declarations `prepare` generates.
`aliases.ts` rewrites `#app` in declarations. | | `src/transpile/` | `transpileDir()`, the internal rolldown plugin that transpiles a directory file by file. It transforms scripts with oxc and `.vue` files with `vue.ts`, compiles stylesheets with `stylesheets.ts`, emits declarations with `declarations.ts`, rewrites import specifiers with `specifiers.ts`, and resolves the tsconfig of each file with `tsconfig.ts`. It imports nothing outside the directory but `src/utils.ts`, so it can be extracted later. | | `src/legacy/` | Compatibility with v1 and unbuild (see [Legacy code](#legacy-code)). | -| `src/utils.ts` | Path, file and regex helpers shared across directories. | +| `src/utils.ts` | Path, file and regex helpers shared across directories, and `logger`, through which every build message goes. | ### `tsdown` with `builder()` diff --git a/package.json b/package.json index a51822d5..23a6418b 100644 --- a/package.json +++ b/package.json @@ -56,9 +56,9 @@ } }, "dependencies": { + "@clack/prompts": "^1.8.1", "browserslist": "^4.29.5", "citty": "^0.2.2", - "consola": "^3.4.2", "get-tsconfig": "^4.14.3", "lightningcss": "^1.33.0", "mlly": "^1.8.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6290a30a..78bf0195 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -175,15 +175,15 @@ importers: .: dependencies: + '@clack/prompts': + specifier: ^1.8.1 + version: 1.9.0 browserslist: specifier: ^4.29.5 version: 4.29.5 citty: specifier: ^0.2.2 version: 0.2.2 - consola: - specifier: ^3.4.2 - version: 3.4.2 get-tsconfig: specifier: ^4.14.3 version: 4.14.3 diff --git a/src/build/build.ts b/src/build/build.ts index 30210122..15726567 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -2,7 +2,6 @@ import { createHash } from 'node:crypto' import { existsSync, readdirSync, readFileSync } from 'node:fs' import { readFile, rm } from 'node:fs/promises' import { dirname, join, normalize, relative, resolve } from 'pathe' -import { consola } from 'consola' import type { NuxtModule } from '@nuxt/schema' import type { TsConfigResult } from 'get-tsconfig' import type { PackageJson } from 'pkg-types' @@ -13,7 +12,7 @@ import { scriptExtension, valueSpecifiers } from '../transpile/specifiers.ts' import { EXCLUDE } from '../transpile/transpile-dir.ts' import type { ResolveExternal } from '../transpile/transpile-dir.ts' import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' -import { findPackageDir, findUp, isInside, isSourceScript, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' +import { findPackageDir, findUp, isInside, isSourceScript, logger, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' import { guide } from './guide.ts' import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts' @@ -97,7 +96,7 @@ export async function resolveBuild({ cwd, pkg, outDir, sourcemap, config }: Pick if (tsconfigs.replaced) { const path = relative(cwd, tsconfigs.replaced) const advice = !isInside(cwd, tsconfigs.replaced) ? 'Add a `tsconfig.json` in the module directory that extends `./.nuxt/tsconfig.json`.' : 'Extend `./.nuxt/tsconfig.json` in the module\'s tsconfig.' - consola.info(`\`${path}\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. ${advice} ${guide('module-tsconfig')}`) + logger.info(`\`${path}\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. ${advice} ${guide('module-tsconfig')}`) } const directories: DirectoryEntry[] = [{ srcDir: resolve(cwd, 'src/runtime'), outDir: join(outDir, 'runtime'), ext: 'js' }, ...config.directories] @@ -204,10 +203,10 @@ export async function onBuildError(plan: BuildPlan, error: unknown, { directory await rm(plan.outDir, { recursive: true, force: true }) } if (plan.isolatedDeclarations && !directory) { - consola.error(ISOLATED_DECLARATIONS_HINT) + logger.error(ISOLATED_DECLARATIONS_HINT) } else if (/\bTS\d{4}\b/.test(String((error as Error | undefined)?.message))) { - consola.error(TYPE_ERROR_HINT) + logger.error(TYPE_ERROR_HINT) } } @@ -249,7 +248,7 @@ export async function finishBuild(plan: BuildPlan, { outputs, builder, keepOutpu if (shouldNudge(plan.isolatedDeclarations)) { const project = plan.moduleProject && relative(cwd, plan.moduleProject) const where = !project ? 'your `tsconfig.json`' : project.startsWith('.nuxt') ? 'a `tsconfig.module.json` that extends `./.nuxt/tsconfig.node.json`' : `\`${project}\`` - consola.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`) + logger.info(`Built in ${duration}ms. Set \`isolatedDeclarations: true\` in ${where} to use the faster oxc declaration generator. ${guide('isolated-declarations')}`) } await checkPublishedPaths(cwd) diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts index ca43a098..eafdf340 100644 --- a/src/build/module-declarations.ts +++ b/src/build/module-declarations.ts @@ -1,12 +1,11 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises' -import { consola } from 'consola' import type { TsConfigResult } from 'get-tsconfig' import { dirname, join, normalize, relative, resolve } from 'pathe' import { createDeclarationProgram } from '../transpile/declarations.ts' import { rewriteSpecifiers } from '../transpile/specifiers.ts' import { hasIsolatedDeclarations, isModuleFile } from '../transpile/tsconfig.ts' -import { isInside, isSourceScript, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts' +import { isInside, isSourceScript, logger, probe, RELATIVE_RE, relativeSpecifier, SCRIPT_RE } from '../utils.ts' import { loadOxc } from './loader.ts' import { writeSourceTypes } from './types.ts' @@ -70,7 +69,7 @@ export async function writeModuleDeclarations(cwd: string, dir: string, { tsconf await writeFile(output, code) })) if (errors.length) { - consola.warn([ + logger.warn([ `Declarations of module code for the module's own app, server and shared type checks could not be generated for every file. The build reports the same errors:`, ...errors, ].join('\n')) diff --git a/src/build/package.ts b/src/build/package.ts index 3450730c..bb18ee37 100644 --- a/src/build/package.ts +++ b/src/build/package.ts @@ -1,11 +1,10 @@ import { existsSync } from 'node:fs' import { basename, join, relative, resolve } from 'pathe' -import { consola } from 'consola' import { readPackageJSON } from 'pkg-types' import type { PackageJson } from 'pkg-types' import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts' -import { DECLARATION_RE, isFile, isInside, TYPESCRIPT_RE } from '../utils.ts' +import { DECLARATION_RE, isFile, isInside, logger, TYPESCRIPT_RE } from '../utils.ts' import { guide } from './guide.ts' /** The fields of `package.json` whose paths are checked for whether they can be published. */ @@ -282,7 +281,7 @@ export async function checkPublishedPaths(cwd: string): Promise { /** Warns with `message` when `condition` holds, and returns `condition`. */ export function warnWhen(condition: boolean, message: string): boolean { if (condition) { - consola.warn(message) + logger.warn(message) } return condition } diff --git a/src/commands/build.ts b/src/commands/build.ts index 633140e7..dac3a6df 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -1,9 +1,9 @@ import { defineCommand } from 'citty' import type { CommandDef } from 'citty' -import { consola } from 'consola' import pkg from '../../package.json' with { type: 'json' } import { guide } from '../build/guide.ts' +import { logger } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' export const MISSING_TSDOWN_HINT: string = `\`${pkg.name}\` builds with \`tsdown\`, which is a peer dependency. Install it in your module: \`pnpm add -D tsdown@"${pkg.peerDependencies.tsdown}"\`. ${guide('install-tsdown')}` @@ -40,7 +40,7 @@ const command: CommandDef = defineCommand( const cwd = resolveCwdArg(context.args) const { build } = await import('../tsdown/build.ts').catch((error) => { if (isMissingTsdown(error)) { - consola.error(MISSING_TSDOWN_HINT) + logger.error(MISSING_TSDOWN_HINT) } throw error }) diff --git a/src/legacy/build-config.ts b/src/legacy/build-config.ts index 44253de4..5e636053 100644 --- a/src/legacy/build-config.ts +++ b/src/legacy/build-config.ts @@ -5,7 +5,6 @@ import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { relative, resolve } from 'pathe' -import { consola } from 'consola' import type { PackageJson } from 'pkg-types' import type { BuildPlan } from '../build/build.ts' @@ -14,7 +13,7 @@ import type { GuideSection } from '../build/guide.ts' import { findModuleCodeIssues, formatModuleCodeIssues, importModule } from '../build/loader.ts' import { bundledEntries, createOptionsCollector, entryName } from '../build/options.ts' import type { BuildHookName, ModuleConfig } from '../build/options.ts' -import { isPlainObject } from '../utils.ts' +import { isPlainObject, logger } from '../utils.ts' import type { BuildContext, BuildHook } from './define.ts' const BUILD_CONFIG_FILES = ['build.config.ts', 'build.config.mts', 'build.config.js', 'build.config.mjs'] @@ -248,10 +247,10 @@ export function assertNoLegacyBuildConfig(cwd: string, pkg: PackageJson): void { export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void { for (const hook of config.ignoredHooks) { - consola.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`) + logger.warn(`Ignoring ${hook}: runtime files are no longer built with mkdist. Remove the hook. ${guide('hooks')}`) } if (config.file) { - consola.warn([ + logger.warn([ `\`${config.file}\` is deprecated. Its options are still applied.`, ...config.importsUnbuild ? ['Import `defineBuildConfig` from `@nuxt/module-builder` instead of `unbuild`.'] : [], 'Move them into `builder()` in `tsdown.config.ts`.', @@ -259,7 +258,7 @@ export function warnDeprecatedBuildConfig(config: LoadedBuildConfig): void { ].join(' ')) } if (config.field === 'unbuild') { - consola.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`) + logger.warn(`The \`unbuild\` field of \`package.json\` is deprecated. Its options are still applied. Rename the field to \`build\`. ${guide('build-configuration')}`) } } diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index fe6db252..800ff92a 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -2,7 +2,6 @@ import { existsSync, readdirSync } from 'node:fs' import { rm } from 'node:fs/promises' import { pathToFileURL } from 'node:url' import { relative, resolve } from 'pathe' -import { consola } from 'consola' import { resolvePath } from 'mlly' import { readPackageJSON } from 'pkg-types' import type { PackageJson } from 'pkg-types' @@ -16,7 +15,7 @@ import type { BuilderOptions, ModuleConfig, ReplaceOptions } from '../build/opti import { sourcePathsPackError, unpublishablePathsError } from '../build/package.ts' import { prepareModule } from '../commands/prepare.ts' import { transpileDir, TYPE_ERRORS_WARNING } from '../transpile/transpile-dir.ts' -import { findUp, realpath } from '../utils.ts' +import { findUp, logger, realpath } from '../utils.ts' import { externalDependencyDeclarations, runtimeExternals } from './externals.ts' import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts' import { unchangedOutputs } from './unchanged.ts' @@ -87,7 +86,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt const buildConfig = loadConfig ? await loadConfig(cwd, pkg, outDir) : resolveModuleOptions(cwd, pkg, outDir, options) if (!existsSync(resolve(cwd, '.nuxt/tsconfig.json'))) { - consola.info(`\`.nuxt\` not found, running \`nuxt-module-build prepare\` first. Add it to the module's \`dev:prepare\` script to skip this step. ${guide('preparing-nuxt')}`) + logger.info(`\`.nuxt\` not found, running \`nuxt-module-build prepare\` first. Add it to the module's \`dev:prepare\` script to skip this step. ${guide('preparing-nuxt')}`) await prepareModule(cwd, { config: buildConfig, outDir, pkg }) } diff --git a/src/utils.ts b/src/utils.ts index 5067e5bc..6081535d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,7 +1,14 @@ import { existsSync, realpathSync, statSync } from 'node:fs' import { readFile, writeFile } from 'node:fs/promises' +import { log } from '@clack/prompts' import { basename, dirname, isAbsolute, join, relative, resolve } from 'pathe' +export const logger = { + info: (message: string): void => log.info(message, { spacing: 0 }), + warn: (message: string): void => log.warn(message, { spacing: 0, output: process.stderr }), + error: (message: string): void => log.error(message, { spacing: 0, output: process.stderr }), +} + export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/ export const TYPESCRIPT_RE: RegExp = /\.[cm]?tsx?$/ export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/ diff --git a/test/builder.spec.ts b/test/builder.spec.ts index 39dd1186..dd5942cf 100644 --- a/test/builder.spec.ts +++ b/test/builder.spec.ts @@ -300,7 +300,7 @@ describe('with a root tsconfig that only lists references', () => { const ownsField = async (dir: string) => (await read(dir, 'dist/module.mjs')).includes('\tvalue;') const output = expectBuilt('moduleProject') expect(output).toContain('tsconfig: tsconfig.module.json') - expect(output).toMatch(/Set `?isolatedDeclarations: true`? in `?tsconfig\.module\.json`?/) + expect(output).toContain('Set `isolatedDeclarations: true` in `tsconfig.module.json`') expect(await ownsField(dirs.moduleProject!)).toBe(false) expect(expectBuilt('tsconfigOption')).toContain('tsconfig: tsconfig.override.json') expect(await ownsField(dirs.tsconfigOption!)).toBe(true) diff --git a/test/cli.spec.ts b/test/cli.spec.ts index 7f279aff..c2f2b1fc 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -764,7 +764,7 @@ describe('a module that imports runtime code, built through a symlink, under a p it('should warn about type errors that do not affect runtime declarations and build anyway', async () => { const output = expectBuilt('runtime') - expect(output).toMatch(/2 type errors were reported while generating declarations for `?src\/runtime`?; the declarations were emitted\. If the module's own type check \(for example `?nuxt typecheck`? or `?vue-tsc --noEmit`?\) passes/) + expect(output).toContain('2 type errors were reported while generating declarations for `src/runtime`; the declarations were emitted. If the module\'s own type check (for example `nuxt typecheck` or `vue-tsc --noEmit`) passes') expect(output).toContain('src/runtime/utils/typo.ts(1,14): error TS2322') expect(output).toContain('src/runtime/components/Typo.vue(3,7): error TS2322') expect(output.match(/type errors? (?:was|were) reported/g)).toHaveLength(1) @@ -788,7 +788,7 @@ describe('a module with `isolatedDeclarations` and no `.nuxt`', () => { const dist = () => join(dirs.isolated!, 'dist') it('should prepare the module before building it', async () => { - expect(expectBuilt('isolated')).toMatch(new RegExp(`\\.nuxt\`? not found, running \`?nuxt-module-build prepare\`? first\\..*${guide('preparing-nuxt')}`)) + expect(expectBuilt('isolated')).toContain(`\`.nuxt\` not found, running \`nuxt-module-build prepare\` first. Add it to the module's \`dev:prepare\` script to skip this step. ${guide('preparing-nuxt')}`) expect(await read(dist(), 'runtime/composables/useAliasedApp.d.ts')).toMatch(/import\("nuxt\/app"\)\.NuxtApp/) }) @@ -1137,7 +1137,7 @@ describe('a module whose code Node cannot load', () => { describe('a module whose declarations cannot be generated', () => { it('should surface isolated declaration diagnostics when the tsconfig opts in', () => { const output = expectFailed('isolatedError') - expect(output).toMatch(/Declaration generation failed under `?isolatedDeclarations/) + expect(output).toContain('Declaration generation failed under `isolatedDeclarations`.') expect(output).toMatch(/TS90\d\d/) expect(output).toContain(guide('isolated-declarations')) expect(output).not.toMatch(/Type declarations could not be generated/) @@ -1179,7 +1179,7 @@ describe('tsconfig lookup', () => { }) it('should generate declarations with the module\'s own `.nuxt` when the tsconfig takes its types from a playground', async () => { - expect(expectBuilt('routes')).toMatch(new RegExp(`\\.\\./tsconfig.json\`? takes its generated types from another app's \`?.nuxt\`?; declarations are generated with \`?.nuxt/tsconfig.json\`? instead. Add a \`?tsconfig.json\`? in the module directory that extends \`?./.nuxt/tsconfig.json\`?. ${guide('module-tsconfig')}`)) + expect(expectBuilt('routes')).toContain(`\`../tsconfig.json\` takes its generated types from another app's \`.nuxt\`; declarations are generated with \`.nuxt/tsconfig.json\` instead. Add a \`tsconfig.json\` in the module directory that extends \`./.nuxt/tsconfig.json\`. ${guide('module-tsconfig')}`) expect(await read(dirs.routes!, 'playground/.nuxt/types/nitro-routes.d.ts')).toContain('/api/secret') for (const file of await listFiles(join(dirs.routes!, 'dist'))) { if (file.includes('.')) { diff --git a/test/legacy.spec.ts b/test/legacy.spec.ts index 2dfd7a8e..b16b831e 100644 --- a/test/legacy.spec.ts +++ b/test/legacy.spec.ts @@ -2,7 +2,6 @@ import { createHash } from 'node:crypto' import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { fileURLToPath } from 'node:url' -import { consola } from 'consola' import { findStaticImports } from 'mlly' import { join, relative } from 'pathe' import ts from 'typescript' @@ -11,6 +10,7 @@ import { beforeAll, describe, expect, it, vi } from 'vitest' import { bundledEntries, entryName } from '../src/build/options.ts' import { assertNoLegacyBuildConfig, formatUnsupportedOptions, loadBuildConfig, translateBuildConfig, warnDeprecatedBuildConfig } from '../src/legacy/build-config.ts' import { guide } from '../src/build/guide.ts' +import { logger } from '../src/utils.ts' import type { FixtureOptions, Result } from './utils.ts' import { cli, exists, fixture, listFiles, read, repoRoot, tsdown } from './utils.ts' @@ -115,7 +115,7 @@ describe('translateBuildConfig', () => { it('should warn about a deprecated config file and ignored hooks in CI too', () => { vi.stubEnv('CI', 'true') - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) try { const config = { ...translate({}), file: 'build.config.ts', importsUnbuild: true, ignoredHooks: ['build.config.ts: hooks[\'mkdist:entry:options\']'] } warnDeprecatedBuildConfig(config) @@ -508,8 +508,8 @@ export default defineBuildConfig({ it('should warn that `build.config.ts` is deprecated', () => { const output = expectBuilt('buildConfig') - expect(output).toMatch(new RegExp(`\`?build\\.config\\.ts\`? is deprecated\\. Its options are still applied\\. Move them into \`?builder\\(\\)\`? in \`?tsdown\\.config\\.ts\`?\\. ${guide('moving-from-buildconfigts')}`)) - expect(output).not.toMatch(/`?unbuild`? field/) + expect(output).toContain(`\`build.config.ts\` is deprecated. Its options are still applied. Move them into \`builder()\` in \`tsdown.config.ts\`. ${guide('moving-from-buildconfigts')}`) + expect(output).not.toContain('`unbuild` field') }) it('should read the `unbuild` field of `package.json` in preference to `build`, with the replacements of `rollup.replace`', async () => { diff --git a/test/unit.spec.ts b/test/unit.spec.ts index b0ce061c..fc99ea2d 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -7,7 +7,6 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { satisfies } from 'verkit' import { version as nuxtVersion } from 'nuxt/package.json' -import { consola } from 'consola' import { basename, dirname, join, resolve } from 'pathe' import { parseTsconfig } from 'get-tsconfig' import { analyseSources, finishBuild, hashGeneratedTypes } from '../src/build/build.ts' @@ -15,7 +14,7 @@ import type { BuildPlan } from '../src/build/build.ts' import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' import { resolveCwdArg } from '../src/commands/_shared.ts' import { moduleSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' -import { relativeSpecifier } from '../src/utils.ts' +import { logger, relativeSpecifier } from '../src/utils.ts' import { setupBuilder } from '../src/tsdown/setup.ts' import { defaultReport, reportsSummary, sizeBreakdown } from '../src/tsdown/report.ts' import { unchangedOutputs } from '../src/tsdown/unchanged.ts' @@ -382,7 +381,7 @@ describe('deprecation checks', () => { const cwd = fileURLToPath(new URL('..', import.meta.url)) it('should warn about referenced `.d.ts` output that is no longer generated', () => { - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) expect(checkLegacyDeclarationPaths(cwd, { exports: { '.': { types: './dist/module.d.ts' } } })).toBe(true) expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringMatching(new RegExp(`Replace \`\\.d\\.ts\` with \`\\.d\\.mts\` in these \`package\\.json\` paths: \`\\./dist/module\\.d\\.ts\`\\. ${guide('declaration-paths')}$`))) warn.mockClear() @@ -444,7 +443,7 @@ describe('deprecation checks', () => { }) it('should warn about referenced `module.cjs` output that is no longer generated', () => { - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) expect(checkLegacyCJSPaths(cwd, { main: './dist/module.cjs' })).toBe(true) expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringMatching(new RegExp(`\`module\\.cjs\`.*Replace it with \`\\./dist/module\\.mjs\`.* ${guide('modulecjs')}$`))) warn.mockClear() @@ -459,7 +458,7 @@ describe('deprecation checks', () => { await mkdir(join(root, 'dist')) await writeFile(join(root, 'dist/module.mjs'), '') await writeFile(join(root, 'package.json'), '{}') - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) const pkg = { types: './dist/stale.d.ts', main: './dist/module.cjs', @@ -485,7 +484,7 @@ describe('deprecation checks', () => { for (const file of ['dist/util.d.mts', 'dist/util.mjs', 'dist/nested/index.d.mts', 'dist/legacy.d.ts', 'dist/gone.mjs']) { await writeFile(join(root, file), '') } - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) const pkg = { exports: { './util': './dist/util.mjs', './gone': './dist/gone.mjs' }, typesVersions: { '*': { 'util': ['dist/util'], 'nested': ['./dist/nested'], 'legacy': ['dist/legacy'], 'gone': ['dist/gone'], 'runtime/*': ['dist/runtime/*'] } }, @@ -503,7 +502,7 @@ describe('deprecation checks', () => { }) it('should warn about a stale `types` field', () => { - const warn = vi.spyOn(consola, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {}) expect(checkStaleTypesField(cwd, { types: './dist/nope.d.ts' })).toBe(true) expect(warn).toHaveBeenCalledExactlyOnceWith(`\`types\` in \`package.json\` points at \`./dist/nope.d.ts\`, which the build does not produce. Set it to \`./dist/types.d.mts\`, which node10 module resolution reads, or remove it: bundler module resolution reads \`exports\` instead. ${guide('the-types-field')}`) warn.mockClear() @@ -764,7 +763,7 @@ describe('declarationPaths', () => { '#components': ['/app/.nuxt/components'], '#imports': ['/app/.nuxt/imports'], '#app': ['/app/node_modules/.pnpm/nuxt@4.0.0/node_modules/nuxt/dist/app'], - 'consola': ['/app/node_modules/.pnpm/consola@3.0.0/node_modules/consola'], + 'pathe': ['/app/node_modules/.pnpm/pathe@2.0.0/node_modules/pathe'], 'not-installed-package': ['/app/node_modules/.pnpm/not-installed-package@1.0.0/node_modules/not-installed-package'], '~/*': ['/app/*'], }, cwd) From 4f2cf4b46e33af4d0b8a33d9940c4cdd789ce8c2 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 12:01:05 +0000 Subject: [PATCH 02/12] refactor: replace `citty` with `node:util` `parseArgs` --- package.json | 1 - pnpm-lock.yaml | 3 - src/cli.ts | 125 +++++++++++++++++++++++++++++++++++----- src/commands/_shared.ts | 19 +++++- src/commands/build.ts | 8 +-- src/commands/prepare.ts | 7 +-- test/cli.spec.ts | 28 +++++++++ 7 files changed, 161 insertions(+), 30 deletions(-) diff --git a/package.json b/package.json index 23a6418b..507da78f 100644 --- a/package.json +++ b/package.json @@ -58,7 +58,6 @@ "dependencies": { "@clack/prompts": "^1.8.1", "browserslist": "^4.29.5", - "citty": "^0.2.2", "get-tsconfig": "^4.14.3", "lightningcss": "^1.33.0", "mlly": "^1.8.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 78bf0195..47083914 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -181,9 +181,6 @@ importers: browserslist: specifier: ^4.29.5 version: 4.29.5 - citty: - specifier: ^0.2.2 - version: 0.2.2 get-tsconfig: specifier: ^4.14.3 version: 4.14.3 diff --git a/src/cli.ts b/src/cli.ts index 1de49893..333994f0 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -1,22 +1,115 @@ #!/usr/bin/env node -import { defineCommand, runMain } from 'citty' -import type { CommandDef } from 'citty' +import { parseArgs } from 'node:util' +import type { ParseArgsOptionsConfig } from 'node:util' import pkg from '../package.json' with { type: 'json' } +import type { CommandDef } from './commands/_shared.ts' +import { logger } from './utils.ts' -const { name, description, version } = pkg +const BIN = 'nuxt-module-build' -const _rDefault = (r: unknown) => (r && typeof r === 'object' && 'default' in r ? r.default : r) as Promise +const commands: Record Promise> = { + prepare: () => import('./commands/prepare.ts').then(module => module.default as CommandDef), + build: () => import('./commands/build.ts').then(module => module.default as CommandDef), +} -const main = defineCommand({ - meta: { - name, - description, - version, - }, - subCommands: { - prepare: () => import('./commands/prepare.ts').then(_rDefault), - build: () => import('./commands/build.ts').then(_rDefault), - }, -}) +class UsageError extends Error {} + +const table = (rows: Array<[string, string]>) => { + const width = Math.max(...rows.map(([name]) => name.length)) + return rows.map(([name, description]) => ` ${name.padEnd(width)} ${description}`) +} + +async function mainUsage() { + const loaded = await Promise.all(Object.values(commands).map(load => load())) + return [ + `${pkg.description} (${pkg.name} v${pkg.version})`, + '', + `Usage: ${BIN} [options]`, + '', + 'Commands:', + ...table(loaded.map(command => [command.meta.name, command.meta.description])), + '', + `Run \`${BIN} --help\` for the options of a command.`, + ].join('\n') +} + +function commandUsage(command: CommandDef) { + const args = Object.entries(command.args) + const positionals = args.filter(([, arg]) => arg.type === 'positional') + const options = args.filter(([, arg]) => arg.type !== 'positional') + return [ + `${command.meta.description} (${BIN} ${command.meta.name})`, + '', + `Usage: ${BIN} ${command.meta.name} [options]${positionals.map(([name]) => ` [${name.toUpperCase()}]`).join('')}`, + '', + ...positionals.length ? ['Arguments:', ...table(positionals.map(([name, arg]) => [name.toUpperCase(), arg.description])), ''] : [], + 'Options:', + ...table([ + ...options.map(([name, arg]): [string, string] => [`--${name}${arg.type === 'string' ? `=<${arg.valueHint ?? 'value'}>` : ''}`, arg.description]), + ['-h, --help', 'Show this help'], + ]), + ].join('\n') +} -runMain(main) +const kebabCase = (name: string) => name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`) + +function parseCommandArgs(command: CommandDef, argv: string[]) { + const options: ParseArgsOptionsConfig = { help: { type: 'boolean', short: 'h' }, stub: { type: 'boolean' } } + for (const [name, arg] of Object.entries(command.args)) { + if (arg.type !== 'positional') { + options[name] = { type: arg.type } + options[kebabCase(name)] ??= { type: arg.type } + } + } + const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true }) as { values: Record, positionals: string[] } + const args: Record = { help: values.help, stub: values.stub } + for (const [name, arg] of Object.entries(command.args)) { + args[name] = arg.type === 'positional' ? positionals.shift() ?? arg.default : values[name] ?? values[kebabCase(name)] ?? arg.default + } + if (positionals.length) { + throw new UsageError(`Unexpected argument \`${positionals[0]}\``) + } + return args +} + +async function main(argv: string[]) { + const [name, ...rest] = argv + if (name === '--help' || name === '-h') { + console.log(await mainUsage()) + return + } + if (name === '--version' || name === '-v') { + console.log(pkg.version) + return + } + const load = name !== undefined && Object.hasOwn(commands, name) ? commands[name] : undefined + if (!load) { + console.error(await mainUsage()) + throw new UsageError(name === undefined ? 'No command specified.' : `Unknown command \`${name}\``) + } + const command = await load() + let args + try { + args = parseCommandArgs(command, rest) + } + catch (error) { + console.error(commandUsage(command)) + throw new UsageError((error as Error).message) + } + if (args.help) { + console.log(commandUsage(command)) + return + } + await command.run({ args }) +} + +main(process.argv.slice(2)).catch((error: unknown) => { + if (error instanceof UsageError) { + console.error() + logger.error(error.message) + } + else { + console.error(error) + } + process.exit(1) +}) diff --git a/src/commands/_shared.ts b/src/commands/_shared.ts index 02b442be..b5642827 100644 --- a/src/commands/_shared.ts +++ b/src/commands/_shared.ts @@ -1,6 +1,24 @@ import { guide } from '../build/guide.ts' import { realpath } from '../utils.ts' +interface ArgDef { + type: 'string' | 'boolean' | 'positional' + description: string + valueHint?: string + default?: string +} + +type ParsedArgs> = { + [Key in keyof Args]?: { boolean: boolean, string: string, positional: string }[Args[Key]['type']] +} + +/** A subcommand of `nuxt-module-build`. */ +export interface CommandDef = Record> { + meta: { name: string, description: string } + args: Args + run(context: { args: ParsedArgs }): Promise +} + export const sharedArgs = { // cwd falls back to rootDir's default (indirect default) cwd: { @@ -12,7 +30,6 @@ export const sharedArgs = { rootDir: { type: 'positional', description: 'Specifies the working directory (default: `.`)', - required: false, default: '.', }, } as const diff --git a/src/commands/build.ts b/src/commands/build.ts index dac3a6df..30edee33 100644 --- a/src/commands/build.ts +++ b/src/commands/build.ts @@ -1,10 +1,8 @@ -import { defineCommand } from 'citty' -import type { CommandDef } from 'citty' - import pkg from '../../package.json' with { type: 'json' } import { guide } from '../build/guide.ts' import { logger } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' +import type { CommandDef } from './_shared.ts' export const MISSING_TSDOWN_HINT: string = `\`${pkg.name}\` builds with \`tsdown\`, which is a peer dependency. Install it in your module: \`pnpm add -D tsdown@"${pkg.peerDependencies.tsdown}"\`. ${guide('install-tsdown')}` @@ -26,7 +24,7 @@ const buildArgs = { }, } as const -const command: CommandDef = defineCommand({ +const command: CommandDef = { meta: { name: 'build', description: 'Build module for distribution', @@ -46,6 +44,6 @@ const command: CommandDef = defineCommand( }) return build(cwd, { outDir: context.args.outDir, sourcemap: context.args.sourcemap }) }, -}) +} export default command diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 73399023..82b5fc02 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -1,7 +1,5 @@ import { pathToFileURL } from 'node:url' import type { Nuxt, NuxtConfig, NuxtModule } from '@nuxt/schema' -import { defineCommand } from 'citty' -import type { CommandDef } from 'citty' import { readFile, writeFile } from 'node:fs/promises' import { parseTsconfig } from 'get-tsconfig' import { resolvePath } from 'mlly' @@ -19,6 +17,7 @@ import { loadBuildConfig } from '../legacy/build-config.ts' import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts' import { isInside, probe } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' +import type { CommandDef } from './_shared.ts' import { loadModuleConfig } from './config-file.ts' const BUILD_DECLARATION_RE = /^declare module "#build\/(.+)";$/ @@ -288,7 +287,7 @@ async function loadUseNuxt(cwd: string): Promise<(() => Nuxt) | undefined> { } } -const command: CommandDef = defineCommand({ +const command: CommandDef = { meta: { name: 'prepare', description: 'Prepare @nuxt/module-builder environment by writing types', @@ -298,6 +297,6 @@ const command: CommandDef = defineCommand({ assertNoStubArg('prepare', context.args) return prepareModule(resolveCwdArg(context.args)) }, -}) +} export default command diff --git a/test/cli.spec.ts b/test/cli.spec.ts index c2f2b1fc..fcd9d39f 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -582,6 +582,13 @@ export type { Kit } from './kit' step('minimal:outDir', cli(['build', '--outDir', '..', dirs.minimal])), step('minimal:stub', cli(['build', '--stub', dirs.minimal])), step('minimal:prepare-stub', cli(['prepare', '--stub', dirs.minimal])), + step('minimal:unknownOption', cli(['build', '--bogus', dirs.minimal])), + step('minimal:help', cli(['build', '--help'])), + step('minimal:extraArgument', cli(['build', dirs.minimal, 'extra'])), + step('cli:help', cli(['--help'])), + step('cli:version', cli(['--version'])), + step('cli:none', cli([])), + step('cli:unknown', cli(['nope'])), step('shape', cli(['build', dirs.shape])), step('loader:prepare', cli(['prepare', dirs.loader])).then(() => Promise.all([ step('loader', cli(['build', dirs.loader])), @@ -910,6 +917,27 @@ describe('a module without a runtime directory', () => { expect(expectFailed(command === 'build' ? 'minimal:stub' : 'minimal:prepare-stub'), command).toContain(`\`nuxt-module-build ${command} --stub\` has been removed. With pnpm or Yarn 4, point \`package.json\` at the module's sources. Otherwise, build \`dist\` with \`tsdown\` and rebuild it with \`tsdown --watch\`. ${guide('stub-builds')}`) } }) + + it('should print the usage, and fail without a known subcommand', () => { + const usage = `Usage: nuxt-module-build [options]\n\nCommands:\n prepare Prepare @nuxt/module-builder environment by writing types\n build Build module for distribution\n` + expect(expectBuilt('cli:help')).toContain(usage) + expect(expectBuilt('cli:version').trim()).toBe(version) + for (const [name, error] of [['cli:none', 'No command specified.'], ['cli:unknown', 'Unknown command `nope`']] as const) { + const output = expectFailed(name) + expect(output, name).toContain(usage) + expect(output, name).toContain(error) + } + }) + + it('should list the options of a subcommand, and fail on arguments it does not take', () => { + const usage = 'Usage: nuxt-module-build build [options] [ROOTDIR]' + expect(expectBuilt('minimal:help')).toContain(usage) + expect(expectBuilt('minimal:help')).toMatch(/^ {2}--outDir= +Build directory/m) + expect(expectBuilt('minimal:help')).toMatch(/^ {2}--sourcemap +Generate sourcemaps/m) + expect(expectFailed('minimal:unknownOption')).toContain(usage) + expect(expectFailed('minimal:unknownOption')).toContain('Unknown option \'--bogus\'') + expect(expectFailed('minimal:extraArgument')).toContain('Unexpected argument `extra`') + }) }) describe('a module whose runtime files import files around them', () => { From b019576ae6aacb085cea1ff72110214dca39f16f Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 12:16:52 +0000 Subject: [PATCH 03/12] refactor: read package.json without pkg-types --- package.json | 1 - pnpm-lock.yaml | 3 --- src/build/build.ts | 2 +- src/build/options.ts | 2 +- src/build/package.ts | 8 +++----- src/commands/prepare.ts | 7 +++---- src/legacy/build-config.ts | 2 +- src/legacy/define.ts | 2 +- src/legacy/package-paths.ts | 2 +- src/tsdown/setup.ts | 10 +++++----- src/utils.ts | 21 +++++++++++++++++++++ test/cli.spec.ts | 7 +++---- test/pack-env.ts | 4 ++-- test/utils.ts | 2 +- test/watch.spec.ts | 2 +- 15 files changed, 44 insertions(+), 31 deletions(-) diff --git a/package.json b/package.json index 507da78f..9d0b1c0e 100644 --- a/package.json +++ b/package.json @@ -62,7 +62,6 @@ "lightningcss": "^1.33.0", "mlly": "^1.8.2", "pathe": "^2.0.3", - "pkg-types": "^2.4.0", "tinyglobby": "^0.2.17", "vue-sfc-transformer": "^0.3.3" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47083914..9812f346 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -193,9 +193,6 @@ importers: pathe: specifier: ^2.0.3 version: 2.0.3 - pkg-types: - specifier: ^2.4.0 - version: 2.4.0 tinyglobby: specifier: ^0.2.17 version: 0.2.17 diff --git a/src/build/build.ts b/src/build/build.ts index 15726567..dca64f24 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -4,7 +4,6 @@ import { readFile, rm } from 'node:fs/promises' import { dirname, join, normalize, relative, resolve } from 'pathe' import type { NuxtModule } from '@nuxt/schema' import type { TsConfigResult } from 'get-tsconfig' -import type { PackageJson } from 'pkg-types' import { glob, globSync } from 'tinyglobby' import builderPkg from '../../package.json' with { type: 'json' } @@ -13,6 +12,7 @@ import { EXCLUDE } from '../transpile/transpile-dir.ts' import type { ResolveExternal } from '../transpile/transpile-dir.ts' import { createTsconfigResolver, declarationPaths, hasIsolatedDeclarations, namedCachePath, tsconfigPaths, writeDependencyImports, writeDerivedTsconfig, writeServerRoutesStub } from '../transpile/tsconfig.ts' import { findPackageDir, findUp, isInside, isSourceScript, logger, probe, relativeSpecifier, SCRIPT_RE, writeIfChanged } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import { rewriteRuntimeDeclarations } from './aliases.ts' import { guide } from './guide.ts' import { assertLoadableModuleCode, importModule, loadOxc } from './loader.ts' diff --git a/src/build/options.ts b/src/build/options.ts index c34b9812..b55f6553 100644 --- a/src/build/options.ts +++ b/src/build/options.ts @@ -1,8 +1,8 @@ import { isAbsolute, normalize, relative, resolve } from 'pathe' -import type { PackageJson } from 'pkg-types' import { assertNoLegacyBuildConfig } from '../legacy/build-config.ts' import { escapeRegExp, isInside, isPlainObject, probe, realpath } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import type { BuildPlan } from './build.ts' import { guide } from './guide.ts' diff --git a/src/build/package.ts b/src/build/package.ts index bb18ee37..2e06b4cc 100644 --- a/src/build/package.ts +++ b/src/build/package.ts @@ -1,10 +1,8 @@ import { existsSync } from 'node:fs' import { basename, join, relative, resolve } from 'pathe' -import { readPackageJSON } from 'pkg-types' -import type { PackageJson } from 'pkg-types' - import { checkLegacyCJSPaths, checkLegacyDeclarationPaths, isLegacyPath } from '../legacy/package-paths.ts' -import { DECLARATION_RE, isFile, isInside, logger, TYPESCRIPT_RE } from '../utils.ts' +import { DECLARATION_RE, isFile, isInside, logger, readPackageJson, TYPESCRIPT_RE } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import { guide } from './guide.ts' /** The fields of `package.json` whose paths are checked for whether they can be published. */ @@ -266,7 +264,7 @@ function exportTarget(target: unknown): string | undefined { * The paths are read as published, with `publishConfig` applied. */ export async function checkPublishedPaths(cwd: string): Promise { - const read = await readPackageJSON(cwd).catch(() => undefined) + const read = await readPackageJson(cwd).catch(() => undefined) if (!read) { return } diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 82b5fc02..69b14473 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -4,8 +4,6 @@ import { readFile, writeFile } from 'node:fs/promises' import { parseTsconfig } from 'get-tsconfig' import { resolvePath } from 'mlly' import { dirname, join, relative, resolve } from 'pathe' -import { readPackageJSON } from 'pkg-types' -import type { PackageJson } from 'pkg-types' import { glob } from 'tinyglobby' import { assertLoadableModuleCode, importModule } from '../build/loader.ts' import { moduleDeclarationPaths, writeModuleDeclarations } from '../build/module-declarations.ts' @@ -15,7 +13,8 @@ import { selfReferencePaths } from '../build/package.ts' import { writeSourceTypes } from '../build/types.ts' import { loadBuildConfig } from '../legacy/build-config.ts' import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts' -import { isInside, probe } from '../utils.ts' +import { isInside, probe, readPackageJson } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' import type { CommandDef } from './_shared.ts' import { loadModuleConfig } from './config-file.ts' @@ -30,7 +29,7 @@ interface PrepareConfig { } async function loadPrepareConfig(cwd: string): Promise { - const pkg = await readPackageJSON(cwd) + const pkg = await readPackageJson(cwd) const moduleConfig = await loadModuleConfig(cwd) const outDir = resolve(cwd, moduleConfig?.outDir ?? 'dist') const config = moduleConfig ? resolveModuleOptions(cwd, pkg, outDir, moduleConfig.options) : await loadBuildConfig(cwd, pkg, outDir) diff --git a/src/legacy/build-config.ts b/src/legacy/build-config.ts index 5e636053..71b248b1 100644 --- a/src/legacy/build-config.ts +++ b/src/legacy/build-config.ts @@ -5,7 +5,6 @@ import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { relative, resolve } from 'pathe' -import type { PackageJson } from 'pkg-types' import type { BuildPlan } from '../build/build.ts' import { guide } from '../build/guide.ts' @@ -14,6 +13,7 @@ import { findModuleCodeIssues, formatModuleCodeIssues, importModule } from '../b import { bundledEntries, createOptionsCollector, entryName } from '../build/options.ts' import type { BuildHookName, ModuleConfig } from '../build/options.ts' import { isPlainObject, logger } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import type { BuildContext, BuildHook } from './define.ts' const BUILD_CONFIG_FILES = ['build.config.ts', 'build.config.mts', 'build.config.js', 'build.config.mjs'] diff --git a/src/legacy/define.ts b/src/legacy/define.ts index 4bb9bbf5..8a07a079 100644 --- a/src/legacy/define.ts +++ b/src/legacy/define.ts @@ -2,7 +2,7 @@ * `defineBuildConfig` and the types of a v1 module's `build.config.ts`, which * `@nuxt/module-builder` still exports for modules that have not moved to `builder()`. */ -import type { PackageJson } from 'pkg-types' +import type { PackageJson } from '../utils.ts' export interface BuildEntry { input: string diff --git a/src/legacy/package-paths.ts b/src/legacy/package-paths.ts index 4f3be881..f11576b8 100644 --- a/src/legacy/package-paths.ts +++ b/src/legacy/package-paths.ts @@ -2,10 +2,10 @@ * Advice for `package.json` paths to the `.d.ts` declarations and `module.cjs` that v1 * of `@nuxt/module-builder` generated for the module entry. */ -import type { PackageJson } from 'pkg-types' import { guide } from '../build/guide.ts' import { list, missingPaths, warnWhen } from '../build/package.ts' +import type { PackageJson } from '../utils.ts' const DECLARATION_RE = /(?:^|\/)(?:module|types)\.d\.ts$/ const CJS_MODULE_RE = /(?:^|\/)module\.cjs$/ diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index 800ff92a..385f8879 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -1,10 +1,9 @@ import { existsSync, readdirSync } from 'node:fs' import { rm } from 'node:fs/promises' +import { createRequire } from 'node:module' import { pathToFileURL } from 'node:url' import { relative, resolve } from 'pathe' import { resolvePath } from 'mlly' -import { readPackageJSON } from 'pkg-types' -import type { PackageJson } from 'pkg-types' import type { InlineConfig, ResolvedConfig, Rolldown, UserConfig } from 'tsdown' import { analyseSources, finishBuild, onBuildError, prepareBuild, preservesJsx, resolveBuild, resolveDirectoryExternal } from '../build/build.ts' @@ -15,7 +14,8 @@ import type { BuilderOptions, ModuleConfig, ReplaceOptions } from '../build/opti import { sourcePathsPackError, unpublishablePathsError } from '../build/package.ts' import { prepareModule } from '../commands/prepare.ts' import { transpileDir, TYPE_ERRORS_WARNING } from '../transpile/transpile-dir.ts' -import { findUp, logger, realpath } from '../utils.ts' +import { findUp, logger, readPackageJson, realpath } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import { externalDependencyDeclarations, runtimeExternals } from './externals.ts' import { defaultReport, reportsSummary, sizeBreakdown } from './report.ts' import { unchangedOutputs } from './unchanged.ts' @@ -76,7 +76,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt } const cwd = realpath(config.cwd ?? process.cwd()) - const pkg = await readPackageJSON(cwd) + const pkg = await readPackageJson(cwd) const packageError = sourcePathsPackError(cwd, pkg) ?? unpublishablePathsError(cwd, pkg) if (packageError) { throw new Error(packageError) @@ -253,7 +253,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt const outputs = await Promise.all(directoryPlugins.map(plugin => plugin.api.outputs)) await finishBuild(plan, { outputs: outputs.flatMap(map => [...map.values()]), - builder: { tsdown: await readPackageJSON('tsdown', { from: import.meta.url }).then(r => r.version || 'unknown').catch(() => 'unknown') }, + builder: { tsdown: (createRequire(import.meta.url)('tsdown/package.json') as PackageJson).version || 'unknown' }, keepOutput: watch, }) }, diff --git a/src/utils.ts b/src/utils.ts index 6081535d..decd807a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -9,6 +9,22 @@ export const logger = { error: (message: string): void => log.error(message, { spacing: 0, output: process.stderr }), } +/** The fields of `package.json` that the builder reads. */ +export interface PackageJson { + name?: string + version?: string + main?: string + module?: string + types?: string + typings?: string + exports?: unknown + imports?: unknown + typesVersions?: unknown + files?: string[] + publishConfig?: Record + [key: string]: unknown +} + export const SCRIPT_RE: RegExp = /\.[cm]?[jt]sx?$/ export const TYPESCRIPT_RE: RegExp = /\.[cm]?tsx?$/ export const DECLARATION_RE: RegExp = /\.d\.[cm]?ts$/ @@ -77,6 +93,11 @@ export function relativeSpecifier(from: string, to: string): string { return RELATIVE_RE.test(path) ? path : `./${path}` } +/** The `package.json` in `dir`. */ +export async function readPackageJson(dir: string): Promise { + return JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as PackageJson +} + /** The directory of an installed package, found the way Node looks up `node_modules`. */ export function findPackageDir(name: string, cwd: string): string | undefined { return findUp(cwd, dir => existsSync(join(dir, 'node_modules', name, 'package.json')) ? join(dir, 'node_modules', name) : undefined) diff --git a/test/cli.spec.ts b/test/cli.spec.ts index fcd9d39f..363ceca3 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -3,13 +3,13 @@ import { pathToFileURL } from 'node:url' import { findStaticImports } from 'mlly' import { version as nuxtVersion } from 'nuxt/package.json' import { join, relative, resolve } from 'pathe' -import { readPackageJSON } from 'pkg-types' -import type { PackageJson } from 'pkg-types' +import { version as tsdownVersion } from 'tsdown/package.json' import { satisfies } from 'verkit' import { beforeAll, describe, expect, it } from 'vitest' import { version } from '../package.json' import { guide } from '../src/build/guide.ts' +import type { PackageJson } from '../src/utils.ts' import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts' import type { Result } from './utils.ts' import { bin, builderImport, cli, cliBin, exampleDir, exists, fixture, listFiles, read, repoRoot, run, succeed, tsdownBin, unresolvedSpecifiers } from './utils.ts' @@ -1521,9 +1521,8 @@ describe('the example', () => { }) it('should generate module metadata as separate JSON file', async () => { - const tsdownPkg = await readPackageJSON('tsdown') expect(JSON.parse(await read(dist(), 'module.json'))).toMatchObject({ - builder: { '@nuxt/module-builder': version, 'tsdown': tsdownPkg.version }, + builder: { '@nuxt/module-builder': version, 'tsdown': tsdownVersion }, configKey: 'myModule', name: 'my-module', version: '1.0.0', diff --git a/test/pack-env.ts b/test/pack-env.ts index d6351334..83d29f25 100644 --- a/test/pack-env.ts +++ b/test/pack-env.ts @@ -1,7 +1,7 @@ import process from 'node:process' -import { readPackageJSON } from 'pkg-types' import { sourcePathsPackError, unpublishablePaths } from '../src/build/package.ts' +import { readPackageJson } from '../src/utils.ts' const PACK_VARS = /^npm_(?:lifecycle_event|execpath|config_user_agent|command)$/i @@ -31,7 +31,7 @@ function packVars() { if (process.env.MODULE_BUILDER_PACK_PROBE) { delete process.env.MODULE_BUILDER_PACK_PROBE const cwd = process.cwd() - const pkg = await readPackageJSON(cwd) + const pkg = await readPackageJson(cwd) const report = (when: string, extra: Record = {}) => process.stderr.write(`[pack-probe] ${when} ${JSON.stringify({ pid: process.pid, ppid: process.ppid, diff --git a/test/utils.ts b/test/utils.ts index d8b7bbc6..80ba5c9e 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -5,10 +5,10 @@ import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' import { dirname, join } from 'pathe' import { exec } from 'tinyexec' -import type { PackageJson } from 'pkg-types' import { onTestFailed } from 'vitest' import { publishedPackage } from '../src/build/package.ts' +import type { PackageJson } from '../src/utils.ts' export const repoRoot = fileURLToPath(new URL('..', import.meta.url)) export const exampleDir = join(repoRoot, 'example') diff --git a/test/watch.spec.ts b/test/watch.spec.ts index d8220f4c..3039a548 100644 --- a/test/watch.spec.ts +++ b/test/watch.spec.ts @@ -3,10 +3,10 @@ import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { setTimeout as delay } from 'node:timers/promises' import { pathToFileURL } from 'node:url' import { join, relative } from 'pathe' -import type { PackageJson } from 'pkg-types' import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' import type { TestContext } from 'vitest' +import type { PackageJson } from '../src/utils.ts' import { builderImport, exists, fixture, read, repoRoot, run, succeed, tsdown, tsdownBin, waitFor, watch } from './utils.ts' const PLUGIN = `export default {\n plugins: [builder()],\n}\n` From 7e0cdea0d095341753365d06012653f379e7058d Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 12:17:02 +0000 Subject: [PATCH 04/12] refactor: parse imports and exports with typescript instead of mlly --- package.json | 1 - pnpm-lock.yaml | 3 - src/build/build.ts | 2 +- src/build/loader.ts | 57 ++++++++++----- src/build/module-declarations.ts | 2 +- src/build/types.ts | 104 +++++++++++++++++++--------- src/commands/prepare.ts | 13 ++-- src/transpile/specifiers.ts | 115 ++++++++++++++++++------------- src/transpile/stylesheets.ts | 5 +- src/transpile/transpile-dir.ts | 6 +- src/transpile/tsconfig.ts | 6 +- src/tsdown/setup.ts | 4 +- src/utils.ts | 14 ++++ test/cli.spec.ts | 15 ++-- test/legacy.spec.ts | 5 +- test/unit.spec.ts | 48 ++++++++++++- test/utils.ts | 7 ++ 17 files changed, 269 insertions(+), 138 deletions(-) diff --git a/package.json b/package.json index 9d0b1c0e..ca045158 100644 --- a/package.json +++ b/package.json @@ -60,7 +60,6 @@ "browserslist": "^4.29.5", "get-tsconfig": "^4.14.3", "lightningcss": "^1.33.0", - "mlly": "^1.8.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.17", "vue-sfc-transformer": "^0.3.3" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9812f346..a6010ce0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -187,9 +187,6 @@ importers: lightningcss: specifier: ^1.33.0 version: 1.33.0 - mlly: - specifier: ^1.8.2 - version: 1.8.2 pathe: specifier: ^2.0.3 version: 2.0.3 diff --git a/src/build/build.ts b/src/build/build.ts index dca64f24..55e883c8 100644 --- a/src/build/build.ts +++ b/src/build/build.ts @@ -291,7 +291,7 @@ function valueImports(roots: string[]) { } found.add(file) const { code } = transformSync(file, readFileSync(file, 'utf8'), { lang: file.match(/\.[cm]?([jt]sx?)$/)![1], jsx: 'preserve', typescript: { onlyRemoveTypeImports: false } }) - for (const specifier of valueSpecifiers(code)) { + for (const specifier of valueSpecifiers(code, file)) { const target = probe(resolve(dirname(file), specifier)) if (target && isSourceScript(target)) { queue.push(normalize(target)) diff --git a/src/build/loader.ts b/src/build/loader.ts index e04be434..e6a8d738 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -1,19 +1,21 @@ import { existsSync, readFileSync } from 'node:fs' import { createRequire, registerHooks } from 'node:module' import { fileURLToPath, pathToFileURL } from 'node:url' -import { dirname, relative, resolve } from 'pathe' -import { resolvePathSync } from 'mlly' +import { dirname, join, relative, resolve } from 'pathe' import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type ts from 'typescript' import type { Transform } from '../transpile/transpile-dir.ts' -import { isInside, NODE_MODULES_RE, probe, relativeSpecifier, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' +import { findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' +import type { PackageJson } from '../utils.ts' import { guide } from './guide.ts' +import { importsKeyFor } from './package.ts' const VIRTUAL_ALIAS_RE = /^#(?:app|imports|build)(?:\/|$)/ const PATH_ALIAS_RE = /^(?:~|@\/)/ const JSON_RE = /\.json$/ const UNLOADABLE_RE = /\.(?:vue|[jt]sx)$/ +const IMPORT_CONDITIONS = new Set(['import', 'node', 'default']) export interface ImportModuleOptions { /** Module root, inside which `version` applies. */ @@ -214,20 +216,6 @@ function walkSources(cwd: string, entries: string[], visit: (file: string, analy } } -function resolvesAsPackage(specifier: string, parentDir: string) { - try { - return resolvePathSync(specifier, { url: pathToFileURL(resolve(parentDir, 'index.js')), conditions: ['import', 'node', 'default'] }) - } - catch { - try { - return createRequire(resolve(parentDir, 'index.js')).resolve(specifier) - } - catch { - return undefined - } - } -} - /** * The module source `specifier` reaches: a relative file, an entry in the `imports` of the * module's `package.json`, or a tsconfig `paths` alias. Packages and the aliases only a @@ -241,7 +229,9 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP const file = probe(resolve(parentDir, specifier)) return file ? { file, via: 'relative' } : undefined } - const resolved = PATH_ALIAS_RE.test(specifier) ? undefined : resolvesAsPackage(specifier, parentDir) + const resolved = PATH_ALIAS_RE.test(specifier) + ? undefined + : (specifier.startsWith('#') && resolvePackageImport(specifier, parentDir)) || resolveFrom(resolve(parentDir, 'index.js'), specifier) if (resolved) { return specifier.startsWith('#') && isInside(cwd, resolved) && !NODE_MODULES_RE.test(resolved) ? { file: resolved, via: 'imports' } : undefined } @@ -253,6 +243,37 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP } } +/** The file that `specifier` maps to through the `imports` of the closest `package.json`, with the conditions of `import`. */ +function resolvePackageImport(specifier: string, parentDir: string) { + const scope = findUp(parentDir, dir => existsSync(join(dir, 'package.json')) ? dir : undefined) + const { imports } = scope ? JSON.parse(readFileSync(join(scope, 'package.json'), 'utf8')) as PackageJson : {} + const key = isPlainObject(imports) ? importsKeyFor(Object.keys(imports), specifier) : undefined + if (!scope || !key) { + return + } + const star = key.indexOf('*') + const target = importTarget((imports as Record)[key], star === -1 ? undefined : specifier.slice(star, specifier.length - key.length + star + 1)) + const file = target?.startsWith('./') ? resolve(scope, target) : undefined + return file && isFile(file) ? file : undefined +} + +function importTarget(target: unknown, match: string | undefined): string | undefined { + if (typeof target === 'string') { + return match === undefined ? target : target.replaceAll('*', match) + } + if (Array.isArray(target)) { + return target.map(item => importTarget(item, match)).find(item => item !== undefined) + } + if (isPlainObject(target)) { + for (const [condition, value] of Object.entries(target)) { + const resolved = IMPORT_CONDITIONS.has(condition) ? importTarget(value, match) : undefined + if (resolved !== undefined) { + return resolved + } + } + } +} + let typescript: typeof ts | undefined function scriptKind(ts: typeof import('typescript'), filename: string) { diff --git a/src/build/module-declarations.ts b/src/build/module-declarations.ts index eafdf340..b86bd9a4 100644 --- a/src/build/module-declarations.ts +++ b/src/build/module-declarations.ts @@ -64,7 +64,7 @@ export async function writeModuleDeclarations(cwd: string, dir: string, { tsconf return relativeSpecifier(output, declaration).replace(/\.d\.([cm]?)ts$/, '.$1js') } return isRelative && target ? relativeSpecifier(output, target).replace(/\.d\.([cm]?)ts$/, '.$1js') : undefined - }) + }, output) await mkdir(dirname(output), { recursive: true }) await writeFile(output, code) })) diff --git a/src/build/types.ts b/src/build/types.ts index 72f7a03e..ede391bb 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -1,18 +1,29 @@ import { existsSync, promises as fsp, readFileSync } from 'node:fs' import { dirname, relative, resolve } from 'pathe' -import { findExports, findTypeExports } from 'mlly' -import type { ESMExport } from 'mlly' +import type ts from 'typescript' +import { parseModule } from '../transpile/specifiers.ts' import { getOrCreate, probe, writeIfChanged } from '../utils.ts' -const TYPE_ONLY_DECLARATIONS = new Set(['interface', 'type']) +interface ExportedName { + name: string + /** Whether this export only exports a type: `export type`, `export { type Foo }`, an interface or a type alias. */ + typeOnly: boolean +} + +interface ModuleExport { + names: ExportedName[] + specifier?: string + /** For `export *` and `export * as`, whether it is `export type *`. */ + star?: { typeOnly: boolean } +} + const DECLARATION_SUFFIXES: Record = { '': ['.d.ts', '.d.mts', '.d.cts', '/index.d.ts', '/index.d.mts'], '.js': ['.d.ts'], '.mjs': ['.d.mts'], '.cjs': ['.d.cts'], } -const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function|const\s+enum|const|let|var|class|enum)\s+([$\w]+)/g /** * Writes `module.d.mts`, which re-exports `entry`, and the `types.d.mts` that adds its type @@ -21,7 +32,7 @@ const VALUE_DECLARATION_RE = /\bexport\s+declare\s+(?:async\s+function|function| */ export async function writeSourceTypes(dir: string, entry: string, reExported: string = entry): Promise { const source = await fsp.readFile(entry, 'utf8') - const hasDefaultExport = findExports(source).some(e => e.type === 'default' || e.names?.includes('default')) + const hasDefaultExport = parseExports(source, entry).some(e => e.names.some(({ name }) => name === 'default')) // TypeScript resolves the `.js` specifier to the `.ts` source, or to its declaration, without `allowImportingTsExtensions`. const path = relative(dir, reExported).replace(/\.([cm]?)tsx?$/, '.$1js') const specifier = path.startsWith('.') ? path : `./${path}` @@ -42,25 +53,14 @@ export async function writeSourceTypes(dir: string, entry: string, reExported: s export async function writeTypes(distDir: string, source?: { exports: Set | undefined }): Promise { const dtsFile = resolve(distDir, 'types.d.mts') - const moduleReExports: ESMExport[] = [] + let moduleReExports: ModuleExport[] = [] let typeOnlyExports = new Set() if (!source) { const moduleTypes = await fsp.readFile(resolve(distDir, 'module.d.mts'), 'utf8').catch(() => '') - const exports = findExports(withoutTypeModifiers(moduleTypes)) - const typeExports = findTypeExports(moduleTypes) - moduleReExports.push(...exports, ...typeExports) - const namedExports = (list: ESMExport[]) => list.filter(e => e.type === 'named' || e.type === 'default').flatMap(e => e.names) - const isTypeOnly = (e: ESMExport) => e.type === 'named' || (e.type === 'declaration' && TYPE_ONLY_DECLARATIONS.has(e.declarationType!)) - const valueExports = new Set([ - ...namedExports(findExports(moduleTypes)), - ...typeExports.filter(e => !isTypeOnly(e)).flatMap(e => e.names), - // `findTypeExports` drops a value declaration that shares its name with a type - // export, so read those names from the generated declarations too. - ...[...moduleTypes.matchAll(VALUE_DECLARATION_RE)].map(match => 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. - typeOnlyExports = new Set([...typeExports.filter(isTypeOnly).flatMap(e => e.names), ...namedExports(exports)].filter(name => !valueExports.has(name))) + moduleReExports = parseExports(moduleTypes, 'module.d.mts') + const names = moduleReExports.flatMap(e => e.names) + const valueExports = new Set(names.filter(e => !e.typeOnly).map(e => e.name)) + typeOnlyExports = new Set(names.map(e => e.name).filter(name => !valueExports.has(name))) } const appShims: string[] = [] @@ -71,7 +71,7 @@ export async function writeTypes(distDir: string, source?: { exports: Set source ? !source.exports || source.exports.has(name) - : moduleReExports.some(exp => exp.names?.includes(name)) + : moduleReExports.some(e => e.names.some(exported => exported.name === name)) if (!hasTypeExport('ModuleOptions')) { schemaImports.push('NuxtModule') @@ -101,7 +101,7 @@ ${schemaShims.length ? `declare module '@nuxt/schema' {\n${schemaShims.join('\n' ${moduleExports.length ? `\n${moduleExports.join('\n')}` : ''} ${source ? 'export * from "./module.mjs"\nexport { default } from "./module.mjs"' : ''} ${[...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')} +${moduleReExports.filter(e => e.star).map(e => `\nexport ${e.star!.typeOnly ? 'type ' : ''}*${e.names[0] ? ` as ${e.names[0].name}` : ''} from '${e.specifier}'`).join('\n')} `.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n' await writeIfChanged(dtsFile, dtsContents) @@ -117,10 +117,9 @@ function exportedNames(file: string, seen = new Set()): Set | un return names } seen.add(file) - const code = readFileSync(file, 'utf8') - for (const exp of [...findExports(withoutTypeModifiers(code).replace(/\bexport\s+type\s*\*/g, 'export *')), ...findTypeExports(code)]) { - if (exp.type !== 'star' || exp.names?.length) { - exp.names?.forEach(name => names.add(name)) + for (const exp of parseExports(readFileSync(file, 'utf8'), file)) { + if (!exp.star || exp.names.length) { + exp.names.forEach(({ name }) => names.add(name)) continue } const target = exp.specifier?.startsWith('.') ? probeWithDeclarations(resolve(dirname(file), exp.specifier)) : undefined @@ -140,17 +139,56 @@ function probeWithDeclarations(path: string) { return probe(path) ?? DECLARATION_SUFFIXES[extension]!.map(suffix => base + suffix).find(candidate => existsSync(candidate)) } -/** `code` with `export { type Foo }` written as `export { Foo }`, which `findExports` reports. */ -function withoutTypeModifiers(code: string) { - return code.replace(/export\s*\{.*?\}/gs, match => match.replace(/\b(type|interface)\b/g, '')) +function parseExports(code: string, filename: string): ModuleExport[] { + const { ts, sourceFile } = parseModule(code, filename) + const exports: ModuleExport[] = [] + const hasModifier = (node: ts.Node, kind: ts.SyntaxKind) => ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(modifier => modifier.kind === kind) + for (const statement of sourceFile.statements) { + if (ts.isExportDeclaration(statement)) { + const specifier = statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) ? statement.moduleSpecifier.text : undefined + const clause = statement.exportClause + if (clause && ts.isNamedExports(clause)) { + exports.push({ specifier, names: clause.elements.map(element => ({ name: element.name.text, typeOnly: statement.isTypeOnly || element.isTypeOnly })) }) + } + else if (specifier) { + exports.push({ specifier, star: { typeOnly: statement.isTypeOnly }, names: clause ? [{ name: clause.name.text, typeOnly: statement.isTypeOnly }] : [] }) + } + } + else if (ts.isExportAssignment(statement)) { + if (!statement.isExportEquals) { + exports.push({ names: [{ name: 'default', typeOnly: false }] }) + } + } + else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword)) { + const typeOnly = ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) + const names = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? ['default'] : declaredNames(ts, statement) + exports.push({ names: names.map(name => ({ name, typeOnly })) }) + } + } + return exports +} + +function declaredNames(ts: typeof import('typescript'), statement: ts.Statement): string[] { + if (ts.isVariableStatement(statement)) { + return statement.declarationList.declarations.flatMap(declaration => bindingNames(ts, declaration.name)) + } + const name = (statement as ts.DeclarationStatement).name + return name && ts.isIdentifier(name) ? [name.text] : [] +} + +function bindingNames(ts: typeof import('typescript'), name: ts.BindingName): string[] { + if (ts.isIdentifier(name)) { + return [name.text] + } + return name.elements.flatMap(element => ts.isBindingElement(element) ? bindingNames(ts, element.name) : []) } -function groupNamedReExports(exports: ESMExport[]) { +function groupNamedReExports(exports: ModuleExport[]) { const groups = new Map>() for (const e of exports) { - if (e.type === 'named' || e.type === 'default' || e.type === 'declaration') { + if (!e.star) { const names = getOrCreate(groups, e.specifier || './module.mjs', () => new Set()) - e.names.forEach(name => names.add(name)) + e.names.forEach(({ name }) => names.add(name)) } } return new Map([...groups].map(([specifier, names]) => [ diff --git a/src/commands/prepare.ts b/src/commands/prepare.ts index 69b14473..00ba0bc0 100644 --- a/src/commands/prepare.ts +++ b/src/commands/prepare.ts @@ -2,7 +2,6 @@ import { pathToFileURL } from 'node:url' import type { Nuxt, NuxtConfig, NuxtModule } from '@nuxt/schema' import { readFile, writeFile } from 'node:fs/promises' import { parseTsconfig } from 'get-tsconfig' -import { resolvePath } from 'mlly' import { dirname, join, relative, resolve } from 'pathe' import { glob } from 'tinyglobby' import { assertLoadableModuleCode, importModule } from '../build/loader.ts' @@ -13,7 +12,7 @@ import { selfReferencePaths } from '../build/package.ts' import { writeSourceTypes } from '../build/types.ts' import { loadBuildConfig } from '../legacy/build-config.ts' import { createTsconfigResolver, isModuleFile, rootTsconfig } from '../transpile/tsconfig.ts' -import { isInside, probe, readPackageJson } from '../utils.ts' +import { isInside, probe, readPackageJson, resolveFrom } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { assertNoStubArg, resolveCwdArg, sharedArgs } from './_shared.ts' import type { CommandDef } from './_shared.ts' @@ -278,11 +277,11 @@ function replaceEntries(modules: unknown[] | undefined, name: string, nuxtModule /** `useNuxt` from the kit the module in `cwd` resolves, so hooks can read the Nuxt instance they run in. */ async function loadUseNuxt(cwd: string): Promise<(() => Nuxt) | undefined> { - for (const id of ['@nuxt/kit', 'nuxt/kit']) { - const path = await resolvePath(id, { url: pathToFileURL(`${cwd}/`) }).catch(() => undefined) - if (path) { - return (await import(pathToFileURL(path).href) as { useNuxt: () => Nuxt }).useNuxt - } + const nuxt = resolveFrom(`${cwd}/`, 'nuxt/package.json') + // `nuxt/kit` re-exports the `@nuxt/kit` that `nuxt` depends on, and some versions of `nuxt` export it only for `import`. + const path = resolveFrom(`${cwd}/`, '@nuxt/kit') ?? (nuxt && resolveFrom(nuxt, '@nuxt/kit')) + if (path) { + return (await import(pathToFileURL(path).href) as { useNuxt: () => Nuxt }).useNuxt } } diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts index c34681cb..d772595c 100644 --- a/src/transpile/specifiers.ts +++ b/src/transpile/specifiers.ts @@ -1,8 +1,12 @@ -import { findDynamicImports, findExports, findStaticImports, findTypeExports } from 'mlly' +import { createRequire } from 'node:module' +import type ts from 'typescript' import { RELATIVE_RE } from '../utils.ts' const JSX_RE = /\.[jt]sx$/ +const DYNAMIC_IMPORT_RE = /\bimport\s*(?:\(|\/[*/])/ +const VUE_SCRIPT_RE = /(]*>)([\s\S]*?)<\/script\s*>/gi +const VUE_LANG_RE = /\blang\s*=\s*["']?(\w+)/ /** The extension `file` is emitted with: `.jsx` for a JSX source when JSX is preserved, `extension` otherwise. */ export function scriptExtension(file: string, extension: string, preserveJsx: boolean): string { @@ -17,51 +21,78 @@ export interface Specifier { end: number } -const DYNAMIC_IMPORT_RE = /^\s*(?:\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*)*(?:(['"])([^'"\n]+)\1|`([^`$]+)`)\s*(?:,[\s\S]*)?$/ - -/** The specifier of an `import()` whose first argument is a string literal. */ -function dynamicImportSpecifier(expression: string) { - const match = expression.match(DYNAMIC_IMPORT_RE) - return match ? match[2] ?? match[3] : undefined +interface Reference extends Specifier { + /** Whether the reference is `import type`, `export type` or an `import()` type. */ + typeOnly: boolean } -const TYPE_STAR_EXPORT_RE = /\bexport\s+type\s*\*(?:\s*as\s+[\w$]+)?\s*from\s*(['"])([^'"\n]+)\1/g +let typescript: typeof import('typescript') | undefined -/** Every string-literal module specifier in `code`: static imports, re-exports (type-only ones included) and `import()` calls. */ -export function moduleSpecifiers(code: string): Specifier[] { - const found = new Map() - const locate = (statement: { code: string, start: number }, specifier: string) => { - const index = Math.max(...['\'', '"', '`'].map(quote => statement.code.indexOf(`${quote}${specifier}${quote}`))) - if (index !== -1) { - const start = statement.start + index - found.set(start, { specifier, start, end: start + specifier.length + 2 }) - } +/** `code` parsed by TypeScript, as the language that the extension of `filename` implies. */ +export function parseModule(code: string, filename: string): { ts: typeof import('typescript'), sourceFile: ts.SourceFile } { + const ts = typescript ??= createRequire(import.meta.url)('typescript') as typeof import('typescript') + const sourceFile = ts.createSourceFile(filename, code, { languageVersion: ts.ScriptTarget.Latest, jsDocParsingMode: ts.JSDocParsingMode.ParseNone }) + return { ts, sourceFile } +} + +function references(code: string, filename: string): Reference[] { + if (!filename.endsWith('.vue')) { + return scriptReferences(code, filename, 0) } - for (const statement of findStaticImports(code)) { - locate(statement, statement.specifier) + return [...code.matchAll(VUE_SCRIPT_RE)].flatMap(({ 1: tag, 2: content, index }) => { + const lang = tag!.match(VUE_LANG_RE)?.[1] ?? 'js' + return scriptReferences(content!, `${filename}.${lang}`, index + tag!.length) + }) +} + +function scriptReferences(code: string, filename: string, offset: number): Reference[] { + const { ts, sourceFile } = parseModule(code, filename) + const found: Reference[] = [] + const add = (node: ts.StringLiteralLike, typeOnly: boolean) => { + found.push({ specifier: node.text, start: offset + node.getStart(sourceFile), end: offset + node.end, typeOnly }) } - for (const statement of [...findExports(code), ...findTypeExports(code)]) { - if (statement.specifier) { - locate(statement, statement.specifier) + const visitStatements = (statements: ts.NodeArray) => { + for (const statement of statements) { + if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { + add(statement.moduleSpecifier, !!statement.importClause?.isTypeOnly) + } + else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) { + add(statement.moduleSpecifier, statement.isTypeOnly) + } + else if (ts.isModuleDeclaration(statement) && statement.body && ts.isModuleBlock(statement.body)) { + visitStatements(statement.body.statements) + } } } - for (const match of code.matchAll(TYPE_STAR_EXPORT_RE)) { - locate({ code: match[0], start: match.index }, match[2]!) - } - for (const statement of findDynamicImports(code)) { - const specifier = dynamicImportSpecifier(statement.expression) - if (specifier) { - locate(statement, specifier) + visitStatements(sourceFile.statements) + if (DYNAMIC_IMPORT_RE.test(code)) { + const visit = (node: ts.Node): void => { + if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteralLike(node.arguments[0])) { + add(node.arguments[0], false) + } + else if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) && ts.isStringLiteral(node.argument.literal)) { + add(node.argument.literal, true) + } + ts.forEachChild(node, visit) } + visit(sourceFile) } - return [...found.values()].sort((a, b) => a.start - b.start) + return found.sort((a, b) => a.start - b.start) +} + +/** + * Every string-literal module specifier in `code`, a script or a single-file component named + * `filename`: static imports, re-exports (type-only ones included), `import()` calls and types. + */ +export function moduleSpecifiers(code: string, filename = 'module.ts'): Specifier[] { + return references(code, filename).map(({ specifier, start, end }) => ({ specifier, start, end })) } /** `code` with each specifier replaced by what `replace` returns for it, when that differs. */ -export function rewriteSpecifiers(code: string, replace: (specifier: string) => string | undefined): string { +export function rewriteSpecifiers(code: string, replace: (specifier: string) => string | undefined, filename?: string): string { let result = '' let cursor = 0 - for (const { specifier, start, end } of moduleSpecifiers(code)) { + for (const { specifier, start, end } of moduleSpecifiers(code, filename)) { const replacement = replace(specifier) if (replacement === undefined || replacement === specifier) { continue @@ -72,21 +103,7 @@ export function rewriteSpecifiers(code: string, replace: (specifier: string) => return result + code.slice(cursor) } -const TYPE_ONLY_RE = /^\s*(?:import|export)\s+type\b/ - -/** The relative specifiers of `code` that are not `import type` or `export type` statements. */ -export function valueSpecifiers(code: string): Set { - const values = new Set() - for (const statement of [...findStaticImports(code), ...findExports(code)]) { - if (statement.specifier && RELATIVE_RE.test(statement.specifier) && !TYPE_ONLY_RE.test(statement.code)) { - values.add(statement.specifier) - } - } - for (const statement of findDynamicImports(code)) { - const specifier = dynamicImportSpecifier(statement.expression) - if (specifier && RELATIVE_RE.test(specifier)) { - values.add(specifier) - } - } - return values +/** The relative specifiers of `code` that are not `import type`, `export type` or `import()` types. */ +export function valueSpecifiers(code: string, filename = 'module.ts'): Set { + return new Set(references(code, filename).filter(({ specifier, typeOnly }) => !typeOnly && RELATIVE_RE.test(specifier)).map(({ specifier }) => specifier)) } diff --git a/src/transpile/stylesheets.ts b/src/transpile/stylesheets.ts index 6ae1268f..711f80cb 100644 --- a/src/transpile/stylesheets.ts +++ b/src/transpile/stylesheets.ts @@ -1,9 +1,8 @@ import { promises as fsp } from 'node:fs' import { pathToFileURL } from 'node:url' -import { resolvePath } from 'mlly' import { join, relative } from 'pathe' -import { getOrCreate } from '../utils.ts' +import { getOrCreate, resolveFrom } from '../utils.ts' export const SASS_RE: RegExp = /\.s[ac]ss$/ @@ -57,7 +56,7 @@ export async function compileSass(file: string, cwd: string): Promise { async function loadSass(cwd: string): Promise { for (const name of ['sass', 'sass-embedded']) { - const path = await resolvePath(name, { url: pathToFileURL(join(cwd, 'package.json')) }).catch(() => undefined) + const path = resolveFrom(join(cwd, 'package.json'), name) if (path) { const sass = await import(pathToFileURL(path).href) return sass.compileString ? sass : sass.default diff --git a/src/transpile/transpile-dir.ts b/src/transpile/transpile-dir.ts index 5adeb75a..523c0e10 100644 --- a/src/transpile/transpile-dir.ts +++ b/src/transpile/transpile-dir.ts @@ -280,8 +280,8 @@ class DirectoryBuild { private async readEdges(importer: string): Promise { const source = await readFile(importer, 'utf8') - const values = valueSpecifiers(importer.endsWith('.vue') ? source : (await this.transpileSource(importer, source)).code) - const specifiers = new Set(moduleSpecifiers(source).map(({ specifier }) => specifier).filter(specifier => RELATIVE_RE.test(specifier))) + const values = valueSpecifiers(importer.endsWith('.vue') ? source : (await this.transpileSource(importer, source)).code, importer) + const specifiers = new Set(moduleSpecifiers(source, importer).map(({ specifier }) => specifier).filter(specifier => RELATIVE_RE.test(specifier))) return [...specifiers].flatMap((specifier) => { const target = probe(resolve(dirname(importer), specifier)) return target && isSourceScript(target) ? [{ specifier, target: normalize(target), value: values.has(specifier) }] : [] @@ -319,7 +319,7 @@ class DirectoryBuild { */ private rewriteSpecifiers(source: string, output: string, code: string, declaration = false) { const referenced = new Set() - const rewritten = rewriteSpecifiers(code, specifier => RELATIVE_RE.test(specifier) ? this.replacement(source, specifier, output, referenced) : undefined) + const rewritten = rewriteSpecifiers(code, specifier => RELATIVE_RE.test(specifier) ? this.replacement(source, specifier, output, referenced) : undefined, output) if (declaration) { this.references.set(source, referenced) } diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 945e5a7d..29c91dd1 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -367,10 +367,10 @@ export async function writeDependencyImports(cwd: string, tsconfig: TsConfigResu } const { default: ts } = await import('typescript') const files = new Set(projects.flatMap(project => projectFiles(parseProject(ts, project.path, true), cwd))) - const sources = await Promise.all([...files].sort().map(file => readFile(file, 'utf8').catch(() => ''))) + const sources = await Promise.all([...files].sort().map(async file => ({ file, source: await readFile(file, 'utf8').catch(() => '') }))) const specifiers = new Map() - for (const source of sources) { - for (const { specifier } of moduleSpecifiers(source)) { + for (const { file, source } of sources) { + for (const { specifier } of moduleSpecifiers(source, file)) { const name = packageName(specifier) if (name && !specifiers.has(name) && findPackageDir(name, cwd)) { specifiers.set(name, specifier) diff --git a/src/tsdown/setup.ts b/src/tsdown/setup.ts index 385f8879..9c80c9d3 100644 --- a/src/tsdown/setup.ts +++ b/src/tsdown/setup.ts @@ -3,7 +3,6 @@ import { rm } from 'node:fs/promises' import { createRequire } from 'node:module' import { pathToFileURL } from 'node:url' import { relative, resolve } from 'pathe' -import { resolvePath } from 'mlly' import type { InlineConfig, ResolvedConfig, Rolldown, UserConfig } from 'tsdown' import { analyseSources, finishBuild, onBuildError, prepareBuild, preservesJsx, resolveBuild, resolveDirectoryExternal } from '../build/build.ts' @@ -266,8 +265,7 @@ export async function setupBuilder(config: UserConfig, inline: InlineConfig, opt * tsdown runs, because built-in plugins only work with the binding that created them. */ async function replacePlugin({ values, ...options }: ReplaceOptions): Promise { - const tsdown = await resolvePath('tsdown', { url: import.meta.url }) - const plugins = await resolvePath('rolldown/plugins', { url: tsdown }) + const plugins = createRequire(import.meta.resolve('tsdown')).resolve('rolldown/plugins') const { replacePlugin } = await import(pathToFileURL(plugins).href) as { replacePlugin: (values: Record, options: Omit) => Rolldown.RolldownPluginOption } return replacePlugin(values, options) } diff --git a/src/utils.ts b/src/utils.ts index decd807a..2230da80 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,6 @@ import { existsSync, realpathSync, statSync } from 'node:fs' import { readFile, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' import { log } from '@clack/prompts' import { basename, dirname, isAbsolute, join, relative, resolve } from 'pathe' @@ -98,6 +99,19 @@ export async function readPackageJson(dir: string): Promise { return JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as PackageJson } +/** + * The file that `specifier` resolves to from `parent`, a file or a directory path ending in + * `/`, with the conditions of `require`. + */ +export function resolveFrom(parent: string | URL, specifier: string): string | undefined { + try { + return createRequire(parent).resolve(specifier) + } + catch { + return undefined + } +} + /** The directory of an installed package, found the way Node looks up `node_modules`. */ export function findPackageDir(name: string, cwd: string): string | undefined { return findUp(cwd, dir => existsSync(join(dir, 'node_modules', name, 'package.json')) ? join(dir, 'node_modules', name) : undefined) diff --git a/test/cli.spec.ts b/test/cli.spec.ts index 363ceca3..811dc697 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -1,6 +1,5 @@ import { mkdir, readFile, rename, rm, symlink, writeFile } from 'node:fs/promises' import { pathToFileURL } from 'node:url' -import { findStaticImports } from 'mlly' import { version as nuxtVersion } from 'nuxt/package.json' import { join, relative, resolve } from 'pathe' import { version as tsdownVersion } from 'tsdown/package.json' @@ -12,7 +11,7 @@ import { guide } from '../src/build/guide.ts' import type { PackageJson } from '../src/utils.ts' import { npmPackFromPnpmScript, packProbeArgs, packProbeContext } from './pack-env.ts' import type { Result } from './utils.ts' -import { bin, builderImport, cli, cliBin, exampleDir, exists, fixture, listFiles, read, repoRoot, run, succeed, tsdownBin, unresolvedSpecifiers } from './utils.ts' +import { bin, builderImport, cli, cliBin, exampleDir, exists, fixture, listFiles, read, repoRoot, run, staticImports, succeed, tsdownBin, unresolvedSpecifiers } from './utils.ts' const LEGACY_TSCONFIG = { extends: './.nuxt/tsconfig.json', exclude: ['dist', 'node_modules', 'playground', '**/tsdown.config.ts'] } const ISOLATED = { @@ -65,7 +64,7 @@ void [light, dark, options] }), } -const runtimeSpecifiers = (code: string) => findStaticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort() +const runtimeSpecifiers = (code: string) => staticImports(code).map(i => i.specifier).filter(s => s.includes('runtime')).sort() const dirs: Record = {} let sourceWithoutDist = false @@ -687,8 +686,8 @@ describe('a module that imports runtime code, built through a symlink, under a p './runtime/utils/name.js', ]) const moduleDts = await read(dist(), 'module.d.mts') - expect(findStaticImports(moduleDts).find(i => i.specifier.includes('plugins'))!.code.trim()).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`) - expect(findStaticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx') + expect(staticImports(moduleDts).find(i => i.specifier.includes('plugins'))!.code).toBe(`import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";`) + expect(staticImports(moduleDts).map(i => i.specifier)).toContain('./runtime/components/JsxComponent.jsx') expect(moduleDts).toContain('from "nuxt/app"') expect(moduleDts).not.toContain('#app') }) @@ -727,7 +726,7 @@ describe('a module that imports runtime code, built through a symlink, under a p }) it('should keep every non-relative runtime import as written', async () => { - expect(findStaticImports(await read(dist(), 'runtime/server/handler.js')).map(i => i.specifier)).toEqual([ + expect(staticImports(await read(dist(), 'runtime/server/handler.js')).map(i => i.specifier)).toEqual([ '#internal/nuxt.config.mjs', '~/app.config', '@/root', @@ -736,7 +735,7 @@ describe('a module that imports runtime code, built through a symlink, under a p '#fixture-cache', '../utils/local.js', ]) - expect(findStaticImports(await read(dist(), 'runtime/utils/options.d.ts')).map(i => i.specifier)).toEqual(['fake-types']) + expect(staticImports(await read(dist(), 'runtime/utils/options.d.ts')).map(i => i.specifier)).toEqual(['fake-types']) }) it('should not emit dependencies or bundler helpers into the runtime directory', async () => { @@ -1551,7 +1550,7 @@ describe('the example', () => { }) it('should correctly add extensions to imports from runtime/ directory', async () => { - const runtimeImport = findStaticImports(await read(dist(), 'module.d.mts')).find(i => i.specifier.includes('runtime')) + const runtimeImport = staticImports(await read(dist(), 'module.d.mts')).find(i => i.specifier.includes('runtime')) expect(runtimeImport!.code.trim()).toMatchInlineSnapshot(`"import { SharedTypeFromRuntime } from "./runtime/plugins/plugin.js";"`) }) diff --git a/test/legacy.spec.ts b/test/legacy.spec.ts index b16b831e..2fe5af2f 100644 --- a/test/legacy.spec.ts +++ b/test/legacy.spec.ts @@ -2,7 +2,6 @@ import { createHash } from 'node:crypto' import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { fileURLToPath } from 'node:url' -import { findStaticImports } from 'mlly' import { join, relative } from 'pathe' import ts from 'typescript' import { beforeAll, describe, expect, it, vi } from 'vitest' @@ -12,7 +11,7 @@ import { assertNoLegacyBuildConfig, formatUnsupportedOptions, loadBuildConfig, t import { guide } from '../src/build/guide.ts' import { logger } from '../src/utils.ts' import type { FixtureOptions, Result } from './utils.ts' -import { cli, exists, fixture, listFiles, read, repoRoot, tsdown } from './utils.ts' +import { cli, exists, fixture, listFiles, read, repoRoot, staticImports, tsdown } from './utils.ts' const exampleDir = fileURLToPath(new URL('../example', import.meta.url)) @@ -479,7 +478,7 @@ export default defineBuildConfig({ it('should import runtime code relative to nested entries', async () => { const helper = await read(dirs.buildConfig!, 'dist/nested/helper.mjs') - expect(findStaticImports(helper).map(i => i.specifier)).toEqual(['../runtime/plugins/plugin.js']) + expect(staticImports(helper).map(i => i.specifier)).toEqual(['../runtime/plugins/plugin.js']) expect(helper).toContain('import("../runtime/composables/useWrappedFetch.js")') expect(helper).not.toContain(dirs.buildConfig) }) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index fc99ea2d..e6f396a7 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -13,7 +13,7 @@ import { analyseSources, finishBuild, hashGeneratedTypes } from '../src/build/bu import type { BuildPlan } from '../src/build/build.ts' import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' import { resolveCwdArg } from '../src/commands/_shared.ts' -import { moduleSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' +import { moduleSpecifiers, rewriteSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' import { logger, relativeSpecifier } from '../src/utils.ts' import { setupBuilder } from '../src/tsdown/setup.ts' import { defaultReport, reportsSummary, sizeBreakdown } from '../src/tsdown/report.ts' @@ -26,7 +26,7 @@ import { transformCss } from '../src/transpile/stylesheets.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 { writeSourceTypes } from '../src/build/types.ts' +import { writeSourceTypes, writeTypes } from '../src/build/types.ts' import ts from 'typescript' import { GUIDE_SECTIONS, guide } from '../src/build/guide.ts' import { findModuleCodeIssues } from '../src/build/loader.ts' @@ -594,6 +594,30 @@ describe('sourcePathsPackError', () => { }) }) +describe('writeTypes', () => { + it('should re-export every declaration and star re-export of `module.d.mts` as written', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-types-')) + await writeFile(join(dir, 'module.d.mts'), [ + 'export declare abstract class Base {}', + 'export declare namespace Helpers { const x: number }', + 'export declare const a: string, b: number', + 'export declare const { c, d: [e] }: { c: 1, d: [2] }', + `export * as ns from './ns.mjs'`, + `export type * from './types.mjs'`, + 'export interface ModuleOptions {}', + 'declare const _default: unknown', + 'export { _default as default }', + ].join('\n')) + await writeTypes(dir) + expect((await readFile(join(dir, 'types.d.mts'), 'utf-8')).split('\n').filter(line => line.startsWith('export'))).toEqual([ + `export { a, b, Base, c, e, Helpers, type ModuleOptions, default } from './module.mjs'`, + `export * as ns from './ns.mjs'`, + `export type * from './types.mjs'`, + ]) + await rm(dir, { recursive: true, force: true }) + }) +}) + describe('writeSourceTypes', () => { it('should re-export the module entry and add its type augmentations', async () => { const cwd = await mkdtemp(join(tmpdir(), 'module-builder-source-types-')) @@ -1239,6 +1263,26 @@ describe('build plan', () => { ].join('\n') expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c', './d']) expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c', './d']) + expect(rewriteSpecifiers(`const load = () => import/* lazy */('./d')`, specifier => `${specifier}.js`)).toBe(`const load = () => import/* lazy */('./d.js')`) + }) + + it('should find imports with comments inside or before them, and imports of string names', () => { + const code = [ + `import {\n a, // the a's value\n} from './a'`, + `/* b */import b from './b'`, + `import { 'c-c' as c } from './c'`, + `import type from './d'`, + ].join('\n') + expect(moduleSpecifiers(code).map(({ specifier }) => specifier)).toEqual(['./a', './b', './c', './d']) + expect([...valueSpecifiers(code)]).toEqual(['./a', './b', './c', './d']) + }) + + it('should ignore import statements inside strings', () => { + const template = 'const template = `\nimport x from \'./in-string\'\n`\n' + expect(moduleSpecifiers(`@decorate\nclass A {}\n${template}`)).toEqual([]) + const sfc = `\n\n\n` + expect(moduleSpecifiers(sfc, 'Component.vue').map(({ specifier }) => specifier)).toEqual(['./a']) + expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./a'`, `'./a.js'`)) }) it('should treat a dot-prefixed name as a path inside the directory', () => { diff --git a/test/utils.ts b/test/utils.ts index 80ba5c9e..bec2aeaf 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -5,12 +5,19 @@ import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath, pathToFileURL } from 'node:url' import { dirname, join } from 'pathe' import { exec } from 'tinyexec' +import ts from 'typescript' import { onTestFailed } from 'vitest' import { publishedPackage } from '../src/build/package.ts' import type { PackageJson } from '../src/utils.ts' export const repoRoot = fileURLToPath(new URL('..', import.meta.url)) + +/** The static `import` declarations of `code`. */ +export function staticImports(code: string): Array<{ specifier: string, code: string }> { + const source = ts.createSourceFile('module.ts', code, ts.ScriptTarget.Latest) + return source.statements.filter(ts.isImportDeclaration).map(statement => ({ specifier: (statement.moduleSpecifier as ts.StringLiteral).text, code: statement.getText(source) })) +} export const exampleDir = join(repoRoot, 'example') export const tsdownBin = join(repoRoot, 'node_modules/tsdown/dist/run.mjs') export const cliBin = join(repoRoot, 'src/cli.ts') From 3ef1dcbde3555f7aa730ebd0dec894c16165f908 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 14:52:26 +0000 Subject: [PATCH 05/12] fix: match script end tags with whitespace or attributes in single-file components --- src/transpile/specifiers.ts | 2 +- test/unit.spec.ts | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts index d772595c..a5fa5698 100644 --- a/src/transpile/specifiers.ts +++ b/src/transpile/specifiers.ts @@ -5,7 +5,7 @@ import { RELATIVE_RE } from '../utils.ts' const JSX_RE = /\.[jt]sx$/ const DYNAMIC_IMPORT_RE = /\bimport\s*(?:\(|\/[*/])/ -const VUE_SCRIPT_RE = /(]*>)([\s\S]*?)<\/script\s*>/gi +const VUE_SCRIPT_RE = /(]*>)([\s\S]*?)<\/script\b[^>]*>/gi const VUE_LANG_RE = /\blang\s*=\s*["']?(\w+)/ /** The extension `file` is emitted with: `.jsx` for a JSX source when JSX is preserved, `extension` otherwise. */ diff --git a/test/unit.spec.ts b/test/unit.spec.ts index e6f396a7..aad6f5c2 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -1285,6 +1285,11 @@ describe('build plan', () => { expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./a'`, `'./a.js'`)) }) + it('should find the imports of a script block whose end tag has whitespace or attributes', () => { + const sfc = `\n` + expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./x'`, `'./x.js'`)) + }) + it('should treat a dot-prefixed name as a path inside the directory', () => { expect(relativeSpecifier('/mod/src/module.ts', '/mod/src/.generated/types.ts')).toBe('./.generated/types.ts') expect(relativeSpecifier('/mod/src/module.ts', '/mod/shared.ts')).toBe('../shared.ts') From d8e0727243730663642ee2bd92649babfac00024 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:09:00 +0000 Subject: [PATCH 07/12] fix: escape quotes and backslashes in rewritten specifiers --- src/transpile/specifiers.ts | 2 +- test/unit.spec.ts | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/transpile/specifiers.ts b/src/transpile/specifiers.ts index 540668e8..5426ba0f 100644 --- a/src/transpile/specifiers.ts +++ b/src/transpile/specifiers.ts @@ -97,7 +97,7 @@ export function rewriteSpecifiers(code: string, replace: (specifier: string) => if (replacement === undefined || replacement === specifier) { continue } - result += code.slice(cursor, start) + code[start] + replacement + code[end - 1] + result += code.slice(cursor, start) + code[start] + replacement.replace(/[\\'"`]|\$\{/g, match => `\\${match}`) + code[end - 1] cursor = end } return result + code.slice(cursor) diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 66af9264..938cee4e 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -1290,6 +1290,11 @@ describe('build plan', () => { expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./a'`, `'./a.js'`)) }) + it('should escape a rewritten specifier for its quotes', () => { + const code = `import './it\\'s'\nimport "./say \\"hi\\""\nconst lazy = import(\`./back\\\`tick\`)\n` + expect(rewriteSpecifiers(code, specifier => `${specifier}.js`)).toBe(`import './it\\'s.js'\nimport "./say \\"hi\\".js"\nconst lazy = import(\`./back\\\`tick.js\`)\n`) + }) + it('should find the imports of a script block with `>` in a quoted attribute', () => { const sfc = `\n` expect(rewriteSpecifiers(sfc, specifier => `${specifier}.js`, 'Component.vue')).toBe(sfc.replace(`'./x'`, `'./x.js'`)) From 17873476d1eebd55f430fb031042ee709c6f9a24 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:09:32 +0000 Subject: [PATCH 08/12] fix: type the dependency fields of `BuildContext.pkg` --- src/utils.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/utils.ts b/src/utils.ts index 2230da80..39649188 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -10,10 +10,14 @@ export const logger = { error: (message: string): void => log.error(message, { spacing: 0, output: process.stderr }), } -/** The fields of `package.json` that the builder reads. */ +/** A `package.json`, typed for the fields that the builder reads and the dependency fields. */ export interface PackageJson { name?: string version?: string + dependencies?: Record + devDependencies?: Record + peerDependencies?: Record + optionalDependencies?: Record main?: string module?: string types?: string From 79f6f5a0325dbe20f9773d5088018e538e71c61b Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:10:03 +0000 Subject: [PATCH 09/12] fix: read a `package.json` that starts with a byte order mark --- src/build/loader.ts | 2 +- src/utils.ts | 2 +- test/unit.spec.ts | 8 +++++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/build/loader.ts b/src/build/loader.ts index e6a8d738..ed018db7 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -246,7 +246,7 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP /** The file that `specifier` maps to through the `imports` of the closest `package.json`, with the conditions of `import`. */ function resolvePackageImport(specifier: string, parentDir: string) { const scope = findUp(parentDir, dir => existsSync(join(dir, 'package.json')) ? dir : undefined) - const { imports } = scope ? JSON.parse(readFileSync(join(scope, 'package.json'), 'utf8')) as PackageJson : {} + const { imports } = scope ? JSON.parse(readFileSync(join(scope, 'package.json'), 'utf8').replace(/^\uFEFF/, '')) as PackageJson : {} const key = isPlainObject(imports) ? importsKeyFor(Object.keys(imports), specifier) : undefined if (!scope || !key) { return diff --git a/src/utils.ts b/src/utils.ts index 39649188..551bb2c6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -100,7 +100,7 @@ export function relativeSpecifier(from: string, to: string): string { /** The `package.json` in `dir`. */ export async function readPackageJson(dir: string): Promise { - return JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as PackageJson + return JSON.parse((await readFile(join(dir, 'package.json'), 'utf8')).replace(/^\uFEFF/, '')) as PackageJson } /** diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 938cee4e..2c0db365 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -14,7 +14,7 @@ import type { BuildPlan } from '../src/build/build.ts' import { resolveModuleOptions, resolveOutDir } from '../src/build/options.ts' import { resolveCwdArg } from '../src/commands/_shared.ts' import { moduleSpecifiers, rewriteSpecifiers, valueSpecifiers } from '../src/transpile/specifiers.ts' -import { logger, relativeSpecifier } from '../src/utils.ts' +import { logger, readPackageJson, relativeSpecifier } from '../src/utils.ts' import { setupBuilder } from '../src/tsdown/setup.ts' import { defaultReport, reportsSummary, sizeBreakdown } from '../src/tsdown/report.ts' import { unchangedOutputs } from '../src/tsdown/unchanged.ts' @@ -1305,6 +1305,12 @@ describe('build plan', () => { expect(relativeSpecifier('/mod/src/module.ts', '/mod/shared.ts')).toBe('../shared.ts') }) + it('should read a `package.json` that starts with a byte order mark', async () => { + const cwd = await tempDir() + await writeFile(join(cwd, 'package.json'), `\uFEFF${JSON.stringify({ name: 'bom' })}`) + expect(await readPackageJson(cwd)).toEqual({ name: 'bom' }) + }) + it('should not follow declaration files when deciding which JSX to compile', async () => { const cwd = await tempDir() await mkdir(join(cwd, 'src/runtime/server'), { recursive: true }) From e0c379b3a220e23dddfbb1ff8b38127763e7f4e3 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:10:46 +0000 Subject: [PATCH 10/12] fix: treat an installed package as a package before matching tsconfig `paths` --- src/build/loader.ts | 7 ++++++- src/transpile/tsconfig.ts | 2 +- test/unit.spec.ts | 17 +++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/build/loader.ts b/src/build/loader.ts index ed018db7..42719e8a 100644 --- a/src/build/loader.ts +++ b/src/build/loader.ts @@ -6,7 +6,8 @@ import { createPathsMatcher, getTsconfig } from 'get-tsconfig' import type ts from 'typescript' import type { Transform } from '../transpile/transpile-dir.ts' -import { findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' +import { packageName } from '../transpile/tsconfig.ts' +import { findPackageDir, findUp, isFile, isInside, isPlainObject, NODE_MODULES_RE, probe, relativeSpecifier, resolveFrom, SCRIPT_RE, TYPESCRIPT_RE } from '../utils.ts' import type { PackageJson } from '../utils.ts' import { guide } from './guide.ts' import { importsKeyFor } from './package.ts' @@ -235,6 +236,10 @@ function resolveSource(specifier: string, parentDir: string, cwd: string, matchP if (resolved) { return specifier.startsWith('#') && isInside(cwd, resolved) && !NODE_MODULES_RE.test(resolved) ? { file: resolved, via: 'imports' } : undefined } + const name = packageName(specifier) + if (name && findPackageDir(name, parentDir)) { + return + } for (const candidate of matchPath?.(specifier) || []) { const file = probe(candidate) if (file) { diff --git a/src/transpile/tsconfig.ts b/src/transpile/tsconfig.ts index 29c91dd1..3bcd91d3 100644 --- a/src/transpile/tsconfig.ts +++ b/src/transpile/tsconfig.ts @@ -56,7 +56,7 @@ function isForeignBuildFile(file: string, dir: string) { } /** The package a bare specifier names, or `undefined` for an alias or a specifier with a protocol. */ -function packageName(specifier: string) { +export function packageName(specifier: string): string | undefined { return specifier.startsWith('#') || /^[~@]\//.test(specifier) || specifier.includes(':') ? undefined : specifier.match(PACKAGE_NAME_RE)?.[0] } diff --git a/test/unit.spec.ts b/test/unit.spec.ts index 2c0db365..f33a3bee 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -359,6 +359,23 @@ describe('findModuleCodeIssues', () => { } }) + it('should not report an installed package with only an `import` condition as a tsconfig `paths` alias', async () => { + const dir = await mkdtemp(join(tmpdir(), 'module-builder-import-only-')) + try { + await mkdir(join(dir, 'src')) + await mkdir(join(dir, 'node_modules/esm-only'), { recursive: true }) + await writeFile(join(dir, 'tsconfig.json'), JSON.stringify({ compilerOptions: { paths: { 'esm-only': ['./src/esm-only.ts'] } } })) + await writeFile(join(dir, 'node_modules/esm-only/package.json'), JSON.stringify({ name: 'esm-only', type: 'module', exports: { '.': { import: './index.js' } } })) + await writeFile(join(dir, 'node_modules/esm-only/index.js'), `export const value = 1\n`) + await writeFile(join(dir, 'src/esm-only.ts'), `export const value = 1\n`) + await writeFile(join(dir, 'src/module.ts'), `import { value } from 'esm-only'\nexport default value\n`) + expect(list(findModuleCodeIssues(dir, ['./src/module.ts'], []))).toEqual([]) + } + finally { + await rm(dir, { recursive: true, force: true }) + } + }) + it('should follow the `imports` of `package.json` into the module\'s sources', async () => { const dir = await mkdtemp(join(tmpdir(), 'module-builder-imports-')) try { From d315685b653eb570a0c4b084fc91dc421675c2f8 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:12:15 +0000 Subject: [PATCH 11/12] fix: re-export every named export in `types.d.mts` from `module.mjs` --- src/build/types.ts | 21 +++++++-------------- test/unit.spec.ts | 5 +++-- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/build/types.ts b/src/build/types.ts index ede391bb..aa7063d3 100644 --- a/src/build/types.ts +++ b/src/build/types.ts @@ -3,7 +3,7 @@ import { dirname, relative, resolve } from 'pathe' import type ts from 'typescript' import { parseModule } from '../transpile/specifiers.ts' -import { getOrCreate, probe, writeIfChanged } from '../utils.ts' +import { probe, writeIfChanged } from '../utils.ts' interface ExportedName { name: string @@ -91,6 +91,7 @@ export async function writeTypes(distDir: string, source?: { exports: Set `\nexport { ${names.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from '${specifier}'`).join('\n')} +${namedReExports.length ? `\nexport { ${namedReExports.map(n => (n === 'default' || !typeOnlyExports.has(n) ? '' : 'type ') + n).join(', ')} } from './module.mjs'` : ''} ${moduleReExports.filter(e => e.star).map(e => `\nexport ${e.star!.typeOnly ? 'type ' : ''}*${e.names[0] ? ` as ${e.names[0].name}` : ''} from '${e.specifier}'`).join('\n')} `.trim().replace(/[\n\r]{3,}/g, '\n\n') + '\n' @@ -183,16 +184,8 @@ function bindingNames(ts: typeof import('typescript'), name: ts.BindingName): st return name.elements.flatMap(element => ts.isBindingElement(element) ? bindingNames(ts, element.name) : []) } -function groupNamedReExports(exports: ModuleExport[]) { - const groups = new Map>() - for (const e of exports) { - if (!e.star) { - const names = getOrCreate(groups, e.specifier || './module.mjs', () => new Set()) - e.names.forEach(({ name }) => names.add(name)) - } - } - return new Map([...groups].map(([specifier, names]) => [ - specifier, - [...names].sort((a, b) => a === 'default' ? 1 : b === 'default' ? -1 : a.localeCompare(b)), - ])) +/** The names that `exports` declare or re-export by name, sorted with `default` last. */ +function namedExports(exports: ModuleExport[]) { + const names = new Set(exports.flatMap(e => e.star ? [] : e.names.map(({ name }) => name))) + return [...names].sort((a, b) => a === 'default' ? 1 : b === 'default' ? -1 : a.localeCompare(b)) } diff --git a/test/unit.spec.ts b/test/unit.spec.ts index f33a3bee..4c39fa65 100644 --- a/test/unit.spec.ts +++ b/test/unit.spec.ts @@ -621,13 +621,14 @@ describe('writeTypes', () => { 'export declare const { c, d: [e] }: { c: 1, d: [2] }', `export * as ns from './ns.mjs'`, `export type * from './types.mjs'`, - 'export interface ModuleOptions {}', + `export type { Options as ModuleOptions } from './options.mjs'`, + `export { t as shared } from './chunk.mjs'`, 'declare const _default: unknown', 'export { _default as default }', ].join('\n')) await writeTypes(dir) expect((await readFile(join(dir, 'types.d.mts'), 'utf-8')).split('\n').filter(line => line.startsWith('export'))).toEqual([ - `export { a, b, Base, c, e, Helpers, type ModuleOptions, default } from './module.mjs'`, + `export { a, b, Base, c, e, Helpers, type ModuleOptions, shared, default } from './module.mjs'`, `export * as ns from './ns.mjs'`, `export type * from './types.mjs'`, ]) From b5922ca22ec194db63c8e6e61aea3cd59ad26903 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Tue, 17 Nov 2026 15:14:33 +0000 Subject: [PATCH 12/12] fix: accept `=true` and `=false` on boolean options --- src/cli.ts | 6 +++++- test/cli.spec.ts | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 333994f0..36d5532c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -61,7 +61,11 @@ function parseCommandArgs(command: CommandDef, argv: string[]) { options[kebabCase(name)] ??= { type: arg.type } } } - const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, allowNegative: true }) as { values: Record, positionals: string[] } + const normalised = argv.map((arg) => { + const [, name, value] = arg.match(/^--([^=]+)=(true|false)$/) ?? [] + return name && options[name]?.type === 'boolean' ? `--${value === 'false' ? 'no-' : ''}${name}` : arg + }) + const { values, positionals } = parseArgs({ args: normalised, options, allowPositionals: true, allowNegative: true }) as { values: Record, positionals: string[] } const args: Record = { help: values.help, stub: values.stub } for (const [name, arg] of Object.entries(command.args)) { args[name] = arg.type === 'positional' ? positionals.shift() ?? arg.default : values[name] ?? values[kebabCase(name)] ?? arg.default diff --git a/test/cli.spec.ts b/test/cli.spec.ts index 811dc697..29bcfe1f 100644 --- a/test/cli.spec.ts +++ b/test/cli.spec.ts @@ -603,7 +603,7 @@ export type { Kit } from './kit' step('parent', cli(['build', dirs.parent])), inOrder(['routes:prepare', () => cli(['prepare', dirs.routes!])], ['routes:playground', () => nuxt(['prepare', join(dirs.routes!, 'playground')])], ['routes', () => cli(['build', dirs.routes!])]), ...['object', 'array', 'function'].map(shape => step(`${shape}:prepare`, cli(['prepare', dirs[shape]!])).then(() => step(shape, cli(['build', dirs[shape]!])))), - step('flags', cli(['build', '--outDir', 'custom', '--no-sourcemap', dirs.flags])), + step('flags', cli(['build', '--outDir', 'custom', '--sourcemap=false', dirs.flags])), step('builderHooks', cli(['build', dirs.builderHooks!])), step('builderHooks:prepare', cli(['prepare', dirs.builderHooks!])), step('configCwd', cli(['prepare', dirs.configCwd!]))