Merge branch 'handleExtraObjectLiteralProperties' of https://github.com/DanielRosenwasser/DefinitelyTyped into handleExtraObjectLiteralProperties

This commit is contained in:
Daniel Rosenwasser
2015-08-25 12:22:15 -07:00
150 changed files with 34628 additions and 5911 deletions
@@ -197,3 +197,12 @@ users = odataResourceClass.odata()
var countResult = odataResourceClass.odata().count();
var total = countResult.result;
var usersSelect1 = odataResourceClass.odata()
.select('name', 'user');
var usersSelect2 = odataResourceClass.odata()
.select(['name', 'user']);
+9 -5
View File
@@ -267,6 +267,7 @@ declare module OData {
interface ICountResult{
result: number;
$promise: angular.IPromise<any>;
}
class Provider<T> {
@@ -278,14 +279,17 @@ declare module OData {
private expandables;
constructor(callback: ProviderCallback<T>);
filter(operand1: any, operand2?: any, operand3?: any): Provider<T>;
orderBy(arg1: any, arg2?: any): Provider<T>;
orderBy(arg1: string, arg2?: string): Provider<T>;
take(amount: number): Provider<T>;
skip(amount: number): Provider<T>;
private execute();
query(success?: any, error?: any): T[];
single(success?: any, error?: any): T;
get(data: any, success?: any, error?: any): T;
expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider<T>;
query(success?: ((p:T[])=>void), error?: (()=>void)): T[];
single(success?: ((p:T)=>void), error?: (()=>void)): T;
get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T;
expand(...params: string[]): Provider<T>;
expand(params: string[]): Provider<T>;
select(...params: string[]): Provider<T>;
select(params: string[]): Provider<T>;
count(success?: (result: ICountResult) => any, error?: () => any):ICountResult;
withInlineCount(): Provider<T>;
}
+15 -1
View File
@@ -1228,7 +1228,21 @@ declare module protractor {
row(index: number): LocatorWithColumn;
}
interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy {
interface IProtractorLocatorStrategy {
/**
* webdriver's By is an enum of locator functions, so we must set it to
* a prototype before inheriting from it.
*/
className: typeof webdriver.By.className;
css: typeof webdriver.By.css;
id: typeof webdriver.By.id;
linkText: typeof webdriver.By.linkText;
js: typeof webdriver.By.js;
name: typeof webdriver.By.name;
partialLinkText: typeof webdriver.By.partialLinkText;
tagName: typeof webdriver.By.tagName;
xpath: typeof webdriver.By.xpath;
/**
* Add a locator to this instance of ProtractorBy. This locator can then be
* used with element(by.locatorName(args)).
@@ -14,12 +14,28 @@ myApp.config((
var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1");
$urlMatcherFactory.caseInsensitive(false);
var isCaseInsensitive = $urlMatcherFactory.caseInsensitive();
$urlMatcherFactory.defaultSquashPolicy("nosquash");
$urlMatcherFactory.strictMode(true);
var isStrictMode = $urlMatcherFactory.strictMode();
$urlMatcherFactory.type("myType2", {
encode: function (item: any) { return item; },
decode: function (item: any) { return item; },
is: function (item: any) { return true; }
});
$urlMatcherFactory.type("fullType", {
decode: (val) => parseInt(val, 10),
encode: (val) => val && val.toString(),
equals: (a, b) => this.is(a) && a === b,
is: (val) => angular.isNumber(val) && isFinite(val) && val % 1 === 0,
pattern: /\d+/
});
var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' });
var concat: ng.ui.IUrlMatcher = matcher.concat('/test');
var str: string = matcher.format({ id:'bob', q:'yes' });
@@ -177,3 +193,35 @@ module UiViewScrollProviderTests {
$uiViewScrollProvider.useAnchorScroll();
}]);
}
interface ITestUserService {
isLoggedIn: () => boolean;
handleLogin: () => ng.IPromise<{}>;
}
module UrlRouterProviderTests {
var app = angular.module("urlRouterProviderTests", ["ui.router"]);
app.config(($urlRouterProvider: ng.ui.IUrlRouterProvider) => {
// Prevent $urlRouter from automatically intercepting URL changes;
// this allows you to configure custom behavior in between
// location changes and route synchronization:
$urlRouterProvider.deferIntercept();
}).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService) => {
$rootScope.$on('$locationChangeSuccess', e => {
// UserService is an example service for managing user state
if (UserService.isLoggedIn()) return;
// Prevent $urlRouter's default handler from firing
e.preventDefault();
UserService.handleLogin().then(() => {
// Once the user has logged in, sync the current URL to the router:
$urlRouter.sync();
});
});
// Configures $urlRouter's listener *after* your custom listener
$urlRouter.listen();
});
}
+113 -3
View File
@@ -91,12 +91,70 @@ declare module angular.ui {
}
interface IUrlMatcherFactory {
/**
* Creates a UrlMatcher for the specified pattern.
*
* @param pattern {string} The URL pattern.
*
* @returns {IUrlMatcher} The UrlMatcher.
*/
compile(pattern: string): IUrlMatcher;
/**
* Returns true if the specified object is a UrlMatcher, or false otherwise.
*
* @param o {any} The object to perform the type check against.
*
* @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods.
*/
isMatcher(o: any): boolean;
type(name: string, definition: any, definitionFn?: any): any;
caseInsensitive(value: boolean): void;
/**
* Returns a type definition for the specified name
*
* @param name {string} The type definition name
*
* @returns {IType} The type definition
*/
type(name: string): IType;
/**
* Registers a custom Type object that can be used to generate URLs with typed parameters.
*
* @param {IType} definition The type definition.
* @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition.
*
* @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider.
*/
type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory;
/**
* Registers a custom Type object that can be used to generate URLs with typed parameters.
*
* @param {IType} definition The type definition.
* @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition.
*
* @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider.
*/
type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory;
/**
* Defines whether URL matching should be case sensitive (the default behavior), or not.
*
* @param value {boolean} false to match URL in a case sensitive manner; otherwise true;
*
* @returns {boolean} the current value of caseInsensitive
*/
caseInsensitive(value?: boolean): boolean;
/**
* Sets the default behavior when generating or matching URLs with default parameter values
*
* @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string.
*/
defaultSquashPolicy(value: string): void;
strictMode(value: boolean): void;
/**
* Defines whether URLs should match trailing slashes, or not (the default behavior).
*
* @param value {boolean} false to match trailing slashes in URLs, otherwise true.
*
* @returns {boolean} the current value of strictMode
*/
strictMode(value?: boolean): boolean;
}
interface IUrlRouterProvider extends angular.IServiceProvider {
@@ -114,6 +172,14 @@ declare module angular.ui {
otherwise(path: string): IUrlRouterProvider;
rule(handler: Function): IUrlRouterProvider;
rule(handler: any[]): IUrlRouterProvider;
/**
* Disables (or enables) deferring location change interception.
*
* If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.
*
* @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true.
*/
deferIntercept(defer?: boolean): void;
}
interface IStateOptions {
@@ -203,6 +269,7 @@ declare module angular.ui {
*
*/
sync(): void;
listen(): void;
}
interface IUiViewScrollProvider {
@@ -212,4 +279,47 @@ declare module angular.ui {
*/
useAnchorScroll(): void;
}
interface IType {
/**
* Converts a parameter value (from URL string or transition param) to a custom/native value.
*
* @param val {string} The URL parameter value to decode.
* @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {any} Returns a custom representation of the URL parameter value.
*/
decode(val: string, key: string): any;
/**
* Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string.
*
* @param val {any} The value to encode.
* @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {string} Returns a string representation of val that can be encoded in a URL.
*/
encode(val: any, key: string): string;
/**
* Determines whether two decoded values are equivalent.
*
* @param a {any} A value to compare against.
* @param b {any} A value to compare against.
*
* @returns {boolean} Returns true if the values are equivalent/equal, otherwise false.
*/
equals? (a: any, b: any): boolean;
/**
* Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object.
*
* @param val {any} The value to check.
* @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects.
*
* @returns {boolean} Returns true if the value matches the type, otherwise false.
*/
is(val: any, key: string): boolean;
/**
* The regular expression pattern used to match values of this type when coming from a substring of a URL.
*/
pattern?: RegExp;
}
}
@@ -0,0 +1,93 @@
/// <reference path="angular-ui-scroll.d.ts" />
var myApp = angular.module('application', ['ui.scroll', 'ui.scroll.jqlite']);
module application {
interface IItem {
id: number;
content: string;
}
class DatasourceTest implements ng.ui.IScrollDatasource<IItem> {
get(index: number, count: number, success: (results: IItem[]) => void): void {
var ret = new Array<IItem>();
for (var i=0; i < count; i++) {
ret.push({id: i, content: 'item ' + i.toString()});
}
success(ret);
}
}
function factory(): any {
return DatasourceTest;
}
myApp.factory('DatasourceTest', factory);
// demo/examples/adapter
myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) {
var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter;
$scope['datasource'] = datasource;
$scope['updateList1'] = (): void => {
firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => {
return item.content += ' *';
})
};
$scope['removeFromList1'] = (): void => {
firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => {
if (scope.$index % 2 === 0) {
return []
}
})
};
var idList1: number = 1000;
$scope['addToList1'] = (): void => {
firstListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
var newItem: IItem;
newItem = void 0;
if (scope.$index === 2) {
newItem = {
id: idList1,
content: 'a new one #' + idList1
};
idList1++;
return [item, newItem];
}
});
};
$scope['updateList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
return item.content += ' *';
});
};
$scope['removeFromList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
if (scope.$index % 2 !== 0) {
return [];
}
});
};
var idList2: number = 2000;
$scope['addToList2'] = (): void => {
secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => {
var newItem: IItem;
newItem = void 0;
if (scope.$index === 4) {
newItem = {
id: idList2,
content: 'a new one #' + idList1
};
idList2++;
return [item, newItem];
}
});
};
}]);
}
+85
View File
@@ -0,0 +1,85 @@
// Type definitions for Angular JS 1.3.1+ (ui.scroll module)
// Project: https://github.com/angular-ui/ui-scroll
// Definitions by: Mark Nadig <https://github.com/marknadig>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.ui {
interface IScrollDatasource<T> {
/**
* The datasource object implements methods and properties to be used by the directive to access the data
*
* @param index indicates the first data row requested
*
* @param count indicates number of data rows requested
*
* @param success function to call when the data are retrieved. The implementation of the service has to call
* this function when the data are retrieved and pass it an array of the items retrieved. If no items are
* retrieved, an empty array has to be passed.
*
* Important: Make sure to respect the index and count parameters of the request. The array passed to the
* success method should have exactly count elements unless it hit eof/bof
*/
get(index: number, count: number, success: (results: Array<T>) => any): void;
}
interface IScrollAdapter {
/**
* a boolean value indicating whether there are any pending load requests.
*/
isLoading: boolean;
/**
* a reference to the item currently in the topmost visible position.
*/
topVisible: any;
/**
* a reference to the DOM element currently in the topmost visible position.
*/
topVisibleElement: ng.IAugmentedJQueryStatic;
/**
* a reference to the scope created for the item currently in the topmost visible position.
*/
topVisibleScope: ng.IRepeatScope;
/**
* calling this method reinitializes and reloads the scroller content.
*/
reload(): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
* @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with
* the given index currently is not in the buffer no updates will be applied. $index property of the item $scope
* can be used to access the index value for a given item
*
* @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will
* be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item,
* the old item stays in place.
*/
applyUpdates(index: number, newItems: any[]): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
* @param updater is a function to be applied to every item currently in the buffer. The function will receive
* 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and
* element is the html element for the item. The return value of the function should be an array of items.
* Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise
* the item is replaced by the items in the array. If the return value is not an array, the item remains
* unaffected, unless some updates were made to the item in the updater function. This can be thought of as
* in place update.
*/
applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void;
/**
* Adds new items after the last item in the buffer
*
* @param newItems provides an array of items to be appended.
*/
append(newItems: any[]): void;
/**
* Adds new items before the first item in the buffer
*
* @param newItems provides an array of items to be prepended.
*/
prepend(newItems: any[]): void;
}
}
File diff suppressed because it is too large Load Diff
+902 -1691
View File
File diff suppressed because it is too large Load Diff
+689
View File
@@ -0,0 +1,689 @@
// Type definitions for Angular v2.0.0-alpha.35
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ngRouter {
/**
* # Router
* The router is responsible for mapping URLs to components.
*
* You can see the state of the router by inspecting the read-only field `router.navigating`.
* This may be useful for showing a spinner, for instance.
*
* ## Concepts
* Routers and component instances have a 1:1 correspondence.
*
* The router holds reference to a number of "outlets." An outlet is a placeholder that the
* router dynamically fills in depending on the current URL.
*
* When the router navigates from a URL, it must first recognizes it and serialize it into an
* `Instruction`.
* The router uses the `RouteRegistry` to get an `Instruction`.
*/
class Router {
navigating: boolean;
lastNavigationAttempt: string;
registry: RouteRegistry;
parent: Router;
hostComponent: any;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
childRouter(hostComponent: any): Router;
/**
* Register an object to notify of route changes. You probably don't need to use this unless
* you're writing a reusable component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
/**
* Navigate to a URL. Returns a promise that resolves when navigation is complete.
*
* If the given URL begins with a `/`, router will navigate absolutely.
* If the given URL does not begin with `/`, the router will navigate relative to this component.
*/
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Subscribe to URL updates from the router
*/
subscribe(onNext: (value: any) => void): void;
/**
* Removes the contents of this router's outlet and all descendant outlets
*/
deactivate(instruction: Instruction): Promise<any>;
/**
* Given a URL, returns an instruction representing the component graph
*/
recognize(url: string): Promise<Instruction>;
/**
* Navigates to either the last URL successfully navigated to, or the last URL requested if the
* router has yet to successfully navigate.
*/
renavigate(): Promise<any>;
/**
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): Instruction;
}
class RootRouter extends Router {
commit(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
}
/**
* A router outlet is a placeholder that Angular dynamically fills based on the application's route.
*
* ## Use
*
* ```
* <router-outlet></router-outlet>
* ```
*/
class RouterOutlet {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
*/
commit(instruction: Instruction): Promise<any>;
/**
* Called by Router during recognition phase
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
/**
* Called by Router during recognition phase
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
}
/**
* The RouterLink directive lets you link to specific parts of your app.
*
* Consider the following route configuration:
*
* ```
* @RouteConfig([
* { path: '/user', component: UserCmp, as: 'user' }
* ]);
* class MyComp {}
* ```
*
* When linking to this `user` route, you can write:
*
* ```
* <a [router-link]="['./user']">link to user component</a>
* ```
*
* RouterLink expects the value to be an array of route names, followed by the params
* for that level of routing. For instance `['/team', {teamId: 1}, 'user', {userId: 2}]`
* means that we want to generate a link for the `team` route with params `{teamId: 1}`,
* and with a child route `user` with params `{userId: 2}`.
*
* The first route name should be prepended with `/`, `./`, or `../`.
* If the route begins with `/`, the router will look up the route from the root of the app.
* If the route begins with `./`, the router will instead look in the current component's
* children for the route. And if the route begins with `../`, the router will look at the
* current component's parent.
*/
class RouterLink {
visibleHref: string;
routeParams: void;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
* It is responsible for creating Instructions from URLs, and generating URLs based on route and
* parameters.
*/
class RouteRegistry {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any): void;
/**
* Given a URL and a parent component, return the most specific instruction for navigating
* the application into the state specified by the url
*/
recognize(url: string, parentComponent: any): Promise<Instruction>;
/**
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
path(): string;
pushState(ctx: any, title: string, url: string): void;
forward(): void;
back(): void;
onPopState(fn: (_: any) => any): void;
getBaseHref(): string;
}
class HashLocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
class HTML5LocationStrategy extends LocationStrategy {
onPopState(fn: EventListener): void;
getBaseHref(): string;
path(): string;
pushState(state: any, title: string, url: string): void;
forward(): void;
back(): void;
}
/**
* This is the service that an application developer will directly interact with.
*
* Responsible for normalizing the URL against the application's base href.
* A normalized URL is absolute from the URL host, includes the application's base href, and has no
* trailing slash:
* - `/my/app/user/123` is normalized
* - `my/app/user/123` **is not** normalized
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
path(): string;
normalize(url: string): string;
normalizeAbsolutely(url: string): string;
go(url: string): void;
forward(): void;
back(): void;
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const APP_BASE_HREF : OpaqueToken ;
/**
* Responsible for performing each step of navigation.
* "Steps" are conceptually similar to "middleware"
*/
class Pipeline {
steps: List<Function>;
process(instruction: Instruction): Promise<any>;
}
/**
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: List<string>;
params: StringMap<string, any>;
componentType: void;
resolveComponentType(): Promise<Type>;
specificity: void;
terminal: void;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: List<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const routerDirectives : List<any> ;
var routerInjectables : List<any> ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class Redirect implements RouteDefinition {
path: string;
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
+251 -31
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular v2.0.0-alpha.34
// Type definitions for Angular v2.0.0-alpha.35
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -8,16 +8,22 @@
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// angular2/router depends transitively on these libraries.
// If you don't have them installed you can install them using TSD
// https://github.com/DefinitelyTyped/tsd
///<reference path="./angular2.d.ts"/>
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
declare module ng {
declare module ngRouter {
/**
* # Router
@@ -87,6 +93,13 @@ declare module ng {
navigate(url: string, _skipLocationChange?: boolean): Promise<any>;
/**
* Navigate via the provided instruction. Returns a promise that resolves when navigation is
* complete.
*/
navigateInstruction(instruction: Instruction, _skipLocationChange?: boolean): Promise<any>;
/**
* Updates this router and all descendant routers according to the given instruction
*/
@@ -122,7 +135,7 @@ declare module ng {
* Generate a URL from a component name and optional map of parameters. The URL is relative to the
* app's base href.
*/
generate(linkParams: List<any>): string;
generate(linkParams: List<any>): Instruction;
}
class RootRouter extends Router {
@@ -144,6 +157,8 @@ declare module ng {
childRouter: Router;
name: string;
/**
* Given an instruction, update the contents of this outlet.
@@ -223,13 +238,13 @@ declare module ng {
/**
* Given a component and a configuration object, add the route to this registry
*/
config(parentComponent: any, config: RouteDefinition, isRootLevelRoute?: boolean): void;
config(parentComponent: any, config: RouteDefinition): void;
/**
* Reads the annotations of a component and configures the registry based on them
*/
configFromComponent(component: any, isRootComponent?: boolean): void;
configFromComponent(component: any): void;
/**
@@ -243,7 +258,7 @@ declare module ng {
* Given a normalized list with component names and params like: `['user', {id: 3 }]`
* generates a url with a leading slash relative to the provided `parentComponent`.
*/
generate(linkParams: List<any>, parentComponent: any): string;
generate(linkParams: List<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
@@ -319,7 +334,7 @@ declare module ng {
subscribe(onNext: (value: any) => void, onThrow?: (exception: any) => void, onReturn?: () => void): void;
}
const appBaseHrefToken : OpaqueToken ;
const APP_BASE_HREF : OpaqueToken ;
/**
@@ -335,70 +350,248 @@ declare module ng {
/**
* Defines route lifecycle method [onActivate]
* Defines route lifecycle method [onActivate], which is called by the router at the end of a
* successful route navigation.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* If `onActivate` returns a promise, the route change will wait until the promise settles to
* instantiate and activate child components.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements OnActivate {
* onActivate(next, prev) {
* this.log = 'Finished navigating from ' + prev.urlPath + ' to ' + next.urlPath;
* }
* }
* ```
*/
interface OnActivate {
onActivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
onActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onDeactivate]
* Defines route lifecycle method [onDeactivate], which is called by the router before destroying
* a component as part of a route change.
*
* If `onDeactivate` returns a promise, the route change will wait until the promise settles.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnDeactivate {
onDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
onDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [onReuse]
* Defines route lifecycle method [onReuse], which is called by the router at the end of a
* successful route navigation when [canReuse] is implemented and returns or resolves to true.
*
* For a single component's navigation, only one of either [onActivate] or [onReuse] will be called,
* depending on the result of [canReuse].
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse() {
* return true;
* }
*
* onReuse(next, prev) {
* this.params = next.params;
* }
* }
* ```
*/
interface OnReuse {
onReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
onReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canDeactivate]
* Defines route lifecycle method [canDeactivate], which is called by the router to determine
* if a component can be removed as part of a navigation.
*
* If `canDeactivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canDeactivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanDeactivate {
* canDeactivate(next, prev) {
* return askUserIfTheyAreSureTheyWantToQuit();
* }
* }
* ```
*/
interface CanDeactivate {
canDeactivate(nextInstruction: Instruction, prevInstruction: Instruction): any;
canDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
/**
* Defines route lifecycle method [canReuse]
* Defines route lifecycle method [canReuse], which is called by the router to determine whether a
* component should be reused across routes, or whether to destroy and instantiate a new component.
*
* If `canReuse` returns or resolves to `true`, the component instance will be reused.
*
* If `canReuse` throws or rejects, the navigation will be cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'my-cmp'
* })
* class MyCmp implements CanReuse, OnReuse {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
* }
* ```
*/
interface CanReuse {
canReuse(nextInstruction: Instruction, prevInstruction: Instruction): any;
canReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction): any;
}
var CanActivate : (hook: (next: Instruction, prev: Instruction) => Promise<boolean>| boolean) => ClassDecorator ;
/**
* An `Instruction` represents the component hierarchy of the application based on a given route
* Defines route lifecycle method [canActivate], which is called by the router to determine
* if a component can be instantiated as part of a navigation.
*
* Note that unlike other lifecycle hooks, this one uses an annotation rather than an interface.
* This is because [canActivate] is called before the component is instantiated.
*
* If `canActivate` returns or resolves to `false`, the navigation is cancelled.
*
* If `canActivate` throws or rejects, the navigation is also cancelled.
*
* ## Example
* ```
* @Directive({
* selector: 'control-panel-cmp'
* })
* @CanActivate(() => checkIfUserIsLoggedIn())
* class ControlPanelCmp {
* // ...
* }
* ```
*/
var CanActivate : (hook: (next: ComponentInstruction, prev: ComponentInstruction) => Promise<boolean>| boolean) =>
ClassDecorator ;
/**
* `Instruction` is a tree of `ComponentInstructions`, with all the information needed
* to transition each component in the app to a given route, including all auxiliary routes.
*
* This is a public API.
*/
class Instruction {
accumulatedUrl: string;
reuse: boolean;
specificity: number;
component: any;
capturedUrl: string;
component: ComponentInstruction;
child: Instruction;
params(): StringMap<string, string>;
auxInstruction: StringMap<string, Instruction>;
replaceChild(child: Instruction): Instruction;
}
/**
* A `ComponentInstruction` represents the route state for a single component. An `Instruction` is
* composed of a tree of these `ComponentInstruction`s.
*
* `ComponentInstructions` is a public API. Instances of `ComponentInstruction` are passed
* to route lifecycle hooks, like {@link CanActivate}.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: List<string>;
params: StringMap<string, any>;
componentType: void;
resolveComponentType(): Promise<Type>;
specificity: void;
terminal: void;
routeData(): Object;
}
class Url {
path: string;
child: Url;
auxiliary: List<Url>;
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
const routerDirectives : List<any> ;
@@ -407,6 +600,8 @@ declare module ng {
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
@@ -425,10 +620,31 @@ declare module ng {
redirectTo: string;
as: string;
loader: Function;
data: any;
}
class AuxRoute implements RouteDefinition {
data: any;
path: string;
component: Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
@@ -447,8 +663,12 @@ declare module ng {
redirectTo?: string;
as?: string;
data?: any;
}
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
@@ -463,7 +683,7 @@ declare module ng {
}
declare module "angular2/router" {
export = ng;
export = ngRouter;
}
+100 -2
View File
@@ -126,18 +126,35 @@ requestHandler = httpBackendService.expect('GET', /test.local/, function (data:
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.expectDELETE('http://test.local');
requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectGET('http://test.local');
requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectHEAD('http://test.local');
requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectJSONP('http://test.local');
requestHandler = httpBackendService.expectJSONP(/test.local/);
requestHandler = httpBackendService.expectJSONP((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH('http://test.local');
requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data');
@@ -157,6 +174,15 @@ requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: st
requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST('http://test.local');
requestHandler = httpBackendService.expectPOST('http://test.local', 'response data');
@@ -176,6 +202,15 @@ requestHandler = httpBackendService.expectPOST(/test.local/, function (data: str
requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT('http://test.local');
requestHandler = httpBackendService.expectPUT('http://test.local', 'response data');
@@ -195,6 +230,15 @@ requestHandler = httpBackendService.expectPUT(/test.local/, function (data: stri
requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', 'http://test.local');
requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data');
@@ -222,18 +266,35 @@ requestHandler = httpBackendService.when('GET', /test.local/, function (data: st
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; });
requestHandler = httpBackendService.whenDELETE('http://test.local');
requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenGET('http://test.local');
requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenHEAD('http://test.local');
requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' });
requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' });
requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenJSONP('http://test.local');
requestHandler = httpBackendService.whenJSONP(/test.local/);
requestHandler = httpBackendService.whenJSONP((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH('http://test.local');
requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data');
@@ -253,6 +314,15 @@ requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: stri
requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST('http://test.local');
requestHandler = httpBackendService.whenPOST('http://test.local', 'response data');
@@ -272,6 +342,15 @@ requestHandler = httpBackendService.whenPOST(/test.local/, function (data: strin
requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT('http://test.local');
requestHandler = httpBackendService.whenPUT('http://test.local', 'response data');
@@ -291,15 +370,34 @@ requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string
requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' });
requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data');
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/);
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' });
requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' });
///////////////////////////////////////
// IRequestHandler
///////////////////////////////////////
var expectedData = { key: 'value'};
requestHandler.passThrough();
requestHandler.respond(function () { });
requestHandler.passThrough().passThrough();
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']);
requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({});
requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; });
requestHandler.respond('data');
requestHandler.respond('data').respond({});
requestHandler.respond(expectedData);
requestHandler.respond({ key: 'value' });
requestHandler.respond({ key: 'value' }, { header: 'value' });
requestHandler.respond(404);
requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText');
requestHandler.respond(404, 'data');
requestHandler.respond(404, 'data').respond({});
requestHandler.respond(404, { key: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' });
requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText');
+180 -109
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
@@ -97,137 +97,208 @@ declare module angular {
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
expectDELETE(url: string, headers?: Object): mock.IRequestHandler;
expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
expectGET(url: string, headers?: Object): mock.IRequestHandler;
expectGET(url: RegExp, headers?: Object): mock.IRequestHandler;
expectHEAD(url: string, headers?: Object): mock.IRequestHandler;
expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
expectJSONP(url: string): mock.IRequestHandler;
expectJSONP(url: RegExp): mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
whenDELETE(url: string, headers?: Object): mock.IRequestHandler;
whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler;
whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
whenGET(url: string, headers?: Object): mock.IRequestHandler;
whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenGET(url: RegExp, headers?: Object): mock.IRequestHandler;
whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenHEAD(url: string, headers?: Object): mock.IRequestHandler;
whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler;
whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenJSONP(url: string): mock.IRequestHandler;
whenJSONP(url: RegExp): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler;
whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
respond(func: Function): void;
respond(status: number, data?: any, headers?: any): void;
respond(data: any, headers?: any): void;
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
// Available wehn ngMockE2E is loaded
passThrough(): void;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
+177 -28
View File
@@ -244,17 +244,71 @@ foo.then((x) => {
// $q signature tests
module TestQ {
var $q: ng.IQService;
var promise1: ng.IPromise<any>;
var promise2: ng.IPromise<any>;
interface TResult {
a: number;
b: string;
c: boolean;
}
var tResult: TResult;
var promiseTResult: angular.IPromise<TResult>;
var $q: angular.IQService;
var promiseAny: angular.IPromise<any>;
// $q constructor
{
let result: angular.IPromise<TResult>;
result = new $q<TResult>((resolve: (value: TResult) => any) => {});
result = new $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
result = $q<TResult>((resolve: (value: TResult) => any) => {});
result = $q<TResult>((resolve: (value: TResult) => any, reject: (value: any) => any) => {});
}
// $q.all
$q.all([promise1, promise2]).then((results: any[]) => {});
$q.all<number>([promise1, promise2]).then((results: number[]) => {});
$q.all({a: promise1, b: promise2}).then((results: {[id: string]: any;}) => {});
$q.all<{a: number; b: string;}>({a: promise1, b: promise2}).then((results: {a: number; b: string;}) => {});
{
let result: angular.IPromise<any[]>;
result = $q.all([promiseAny, promiseAny]);
}
{
let result: angular.IPromise<TResult[]>;
result = $q.all<TResult>([promiseAny, promiseAny]);
}
{
let result: angular.IPromise<{[id: string]: any;}>;
result = $q.all({a: promiseAny, b: promiseAny});
}
{
let result: angular.IPromise<{a: number; b: string;}>;
result = $q.all<{a: number; b: string;}>({a: promiseAny, b: promiseAny});
}
// $q.defer
{
let result: angular.IDeferred<TResult>;
result = $q.defer<TResult>();
}
// $q.reject
{
let result: angular.IPromise<any>;
result = $q.reject();
result = $q.reject('');
}
// $q.when
{
let result: angular.IPromise<void>;
result = $q.when();
}
{
let result: angular.IPromise<TResult>;
result = $q.when<TResult>(tResult);
result = $q.when<TResult>(promiseTResult);
}
}
var httpFoo: ng.IHttpPromise<number>;
httpFoo.then((x) => {
// When returning a promise the generic type must be inferred.
@@ -273,6 +327,48 @@ httpFoo.success((data, status, headers, config) => {
});
// Deferred signature tests
module TestDeferred {
var any: any;
interface TResult {
a: number;
b: string;
c: boolean;
}
var tResult: TResult;
var deferred: angular.IDeferred<TResult>;
// deferred.resolve
{
let result: void;
result = <void>deferred.resolve();
result = <void>deferred.resolve(tResult);
}
// deferred.reject
{
let result: void;
result = deferred.reject();
result = deferred.reject(any);
}
// deferred.notify
{
let result: void;
result = deferred.notify();
result = deferred.notify(any);
}
// deferred.promise
{
let result: angular.IPromise<TResult>;
result = deferred.promise;
}
}
// Promise signature tests
module TestPromise {
var result: any;
@@ -283,34 +379,48 @@ module TestPromise {
b: string;
c: boolean;
}
interface TOther {
d: number;
e: string;
f: boolean;
}
var tresult: TResult;
var tresultPromise: ng.IPromise<TResult>;
var tother: TOther;
var totherPromise: ng.IPromise<TOther>;
var promise: angular.IPromise<TResult>;
interface IPromiseSuccessCallback<T, U> {
(promiseValue: T): angular.IHttpPromise<U>|angular.IPromise<U>|U|angular.IPromise<void>;
}
var successCallbackAnyFn: IPromiseSuccessCallback<TResult, any>;
var successCallbackTResultFn: IPromiseSuccessCallback<TResult, TResult>;
interface IPromiseErrorCallback<T> {
(error: any): angular.IHttpPromise<T>|angular.IPromise<T>|T;
}
var errorCallbackAnyFn: IPromiseErrorCallback<any>;
var errorCallbackTResultFn: IPromiseErrorCallback<TResult>;
// promise.then
result = <angular.IPromise<any>>promise.then(successCallbackAnyFn);
result = <angular.IPromise<any>>promise.then(successCallbackAnyFn, (any) => any);
result = <angular.IPromise<any>>promise.then(successCallbackAnyFn, (any) => any, (any) => any);
result = <angular.IPromise<TResult>>promise.then<TResult>(successCallbackTResultFn);
result = <angular.IPromise<TResult>>promise.then<TResult>(successCallbackTResultFn, (any) => any);
result = <angular.IPromise<TResult>>promise.then<TResult>(successCallbackTResultFn, (any) => any, (any) => any);
result = <angular.IPromise<any>>promise.then((result) => any);
result = <angular.IPromise<any>>promise.then((result) => any, (any) => any);
result = <angular.IPromise<any>>promise.then((result) => any, (any) => any, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => result);
result = <angular.IPromise<TResult>>promise.then((result) => result, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => result, (any) => any, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise, (any) => any);
result = <angular.IPromise<TResult>>promise.then((result) => tresultPromise, (any) => any, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => tother);
result = <angular.IPromise<TOther>>promise.then((result) => tother, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => tother, (any) => any, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise, (any) => any);
result = <angular.IPromise<TOther>>promise.then((result) => totherPromise, (any) => any, (any) => any);
// promise.catch
result = <angular.IPromise<any>>promise.catch(errorCallbackAnyFn);
result = <angular.IPromise<TResult>>promise.catch<TResult>(errorCallbackTResultFn);
result = <angular.IPromise<any>>promise.catch((err) => any);
result = <angular.IPromise<TResult>>promise.catch((err) => tresult);
result = <angular.IPromise<TOther>>promise.catch((err) => tother);
// promise.finally
result = <angular.IPromise<any>>promise.finally(() => any);
result = <angular.IPromise<TResult>>promise.finally<TResult>(() => any);
result = <angular.IPromise<TResult>>promise.finally(() => any);
result = <angular.IPromise<TResult>>promise.finally(() => tresult);
result = <angular.IPromise<TResult>>promise.finally(() => tother);
}
@@ -329,6 +439,45 @@ var scope: ng.IScope = element.scope();
var isolateScope: ng.IScope = element.isolateScope();
// $timeout signature tests
module TestTimeout {
interface TResult {
a: number;
b: string;
c: boolean;
}
var fnTResult: (...args: any[]) => TResult;
var promiseAny: angular.IPromise<any>;
var $timeout: angular.ITimeoutService;
// $timeout
{
let result: angular.IPromise<any>;
result = $timeout();
}
{
let result: angular.IPromise<void>;
result = $timeout(1);
result = $timeout(1, true);
}
{
let result: angular.IPromise<TResult>;
result = $timeout(fnTResult);
result = $timeout(fnTResult, 1);
result = $timeout(fnTResult, 1, true);
result = $timeout(fnTResult, 1, true, 1);
result = $timeout(fnTResult, 1, true, 1, '');
result = $timeout(fnTResult, 1, true, 1, '', true);
}
// $timeout.cancel
{
let result: boolean;
result = $timeout.cancel();
result = $timeout.cancel(promiseAny);
}
}
function test_IAttributes(attributes: ng.IAttributes){
return attributes;
+6 -3
View File
@@ -725,8 +725,9 @@ declare module angular {
// see http://docs.angularjs.org/api/ng.$timeout
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
<T>(func: (...args: any[]) => T, delay?: number, invokeApply?: boolean): IPromise<T>;
cancel(promise: IPromise<any>): boolean;
(delay?: number, invokeApply?: boolean): IPromise<void>;
<T>(fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise<T>;
cancel(promise?: IPromise<any>): boolean;
}
///////////////////////////////////////////////////////////////////////////
@@ -998,6 +999,8 @@ declare module angular {
interface IQService {
new <T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;
new <T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;
<T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;
<T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
@@ -1060,7 +1063,7 @@ declare module angular {
*
* Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.
*/
finally<TResult>(finallyCallback: () => any): IPromise<TResult>;
finally(finallyCallback: () => any): IPromise<T>;
}
interface IDeferred<T> {
+146
View File
@@ -0,0 +1,146 @@
///<reference path="apn.d.ts"/>
import apn = require("apn");
//Hand made TypeScript tests
//==========================
//Create with a hex string
var device1 = new apn.Device("ca11ab1e");
//Create with a Buffer
var device2 = new apn.Device(new Buffer("ca55e77e"));
//Create the notification
var notification = new apn.Notification();
notification.alert = {
title: "The Title",
body: "This is the body",
};
notification.badge = 5;
//Fluid api
notification.setAlertTitle("The Title")
.setAlertText("This is the body")
.setLaunchImage("LaunchImage");
//Establish the connection
var connection = new apn.Connection({
cert: "path/to/cert.pem",
key: "path/to/cert.pem"
});
//Testing some specialized event listeners
connection.on("error", (error) => {
console.log("push error", error.name, error.message);
});
connection.on("transmissionError", (errorCode, notification, device) => {
console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString());
});
//Send it using hex string
connection.pushNotification(notification, "ba5eba11");
//Send it using Buffer
connection.pushNotification(notification, new Buffer("5ca1ab1e"));
//Send it using Device
connection.pushNotification(notification, device1);
//Connecting to feedback service
var feedbackService = new apn.Feedback({
cert: "path/to/cert.pem",
key: "path/to/cert.pem",
interval: 0
});
feedbackService.on("error", (error:Error) => {
console.log("push feedback error", error.name, error.message);
});
function processFeedbackData(device:apn.Device, time:number) {
}
feedbackService.on("feedback", (feedbackData) => {
feedbackData.forEach((data) => {
processFeedbackData(data.device, data.time);
})
});
feedbackService.start();
//Original examples from apn package
//==================================
//sending-to-multiple-devices.js
//------------------------------
var tokens = ["<insert token here>", "<insert token here>"];
if(tokens[0] === "<insert token here>") {
console.log("Please set token to a valid device token for the push notification service");
process.exit();
}
// Create a connection to the service using mostly default parameters.
var service = new apn.connection({ production: false });
service.on("connected", function() {
console.log("Connected");
});
service.on("transmitted", function(notification, device) {
console.log("Notification transmitted to:" + device.token.toString("hex"));
});
service.on("transmissionError", function(errCode, notification, device) {
console.error("Notification caused error: " + errCode + " for device ", device, notification);
if (errCode === 8) {
console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox");
}
});
service.on("timeout", function () {
console.log("Connection Timeout");
});
service.on("disconnected", function() {
console.log("Disconnected from APNS");
});
service.on("socketError", console.error);
// If you plan on sending identical paylods to many devices you can do something like this.
function pushNotificationToMany() {
console.log("Sending the same notification each of the devices with one call to pushNotification.");
var note = new apn.notification();
note.setAlertText("Hello, from node-apn!");
note.badge = 1;
service.pushNotification(note, tokens);
}
pushNotificationToMany();
// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device.
function pushSomeNotifications() {
console.log("Sending a tailored notification to %d devices", tokens.length);
tokens.forEach(function(token, i) {
var note = new apn.notification();
note.setAlertText("Hello, from node-apn! You are number: " + i);
note.badge = i;
service.pushNotification(note, token);
});
}
pushSomeNotifications();
//feedback.js
//-----------
function handleFeedback(feedbackData:apn.FeedbackData[]) {
feedbackData.forEach(function(feedbackItem) {
console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time);
});
}
// Setup a connection to the feedback service using a custom interval (10 seconds)
var feedback = new apn.feedback({ production: false, interval: 10 });
feedback.on("feedback", handleFeedback);
feedback.on("feedbackError", console.error);
+364
View File
@@ -0,0 +1,364 @@
// Type definitions for node-apn
// Project: https://github.com/argon/node-apn
// Definitions by: Zenorbi <https://github.com/zenorbi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../node/node.d.ts"/>
declare module "apn" {
import events = require("events");
import net = require("net");
export interface ConnectionOptions {
/**
* The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`)
*/
cert?:string|Buffer;
/**
* The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`)
*/
key?:string|Buffer;
/**
* An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048).
*/
ca?:(string|Buffer)[];
/**
* File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above.
*/
pfx?:string|Buffer;
/**
* The passphrase for the connection key, if required
*/
passphrase?:string;
/**
* Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly)
*/
production?:boolean;
/**
* Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes.
*/
voip?:boolean;
/**
* Gateway port (Defaults to: `2195`)
*/
port?:number;
/**
* Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`)
*/
rejectUnauthorized?:boolean;
/**
* Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`)
*/
cacheLength?:number;
/**
* Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`)
*/
autoAdjustCache?:boolean;
/**
* The maximum number of connections to create for sending messages. (Defaults to: `1`)
*/
maxConnections?:number;
/**
* The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`}
*/
connectTimeout?:number;
/**
* The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h)
*/
connectionTimeout?:number;
/**
* The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10)
*/
connectionRetryLimit?:number;
/**
* Whether to buffer notifications and resend them after failure. (Defaults to: `true`)
*/
buffersNotifications?:number;
/**
* Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`)
*/
fastMode?:boolean;
}
export class Connection extends events.EventEmitter {
constructor(options:ConnectionOptions);
/**
* This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient.
*
* A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method.
*/
pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void;
/**
* Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size.
*/
setCacheLength(newLength:number):void;
/**
* Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again.
*/
shutdown():void;
/**
* Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates.
*/
on(event: "error", listener: (error:Error) => void):Connection;
/**
* Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary.
*/
on(event: "socketError", listener: (error:Error) => void):Connection;
/**
* Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission.
*/
on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):Connection;
/**
* Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent.
*/
on(event: "completed", listener: () => void):Connection;
/**
* Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently.
*
* **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered.
*/
on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):Connection;
/**
* Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally.
*/
on(event: "connected", listener: (openSockets:net.Socket[]) => void):Connection;
/**
* Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required.
*/
on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):Connection;
/**
* Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted.
*/
on(event: "timeout", listener: () => void):Connection;
/**
* Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned.
* Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`.
*/
on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):Connection;
on(event: string, listener: Function):Connection;
}
export interface NotificationAlertOptions {
title?:string;
body:string;
"title-loc-key"?:string;
"title-loc-args"?:string[];
"action-loc-key"?:string;
"loc-key"?:string;
"loc-args"?:string[];
"launch-image"?:string;
}
export class Notification {
/**
* The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default).
*/
public retryLimit:number;
/**
* The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately.
*/
public expiry:number;
/**
* From Apple's Documentation, Provide one of the following values:
*
* - 10 - The push message is sent immediately. (Default)
* > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key.
* - 5 - The push message is sent at a time that conserves power on the device receiving it.
*/
public priority:number;
/**
* The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default.
*/
public encoding:string;
/**
* This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending.
*/
public payload:any;
/**
* The value to specify for `payload.aps.badge`
*/
public badge:number;
/**
* The value to specify for `payload.aps.sound`
*/
public sound:string;
/**
* The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation.
*/
public alert:string|NotificationAlertOptions;
/**
* Setting this to true will specify "content-available" in the payload when it is compiled.
*/
public newsstandAvailable:boolean;
/**
* Setting this to true will specify "content-available" in the payload when it is compiled.
*/
public contentAvailable:boolean;
/**
* The value to specify for the `mdm` field where applicable.
*/
public mdm:string|Object;
/**
* The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation.
*/
public urlArgs:string[];
/**
* When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space.
*/
public truncateAtWordEnd:boolean;
/**
* You can optionally pass in an object representing the payload, or configure properties on the returned object.
*/
constructor(payload?:any);
/**
* Set the `aps.alert` text body. This will use the most space-efficient means.
*/
setAlertText(alertText:string):Notification;
/**
* Set the `title` property of the `aps.alert` object - used with Safari Push Notifications
*/
setAlertTitle(alertTitle:string):Notification;
/**
* Set the `action` property of the `aps.alert` object - used with Safari Push Notifications
*/
setAlertAction(alertAction:string):Notification;
/**
* Set the `action-loc-key` property of the `aps.alert` object.
*/
setActionLocKey(key:string):Notification;
/**
* Set the `loc-key` property of the `aps.alert` object.
*/
setLocKey(key:string):Notification;
/**
* Set the `loc-args` property of the `aps.alert` object.
*/
setLocArgs(args:string[]):Notification;
/**
* Set the `launch-image` property of the `aps.alert` object.
*/
setLaunchImage(image:string):Notification;
/**
* Set the `mdm` property on the payload.
*/
setMDM(mdm:string|Object):Notification;
/**
* Set the `content-available` property of the `aps` object.
*/
setNewsstandAvailable(available:boolean):Notification;
/**
* Set the `content-available` property of the `aps` object.
*/
setContentAvailable(available:boolean):Notification;
/**
* Set the `url-args` property of the `aps` object.
*/
setUrlArgs(urlArgs:string[]):Notification;
/**
* Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes.
*/
trim():number;
}
export class Device {
public token:Buffer;
/**
* `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid.
*/
constructor(deviceToken:string|Buffer);
}
export interface FeedbackOptions {
/**
* The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`)
*/
cert?:string|Buffer;
/**
* The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`)
*/
key?:string|Buffer;
/**
* An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048).
*/
ca?:(string|Buffer)[];
/**
* File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above.
*/
pfx?:string|Buffer;
/**
* The passphrase for the connection key, if required
*/
passphrase?:string;
/**
* Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly)
*/
production?:boolean;
/**
* Feedback server port (Defaults to: `2196`)
*/
port?:number;
/**
* Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true)
*/
batchFeedback?:boolean;
/**
* The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled)
*/
batchSize?:number;
/**
* How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`)
*/
interval?:number;
}
export interface FeedbackData {
time:number;
device:Device;
}
/**
* Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()`
*/
export class Feedback {
constructor(options:FeedbackOptions);
/**
* Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically.
*/
start():void;
/**
* You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time.
*/
cancel():void;
/**
* Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates.
*/
on(event: "error", listener: (error:Error) => void):Feedback;
/**
* Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover.
*/
on(event: "feedbackError", listener: (error:Error) => void):Feedback;
/**
* Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token.
*/
on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback;
on(event: string, listener: Function):Feedback;
}
export enum Errors {
"noErrorsEncountered"= 0,
"processingError"= 1,
"missingDeviceToken"= 2,
"missingTopic"= 3,
"missingPayload"= 4,
"invalidTokenSize"= 5,
"invalidTopicSize"= 6,
"invalidPayloadSize"= 7,
"invalidToken"= 8,
"apnsShutdown"= 10,
"none"= 255,
"retryLimitExceeded"= 512,
"moduleInitialisationFailed"= 513,
"connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted
"connectionTerminated"= 515
}
//Lowercase aliases
export {Connection as connection};
export {Device as device};
export {Errors as error};
export {Feedback as feedback};
export {Notification as notification};
}
+36 -4
View File
@@ -4,21 +4,25 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AutoCollectConsole {
constructor(client: Client): AutoCollectConsole;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
interface AutoCollectExceptions {
constructor(client:Client): AutoCollectExceptions;
isInitialized(): boolean;
enable(isEnabled:boolean): void;
}
interface AutoCollectPerformance {
constructor(client: Client): AutoCollectPerformance;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
interface AutoCollectRequests {
constructor(client: Client): AutoCollectRequests;
enable(isEnabled: boolean): void;
isInitialized(): boolean;
}
@@ -85,14 +89,17 @@ declare module ContractsModule {
sampleRate: string;
internalSdkVersion: string;
internalAgentVersion: string;
constructor(): ContextTagKeys;
}
interface Domain {
ver: number;
properties: any;
constructor(): Domain;
}
interface Data<TDomain extends ContractsModule.Domain> {
baseType: string;
baseData: TDomain;
constructor(): Data<TDomain>;
}
interface Envelope {
ver: number;
@@ -112,18 +119,21 @@ declare module ContractsModule {
[key: string]: string;
};
data: Data<Domain>;
constructor(): Envelope;
}
interface EventData extends ContractsModule.Domain {
ver: number;
name: string;
properties: any;
measurements: any;
constructor(): EventData;
}
interface MessageData extends ContractsModule.Domain {
ver: number;
message: string;
severityLevel: ContractsModule.SeverityLevel;
properties: any;
constructor(): MessageData;
}
interface ExceptionData extends ContractsModule.Domain {
ver: number;
@@ -134,6 +144,7 @@ declare module ContractsModule {
crashThreadId: number;
properties: any;
measurements: any;
constructor(): ExceptionData;
}
interface StackFrame {
level: number;
@@ -141,6 +152,7 @@ declare module ContractsModule {
assembly: string;
fileName: string;
line: number;
constructor(): StackFrame;
}
interface ExceptionDetails {
id: number;
@@ -150,6 +162,7 @@ declare module ContractsModule {
hasFullStack: boolean;
stack: string;
parsedStack: StackFrame[];
constructor(): ExceptionDetails;
}
interface DataPoint {
name: string;
@@ -159,11 +172,13 @@ declare module ContractsModule {
min: number;
max: number;
stdDev: number;
constructor(): DataPoint;
}
interface MetricData extends ContractsModule.Domain {
ver: number;
metrics: DataPoint[];
properties: any;
constructor(): MetricData;
}
interface PageViewData extends ContractsModule.EventData {
ver: number;
@@ -172,6 +187,7 @@ declare module ContractsModule {
duration: string;
properties: any;
measurements: any;
constructor(): PageViewData;
}
interface PageViewPerfData extends ContractsModule.PageViewData {
ver: number;
@@ -185,6 +201,7 @@ declare module ContractsModule {
domProcessing: string;
properties: any;
measurements: any;
constructor(): PageViewPerfData;
}
interface RemoteDependencyData extends ContractsModule.Domain {
ver: number;
@@ -202,6 +219,7 @@ declare module ContractsModule {
commandName: string;
dependencyTypeName: string;
properties: any;
constructor(): RemoteDependencyData;
}
interface AjaxCallData extends ContractsModule.PageViewData {
ver: number;
@@ -218,6 +236,7 @@ declare module ContractsModule {
success: boolean;
properties: any;
measurements: any;
constructor(): AjaxCallData;
}
interface RequestData extends ContractsModule.Domain {
ver: number;
@@ -231,10 +250,12 @@ declare module ContractsModule {
url: string;
properties: any;
measurements: any;
constructor(): RequestData;
}
interface SessionStateData extends ContractsModule.Domain {
ver: number;
state: ContractsModule.SessionState;
constructor(): SessionStateData;
}
interface PerformanceCounterData extends ContractsModule.Domain {
ver: number;
@@ -248,6 +269,7 @@ declare module ContractsModule {
stdDev: number;
value: number;
properties: any;
constructor(): PerformanceCounterData;
}
}
@@ -309,10 +331,14 @@ interface Client {
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
* telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
* @param name A string that identifies the metric.
* @param value The value of the metric
* @param name A string that identifies the metric.
* @param value The value of the metric
* @param count the number of samples used to get this value
* @param min the min sample for this set
* @param max the max sample for this set
* @param stdDev the standard deviation of the set
*/
trackMetric(name: string, value: number): void;
trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number): void;
trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: {
[key: string]: string;
}): void;
@@ -381,10 +407,16 @@ declare class ApplicationInsights {
private static _performance;
private static _requests;
private static _isStarted;
/**
* Initializes a client with the given instrumentation key, if this is not specified, the value will be
* read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY
* @returns {ApplicationInsights/Client} a new client
*/
static getClient(instrumentationKey?: string): Client;
/**
* Initializes the default client of the client and sets the default configuration
* @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be
* read from the environment variable APPINSIGHTS_INSTRUMENTATION_KEY
* read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY
* @returns {ApplicationInsights} this interface
*/
static setup(instrumentationKey?: string): typeof ApplicationInsights;
+121 -16
View File
@@ -5,8 +5,19 @@ var fs, path;
function callback() {}
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.select(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.parallel([
function () { },
@@ -25,6 +36,11 @@ async.map(data, asyncProcess, function (err, results) {
});
var openFiles = ['file1', 'file2'];
var openFilesObj = {
file1: "fileOne",
file2: "fileTwo"
}
var saveFile = function () { }
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
@@ -32,18 +48,34 @@ async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
async.eachLimit(documents, 20, requestApi, function (err) { });
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
// forEachOf* functions. May accept array or object.
function forEachOfIterator(item, key, forEachOfIteratorCallback) {
console.log("ForEach: item=" + item + ", key=" + key);
forEachOfIteratorCallback();
}
async.forEachOf(openFiles, forEachOfIterator, function (err) { });
async.forEachOf(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { });
var process;
async.reduce([1, 2, 3], 0, function (memo, item, callback) {
var numArray = [1, 2, 3];
function reducer(memo, item, callback) {
process.nextTick(function () {
callback(null, memo + item)
});
}, function (err, result) { });
}
async.reduce(numArray, 0, reducer, function (err, result) { });
async.inject(numArray, 0, reducer, function (err, result) { });
async.foldl(numArray, 0, reducer, function (err, result) { });
async.reduceRight(numArray, 0, reducer, function (err, result) { });
async.foldr(numArray, 0, reducer, function (err, result) { });
async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
fs.stat(file, function (err, stats) {
@@ -52,10 +84,18 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
}, function (err, results) { });
async.some(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.any(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.every(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.all(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
// Control Flow //
async.series([
function (callback) {
@@ -77,7 +117,6 @@ async.series<string>([
],
function (err, results) { });
async.series({
one: function (callback) {
setTimeout(function () {
@@ -173,21 +212,47 @@ async.parallel<number>({
}, 100);
},
},
function (err, results) { });
function (err, results) { });
var count = 0;
async.whilst(
function () { return count < 5; },
function (callback) {
count++;
setTimeout(callback, 1000);
async.parallelLimit({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
function (err) { }
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
2,
function (err, results) { }
);
function whileFn(callback) {
count++;
setTimeout(callback, 1000);
}
function whileTest() { return count < 5; }
var count = 0;
async.whilst(whileTest, whileFn, function (err) { });
async.until(whileTest, whileFn, function (err) { });
async.doWhilst(whileFn, whileTest, function (err) { });
async.doUntil(whileFn, whileTest, function (err) { });
async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) });
async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) });
async.forever(function (errBack) {
errBack(new Error("Not going on forever."));
},
function (error) {
console.log(error);
}
);
async.waterfall([
function (callback) {
callback(null, 'one', 'two');
@@ -279,6 +344,26 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for (var i = 0; i < tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({ name: 'foo' }, function (err) {
console.log('finished processing foo');
});
cargo.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
cargo.push({ name: 'baz' }, function (err) {
console.log('finished processing baz');
});
var filename = '';
async.auto({
get_data: function (callback) { },
@@ -291,6 +376,9 @@ async.auto({
email_link: ['write_file', <any>function (callback, results) { }]
});
async.retry(3, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { });
async.parallel([
function (callback) { },
@@ -336,3 +424,20 @@ var slow_fn = function (name, callback) {
};
var fn = async.memoize(slow_fn);
fn('some name', function () {});
async.unmemoize(fn);
async.ensureAsync(function () { });
async.constant(42);
async.asyncify(function () { });
async.log(function (name, callback) {
setTimeout(function () {
callback(null, 'hello ' + name);
}, 0);
}, "world"
);
async.dir(function (name, callback) {
setTimeout(function () {
callback(null, { hello: name });
}, 1000);
}, "world");
+162 -129
View File
@@ -1,132 +1,165 @@
// Type definitions for Async 0.9.2
// Project: https://github.com/caolan/async
// Type definitions for Async 1.4.2
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
// Common interface between Arrays and Array-like objects
interface List<T> {
[index: number]: T;
length: number;
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncFunction<T> { (callback: (err: Error, result?: T) => void): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
started: boolean;
running(): number;
idle(): boolean;
concurrency: number;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
paused: boolean;
pause(): void
resume(): void;
kill(): void;
}
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, index: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncFunction<T> { (callback: AsyncResultCallback<T>): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback: ErrorCallback): void;
forEachOf<T>(obj: List<T>, iterator: AsyncForEachOfIterator<T>, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: List<T>, iterator: AsyncForEachOfIterator<T>, callback: ErrorCallback): void;
forEachOfLimit<T>(obj: List<T>, limit: number, iterator: AsyncForEachOfIterator<T>, callback: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
detectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
any<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: AsyncResultArrayCallback<T>): any;
every<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
waterfall(tasks: Function[], callback?: (err: any, ...arguments: any[]) => void): void;
queue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
auto(tasks: any, callback?: AsyncResultArrayCallback<any>): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
times<R> (n: number, iterator: AsyncResultIterator<number, R>, callback: AsyncResultArrayCallback<R>): void;
timesSeries<R> (n: number, iterator: AsyncResultIterator<number, R>, callback: AsyncResultArrayCallback<R>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncCargo {
length(): number;
payload: number;
push(task: any, callback? : Function): void;
push(task: any[], callback? : Function): void;
saturated(): void;
empty(): void;
drain(): void;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEachOf(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOf<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfLimit<T>(obj: T[], limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncResultIterator<T, boolean>, callback?: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: AsyncFunction<T>[], callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void;
forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void;
waterfall(tasks: Function[], callback?: (err: Error, result: any) => void): void;
compose(...fns: Function[]): void;
seq(...fns: Function[]): void;
applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
setImmediate(callback: Function): void;
times<T> (n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesSeries<T>(n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesLimit<T>(n: number, limit: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
ensureAsync(fn: (... argsAndCallback: any[]) => void): Function;
constant(...values: any[]): Function;
asyncify(fn: Function): Function;
wrapSync(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="auto-launch.d.ts" />
import AutoLaunch = require('auto-launch');
var a1 = new AutoLaunch({
name: 'Foo',
});
var a2 = new AutoLaunch({
name: 'Foo',
path: '/Applications/Foo.app',
isHidden: true,
});
a1.enable();
a2.disable();
var enabled: boolean = a1.isEnabled();
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for auto-launch 0.1.18
// Project: https://github.com/Teamwork/node-auto-launch
// Definitions by: rhysd <https://github.com/rhysd>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AutoLaunchOption {
/**
* Application name.
*/
name: string;
/**
* Hidden on launch or not. Default is false.
*/
isHidden?: boolean;
/**
* Path to application directory.
* Default is process.execPath.
*/
path?: string;
}
declare class AutoLaunch {
constructor(opts: AutoLaunchOption);
/**
* Enables to launch at start up
*/
enable(callback?: (err: Error) => void): void;
/**
* Disables to launch at start up
*/
disable(callback?: (err: Error) => void): void;
/**
* Returns if auto start up is enabled
*/
isEnabled(callback?: (err: Error) => void): boolean;
}
declare module "auto-launch" {
var al: typeof AutoLaunch;
export = al;
}
+2 -1
View File
@@ -309,7 +309,8 @@ declare module Backbone {
interface ViewOptions<TModel extends Model> {
model?: TModel;
collection?: Backbone.Collection<TModel>;
// TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view.
collection?: Backbone.Collection<any>;
el?: any;
id?: string;
className?: string;
+7
View File
@@ -0,0 +1,7 @@
import Bowser = require('bowser');
Bowser.msedge === true;
Bowser.test(['msie']) === true;
Bowser.a === Bowser.c;
Bowser.osversion > 10;
Bowser.osversion === '10.1A';
+54
View File
@@ -0,0 +1,54 @@
// Type definitions for Bowser 1.x
// Project: https://github.com/ded/bowser
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'bowser' {
var def: BowserModule.IBowser;
export = def;
}
declare module BowserModule {
export interface IBowserUA {
msie: boolean;
chrome: boolean;
webkit: boolean;
phantom: boolean;
opera: boolean;
safari: boolean;
android: boolean;
ios: boolean;
webos: boolean;
msedge: boolean;
seamonkey: boolean;
firefox: boolean;
yandexbrowser: boolean;
blackberry: boolean;
tablet: boolean;
mobile: boolean;
silk: boolean;
bada: boolean;
tizen: boolean;
windowsphone: boolean;
firefoxos: boolean;
gecko: boolean;
sailfish: boolean;
chromeBook: boolean;
/** Grade A browser */
a: boolean;
/** Grade C browser */
c: boolean;
/** Grade X browser */
x: boolean;
name: string;
version: string;
osversion: string|number;
}
export interface IBowser extends IBowserUA {
test(browserList: string[]): boolean;
_detect(ua: string): IBowser;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="bunyan.d.ts" />
import bunyan = require('bunyan');
import * as bunyan from 'bunyan';
var ringBufferOptions:bunyan.RingBufferOptions = {
limit: 100
+3 -5
View File
@@ -6,9 +6,7 @@
/// <reference path="../node/node.d.ts" />
declare module "bunyan" {
import events = require('events');
import EventEmitter = events.EventEmitter;
import WritableStream = NodeJS.WritableStream;
import { EventEmitter } from 'events';
class Logger extends EventEmitter {
constructor(options:LoggerOptions);
@@ -52,7 +50,7 @@ declare module "bunyan" {
name: string;
streams?: Stream[];
level?: string | number;
stream?: WritableStream;
stream?: NodeJS.WritableStream;
serializers?: Serializers;
src?: boolean;
}
@@ -65,7 +63,7 @@ declare module "bunyan" {
type?: string;
level?: number | string;
path?: string;
stream?: WritableStream | Stream;
stream?: NodeJS.WritableStream | Stream;
closeOnExit?: boolean;
}
+45 -14
View File
@@ -1,23 +1,54 @@
/// <reference path="chai-as-promised.d.ts" />
/// <reference path="../promises-a-plus/promises-a-plus.d.ts" />
/// <reference path="../q/Q.d.ts" />
import chai = require('chai');
import chaiAsPromised = require('chai-as-promised');
import Q = require('q');
chai.use(chaiAsPromised);
// ReSharper disable WrongExpressionStatement
var promise: any;
chai.expect(promise).to.eventually.equal(3);
chai.expect(promise).to.become(3);
chai.expect(promise).to.be.fulfilled;
chai.expect(promise).to.be.rejected;
chai.expect(promise).to.be.rejectedWith(Error);
chai.expect(promise).to.notify(() => console.log('done'));
// BDD API (expect)
var thenableNum: PromisesAPlus.Thenable<number>;
thenableNum = chai.expect(thenableNum).to.eventually.equal(3);
thenableNum = chai.expect(thenableNum).to.eventually.have.property('foo');
thenableNum = chai.expect(thenableNum).to.become(3);
thenableNum = chai.expect(thenableNum).to.be.fulfilled;
thenableNum = chai.expect(thenableNum).to.be.rejected;
thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error);
thenableNum = chai.expect(thenableNum).to.notify(() => console.log('done'));
chai.assert.eventually.equal(promise, 4, 'Message');
chai.assert.isFulfilled(promise, "optional message");
chai.assert.becomes(promise, "foo", "optional message");
chai.assert.doesNotBecome(promise, "foo", "optional message");
chai.assert.isRejected(promise, "optional message");
chai.assert.isRejected(promise, Error, "optional message");
chai.assert.isRejected(promise, /error message matcher/, "optional message");
// BDD API (should)
thenableNum = thenableNum.should.be.fulfilled;
thenableNum = thenableNum.should.eventually.deep.equal(3);
thenableNum = thenableNum.should.become(3);
thenableNum = thenableNum.should.be.rejected;
thenableNum = thenableNum.should.be.rejectedWith(Error);
thenableNum = thenableNum.should.eventually.equal(3).notify(() => console.log('done'));
thenableNum = thenableNum.should.be.fulfilled.and.notify(() => console.log('done'));
// Complex examples on https://github.com/domenic/chai-as-promised#working-with-non-promisefriendly-test-runners
thenableNum.should.be.fulfilled.then(function () {
thenableNum.should.equal("after");
}).should.notify(() => console.log('done'));
Q.all([
thenableNum.should.become("happy"),
thenableNum.should.eventually.have.property("fun times"),
thenableNum.should.be.rejectedWith(TypeError, "only joyful types are allowed")
]).should.notify(() => console.log('done'));
// Assert API
var thenableVoid: PromisesAPlus.Thenable<void>;
thenableVoid = chai.assert.eventually.equal(thenableNum, 4, 'Message');
thenableVoid = chai.assert.isFulfilled(thenableNum, "optional message");
thenableVoid = chai.assert.becomes(thenableNum, "foo", "optional message");
thenableVoid = chai.assert.doesNotBecome(thenableNum, "foo", "optional message");
thenableVoid = chai.assert.isRejected(thenableNum, "optional message");
thenableVoid = chai.assert.isRejected(thenableNum, Error, "optional message");
thenableVoid = chai.assert.isRejected(thenableNum, /error message matcher/, "optional message");
// Check that original chai assertions are not broken
var undef: void;
undef = chai.assert.equal(10, 4, 'Message');
+264 -16
View File
@@ -1,9 +1,10 @@
// Type definitions for chai-as-promised
// Project: https://github.com/domenic/chai-as-promised/
// Definitions by: jt000 <https://github.com/jt000>
// Definitions by: jt000 <https://github.com/jt000>, Yuki Kokubun <https://github.com/Kuniwak>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../chai/chai.d.ts" />
/// <reference path="../promises-a-plus/promises-a-plus.d.ts" />
declare module 'chai-as-promised' {
function chaiAsPromised(chai: any, utils: any): void;
@@ -12,25 +13,272 @@ declare module 'chai-as-promised' {
declare module Chai {
interface Assertion {
become(expected: any): Assertion;
fulfilled: Assertion;
rejected: Assertion;
rejectedWith(expected: any): Assertion;
notify(fn: Function): Assertion;
// For BDD API
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
eventually: PromisedAssertion;
become(expected: any): PromisedAssertion;
fulfilled: PromisedAssertion;
rejected: PromisedAssertion;
rejectedWith(expected: any, message?: string): PromisedAssertion;
notify(fn: Function): PromisedAssertion;
}
interface LanguageChains {
eventually: Assertion;
// Eventually does not have .then(), but PromisedAssertion have.
interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison {
// From chai-as-promised
become(expected: PromisesAPlus.Thenable<any>): PromisedAssertion;
fulfilled: PromisedAssertion;
rejected: PromisedAssertion;
rejectedWith(expected: any): PromisedAssertion;
notify(fn: Function): PromisedAssertion;
// From chai
not: PromisedAssertion;
deep: PromisedDeep;
a: PromisedTypeComparison;
an: PromisedTypeComparison;
include: PromisedInclude;
contain: PromisedInclude;
ok: PromisedAssertion;
true: PromisedAssertion;
false: PromisedAssertion;
null: PromisedAssertion;
undefined: PromisedAssertion;
exist: PromisedAssertion;
empty: PromisedAssertion;
arguments: PromisedAssertion;
Arguments: PromisedAssertion;
equal: PromisedEqual;
equals: PromisedEqual;
eq: PromisedEqual;
eql: PromisedEqual;
eqls: PromisedEqual;
property: PromisedProperty;
ownProperty: PromisedOwnProperty;
haveOwnProperty: PromisedOwnProperty;
length: PromisedLength;
lengthOf: PromisedLength;
match(regexp: RegExp|string, message?: string): PromisedAssertion;
string(string: string, message?: string): PromisedAssertion;
keys: PromisedKeys;
key(string: string): PromisedAssertion;
throw: PromisedThrow;
throws: PromisedThrow;
Throw: PromisedThrow;
respondTo(method: string, message?: string): PromisedAssertion;
itself: PromisedAssertion;
satisfy(matcher: Function, message?: string): PromisedAssertion;
closeTo(expected: number, delta: number, message?: string): PromisedAssertion;
members: PromisedMembers;
}
interface PromisedAssertion extends Eventually, PromisesAPlus.Thenable<any> {
}
interface PromisedLanguageChains {
eventually: Eventually;
// From chai
to: PromisedAssertion;
be: PromisedAssertion;
been: PromisedAssertion;
is: PromisedAssertion;
that: PromisedAssertion;
which: PromisedAssertion;
and: PromisedAssertion;
has: PromisedAssertion;
have: PromisedAssertion;
with: PromisedAssertion;
at: PromisedAssertion;
of: PromisedAssertion;
same: PromisedAssertion;
}
interface PromisedNumericComparison {
above: PromisedNumberComparer;
gt: PromisedNumberComparer;
greaterThan: PromisedNumberComparer;
least: PromisedNumberComparer;
gte: PromisedNumberComparer;
below: PromisedNumberComparer;
lt: PromisedNumberComparer;
lessThan: PromisedNumberComparer;
most: PromisedNumberComparer;
lte: PromisedNumberComparer;
within(start: number, finish: number, message?: string): PromisedAssertion;
}
interface PromisedNumberComparer {
(value: number, message?: string): PromisedAssertion;
}
interface PromisedTypeComparison {
(type: string, message?: string): PromisedAssertion;
instanceof: PromisedInstanceOf;
instanceOf: PromisedInstanceOf;
}
interface PromisedInstanceOf {
(constructor: Object, message?: string): PromisedAssertion;
}
interface PromisedDeep {
equal: PromisedEqual;
include: PromisedInclude;
property: PromisedProperty;
}
interface PromisedEqual {
(value: any, message?: string): PromisedAssertion;
}
interface PromisedProperty {
(name: string, value?: any, message?: string): PromisedAssertion;
}
interface PromisedOwnProperty {
(name: string, message?: string): PromisedAssertion;
}
interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison {
(length: number, message?: string): PromisedAssertion;
}
interface PromisedInclude {
(value: Object, message?: string): PromisedAssertion;
(value: string, message?: string): PromisedAssertion;
(value: number, message?: string): PromisedAssertion;
keys: PromisedKeys;
members: PromisedMembers;
}
interface PromisedKeys {
(...keys: string[]): PromisedAssertion;
(keys: any[]): PromisedAssertion;
}
interface PromisedThrow {
(): PromisedAssertion;
(expected: string, message?: string): PromisedAssertion;
(expected: RegExp, message?: string): PromisedAssertion;
(constructor: Error, expected?: string, message?: string): PromisedAssertion;
(constructor: Error, expected?: RegExp, message?: string): PromisedAssertion;
(constructor: Function, expected?: string, message?: string): PromisedAssertion;
(constructor: Function, expected?: RegExp, message?: string): PromisedAssertion;
}
interface PromisedMembers {
(set: any[], message?: string): PromisedAssertion;
}
// For Assert API
interface Assert {
eventually: Assert;
isFulfilled(promise: any, message?: string): void;
becomes(promise: any, expected: any, message?: string): void;
doesNotBecome(promise: any, expected: any, message?: string): void;
isRejected(promise: any, message?: string): void;
isRejected(promise: any, expected: any, message?: string): void;
isRejected(promise: any, match: RegExp, message?: string): void;
eventually: PromisedAssert;
isFulfilled(promise: PromisesAPlus.Thenable<any>, message?: string): PromisesAPlus.Thenable<void>;
becomes(promise: PromisesAPlus.Thenable<any>, expected: any, message?: string): PromisesAPlus.Thenable<void>;
doesNotBecome(promise: PromisesAPlus.Thenable<any>, expected: any, message?: string): PromisesAPlus.Thenable<void>;
isRejected(promise: PromisesAPlus.Thenable<any>, message?: string): PromisesAPlus.Thenable<void>;
isRejected(promise: PromisesAPlus.Thenable<any>, expected: any, message?: string): PromisesAPlus.Thenable<void>;
isRejected(promise: PromisesAPlus.Thenable<any>, match: RegExp, message?: string): PromisesAPlus.Thenable<void>;
notify(fn: Function): PromisesAPlus.Thenable<void>;
}
export interface PromisedAssert {
fail(actual?: any, expected?: any, msg?: string, operator?: string): PromisesAPlus.Thenable<void>;
ok(val: any, msg?: string): PromisesAPlus.Thenable<void>;
notOk(val: any, msg?: string): PromisesAPlus.Thenable<void>;
equal(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
notEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
strictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
notStrictEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
deepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
notDeepEqual(act: any, exp: any, msg?: string): PromisesAPlus.Thenable<void>;
isTrue(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isFalse(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNull(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotNull(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isUndefined(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isDefined(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isFunction(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotFunction(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isObject(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotObject(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isArray(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotArray(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isString(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotString(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNumber(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotNumber(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isBoolean(val: any, msg?: string): PromisesAPlus.Thenable<void>;
isNotBoolean(val: any, msg?: string): PromisesAPlus.Thenable<void>;
typeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable<void>;
notTypeOf(val: any, type: string, msg?: string): PromisesAPlus.Thenable<void>;
instanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable<void>;
notInstanceOf(val: any, type: Function, msg?: string): PromisesAPlus.Thenable<void>;
include(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable<void>;
include(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable<void>;
notInclude(exp: string, inc: any, msg?: string): PromisesAPlus.Thenable<void>;
notInclude(exp: any[], inc: any, msg?: string): PromisesAPlus.Thenable<void>;
match(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable<void>;
notMatch(exp: any, re: RegExp, msg?: string): PromisesAPlus.Thenable<void>;
property(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable<void>;
notProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable<void>;
deepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable<void>;
notDeepProperty(obj: Object, prop: string, msg?: string): PromisesAPlus.Thenable<void>;
propertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable<void>;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable<void>;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable<void>;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): PromisesAPlus.Thenable<void>;
lengthOf(exp: any, len: number, msg?: string): PromisesAPlus.Thenable<void>;
//alias frenzy
throw(fn: Function, msg?: string): PromisesAPlus.Thenable<void>;
throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable<void>;
throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
throws(fn: Function, msg?: string): PromisesAPlus.Thenable<void>;
throws(fn: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
throws(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable<void>;
throws(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
Throw(fn: Function, msg?: string): PromisesAPlus.Thenable<void>;
Throw(fn: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
Throw(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable<void>;
Throw(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
doesNotThrow(fn: Function, msg?: string): PromisesAPlus.Thenable<void>;
doesNotThrow(fn: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
doesNotThrow(fn: Function, errType: Function, msg?: string): PromisesAPlus.Thenable<void>;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): PromisesAPlus.Thenable<void>;
operator(val: any, operator: string, val2: any, msg?: string): PromisesAPlus.Thenable<void>;
closeTo(act: number, exp: number, delta: number, msg?: string): PromisesAPlus.Thenable<void>;
sameMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable<void>;
includeMembers(set1: any[], set2: any[], msg?: string): PromisesAPlus.Thenable<void>;
ifError(val: any, msg?: string): PromisesAPlus.Thenable<void>;
}
}
+4 -2
View File
@@ -102,12 +102,14 @@ $('ul').insert("<li>1</li><li>2</li><li>3</li>", 3);
$('ul').insert("<li>1</li><li>2</li><li>3</li>");
$('ul').html('<li>1</li><li><2/li><li>3</li>');
$('ul').html('');
var listContent = $('ul').html();
$('ul').prepend('<li class="title">The title</li>');
$('ul').append('<li>The Last Item</li>');
var inputName = $('input').attr('name');
$('input').attr('name', 'wobba');
var inputName = $('input').prop('name');
$('input').prop('name', 'wobba');
var inputProperty = $('input').prop('disabled');
$('input[type=checked]').prop('checked', true);
$('input').removeProp('disabled');
$('input').hasAttr('disabled').css('border', 'solid 1px red');
$('input').removeAttr('disabled');
$('article').hasClass('current').css('display', 'block');
+16 -9
View File
@@ -1,4 +1,4 @@
// Type definitions for chocolatechip v4.0.2
// Type definitions for chocolatechip v4.0.3
// Project: https://github.com/chocolatechipui/ChocolateChipJS
// Definitions by: Robert Biggs <http://chocolatechip-ui.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -176,7 +176,8 @@ interface ChocolateChipStatic {
* @param response The response from a Promise.
* @result
*/
json(reponse: Response): JSON;
json(reponse: Response): JSON;
/**
* This method will defer the execution of a function until the call stack is clear.
*
@@ -198,7 +199,7 @@ interface ChocolateChipStatic {
* This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception.
*
* @param result The result of a method to test if it can be returned in an array.
* @return An array hold the results of a method, otherwise an empty array.
* @return An array holding the results of a method, otherwise an empty array.
*/
returnResult(result: HTMLElement[]): any[];
@@ -836,12 +837,12 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
hasAttr(attributeName: string): ChocolateChipElementArray;
/**
* Get the value of an attribute for the first element in the set of matched elements.
* Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean.
*
* @param attributeName The name of the attribute to get.
* @return string
* @return boolean
*/
prop(attributeName: string): string;
prop(propertyName: string): boolean;
/**
* Set an property for the set of matched elements.
@@ -850,7 +851,15 @@ interface ChocolateChipElementArray extends Array<HTMLElement> {
* @param value A string indicating the value to set the property to.
* @return HTMLElement[]
*/
prop(propertyName: string, value: string): ChocolateChipElementArray;
prop(propertyName: string, value: any | boolean): ChocolateChipElementArray;
/**
* Remove an element property.
*
* @param property The property to remove.
* @return HTMLElement[]
*/
removeProp(property: string): ChocolateChipElementArray;
/**
* Adds the specified class(es) to each of the set of matched elements.
@@ -1471,5 +1480,3 @@ interface Window {
}
declare var $: ChocolateChipStatic;
declare var fetch: fetch;
declare var chocolatechipjs: ChocolateChipStatic;
+1 -1
View File
@@ -787,7 +787,7 @@ declare module CodeMirror {
viewportMargin?: number;
/** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */
lint?: LintOptions;
lint?: boolean | LintOptions;
}
interface TextMarkerOptions {
+6 -2
View File
@@ -176,8 +176,12 @@ file.download('http://some.server.com/download.php',
console.error('Failed with exception ' + err.exception);
}
},
{ headers: null },
true);
true,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
});
file.upload('cdvfile://localhost/persistent/path/to/downloads/',
'http://some.server.com/download.php',
+2
View File
@@ -24,6 +24,8 @@ interface Device {
uuid: string;
/** Get the operating system version. */
version: string;
/** Get the device's manufacturer. */
manufacturer: string;
}
declare var device: Device;
+4 -4
View File
@@ -53,8 +53,8 @@ interface FileTransfer {
target: string,
successCallback: (fileEntry: FileEntry) => void,
errorCallback: (error: FileTransferError) => void,
options?: FileDownloadOptions,
trustAllHosts?: boolean): void;
trustAllHosts?: boolean,
options?: FileDownloadOptions): void;
/**
* Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object
* which has an error code of FileTransferError.ABORT_ERR.
@@ -98,8 +98,8 @@ interface FileUploadOptions {
/** Optional parameters for download method. */
interface FileDownloadOptions {
/** A map of header name/header values. Use an array to specify more than one value. */
headers?: Object[];
/** A map of header name/header values. */
headers?: {};
}
/** A FileTransferError object is passed to an error callback when an error occurs. */
File diff suppressed because it is too large Load Diff
+76 -15
View File
@@ -1,4 +1,4 @@
// Type definitions for DevExtreme 15.1.5
// Type definitions for DevExtreme 15.1.6
// Project: http://js.devexpress.com/
// Definitions by: DevExpress Inc. <http://devexpress.com/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -63,7 +63,7 @@ declare module DevExpress {
export function processHardwareBackButton(): void;
/** Specifies whether or not the entire application/site supports right-to-left representation. */
export var rtlEnabled: boolean;
/** Registers a new component in the DevExpress.ui namespace, and a jQuery plugin and Knockout binding for the required component. */
/** Registers a new component in the DevExpress.ui namespace as a jQuery plugin, Angular directive and Knockout binding. */
export function registerComponent(name: string, componentClass: Object): void;
/** Registers a new component in the specified namespace as a jQuery plugin, Angular directive and Knockout binding. */
export function registerComponent(name: string, namespace: Object, componentClass: Object): void;
@@ -323,7 +323,7 @@ declare module DevExpress {
key(): any;
/** Returns the key of the Store item that matches the specified object. */
keyOf(obj: Object): any;
/** Starts loading the data. */
/** Starts loading data. */
load(obj?: LoadOptions): JQueryPromise<any[]>;
/** Removes the data item specified by the key. */
remove(key: any): JQueryPromise<any>;
@@ -427,6 +427,8 @@ declare module DevExpress {
select?: Object;
/** An array of the strings that represent the names of the navigation properties to be loaded simultaneously with the OData store's entity. */
expand?: Object;
/** Specifies whether or not the DataSource instance requests the total count of items available in the storage. */
requireTotalCount?: boolean;
/** Specifies the initial sort option value. */
sort?: Object;
/** Specifies the underlying Store instance used to access data. */
@@ -496,6 +498,10 @@ declare module DevExpress {
select(): Object;
/** Sets the select option value. */
select(expr: Object): void;
/** Returns the current requireTotalCount option value. */
requireTotalCount(): boolean;
/** Sets the requireTotalCount option value. */
requireTotalCount(value: boolean): void;
/** Returns the current sort option value. */
sort(): Object;
/** Sets the sort option value. */
@@ -817,11 +823,26 @@ declare module DevExpress {
export function setTemplateEngine(name: string): void;
/** Sets a custom template engine defined via custom compile and render functions. */
export function setTemplateEngine(options: Object): void;
/** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */
export var utils: {
/** Sets parameters for the viewport meta tag. */
initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void;
};
}
/** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */
export var utils: {
/** Sets parameters for the viewport meta tag. */
initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void;
};
/** An object that serves as a namespace for DevExtreme Data Visualization Widgets. */
export module viz {
/** Applies a theme for the entire page with several DevExtreme visualization widgets. */
export function currentTheme(theme: string): void;
/** Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. */
export function currentTheme(platform: string, colorScheme: string): void;
/** Registers a new theme based on the existing one. */
export function registerTheme(customTheme: Object, baseTheme: string): void;
/** Applies a predefined or registered custom palette to all visualization widgets at once. */
export function currentPalette(paletteName: string): void;
/** Obtains the color sets of a predefined or registered palette. */
export function getPalette(paletteName: string): Object;
/** Registers a new palette. */
export function registerPalette(paletteName: string, palette: Object): void;
}
}
declare module DevExpress.ui {
@@ -894,7 +915,7 @@ declare module DevExpress.ui {
constructor(element: JQuery, options?: dxTooltipOptions);
constructor(element: Element, options?: dxTooltipOptions);
}
export interface dxDropDownListOptions extends dxDropDownEditorOptions {
export interface dxDropDownListOptions extends dxDropDownEditorOptions, DataExpressionMixinOptions {
/** Returns the value currently displayed by the widget. */
displayValue?: string;
/** The minimum number of characters that must be entered into the text box to begin a search. */
@@ -1191,7 +1212,7 @@ declare module DevExpress.ui {
/** Updates the dimensions of the scrollable contents. */
update(): void;
}
export interface dxRadioGroupOptions extends CollectionWidgetOptions {
export interface dxRadioGroupOptions extends CollectionWidgetOptions, DataExpressionMixinOptions {
/** Specifies the radio group layout. */
layout?: string;
}
@@ -1747,9 +1768,9 @@ declare module DevExpress.ui {
/** A Globalize format string specifying the date display format. */
formatString?: string;
/** The last date that can be selected within the widget. */
max?: Date;
max?: any;
/** The minimum date that can be selected within the widget. */
min?: Date;
min?: any;
/** The text displayed by the widget when the widget value is not yet specified. This text is also used as a title of the date picker. */
placeholder?: string;
/**
@@ -1757,8 +1778,8 @@ declare module DevExpress.ui {
* @deprecated Use 'pickerType' option instead.
*/
useCalendar?: boolean;
/** A Date object specifying the date and time currently selected using the date box. */
value?: Date;
/** An object or a value, specifying the date and time currently selected using the date box. */
value?: any;
/**
* Specifies whether or not the widget uses the native HTML input element.
* @deprecated Use 'pickerType' option instead.
@@ -2661,6 +2682,8 @@ declare module DevExpress.ui {
updateAppointment(target: Object, appointment: Object): void;
/** Deletes the appointment defined by the parameter from the the data associated with the widget. */
deleteAppointment(appointment: Object): void;
/** Scrolls the scheduler work space to the specified time. */
scrollToTime(hours: number, minutes: number): void;
}
export interface dxColorBoxOptions extends dxDropDownEditorOptions {
/** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */
@@ -2735,6 +2758,10 @@ declare module DevExpress.ui {
onItemExpanded?: Function;
/** A handler for the itemCollapsed event. */
onItemCollapsed?: Function;
onItemClick?: Function;
onItemContextMenu?: Function;
onItemRendered?: Function;
onItemHold?: Function;
hoverStateEnabled?: boolean;
focusStateEnabled?: boolean;
}
@@ -3795,6 +3822,8 @@ declare module DevExpress.framework {
onExecute?: any;
/** Indicates whether or not the widget that displays this command is disabled. */
disabled?: boolean;
/** Specifies whether the current command should is rendered when a view is being rendered, or after a view has been shown. */
renderStage?: string;
/** Specifies the name of the icon shown inside the widget associated with this command. */
icon?: string;
iconSrc?: string;
@@ -4042,6 +4071,36 @@ declare module DevExpress.framework {
}
}
declare module DevExpress.viz.core {
/**
* Applies a theme for the entire page with several DevExtreme visualization widgets.
* @deprecated Use the DevExpress.viz.currentTheme(theme) method instead.
*/
export function currentTheme(theme: string): void;
/**
* Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets.
* @deprecated Use the DevExpress.viz.currentTheme(platform, colorScheme) method instead.
*/
export function currentTheme(platform: string, colorScheme: string): void;
/**
* Registers a new theme based on the existing one.
* @deprecated Use the DevExpress.viz.registerTheme(customTheme, baseTheme) method instead.
*/
export function registerTheme(customTheme: Object, baseTheme: string): void;
/**
* Applies a predefined or registered custom palette to all visualization widgets at once.
* @deprecated Use the DevExpress.viz.currentPalette(paletteName) method instead.
*/
export function currentPalette(paletteName: string): void;
/**
* Obtains the color sets of a predefined or registered palette.
* @deprecated Use the DevExpress.viz.getPalette(paletteName) method instead.
*/
export function getPalette(paletteName: string): Object;
/**
* Registers a new palette.
* @deprecated Use the DevExpress.viz.registerPalette(paletteName, palette) method instead.
*/
export function registerPalette(paletteName: string, palette: Object): void;
export interface Border {
/** Sets a border color for a selected series. */
color?: string;
@@ -5270,7 +5329,7 @@ declare module DevExpress.viz.charts {
position?: string;
}
export interface ChartTooltip extends BaseChartTooltip {
/** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies only to the Bar series. */
/** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies to the Bar and Bubble series. */
location?: string;
/** Specifies the kind of information to display in a tooltip. */
shared?: boolean;
@@ -5860,6 +5919,8 @@ Indicates whether or not animation is enabled.
};
/** Specifies a value indicating whether all bars in a series must have the same width, or may have different widths if any points in other series are missing. */
equalBarWidth?: any;
/** Sets the name of the palette to be used in the range selector's chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */
palette?: any;
/** An object defining the charts series. */
series?: Array<viz.charts.SeriesConfig>;
/** Defines options for the series template. */
+19 -19
View File
@@ -33,7 +33,7 @@ interface DropzoneOptions {
resize?: ( file?: any ) => any;
init?: () => void;
acceptedFiles?: string;
accept?: ( file: DropzoneFile, doneCallback: ( ...args ) => void ) => void;
accept?: ( file: DropzoneFile, doneCallback: ( ...args: any[] ) => void ) => void;
autoProcessQueue?: boolean;
previewTemplate?: string;
forceFallback?: boolean;
@@ -67,9 +67,9 @@ declare class Dropzone {
disable(): void;
destroy(): Dropzone;
on( eventName, callback: ( ...args ) => any );
on( eventName: string, callback: ( ...args: any[] ) => any ): void;
off( eventName ): void;
off( eventName: string ): void;
addFile( file: DropzoneFile ): void;
@@ -99,24 +99,24 @@ declare class Dropzone {
getFilesWithStatus( status: string ): DropzoneFile[];
enqueueFile( file: DropzoneFile ): void;
enqueueFiles( file: DropzoneFile[] ): void;
createThumbnail( file: DropzoneFile, callback?: (...any) => {}): any;
createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any ) => any ): any;
createThumbnail( file: DropzoneFile, callback?: (...any: any[]) => {}): any;
createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any: any[] ) => any ): any;
emit( eventName: string, file: DropzoneFile, str?: string );
emit( eventName: "thumbnail", file: DropzoneFile, path: string );
emit( eventName: "addedfile", file: DropzoneFile );
emit( eventName: "removedfile", file: DropzoneFile );
emit( eventName: "processing", file: DropzoneFile );
emit( eventName: "canceled", file: DropzoneFile );
emit( eventName: "complete", file: DropzoneFile );
emit( eventName: string, file: DropzoneFile, str?: string ): void;
emit( eventName: "thumbnail", file: DropzoneFile, path: string ): void;
emit( eventName: "addedfile", file: DropzoneFile ): void;
emit( eventName: "removedfile", file: DropzoneFile ): void;
emit( eventName: "processing", file: DropzoneFile ): void;
emit( eventName: "canceled", file: DropzoneFile ): void;
emit( eventName: "complete", file: DropzoneFile ): void;
emit( eventName: string, e: Event );
emit( eventName: "drop", e: Event );
emit( eventName: "dragstart", e: Event );
emit( eventName: "dragend", e: Event );
emit( eventName: "dragenter", e: Event );
emit( eventName: "dragover", e: Event );
emit( eventName: "dragleave", e: Event );
emit( eventName: string, e: Event ): void;
emit( eventName: "drop", e: Event ): void;
emit( eventName: "dragstart", e: Event ): void;
emit( eventName: "dragend", e: Event ): void;
emit( eventName: "dragenter", e: Event ): void;
emit( eventName: "dragover", e: Event ): void;
emit( eventName: "dragleave", e: Event ): void;
}
interface JQuery {
+43
View File
@@ -0,0 +1,43 @@
/**
* Created by karl on 14/07/15.
*/
/// <reference path="../express/express.d.ts" />
/// <reference path="../easy-xapi/easy-xapi.d.ts" />
/// <reference path="./easy-xapi-utils.d.ts" />
import express = require('express');
import eXapi = require('easy-xapi');
import eUtils = require('easy-xapi-utils');
eXapi.init({
jSend: {
partial: true
}
});
var xApi = eXapi.create({
root: __dirname,
log: {
name: 'Log',
level: 'info'
},
port: 3000,
name: 'test',
mount: function (app) {
app.get('/', eUtils.isLoggedIn(), function (req, res) {
res.send('ok');
});
app.get('/role', eUtils.isLoggedIn('admin'), function (req, res) {
res.send('ok');
});
app.get('/', eUtils.isLoggedOut(), function (req, res) {
res.send('ok');
});
app.get('/role', eUtils.hasRole('guest'), function (req, res) {
res.send('ok');
});
}
});
xApi.listen();
+16
View File
@@ -0,0 +1,16 @@
// Type definitions for easy-xapi-utils
// Project: https://github.com/DeadAlready/easy-xapi-utils
// Definitions by: Karl Düüna <https://github.com/DeadAlready/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
/// <reference path="../easy-jsend/easy-jsend.d.ts" />
/// <reference path="../easy-x-headers/easy-x-headers.d.ts" />
declare module "easy-xapi-utils" {
import express = require('express');
export function isLoggedIn(role?: string): express.RequestHandler;
export function isLoggedOut(): express.RequestHandler;
export function hasRole(role: string): express.RequestHandler;
}
+21
View File
@@ -0,0 +1,21 @@
/// <reference path="envify.d.ts" />
/// <reference path="../browserify/browserify.d.ts" />
import browserify = require('browserify');
import envify = require('envify/custom');
import fs = require('fs');
var b = browserify('main.js')
, output = fs.createWriteStream('bundle.js');
b.transform(envify({
NODE_ENV: 'development'
}));
b.bundle().pipe(output);
b.transform(envify({
_: 'purge'
, NODE_ENV: 'development'
}));
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for envify
// Project: https://github.com/hughsk/envify
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "envify" {
var envify: Function;
export = envify;
}
declare module "envify/custom" {
function envify(environment: { [name: string]: any }): Function;
export = envify;
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./express-less.d.ts" />
import express = require('express');
import expressLess = require('express-less');
var app = express();
var lessOptions: expressLess.Options = {};
lessOptions.compress = true;
lessOptions.debug = true;
app.use('/less-css', expressLess(__dirname));
app.use('/less-css-with-options', expressLess(__dirname + "/less", lessOptions));
+21
View File
@@ -0,0 +1,21 @@
// Type definitions for express-less
// Project: https://www.npmjs.com/package/express-less
// Definitions by: xyb <https://github.com/xieyubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-less" {
import express = require('express');
function less(root: string, options?: less.Options): express.RequestHandler;
module less {
export interface Options {
debug?: boolean;
compress?: boolean;
}
}
export = less;
}
+19 -19
View File
@@ -34,8 +34,8 @@ function sample1() {
function sample2() {
var dot, i,
t1, t2,
var dot: fabric.ICircle, i: number,
t1: number, t2: number,
startTimer = function() {
t1 = new Date().getTime();
return t1;
@@ -89,16 +89,16 @@ function sample2() {
function sample3() {
var $ = function(id) { return document.getElementById(id) };
var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id) };
function applyFilter(index, filter) {
var obj = <fabric.IImage>canvas.getActiveObject();
function applyFilter(index: number, filter: any) {
var obj: fabric.IImage = <fabric.IImage>canvas.getActiveObject();
obj.filters[index] = filter;
obj.applyFilters(canvas.renderAll.bind(canvas));
}
function applyFilterValue(index, prop, value) {
var obj = <fabric.IImage>canvas.getActiveObject();
function applyFilterValue(index: number, prop: string, value: any) {
var obj: fabric.IImage = <fabric.IImage>canvas.getActiveObject();
if (obj.filters[index]) {
obj.filters[index][prop] = value;
obj.applyFilters(canvas.renderAll.bind(canvas));
@@ -214,7 +214,7 @@ function sample3() {
function sample4() {
var canvas = new fabric.Canvas('c');
var $ = function(id) { return document.getElementById(id); };
var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id); };
var rect = new fabric.Rect({
width: 100,
@@ -339,10 +339,10 @@ function sample6() {
canvas.centerObject(obj);
canvas.add(obj);
canvas.add(obj.clone(() => {}).set({ left: 100, top: 100, angle: -15 }));
canvas.add(obj.clone(() => {}).set({ left: 480, top: 100, angle: 15 }));
canvas.add(obj.clone(() => {}).set({ left: 100, top: 400, angle: -15 }));
canvas.add(obj.clone(() => {}).set({ left: 480, top: 400, angle: 15 }));
canvas.add(obj.clone(() => { }).set({ left: 100, top: 100, angle: -15 }));
canvas.add(obj.clone(() => { }).set({ left: 480, top: 100, angle: 15 }));
canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 }));
canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 }));
canvas.on('mouse:move', function(options) {
var p = canvas.getPointer(options.e);
@@ -456,7 +456,7 @@ function sample8() {
top = fabric.util.getRandomInt(0 + offset, 500 - offset),
angle = fabric.util.getRandomInt(-20, 40),
width = fabric.util.getRandomInt(30, 50),
opacity = (function(min, max) { return Math.random() * (max - min) + min; })(0.5, 1);
opacity = (function(min: number, max: number) { return Math.random() * (max - min) + min; })(0.5, 1);
switch (className) {
@@ -522,7 +522,7 @@ function sample8() {
break;
case 'shape':
var id = element.id, match;
var id: any = element.id, match: RegExpExecArray;
if (match = /\d+$/.exec(id)) {
fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) {
var loadedObject = fabric.util.groupSVGElements(objects, options);
@@ -586,7 +586,7 @@ function sample8() {
}
};
var supportsInputOfType = function(type) {
var supportsInputOfType = function(type: string) {
return function() {
var el = <HTMLInputElement>document.createElement('input');
try {
@@ -746,7 +746,7 @@ function sample8() {
canvas.on('object:selected', onObjectSelected);
canvas.on('group:selected', onObjectSelected);
function onObjectSelected(e) {
function onObjectSelected(e: fabric.IEvent) {
var selectedObject = e.target;
for (var i = activeObjectButtons.length; i--;) {
@@ -1033,7 +1033,7 @@ function sample8() {
};
canvas.on('object:selected', function(e: fabric.IEvent) {
slider.value = String((<fabric.IText>e.target).lineHeight );
slider.value = String((<fabric.IText>e.target).lineHeight);
});
})();
}
@@ -1050,6 +1050,6 @@ function sample8() {
function sample9() {
var canvas = new fabric.Canvas('c');
canvas.setBackgroundImage('yolo.jpg',() => { "a" }, { opacity: 45 });
canvas.setBackgroundImage('yolo.jpg',() => { "a" });
canvas.setBackgroundImage('yolo.jpg', () => { "a" }, { opacity: 45 });
canvas.setBackgroundImage('yolo.jpg', () => { "a" });
}
+24 -24
View File
@@ -1,6 +1,6 @@
// Type definitions for FabricJS v1.5.0
// Project: http://fabricjs.com/
// Definitions by: Oliver Klemencic <https://github.com/oklemencic/>, Joseph Livecchi <https://github.com/joewashear007/>
// Definitions by: Oliver Klemencic <https://github.com/oklemencic/>, Joseph Livecchi <https://github.com/joewashear007/>, Michael Randolph <https://github.com/mrand01/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/* tslint:disable:no-unused-variable */
@@ -41,7 +41,7 @@ declare module fabric {
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function);
function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void;
/**
* Takes url corresponding to an SVG document, and parses it into a set of fabric objects.
* Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy)
@@ -49,14 +49,14 @@ declare module fabric {
* @param {Function} callback
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function);
function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void;
/**
* Returns CSS rules for a given SVG document
* @param {SVGDocument} doc SVG document to parse
*/
function getCSSRules(doc: SVGElement): any;
function parseElements(elements: any[], callback: Function, options: any, reviver?: Function);
function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void;
/**
* Parses "points" attribute, returning an array of values
* @param {String} points points attribute string
@@ -99,7 +99,7 @@ declare module fabric {
* @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document).
* @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created.
*/
function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function);
function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function): void;
/**
* Parses "transform" attribute, returning an array of values
* @param {String} attributeValue String containing attribute value
@@ -111,11 +111,11 @@ declare module fabric {
/**
* Wrapper around `console.log` (when available)
*/
function log(...values: any[]);
function log(...values: any[]): void;
/**
* Wrapper around `console.warn` (when available)
*/
function warn(...values: any[]);
function warn(...values: any[]): void;
////////////////////////////////////////////////////
// Classes
@@ -438,7 +438,7 @@ declare module fabric {
/**
* Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1])
*/
setSource(source: number[]);
setSource(source: number[]): void;
/**
* Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255)
@@ -474,7 +474,7 @@ declare module fabric {
* Sets value of alpha channel for this color
* @param {Number} alpha Alpha value 0-1
*/
setAlpha(alpha: number);
setAlpha(alpha: number): void;
/**
* Transforms color to its grayscale representation
@@ -627,17 +627,17 @@ declare module fabric {
/**
* Appends a point to intersection
*/
appendPoint(point: IPoint);
appendPoint(point: IPoint): void;
/**
* Appends points to intersection
*/
appendPoints(points: IPoint[]);
appendPoints(points: IPoint[]): void;
}
interface IIntersectionStatic {
/**
* Intersection class
*/
new (status?: string);
new (status?: string): void;
/**
* Checks if polygon intersects another polygon
*/
@@ -1313,7 +1313,7 @@ declare module fabric {
/**
* Callback; invoked right before object is about to be scaled/rotated
*/
onBeforeScaleRotate(target: IObject);
onBeforeScaleRotate(target: IObject): void;
// Functions from object straighten mixin
// --------------------------------------------------------------------------------------------------------------------------------
@@ -1839,12 +1839,12 @@ declare module fabric {
filters: IBaseFilter[];
}
interface IImage extends IObject, IImageOptions {
initialize(element?: string|HTMLImageElement, options?: IImageOptions);
initialize(element?: string|HTMLImageElement, options?: IImageOptions): void;
/**
* Applies filters assigned to this image (from "filters" array)
* @param {Function} callback Callback is invoked when all filters have been applied and new image is generated
*/
applyFilters(callback: Function);
applyFilters(callback: Function): void;
/**
* Returns a clone of an instance
* @param {Function} callback Callback is invoked with a clone as a first argument
@@ -1871,7 +1871,7 @@ declare module fabric {
* @return {String} Source of an image
*/
getSrc(): string;
render(ctx: CanvasRenderingContext2D, noTransform: boolean);
render(ctx: CanvasRenderingContext2D, noTransform: boolean): void;
/**
* Sets image element for this instance to a specified one.
@@ -2539,7 +2539,7 @@ declare module fabric {
* Sets object's properties from options
* @param {Object} [options] Options object
*/
setOptions(options: any);
setOptions(options: any): void;
/**
* Sets sourcePath of an object
* @param {String} value Value to set sourcePath to
@@ -2850,7 +2850,7 @@ declare module fabric {
}
interface IPathGroup extends IObject {
initialize(paths: IPath[], options?: IObjectOptions);
initialize(paths: IPath[], options?: IObjectOptions): void;
/**
* Returns number representation of object's complexity
* @return {Number} complexity
@@ -2865,7 +2865,7 @@ declare module fabric {
* Renders this group on a specified context
* @param {CanvasRenderingContext2D} ctx Context to render this instance on
*/
render(ctx: CanvasRenderingContext2D);
render(ctx: CanvasRenderingContext2D): void;
/**
* Returns dataless object representation of this path group
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
@@ -2993,7 +2993,7 @@ declare module fabric {
minY?: number;
}
interface IPolyline extends IObject, IPolylineOptions {
initialize(points: IPoint[], options?: IPolylineOptions);
initialize(points: IPoint[], options?: IPolylineOptions): void;
/**
* Returns complexity of an instance
* @return {Number} complexity of this instance
@@ -3158,7 +3158,7 @@ declare module fabric {
* Renders text instance on a specified context
* @param {CanvasRenderingContext2D} ctx Context to render on
*/
render(ctx: CanvasRenderingContext2D, noTransform: boolean);
render(ctx: CanvasRenderingContext2D, noTransform: boolean): void;
/**
* Returns object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
@@ -3347,7 +3347,7 @@ declare module fabric {
* Returns true if object has no styling
*/
isEmptyStyles(): boolean;
render(ctx: CanvasRenderingContext2D, noTransform: boolean);
render(ctx: CanvasRenderingContext2D, noTransform: boolean): void;
/**
* Returns object representation of an instance
* @method toObject
@@ -4360,13 +4360,13 @@ declare module fabric {
* @param {Object} [properties] Properties shared by all instances of this class
* (be careful modifying objects defined here as this would affect all instances)
*/
createClass(parent: Function, properties?: any);
createClass(parent: Function, properties?: any): void;
/**
* Helper for creation of "classes".
* @param {Object} [properties] Properties shared by all instances of this class
* (be careful modifying objects defined here as this would affect all instances)
*/
createClass(properties?: any);
createClass(properties?: any): void;
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="fs-ext.d.ts" />
/// <reference path="../node/node.d.ts" />
import fs = require('fs-ext');
var num:number;
var str:string;
//from node.js 'fs' module
fs.appendFileSync(str, "data");
fs.flock(num, str, (err)=>{
});
fs.flockSync(num, str);
fs.fcntl(num, str, num, (err, res)=>{
});
fs.fcntl(num, str, (err, res)=>{
});
fs.fcntlSync(num, str, num);
fs.seek(num, num, num, (err, pos)=>{
});
fs.seekSync(num, num, num);
fs.utime(str, num, num, (err)=>{
});
fs.utimeSync(str, num, num);
+102
View File
@@ -0,0 +1,102 @@
// Type definitions for fs-ext
// Project: https://github.com/baudehlo/node-fs-ext
// Definitions by: Oguzhan Ergin <https://github.com/OguzhanE>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../node/node.d.ts"/>
declare module "fs-ext" {
export * from "fs";
/**
* Asynchronous flock(2). No arguments other than a possible error are passed to the callback.
* @param fd File Descriptor
* @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc.
**/
export function flock(fd: number, flags: string, callback: (err: Error) => void): void;
/**
* Synchronous flock(2). Throws an exception on error.
* @param fd File Descriptor
* @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc.
**/
export function flockSync(fd: number, flags: string):void;
/**
* Asynchronous fcntl(2).
* @param fd File Descriptor
* @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD )
* Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD.
* @param arg arg
**/
export function fcntl(fd: number, cmd: string, arg: number, callback: (err: Error, result: number) => void):void;
/**
* Asynchronous fcntl(2).
* @param fd File Descriptor
* @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD )
* Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD.
**/
export function fcntl(fd: number, cmd: string, callback: (err: Error, result: number) => void):void;
/**
* Synchronous fcntl(2). Throws an exception on error.
* @param fd File Descriptor
* @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD )
* Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD.
* @param arg arg
* @return Returns flags
**/
export function fcntlSync(fd: number, cmd: string, arg?: number): number;
/**
* Asynchronous lseek(2).
* @param fd File Descriptor
* @param offset Offset
* @param whence
* Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new
* position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end
* of the file plus offset bytes (usually negative or zero to seek to the end of the file).
**/
export function seek(fd: number, offset: number, whence: number, callback: (err: Error, currFilePos: number) => void): void;
/**
* Synchronous lseek(2). Throws an exception on error. Returns current file position.
* @param fd File Descriptor
* @param offset Offset
* @param whence
* Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new
* position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end
* of the file plus offset bytes (usually negative or zero to seek to the end of the file).
* @returns Returns current file position.
**/
export function seekSync(fd: number, offset: number, whence: number): number;
/**
* Asynchronous utime(2).
* @param path File path
* @param atime
* Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds,
* so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000
* Just like for utime(2), the absence of the atime and mtime means 'now'.
* @param mtime
* Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds,
* so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000
* Just like for utime(2), the absence of the atime and mtime means 'now'.
**/
export function utime(path: string, atime: number, mtime: number, callback: (err: Error) => void):void;
/**
* Synchronous version of utime(). Throws an exception on error.
* @param path File path
* @param atime
* Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds,
* so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000
* Just like for utime(2), the absence of the atime and mtime means 'now'.
* @param mtime
* Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds,
* so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000
* Just like for utime(2), the absence of the atime and mtime means 'now'.
**/
export function utimeSync(path: string, atime: number, mtime: number):void;
}
@@ -51,6 +51,35 @@ app.on('ready', () => {
// when you should delete the corresponding element.
mainWindow = null;
});
mainWindow.print({silent: true, printBackground: false});
mainWindow.webContents.print({silent: true, printBackground: false});
mainWindow.print();
mainWindow.webContents.print();
mainWindow.print({silent: true, printBackground: false});
mainWindow.webContents.print({silent: true, printBackground: false});
mainWindow.print();
mainWindow.webContents.print();
mainWindow.printToPDF({
marginsType: 1,
pageSize: 'A3',
printBackground: true,
printSelectionOnly: true,
landscape: true,
}, (error: Error, data: Buffer) => {});
mainWindow.webContents.printToPDF({
marginsType: 1,
pageSize: 'A3',
printBackground: true,
printSelectionOnly: true,
landscape: true,
}, (error: Error, data: Buffer) => {});
mainWindow.printToPDF({}, (err, data) => {});
mainWindow.webContents.printToPDF({}, (err, data) => {});
});
// Desktop environment integration
+67 -6
View File
@@ -377,17 +377,22 @@ declare module GitHubElectron {
capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
capturePage(callback: (image: NativeImage) => void): void;
/**
* Prints the window's web page. Calling window.print() in a web page is
* equivalent to calling BrowserWindow.print({silent: false, printBackground: false}).
* Same with webContents.print([options])
*/
print(options?: {
/**
* When false, Electron will pick up system's default printer and default
* settings for printing.
*/
silent?: boolean;
printBackground?: boolean;
}): void;
/**
* Same with webContents.printToPDF([options])
*/
printToPDF(options: {
marginsType?: number;
pageSize?: string;
printBackground?: boolean;
printSelectionOnly?: boolean;
landscape?: boolean;
}, callback: (error: Error, data: Buffer) => void): void;
/**
* Same with webContents.loadUrl(url).
*/
@@ -659,6 +664,62 @@ declare module GitHubElectron {
* @param isFulfilled Whether the JS promise is fulfilled.
*/
(isFulfilled: boolean) => void): void;
/**
*
* Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing.
* Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}).
* Note:
* On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size.
*/
print(options?: {
/**
* Don't ask user for print settings, defaults to false
*/
silent?: boolean;
/**
* Also prints the background color and image of the web page, defaults to false.
*/
printBackground: boolean;
}): void;
/**
* Prints windows' web page as PDF with Chromium's preview printing custom settings.
*/
printToPDF(options: {
/**
* Specify the type of margins to use. Default is 0.
* 0 - default
* 1 - none
* 2 - minimum
*/
marginsType?: number;
/**
* String - Specify page size of the generated PDF. Default is A4.
* A4
* A3
* Legal
* Letter
* Tabloid
*/
pageSize?: string;
/**
* Whether to print CSS backgrounds. Default is false.
*/
printBackground?: boolean;
/**
* Whether to print selection only. Default is false.
*/
printSelectionOnly?: boolean;
/**
* true for landscape, false for portrait. Default is false.
*/
landscape?: boolean;
},
/**
* Callback function on completed converting to PDF.
* error Error
* data Buffer - PDF file content
*/
callback: (error: Error, data: Buffer) => void): void;
/**
* Send args.. to the web page via channel in asynchronous message, the web page
* can handle it by listening to the channel event of ipc module.
+19
View File
@@ -0,0 +1,19 @@
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="./gulp-changed.d.ts" />
/// <reference path="../gulp-minify-html/gulp-minify-html.d.ts" />
import * as gulp from "gulp";
import changed = require("gulp-changed");
import minifyHtml = require("gulp-minify-html");
// Without options
gulp.src("*.html")
.pipe(changed("build"))
.pipe(minifyHtml())
.pipe(gulp.dest("build"));
// With some options
gulp.src("*.html")
.pipe(changed("build", { hasChanged: changed.compareSha1Digest }))
.pipe(minifyHtml())
.pipe(gulp.dest("build"));
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for gulp-changed
// Project: https://github.com/sindresorhus/gulp-changed
// Definitions by: Thomas Corbière <https://github.com/tomc974>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
/// <reference path="../vinyl/vinyl.d.ts"/>
declare module "gulp-changed"
{
import { Transform } from "stream";
import File = require("vinyl");
interface IComparator
{
/**
* @param stream Should be used to queue sourceFile if it passes some comparison
* @param callback Should be called when done
* @param sourceFile File to operate on
* @param destPath Destination for sourceFile as an absolute path
*/
(stream: Transform, callback: Function, sourceFile: File, destPath: string): void;
}
interface IDestination
{
(file: string|Buffer): string;
}
interface IOptions
{
/**
* The working directory the folder is relative to.
* @default process.cwd()
*/
cwd?: string;
/**
* Extension of the destination files.
*/
extension?: string;
/**
* Function that determines whether the source file is different from the destination file.
* @default changed.compareLastModifiedTime
*/
hasChanged?: IComparator;
}
interface IGulpChanged
{
(destination: string|IDestination, options?: IOptions): NodeJS.ReadWriteStream;
compareLastModifiedTime: IComparator;
compareSha1Digest: IComparator;
}
const changed: IGulpChanged;
export = changed;
}
+53
View File
@@ -0,0 +1,53 @@
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="gulp-coffeeify.d.ts" />
import gulp = require('gulp');
import coffeeify = require('gulp-coffeeify');
// Basic usage
gulp.task('scripts', function() {
gulp.src('src/coffee/**/*.coffee')
.pipe(coffeeify())
.pipe(gulp.dest('./build/js'));
});
gulp.task('scripts', function() {
gulp.src('src/coffee/**/*.coffee')
.pipe(coffeeify({
options: {
debug: true, // source map
paths: [__dirname + '/node_modules', __dirname + '/src/coffee']
}
}))
.pipe(gulp.dest('./build/js'));
});
gulp.task('scripts', function() {
gulp.src('src/coffee/**/*.coffee')
.pipe(coffeeify({
aliases: [
{
cwd: 'src/coffee/app',
base: 'app'
}
]
}))
.pipe(gulp.dest('./build/js'));
});
var xform = function(data: string){
return 'module.exports = "' + data + '"';
};
gulp.task('scripts', function() {
gulp.src('src/coffee/**/*.coffee')
.pipe(coffeeify({
transforms: [
{
ext: '.extension',
transform: xform
}
]
}))
.pipe(gulp.dest('./build/js'));
});
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for gulp-coffeeify
// Project: https://github.com/nariyu/gulp-coffeeify
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-coffeeify" {
namespace coffeeify {
interface Coffeeify {
(option?: Option): NodeJS.ReadWriteStream;
}
interface Option {
options?: {
debug?: boolean;
paths?: string[];
},
/**
* [DEPRECATED]: You should use a 'paths' options of browserify.
*/
aliases?: Aliases;
/**
* [DEPRECATED]
*/
transforms?: Transforms;
}
interface Aliases {
cwd?: string;
base?: string;
}
interface Transforms {
ext?: string;
transform?(data: string): string;
}
}
var coffeeify: coffeeify.Coffeeify;
export = coffeeify;
}
+11
View File
@@ -0,0 +1,11 @@
/// <reference path="./gulp-dtsm.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import dtsm = require('gulp-dtsm');
import gulp = require('gulp');
var stream: NodeJS.WritableStream = dtsm();
gulp.task('dtsm', () => gulp.src('./dtsm.json').pipe(dtsm()));
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for gulp-dtsm 0.0.0
// Project: https://github.com/9joneg/gulp-dtsm
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-dtsm" {
function dtsm(): NodeJS.WritableStream;
export = dtsm;
}
+18 -6
View File
@@ -1,10 +1,22 @@
/// <reference path="./gulp-if.d.ts"/>
/// <reference path="../gulp/gulp.d.ts"/>
import gulp = require("gulp");
import _if = require("gulp-if");
import gulp = require('gulp');
import _if = require('gulp-if');
gulp.src("test.css")
.pipe(_if(true, gulp.src("test.css")));
gulp.src('test.css')
.pipe(_if(true, gulp.src('test.css')));
gulp.src("test.css")
.pipe(_if(false, gulp.src("test.css"), gulp.src("test.css")));
gulp.src('test.css')
.pipe(_if(false, gulp.src('test.css'), gulp.src('test.css')));
gulp.src('test.css')
.pipe(_if({isDirectory: true}, gulp.src('test.css')));
gulp.src('test.css')
.pipe(_if({isFile: true}, gulp.src('test.css')));
gulp.src('test.css')
.pipe(_if(file => true, gulp.src('test.css')));
gulp.src('test.css')
.pipe(_if(/.*?\.css/, gulp.src('test.css')));
+56 -6
View File
@@ -1,14 +1,64 @@
// Type definitions for gulp-if
// Project: https://github.com/robrich/gulp-if
// Definitions by: Asana <https://asana.com>
// Definitions by: Asana <https://asana.com>, Joe Skeen <http://github.com/joeskeen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
/// <reference path="../vinyl/vinyl.d.ts"/>
declare module "gulp-if" {
function gulpIf(
condition: boolean,
stream: NodeJS.ReadWriteStream,
elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
declare module 'gulp-if' {
import fs = require('fs');
import vinyl = require('vinyl');
interface GulpIf {
/**
* gulp-if will pipe data to stream whenever condition is truthy.
* If condition is falsey and elseStream is passed, data will pipe to elseStream
* After data is piped to stream or elseStream or neither, data is piped down-stream.
*
* @param condition whether input should be piped to stream
* @param stream the stream to pipe to if condition is true
* @param elseStream (optional) the stream to pipe to if condition is false
*/
(condition: boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
/**
* gulp-if will pipe data to stream whenever condition is truthy.
* If condition is falsey and elseStream is passed, data will pipe to elseStream
* After data is piped to stream or elseStream or neither, data is piped down-stream.
*
* @param condition a Node Stat filter condition to be executed on the vinyl file's Stats object
* @param stream the stream to pipe to if condition is true
* @param elseStream (optional) the stream to pipe to if condition is false
*/
(condition: StatFilterCondition, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
/**
* gulp-if will pipe data to stream whenever condition is truthy.
* If condition is falsey and elseStream is passed, data will pipe to elseStream
* After data is piped to stream or elseStream or neither, data is piped down-stream.
*
* @param condition a function taking a vinyl file and returning a boolean
* @param stream the stream to pipe to if condition is true
* @param elseStream (optional) the stream to pipe to if condition is false
*/
(condition: (fs: vinyl) => boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
/**
* gulp-if will pipe data to stream whenever condition is truthy.
* If condition is falsey and elseStream is passed, data will pipe to elseStream
* After data is piped to stream or elseStream or neither, data is piped down-stream.
*
* @param condition a RegularExpression that works on the file.path
* @param stream the stream to pipe to if condition is true
* @param elseStream (optional) the stream to pipe to if condition is false
*/
(condition: RegExp, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream;
}
interface StatFilterCondition {
isDirectory?: boolean;
isFile?: boolean;
}
var gulpIf: GulpIf;
export = gulpIf;
}
+16
View File
@@ -4,6 +4,22 @@
import gulp = require("gulp");
import less = require("gulp-less");
// Without options
gulp.task("less", () => {
gulp.src("less/**/*.less")
.pipe(less())
.pipe(gulp.dest("public/css"));
});
// With an empty option object
gulp.task("less", () => {
gulp.src("less/**/*.less")
.pipe(less({}))
.pipe(gulp.dest("public/css"));
});
// With some options
gulp.task("less", () => {
gulp.src("less/**/*.less")
.pipe(less({
+2 -1
View File
@@ -8,7 +8,8 @@
declare module "gulp-less" {
interface IOptions {
paths: string[];
modifyVars?: {};
paths?: string[];
plugins?: any[];
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="../gulp-minify-html/gulp-minify-html.d.ts" />
/// <reference path="./gulp-newer.d.ts" />
import * as gulp from "gulp";
import newer = require("gulp-newer");
import minifyHtml = require("gulp-minify-html");
gulp.src("*.html")
.pipe(newer("build"))
.pipe(minifyHtml())
.pipe(gulp.dest("build"));
gulp.src("*.html")
.pipe(newer({ dest: "build" }))
.pipe(minifyHtml())
.pipe(gulp.dest("build"));
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for gulp-newer
// Project: https://github.com/tschaub/gulp-newer
// Definitions by: Thomas Corbière <https://github.com/tomc974>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module "gulp-newer"
{
interface IOptions
{
/**
* Path to destination directory or file.
*/
dest: string;
/**
* Source files will be matched to destination files with the provided extension.
*/
ext?: string;
/**
* Map relative source paths to relative destination paths.
*/
map?: (relativePath: string) => string;
}
interface IGulpNewer
{
/**
* Create a transform stream that passes through files whose modification time
* is more recent than the corresponding destination file's modification time.
* @param dest Path to destination directory or file.
*/
(dest: string): NodeJS.ReadWriteStream;
/**
* Create a transform stream that passes through files whose modification time
* is more recent than the corresponding destination file's modification time.
*/
(options: IOptions): NodeJS.ReadWriteStream;
}
const newer: IGulpNewer;
export = newer;
}
+36
View File
@@ -0,0 +1,36 @@
/// <reference path="../node/node" />
/// <reference path="../gulp/gulp" />
/// <reference path="gulp-plumber" />
import gulp = require('gulp');
import plumber = require('gulp-plumber');
//default behavior
gulp.src('./src/*.ext')
.pipe(plumber())
.pipe(gulp.dest('./dist'));
//error handler function
gulp.src('./src/*.ext')
.pipe(plumber((error) => {
console.log(error);
}))
.pipe(gulp.dest('./dist'));
gulp.src('./src/*.ext')
.pipe(plumber({}))
.pipe(gulp.dest('./dist'));
gulp.src('./src/*.ext')
.pipe(plumber({ inherit: false }))
.pipe(gulp.dest('./dist'));
gulp.src('./src/*.ext')
.pipe(plumber({ errorHandler: (error) => console.log(error) }))
.pipe(gulp.dest('./dist'));
//plumber.stop()
gulp.src('./src/*.scss')
.pipe(plumber())
.pipe(plumber.stop())
.pipe(gulp.dest('./dist'));
+51
View File
@@ -0,0 +1,51 @@
// Type definitions for gulp-plumber
// Project: https://github.com/floatdrop/gulp-plumber
// Definitions by: Joe Skeen <http://github.com/joeskeen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/** Prevent pipe breaking caused by errors from gulp plugins */
declare module 'gulp-plumber' {
/** Prevent pipe breaking caused by errors from gulp plugins */
interface GulpPlumber {
/**
* Returns Stream, that fixes pipe methods on Streams that are next in pipeline.
*
* @param options Sets options as described in the Options interface
*/
(options?: Options): NodeJS.ReadWriteStream;
/**
* Returns Stream, that fixes pipe methods on Streams that are next in pipeline.
*
* @param errorHandler the function to be attached to the stream on('error')
*/
(errorHandler: ErrorHandlerFunction): NodeJS.ReadWriteStream;
/** returns default behaviour for pipeline after it was piped */
stop(): NodeJS.ReadWriteStream;
}
interface Options {
/**
* Handle errors in underlying streams and output them to console. Default true.
* If function passed, it will be attached to stream on('error')
* If false passed, error handler will not be attached
* If undefined passed, default error handler will be attached
*/
errorHandler?: ErrorHandlerFunction | boolean;
/** Monkeypatch pipe functions in underlying streams in pipeline. Default true. */
inherit?: boolean;
}
/** an error handler function to be attached to the stream on('error') */
interface ErrorHandlerFunction {
/** an error handler function to be attached to the stream on('error') */
(error: any): void;
}
/** Prevent pipe breaking caused by errors from gulp plugins */
var gulpPlumber: GulpPlumber;
export = gulpPlumber;
}
+50
View File
@@ -0,0 +1,50 @@
/** Tests taken from https://github.com/pgilad/gulp-sort#usage */
/// <reference path="../node/node" />
/// <reference path="../gulp/gulp" />
/// <reference path="gulp-sort" />
import gulp = require('gulp');
import sort = require('gulp-sort');
import gulpUtil = require('gulp-util');
// default sort
gulp.src('./src/js/**/*.js')
.pipe(sort())
.pipe(gulp.dest('./build/js'));
// pass in a custom comparator function
gulp.src('./src/js/**/*.js')
.pipe(sort(customComparator))
.pipe(gulp.dest('./build/js'));
// sort descending
gulp.src('./src/js/**/*.js')
.pipe(sort({
asc: false
}))
.pipe(gulp.dest('./build/js'));
// sort with a custom comparator
gulp.src('./src/js/**/*.js')
.pipe(sort({
comparator: function(file1, file2) {
if (file1.path.indexOf('build') > -1) {
return 1;
}
if (file2.path.indexOf('build') > -1) {
return -1;
}
return 0;
}
}))
.pipe(gulp.dest('./build/js'));
function customComparator(file1: gulpUtil.File, file2: gulpUtil.File) {
if (file1.path.indexOf('build') > -1) {
return 1;
}
if (file2.path.indexOf('build') > -1) {
return -1;
}
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for gulp-sort
// Project: https://github.com/pgilad/gulp-sort
// Definitions by: Joe Skeen <http://github.com/joeskeen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../gulp-util/gulp-util.d.ts" />
/** Sort files in stream by path or any custom sort comparator */
declare module 'gulp-sort' {
import gulpUtil = require('gulp-util');
interface IOptions {
/**
* A function to compare two files.
* Returns:
* -1 if file1 should be before file2,
* 0 if file1 is equivalent to file2, and
* 1 if file1 should be after file2
*/
comparator?: IComparatorFunction;
/** Whether to sort in ascending order, default is true */
asc?: boolean;
}
interface IComparatorFunction {
/**
* A function to compare two files.
* Returns:
* -1 if file1 should be before file2,
* 0 if file1 is equivalent to file2, and
* 1 if file1 should be after file2
*/
(file1: gulpUtil.File, file2: gulpUtil.File): number;
}
/** Sort files in stream by path or any custom sort comparator */
function gulpSort(): NodeJS.ReadWriteStream;
function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream;
function gulpSort(options: IOptions): NodeJS.ReadWriteStream;
export = gulpSort;
}
+1
View File
@@ -13,6 +13,7 @@ interface HighchartsPosition {
}
interface HighchartsDateTimeFormats {
millisecond?: string; // '%H:%M:%S.%L'
second?: string; // '%H:%M:%S'
minute?: string; // '%H:%M'
hour?: string; // '%H:%M'
+8 -8
View File
@@ -5,23 +5,23 @@
interface HistoryAdapter {
bind(element: any, event: string, callback: () => void);
trigger(element: any, event: string);
onDomLoad(callback: () => void);
bind(element: any, event: string, callback: () => void): void;
trigger(element: any, event: string): void;
onDomLoad(callback: () => void): void;
}
// Since History is defined in lib.d.ts as well
// Since History is defined in lib.d.ts as well
// the name for our interfaces was chosen to be Historyjs
// However at runtime you would need to do
// https://github.com/borisyankov/DefinitelyTyped/issues/277
// https://github.com/borisyankov/DefinitelyTyped/issues/277
// var Historyjs: Historyjs = <any>History;
interface Historyjs {
enabled: boolean;
pushState(data: any, title: string, url: string);
replaceState(data: any, title: string, url: string);
pushState(data: any, title: string, url: string): void;
replaceState(data: any, title: string, url: string): void;
getState(): HistoryState;
getStateByIndex(index: number): HistoryState;
getCurrentIndex(): number;
@@ -58,4 +58,4 @@ interface HistoryOptions {
delayInit?: number;
}
}
+6 -2
View File
@@ -17,6 +17,10 @@ interface IResourceStoreKey {
[key: string]: any;
}
interface I18nTranslateOptions extends I18nextOptions {
defaultValue?: any; // normally a string
}
interface I18nextOptions {
lng?: string; // Default value: undefined
load?: string; // Default value: 'all'
@@ -108,8 +112,8 @@ interface I18nextStatic {
load: (languages: string[], options: I18nextOptions, callback: (err: Error, store: IResourceStore) => void ) => void;
postMissing: (language: string, namespace: string, key: string, defaultValue: any, languages: string[]) => void;
};
t(key: string, options?: any): string;
translate(key: string, options?: any): string;
t(key: string, options?: I18nTranslateOptions): string;
translate(key: string, options?: I18nTranslateOptions): string;
exists(key: string, options?: any): boolean;
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="imagesLoaded.d.ts" />
/// <reference path="imagesloaded.d.ts" />
function test_ctor() {
// element
+1 -1
View File
@@ -16,7 +16,7 @@ declare module ionic {
cancelText?: string;
destructiveText?: string;
cancel?: ()=>any;
buttonClicked?: ()=>any;
buttonClicked?: (index: any)=>any;
destructiveButtonClicked?: ()=>any;
cancelOnStateChange?: boolean;
cssClass?: string;
+54
View File
@@ -0,0 +1,54 @@
/// <reference path="jquery.ajaxFile.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../knockout/knockout.d.ts" />
function testRawApi(){
var inputElement:HTMLInputElement = null;
var resultPromise = AjaxFile.send({
method: 'POST',
url: '/',
desiredResponseDataType: JQueryAjaxFile.DataType.Json,
files: [
{ name: 'joeFile', element: inputElement }
],
data: {
name: 'joe'
},
timeoutInSeconds: 30
})
.then(result => console.log('Result: ' + result.data), result => console.log('Error: ' + result.error))
.done(result => console.log('Result: ' + result.data))
.fail(result => console.log('Error: ' + result.error + " " + result.status.code + " " + result.status.text + " " + result.status.isSuccess))
.always(result => console.log('end'))
.abord();
}
function testJQuery() {
var inputElement: HTMLInputElement = null;
var extension: JQueryAjaxFile.IAjaxFileJQueryExtension = $.fn.ajaxWithFile;
var option: JQueryAjaxFile.IJQueryOption = {
type: 'POST',
url: '/',
dataType: "json",
files: [
{ name: 'joeFile', element: inputElement }
],
data: {
name: 'joe'
},
success(result) { console.log('Result: ' + result); },
error(jqXhr, textStatus, errorThrown) { console.log('Error: ' + errorThrown); },
complete(jqXhr, textStatus) { console.log('end'); },
global: true,
timeout: 60
};
extension.ajaxWithFile(option);
}
function testKnockoutExtension(){
var fileHandler:KnockoutBindingHandler = ko.bindingHandlers.file;
}
testKnockoutExtension();
testJQuery();
testRawApi();
+119
View File
@@ -0,0 +1,119 @@
// Type definitions for jquery.ajaxfile v0.1.0
// Project: https://github.com/fpellet/jquery.ajaxFile
// Definitions by: Florent PELLET <https://github.com/fpellet/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../knockout/knockout.d.ts" />
declare namespace JQueryAjaxFile {
export enum DataType {
Json,
Xml,
Text
}
interface IFileData {
name: string;
element: HTMLInputElement;
}
interface IOption {
method?: string;
url?: string;
data?: any;
files?: IFileData[];
desiredResponseDataType?: DataType;
timeoutInSeconds?: number;
}
interface IResponseStatus {
code: number;
text: string;
isSuccess: boolean;
}
interface IAjaxFileResult {
error?: any;
data?: any;
status?: IResponseStatus;
}
interface IAjaxFileResultCallback {
(result: IAjaxFileResult): void;
}
interface IAjaxFilePromise {
then(success: IAjaxFileResultCallback, error?: IAjaxFileResultCallback): IAjaxFilePromise;
done(success: IAjaxFileResultCallback): IAjaxFilePromise;
fail(error: IAjaxFileResultCallback): IAjaxFilePromise;
always(error: IAjaxFileResultCallback): IAjaxFilePromise;
abord(): void;
}
interface IAjaxFileStatic {
send(option: IOption): IAjaxFilePromise;
}
interface IJQueryXHR {
readyState: any;
status: number;
statusText: string;
responseXML: Document;
responseText: string;
statusCode?: { [key: string]: any; };
abort(statusText?: string): void;
setRequestHeader(header: string, value: string): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string;
beforeSend?(jqXHR: IJQueryXHR, settings: JQueryAjaxSettings): any;
dataFilter?(data: any, ty: any): any;
success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any;
error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any;
complete?(jqXHR: IJQueryXHR, textStatus: string): any;
}
interface IJQueryOption {
type?: string;
url?: string;
data?: any;
files?: IFileData[];
dataType?: string;
timeout?: number;
global?: boolean;
error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any;
success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any;
complete?(jqXHR: IJQueryXHR, textStatus: string): any;
}
interface IAjaxFileJQueryExtension {
ajaxWithFile(jqueryOption: IJQueryOption): JQueryDeferred<any>;
}
}
declare var AjaxFile: JQueryAjaxFile.IAjaxFileStatic;
declare module 'ajaxfile' {
export = AjaxFile;
}
declare namespace AjaxFileKnockout {
interface IFileInputWrapper {
getElement(): HTMLInputElement;
fileSelected(): boolean;
}
}
interface KnockoutBindingHandlers {
file: KnockoutBindingHandler;
}
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="jquery.dynatree.d.ts" />
var dynatree = $('element').dynatree();
dynatree.visit((node)=>{
return false;
});
dynatree.visit((node)=>{
return false;
}, true);
var node = dynatree.getActiveNode();
node.select(true);
+5 -5
View File
@@ -41,7 +41,7 @@ interface DynaTree {
selectKey(key: string, flag: string): DynaTreeNode;
serializeArray(stopOnParents: boolean): any[];
toDict(includeRoot?: boolean): any;
visit(fn: (node: DynaTreeNode) =>boolean, includeRoot: boolean): void;
visit(fn: (node: DynaTreeNode) =>boolean, includeRoot?: boolean): void;
}
@@ -54,7 +54,7 @@ interface DynaTreeNode {
appendAjax(ajaxOptions: JQueryAjaxSettings): void;
countChildren(): number;
deactivate(): void;
expand(flag: string): void;
expand(flag: boolean): void;
focus(): void;
getChildren(): DynaTreeNode[];
getEventTargetType(event: Event): string;
@@ -83,11 +83,11 @@ interface DynaTreeNode {
removeChildren(): void;
render(useEffects: boolean, includeInvisible: boolean): void;
resetLazy(): void;
scheduleAction(mode: string, ms: number);
select(flag: string): void;
scheduleAction(mode: string, ms: number): void;
select(flag: boolean): void;
setLazyNodeStatus(status: number): void;
setTitle(title: string): void;
sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean);
sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean): void;
toDict(recursive: boolean, callback?: (node: any) =>any): any;
toggleExpand(): void;
toggleSelect(): void;
+2 -2
View File
@@ -24,8 +24,8 @@ interface RetryOption {
interface DeferredizedFunction { (...arg: any[]): Deferred; }
interface DeferredizedFunctionWithNumber { (n: number): Deferred; }
interface FunctionWithNumber { (i: number, o?: any); }
interface ErrorCallback { (d: Deferred, ...args: any[]); }
interface FunctionWithNumber { (i: number, o?: any): any; }
interface ErrorCallback { (d: Deferred, ...args: any[]): any; }
declare class Deferred {
+121
View File
@@ -0,0 +1,121 @@
/// <reference path='./jug.d.ts' />
import jug = require('jug');
/*
Example 1.
*/
var root = jug.init();
root
.seed()
.seed();
root.data({
interest: {
genre: 'Action',
year: 2014,
stars: [ 'Eva Green', 'Duck Dogers' ]
}
});
root.edge( 0 ).data({
info: {
name: '300: Rise of an Empire',
genre: 'Action',
stars: [ 'Eva Green', 'Duck Dogers' ],
year: 2014
}
});
root.edge( 1 ).data({
info: {
name: 'Man of Steel',
genre: 'Action',
stars: [ 'Henry Cavill' ],
year: 2013
}
});
root.edge(1).seed({
test: {
some: 'value'
}
});
var distance = root.proximity('interest', 'info');
var close = distance.indexOf( 0 );
var nodeData = root.edge( close ).data();
/*
Example 2.
*/
var wire = jug.init({
interest: {
cloth: 't-shirt',
color: 'red',
size: 'medium'
}
});
/*
Seed node
*/
wire.seed();
/*
Seed node with data.
*/
wire.seed({
info: {
cloth: 't-shirt',
color: 'red',
size: 'medium'
}
});
/*
Access node.
*/
wire.edge(0);
/*
Get distance between nodes
*/
// first argument is 'from' object
// second argument is 'to' object
root.proximity('interest', 'info');
/*
Find a node.
*/
wire.find('info', { color: 'red' });
/*
Verify the level.
*/
wire.edge(0).level();
/*
Verify if the current node is the root
*/
wire.isRoot();
/*
Getting childs of an specified edge
*/
wire.getChildsOf(0);
/*
Getting parents of an specified level and edge.
*/
wire.getParentsFrom(1, 0);
/*
Getting the length of childs of an specified edge.
*/
wire.getScopeOf(0);
/*
Getting siblings of current level, excluding the index indicated.
*/
wire.getSiblingsOf(1);
+135
View File
@@ -0,0 +1,135 @@
// Type definitions for jug
// Project: https://github.com/kaiquewdev/Graph
// Definitions by: yevt <https://github.com/yevt>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "jug" {
/**
* Internal structure of a vertex
*/
interface VertexStructure {
level: number;
edge: Array<Vertex>,
data: VertexData,
parent: Vertex
}
/**
* User data of a vertex.
*/
type VertexData = Object;
/**
* Graph constructor function.
*/
interface GraphConstructor {
new():Graph;
}
/**
* Creates root node of a graph.
*/
interface Graph {
vertex:VertexConstructor;
init(data?:VertexData):Vertex;
}
/**
* Vertex constructor function.
*/
interface VertexConstructor {
new(obj?:VertexData):Vertex;
}
/**
* Represents one node of a graph.
*/
interface Vertex {
/**
* Initial vertex data.
*/
internal: VertexStructure;
/**
* Verify the level.
*/
level(): number;
/**
* Get edge count.
*/
edge(): number;
/**
* Access node.
* @param index - edge index.
*/
edge(index:number): Vertex;
/**
* Seed node.
* @param [data] - created vertex UserData.
*/
seed(data?:VertexData): Vertex;
/**
* Verify if the current node is the root.
*/
isRoot(): boolean;
/**
* Set node data.
* @param obj - data to be set.
*/
data(obj:VertexData): Vertex;
/**
* Get node data.
*/
data(): VertexData;
/**
* Get distance between nodes.
* @param from
* @param to
*/
proximity(from:string, to:string): Array<number>;
/**
* Find a node.
* @param {string} type - object type.
* @param {Object} query - _.where query object.
*/
find(type:string|void, query:Object): Array<VertexData>;
/**
* Get siblings of specified edge.
* @param {number} index - edge index.
*/
getSiblingsOf(index:number): Array<VertexData>;
/**
* Getting childs of an specified edge.
* @param egde - target vertex;
*/
getChildsOf(egde:number): Array<VertexData>;
/**
* Getting parents of an specified level and edge.
* @param {number} level - max level.
* @param {number} edge - edge index.
*/
getParentsFrom(level:number, edge:number): Array<VertexData>;
/**
* Getting the length of childs of an specified edge.
* @param {number} edge - edge index.
*/
getScopeOf(edge:number): number;
}
var jug:Graph;
export = jug;
}
+215 -64
View File
@@ -91,6 +91,12 @@ var result: any;
var any: any;
interface TResult {
a: number;
b: string;
c: boolean;
}
// _.MapCache
var testMapCache: _.MapCache;
result = <(key: string) => boolean>testMapCache.delete;
@@ -123,6 +129,7 @@ result = <_.LoDashObjectWrapper<_.Dictionary<string>>>_(<{ [index: string]: stri
//Wrapped array shortcut methods
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).concat(5, 6);
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).concat([5, 6]);
result = <string>_([1, 2, 3, 4]).join(',');
result = <number>_([1, 2, 3, 4]).pop();
result = <_.LoDashArrayWrapper<number>>_([1, 2, 3, 4]).push(5, 6, 7);
@@ -639,6 +646,7 @@ result = <number>_(stoogesAgesDict).sum('age');
result = <string[]>_.pluck(stoogesAges, 'name');
result = <string[]>_(stoogesAges).pluck('name').value();
result = <string[]>_.pluck(stoogesAges, ['name']);
// _.partition
result = <string[][]>_.partition<string>('abcd', (n) => n < 'c');
@@ -1091,41 +1099,89 @@ helloWrap2();
* Lang *
********/
// _.cloneDeep
interface TestCloneDeepFn {
// _.clone
interface TestCloneCustomizerFn {
(value: any): any;
}
var testCloneDeepFn: TestCloneDeepFn;
result = <number>_.cloneDeep<number>(1);
result = <number>_.cloneDeep<number>(1, testCloneDeepFn);
result = <number>_.cloneDeep<number>(1, testCloneDeepFn, any);
result = <string>_.cloneDeep<string>('a');
result = <string>_.cloneDeep<string>('a', testCloneDeepFn);
result = <string>_.cloneDeep<string>('a', testCloneDeepFn, any);
result = <boolean>_.cloneDeep<boolean>(true);
result = <boolean>_.cloneDeep<boolean>(true, testCloneDeepFn);
result = <boolean>_.cloneDeep<boolean>(true, testCloneDeepFn, any);
result = <number[]>_.cloneDeep<number[]>([1, 2]);
result = <number[]>_.cloneDeep<number[]>([1, 2], testCloneDeepFn);
result = <number[]>_.cloneDeep<number[]>([1, 2], testCloneDeepFn, any);
result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}});
result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn);
result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn, any);
result = <number>_(1).cloneDeep();
result = <number>_(1).cloneDeep(testCloneDeepFn);
result = <number>_(1).cloneDeep(testCloneDeepFn, any);
result = <string>_('a').cloneDeep();
result = <string>_('a').cloneDeep(testCloneDeepFn);
result = <string>_('a').cloneDeep(testCloneDeepFn, any);
result = <boolean>_(true).cloneDeep();
result = <boolean>_(true).cloneDeep(testCloneDeepFn);
result = <boolean>_(true).cloneDeep(testCloneDeepFn, any);
result = <number[]>_([1, 2]).cloneDeep();
result = <number[]>_([1, 2]).cloneDeep(testCloneDeepFn);
result = <number[]>_([1, 2]).cloneDeep(testCloneDeepFn, any);
result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep();
result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn);
result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn, any);
var testCloneCustomizerFn: TestCloneCustomizerFn;
{
let result: number;
result = _.clone<number>(42);
result = _.clone<number>(42, false);
result = _.clone<number>(42, false, testCloneCustomizerFn);
result = _.clone<number>(42, false, testCloneCustomizerFn, any);
result = _.clone<number>(42, testCloneCustomizerFn);
result = _.clone<number>(42, testCloneCustomizerFn, any);
result = _(42).clone();
result = _(42).clone(false);
result = _(42).clone(false, testCloneCustomizerFn);
result = _(42).clone(false, testCloneCustomizerFn, any);
result = _(42).clone(testCloneCustomizerFn);
result = _(42).clone(testCloneCustomizerFn, any);
}
{
let result: string[];
result = _.clone<string[]>([]);
result = _.clone<string[]>([], false);
result = _.clone<string[]>([], false, testCloneCustomizerFn);
result = _.clone<string[]>([], false, testCloneCustomizerFn, any);
result = _.clone<string[]>([], testCloneCustomizerFn);
result = _.clone<string[]>([], testCloneCustomizerFn, any);
result = _<string>([]).clone();
result = _<string>([]).clone(false);
result = _<string>([]).clone(false, testCloneCustomizerFn);
result = _<string>([]).clone(false, testCloneCustomizerFn, any);
result = _<string>([]).clone(testCloneCustomizerFn);
result = _<string>([]).clone(testCloneCustomizerFn, any);
}
{
let result: {a: {b: number;}};
result = _.clone<{a: {b: number;}}>({a: {b: 2}});
result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false);
result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn);
result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn, any);
result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn);
result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn, any);
result = _({a: {b: 2}}).clone();
result = _({a: {b: 2}}).clone(false);
result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn);
result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn, any);
result = _({a: {b: 2}}).clone(testCloneCustomizerFn);
result = _({a: {b: 2}}).clone(testCloneCustomizerFn, any);
}
// _.cloneDeep
interface TestCloneDeepCustomizerFn {
(value: any): any;
}
var testCloneDeepCustomizerFn: TestCloneDeepCustomizerFn;
{
let result: number;
result = _.cloneDeep<number>(42);
result = _.cloneDeep<number>(42, testCloneDeepCustomizerFn);
result = _.cloneDeep<number>(42, testCloneDeepCustomizerFn, any);
result = _(42).cloneDeep();
result = _(42).cloneDeep(testCloneDeepCustomizerFn);
result = _(42).cloneDeep(testCloneDeepCustomizerFn, any);
}
{
let result: string[];
result = _.cloneDeep<string[]>([]);
result = _.cloneDeep<string[]>([], testCloneDeepCustomizerFn);
result = _.cloneDeep<string[]>([], testCloneDeepCustomizerFn, any);
result = _<string>([]).cloneDeep();
result = _<string>([]).cloneDeep(testCloneDeepCustomizerFn);
result = _<string>([]).cloneDeep(testCloneDeepCustomizerFn, any);
}
{
let result: {a: {b: number;}};
result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}});
result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn);
result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn, any);
result = _({a: {b: 2}}).cloneDeep();
result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn);
result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn, any);
}
// _.gt
result = <boolean>_.gt(1, 2);
@@ -1139,6 +1195,24 @@ result = <boolean>_(1).gte(2);
result = <boolean>_([]).gte(2);
result = <boolean>_({}).gte(2);
// _.isArguments
result = <boolean>_.isArguments(any);
result = <boolean>_(1).isArguments();
result = <boolean>_<any>([]).isArguments();
result = <boolean>_({}).isArguments();
// _.isArray
result = <boolean>_.isArray(any);
result = <boolean>_(1).isArray();
result = <boolean>_<any>([]).isArray();
result = <boolean>_({}).isArray();
// _.isDate
result = <boolean>_.isDate(any);
result = <boolean>_(42).isDate();
result = <boolean>_<any>([]).isDate();
result = <boolean>_({}).isDate();
// _.isEmpty
result = <boolean>_.isEmpty([1, 2, 3]);
result = <boolean>_.isEmpty({});
@@ -1147,6 +1221,24 @@ result = <boolean>_([1, 2, 3]).isEmpty();
result = <boolean>_({}).isEmpty();
result = <boolean>_('').isEmpty();
// _.isError
result = <boolean>_.isError(any);
result = <boolean>_(1).isError();
result = <boolean>_<any>([]).isError();
result = <boolean>_({}).isError();
// _.isFinite
result = <boolean>_.isFinite(any);
result = <boolean>_(1).isFinite();
result = <boolean>_<any>([]).isFinite();
result = <boolean>_({}).isFinite();
// _.isFunction
result = <boolean>_.isFunction(any);
result = <boolean>_(1).isFunction();
result = <boolean>_<any>([]).isFunction();
result = <boolean>_({}).isFunction();
// _.isMatch
var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean;
result = <boolean>_.isMatch({}, {});
@@ -1168,10 +1260,34 @@ result = <boolean>_(undefined).isNaN();
result = <boolean>_.isNative(Array.prototype.push);
result = <boolean>_(Array.prototype.push).isNative();
// _.isNumber
result = <boolean>_.isNumber(any);
result = <boolean>_(1).isNumber();
result = <boolean>_<any>([]).isNumber();
result = <boolean>_({}).isNumber();
// _.isRegExp
result = <boolean>_.isRegExp(any);
result = <boolean>_(1).isRegExp();
result = <boolean>_<any>([]).isRegExp();
result = <boolean>_({}).isRegExp();
// _.isString
result = <boolean>_.isString(any);
result = <boolean>_(1).isString();
result = <boolean>_<any>([]).isString();
result = <boolean>_({}).isString();
// _.isTypedArray
result = <boolean>_.isTypedArray([]);
result = <boolean>_([]).isTypedArray();
// _.isUndefined
result = <boolean>_.isUndefined(any);
result = <boolean>_(1).isUndefined();
result = <boolean>_<any>([]).isUndefined();
result = <boolean>_({}).isUndefined();
// _.lt
result = <boolean>_.lt(1, 2);
result = <boolean>_(1).lt(2);
@@ -1262,12 +1378,6 @@ result = <{}>_(testCreateProto).create(testCreateProps).value();
result = <TestCreateProto>_(testCreateProto).create<TestCreateProto>().value();
result = <TestCreateTResult>_(testCreateProto).create<TestCreateTResult>(testCreateProps).value();
result = <IStoogesAge[]>_.clone(stoogesAges);
result = <IStoogesAge[]>_.clone(stoogesAges, true);
result = <any>_.clone(stoogesAges, true, function (value) {
return _.isElement(value) ? value.cloneNode(false) : undefined;
});
interface Food {
name: string;
type: string;
@@ -1363,15 +1473,8 @@ interface FirstSecond {
}
result = <FirstSecond>_.invert({ 'first': 'moe', 'second': 'larry' });
(function (...args: any[]) { return <boolean>_.isArguments(arguments); })(1, 2, 3);
(function () { return <boolean>_.isArray(arguments); })();
result = <boolean>_.isArray([1, 2, 3]);
result = <boolean>_.isBoolean(null);
result = <boolean>_.isDate(new Date());
result = <boolean>_.isElement(document.body);
// _.isEqual (alias: _.eq)
@@ -1399,19 +1502,9 @@ result = <boolean>_(testEqArray).isEqual(testEqOtherArray, testEqCustomizerFn);
result = <boolean>_.eq(testEqArray, testEqOtherArray, testEqCustomizerFn);
result = <boolean>_(testEqArray).eq(testEqOtherArray, testEqCustomizerFn);
result = <boolean>_.isFinite(-101);
result = <boolean>_.isFinite('10');
result = <boolean>_.isFinite(true);
result = <boolean>_.isFinite('');
result = <boolean>_.isFinite(Infinity);
result = <boolean>_.isFunction(_);
result = <boolean>_.isNull(null);
result = <boolean>_.isNull(undefined);
result = <boolean>_.isNumber(8.4 * 5);
result = <boolean>_.isObject({});
result = <boolean>_.isObject([1, 2, 3]);
result = <boolean>_.isObject(1);
@@ -1427,12 +1520,6 @@ result = <boolean>_.isPlainObject(new Stooge('moe', 40));
result = <boolean>_.isPlainObject([1, 2, 3]);
result = <boolean>_.isPlainObject({ 'name': 'moe', 'age': 40 });
result = <boolean>_.isRegExp(/moe/);
result = <boolean>_.isString('moe');
result = <boolean>_.isUndefined(void 0);
result = <string[]>_.keys({ 'one': 1, 'two': 2, 'three': 3 });
result = <string[]>_({ 'one': 1, 'two': 2, 'three': 3 }).keys().value();
@@ -1539,9 +1626,17 @@ result = <number[]>_(new TestValueIn()).valuesIn<number>().value();
// → [1, 2, 3]
/**********
* Utilities *
* Utility *
***********/
// _.attempt
interface TestAttemptFn {
(): TResult;
}
var testAttempFn: TestAttemptFn;
result = <TResult|Error>_.attempt<TResult>(testAttempFn);
result = <TResult|Error>_(testAttempFn).attempt<TResult>();
result = <{ name: string }>_.identity({ 'name': 'moe' });
_.mixin({
@@ -1571,6 +1666,10 @@ result = <void>_(any).noop(true, 'a', 1);
var object = {
'cheese': 'crumpets',
'one': 1,
'nested': {
'two': 2
},
'stuff': function () {
return 'nonsense';
}
@@ -1578,6 +1677,8 @@ var object = {
result = <string>_.result(object, 'cheese');
result = <string>_.result(object, 'stuff');
result = _.result<number>(object, 'one');
result = _.result<number>(object, ['nested', 'two'] );
var tempObject = {};
result = <typeof _>_.runInContext(tempObject);
@@ -1650,10 +1751,21 @@ result = <string>_.uniqueId();
* String
*********/
// _.camelCase
result = <string>_.camelCase('Foo Bar');
result = <string>_('Foo Bar').camelCase();
result = <string>_.capitalize('fred');
// _.deburr
result = <string>_.deburr('déjà vu');
result = <string>_('déjà vu').deburr();
// _.endsWith
result = <boolean>_.endsWith('abc', 'c');
result = <boolean>_.endsWith('abc', 'c', 1);
result = <boolean>_('abc').endsWith('c');
result = <boolean>_('abc').endsWith('c', 1);
// _.escape
result = <string>_.escape('fred, barney, & pebbles');
@@ -1663,14 +1775,33 @@ result = <string>_('fred, barney, & pebbles').escape();
result = <string>_.escapeRegExp('[lodash](https://lodash.com/)');
result = <string>_('[lodash](https://lodash.com/)').escapeRegExp();
// _.kebabCase
result = <string>_.kebabCase('Foo Bar');
result = <string>_('Foo Bar').kebabCase();
// _.pad
result = <string>_.pad('abd');
result = <string>_.pad('abc', 8);
result = <string>_.pad('abc', 8, '_-');
result = <string>_('abc').pad();
result = <string>_('abc').pad(8);
result = <string>_('abc').pad(8, '_-');
// _.padLeft
result = <string>_.padLeft('abc');
result = <string>_.padLeft('abc', 6);
result = <string>_.padLeft('abc', 6, '_-');
result = <string>_('abc').padLeft();
result = <string>_('abc').padLeft(6);
result = <string>_('abc').padLeft(6, '_-');
// _.padRight
result = <string>_.padRight('abc');
result = <string>_.padRight('abc', 6);
result = <string>_.padRight('abc', 6, '_-');
result = <string>_.repeat('*', 3);
result = <string>_('abc').padRight();
result = <string>_('abc').padRight(6);
result = <string>_('abc').padRight(6, '_-');
// _.parseInt
result = <number>_.parseInt('08');
@@ -1678,12 +1809,23 @@ result = <number>_.parseInt('08', 10);
result = <number>_('08').parseInt();
result = <number>_('08').parseInt(10);
// _.repeat
result = <string>_.repeat('*', 3);
result = <string>_('*').repeat(3);
// _.snakeCase
result = <string>_.snakeCase('Foo Bar');
result = <string>_('Foo Bar').snakeCase();
// _.startCase
result = <string>_.startCase('--foo-bar');
result = <string>_('--foo-bar').startCase();
// _.startsWith
result = <boolean>_.startsWith('abc', 'a');
result = <boolean>_.startsWith('abc', 'a', 1);
result = <boolean>_('abc').startsWith('a');
result = <boolean>_('abc').startsWith('a', 1);
// _.trim
result = <string>_.trim();
@@ -1706,18 +1848,27 @@ result = <string>_.trimRight('-_-abc-_-', '_-');
result = <string>_('-_-abc-_-').trimRight();
result = <string>_('-_-abc-_-').trimRight('_-');
// _.trunc
result = <string>_.trunc('hi-diddly-ho there, neighborino');
result = <string>_.trunc('hi-diddly-ho there, neighborino', 24);
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' });
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ });
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'omission': ' […]' });
result = <string>_('hi-diddly-ho there, neighborino').trunc();
result = <string>_('hi-diddly-ho there, neighborino').trunc(24);
result = <string>_('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': ' ' });
result = <string>_('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': /,? +/ });
result = <string>_('hi-diddly-ho there, neighborino').trunc({ 'omission': ' […]' });
// _.unescape
result = <string>_.unescape('fred, barney, &amp; pebbles');
result = <string>_('fred, barney, &amp; pebbles').unescape();
// _.words
result = <string[]>_.words('fred, barney, & pebbles');
result = <string[]>_.words('fred, barney, & pebbles', /[^, ]+/g);
result = <string[]>_('fred, barney, & pebbles').words();
result = <string[]>_('fred, barney, & pebbles').words(/[^, ]+/g);
/**********
* Utilities *
+541 -189
View File
@@ -252,7 +252,7 @@ declare module _ {
interface LoDashObjectWrapper<T> extends LoDashWrapperBase<T, LoDashObjectWrapper<T>> { }
interface LoDashArrayWrapper<T> extends LoDashWrapperBase<T[], LoDashArrayWrapper<T>> {
concat(...items: T[]): LoDashArrayWrapper<T>;
concat(...items: Array<T|Array<T>>): LoDashArrayWrapper<T>;
join(seperator?: string): string;
pop(): T;
push(...items: T[]): LoDashArrayWrapper<T>;
@@ -1092,16 +1092,16 @@ declare module _ {
* @param values The values to remove.
* @return array.
**/
pull(
array: Array<any>,
...values: any[]): any[];
pull<T>(
array: Array<T>,
...values: T[]): T[];
/**
* @see _.pull
**/
pull(
array: List<any>,
...values: any[]): any[];
pull<T>(
array: List<T>,
...values: T[]): T[];
}
interface LoDashStatic {
@@ -1141,50 +1141,50 @@ declare module _ {
* @param thisArg The this binding of callback.
* @return A new array of removed elements.
**/
remove(
array: Array<any>,
callback?: ListIterator<any, boolean>,
thisArg?: any): any[];
remove<T>(
array: Array<T>,
callback?: ListIterator<T, boolean>,
thisArg?: any): T[];
/**
* @see _.remove
**/
remove(
array: List<any>,
callback?: ListIterator<any, boolean>,
thisArg?: any): any[];
remove<T>(
array: List<T>,
callback?: ListIterator<T, boolean>,
thisArg?: any): T[];
/**
* @see _.remove
* @param pluckValue _.pluck style callback
**/
remove(
array: Array<any>,
pluckValue?: string): any[];
remove<T>(
array: Array<T>,
pluckValue?: string): T[];
/**
* @see _.remove
* @param pluckValue _.pluck style callback
**/
remove(
array: List<any>,
pluckValue?: string): any[];
remove<T>(
array: List<T>,
pluckValue?: string): T[];
/**
* @see _.remove
* @param whereValue _.where style callback
**/
remove(
array: Array<any>,
wherealue?: Dictionary<any>): any[];
remove<W, T>(
array: Array<T>,
wherealue?: Dictionary<W>): T[];
/**
* @see _.remove
* @param whereValue _.where style callback
**/
remove(
array: List<any>,
wherealue?: Dictionary<any>): any[];
remove<W, T>(
array: List<T>,
wherealue?: Dictionary<W>): T[];
/**
* @see _.remove
@@ -2494,7 +2494,7 @@ declare module _ {
* @see _.fill
*/
fill<TResult>(
value: any,
value: TResult,
start?: number,
end?: number): LoDashArrayWrapper<TResult>;
}
@@ -2504,7 +2504,7 @@ declare module _ {
* @see _.fill
*/
fill<TResult>(
value: any,
value: TResult,
start?: number,
end?: number): LoDashObjectWrapper<List<TResult>>;
}
@@ -4069,21 +4069,21 @@ declare module _ {
**/
pluck<T extends {}>(
collection: Array<T>,
property: string): any[];
property: string|string[]): any[];
/**
* @see _.pluck
**/
pluck<T extends {}>(
collection: List<T>,
property: string): any[];
property: string|string[]): any[];
/**
* @see _.pluck
**/
pluck<T extends {}>(
collection: Dictionary<T>,
property: string): any[];
property: string|string[]): any[];
}
interface LoDashArrayWrapper<T> {
@@ -5997,6 +5997,88 @@ declare module _ {
* Lang *
********/
//_.clone
interface LoDashStatic {
/**
* Creates a clone of value. If isDeep is true nested objects are cloned, otherwise they are assigned by
* reference. If customizer is provided its invoked to produce the cloned values. If customizer returns
* undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up
* to three argument; (value [, index|key, object]).
* Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments
* objects and objects created by constructors other than Object are cloned to plain Object objects. An empty
* object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.
* @param value The value to clone.
* @param isDeep Specify a deep clone.
* @param customizer The function to customize cloning values.
* @param thisArg The this binding of customizer.
* @return Returns the cloned value.
*/
clone<T>(
value: T,
isDeep?: boolean,
customizer?: (value: any) => any,
thisArg?: any): T;
/**
* @see _.clone
*/
clone<T>(
value: T,
customizer?: (value: any) => any,
thisArg?: any): T;
}
interface LoDashWrapper<T> {
/**
* @see _.clone
*/
clone(
isDeep?: boolean,
customizer?: (value: any) => any,
thisArg?: any): T;
/**
* @see _.clone
*/
clone(
customizer?: (value: any) => any,
thisArg?: any): T;
}
interface LoDashArrayWrapper<T> {
/**
* @see _.clone
*/
clone(
isDeep?: boolean,
customizer?: (value: any) => any,
thisArg?: any): T[];
/**
* @see _.clone
*/
clone(
customizer?: (value: any) => any,
thisArg?: any): T[];
}
interface LoDashObjectWrapper<T> {
/**
* @see _.clone
*/
clone(
isDeep?: boolean,
customizer?: (value: any) => any,
thisArg?: any): T;
/**
* @see _.clone
*/
clone(
customizer?: (value: any) => any,
thisArg?: any): T;
}
//_.cloneDeep
interface LoDashStatic {
/**
@@ -6007,13 +6089,13 @@ declare module _ {
* objects and objects created by constructors other than Object are cloned to plain Object objects. An empty
* object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps.
* @param value The value to deep clone.
* @param callback The function to customize cloning values.
* @param customizer The function to customize cloning values.
* @param thisArg The this binding of customizer.
* @return Returns the deep cloned value.
*/
cloneDeep<T>(
value: T,
callback?: (value: any) => any,
customizer?: (value: any) => any,
thisArg?: any): T;
}
@@ -6022,7 +6104,7 @@ declare module _ {
* @see _.cloneDeep
*/
cloneDeep(
callback?: (value: any) => any,
customizer?: (value: any) => any,
thisArg?: any): T;
}
@@ -6031,7 +6113,7 @@ declare module _ {
* @see _.cloneDeep
*/
cloneDeep(
callback?: (value: any) => any,
customizer?: (value: any) => any,
thisArg?: any): T[];
}
@@ -6040,7 +6122,7 @@ declare module _ {
* @see _.cloneDeep
*/
cloneDeep(
callback?: (value: any) => any,
customizer?: (value: any) => any,
thisArg?: any): T;
}
@@ -6080,6 +6162,57 @@ declare module _ {
gte(other: any): boolean;
}
//_.isArguments
interface LoDashStatic {
/**
* Checks if value is classified as an arguments object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
*/
isArguments(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.isArguments
*/
isArguments(): boolean;
}
//_.isArray
interface LoDashStatic {
/**
* Checks if value is classified as an Array object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
**/
isArray(value?: any): boolean;
}
interface LoDashWrapperBase<T,TWrapper> {
/**
* @see _.isArray
*/
isArray(): boolean;
}
//_.isDate
interface LoDashStatic {
/**
* Checks if value is classified as a Date object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
**/
isDate(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.isDate
*/
isDate(): boolean;
}
//_.isEmpty
interface LoDashStatic {
/**
@@ -6098,6 +6231,59 @@ declare module _ {
isEmpty(): boolean;
}
//_.isError
interface LoDashStatic {
/**
* Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError
* object.
* @param value The value to check.
* @return Returns true if value is an error object, else false.
*/
isError(value: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.isError
*/
isError(): boolean;
}
//_.isFinite
interface LoDashStatic {
/**
* Checks if value is a finite primitive number.
* Note: This method is based on Number.isFinite.
* @param value The value to check.
* @return Returns true if value is a finite number, else false.
**/
isFinite(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.isFinite
*/
isFinite(): boolean;
}
//_.isFunction
interface LoDashStatic {
/**
* Checks if value is classified as a Function object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
**/
isFunction(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.isFunction
*/
isFunction(): boolean;
}
//_.isMatch
interface isMatchCustomizer {
(value: any, other: any, indexOrKey?: number|string): boolean;
@@ -6160,6 +6346,58 @@ declare module _ {
isNative(): boolean;
}
//_.isNumber
interface LoDashStatic {
/**
* Checks if value is classified as a Number primitive or object.
* Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
*/
isNumber(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* see _.isNumber
*/
isNumber(): boolean;
}
//_.isRegExp
interface LoDashStatic {
/**
* Checks if value is classified as a RegExp object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
*/
isRegExp(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* see _.isRegExp
*/
isRegExp(): boolean;
}
//_.isString
interface LoDashStatic {
/**
* Checks if value is classified as a String primitive or object.
* @param value The value to check.
* @return Returns true if value is correctly classified, else false.
**/
isString(value?: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* see _.isString
*/
isString(): boolean;
}
//_.isTypedArray
interface LoDashStatic {
/**
@@ -6177,6 +6415,23 @@ declare module _ {
isTypedArray(): boolean;
}
//_.isUndefined
interface LoDashStatic {
/**
* Checks if value is undefined.
* @param value The value to check.
* @return Returns true if value is undefined, else false.
**/
isUndefined(value: any): boolean;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* see _.isUndefined
*/
isUndefined(): boolean;
}
//_.lt
interface LoDashStatic {
/**
@@ -6496,26 +6751,6 @@ declare module _ {
create<TResult extends {}>(properties?: Object): LoDashObjectWrapper<TResult>;
}
//_.clone
interface LoDashStatic {
/**
* Creates a clone of value. If deep is true nested objects will also be cloned, otherwise
* they will be assigned by reference. If a callback is provided it will be executed to produce
* the cloned values. If the callback returns undefined cloning will be handled by the method
* instead. The callback is bound to thisArg and invoked with one argument; (value).
* @param value The value to clone.
* @param deep Specify a deep clone.
* @param callback The function to customize cloning values.
* @param thisArg The this binding of callback.
* @return The cloned value.
**/
clone<T>(
value: T,
deep?: boolean,
callback?: (value: any) => any,
thisArg?: any): T;
}
//_.defaults
interface LoDashStatic {
/**
@@ -6810,13 +7045,12 @@ declare module _ {
//_.has
interface LoDashStatic {
/**
* Checks if the specified object property exists and is a direct property, instead of an
* inherited property.
* @param object The object to check.
* @param property The property to check for.
* @return True if key is a direct property, else false.
* Checks if path is a direct property.
* @param object The object to query.
* @param path The path to check.
* @return True if path is a direct property, else False.
**/
has(object: any, property: string): boolean;
has(object: any, path: string|string[]): boolean;
}
//_.invert
@@ -6829,26 +7063,6 @@ declare module _ {
invert(object: any): any;
}
//_.isArguments
interface LoDashStatic {
/**
* Checks if value is an arguments object.
* @param value The value to check.
* @return True if the value is an arguments object, else false.
**/
isArguments(value?: any): boolean;
}
//_.isArray
interface LoDashStatic {
/**
* Checks if value is an array.
* @param value The value to check.
* @return True if the value is an array, else false.
**/
isArray(value?: any): boolean;
}
//_.isBoolean
interface LoDashStatic {
/**
@@ -6859,16 +7073,6 @@ declare module _ {
isBoolean(value?: any): boolean;
}
//_.isDate
interface LoDashStatic {
/**
* Checks if value is a date.
* @param value The value to check.
* @return True if the value is a date, else false.
**/
isDate(value?: any): boolean;
}
//_.isElement
interface LoDashStatic {
/**
@@ -6879,17 +7083,6 @@ declare module _ {
isElement(value?: any): boolean;
}
//_.isError
interface LoDashStatic {
/**
* Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError,
* or URIError object.
* @param value The value to check.
* @return True if value is an error object, else false.
*/
isError(value: any): boolean;
}
//_.isEqual
interface EqCustomizer {
(value: any, other: any, indexOrKey?: number|string): boolean;
@@ -6970,29 +7163,6 @@ declare module _ {
thisArg?: any): boolean;
}
//_.isFinite
interface LoDashStatic {
/**
* Checks if value is, or can be coerced to, a finite number.
*
* Note: This is not the same as native isFinite which will return true for booleans and empty
* strings. See http://es5.github.io/#x15.1.2.5.
* @param value The value to check.
* @return True if the value is finite, else false.
**/
isFinite(value?: any): boolean;
}
//_.isFunction
interface LoDashStatic {
/**
* Checks if value is a function.
* @param value The value to check.
* @return True if the value is a function, else false.
**/
isFunction(value?: any): boolean;
}
//_.isNull
interface LoDashStatic {
/**
@@ -7003,18 +7173,6 @@ declare module _ {
isNull(value?: any): boolean;
}
//_.isNumber
interface LoDashStatic {
/**
* Checks if value is a number.
*
* Note: NaN is considered a number. See http://es5.github.io/#x8.5.
* @param value The value to check.
* @return True if the value is a number, else false.
**/
isNumber(value?: any): boolean;
}
//_.isObject
interface LoDashStatic {
/**
@@ -7036,36 +7194,6 @@ declare module _ {
isPlainObject(value?: any): boolean;
}
//_.isRegExp
interface LoDashStatic {
/**
* Checks if value is a regular expression.
* @param value The value to check.
* @return True if the value is a regular expression, else false.
**/
isRegExp(value?: any): boolean;
}
//_.isString
interface LoDashStatic {
/**
* Checks if value is a string.
* @param value The value to check.
* @return True if the value is a string, else false.
**/
isString(value?: any): boolean;
}
//_.isUndefined
interface LoDashStatic {
/**
* Checks if value is undefined.
* @param value The value to check.
* @return True if the value is undefined, else false.
**/
isUndefined(value?: any): boolean;
}
//_.keys
interface LoDashStatic {
/**
@@ -7438,11 +7566,62 @@ declare module _ {
* String *
**********/
//_.camelCase
interface LoDashStatic {
/**
* Converts string to camel case.
* @param string The string to convert.
* @return Returns the camel cased string.
*/
camelCase(string?: string): string;
}
interface LoDashWrapper<T> {
/**
* @see _.camelCase
*/
camelCase(): string;
}
interface LoDashStatic {
camelCase(str?: string): string;
capitalize(str?: string): string;
deburr(str?: string): string;
endsWith(str?: string, target?: string, position?: number): boolean;
}
//_.deburr
interface LoDashStatic {
/**
* Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining
* diacritical marks.
* @param string The string to deburr.
* @return Returns the deburred string.
*/
deburr(string?: string): string;
}
interface LoDashWrapper<T> {
/**
* @see _.deburr
*/
deburr(): string;
}
//_.endsWith
interface LoDashStatic {
/**
* Checks if string ends with the given target string.
* @param string The string to search.
* @param target The string to search for.
* @param position The position to search from.
* @return Returns true if string ends with target, else false.
*/
endsWith(string?: string, target?: string, position?: number): boolean;
}
interface LoDashWrapper<T> {
/**
* @see _.endsWith
*/
endsWith(target?: string, position?: number): boolean;
}
// _.escape
@@ -7480,11 +7659,82 @@ declare module _ {
escapeRegExp(): string;
}
//_.kebabCase
interface LoDashStatic {
kebabCase(str?: string): string;
pad(str?: string, length?: number, chars?: string): string;
padLeft(str?: string, length?: number, chars?: string): string;
padRight(str?: string, length?: number, chars?: string): string;
/**
* Converts string to kebab case.
* @param string The string to convert.
* @return Returns the kebab cased string.
*/
kebabCase(string?: string): string;
}
interface LoDashWrapper<T> {
/**
* @see _.kebabCase
*/
kebabCase(): string;
}
interface LoDashStatic {
/**
*
* @param string The string to pad.
* @param length The padding length.
* @param chars The string used as padding.
* @return Returns the padded string.
*/
pad(string?: string, length?: number, chars?: string): string;
}
//_.pad
interface LoDashWrapper<T> {
/**
* @see _.pad
*/
pad(length?: number, chars?: string): string;
}
//_.padLeft
interface LoDashStatic {
/**
* Pads string on the left side if its shorter than length. Padding characters are truncated if they exceed
* length.
* @param string The string to pad.
* @param length The padding length.
* @param chars The string used as padding.
* @return Returns the padded string.
*/
padLeft(string?: string, length?: number, chars?: string): string;
}
//_.padLeft
interface LoDashWrapper<T> {
/**
* @see _.padLeft
*/
padLeft(length?: number, chars?: string): string;
}
//_.padRight
interface LoDashStatic {
/**
* Pads string on the right side if its shorter than length. Padding characters are truncated if they exceed
* length.
* @param string The string to pad.
* @param length The padding length.
* @param chars The string used as padding.
* @return Returns the padded string.
*/
padRight(string?: string, length?: number, chars?: string): string;
}
//_.padRight
interface LoDashWrapper<T> {
/**
* @see _.padRight
*/
padRight(length?: number, chars?: string): string;
}
//_.parseInt
@@ -7507,8 +7757,22 @@ declare module _ {
parseInt(radix?: number): number;
}
//_.repeat
interface LoDashStatic {
repeat(str?: string, n?: number): string;
/**
* Repeats the given string n times.
* @param string The string to repeat.
* @param n The number of times to repeat the string.
* @return Returns the repeated string.
*/
repeat(string?: string, n?: number): string;
}
interface LoDashWrapper<T> {
/**
* @see _.repeat
*/
repeat(n?: number): string;
}
//_.snakeCase
@@ -7528,9 +7792,40 @@ declare module _ {
snakeCase(): string;
}
//_.startCase
interface LoDashStatic {
startCase(str?: string): string;
startsWith(str?: string, target?: string, position?: number): boolean;
/**
* Converts string to start case.
* @param string The string to convert.
* @return Returns the start cased string.
*/
startCase(string?: string): string;
}
interface LoDashWrapper<T> {
/**
* @see _.startCase
*/
startCase(): string;
}
//_.startsWith
interface LoDashStatic {
/**
* Checks if string starts with the given target string.
* @param string The string to search.
* @param target The string to search for.
* @param position The position to search from.
* @return Returns true if string starts with target, else false.
*/
startsWith(string?: string, target?: string, position?: number): boolean;
}
interface LoDashWrapper<T> {
/**
* @see _.startsWith
*/
startsWith(target?: string, position?: number): boolean;
}
//_.trim
@@ -7587,9 +7882,32 @@ declare module _ {
trimRight(chars?: string): string;
}
//_.trunc
interface TruncOptions {
/** The maximum string length. */
length?: number;
/** The string to indicate text is omitted. */
omission?: string;
/** The separator pattern to truncate to. */
separator?: string|RegExp;
}
interface LoDashStatic {
trunc(str?: string, len?: number): string;
trunc(str?: string, options?: { length?: number; omission?: string; separator?: string|RegExp }): string;
/**
* Truncates string if its longer than the given maximum string length. The last characters of the truncated
* string are replaced with the omission string which defaults to "…".
* @param string The string to truncate.
* @param options The options object or maximum string length.
* @return Returns the truncated string.
*/
trunc(string?: string, options?: TruncOptions|number): string;
}
interface LoDashWrapper<T> {
/**
* @see _.trunc
*/
trunc(options?: TruncOptions|number): string;
}
//_.unescape
@@ -7610,13 +7928,45 @@ declare module _ {
unescape(): string;
}
//_.words
interface LoDashStatic {
words(str?: string, pattern?: string|RegExp): string[];
/**
* Splits string into an array of its words.
* @param string The string to inspect.
* @param pattern The pattern to match words.
* @return Returns the words of string.
*/
words(string?: string, pattern?: string|RegExp): string[];
}
/*************
* Utilities *
*************/
interface LoDashWrapper<T> {
/**
* @see _.words
*/
words(pattern?: string|RegExp): string[];
}
/***********
* Utility *
***********/
//_.attempt
interface LoDashStatic {
/**
* Attempts to invoke func, returning either the result or the caught error object. Any additional arguments
* are provided to func when its invoked.
* @param func The function to attempt.
* @return Returns the func result or error object.
*/
attempt<TResult>(func: (...args: any[]) => TResult): TResult|Error;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.attempt
*/
attempt<TResult>(): TResult|Error;
}
//_.identity
interface LoDashStatic {
@@ -7822,12 +8172,14 @@ declare module _ {
/**
* Resolves the value of property on object. If property is a function it will be invoked with
* the this binding of object and its result returned, else the property value is returned. If
* object is falsey then undefined is returned.
* @param object The object to inspect.
* @param property The property to get the value of.
* object is false then undefined is returned.
* @param object The object to query.
* @param path The path of the property to resolve.
* @param defaultValue The value returned if the resolved value is undefined.
* @return The resolved value.
**/
result(object: any, property: string): any;
result<T>(object: any, path: string|string[], defaultValue?: T): T;
}
//_.runInContext
+69
View File
@@ -0,0 +1,69 @@
import mailparser_mod = require("mailparser");
import MailParser = mailparser_mod.MailParser;
import ParsedMail = mailparser_mod.ParsedMail;
var mailparser = new MailParser();
mailparser.on("headers", function(headers){
console.log(headers.received);
});
mailparser.on("end", function(mail){
mail; // object structure for parsed e-mail
});
// Decode a simple e-mail
// This example decodes an e-mail from a string
var email = "From: 'Sender Name' <sender@example.com>\r\n"+
"To: 'Receiver Name' <receiver@example.com>\r\n"+
"Subject: Hello world!\r\n"+
"\r\n"+
"How are you today?";
// setup an event listener when the parsing finishes
mailparser.on("end", function(mail_object){
console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}]
console.log("Subject:", mail_object.subject); // Hello world!
console.log("Text body:", mail_object.text); // How are you today?
});
// send the email source to the parser
mailparser.write(email);
mailparser.end();
// Pipe file to MailParser
// This example pipes a readableStream file to MailParser
mailparser = new MailParser();
import fs = require("fs");
mailparser.on("end", function(mail_object){
console.log("Subject:", mail_object.subject);
});
fs.createReadStream("email.eml").pipe(mailparser);
// Attachments
mailparser.on("end", function(mail_object : ParsedMail){
mail_object.attachments.forEach(function(attachment){
console.log(attachment.fileName);
});
});
// Attachment streaming
var mp = new MailParser({
streamAttachments: true
})
mp.on("attachment", function(attachment, mail){
var output = fs.createWriteStream(attachment.generatedFileName);
attachment.stream.pipe(output);
});
+86
View File
@@ -0,0 +1,86 @@
// Type definitions for mailparser v0.5.2
// Project: https://www.npmjs.com/package/mailparser
// Definitions by: Peter Snider <https://github.com/psnider/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path='../node/node.d.ts' />
declare module 'mailparser' {
import WritableStream = NodeJS.WritableStream;
import EventEmitter = NodeJS.EventEmitter;
interface Options {
debug?: boolean; // if set to true print all incoming lines to console
streamAttachments?: boolean; // if set to true, stream attachments instead of including them
unescapeSMTP?: boolean; // if set to true replace double dots in the beginning of the file
defaultCharset?: string; // the default charset for text/plain and text/html content, if not set reverts to Latin-1
showAttachmentLinks?: boolean; // if set to true, show inlined attachment links <a href="cid:...">filename</a>
}
interface EmailAddress {
address: string;
name: string;
}
interface Attachment {
contentType: string;
fileName: string;
contentDisposition: string; // e.g. 'attachment'
contentId: string; // e.g. '5.1321281380971@localhost'
transferEncoding: string; // e.g. 'base64'
length: number; // length of the attachment in bytes
generatedFileName: string; // e.g. 'image.png'
checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b'
content: Buffer; // possibly a SlowBuffer
}
// emitted with the 'end' event
interface ParsedMail {
headers: any; // unprocessed headers in the form of - {key: value} - if there were multiple fields with the same key then the value is an array
from: EmailAddress[]; // should be only one though)
to: EmailAddress[];
cc?: EmailAddress[];
bcc?: EmailAddress[];
subject: string; // the subject line
references?: string[]; // an array of reference message id values (not set if no reference values present)
inReplyTo?: string[]; // an array of In-Reply-To message id values (not set if no in-reply-to values present)
priority?: string; // priority of the e-mail, always one of the following: normal (default), high, low
text: string; // text body
html: string; // html body
date?: Date; // If date could not be resolved or is not found this field is not set. Check the original date string from headers.date
attachments?: Attachment[];
}
class MailParser implements WritableStream {
constructor(options? : Options);
on(event : string, callback : (any : any) => void) : void;
// from WritableStream
writable: boolean;
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
// from EventEmitter
static listenerCount(emitter: EventEmitter, event: string): number;
addListener(event: string, listener: Function): EventEmitter;
on(event: string, listener: Function): EventEmitter;
once(event: string, listener: Function): EventEmitter;
removeListener(event: string, listener: Function): EventEmitter;
removeAllListeners(event?: string): EventEmitter;
setMaxListeners(n: number): void;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
}
}
+1 -1
View File
@@ -179,7 +179,7 @@ module Marionette.Tests {
}
}
class MyCollectionView extends Marionette.CollectionView<MyModel> {
class MyCollectionView extends Marionette.CollectionView<MyModel, MyView> {
constructor() {
this.childView = MyView;
this.childEvents = {
+59 -47
View File
@@ -9,49 +9,49 @@
declare module Backbone {
// Backbone.BabySitter
class ChildViewContainer<TModel extends Backbone.Model> {
class ChildViewContainer<TView extends View<Backbone.Model>> {
constructor(initialViews?: any[]);
add(view: View<TModel>, customIndex?: number): void;
findByModel(model: TModel): View<TModel>;
findByModelCid(modelCid: string): View<TModel>;
findByCustom(index: number): View<TModel>;
findByIndex(index: number): View<TModel>;
findByCid(cid: string): View<TModel>;
remove(view: View<TModel>): void;
add(view: TView, customIndex?: number): void;
findByModel<TModel extends Backbone.Model>(model: TModel): TView;
findByModelCid(modelCid: string): TView;
findByCustom(index: number): TView;
findByIndex(index: number): TView;
findByCid(cid: string): TView;
remove(view: TView): void;
call(method: any): void;
apply(method: any, args?: any[]): void;
//mixins from Collection (copied from Backbone's Collection declaration)
all(iterator: (element: View<TModel>, index: number) => boolean, context?: any): boolean;
any(iterator: (element: View<TModel>, index: number) => boolean, context?: any): boolean;
all(iterator: (element: TView, index: number) => boolean, context?: any): boolean;
any(iterator: (element: TView, index: number) => boolean, context?: any): boolean;
contains(value: any): boolean;
detect(iterator: (item: any) => boolean, context?: any): any;
each(iterator: (element: View<TModel>, index: number, list?: any) => void, context?: any): any;
every(iterator: (element: View<TModel>, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: View<TModel>, index: number) => boolean, context?: any): View<TModel>[];
find(iterator: (element: View<TModel>, index: number) => boolean, context?: any): View<TModel>;
first(): View<TModel>;
forEach(iterator: (element: View<TModel>, index: number, list?: any) => void, context?: any): void;
each(iterator: (element: TView, index: number, list?: any) => void, context?: any): any;
every(iterator: (element: TView, index: number) => boolean, context?: any): boolean;
filter(iterator: (element: TView, index: number) => boolean, context?: any): TView[];
find(iterator: (element: TView, index: number) => boolean, context?: any): TView;
first(): TView;
forEach(iterator: (element: TView, index: number, list?: any) => void, context?: any): void;
include(value: any): boolean;
initial(): View<TModel>;
initial(n: number): View<TModel>[];
initial(): TView;
initial(n: number): TView[];
invoke(methodName: string, args?: any[]): any;
isEmpty(object: any): boolean;
last(): View<TModel>;
last(n: number): View<TModel>[];
lastIndexOf(element: View<TModel>, fromIndex?: number): number;
map<U>(iterator: (element: View<TModel>, index: number, context?: any) => U, context?: any): U[];
last(): TView;
last(n: number): TView[];
lastIndexOf(element: TView, fromIndex?: number): number;
map<U>(iterator: (element: TView, index: number, context?: any) => U, context?: any): U[];
pluck(attribute: string): any[];
reject(iterator: (element: View<TModel>, index: number) => boolean, context?: any): View<TModel>[];
rest(): View<TModel>;
rest(n: number): View<TModel>[];
reject(iterator: (element: TView, index: number) => boolean, context?: any): TView[];
rest(): TView;
rest(n: number): TView[];
select(iterator: any, context?: any): any[];
some(iterator: (element: View<TModel>, index: number) => boolean, context?: any): boolean;
some(iterator: (element: TView, index: number) => boolean, context?: any): boolean;
toArray(): any[];
without(...values: any[]): View<TModel>[];
without(...values: any[]): TView[];
}
// Backbone.Wreqr
@@ -856,7 +856,7 @@ declare module Marionette {
* DOM. This behavior can be disabled by specifying {sort: false} on
* initialize.
*/
class CollectionView<TModel extends Backbone.Model> extends View<TModel> {
class CollectionView<TModel extends Backbone.Model, TView extends View<Backbone.Model>> extends View<TModel> {
constructor(options?: CollectionViewOptions<TModel>);
/**
@@ -864,7 +864,7 @@ declare module Marionette {
* Backbone view object definition, not an instance. It can be any
* Backbone.View or be derived from Marionette.ItemView
*/
childView: any;
childView: new (...args:any[]) => TView;
/**
* There may be scenarios where you need to pass data from your parent
@@ -918,14 +918,14 @@ declare module Marionette {
* collection view, iterate them, find them by a given indexer such as the
* view's model or collection, and more.
*/
children: Backbone.ChildViewContainer<TModel>;
children: Backbone.ChildViewContainer<TView>;
/**
* The render method of the collection view is responsible for rendering the
* entire collection. It loops through each of the children in the collection
* and renders them individually as an childView.
*/
render(): CollectionView<TModel>;
render(): CollectionView<TModel, TView>;
/**
* The addChild method is responsible for rendering the childViews and
@@ -933,9 +933,9 @@ declare module Marionette {
* responsible for triggering the events per ChildView. In most cases you
* should not override this method.
*/
addChild(item: any, ChildView: Backbone.View<TModel>, index: Number): void;
addChild(item: any, ChildView: TView, index: Number): void;
renderChildView(view: Backbone.View<TModel>, index: Number): void;
renderChildView(view: TView, index: Number): void;
/**
* When a custom view instance needs to be created for the childView that
@@ -943,13 +943,13 @@ declare module Marionette {
* takes three parameters and returns a view instance to be used as the
* child view.
*/
buildChildView(child: any, ItemViewType: any, itemViewOptions: any): View<TModel>;
buildChildView(child: any, ItemViewType: any, itemViewOptions: any): TView;
/**
* Remove the child view and destroy it. This function also updates the indices of
* later views in the collection in order to keep the children in sync with the collection.
*/
removeChildView(view: any): void;
removeChildView(view: TView): void;
/**
* Determines if the view is empty. If you want to control when the empty
@@ -988,14 +988,14 @@ declare module Marionette {
* a collection and displaying the sorted list in the correct order on the
* screen.
*/
attachHtml(collectionView: CollectionView<TModel>, childView: Backbone.View<TModel>, index: number): void;
attachHtml(collectionView: CollectionView<TModel, TView>, childView: TView, index: number): void;
/**
* The value returned by this method is the ChildView class that will be
* instantiated when a Model needs to be initially rendered. This method
* also gives you the ability to customize per Model ChildViews.
*/
getChildView(item: TModel): any;
getChildView<M extends Backbone.Model>(item: M): new (...args:any[]) => TView;
/**
* If you need the emptyView's class chosen dynamically, specify
@@ -1020,27 +1020,27 @@ declare module Marionette {
* instance is about to be added to the collection view. It provides
* access to the view instance for the child that was added.
*/
onBeforeAddChild(view: any): void;
onBeforeAddChild(childView: TView): void;
/**
* This callback function allows you to know when a child / child view
* instance has been added to the collection view. It provides access to
* the view instance for the child that was added.
*/
onAddChild(childView: any): void;
onAddChild(childView: TView): void;
/**
* This callback function allows you to know when a childView instance is
* about to be removed from the collectionView. It provides access to the
* view instance for the child that was removed.
*/
onBeforeRemoveChild(childView: any): void;
onBeforeRemoveChild(childView: TView): void;
/**
* This callback function allows you to know when a child / childView
* instance has been deleted or removed from the collection.
*/
onRemoveChild(childView: any): void;
onRemoveChild(childView: TView): void;
}
/**
@@ -1049,7 +1049,7 @@ declare module Marionette {
* structure, or for scenarios where a collection needs to be rendered within
* a wrapper template.
*/
class CompositeView<TModel extends Backbone.Model> extends CollectionView<TModel> {
class CompositeView<TModel extends Backbone.Model, TView extends View<Backbone.Model>> extends CollectionView<TModel, TView> {
constructor(options?: CollectionViewOptions<TModel>);
@@ -1058,7 +1058,7 @@ declare module Marionette {
* CompositeView's template is rendered and the childView's templates are
* added to this.
*/
childView: any;
childView: new (...args:any[]) => TView;
/**
* By default the composite view uses the same attachHtml method that the
@@ -1074,7 +1074,7 @@ declare module Marionette {
/**
* Renders the view.
*/
render(): CompositeView<TModel>;
render(): CompositeView<TModel, TView>;
/**
* Invoked before the model has been rendered
@@ -1097,6 +1097,13 @@ declare module Marionette {
onRenderCollection(): void;
}
interface LayoutViewOptions<TModel extends Backbone.Model> extends Backbone.ViewOptions<TModel> {
/**
* The LayoutView takes an additional parameter where you can pass the regions as option on creation.
*/
regions?:any;
}
/**
* A LayoutView is a hybrid of an ItemView and a collection of Region objects.
* They are ideal for rendering application layouts with multiple sub-regions
@@ -1119,7 +1126,12 @@ declare module Marionette {
* A hash that can contain a regions hash that allows you to specify regions per
* LayoutView instance.
*/
constructor(options?: any);
constructor(options?: LayoutViewOptions<TModel>);
/**
* Regions hash or a method returning the regions hash that maps regions/selectors to methods on your View.
**/
regions():any;
/** Adds a region to the layout view. */
addRegion(name: string, definition: any): Region;
@@ -1129,7 +1141,7 @@ declare module Marionette {
*/
addRegions(regions: any): any;
/** Returns a region from the layout view */
/** Returns a region from the layout view */
getRegion(name: string): Region;
/**
@@ -1147,7 +1159,7 @@ declare module Marionette {
* for customized region interactions and business specific
* view logic for better control over single regions.
*/
getRegionManager(): any;
getRegionManager(): RegionManager;
}
interface AppRouterOptions extends Backbone.RouterOptions {
+15
View File
@@ -9,8 +9,12 @@ var strArr: string[];
var args: string[];
var obj: minimist.ParsedArgs;
var opts: Opts;
var arg: any;
opts.string = str;
opts.string = strArr;
opts.boolean = true;
opts.boolean = str;
opts.boolean = strArr;
opts.alias = {
foo: strArr
@@ -21,8 +25,19 @@ opts.default = {
opts.default = {
foo: num
};
opts.unknown = (arg: string) => {
if(/xyz/.test(arg)){
return true;
}
return false;
};
opts.stopEarly = true;
opts['--'] = true;
obj = minimist();
obj = minimist(strArr);
obj = minimist(strArr, opts);
var remainingArgCount = obj._.length;
arg = obj['foo'];
+12 -4
View File
@@ -1,6 +1,6 @@
// Type definitions for minimist 0.0.8
// Type definitions for minimist 1.1.3
// Project: https://github.com/substack/minimist
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Necroskillz <https://github.com/Necroskillz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'minimist' {
@@ -10,18 +10,26 @@ declare module 'minimist' {
export interface Opts {
// a string or array of strings argument names to always treat as strings
// string?: string;
string?: string[];
string?: string|string[];
// a string or array of strings to always treat as booleans
// boolean?: string;
boolean?: string[];
boolean?: boolean|string|string[];
// an object mapping string names to strings or arrays of string argument names to use
// alias?: {[key:string]: string};
alias?: {[key:string]: string[]};
// an object mapping string argument names to default values
default?: {[key:string]: any};
// when true, populate argv._ with everything after the first non-option
stopEarly?: boolean;
// a function which is invoked with a command line parameter not defined in the opts configuration object.
// If the function returns false, the unknown option is not added to argv
unknown?: (arg: string) => boolean;
// when true, populate argv._ with everything before the -- and argv['--'] with everything after the --
'--'?: boolean;
}
export interface ParsedArgs {
[arg: string]: any;
_: string[];
}
}
+2
View File
@@ -467,6 +467,8 @@ declare module moment {
*/
ISO_8601(): void;
defaultFormat: string;
}
}
+2
View File
@@ -459,3 +459,5 @@ moment.locale('en', {
});
console.log(moment.version);
moment.defaultFormat = 'YYYY-MM-DD HH:mm';
@@ -0,0 +1,21 @@
/// <reference path="node-jsfl-runner.d.ts" />
import * as jsfl from 'node-jsfl-runner';
let myJSFL: jsfl.JSFL = {
init: (param: string): void => {
}
}
jsfl.createJSFL(myJSFL, 'fileName.jsfl', ['Hello!'], (err: NodeJS.ErrnoException) => {
});
jsfl.runJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => {
});
jsfl.deleteJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => {
});
+35
View File
@@ -0,0 +1,35 @@
// Type definitions for node-jsfl-runner
// Project: https://www.npmjs.com/package/node-jsfl-runner
// Definitions by: Michael Randolph <https://github.com/mrand01>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "node-jsfl-runner" {
interface JSFL {
init: (...args: any[]) => void;
[index: string]: any;
}
/**
* Creates a JSFL file from a JSFL object
* @param jsfl A valid JSFL object
* @param fileName Path to output JSFL file location
* @param initParams Parameters to pass to JSFL init function
* @param callback Callback
*/
function createJSFL(jsfl: JSFL, fileName: string, initParams: Array<any>, callback: (err: NodeJS.ErrnoException) => void): void;
/**
* Deletes a JSFL file
* @param fileName Path to JSFL file to delete
* @param callback Callback
*/
function deleteJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void;
/**
* Runs a JSFL file
* @param fileName Path to JSFL file to run
* @param callback Callback
*/
function runJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void;
}
+162
View File
@@ -0,0 +1,162 @@
/// <reference path="node-notifier.d.ts" />
'use strict';
import notifier = require('node-notifier');
import * as path from 'path';
notifier.notify({
title: 'My awesome title',
message: 'Hello from node, Mr. User!',
icon: path.join(__dirname, 'coulson.jpg'), // absolute path (not balloons)
sound: true, // Only Notification Center or Windows Toasters
wait: true // wait with callback until user action is taken on notification
}, function (err: any, response: any) {
// response is response from notification
});
notifier.on('click', function (notifierObject: any, options: any) {
// Happens if `wait: true` and user clicks notification
});
notifier.on('timeout', function (notifierObject: any, options: any) {
// Happens if `wait: true` and notification closes
});
const options = { };
import NotificationCenter = require('node-notifier/notifiers/notificationcenter');
new NotificationCenter(options).notify();
import NotifySend = require('node-notifier/notifiers/notifysend');
new NotifySend(options).notify();
import WindowsToaster = require('node-notifier/notifiers/toaster');
new WindowsToaster(options).notify();
import Growl = require('node-notifier/notifiers/growl');
new Growl(options).notify();
import WindowsBalloon = require('node-notifier/notifiers/balloon');
new WindowsBalloon(options).notify();
var nn = require('node-notifier');
new nn.NotificationCenter(options).notify();
new nn.NotifySend(options).notify();
new nn.WindowsToaster(options).notify(options);
new nn.WindowsBalloon(options).notify(options);
new nn.Growl(options).notify(options);
//
// All notification options with their defaults:
//
var NotificationCenter2 = require('node-notifier').NotificationCenter;
var notifier2 = new NotificationCenter2({
withFallback: false, // use Growl if <= 10.8?
customPath: void 0 // Relative path if you want to use your fork of terminal-notifier
});
notifier2.notify({
'title': void 0,
'subtitle': void 0,
'message': void 0,
'sound': false, // Case Sensitive string of sound file (see below)
'icon': 'Terminal Icon', // Set icon? (Absolute path to image)
'contentImage': void 0, // Attach image? (Absolute path)
'open': void 0, // URL to open on click
'wait': false // if wait for notification to end
}, function(error: any, response: any) {
console.log(response);
});
//
// Usage WindowsToaster
//
var WindowsToaster2 = require('node-notifier').WindowsToaster;
var notifier3 = new WindowsToaster2({
withFallback: false, // Fallback to Growl or Balloons?
customPath: void 0 // Relative path if you want to use your fork of toast.exe
});
notifier3.notify({
title: void 0,
message: void 0,
icon: void 0, // absolute path to an icon
sound: false, // true | false.
wait: false, // if wait for notification to end
}, function(error: any, response: any) {
console.log(response);
});
//
// Usage Growl
//
var Growl2 = require('node-notifier').Growl;
import * as fs from 'fs';
var notifier4 = new Growl2({
name: 'Growl Name Used', // Defaults as 'Node'
host: 'localhost',
port: 23053
});
notifier4.notify({
title: 'Foo',
message: 'Hello World',
icon: fs.readFileSync(__dirname + "/coulson.jpg"),
wait: false, // if wait for user interaction
// and other growl options like sticky etc.
sticky: false,
label: void 0,
priority: void 0
});
//
// Usage WindowsBalloon
//
var WindowsBalloon2 = require('node-notifier').WindowsBalloon;
var notifier5 = new WindowsBalloon2({
withFallback: false, // Try Windows 8 and Growl first?
customPath: void 0 // Relative path if you want to use your fork of notifu
});
notifier5.notify({
title: void 0,
message: void 0,
sound: false, // true | false.
time: 5000, // How long to show balloons in ms
wait: false, // if wait for notification to end
}, function(error: any, response: any) {
console.log(response);
});
//
// Usage NotifySend
//
var NotifySend2 = require('node-notifier').NotifySend;
var notifier6 = new NotifySend2();
notifier6.notify({
title: 'Foo',
message: 'Hello World',
icon: __dirname + "/coulson.jpg",
// .. and other notify-send flags:
urgency: void 0,
time: void 0,
category: void 0,
hint: void 0,
});
+167
View File
@@ -0,0 +1,167 @@
// Type definitions for node-notifier
// Project: https://github.com/mikaelbr/node-notifier
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../node/node.d.ts" />
declare module "node-notifier" {
import NotificationCenter = require('node-notifier/notifiers/notificationcenter');
import NotifySend = require("node-notifier/notifiers/notifysend");
import WindowsToaster = require("node-notifier/notifiers/toaster");
import WindowsBalloon = require("node-notifier/notifiers/balloon");
import Growl = require("node-notifier/notifiers/growl");
namespace nodeNotifier {
interface NodeNotifier extends NodeJS.EventEmitter {
notify(notification?: Notification, callback?: NotificationCallback): NodeNotifier;
NotificationCenter: NotificationCenter;
NotifySend: NotifySend;
WindowsToaster: WindowsToaster;
WindowsBalloon: WindowsBalloon;
Growl: Growl;
}
interface Notification {
title?: string;
message?: string;
/** Absolute path (not balloons) */
icon?: string;
/** Only Notification Center or Windows Toasters */
sound?: boolean;
/** Wait with callback until user action is taken on notification */
wait?: boolean;
}
interface NotificationCallback {
(err: any, response: any): any;
}
interface Option {
withFallback?: boolean;
customPath?: string;
}
}
var nodeNotifier: nodeNotifier.NodeNotifier;
export = nodeNotifier;
}
declare module "node-notifier/notifiers/notificationcenter" {
import notifier = require('node-notifier');
class NotificationCenter {
constructor(option?: notifier.Option);
notify(notification?: NotificationCenter.Notification, callback?: notifier.NotificationCallback): NotificationCenter;
}
namespace NotificationCenter {
interface Notification extends notifier.Notification {
subtitle?: string;
/** Attach image? (Absolute path) */
contentImage?: string;
/** URL to open on click */
open?: string;
}
}
export = NotificationCenter;
}
declare module "node-notifier/notifiers/notifysend" {
import notifier = require('node-notifier');
class NotifySend {
constructor(option?: notifier.Option);
notify(notification?: NotifySend.Notification, callback?: notifier.NotificationCallback): NotifySend;
}
namespace NotifySend {
interface Notification {
title?: string;
message?: string;
icon?: string;
/** Specifies the urgency level (low, normal, critical). */
urgency?: string;
/** Specifies the timeout in milliseconds at which to expire the notification */
time?: number;
/** Specifies the notification category */
category?: string;
/** Specifies basic extra data to pass. Valid types are int, double, string and byte. */
hint?: string;
}
}
export = NotifySend;
}
declare module "node-notifier/notifiers/toaster" {
import notifier = require('node-notifier');
class WindowsToaster {
constructor(option?: notifier.Option);
notify(notification?: notifier.Notification, callback?: notifier.NotificationCallback): WindowsToaster;
}
export = WindowsToaster;
}
declare module "node-notifier/notifiers/growl" {
import notifier = require('node-notifier');
class Growl {
constructor(option?: Growl.Option);
notify(notification?: Growl.Notification, callback?: notifier.NotificationCallback): Growl;
}
namespace Growl {
interface Option {
name?: string;
host?: string;
port?: number;
}
interface Notification {
title?: string;
message?: string;
/** Absolute path (not balloons) */
icon?: string;
/** Wait with callback until user action is taken on notification */
wait?: boolean;
/** whether or not to sticky the notification (defaults to false) */
sticky?: boolean;
/** type of notification to use (defaults to the first registered type) */
label: string;
/** the priority of the notification from lowest (-2) to highest (2) */
priority: number;
}
}
export = Growl;
}
declare module "node-notifier/notifiers/balloon" {
import notifier = require('node-notifier');
class WindowsBalloon {
constructor(option?: notifier.Option);
notify(notification?: WindowsBalloon.Notification, callback?: notifier.NotificationCallback): WindowsBalloon;
}
namespace WindowsBalloon {
interface Notification {
title?: string;
message?: string;
/** Only Notification Center or Windows Toasters */
sound?: boolean;
/** How long to show balloons in ms */
time?: number;
/** Wait with callback until user action is taken on notification */
wait?: boolean;
}
}
export = WindowsBalloon;
}
+46
View File
@@ -0,0 +1,46 @@
/// <reference path="../express/express.d.ts" />
/// <reference path="node-slack.d.ts" />
import express = require('express');
import Slack = require('node-slack');
let app = express();
var hook_url: string = 'foo_hook';
var options: Slack.Option = { proxy: '' };
var slack = new Slack(hook_url, options);
slack.send({
text: 'Howdy!',
channel: '#foo',
username: 'Bot'
});
var attachment_array: any[] = [];
slack.send({
text: 'Howdy!',
channel: '#foo',
username: 'Bot',
icon_emoji: 'taco',
attachments: attachment_array,
unfurl_links: true,
link_names: 1
});
app.post('/yesman', function(req, res) {
var reply = slack.respond(req.body, function(hook: any) {
return {
text: 'Good point, ' + hook.user_name,
username: 'Bot'
};
});
res.json(reply);
});
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for node-slack
// Project: https://github.com/xoxco/node-slack
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../request/request.d.ts" />
declare module "node-slack" {
import request = require('request');
class Slack {
constructor(hookUrl: string, option?: Slack.Option);
send(message: Slack.Message): any; //TODO: Here comes deferred's promise as a return type
send(message: Slack.Message, callback: Slack.SendCallback): request.Request;
respond(query: Slack.Query): Slack.TextResponse;
respond(query: Slack.Query, callback: Slack.ResponseCallback): Slack.TextResponse;
}
namespace Slack {
interface Option {
proxy: string;
}
interface Message {
text: string;
channel?: string;
username?: string;
icon_emoji?: string;
attachments?: any[];
unfurl_links?: boolean;
link_names?: number;
}
interface SendCallback {
(err: any, body: any): any;
}
interface Query {
token?: string;
team_id?: string;
channel_id?: string;
channel_name?: string;
timestamp?: number;
user_id?: string;
user_name?: string;
text: string;
}
interface TextResponse {
text: string;
}
interface ResponseCallback {
(err: any, query: Query): any;
}
}
export = Slack;
}
+29
View File
@@ -0,0 +1,29 @@
/// <reference path="oblo-util.d.ts" />
util.debug = false;
util.log('Log message');
util.error('Error message');
util.clip(0, 100, -15);
util.square(3);
util.replicate(10, 'x');
util.pad(' ', 10, 'short');
util.padZero(4, 247);
util.addslashes('\\"\'');
util.showJSON({name: 'Clyde', color: 'orange'}, ' ', 7);
util.showTime(new Date());
util.showDate(new Date());
util.readDate('15-10-2004');
util.setAttr($('#someElement'), 'attrName', false);
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for oblo-util v0.6.4
// Project: https://github.com/Oblosys/oblo-util
// Definitions by: Martijn Schrage <https://github.com/Oblosys/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface ObloUtilStatic {
debug : boolean;
log(...args: any[]) : void;
error(...args: any[]) : void;
clip(min : number, max : number, x : number) : number;
square(x : number) : number;
replicate<X>(n : number, x : X) : X[];
pad(c : string, l : number, str : any) : string;
padZero(l : number, n : number) : string;
addslashes(str : string) : string;
showJSON(json : any, indentStr? : string, maxDepth? : number) : string;
showTime(date : Date) : string;
showDate(date : Date) : string;
readDate(dateStr : string) : Date;
setAttr($elt : JQuery, attrName : string, isSet : boolean) : void;
}
declare var util: ObloUtilStatic;
declare module "oblo-util" {
export = util;
}
+107
View File
@@ -0,0 +1,107 @@
/// <reference path="../requirejs/require.d.ts" />
/// <reference path="orchestrator.d.ts" />
'use strict';
import Orchestrator = require('orchestrator');
var orchestrator = new Orchestrator();
// API:
//
// orchestrator.add(name[, deps][, function]);
//
orchestrator.add('thing1', function() {
// do stuff
});
orchestrator.add('thing2', function() {
// do stuff
});
orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() {
// Do stuff
});
orchestrator.add('thing2', function(callback: any){
var err: any = null;
// do stuff
callback(err);
});
var Q = require('q');
orchestrator.add('thing3', function(){
var deferred = Q.defer();
// do async stuff
setTimeout(function () {
deferred.resolve();
}, 1);
return deferred.promise;
});
//TODO: map-stream currently not on DefinitelyTyped
//var map = require('map-stream');
//
//orchestrator.add('thing4', function(){
// var stream = map(function (args, cb) {
// cb(null, args);
// });
// // do stream stuff
// return stream;
//});
//
// orchestrator.hasTask(name);
//
orchestrator.hasTask('thing1');
//
// orchestrator.start(tasks...[, cb]);
//
orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err: any) {
// all done
});
orchestrator.start(['thing1','thing2'], ['thing3','thing4']);
//
// orchestrator.stop()
//
orchestrator.stop();
//
// orchestrator.on(event, cb);
//
orchestrator.on('task_start', function (e) {
var message: string = e.message;
var task: string = e.task;
var err: any = e.err;
});
orchestrator.on('task_stop', function (e) {
var message: string = e.message;
var task: string = e.task;
var duration: number = e.duration;
});
//
// orchestrator.onAll(cb);
//
orchestrator.onAll(function (e) {
var message: string = e.message;
var task: string = e.task;
var err: any = e.err;
var src: string = e.src;
});
+127
View File
@@ -0,0 +1,127 @@
// Type definitions for Orchestrator
// Project: https://github.com/orchestrator/orchestrator
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../q/Q.d.ts" />
declare type Strings = string|string[];
declare module "orchestrator" {
class Orchestrator {
add: Orchestrator.AddMethod;
/**
* Have you defined a task with this name?
* @param name The task name to query
*/
hasTask(name: string): boolean;
start: Orchestrator.StartMethod;
stop(): void;
/**
* Listen to orchestrator internals
* @param event Event name to listen to:
* <ul>
* <li>start: from start() method, shows you the task sequence
* <li>stop: from stop() method, the queue finished successfully
* <li>err: from stop() method, the queue was aborted due to a task error
* <li>task_start: from _runTask() method, task was started
* <li>task_stop: from _runTask() method, task completed successfully
* <li>task_err: from _runTask() method, task errored
* <li>task_not_found: from start() method, you're trying to start a task that doesn't exist
* <li>task_recursion: from start() method, there are recursive dependencies in your task list
* </ul>
* @param cb Passes single argument: e: event details
*/
on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator;
/**
* Listen to all orchestrator events from one callback
* @param cb Passes single argument: e: event details
*/
onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void;
}
namespace Orchestrator {
interface AddMethodCallback {
/**
* Accept a callback
* @param callback
*/
(callback?: Function): any;
/**
* Return a promise
*/
(): Q.Promise<any>;
/**
* Return a stream: (task is marked complete when stream ends)
*/
(): any; //TODO: stream type should be here e.g. map-stream
}
/**
* Define a task
*/
interface AddMethod {
/**
* Define a task
* @param name The name of the task.
* @param deps An array of task names to be executed and completed before your task will run.
* @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete:
* <ul>
* <li>Take in a callback</li>
* <li>Return a stream or a promise</li>
* </ul>
*/
(name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator;
/**
* Define a task
* @param name The name of the task.
* @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete:
* <ul>
* <li>Take in a callback</li>
* <li>Return a stream or a promise</li>
* </ul>
*/
(name: string, fn?: AddMethodCallback|Function): Orchestrator;
}
/**
* Start running the tasks
*/
interface StartMethod {
/**
* Start running the tasks
* @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments.
* @param cb Callback to call after run completed.
*/
(tasks: Strings, cb?: (error?: any) => any): Orchestrator;
/**
* Start running the tasks
* @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments.
* @param cb Callback to call after run completed.
*/
(...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator;
//TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument...
(task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator;
(task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator;
}
interface OnCallbackEvent {
message: string;
task: string;
err: any;
duration?: number;
}
interface OnAllCallbackEvent extends OnCallbackEvent {
src: string;
}
}
export = Orchestrator;
}
+1 -1
View File
@@ -857,7 +857,7 @@ declare namespace Parse {
function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void;
function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void;
function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void;
function httpRequest<T>(options: HTTPOptions): Promise<HttpResponse>;
function httpRequest(options: HTTPOptions): Promise<HttpResponse>;
function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse;
function run<T>(name: string, data?: any, options?: SuccessFailureOptions): Promise<T>;
function useMasterKey(): void;
+31 -31
View File
@@ -15,36 +15,36 @@ interface IResolver {
purge(options?: {topic?: string, binding?: string, compact?: boolean}): void;
}
interface ICallback {
(data: any, envelope: IEnvelope): void
interface ICallback<T> {
(data: T, envelope: IEnvelope<T>): void
}
interface ISubscriptionDefinition {
interface ISubscriptionDefinition<T> {
channel: string;
topic: string;
callback: ICallback;
callback: ICallback<T>;
// after and before lack documentation
constraint(predicateFn: (data: any, envelope: IEnvelope) => boolean): ISubscriptionDefinition;
constraints(predicateFns: ((data: any, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition;
context(theContext: any): ISubscriptionDefinition;
debounce(interval: number): ISubscriptionDefinition;
defer(): ISubscriptionDefinition;
delay(waitTime: number): ISubscriptionDefinition;
disposeAfter(maxCalls: number): ISubscriptionDefinition;
distinct(): ISubscriptionDefinition;
distinctUntilChanged(): ISubscriptionDefinition;
logError(): ISubscriptionDefinition;
once(): ISubscriptionDefinition;
throttle(interval: number): ISubscriptionDefinition;
subscribe(callback: ICallback): ISubscriptionDefinition;
constraint(predicateFn: (data: T, envelope: IEnvelope<T>) => boolean): ISubscriptionDefinition<T>;
constraints(predicateFns: ((data: T, envelope: IEnvelope<T>) => boolean)[]): ISubscriptionDefinition<T>;
context(theContext: any): ISubscriptionDefinition<T>;
debounce(interval: number): ISubscriptionDefinition<T>;
defer(): ISubscriptionDefinition<T>;
delay(waitTime: number): ISubscriptionDefinition<T>;
disposeAfter(maxCalls: number): ISubscriptionDefinition<T>;
distinct(): ISubscriptionDefinition<T>;
distinctUntilChanged(): ISubscriptionDefinition<T>;
logError(): ISubscriptionDefinition<T>;
once(): ISubscriptionDefinition<T>;
throttle(interval: number): ISubscriptionDefinition<T>;
subscribe(callback: ICallback<T>): ISubscriptionDefinition<T>;
unsubscribe(): void;
}
interface IEnvelope {
interface IEnvelope<T> {
topic: string;
data?: any;
data?: T;
/*Uses DEFAULT_CHANNEL if no channel is provided*/
channel?: string;
@@ -53,10 +53,10 @@ interface IEnvelope {
}
interface IChannelDefinition {
subscribe(topic: string, callback: ICallback): ISubscriptionDefinition;
interface IChannelDefinition<T> {
subscribe(topic: string, callback: ICallback<T>): ISubscriptionDefinition<T>;
publish(topic: string, data?: any): void;
publish(topic: string, data?: T): void;
channel: string;
}
@@ -73,24 +73,24 @@ interface IDestinationArg {
interface IPostal {
subscriptions: {};
wiretaps: ICallback[];
wiretaps: ICallback<any>[];
addWireTap(callback: ICallback): () => void;
addWireTap(callback: ICallback<any>): () => void;
channel(name?: string): IChannelDefinition;
channel<T>(name?: string): IChannelDefinition<T>;
getSubscribersFor(): ISubscriptionDefinition[];
getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[];
getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[];
getSubscribersFor(): ISubscriptionDefinition<any>[];
getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition<any>[];
getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition<any>) => boolean): ISubscriptionDefinition<any>[];
linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void;
publish(envelope: IEnvelope): void;
publish(envelope: IEnvelope<any>): void;
reset(): void;
subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition;
unsubscribe(sub: ISubscriptionDefinition): void;
subscribe(options: {channel?: string, topic: string, callback: ICallback<any>}): ISubscriptionDefinition<any>;
unsubscribe(sub: ISubscriptionDefinition<any>): void;
unsubscribeFor(): void;
unsubscribeFor(options: {channel?: string, topic?: string, context?: any}): void;

Some files were not shown because too many files have changed in this diff Show More