diff --git a/.gitignore b/.gitignore index 068fb517..11b75003 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,5 @@ node_modules coverage/**/* xunit.xml test-reports.xml +!test-scripts/** +!scripts/** diff --git a/.npmignore b/.npmignore index e6f3731f..b6ac18e1 100644 --- a/.npmignore +++ b/.npmignore @@ -6,4 +6,7 @@ test-reports.xml *.tgz .vscode .npmignore - +test/**/* +test-scripts/**/* +lib/common/test/**/* +lib/common/test-scripts/**/* diff --git a/Gruntfile.js b/Gruntfile.js index 351f4207..5e6a00b7 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -36,16 +36,7 @@ module.exports = function(grunt) { pkg: grunt.file.readJSON("package.json"), ts: { - options: { - target: 'es5', - module: 'commonjs', - sourceMap: true, - declaration: false, - removeComments: false, - noImplicitAny: true, - experimentalDecorators: true, - emitDecoratorMetadata: true - }, + options: grunt.file.readJSON("tsconfig.json").compilerOptions, devlib: { src: ["**/*.ts", "!node_modules/**/*.ts"], @@ -124,7 +115,16 @@ module.exports = function(grunt) { }, clean: { - src: ["test/**/*.js*", "**/*.js*", "!**/*.json", "!Gruntfile.js", "!node_modules/**/*", "!bin/common-lib.js", "!vendor/*.js", "*.tgz"] + src: ["test/**/*.js*", + "**/*.js*", + "!**/*.json", + "!Gruntfile.js", + "!node_modules/**/*", + "!bin/common-lib.js", + "!vendor/*.js", + "*.tgz", + "!test-scripts/**/*", + "!scripts/**/*"] } }); diff --git a/appbuilder/services/npm-service.ts b/appbuilder/services/npm-service.ts index 6b78a779..87569685 100644 --- a/appbuilder/services/npm-service.ts +++ b/appbuilder/services/npm-service.ts @@ -118,8 +118,9 @@ export class NpmService implements INpmService { }).future()(); } - public search(projectDir: string, keywords: string[], args: string[] = []): IFuture { + public search(projectDir: string, keywords: string[], args?: string[]): IFuture { return ((): IBasicPluginInformation[] => { + args = args === undefined ? [] : args; let result: IBasicPluginInformation[] = []; let commandArguments = _.concat(["search"], args, keywords); let spawnResult = this.executeNpmCommandCore(projectDir, commandArguments).wait(); @@ -296,7 +297,7 @@ export class NpmService implements INpmService { let defs = _.map(definitionFiles, def => this.getReferenceLine(fromWindowsRelativePathToUnix(path.relative(projectDir, def)))); this.$logger.trace(`Adding lines for definition files: ${definitionFiles.join(", ")}`); - lines.push(...defs); + lines = lines.concat(defs); } }); @@ -333,7 +334,8 @@ export class NpmService implements INpmService { return `/// `; } - private getNpmArguments(command: string, npmArguments: string[] = []): string[] { + private getNpmArguments(command: string, npmArguments?: string[]): string[] { + npmArguments = npmArguments === undefined ? [] : npmArguments; return npmArguments.concat([command]); } diff --git a/codeGeneration/code-printer.ts b/codeGeneration/code-printer.ts index 738351f3..0e0f597e 100644 --- a/codeGeneration/code-printer.ts +++ b/codeGeneration/code-printer.ts @@ -7,7 +7,8 @@ export class CodePrinter { private static START_BLOCK_CHAR = "{"; private static END_BLOCK_CHAR = "}"; - public composeBlock(block: CodeGeneration.IBlock, indentSize: number = 0): string { + public composeBlock(block: CodeGeneration.IBlock, indentSize?: number): string { + indentSize = indentSize === undefined ? 0 : indentSize; let content = this.getIndentation(indentSize); if(block.opener) { diff --git a/decorators.ts b/decorators.ts index 3730526f..13d569f9 100644 --- a/decorators.ts +++ b/decorators.ts @@ -1,4 +1,3 @@ -import * as Promise from "bluebird"; import * as fiberBootstrap from "./fiber-bootstrap"; import * as assert from "assert"; import {isFuture} from "./helpers"; @@ -47,6 +46,18 @@ export function exportedPromise(moduleName: string, postAction?: () => void): an } function getPromise(originalValue: any, config?: { postActionMethod: () => void, shouldExecutePostAction?: boolean }): Promise { + let postAction = (data: any) => { + if (config && config.postActionMethod && config.shouldExecutePostAction) { + config.postActionMethod(); + } + + if (data instanceof Error) { + throw data; + } + + return data; + }; + return new Promise((onFulfilled: Function, onRejected: Function) => { if (isFuture(originalValue)) { fiberBootstrap.run(function () { @@ -60,11 +71,7 @@ function getPromise(originalValue: any, config?: { postActionMethod: () => void, } else { onFulfilled(originalValue); } - }).lastly(() => { - if (config && config.postActionMethod && config.shouldExecutePostAction) { - config.postActionMethod(); - } - }); + }).then(postAction, postAction); } export function exported(moduleName: string): any { diff --git a/definitions/bluebird.d.ts b/definitions/bluebird.d.ts deleted file mode 100644 index 7401a50b..00000000 --- a/definitions/bluebird.d.ts +++ /dev/null @@ -1,711 +0,0 @@ -// Type definitions for bluebird 2.0.0 -// Project: https://github.com/petkaantonov/bluebird -// Definitions by: Bart van der Schoor -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts -// By: Campredon - -// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code): -// - https://github.com/borisyankov/DefinitelyTyped/issues/1563 - -// 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 (more overloads?) - -declare class Promise implements Promise.Thenable, Promise.Inspection { - /** - * 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) => 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(onFulfill: (value: R) => U|Promise.Thenable, onReject: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: R) => U|Promise.Thenable, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * 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(onReject?: (error: any) => Promise.Thenable): Promise; - caught(onReject?: (error: any) => Promise.Thenable): Promise; - - catch(onReject?: (error: any) => U): Promise; - caught(onReject?: (error: any) => U): Promise; - - /** - * 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(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable): Promise; - - catch(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; - caught(ErrorClass: Function, onReject: (error: any) => Promise.Thenable): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => U): Promise; - caught(ErrorClass: Function, onReject: (error: any) => U): Promise; - - /** - * 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(onReject: (reason: any) => Promise.Thenable): Promise; - error(onReject: (reason: any) => U): Promise; - - /** - * 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: () => Promise.Thenable): Promise; - finally(handler: () => U): Promise; - - lastly(handler: () => Promise.Thenable): Promise; - lastly(handler: () => U): Promise; - - /** - * 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; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; - done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; - done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; - done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; - - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: R) => Promise.Thenable): Promise; - tap(onFulfill: (value: R) => U): Promise; - - /** - * 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; - - /** - * 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; - - /** - * 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; - - /** - * 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; - 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; - - /** - * 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(): Promise; - - /** - * 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(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable(): Promise; - - /** - * 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; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. - * - * throws `TypeError` - */ - value(): R; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. - * - * throws `TypeError` - */ - reason(): any; - - /** - * 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; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Promise; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO find way to fix get() - // get(propertyName: string): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * 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(): Promise; - thenReturn(): Promise; - return(value: U): Promise; - thenReturn(value: U): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Promise; - thenThrow(reason: Error): Promise; - - /** - * 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(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; - /* - // TODO or something like this? - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; - */ - /** - * 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(): Promise; - - /** - * 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; - - /** - * 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(): Promise[]>; - - /** - * 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(): Promise; - - /** - * 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(count: number): Promise; - - /** - * 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(): Promise; - - /** - * 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(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; - map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; - - /** - * 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(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - /** - * 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(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; - filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; - - /** - * 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. - */ - static try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - static try(fn: () => R, args?: any[], ctx?: any): Promise; - - static attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - static attempt(fn: () => R, args?: any[], ctx?: any): Promise; - - /** - * 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. - */ - static 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. - */ - static resolve(): Promise; - static resolve(value: Promise.Thenable): Promise; - static resolve(value: R): Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - static reject(reason: any): Promise; - static reject(reason: any): Promise; - - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - static defer(): Promise.Resolver; - - /** - * 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. - */ - static cast(value: Promise.Thenable): Promise; - static cast(value: R): Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - static bind(thisArg: any): Promise; - - /** - * See if `value` is a trusted Promise. - */ - static 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. - */ - static 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 - static delay(value: Promise.Thenable, ms: number): Promise; - static delay(value: R, ms: number): Promise; - static delay(ms: number): Promise; - - /** - * 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`. - */ - static promisify(func: (callback: (err:any, result: T) => void) => void, receiver?: any): () => Promise; - static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; - static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; - static 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? - static 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 - static coroutine(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 - static spawn(generatorFunction: Function): Promise; - - /** - * 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. - */ - static 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. - */ - static 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 - static all(values: Promise.Thenable[]>): Promise; - // promise of array with values - static all(values: Promise.Thenable): Promise; - // array with promises of value - static all(values: Promise.Thenable[]): Promise; - // array with values - static all(values: R[]): Promise; - - /** - * 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 - static props(object: Promise): Promise; - // object - static props(object: Object): Promise; - - /** - * 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 - static settle(values: Promise.Thenable[]>): Promise[]>; - // promise of array with values - static settle(values: Promise.Thenable): Promise[]>; - // array with promises of value - static settle(values: Promise.Thenable[]): Promise[]>; - // array with values - static settle(values: R[]): Promise[]>; - - /** - * 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 - static any(values: Promise.Thenable[]>): Promise; - // promise of array with values - static any(values: Promise.Thenable): Promise; - // array with promises of value - static any(values: Promise.Thenable[]): Promise; - // array with values - static any(values: R[]): Promise; - - /** - * 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 - static race(values: Promise.Thenable[]>): Promise; - // promise of array with values - static race(values: Promise.Thenable): Promise; - // array with promises of value - static race(values: Promise.Thenable[]): Promise; - // array with values - static race(values: R[]): Promise; - - /** - * 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 - static some(values: Promise.Thenable[]>, count: number): Promise; - // promise of array with values - static some(values: Promise.Thenable, count: number): Promise; - // array with promises of value - static some(values: Promise.Thenable[], count: number): Promise; - // array with values - static some(values: R[], count: number): Promise; - - /** - * 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 - static join(...values: Promise.Thenable[]): Promise; - // variadic array with values - static join(...values: R[]): Promise; - - /** - * 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 - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // promise of array with values - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // array with promises of value - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - - /** - * 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 - static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // promise of array with values - static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // array with promises of value - static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - // array with values - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - /** - * 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 - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // promise of array with values - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // array with promises of value - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - - // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; -} - -declare module Promise { - export interface RangeError extends Error { - } - export interface CancellationError extends Error { - } - export interface TimeoutError extends Error { - } - export interface TypeError extends Error { - } - export interface RejectionError extends Error { - } - export interface OperationalError extends Error { - } - - // Ideally, we'd define e.g. "export class RangeError extends Error {}", - // but as Error is defined as an interface (not a class), TypeScript doesn't - // allow extending Error, only implementing it. - // However, if we want to catch() only a specific error type, we need to pass - // a constructor function to it. So, as a workaround, we define them here as such. - export function RangeError(): RangeError; - export function CancellationError(): CancellationError; - export function TimeoutError(): TimeoutError; - export function TypeError(): TypeError; - export function RejectionError(): RejectionError; - export function OperationalError(): OperationalError; - - export interface Thenable { - then(onFulfilled: (value: R) => U|Thenable, onRejected: (error: any) => Thenable): Thenable; - then(onFulfilled: (value: R) => U|Thenable, onRejected?: (error: any) => U): Thenable; - } - - export interface Resolver { - /** - * Returns a reference to the controlled promise that can be passed to clients. - */ - promise: Promise; - - /** - * 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; - resolve(): 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: (err: any, value: R, ...values: R[]) => void; - } - - export interface Inspection { - /** - * 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` - */ - reason(): any; - } - - /** - * Changes how bluebird schedules calls a-synchronously. - * - * @param scheduler Should be a function that asynchronously schedules - * the calling of the passed in function - */ - export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; -} - -declare module 'bluebird' { - export = Promise; -} \ No newline at end of file diff --git a/definitions/colors.d.ts b/definitions/colors.d.ts index d915734f..5c9b8009 100644 --- a/definitions/colors.d.ts +++ b/definitions/colors.d.ts @@ -7,7 +7,8 @@ declare module "colors" { } interface String { - bold: String; + // In ES6 there's a method called `bold` in String interface. + // bold: String; italic: String; underline: String; inverse: String; @@ -20,4 +21,4 @@ interface String { magenta: String; red: String; yellow: String; -} \ No newline at end of file +} diff --git a/errors.ts b/errors.ts index 23ba6d01..0c100ac0 100644 --- a/errors.ts +++ b/errors.ts @@ -110,6 +110,8 @@ export class Errors implements IErrors { public printCallStack: boolean = false; fail(optsOrFormatStr: any, ...args: any[]): void { + const argsArray = args || []; + let opts = optsOrFormatStr; if (_.isString(opts)) { opts = { formatStr: opts }; @@ -117,9 +119,10 @@ export class Errors implements IErrors { let exception: any = new (Exception)(); exception.name = opts.name || "Exception"; - exception.message = util.format(opts.formatStr, ...args); + exception.message = util.format.apply(null, [opts.formatStr].concat(argsArray)); try { - exception.message = this.$injector.resolve("messagesService").getMessage(opts.formatStr, ...args); + const $messagesService = this.$injector.resolve("messagesService"); + exception.message = $messagesService.getMessage.apply($messagesService, [opts.formatStr].concat(argsArray)); } catch (err) { // Ignore } diff --git a/file-system.ts b/file-system.ts index 84ddd6d5..381ccef6 100644 --- a/file-system.ts +++ b/file-system.ts @@ -535,7 +535,7 @@ export class FileSystem implements IFileSystem { return future; } - public rm(options: string = undefined, ...files: string[]): void { + public rm(options?: string, ...files: string[]): void { shelljs.rm(options, files); } diff --git a/helpers.ts b/helpers.ts index e4bca8c9..252af627 100644 --- a/helpers.ts +++ b/helpers.ts @@ -40,9 +40,11 @@ export function quoteString(s: string): string { return (platform() === "win32") ? cmdQuote(s) : bashQuote(s); } -export function createGUID(useBraces: boolean = true) { +export function createGUID(useBraces?: boolean) { let output: string; + useBraces = useBraces === undefined ? true : useBraces; + if (useBraces) { output = "{" + uuid.v4() + "}"; } else { @@ -64,7 +66,8 @@ export function isResponseRedirect(response: Server.IRequestResponseData) { return _.includes([301, 302, 303, 307, 308], response.statusCode); } -export function formatListOfNames(names: string[], conjunction = "or"): string { +export function formatListOfNames(names: string[], conjunction?: string): string { + conjunction = conjunction === undefined ? "or" : conjunction; if (names.length <= 1) { return names[0]; } else { @@ -357,10 +360,12 @@ export function connectEventuallyUntilTimeout(factory: () => net.Socket, timeout // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. -let FN_NAME_AND_ARGS = /^function\s*([^\(]*)\(\s*([^\)]*)\)/m; -let FN_ARG_SPLIT = /,/; -let FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; -let STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; +const CLASS_NAME = /class\s+([A-Z].+?)(?:\s+.*?)?\{/; +const CONSTRUCTOR_ARGS = /constructor\s*([^\(]*)\(\s*([^\)]*)\)/m; +const FN_NAME_AND_ARGS = /^(?:function)?\s*([^\(]*)\(\s*([^\)]*)\)\s*\{/m; +const FN_ARG_SPLIT = /,/; +const FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; +const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; export function annotate(fn: any) { let $inject: any, @@ -371,16 +376,27 @@ export function annotate(fn: any) { if (!($inject = fn.$inject) || $inject.name !== fn.name) { $inject = { args: [], name: "" }; fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_NAME_AND_ARGS); - $inject.name = argDecl[1]; - if (fn.length) { + + let nameMatch = fnText.match(CLASS_NAME); + + if (nameMatch) { + argDecl = fnText.match(CONSTRUCTOR_ARGS); + } else { + nameMatch = argDecl = fnText.match(FN_NAME_AND_ARGS); + } + + $inject.name = nameMatch && nameMatch[1]; + + if (argDecl && fnText.length) { argDecl[2].split(FN_ARG_SPLIT).forEach((arg) => { arg.replace(FN_ARG, (all, underscore, name) => $inject.args.push(name)); }); } + fn.$inject = $inject; } } + return $inject; } diff --git a/logger.ts b/logger.ts index 109b0683..01f139e7 100644 --- a/logger.ts +++ b/logger.ts @@ -65,7 +65,7 @@ export class Logger implements ILogger { } warnWithLabel(...args: string[]): void { - let message = util.format(...args); + let message = util.format.apply(null, args); this.warn(`${Logger.LABEL} ${message}`); } diff --git a/mobile/android/android-emulator-services.ts b/mobile/android/android-emulator-services.ts index f22f785f..d6ebe9d1 100644 --- a/mobile/android/android-emulator-services.ts +++ b/mobile/android/android-emulator-services.ts @@ -419,7 +419,7 @@ class AndroidEmulatorServices implements Mobile.IAndroidEmulatorServices { }).future()(); } - private parseAvdFile(avdName: string, avdFileName: string, avdInfo: Mobile.IAvdInfo = null): IFuture { + private parseAvdFile(avdName: string, avdFileName: string, avdInfo?: Mobile.IAvdInfo): IFuture { return (() => { if (!this.$fs.exists(avdFileName).wait()) { return null; diff --git a/mobile/android/device-android-debug-bridge.ts b/mobile/android/device-android-debug-bridge.ts index 0f04e6ef..524f8398 100644 --- a/mobile/android/device-android-debug-bridge.ts +++ b/mobile/android/device-android-debug-bridge.ts @@ -20,8 +20,9 @@ export class DeviceAndroidDebugBridge extends AndroidDebugBridge implements Mobi return super.executeCommand(args, options); } - public sendBroadcastToDevice(action: string, extras: IStringDictionary = {}): IFuture { + public sendBroadcastToDevice(action: string, extras?: IStringDictionary): IFuture { return (() => { + extras = extras || {}; let broadcastCommand = ["am", "broadcast", "-a", `${action}`]; _.each(extras, (value, key) => broadcastCommand.push("-e", key, value)); diff --git a/mobile/ios/simulator/ios-emulator-services.ts b/mobile/ios/simulator/ios-emulator-services.ts index 090bd86e..1976a70e 100644 --- a/mobile/ios/simulator/ios-emulator-services.ts +++ b/mobile/ios/simulator/ios-emulator-services.ts @@ -18,14 +18,16 @@ class IosEmulatorServices implements Mobile.IiOSSimulatorService { return Future.fromResult(); } - public checkAvailability(dependsOnProject: boolean = true): IFuture { + public checkAvailability(dependsOnProject?: boolean): IFuture { return (() => { - if(!this.$hostInfo.isDarwin) { + dependsOnProject = dependsOnProject === undefined ? true : dependsOnProject; + + if (!this.$hostInfo.isDarwin) { this.$errors.failWithoutHelp("iOS Simulator is available only on Mac OS X."); } let platform = this.$devicePlatformsConstants.iOS; - if(dependsOnProject && !this.$emulatorSettingsService.canStart(platform).wait()) { + if (dependsOnProject && !this.$emulatorSettingsService.canStart(platform).wait()) { this.$errors.failWithoutHelp("The current project does not target iOS and cannot be run in the iOS Simulator."); } }).future()(); @@ -45,7 +47,7 @@ class IosEmulatorServices implements Mobile.IiOSSimulatorService { let iosSimPath = this.$iOSSimResolver.iOSSimPath; let nodeCommandName = process.argv[0]; - let opts = [ "notify-post", notification ]; + let opts = ["notify-post", notification]; if (this.$options.device) { opts.push("--device", this.$options.device); @@ -59,7 +61,7 @@ class IosEmulatorServices implements Mobile.IiOSSimulatorService { let iosSimPath = this.$iOSSimResolver.iOSSimPath; let nodeCommandName = process.argv[0]; - if(this.$options.availableDevices) { + if (this.$options.availableDevices) { this.$childProcess.spawnFromEvent(nodeCommandName, [iosSimPath, "device-types"], "close", { stdio: "inherit" }).wait(); return; } @@ -73,18 +75,18 @@ class IosEmulatorServices implements Mobile.IiOSSimulatorService { opts = opts.concat("--timeout", this.$options.timeout); } - if(this.$options.sdk) { + if (this.$options.sdk) { opts = opts.concat("--sdkVersion", this.$options.sdk); } - if(!this.$options.justlaunch) { + if (!this.$options.justlaunch) { opts.push("--logging"); } else { - if(emulatorOptions) { - if(emulatorOptions.stderrFilePath) { + if (emulatorOptions) { + if (emulatorOptions.stderrFilePath) { opts = opts.concat("--stderr", emulatorOptions.stderrFilePath); } - if(emulatorOptions.stdoutFilePath) { + if (emulatorOptions.stdoutFilePath) { opts = opts.concat("--stdout", emulatorOptions.stdoutFilePath); } } @@ -92,17 +94,17 @@ class IosEmulatorServices implements Mobile.IiOSSimulatorService { opts.push("--exit"); } - if(this.$options.device) { + if (this.$options.device) { opts = opts.concat("--device", this.$options.device); } else if (emulatorOptions && emulatorOptions.deviceType) { opts = opts.concat("--device", emulatorOptions.deviceType); } - if(emulatorOptions && emulatorOptions.args) { + if (emulatorOptions && emulatorOptions.args) { opts.push(`--args=${emulatorOptions.args}`); } - if(emulatorOptions && emulatorOptions.waitForDebugger) { + if (emulatorOptions && emulatorOptions.waitForDebugger) { opts.push("--waitForDebugger"); } diff --git a/mobile/mobile-core/android-device-discovery.ts b/mobile/mobile-core/android-device-discovery.ts index f07e7e80..50453422 100644 --- a/mobile/mobile-core/android-device-discovery.ts +++ b/mobile/mobile-core/android-device-discovery.ts @@ -82,7 +82,9 @@ export class AndroidDeviceDiscovery extends DeviceDiscovery implements Mobile.IA .filter((element: string) => !helpers.isNullOrWhitespace(element)) .map((element: string) => { // http://developer.android.com/tools/help/adb.html#devicestatus - let [identifier, status] = element.split('\t'); + let data = element.split('\t'), + identifier = data[0], + status = data[1]; return { identifier: identifier, status: status diff --git a/package.json b/package.json index 48fee4c6..26e9e9c4 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,8 @@ "mobile-cli-lib": "./bin/common-lib.js" }, "scripts": { - "test": "node_modules/.bin/istanbul cover node_modules/mocha/bin/_mocha -- --ui mocha-fibers --recursive --reporter spec-xunit-file --require test/test-bootstrap.js --timeout 15000 test/unit-tests/" + "mocha": "node test-scripts/mocha.js", + "test": "node test-scripts/istanbul.js" }, "main": "./common-lib.js", "repository": { @@ -24,7 +25,6 @@ "Proton" ], "dependencies": { - "bluebird": "2.9.34", "bplist-parser": "0.0.6", "bufferpack": "0.0.6", "byline": "4.2.1", @@ -81,7 +81,7 @@ "grunt-shell": "1.3.0", "grunt-ts": "6.0.0-beta.3", "grunt-tslint": "3.3.0", - "istanbul": "0.3.17", + "istanbul": "0.4.5", "mocha": "2.5.3", "mocha-fibers": "1.1.1", "spec-xunit-file": "0.0.1-3", diff --git a/queue.ts b/queue.ts index fd30d824..a1c1849a 100644 --- a/queue.ts +++ b/queue.ts @@ -3,7 +3,8 @@ import Future = require("fibers/future"); export class Queue implements IQueue { private future: IFuture; - public constructor(private items: T[] = []) { + public constructor(private items?: T[]) { + this.items = this.items === undefined ? [] : this.items; } public enqueue(item: T): void { diff --git a/scripts/node-args.js b/scripts/node-args.js new file mode 100644 index 00000000..0a037192 --- /dev/null +++ b/scripts/node-args.js @@ -0,0 +1,15 @@ +"use strict"; + +const getNodeArgs = () => { + const nodeVersion = process.version; + const requiresHarmonyFlagRegex = /^v[45]\./; + const nodeArgs = []; + + if (requiresHarmonyFlagRegex.test(nodeVersion)) { + nodeArgs.push("--harmony"); + } + + return nodeArgs; +}; + +module.exports.getNodeArgs = getNodeArgs; \ No newline at end of file diff --git a/services/messages-service.ts b/services/messages-service.ts index 43a712b2..cafbb3b9 100644 --- a/services/messages-service.ts +++ b/services/messages-service.ts @@ -36,13 +36,15 @@ export class MessagesService implements IMessagesService { } public getMessage(id: string, ...args: string[]): string { + const argsArray = args || []; + let keys = id.split("."), - result = this.getFormatedMessage(id, ...args); + result = this.getFormatedMessage.apply(this, [id].concat(argsArray)); _.each(this.messageJsonFilesContents, jsonFileContents => { let messageValue = this.getMessageFromJsonRecursive(keys, jsonFileContents, 0); if (messageValue) { - result = this.getFormatedMessage(messageValue, ...args); + result = this.getFormatedMessage.apply(this, [messageValue].concat(argsArray)); return false; } }); @@ -81,7 +83,7 @@ export class MessagesService implements IMessagesService { } private getFormatedMessage(message: string, ...args: string[]): string { - return ~message.indexOf("%") ? util.format(message, ...args) : message; + return ~message.indexOf("%") ? util.format.apply(null, [message].concat(args || [])) : message; } } diff --git a/test-scripts/istanbul.js b/test-scripts/istanbul.js new file mode 100644 index 00000000..30f4acd2 --- /dev/null +++ b/test-scripts/istanbul.js @@ -0,0 +1,19 @@ +"use strict"; + +const childProcess = require("child_process"); +const path = require("path"); +const pathToNodeModules = path.join(__dirname, "..", "node_modules"); +const pathToIstanbul = path.join(pathToNodeModules, "istanbul", "lib", "cli.js"); +const pathToMocha = path.join(pathToNodeModules, "mocha", "bin", "_mocha"); + +const istanbulArgs = [ pathToIstanbul, "cover", pathToMocha ]; + +const nodeArgs = require("../scripts/node-args").getNodeArgs(); + +const args = nodeArgs.concat(istanbulArgs); + +const nodeProcess = childProcess.spawn("node", args, { stdio: "inherit" }); +nodeProcess.on("close", (code) => { + // We need this handler so if any test fails, we'll exit with same exit code as istanbul. + process.exit(code); +}); \ No newline at end of file diff --git a/test-scripts/mocha.js b/test-scripts/mocha.js new file mode 100644 index 00000000..19b964e9 --- /dev/null +++ b/test-scripts/mocha.js @@ -0,0 +1,15 @@ +"use strict"; + +const childProcess = require("child_process"); +const path = require("path"); +const pathToMocha = path.join(__dirname, "..", "node_modules", "mocha", "bin", "_mocha"); + +const nodeArgs = require("../scripts/node-args").getNodeArgs(); + +const args = nodeArgs.concat(pathToMocha); + +const nodeProcess = childProcess.spawn("node", args, { stdio: "inherit" }); +nodeProcess.on("close", (code) => { + // We need this handler so if any test fails, we'll exit with same exit code as mocha. + process.exit(code); +}); diff --git a/test/mocha.opts b/test/mocha.opts new file mode 100644 index 00000000..a138b1e0 --- /dev/null +++ b/test/mocha.opts @@ -0,0 +1,6 @@ +--ui mocha-fibers +--recursive +--reporter spec-xunit-file +--require test/test-bootstrap.js +--timeout 150000 +test/unit-tests \ No newline at end of file diff --git a/test/unit-tests/appbuilder/device-emitter.ts b/test/unit-tests/appbuilder/device-emitter.ts index 57847db8..0596db1f 100644 --- a/test/unit-tests/appbuilder/device-emitter.ts +++ b/test/unit-tests/appbuilder/device-emitter.ts @@ -12,6 +12,12 @@ class AndroidDeviceDiscoveryMock extends EventEmitter { } } +// Injector dependencies must be classes. +// EventEmitter is function, so our annotate method will fail. +class CustomEventEmitter extends EventEmitter { + constructor() { super(); } +} + let companionAppIdentifiers = { "cordova": { "android": "cordova-android", @@ -28,12 +34,12 @@ let companionAppIdentifiers = { function createTestInjector(): IInjector { let testInjector = new Yok(); testInjector.register("androidDeviceDiscovery", AndroidDeviceDiscoveryMock); - testInjector.register("iOSDeviceDiscovery", EventEmitter); - testInjector.register("iOSSimulatorDiscovery", EventEmitter); + testInjector.register("iOSDeviceDiscovery", CustomEventEmitter); + testInjector.register("iOSSimulatorDiscovery", CustomEventEmitter); testInjector.register("devicesService", { initialize: (opts: { skipInferPlatform: boolean }) => Future.fromResult() }); - testInjector.register("deviceLogProvider", EventEmitter); + testInjector.register("deviceLogProvider", CustomEventEmitter); testInjector.register("companionAppsService", { getAllCompanionAppIdentifiers: () => companionAppIdentifiers }); diff --git a/test/unit-tests/decorators.ts b/test/unit-tests/decorators.ts index c8f3756d..36882bec 100644 --- a/test/unit-tests/decorators.ts +++ b/test/unit-tests/decorators.ts @@ -2,7 +2,6 @@ import * as decoratorsLib from "../../decorators"; import { Yok } from "../../yok"; import {assert} from "chai"; import Future = require("fibers/future"); -import * as Promise from "bluebird"; describe("decorators", () => { let moduleName = "moduleName", // This is the name of the injected dependency that will be resolved, for example fs, devicesService, etc. @@ -129,7 +128,7 @@ describe("decorators", () => { generatePublicApiFromExportedPromiseDecorator(); let promises: Promise[] = $injector.publicApi.__modules__[moduleName][propertyName](); - Promise.all(promises) + Promise.all(promises) .then((promiseResults: string[]) => { _.each(promiseResults, (val: string, index: number) => { assert.deepEqual(val, expectedResults[index]); diff --git a/test/unit-tests/mobile/application-manager-base.ts b/test/unit-tests/mobile/application-manager-base.ts index b1391b39..b5485275 100644 --- a/test/unit-tests/mobile/application-manager-base.ts +++ b/test/unit-tests/mobile/application-manager-base.ts @@ -513,7 +513,7 @@ describe("ApplicationManagerBase", () => { while (currentlyInstalledApps.length) { let currentlyRemovedApps = currentlyInstalledApps.splice(0, 2); - removedApps.push(...currentlyRemovedApps); + removedApps = removedApps.concat(currentlyRemovedApps); testInstalledAppsResults(); } }); @@ -571,11 +571,11 @@ describe("ApplicationManagerBase", () => { for (let index = 10; index < 13; index++) { let currentlyRemovedApps = currentlyInstalledApps.splice(0, 2); - removedApps.push(...currentlyRemovedApps); + removedApps = removedApps.concat(currentlyRemovedApps); let currentlyAddedApps = [`app${index}`]; - currentlyInstalledApps.push(...currentlyAddedApps); - installedApps.push(...currentlyAddedApps); + currentlyInstalledApps = currentlyInstalledApps.concat(currentlyAddedApps); + installedApps = installedApps.concat(currentlyAddedApps); testInstalledAppsResults(); } diff --git a/test/unit-tests/stubs.ts b/test/unit-tests/stubs.ts index 33a80670..35685903 100644 --- a/test/unit-tests/stubs.ts +++ b/test/unit-tests/stubs.ts @@ -9,22 +9,22 @@ export class CommonLoggerStub implements ILogger { fatal(...args: string[]): void {} error(...args: string[]): void {} warn(...args: string[]): void { - this.out(...args); + this.out.apply(this, args); } warnWithLabel(...args: string[]): void {} info(...args: string[]): void { - this.out(...args); + this.out.apply(this, args); } debug(...args: string[]): void {} trace(...args: string[]): void { - this.traceOutput += util.format(...args) + "\n"; + this.traceOutput += util.format.apply(null, args) + "\n"; } public output = ""; public traceOutput = ""; out(...args: string[]): void { - this.output += util.format(...args) + "\n"; + this.output += util.format.apply(null, args) + "\n"; } write(...args: string[]): void { } @@ -48,7 +48,7 @@ export class ErrorsStub implements IErrors { fail(opts:{formatStr?: string; errorCode?: number; suppressCommandHelp?: boolean}, ...args: any[]): void; fail(...args: any[]) { - throw new Error(require("util").format.apply(null,args)); + throw new Error(util.format.apply(null, args)); } failWithoutHelp(message: string, ...args: any[]): void { diff --git a/test/unit-tests/yok.ts b/test/unit-tests/yok.ts index 4ab0b39a..7daeddda 100644 --- a/test/unit-tests/yok.ts +++ b/test/unit-tests/yok.ts @@ -15,137 +15,292 @@ class MyClass { } describe("yok", () => { - it("resolves pre-constructed singleton", () => { - let injector = new Yok(); - let obj = {}; - injector.register("foo", obj); + describe("functions", () => { + it("resolves pre-constructed singleton", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); - let resolved = injector.resolve("foo"); + let resolved = injector.resolve("foo"); - assert.strictEqual(obj, resolved); - }); + assert.strictEqual(obj, resolved); + }); - it("resolves given constructor", () => { - let injector = new Yok(); - let obj:any; - injector.register("foo", () => { - obj = {foo:"foo"}; - return obj; + it("resolves given constructor", () => { + let injector = new Yok(); + let obj:any; + injector.register("foo", () => { + obj = {foo:"foo"}; + return obj; + }); + + let resolved = injector.resolve("foo"); + + assert.strictEqual(resolved, obj); }); - let resolved = injector.resolve("foo"); + it("resolves constructed singleton", () => { + let injector = new Yok(); + injector.register("foo", {foo:"foo"}); - assert.strictEqual(resolved, obj); - }); + let r1 = injector.resolve("foo"); + let r2 = injector.resolve("foo"); - it("resolves constructed singleton", () => { - let injector = new Yok(); - injector.register("foo", {foo:"foo"}); + assert.strictEqual(r1, r2); + }); - let r1 = injector.resolve("foo"); - let r2 = injector.resolve("foo"); + it("injects directly into passed constructor", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); - assert.strictEqual(r1, r2); - }); + function Test(foo:any) { + this.foo = foo; + } - it("injects directly into passed constructor", () => { - let injector = new Yok(); - let obj = {}; - injector.register("foo", obj); + let result = injector.resolve(Test); - function Test(foo:any) { - this.foo = foo; - } + assert.strictEqual(obj, result.foo); + }); - let result = injector.resolve(Test); + it("inject dependency into registered constructor", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); - assert.strictEqual(obj, result.foo); - }); + function Test(foo:any) { + this.foo = foo; + } - it("inject dependency into registered constructor", () => { - let injector = new Yok(); - let obj = {}; - injector.register("foo", obj); + injector.register("test", Test); - function Test(foo:any) { - this.foo = foo; - } + let result = injector.resolve("test"); - injector.register("test", Test); + assert.strictEqual(obj, result.foo); + }); - let result = injector.resolve("test"); + it("inject dependency with $ prefix", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); - assert.strictEqual(obj, result.foo); - }); + function Test($foo:any) { + this.foo = $foo; + } - it("inject dependency with $ prefix", () => { - let injector = new Yok(); - let obj = {}; - injector.register("foo", obj); + let result = injector.resolve(Test); - function Test($foo:any) { - this.foo = $foo; - } + assert.strictEqual(obj, result.foo); + }); - let result = injector.resolve(Test); + it("inject into TS constructor", () => { + let injector = new Yok(); - assert.strictEqual(obj, result.foo); - }); + injector.register("x", "foo"); + injector.register("y", 123); - it("inject into TS constructor", () => { - let injector = new Yok(); + let result = injector.resolve(MyClass); - injector.register("x", "foo"); - injector.register("y", 123); + assert.strictEqual(result.y, 123); + result.checkX(); + }); - let result = injector.resolve(MyClass); + it("resolves a parameterless constructor", () => { + let injector = new Yok(); - assert.strictEqual(result.y, 123); - result.checkX(); - }); + function Test() { + this.foo = "foo"; + } - it("resolves a parameterless constructor", () => { - let injector = new Yok(); + let result = injector.resolve(Test); - function Test() { - this.foo = "foo"; - } + assert.equal(result.foo, "foo"); + }); - let result = injector.resolve(Test); + it("returns null when it can't resolve a command", () => { + let injector = new Yok(); + let command = injector.resolveCommand("command"); + assert.isNull(command); + }); - assert.equal(result.foo, "foo"); - }); + it("throws when it can't resolve a registered command", () => { + let injector = new Yok(); - it("returns null when it can't resolve a command", () => { - let injector = new Yok(); - let command = injector.resolveCommand("command"); - assert.isNull(command); - }); + function Command(whatever:any) { /* intentionally left blank */ } - it("throws when it can't resolve a registered command", () => { - let injector = new Yok(); + injector.registerCommand("command", Command); - function Command(whatever:any) { /* intentionally left blank */ } + assert.throws(() => injector.resolveCommand("command")); + }); + + it("disposes", () => { + let injector = new Yok(); + + function Thing() { /* intentionally left blank */ } - injector.registerCommand("command", Command); + Thing.prototype.dispose = function() { + this.disposed = true; + }; + + injector.register("thing", Thing); + let thing = injector.resolve("thing"); + injector.dispose(); + + assert.isTrue(thing.disposed); + }); - assert.throws(() => injector.resolveCommand("command")); }); - it("disposes", () => { - let injector = new Yok(); + describe("classes", () => { + it("resolves pre-constructed singleton", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); - function Thing() { /* intentionally left blank */ } + let resolved = injector.resolve("foo"); - Thing.prototype.dispose = function() { - this.disposed = true; - }; + assert.strictEqual(obj, resolved); + }); - injector.register("thing", Thing); - let thing = injector.resolve("thing"); - injector.dispose(); + it("resolves given constructor", () => { + let injector = new Yok(); + let obj:any; + injector.register("foo", () => { + obj = {foo:"foo"}; + return obj; + }); + + let resolved = injector.resolve("foo"); - assert.isTrue(thing.disposed); + assert.strictEqual(resolved, obj); + }); + + it("resolves constructed singleton", () => { + let injector = new Yok(); + injector.register("foo", {foo:"foo"}); + + let r1 = injector.resolve("foo"); + let r2 = injector.resolve("foo"); + + assert.strictEqual(r1, r2); + }); + + it("injects directly into passed constructor", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); + + class Test { + private foo: any; + + constructor(foo: any) { + this.foo = foo; + } + } + + let result = injector.resolve(Test); + assert.strictEqual(obj, result.foo); + }); + + it("inject dependency into registered constructor", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); + + class Test { + private foo: any; + + constructor(foo: any) { + this.foo = foo; + } + } + + injector.register("test", Test); + + let result = injector.resolve("test"); + + assert.strictEqual(obj, result.foo); + }); + + it("inject dependency with $ prefix", () => { + let injector = new Yok(); + let obj = {}; + injector.register("foo", obj); + + class Test { + private foo: any; + constructor($foo: any) { + this.foo = $foo; + } + } + + let result = injector.resolve(Test); + + assert.strictEqual(obj, result.foo); + }); + + it("inject into TS constructor", () => { + let injector = new Yok(); + + injector.register("x", "foo"); + injector.register("y", 123); + + let result = injector.resolve(MyClass); + + assert.strictEqual(result.y, 123); + result.checkX(); + }); + + it("resolves a parameterless constructor", () => { + let injector = new Yok(); + + class Test { + private foo: any; + constructor() { + this.foo = "foo"; + } + } + + let result = injector.resolve(Test); + + assert.equal(result.foo, "foo"); + }); + + it("returns null when it can't resolve a command", () => { + let injector = new Yok(); + let command = injector.resolveCommand("command"); + assert.isNull(command); + }); + + it("throws when it can't resolve a registered command", () => { + let injector = new Yok(); + + class Command { + constructor(whatever:any) { /* intentionally left blank */ } + } + + injector.registerCommand("command", Command); + + assert.throws(() => injector.resolveCommand("command")); + }); + + it("disposes", () => { + let injector = new Yok(); + + class Thing { + public disposed = false; + + public dispose() { + this.disposed = true; + } + }; + + injector.register("thing", Thing); + let thing = injector.resolve("thing"); + injector.dispose(); + + assert.isTrue(thing.disposed); + }); }); it("throws error when module is required more than once", () => { diff --git a/tsconfig.json b/tsconfig.json index 4306e05c..783eb5e9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,8 +1,11 @@ { "compilerOptions": { - "target": "ES5", + "target": "es6", "module": "commonjs", "sourceMap": true, + "declaration": false, + "removeComments": false, + "noImplicitAny": true, "experimentalDecorators": true }, "exclude": [ diff --git a/yok.ts b/yok.ts index 933b42c2..b30cf0e5 100644 --- a/yok.ts +++ b/yok.ts @@ -290,8 +290,8 @@ export class Yok implements IInjector { return commandName.indexOf("*") > 0 && commandName.indexOf("|") > 0; } - public register(name: string, resolver: any, shared: boolean = true): void { - + public register(name: string, resolver: any, shared?: boolean): void { + shared = shared === undefined ? true : shared; trace("registered '%s'", name); let dependency: any = this.modules[name] || {}; @@ -364,12 +364,7 @@ export class Yok implements IInjector { let name = ctor.$inject.name; if (name && name[0] === name[0].toUpperCase()) { - let EmptyCtor = function () { /* intentionally left blank */ }; - EmptyCtor.prototype = ctor.prototype; - let obj = new (EmptyCtor)(); - - ctor.apply(obj, resolvedArgs); - return obj; + return new (ctor)(...resolvedArgs); } else { return ctor.apply(null, resolvedArgs); }