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

Replace relative paths when exporting from d.ts with added tests #132

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
54 changes: 53 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export interface Options {
// declare some constants so we don't have magic integers without explanation
const DTSLEN = '.d.ts'.length;

// used to find relative paths to replace with their absolute
const relativePathsRegex = /(?:from\s+|import\s+|require\()['"]((?:\.|\.\.)\/[^'"]*)['"]/g;

const filenameToMid: (filename: string) => string = (function () {
if (pathUtil.sep === '/') {
return function (filename: string) {
Expand All @@ -62,6 +65,53 @@ const filenameToMid: (filename: string) => string = (function () {
}
})();

/**
* Get the absolute path from base path and relative one
* @param base The base path
* @param relative The relative path inside the base path
*/
function getAbsolutePath(base: string, relative: string) {
let stack: string[] = base.split('/');
const parts: string[] = relative.split('/');

stack.pop();
// remove current file name (or empty string)
// (omit if "base" is the current folder without trailing slash)

for (let part of parts) {
if (part === '.') {
continue;
}
if (part === '..') {
stack.pop();
} else {
stack.push(part);
}
}
// remove empty elements from the array to avoid ending /
stack = stack.filter(function(e) { return e; });
return stack.join('/');
}

/**
* Replace all relative paths in a given content with absolute ones
* @param basePath The base path
* @param content The content to search for relative paths
*/
function replaceRelativePaths(basePath: string, content: string): string {
let match = null;
let resultContent: string = content;
while ((match = relativePathsRegex.exec(content)) != null) {
let relativePath = match[1];
let absolutePath = getAbsolutePath(basePath, relativePath);
// replace relative paths with absolute
resultContent = resultContent.replace(`'${relativePath}'`, `'${absolutePath}'`);
resultContent = resultContent.replace(`"${relativePath}"`, `"${absolutePath}"`);
}

return resultContent;
}

/**
* A helper function that takes TypeScript diagnostic errors and returns an error
* object.
Expand Down Expand Up @@ -469,7 +519,7 @@ export default function generate(options: Options): Promise<void> {

output.write('declare module \'' + resolvedModuleId + '\' {' + eol + indent);

const content = processTree(declarationFile, function (node) {
let content = processTree(declarationFile, function (node) {
if (isNodeKindExternalModuleReference(node)) {
// TODO figure out if this branch is possible, and if so, write a test
// that covers it.
Expand Down Expand Up @@ -497,6 +547,8 @@ export default function generate(options: Options): Promise<void> {
}
});

content = replaceRelativePaths(resolvedModuleId, content);

output.write(content.replace(nonEmptyLineStart, '$&' + indent));
output.write(eol + '}' + eol);
}
Expand Down
1 change: 1 addition & 0 deletions tests/support/foo-relative-path/sub/bar.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './folder/bar/bar';
1 change: 1 addition & 0 deletions tests/support/foo-relative-path/sub/baz.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './baz/baz';
1 change: 1 addition & 0 deletions tests/support/foo-relative-path/sub/baz/baz.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '../folder/bar/bar';
4 changes: 4 additions & 0 deletions tests/support/foo-relative-path/sub/folder/bar/bar.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export declare interface Bar {
bar: string;
foo: number;
}
18 changes: 16 additions & 2 deletions tests/unit/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ registerSuite('index', {
assert.include(contents, `declare module 'foo/FooImplExportDeclaration'`);
});
},
'add reference types package dependency ': function () {
'add reference types package dependency': function () {
return generate({
baseDir: 'tests/support/foo',
files: [ 'index.ts' ],
Expand All @@ -217,7 +217,7 @@ registerSuite('index', {
assert.include(contents, `/// <reference types="es6-promise" />`);
});
},
'add external path dependency ': function () {
'add external path dependency': function () {
return generate({
baseDir: 'tests/support/foo',
files: [ 'index.ts' ],
Expand All @@ -227,5 +227,19 @@ registerSuite('index', {
const contents = fs.readFileSync('tmp/foo.d.ts', { encoding: 'utf8' });
assert.include(contents, `/// <reference path="../some/path/es6-promise.d.ts" />`);
});
},
'project with relative imports in .d.ts files': function () {
return generate({
baseDir: 'tests/support/foo-relative-path',
files: [ 'sub/bar.d.ts', 'sub/baz.d.ts' ],
out: 'tmp/foo.d.ts'
}).then(function () {
const contents = fs.readFileSync('tmp/foo.d.ts', { encoding: 'utf8' });
assert.include(contents, `export * from 'sub/folder/bar/bar'`);
assert.include(contents, `export * from 'sub/baz/baz'`);

// all relative paths should be replaced with absolute ones so there should be no exports like this
assert.notInclude(contents, `export * from '.`);
});
}
});