@teambit/typescript 0.0.555 → 0.0.556
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.
- package/package.json +23 -17
- package/cmds/init.cmd.ts +0 -0
- package/compiler-options.ts +0 -27
- package/index.ts +0 -5
- package/package-tar/teambit-typescript-0.0.555.tgz +0 -0
- package/tsconfig.default.json +0 -25
- package/tsconfig.json +0 -34
- package/types/asset.d.ts +0 -29
- package/types/style.d.ts +0 -42
- package/typescript.aspect.ts +0 -5
- package/typescript.compiler.spec.ts +0 -63
- package/typescript.compiler.ts +0 -293
- package/typescript.composition.tsx +0 -7
- package/typescript.docs.mdx +0 -8
- package/typescript.extractor.ts +0 -33
- package/typescript.main.runtime.ts +0 -165
- package/typescript.parser.spec.ts +0 -129
- package/typescript.parser.ts +0 -102
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teambit/typescript",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.556",
|
|
4
4
|
"homepage": "https://bit.dev/teambit/typescript/typescript",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"componentId": {
|
|
7
7
|
"scope": "teambit.typescript",
|
|
8
8
|
"name": "typescript",
|
|
9
|
-
"version": "0.0.
|
|
9
|
+
"version": "0.0.556"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@teambit/harmony": "0.2.11",
|
|
@@ -16,18 +16,18 @@
|
|
|
16
16
|
"p-map-series": "2.1.0",
|
|
17
17
|
"@babel/runtime": "7.12.18",
|
|
18
18
|
"core-js": "^3.0.0",
|
|
19
|
-
"@teambit/compiler": "0.0.
|
|
20
|
-
"@teambit/typescript.modules.ts-config-mutator": "0.0.
|
|
21
|
-
"@teambit/bit-error": "0.0.
|
|
22
|
-
"@teambit/builder": "0.0.
|
|
23
|
-
"@teambit/isolator": "0.0.
|
|
24
|
-
"@teambit/logger": "0.0.
|
|
25
|
-
"@teambit/component": "0.0.
|
|
26
|
-
"@teambit/schema": "0.0.
|
|
27
|
-
"@teambit/cli": "0.0.
|
|
28
|
-
"@teambit/pkg": "0.0.
|
|
29
|
-
"@teambit/ts-server": "0.0.
|
|
30
|
-
"@teambit/workspace": "0.0.
|
|
19
|
+
"@teambit/compiler": "0.0.556",
|
|
20
|
+
"@teambit/typescript.modules.ts-config-mutator": "0.0.44",
|
|
21
|
+
"@teambit/bit-error": "0.0.373",
|
|
22
|
+
"@teambit/builder": "0.0.556",
|
|
23
|
+
"@teambit/isolator": "0.0.556",
|
|
24
|
+
"@teambit/logger": "0.0.472",
|
|
25
|
+
"@teambit/component": "0.0.556",
|
|
26
|
+
"@teambit/schema": "0.0.556",
|
|
27
|
+
"@teambit/cli": "0.0.387",
|
|
28
|
+
"@teambit/pkg": "0.0.556",
|
|
29
|
+
"@teambit/ts-server": "0.0.10",
|
|
30
|
+
"@teambit/workspace": "0.0.556"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"chai": "4.3.0",
|
|
@@ -39,10 +39,10 @@
|
|
|
39
39
|
"@types/jest": "^26.0.0",
|
|
40
40
|
"@types/react-dom": "^17.0.5",
|
|
41
41
|
"@types/node": "12.20.4",
|
|
42
|
-
"@teambit/typescript.aspect-docs.typescript": "0.0.
|
|
42
|
+
"@teambit/typescript.aspect-docs.typescript": "0.0.106"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@teambit/legacy": "1.0.
|
|
45
|
+
"@teambit/legacy": "1.0.173",
|
|
46
46
|
"react-dom": "^16.8.0 || ^17.0.0",
|
|
47
47
|
"react": "^16.8.0 || ^17.0.0"
|
|
48
48
|
},
|
|
@@ -70,12 +70,18 @@
|
|
|
70
70
|
"react": "-"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
|
-
"@teambit/legacy": "1.0.
|
|
73
|
+
"@teambit/legacy": "1.0.173",
|
|
74
74
|
"react-dom": "^16.8.0 || ^17.0.0",
|
|
75
75
|
"react": "^16.8.0 || ^17.0.0"
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
},
|
|
79
|
+
"files": [
|
|
80
|
+
"dist",
|
|
81
|
+
"!dist/tsconfig.tsbuildinfo",
|
|
82
|
+
"README.md",
|
|
83
|
+
"README.mdx"
|
|
84
|
+
],
|
|
79
85
|
"private": false,
|
|
80
86
|
"engines": {
|
|
81
87
|
"node": ">=12.22.0"
|
package/cmds/init.cmd.ts
DELETED
|
File without changes
|
package/compiler-options.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import type { CompilerOptions } from '@teambit/compiler';
|
|
2
|
-
|
|
3
|
-
export type TypeScriptCompilerOptions = {
|
|
4
|
-
/**
|
|
5
|
-
* tsconfig to use during compilation.
|
|
6
|
-
*/
|
|
7
|
-
tsconfig: Record<string, any>;
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* path for .d.ts files to include during build.
|
|
11
|
-
*/
|
|
12
|
-
types: string[];
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Run the compiler for .js files. this will only affect whether to run the compiler on the files
|
|
16
|
-
* or not. It won't change the tsconfig to support or not support js files.
|
|
17
|
-
*/
|
|
18
|
-
compileJs?: boolean;
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Run the compiler for .js files. this will only affect whether to run the compiler on the files
|
|
22
|
-
* or not. It won't change the tsconfig to support or not support jsx files.
|
|
23
|
-
*/
|
|
24
|
-
compileJsx?: boolean;
|
|
25
|
-
} & Partial<CompilerOptions>;
|
|
26
|
-
|
|
27
|
-
export type TsCompilerOptionsWithoutTsConfig = Omit<TypeScriptCompilerOptions, 'tsconfig'>;
|
package/index.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
export { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
|
|
2
|
-
export { TypescriptCompiler } from './typescript.compiler';
|
|
3
|
-
export type { TypescriptMain, TsConfigTransformer } from './typescript.main.runtime';
|
|
4
|
-
export type { TypeScriptCompilerOptions, TsCompilerOptionsWithoutTsConfig } from './compiler-options';
|
|
5
|
-
export { TypescriptAspect } from './typescript.aspect';
|
|
Binary file
|
package/tsconfig.default.json
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "es2015",
|
|
4
|
-
"module": "commonjs",
|
|
5
|
-
"jsx": "react",
|
|
6
|
-
"composite": true,
|
|
7
|
-
"declaration": true,
|
|
8
|
-
"sourceMap": true,
|
|
9
|
-
"skipLibCheck": true,
|
|
10
|
-
"outDir": "dist",
|
|
11
|
-
"rootDir": ".",
|
|
12
|
-
"esModuleInterop": true,
|
|
13
|
-
"experimentalDecorators": true,
|
|
14
|
-
"emitDecoratorMetadata": true,
|
|
15
|
-
"strict": true,
|
|
16
|
-
"moduleResolution": "node",
|
|
17
|
-
"noImplicitAny": false,
|
|
18
|
-
"removeComments": true,
|
|
19
|
-
"preserveConstEnums": true,
|
|
20
|
-
"resolveJsonModule": true
|
|
21
|
-
},
|
|
22
|
-
"exclude": [
|
|
23
|
-
"dist"
|
|
24
|
-
]
|
|
25
|
-
}
|
package/tsconfig.json
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"lib": [
|
|
4
|
-
"es2019",
|
|
5
|
-
"DOM",
|
|
6
|
-
"ES6",
|
|
7
|
-
"DOM.Iterable",
|
|
8
|
-
"ScriptHost"
|
|
9
|
-
],
|
|
10
|
-
"target": "es2015",
|
|
11
|
-
"module": "commonjs",
|
|
12
|
-
"jsx": "react",
|
|
13
|
-
"declaration": true,
|
|
14
|
-
"sourceMap": true,
|
|
15
|
-
"skipLibCheck": true,
|
|
16
|
-
"moduleResolution": "node",
|
|
17
|
-
"esModuleInterop": true,
|
|
18
|
-
"outDir": "dist",
|
|
19
|
-
"composite": true,
|
|
20
|
-
"emitDeclarationOnly": true,
|
|
21
|
-
"experimentalDecorators": true,
|
|
22
|
-
"emitDecoratorMetadata": true,
|
|
23
|
-
"allowSyntheticDefaultImports": true,
|
|
24
|
-
"strictPropertyInitialization": false,
|
|
25
|
-
"strict": true,
|
|
26
|
-
"noImplicitAny": false,
|
|
27
|
-
"rootDir": ".",
|
|
28
|
-
"preserveConstEnums": true,
|
|
29
|
-
"resolveJsonModule": true
|
|
30
|
-
},
|
|
31
|
-
"exclude": [
|
|
32
|
-
"dist"
|
|
33
|
-
]
|
|
34
|
-
}
|
package/types/asset.d.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
declare module '*.png' {
|
|
2
|
-
const value: any;
|
|
3
|
-
export = value;
|
|
4
|
-
}
|
|
5
|
-
declare module '*.svg' {
|
|
6
|
-
import type { FunctionComponent, SVGProps } from 'react';
|
|
7
|
-
|
|
8
|
-
export const ReactComponent: FunctionComponent<SVGProps<SVGSVGElement> & { title?: string }>;
|
|
9
|
-
const src: string;
|
|
10
|
-
export default src;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
// @TODO Gilad
|
|
14
|
-
declare module '*.jpg' {
|
|
15
|
-
const value: any;
|
|
16
|
-
export = value;
|
|
17
|
-
}
|
|
18
|
-
declare module '*.jpeg' {
|
|
19
|
-
const value: any;
|
|
20
|
-
export = value;
|
|
21
|
-
}
|
|
22
|
-
declare module '*.gif' {
|
|
23
|
-
const value: any;
|
|
24
|
-
export = value;
|
|
25
|
-
}
|
|
26
|
-
declare module '*.bmp' {
|
|
27
|
-
const value: any;
|
|
28
|
-
export = value;
|
|
29
|
-
}
|
package/types/style.d.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
declare module '*.module.css' {
|
|
2
|
-
const classes: { readonly [key: string]: string };
|
|
3
|
-
export default classes;
|
|
4
|
-
}
|
|
5
|
-
declare module '*.module.scss' {
|
|
6
|
-
const classes: { readonly [key: string]: string };
|
|
7
|
-
export default classes;
|
|
8
|
-
}
|
|
9
|
-
declare module '*.module.sass' {
|
|
10
|
-
const classes: { readonly [key: string]: string };
|
|
11
|
-
export default classes;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
declare module '*.module.less' {
|
|
15
|
-
const classes: { readonly [key: string]: string };
|
|
16
|
-
export default classes;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
declare module '*.less' {
|
|
20
|
-
const classes: { readonly [key: string]: string };
|
|
21
|
-
export default classes;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
declare module '*.css' {
|
|
25
|
-
const classes: { readonly [key: string]: string };
|
|
26
|
-
export default classes;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
declare module '*.sass' {
|
|
30
|
-
const classes: { readonly [key: string]: string };
|
|
31
|
-
export default classes;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
declare module '*.scss' {
|
|
35
|
-
const classes: { readonly [key: string]: string };
|
|
36
|
-
export default classes;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
declare module '*.mdx' {
|
|
40
|
-
const component: any;
|
|
41
|
-
export default component;
|
|
42
|
-
}
|
package/typescript.aspect.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { Logger } from '@teambit/logger';
|
|
2
|
-
import ts from 'typescript';
|
|
3
|
-
import { expect } from 'chai';
|
|
4
|
-
import path from 'path';
|
|
5
|
-
import { TypescriptAspect } from './typescript.aspect';
|
|
6
|
-
|
|
7
|
-
import { TypescriptCompiler } from './typescript.compiler';
|
|
8
|
-
import type { TsCompilerOptionsWithoutTsConfig } from './compiler-options';
|
|
9
|
-
|
|
10
|
-
const defaultOpts = {
|
|
11
|
-
tsconfig: {},
|
|
12
|
-
types: [],
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
describe('TypescriptCompiler', () => {
|
|
16
|
-
describe('getDistPathBySrcPath', () => {
|
|
17
|
-
it('should replace the extension with .js and prepend the dist dir', () => {
|
|
18
|
-
const tsCompiler = getTsCompiler();
|
|
19
|
-
expect(tsCompiler.getDistPathBySrcPath('index.ts')).to.equal(path.join('dist', 'index.js'));
|
|
20
|
-
expect(tsCompiler.getDistPathBySrcPath('index.tsx')).to.equal(path.join('dist', 'index.js'));
|
|
21
|
-
});
|
|
22
|
-
it('should not replace the extension if the file is not supported', () => {
|
|
23
|
-
const tsCompiler = getTsCompiler();
|
|
24
|
-
expect(tsCompiler.getDistPathBySrcPath('style.css')).to.equal(path.join('dist', 'style.css'));
|
|
25
|
-
expect(tsCompiler.getDistPathBySrcPath('index.d.ts')).to.equal(path.join('dist', 'index.d.ts'));
|
|
26
|
-
});
|
|
27
|
-
});
|
|
28
|
-
describe('isFileSupported', () => {
|
|
29
|
-
it('should support .ts files', () => {
|
|
30
|
-
const tsCompiler = getTsCompiler();
|
|
31
|
-
expect(tsCompiler.isFileSupported('index.ts')).to.be.true;
|
|
32
|
-
});
|
|
33
|
-
it('should support .tsx files', () => {
|
|
34
|
-
const tsCompiler = getTsCompiler();
|
|
35
|
-
expect(tsCompiler.isFileSupported('index.tsx')).to.be.true;
|
|
36
|
-
});
|
|
37
|
-
it('should not support .jsx files by default', () => {
|
|
38
|
-
const tsCompiler = getTsCompiler();
|
|
39
|
-
expect(tsCompiler.isFileSupported('index.jsx')).to.be.false;
|
|
40
|
-
});
|
|
41
|
-
it('should not support .js files by default', () => {
|
|
42
|
-
const tsCompiler = getTsCompiler();
|
|
43
|
-
expect(tsCompiler.isFileSupported('index.js')).to.be.false;
|
|
44
|
-
});
|
|
45
|
-
it('should support .jsx files when passing compileJsx', () => {
|
|
46
|
-
const tsCompiler = getTsCompiler({ compileJsx: true, ...defaultOpts });
|
|
47
|
-
expect(tsCompiler.isFileSupported('index.jsx')).to.be.true;
|
|
48
|
-
});
|
|
49
|
-
it('should support .js files when passing compileJs', () => {
|
|
50
|
-
const tsCompiler = getTsCompiler({ compileJs: true, ...defaultOpts });
|
|
51
|
-
expect(tsCompiler.isFileSupported('index.js')).to.be.true;
|
|
52
|
-
});
|
|
53
|
-
it('should not support .d.ts files', () => {
|
|
54
|
-
const tsCompiler = getTsCompiler();
|
|
55
|
-
expect(tsCompiler.isFileSupported('index.d.ts')).to.be.false;
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
function getTsCompiler(opts: TsCompilerOptionsWithoutTsConfig = defaultOpts) {
|
|
61
|
-
const finalOpts = Object.assign({}, defaultOpts, opts);
|
|
62
|
-
return new TypescriptCompiler(TypescriptAspect.id, new Logger('test'), finalOpts, ts);
|
|
63
|
-
}
|
package/typescript.compiler.ts
DELETED
|
@@ -1,293 +0,0 @@
|
|
|
1
|
-
import { BuildContext, BuiltTaskResult, ComponentResult } from '@teambit/builder';
|
|
2
|
-
import { Compiler, TranspileFileParams, TranspileFileOutput } from '@teambit/compiler';
|
|
3
|
-
import { Network } from '@teambit/isolator';
|
|
4
|
-
import { Logger } from '@teambit/logger';
|
|
5
|
-
import fs from 'fs-extra';
|
|
6
|
-
import path from 'path';
|
|
7
|
-
import ts from 'typescript';
|
|
8
|
-
import { BitError } from '@teambit/bit-error';
|
|
9
|
-
import PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';
|
|
10
|
-
import { TypeScriptCompilerOptions } from './compiler-options';
|
|
11
|
-
|
|
12
|
-
export class TypescriptCompiler implements Compiler {
|
|
13
|
-
distDir: string;
|
|
14
|
-
distGlobPatterns: string[];
|
|
15
|
-
shouldCopyNonSupportedFiles: boolean;
|
|
16
|
-
artifactName: string;
|
|
17
|
-
constructor(
|
|
18
|
-
readonly id: string,
|
|
19
|
-
private logger: Logger,
|
|
20
|
-
private options: TypeScriptCompilerOptions,
|
|
21
|
-
private tsModule: typeof ts
|
|
22
|
-
) {
|
|
23
|
-
this.distDir = options.distDir || 'dist';
|
|
24
|
-
this.distGlobPatterns = options.distGlobPatterns || [`${this.distDir}/**`, `!${this.distDir}/tsconfig.tsbuildinfo`];
|
|
25
|
-
this.shouldCopyNonSupportedFiles =
|
|
26
|
-
typeof options.shouldCopyNonSupportedFiles === 'boolean' ? options.shouldCopyNonSupportedFiles : true;
|
|
27
|
-
this.artifactName = options.artifactName || 'dist';
|
|
28
|
-
this.options.tsconfig ||= {};
|
|
29
|
-
this.options.tsconfig.compilerOptions ||= {};
|
|
30
|
-
// mutate the outDir, otherwise, on capsules, the dists might be written to a different directory and make confusion
|
|
31
|
-
this.options.tsconfig.compilerOptions.outDir = this.distDir;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
displayName = 'TypeScript';
|
|
35
|
-
|
|
36
|
-
displayConfig() {
|
|
37
|
-
return this.stringifyTsconfig(this.options.tsconfig);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* compile one file on the workspace
|
|
42
|
-
*/
|
|
43
|
-
transpileFile(fileContent: string, options: TranspileFileParams): TranspileFileOutput {
|
|
44
|
-
if (!this.isFileSupported(options.filePath)) {
|
|
45
|
-
return null; // file is not supported
|
|
46
|
-
}
|
|
47
|
-
const compilerOptionsFromTsconfig = this.tsModule.convertCompilerOptionsFromJson(
|
|
48
|
-
this.options.tsconfig.compilerOptions,
|
|
49
|
-
'.'
|
|
50
|
-
);
|
|
51
|
-
if (compilerOptionsFromTsconfig.errors.length) {
|
|
52
|
-
// :TODO @david replace to a more concrete error type and put in 'exceptions' directory here.
|
|
53
|
-
const formattedErrors = this.tsModule.formatDiagnosticsWithColorAndContext(
|
|
54
|
-
compilerOptionsFromTsconfig.errors,
|
|
55
|
-
this.getFormatDiagnosticsHost()
|
|
56
|
-
);
|
|
57
|
-
throw new Error(`failed parsing the tsconfig.json.\n${formattedErrors}`);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const compilerOptions = compilerOptionsFromTsconfig.options;
|
|
61
|
-
compilerOptions.sourceRoot = options.componentDir;
|
|
62
|
-
compilerOptions.rootDir = '.';
|
|
63
|
-
const result = this.tsModule.transpileModule(fileContent, {
|
|
64
|
-
compilerOptions,
|
|
65
|
-
fileName: options.filePath,
|
|
66
|
-
reportDiagnostics: true,
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
if (result.diagnostics && result.diagnostics.length) {
|
|
70
|
-
const formatHost = this.getFormatDiagnosticsHost();
|
|
71
|
-
const error = this.tsModule.formatDiagnosticsWithColorAndContext(result.diagnostics, formatHost);
|
|
72
|
-
|
|
73
|
-
// :TODO @david please replace to a more concrete error type and put in 'exceptions' directory here.
|
|
74
|
-
throw new Error(error);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const outputPath = this.replaceFileExtToJs(options.filePath);
|
|
78
|
-
const outputFiles = [{ outputText: result.outputText, outputPath }];
|
|
79
|
-
if (result.sourceMapText) {
|
|
80
|
-
outputFiles.push({
|
|
81
|
-
outputText: result.sourceMapText,
|
|
82
|
-
outputPath: `${outputPath}.map`,
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
return outputFiles;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
async preBuild(context: BuildContext) {
|
|
89
|
-
const capsules = context.capsuleNetwork.seedersCapsules;
|
|
90
|
-
const capsuleDirs = capsules.map((capsule) => capsule.path);
|
|
91
|
-
await this.writeTsConfig(capsuleDirs);
|
|
92
|
-
await this.writeTypes(capsuleDirs);
|
|
93
|
-
await this.writeNpmIgnore(capsuleDirs);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* compile multiple components on the capsules
|
|
98
|
-
*/
|
|
99
|
-
async build(context: BuildContext): Promise<BuiltTaskResult> {
|
|
100
|
-
const componentsResults = await this.runTscBuild(context.capsuleNetwork);
|
|
101
|
-
|
|
102
|
-
return {
|
|
103
|
-
artifacts: this.getArtifactDefinition(),
|
|
104
|
-
componentsResults,
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async postBuild(context: BuildContext) {
|
|
109
|
-
await Promise.all(
|
|
110
|
-
context.capsuleNetwork.seedersCapsules.map(async (capsule) => {
|
|
111
|
-
const packageJson = PackageJsonFile.loadFromCapsuleSync(capsule.path);
|
|
112
|
-
// the types['index.ts'] is needed only during the build to avoid errors when tsc finds the
|
|
113
|
-
// same type once in the d.ts and once in the ts file.
|
|
114
|
-
if (packageJson.packageJsonObject.types) {
|
|
115
|
-
delete packageJson.packageJsonObject.types;
|
|
116
|
-
await packageJson.write();
|
|
117
|
-
}
|
|
118
|
-
})
|
|
119
|
-
);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
getArtifactDefinition() {
|
|
123
|
-
return [
|
|
124
|
-
{
|
|
125
|
-
generatedBy: this.id,
|
|
126
|
-
name: this.artifactName,
|
|
127
|
-
globPatterns: this.distGlobPatterns,
|
|
128
|
-
},
|
|
129
|
-
];
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* given a source file, return its parallel in the dists. e.g. index.ts => dist/index.js
|
|
134
|
-
*/
|
|
135
|
-
getDistPathBySrcPath(srcPath: string) {
|
|
136
|
-
const fileWithJSExtIfNeeded = this.replaceFileExtToJs(srcPath);
|
|
137
|
-
return path.join(this.distDir, fileWithJSExtIfNeeded);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* whether typescript is able to compile the given path
|
|
142
|
-
*/
|
|
143
|
-
isFileSupported(filePath: string): boolean {
|
|
144
|
-
const isJsAndCompile = !!this.options.compileJs && filePath.endsWith('.js');
|
|
145
|
-
const isJsxAndCompile = !!this.options.compileJsx && filePath.endsWith('.jsx');
|
|
146
|
-
return (
|
|
147
|
-
(filePath.endsWith('.ts') || filePath.endsWith('.tsx') || isJsAndCompile || isJsxAndCompile) &&
|
|
148
|
-
!filePath.endsWith('.d.ts')
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* we have two options here:
|
|
154
|
-
* 1. pass all capsules-dir at the second parameter of createSolutionBuilder and then no
|
|
155
|
-
* need to write the main tsconfig.json with all the references.
|
|
156
|
-
* 2. write main tsconfig.json and pass the capsules root-dir.
|
|
157
|
-
* we went with option #2 because it'll be easier for users to go to the capsule-root and run
|
|
158
|
-
* `tsc --build` to debug issues.
|
|
159
|
-
*/
|
|
160
|
-
private async runTscBuild(network: Network): Promise<ComponentResult[]> {
|
|
161
|
-
const rootDir = network.capsulesRootDir;
|
|
162
|
-
const capsules = network.graphCapsules;
|
|
163
|
-
const capsuleDirs = capsules.getAllCapsuleDirs();
|
|
164
|
-
const formatHost = {
|
|
165
|
-
getCanonicalFileName: (p) => p,
|
|
166
|
-
getCurrentDirectory: () => '', // it helps to get the files with absolute paths
|
|
167
|
-
getNewLine: () => this.tsModule.sys.newLine,
|
|
168
|
-
};
|
|
169
|
-
const componentsResults: ComponentResult[] = [];
|
|
170
|
-
let currentComponentResult: Partial<ComponentResult> = { errors: [] };
|
|
171
|
-
const reportDiagnostic = (diagnostic: ts.Diagnostic) => {
|
|
172
|
-
const errorStr = process.stdout.isTTY
|
|
173
|
-
? this.tsModule.formatDiagnosticsWithColorAndContext([diagnostic], formatHost)
|
|
174
|
-
: this.tsModule.formatDiagnostic(diagnostic, formatHost);
|
|
175
|
-
if (!diagnostic.file) {
|
|
176
|
-
// the error is general and not related to a specific file. e.g. tsconfig is missing.
|
|
177
|
-
throw new BitError(errorStr);
|
|
178
|
-
}
|
|
179
|
-
this.logger.consoleFailure(errorStr);
|
|
180
|
-
if (!currentComponentResult.component || !currentComponentResult.errors) {
|
|
181
|
-
throw new Error(`currentComponentResult is not defined yet for ${diagnostic.file}`);
|
|
182
|
-
}
|
|
183
|
-
currentComponentResult.errors.push(errorStr);
|
|
184
|
-
};
|
|
185
|
-
// this only works when `verbose` is `true` in the `ts.createSolutionBuilder` function.
|
|
186
|
-
const reportSolutionBuilderStatus = (diag: ts.Diagnostic) => {
|
|
187
|
-
const msg = diag.messageText as string;
|
|
188
|
-
this.logger.debug(msg);
|
|
189
|
-
};
|
|
190
|
-
const errorCounter = (errorCount: number) => {
|
|
191
|
-
this.logger.info(`total error found: ${errorCount}`);
|
|
192
|
-
};
|
|
193
|
-
const host = this.tsModule.createSolutionBuilderHost(
|
|
194
|
-
undefined,
|
|
195
|
-
undefined,
|
|
196
|
-
reportDiagnostic,
|
|
197
|
-
reportSolutionBuilderStatus,
|
|
198
|
-
errorCounter
|
|
199
|
-
);
|
|
200
|
-
await this.writeProjectReferencesTsConfig(rootDir, capsuleDirs);
|
|
201
|
-
const solutionBuilder = this.tsModule.createSolutionBuilder(host, [rootDir], { verbose: true });
|
|
202
|
-
let nextProject;
|
|
203
|
-
const longProcessLogger = this.logger.createLongProcessLogger('compile typescript components', capsules.length);
|
|
204
|
-
// eslint-disable-next-line no-cond-assign
|
|
205
|
-
while ((nextProject = solutionBuilder.getNextInvalidatedProject())) {
|
|
206
|
-
// regex to make sure it will work correctly for both linux and windows
|
|
207
|
-
// it replaces both /tsconfig.json and \tsocnfig.json
|
|
208
|
-
const capsulePath = nextProject.project.replace(/[/\\]tsconfig.json/, '');
|
|
209
|
-
const currentComponentId = capsules.getIdByPathInCapsule(capsulePath);
|
|
210
|
-
if (!currentComponentId) throw new Error(`unable to find component for ${capsulePath}`);
|
|
211
|
-
longProcessLogger.logProgress(currentComponentId.toString());
|
|
212
|
-
const capsule = capsules.getCapsule(currentComponentId);
|
|
213
|
-
if (!capsule) throw new Error(`unable to find capsule for ${currentComponentId.toString()}`);
|
|
214
|
-
currentComponentResult.component = capsule.component;
|
|
215
|
-
currentComponentResult.startTime = Date.now();
|
|
216
|
-
nextProject.done();
|
|
217
|
-
currentComponentResult.endTime = Date.now();
|
|
218
|
-
componentsResults.push({ ...currentComponentResult } as ComponentResult);
|
|
219
|
-
currentComponentResult = { errors: [] };
|
|
220
|
-
}
|
|
221
|
-
longProcessLogger.end();
|
|
222
|
-
|
|
223
|
-
return componentsResults;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
private getFormatDiagnosticsHost(): ts.FormatDiagnosticsHost {
|
|
227
|
-
return {
|
|
228
|
-
getCanonicalFileName: (p) => p,
|
|
229
|
-
getCurrentDirectory: this.tsModule.sys.getCurrentDirectory,
|
|
230
|
-
getNewLine: () => this.tsModule.sys.newLine,
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
private async writeTypes(dirs: string[]) {
|
|
235
|
-
await Promise.all(
|
|
236
|
-
this.options.types.map(async (typePath) => {
|
|
237
|
-
const contents = await fs.readFile(typePath, 'utf8');
|
|
238
|
-
const filename = path.basename(typePath);
|
|
239
|
-
|
|
240
|
-
await Promise.all(
|
|
241
|
-
dirs.map(async (dir) => {
|
|
242
|
-
const filePath = path.join(dir, 'types', filename);
|
|
243
|
-
if (!(await fs.pathExists(filePath))) {
|
|
244
|
-
await fs.outputFile(filePath, contents);
|
|
245
|
-
}
|
|
246
|
-
})
|
|
247
|
-
);
|
|
248
|
-
})
|
|
249
|
-
);
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* when using project-references, typescript adds a file "tsconfig.tsbuildinfo" which is not
|
|
254
|
-
* needed for the package.
|
|
255
|
-
*/
|
|
256
|
-
private async writeNpmIgnore(dirs: string[]) {
|
|
257
|
-
const NPM_IGNORE_FILE = '.npmignore';
|
|
258
|
-
await Promise.all(
|
|
259
|
-
dirs.map(async (dir) => {
|
|
260
|
-
const npmIgnorePath = path.join(dir, NPM_IGNORE_FILE);
|
|
261
|
-
const npmIgnoreEntriesStr = `\n${this.distDir}/tsconfig.tsbuildinfo\n`;
|
|
262
|
-
await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);
|
|
263
|
-
})
|
|
264
|
-
);
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
private async writeProjectReferencesTsConfig(rootDir: string, projects: string[]) {
|
|
268
|
-
const files = [];
|
|
269
|
-
const references = projects.map((project) => ({ path: project }));
|
|
270
|
-
const tsconfig = { files, references };
|
|
271
|
-
const tsconfigStr = this.stringifyTsconfig(tsconfig);
|
|
272
|
-
await fs.writeFile(path.join(rootDir, 'tsconfig.json'), tsconfigStr);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
private async writeTsConfig(dirs: string[]) {
|
|
276
|
-
const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);
|
|
277
|
-
await Promise.all(dirs.map((dir) => fs.writeFile(path.join(dir, 'tsconfig.json'), tsconfigStr)));
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
private stringifyTsconfig(tsconfig) {
|
|
281
|
-
return JSON.stringify(tsconfig, undefined, 2);
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
private replaceFileExtToJs(filePath: string): string {
|
|
285
|
-
if (!this.isFileSupported(filePath)) return filePath;
|
|
286
|
-
const fileExtension = path.extname(filePath);
|
|
287
|
-
return filePath.replace(new RegExp(`${fileExtension}$`), '.js'); // makes sure it's the last occurrence
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
version() {
|
|
291
|
-
return this.tsModule.version;
|
|
292
|
-
}
|
|
293
|
-
}
|
package/typescript.docs.mdx
DELETED
package/typescript.extractor.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
// import { tmpdir } from 'os';
|
|
2
|
-
import { TsConfigSourceFile } from 'typescript';
|
|
3
|
-
// import { resolve, join } from 'path';
|
|
4
|
-
import { Module, SchemaExtractor } from '@teambit/schema';
|
|
5
|
-
import { Component } from '@teambit/component';
|
|
6
|
-
import { Application } from 'typedoc';
|
|
7
|
-
|
|
8
|
-
export class TypeScriptExtractor implements SchemaExtractor {
|
|
9
|
-
constructor(private tsconfig: TsConfigSourceFile) {}
|
|
10
|
-
|
|
11
|
-
async extract(component: Component) {
|
|
12
|
-
// const tsconfig = this.tsconfig;
|
|
13
|
-
const paths = component.state.filesystem.files.map((file) => file.path).filter((path) => path.endsWith('index.ts'));
|
|
14
|
-
// const paths = ['/Users/ranmizrahi/Bit/bit/scopes/workspace/workspace/index.ts'];
|
|
15
|
-
const app = new Application();
|
|
16
|
-
app.bootstrap({
|
|
17
|
-
// typedoc options here
|
|
18
|
-
entryPoints: paths,
|
|
19
|
-
});
|
|
20
|
-
const project = app.convert();
|
|
21
|
-
// typedocApp.options.setValues({
|
|
22
|
-
// inputFiles: paths,
|
|
23
|
-
// allowJs: true,
|
|
24
|
-
// lib: ['lib.es2015.d.ts', 'lib.es2019.d.ts', 'lib.es6.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
|
|
25
|
-
// jsx: 2,
|
|
26
|
-
// noEmit: true,
|
|
27
|
-
// exclude: ['node_modules', '*.scss'],
|
|
28
|
-
// esModuleInterop: true,
|
|
29
|
-
// });
|
|
30
|
-
if (!project) throw new Error('typedoc failed generating docs');
|
|
31
|
-
return app.serializer.projectToObject(project) as any as Module;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
@@ -1,165 +0,0 @@
|
|
|
1
|
-
import ts, { TsConfigSourceFile } from 'typescript';
|
|
2
|
-
import { MainRuntime } from '@teambit/cli';
|
|
3
|
-
import { Compiler } from '@teambit/compiler';
|
|
4
|
-
import { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';
|
|
5
|
-
import { SchemaAspect, SchemaExtractor, SchemaMain } from '@teambit/schema';
|
|
6
|
-
import { PackageJsonProps } from '@teambit/pkg';
|
|
7
|
-
import { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
|
|
8
|
-
import WorkspaceAspect from '@teambit/workspace';
|
|
9
|
-
import type { WatchOptions, Workspace } from '@teambit/workspace';
|
|
10
|
-
import pMapSeries from 'p-map-series';
|
|
11
|
-
import { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';
|
|
12
|
-
import type { Component } from '@teambit/component';
|
|
13
|
-
import { TypeScriptExtractor } from './typescript.extractor';
|
|
14
|
-
import { TypeScriptCompilerOptions } from './compiler-options';
|
|
15
|
-
import { TypescriptAspect } from './typescript.aspect';
|
|
16
|
-
import { TypescriptCompiler } from './typescript.compiler';
|
|
17
|
-
import { TypeScriptParser } from './typescript.parser';
|
|
18
|
-
|
|
19
|
-
export type TsMode = 'build' | 'dev';
|
|
20
|
-
|
|
21
|
-
export type TsConfigTransformContext = {
|
|
22
|
-
// mode: TsMode;
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
export type TsConfigTransformer = (
|
|
26
|
-
config: TypescriptConfigMutator,
|
|
27
|
-
context: TsConfigTransformContext
|
|
28
|
-
) => TypescriptConfigMutator;
|
|
29
|
-
|
|
30
|
-
export class TypescriptMain {
|
|
31
|
-
private tsServer: TsserverClient;
|
|
32
|
-
constructor(private logger: Logger, private workspace?: Workspace) {
|
|
33
|
-
if (this.workspace) {
|
|
34
|
-
this.workspace.registerOnPreWatch(this.onPreWatch.bind(this));
|
|
35
|
-
this.workspace.registerOnComponentChange(this.onComponentChange.bind(this));
|
|
36
|
-
this.workspace.registerOnComponentAdd(this.onComponentChange.bind(this));
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* create a new compiler.
|
|
41
|
-
*/
|
|
42
|
-
createCompiler(
|
|
43
|
-
options: TypeScriptCompilerOptions,
|
|
44
|
-
transformers: TsConfigTransformer[] = [],
|
|
45
|
-
tsModule = ts
|
|
46
|
-
): Compiler {
|
|
47
|
-
const configMutator = new TypescriptConfigMutator(options);
|
|
48
|
-
const transformerContext: TsConfigTransformContext = {};
|
|
49
|
-
const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);
|
|
50
|
-
return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* get TsserverClient instance if initiated already, otherwise, return undefined.
|
|
55
|
-
*/
|
|
56
|
-
getTsserverClient(): TsserverClient | undefined {
|
|
57
|
-
return this.tsServer;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* starts a tsserver process to communicate with its API.
|
|
62
|
-
* @param projectPath absolute path of the project root directory
|
|
63
|
-
* @param options TsserverClientOpts
|
|
64
|
-
* @param files optionally, if check-types is enabled, provide files to open and type check.
|
|
65
|
-
* @returns TsserverClient
|
|
66
|
-
*/
|
|
67
|
-
async initTsserverClient(
|
|
68
|
-
projectPath: string,
|
|
69
|
-
options: TsserverClientOpts = {},
|
|
70
|
-
files: string[] = []
|
|
71
|
-
): Promise<TsserverClient> {
|
|
72
|
-
this.tsServer = new TsserverClient(projectPath, this.logger, options, files);
|
|
73
|
-
this.tsServer.init();
|
|
74
|
-
return this.tsServer;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* starts a tsserver process to communicate with its API. use only when running on the workspace.
|
|
79
|
-
* @param options TsserverClientOpts
|
|
80
|
-
* @param files optionally, if check-types is enabled, provide files to open and type check.
|
|
81
|
-
* @returns TsserverClient
|
|
82
|
-
*/
|
|
83
|
-
async initTsserverClientFromWorkspace(
|
|
84
|
-
options: TsserverClientOpts = {},
|
|
85
|
-
files: string[] = []
|
|
86
|
-
): Promise<TsserverClient> {
|
|
87
|
-
if (!this.workspace) {
|
|
88
|
-
throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);
|
|
89
|
-
}
|
|
90
|
-
return this.initTsserverClient(this.workspace.path, options, files);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* create an instance of a typescript semantic schema extractor.
|
|
95
|
-
*/
|
|
96
|
-
createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor {
|
|
97
|
-
return new TypeScriptExtractor(tsconfig);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* add the default package json properties to the component
|
|
102
|
-
* :TODO @gilad why do we need this DSL? can't I just get the args here.
|
|
103
|
-
*/
|
|
104
|
-
getPackageJsonProps(): PackageJsonProps {
|
|
105
|
-
return {
|
|
106
|
-
main: 'dist/{main}.js',
|
|
107
|
-
types: '{main}.ts',
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
private getAllFilesForTsserver(components: Component[]): string[] {
|
|
112
|
-
const files = components
|
|
113
|
-
.map((c) => c.filesystem.files)
|
|
114
|
-
.flat()
|
|
115
|
-
.map((f) => f.path);
|
|
116
|
-
return files.filter((f) => f.endsWith('.ts') || f.endsWith('.tsx'));
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
private async onPreWatch(components: Component[], watchOpts: WatchOptions) {
|
|
120
|
-
const workspace = this.workspace;
|
|
121
|
-
if (!workspace || !watchOpts.spawnTSServer) {
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
const { verbose, checkTypes } = watchOpts;
|
|
125
|
-
const files = checkTypes ? this.getAllFilesForTsserver(components) : [];
|
|
126
|
-
await this.initTsserverClientFromWorkspace({ verbose, checkTypes }, files);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
private async onComponentChange(component: Component, files: string[]) {
|
|
130
|
-
if (!this.tsServer) {
|
|
131
|
-
return {
|
|
132
|
-
results: 'N/A',
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
await pMapSeries(files, (file) => this.tsServer.onFileChange(file));
|
|
136
|
-
return {
|
|
137
|
-
results: 'succeed',
|
|
138
|
-
};
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
static runtime = MainRuntime;
|
|
142
|
-
static dependencies = [SchemaAspect, LoggerAspect, WorkspaceAspect];
|
|
143
|
-
|
|
144
|
-
static async provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]) {
|
|
145
|
-
schema.registerParser(new TypeScriptParser());
|
|
146
|
-
const logger = loggerExt.createLogger(TypescriptAspect.id);
|
|
147
|
-
schema.registerParser(new TypeScriptParser(logger));
|
|
148
|
-
|
|
149
|
-
return new TypescriptMain(logger, workspace);
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
TypescriptAspect.addRuntime(TypescriptMain);
|
|
154
|
-
|
|
155
|
-
export function runTransformersWithContext(
|
|
156
|
-
config: TypescriptConfigMutator,
|
|
157
|
-
transformers: TsConfigTransformer[] = [],
|
|
158
|
-
context: TsConfigTransformContext
|
|
159
|
-
): TypescriptConfigMutator {
|
|
160
|
-
if (!Array.isArray(transformers)) return config;
|
|
161
|
-
const newConfig = transformers.reduce((acc, transformer) => {
|
|
162
|
-
return transformer(acc, context);
|
|
163
|
-
}, config);
|
|
164
|
-
return newConfig;
|
|
165
|
-
}
|
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import ts from 'typescript';
|
|
2
|
-
import { expect } from 'chai';
|
|
3
|
-
|
|
4
|
-
import { TypeScriptParser } from './typescript.parser';
|
|
5
|
-
|
|
6
|
-
describe('TypescriptParser', () => {
|
|
7
|
-
describe('getExports', () => {
|
|
8
|
-
const exampleArrowFunction = `
|
|
9
|
-
export const arrow = () => { return 3; }
|
|
10
|
-
arrow.textProperty = "propertyValue";
|
|
11
|
-
`;
|
|
12
|
-
|
|
13
|
-
const exampleFunction = `
|
|
14
|
-
export function func() { return 3; }
|
|
15
|
-
func.textProperty = "propertyValue";
|
|
16
|
-
`;
|
|
17
|
-
|
|
18
|
-
const exampleClass = `
|
|
19
|
-
export class classy{ render() { return 3; } }
|
|
20
|
-
classy.textProperty = "propertyValue";
|
|
21
|
-
`;
|
|
22
|
-
|
|
23
|
-
it('should parse arrowFunctions', () => {
|
|
24
|
-
const ast = ts.createSourceFile('example.tsx', exampleArrowFunction, ts.ScriptTarget.Latest);
|
|
25
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
26
|
-
|
|
27
|
-
const exportArrow = exports.find((x) => x.identifier === 'arrow');
|
|
28
|
-
|
|
29
|
-
expect(exportArrow).to.exist;
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
it('should parse function exports', () => {
|
|
33
|
-
const ast = ts.createSourceFile('example.tsx', exampleFunction, ts.ScriptTarget.Latest);
|
|
34
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
35
|
-
|
|
36
|
-
const exportFunction = exports.find((x) => x.identifier === 'func');
|
|
37
|
-
|
|
38
|
-
expect(exportFunction).to.exist;
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
it('should parse classes', () => {
|
|
42
|
-
const ast = ts.createSourceFile('example.tsx', exampleClass, ts.ScriptTarget.Latest);
|
|
43
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
44
|
-
|
|
45
|
-
const exportClass = exports.find((x) => x.identifier === 'classy');
|
|
46
|
-
|
|
47
|
-
expect(exportClass).to.exist;
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
describe('staticProperties', () => {
|
|
51
|
-
it('should include staticProperties, when on arrowFunctions', () => {
|
|
52
|
-
const ast = ts.createSourceFile('example.tsx', exampleArrowFunction, ts.ScriptTarget.Latest);
|
|
53
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
54
|
-
|
|
55
|
-
const exportArrow = exports.find((x) => x.identifier === 'arrow');
|
|
56
|
-
|
|
57
|
-
expect(exportArrow?.staticProperties?.get('textProperty')).to.equal('propertyValue');
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
it('should include staticProperties, when on regular functions', () => {
|
|
61
|
-
const ast = ts.createSourceFile('example.tsx', exampleFunction, ts.ScriptTarget.Latest);
|
|
62
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
63
|
-
|
|
64
|
-
const exportClass = exports.find((x) => x.identifier === 'func');
|
|
65
|
-
|
|
66
|
-
expect(exportClass?.staticProperties?.get('textProperty')).to.equal('propertyValue');
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it('should include staticProperties, when on classes', () => {
|
|
70
|
-
const ast = ts.createSourceFile('example.tsx', exampleClass, ts.ScriptTarget.Latest);
|
|
71
|
-
const exports = new TypeScriptParser().getExports(ast);
|
|
72
|
-
|
|
73
|
-
const exportClass = exports.find((x) => x.identifier === 'classy');
|
|
74
|
-
|
|
75
|
-
expect(exportClass?.staticProperties?.get('textProperty')).to.equal('propertyValue');
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
describe('collectStaticProperties', () => {
|
|
81
|
-
const exampleFile = `
|
|
82
|
-
export const hello = () => { return 3; }
|
|
83
|
-
|
|
84
|
-
hello.text = "is";
|
|
85
|
-
hello.count = 3;
|
|
86
|
-
hello.nullish = null;
|
|
87
|
-
hello.undef = undefined;
|
|
88
|
-
hello.disable = false;
|
|
89
|
-
hello.enable = true;
|
|
90
|
-
hello.complextLiteral = \`what \${hello.text} it?\`;
|
|
91
|
-
hello.nonAssignedProperty += 'value';
|
|
92
|
-
`;
|
|
93
|
-
|
|
94
|
-
it('should parse all primitive values', () => {
|
|
95
|
-
const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
|
|
96
|
-
const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
|
|
97
|
-
|
|
98
|
-
expect(staticProperties).to.exist;
|
|
99
|
-
|
|
100
|
-
const exportHello = staticProperties.get('hello');
|
|
101
|
-
expect(exportHello).to.exist;
|
|
102
|
-
|
|
103
|
-
expect(exportHello?.get('text')).to.equal('is');
|
|
104
|
-
expect(exportHello?.get('count')).to.equal(3);
|
|
105
|
-
expect(exportHello?.get('nullish')).to.equal(null);
|
|
106
|
-
expect(exportHello?.get('undef')).to.equal(undefined);
|
|
107
|
-
expect(exportHello?.get('disable')).to.equal(false);
|
|
108
|
-
expect(exportHello?.get('enable')).to.equal(true);
|
|
109
|
-
|
|
110
|
-
expect(exportHello?.has('complextLiteral')).to.be.false;
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
it('should skip non primitive values', () => {
|
|
114
|
-
const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
|
|
115
|
-
const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
|
|
116
|
-
const exportHello = staticProperties.get('hello');
|
|
117
|
-
|
|
118
|
-
expect(exportHello?.has('complextLiteral')).to.be.false;
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
it('should skip non assignment statements', () => {
|
|
122
|
-
const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
|
|
123
|
-
const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
|
|
124
|
-
const exportHello = staticProperties.get('hello');
|
|
125
|
-
|
|
126
|
-
expect(exportHello?.has('nonAssignedProperty')).to.be.false;
|
|
127
|
-
});
|
|
128
|
-
});
|
|
129
|
-
});
|
package/typescript.parser.ts
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import { Export, Module, Parser, StaticProperties } from '@teambit/schema';
|
|
2
|
-
import { Logger } from '@teambit/logger';
|
|
3
|
-
import { readFileSync } from 'fs-extra';
|
|
4
|
-
import ts, {
|
|
5
|
-
isClassDeclaration,
|
|
6
|
-
isFunctionDeclaration,
|
|
7
|
-
isVariableStatement,
|
|
8
|
-
SourceFile,
|
|
9
|
-
VariableStatement,
|
|
10
|
-
} from 'typescript';
|
|
11
|
-
|
|
12
|
-
export class TypeScriptParser implements Parser {
|
|
13
|
-
public extension = /^.*\.(js|jsx|ts|tsx)$/;
|
|
14
|
-
|
|
15
|
-
getExports(sourceFile: SourceFile): Export[] {
|
|
16
|
-
const staticProperties = this.parseStaticProperties(sourceFile);
|
|
17
|
-
|
|
18
|
-
const exports = sourceFile.statements.filter((statement) => {
|
|
19
|
-
if (!statement.modifiers) return false;
|
|
20
|
-
return statement.modifiers.find((modifier) => {
|
|
21
|
-
return modifier.kind === ts.SyntaxKind.ExportKeyword;
|
|
22
|
-
});
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
const exportModels = exports.map((statement) => {
|
|
26
|
-
// todo refactor to a registry of variable statements.
|
|
27
|
-
if (isVariableStatement(statement)) {
|
|
28
|
-
const child = (statement as VariableStatement).declarationList.declarations[0];
|
|
29
|
-
const name = (child as any).name.text;
|
|
30
|
-
return new Export(name, staticProperties.get(name));
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
if (isFunctionDeclaration(statement)) {
|
|
34
|
-
if (!statement.name) return undefined;
|
|
35
|
-
const name = statement.name.text;
|
|
36
|
-
return new Export(name, staticProperties.get(name));
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (isClassDeclaration(statement)) {
|
|
40
|
-
if (!statement.name) return undefined;
|
|
41
|
-
const name = statement.name.text;
|
|
42
|
-
return new Export(name, staticProperties.get(name));
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
return undefined;
|
|
46
|
-
});
|
|
47
|
-
const withoutEmpty = exportModels.filter((exportModel) => exportModel !== undefined);
|
|
48
|
-
// @ts-ignore
|
|
49
|
-
return withoutEmpty;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
parseModule(modulePath: string) {
|
|
53
|
-
const ast = ts.createSourceFile(modulePath, readFileSync(modulePath, 'utf8'), ts.ScriptTarget.Latest);
|
|
54
|
-
|
|
55
|
-
const moduleExports = this.getExports(ast);
|
|
56
|
-
|
|
57
|
-
return new Module(moduleExports);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
parseStaticProperties(sourceFile: SourceFile) {
|
|
61
|
-
// TODO - should we also parse staticProperties inside classes / objects?
|
|
62
|
-
|
|
63
|
-
const exportStaticProperties = new Map<string, StaticProperties>();
|
|
64
|
-
|
|
65
|
-
sourceFile.statements.forEach((statement) => {
|
|
66
|
-
try {
|
|
67
|
-
if (!ts.isExpressionStatement(statement)) return;
|
|
68
|
-
if (!ts.isBinaryExpression(statement.expression)) return;
|
|
69
|
-
if (statement.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return;
|
|
70
|
-
if (!ts.isPropertyAccessExpression(statement.expression.left)) return;
|
|
71
|
-
if (!ts.isIdentifier(statement.expression.left.expression)) return;
|
|
72
|
-
|
|
73
|
-
const targetName = statement.expression.left.expression.text;
|
|
74
|
-
const propertyName = statement.expression.left.name.text;
|
|
75
|
-
|
|
76
|
-
if (!exportStaticProperties.has(targetName)) exportStaticProperties.set(targetName, new Map());
|
|
77
|
-
|
|
78
|
-
const existingProperties = exportStaticProperties.get(targetName);
|
|
79
|
-
|
|
80
|
-
if (ts.isStringLiteral(statement.expression.right)) {
|
|
81
|
-
existingProperties?.set(propertyName, statement.expression.right.text);
|
|
82
|
-
} else if (ts.isNumericLiteral(statement.expression.right)) {
|
|
83
|
-
existingProperties?.set(propertyName, +statement.expression.right.text);
|
|
84
|
-
} else if (statement.expression.right.kind === ts.SyntaxKind.UndefinedKeyword) {
|
|
85
|
-
existingProperties?.set(propertyName, undefined);
|
|
86
|
-
} else if (statement.expression.right.kind === ts.SyntaxKind.NullKeyword) {
|
|
87
|
-
existingProperties?.set(propertyName, null);
|
|
88
|
-
} else if (statement.expression.right.kind === ts.SyntaxKind.TrueKeyword) {
|
|
89
|
-
existingProperties?.set(propertyName, true);
|
|
90
|
-
} else if (statement.expression.right.kind === ts.SyntaxKind.FalseKeyword) {
|
|
91
|
-
existingProperties?.set(propertyName, false);
|
|
92
|
-
}
|
|
93
|
-
} catch (err) {
|
|
94
|
-
this.logger?.error('failed parsing static properties', err);
|
|
95
|
-
}
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
return exportStaticProperties;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
constructor(private logger?: Logger | undefined) {}
|
|
102
|
-
}
|