-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.ts
148 lines (119 loc) Β· 4.91 KB
/
build.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { basename, join } from 'path'
import { build, EmitOptions } from 'tsc-prog'
import * as ts from 'typescript'
import * as tsdoc from '@microsoft/tsdoc'
import { writeFileSync } from 'fs'
const basePath = process.cwd()
const folderName = basename(basePath)
const dtsEntryPoint = 'index.d.ts'
let bundle: EmitOptions.Bundle | undefined
if (folderName !== 'http' && folderName !== 'mongoose') {
bundle = {
entryPoint: dtsEntryPoint,
augmentations: false,
}
}
if (folderName === 'mongoose') {
bundle = {
entryPoint: dtsEntryPoint,
augmentations: false,
extras: [{ position: 'after-imports', declaration: 'import * as mongoose from "mongoose";' }],
}
}
build({
basePath,
configFilePath: 'tsconfig.json',
compilerOptions: {
rootDir: 'src',
outDir: 'dist',
declaration: true,
skipLibCheck: true,
stripInternal: true,
},
include: [`src/**/*`],
exclude: ['**/__tests__', '**/test.ts', '**/*.test.ts', '**/*.spec.ts', 'node_modules'],
clean: { outDir: true },
bundleDeclaration: bundle,
})
syncOverloadsDoc()
function syncOverloadsDoc() {
console.log('Syncing inherited docs for overloaded functions')
const tsdocConfig = new tsdoc.TSDocConfiguration()
tsdocConfig.setSupportForTags(tsdoc.StandardTags.allDefinitions, true)
const docParser = new tsdoc.TSDocParser(tsdocConfig)
const dtsPath = join(basePath, 'dist', dtsEntryPoint)
const dtsFile = ts.createProgram({ options: {}, rootNames: [dtsPath] }).getSourceFile(dtsPath)!
const dtsText = dtsFile.getFullText()
const docMap = new Map<string, string>()
ts.visitNode(dtsFile, visitInheritedDoc)
console.log('Rewriting typings file')
// todo: use emitter with transformer instead of naive replace
// https://stackoverflow.com/questions/43829884
let dtsTextFinal = dtsText
docMap.forEach((refDoc, inheritDoc) => {
const inheritDocRe = new RegExp(escapeRegExp(inheritDoc), 'g')
dtsTextFinal = dtsTextFinal.replace(inheritDocRe, refDoc)
})
// Rewrite ts-ignore jsdoc comment into basic comment.
const tsIgnoreRe = /\/\*\* ?@ts-ignore(.*) ?\*\//g
dtsTextFinal = dtsTextFinal.replace(tsIgnoreRe, '// @ts-ignore$1')
// Hack to fix generic type with private property $typeof.
// todo: make it more dynamic
const privateTypeofRe = /private \$typeof\?;/g
dtsTextFinal = dtsTextFinal.replace(privateTypeofRe, 'private $typeof?: C;')
writeFileSync(dtsPath, dtsTextFinal, 'utf8')
function visitInheritedDoc(node: ts.Node): ts.VisitResult<ts.Node> {
if (ts.isFunctionDeclaration(node)) {
const [commentRange] = ts.getJSDocCommentRanges(node, dtsText) || []
if (!commentRange) return
const textRange = tsdoc.TextRange.fromStringRange(dtsText, commentRange.pos, commentRange.end)
const docCommentText = textRange.toString()
const { docComment, log } = docParser.parseRange(textRange)
log.messages.forEach((m) => console.error(m.unformattedText))
if (docComment.inheritDocTag && docComment.inheritDocTag.declarationReference) {
const { memberReferences } = docComment.inheritDocTag.declarationReference
const { memberIdentifier, selector: selectorWrapper } = memberReferences[0]
if (!memberIdentifier || !selectorWrapper) {
console.error('Missing reference or selector:', docCommentText)
return
}
const { identifier } = memberIdentifier
const { selector, selectorKind } = selectorWrapper
if (selectorKind !== 'index') {
console.error('Only index selector is supported:', docCommentText)
return
}
docMap.set(docCommentText, getRefDocComment(identifier, selector))
}
}
return node.forEachChild(visitInheritedDoc)
}
function getRefDocComment(identifier: string, selector: string): string {
const declarations: ts.FunctionDeclaration[] = []
ts.visitNode(dtsFile, getDeclarations)
if (!declarations.length || declarations.length === 1) throw Error(`${identifier} not overloaded`)
const ref = declarations[Number(selector) - 1]
if (!ref) throw Error(`Cannot find ${identifier}: wrong selector (${selector})`)
const [commentRange] = ts.getJSDocCommentRanges(ref, dtsText) || []
if (!commentRange) return ''
const textRange = tsdoc.TextRange.fromStringRange(dtsText, commentRange.pos, commentRange.end)
return textRange.toString()
function getDeclarations(node: ts.Node): ts.VisitResult<ts.Node> {
if (ts.isFunctionDeclaration(node) && node.name && node.name.text === identifier) {
declarations.push(node)
}
return node.forEachChild(getDeclarations)
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
function escapeRegExp(value: string) {
return value.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
}
}
declare module 'typescript' {
/**
* Retrieves the JSDoc-style comments associated with a specific AST node.
* @see https://github.com/microsoft/TypeScript/blob/v3.5.3/src/compiler/utilities.ts#L997-L1010
*/
function getJSDocCommentRanges(node: Node, text: string): CommentRange[] | undefined
}