-
-
Notifications
You must be signed in to change notification settings - Fork 679
Expand file tree
/
Copy pathvalidate-jsdoc-codeblocks.js
More file actions
420 lines (348 loc) · 12.9 KB
/
validate-jsdoc-codeblocks.js
File metadata and controls
420 lines (348 loc) · 12.9 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import path from 'node:path';
import ts from 'typescript';
import {createFSBackedSystem, createVirtualTypeScriptEnvironment} from '@typescript/vfs';
const CODEBLOCK_REGEX = /(?<openingFence>```(?:ts|typescript)?\n)(?<code>[\s\S]*?)```/gv;
const FILENAME = 'example-codeblock.ts';
const TWOSLASH_COMMENT = '//=>';
const compilerOptions = {
lib: ['lib.es2023.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.Node20,
moduleResolution: ts.ModuleResolutionKind.Node16,
strict: true,
noImplicitReturns: true,
noImplicitOverride: true,
noUnusedLocals: false, // This is intentionally disabled
noUnusedParameters: true,
noFallthroughCasesInSwitch: true,
noUncheckedIndexedAccess: true,
noPropertyAccessFromIndexSignature: true,
noUncheckedSideEffectImports: true,
useDefineForClassFields: true,
exactOptionalPropertyTypes: true,
};
const virtualFsMap = new Map([[FILENAME, '// Can\'t be empty']]);
const rootDir = path.join(import.meta.dirname, '..');
const system = createFSBackedSystem(virtualFsMap, rootDir, ts);
const defaultEnv = createVirtualTypeScriptEnvironment(system, [FILENAME], ts, compilerOptions);
function parseCompilerOptions(code) {
const options = {};
const lines = code.split('\n');
for (const line of lines) {
if (!line.trim()) {
// Skip empty lines
continue;
}
const match = line.match(/^\s*\/\/ @(\w+): (.*)$/v);
if (!match) {
// Stop parsing at the first non-matching line
return options;
}
const [, key, value] = match;
const trimmedValue = value.trim();
try {
options[key] = JSON.parse(trimmedValue);
} catch {
options[key] = trimmedValue;
}
}
return options;
}
function getJSDocNode(sourceCode, node) {
let previousToken = sourceCode.getTokenBefore(node, {includeComments: true});
// Skip over any line comments immediately before the node
while (previousToken && previousToken.type === 'Line') {
previousToken = sourceCode.getTokenBefore(previousToken, {includeComments: true});
}
if (previousToken && previousToken.type === 'Block' && previousToken.value.startsWith('*')) {
return previousToken;
}
return undefined;
}
export const validateJSDocCodeblocksRule = /** @type {const} */ ({
meta: {
type: 'suggestion',
docs: {
description: 'Ensures JSDoc example codeblocks don\'t have errors',
},
fixable: 'code',
messages: {
invalidCodeblock: '{{errorMessage}}',
incorrectTwoslashType: 'Expected twoslash comment to be: {{expectedComment}}, but found: {{actualComment}}',
incorrectTwoslashFormat: 'Expected twoslash comment to be: {{expectedComment}}, but found: {{actualComment}}',
},
schema: [{
type: 'object',
properties: {
verbosityLevels: {
type: 'array',
uniqueItems: true,
items: {
minimum: 0,
type: 'number',
},
},
},
}],
/** @type {unknown[]} */
defaultOptions: [{
verbosityLevels: [],
}],
},
create(context) {
const filename = context.filename.replaceAll('\\', '/');
// Skip internal files
if (filename.includes('/internal/')) {
return {};
}
try {
defaultEnv.updateFile(context.filename, context.sourceCode.getText());
} catch {
// Ignore
}
return {
TSTypeAliasDeclaration(node) {
const {parent} = node;
// Skip if type is not exported or starts with an underscore (private/internal)
if (parent.type !== 'ExportNamedDeclaration' || node.id.name.startsWith('_')) {
return;
}
const previousNodes = [];
const jsdocForExport = getJSDocNode(context.sourceCode, parent);
if (jsdocForExport) {
previousNodes.push(jsdocForExport);
}
// Handle JSDoc blocks for options
if (node.id.name.endsWith('Options') && node.typeAnnotation.type === 'TSTypeLiteral') {
for (const member of node.typeAnnotation.members) {
const jsdocForMember = getJSDocNode(context.sourceCode, member);
if (jsdocForMember) {
previousNodes.push(jsdocForMember);
}
}
}
for (const previousNode of previousNodes) {
const comment = previousNode.value;
for (const match of comment.matchAll(CODEBLOCK_REGEX)) {
const {code, openingFence} = match.groups ?? {};
// Skip empty code blocks
if (!code || !openingFence) {
continue;
}
const matchOffset = match.index + openingFence.length + 2; // Add `2` because `comment` doesn't include the starting `/*`
const codeStartIndex = previousNode.range[0] + matchOffset;
const overrides = parseCompilerOptions(code);
let env = defaultEnv;
if (Object.keys(overrides).length > 0) {
const {options, errors} = ts.convertCompilerOptionsFromJson(overrides, rootDir);
if (errors.length === 0) {
// Create a new environment with overridden options
env = createVirtualTypeScriptEnvironment(system, [FILENAME], ts, {...compilerOptions, ...options});
}
}
env.updateFile(FILENAME, code);
const syntacticDiagnostics = env.languageService.getSyntacticDiagnostics(FILENAME);
const semanticDiagnostics = env.languageService.getSemanticDiagnostics(FILENAME);
const diagnostics = syntacticDiagnostics.length > 0 ? syntacticDiagnostics : semanticDiagnostics; // Show semantic errors only if there are no syntactic errors
for (const diagnostic of diagnostics) {
// If diagnostic location is not available, report on the entire code block
const diagnosticStart = codeStartIndex + (diagnostic.start ?? 0);
const diagnosticEnd = diagnosticStart + (diagnostic.length ?? code.length);
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(diagnosticStart),
end: context.sourceCode.getLocFromIndex(diagnosticEnd),
},
messageId: 'invalidCodeblock',
data: {
errorMessage: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
},
});
}
if (diagnostics.length === 0) {
validateTwoslashTypes(context, env, code, codeStartIndex);
}
}
}
},
};
},
});
function getLeftmostQuickInfo(env, line, lineOffset, verbosityLevel) {
for (let i = 0; i < line.length; i++) {
const quickInfo = env.languageService.getQuickInfoAtPosition(FILENAME, lineOffset + i, undefined, verbosityLevel);
if (quickInfo?.displayParts) {
return quickInfo;
}
}
}
function extractTypeFromQuickInfo(quickInfo) {
const {displayParts} = quickInfo;
// For interfaces and enums, return everything after the keyword
const keywordIndex = displayParts.findIndex(
part => part.kind === 'keyword' && ['interface', 'enum'].includes(part.text),
);
if (keywordIndex !== -1) {
return displayParts.slice(keywordIndex + 1).map(part => part.text).join('').trim();
}
let depth = 0;
const separatorIndex = displayParts.findIndex(part => {
if (part.kind === 'punctuation') {
if (['(', '{', '<'].includes(part.text)) {
depth++;
} else if ([')', '}', '>'].includes(part.text)) {
depth--;
} else if (part.text === ':' && depth === 0) {
return true;
}
} else if (part.kind === 'operator' && part.text === '=' && depth === 0) {
return true;
}
return false;
});
// If `separatorIndex` is `-1` (not found), return the entire thing
return displayParts.slice(separatorIndex + 1).map(part => part.text).join('').trim();
}
function normalizeType(type, onlySortNumbers = false) {
const sourceFile = ts.createSourceFile(
'twoslash-type.ts',
`declare const test: ${type};`,
ts.ScriptTarget.Latest,
);
const typeNode = sourceFile.statements[0].declarationList.declarations[0].type;
const print = node => ts.createPrinter().printNode(ts.EmitHint.Unspecified, node, sourceFile);
const isNumeric = v => v.trim() !== '' && Number.isFinite(Number(v));
const visit = node => {
node = ts.visitEachChild(node, visit, undefined);
if (ts.isUnionTypeNode(node)) {
let types = node.types.map(t => [print(t), t]);
if (onlySortNumbers) {
// Sort only numeric members while keeping non-numeric members at their original positions
const sortedNumericTypes = types.filter(([a]) => isNumeric(a)).toSorted(([a], [b]) => Number(a) - Number(b));
let numericIndex = 0;
types = types.map(t => isNumeric(t[0]) ? sortedNumericTypes[numericIndex++][1] : t[1]);
} else {
types = types
.toSorted(([a], [b]) => a < b ? -1 : (a > b ? 1 : 0))
.map(t => t[1]);
}
return ts.factory.updateUnionTypeNode(
node,
ts.factory.createNodeArray(types),
);
}
// Prefer single-line formatting for tuple types
if (ts.isTupleTypeNode(node)) {
const updated = ts.factory.createTupleTypeNode(node.elements);
ts.setEmitFlags(updated, ts.EmitFlags.SingleLine);
return updated;
}
// Replace double-quoted string literals with single-quoted ones
if (ts.isStringLiteral(node)) {
const updated = ts.factory.createStringLiteral(node.text, true);
// Preserve non-ASCII characters like emojis.
ts.setEmitFlags(updated, ts.EmitFlags.NoAsciiEscaping);
return updated;
}
return node;
};
return print(visit(typeNode)).replaceAll(/^( +)/gmv, indentation => {
// Replace spaces used for indentation with tabs
const spacesPerTab = 4;
const tabCount = Math.floor(indentation.length / spacesPerTab);
const remainingSpaces = indentation.length % spacesPerTab;
return '\t'.repeat(tabCount) + ' '.repeat(remainingSpaces);
});
}
function getCommentForType(type) {
let comment = type;
if (type.length < 80) {
comment = type
.replaceAll(/\r?\n\s*/gv, ' ') // Collapse into single line
.replaceAll(/\{\s+/gv, '{') // Remove spaces after `{`
.replaceAll(/\s+\}/gv, '}') // Remove spaces before `}`
.replaceAll(/;(?=\})/gv, ''); // Remove semicolons before `}`
}
return `${TWOSLASH_COMMENT} ${comment.replaceAll('\n', '\n// ')}`;
}
function reportTypeMismatch({context, messageId, start, end, data, fix}) {
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(start),
end: context.sourceCode.getLocFromIndex(end),
},
messageId,
data,
fix(fixer) {
return fixer.replaceTextRange([start, end], fix);
},
});
}
function validateTwoslashTypes(context, env, code, codeStartIndex) {
const sourceFile = env.languageService.getProgram().getSourceFile(FILENAME);
const lines = code.split('\n');
const specifiedVerbosityLevels = context.options[0].verbosityLevels;
const verbosityLevels = [0, ...specifiedVerbosityLevels, Infinity]; // Keep `Infinity` last since suggestion logic relies on the order
for (const [index, line] of lines.entries()) {
const dedentedLine = line.trimStart();
if (!dedentedLine.startsWith(TWOSLASH_COMMENT)) {
continue;
}
const previousLineIndex = index - 1;
if (previousLineIndex < 0) {
continue;
}
let rawActualType = dedentedLine.slice(TWOSLASH_COMMENT.length);
let actualComment = dedentedLine;
let actualCommentEndLine = index;
for (let i = index + 1; i < lines.length; i++) {
const dedentedNextLine = lines[i].trimStart();
if (!dedentedNextLine.startsWith('//') || dedentedNextLine.startsWith(TWOSLASH_COMMENT)) {
break;
}
actualComment += '\n' + dedentedNextLine;
rawActualType += '\n' + dedentedNextLine.slice(2); // Remove the `//` from start
actualCommentEndLine = i;
}
const previousLine = lines[previousLineIndex];
const previousLineOffset = sourceFile.getPositionOfLineAndCharacter(previousLineIndex, 0);
const actualCommentIndex = line.indexOf(TWOSLASH_COMMENT);
const actualCommentStartOffset = sourceFile.getPositionOfLineAndCharacter(index, actualCommentIndex);
const actualCommentEndOffset = sourceFile.getPositionOfLineAndCharacter(actualCommentEndLine, lines[actualCommentEndLine].length);
const start = codeStartIndex + actualCommentStartOffset;
const end = codeStartIndex + actualCommentEndOffset;
const indent = line.slice(0, actualCommentIndex);
const quickInfos = verbosityLevels
.map(verbosity => getLeftmostQuickInfo(env, previousLine, previousLineOffset, verbosity))
.filter(qi => qi?.displayParts);
if (quickInfos.length > 0) {
const expectedTypes = quickInfos.map(qi => normalizeType(extractTypeFromQuickInfo(qi)));
const actualType = normalizeType(rawActualType);
if (expectedTypes.includes(actualType)) {
// If the types match, check for formatting errors and unordered numbers in unions
const expectedComment = getCommentForType(normalizeType(rawActualType, true));
if (actualComment !== expectedComment) {
reportTypeMismatch({
messageId: 'incorrectTwoslashFormat',
context,
start,
end,
data: {expectedComment, actualComment},
fix: expectedComment.replaceAll('\n', `\n${indent}`),
});
}
} else {
// For suggestion, use infinite verbosity, and it should be the last one
const expectedComment = getCommentForType(expectedTypes.at(-1));
reportTypeMismatch({
messageId: 'incorrectTwoslashType',
context,
start,
end,
data: {expectedComment, actualComment},
fix: expectedComment.replaceAll('\n', `\n${indent}`),
});
}
}
}
}