chore(dgeni): clean up legacy typings bundle creation

Fixes #4967

Closes #4991
This commit is contained in:
Alex Eagle 2015-10-28 15:22:40 -07:00 committed by Alex Eagle
parent c17c33ca14
commit 5f2eb3e078
33 changed files with 161 additions and 3022 deletions

View File

@ -1,3 +1,3 @@
{ {
"directory": "bower_components" "directory" : "bower_components"
} }

View File

@ -1,121 +0,0 @@
var Package = require('dgeni').Package;
var jsdocPackage = require('dgeni-packages/jsdoc');
var nunjucksPackage = require('dgeni-packages/nunjucks');
var typescriptPackage = require('../typescript-package');
var gitPackage = require('dgeni-packages/git');
var path = require('canonical-path');
// Define the dgeni package for generating the docs
module.exports = new Package('angular-v2-docs', [jsdocPackage, nunjucksPackage, typescriptPackage, gitPackage])
// Register the processors
.processor(require('./processors/createTypeDefinitionFile'))
.config(function(readFilesProcessor, inlineTagProcessor) {
readFilesProcessor.basePath = path.resolve(__dirname, '../..');
// Don't run unwanted processors
readFilesProcessor.$enabled = false;
inlineTagProcessor.$enabled = false;
})
// Configure the log service
.config(function(log) {
log.level = 'info';
})
.config(function(renderDocsProcessor, versionInfo) {
renderDocsProcessor.extraData.versionInfo = versionInfo;
})
.config(function(readFilesProcessor, inlineTagProcessor, readTypeScriptModules, createTypeDefinitionFile) {
// Don't run unwanted processors
readFilesProcessor.$enabled = false; // We are not using the normal file reading processor
inlineTagProcessor.$enabled = false; // We are not actually processing the inline link tags
// Configure file reading
readFilesProcessor.basePath = path.resolve(__dirname, '../..');
readTypeScriptModules.sourceFiles = [
'angular2/angular2.ts',
'angular2/web_worker/worker.ts',
'angular2/web_worker/ui.ts',
'angular2/router.ts',
'angular2/http.ts',
'angular2/testing.ts'
];
readTypeScriptModules.basePath = path.resolve(path.resolve(__dirname, '../../modules'));
createTypeDefinitionFile.typeDefinitions = [
{
id: 'angular2/angular2',
references: [],
modules: {
'angular2/angular2': {namespace: 'ng', id: 'angular2/angular2'},
'angular2/web_worker/worker': {namespace: 'ngWorker', id: 'angular2/web_worker/worker'},
'angular2/web_worker/ui': {namespace: 'ngUi', id: 'angular2/web_worker/ui'}
}
},
{
id: 'angular2/router',
references: ['./angular2.d.ts'],
remapTypes: {Type: 'ng.Type', InjectableReference: 'ng.InjectableReference', ElementRef: 'ng.ElementRef', DynamicComponentLoader: 'ng.DynamicComponentLoader'},
modules: {'angular2/router': {namespace: 'ngRouter', id: 'angular2/router'}}
},
{
id: 'angular2/http',
references: ['./angular2.d.ts'],
remapTypes: {Type: 'ng.Type', Observable: 'ng.Observable', EventEmitter: 'ng.EventEmitter', InjectableReference: 'ng.InjectableReference' },
modules: {'angular2/http': {namespace: 'ngHttp', id: 'angular2/http'}}
},
{
id: 'angular2/testing',
references: ['./angular2.d.ts'],
remapTypes: { Type: 'ng.Type', Binding: 'ng.Binding', Provider: 'ng.Provider', ViewMetadata: 'ng.ViewMetadata', Injector: 'ng.Injector',
Predicate: 'ng.Predicate', ElementRef: 'ng.ElementRef', DebugElement: 'ng.DebugElement',
InjectableReference: 'ng.InjectableReference', ComponentRef: 'ng.ComponentRef' },
modules: {'angular2/testing': {namespace: 'ngTesting', id: 'angular2/testing'}}
}
];
})
.config(function(parseTagsProcessor, getInjectables) {
// We actually don't want to parse param docs in this package as we are getting the data out using TS
parseTagsProcessor.tagDefinitions.forEach(function(tagDef) {
if (tagDef.name === 'param') {
tagDef.docProperty = 'paramData';
tagDef.transforms = [];
}
});
})
// Configure file writing
.config(function(writeFilesProcessor) {
writeFilesProcessor.outputFolder = 'dist/docs';
})
// Configure rendering
.config(function(templateFinder, templateEngine) {
// Nunjucks and Angular conflict in their template bindings so change Nunjucks
templateEngine.config.tags = {
variableStart: '{$',
variableEnd: '$}'
};
templateFinder.templateFolders
.unshift(path.resolve(__dirname, 'templates'));
templateFinder.templatePatterns = [
'${ doc.template }',
'${ doc.id }.${ doc.docType }.template.html',
'${ doc.id }.template.html',
'${ doc.docType }.template.html',
'common.template.html'
];
});

View File

@ -1,11 +0,0 @@
var Package = require('dgeni').Package;
module.exports = function mockPackage() {
return new Package('mockPackage', [require('../')])
// provide a mock log service
.factory('log', function() { return require('dgeni/lib/mocks/log')(false); })
// .factory('templateEngine', function() { return {}; });
};

View File

@ -1,220 +0,0 @@
'use strict';
function DtsSerializer(remap) {
this.remap = remap;
}
DtsSerializer.prototype = {
_initializerRegex: /\s*=[^>][^,}]*/g,
constructor: DtsSerializer,
declaration: function(buffer, ast) {
buffer.push(ast.name);
if (ast.optional) buffer.push('?');
if (ast.typeParameters) {
buffer.push('<');
buffer.push(ast.typeParameters.join(', '));
buffer.push('>');
}
if (ast.parameters) {
buffer.push('(');
var parameters = ast.parameters;
for (var i = 0; i < parameters.length; i++) {
parameters[i] = parameters[i].replace(this._initializerRegex, '');
}
buffer.push(parameters.join(', '));
buffer.push(')');
}
if (!isConstructor(ast)) {
if (ast.returnType) {
buffer.push(': ', ast.returnType);
} else if (ast.parameters) {
buffer.push(': void');
} else {
buffer.push(': any');
}
}
buffer.push(';\n');
},
comment: function(buffer, commentText) {
if (!(commentText && commentText.match(/\S/))) return;
buffer.push('/**\n');
commentText.replace(/\n*$/, '').split('\n').forEach(function(line) {
buffer.push(' * ' + line + '\n');
});
buffer.push(' */\n');
},
member: function(buffer, ast) {
if (ast.private || ast.internal) return;
buffer.push('\n');
this.comment(buffer, ast.content);
if (ast.isStatic) buffer.push('static ');
this.declaration(buffer, ast);
},
interfaceOrClass: function(buffer, ast, isInterface) {
if (ast.abstract) {
buffer.push('abstract ');
}
buffer.push(isInterface ? 'interface ' : 'class ');
buffer.push(ast.name);
buffer.push(ast.typeParams);
buffer.push(ast.heritage);
buffer.push(' {');
buffer.indent();
if (ast.newMember) this.member(buffer, ast.newMember);
if (ast.callMember) this.member(buffer, ast.callMember);
if (ast.constructorDoc) this.member(buffer, ast.constructorDoc);
ast.statics.forEach(function(staticMember) {
this.member(buffer, staticMember);
}.bind(this));
ast.members.forEach(function(member) {
this.member(buffer, member);
}.bind(this));
buffer.unindent();
buffer.push('}');
},
enum: function(buffer, ast) {
buffer.push('enum ');
buffer.push(ast.name);
buffer.push(ast.typeParams);
buffer.push(ast.heritage);
buffer.push(' {');
buffer.indent();
ast.members.forEach(function(member, index) {
buffer.push('\n');
this.comment(buffer, member.content);
buffer.push(member.name);
if (index !== (ast.members.length - 1)) {
buffer.push(',\n');
}
}.bind(this));
buffer.unindent();
buffer.push('}\n');
},
function: function(buffer, ast) {
buffer.push('function ');
this.declaration(buffer, ast);
},
var: function(buffer, ast) {
buffer.push('var ');
this.declaration(buffer, ast);
},
let: function(buffer, ast) {
buffer.push('let ');
this.declaration(buffer, ast);
},
const: function(buffer, ast) {
buffer.push('const ');
this.declaration(buffer, ast);
},
typeAlias: function(buffer, ast) {
buffer.push('type ', ast.name, ' = ', ast.returnType);
},
serializeExport: function(ast) {
var buffer = new Buffer();
buffer.push('\n');
try {
this.comment(buffer, ast.content);
switch (ast.docType) {
case 'class': this.interfaceOrClass(buffer, ast, false); break;
case 'interface': this.interfaceOrClass(buffer, ast, true); break;
case 'function': this.function(buffer, ast); break;
case 'enum': this.enum(buffer, ast); break;
case 'var': this.var(buffer, ast); break;
case 'let': this.let(buffer, ast); break;
case 'const': this.const(buffer, ast); break;
case 'type-alias': this.typeAlias(buffer, ast); break;
default: throw new Error("unknown docType: " + ast.docType);
}
var string = buffer.toString();
for (var key in this.remap) {
if (this.remap.hasOwnProperty(key)) {
string = string.replace(new RegExp('\\b' + key + '\\b', 'gm'), this.remap[key]);
}
}
return string;
} catch (e) {
console.log(e.toString(), e.stack);
return 'ERROR: ' + e.toString();
}
}
};
function Buffer() {
this._globalBuffer = [];
this._indentedBuffer = [];
this._indentationLevel = 1;
}
Buffer.prototype = {
constructor: Buffer,
push: function() {
this._indentedBuffer.push.apply(this._indentedBuffer, arguments);
},
indent: function() {
this._globalBuffer.push({indentationLevel: this._indentationLevel, content: this._indentedBuffer.join('')});
this._indentationLevel++;
this._indentedBuffer = [];
},
unindent: function() {
this._globalBuffer.push({indentationLevel: this._indentationLevel, content: this._indentedBuffer.join('')});
this._indentationLevel--;
this._indentedBuffer = [];
},
toString: function() {
if (this._indentationLevel !== 1) {
throw new Exception("Forgot to unindent? Indentation level: " + this._indentationLevel);
}
this.unindent();
var string = '';
this._globalBuffer.forEach(function(indentedChunk) {
var indentation = (new Array(indentedChunk.indentationLevel * 2 + 1)).join(' ');
indentedChunk.content.split('\n').forEach(function(line) {
string += indentation + line + '\n';
});
});
return string;
}
};
function isConstructor(ast) {
return ast.parameters && ast.name === "constructor";
}
module.exports = {
DtsSerializer: DtsSerializer
};

View File

@ -1,72 +0,0 @@
var _ = require('lodash');
var path = require('canonical-path');
var codeGen = require('./code_gen.js');
module.exports = function createTypeDefinitionFile(log, convertPrivateClassesToInterfaces) {
return {
$runAfter: ['processing-docs'],
$runBefore: ['docs-processed'],
$validate: {
dtsPath: { presence: true },
dtsExtension: { presence: true },
typeDefinitions: { presence: true }
},
dtsPath: 'typings',
dtsExtension: '.d.ts',
typeDefinitions: [],
$process: function(docs) {
var dtsPath = this.dtsPath;
var dtsExtension = this.dtsExtension;
// For each type definition that we wish to create we define a dgeni "doc" for it
var typeDefDocs = _.map(this.typeDefinitions, function(def) {
var id = def.id + dtsExtension;
var docPath = path.join(dtsPath, id);
return {
docType: 'type-definition',
id: id,
aliases: [id],
path: docPath,
outputPath: docPath,
// A type definition may include a number of top level modules
// And those modules could be aliased (such as 'angular2/angular2.api' ->
// 'angular2/angular2')
moduleDocs: _.transform(def.modules,
function(moduleDocs, props, alias) {
moduleDocs[props.id] = {
id: alias,
doc: null, namespace: props.namespace,
references: def.references
};
}),
dts: new codeGen.DtsSerializer(def.remapTypes)
};
});
// Now add all the module docs to their corresponding type definition doc
_.forEach(docs, function(doc) {
_.forEach(typeDefDocs, function(typeDefDoc) {
if(typeDefDoc.moduleDocs[doc.id]) {
// Add a copy, because we are going to modify it
typeDefDoc.moduleDocs[doc.id].doc = doc;
}
});
});
return _.filter(typeDefDocs, function(doc) {
_.forEach(doc.moduleDocs, function(modDoc, alias) {
if (!doc || !modDoc.doc) {
log.error('createTypeDefinitionFile processor: no such module "' + alias + '" (Did you forget to add it to the modules to load?)');
doc = null;
return;
}
convertPrivateClassesToInterfaces(modDoc.doc.exports, true);
});
return !!doc;
});
}
};
};

View File

@ -1,53 +0,0 @@
var mockPackage = require('../mocks/mockPackage');
var Dgeni = require('dgeni');
var path = require('canonical-path');
var _ = require('lodash');
describe('createTypeDefinitionFile processor', function() {
var dgeni, injector, processor;
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
processor = injector.get('createTypeDefinitionFile');
// Initialize the processor
processor.typeDefinitions = [{
id: 'angular2/angular2',
modules: {
'angular2/angular2': {
id: 'angular2/angular2',
namespace: 'ng'
}
}
}];
});
describe('classes with @internal constructors', function() {
it('should convert heritage from `implements` into `extends`', function() {
// Create some mock docs for testing
var docs = [
{
id: 'angular2/angular2',
exports: [
{ docType: 'class', heritage: 'implements Xyz', constructorDoc: { internal: true } }
]
}
];
docs = processor.$process(docs);
expect(docs.length).toEqual(1);
expect(docs[0].docType).toEqual('type-definition');
var moduleDoc = docs[0].moduleDocs['angular2/angular2'].doc;
expect(moduleDoc.exports.length).toEqual(2);
expect(moduleDoc.exports[0].heritage).toEqual('extends Xyz');
});
});
});

View File

@ -1,17 +0,0 @@
{% extends '../type-definition.template.html' %}
{% block staticDeclarations %}
interface Map<K,V> {}
{% for alias, module in doc.moduleDocs %}
declare module {$ module.namespace $} {
// See https://github.com/Microsoft/TypeScript/issues/1168
class BaseException /* extends Error */ {
message: string;
stack: string;
toString(): string;
}
interface InjectableReference {}
}
{% endfor %}
{% endblock %}

View File

@ -1,43 +0,0 @@
{%- macro commentBlock(doc, level) -%}
{%- if doc.content | trim %}
{% if level > 1 %}{$ '/**' | indent(level-1, true) | replace(r/\n$/, "") $}{% else %}/**{% endif %}
{$ doc.content | trim | replace(r/^/gm, "* ") | indent(level, true) | replace(r/\n$/, "") $}
{$ '*/' | indent(level, true) | replace(r/\n$/, "") $}{% endif -%}
{%- endmacro -%}
// Type definitions for Angular v{$ versionInfo.currentVersion.full | replace(r/\+/, "_") $}
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
{% for alias, module in doc.moduleDocs %}
{%- if module.references.length %}
// {$ alias $} depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
{%- endif %}
{% for reference in module.references %}
///<reference path="{$ reference $}"/>{% endfor %}{% endfor %}
{% block staticDeclarations %}{% endblock %}
{% for alias, module in doc.moduleDocs %}
{$ commentBlock(module.doc, 1) $}
declare module {$ module.namespace $} {
{%- for export in module.doc.exports -%}
{$ doc.dts.serializeExport(export) $}
{% endfor %}
}
declare module "{$ alias $}" {
export = {$ module.namespace $};
}
{% endfor %}

View File

@ -1,74 +0,0 @@
var basePackage = require('dgeni-packages/base');
var jsdocPackage = require('dgeni-packages/jsdoc');
var Package = require('dgeni').Package;
var path = require('canonical-path');
// Define the dgeni package for generating the docs
module.exports = new Package('typescript-parsing', [basePackage, jsdocPackage])
// Register the services and file readers
.factory(require('./services/modules'))
.factory(require('./services/tsParser'))
.factory(require('./services/tsParser/createCompilerHost'))
.factory(require('./services/tsParser/getFileInfo'))
.factory(require('./services/tsParser/getExportDocType'))
.factory(require('./services/tsParser/getContent'))
.factory(require('./services/convertPrivateClassesToInterfaces'))
.factory('EXPORT_DOC_TYPES', function() {
return [
'class',
'interface',
'function',
'var',
'const',
'enum',
'type-alias'
];
})
// Register the processors
.processor(require('./processors/readTypeScriptModules'))
// Configure the log service
.config(function(log) {
log.level = 'warn';
})
.config(function(parseTagsProcessor) {
parseTagsProcessor.tagDefinitions.push({ name: 'internal', transforms: function() { return true; } });
})
// Configure ids and paths
.config(function(computeIdsProcessor, computePathsProcessor, EXPORT_DOC_TYPES) {
computeIdsProcessor.idTemplates.push({
docTypes: ['member'],
idTemplate: '${classDoc.id}.${name}',
getAliases: function(doc) { return [doc.id]; }
});
computePathsProcessor.pathTemplates.push({
docTypes: ['member'],
pathTemplate: '${classDoc.path}/${name}',
getOutputPath: function() {} // These docs are not written to their own file, instead they are part of their class doc
});
var MODULES_DOCS_PATH = 'partials/modules';
computePathsProcessor.pathTemplates.push({
docTypes: ['module'],
pathTemplate: '/${id}',
outputPathTemplate: MODULES_DOCS_PATH + '/${id}/index.html'
});
computePathsProcessor.pathTemplates.push({
docTypes: EXPORT_DOC_TYPES,
pathTemplate: '${moduleDoc.path}/${name}',
outputPathTemplate: MODULES_DOCS_PATH + '/${path}/index.html'
});
});

View File

@ -1,11 +0,0 @@
var Package = require('dgeni').Package;
module.exports = function mockPackage() {
return new Package('mockPackage', [require('../')])
// provide a mock log service
.factory('log', function() { return require('dgeni/lib/mocks/log')(false); })
.factory('templateEngine', function() { return {}; });
};

View File

@ -1,4 +0,0 @@
export var __esModule = true;
export class OKToExport {}
export function _thisIsPrivate() {}
export var thisIsOK = '!';

View File

@ -1,5 +0,0 @@
export interface MyInterface {
optionalProperty? : string
<T, U extends Findable<T>>(param: T) : U
new (param: number) : MyInterface
}

View File

@ -1,6 +0,0 @@
export class Test {
firstItem;
constructor() { this.doStuff(); }
otherMethod() {}
doStuff() {}
}

View File

@ -1 +0,0 @@
export var x = 10;

View File

@ -1 +0,0 @@
export { x as y} from './privateModule';

View File

@ -1 +0,0 @@
export var x = 100;

View File

@ -1,34 +0,0 @@
/**
* @module
* @description
* This is the module description
*/
export * from 'importedSrc';
/**
* This is some random other comment
*/
/**
* This is MyClass
*/
export class MyClass {
message: String;
/**
* Create a new MyClass
* @param {String} name The name to say hello to
*/
constructor(name) { this.message = 'hello ' + name; }
/**
* Return a greeting message
*/
greet() { return this.message; }
}
/**
* An exported function
*/
export var myFn = (val: number) => return val * 2;

View File

@ -1,413 +0,0 @@
var glob = require('glob');
var path = require('canonical-path');
var _ = require('lodash');
var ts = require('typescript');
module.exports = function readTypeScriptModules(tsParser, modules, getFileInfo,
getExportDocType, getContent, log) {
return {
$runAfter: ['files-read'],
$runBefore: ['parsing-tags'],
$validate: {
sourceFiles: {presence: true},
basePath: {presence: true},
hidePrivateMembers: {inclusion: [true, false]},
sortClassMembers: {inclusion: [true, false]},
ignoreExportsMatching: {}
},
// A collection of globs that identify those modules for which we should create docs
sourceFiles: [],
// The base path from which to load the source files
basePath: '.',
// We can ignore members of classes that are private
hidePrivateMembers: true,
// We leave class members sorted in order of declaration
sortClassMembers: false,
// We can provide a collection of strings or regexes to ignore exports whose export names match
ignoreExportsMatching: ['___esModule'],
$process: function(docs) {
// Convert ignoreExportsMatching to an array of regexes
var ignoreExportsMatching = convertToRegexCollection(this.ignoreExportsMatching);
var hidePrivateMembers = this.hidePrivateMembers;
var sortClassMembers = this.sortClassMembers;
var basePath = path.resolve(this.basePath);
var filesPaths = expandSourceFiles(this.sourceFiles, basePath);
var parseInfo = tsParser.parse(filesPaths, this.basePath);
var moduleSymbols = parseInfo.moduleSymbols;
// Iterate through each of the modules that were parsed and generate a module doc
// as well as docs for each module's exports.
moduleSymbols.forEach(function(moduleSymbol) {
var moduleDoc = createModuleDoc(moduleSymbol, basePath);
// Add this module doc to the module lookup collection and the docs collection
modules[moduleDoc.id] = moduleDoc;
docs.push(moduleDoc);
// Iterate through this module's exports and generate a doc for each
moduleSymbol.exportArray.forEach(function(exportSymbol) {
// Ignore exports starting with an underscore
if (anyMatches(ignoreExportsMatching, exportSymbol.name)) return;
// If the symbol is an Alias then for most things we want the original resolved symbol
var resolvedExport = exportSymbol.resolvedSymbol || exportSymbol;
var exportDoc = createExportDoc(exportSymbol.name, resolvedExport, moduleDoc, basePath, parseInfo.typeChecker);
log.debug('>>>> EXPORT: ' + exportDoc.name + ' (' + exportDoc.docType + ') from ' + moduleDoc.id);
exportDoc.members = [];
exportDoc.statics = [];
// Generate docs for each of the export's members
if (resolvedExport.flags & ts.SymbolFlags.HasMembers) {
for(var memberName in resolvedExport.members) {
// FIXME(alexeagle): why do generic type params appear in members?
if (memberName === 'T') {
continue;
}
log.silly('>>>>>> member: ' + memberName + ' from ' + exportDoc.id + ' in ' + moduleDoc.id);
var memberSymbol = resolvedExport.members[memberName];
var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker);
// We special case the constructor and sort the other members alphabetically
if (memberSymbol.flags & ts.SymbolFlags.Constructor) {
exportDoc.constructorDoc = memberDoc;
docs.push(memberDoc);
} else if (!hidePrivateMembers || memberSymbol.name.charAt(0) !== '_') {
docs.push(memberDoc);
exportDoc.members.push(memberDoc);
} else if (memberSymbol.name === '__call' && memberSymbol.flags & ts.SymbolFlags.Signature) {
docs.push(memberDoc);
exportDoc.callMember = memberDoc;
} else if (memberSymbol.name === '__new' && memberSymbol.flags & ts.SymbolFlags.Signature) {
docs.push(memberDoc);
exportDoc.newMember = memberDoc;
}
}
}
if (exportDoc.docType === 'enum') {
for(var memberName in resolvedExport.exports) {
log.silly('>>>>>> member: ' + memberName + ' from ' + exportDoc.id + ' in ' + moduleDoc.id);
var memberSymbol = resolvedExport.exports[memberName];
var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker);
docs.push(memberDoc);
exportDoc.members.push(memberDoc);
}
} else if (resolvedExport.flags & ts.SymbolFlags.HasExports) {
for (var exported in resolvedExport.exports) {
if (exported === 'prototype') continue;
if (hidePrivateMembers && exported.charAt(0) === '_') continue;
var memberSymbol = resolvedExport.exports[exported];
var memberDoc = createMemberDoc(memberSymbol, exportDoc, basePath, parseInfo.typeChecker);
memberDoc.isStatic = true;
docs.push(memberDoc);
exportDoc.statics.push(memberDoc);
}
}
if (sortClassMembers) {
exportDoc.members.sort(function(a, b) {
if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
return 0;
});
}
// Add this export doc to its module doc
moduleDoc.exports.push(exportDoc);
docs.push(exportDoc);
});
});
}
};
function createModuleDoc(moduleSymbol, basePath) {
var id = moduleSymbol.name.replace(/^"|"$/g, '');
var moduleDoc = {
docType: 'module',
id: id,
aliases: [id],
moduleTree: moduleSymbol,
content: getContent(moduleSymbol),
exports: [],
fileInfo: getFileInfo(moduleSymbol, basePath),
location: getLocation(moduleSymbol)
};
return moduleDoc;
}
function createExportDoc(name, exportSymbol, moduleDoc, basePath, typeChecker) {
var typeParamString = '';
var heritageString = '';
var typeDefinition = '';
exportSymbol.declarations.forEach(function(decl) {
var sourceFile = ts.getSourceFileOfNode(decl);
if (decl.typeParameters) {
typeParamString = '<' + getText(sourceFile, decl.typeParameters) + '>';
}
if (decl.symbol.flags & ts.SymbolFlags.TypeAlias) {
typeDefinition = getText(sourceFile, decl.type);
}
if (decl.heritageClauses) {
decl.heritageClauses.forEach(function(heritage) {
if (heritage.token == ts.SyntaxKind.ExtendsKeyword) {
heritageString += " extends";
heritage.types.forEach(function(typ, idx) {
heritageString += (idx > 0 ? ',' : '') + typ.getFullText();
});
}
if (heritage.token == ts.SyntaxKind.ImplementsKeyword) {
heritageString += " implements";
heritage.types.forEach(function(typ, idx) {
heritageString += (idx > 0 ? ', ' : '') + typ.getFullText();
});
}
});
}
});
//Make sure duplicate aliases aren't created, so "Ambiguous link" warnings are prevented
var aliasNames = [name, moduleDoc.id + '/' + name];
if (typeParamString) {
aliasNames.push(name + typeParamString);
aliasNames.push(moduleDoc.id + '/' + name + typeParamString);
}
var exportDoc = {
docType: getExportDocType(exportSymbol),
name: name,
id: moduleDoc.id + '/' + name,
typeParams: typeParamString,
heritage: heritageString,
decorators: getDecorators(exportSymbol),
aliases: aliasNames,
moduleDoc: moduleDoc,
content: getContent(exportSymbol),
fileInfo: getFileInfo(exportSymbol, basePath),
location: getLocation(exportSymbol)
};
if (exportDoc.docType === 'var' || exportDoc.docType === 'const') {
exportDoc.symbolTypeName = exportSymbol.valueDeclaration.type &&
exportSymbol.valueDeclaration.type.typeName &&
exportSymbol.valueDeclaration.type.typeName.text;
}
if (exportDoc.docType === 'type-alias') {
exportDoc.returnType = getReturnType(typeChecker, exportSymbol);
}
if(exportSymbol.flags & ts.SymbolFlags.Function) {
exportDoc.parameters = getParameters(typeChecker, exportSymbol);
}
if(exportSymbol.flags & ts.SymbolFlags.Value) {
exportDoc.returnType = getReturnType(typeChecker, exportSymbol);
}
if (exportSymbol.flags & ts.SymbolFlags.TypeAlias) {
exportDoc.typeDefinition = typeDefinition;
}
if (isAbstract(exportSymbol)) {
exportDoc.abstract = true;
}
// Compute the original module name from the relative file path
exportDoc.originalModule = exportDoc.fileInfo.relativePath
.replace(new RegExp('\.' + exportDoc.fileInfo.extension + '$'), '');
return exportDoc;
}
function createMemberDoc(memberSymbol, classDoc, basePath, typeChecker) {
var memberDoc = {
docType: 'member',
classDoc: classDoc,
name: memberSymbol.name,
decorators: getDecorators(memberSymbol),
content: getContent(memberSymbol),
fileInfo: getFileInfo(memberSymbol, basePath),
location: getLocation(memberSymbol)
};
memberDoc.typeParameters = getTypeParameters(typeChecker, memberSymbol);
if(memberSymbol.flags & (ts.SymbolFlags.Signature) ) {
memberDoc.parameters = getParameters(typeChecker, memberSymbol);
memberDoc.returnType = getReturnType(typeChecker, memberSymbol);
switch(memberDoc.name) {
case '__call':
memberDoc.name = '';
break;
case '__new':
memberDoc.name = 'new';
break;
}
}
if (memberSymbol.flags & ts.SymbolFlags.Method) {
// NOTE: we use the property name `parameters` here so we don't conflict
// with the `params` property that will be updated by dgeni reading the
// `@param` tags from the docs
memberDoc.parameters = getParameters(typeChecker, memberSymbol);
}
if (memberSymbol.flags & ts.SymbolFlags.Constructor) {
memberDoc.parameters = getParameters(typeChecker, memberSymbol);
memberDoc.name = 'constructor';
}
if(memberSymbol.flags & ts.SymbolFlags.Value) {
memberDoc.returnType = getReturnType(typeChecker, memberSymbol);
}
if(memberSymbol.flags & ts.SymbolFlags.Optional) {
memberDoc.optional = true;
}
return memberDoc;
}
function getDecorators(symbol) {
var declaration = symbol.valueDeclaration || symbol.declarations[0];
var sourceFile = ts.getSourceFileOfNode(declaration);
var decorators = declaration.decorators && declaration.decorators.map(function(decorator) {
decorator = decorator.expression;
return {
name: decorator.expression ? decorator.expression.text : decorator.text,
arguments: decorator.arguments && decorator.arguments.map(function(argument) {
return getText(sourceFile, argument).trim();
})
};
});
return decorators;
}
function getParameters(typeChecker, symbol) {
var declaration = symbol.valueDeclaration || symbol.declarations[0];
var sourceFile = ts.getSourceFileOfNode(declaration);
if (!declaration.parameters) {
var location = getLocation(symbol);
throw new Error('missing declaration parameters for "' + symbol.name +
'" in ' + sourceFile.fileName +
' at line ' + location.start.line);
}
return declaration.parameters.map(function(parameter) {
var paramText = '';
if (parameter.dotDotDotToken) {
paramText += '...';
}
paramText += getText(sourceFile, parameter.name);
if (parameter.questionToken || parameter.initializer) {
paramText += '?';
}
if (parameter.type) {
paramText += ':' + getType(sourceFile, parameter.type);
} else {
paramText += ': any';
if (parameter.dotDotDotToken) {
paramText += '[]';
}
}
return paramText.trim();
});
}
function getTypeParameters(typeChecker, symbol) {
var declaration = symbol.valueDeclaration || symbol.declarations[0];
var sourceFile = ts.getSourceFileOfNode(declaration);
if (!declaration.typeParameters) return;
var typeParams = declaration.typeParameters.map(function(type) {
return getText(sourceFile, type).trim();
});
return typeParams;
}
function getReturnType(typeChecker, symbol) {
var declaration = symbol.valueDeclaration || symbol.declarations[0];
var sourceFile = ts.getSourceFileOfNode(declaration);
if (declaration.type) {
return getType(sourceFile, declaration.type).trim();
}
}
function isAbstract(symbol) {
var declaration = symbol.valueDeclaration || symbol.declarations[0];
return declaration.flags & ts.NodeFlags.Abstract;
}
function expandSourceFiles(sourceFiles, basePath) {
var filePaths = [];
sourceFiles.forEach(function(sourcePattern) {
filePaths = filePaths.concat(glob.sync(sourcePattern, { cwd: basePath }));
});
return filePaths;
}
function getText(sourceFile, node) {
return sourceFile.text.substring(node.pos, node.end);
}
// Strip any local renamed imports from the front of types
function getType(sourceFile, type) {
var text = getText(sourceFile, type);
while (text.indexOf(".") >= 0) {
// Keep namespaced symbols in RxNext
if (text.match(/^\s*RxNext\./)) break;
// handle the case List<thing.stuff> -> List<stuff>
text = text.replace(/([^.<]*)\.([^>]*)/, "$2");
}
return text;
}
function getLocation(symbol) {
var node = symbol.valueDeclaration || symbol.declarations[0];
var sourceFile = ts.getSourceFileOfNode(node);
var location = {
start: ts.getLineAndCharacterOfPosition(sourceFile, node.pos),
end: ts.getLineAndCharacterOfPosition(sourceFile, node.end)
};
return location;
}
};
function convertToRegexCollection(items) {
if (!items) return [];
// Must be an array
if (!_.isArray(items)) {
items = [items];
}
// Convert string to exact matching regexes
return items.map(function(item) {
return _.isString(item) ? new RegExp('^' + item + '$') : item;
});
}
function anyMatches(regexes, item) {
for(var i=0; i<regexes.length; ++i) {
if ( item.match(regexes[i]) ) return true;
}
return false;
}

View File

@ -1,127 +0,0 @@
var mockPackage = require('../mocks/mockPackage');
var Dgeni = require('dgeni');
var path = require('canonical-path');
var _ = require('lodash');
describe('readTypeScriptModules', function() {
var dgeni, injector, processor;
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
processor = injector.get('readTypeScriptModules');
processor.basePath = path.resolve(__dirname, '../mocks/readTypeScriptModules');
});
describe('exportDocs', function() {
it('should provide the original module if the export is re-exported', function() {
processor.sourceFiles = [ 'publicModule.ts' ];
var docs = [];
processor.$process(docs);
var exportedDoc = docs[1];
expect(exportedDoc.originalModule).toEqual('privateModule');
});
});
describe('ignoreExportsMatching', function() {
it('should ignore exports that match items in the `ignoreExportsMatching` property', function() {
processor.sourceFiles = [ 'ignoreExportsMatching.ts'];
processor.ignoreExportsMatching = [/^_/];
var docs = [];
processor.$process(docs);
var moduleDoc = docs[0];
expect(moduleDoc.docType).toEqual('module');
expect(moduleDoc.exports).toEqual([
jasmine.objectContaining({ name: 'OKToExport' }),
jasmine.objectContaining({ name: 'thisIsOK' })
]);
});
it('should only ignore `___esModule` exports by default', function() {
processor.sourceFiles = [ 'ignoreExportsMatching.ts'];
var docs = [];
processor.$process(docs);
var moduleDoc = docs[0];
expect(moduleDoc.docType).toEqual('module');
expect(getNames(moduleDoc.exports)).toEqual([
'OKToExport',
'_thisIsPrivate',
'thisIsOK'
]);
});
});
describe('interfaces', function() {
it('should mark optional properties', function() {
processor.sourceFiles = [ 'interfaces.ts'];
var docs = [];
processor.$process(docs);
var moduleDoc = docs[0];
var exportedInterface = moduleDoc.exports[0];
var member = exportedInterface.members[0];
expect(member.name).toEqual('optionalProperty');
expect(member.optional).toEqual(true);
});
it('should handle "call" type interfaces', function() {
processor.sourceFiles = [ 'interfaces.ts'];
var docs = [];
processor.$process(docs);
var moduleDoc = docs[0];
var exportedInterface = moduleDoc.exports[0];
expect(exportedInterface.callMember).toBeDefined();
expect(exportedInterface.callMember.parameters).toEqual(['param: T']);
expect(exportedInterface.callMember.returnType).toEqual('U');
expect(exportedInterface.callMember.typeParameters).toEqual(['T', 'U extends Findable<T>']);
expect(exportedInterface.newMember).toBeDefined();
expect(exportedInterface.newMember.parameters).toEqual(['param: number']);
expect(exportedInterface.newMember.returnType).toEqual('MyInterface');
});
});
describe('ordering of members', function() {
it('should order class members in order of appearance (by default)', function() {
processor.sourceFiles = ['orderingOfMembers.ts'];
var docs = [];
processor.$process(docs);
var classDoc = _.find(docs, { docType: 'class' });
expect(classDoc.docType).toEqual('class');
expect(getNames(classDoc.members)).toEqual([
'firstItem',
'otherMethod',
'doStuff',
]);
});
it('should not order class members if not sortClassMembers is false', function() {
processor.sourceFiles = ['orderingOfMembers.ts'];
processor.sortClassMembers = false;
var docs = [];
processor.$process(docs);
var classDoc = _.find(docs, { docType: 'class' });
expect(classDoc.docType).toEqual('class');
expect(getNames(classDoc.members)).toEqual([
'firstItem',
'otherMethod',
'doStuff'
]);
});
});
});
function getNames(collection) {
return collection.map(function(item) { return item.name; });
}

View File

@ -1,31 +0,0 @@
var _ = require('lodash');
module.exports = function convertPrivateClassesToInterfaces() {
return function(exportDocs, addInjectableReference) {
_.forEach(exportDocs, function(exportDoc) {
// Search for classes with a constructor marked as `@internal`
if (exportDoc.docType === 'class' && exportDoc.constructorDoc && exportDoc.constructorDoc.internal) {
// Convert this class to an interface with no constructor
exportDoc.docType = 'interface';
exportDoc.constructorDoc = null;
if (exportDoc.heritage) {
// convert the heritage since interfaces use `extends` not `implements`
exportDoc.heritage = exportDoc.heritage.replace('implements', 'extends');
}
if (addInjectableReference) {
// Add the `declare var SomeClass extends InjectableReference` construct
exportDocs.push({
docType: 'var',
name: exportDoc.name,
id: exportDoc.id,
returnType: 'InjectableReference'
});
}
}
});
};
};

View File

@ -1,76 +0,0 @@
var mockPackage = require('../mocks/mockPackage');
var Dgeni = require('dgeni');
var _ = require('lodash');
describe('readTypeScriptModules', function() {
var dgeni, injector, convertPrivateClassesToInterfaces;
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
convertPrivateClassesToInterfaces = injector.get('convertPrivateClassesToInterfaces');
});
it('should convert @internal class docs to interface docs', function() {
var docs = [
{
docType: 'class',
name: 'privateClass',
id: 'privateClass',
constructorDoc: { internal: true }
}
];
convertPrivateClassesToInterfaces(docs, false);
expect(docs[0].docType).toEqual('interface');
});
it('should not touch non-internal class docs', function() {
var docs = [
{
docType: 'class',
name: 'privateClass',
id: 'privateClass',
constructorDoc: { }
}
];
convertPrivateClassesToInterfaces(docs, false);
expect(docs[0].docType).toEqual('class');
});
it('should convert the heritage since interfaces use `extends` not `implements`', function() {
var docs = [
{
docType: 'class',
name: 'privateClass',
id: 'privateClass',
constructorDoc: { internal: true },
heritage: 'implements parentInterface'
}
];
convertPrivateClassesToInterfaces(docs, false);
expect(docs[0].heritage).toEqual('extends parentInterface');
});
it('should add new injectable reference types, if specified, to the passed in collection', function() {
var docs = [
{
docType: 'class',
name: 'privateClass',
id: 'privateClass',
constructorDoc: { internal: true },
heritage: 'implements parentInterface'
}
];
convertPrivateClassesToInterfaces(docs, true);
expect(docs[1]).toEqual({
docType : 'var',
name : 'privateClass',
id : 'privateClass',
returnType : 'InjectableReference'
});
});
});

View File

@ -1,3 +0,0 @@
module.exports = function modules() {
return {};
};

View File

@ -1,75 +0,0 @@
var ts = require('typescript');
var fs = require('fs');
var path = require('canonical-path');
// We need to provide our own version of CompilerHost because we want to set the
// base directory and specify what extensions to consider when trying to load a source
// file
module.exports = function createCompilerHost(log) {
return function createCompilerHost(options, baseDir, extensions) {
return {
getSourceFile: function(fileName, languageVersion, onError) {
var text, resolvedPath, resolvedPathWithExt;
// Strip off the extension and resolve relative to the baseDir
baseFilePath = fileName.replace(/\.[^.]+$/, '');
resolvedPath = path.resolve(baseDir, baseFilePath);
// Iterate through each possible extension and return the first source file that is actually found
for(var i=0; i<extensions.length; i++) {
// Try reading the content from files using each of the given extensions
try {
resolvedPathWithExt = resolvedPath + extensions[i];
log.silly('getSourceFile:', resolvedPathWithExt);
text = fs.readFileSync(resolvedPathWithExt, { encoding: options.charset });
log.debug('found source file:', fileName, resolvedPathWithExt);
return ts.createSourceFile(baseFilePath + extensions[i], text, languageVersion);
}
catch(e) {
// Try again if the file simply did not exist, otherwise report the error as a warning
if(e.code !== 'ENOENT') {
if (onError) onError(e.message);
log.warn('Error reading ' + resolvedPathWithExt + ' : ' + e.message);
}
}
}
},
getDefaultLibFileName: function(options) {
return path.resolve(path.dirname(ts.sys.getExecutingFilePath()), ts.getDefaultLibFileName(options));
},
writeFile: function(fileName, data, writeByteOrderMark, onError) {
// no-op
},
getCurrentDirectory: function() {
return baseDir;
},
useCaseSensitiveFileNames: function() {
return ts.sys.useCaseSensitiveFileNames;
},
getCanonicalFileName: function(fileName) {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
},
getNewLine: function() {
return ts.sys.newLine;
},
fileExists: function(fileName) {
var resolvedPath = path.resolve(baseDir, fileName);
try {
fs.statSync(resolvedPath);
return true;
} catch (e) {
return false;
}
},
readFile: function(fileName) {
var resolvedPath = path.resolve(baseDir, fileName);
return fs.readFileSync(resolvedPath, { encoding: options.charset });
}
};
};
};

View File

@ -1,80 +0,0 @@
var mockPackage = require('../../mocks/mockPackage');
var Dgeni = require('dgeni');
var path = require('canonical-path');
var ts = require('typescript');
describe('createCompilerHost', function() {
var dgeni, injector, options, host, baseDir, extensions;
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
var createCompilerHost = injector.get('createCompilerHost');
options = { charset: 'utf8' };
baseDir = path.resolve(__dirname, '../../mocks/tsParser');
extensions = ['.ts', '.js'];
host = createCompilerHost(options, baseDir, extensions);
});
describe('getSourceFile', function() {
it('should return a SourceFile object for a given path, with fileName relative to baseDir', function() {
var sourceFile = host.getSourceFile('testSrc.ts');
expect(sourceFile.fileName).toEqual('testSrc.ts');
expect(sourceFile.pos).toEqual(0);
expect(sourceFile.text).toEqual(jasmine.any(String));
});
it('should try each of the configured extensions and update the filename to the correct extension', function() {
var sourceFile = host.getSourceFile('testSrc.js');
expect(sourceFile.fileName).toEqual('testSrc.ts');
sourceFile = host.getSourceFile('../mockPackage.ts');
expect(sourceFile.fileName).toEqual('../mockPackage.js');
});
});
describe('getDefaultLibFileName', function() {
it('should return a path to the default library', function() {
expect(host.getDefaultLibFileName(options)).toContain('typescript/lib/lib.d.ts');
});
});
describe('writeFile', function() {
it('should do nothing', function() {
host.writeFile();
});
});
describe('getCurrentDirectory', function() {
it('should return the baseDir', function() {
expect(host.getCurrentDirectory()).toEqual(baseDir);
});
});
describe('useCaseSensitiveFileNames', function() {
it('should return true if the OS is case sensitive', function() {
expect(host.useCaseSensitiveFileNames()).toBe(ts.sys.useCaseSensitiveFileNames);
});
});
describe('getCanonicalFileName', function() {
it('should lower case the filename', function() {
var expectedFilePath = host.useCaseSensitiveFileNames() ? 'SomeFile.ts' : 'somefile.ts';
expect(host.getCanonicalFileName('SomeFile.ts')).toEqual(expectedFilePath);
});
});
describe('getNewLine', function() {
it('should return the newline character for the OS', function() {
expect(host.getNewLine()).toEqual(require('os').EOL);
});
});
});

View File

@ -1,49 +0,0 @@
var ts = require('typescript');
var LEADING_STAR = /^[^\S\r\n]*\*[^\S\n\r]?/gm;
module.exports = function getContent() {
return function(symbol) {
var content = "";
if (!symbol.declarations) return content;
symbol.declarations.forEach(function(declaration) {
// If this is left side of dotted module declaration, there is no doc comment associated with this declaration
if (declaration.kind === ts.SyntaxKind.ModuleDeclaration && declaration.body.kind === ts.SyntaxKind.ModuleDeclaration) {
return content;
}
// If this is dotted module name, get the doc comments from the parent
while (declaration.kind === ts.SyntaxKind.ModuleDeclaration && declaration.parent.kind === ts.SyntaxKind.ModuleDeclaration) {
declaration = declaration.parent;
}
// If this is a variable declaration then we get the doc comments from the grand parent
if (declaration.kind === ts.SyntaxKind.VariableDeclaration) {
declaration = declaration.parent.parent;
}
// Get the source file of this declaration
var sourceFile = ts.getSourceFileOfNode(declaration);
var commentRanges = ts.getJsDocComments(declaration, sourceFile);
if (commentRanges) {
commentRanges.forEach(function(commentRange) {
content += sourceFile.text
.substring(commentRange.pos+ '/**'.length, commentRange.end - '*/'.length)
.replace(LEADING_STAR, '')
.trim();
if (commentRange.hasTrailingNewLine) {
content += '\n';
}
});
}
content += '\n';
});
return content;
};
};

View File

@ -1,54 +0,0 @@
var ts = require('typescript');
module.exports = function getExportDocType(log) {
return function(symbol) {
if(symbol.flags & ts.SymbolFlags.Function) {
return 'function';
}
if(symbol.flags & ts.SymbolFlags.Class) {
return 'class';
}
if(symbol.flags & ts.SymbolFlags.Interface) {
return 'interface';
}
if(symbol.flags & ts.SymbolFlags.ConstEnum) {
return 'enum';
}
if(symbol.flags & ts.SymbolFlags.RegularEnum) {
return 'enum';
}
if(symbol.flags & ts.SymbolFlags.Property) {
return 'module-property';
}
if(symbol.flags & ts.SymbolFlags.TypeAlias) {
return 'type-alias';
}
if(symbol.flags & ts.SymbolFlags.FunctionScopedVariable) {
return 'var';
}
if(symbol.flags & ts.SymbolFlags.BlockScopedVariable) {
return getBlockScopedVariableDocType(symbol);
}
log.warn('getExportDocType(): Unknown symbol type', {
symbolName: symbol.name,
symbolType: symbol.flags,
symbolTarget: symbol.target,
file: ts.getSourceFileOfNode(symbol.declarations[0]).fileName
});
return 'unknown';
};
function getBlockScopedVariableDocType(symbol) {
var node = symbol.valueDeclaration;
while(node) {
if ( node.flags & 0x2000 /* const */) {
return 'const';
}
node = node.parent;
}
return 'let';
}
};

View File

@ -1,20 +0,0 @@
var path = require('canonical-path');
var ts = require('typescript');
module.exports = function getFileInfo(log) {
return function (symbol, basePath) {
var fileName = ts.getSourceFileOfNode(symbol.declarations[0]).fileName;
var file = path.resolve(basePath, fileName);
var fileInfo = {
filePath: file,
baseName: path.basename(file, path.extname(file)),
extension: path.extname(file).replace(/^\./, ''),
basePath: basePath,
relativePath: fileName,
projectRelativePath: fileName
};
return fileInfo;
};
};

View File

@ -1,74 +0,0 @@
var ts = require('typescript');
var path = require('canonical-path');
module.exports = function tsParser(createCompilerHost, log) {
return {
// These are the extension that we should consider when trying to load a module
// During migration from Traceur, there is a mix of `.ts`, `.es6` and `.js` (atScript)
// files in the project and the TypeScript compiler only looks for `.ts` files when trying
// to load imports.
extensions: ['.ts', '.js'],
// The options for the TS compiler
options: {
allowNonTsExtensions: true,
charset: 'utf8'
},
parse: function(fileNames, baseDir) {
// "Compile" a program from the given module filenames, to get hold of a
// typeChecker that can be used to interrogate the modules, exports and so on.
var host = createCompilerHost(this.options, baseDir, this.extensions);
var program = ts.createProgram(fileNames, this.options, host);
var typeChecker = program.getTypeChecker();
// Create an array of module symbols for each file we were given
var moduleSymbols = [];
fileNames.forEach(function(fileName) {
var sourceFile = program.getSourceFile(fileName);
if (!sourceFile) {
throw new Error('Invalid source file: ' + fileName);
} else if (!sourceFile.symbol) {
// Some files contain only a comment and no actual module code
log.warn('No module code found in ' + fileName);
} else {
moduleSymbols.push(sourceFile.symbol);
}
});
moduleSymbols.forEach(function(tsModule) {
// The type checker has a nice helper function that returns an array of Symbols
// representing the exports for a given module
tsModule.exportArray = typeChecker.getExportsOfModule(tsModule);
// Although 'star' imports (e.g. `export * from 'some/module';) get resolved automatically
// by the compiler/binder, it seems that explicit imports (e.g. `export {SomeClass} from 'some/module'`)
// do not so we have to do a little work.
tsModule.exportArray.forEach(function(moduleExport) {
if (moduleExport.flags & ts.SymbolFlags.Alias) {
// To maintain the alias information (particularly the alias name)
// we just attach the original "resolved" symbol to the alias symbol
moduleExport.resolvedSymbol = typeChecker.getAliasedSymbol(moduleExport);
}
});
});
moduleSymbols.typeChecker = typeChecker;
return {
moduleSymbols: moduleSymbols,
typeChecker: typeChecker,
program: program,
host: host
};
}
};
};

View File

@ -1,21 +0,0 @@
var mockPackage = require('../../mocks/mockPackage');
var Dgeni = require('dgeni');
var path = require('canonical-path');
describe('tsParser', function() {
var dgeni, injector, parser;
beforeEach(function() {
dgeni = new Dgeni([mockPackage()]);
injector = dgeni.configureInjector();
parser = injector.get('tsParser');
});
it("should parse a TS file", function() {
var parseInfo = parser.parse(['testSrc.ts'], path.resolve(__dirname, '../../mocks/tsParser'));
var tsModules = parseInfo.moduleSymbols;
expect(tsModules.length).toEqual(1);
expect(tsModules[0].exportArray.length).toEqual(3);
expect(tsModules[0].exportArray.map(function(i) { return i.name; })).toEqual(['MyClass', 'myFn', 'x']);
});
});

View File

@ -418,22 +418,6 @@ gulp.task('serve.e2e.dart', ['build.js.cjs'], function(neverDone) {
}); });
// --------------
// d.ts generation
var Dgeni = require('dgeni');
gulp.task('docs/typings', [], function() {
try {
var dgeni = new Dgeni([require('./docs/typescript-definition-package')]);
return dgeni.generate();
} catch(x) {
console.log(x);
console.log(x.stack);
throw x;
}
});
// ------------------ // ------------------
// CI tests suites // CI tests suites
@ -450,7 +434,7 @@ function runKarma(configFile, done) {
gulp.task('test.js', function(done) { gulp.task('test.js', function(done) {
runSequence('test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci', runSequence('test.unit.tools/ci', 'test.transpiler.unittest', 'test.unit.js/ci',
'test.unit.cjs/ci', 'test.typings', 'test.typings.npm', sequenceComplete(done)); 'test.unit.cjs/ci', 'test.typings', sequenceComplete(done));
}); });
gulp.task('test.dart', function(done) { gulp.task('test.dart', function(done) {
@ -786,52 +770,22 @@ gulp.task('pre-test-checks', function(done) {
// feedback while allowing tests to execute. // feedback while allowing tests to execute.
gulp.task('static-checks', ['!build.tools'], function(done) { gulp.task('static-checks', ['!build.tools'], function(done) {
runSequence( runSequence(
['enforce-format', 'lint', 'test.typings'], // We do not run test.typings here because it requires building, which is too slow.
['enforce-format', 'lint'],
sequenceComplete(done)); sequenceComplete(done));
}); });
gulp.task('!pre.test.typings', ['docs/typings'], function() {
return gulp
.src([
'modules/angular2/typings/**/*'], {
base: 'modules/angular2/typings/**'
}
)
.pipe(gulp.dest('dist/docs/typings/*'));
});
// ----------------- // -----------------
// Tests for the typings we deliver for TS users // Tests for the typings we deliver for TS users
// //
// There are currently two mechanisms for this. // Typings are contained in individual .d.ts files produced by the compiler,
// The first is the legacy, bundled .d.ts file produced by dgeni.
// This is tested by 'test.typings'.
//
// The second is individual .d.ts files produced by the compiler,
// distributed in our npm package, and loaded from node_modules by // distributed in our npm package, and loaded from node_modules by
// the typescript compiler. // the typescript compiler.
// This is tested by 'test.typings.npm'.
//
// During the transition, we support both packaging/delivery types.
// TODO(alexeagle): remove the dgeni bundle when users have switched
gulp.task('test.typings', ['!pre.test.typings'], function() {
return gulp.src(['typing_spec/*.ts', 'dist/docs/typings/angular2/*.d.ts',
'dist/docs/typings/http.d.ts',
'dist/docs/typings/es6-shim/es6-shim.d.ts',
'dist/docs/typings/jasmine/jasmine.d.ts'])
.pipe(tsc({target: 'ES5', module: 'commonjs',
experimentalDecorators: true,
noImplicitAny: true,
// Don't use the version of typescript that gulp-typescript depends on, we need 1.5
// see https://github.com/ivogabe/gulp-typescript#typescript-version
typescript: require('typescript')}));
});
// Make sure the two typings tests are isolated, by running this one in a tempdir // Make sure the two typings tests are isolated, by running this one in a tempdir
var tmpdir = path.join(os.tmpdir(), 'test.typings', new Date().getTime().toString()); var tmpdir = path.join(os.tmpdir(), 'test.typings', new Date().getTime().toString());
gulp.task('!pre.test.typings.layoutNodeModule', function() { gulp.task('!pre.test.typings.layoutNodeModule', ['build.js.cjs'], function() {
return gulp return gulp
.src(['dist/js/cjs/angular2/**/*'], {base: 'dist/js/cjs'}) .src(['dist/js/cjs/angular2/**/*'], {base: 'dist/js/cjs'})
.pipe(gulp.dest(path.join(tmpdir, 'node_modules'))); .pipe(gulp.dest(path.join(tmpdir, 'node_modules')));
@ -841,7 +795,7 @@ gulp.task('!pre.test.typings.copyTypingsSpec', function() {
.src(['typing_spec/basic_spec.ts'], {base: 'typing_spec'}) .src(['typing_spec/basic_spec.ts'], {base: 'typing_spec'})
.pipe(gulp.dest(path.join(tmpdir))); .pipe(gulp.dest(path.join(tmpdir)));
}); });
gulp.task('test.typings.npm', [ gulp.task('test.typings', [
'!pre.test.typings.layoutNodeModule', '!pre.test.typings.layoutNodeModule',
'!pre.test.typings.copyTypingsSpec' '!pre.test.typings.copyTypingsSpec'
], function() { ], function() {

View File

@ -3062,440 +3062,6 @@
} }
} }
}, },
"dgeni": {
"version": "0.4.1",
"dependencies": {
"dependency-graph": {
"version": "0.1.0",
"dependencies": {
"underscore": {
"version": "1.4.4"
}
}
},
"di": {
"version": "0.0.1"
},
"optimist": {
"version": "0.6.1",
"dependencies": {
"wordwrap": {
"version": "0.0.3"
},
"minimist": {
"version": "0.0.10"
}
}
},
"q": {
"version": "0.9.7"
},
"validate.js": {
"version": "0.2.0"
},
"winston": {
"version": "0.7.3",
"dependencies": {
"async": {
"version": "0.2.10"
},
"colors": {
"version": "0.6.2"
},
"cycle": {
"version": "1.0.3"
},
"eyes": {
"version": "0.1.8"
},
"pkginfo": {
"version": "0.3.0"
},
"request": {
"version": "2.16.6",
"dependencies": {
"form-data": {
"version": "0.0.10",
"dependencies": {
"combined-stream": {
"version": "0.0.7",
"dependencies": {
"delayed-stream": {
"version": "0.0.5"
}
}
}
}
},
"mime": {
"version": "1.2.11"
},
"hawk": {
"version": "0.10.2",
"dependencies": {
"hoek": {
"version": "0.7.6"
},
"boom": {
"version": "0.3.8"
},
"cryptiles": {
"version": "0.1.3"
},
"sntp": {
"version": "0.1.4"
}
}
},
"cookie-jar": {
"version": "0.2.0"
},
"aws-sign": {
"version": "0.2.0"
},
"oauth-sign": {
"version": "0.2.0"
},
"forever-agent": {
"version": "0.2.0"
},
"tunnel-agent": {
"version": "0.2.0"
},
"json-stringify-safe": {
"version": "3.0.0"
},
"qs": {
"version": "0.5.6"
}
}
},
"stack-trace": {
"version": "0.0.9"
}
}
}
}
},
"dgeni-packages": {
"version": "0.10.18",
"dependencies": {
"catharsis": {
"version": "0.8.7",
"dependencies": {
"underscore-contrib": {
"version": "0.3.0",
"dependencies": {
"underscore": {
"version": "1.6.0"
}
}
}
}
},
"change-case": {
"version": "2.3.0",
"dependencies": {
"camel-case": {
"version": "1.1.2"
},
"constant-case": {
"version": "1.1.1"
},
"dot-case": {
"version": "1.1.1"
},
"is-lower-case": {
"version": "1.1.1"
},
"is-upper-case": {
"version": "1.1.1"
},
"lower-case": {
"version": "1.1.2"
},
"lower-case-first": {
"version": "1.0.0"
},
"param-case": {
"version": "1.1.1"
},
"pascal-case": {
"version": "1.1.1"
},
"path-case": {
"version": "1.1.1"
},
"sentence-case": {
"version": "1.1.2"
},
"snake-case": {
"version": "1.1.1"
},
"swap-case": {
"version": "1.1.1"
},
"title-case": {
"version": "1.1.1"
},
"upper-case": {
"version": "1.1.2"
},
"upper-case-first": {
"version": "1.1.1"
}
}
},
"esprima": {
"version": "1.2.5"
},
"estraverse": {
"version": "1.9.3"
},
"glob": {
"version": "3.2.11",
"dependencies": {
"inherits": {
"version": "2.0.1"
}
}
},
"htmlparser2": {
"version": "3.8.3",
"dependencies": {
"domhandler": {
"version": "2.3.0"
},
"domutils": {
"version": "1.5.1",
"dependencies": {
"dom-serializer": {
"version": "0.1.0",
"dependencies": {
"domelementtype": {
"version": "1.1.3"
},
"entities": {
"version": "1.1.1"
}
}
}
}
},
"domelementtype": {
"version": "1.3.0"
},
"readable-stream": {
"version": "1.1.13",
"dependencies": {
"core-util-is": {
"version": "1.0.1"
},
"isarray": {
"version": "0.0.1"
},
"string_decoder": {
"version": "0.10.31"
},
"inherits": {
"version": "2.0.1"
}
}
},
"entities": {
"version": "1.0.0"
}
}
},
"minimatch": {
"version": "0.3.0",
"dependencies": {
"lru-cache": {
"version": "2.6.5"
},
"sigmund": {
"version": "1.0.1"
}
}
},
"nunjucks": {
"version": "1.3.4",
"dependencies": {
"optimist": {
"version": "0.6.1",
"dependencies": {
"wordwrap": {
"version": "0.0.3"
},
"minimist": {
"version": "0.0.10"
}
}
},
"chokidar": {
"version": "0.12.6",
"dependencies": {
"readdirp": {
"version": "1.3.0",
"dependencies": {
"graceful-fs": {
"version": "2.0.3"
},
"minimatch": {
"version": "0.2.14",
"dependencies": {
"lru-cache": {
"version": "2.6.5"
},
"sigmund": {
"version": "1.0.1"
}
}
},
"readable-stream": {
"version": "1.0.33",
"dependencies": {
"core-util-is": {
"version": "1.0.1"
},
"isarray": {
"version": "0.0.1"
},
"string_decoder": {
"version": "0.10.31"
},
"inherits": {
"version": "2.0.1"
}
}
}
}
},
"async-each": {
"version": "0.1.6"
}
}
}
}
},
"q": {
"version": "1.0.1"
},
"q-io": {
"version": "1.10.9",
"dependencies": {
"q": {
"version": "0.9.7"
},
"qs": {
"version": "0.1.0"
},
"url2": {
"version": "0.0.0"
},
"mime": {
"version": "1.2.11"
},
"mimeparse": {
"version": "0.1.4"
},
"collections": {
"version": "0.2.2",
"dependencies": {
"weak-map": {
"version": "1.0.0"
}
}
}
}
},
"stringmap": {
"version": "0.2.2"
},
"winston": {
"version": "0.7.3",
"dependencies": {
"async": {
"version": "0.2.10"
},
"colors": {
"version": "0.6.2"
},
"cycle": {
"version": "1.0.3"
},
"eyes": {
"version": "0.1.8"
},
"pkginfo": {
"version": "0.3.0"
},
"request": {
"version": "2.16.6",
"dependencies": {
"form-data": {
"version": "0.0.10",
"dependencies": {
"combined-stream": {
"version": "0.0.7",
"dependencies": {
"delayed-stream": {
"version": "0.0.5"
}
}
}
}
},
"mime": {
"version": "1.2.11"
},
"hawk": {
"version": "0.10.2",
"dependencies": {
"hoek": {
"version": "0.7.6"
},
"boom": {
"version": "0.3.8"
},
"cryptiles": {
"version": "0.1.3"
},
"sntp": {
"version": "0.1.4"
}
}
},
"cookie-jar": {
"version": "0.2.0"
},
"aws-sign": {
"version": "0.2.0"
},
"oauth-sign": {
"version": "0.2.0"
},
"forever-agent": {
"version": "0.2.0"
},
"tunnel-agent": {
"version": "0.2.0"
},
"json-stringify-safe": {
"version": "3.0.0"
},
"qs": {
"version": "0.5.6"
}
}
},
"stack-trace": {
"version": "0.0.9"
}
}
}
}
},
"es6-shim": { "es6-shim": {
"version": "0.33.3" "version": "0.33.3"
}, },

988
npm-shrinkwrap.json generated

File diff suppressed because it is too large Load Diff

View File

@ -54,8 +54,6 @@
"conventional-changelog": "^0.2.1", "conventional-changelog": "^0.2.1",
"css": "mlaval/css#issue65", "css": "mlaval/css#issue65",
"del": "~1", "del": "~1",
"dgeni": "^0.4.1",
"dgeni-packages": "^0.10.11",
"es6-shim": "^0.33.3", "es6-shim": "^0.33.3",
"event-stream": "^3.1.5", "event-stream": "^3.1.5",
"firefox-profile": "^0.3.4", "firefox-profile": "^0.3.4",