Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not fail when exporting multiple symbols which match a wildcard module declaration, fixes #62 #64

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions example/type08/DeclareTtfModule.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module '*.ttf';
5 changes: 5 additions & 0 deletions example/type08/WildcardDeclaration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference path="./DeclareTtfModule.d.ts" />
import Friend from 'Friend.ttf';
import AlsoFriend from './fonts/AlsoFriend.ttf';

export { Friend, AlsoFriend };
83 changes: 83 additions & 0 deletions example/type08/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
// This is an alias to @tsconfig/node12: https://github.com/tsconfig/bases
"extends": "@tsconfig/node16/tsconfig.json",

// Most ts-node options can be specified here using their programmatic names.
"ts-node": {
// It is faster to skip typechecking.
// Remove if you want ts-node to do typechecking.
"transpileOnly": true,

"files": true,

"compilerOptions": {
// compilerOptions specified here will override those declared below,
// but *only* in ts-node. Useful if you want ts-node and tsc to use
// different options with a single tsconfig.json.
}
},
"compileOnSave": false,
"buildOnSave": false,
"compilerOptions": {
/* Basic Options */
// "target": "ES2019", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
// "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [ "dom", "ES2017", "ES2018", "ES2019", ], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
"removeComments": true /* Do not emit comments to output. */,
// "noEmit": true, /* Do not emit outputs. */
"importHelpers": true /* Import emit helpers from 'tslib'. */,
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */,
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": false, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"baseUrl": "." /* Base directory to resolve non-absolute module names. */,
"paths": {} /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */,
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./maps", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,

"pretty": true,
"typeRoots": []
},
"exclude": ["../src/**/*"]
}
39 changes: 39 additions & 0 deletions src/compilers/__tests__/compilers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const share: {
project06: tsm.Project;
projectPath07: string;
project07: tsm.Project;
projectPath08: string;
project08: tsm.Project;
} = {} as any;

beforeAll(() => {
Expand Down Expand Up @@ -68,6 +70,12 @@ beforeAll(() => {
tsConfigFilePath: share.projectPath07,
...tsMorphProjectOption,
});

share.projectPath08 = posixJoin(env.exampleType08Path, 'tsconfig.json');
share.project08 = new tsm.Project({
tsConfigFilePath: share.projectPath08,
...tsMorphProjectOption,
});
});

test('c001-getExportedName', async () => {
Expand Down Expand Up @@ -307,3 +315,34 @@ test('c005-getExportInfos-partial-ignore', async () => {

expect(terminateCircularResult).toEqual(expectation.default);
});

test('c006-getExportInfos-module-wildcard', async () => {
const expectFileName =
expect.getState().currentTestName?.replace(/^([cC][0-9]+)(-.+)/, 'expect$2.ts') ?? '';

const projectPath = env.exampleType08Path;
const project = share.project08;

const ignoreFilePath = posixJoin(projectPath, defaultIgnoreFileName);
const ignoreFiles = await getIgnoreConfigFiles(projectPath, ignoreFilePath);
const ignoreContents = await getIgnoreConfigContents({
cwd: projectPath,
...ignoreFiles,
});

const option: TCreateOptionWithDirInfo = {
...env.createOptionWithDirInfo,
project: projectPath,
skipEmptyDir: false,
keepFileExt: false,
topDirDepth: 0,
startAt: projectPath,
topDirs: [projectPath],
};

const result = await getExportInfos(project, option, ignoreContents);
const expectation = await import(path.join(__dirname, 'expects', expectFileName));
const moduleDeclarationExcludedResult = getTestValue(result);

expect(moduleDeclarationExcludedResult).toEqual(expectation.default);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as env from '@testenv/env';
import { posixJoin } from '@tools/misc';
import { replaceSepToPosix } from 'my-node-fp';

export default [
{
resolvedFilePath: posixJoin(env.exampleType08Path, 'WildcardDeclaration.ts'),
resolvedDirPath: replaceSepToPosix(env.exampleType08Path),
relativeFilePath: posixJoin('WildcardDeclaration.ts'),
depth: 0,
isEmpty: false,
starExported: true,
namedExports: [
{
identifier: "'*.ttf'",
isIsolatedModules: false,
},
{
identifier: "'*.ttf'",
isIsolatedModules: false,
},
],
},
];
49 changes: 49 additions & 0 deletions src/modules/__tests__/create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const share: {
project03: tsm.Project;
project04Path: string;
project04: tsm.Project;
project08Path: string;
project08: tsm.Project;
} = {} as any;

beforeAll(() => {
Expand All @@ -41,6 +43,12 @@ beforeAll(() => {
tsConfigFilePath: share.project04Path,
...tsMorphProjectOption,
});

share.project08Path = posixJoin(env.exampleType08Path, 'tsconfig.json');
share.project08 = new tsm.Project({
tsConfigFilePath: share.project08Path,
...tsMorphProjectOption,
});
});

test('c001-createDescendantIndex-non-skip-empty-dir', async () => {
Expand Down Expand Up @@ -368,3 +376,44 @@ test('c006-createIndexInfos-partial-ignore', async () => {

expect(terminateCircularResult).toEqual(expectation.default);
});

test('c007-createIndexInfos-module-wildcard', async () => {
const expectFileName =
expect.getState().currentTestName?.replace(/^([cC][0-9]+)(-.+)/, 'expect$2.ts') ?? '';

const projectPath = env.exampleType08Path;
const ignoreFilePath = posixJoin(projectPath, defaultIgnoreFileName);

// option modify for expectation
const option: TCreateOptionWithDirInfo = {
...env.createOptionWithDirInfo,
startAt: projectPath,
skipEmptyDir: true,
keepFileExt: false,
topDirs: [projectPath],
};

const ignoreFiles = await getIgnoreConfigFiles(projectPath, ignoreFilePath);
const ignoreContents = await getIgnoreConfigContents({ cwd: projectPath, ...ignoreFiles });

const exportInfos = await getExportInfos(share.project08, option, ignoreContents);
const exportDuplicationValidateResult = validateExportDuplication(exportInfos);
const validateResult = validateFileNameDuplication(
exportInfos.filter(
(exportInfo) =>
exportDuplicationValidateResult.filePaths.includes(exportInfo.resolvedFilePath) === false,
),
option,
);
const validExportInfos = exportInfos.filter(
(exportInfo) =>
validateResult.filePaths.includes(exportInfo.resolvedFilePath) === false &&
exportDuplicationValidateResult.filePaths.includes(exportInfo.resolvedFilePath) === false,
);
const result = await createIndexInfos(validExportInfos, ignoreContents, option);
const terminateCircularResult = getTestValue(result);

const expectation = await import(path.join(__dirname, 'expects', expectFileName));

expect(terminateCircularResult).toEqual(expectation.default);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as env from '@testenv/env';
import { posixJoin } from '@tools/misc';
import { replaceSepToPosix } from 'my-node-fp';

export default [
{
depth: 0,
resolvedDirPath: replaceSepToPosix(env.exampleType08Path),
exportStatements: ["export * from './WildcardDeclaration';"],
resolvedFilePaths: [posixJoin(env.exampleType08Path, 'WildcardDeclaration.ts')],
},
];
1 change: 1 addition & 0 deletions src/testenv/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const exampleType04Path = posixJoin(examplePath, 'type04');
export const exampleType05Path = posixJoin(examplePath, 'type05');
export const exampleType06Path = posixJoin(examplePath, 'type06');
export const exampleType07Path = posixJoin(examplePath, 'type07');
export const exampleType08Path = posixJoin(examplePath, 'type08');

export const commonOption: ICommonCliOption = {
c: posixJoin(exampleRcloaderPath, '.ctirc'),
Expand Down
6 changes: 5 additions & 1 deletion src/validations/validateExportDuplication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ function createReason(exportInfo: IExportInfo, identifier: string) {
});
}

const MATCH_WILDCARD_DECLARATION_IDENTIFIER = /['"]\*/;

/**
* Detect export duplication from every typescript source file.
*
Expand All @@ -57,7 +59,9 @@ export default function validateExportDuplication(exportInfos: IExportInfo[]) {
);

exportedNames.forEach((exportedName) => {
next[exportedName.identifier] = [...(next[exportedName.identifier] ?? []), exportInfo];
if (!MATCH_WILDCARD_DECLARATION_IDENTIFIER.test(exportedName.identifier)) {
next[exportedName.identifier] = [...(next[exportedName.identifier] ?? []), exportInfo];
}
});

return next;
Expand Down