-
Notifications
You must be signed in to change notification settings - Fork 242
/
assembler.ts
3493 lines (3156 loc) · 107 KB
/
assembler.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 spec from '@jsii/spec';
import { PackageJson } from '@jsii/spec';
import * as Case from 'case';
import * as chalk from 'chalk';
import * as crypto from 'crypto';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import deepEqual = require('deep-equal');
import * as fs from 'fs-extra';
import * as log4js from 'log4js';
import * as path from 'path';
import * as ts from 'typescript';
import {
getReferencedDocParams,
parseSymbolDocumentation,
renderSymbolDocumentation,
TypeSystemHints,
} from './docs';
import { Emitter } from './emitter';
import { JsiiDiagnostic } from './jsii-diagnostic';
import * as literate from './literate';
import * as bindings from './node-bindings';
import { ProjectInfo } from './project-info';
import { isReservedName } from './reserved-words';
import { symbolIdentifier } from './symbol-id';
import { DeprecatedRemover } from './transforms/deprecated-remover';
import { DeprecationWarningsInjector } from './transforms/deprecation-warnings';
import { RuntimeTypeInfoInjector } from './transforms/runtime-info';
import { TsCommentReplacer } from './transforms/ts-comment-replacer';
import { combinedTransformers } from './transforms/utils';
import { Validator } from './validator';
import { SHORT_VERSION, VERSION } from './version';
import { enabledWarnings } from './warnings';
// eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
const sortJson = require('sort-json');
const LOG = log4js.getLogger('jsii/assembler');
/**
* The JSII Assembler consumes a ``ts.Program`` instance and emits a JSII assembly.
*/
export class Assembler implements Emitter {
private readonly commentReplacer = new TsCommentReplacer();
private readonly runtimeTypeInfoInjector: RuntimeTypeInfoInjector;
private readonly deprecatedRemover?: DeprecatedRemover;
private readonly warningsInjector?: DeprecationWarningsInjector;
private readonly mainFile: string;
private readonly tscRootDir?: string;
private _diagnostics = new Array<JsiiDiagnostic>();
private _deferred = new Array<DeferredRecord>();
private _types: { [fqn: string]: spec.Type } = {};
/** Map of Symbol to namespace export Symbol */
private readonly _submoduleMap = new Map<ts.Symbol, ts.Symbol>();
/**
* Submodule information
*
* Contains submodule information for all namespaces that have been seen
* across all assemblies (this and dependencies).
*
* Filtered to local submodules only at time of writing the assembly out to disk.
*/
private readonly _submodules = new Map<ts.Symbol, SubmoduleSpec>();
/**
* @param projectInfo information about the package being assembled
* @param program the TypeScript program to be assembled from
* @param stdlib the directory where the TypeScript stdlib is rooted
*/
public constructor(
public readonly projectInfo: ProjectInfo,
public readonly program: ts.Program,
public readonly stdlib: string,
options: AssemblerOptions = {},
) {
if (options.stripDeprecated) {
let allowlistedDeprecations: Set<string> | undefined;
if (options.stripDeprecatedAllowListFile) {
if (!fs.existsSync(options.stripDeprecatedAllowListFile)) {
throw new Error(
`--strip-deprecated file not found: ${options.stripDeprecatedAllowListFile}`,
);
}
allowlistedDeprecations = new Set<string>(
fs
.readFileSync(options.stripDeprecatedAllowListFile, 'utf8')
.split('\n'),
);
}
this.deprecatedRemover = new DeprecatedRemover(
this._typeChecker,
allowlistedDeprecations,
);
}
if (options.addDeprecationWarnings) {
this.warningsInjector = new DeprecationWarningsInjector(
this._typeChecker,
);
}
const dts = projectInfo.types;
let mainFile = dts.replace(/\.d\.ts(x?)$/, '.ts$1');
// If out-of-source build was configured (tsc's outDir and rootDir), the
// main file's path needs to be re-rooted from the outDir into the rootDir.
const tscOutDir = program.getCompilerOptions().outDir;
if (tscOutDir != null) {
mainFile = path.relative(tscOutDir, mainFile);
// rootDir may be set explicitly or not. If not, inferRootDir replicates
// tsc's behavior of using the longest prefix of all built source files.
this.tscRootDir =
program.getCompilerOptions().rootDir ?? inferRootDir(program);
if (this.tscRootDir != null) {
mainFile = path.join(this.tscRootDir, mainFile);
}
}
this.mainFile = path.resolve(projectInfo.projectRoot, mainFile);
this.runtimeTypeInfoInjector = new RuntimeTypeInfoInjector(
projectInfo.version,
);
}
public get customTransformers(): ts.CustomTransformers {
return combinedTransformers(
this.deprecatedRemover?.customTransformers ?? {},
this.runtimeTypeInfoInjector.makeTransformers(),
this.commentReplacer.makeTransformers(),
this.warningsInjector?.customTransformers ?? {},
);
}
private get _typeChecker(): ts.TypeChecker {
return this.program.getTypeChecker();
}
/**
* Attempt emitting the JSII assembly for the program.
*
* @return the result of the assembly emission.
*/
public async emit(): Promise<ts.EmitResult> {
this._diagnostics = [];
if (!this.projectInfo.description) {
this._diagnostics.push(
JsiiDiagnostic.JSII_0001_PKG_MISSING_DESCRIPTION.createDetached(),
);
}
if (!this.projectInfo.homepage) {
this._diagnostics.push(
JsiiDiagnostic.JSII_0002_PKG_MISSING_HOMEPAGE.createDetached(),
);
}
const readme = await _loadReadme.call(this);
if (readme == null) {
this._diagnostics.push(
JsiiDiagnostic.JSII_0003_MISSING_README.createDetached(),
);
}
const docs = _loadDocs.call(this);
this._types = {};
this._deferred = [];
const visitPromises = new Array<Promise<any>>();
const sourceFile = this.program.getSourceFile(this.mainFile);
if (sourceFile == null) {
this._diagnostics.push(
JsiiDiagnostic.JSII_0004_COULD_NOT_FIND_ENTRYPOINT.createDetached(
this.mainFile,
),
);
} else {
await this._registerDependenciesNamespaces(sourceFile);
if (LOG.isTraceEnabled()) {
LOG.trace(
`Processing source file: ${chalk.blue(
path.relative(this.projectInfo.projectRoot, sourceFile.fileName),
)}`,
);
}
const symbol = this._typeChecker.getSymbolAtLocation(sourceFile);
if (symbol) {
const moduleExports = this._typeChecker.getExportsOfModule(symbol);
await Promise.all(
moduleExports.map((item) =>
this._registerNamespaces(item, this.projectInfo.projectRoot),
),
);
for (const node of moduleExports) {
visitPromises.push(
this._visitNode(
node.declarations[0],
new EmitContext([], this.projectInfo.stability),
),
);
}
}
}
await Promise.all(visitPromises);
this.callDeferredsInOrder();
// Skip emitting if any diagnostic message is an error
if (
this._diagnostics.find(
(diag) => diag.category === ts.DiagnosticCategory.Error,
) != null
) {
LOG.debug('Skipping emit due to errors.');
// Clearing ``this._types`` to allow contents to be garbage-collected.
delete this._types;
try {
return { diagnostics: this._diagnostics, emitSkipped: true };
} finally {
// Clearing ``this._diagnostics`` to allow contents to be garbage-collected.
delete this._diagnostics;
}
}
const jsiiVersion =
this.projectInfo.jsiiVersionFormat === 'short' ? SHORT_VERSION : VERSION;
const assembly: spec.Assembly = {
schema: spec.SchemaVersion.LATEST,
name: this.projectInfo.name,
version: this.projectInfo.version,
description: this.projectInfo.description ?? this.projectInfo.name,
license: this.projectInfo.license,
keywords: this.projectInfo.keywords,
homepage: this.projectInfo.homepage ?? this.projectInfo.repository.url,
author: this.projectInfo.author,
contributors: this.projectInfo.contributors && [
...this.projectInfo.contributors,
],
repository: this.projectInfo.repository,
dependencies: noEmptyDict({
...this.projectInfo.dependencies,
...this.projectInfo.peerDependencies,
}),
dependencyClosure: noEmptyDict(
toDependencyClosure(this.projectInfo.dependencyClosure),
),
bundled: this.projectInfo.bundleDependencies,
types: this._types,
submodules: noEmptyDict(toSubmoduleDeclarations(this.mySubmodules())),
targets: this.projectInfo.targets,
metadata: {
...this.projectInfo.metadata,
// Downstream consumers need this to map a symbolId in the outDir to a
// symbolId in the rootDir.
tscRootDir: this.tscRootDir,
},
docs,
readme,
jsiiVersion,
bin: this.projectInfo.bin,
fingerprint: '<TBD>',
};
if (this.deprecatedRemover) {
this._diagnostics.push(...this.deprecatedRemover.removeFrom(assembly));
}
if (this.warningsInjector) {
const jsiiMetadata = {
...(assembly.metadata?.jsii ?? {}),
...{ compiledWithDeprecationWarnings: true },
};
if (assembly.metadata) {
assembly.metadata.jsii = jsiiMetadata;
} else {
assembly.metadata = { jsii: jsiiMetadata };
}
this.warningsInjector.process(assembly, this.projectInfo);
}
const validator = new Validator(this.projectInfo, assembly);
const validationResult = await validator.emit();
if (!validationResult.emitSkipped) {
const assemblyPath = path.join(this.projectInfo.projectRoot, '.jsii');
LOG.trace(`Emitting assembly: ${chalk.blue(assemblyPath)}`);
await fs.writeJson(assemblyPath, _fingerprint(assembly), {
encoding: 'utf8',
spaces: 2,
});
}
try {
return {
diagnostics: [...this._diagnostics, ...validationResult.diagnostics],
emitSkipped: validationResult.emitSkipped,
};
} finally {
// Clearing ``this._types`` to allow contents to be garbage-collected.
delete this._types;
// Clearing ``this._diagnostics`` to allow contents to be garbage-collected.
delete this._diagnostics;
}
async function _loadReadme(this: Assembler) {
// Search for `README.md` in a case-insensitive way
const fileName = (await fs.readdir(this.projectInfo.projectRoot)).find(
(file) => file.toLocaleLowerCase() === 'readme.md',
);
if (fileName == null) {
return undefined;
}
const readmePath = path.join(this.projectInfo.projectRoot, fileName);
return loadAndRenderReadme(readmePath, this.projectInfo.projectRoot);
}
function _loadDocs(this: Assembler): spec.Docs | undefined {
if (!this.projectInfo.stability && !this.projectInfo.deprecated) {
return undefined;
}
const deprecated = this.projectInfo.deprecated;
const stability = this.projectInfo.stability;
return { deprecated, stability };
}
}
/**
* Defer a callback until a (set of) types are available
*
* This is a helper function around _defer() which encapsulates the _dereference
* action (which is basically the majority use case for _defer anyway).
*
* Will not invoke the function with any 'undefined's; an error will already have been emitted in
* that case anyway.
*
* @param fqn FQN of the current type (the type that has a dependency on baseTypes)
* @param baseTypes Array of type references to be looked up
* @param referencingNode Node to report a diagnostic on if we fail to look up a t ype
* @param cb Callback to be invoked with the Types corresponding to the TypeReferences in baseTypes
*/
private _deferUntilTypesAvailable(
fqn: string,
baseTypes: Array<string | spec.NamedTypeReference>,
referencingNode: ts.Node,
cb: (...xs: spec.Type[]) => void,
) {
// We can do this one eagerly
if (baseTypes.length === 0) {
cb();
return;
}
const baseFqns = baseTypes.map((bt) =>
typeof bt === 'string' ? bt : bt.fqn,
);
this._defer(fqn, baseFqns, () => {
const resolved = baseFqns
.map((x) => this._dereference(x, referencingNode))
.filter((x) => x !== undefined);
if (resolved.length > 0) {
cb(...(resolved as spec.Type[]));
}
});
}
/**
* Defer checks for after the program has been entirely processed; useful for verifying type references that may not
* have been discovered yet, and verifying properties about them.
*
* The callback is guaranteed to be executed only after all deferreds for all types in 'dependedFqns' have
* been executed.
*
* @param fqn FQN of the current type.
* @param dependedFqns List of FQNs of types this callback depends on. All deferreds for all
* @param cb the function to be called in a deferred way. It will be bound with ``this``, so it can depend on using
* ``this``.
*/
private _defer(fqn: string, dependedFqns: string[], cb: () => void) {
this._deferred.push({ fqn, dependedFqns, cb: cb.bind(this) });
}
/**
* Obtains the ``spec.Type`` for a given ``spec.NamedTypeReference``.
*
* @param ref the type reference to be de-referenced
*
* @returns the de-referenced type, if it was found, otherwise ``undefined``.
*/
private _dereference(
ref: string | spec.NamedTypeReference,
referencingNode: ts.Node | undefined,
): spec.Type | undefined {
if (typeof ref !== 'string') {
ref = ref.fqn;
}
const [assm] = ref.split('.');
let type;
if (assm === this.projectInfo.name) {
type = this._types[ref];
} else {
const assembly = this.projectInfo.dependencyClosure.find(
(dep) => dep.name === assm,
);
type = assembly?.types?.[ref];
// since we are exposing a type of this assembly in this module's public API,
// we expect it to appear as a peer dependency instead of a normal dependency.
if (assembly) {
if (!(assembly.name in this.projectInfo.peerDependencies)) {
this._diagnostics.push(
JsiiDiagnostic.JSII_0005_MISSING_PEER_DEPENDENCY.create(
referencingNode!, // Cheating here for now, until the referencingNode can be made required
assembly.name,
ref,
),
);
}
}
}
if (!type) {
this._diagnostics.push(
JsiiDiagnostic.JSII_9002_UNRESOLVEABLE_TYPE.create(
referencingNode!, // Cheating here for now, until the referencingNode can be made required
ref,
),
);
}
return type;
}
/**
* Compute the JSII fully qualified name corresponding to a ``ts.Type`` instance. If for any reason a name cannot be
* computed for the type, a marker is returned instead, and an ``ts.DiagnosticCategory.Error`` diagnostic is
* inserted in the assembler context.
*
* @param type the type for which a JSII fully qualified name is needed.
* @param typeAnnotationNode the type annotation for which this FQN is generated. This is used for attaching the error
* marker. When there is no explicit type annotation (e.g: inferred method return type), the
* preferred substitute is the "type-inferred" element's name.
* @param typeUse the reason why this type was resolved (e.g: "return type")
* @param isThisType whether this type was specified or inferred as "this" or not
*
* @returns the FQN of the type, or some "unknown" marker.
*/
private async _getFQN(
type: ts.Type,
typeAnnotationNode: ts.Node,
typeUse: TypeUseKind,
isThisType: boolean,
): Promise<string> {
const sym = symbolFromType(type, this._typeChecker);
const typeDeclaration = sym.valueDeclaration ?? sym.declarations?.[0];
// Set to true to prevent further adding of Error diagnostics for known-bad reference
let hasError = false;
if (this._isPrivateOrInternal(sym)) {
// Check if this type is "this" (explicit or inferred method return type).
this._diagnostics.push(
JsiiDiagnostic.JSII_3001_EXPOSED_INTERNAL_TYPE.create(
typeAnnotationNode,
sym,
isThisType,
typeUse,
).addRelatedInformation(
typeDeclaration,
`The referenced type is declared here`,
),
);
hasError = true;
}
const tsName = this._typeChecker.getFullyQualifiedName(sym);
const groups = /^"([^"]+)"\.(.*)$/.exec(tsName);
if (!groups) {
if (!hasError) {
this._diagnostics.push(
JsiiDiagnostic.JSII_3001_EXPOSED_INTERNAL_TYPE.create(
typeAnnotationNode,
sym,
isThisType,
typeUse,
).addRelatedInformation(
typeDeclaration,
`The referenced type is declared here`,
),
);
hasError = true;
}
return tsName;
}
const [, modulePath, typeName] = groups;
const pkg = await findPackageInfo(modulePath);
if (!pkg) {
if (!hasError) {
this._diagnostics.push(
JsiiDiagnostic.JSII_9003_UNRESOLVEABLE_MODULE.create(
typeAnnotationNode,
modulePath,
).addRelatedInformation(
typeDeclaration,
`The referenced type is declared here`,
),
);
hasError = true;
}
return `unknown.${typeName}`;
}
// If the symbol comes from an assembly whose submodules we've already
// spidered (or from the current assembly), look up there. This relies
// on an entry-point import of the library having been done first
// (`import * as x from 'module-root';`)
const submodule = this._submoduleMap.get(sym);
if (submodule != null) {
const submoduleNs = this._submodules.get(submodule)!.fqnResolutionPrefix;
return `${submoduleNs}.${typeName}`;
}
// This is the fallback: in case we can't find a symbolId for the given
// type, we're return this value. This is for backwards compatibility with
// modules that haven't been compiled to have symbolId support. Those also
// most likely won't be using submodules so this legacy guess will be correct.
const fallbackFqn = `${pkg.name}.${typeName}`;
// If the type is coming from the current module, we won't find it in a dependency
if (pkg.name === this.projectInfo.name) {
return fallbackFqn;
}
// Otherwise look up the symbol identifier in the dependency assemblies
// This is now the preferred mechanism but we can't do this as the only mechanism,
// as we may still have compile against very old assemblies that don't have a
// symbol identifier table at all.
const dep = this.projectInfo.dependencyClosure.find(
(d) => d.name === pkg.name,
);
if (!dep) {
this._diagnostics.push(
JsiiDiagnostic.JSII_9000_UNKNOWN_MODULE.create(
typeAnnotationNode,
pkg.name,
),
);
return fallbackFqn;
}
const symbolId = symbolIdentifier(this._typeChecker, sym, {
assembly: dep,
});
const fqn =
(dep && symbolId ? symbolIdIndex(dep)[symbolId] : undefined) ??
fallbackFqn;
if (!fqn || !this._dereference({ fqn }, sym.valueDeclaration)) {
if (!hasError) {
this._diagnostics.push(
JsiiDiagnostic.JSII_3002_USE_OF_UNEXPORTED_FOREIGN_TYPE.create(
typeAnnotationNode,
fqn ?? tsName,
typeUse,
pkg,
).addRelatedInformation(
typeDeclaration,
`The referenced type is declared here`,
),
);
hasError = true;
}
}
return fqn;
}
/**
* For all modules in the dependency closure, crawl their exports to register
* the submodules they contain.
*
* @param entryPoint the main source file for the currently compiled module.
*/
private async _registerDependenciesNamespaces(entryPoint: ts.SourceFile) {
for (const assm of this.projectInfo.dependencyClosure) {
const resolved = ts.resolveModuleName(
assm.name,
entryPoint.fileName,
this.program.getCompilerOptions(),
ts.sys,
);
// If we can't resolve the module name, simply ignore it (TypeScript compilation likely failed)
if (resolved.resolvedModule == null) {
continue;
}
const source = this.program.getSourceFile(
resolved.resolvedModule.resolvedFileName,
);
const depMod = source && this._typeChecker.getSymbolAtLocation(source);
// It's unlikely, but if we can't get the SourceFile here, ignore it (TypeScript compilation probably failed)
if (depMod == null) {
continue;
}
const depRoot = packageRoot(resolved.resolvedModule.resolvedFileName);
for (const symbol of this._typeChecker.getExportsOfModule(depMod)) {
// eslint-disable-next-line no-await-in-loop
await this._registerNamespaces(symbol, depRoot);
}
}
function packageRoot(file: string): string {
const parent = path.dirname(file);
if (path.basename(parent) === 'node_modules' || parent === file) {
return file;
}
return packageRoot(parent);
}
}
private async _registerNamespaces(
symbol: ts.Symbol,
packageRoot: string,
): Promise<void> {
const declaration = symbol.valueDeclaration ?? symbol.declarations[0];
if (declaration == null) {
// Nothing to do here...
return;
}
if (ts.isModuleDeclaration(declaration)) {
// Looks like:
//
// export some_namespace {
// ...
// }
//
// No way to configure targets
const { fqn, fqnResolutionPrefix } = await qualifiedNameOf.call(
this,
symbol,
true,
);
this._submodules.set(symbol, {
fqn,
fqnResolutionPrefix,
symbolId: symbolIdentifier(this._typeChecker, symbol),
locationInModule: this.declarationLocation(declaration),
});
await this._addToSubmodule(symbol, symbol, packageRoot);
return;
}
if (!ts.isNamespaceExport(declaration)) {
// Nothing to do here...
return;
}
const moduleSpecifier = declaration.parent.moduleSpecifier;
if (moduleSpecifier == null || !ts.isStringLiteral(moduleSpecifier)) {
// There is a grammar error here, so we'll let tsc report this for us.
return;
}
const resolution = ts.resolveModuleName(
moduleSpecifier.text,
declaration.getSourceFile().fileName,
this.program.getCompilerOptions(),
ts.sys,
);
if (resolution.resolvedModule == null) {
// Unresolvable module... We'll let tsc report this for us.
return;
}
if (
// We're not looking into a dependency's namespace exports, and the resolution says it's external
(packageRoot === this.projectInfo.projectRoot &&
resolution.resolvedModule.isExternalLibraryImport) ||
// Or the module resolves outside of the current dependency's tree entirely
!isUnder(resolution.resolvedModule.resolvedFileName, packageRoot) ||
// Or the module is under one the current dependency's node_modules subtree
resolution.resolvedModule.resolvedFileName
.split('/') // Separator is always '/', even on Windows
.filter((entry) => entry === 'node_modules').length !==
packageRoot.split('/').filter((entry) => entry === 'node_modules')
.length
) {
// External re-exports are "pure-javascript" sugar; they need not be
// represented in the jsii Assembly since the types in there will be
// resolved through dependencies.
return;
}
const sourceFile = this.program.getSourceFile(
resolution.resolvedModule.resolvedFileName,
)!;
const sourceModule = this._typeChecker.getSymbolAtLocation(sourceFile);
// If there's no module, it's a syntax error, and tsc will have reported it for us.
if (sourceModule) {
if (
symbol.name !== Case.camel(symbol.name) &&
symbol.name !== Case.snake(symbol.name)
) {
this._diagnostics.push(
JsiiDiagnostic.JSII_8004_SUBMOULE_NAME_CASING.create(
declaration.name,
symbol.name,
),
);
}
const { fqn, fqnResolutionPrefix } = await qualifiedNameOf.call(
this,
symbol,
);
const targets = await loadSubmoduleTargetConfig(sourceFile.fileName);
const readme = await loadSubmoduleReadMe(
sourceFile.fileName,
this.projectInfo.projectRoot,
);
this._submodules.set(symbol, {
fqn,
fqnResolutionPrefix,
targets,
readme,
symbolId: symbolIdentifier(this._typeChecker, symbol),
locationInModule: this.declarationLocation(declaration),
});
await this._addToSubmodule(symbol, sourceModule, packageRoot);
}
async function qualifiedNameOf(
this: Assembler,
sym: ts.Symbol,
inlineNamespace = false,
): Promise<{ fqn: string; fqnResolutionPrefix: string }> {
if (this._submoduleMap.has(sym)) {
const parent = this._submodules.get(this._submoduleMap.get(sym)!)!;
const fqn = `${parent.fqn}.${sym.name}`;
return {
fqn,
fqnResolutionPrefix: inlineNamespace
? parent.fqnResolutionPrefix
: fqn,
};
}
const symbolLocation = sym
.getDeclarations()?.[0]
?.getSourceFile()?.fileName;
const pkgInfo = symbolLocation
? await findPackageInfo(symbolLocation)
: undefined;
const assemblyName: string = pkgInfo?.name ?? this.projectInfo.name;
const fqn = `${assemblyName}.${sym.name}`;
return {
fqn,
fqnResolutionPrefix: inlineNamespace ? this.projectInfo.name : fqn,
};
}
async function loadSubmoduleTargetConfig(
submoduleMain: string,
): Promise<SubmoduleSpec['targets']> {
const jsiirc = path.resolve(submoduleMain, '..', '.jsiirc.json');
if (!(await fs.pathExists(jsiirc))) {
return undefined;
}
const data = await fs.readJson(jsiirc);
return data.targets;
}
/**
* Load the README for the given submodule
*
* If the submodule is loaded from a complete directory (determined by the 'main'
* file ending in `index.[d.]ts`, then we load `README.md` in that same directory.
*
* If the submodule is loaded from a file, like `mymodule.[d.]ts`, we will load
* `mymodule.README.md`.
*/
async function loadSubmoduleReadMe(
submoduleMain: string,
projectRoot: string,
): Promise<SubmoduleSpec['readme']> {
const fileBase = path.basename(submoduleMain).replace(/(\.d)?\.ts$/, '');
const readMeName =
fileBase === 'index' ? `README.md` : `${fileBase}.README.md`;
const fullPath = path.join(path.dirname(submoduleMain), readMeName);
return loadAndRenderReadme(fullPath, projectRoot);
}
}
/**
* Registers Symbols to a particular submodule. This is used to associate
* declarations exported by an `export * as ns from 'moduleLike';` statement
* so that they can subsequently be correctly namespaced.
*
* @param ns the symbol that identifies the submodule.
* @param moduleLike the module-like symbol bound to the submodule.
* @param packageRoot the root of the package being traversed.
*/
private async _addToSubmodule(
ns: ts.Symbol,
moduleLike: ts.Symbol,
packageRoot: string,
) {
// For each symbol exported by the moduleLike, map it to the ns submodule.
for (const symbol of this._typeChecker.getExportsOfModule(moduleLike)) {
if (this._submoduleMap.has(symbol)) {
const currNs = this._submoduleMap.get(symbol)!;
// Checking if there's been two submodules exporting the same symbol,
// which is illegal. We can tell if the currently registered symbol has
// a different name than the one we're currently trying to register in.
if (currNs.name !== ns.name) {
const currNsDecl = currNs.valueDeclaration ?? currNs.declarations[0];
const nsDecl = ns.valueDeclaration ?? ns.declarations[0];
// Make sure the error message always lists causes in the same order
const refs = [
{ decl: currNsDecl, name: currNs.name } as const,
{ decl: nsDecl, name: ns.name } as const,
].sort(({ name: l }, { name: r }) => l.localeCompare(r));
this._diagnostics.push(
JsiiDiagnostic.JSII_3003_SYMBOL_IS_EXPORTED_TWICE.create(
_nameOrDeclarationNode(symbol),
refs[0].name,
refs[1].name,
)
.addRelatedInformation(
refs[0].decl,
`Symbol is exported under the "${refs[0].name}" submodule`,
)
.addRelatedInformation(
refs[1].decl,
`Symbol is exported under the "${refs[1].name}" submodule`,
),
);
}
// Found two re-exports, which is odd, but they use the same submodule,
// so it's probably okay? That's likely a tsc error, which will have
// been reported for us already anyway.
continue;
}
this._submoduleMap.set(symbol, ns);
// If the exported symbol has any declaration, and that delcaration is of
// an entity that can have nested declarations of interest to jsii
// (classes, interfaces, enums, modules), we need to also associate those
// nested symbols to the submodule (or they won't be named correctly!)
const decl = symbol.declarations?.[0];
if (decl != null) {
if (
ts.isClassDeclaration(decl) ||
ts.isInterfaceDeclaration(decl) ||
ts.isEnumDeclaration(decl)
) {
const type = this._typeChecker.getTypeAtLocation(decl);
if (isSingleValuedEnum(type, this._typeChecker)) {
// type.symbol !== symbol, because symbol is the enum itself, but
// since it's single-valued, the TypeChecker will only show us the
// value's symbol later on.
this._submoduleMap.set(type.symbol, ns);
}
if (type.symbol.exports) {
// eslint-disable-next-line no-await-in-loop
await this._addToSubmodule(ns, symbol, packageRoot);
}
} else if (ts.isModuleDeclaration(decl)) {
// eslint-disable-next-line no-await-in-loop
await this._registerNamespaces(symbol, packageRoot);
} else if (ts.isNamespaceExport(decl)) {
// eslint-disable-next-line no-await-in-loop
await this._registerNamespaces(symbol, packageRoot);
}
}
}
}
/**
* Register exported types in ``this.types``.
*
* @param node a node found in a module
* @param namePrefix the prefix for the types' namespaces
*/
// eslint-disable-next-line complexity
private async _visitNode(
node: ts.Declaration,
context: EmitContext,
): Promise<spec.Type[]> {
if (ts.isNamespaceExport(node)) {
// export * as ns from 'module';
// Note: the "ts.NamespaceExport" refers to the "export * as ns" part of
// the statement only. We must refer to `node.parent` in order to be able
// to access the module specifier ("from 'module'") part.
const symbol = this._typeChecker.getSymbolAtLocation(
node.parent.moduleSpecifier!,
)!;
if (LOG.isTraceEnabled()) {
LOG.trace(
`Entering submodule: ${chalk.cyan(
[...context.namespace, symbol.name].join('.'),
)}`,
);
}
const nsContext = context.appendNamespace(node.name.text);
const promises = new Array<Promise<spec.Type[]>>();
for (const child of this._typeChecker.getExportsOfModule(symbol)) {
promises.push(this._visitNode(child.declarations[0], nsContext));
}
const allTypes = flattenPromises(promises);
if (LOG.isTraceEnabled()) {
LOG.trace(
`Leaving submodule: ${chalk.cyan(
[...context.namespace, symbol.name].join('.'),
)}`,
);
}
return allTypes;
}
if (ts.isExportSpecifier(node)) {
// This is what happens when one does `export { Symbol } from "./location";`
// ExportSpecifier: ~~~~~~
const resolvedSymbol =
this._typeChecker.getExportSpecifierLocalTargetSymbol(node);
if (!resolvedSymbol) {
// A grammar error, compilation will already have failed
return [];
}
return this._visitNode(
resolvedSymbol.valueDeclaration ?? resolvedSymbol.declarations[0],
context,
);
}
if ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export) === 0) {
return [];
}
let jsiiType: spec.Type | undefined;
if (ts.isClassDeclaration(node) && _isExported(node)) {
// export class Name { ... }
this._validateHeritageClauses(node.heritageClauses);
jsiiType = await this._visitClass(
this._typeChecker.getTypeAtLocation(node),
context,
);
if (jsiiType) {
this.registerExportedClassFqn(node, jsiiType.fqn);
}
} else if (ts.isInterfaceDeclaration(node) && _isExported(node)) {
// export interface Name { ... }
this._validateHeritageClauses(node.heritageClauses);
jsiiType = await this._visitInterface(
this._typeChecker.getTypeAtLocation(node),
context,
);
} else if (ts.isEnumDeclaration(node) && _isExported(node)) {
// export enum Name { ... }
jsiiType = await this._visitEnum(
this._typeChecker.getTypeAtLocation(node),
context,
);
} else if (ts.isModuleDeclaration(node)) {
// export namespace name { ... }
const name = node.name.getText();
const symbol = this._typeChecker.getSymbolAtLocation(node.name)!;
if (LOG.isTraceEnabled()) {
LOG.trace(
`Entering namespace: ${chalk.cyan(
[...context.namespace, name].join('.'),
)}`,
);
}
const allTypesPromises = new Array<Promise<spec.Type[]>>();
for (const prop of this._typeChecker.getExportsOfModule(symbol)) {
allTypesPromises.push(
this._visitNode(