converted tester to promises & lazy iteration

added bluebird & lazy.js dependencies
checking-in used definitions
added tsd.json

parallelized async with bluebird
most iteration uses lazy.js

re-factored test flow to promise structure (instead of chain)
renamed some stuff
linted some quotes

cleaned up output
added some color
This commit is contained in:
Bart van der Schoor 2014-02-28 20:57:07 +01:00
parent c47743cdd5
commit ca2fa0719b
24 changed files with 3054 additions and 766 deletions

11
.gitignore vendored
View File

@ -29,8 +29,9 @@ Properties
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
.idea
*.iml
node_modules
.idea
*.iml
*.js.map
node_modules

View File

@ -1 +1 @@
/// <reference path='../../node/node.d.ts' />
/// <reference path="typings/tsd.d.ts" />

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
/// <reference path="_ref.d.ts" />
/// <reference path="typings/tsd.d.ts" />
/// <reference path="src/host/exec.ts" />
/// <reference path="src/exec.ts" />
/// <reference path="src/file.ts" />
/// <reference path="src/tsc.ts" />
@ -19,24 +19,30 @@
/// <reference path="src/suite/tscParams.ts" />
module DT {
'use-strict';
require('source-map-support').install();
// hacky typing
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var assert = require('assert');
var tsExp = /\.ts$/;
export var DEFAULT_TSC_VERSION = "0.9.1.1";
export var DEFAULT_TSC_VERSION = '0.9.1.1';
/////////////////////////////////
// Single test
/////////////////////////////////
export class Test {
constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) {
}
public run(callback: (result: TestResult) => void) {
Tsc.run(this.tsfile.filePathWithName, this.options, (execResult) => {
public run(): Promise<TestResult> {
return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => {
var testResult = new TestResult();
testResult.hostedBy = this.suite;
testResult.targetFile = this.tsfile;
@ -46,7 +52,7 @@ module DT {
testResult.stderr = execResult.stderr;
testResult.exitCode = execResult.exitCode;
callback(testResult);
return testResult;
});
}
}
@ -76,12 +82,10 @@ module DT {
/////////////////////////////////
// The main class to kick things off
/////////////////////////////////
// TODO move to bluebird (Promises)
// TODO move to lazy.js (functional)
export class TestRunner {
files: File[];
timer: Timer;
suites: ITestSuite[] = [];
private files: File[];
private timer: Timer;
private suites: ITestSuite[] = [];
private index: FileIndex;
private changes: GitChanges;
@ -92,29 +96,13 @@ module DT {
this.index = new FileIndex(this.options);
this.changes = new GitChanges(this.dtPath);
// should be async (way faster)
// only includes .d.ts or -tests.ts or -test.ts or .ts
var filesName = glob.sync('**/*.ts', { cwd: dtPath });
this.files = filesName.filter((fileName) => {
return this.checkAcceptFile(fileName);
}).sort().map((fileName) => {
return new File(dtPath, fileName);
});
this.print = new Print(this.options.tscVersion);
}
public addSuite(suite: ITestSuite): void {
this.suites.push(suite);
}
public run(): void {
this.timer = new Timer();
this.timer.start();
// we need promises
this.doGetChanges();
}
private checkAcceptFile(fileName: string): boolean {
var ok = tsExp.test(fileName);
ok = ok && fileName.indexOf('_infrastructure') < 0;
@ -123,155 +111,179 @@ module DT {
return ok;
}
private doGetChanges(): void {
this.changes.getChanges((err) => {
if (err) {
throw err;
}
console.log('');
console.log('changes:');
console.log('---');
public run(): Promise<boolean> {
this.timer = new Timer();
this.timer.start();
this.changes.paths.forEach((file) => {
console.log(file);
// only includes .d.ts or -tests.ts or -test.ts or .ts
return Promise.promisify(glob).call(glob, '**/*.ts', {
cwd: dtPath
}).then((filesNames: string[]) => {
this.files = Lazy(filesNames).filter((fileName) => {
return this.checkAcceptFile(fileName);
}).map((fileName: string) => {
return new File(dtPath, fileName);
}).toArray();
this.print.printChangeHeader();
return Promise.all([
this.doParseFiles(),
this.doGetChanges()
]);
}).then(() => {
return this.doCollectTargets();
}).then((files) => {
return this.runTests(files);
}).then(() => {
return !this.suites.some((suite) => {
return suite.ngTests.length !== 0
});
console.log('---');
// chain
this.doGetReferences();
});
}
private doGetReferences(): void {
this.index.parseFiles(this.files, () => {
console.log('');
console.log('files:');
console.log('---');
this.files.forEach((file) => {
console.log(file.filePathWithName);
file.references.forEach((file) => {
console.log(' - %s', file.filePathWithName);
});
});
console.log('---');
private doParseFiles(): Promise<void> {
return this.index.parseFiles(this.files).then(() => {
/*
this.print.printSubHeader('Files:');
this.print.printDiv();
this.files.forEach((file) => {
this.print.printLine(file.filePathWithName);
file.references.forEach((file) => {
this.print.printElement(file.filePathWithName);
});
});
this.print.printBreak();*/
// chain
this.doCollectTargets();
});
}).thenReturn();
}
private doCollectTargets(): void {
private doGetChanges(): Promise<void> {
return this.changes.getChanges().then(() => {
this.print.printSubHeader('All changes');
this.print.printDiv();
// TODO clean this up when functional (do we need changeMap?)
Lazy(this.changes.paths).each((file) => {
this.print.printLine(file);
});
}).thenReturn();
}
// bake map for lookup
var changeMap = this.changes.paths.filter((full) => {
return this.checkAcceptFile(full);
}).map((local) => {
return path.resolve(this.dtPath, local);
}).reduce((memo, full) => {
var file = this.index.getFile(full);
if (!file) {
// what does it mean? deleted?
console.log('not in index: ' + full);
return memo;
}
memo[full] = file;
return memo;
}, Object.create(null));
private doCollectTargets(): Promise<File[]> {
return new Promise((resolve) => {
// collect referring files (and also log)
var touched = Object.create(null);
console.log('');
console.log('relevant changes:');
console.log('---');
Object.keys(changeMap).sort().forEach((src) => {
touched[src] = changeMap[src];
console.log(changeMap[src].formatName);
});
console.log('---');
// bake map for lookup
var changeMap = Object.create(null);
// terrible loop (whatever)
// just add stuff until there is nothing new added
// TODO improve it
var added:number;
do {
added = 0;
this.files.forEach((file) => {
// lol getter
if (file.fullPath in touched) {
Lazy(this.changes.paths).filter((full) => {
return this.checkAcceptFile(full);
}).map((local) => {
return path.resolve(this.dtPath, local);
}).each((full) => {
var file = this.index.getFile(full);
if (!file) {
// TODO figure out what to do here
// what does it mean? deleted?
console.log('not in index: ' + full);
return;
}
// check if one of our references is touched
file.references.some((ref) => {
if (ref.fullPath in touched) {
// add us
touched[file.fullPath] = file;
added++;
return true;
}
return false;
});
changeMap[full] = file;
});
}
while(added > 0);
console.log('');
console.log('touched:');
console.log('---');
var files: File[] = Object.keys(touched).sort().map((src) => {
console.log(touched[src].formatName);
return touched[src];
this.print.printDiv();
this.print.printSubHeader('Relevant changes');
this.print.printDiv();
Object.keys(changeMap).sort().forEach((src) => {
this.print.printLine(changeMap[src].formatName);
});
// terrible loop (whatever)
// just add stuff until there is nothing new added
// TODO improve it
var added: number;
var files = this.files.slice(0);
do {
added = 0;
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
if (file.fullPath in changeMap) {
this.files.splice(i, 1);
continue;
}
// check if one of our references is touched
for (var j = 0, jj = file.references.length; j < jj; j++) {
if (file.references[j].fullPath in changeMap) {
// add us
changeMap[file.fullPath] = file;
added++;
break;
}
}
}
}
while (added > 0);
this.print.printDiv();
this.print.printSubHeader('Reference mapped');
this.print.printDiv();
var result: File[] = Object.keys(changeMap).sort().map((src) => {
this.print.printLine(changeMap[src].formatName);
changeMap[src].references.forEach((file: File) => {
this.print.printElement(file.formatName);
});
return changeMap[src];
});
resolve(result);
});
console.log('---');
this.runTests(files);
}
private runTests(files: File[]): void {
private runTests(files: File[]): Promise<boolean> {
return Promise.attempt(() => {
assert(Array.isArray(files), 'files must be array');
var syntaxChecking = new SyntaxChecking(this.options);
var testEval = new TestEval(this.options);
if (!this.options.findNotRequiredTscparams) {
this.addSuite(syntaxChecking);
this.addSuite(testEval);
}
var syntaxChecking = new SyntaxChecking(this.options);
var testEval = new TestEval(this.options);
var typings = syntaxChecking.filterTargetFiles(files).length;
var testFiles = testEval.filterTargetFiles(files).length;
if (!this.options.findNotRequiredTscparams) {
this.addSuite(syntaxChecking);
this.addSuite(testEval);
}
this.print = new Print(this.options.tscVersion, typings, testFiles, files.length);
this.print.printHeader();
return Promise.all([
syntaxChecking.filterTargetFiles(files),
testEval.filterTargetFiles(files)
]);
}).spread((syntaxFiles, testFiles) => {
this.print.init(syntaxFiles.length, testFiles.length, files.length);
this.print.printHeader();
if (this.options.findNotRequiredTscparams) {
this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
}
if (this.options.findNotRequiredTscparams) {
this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
}
var count = 0;
var executor = () => {
var suite = this.suites[count];
if (suite) {
return Promise.reduce(this.suites, (count, suite: ITestSuite) => {
suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print);
this.print.printSuiteHeader(suite.testSuiteName);
var targetFiles = suite.filterTargetFiles(files);
suite.start(targetFiles, (testResult, index) => {
this.testCompleteCallback(testResult, index);
}, (suite) => {
this.suiteCompleteCallback(suite);
count++;
executor();
return suite.filterTargetFiles(files).then((targetFiles) => {
return suite.start(targetFiles, (testResult, index) => {
this.printTestComplete(testResult, index);
});
}).then((suite) => {
this.printSuiteComplete(suite);
return count++;
});
}
else {
this.timer.end();
this.allTestCompleteCallback(files);
}
};
executor();
}, 0);
}).then((count) => {
this.timer.end();
this.finaliseTests(files);
});
}
private testCompleteCallback(testResult: TestResult, index: number) {
private printTestComplete(testResult: TestResult, index: number): void {
var reporter = testResult.hostedBy.testReporter;
if (testResult.success) {
reporter.printPositiveCharacter(index, testResult);
@ -281,7 +293,7 @@ module DT {
}
}
private suiteCompleteCallback(suite: ITestSuite) {
private printSuiteComplete(suite: ITestSuite): void {
this.print.printBreak();
this.print.printDiv();
@ -290,16 +302,19 @@ module DT {
this.print.printFailedCount(suite.ngTests.length, suite.testResults.length);
}
private allTestCompleteCallback(files: File[]) {
var testEval = this.suites.filter(suite => suite instanceof TestEval)[0];
private finaliseTests(files: File[]): void {
var testEval: TestEval = Lazy(this.suites).filter((suite) => {
return suite instanceof TestEval;
}).first();
if (testEval) {
var existsTestTypings: string[] = testEval.testResults.map((testResult) => {
var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => {
return testResult.targetFile.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
var typings: string[] = files.map((file) => {
var typings: string[] = Lazy(files).map((file) => {
return file.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
@ -308,6 +323,7 @@ module DT {
var withoutTestTypings: string[] = typings.filter((typing) => {
return existsTestTypings.indexOf(typing) < 0;
});
this.print.printDiv();
this.print.printTypingsWithoutTest(withoutTestTypings);
}
@ -324,10 +340,11 @@ module DT {
this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length);
});
if (testEval) {
this.print.printSuiteErrorCount("Without tests", withoutTestTypings.length, typings.length, '\33[33m\33[1m');
this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true);
}
this.print.printDiv();
if (this.suites.some((suite) => {
return suite.ngTests.length !== 0
})) {
@ -341,30 +358,29 @@ module DT {
});
this.print.printBoldDiv();
});
process.exit(1);
}
}
}
var dtPath = path.resolve(path.dirname((module).filename), '..', '..');
var findNotRequiredTscparams = process.argv.some(arg => arg == "--try-without-tscparams");
var tscVersionIndex = process.argv.indexOf("--tsc-version");
var findNotRequiredTscparams = process.argv.some(arg => arg == '--try-without-tscparams');
var tscVersionIndex = process.argv.indexOf('--tsc-version');
var tscVersion = DEFAULT_TSC_VERSION;
if (-1 < tscVersionIndex) {
if (tscVersionIndex > -1) {
tscVersion = process.argv[tscVersionIndex + 1];
}
console.log('--');
console.log(' dtPath %s', dtPath);
console.log(' tscVersion %s', tscVersion);
console.log(' findNotRequiredTscparams %s', findNotRequiredTscparams);
console.log('--');
console.log('');
var runner = new TestRunner(dtPath, {
tscVersion: tscVersion,
findNotRequiredTscparams: findNotRequiredTscparams
});
runner.run();
runner.run().then((success) => {
if (!success) {
process.exit(1);
}
}).catch((err) => {
throw err;
process.exit(2);
});
}

View File

@ -1,14 +1,16 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use-strict';
'use strict';
var fs = require('fs');
var path = require('path');
var Git = require('git-wrapper');
var Promise: typeof Promise = require('bluebird');
export class GitChanges {
git;
options = {};
paths: string[] = [];
@ -18,21 +20,16 @@ module DT {
throw new Error('cannot locate git-dir: ' + dir);
}
this.options['git-dir'] = dir;
this.git = new Git(this.options);
this.git.exec = Promise.promisify(this.git.exec);
}
getChanges(callback: (err) => void): void {
//git diff --name-only HEAD~1
var git = new Git(this.options);
getChanges(): Promise<void> {
var opts = {};
var args = ['--name-only HEAD~1'];
git.exec('diff', opts, args, (err, msg: string) => {
if (err) {
callback(err);
return;
}
return this.git.exec('diff', opts, args).then((msg: string) => {
this.paths = msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g);
// console.log(paths);
callback(null);
});
}
}

View File

@ -0,0 +1,30 @@
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var nodeExec = require('child_process').exec;
export class ExecResult {
error;
stdout = '';
stderr = '';
exitCode: number;
}
export function exec(filename: string, cmdLineArgs: string[]): Promise<ExecResult> {
return new Promise((resolve) => {
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => {
result.error = error;
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
resolve(result);
});
});
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use-strict';
'use strict';
var path = require('path');
@ -20,6 +20,7 @@ module DT {
references: File[] = [];
constructor(baseDir: string, filePathWithName: string) {
// why choose?
this.baseDir = baseDir;
this.filePathWithName = filePathWithName;
this.ext = path.extname(this.filePathWithName);
@ -28,7 +29,7 @@ module DT {
this.formatName = path.join(this.dir, this.file + this.ext);
this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext);
// lock it (shallow)
// lock it (shallow) (needs `use strict` in each file to work)
// Object.freeze(this);
}

View File

@ -1,46 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Allows for executing a program with command-line arguments and reading the result
interface IExec {
exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void;
}
class ExecResult {
public stdout = "";
public stderr = "";
public exitCode: number;
}
class NodeExec implements IExec {
public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void): void {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
}
}
var Exec: IExec = function (): IExec {
return new NodeExec();
}();

View File

@ -3,28 +3,25 @@
/// <reference path="util.ts" />
module DT {
'use-strict';
'use strict';
var fs = require('fs');
var path = require('path');
var Lazy = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var readFile = Promise.promisify(fs.readFile);
/////////////////////////////////
// Track all files in the repo: map full path to File objects
/////////////////////////////////
export class FileIndex {
fileMap: {[path:string]:File
};
fileMap: {[fullPath:string]:File};
options: ITestRunnerOptions;
constructor(public options: ITestRunnerOptions) {
}
parseFiles(files: File[], callback: () => void): void {
this.fileMap = Object.create(null);
files.forEach((file) => {
this.fileMap[file.fullPath] = file;
});
this.loadReferences(files, () => {
callback();
});
constructor(options: ITestRunnerOptions) {
this.options = options;
}
hasFile(target: string): boolean {
@ -38,43 +35,53 @@ module DT {
return null;
}
private loadReferences(files: File[], callback: () => void): void {
var queue = files.slice(0);
var active = [];
var max = 50;
var next = () => {
if (queue.length === 0 && active.length === 0) {
callback();
return;
}
// queue paralel
while (queue.length > 0 && active.length < max) {
var file = queue.pop();
active.push(file);
this.parseFile(file, (file) => {
active.splice(active.indexOf(file), 1);
next();
});
}
};
process.nextTick(next);
parseFiles(files: File[]): Promise<void> {
return Promise.attempt(() => {
this.fileMap = Object.create(null);
files.forEach((file) => {
this.fileMap[file.fullPath] = file;
});
return this.loadReferences(files);
});
}
private parseFile(file: File, callback: (file: File) => void): void {
fs.readFile(file.filePathWithName, {
private loadReferences(files: File[]): Promise<void> {
return new Promise((resolve, reject) => {
var queue = files.slice(0);
var active = [];
var max = 50;
var next = () => {
if (queue.length === 0 && active.length === 0) {
resolve();
return;
}
// queue paralel
while (queue.length > 0 && active.length < max) {
var file = queue.pop();
active.push(file);
this.parseFile(file).then((file) => {
active.splice(active.indexOf(file), 1);
next();
}).catch((err) => {
queue = [];
active = [];
reject(err);
});
}
};
next();
});
}
// TODO replace with a stream?
private parseFile(file: File): Promise<File> {
return readFile(file.filePathWithName, {
encoding: 'utf8',
flag: 'r'
}, (err, content) => {
if (err) {
// just blow up?
throw err;
}
// console.log('----');
// console.log(file.filePathWithName);
file.references = extractReferenceTags(content).map((ref: string) => {
}).then((content) => {
file.references = Lazy(extractReferenceTags(content)).map((ref) => {
return path.resolve(path.dirname(file.fullPath), ref);
}).reduce((memo: File[], ref: string) => {
}).reduce((memo: File[], ref) => {
if (ref in this.fileMap) {
memo.push(this.fileMap[ref]);
}
@ -83,10 +90,8 @@ module DT {
}
return memo;
}, []);
// console.log(file.references);
callback(file);
// return the object
return file;
});
}
}

View File

@ -2,16 +2,26 @@
/// <reference path="../runner.ts" />
module DT {
'use-strict';
/////////////////////////////////
// All the common things that we pring are functions of this class
// All the common things that we print are functions of this class
/////////////////////////////////
export class Print {
WIDTH = 77;
constructor(public version: string, public typings: number, public tests: number, public tsFiles: number) {
typings: number;
tests: number;
tsFiles: number
constructor(public version: string){
}
public init(typings: number, tests: number, tsFiles: number) {
this.typings = typings;
this.tests = tests;
this.tsFiles = tsFiles;
}
public out(s: any): Print {
@ -23,9 +33,15 @@ module DT {
return new Array(times + 1).join(s);
}
public printChangeHeader() {
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n');
this.out('=============================================================================\n');
}
public printHeader() {
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped test runner 0.4.0\33[0m\n');
this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n');
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n');
this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n');
@ -36,9 +52,9 @@ module DT {
public printSuiteHeader(title: string) {
var left = Math.floor((this.WIDTH - title.length ) / 2) - 1;
var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1;
this.out(this.repeat("=", left)).out(" \33[34m\33[1m");
this.out(this.repeat('=', left)).out(' \33[34m\33[1m');
this.out(title);
this.out("\33[0m ").out(this.repeat("=", right)).printBreak();
this.out('\33[0m ').out(this.repeat('=', right)).printBreak();
}
public printDiv() {
@ -66,16 +82,18 @@ module DT {
}
public clearCurrentLine(): Print {
this.out("\r\33[K");
this.out('\r\33[K');
return this;
}
public printSuccessCount(current: number, total: number) {
this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printFailedCount(current: number, total: number) {
this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printTypingsWithoutTestsMessage() {
@ -90,9 +108,31 @@ module DT {
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
}
public printSuiteErrorCount(errorHeadline: string, current: number, total: number, valuesColor = '\33[31m\33[1m') {
public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length));
this.out(':\33[0m ' + valuesColor + ((current / total) * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
if (warn) {
this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
else {
this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
}
public printSubHeader(file: string) {
this.out(' \33[36m\33[1m' + file + '\33[0m\n');
}
public printLine(file: string) {
this.out(file + '\n');
}
public printElement(file: string) {
this.out(' - ' + file + '\n');
}
public printElement2(file: string) {
this.out(' - ' + file + '\n');
}
public printTypingsWithoutTestName(file: string) {

View File

@ -2,8 +2,6 @@
/// <reference path="../printer.ts" />
module DT {
'use-strict';
/////////////////////////////////
// Test reporter interface
// for example, . and x
@ -27,7 +25,7 @@ module DT {
}
public printNegativeCharacter(index: number, testResult: TestResult) {
this.print.out("x");
this.print.out('x');
this.printBreakIfNeeded(index);
}

View File

@ -1,7 +1,9 @@
/// <reference path="../../runner.ts" />
module DT {
'use-strict';
'use strict';
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// The interface for test suite
@ -9,9 +11,9 @@ module DT {
export interface ITestSuite {
testSuiteName:string;
errorHeadline:string;
filterTargetFiles(files: File[]):File[];
filterTargetFiles(files: File[]): Promise<File[]>;
start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void, suiteCallback: (suite: ITestSuite) => void):void;
start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise<ITestSuite>;
testResults:TestResult[];
okTests:TestResult[];
@ -34,41 +36,30 @@ module DT {
constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) {
}
public filterTargetFiles(files: File[]): File[] {
throw new Error("please implement this method");
public filterTargetFiles(files: File[]): Promise<File[]> {
throw new Error('please implement this method');
}
public start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void, suiteCallback: (suite: ITestSuite) => void): void {
targetFiles = this.filterTargetFiles(targetFiles);
public start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise<ITestSuite> {
this.timer.start();
var count = 0;
// exec test is async process. serialize.
var executor = () => {
var targetFile = targetFiles[count];
if (targetFile) {
this.runTest(targetFile, (result) => {
return this.filterTargetFiles(targetFiles).then((targetFiles) => {
return Promise.reduce(targetFiles, (count, targetFile) => {
return this.runTest(targetFile).then((result) => {
testCallback(result, count + 1);
count++;
executor();
return count++;
});
}
else {
this.timer.end();
this.finish(suiteCallback);
}
};
executor();
}
public runTest(targetFile: File, callback: (result: TestResult) => void): void {
new Test(this, targetFile, {tscVersion: this.options.tscVersion}).run((result) => {
this.testResults.push(result);
callback(result);
}, 0);
}).then((count: number) => {
this.timer.end();
return this;
});
}
public finish(suiteCallback: (suite: ITestSuite) => void) {
suiteCallback(this);
public runTest(targetFile: File): Promise<TestResult> {
return new Test(this, targetFile, {tscVersion: this.options.tscVersion}).run().then((result) => {
this.testResults.push(result);
return result;
});
}
public get okTests(): TestResult[] {

View File

@ -2,7 +2,11 @@
/// <reference path="../util.ts" />
module DT {
'use-strict';
'use strict';
var Promise: typeof Promise = require('bluebird');
var endDts = /.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
@ -10,13 +14,13 @@ module DT {
export class SyntaxChecking extends TestSuiteBase {
constructor(options: ITestRunnerOptions) {
super(options, "Syntax checking", "Syntax error");
super(options, 'Syntax checking', 'Syntax error');
}
public filterTargetFiles(files: File[]): File[] {
return files.filter((file) => {
return DT.endsWith(file.formatName.toUpperCase(), '.D.TS');
});
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endDts.test(file.formatName);
}));
}
}
}

View File

@ -2,20 +2,25 @@
/// <reference path="../util.ts" />
module DT {
'use-strict';
'use strict';
var Promise: typeof Promise = require('bluebird');
var endTestDts = /-test.ts$/i;
/////////////////////////////////
// Compile with *-tests.ts
/////////////////////////////////
export class TestEval extends TestSuiteBase {
constructor(options) {
super(options, "Typing tests", "Failed tests");
super(options, 'Typing tests', 'Failed tests');
}
public filterTargetFiles(files: File[]): File[] {
return files.filter((file) => {
return DT.endsWith(file.formatName.toUpperCase(), '-TESTS.TS')
});
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endTestDts.test(file.formatName);
}));
}
}

View File

@ -1,10 +1,11 @@
/// <reference path="../../runner.ts" />
/// <reference path="../file.ts" />
/// <reference path='../../runner.ts' />
/// <reference path='../file.ts' />
module DT {
'use-strict';
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// Try compile without .tscparams
@ -15,7 +16,7 @@ module DT {
printErrorCount = false;
constructor(options: ITestRunnerOptions, private print: Print) {
super(options, "Find not required .tscparams files", "New arrival!");
super(options, 'Find not required .tscparams files', 'New arrival!');
this.testReporter = {
printPositiveCharacter: (index: number, testResult: TestResult) => {
@ -28,29 +29,28 @@ module DT {
}
}
public filterTargetFiles(files: File[]): File[] {
return files.filter((file) => {
return fs.existsSync(file.filePathWithName + '.tscparams');
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.filter(files, (file) => {
return new Promise((resolve) => {
fs.exists(file.filePathWithName + '.tscparams', resolve);
});
});
}
public runTest(targetFile: File, callback: (result: TestResult) => void): void {
public runTest(targetFile: File): Promise<TestResult> {
this.print.clearCurrentLine().out(targetFile.formatName);
new Test(this, targetFile, {
return new Test(this, targetFile, {
tscVersion: this.options.tscVersion,
useTscParams: false,
checkNoImplicitAny: true
}).run(result=> {
}).run().then((result: TestResult) => {
this.testResults.push(result);
callback(result);
this.print.clearCurrentLine();
return result
});
}
public finish(suiteCallback: (suite: ITestSuite)=>void) {
this.print.clearCurrentLine();
suiteCallback(this);
}
public get ngTests(): TestResult[] {
// Do not show ng test results
return [];

View File

@ -2,7 +2,7 @@
/// <reference path="../runner.ts" />
module DT {
'use-strict';
'use strict';
/////////////////////////////////
// Timer.start starts a timer
@ -36,14 +36,14 @@ module DT {
}
return (<string><any> (day_diff == 0 && (
diff < 60 && (diff + " seconds") ||
diff < 120 && "1 minute" ||
diff < 3600 && Math.floor(diff / 60) + " minutes" ||
diff < 7200 && "1 hour" ||
diff < 86400 && Math.floor(diff / 3600) + " hours") ||
day_diff == 1 && "Yesterday" ||
day_diff < 7 && day_diff + " days" ||
day_diff < 31 && Math.ceil(day_diff / 7) + " weeks"));
diff < 60 && (diff + ' seconds') ||
diff < 120 && '1 minute' ||
diff < 3600 && Math.floor(diff / 60) + ' minutes' ||
diff < 7200 && '1 hour' ||
diff < 86400 && Math.floor(diff / 3600) + ' hours') ||
day_diff == 1 && 'Yesterday' ||
day_diff < 7 && day_diff + ' days' ||
day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'));
}
}
}

View File

@ -1,11 +1,14 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
/// <reference path="host/exec.ts" />
/// <reference path='../_ref.d.ts' />
/// <reference path='../runner.ts' />
/// <reference path='exec.ts' />
module DT {
'use-strict';
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
export interface TscExecOptions {
tscVersion?:string;
useTscParams?:boolean;
@ -13,33 +16,31 @@ module DT {
}
export class Tsc {
public static run(tsfile: string, options: TscExecOptions, callback: (result: ExecResult) => void) {
options = options || {};
options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
if (typeof options.checkNoImplicitAny === "undefined") {
options.checkNoImplicitAny = true;
}
if (typeof options.useTscParams === "undefined") {
options.useTscParams = true;
}
if (!fs.existsSync(tsfile)) {
throw new Error(tsfile + " not exists");
}
var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
if (!fs.existsSync(tscPath)) {
throw new Error(tscPath + ' is not exists');
}
var command = 'node ' + tscPath + ' --module commonjs ';
if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
command += '@' + tsfile + '.tscparams';
}
else if (options.checkNoImplicitAny) {
command += '--noImplicitAny';
}
Exec.exec(command, [tsfile], (execResult) => {
callback(execResult);
public static run(tsfile: string, options: TscExecOptions): Promise<ExecResult> {
return Promise.attempt(() => {
options = options || {};
options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
if (typeof options.checkNoImplicitAny === 'undefined') {
options.checkNoImplicitAny = true;
}
if (typeof options.useTscParams === 'undefined') {
options.useTscParams = true;
}
if (!fs.existsSync(tsfile)) {
throw new Error(tsfile + ' not exists');
}
var tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
if (!fs.existsSync(tscPath)) {
throw new Error(tscPath + ' is not exists');
}
var command = 'node ' + tscPath + ' --module commonjs ';
if (options.useTscParams && fs.existsSync(tsfile + '.tscparams')) {
command += '@' + tsfile + '.tscparams';
}
else if (options.checkNoImplicitAny) {
command += '--noImplicitAny';
}
return exec(command, [tsfile]);
});
}
}

View File

@ -1,7 +1,11 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use-strict';
'use strict';
var fs = require('fs');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var referenceTagExp = /<reference[ \t]*path=["']?([\w\.\/_-]*)["']?[ \t]*\/>/g;
@ -25,4 +29,12 @@ module DT {
}
return ret;
}
export function fileExists(target: string): Promise<boolean> {
return new Promise((resolve, reject) => {
fs.exists(target, (bool: boolean) => {
resolve(bool);
});
});
}
}

View File

@ -0,0 +1,655 @@
// Type definitions for bluebird 1.0.0
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
// By: Campredon <https://github.com/fdecampredon/>
// Warning: recommended to use `tsc > v1.0.0` (critical bugs in generic code:
// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// TODO fix remaining TODO annotations in both definition and test
// TODO verify support to have no return statement in handlers to get a Promise<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
constructor(callback: (resolve: (thenable: Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void);
/**
* Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(onReject?: (error: any) => U): Promise<U>;
caught<U>(onReject?: (error: any) => U): Promise<U>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called.
*
* This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
/**
* Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error<U>(onReject: (reason: any) => Promise.Thenable<U>): Promise<U>;
error<U>(onReject: (reason: any) => U): Promise<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
finally(handler: (value: R) => R): Promise<R>;
lastly(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
lastly(handler: (value: R) => R): Promise<R>;
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Promise<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
*/
progressed(handler: (note: any) => any): Promise<R>;
/**
* Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
delay(ms: number): Promise<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string): Promise<R>;
/**
* Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success.
* Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void): Promise<R>;
nodeify(...sink: any[]): void;
/**
* Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
*/
cancellable(): Promise<R>;
/**
* Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending.
*
* That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason.
*
* In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`.
*
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
// TODO what to do with this?
cancel<U>(): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
*/
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Create an uncancellable promise based on this promise.
*/
uncancellable(): Promise<R>;
/**
* See if this promise can be cancelled.
*/
isCancellable(): boolean;
/**
* See if this `promise` has been fulfilled.
*/
isFulfilled(): boolean;
/**
* See if this `promise` has been rejected.
*/
isRejected(): boolean;
/**
* See if this `promise` is still defer.
*/
isPending(): boolean;
/**
* See if this `promise` is resolved -> either fulfilled or rejected.
*/
isResolved(): boolean;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
*/
inspect(): Promise.Inspection<R>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise<any>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
// TODO find way to fix get()
// get<U>(propertyName: string): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return<U>(value: U): Promise<U>;
thenReturn<U>(value: U): Promise<U>;
return(): Promise<void>;
thenReturn(): Promise<void>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Promise<R>;
thenThrow(reason: Error): Promise<R>;
/**
* Convert to String.
*/
toString(): string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON(): Object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
// TODO how to model instance.spread()? like Q?
spread<U>(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U>(onFulfill: Function, onReject?: (reason: any) => U): Promise<U>;
/*
// TODO or something like this?
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => U): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise<U>;
*/
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
all<U>(): Promise<U[]>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO how to model instance.props()?
props(): Promise<Object>;
/**
* Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
settle<U>(): Promise<Promise.Inspection<U>[]>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
any<U>(): Promise<U>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
some<U>(count: number): Promise<U[]>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
race<U>(): Promise<U>;
/**
* Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U>;
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => U): Promise<U>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
// TODO type inference from array-resolving promise?
filter<U>(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<U>;
filter<U>(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise<U>;
}
declare module Promise {
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable<U>;
}
export interface Resolver<R> {
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: R): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason: any): void;
/**
* Progress the underlying promise with `value` as the progression value.
*/
progress(value: any): void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback: Function;
}
export interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled(): boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected(): boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
error(): any;
}
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
// TODO find way to enable try() without tsc borking
// see also: https://typescript.codeplex.com/workitem/2194
/*
export function try<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
export function try<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
*/
export function attempt<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
export function attempt<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
/**
* Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
export function method(fn: Function): Function;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
export function resolve<R>(value: Promise.Thenable<R>): Promise<R>;
export function resolve<R>(value: R): Promise<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
export function reject(reason: any): Promise<void>;
/**
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
*/
export function defer<R>(): Promise.Resolver<R>;
/**
* Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
export function cast<R>(value: Promise.Thenable<R>): Promise<R>;
export function cast<R>(value: R): Promise<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
export function bind(thisArg: any): Promise<void>;
/**
* See if `value` is a trusted Promise.
*/
export function is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
export function longStackTraces(): void;
/**
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
// TODO enable more overloads
export function delay<R>(value: Promise.Thenable<R>, ms: number): Promise<R>;
export function delay<R>(value: R, ms: number): Promise<R>;
export function delay(ms: number): Promise<void>;
/**
* Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
// TODO how to model promisify?
export function promisify(nodeFunction: Function, receiver?: any): Function;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
export function promisifyAll(target: Object): Object;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix coroutine GeneratorFunction
export function coroutine<R>(generatorFunction: Function): Function;
/**
* Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix spawn GeneratorFunction
export function spawn<R>(generatorFunction: Function): Promise<R>;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else.
*/
export function noConflict(): typeof Promise;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
export function onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// promise of array with promises of value
export function all<R>(values: Thenable<Thenable<R>[]>): Promise<R[]>;
// promise of array with values
export function all<R>(values: Thenable<R[]>): Promise<R[]>;
// array with promises of value
export function all<R>(values: Thenable<R>[]): Promise<R[]>;
// array with values
export function all<R>(values: R[]): Promise<R[]>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// TODO verify this is correct
// trusted promise for object
export function props(object: Promise<Object>): Promise<Object>;
// object
export function props(object: Object): Promise<Object>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array.
*
* *original: The array is not modified. The input array sparsity is retained in the resulting array.*
*/
// promise of array with promises of value
export function settle<R>(values: Thenable<Thenable<R>[]>): Promise<Promise.Inspection<R>[]>;
// promise of array with values
export function settle<R>(values: Thenable<R[]>): Promise<Promise.Inspection<R>[]>;
// array with promises of value
export function settle<R>(values: Thenable<R>[]): Promise<Promise.Inspection<R>[]>;
// array with values
export function settle<R>(values: R[]): Promise<Promise.Inspection<R>[]>;
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
// promise of array with promises of value
export function any<R>(values: Thenable<Thenable<R>[]>): Promise<R>;
// promise of array with values
export function any<R>(values: Thenable<R[]>): Promise<R>;
// array with promises of value
export function any<R>(values: Thenable<R>[]): Promise<R>;
// array with values
export function any<R>(values: R[]): Promise<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
// promise of array with promises of value
export function race<R>(values: Thenable<Thenable<R>[]>): Promise<R>;
// promise of array with values
export function race<R>(values: Thenable<R[]>): Promise<R>;
// array with promises of value
export function race<R>(values: Thenable<R>[]): Promise<R>;
// array with values
export function race<R>(values: R[]): Promise<R>;
/**
* Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
export function some<R>(values: Thenable<Thenable<R>[]>, count: number): Promise<R[]>;
// promise of array with values
export function some<R>(values: Thenable<R[]>, count: number): Promise<R[]>;
// array with promises of value
export function some<R>(values: Thenable<R>[], count: number): Promise<R[]>;
// array with values
export function some<R>(values: R[], count: number): Promise<R[]>;
/**
* Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments.
*/
// variadic array with promises of value
export function join<R>(...values: Thenable<R>[]): Promise<R[]>;
// variadic array with values
export function join<R>(...values: R[]): Promise<R[]>;
/**
* Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
export function map<R, U>(values: Thenable<Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// promise of array with values
export function map<R, U>(values: Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with promises of value
export function map<R, U>(values: Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with values
export function map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => Thenable<U>): Promise<U[]>;
export function map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
/**
* Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
// promise of array with promises of value
export function reduce<R, U>(values: Thenable<Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// promise of array with values
export function reduce<R, U>(values: Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with promises of value
export function reduce<R, U>(values: Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with values
export function reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Thenable<U>, initialValue?: U): Promise<U>;
export function reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
// promise of array with promises of value
export function filter<R>(values: Thenable<Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// promise of array with values
export function filter<R>(values: Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with promises of value
export function filter<R>(values: Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with values
export function filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => Thenable<boolean>): Promise<R[]>;
export function filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
}
declare module 'bluebird' {
export = Promise;
}

View File

@ -0,0 +1,252 @@
// Type definitions for Lazy.js 0.3.2
// Project: https://github.com/dtao/lazy.js/
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module LazyJS {
interface LazyStatic {
(value: string):StringLikeSequence;
<T>(value: T[]):ArrayLikeSequence<T>;
(value: any[]):ArrayLikeSequence<any>;
<T>(value: Object):ObjectLikeSequence<T>;
(value: Object):ObjectLikeSequence<any>;
strict():LazyStatic;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number):GeneratedSequence<T>;
range(to: number):GeneratedSequence<number>;
range(from: number, to: number, step?: number):GeneratedSequence<number>;
repeat<T>(value: T, count?: number):GeneratedSequence<T>;
on<T>(eventType: string):Sequence<T>;
readFile(path: string):StringLikeSequence;
makeHttpRequest(path: string):StringLikeSequence;
}
interface ArrayLike<T> {
length:number;
[index:number]:T;
}
interface Callback {
():void;
}
interface ErrorCallback {
(error: any):void;
}
interface ValueCallback<T> {
(value: T):void;
}
interface GetKeyCallback<T> {
(value: T):string;
}
interface TestCallback<T> {
(value: T):boolean;
}
interface MapCallback<T, U> {
(value: T):U;
}
interface MapStringCallback {
(value: string):string;
}
interface NumberCallback<T> {
(value: T):number;
}
interface MemoCallback<T, U> {
(memo: U, value: T):U;
}
interface GeneratorCallback<T> {
(index: number):T;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator<T> {
new (sequence: Sequence<T>):Iterator<T>;
current():T;
moveNext():boolean;
}
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number):GeneratedSequence<T>;
length():number;
}
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>):AsyncHandle<T>;
}
interface AsyncHandle<T> {
cancel():void;
onComplete(callback: Callback):void;
onError(callback: ErrorCallback):void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>):Sequence<T>;
}
interface SequenceBase<T> extends SequenceBaser<T> {
first():any;
first(count: number):Sequence<T>;
indexOf(value: any, startIndex?: number):Sequence<T>;
last():any;
last(count: number):Sequence<T>;
lastIndexOf(value: any):Sequence<T>;
reverse():Sequence<T>;
}
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval: number):AsyncSequence<T>;
chunk(size: number):Sequence<T>;
compact():Sequence<T>;
concat(var_args: T[]):Sequence<T>;
consecutive(length: number):Sequence<T>;
contains(value: T):boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
flatten(): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sortBy(sortFn: NumberCallback<T>): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): Sequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): StringLikeSequence;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser<string> {
charAt(index: number): string;
charCodeAt(index: number): number;
contains(value: string): boolean;
endsWith(suffix: string): boolean;
first(): string;
first(count: number): StringLikeSequence;
indexOf(substring: string, startIndex?: number): number;
last(): string;
last(count: number): StringLikeSequence;
lastIndexOf(substring: string, startIndex?: number): number;
mapString(mapFn: MapStringCallback): StringLikeSequence;
match(pattern: RegExp): StringLikeSequence;
reverse(): StringLikeSequence;
split(delimiter: string): StringLikeSequence;
split(delimiter: RegExp): StringLikeSequence;
startsWith(prefix: string): boolean;
substring(start: number, stop?: number): StringLikeSequence;
toLowerCase(): StringLikeSequence;
toUpperCase(): StringLikeSequence;
}
}
declare var Lazy: LazyJS.LazyStatic;
declare module 'lazy.js' {
export = Lazy;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
/// <reference path="node/node.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="lazy.js/lazy.js.d.ts" />

View File

@ -8,6 +8,8 @@
"dependencies": {
"git-wrapper": "~0.1.1",
"glob": "~3.2.9",
"source-map-support": "~0.2.5"
"source-map-support": "~0.2.5",
"bluebird": "~1.0.7",
"lazy.js": "~0.3.2"
}
}

15
tsd.json Normal file
View File

@ -0,0 +1,15 @@
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "_infrastructure/tests/typings",
"bundle": "_infrastructure/tests/typings/tsd.d.ts",
"installed": {
"bluebird/bluebird.d.ts": {
"commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6"
},
"node/node.d.ts": {
"commit": "bac5b4311465c7052467ec315d0cbb1c640a69d6"
}
}
}