/
index.ts
1221 lines (1014 loc) · 30.8 KB
/
index.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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as util from "util";
import * as path from "path";
import * as cp from "child_process";
import * as os from "os";
import * as fs from "fs";
import * as semver from "semver";
import * as typedoc from "typedoc";
import * as markdown from "extra-markdown-text";
import * as javascript from "extra-javascript-text";
import * as jsdoc from "extra-jsdoc-text";
import kleur from "kleur";
import {ExecSyncOptions} from "child_process";
import {URL} from "url";
import {Octokit} from "@octokit/rest";
import {Jsdoc} from "extra-jsdoc-text";
import {
Reflection,
ReflectionKind,
Comment,
CommentDisplayPart,
DeclarationReflection,
SignatureReflection,
ProjectReflection,
ReflectionFlags,
} from "typedoc";
// STRING
// ======
/**
* Convert string to kebab-case.
* @param x string
* @param sep separator [-]
* @returns string in kebab-case
*/
function kebabCase(x: string, sep: string="-"): string {
var rdelta = /([^A-Z])([A-Z])|(\D)(\d)/g;
var rtrim = /^[^a-zA-Z0-9\.]+|[^a-zA-Z0-9\.]+$/g;
var rsep = /[^a-zA-Z0-9\.]+/g;
x = x.replace(rdelta, `$1$3${sep}$2$4`);
x = x.replace(rsep, sep);
x = x.replace(rtrim, "");
return x.toLowerCase();
}
/**
* Wrap a string by specified column width.
* @param x string
* @param cols column width [0 => unlimited]
* @returns wrapped string
*/
function wrapText(x: string, cols: number=0): string {
var a = "", cols = cols || x.length;
for (var i=0; i<x.length; i+=cols)
a += x.substring(i, i+cols) + "\n";
return a.substring(0, a.length-1);
}
/**
* Indent a string by specified prefix text.
* @param x string
* @param pre prefix text []
* @returns indented text
*/
function indentText(x: string, pre: string=""): string {
return x.split("\n").map(l => pre + l).join("\n").replace(/[ \t]+\n/g, "\n");
}
// PATH
// ====
/**
* Get file name without extension.
* @param pth file path
* @returns file name
*/
function filename(pth: string): string {
var f = path.basename(pth);
return f.replace(/\..*/, "");
}
/**
* Get symbol name for file.
* @param pth file path
* @returns symbol name
*/
export function symbolname(pth: string): string {
return filename(pth).replace(/[^\w$]+/g, "_");
}
/**
* Get keyword name for file.
* @param pth file path
* @returns keyword name
*/
export function keywordname(pth: string): string {
return kebabCase(filename(pth)).replace(/\W+/g, "-");
}
// CONSOLE
// =======
/**
* Get formatted data for display to console.
* @param x data
* @returns formatted data
*/
function fixup(x?: any): string {
x = x || "";
x = typeof x !== "string"? util.inspect(x) : x;
return x.replace(/^\w+:/, (m: string) => kleur.bold(m));
}
/**
* Print error message to stderr with newline.
* @param x data
*/
export function error(x?: any): void {
console.error(kleur.red(fixup(x)));
}
/**
* Print warning message to stderr with newline.
* @param x data
*/
export function warn(x?: any): void {
console.warn(kleur.yellow(fixup(x)));
}
/**
* Print log message to stdout with newline.
* @param x data
*/
export function log(x?: any): void {
console.log(kleur.cyan(fixup(x)));
}
/**
* Print info message to stdout with newline.
* @param x data
*/
export function info(x?: any): void {
console.info(kleur.grey(fixup(x)));
}
// CHILD-PROCESS
// =============
/** Exec options. */
export interface ExecOptions extends ExecSyncOptions {
/** Hide command log. */
commandHide?: boolean,
}
/**
* Execute command with output, and print the command.
* @param cmd command to execute
* @param options exec options
* @returns command output
*/
export function exec(cmd: string, options?: ExecOptions): string | Buffer {
var o = Object.assign({stdio: [0, 1, 2]}, options);
if (!o.commandHide) info(`$ ${cmd}`);
var a = cp.execSync(cmd, o);
if (!o.commandHide) info();
return a;
}
/**
* Execute command and get its output as string.
* @param cmd command to execute
* @param options exec options
* @returns command output
*/
export function execStr(cmd: string, options?: ExecOptions): string {
info(`$ ${cmd}`);
var o = Object.assign({encoding: "utf8"}, options);
var a = cp.execSync(cmd, o).toString().trim();
info();
return a;
}
// FS
// ==
/**
* Read file text with Unix EOL.
* @param pth file path
* @returns file text
*/
export function readFileText(pth: string): string {
var txt = fs.readFileSync(pth, "utf8");
return txt.replace(/\r?\n/g, "\n");
}
/**
* Write file text with system EOL.
* @param pth file path
* @param txt file text
*/
export function writeFileText(pth: string, txt: string): void {
var txt = txt.replace(/\r?\n/g, os.EOL);
fs.writeFileSync(pth, txt);
}
/**
* Read JSON file as object.
* @param pth path of JSON file
* @returns object
*/
export function readJson(pth: string): any {
return JSON.parse(readFileText(pth));
}
/**
* Write object to JSON file.
* @param pth path of JSON file
* @param val object
*/
export function writeJson(pth: string, val: any): void {
writeFileText(pth, JSON.stringify(val, null, 2) + "\n");
}
/** Records file path and data. */
export interface Document {
/** File path. */
path: string,
/** File data. */
data: string | Buffer,
}
/**
* Read document.
* @param pth file path
* @returns document \{path, data\}
*/
export function readDocument(pth: string): Document {
var data = fs.existsSync(pth)? fs.readFileSync(pth) : null;
return {path: pth, data};
}
/**
* Write document.
* @param doc document \{path, data\}
*/
export function writeDocument(doc: Document): void {
if (doc.data!=null) fs.writeFileSync(doc.path, doc.data);
else if (fs.existsSync(doc.path)) fs.unlinkSync(doc.path);
}
// GIT
// ===
/**
* Get repository's remote URL.
* @returns remote URL
*/
function gitRemoteUrl(): string {
return execStr(`git config --get remote.origin.url`);
}
/**
* Get current branch of git repository.
* @returns branch name
*/
function gitBranch(): string {
return execStr(`git rev-parse --abbrev-ref HEAD`);
}
/**
* Get diff of a file in git repository.
* @param pth path of file
* @returns diff text
*/
function gitDiff(pth: string): string {
var f = path.basename(pth);
var cwd = path.dirname(pth);
return execStr(`git diff "${f}"`, {cwd});
}
/**
* Add submodule to git repository.
* @param url submodule url
* @param out output directory
*/
function gitAddSubmodule(url: string, out: string): void {
if (!url) { exec(`git submodule update --remote --merge`); return; }
exec(`git submodule add ${url} "${out}"`);
exec(`git submodule update --init`);
}
/** Git commit push options. */
export interface GitCommitPushOptions extends ExecOptions {
/** Commit options. */
commit?: string,
/** Push options. */
push?: string,
}
/**
* Commit new changes and push to remote.
* @param msg commit message (amend if empty)
* @param options commit options
*/
export function gitCommitPush(msg: string="", options: GitCommitPushOptions=null): void {
var o = Object.assign({commit: "", push: ""}, options);
if (msg) o.commit += ` -m "${msg}"`;
else o.commit += ` --amend --no-edit`;
if (!msg) o.push += ` -f`;
exec(`git add .`, o);
exec(`git commit${o.commit}`, o);
exec(`git push${o.push}`, o);
}
/** Git setup branch options. */
export interface GitSetupBranchOptions extends ExecOptions {
/** First file [index.html]. */
file?: string,
}
/**
* Setup new branch and push to remote.
* @param branch branch name
* @param options setup options
*/
export function gitSetupBranch(branch: string, options: GitSetupBranchOptions=null): void {
var o = Object.assign({}, options);
log(`Creating ${branch} branch ...`);
exec(`git checkout --orphan ${branch}`, o);
exec(`git rm -rf .`, o);
exec(`git clean -fxd`, o);
exec(`touch ${o.file || "index.html"}`, o);
var co = Object.assign({push: ` --set-upstream origin ${branch}`}, options);
gitCommitPush("initial commit", co);
}
// BUNDLE / BROWSERIFY
// ===================
/**
* Add banner (header comment) to script text.
* @param txt script text
* @returns script text with banner
*/
export function addBanner(txt: string): string {
txt = txt.trim();
if (txt.length===0) return "";
if (/^\/\/[^\n]*$|^\/\*[\s\S]*?\*\/$/.test(txt)) return `${txt}\n`;
if (txt.includes("\n")) return `/**\n${txt}\n*/\n`;
return `/** ${txt} */\n`;
}
/** Bundle options. */
export interface BundleOptions {
/** Bundle config script [rollup.config.js]. */
config?: string,
/** Environment variables for bundle config script. */
env?: NodeJS.Dict<string>,
}
function bundleEnvArgs(env?: any): string {
var a = "";
if (!env) return a;
for (var k in env)
a += ` --environment ${k}:${env[k]}`;
return a;
}
/**
* Bundle a script file with config.
* @param src source file
* @param options bundle options \{config, env\}
*/
export function bundleScript(src?: string, options?: BundleOptions): void {
var o = Object.assign({}, options);
if (src) src = src.replace(/\.ts$/, ".js");
var cfg = o.config || "rollup.config.js";
var inp = src? `-i "${src}"` : "";
var env = bundleEnvArgs(o.env);
exec(`rollup -c "${cfg}" ${inp} ${env}`);
}
/** Webify options. */
export interface WebifyOptions {
/** Source script format (cjs, esm) [cjs]. */
format?: string,
/** Standalone symbol name. */
symbol?: string,
/** Banner text for script. */
banner?: string,
}
/**
* Webify a script file.
* @param src source script file
* @param dst destination script file
* @param options webify options
*/
export function webifyScript(src: string, dst: string, options?: WebifyOptions): void {
var o = Object.assign({}, options);
var cjs = !o.format || /c?js/i.test(o.format);
var tfm = o.format==="esm"? "-t babelify" : "";
var sym = o.symbol? `-s "${o.symbol}"` : "";
if (cjs) exec(`browserify "${src}" ${tfm} -o "${src}.1" ${sym}`);
else exec(`cp "${src}" "${src}.1"`);
exec(`terser "${src}.1" -o "${src}.2" -c -m`);
var txt = readFileText(`${src}.2`);
writeFileText(dst, addBanner(o.banner || "") + txt);
exec(`rm -f "${src}.1"`);
exec(`rm -f "${src}.2"`);
}
/** JSDoc details with some symbol details. */
export interface JsdocToken extends Jsdoc {
/** Symbol name. */
name: string,
/** Symbol kind. */
kind: string,
/** Symbol is exported? */
isExported: boolean,
/** Symbol is default? */
isDefault: boolean,
}
/**
* Perform operation on jsdoc token.
* @param j jsdoc token
* @returns resulting jsdoc token; or null to keep as-is
*/
export type OnJsdocToken = (j: JsdocToken) => JsdocToken;
/**
* Transform JSDocs in a script file.
* @param src source script file
* @param dst destination script file
* @param fm jsdoc token transformer (j)
*/
export function jsdocifyScript(src: string, dst: string, fm: OnJsdocToken): void {
var txt = readFileText(src);
txt = javascript.replaceJsdocSymbols(txt, (full, txt, name, kind, isExported, isDefault) => {
var a = fm(Object.assign(jsdoc.parse(txt), {name, kind, isExported, isDefault}));
return a? full.replace(txt, jsdoc.stringify(a)) : full;
});
writeFileText(dst, txt);
}
// GITHUB
// ======
/** GitHub URL details. */
export interface GithubUrlDetails {
/** Owner name. */
owner: string,
/** Repository name. */
repo: string,
}
/**
* Get details from GitHub URL.
* @param url remote url
* @returns url details
*/
export function parseGithubUrl(url: string): GithubUrlDetails {
var p = new URL(url).pathname;
p = p.replace(/^\/|^.*?:/, "");
p = p.replace(/^git+|\.git$/, "");
var [owner, repo] = p.split("/");
return {owner, repo};
}
/** GitHub Repository details. */
export interface GithubRepoDetails {
/** Authorization token [$GITHUB_TOKEN]. */
auth?: string,
/** Owner name. */
owner?: string,
/** Repository name. */
repo?: string,
/** Repository description. */
description?: string,
/** Respoitory homepage URL. */
homepage?: string,
/** Repository topics. */
topics?: string[],
}
function githubTopics(ks: string[]): string[] {
return ks.map(keywordname).filter(k => k.length<=35).slice(0, 20);
}
/**
* Update GitHub repository details.
* @param options repository details
*/
export async function updateGithubRepoDetails(options: GithubRepoDetails=null): Promise<void> {
var E = process.env;
var m = readMetadata(".");
var u = parseGithubUrl(m.repository.url);
var o = Object.assign({}, options);
var owner = o.owner || u.owner;
var repo = o.repo || u.repo;
var description = o.description || m.description;
var homepage = o.homepage || `https://www.npmjs.com/package/${m.name}`;
var topics = githubTopics(o.topics || m.keywords);
var octokit = new Octokit({auth: o.auth || E.GITHUB_TOKEN});
info("Updating GitHub details:\n");
info(`Description: ${description}`);
info(`Website: ${homepage}`);
info(`Topics: ${(topics || []).join(", ")}`);
await octokit.repos.update({owner, repo, description, homepage});
await octokit.repos.replaceAllTopics({owner, repo, names: topics});
}
// PACKAGE
// =======
/**
* Read package.json data.
* @param dir package directory
* @returns package.json data
*/
export function readMetadata(dir: string="."): any {
var pth = path.join(dir, "package.json");
return readJson(pth);
}
/**
* Write package.json data.
* @param dir package directory
* @param val package.json data
*/
export function writeMetadata(dir: string, val: any): void {
var pth = path.join(dir, "package.json");
writeJson(pth, val);
}
/**
* Get current registry.
* @param dir package directory
* @returns current registry
*/
export function registry(dir: string="."): string {
var cwd = dir;
return execStr(`npm config get registry`, {cwd});
}
/**
* Set current registry.
* @param dir package directory
* @param url registry url
*/
export function setRegistry(dir: string, url: string): void {
var pth = path.join(dir, ".npmrc");
var txt = fs.existsSync(pth)? readFileText(pth) : "";
var has = /^registry\s*=/.test(txt);
if (has) txt = txt.replace(/^registry\s*=.*$/gm, `registry=${url}`);
else txt = txt + `\nregistry=${url}`;
writeFileText(pth, txt.trim() + "\n");
}
/**
* Get latest package version.
* @param name package name
* @returns latest package version
*/
export function latestVersion(name: string): string {
return execStr(`npm view ${name} version`);
}
/**
* Get next unpublished version for package.
* @param name package name
* @param ver package version
* @returns next unpublished version
*/
export function nextUnpublishedVersion(name: string, ver: string): string {
var u = latestVersion(name);
var d = semver.diff(u, ver);
if (d==="major" || d==="minor") return ver;
if (semver.lt(u, ver)) return ver;
return semver.inc(u, "patch");
}
/**
* Publish package to NPM.
* @param dir package directory
*/
export function publish(dir: string="."): void {
var cwd = dir;
exec(`npm publish`, {cwd});
}
/**
* Publish package to GitHub.
* @param dir package directory
* @param owner owner name
*/
export function publishGithub(dir: string, owner: string): void {
var err = null;
var _package = readDocument(path.join(dir, "package.json"));
var _npmrc = readDocument(path.join(dir, ".npmrc"));
var m = readMetadata(dir);
var pkg = m.name.replace("@", "").replace("/", "--");
m.name = `@${owner}/${pkg}`;
writeMetadata(dir, m);
setRegistry(dir, `https://npm.pkg.github.com/${owner}`);
try { publish(dir); }
catch (e) { err = e; }
writeDocument(_npmrc);
writeDocument(_package);
if (err) throw err;
}
// DOCS
// ====
/**
* Generate docs using typedoc.
* @param src main source file
* @param out output directory
*/
export function generateDocs(src: string, out: string=".docs"): void {
exec(`typedoc --plugin extra-typedoc-theme "${src}" --out "${out}"`);
}
/**
* Publish docs to gh-pages.
* @param dir docs directory
*/
export function publishDocs(dir: string=".docs"): void {
var url = gitRemoteUrl();
var cwd = fs.mkdtempSync(path.join(os.tmpdir(), dir));
exec(`git clone ${url} "${cwd}"`);
try { exec(`git checkout gh-pages`, {cwd}); }
catch(e) { gitSetupBranch("gh-pages", {cwd}); }
exec(`rm -rf "${cwd}"/*`);
exec(`mv "${dir}"/* "${cwd}"/`);
gitCommitPush("", {cwd});
exec(`rm -rf ${cwd}`);
}
/**
* Get the reflection that is referred to.
* @param docs docs reflection
* @param r reflection
* @returns referred reflection, or the same if nothing is referred
*/
export function docsRefer<T=Reflection>(docs: ProjectReflection, r: T): T {
// @ts-ignore
if (!r.target) return r;
// @ts-ignore
return docsRefer(docs, docs.getReflectionById(r.target));
}
/**
* Get name of a reflection.
* @param r reflection
* @returns reflection name
*/
export function docsName(r: Reflection): string {
return r.name;
}
/**
* Get location of reflection.
* @param r reflection
* @returns location of reflection
*/
export function docsLocation(r: Reflection): string {
var [s] = (r as DeclarationReflection).sources || [];
return s==null? null : s.fileName + ":" + s.line.toString().padStart(6, "0");
}
/**
* Get flags of a reflection.
* @param r reflection
* @returns flags
*/
export function docsFlags(r: Reflection): ReflectionFlags {
return r.flags;
}
/**
* Get kind name of a reflection.
* @param r reflection
* @returns kind name
*/
export function docsKind(r: Reflection): string {
return ReflectionKind[r.kind];
}
function docsFindSignatures(r: Reflection): SignatureReflection[] {
// @ts-ignore
if (r.signatures) return r.signatures;
// @ts-ignore
if (r.declaration) return docsFindSignatures(r.declaration);
// @ts-ignore
if (r.type) return docsFindSignatures(r.type);
return [];
}
function docsFindComment(r: Reflection, sig: number=0): Comment {
if (r==null) return null;
if (r.comment) return r.comment;
return docsFindComment(docsFindSignatures(r)[sig]);
}
/**
* Get child count of a reflection.
* @param r reflection
* @returns child count
*/
export function docsChildCount(r: Reflection): number {
// @ts-ignore
return r.children? r.children.length : 0;
}
/**
* Get parameter count of a reflection (function).
* @param r reflection
* @returns parameter count
*/
export function docsParameterCount(r: Reflection): number {
// @ts-ignore
return r.parameters? r.parameters.length : 0;
}
/**
* Get signature count of a reflection.
* @param r reflection
* @returns signature count
*/
export function docsSignatureCount(r: Reflection): number {
return docsFindSignatures(r).length;
}
/**
* Get type name of a reflection.
* @param r reflection
* @returns type name
*/
export function docsType(r: Reflection, sig: number=0): string {
if (r==null) return null;
// @ts-ignore
if (r.type) return r.type.toString();
if (/class|interface|type/i.test(ReflectionKind[r.kind])) return r.name;
return docsType(docsFindSignatures(r)[sig]);
}
function contentText(ps: CommentDisplayPart[]): string {
var a = "";
for (var p of ps)
a += p.text;
return a;
}
/**
* Get description of a reflection.
* @param r reflection
* @param sig signature index
* @returns description/comment
*/
export function docsDescription(r: Reflection, sig: number=0): string {
var c = docsFindComment(r, sig), a = '';
if (c==null || c.summary==null) return null;
return contentText(c.summary).trim();
}
/**
* Get returns description of a reflection (function).
* @param r reflection
* @param sig signature index
* @returns returns description/comment
*/
export function docsReturns(r: Reflection, sig: number=0): string {
var c = docsFindComment(r, sig);
if (c==null) return null;
var t = c.getTag("@returns");
if (t==null) return null;
return contentText(t.content);
}
/** Details of a reflection. */
export interface DocsDetails {
/** Name of a reflection. */
name: string,
/** Location of reflection. */
location?: string,
/** Flags of a reflection. */
flags: ReflectionFlags,
/** Kind name of a reflection */
kind: string,
/** Type name of a reflection. */
type: string,
/** Description/comment of a reflection. */
description?: string,
/** Details of children/signatures/parameters of a reflection. */
children?: DocsDetails[],
/** Return details/comment of a reflection (function). */
returns?: string,
}
/**
* Get details of a reflection.
* @param r reflection
* @returns reflection details \{name, kind, type, description, params, returns\}
*/
export function docsDetails(r: Reflection): DocsDetails {
// @ts-ignore
var s: Reflection[] = r.children || r.parameters || docsFindSignatures(r);
return {
name: docsName(r),
location: docsLocation(r),
flags: docsFlags(r),
kind: docsKind(r),
type: docsType(r),
description: docsDescription(r),
children: s? s.map(docsDetails) : null,
returns: docsReturns(r),
};
}
/**
* Get details of a reflection, referring the necessary details.
* @param docs docs reflection
* @param r reflection
* @returns reflection details \{name, kind, type, description, params, returns\}
*/
export function docsReferDetails(docs: ProjectReflection, r: Reflection): DocsDetails {
var s = docsRefer(docs, r);
if (s===r) return docsDetails(r);
var kind = `${docsKind(r)}/${docsKind(s)}`;
return Object.assign(docsDetails(s), docsDetails(r), {kind});
}
/**
* Load docs from source file.
* @param entryPoints entry source files
* @returns docs reflection
*/
export function loadDocs(entryPoints?: string[]): ProjectReflection {
entryPoints = entryPoints || ["src/index.ts"];
var app = new typedoc.Application();
app.options.addReader(new typedoc.TSConfigReader());
app.options.addReader(new typedoc.TypeDocReader());
app.bootstrap({entryPoints});
return app.convert();
}
// WIKI
// ====
/** Markdown options. */
export interface MarkdownOptions {
/** GitHub owner name. [owner] */
owner?: string,
/** GitHub repo name. [repo] */
repo?: string,
/** Use wiki links? [false] */
useWiki?: boolean,
/** Namespace prefix. */
prefix?: string,
/** Wrap comment text after. [0 => unlimited] */
wrapText?: number,
/** Include types? [false] */
withType?: boolean,
/** Include root description? [false] */
withDescription?: boolean,
}
function wikiText(txt: string, short: boolean=false): string {
txt = txt.replace(/\{@\w+\s+(.*?)\}/g, "`$1`");
if (short) txt = txt.replace(/([\?\!\.])\s[\s\S]*/, "$1").replace(/\s*\n\s*/, " ");
return txt.trim();
}
function wikiDescription(txt: string, cols: number=0): string {
if (!txt) return "";
return wrapText(wikiText(txt), cols).split("\n").map(l => `// ${l}`).join("\n") + "\n";
}
function wikiFlagsPrefix(d: DocsDetails): string {
var a = "", f = d.flags;
if (f.isAbstract) a += "abstract ";
if (f.isReadonly) a += "readonly ";
if (f.isStatic) a += "static ";
return a;
}
function wikiVariable(d: DocsDetails, e: DocsDetails, o?: MarkdownOptions): string {
var text = wikiDescription(e?.description, o?.wrapText), f = d.flags;
var code = wikiFlagsPrefix(d) + (f.isConst? "const" : "var") + " ";
code += d.name + (o?.withType? ": "+d.type : "") + "\n";
return text + code;
}
function wikiProperty(d: DocsDetails, e: DocsDetails, o?: MarkdownOptions): string {
var text = wikiDescription(e?.description, o?.wrapText);
var code = wikiFlagsPrefix(d) + d.name + (o?.withType? ": "+d.type : "") + ",\n";
return text + code;
}
function wikiInterface(d: DocsDetails, e: DocsDetails, o?: MarkdownOptions): string {
var text = wikiDescription(e?.description, o?.wrapText);
var code = `interface ${d.name} {\n`;
for (var c of d.children || [])
code += indentText(wikiProperty(c, c, o), " ");