Skip to content

Commit

Permalink
fix(find-lazy-modules): Allow for any valid keys/value to be used
Browse files Browse the repository at this point in the history
and properly understand and return the modules in this case.

Also refactored that function to be clearer, and added a test to cover.
I made sure the test was failing before this PR ;)

Fixes angular#1891, angular#1960.

cc @filipesilva @ericjim @chalin - See similar
angular#1972
  • Loading branch information
hansl committed Sep 5, 2016
1 parent a647e51 commit c9290ff
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 39 deletions.
62 changes: 31 additions & 31 deletions addon/ng2/models/find-lazy-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,47 @@ import * as ts from 'typescript';
import {getSource, findNodes, getContentOfKeyLiteral} from '../utilities/ast-utils';


function flatMap<T, R>(obj: Array<T>, mapFn: (item: T) => R | R[]): Array<R> {
return obj.reduce((arr: R[], current: T) => {
const result = mapFn.call(null, current);
return result !== undefined ? arr.concat(result) : arr;
}, <R[]>[]);
}


export function findLoadChildren(tsFilePath: string): string[] {
const source = getSource(tsFilePath);
const unique: { [path: string]: boolean } = {};

let nodes = flatMap(
findNodes(source, ts.SyntaxKind.ObjectLiteralExpression),
node => findNodes(node, ts.SyntaxKind.PropertyAssignment))
.filter((node: ts.PropertyAssignment) => {
const key = getContentOfKeyLiteral(source, node.name);
if (!key) {
// key is an expression, can't do anything.
return false;
}
return key == 'loadChildren';
})
// Remove initializers that are not files.
.filter((node: ts.PropertyAssignment) => {
return node.initializer.kind === ts.SyntaxKind.StringLiteral;
})
// Get the full text of the initializer.
.map((node: ts.PropertyAssignment) => {
return JSON.parse(node.initializer.getText(source)); // tslint:disable-line
});

return nodes
return (
// Find all object literals.
findNodes(source, ts.SyntaxKind.ObjectLiteralExpression)
// Get all their property assignments.
.map(node => findNodes(node, ts.SyntaxKind.PropertyAssignment))
// Flatten into a single array (from an array of array<property assignments>).
.reduce((prev, curr) => curr ? prev.concat(curr) : prev, [])
// Remove every property assignment that aren't 'loadChildren'.
.filter((node: ts.PropertyAssignment) => {
const key = getContentOfKeyLiteral(source, node.name);
if (!key) {
// key is an expression, can't do anything.
return false;
}
return key == 'loadChildren';
})
// Remove initializers that are not files.
.filter((node: ts.PropertyAssignment) => {
return node.initializer.kind === ts.SyntaxKind.StringLiteral;
})
// Get the full text of the initializer.
.map((node: ts.PropertyAssignment) => {
const literal = node.initializer as ts.StringLiteral;
return literal.text;
})
// Map to the module name itself.
.map((moduleName: string) => moduleName.split('#')[0])
// Only get unique values (there might be multiple modules from a single URL, or a module used
// multiple times).
.filter((value: string) => {
if (unique[value]) {
return false;
} else {
unique[value] = true;
return true;
}
})
.map((moduleName: string) => moduleName.split('#')[0]);
}));
}


Expand All @@ -57,6 +56,7 @@ export function findLazyModules(projectRoot: any): string[] {
.forEach(tsPath => {
findLoadChildren(tsPath).forEach(moduleName => {
const fileName = path.resolve(path.dirname(tsPath), moduleName) + '.ts';
console.log(1, fileName);
if (fs.existsSync(fileName)) {
result[moduleName] = true;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/bootstrap-local.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ require.extensions['.ts'] = function(m, filename) {
const source = fs.readFileSync(filename).toString();

try {
const result = ts.transpile(source, compilerOptions);
const result = ts.transpile(source, compilerOptions, filename);

// Send it to node to execute.
return m._compile(result, filename);
Expand Down
10 changes: 4 additions & 6 deletions packages/ast-tools/src/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,12 @@ export function insertAfterLastOccurrence(nodes: ts.Node[], toInsert: string,


export function getContentOfKeyLiteral(source: ts.SourceFile, node: ts.Node): string {
console.log(10, node.kind, (node as any).text);
if (node.kind == ts.SyntaxKind.Identifier) {
return (<ts.Identifier>node).text;
return (node as ts.Identifier).text;
} else if (node.kind == ts.SyntaxKind.StringLiteral) {
try {
return JSON.parse(node.getFullText(source));
} catch (e) {
return null;
}
const literal = node as ts.StringLiteral;
return literal.text;
} else {
return null;
}
Expand Down
49 changes: 49 additions & 0 deletions tests/acceptance/find-lazy-module.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import * as mockFs from 'mock-fs';
import {stripIndents} from 'common-tags';
import {expect} from 'chai';

import {findLazyModules} from '../../addon/ng2/models/find-lazy-modules';


(describe as any).only('find-lazy-module', () => {
beforeEach(() => {
mockFs({
'project-root': {
'fileA.ts': stripIndents`
const r1 = {
"loadChildren": "moduleA"
};
const r2 = {
loadChildren: "moduleB"
};
const r3 = {
'loadChildren': 'moduleC'
};
const r4 = {
"loadChildren": 'app/+workspace/+settings/settings.module#SettingsModule'
};
const r5 = {
loadChildren: 'unexistentModule'
};
`,
// Create those files too as they have to exist.
'moduleA.ts': '',
'moduleB.ts': '',
'moduleC.ts': '',
'moduleD.ts': '',
'app': { '+workspace': { '+settings': { 'settings.module.ts': '' } } }
}
})
});
afterEach(() => mockFs.restore());

it('works', () => {
debugger;
expect(findLazyModules('project-root')).to.eql([
'moduleA',
'moduleB',
'moduleC',
'app/+workspace/+settings/settings.module'
]);
});
});
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"outDir": "./dist/",
"rootDir": ".",
"sourceMap": true,
"sourceRoot": "",
"inlineSourceMap": true,
"target": "es5",
"lib": ["es6"],
"baseUrl": "",
Expand Down

0 comments on commit c9290ff

Please sign in to comment.