embedoc 0.14.8 → 0.14.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +125 -1
  2. package/cli-contract.yaml +3 -3
  3. package/dist/cli.js +4 -5
  4. package/dist/cli.js.map +1 -1
  5. package/dist/core/dependency.d.ts.map +1 -1
  6. package/dist/core/dependency.js +2 -5
  7. package/dist/core/dependency.js.map +1 -1
  8. package/dist/core/generator.d.ts.map +1 -1
  9. package/dist/core/generator.js +32 -2
  10. package/dist/core/generator.js.map +1 -1
  11. package/dist/core/inline-datasource.d.ts +11 -2
  12. package/dist/core/inline-datasource.d.ts.map +1 -1
  13. package/dist/core/inline-datasource.js +11 -2
  14. package/dist/core/inline-datasource.js.map +1 -1
  15. package/dist/core/processor.d.ts +5 -0
  16. package/dist/core/processor.d.ts.map +1 -1
  17. package/dist/core/processor.js +11 -10
  18. package/dist/core/processor.js.map +1 -1
  19. package/dist/datasources/csv.d.ts.map +1 -1
  20. package/dist/datasources/csv.js +2 -11
  21. package/dist/datasources/csv.js.map +1 -1
  22. package/dist/datasources/filter.d.ts +12 -0
  23. package/dist/datasources/filter.d.ts.map +1 -0
  24. package/dist/datasources/filter.js +19 -0
  25. package/dist/datasources/filter.js.map +1 -0
  26. package/dist/datasources/glob.d.ts.map +1 -1
  27. package/dist/datasources/glob.js +2 -14
  28. package/dist/datasources/glob.js.map +1 -1
  29. package/dist/datasources/index.d.ts +1 -0
  30. package/dist/datasources/index.d.ts.map +1 -1
  31. package/dist/datasources/index.js +4 -0
  32. package/dist/datasources/index.js.map +1 -1
  33. package/dist/datasources/json.d.ts.map +1 -1
  34. package/dist/datasources/json.js +2 -14
  35. package/dist/datasources/json.js.map +1 -1
  36. package/dist/datasources/typescript.d.ts +40 -0
  37. package/dist/datasources/typescript.d.ts.map +1 -0
  38. package/dist/datasources/typescript.js +901 -0
  39. package/dist/datasources/typescript.js.map +1 -0
  40. package/dist/datasources/yaml.d.ts.map +1 -1
  41. package/dist/datasources/yaml.js +2 -14
  42. package/dist/datasources/yaml.js.map +1 -1
  43. package/dist/embed-api.d.ts +13 -1
  44. package/dist/embed-api.d.ts.map +1 -1
  45. package/dist/embed-api.js +4 -0
  46. package/dist/embed-api.js.map +1 -1
  47. package/dist/embedoc.bundle.mjs +123 -100
  48. package/dist/embedoc.bundle.mjs.map +4 -4
  49. package/dist/generated/contract.d.ts.map +1 -1
  50. package/dist/generated/contract.js +2 -2
  51. package/dist/generated/contract.js.map +1 -1
  52. package/dist/generated/program.d.ts.map +1 -1
  53. package/dist/generated/program.js +4 -2
  54. package/dist/generated/program.js.map +1 -1
  55. package/dist/helpers/api-markdown.d.ts +47 -0
  56. package/dist/helpers/api-markdown.d.ts.map +1 -0
  57. package/dist/helpers/api-markdown.js +381 -0
  58. package/dist/helpers/api-markdown.js.map +1 -0
  59. package/dist/index.d.ts +4 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +2 -1
  62. package/dist/index.js.map +1 -1
  63. package/dist/types/index.d.ts +164 -4
  64. package/dist/types/index.d.ts.map +1 -1
  65. package/docs/api/README.md +1080 -401
  66. package/docs/cli-reference.md +2 -2
  67. package/package.json +31 -17
@@ -0,0 +1,901 @@
1
+ /**
2
+ * TypeScript Datasource
3
+ * Public API of TypeScript entry points, read with the TypeScript compiler API.
4
+ * One record per exported symbol (see ApiSymbol).
5
+ */
6
+ import { dirname, relative, resolve, sep } from 'node:path';
7
+ import { filterRows } from './filter.js';
8
+ const SUPPORTED_TYPESCRIPT = '>=5.0.0 <7.0.0';
9
+ const KIND_INFO = {
10
+ namespace: { label: 'Namespace', dir: 'namespaces' },
11
+ enum: { label: 'Enumeration', dir: 'enumerations' },
12
+ class: { label: 'Class', dir: 'classes' },
13
+ interface: { label: 'Interface', dir: 'interfaces' },
14
+ type: { label: 'Type Alias', dir: 'type-aliases' },
15
+ variable: { label: 'Variable', dir: 'variables' },
16
+ function: { label: 'Function', dir: 'functions' },
17
+ reference: { label: 'Reference', dir: 'references' },
18
+ };
19
+ /** Tags that always hide a symbol or member. */
20
+ const HIDDEN_TAGS = new Set(['hidden', 'ignore']);
21
+ const EMPTY_DOC = {
22
+ summary: '',
23
+ tags: [],
24
+ parameters: new Map(),
25
+ typeParameters: new Map(),
26
+ returns: '',
27
+ };
28
+ /** Trim blank lines around a block and the indentation all its lines share. */
29
+ function trimBlock(lines) {
30
+ while (lines.length > 0 && lines[0].trim() === '')
31
+ lines.shift();
32
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '')
33
+ lines.pop();
34
+ return lines.join('\n');
35
+ }
36
+ /**
37
+ * Positions of block tags (`@name` at the start of the line or after
38
+ * whitespace) outside inline code spans.
39
+ */
40
+ function blockTagPositions(line) {
41
+ const positions = [];
42
+ let span = 0; // length of the backtick run that opened the current code span
43
+ for (let i = 0; i < line.length; i++) {
44
+ if (line[i] === '`') {
45
+ let run = 1;
46
+ while (line[i + run] === '`')
47
+ run++;
48
+ if (span === 0)
49
+ span = run;
50
+ else if (run === span)
51
+ span = 0;
52
+ i += run - 1;
53
+ continue;
54
+ }
55
+ if (span === 0 &&
56
+ line[i] === '@' &&
57
+ (i === 0 || /\s/.test(line[i - 1])) &&
58
+ /[A-Za-z]/.test(line[i + 1] ?? '')) {
59
+ positions.push(i);
60
+ }
61
+ }
62
+ return positions;
63
+ }
64
+ /**
65
+ * Parse a `/** ... *\/` comment. A block tag is `@name` at the start of a line
66
+ * or after whitespace, outside fenced code and inline code, so `@decorator`
67
+ * lines in an example are code, not tags (the compiler's own JSDoc parser
68
+ * takes them for tags). Indentation inside the comment is kept.
69
+ */
70
+ export function parseDocComment(raw) {
71
+ const body = raw.replace(/^\/\*\*/, '').replace(/\*\/$/, '');
72
+ const lines = body.split(/\r?\n/).map((line, i) => {
73
+ if (i === 0)
74
+ return line.trim();
75
+ return line.replace(/^\s*\*(?: |(?=\S)|$)/, '').replace(/\s+$/, '');
76
+ });
77
+ const blocks = [{ tag: null, lines: [] }];
78
+ let fence = null;
79
+ for (const line of lines) {
80
+ const fenceMatch = /^\s*(```+|~~~+)/.exec(line);
81
+ if (fenceMatch) {
82
+ const marker = fenceMatch[1];
83
+ if (fence === null)
84
+ fence = marker[0].repeat(marker.length);
85
+ else if (marker.startsWith(fence))
86
+ fence = null;
87
+ }
88
+ const positions = fence === null && !fenceMatch ? blockTagPositions(line) : [];
89
+ if (positions.length === 0) {
90
+ blocks[blocks.length - 1].lines.push(line);
91
+ continue;
92
+ }
93
+ const before = line.slice(0, positions[0]).replace(/\s+$/, '');
94
+ if (before !== '')
95
+ blocks[blocks.length - 1].lines.push(before);
96
+ positions.forEach((start, k) => {
97
+ const segment = line.slice(start, positions[k + 1] ?? line.length).replace(/\s+$/, '');
98
+ const m = /^@([A-Za-z][\w-]*)\s*([\s\S]*)$/.exec(segment);
99
+ blocks.push({ tag: m[1], lines: [m[2]] });
100
+ });
101
+ }
102
+ const doc = {
103
+ summary: trimBlock(blocks[0].lines),
104
+ tags: [],
105
+ parameters: new Map(),
106
+ typeParameters: new Map(),
107
+ returns: '',
108
+ };
109
+ for (const block of blocks.slice(1)) {
110
+ const tag = block.tag;
111
+ const text = trimBlock(block.lines);
112
+ if (tag === 'param' || tag === 'template' || tag === 'typeParam') {
113
+ // `@param {type} [name=default] - description`
114
+ const m = /^(?:\{[^}]*\}\s*)?\[?([\w$.]+)(?:=[^\]]*)?\]?\s*(?:-\s*)?([\s\S]*)$/.exec(text);
115
+ if (m) {
116
+ const map = tag === 'param' ? doc.parameters : doc.typeParameters;
117
+ // A dotted name documents a property of a parameter, not the parameter.
118
+ if (!m[1].includes('.') && !map.has(m[1]))
119
+ map.set(m[1], m[2].trim());
120
+ }
121
+ }
122
+ else if (tag === 'returns' || tag === 'return') {
123
+ doc.returns = text.replace(/^\{[^}]*\}\s*/, '');
124
+ }
125
+ else {
126
+ doc.tags.push({ tag, text });
127
+ }
128
+ }
129
+ return doc;
130
+ }
131
+ /**
132
+ * Load the `typescript` package (an optional peer dependency).
133
+ */
134
+ async function loadTypeScript() {
135
+ let mod;
136
+ try {
137
+ mod = await import('typescript');
138
+ }
139
+ catch (error) {
140
+ const message = error instanceof Error ? error.message : String(error);
141
+ throw new Error(`The "typescript" datasource needs the "typescript" package (${SUPPORTED_TYPESCRIPT}). ` +
142
+ `Install it in your project (npm install -D typescript). Cause: ${message}`, { cause: error });
143
+ }
144
+ const ts = (mod.default ?? mod);
145
+ if (typeof ts.createProgram !== 'function') {
146
+ throw new Error(`The "typescript" datasource needs the TypeScript compiler API (${SUPPORTED_TYPESCRIPT}); ` +
147
+ `the installed "typescript" package does not provide it.`);
148
+ }
149
+ return ts;
150
+ }
151
+ function toPosix(p) {
152
+ return p.split(sep).join('/');
153
+ }
154
+ function commonDirectory(files) {
155
+ const parts = files.map((f) => dirname(f).split(sep));
156
+ const first = parts[0] ?? [];
157
+ let length = first.length;
158
+ for (const p of parts) {
159
+ let i = 0;
160
+ while (i < length && i < p.length && p[i] === first[i])
161
+ i++;
162
+ length = i;
163
+ }
164
+ return first.slice(0, length).join(sep) || sep;
165
+ }
166
+ /** `{@link Target}`, `{@link Target|text}`, `{@link Target text}` (also linkcode / linkplain). */
167
+ export const INLINE_LINK = /\{@link(?:code|plain)?\s+([^}|\s]+)(?:\s*\|\s*|\s+)?([^}]*)\}/g;
168
+ /**
169
+ * Record on each symbol which `{@link ...}` targets in its documentation name an
170
+ * exported symbol of the same datasource, so a renderer of one record can link them.
171
+ */
172
+ function resolveLinks(records) {
173
+ const byName = new Map(records.map((r) => [r.name, r]));
174
+ for (const record of records) {
175
+ const texts = [];
176
+ const collect = (summary, tags) => {
177
+ texts.push(summary, ...tags.map((t) => t.text));
178
+ };
179
+ const collectSignature = (sig) => {
180
+ collect(sig.summary, sig.tags);
181
+ texts.push(...sig.parameters.map((p) => p.description));
182
+ if (sig.returns)
183
+ texts.push(sig.returns.description);
184
+ };
185
+ collect(record.summary, record.tags);
186
+ record.signatures.forEach(collectSignature);
187
+ for (const member of record.members) {
188
+ collect(member.summary, member.tags);
189
+ member.signatures.forEach(collectSignature);
190
+ }
191
+ const found = new Map();
192
+ const targets = record.referenceOf ? [record.referenceOf] : [];
193
+ for (const text of texts) {
194
+ for (const match of text.matchAll(INLINE_LINK))
195
+ targets.push(match[1]);
196
+ }
197
+ for (const target of targets) {
198
+ if (found.has(target))
199
+ continue;
200
+ const [name, ...rest] = target.split(/[.#]/);
201
+ const symbol = byName.get(name ?? '');
202
+ if (!symbol)
203
+ continue;
204
+ found.set(target, {
205
+ target,
206
+ name: symbol.name,
207
+ kind: symbol.kind,
208
+ kindDir: symbol.kindDir,
209
+ member: rest.length > 0 ? rest.join('.') : null,
210
+ });
211
+ }
212
+ record.links = [...found.values()];
213
+ }
214
+ }
215
+ /** Order of UTF-16 code units (so `Middleware.ts` comes before `decorators.ts`). */
216
+ function compareCodeUnits(a, b) {
217
+ return a < b ? -1 : a > b ? 1 : 0;
218
+ }
219
+ /** Case-insensitive order, then code units to break ties. */
220
+ function compareText(a, b) {
221
+ const la = a.toLowerCase();
222
+ const lb = b.toLowerCase();
223
+ if (la !== lb)
224
+ return la < lb ? -1 : 1;
225
+ return a < b ? -1 : a > b ? 1 : 0;
226
+ }
227
+ /**
228
+ * Reads exported symbols with one program and type checker.
229
+ */
230
+ class ApiExtractor {
231
+ ts;
232
+ program;
233
+ checker;
234
+ options;
235
+ typeFlags;
236
+ constructor(ts, program, checker, options) {
237
+ this.ts = ts;
238
+ this.program = program;
239
+ this.checker = checker;
240
+ this.options = options;
241
+ this.typeFlags =
242
+ ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope;
243
+ }
244
+ extract(entryFiles) {
245
+ const { ts, checker } = this;
246
+ // Every exported name of each symbol, in export order.
247
+ const exportsOf = new Map();
248
+ for (const file of entryFiles) {
249
+ const sourceFile = this.program.getSourceFile(file);
250
+ if (!sourceFile) {
251
+ throw new Error(`TypeScript entry point not found in the program: ${file}`);
252
+ }
253
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
254
+ if (!moduleSymbol) {
255
+ continue; // A file without exports has no public API.
256
+ }
257
+ for (const exported of checker.getExportsOfModule(moduleSymbol)) {
258
+ const target = exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported;
259
+ const names = exportsOf.get(target) ?? [];
260
+ if (!names.some((n) => n.name === exported.name))
261
+ names.push(exported);
262
+ exportsOf.set(target, names);
263
+ }
264
+ }
265
+ const symbols = [];
266
+ for (const [target, exported] of exportsOf) {
267
+ // The symbol is documented under its own name when that name is exported;
268
+ // every other exported name is a reference to it.
269
+ const primary = exported.find((e) => e.name === target.name) ?? exported[0];
270
+ const built = this.buildSymbol(primary.name, target);
271
+ if (!built)
272
+ continue;
273
+ symbols.push(built);
274
+ for (const alias of exported) {
275
+ if (alias === primary)
276
+ continue;
277
+ const reference = this.buildReference(alias, built.symbol);
278
+ if (reference)
279
+ symbols.push(reference);
280
+ }
281
+ }
282
+ symbols.sort((a, b) => {
283
+ if (this.options.sort === 'source-order') {
284
+ const byPath = compareCodeUnits(a.position[0], b.position[0]);
285
+ if (byPath !== 0)
286
+ return byPath;
287
+ if (a.position[1] !== b.position[1])
288
+ return a.position[1] - b.position[1];
289
+ }
290
+ return compareText(a.symbol.name, b.symbol.name);
291
+ });
292
+ const records = symbols.map((s) => s.symbol);
293
+ resolveLinks(records);
294
+ return records;
295
+ }
296
+ /** A second exported name of a symbol (`export { A as B }`). */
297
+ buildReference(alias, of) {
298
+ const declaration = alias.declarations?.[0];
299
+ if (!declaration)
300
+ return null;
301
+ const doc = this.docOf(declaration);
302
+ if (this.isHidden(doc.tags))
303
+ return null;
304
+ const sf = declaration.getSourceFile();
305
+ return {
306
+ symbol: {
307
+ name: alias.name,
308
+ kind: 'reference',
309
+ kindLabel: KIND_INFO.reference.label,
310
+ kindDir: KIND_INFO.reference.dir,
311
+ category: null,
312
+ summary: doc.summary,
313
+ tags: doc.tags,
314
+ code: null,
315
+ typeParameters: [],
316
+ extends: [],
317
+ implements: [],
318
+ signatures: [],
319
+ members: [],
320
+ source: this.sourceOf(declaration),
321
+ referenceOf: of.name,
322
+ links: [],
323
+ },
324
+ position: [toPosix(relative(this.options.baseDir, sf.fileName)), this.nameNode(declaration).getStart()],
325
+ };
326
+ }
327
+ buildSymbol(name, symbol) {
328
+ const { ts } = this;
329
+ const declarations = (symbol.declarations ?? []).filter((d) => !this.isExcludedFile(d));
330
+ const declaration = this.primaryDeclaration(declarations);
331
+ if (!declaration)
332
+ return null;
333
+ const kind = this.kindOf(declaration);
334
+ if (!kind)
335
+ return null;
336
+ const doc = this.docOf(declaration);
337
+ if (this.isHidden(doc.tags))
338
+ return null;
339
+ const categoryTag = doc.tags.find((t) => t.tag === 'category');
340
+ const record = {
341
+ name,
342
+ kind,
343
+ kindLabel: KIND_INFO[kind].label,
344
+ kindDir: KIND_INFO[kind].dir,
345
+ category: categoryTag ? categoryTag.text.trim() || null : null,
346
+ summary: doc.summary,
347
+ tags: doc.tags,
348
+ code: null,
349
+ typeParameters: [],
350
+ extends: [],
351
+ implements: [],
352
+ signatures: [],
353
+ members: [],
354
+ source: this.sourceOf(declaration),
355
+ referenceOf: null,
356
+ links: [],
357
+ };
358
+ if (ts.isClassDeclaration(declaration)) {
359
+ record.typeParameters = this.typeParameters(declaration.typeParameters, doc);
360
+ this.heritage(declaration, record);
361
+ record.members = this.members(declaration.members, name);
362
+ }
363
+ else if (ts.isInterfaceDeclaration(declaration)) {
364
+ record.typeParameters = this.typeParameters(declaration.typeParameters, doc);
365
+ const interfaces = declarations.filter(ts.isInterfaceDeclaration);
366
+ for (const d of interfaces)
367
+ this.heritage(d, record);
368
+ record.members = interfaces.flatMap((d) => this.members(d.members, name));
369
+ }
370
+ else if (ts.isEnumDeclaration(declaration)) {
371
+ record.members = declarations
372
+ .filter(ts.isEnumDeclaration)
373
+ .flatMap((d) => d.members.map((m) => this.enumMember(m)))
374
+ .filter((m) => m !== null);
375
+ }
376
+ else if (ts.isTypeAliasDeclaration(declaration)) {
377
+ record.typeParameters = this.typeParameters(declaration.typeParameters, doc);
378
+ const params = this.typeParameterList(declaration.typeParameters);
379
+ record.code = `type ${name}${params} = ${declaration.type.getText()};`;
380
+ if (ts.isTypeLiteralNode(declaration.type)) {
381
+ record.members = this.members(declaration.type.members, name);
382
+ }
383
+ }
384
+ else if (kind === 'function') {
385
+ record.signatures = this.functionSignatures(name, symbol, declaration);
386
+ }
387
+ else if (ts.isVariableDeclaration(declaration)) {
388
+ const isConst = (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0;
389
+ const type = declaration.type
390
+ ? declaration.type.getText()
391
+ : this.checker.typeToString(this.checker.getTypeAtLocation(declaration.name), undefined, this.typeFlags);
392
+ record.code = `${isConst ? 'const' : 'let'} ${name}: ${type};`;
393
+ record.members = this.variableMembers(declaration);
394
+ }
395
+ const sf = declaration.getSourceFile();
396
+ return {
397
+ symbol: record,
398
+ position: [toPosix(relative(this.options.baseDir, sf.fileName)), this.nameNode(declaration).getStart()],
399
+ };
400
+ }
401
+ isExcludedFile(node) {
402
+ if (!this.options.excludeExternals)
403
+ return false;
404
+ const sf = node.getSourceFile();
405
+ return (this.program.isSourceFileFromExternalLibrary(sf) ||
406
+ this.program.isSourceFileDefaultLibrary(sf) ||
407
+ toPosix(sf.fileName).includes('/node_modules/'));
408
+ }
409
+ primaryDeclaration(declarations) {
410
+ const { ts } = this;
411
+ const order = [
412
+ ts.isClassDeclaration,
413
+ ts.isInterfaceDeclaration,
414
+ ts.isEnumDeclaration,
415
+ ts.isTypeAliasDeclaration,
416
+ ts.isFunctionDeclaration,
417
+ ts.isVariableDeclaration,
418
+ ts.isModuleDeclaration,
419
+ ];
420
+ for (const test of order) {
421
+ const found = declarations.find(test);
422
+ if (found)
423
+ return found;
424
+ }
425
+ return undefined;
426
+ }
427
+ kindOf(declaration) {
428
+ const { ts } = this;
429
+ if (ts.isClassDeclaration(declaration))
430
+ return 'class';
431
+ if (ts.isInterfaceDeclaration(declaration))
432
+ return 'interface';
433
+ if (ts.isEnumDeclaration(declaration))
434
+ return 'enum';
435
+ if (ts.isTypeAliasDeclaration(declaration))
436
+ return 'type';
437
+ if (ts.isFunctionDeclaration(declaration))
438
+ return 'function';
439
+ if (ts.isModuleDeclaration(declaration))
440
+ return 'namespace';
441
+ if (ts.isVariableDeclaration(declaration)) {
442
+ const init = declaration.initializer;
443
+ const functionLike = init !== undefined && (ts.isArrowFunction(init) || ts.isFunctionExpression(init));
444
+ // A variable initialized with a function and no type annotation is a function.
445
+ return functionLike && !declaration.type ? 'function' : 'variable';
446
+ }
447
+ return null;
448
+ }
449
+ nameNode(node) {
450
+ const name = node.name;
451
+ return name ?? node;
452
+ }
453
+ sourceOf(node) {
454
+ const sf = node.getSourceFile();
455
+ const line = sf.getLineAndCharacterOfPosition(this.nameNode(node).getStart()).line + 1;
456
+ const path = toPosix(relative(this.options.baseDir, sf.fileName));
457
+ const file = toPosix(relative(this.options.displayDir, sf.fileName));
458
+ let url = null;
459
+ const template = this.options.sourceLinkTemplate;
460
+ if (template) {
461
+ url = template
462
+ .replace(/\{gitRevision\}/g, this.options.gitRevision ?? '')
463
+ .replace(/\{path\}/g, path)
464
+ .replace(/\{line\}/g, String(line));
465
+ }
466
+ return { file, path, line, url };
467
+ }
468
+ /** The documentation comment closest to a declaration. */
469
+ docOf(node) {
470
+ const { ts } = this;
471
+ const docs = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc);
472
+ const doc = docs[docs.length - 1];
473
+ if (!doc)
474
+ return EMPTY_DOC;
475
+ return parseDocComment(doc.getSourceFile().text.slice(doc.pos, doc.end));
476
+ }
477
+ isHidden(tags) {
478
+ return tags.some((t) => HIDDEN_TAGS.has(t.tag) || (this.options.excludeInternal && t.tag === 'internal'));
479
+ }
480
+ typeText(node, fallback) {
481
+ if (node)
482
+ return node.getText();
483
+ return this.checker.typeToString(fallback(), undefined, this.typeFlags);
484
+ }
485
+ typeParameterList(params) {
486
+ if (!params || params.length === 0)
487
+ return '';
488
+ return `<${params.map((p) => p.getText()).join(', ')}>`;
489
+ }
490
+ typeParameters(params, doc) {
491
+ if (!params)
492
+ return [];
493
+ return params.map((p) => ({
494
+ name: p.name.text,
495
+ constraint: p.constraint ? p.constraint.getText() : null,
496
+ default: p.default ? p.default.getText() : null,
497
+ description: doc.typeParameters.get(p.name.text) ?? '',
498
+ }));
499
+ }
500
+ heritage(node, record) {
501
+ const { ts } = this;
502
+ for (const clause of node.heritageClauses ?? []) {
503
+ const types = clause.types.map((t) => t.getText());
504
+ if (clause.token === ts.SyntaxKind.ExtendsKeyword)
505
+ record.extends.push(...types);
506
+ else
507
+ record.implements.push(...types);
508
+ }
509
+ }
510
+ parameters(params, doc) {
511
+ const { ts } = this;
512
+ return params
513
+ .filter((p) => !(ts.isIdentifier(p.name) && p.name.text === 'this'))
514
+ .map((p) => ({
515
+ name: p.name.getText(),
516
+ type: this.typeText(p.type, () => this.checker.getTypeAtLocation(p)),
517
+ optional: p.questionToken !== undefined || p.initializer !== undefined,
518
+ rest: p.dotDotDotToken !== undefined,
519
+ defaultValue: p.initializer ? p.initializer.getText() : null,
520
+ description: ts.isIdentifier(p.name) ? (doc.parameters.get(p.name.text) ?? '') : '',
521
+ }));
522
+ }
523
+ parameterCode(params) {
524
+ return params
525
+ .map((p) => `${p.rest ? '...' : ''}${p.name}${p.optional && !p.rest ? '?' : ''}: ${p.type}`)
526
+ .join(', ');
527
+ }
528
+ returnsOf(declaration, signature, doc) {
529
+ const type = declaration.type
530
+ ? declaration.type.getText()
531
+ : signature
532
+ ? this.checker.typeToString(this.checker.getReturnTypeOfSignature(signature), undefined, this.typeFlags)
533
+ : 'void';
534
+ return { type, description: doc.returns };
535
+ }
536
+ /**
537
+ * Build a signature record. `prefix` is the code before the type parameters,
538
+ * e.g. `function name`, `static name`, `new Name`, `get name`.
539
+ * A construct signature names the constructed type in `constructs`.
540
+ * `docNode` carries the comment (the variable of `const f = () => ...`).
541
+ */
542
+ signature(declaration, prefix, kind, constructs = '', docNode = declaration) {
543
+ const doc = this.docOf(docNode);
544
+ const parameters = this.parameters(declaration.parameters, doc);
545
+ const typeParameters = this.typeParameters(declaration.typeParameters, doc);
546
+ const tsSignature = this.checker.getSignatureFromDeclaration(declaration);
547
+ let returns = null;
548
+ let suffix = '';
549
+ if (kind === 'construct') {
550
+ suffix = `: ${constructs}`;
551
+ }
552
+ else if (kind !== 'set') {
553
+ returns = this.returnsOf(declaration, tsSignature, doc);
554
+ suffix = `: ${returns.type}`;
555
+ }
556
+ const typeParamCode = this.typeParameterList(declaration.typeParameters);
557
+ return {
558
+ code: `${prefix}${typeParamCode}(${this.parameterCode(parameters)})${suffix};`,
559
+ summary: doc.summary,
560
+ tags: doc.tags,
561
+ typeParameters,
562
+ parameters,
563
+ returns,
564
+ source: this.sourceOf(docNode),
565
+ };
566
+ }
567
+ /** Overload declarations, or the implementation when there are no overloads. */
568
+ publicOverloads(declarations) {
569
+ const withoutBody = declarations.filter((d) => !('body' in d) || d.body === undefined);
570
+ return withoutBody.length > 0 ? withoutBody : declarations;
571
+ }
572
+ functionSignatures(name, symbol, declaration) {
573
+ const { ts } = this;
574
+ if (ts.isVariableDeclaration(declaration)) {
575
+ const init = declaration.initializer;
576
+ if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {
577
+ // The doc comment of `export const f = () => ...` is on the variable statement.
578
+ return [this.signature(init, `function ${name}`, 'call', '', declaration)];
579
+ }
580
+ return [];
581
+ }
582
+ const functions = (symbol.declarations ?? []).filter(ts.isFunctionDeclaration);
583
+ return this.publicOverloads(functions).map((d) => this.signature(d, `function ${name}`, 'call'));
584
+ }
585
+ modifiers(node) {
586
+ const { ts } = this;
587
+ const mods = ts.canHaveModifiers(node) ? (ts.getModifiers(node) ?? []) : [];
588
+ return new Set(mods.map((m) => m.kind));
589
+ }
590
+ isPrivate(node, mods) {
591
+ const name = node.name;
592
+ return mods.has(this.ts.SyntaxKind.PrivateKeyword) || (name !== undefined && this.ts.isPrivateIdentifier(name));
593
+ }
594
+ members(elements, ownerName) {
595
+ const { ts } = this;
596
+ const groups = new Map();
597
+ const order = [];
598
+ for (const element of elements) {
599
+ if (ts.isClassStaticBlockDeclaration(element) || ts.isSemicolonClassElement(element))
600
+ continue;
601
+ const mods = this.modifiers(element);
602
+ if (this.options.excludePrivate && this.isPrivate(element, mods))
603
+ continue;
604
+ let key;
605
+ if (ts.isConstructorDeclaration(element) || ts.isConstructSignatureDeclaration(element))
606
+ key = 'constructor';
607
+ else if (ts.isCallSignatureDeclaration(element))
608
+ key = '()';
609
+ else if (ts.isIndexSignatureDeclaration(element))
610
+ key = `[${element.parameters.map((p) => p.getText()).join(', ')}]`;
611
+ else {
612
+ const name = element.name ? element.name.getText() : '';
613
+ key = `${mods.has(ts.SyntaxKind.StaticKeyword) ? 'static ' : ''}${name}`;
614
+ }
615
+ if (!groups.has(key)) {
616
+ groups.set(key, []);
617
+ order.push(key);
618
+ }
619
+ groups.get(key).push(element);
620
+ }
621
+ const members = [];
622
+ for (const key of order) {
623
+ const member = this.member(groups.get(key), ownerName);
624
+ if (member)
625
+ members.push(member);
626
+ if (key === 'constructor')
627
+ members.push(...this.parameterProperties(groups.get(key)));
628
+ }
629
+ if (this.options.sort === 'alphabetical') {
630
+ members.sort((a, b) => compareText(a.name, b.name));
631
+ }
632
+ return members;
633
+ }
634
+ member(elements, ownerName) {
635
+ const { ts } = this;
636
+ const first = elements[0];
637
+ const doc = this.docOf(first);
638
+ if (this.isHidden(doc.tags))
639
+ return null;
640
+ const mods = this.modifiers(first);
641
+ const isStatic = mods.has(ts.SyntaxKind.StaticKeyword);
642
+ const isAbstract = mods.has(ts.SyntaxKind.AbstractKeyword);
643
+ // Modifiers shown in the signature code (headings use the plain name).
644
+ const staticPrefix = `${isStatic ? 'static ' : ''}${isAbstract ? 'abstract ' : ''}`;
645
+ const base = {
646
+ static: isStatic,
647
+ readonly: mods.has(ts.SyntaxKind.ReadonlyKeyword),
648
+ optional: first.questionToken !== undefined,
649
+ protected: mods.has(ts.SyntaxKind.ProtectedKeyword),
650
+ abstract: isAbstract,
651
+ summary: doc.summary,
652
+ tags: doc.tags,
653
+ source: this.sourceOf(first),
654
+ };
655
+ if (ts.isConstructorDeclaration(first) || ts.isConstructSignatureDeclaration(first)) {
656
+ const decls = this.publicOverloads(elements);
657
+ const owner = `${ownerName}${this.ownerTypeArguments(first)}`;
658
+ return {
659
+ ...base,
660
+ name: 'constructor',
661
+ kind: 'constructor',
662
+ type: null,
663
+ signatures: decls.map((d) => this.signature(d, `new ${ownerName}`, 'construct', owner)),
664
+ };
665
+ }
666
+ if (ts.isCallSignatureDeclaration(first)) {
667
+ return {
668
+ ...base,
669
+ name: '()',
670
+ kind: 'call-signature',
671
+ type: null,
672
+ signatures: elements.map((d) => this.signature(d, '', 'call')),
673
+ };
674
+ }
675
+ if (ts.isIndexSignatureDeclaration(first)) {
676
+ const params = first.parameters.map((p) => p.getText()).join(', ');
677
+ return {
678
+ ...base,
679
+ name: `[${params}]`,
680
+ kind: 'index-signature',
681
+ type: this.typeText(first.type, () => this.checker.getTypeAtLocation(first)),
682
+ signatures: [],
683
+ };
684
+ }
685
+ const name = first.name ? first.name.getText() : '';
686
+ if (ts.isMethodDeclaration(first) || ts.isMethodSignature(first)) {
687
+ const decls = this.publicOverloads(elements);
688
+ return {
689
+ ...base,
690
+ name,
691
+ kind: 'method',
692
+ type: null,
693
+ signatures: decls.map((d) => this.signature(d, `${staticPrefix}${name}`, 'call')),
694
+ };
695
+ }
696
+ if (ts.isGetAccessorDeclaration(first) || ts.isSetAccessorDeclaration(first)) {
697
+ const getters = elements.filter(ts.isGetAccessorDeclaration);
698
+ const setters = elements.filter(ts.isSetAccessorDeclaration);
699
+ return {
700
+ ...base,
701
+ name,
702
+ kind: 'accessor',
703
+ type: null,
704
+ signatures: [
705
+ ...getters.map((d) => this.signature(d, `${staticPrefix}get ${name}`, 'get')),
706
+ ...setters.map((d) => this.signature(d, `${staticPrefix}set ${name}`, 'set')),
707
+ ],
708
+ };
709
+ }
710
+ if (ts.isPropertyDeclaration(first) || ts.isPropertySignature(first)) {
711
+ return {
712
+ ...base,
713
+ name,
714
+ kind: 'property',
715
+ type: this.typeText(first.type, () => this.checker.getTypeAtLocation(first.name)),
716
+ signatures: [],
717
+ };
718
+ }
719
+ return null;
720
+ }
721
+ /**
722
+ * Properties of the object literal or type literal part of a variable's type
723
+ * (`const x = Object.assign(fn, { a, b })`), so they are documented with it.
724
+ */
725
+ variableMembers(declaration) {
726
+ const { ts, checker } = this;
727
+ const type = checker.getTypeAtLocation(declaration.name);
728
+ const parts = type.isIntersection() ? type.types : [type];
729
+ const members = [];
730
+ for (const part of parts) {
731
+ const owner = part.getSymbol();
732
+ if (!owner || !(owner.flags & (ts.SymbolFlags.ObjectLiteral | ts.SymbolFlags.TypeLiteral)))
733
+ continue;
734
+ for (const property of checker.getPropertiesOfType(part)) {
735
+ const decl = property.valueDeclaration ?? property.declarations?.[0];
736
+ if (!decl)
737
+ continue;
738
+ const doc = this.docOf(decl);
739
+ if (this.isHidden(doc.tags))
740
+ continue;
741
+ members.push({
742
+ name: property.name,
743
+ kind: 'property',
744
+ static: false,
745
+ readonly: false,
746
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
747
+ protected: false,
748
+ abstract: false,
749
+ type: checker.typeToString(checker.getTypeOfSymbolAtLocation(property, declaration), undefined, this.typeFlags),
750
+ summary: doc.summary,
751
+ tags: doc.tags,
752
+ signatures: [],
753
+ source: this.sourceOf(decl),
754
+ });
755
+ }
756
+ }
757
+ if (this.options.sort === 'alphabetical') {
758
+ members.sort((a, b) => compareText(a.name, b.name));
759
+ }
760
+ return members;
761
+ }
762
+ /**
763
+ * Properties declared by constructor parameters (`constructor(public readonly x: T)`).
764
+ * Their description is the constructor's `@param` text.
765
+ */
766
+ parameterProperties(elements) {
767
+ const { ts } = this;
768
+ const members = [];
769
+ for (const ctor of elements) {
770
+ if (!ts.isConstructorDeclaration(ctor))
771
+ continue;
772
+ const doc = this.docOf(ctor);
773
+ for (const param of ctor.parameters) {
774
+ if (!ts.isParameterPropertyDeclaration(param, ctor) || !ts.isIdentifier(param.name))
775
+ continue;
776
+ const mods = this.modifiers(param);
777
+ if (this.options.excludePrivate && mods.has(ts.SyntaxKind.PrivateKeyword))
778
+ continue;
779
+ members.push({
780
+ name: param.name.text,
781
+ kind: 'property',
782
+ static: false,
783
+ readonly: mods.has(ts.SyntaxKind.ReadonlyKeyword),
784
+ optional: param.questionToken !== undefined || param.initializer !== undefined,
785
+ protected: mods.has(ts.SyntaxKind.ProtectedKeyword),
786
+ abstract: false,
787
+ type: this.typeText(param.type, () => this.checker.getTypeAtLocation(param)),
788
+ summary: doc.parameters.get(param.name.text) ?? '',
789
+ tags: [],
790
+ signatures: [],
791
+ source: this.sourceOf(param),
792
+ });
793
+ }
794
+ }
795
+ return members;
796
+ }
797
+ /** `<T, U>` of the class that declares a constructor, for `new C<T>(...): C<T>`. */
798
+ ownerTypeArguments(element) {
799
+ const parent = element.parent;
800
+ if (this.ts.isClassDeclaration(parent) && parent.typeParameters && parent.typeParameters.length > 0) {
801
+ return `<${parent.typeParameters.map((p) => p.name.text).join(', ')}>`;
802
+ }
803
+ return '';
804
+ }
805
+ enumMember(member) {
806
+ const doc = this.docOf(member);
807
+ if (this.isHidden(doc.tags))
808
+ return null;
809
+ const value = this.checker.getConstantValue(member);
810
+ return {
811
+ name: member.name.getText(),
812
+ kind: 'enum-member',
813
+ static: false,
814
+ readonly: true,
815
+ optional: false,
816
+ protected: false,
817
+ abstract: false,
818
+ type: value === undefined ? (member.initializer?.getText() ?? null) : JSON.stringify(value),
819
+ summary: doc.summary,
820
+ tags: doc.tags,
821
+ signatures: [],
822
+ source: this.sourceOf(member),
823
+ };
824
+ }
825
+ }
826
+ export class TypeScriptDatasource {
827
+ type = 'typescript';
828
+ data = null;
829
+ config;
830
+ constructor(config) {
831
+ const entryPoints = config['entry_points'];
832
+ if (!Array.isArray(entryPoints) ||
833
+ entryPoints.length === 0 ||
834
+ !entryPoints.every((e) => typeof e === 'string')) {
835
+ throw new Error('TypeScript datasource requires "entry_points" (a list of file paths)');
836
+ }
837
+ const template = config['source_link_template'];
838
+ if (template !== undefined && typeof template !== 'string') {
839
+ throw new Error('TypeScript datasource "source_link_template" must be a string');
840
+ }
841
+ if (typeof template === 'string' && template.includes('{gitRevision}') && typeof config['git_revision'] !== 'string') {
842
+ throw new Error('TypeScript datasource "source_link_template" uses {gitRevision}; set "git_revision" (e.g. main)');
843
+ }
844
+ const sort = config['sort'];
845
+ if (sort !== undefined && sort !== 'source-order' && sort !== 'alphabetical') {
846
+ throw new Error('TypeScript datasource "sort" must be "source-order" or "alphabetical"');
847
+ }
848
+ for (const key of ['exclude_internal', 'exclude_private', 'exclude_externals']) {
849
+ if (config[key] !== undefined && typeof config[key] !== 'boolean') {
850
+ throw new Error(`TypeScript datasource "${key}" must be true or false`);
851
+ }
852
+ }
853
+ this.config = config;
854
+ }
855
+ async loadData() {
856
+ if (this.data !== null) {
857
+ return this.data;
858
+ }
859
+ const ts = await loadTypeScript();
860
+ const cwd = process.cwd();
861
+ const entryFiles = this.config.entry_points.map((e) => resolve(cwd, e));
862
+ const configPath = this.config.tsconfig
863
+ ? resolve(cwd, this.config.tsconfig)
864
+ : ts.findConfigFile(dirname(entryFiles[0]), ts.sys.fileExists);
865
+ let options = {};
866
+ if (configPath) {
867
+ const read = ts.readConfigFile(configPath, ts.sys.readFile);
868
+ if (read.error) {
869
+ throw new Error(`Cannot read ${configPath}: ${ts.flattenDiagnosticMessageText(read.error.messageText, '\n')}`);
870
+ }
871
+ options = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(configPath)).options;
872
+ }
873
+ options = { ...options, noEmit: true };
874
+ const program = ts.createProgram({ rootNames: entryFiles, options });
875
+ const extractor = new ApiExtractor(ts, program, program.getTypeChecker(), {
876
+ excludeInternal: this.config.exclude_internal ?? true,
877
+ excludePrivate: this.config.exclude_private ?? true,
878
+ excludeExternals: this.config.exclude_externals ?? true,
879
+ sourceLinkTemplate: this.config.source_link_template ?? null,
880
+ gitRevision: this.config.git_revision ?? null,
881
+ sort: this.config.sort ?? 'source-order',
882
+ baseDir: cwd,
883
+ displayDir: commonDirectory(entryFiles),
884
+ });
885
+ this.data = extractor.extract(entryFiles);
886
+ return this.data;
887
+ }
888
+ async query(sql, params = []) {
889
+ return filterRows(await this.loadData(), sql, params);
890
+ }
891
+ async getAll() {
892
+ return this.loadData();
893
+ }
894
+ async close() {
895
+ this.data = null;
896
+ }
897
+ }
898
+ export function createTypeScriptDatasource(config) {
899
+ return new TypeScriptDatasource(config);
900
+ }
901
+ //# sourceMappingURL=typescript.js.map