Skip to content

Commit ccfeccb

Browse files
gitKrystansxzzbot
andauthored
fix: keep an entry's file-level doc comment (#311)
Co-authored-by: Kevin Bot <[email protected]>
1 parent 5a3f7f9 commit ccfeccb

6 files changed

Lines changed: 119 additions & 4 deletions

File tree

‎src/fake-js/index.ts‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ export function createFakeJsPlugin({
7272
}: Pick<OptionsResolved, 'sourcemap' | 'cjsDefault' | 'sideEffects'>): Plugin {
7373
let declarationIdx = 0
7474
const declarationMap = new Map<number /* declaration id */, DeclarationInfo>()
75+
const moduleDeclarationsMap = new Map<
76+
string /* filename */,
77+
number[] /* declaration ids */
78+
>()
7579
const commentsMap = new Map<string /* filename */, t.Comment[]>()
80+
const fileCommentsMap = new Map<string /* filename */, t.Comment[]>()
7681
const moduleExportsMap = new Map<string /* filename */, ModuleExports>()
7782
const warnedCjsDtsInputs = new Set<string>()
7883

@@ -164,6 +169,11 @@ export function createFakeJsPlugin({
164169
)
165170
}
166171

172+
// A watch rebuild transforms changed modules again, so drop what the
173+
// previous transform stored. Unchanged modules may keep their cached
174+
// output with incremental builds, so their state must stay.
175+
clearModuleState(id)
176+
167177
const { program } = file
168178
moduleExportsMap.set(id, await collectModuleExports(this, program.body, id))
169179
const identifierMap: Record<string, number> = Object.create(null)
@@ -189,7 +199,16 @@ export function createFakeJsPlugin({
189199

190200
for (const [i, stmt] of program.body.entries()) {
191201
const setStmt = (stmt: t.ProgramStatement) => (program.body[i] = stmt)
192-
if (rewriteImportExport(stmt, setStmt, appendStmts)) continue
202+
if (rewriteImportExport(stmt, setStmt, appendStmts)) {
203+
// The file's doc comment, e.g. `@module`, is attached to its first
204+
// statement. An import or export keeps no comments, so save it for
205+
// `renderChunk` to restore.
206+
if (i === 0) {
207+
const docComments = stmt.comments?.filter(isDocComment)
208+
if (docComments?.length) fileCommentsMap.set(id, docComments)
209+
}
210+
continue
211+
}
193212

194213
const sideEffect =
195214
stmt.type === 'TSModuleDeclaration' && stmt.kind !== 'namespace'
@@ -280,7 +299,7 @@ export function createFakeJsPlugin({
280299
decl.comments = stmt.comments
281300
}
282301

283-
const declarationId = registerDeclaration({
302+
const declarationId = registerDeclaration(id, {
284303
decl,
285304
deps,
286305
bindings,
@@ -567,6 +586,14 @@ export function createFakeJsPlugin({
567586
program.body.push(b.ExportNamedDeclaration({}))
568587
}
569588

589+
// recover the entry's doc comment, but not those of the modules it inlines
590+
const fileComments =
591+
chunk.facadeModuleId && fileCommentsMap.get(chunk.facadeModuleId)
592+
if (fileComments) {
593+
program.body[0].comments ||= []
594+
program.body[0].comments.unshift(...fileComments)
595+
}
596+
570597
// recover comments
571598
const comments = new Set<t.Comment>()
572599
const commentsValue = new Set<string>() // deduplicate
@@ -581,7 +608,6 @@ export function createFakeJsPlugin({
581608
commentsValue.add(id)
582609
comments.add(c)
583610
})
584-
commentsMap.delete(id)
585611
}
586612
}
587613
if (comments.size) {
@@ -606,12 +632,27 @@ export function createFakeJsPlugin({
606632
}
607633
}
608634

609-
function registerDeclaration(info: DeclarationInfo) {
635+
function registerDeclaration(id: string, info: DeclarationInfo) {
610636
const declarationId = declarationIdx++
611637
declarationMap.set(declarationId, info)
638+
639+
let ids = moduleDeclarationsMap.get(id)
640+
if (!ids) moduleDeclarationsMap.set(id, (ids = []))
641+
ids.push(declarationId)
642+
612643
return declarationId
613644
}
614645

646+
function clearModuleState(id: string) {
647+
for (const declarationId of moduleDeclarationsMap.get(id) || []) {
648+
declarationMap.delete(declarationId)
649+
}
650+
moduleDeclarationsMap.delete(id)
651+
moduleExportsMap.delete(id)
652+
commentsMap.delete(id)
653+
fileCommentsMap.delete(id)
654+
}
655+
615656
function getDeclaration(declarationId: number) {
616657
return declarationMap.get(declarationId)!
617658
}
@@ -682,3 +723,11 @@ function removeDtsOnlyRuntimeChunks(bundle: OutputBundle): void {
682723
}
683724
}
684725
}
726+
727+
function isDocComment(comment: t.Comment): boolean {
728+
return (
729+
comment.position === 'before' &&
730+
comment.type === 'Block' &&
731+
comment.value.startsWith('*')
732+
)
733+
}

‎tests/__snapshots__/index.test.ts.snap‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,18 @@ import { n as input2, t as Input2 } from "./chunks/BBKVF6ft.js";
231231
export { Input2, input2 };"
232232
`;
233233
234+
exports[`file doc comment before an import 1`] = `
235+
"// index.d.ts
236+
/**
237+
* Docs for this entry point.
238+
*
239+
* @module
240+
*/
241+
type Raw = string;
242+
export declare function makeId(value: string): Raw;
243+
export {};"
244+
`;
245+
234246
exports[`import = syntax 1`] = `
235247
"// import-equals.d.ts
236248
import * as zodModule from "external-zod";
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/**
2+
* Docs for an inlined module.
3+
*
4+
* @module
5+
*/
6+
7+
export type { Raw as Id } from './raw'
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/**
2+
* Docs for this entry point.
3+
*
4+
* @module
5+
*/
6+
7+
import type { Id } from './id'
8+
9+
export function makeId(value: string): Id {
10+
return value
11+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export type Raw = string

‎tests/index.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2+
import os from 'node:os'
13
import path from 'node:path'
24
import { fileURLToPath } from 'node:url'
35
import { normalizePath, rolldownBuild } from '@sxzz/test-utils'
@@ -847,3 +849,36 @@ describe('rolldown runtime chunk', () => {
847849
)
848850
})
849851
})
852+
853+
test('file doc comment before an import', async () => {
854+
const { snapshot } = await rolldownBuild(
855+
path.resolve(dirname, 'fixtures/file-doc-comment/index.ts'),
856+
[dts({ emitDtsOnly: true })],
857+
)
858+
expect(snapshot).toContain('Docs for this entry point.')
859+
// only the entry's own comment, not those of the modules it inlines
860+
expect(snapshot).not.toContain('Docs for an inlined module.')
861+
expect(snapshot).toMatchSnapshot()
862+
})
863+
864+
test('file doc comment removed before a rebuild', async () => {
865+
const dir = await mkdtemp(path.join(os.tmpdir(), 'dts-file-doc-comment-'))
866+
try {
867+
await cp(path.resolve(dirname, 'fixtures/file-doc-comment'), dir, {
868+
recursive: true,
869+
})
870+
const input = path.join(dir, 'index.ts')
871+
// reusing the plugins mimics a watch rebuild, which transforms again
872+
const plugins = [dts({ emitDtsOnly: true })]
873+
874+
const first = await rolldownBuild(input, plugins)
875+
expect(first.snapshot).toContain('Docs for this entry point.')
876+
877+
const code = await readFile(input, 'utf8')
878+
await writeFile(input, code.replace(/^\/\*\*[\s\S]*?\*\/\n/, ''))
879+
const second = await rolldownBuild(input, plugins)
880+
expect(second.snapshot).not.toContain('Docs for this entry point.')
881+
} finally {
882+
await rm(dir, { recursive: true, force: true })
883+
}
884+
})

0 commit comments

Comments
 (0)