Merge branch 'master' of https://github.com/borisyankov/DefinitelyTyped into jqueryui-buttonoptions

This commit is contained in:
error
2015-09-11 13:23:30 -05:00
117 changed files with 30082 additions and 3771 deletions
+3
View File
@@ -5,6 +5,9 @@
/// <reference path="../angularjs/angular.d.ts" />
// Support for AMD require
declare module 'angular-bootstrap' {}
declare module angular.ui.bootstrap {
interface IAccordionConfig {
@@ -158,7 +158,9 @@ class UrlLocatorTestService implements IUrlLocatorTestService {
private stateServiceTest() {
this.$state.go("myState");
this.$state.go(this.$state.current);
this.$state.transitionTo("myState");
this.$state.transitionTo(this.$state.current);
if (this.$state.includes("myState") === true) {
//
}
+3
View File
@@ -228,8 +228,11 @@ declare module angular.ui {
* @param options Options object.
*/
go(to: string, params?: {}, options?: IStateOptions): angular.IPromise<any>;
go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise<any>;
transitionTo(state: string, params?: {}, updateLocation?: boolean): void;
transitionTo(state: IState, params?: {}, updateLocation?: boolean): void;
transitionTo(state: string, params?: {}, options?: IStateOptions): void;
transitionTo(state: IState, params?: {}, options?: IStateOptions): void;
includes(state: string, params?: {}): boolean;
is(state:string, params?: {}): boolean;
is(state: IState, params?: {}): boolean;
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -16,7 +16,7 @@ class Cmp {
Cmp.annotations = [
Component({
selector: 'cmp',
injectables: [Service, bind(Service2).toValue(null)]
bindings: [Service, bind(Service2).toValue(null)]
}),
View({
template: '{{greeting}} world!',
@@ -27,9 +27,9 @@ Cmp.annotations = [
properties: [
'text: tooltip'
],
hostListeners: {
'onmouseenter': 'onMouseEnter()',
'onmouseleave': 'onMouseLeave()'
host: {
'(onmouseenter)': 'onMouseEnter()',
'(onmouseleave)': 'onMouseLeave()'
}
})
];
+6646 -354
View File
File diff suppressed because it is too large Load Diff
+1007
View File
File diff suppressed because it is too large Load Diff
+1007
View File
File diff suppressed because it is too large Load Diff
+9 -9
View File
@@ -81,7 +81,7 @@ declare module ngRouter {
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
config(definitions: Array<RouteDefinition>): Promise<any>;
/**
@@ -135,7 +135,7 @@ declare module ngRouter {
* 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;
generate(linkParams: Array<any>): Instruction;
}
class RootRouter extends Router {
@@ -258,7 +258,7 @@ declare module ngRouter {
* 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;
generate(linkParams: Array<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
@@ -343,7 +343,7 @@ declare module ngRouter {
*/
class Pipeline {
steps: List<Function>;
steps: Array<Function>;
process(instruction: Instruction): Promise<any>;
}
@@ -547,7 +547,7 @@ declare module ngRouter {
urlPath: string;
urlParams: List<string>;
urlParams: Array<string>;
params: StringMap<string, any>;
@@ -568,7 +568,7 @@ declare module ngRouter {
child: Url;
auxiliary: List<Url>;
auxiliary: Array<Url>;
params: StringMap<string, any>;
@@ -594,9 +594,9 @@ declare module ngRouter {
}
const routerDirectives : List<any> ;
const routerDirectives : Array<any> ;
var routerInjectables : List<any> ;
var routerInjectables : Array<any> ;
class Route implements RouteDefinition {
@@ -669,7 +669,7 @@ declare module ngRouter {
const ROUTE_DATA : OpaqueToken ;
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
var RouteConfig : (configs: Array<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
+9 -9
View File
@@ -81,7 +81,7 @@ declare module ngRouter {
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
config(definitions: Array<RouteDefinition>): Promise<any>;
/**
@@ -135,7 +135,7 @@ declare module ngRouter {
* 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;
generate(linkParams: Array<any>): Instruction;
}
class RootRouter extends Router {
@@ -258,7 +258,7 @@ declare module ngRouter {
* 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;
generate(linkParams: Array<any>, parentComponent: any): Instruction;
}
class LocationStrategy {
@@ -343,7 +343,7 @@ declare module ngRouter {
*/
class Pipeline {
steps: List<Function>;
steps: Array<Function>;
process(instruction: Instruction): Promise<any>;
}
@@ -547,7 +547,7 @@ declare module ngRouter {
urlPath: string;
urlParams: List<string>;
urlParams: Array<string>;
params: StringMap<string, any>;
@@ -568,7 +568,7 @@ declare module ngRouter {
child: Url;
auxiliary: List<Url>;
auxiliary: Array<Url>;
params: StringMap<string, any>;
@@ -596,9 +596,9 @@ declare module ngRouter {
const ROUTE_DATA : OpaqueToken ;
const ROUTER_DIRECTIVES : List<any> ;
const ROUTER_DIRECTIVES : Array<any> ;
const ROUTER_BINDINGS : List<any> ;
const ROUTER_BINDINGS : Array<any> ;
class Route implements RouteDefinition {
@@ -669,7 +669,7 @@ declare module ngRouter {
data?: any;
}
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
var RouteConfig : (configs: Array<RouteDefinition>) => ClassDecorator ;
interface ComponentDefinition {
+738
View File
@@ -0,0 +1,738 @@
// Type definitions for Angular v2.0.0-alpha.37
// 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;
/**
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
auxRouter(hostComponent: any): Router;
/**
* Register an outlet to notified of primary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerPrimaryOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Register an outlet to notified of auxiliary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerAuxOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Given an instruction, returns `true` if the instruction is currently active,
* otherwise `false`.
*/
isRouteActive(instruction: Instruction): boolean;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
* # Usage
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
* { 'path': '/user/:id', 'component': UserComp },
* ]);
* ```
*/
config(definitions: 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): Object;
/**
* 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: 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 {
name: string;
/**
* Called by the Router to instantiate a new component during the commit phase of a navigation.
* This method in turn is responsible for calling the `onActivate` hook of its child.
*/
activate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during the commit phase of a navigation when an outlet
* reuses a component between different routes.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
reuse(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} when an outlet reuses a component across navigations.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
deactivate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If this resolves to `false`, the given navigation is cancelled.
*
* This method delegates to the child component's `canDeactivate` hook if it exists,
* and otherwise resolves to true.
*/
canDeactivate(nextInstruction: ComponentInstruction): Promise<boolean>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If the new child component has a different Type than the existing child component,
* this will resolve to `false`. You can't reuse an old component when the new component
* is of a different Type.
*
* Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
* or resolves to true if the hook is not present.
*/
canReuse(nextInstruction: ComponentInstruction): Promise<boolean>;
}
/**
* 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;
isRouteActive: boolean;
routeParams: any;
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: 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 PathLocationStrategy 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 {
platformStrategy: LocationStrategy;
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: 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}.
*
* `ComponentInstruction`s are [https://en.wikipedia.org/wiki/Hash_consing](hash consed). You should
* never construct one yourself with "new." Instead, rely on {@link PathRecognizer} to construct
* `ComponentInstruction`s.
*
* You should not modify this object. It should be treated as immutable.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: string[];
params: StringMap<string, any>;
componentType: any;
resolveComponentType(): Promise<ng.Type>;
specificity: any;
terminal: any;
routeData(): Object;
}
/**
* This class represents a parsed URL
*/
class Url {
path: string;
child: Url;
auxiliary: Url[];
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
const ROUTE_DATA : OpaqueToken ;
const ROUTER_DIRECTIVES : any[] ;
const ROUTER_BINDINGS : any[] ;
class Route implements RouteDefinition {
data: any;
path: string;
component: ng.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: ng.Type;
as: string;
loader: Function;
redirectTo: string;
}
class AsyncRoute implements RouteDefinition {
data: any;
path: string;
loader: Function;
as: string;
}
interface RouteDefinition {
path: string;
component?: ng.Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
var RouteConfig : (configs: RouteDefinition[]) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: ng.Type;
}
}
declare module "angular2/router" {
export = ngRouter;
}
+277 -228
View File
@@ -1,4 +1,4 @@
// Type definitions for Angular v2.0.0-alpha.36
// Type definitions for Angular v2.0.0-alpha.37
// Project: http://angular.io/
// Definitions by: angular team <https://github.com/angular/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -28,52 +28,75 @@ 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.
* Constructs a child router. You probably don't need to use this unless you're writing a reusable
* component.
*/
registerOutlet(outlet: RouterOutlet): Promise<boolean>;
auxRouter(hostComponent: any): Router;
/**
* Register an outlet to notified of primary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerPrimaryOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Register an outlet to notified of auxiliary route changes.
*
* You probably don't need to use this unless you're writing a reusable component.
*/
registerAuxOutlet(outlet: RouterOutlet): Promise<boolean>;
/**
* Given an instruction, returns `true` if the instruction is currently active,
* otherwise `false`.
*/
isRouteActive(instruction: Instruction): boolean;
/**
* Dynamically update the routing configuration and trigger a navigation.
*
*
* # Usage
*
*
* ```
* router.config([
* { 'path': '/', 'component': IndexComp },
@@ -81,129 +104,153 @@ declare module ngRouter {
* ]);
* ```
*/
config(definitions: List<RouteDefinition>): Promise<any>;
config(definitions: 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): Object;
/**
* 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;
generate(linkParams: 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.
* Called by the Router to instantiate a new component during the commit phase of a navigation.
* This method in turn is responsible for calling the `onActivate` hook of its child.
*/
commit(instruction: Instruction): Promise<any>;
activate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by Router during recognition phase
* Called by the {@link Router} during the commit phase of a navigation when an outlet
* reuses a component between different routes.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
canDeactivate(nextInstruction: Instruction): Promise<boolean>;
reuse(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by Router during recognition phase
* Called by the {@link Router} when an outlet reuses a component across navigations.
* This method in turn is responsible for calling the `onReuse` hook of its child.
*/
canReuse(nextInstruction: Instruction): Promise<boolean>;
deactivate(nextInstruction: Instruction): Promise<any>;
deactivate(nextInstruction: ComponentInstruction): Promise<any>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If this resolves to `false`, the given navigation is cancelled.
*
* This method delegates to the child component's `canDeactivate` hook if it exists,
* and otherwise resolves to true.
*/
canDeactivate(nextInstruction: ComponentInstruction): Promise<boolean>;
/**
* Called by the {@link Router} during recognition phase of a navigation.
*
* If the new child component has a different Type than the existing child component,
* this will resolve to `false`. You can't reuse an old component when the new component
* is of a different Type.
*
* Otherwise, this method delegates to the child component's `canReuse` hook if it exists,
* or resolves to true if the hook is not present.
*/
canReuse(nextInstruction: ComponentInstruction): Promise<boolean>;
}
/**
* 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
@@ -211,21 +258,23 @@ declare module ngRouter {
* current component's parent.
*/
class RouterLink {
visibleHref: string;
isRouteActive: boolean;
routeParams: any;
onClick(): boolean;
}
class RouteParams {
params: StringMap<string, string>;
get(param: string): string;
}
/**
* The RouteRegistry holds route configurations for each component in an Angular app.
@@ -233,83 +282,83 @@ declare module ngRouter {
* 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;
generate(linkParams: 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 PathLocationStrategy 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:
@@ -318,47 +367,49 @@ declare module ngRouter {
* - `/my/app/user/123/` **is not** normalized
*/
class Location {
platformStrategy: LocationStrategy;
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>;
steps: 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({
@@ -372,17 +423,17 @@ declare module ngRouter {
* ```
*/
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({
@@ -392,7 +443,7 @@ declare module ngRouter {
* canReuse() {
* return true;
* }
*
*
* onReuse(next, prev) {
* this.params = next.params;
* }
@@ -400,18 +451,18 @@ declare module ngRouter {
* ```
*/
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({
@@ -421,7 +472,7 @@ declare module ngRouter {
* canReuse() {
* return true;
* }
*
*
* onReuse(next, prev) {
* this.params = next.params;
* }
@@ -429,19 +480,19 @@ declare module ngRouter {
* ```
*/
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({
@@ -455,19 +506,19 @@ declare module ngRouter {
* ```
*/
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({
@@ -477,7 +528,7 @@ declare module ngRouter {
* canReuse(next, prev) {
* return next.params.id == prev.params.id;
* }
*
*
* onReuse(next, prev) {
* this.id = next.params.id;
* }
@@ -485,22 +536,22 @@ declare module ngRouter {
* ```
*/
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({
@@ -514,172 +565,170 @@ declare module ngRouter {
*/
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}.
*
* `ComponentInstruction`s are [https://en.wikipedia.org/wiki/Hash_consing](hash consed). You should
* never construct one yourself with "new." Instead, rely on {@link PathRecognizer} to construct
* `ComponentInstruction`s.
*
* You should not modify this object. It should be treated as immutable.
*/
class ComponentInstruction {
reuse: boolean;
urlPath: string;
urlParams: List<string>;
urlParams: string[];
params: StringMap<string, any>;
componentType: any;
resolveComponentType(): Promise<Type>;
resolveComponentType(): Promise<ng.Type>;
specificity: any;
terminal: any;
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.
* This class represents a parsed URL
*/
interface Type extends Function {
new(args: any): any;
class Url {
path: string;
child: Url;
auxiliary: Url[];
params: StringMap<string, any>;
toString(): string;
segmentToString(): string;
}
class OpaqueToken {
toString(): string;
}
const ROUTE_DATA : OpaqueToken ;
const ROUTER_DIRECTIVES : List<any> ;
const ROUTER_BINDINGS : List<any> ;
const ROUTER_DIRECTIVES : any[] ;
const ROUTER_BINDINGS : any[] ;
class Route implements RouteDefinition {
data: any;
path: string;
component: Type;
component: ng.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;
component: ng.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;
component?: ng.Type | ComponentDefinition;
loader?: Function;
redirectTo?: string;
as?: string;
data?: any;
}
var RouteConfig : (configs: List<RouteDefinition>) => ClassDecorator ;
var RouteConfig : (configs: RouteDefinition[]) => ClassDecorator ;
interface ComponentDefinition {
type: string;
loader?: Function;
component?: Type;
component?: ng.Type;
}
}
declare module "angular2/router" {
+5
View File
@@ -10,6 +10,11 @@ declare module "angular-mocks/ngMock" {
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _: string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _: string;
export = _;
+2 -3
View File
@@ -3,7 +3,7 @@
module Analytics {
angular.module("angulartics.app", ["angulartics"])
.config(["$analyticsProvider", ($analyticsProvider: Angulartics.IAnalyticsServiceProvider) => {
.config(["$analyticsProvider", ($analyticsProvider:angulartics.IAnalyticsServiceProvider) => {
angulartics.waitForVendorApi("location", 1000, (message: string) => {
console.log(message);
});
@@ -17,9 +17,8 @@ module Analytics {
console.log(action);
});
$analyticsProvider.registerPageTrack((path: string, locationObj: ng.ILocationService) => {
$analyticsProvider.registerPageTrack((path:string, locationObj:angular.ILocationService) => {
console.log("viewed " + path);
});
}]);
}
+7 -8
View File
@@ -4,16 +4,15 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angulartics {
interface Angulartics {
waitForVendorApi(objectName: string, delay: number, containsField?: any, registerFn?: any, onTimeout?: boolean): void;
}
declare module Angulartics {
interface IAngularticsStatic {
waitForVendorApi(objectName:string, delay:number, containsField?:any, registerFn?:any, onTimeout?:boolean): void;
}
interface IAnalyticsService {
eventTrack(eventName: string, properties?: any): any;
pageTrack(path: string, location?: ng.ILocationService): any;
pageTrack(path:string, location?:angular.ILocationService): any;
setAlias(alias: string): any;
setUsername(username: string): any;
setUserProperties(properties: any): any;
@@ -27,7 +26,7 @@ declare module Angulartics {
withAutoBase(value: boolean): void;
developerMode(value: boolean): void;
registerPageTrack(callback: (path: string, location?: ng.ILocationService) => any): void;
registerPageTrack(callback:(path:string, location?:angular.ILocationService) => any): void;
registerEventTrack(callback: (eventName: string, properties?: any) => any): void;
registerSetAlias(callback: (alias: string) => any): void
registerSetUsername(callback: (username: string) => any): void
@@ -36,4 +35,4 @@ declare module Angulartics {
}
}
declare var angulartics:Angulartics;
declare var angulartics:angulartics.IAngularticsStatic;
+14
View File
@@ -0,0 +1,14 @@
/// <reference path="archiver.d.ts" />
/// <reference path="../node/node.d.ts" />
import Archiver = require('archiver');
import FS = require('fs');
var archiver = Archiver.create('zip');
var writeStream = FS.createWriteStream('./archiver.d.ts');
var readStream = FS.createReadStream('./archiver.d.ts');
archiver.pipe(writeStream);
archiver.append(readStream, {name: 'archiver.d.ts'});
archiver.finalize();
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for archiver v0.15.0
// Project: https://github.com/archiverjs/node-archiver
// Definitions by: Esri <https://github.com/archiverjs/node-archiver>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/* =================== USAGE ===================
import Archiver = require('archiver);
var archiver = Archiver.create('zip');
archiver.pipe(FS.createWriteStream('xxx'));
archiver.append(FS.createReadStream('xxx'));
archiver.finalize();
=============================================== */
/// <reference path="../node/node.d.ts" />
declare module "archiver" {
import * as FS from 'fs';
interface nameInterface {
name?: string;
}
interface Archiver {
pipe(writeStream: FS.WriteStream): void;
append(readStream: FS.ReadStream, name: nameInterface): void;
finalize(): void;
}
interface Options {
}
function archiver(format: string, options?: Options): Archiver;
namespace archiver {
function create(format: string, options?: Options): Archiver;
}
export = archiver;
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="better-curry.d.ts" />
import bc = require('better-curry');
bc.flatten([1,2,3,[1,2],['a']]) === [];
bc.MAX_OPTIMIZED = 5;
function fn(...args: number[]): number[] {
return [].concat([1]);
}
function fn2(arg1: string, arg2: any): number {
return parseInt(arg1 + String(arg2)) + 1;
}
bc.predefine(fn, [1,2])() === [];
bc.predefine(fn, [1,2]).__length === 3;
var f = bc.wrap(fn2, {}, 10, true);
f('1', 2) === 3;
var delegate = bc.delegate({}, 'ok');
delegate.access('ok') === delegate;
delegate.getter('getter').setter('setter') === delegate;
delegate.all(['1','2']);
delegate.revoke('adsf').access('asdf');
BetterCurry.wrap(fn2, {}, -1, false).__length === 10;
+50
View File
@@ -0,0 +1,50 @@
// Type definitions for better-curry
// Project: https://github.com/pocesar/js-bettercurry
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var BetterCurry: BetterCurryModule.BetterCurry;
declare module BetterCurryModule {
export interface DelegateOptions {
as?: string;
len?: number;
args?: any[];
name?: string;
}
export class Delegate<T> {
proto: T;
target: string;
methods: any[];
getters: any[];
setters: any[];
all: (skip?: string[]) => void;
method: (name: string|DelegateOptions) => Delegate<T>;
getter: (name: string|DelegateOptions) => Delegate<T>;
setter: (name: string|DelegateOptions) => Delegate<T>;
access: (name: string|DelegateOptions) => Delegate<T>;
revoke: (name: string) => Delegate<T>;
constructor(proto: T, target: string);
}
export interface OriginalFunctionReminder<T> extends Function {
__length: number;
}
export interface BetterCurry {
predefine: <T extends Function>(fn: T, args: any[], context?: Object, len?: number, checkArguments?: boolean) => OriginalFunctionReminder<T>;
wrap: <T extends Function>(fn: T, context?: Object, len?: number, checkArguments?: boolean) => OriginalFunctionReminder<T>;
flatten: (...args: Array<Array<any>|any>) => any[];
delegate: <T>(proto: T, target: string) => Delegate<T>;
MAX_OPTIMIZED: number;
}
}
declare module 'better-curry' {
var bc: BetterCurryModule.BetterCurry;
export = bc;
}
+2 -2
View File
@@ -6,7 +6,7 @@
declare module BigJsLibrary {
export enum RoundingMode {
export const enum RoundingMode {
RoundTowardsZero = 0,
RoundTowardsNearestAwayFromZero = 1,
RoundTowardsNearestTowardsEven = 2,
@@ -200,4 +200,4 @@ declare module BigJsLibrary {
}
}
declare var Big: BigJsLibrary.BigJS;
declare var Big: BigJsLibrary.BigJS;
+35
View File
@@ -0,0 +1,35 @@
/// <reference path="bluebird-retry.d.ts" />
/// <reference path="../bluebird/bluebird.d.ts" />
import Promise = require('bluebird');
import retry = require('bluebird-retry');
function promiseSuccess(text:string) {
return Promise.resolve(text);
};
var count = 0;
function myfunc() {
console.log('myfunc called ' + (++count) + ' times');
if (count < 3) {
throw new Error('i fail the first two times');
} else {
return promiseSuccess('i succeed the third time');
}
}
retry(myfunc)
.done(function(result) { console.log(result); } );
//Options example
function logFail() {
console.log(new Date().toISOString());
throw new Error('bail');
}
var options:retry.Options = {
max_tries: 4,
interval: 500
};
retry(logFail, options);
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for bluebird-retry
// Project: https://github.com/jut-io/bluebird-retry
// Definitions by: Pascal Vomhoff <https://github.com/pvomhoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
declare module "bluebird-retry" {
import Promise = require('bluebird');
function retry<T>(func:(param:T)=>void, options?:retry.Options):Promise<T>;
module retry {
export interface Options {
interval?:number;
backoff?:number;
max_interval?:number;
timeout?:number;
max_tries?:number;
}
}
export = retry;
}
+7
View File
@@ -137,6 +137,13 @@ interface JQueryEventObject {
value: number|ChangeValue;
}
interface SliderStatics {
new (selector: string, opts: SliderOptions): Slider;
prototype: Slider;
}
declare var Slider: SliderStatics;
/**
* This class is actually not used when using the jQuery version of bootstrap-slider
* The method documentation is still here thouh.
+308
View File
@@ -0,0 +1,308 @@
// Type definitions for chai 2.0.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
}
export interface ExpectStatic extends AssertionStatic {
}
export interface AssertStatic extends Assert {
}
export interface AssertionStatic {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
a: TypeComparison;
an: TypeComparison;
include: Include;
contain: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
Arguments: Assertion;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
length: Length;
lengthOf: Length;
match(regexp: RegExp|string, message?: string): Assertion;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo(method: string, message?: string): Assertion;
itself: Assertion;
satisfy(matcher: Function, message?: string): Assertion;
closeTo(expected: number, delta: number, message?: string): Assertion;
members: Members;
}
interface LanguageChains {
to: Assertion;
be: Assertion;
been: Assertion;
is: Assertion;
that: Assertion;
which: Assertion;
and: Assertion;
has: Assertion;
have: Assertion;
with: Assertion;
at: Assertion;
of: Assertion;
same: Assertion;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Assertion;
}
interface NumberComparer {
(value: number, message?: string): Assertion;
}
interface TypeComparison {
(type: string, message?: string): Assertion;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Assertion;
}
interface Deep {
equal: Equal;
include: Include;
property: Property;
}
interface Equal {
(value: any, message?: string): Assertion;
}
interface Property {
(name: string, value?: any, message?: string): Assertion;
}
interface OwnProperty {
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
interface Include {
(value: Object, message?: string): Assertion;
(value: string, message?: string): Assertion;
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
}
interface Throw {
(): Assertion;
(expected: string, message?: string): Assertion;
(expected: RegExp, message?: string): Assertion;
(constructor: Error, expected?: string, message?: string): Assertion;
(constructor: Error, expected?: RegExp, message?: string): Assertion;
(constructor: Function, expected?: string, message?: string): Assertion;
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
* @param message Message to display on error.
*/
(expression: any, message?: string): void;
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
strictEqual(act: any, exp: any, msg?: string): void;
notStrictEqual(act: any, exp: any, msg?: string): void;
deepEqual(act: any, exp: any, msg?: string): void;
notDeepEqual(act: any, exp: any, msg?: string): void;
isTrue(val: any, msg?: string): void;
isFalse(val: any, msg?: string): void;
isNull(val: any, msg?: string): void;
isNotNull(val: any, msg?: string): void;
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
isObject(val: any, msg?: string): void;
isNotObject(val: any, msg?: string): void;
isArray(val: any, msg?: string): void;
isNotArray(val: any, msg?: string): void;
isString(val: any, msg?: string): void;
isNotString(val: any, msg?: string): void;
isNumber(val: any, msg?: string): void;
isNotNumber(val: any, msg?: string): void;
isBoolean(val: any, msg?: string): void;
isNotBoolean(val: any, msg?: string): void;
typeOf(val: any, type: string, msg?: string): void;
notTypeOf(val: any, type: string, msg?: string): void;
instanceOf(val: any, type: Function, msg?: string): void;
notInstanceOf(val: any, type: Function, msg?: string): void;
include(exp: string, inc: any, msg?: string): void;
include(exp: any[], inc: any, msg?: string): void;
notInclude(exp: string, inc: any, msg?: string): void;
notInclude(exp: any[], inc: any, msg?: string): void;
match(exp: any, re: RegExp, msg?: string): void;
notMatch(exp: any, re: RegExp, msg?: string): void;
property(obj: Object, prop: string, msg?: string): void;
notProperty(obj: Object, prop: string, msg?: string): void;
deepProperty(obj: Object, prop: string, msg?: string): void;
notDeepProperty(obj: Object, prop: string, msg?: string): void;
propertyVal(obj: Object, prop: string, val: any, msg?: string): void;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
lengthOf(exp: any, len: number, msg?: string): void;
//alias frenzy
throw(fn: Function, msg?: string): void;
throw(fn: Function, regExp: RegExp): void;
throw(fn: Function, errType: Function, msg?: string): void;
throw(fn: Function, errType: Function, regExp: RegExp): void;
throws(fn: Function, msg?: string): void;
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, errType: Function, msg?: string): void;
throws(fn: Function, errType: Function, regExp: RegExp): void;
Throw(fn: Function, msg?: string): void;
Throw(fn: Function, regExp: RegExp): void;
Throw(fn: Function, errType: Function, msg?: string): void;
Throw(fn: Function, errType: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, msg?: string): void;
doesNotThrow(fn: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, errType: Function, msg?: string): void;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void;
operator(val: any, operator: string, val2: any, msg?: string): void;
closeTo(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(set1: any[], set2: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
}
export interface Config {
includeStack: boolean;
}
export class AssertionError {
constructor(message: string, _props?: any, ssf?: Function);
name: string;
message: string;
showDiff: boolean;
stack: string;
}
}
declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}
+248 -42
View File
@@ -31,6 +31,16 @@ function fail() {
err(() => {
should.fail('foo', 'bar', 'should fail', 'equal');
}, 'expected fail to throw an AssertionError');
err(() => {
expect.fail('foo', 'bar');
}, 'expected fail to throw an AssertionError');
err(() => {
expect.fail('foo', 'bar', 'should fail');
}, 'expected fail to throw an AssertionError');
err(() => {
expect.fail('foo', 'bar', 'should fail', 'equal');
}, 'expected fail to throw an AssertionError');
}
// ReSharper disable once InconsistentNaming
@@ -107,11 +117,20 @@ function _undefined() {
}, 'expected \'\' to be undefined');
}
function _NaN() {
expect(NaN).to.be.NaN;
expect(12).to.be.not.NaN;
expect("NaN").to.be.not.NaN;
(NaN).should.be.NaN;
(12).should.be.not.NaN;
("NaN").should.be.not.NaN;
}
function exist() {
var foo = 'bar';
expect(foo).to.exist;
should.exist(foo);
expect(void(0)).to.not.exist;
expect(void (0)).to.not.exist;
should.not.exist(void (0));
}
@@ -128,8 +147,8 @@ function argumentsTest() {
}
function equal() {
expect(undefined).to.equal(void(0));
should.equal(undefined, void(0));
expect(undefined).to.equal(void (0));
should.equal(undefined, void (0));
}
function _typeof() {
@@ -372,6 +391,9 @@ function match() {
expect('foobar').to.not.match(/^bar/);
'foobar'.should.not.match(/^bar/);
expect('foobar').matches(/^foo/);
'foobar'.should.not.matches(/^bar/);
err(() => {
expect('foobar').to.match(/^bar/i, 'blah');
'foobar'.should.match(/^bar/i, 'blah');
@@ -490,8 +512,8 @@ function deepEqual3() {
function deepInclude() {
expect(['foo', 'bar']).to.deep.include(['bar', 'foo']);
['foo', 'bar'].should.deep.include(['bar', 'foo']);
expect(['foo', 'bar']).not.to.deep.equal(['foo', 'baz' ]);
['foo', 'bar'].should.not.deep.equal(['foo', 'baz' ]);
expect(['foo', 'bar']).not.to.deep.equal(['foo', 'baz']);
['foo', 'bar'].should.not.deep.equal(['foo', 'baz']);
}
class FakeArgs {
@@ -670,6 +692,20 @@ function ownProperty() {
}, 'blah: expected { length: 12 } to not have own property \'length\'');
}
function ownPropertyDescriptor() {
expect('test').to.have.ownPropertyDescriptor('length');
expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 });
expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 });
expect('test').to.haveOwnPropertyDescriptor('length').to.have.property('enumerable', false);
expect('test').to.haveOwnPropertyDescriptor('length').to.contain.keys('value');
'test'.should.have.ownPropertyDescriptor('length');
'test'.should.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 });
'test'.should.not.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 });
'test'.should.haveOwnPropertyDescriptor('length').to.have.property('enumerable', false);
'test'.should.haveOwnPropertyDescriptor('length').to.contain.keys('value');
}
function string() {
expect('foobar').to.have.string('bar');
'foobar'.should.have.string('bar');
@@ -707,6 +743,10 @@ function include() {
['foo', 'bar'].should.not.include('baz');
expect(['foo', 'bar']).to.not.include(1);
['foo', 'bar'].should.not.include(1);
// alias
expect(['foo', 'bar']).includes('foo');
['foo', 'bar'].should.includes('foo');
err(() => {
expect(['foo']).to.include('bar', 'blah');
@@ -732,6 +772,14 @@ function keys() {
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('bar', 'foo');
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('baz');
({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('baz');
// alias
expect({ foo: 1, bar: 2, baz: 3 }).contains.keys('baz');
expect({ foo: 1, bar: 2 }).to.have.all.keys(['foo', 'bar']);
expect({ foo: 1, bar: 2 }).to.have.any.keys(['foo', 'bar']);
({ foo: 1, bar: 2, baz: 3 }).should.contain.all.keys('baz');
({ foo: 1, bar: 2, baz: 3 }).should.contain.any.keys('baz');
expect({ foo: 1, bar: 2 }).to.contain.keys('foo');
({ foo: 1, bar: 2 }).should.contain.keys('foo');
@@ -830,7 +878,28 @@ function chaining() {
tea.should.be.a('object').and.have.property('name', 'chai');
}
class PoorlyConstructedError {}
function exxtensible() {
expect({}).to.be.extensible;
expect(Object.preventExtensions({})).to.be.not.extensible;
({}).should.be.extensible;
Object.preventExtensions({}).should.not.be.extensible;
}
function sealed() {
expect({}).to.be.not.sealed;
expect(Object.seal({})).to.be.sealed;
({}).should.be.not.sealed;
Object.seal({}).should.be.sealed;
}
function frozen() {
expect({}).to.be.not.frozen;
expect(Object.freeze({})).to.be.frozen;
({}).should.be.not.frozen;
Object.freeze({}).should.be.frozen;
}
class PoorlyConstructedError { }
function _throw() {
// See GH-45: some poorly-constructed custom errors don't have useful names
// on either their constructor or their constructor prototype, but instead
@@ -1023,34 +1092,44 @@ function _throw() {
}, 'blah: expected [Function] to throw error including \'hello\' but got \'testing\'');
}
function use(){
function use() {
// ReSharper disable once InconsistentNaming
chai.use((_chai) => {
_chai.can.use.any();
_chai.can.use.any();
});
}
class Klass {
val: number;
constructor() { this.val = 0; }
bar() { }
static baz() { }
}
function respondTo() {
var bar = {};
var obj = new Klass();
expect(Foo).to.respondTo('bar');
Foo.should.respondTo('bar');
expect(Foo).to.not.respondTo('foo');
Foo.should.not.respondTo('foo');
expect(Foo).itself.to.respondTo('func');
expect(Foo).itself.not.to.respondTo('bar');
expect(Klass).to.respondTo('bar');
expect(obj).respondsTo('bar');
Klass.should.respondTo('bar');
Klass.should.respondsTo('bar');
expect(Klass).to.not.respondTo('foo');
Klass.should.not.respondTo('foo');
expect(Klass).itself.to.respondTo('func');
expect(Klass).itself.not.to.respondTo('bar');
expect(bar).to.respondTo('foo');
bar.should.respondTo('foo');
expect(obj).not.to.respondTo('foo');
obj.should.not.respondTo('foo');
err(() => {
expect(Foo).to.respondTo('baz', 'constructor');
Foo.should.respondTo('baz', 'constructor');
}, /^(constructor: expected)(.*)(\[Function: Foo\])(.*)(to respond to \'baz\')$/);
expect(Klass).to.respondTo('baz', 'constructor');
Klass.should.respondTo('baz', 'constructor');
}, /^(constructor: expected)(.*)(\[Function: Klass\])(.*)(to respond to \'baz\')$/);
err(() => {
expect(bar).to.respondTo('baz', 'object');
bar.should.respondTo('baz', 'object');
expect(obj).to.respondTo('baz', 'object');
obj.should.respondTo('baz', 'object');
}, /^(object: expected)(.*)(\{ foo: \[Function\] \}|\{ Object \()(.*)(to respond to \'baz\')$/);
}
@@ -1116,6 +1195,23 @@ function sameMembers() {
[5, 4].should.not.have.same.members([6, 3]);
expect([5, 4]).to.not.have.same.members([5, 4, 2]);
[5, 4].should.not.have.same.members([5, 4, 2]);
assert.sameMembers([5, 4], [4, 5]);
}
function sameDeepMembers() {
expect([{ id: 5 }, { id: 4 }]).to.have.same.deep.members([{ id: 4 }, { id: 5 }]);
[{ id: 5 }, { id: 4 }].should.have.same.deep.members([{ id: 4 }, { id: 5 }]);
expect([{ id: 5 }, { id: 4 }]).to.have.same.members([{ id: 5 }, { id: 4 }]);
[{ id: 5 }, { id: 4 }].should.have.same.members([{ id: 5 }, { id: 4 }]);
expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([]);
[{ id: 5 }, { id: 4 }].should.not.have.same.members([]);
expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([{ id: 6 }, { id: 3 }]);
[{ id: 5 }, { id: 4 }].should.not.have.same.members([{ id: 6 }, { id: 3 }]);
expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([{ id: 5 }, { id: 4 }, { id: 2 }]);
[{ id: 5 }, { id: 4 }].should.not.have.same.members([{ id: 5 }, { id: 4 }, { id: 2 }]);
assert.sameDeepMembers([{ id: 5 }, { id: 4 }], [{ id: 4 }, { id: 5 }]);
}
function members() {
@@ -1127,16 +1223,48 @@ function members() {
expect([5, 4]).not.members([5, 4, 2]);
}
function increaseDecreaseChange() {
var obj = { val: 10 };
var inc = () => { obj.val++; };
var dec = () => { obj.val--; };
var same = () => { };
expect(inc).to.increase(obj, "val");
expect(inc).increases(obj, "val");
expect(inc).to.change(obj, "val");
expect(dec).to.decrease(obj, "val");
expect(dec).decreases(obj, "val");
expect(dec).to.change(obj, "val");
expect(dec).changes(obj, "val");
expect(inc).to.not.decrease(obj, "val");
expect(dec).to.not.increase(obj, "val");
expect(same).to.not.increase(obj, "val");
expect(same).to.not.decrease(obj, "val");
expect(same).to.not.change(obj, "val");
inc.should.increase(obj, "val");
inc.should.change(obj, "val");
dec.should.decrease(obj, "val");
dec.should.change(obj, "val");
inc.should.not.decrease(obj, "val");
dec.should.not.increase(obj, "val");
same.should.not.change(obj, "val");
}
//tdd
declare function suite(description: string, action: Function):void;
declare function test(description: string, action: Function):void;
declare function suite(description: string, action: Function): void;
declare function test(description: string, action: Function): void;
interface FieldObj {
field: any;
}
class CrashyObject {
inspect (): void {
inspect(): void {
throw new Error('Arg\'s inspect() called even though the test passed');
}
}
@@ -1172,6 +1300,9 @@ suite('assert', () => {
assert.ok(true);
assert.ok(1);
assert.ok('test');
assert.isOk(true);
assert.isOk(1);
assert.isOk('test');
err(() => {
assert.ok(false);
@@ -1186,6 +1317,27 @@ suite('assert', () => {
}, 'expected \'\' to be truthy');
});
test('notOk', () => {
assert.notOk(false);
assert.notOk(0);
assert.notOk('');
assert.isNotOk(false);
assert.isNotOk(0);
assert.isNotOk('');
err(() => {
assert.notOk(true);
}, 'expected true to be falsy');
err(() => {
assert.notOk(1);
}, 'expected 1 to be falsy');
err(() => {
assert.notOk('test');
}, 'expected \'test\' to be falsy');
});
test('isFalse', () => {
assert.isFalse(false);
@@ -1199,7 +1351,7 @@ suite('assert', () => {
});
test('equal', () => {
assert.equal(void(0), undefined);
assert.equal(void (0), undefined);
});
test('typeof / notTypeOf', () => {
@@ -1288,19 +1440,19 @@ suite('assert', () => {
});
test('deepEqual', () => {
assert.deepEqual({tea: 'chai'}, {tea: 'chai'});
assert.deepEqual({ tea: 'chai' }, { tea: 'chai' });
err(() => {
assert.deepEqual({tea: 'chai'}, {tea: 'black'});
assert.deepEqual({ tea: 'chai' }, { tea: 'black' });
}, 'expected { tea: \'chai\' } to deeply equal { tea: \'black\' }');
var obja = Object.create({ tea: 'chai' })
, objb = Object.create({ tea: 'chai' });
, objb = Object.create({ tea: 'chai' });
assert.deepEqual(obja, objb);
var obj1 = Object.create({tea: 'chai'})
, obj2 = Object.create({tea: 'black'});
var obj1 = Object.create({ tea: 'chai' })
, obj2 = Object.create({ tea: 'black' });
err(() => {
assert.deepEqual(obj1, obj2);
@@ -1309,13 +1461,13 @@ suite('assert', () => {
test('deepEqual (ordering)', () => {
var a = { a: 'b', c: 'd' }
, b = { c: 'd', a: 'b' };
, b = { c: 'd', a: 'b' };
assert.deepEqual(a, b);
});
test('deepEqual (circular)', () => {
var circularObject:any = {}
, secondCircularObject:any = {};
var circularObject: any = {}
, secondCircularObject: any = {};
circularObject.field = circularObject;
secondCircularObject.field = secondCircularObject;
@@ -1328,15 +1480,15 @@ suite('assert', () => {
});
test('notDeepEqual', () => {
assert.notDeepEqual({tea: 'jasmine'}, {tea: 'chai'});
assert.notDeepEqual({ tea: 'jasmine' }, { tea: 'chai' });
err(() => {
assert.notDeepEqual({tea: 'chai'}, {tea: 'chai'});
assert.notDeepEqual({ tea: 'chai' }, { tea: 'chai' });
}, 'expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }');
});
test('notDeepEqual (circular)', () => {
var circularObject:any = {}
, secondCircularObject:any = { tea: 'jasmine' };
var circularObject: any = {}
, secondCircularObject: any = { tea: 'jasmine' };
circularObject.field = circularObject;
secondCircularObject.field = secondCircularObject;
@@ -1380,6 +1532,22 @@ suite('assert', () => {
}, 'expected undefined to not equal undefined');
});
test('isNaN', () => {
assert.isNaN(NaN);
err(() => {
assert.isNaN(12);
}, 'expected 12 to be NaN');
});
test('isNotNaN', () => {
assert.isNotNaN(12);
err(() => {
assert.isNotNaN(NaN);
}, 'expected NaN to not NaN');
});
test('isFunction', () => {
var func = () => {
};
@@ -1431,7 +1599,7 @@ suite('assert', () => {
test('isNotString', () => {
assert.isNotString(3);
assert.isNotString([ 'hello' ]);
assert.isNotString(['hello']);
err(() => {
assert.isNotString('hello');
@@ -1449,7 +1617,7 @@ suite('assert', () => {
test('isNotNumber', () => {
assert.isNotNumber('hello');
assert.isNotNumber([ 5 ]);
assert.isNotNumber([5]);
err(() => {
assert.isNotNumber(4);
@@ -1479,7 +1647,7 @@ suite('assert', () => {
test('include', () => {
assert.include('foobar', 'bar');
assert.include([ 1, 2, 3], 3);
assert.include([1, 2, 3], 3);
err(() => {
assert.include('foobar', 'baz');
@@ -1492,7 +1660,7 @@ suite('assert', () => {
test('notInclude', () => {
assert.notInclude('foobar', 'baz');
assert.notInclude([ 1, 2, 3 ], 4);
assert.notInclude([1, 2, 3], 4);
err(() => {
assert.notInclude('foobar', 'bar');
@@ -1739,4 +1907,42 @@ suite('assert', () => {
}, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]');
});
test('isAbove', () => {
assert.isAbove(10, 5);
err(() => {
assert.isAbove(1, 5);
}, 'expected 1 to be above 5');
err(() => {
assert.isAbove(5, 5);
}, 'expected 5 to be above 5');
});
test('isBelow', () => {
assert.isBelow(5, 10);
err(() => {
assert.isBelow(5, 1);
}, 'expected 5 to be above 1');
err(() => {
assert.isBelow(5, 5);
}, 'expected 5 to be below 5');
});
test('extensible', () => { assert.extensible({}); });
test('isExtensible', () => { assert.isExtensible({}); });
test('notExtensible', () => { assert.notExtensible(Object.preventExtensions({})); });
test('isNotExtensible', () => { assert.isNotExtensible(Object.preventExtensions({})); });
test('sealed', () => { assert.sealed(Object.seal({})); });
test('isSealed', () => { assert.isSealed(Object.seal({})); });
test('notSealed', () => { assert.notSealed({}); });
test('isNotSealed', () => { assert.isNotSealed({}); });
test('frozen', () => { assert.frozen(Object.freeze({})); });
test('isFrozen', () => { assert.isFrozen(Object.freeze({})); });
test('notFrozen', () => { assert.notFrozen({}); });
test('isNotFrozen', () => { assert.isNotFrozen({}); });
});
+87 -7
View File
@@ -1,10 +1,13 @@
// Type definitions for chai 2.0.0
// Type definitions for chai 3.2.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>
// Andrew Brown <https://github.com/AGBrown>,
// Olivier Chevet <https://github.com/olivr70>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// <reference path="../assertion-error/assertion-error.d.ts"/>
declare module Chai {
interface ChaiStatic {
@@ -16,9 +19,11 @@ declare module Chai {
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
fail(actual?: any, expected?: any, message?: string, operator?: string): void;
}
export interface AssertStatic extends Assert {
@@ -49,15 +54,20 @@ declare module Chai {
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
any: KeyFilter;
all: KeyFilter;
a: TypeComparison;
an: TypeComparison;
include: Include;
includes: Include;
contain: Include;
contains: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
NaN: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
@@ -70,20 +80,35 @@ declare module Chai {
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
ownPropertyDescriptor: OwnPropertyDescriptor;
haveOwnPropertyDescriptor: OwnPropertyDescriptor;
length: Length;
lengthOf: Length;
match(regexp: RegExp|string, message?: string): Assertion;
match: Match;
matches: Match;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo(method: string, message?: string): Assertion;
respondTo: RespondTo;
respondsTo: RespondTo;
itself: Assertion;
satisfy(matcher: Function, message?: string): Assertion;
satisfy: Satisfy;
satisfies: Satisfy;
closeTo(expected: number, delta: number, message?: string): Assertion;
members: Members;
increase: PropertyChange;
increases: PropertyChange;
decrease: PropertyChange;
decreases: PropertyChange;
change: PropertyChange;
changes: PropertyChange;
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
}
interface LanguageChains {
@@ -134,6 +159,11 @@ declare module Chai {
equal: Equal;
include: Include;
property: Property;
members: Members;
}
interface KeyFilter {
keys: Keys;
}
interface Equal {
@@ -148,6 +178,11 @@ declare module Chai {
(name: string, message?: string): Assertion;
}
interface OwnPropertyDescriptor {
(name: string, descriptor: PropertyDescriptor, message?: string): Assertion;
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
@@ -158,11 +193,18 @@ declare module Chai {
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
any: KeyFilter;
all: KeyFilter;
}
interface Match {
(regexp: RegExp|string, message?: string): Assertion;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
(keys: Object): Assertion;
}
interface Throw {
@@ -175,10 +217,22 @@ declare module Chai {
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface RespondTo {
(method: string, message?: string): Assertion;
}
interface Satisfy {
(matcher: Function, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
interface PropertyChange {
(object: Object, prop: string, msg?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
@@ -189,7 +243,9 @@ declare module Chai {
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
isOk(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
isNotOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
@@ -209,6 +265,12 @@ declare module Chai {
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isNaN(val: any, msg?: string): void;
isNotNaN(val: any, msg?: string): void;
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
@@ -279,9 +341,27 @@ declare module Chai {
closeTo(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
isExtensible(obj: {}, msg?: string): void;
extensible(obj: {}, msg?: string): void;
isNotExtensible(obj: {}, msg?: string): void;
notExtensible(obj: {}, msg?: string): void;
isSealed(obj: {}, msg?: string): void;
sealed(obj: {}, msg?: string): void;
isNotSealed(obj: {}, msg?: string): void;
notSealed(obj: {}, msg?: string): void;
isFrozen(obj: Object, msg?: string): void;
frozen(obj: Object, msg?: string): void;
isNotFrozen(obj: Object, msg?: string): void;
notFrozen(obj: Object, msg?: string): void;
}
export interface Config {
@@ -305,4 +385,4 @@ declare module "chai" {
interface Object {
should: Chai.Assertion;
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
/// <reference path="cheerio.d.ts" />
import cheerio from 'cheerio';
import * as cheerio from 'cheerio';
/*
* LOADING
+1 -1
View File
@@ -262,5 +262,5 @@ interface CheerioAPI extends CheerioSelector {
declare var cheerio:CheerioAPI;
declare module "cheerio" {
export default cheerio;
export = cheerio;
}
+8 -3
View File
@@ -1,13 +1,18 @@
// Type definitions for classnames
// Project: https://github.com/JedWatson/classnames
// Definitions by: Dave Keen <http://www.keendevelopment.ch>
// Definitions by: Dave Keen <http://www.keendevelopment.ch>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface ClassDictionary {
[id: string]: boolean;
}
interface ClassNamesFn {
(...classes: (string | ClassDictionary)[]): string;
}
declare var classNames: ClassNamesFn;
declare module "classnames" {
function classNames(...classes: (string|ClassDictionary)[]): string;
export = classNames
}
}
@@ -1,5 +1,5 @@
/// <reference path="codemirror.d.ts" />
/// <reference path="showhint.d.ts" />
/// <reference path="codemirror-showhint.d.ts" />
var doc = new CodeMirror.Doc('text');
var pos = new CodeMirror.Pos(2, 3);
CodeMirror.showHint(doc);
@@ -1,10 +1,12 @@
// Type definitions for CodeMirror
// Project: https://github.com/marijnh/CodeMirror
// Definitions by: jacqt <https://github.com/jacqt>
// Definitions by: jacqt <https://github.com/jacqt>, basarat <https://github.com/basarat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// See docs https://codemirror.net/doc/manual.html#addon_show-hint
declare module CodeMirror {
var commands : any;
var commands: any;
/** Provides a framework for showing autocompletion hints. Defines editor.showHint, which takes an optional
options object, and pops up a widget that allows the user to select a completion. Finding hints is done with
@@ -12,13 +14,12 @@ declare module CodeMirror {
and return a {list, from, to} object, where list is an array of strings or objects (the completions), and
from and to give the start and end of the token that is being completed as {line, ch} objects. An optional
selectedHint property (an integer) can be added to the completion object to control the initially selected hint. */
function showHint (cm: CodeMirror.Doc, hinter?: (doc : CodeMirror.Doc) => Hints, options?: IShowHintOptions) : void;
function showHint(cm: CodeMirror.Doc, hinter?: (doc: CodeMirror.Doc) => Hints, options?: ShowHintOptions): void;
interface Hints {
from: Position;
to: Position;
list: Hint[] | string[];
list: (Hint | string)[];
}
/** Interface used by showHint.js Codemirror add-on
@@ -28,25 +29,27 @@ declare module CodeMirror {
className?: string;
displayText?: string;
from?: Position;
render?: (element: any, self: any, data: any) => void;
/** Called if a completion is picked. If provided *you* are responsible for applying the completion */
hint?: (cm: any, data: Hints, cur: Hint) => void;
render?: (element: HTMLLIElement, data: Hints, cur: Hint) => void;
to?: Position;
}
interface Editor {
/** An extension of the existing CodeMirror typings for the Editor.on("keyup", func) syntax */
on(eventName: string, handler: (doc: CodeMirror.Doc, event : any ) => void ): void;
off(eventName: string, handler: (doc: CodeMirror.Doc, event : any) => void ): void;
on(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void;
off(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void;
}
/** Extend CodeMirror.Doc with a state object, so that the Doc.state.completionActive property is reachable*/
interface Doc {
state: any;
showHint: (options: IShowHintOptions) => void;
showHint: (options: ShowHintOptions) => void;
}
interface IShowHintOptions {
interface ShowHintOptions {
completeSingle: boolean;
hint: (doc : CodeMirror.Doc) => Hints;
hint: (doc: CodeMirror.Doc) => Hints;
}
/** The Handle used to interact with the autocomplete dialog box.*/
@@ -59,4 +62,13 @@ declare module CodeMirror {
pick(): void;
data: any;
}
interface EditorConfiguration {
showHint?: boolean;
hintOptions?: ShowHintOptions;
}
}
declare module "codemirror/addon/hint/show-hint" {
export = CodeMirror;
}
+4
View File
@@ -1090,3 +1090,7 @@ declare module CodeMirror {
to?: Position;
}
}
declare module "codemirror" {
export = CodeMirror;
}
+2 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for cookie-parser
// Type definitions for cookie-parser v1.3.4
// Project: https://github.com/expressjs/cookie-parser
// Definitions by: Santi Albo <https://github.com/santialbo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -8,5 +8,6 @@
declare module "cookie-parser" {
import express = require('express');
function e(secret?: string, options?: any): express.RequestHandler;
namespace e{}
export = e;
}
+21 -4
View File
@@ -1,17 +1,32 @@
// Type definitions for Apache Cordova Vibration plugin.
// Project: https://github.com/apache/cordova-plugin-vibration
// Definitions by: Microsoft Open Technologies, Inc. <http://msopentech.com>
// Definitions by: Microsoft Open Technologies, Inc. <http://msopentech.com>, Louis Lagrange <https://github.com/Minishlink/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//
//
// Copyright (c) Microsoft Open Technologies, Inc.
// Licensed under the MIT license.
interface Navigator {
/**
* Vibrates the device for the specified amount of time.
* @param time Milliseconds to vibrate the device. 0 cancels the vibration. Ignored on iOS.
*/
vibrate(time: number): void;
/**
* Vibrates the device with a given pattern.
* @param time Sequence of durations (in milliseconds) for which to turn on or off the vibrator. Ignored on iOS.
*/
vibrate(time: number[]): void;
}
interface Notification {
/**
* Vibrates the device for the specified amount of time.
* @param time Milliseconds to vibrate the device. Ignored on iOS.
* @deprecated
*/
vibrate(time: number): void
vibrate(time: number): void;
/**
* Vibrates the device with a given pattern.
* @param number[] pattern Pattern with which to vibrate the device.
@@ -19,10 +34,12 @@ interface Notification {
* The next value - the number of milliseconds for which to keep the vibrator on before turning it off.
* @param number repeat Optional index into the pattern array at which to start repeating (will repeat until canceled),
* or -1 for no repetition (default).
* @deprecated
*/
vibrateWithPattern(pattern: number[], repeat: number): void;
/**
* Immediately cancels any currently running vibration.
* @deprecated
*/
cancelVibration(): void;
}
}
+60 -75
View File
@@ -5,7 +5,7 @@ module Tests.ui {
activeStateEnabled: true,
allowColumnReordering: true,
allowColumnResizing: true,
onCellClick: function () { },
onCellClick: function() { },
cellHintEnabled: true,
columnAutoWidth: true,
columnChooser: {
@@ -17,67 +17,52 @@ module Tests.ui {
},
columns: [
{
text: '5 columns with custom css class', value: [
{ dataField: 'Processed', dataType: 'boolean', allowSorting: false },
{ dataField: 'CustomerID', cssClass: 'customCssClass' },
'OrderDate',
{ dataField: 'Freight', validationRules: [{ type: "range", min: 1, max: 100 }] },
{ dataField: 'ShipName', validationRules: [{ type: 'required' }] },
'ShipCity']
},
{
text: 'with show editor always', value: [
{ dataField: 'Processed', dataType: 'boolean', allowSorting: false, showEditorAlways: true },
{ dataField: 'OrderDate', dataType: 'date', showEditorAlways: true },
{ dataField: 'CustomerID', showEditorAlways: true },
{ dataField: 'Freight', showEditorAlways: true },
{ dataField: 'ShipName', showEditorAlways: true }]
},
{
text: 'custom template/edit/header template', value: [
'CustomerID',
'OrderDate',
'Freight',
{
dataField: 'ShipVia',
editCellTemplate: function (container: JQuery, options: { value: number }) {
container.addClass('dx-editor-cell');
container.append($('<div />').dxSelectBox({
value: options.value,
dataSource: [
{ ShipperID: 1, CompanyName: 'Speedy Express' },
{ ShipperID: 2, CompanyName: 'United Package' },
{ ShipperID: 3, CompanyName: 'Federal Shipping' }
],
valueExpr: 'ShipperID',
displayExpr: 'CompanyName'
}));
},
cellTemplate: function (container: JQuery, options: { value: number }) {
container.text(String(options.value));
},
headerCellTemplate: function (container: JQuery, options: { headerCaption: string }) {
container.append($('<div/>').css({ border: '1px solid red' }).text(options.headerCaption));
}
},
'ShipName',
'ShipCity']
},
{ text: 'none', value: '' },
{
text: 'custom template/header hogan template', value: [
'CustomerID',
'OrderDate',
'Freight',
{
dataField: 'ShipVia',
cellTemplate: '#hoganColumnTemplate',
headerCellTemplate: $('#hoganHeaderColumnTemplate')
},
'ShipName',
'ShipCity']
}],
customizeColumns: function (columns) {
alignment: "center",
allowFixing: true,
allowEditing: true,
allowFiltering: true,
allowGrouping: true,
allowHiding: true,
allowReordering: true,
allowResizing: true,
allowSearch: true,
allowSorting: true,
autoExpandGroup: true,
calculateCellValue: function(rowData: Object) { return "test-value"; },
calculateFilterExpression: function(filterValue: any, selectedFilterOperation: string) { return []; },
caption: "Test column",
cellTemplate: function(container: JQuery, options: Object) { $("<span>Template</span>").appendTo(container); },
cssClass: "test-ccs-class-name",
customizeText: function(cellInfo: { value: any, valueText: string; }) { return "New text" },
dataField: "Test",
dataType: "string",
encodeHtml: true,
falseText: "FALSE",
filterOperations: ["contains", "notcontains"],
filterType: "exclude",
filterValue: "Test-filter-value",
fixed: true,
fixedPosition: "right",
groupIndex: 0,
lookup: {
allowClearing: true,
dataSource: ["first", "second"],
displayExpr: "this",
valueExpr: "this"
},
name: "test-column-name",
showEditorAlways: true,
showInColumnChooser: true,
showWhenGrouped: true,
sortIndex: 1,
sortOrder: "desc",
trueText: "TRUE",
visible: true,
visibleIndex: 0,
width: "100%"
}
],
customizeColumns: function(columns) {
var i: number;
for (i = 0; i < columns.length; i++) {
if (columns[i].dataField.indexOf('Date') > 0) {
@@ -94,16 +79,16 @@ module Tests.ui {
valueExpr: 'CustomerID',
displayExpr: 'ContactName'
}
}
}
if (columns[i].dataField === 'EmployeeID') {
columns[i].lookup = {
dataSource: { store: [], sort: 'LastName' },
valueExpr: 'EmployeeID',
displayExpr: function (data: any) {
displayExpr: function(data: any) {
return data.LastName + ' ' + data.FirstName;
}
}
}
}
if (columns[i].dataField === 'ShipVia') {
columns[i].lookup = {
dataSource: [
@@ -114,14 +99,14 @@ module Tests.ui {
valueExpr: 'ShipperID',
displayExpr: 'CompanyName'
}
}
}
if (columns[i].dataField === 'ShipCity') {
columns[i].editCellTemplate = function (container: JQuery, options: { value: string; setValue: Function }) {
columns[i].editCellTemplate = function(container: JQuery, options: { value: string; setValue: Function }) {
$('<div/>').dxAutocomplete({
items: ["Bern", "Lyon", "Lander"],
dataSource: ["Bern", "Lyon", "Lander"],
value: options.value,
onValueChanged: function (e:{ value: string }) {
options.setValue(e.value);
onValueChanged: function() {
options.setValue("test-value");
}
}).appendTo(container);
}
@@ -242,10 +227,10 @@ module Tests.viz {
{ valueField: 's8' }
],
title: 'Long Chart\'s Title',
onPointClick: function (arg: any) {
onPointClick: function(arg: any) {
arg.target.isSelected() ? arg.target.clearSelection() : arg.target.select();
},
onSeriesClick: function (arg: any) {
onSeriesClick: function(arg: any) {
arg.target.isVisible() ? arg.target.hide() : arg.target.show();
}
};
@@ -313,8 +298,8 @@ module Tests.data {
pageSize: 25,
paginate: true,
map: function (item) { return item; },
postProcess: function (data) { return data; },
map: function(item) { return item; },
postProcess: function(data) { return data; },
searchExpr: "expr",
searchOperation: "contains",
searchValue: "somevalue",
@@ -328,7 +313,7 @@ module Tests.data {
});
new DevExpress.data.CustomStore(<DevExpress.data.CustomStoreOptions>{
load: function () {
load: function() {
return $.Deferred().promise();
}
});
+68 -68
View File
@@ -35,7 +35,7 @@ declare module DevExpress {
brokenRules: any[];
validators: IValidator[];
}
export interface GroupConfig extends EventsMixin<GroupConfig> {
export interface GroupConfig extends EventsMixin<GroupConfig> {
group: any;
validators: IValidator[];
validate(): ValidationGroupValidationResult;
@@ -56,7 +56,7 @@ declare module DevExpress {
/** Validates the rules that are defined within the dxValidator objects that are registered for the specified ViewModel. */
export function validateModel(model: Object): ValidationGroupValidationResult;
/** Registers all the dxValidator objects by which the fields of the specified ViewModel are extended. */
export function registerModelForValidation(model: Object) : void;
export function registerModelForValidation(model: Object): void;
}
export var hardwareBackButton: JQueryCallback;
/** Processes the hardware back button click. */
@@ -1789,7 +1789,7 @@ declare module DevExpress.ui {
interval?: number;
/** Specifies the maximum zoom level of a calendar, which is used to pick the date. */
maxZoomLevel?: string;
/** Specifies the minimal zoom level of a calendar, which is used to pick the date. */
/** Specifies the minimal zoom level of a calendar, which is used to pick the date. */
minZoomLevel?: string;
/** Specifies the type of date/time picker. */
pickerType?: string;
@@ -4335,16 +4335,16 @@ declare module DevExpress.viz.core {
}) => void;
/** A handler for the incidentOccurred event. */
onIncidentOccurred?: (
component: BaseWidget,
element: Element,
target: {
id: string;
type: string;
args: any;
text: string;
widget: string;
version: string;
}
component: BaseWidget,
element: Element,
target: {
id: string;
type: string;
args: any;
text: string;
widget: string;
version: string;
}
) => void;
/** Notifies a widget that it is embedded into an HTML page that uses a path modifier. */
pathModified?: boolean;
@@ -4659,59 +4659,59 @@ declare module DevExpress.viz.charts {
};
}
export interface CommonPointOptions {
/** Specifies border options for points in the line and area series. */
/** Specifies border options for points in the line and area series. */
border?: viz.core.Border;
/** Specifies the points color. */
color?: string;
/** Specifies what series points to highlight when a point is hovered over. */
hoverMode?: string;
/** An object defining configuration options for a hovered point. */
hoverStyle?: {
/** An object defining the border options for a hovered point. */
border?: viz.core.Border;
/** Specifies the points color. */
/** Sets a color for a point when it is hovered over. */
color?: string;
/** Specifies what series points to highlight when a point is hovered over. */
hoverMode?: string;
/** An object defining configuration options for a hovered point. */
hoverStyle?: {
/** An object defining the border options for a hovered point. */
border?: viz.core.Border;
/** Sets a color for a point when it is hovered over. */
color?: string;
/** Specifies the diameter of a hovered point in the series that represents data points as symbols (not as bars for instance). */
size?: number;
};
/** Specifies what series points to highlight when a point is selected. */
selectionMode?: string;
/** An object defining configuration options for a selected point. */
selectionStyle?: {
/** An object defining the border options for a selected point. */
border?: viz.core.Border;
/** <p>Sets a color for a point when it is selected.</p> */
color?: string;
/** Specifies the diameter of a selected point in the series that represents data points as symbols (not as bars for instance). */
size?: number;
};
/** Specifies the point diameter in pixels for those series that represent data points as symbols (not as bars for instance). */
/** Specifies the diameter of a hovered point in the series that represents data points as symbols (not as bars for instance). */
size?: number;
/** Specifies a symbol for presenting points of the line and area series. */
symbol?: string;
visible?: boolean;
};
/** Specifies what series points to highlight when a point is selected. */
selectionMode?: string;
/** An object defining configuration options for a selected point. */
selectionStyle?: {
/** An object defining the border options for a selected point. */
border?: viz.core.Border;
/** <p>Sets a color for a point when it is selected.</p> */
color?: string;
/** Specifies the diameter of a selected point in the series that represents data points as symbols (not as bars for instance). */
size?: number;
};
/** Specifies the point diameter in pixels for those series that represent data points as symbols (not as bars for instance). */
size?: number;
/** Specifies a symbol for presenting points of the line and area series. */
symbol?: string;
visible?: boolean;
}
export interface ChartCommonPointOptions extends CommonPointOptions {
/** An object specifying the parameters of an image that is used as a point marker. */
image?: {
/** Specifies the height of an image that is used as a point marker. */
height?: any;
/** Specifies a URL leading to the image to be used as a point marker. */
url?: any;
/** Specifies the width of an image that is used as a point marker. */
width?: any;
};
/** An object specifying the parameters of an image that is used as a point marker. */
image?: {
/** Specifies the height of an image that is used as a point marker. */
height?: any;
/** Specifies a URL leading to the image to be used as a point marker. */
url?: any;
/** Specifies the width of an image that is used as a point marker. */
width?: any;
};
}
export interface PolarCommonPointOptions extends CommonPointOptions {
/** An object specifying the parameters of an image that is used as a point marker. */
image?: {
/** Specifies the height of an image that is used as a point marker. */
height?: number;
/** Specifies a URL leading to the image to be used as a point marker. */
url?: string;
/** Specifies the width of an image that is used as a point marker. */
width?: number;
};
/** An object specifying the parameters of an image that is used as a point marker. */
image?: {
/** Specifies the height of an image that is used as a point marker. */
height?: number;
/** Specifies a URL leading to the image to be used as a point marker. */
url?: string;
/** Specifies the width of an image that is used as a point marker. */
width?: number;
};
}
/** An object that defines configuration options for chart series. */
export interface CommonSeriesConfig extends BaseCommonSeriesConfig {
@@ -5094,17 +5094,17 @@ declare module DevExpress.viz.charts {
text?: string;
}
export interface AxisLabel {
/** Specifies the text for a hint that appears when a user hovers the mouse pointer over a label on the value axis. */
/** Specifies the text for a hint that appears when a user hovers the mouse pointer over a label on the value axis. */
customizeHint?: (argument: { value: any; valueText: string }) => string;
/** Specifies a callback function that returns the text to be displayed in value axis labels. */
/** Specifies a callback function that returns the text to be displayed in value axis labels. */
customizeText?: (argument: { value: any; valueText: string }) => string;
/** Specifies a format for the text displayed by axis labels. */
/** Specifies a format for the text displayed by axis labels. */
format?: string;
/** Specifies a precision for the formatted value displayed in the axis labels. */
/** Specifies a precision for the formatted value displayed in the axis labels. */
precision?: number;
}
export interface ChartAxisLabel extends ChartCommonAxisLabel, AxisLabel {}
export interface PolarAxisLabel extends PolarCommonAxisLabel, AxisLabel {}
export interface ChartAxisLabel extends ChartCommonAxisLabel, AxisLabel { }
export interface PolarAxisLabel extends PolarCommonAxisLabel, AxisLabel { }
export interface AxisTitle extends CommonAxisTitle {
/** Specifies the text for the value axis title. */
text?: string;
@@ -5120,7 +5120,7 @@ declare module DevExpress.viz.charts {
value?: any;
}
export interface PolarConstantLine extends PolarCommonConstantLineStyle {
/** An object defining constant line label options. */
/** An object defining constant line label options. */
label?: PolarConstantLineLabel;
/** Specifies a value to be displayed by a constant line. */
value?: any;
@@ -5173,7 +5173,7 @@ declare module DevExpress.viz.charts {
/** Specifies the elements that will be highlighted when the argument axis is hovered over. */
hoverMode?: string;
}
export interface ChartArgumentAxis extends ChartAxis, ArgumentAxis {}
export interface ChartArgumentAxis extends ChartAxis, ArgumentAxis { }
export interface PolarArgumentAxis extends PolarAxis, ArgumentAxis {
/** Specifies a start angle for the argument axis in degrees. */
startAngle?: number;
@@ -5189,7 +5189,7 @@ declare module DevExpress.viz.charts {
showZero?: boolean;
/** Specifies the desired type of axis values. */
valueType?: string;
}
}
export interface ChartValueAxis extends ChartAxis, ValueAxis {
/** Specifies the spacing, in pixels, between multiple value axes in a chart. */
multipleAxesSpacing?: number;
+28
View File
@@ -0,0 +1,28 @@
///<reference path='fontoxml.d.ts' />
var workflow:com.fontoxml.IWorkflowInfo = {
id:"1",
displayName:"workflow"
}
var user:com.fontoxml.IUserInfo = {
id: "123",
displayName: "test",
roleId: "editor"
}
var init:com.fontoxml.IInvocator = {
documentIds: ["11-22-33","44-55-66"],
cmsBaseUrl: "/test/",
editSessionToken: "aa-bb-cc-dd-ee",
user: user,
workflow: workflow,
autosave: false,
heartbeat: 300
}
var simpleinit:com.fontoxml.IInvocator = {
documentIds: ["11-22-33","44-55-66"],
cmsBaseUrl: "/test/",
editSessionToken: "aa-bb-cc-dd-ee"
}
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for FontoXML
// Project: http://www.fontoxml.com/
// Definitions by: Roland Zwaga <https://github.com/rolandzwaga>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module com.fontoxml
{
//This is a description of how to invoke the FontoXML editor, and instruct it to load (a) document(s).
//Please keep in mind that the URL length may be limited in certain browsers, so a safe limit of 2000 characters
//for the whole URL including query parameters should be used.
export interface IInvocator
{
//The document id's of the documents to load from the CMS.
documentIds: string[];
//The base URL where the CMS endpoints are exposed.
cmsBaseUrl: string;
//The edit session token to use for accessing the CMS endpoints.
editSessionToken: string;
//User information.
user?: IUserInfo;
//Workflow information.
workflow?: IWorkflowInfo;
//Allow/disallow auto-save functionality.
autosave?: boolean;
//If set to a positive integer, enable the Heartbeat API to send every x seconds.
heartbeat?: number;
}
export interface IWorkflowInfo
{
id:string;
displayName:string;
}
export interface IUserInfo extends IWorkflowInfo
{
roleId:string;
}
}
@@ -43,6 +43,8 @@ app.on('ready', () => {
// and load the index.html of the app.
mainWindow.loadUrl(`file://${__dirname}/index.html`);
mainWindow.loadUrl('file://foo/bar', {userAgent: 'cool-agent', httpReferrer: 'greateRefferer'});
mainWindow.webContents.loadUrl('file://foo/bar', {userAgent: 'cool-agent', httpReferrer: 'greateRefferer'});
mainWindow.openDevTools()
var opened: boolean = mainWindow.isDevToolsOpened()
@@ -409,6 +411,7 @@ app.on('ready', () => {
]);
appIcon.setToolTip('This is my application.');
appIcon.setContextMenu(contextMenu);
appIcon.setImage('/path/to/new/icon');
});
// clipboard
+9 -3
View File
@@ -400,7 +400,10 @@ declare module GitHubElectron {
/**
* Same with webContents.loadUrl(url).
*/
loadUrl(url: string): void;
loadUrl(url: string, options?: {
httpReferrer?: string;
userAgent?: string;
}): void;
/**
* Same with webContents.reload.
*/
@@ -537,7 +540,10 @@ declare module GitHubElectron {
* Loads the url in the window.
* @param url Must contain the protocol prefix (e.g., the http:// or file://).
*/
loadUrl(url: string): void;
loadUrl(url: string, options?: {
httpReferrer?: string;
userAgent?: string;
}): void;
/**
* @returns The URL of current web page.
*/
@@ -1212,7 +1218,7 @@ declare module GitHubElectron {
/**
* Sets the image associated with this tray icon.
*/
setImage(image: NativeImage): void;
setImage(image: NativeImage|string): void;
/**
* Sets the image associated with this tray icon when pressed.
*/
+1 -1
View File
@@ -32,7 +32,7 @@ declare module JQueryGlide {
/**
* Default: 500
* Animation time in ms
* @type {Int}
* @type {number}
*/
animationDuration?: number;
/**
Vendored
+1
View File
@@ -13,6 +13,7 @@ declare module "gm" {
module m {
export interface ClassOptions {
imageMagick?: boolean;
nativeAutoOrient?: boolean;
}
export interface CompareCallback {
+93
View File
@@ -0,0 +1,93 @@
/// <reference path="gulp-cheerio.d.ts" />
/// <reference path="../vinyl/vinyl.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="../cheerio/cheerio.d.ts" />
import cheerio = require('gulp-cheerio');
import gulp = require('gulp');
import Vinyl = require('vinyl');
//
// There are two ways to use gulp-cheerio: synchronous and asynchronous. See the following usage examples:
//
gulp.task('sync', function () {
return gulp
.src(['src/*.html'])
.pipe(cheerio(function ($: CheerioStatic, file: Vinyl) {
// Each file will be run through cheerio and each corresponding `$` will be passed here.
// `file` is the gulp file object
// Make all h1 tags uppercase
$('h1').each(function () {
var h1 = $(this);
h1.text(h1.text().toUpperCase());
});
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('async', function () {
return gulp
.src(['src/*.html'])
.pipe(cheerio(function ($: CheerioStatic, file: Vinyl, done: Function) {
// The only difference here is the inclusion of a `done` parameter.
// Call `done` when everything is finished. `done` accepts an error if applicable.
done();
}))
.pipe(gulp.dest('dist/'));
});
//TODO
//
// Additional options can be passed by passing an object as the main argument with your function as the run option:
//
gulp.task('sync', function () {
return gulp
.src(['src/*.html'])
.pipe(cheerio({
run: function ($: CheerioStatic, file: Vinyl) {
// Each file will be run through cheerio and each corresponding `$` will be passed here.
// `file` is the gulp file object
// Make all h1 tags uppercase
$('h1').each(function () {
var h1 = $(this);
h1.text(h1.text().toUpperCase());
});
}
}))
.pipe(gulp.dest('dist/'));
});
gulp.task('async', function () {
return gulp
.src(['src/*.html'])
.pipe(cheerio({
run: function ($: CheerioStatic, file: Vinyl, done: Function) {
// The only difference here is the inclusion of a `done` parameter.
// Call `done` when everything is finished. `done` accepts an error if applicable.
done();
}
}))
.pipe(gulp.dest('dist/'));
});
cheerio({
run: function () {},
parserOptions: {
// Options here
}
});
cheerio({
run: function () {},
parserOptions: {
xmlMode: true
}
});
cheerio({
cheerio: require('../cheerio/cheerio.d.ts') as CheerioStatic // special version of `cheerio`
});
+34
View File
@@ -0,0 +1,34 @@
// Type definitions for gulp-cheerio
// Project: https://github.com/KenPowers/gulp-cheerio
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../cheerio/cheerio.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="../vinyl/vinyl.d.ts"/>
declare module "gulp-cheerio" {
import Vinyl = require('vinyl');
namespace cheerio {
interface Cheerio {
(callback: Callback): NodeJS.ReadWriteStream;
(option: Option): NodeJS.ReadWriteStream;
}
interface Callback {
($: CheerioStatic, file: Vinyl, done?: Function): any;
}
interface Option {
run?: Callback;
parserOptions?: CheerioOptionsInterface;
cheerio?: CheerioStatic;
}
}
var cheerio: cheerio.Cheerio;
export = cheerio;
}
+57
View File
@@ -0,0 +1,57 @@
/// <reference path="gulp-coffeelint.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import coffeelint = require('gulp-coffeelint');
import gulp = require('gulp');
gulp.task('lint', function () {
gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter())
});
gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter('csv'));
declare var stylish: Function;
gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter(stylish));
gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter('coffelint-stylish'));
gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter('coffeelint-stylish'))
.pipe(coffeelint.reporter('fail'));
var myReporter = (function() {
function MyReporter(errorReport: any) {
this.errorReport = errorReport;
}
MyReporter.prototype.publish = function() {
var hasError = this.errorReport.hasError();
if (hasError) {
return console.log('Oh no!');
}
return console.log('Oh yeah!');
};
return MyReporter;
})();
gulp.task('lint', function() {
return gulp.src('./src/*.coffee')
.pipe(coffeelint())
.pipe(coffeelint.reporter(myReporter));
});
+26
View File
@@ -0,0 +1,26 @@
// Type definitions for gulp-coffeelint
// Project: https://github.com/janraasch/gulp-coffeelint
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-coffeelint" {
namespace coffeelint {
interface Coffeelint {
/**
* @param optFile Absolute path of a json file containing options for coffeelint.
* @param opt Options you wish to send to coffeelint. If optFile is given, this will be ignored.
* @param literate Are we dealing with Literate CoffeeScript?
* @param rules Add custom rules to coffeelint.
*/
(optFile?: string, opt?: any, literate?: boolean, rules?: Function[]): NodeJS.ReadWriteStream;
reporter(reporter?: string|Function): NodeJS.ReadWriteStream;
}
}
var coffeelint: coffeelint.Coffeelint;
export = coffeelint;
}
+1 -1
View File
@@ -2,7 +2,7 @@
/// <reference path="../gulp/gulp.d.ts" />
import gulp = require("gulp");
import concat = require("gulp-concat");
import * as concat from "gulp-concat";
gulp.task("concat:simple", () => {
gulp.src(["file*.txt"])
+6 -3
View File
@@ -35,8 +35,11 @@ declare module "gulp-concat" {
contents?: NodeJS.ReadableStream | Buffer;
}
function concat(filename: string, options?: IOptions): NodeJS.ReadWriteStream;
function concat(options: IVinylOptions): NodeJS.ReadWriteStream;
interface IConcat {
(filename: string, options?: IOptions): NodeJS.ReadWriteStream;
(options: IVinylOptions): NodeJS.ReadWriteStream;
}
export = concat;
var _tmp: IConcat;
export = _tmp;
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="gulp-gzip.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import gulp = require('gulp');
import gzip = require('gulp-gzip');
gzip({ append: true });
gzip({ extension: 'zip' }); // note that the `.` should not be included in the extension
gzip({ preExtension: 'gz' }); // note that the `.` should not be included in the extension
gzip({ threshold: '1kb' });
gzip({ threshold: 1024 });
gzip({ threshold: true });
gzip({ gzipOptions: { level: 9 } });
gzip({ gzipOptions: { memLevel: 1 } });
gulp.task('compress', function() {
gulp.src('./dev/scripts/*.js')
.pipe(gzip())
.pipe(gulp.dest('./public/scripts'));
});
+47
View File
@@ -0,0 +1,47 @@
// Type definitions for gulp-gzip
// Project: https://github.com/jstuckey/gulp-gzip
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-gzip" {
import zlib = require('zlib');
namespace gzip {
interface Gzip {
(options?: Options): NodeJS.ReadWriteStream;
}
interface Options {
/**
* Appends .gz file extension if true.
* @default true
*/
append?: boolean;
/**
* Appends an arbitrary extension to the filename. Disables append and preExtension options.
*/
extension?: string;
/**
* Appends an arbitrary pre-extension to the filename. Disables append and extension options.
*/
preExtension?: string;
/**
* Minimum size required to compress a file.
* @default false
*/
threshold?: number|string|boolean;
/**
* Options object to pass through to zlib.Gzip.
* See <a href='https://nodejs.org/api/zlib.html#zlib_options'>zlib</a> documentation for more information.
*/
gzipOptions?: zlib.ZlibOptions;
}
}
var gzip: gzip.Gzip;
export = gzip;
}
@@ -0,0 +1,17 @@
/// <reference path="gulp-ng-annotate.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import ngAnnotate = require('gulp-ng-annotate');
import gulp = require('gulp');
gulp.task('default', function () {
return gulp.src('src/app.js')
.pipe(ngAnnotate())
.pipe(gulp.dest('dist'));
});
ngAnnotate({
remove: true,
add: true,
single_quotes: true
});
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for gulp-ng-annotate
// Project: https://github.com/Kagami/gulp-ng-annotate
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-ng-annotate" {
namespace ngAnnotate {
interface NgAnnotate {
(option?: Option): NodeJS.ReadWriteStream;
}
//TODO: Should be on ng-annotate module
interface Option {
/**
* Add annotations where non-existing
*/
add?: boolean;
/**
* Remove all existing annotations
*/
remove?: boolean;
/**
* List optional matchers
*/
list?: boolean;
/**
* Restrict matching further or to expand matching
*/
regexp?: string;
/**
* Enable optional matcher
*/
enable?: boolean;
/**
* Output '$scope' instead of "$scope".
*/
single_quotes?: boolean;
/**
* Rename providers (services, factories, controllers, etc.) with a new name when declared and referenced through annotation
*/
rename?: RenameOption[];
/**
* Load a user plugin with the provided path
*/
plugin?: any[];
}
interface RenameOption {
from: string;
to: string;
}
}
var ngAnnotate: ngAnnotate.NgAnnotate;
export = ngAnnotate;
}
+43
View File
@@ -0,0 +1,43 @@
/// <reference path="gulp-nodemon.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import gulp = require('gulp');
import path = require('path');
import nodemon = require('gulp-nodemon');
gulp.task('start', function () {
nodemon({
script: 'server.js'
, ext: 'js html'
, env: { 'NODE_ENV': 'development' }
})
});
nodemon({
script: 'index.js'
, tasks: ['browserify']
});
nodemon({
script: './index.js'
, ext: 'js css'
, tasks: function (changedFiles: string[]): string[] {
var tasks: string[] = [];
changedFiles.forEach(function (file: string) {
if (path.extname(file) === '.js' && !~tasks.indexOf('lint')) tasks.push('lint')
if (path.extname(file) === '.css' && !~tasks.indexOf('cssmin')) tasks.push('cssmin')
});
return tasks
}
});
gulp.task('develop', function () {
nodemon({ script: 'server.js'
, ext: 'html js'
, ignore: ['ignored.js']
, tasks: ['lint'] })
.on('restart', function () {
console.log('restarted!')
})
});
+88
View File
@@ -0,0 +1,88 @@
// Type definitions for gulp-nodemon
// Project: https://github.com/JacksonGariety/gulp-nodemon
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "gulp-nodemon" {
namespace nodemon {
interface Nodemon {
(option?: Option): EventEmitter;
}
interface Option extends _Option {
tasks?: string[]|((changedFiles: string[]) => string[]);
}
// TODO: Properties may be insufficient
// TODO: In future this interface should be moved to nodemon.d.ts
interface _Option {
env?: { [key: string]: string|boolean|number; };
script?: string;
/**
* Extensions to look for, ie. js,jade,hbs.
*/
ext?: string;
/**
* Execute script with "app", ie. -x "python -v".
*/
exec?: string;
/**
* Watch directory "dir" or files. use once for each directory or file to watch.
*/
watch?: string[];
/**
* Ignore specific files or directories.
*/
ignore?: string[];
/**
* Minimise nodemon messages to start/stop only.
*/
quiet?: boolean;
/**
* Show detail on what is causing restarts.
*/
verbose?: boolean;
/**
* Try to read from stdin.
*/
stdin?: boolean;
stdout?: boolean;
/**
* Execute script on change only, not startup
*/
runOnChangeOnly?: boolean;
/**
* Debounce restart in seconds.
*/
delay?: number;
/**
* Forces node to use the most compatible version for watching file changes.
*/
legacyWatch?: boolean;
/**
* Exit on crash, allows use of nodemon with daemon tools like forever.js.
*/
exitcrash?: boolean;
execMap?: { [key: string]: string|boolean|number; };
events?: { [key: string]: string; };
restartable?: string;
}
interface EventEmitter extends NodeJS.EventEmitter {
addListener(event: string, listener: Function): EventEmitter;
addListener(event: string, tasks: string[]): EventEmitter;
on(event: string, listener: Function): EventEmitter;
on(event: string, tasks: string[]): EventEmitter;
once(event: string, listener: Function): EventEmitter;
once(event: string, tasks: string[]): EventEmitter;
}
}
var nodemon: nodemon.Nodemon;
export = nodemon;
}
+1 -1
View File
@@ -1,7 +1,7 @@
/// <reference path="./gulp-sass.d.ts"/>
/// <reference path="../gulp/gulp.d.ts"/>
import gulp = require("gulp");
import sass = require("gulp-sass");
import * as sass from "gulp-sass";
gulp.task('sass', function () {
gulp.src('./scss/*.scss')
+5 -2
View File
@@ -43,7 +43,10 @@ declare module "gulp-sass" {
sync?: boolean;
}
function sass(opts?: Options): NodeJS.ReadWriteStream;
interface Sass {
(opts?: Options): NodeJS.ReadWriteStream;
}
export = sass;
var _tmp: Sass;
export = _tmp;
}
+2
View File
@@ -80,3 +80,5 @@ Handlebars.registerHelper('fullName', (person: typeof context.author) => {
});
var escapedExpression = Handlebars.Utils.escapeExpression('<script>alert(\'xss\');</script>');
Handlebars.helpers !== undefined;
+1
View File
@@ -18,6 +18,7 @@ declare module Handlebars {
export var Utils: typeof hbs.Utils;
export var logger: Logger;
export var templates: HandlebarsTemplates;
export var helpers: any;
export module AST {
export var helpers: hbs.AST.helpers;
+1 -1
View File
@@ -24,7 +24,7 @@ interface HighChartsNGConfig {
currentMin?: number;
currentMax?: number;
title?: { text?: string }
},
};
//Whether to use HighStocks instead of HighCharts (optional). Defaults to false.
useHighStocks?: boolean;
//size (optional) if left out the chart will default to size of the div or something sensible.
+528
View File
@@ -0,0 +1,528 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="inquirer.d.ts" />
import inquirer = require('inquirer');
inquirer.prompt([/* Pass your questions in here */], function( answers: inquirer.Answers ) {
// Use user feedback for... whatever!!
});
//
// examples/bottom-bar.js
//
//var BottomBar = require("../lib/ui/bottom-bar");
var BottomBar = inquirer.ui.BottomBar;
declare var cmdify: any;
var loader = [
"/ Installing",
"| Installing",
"\\ Installing",
"- Installing"
];
var i = 4;
var ui = new BottomBar({ bottomBar: loader[i % 4] });
setInterval(function() {
ui.updateBottomBar( loader[i++ % 4] );
}, 300 );
var spawn = require("child_process").spawn;
var cmd = spawn(cmdify("npm"), [ "-g", "install", "inquirer" ], { stdio: "pipe" });
cmd.stdout.pipe( ui.log );
cmd.on( "close", function() {
ui.updateBottomBar("Installation done!\n");
process.exit();
});
//
// examples/checkbox.js
//
/**
* Checkbox list examples
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt([
{
type: "checkbox",
message: "Select toppings",
name: "toppings",
choices: [
new inquirer.Separator("The usual:"),
{
name: "Peperonni"
},
{
name: "Cheese",
checked: true
},
{
name: "Mushroom"
},
new inquirer.Separator("The extras:"),
{
name: "Pineapple",
},
{
name: "Bacon"
},
{
name: "Olives",
disabled: "out of stock"
},
{
name: "Extra cheese"
}
],
validate: function( answer ) {
if ( answer.length < 1 ) {
return "You must choose at least one topping.";
}
return true;
}
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/expand.js
//
/**
* Expand list examples
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt([
{
type: "expand",
message: "Conflict on `file.js`: ",
name: "overwrite",
choices: [
{
key: "y",
name: "Overwrite",
value: "overwrite"
},
{
key: "a",
name: "Overwrite this one and all next",
value: "overwrite_all"
},
{
key: "d",
name: "Show diff",
value: "diff"
},
new inquirer.Separator(),
{
key: "x",
name: "Abort",
value: "abort"
}
]
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/input.js
//
/**
* Input prompt example
*/
"use strict";
//var inquirer = require("../lib/inquirer");
var questions = [
{
type: "input",
name: "first_name",
message: "What's your first name"
},
{
type: "input",
name: "last_name",
message: "What's your last name",
default: function () { return "Doe"; }
},
{
type: "input",
name: "phone",
message: "What's your phone number",
validate: function( value: string ): string|boolean {
var pass = value.match(/^([01]{1})?[\-\.\s]?\(?(\d{3})\)?[\-\.\s]?(\d{3})[\-\.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i);
if (pass) {
return true;
} else {
return "Please enter a valid phone number";
}
}
}
];
inquirer.prompt( questions, function( answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/list.js
//
/**
* List prompt example
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt([
{
type: "list",
name: "theme",
message: "What do you want to do?",
choices: [
"Order a pizza",
"Make a reservation",
new inquirer.Separator(),
"Ask opening hours",
"Talk to the receptionnist"
]
},
{
type: "list",
name: "size",
message: "What size do you need",
choices: [ "Jumbo", "Large", "Standard", "Medium", "Small", "Micro" ],
filter: function( val: string ) { return val.toLowerCase(); }
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/long-list.js
//
/**
* Paginated list
*/
"use strict";
//var inquirer = require("../lib/inquirer");
var choices = Array.apply(0, new Array(26)).map(function(x: number,y: number) {
return String.fromCharCode(y + 65);
});
choices.push("Multiline option \n super cool feature");
choices.push("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.");
inquirer.prompt([
{
type : "list",
name : "letter",
message : "What's your favorite letter?",
paginated : true,
choices : choices
},
{
type : "checkbox",
name : "name",
message : "Select the letter contained in your name:",
paginated : true,
choices : choices
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/nested-call.js
//
/**
* Nested Inquirer call
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt({
type: "list",
name: "chocolate",
message: "What's your favorite chocolate?",
choices: [ "Mars", "Oh Henry", "Hershey" ]
}, function( answers: inquirer.Answers ) {
inquirer.prompt({
type: "list",
name: "beverage",
message: "And your favorite beverage?",
choices: [ "Pepsi", "Coke", "7up", "Mountain Dew", "Red Bull" ]
});
});
//
// examples/password.js
//
/**
* Password prompt example
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt([
{
type: "password",
message: "Enter your git password",
name: "password"
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/pizza.js
//
/**
* Pizza delivery prompt example
* run example by writing `node pizza.js` in your console
*/
"use strict";
//var inquirer = require("../lib/inquirer");
console.log("Hi, welcome to Node Pizza");
var questions2 = [
{
type: "confirm",
name: "toBeDelivered",
message: "Is it for a delivery",
default: false
},
{
type: "input",
name: "phone",
message: "What's your phone number",
validate: function( value: string ): string|boolean {
var pass = value.match(/^([01]{1})?[\-\.\s]?\(?(\d{3})\)?[\-\.\s]?(\d{3})[\-\.\s]?(\d{4})\s?((?:#|ext\.?\s?|x\.?\s?){1}(?:\d+)?)?$/i);
if (pass) {
return true;
} else {
return "Please enter a valid phone number";
}
}
},
{
type: "list",
name: "size",
message: "What size do you need",
choices: [ "Large", "Medium", "Small" ],
filter: function( val: string ) { return val.toLowerCase(); }
},
{
type: "input",
name: "quantity",
message: "How many do you need",
validate: function( value: string ) {
var valid = !isNaN(parseFloat(value));
return valid || "Please enter a number";
},
filter: Number
},
{
type: "expand",
name: "toppings",
message: "What about the toping",
choices: [
{
key: "p",
name: "Peperonni and chesse",
value: "PeperonniChesse"
},
{
key: "a",
name: "All dressed",
value: "alldressed"
},
{
key: "w",
name: "Hawaïan",
value: "hawaian"
}
]
},
{
type: "rawlist",
name: "beverage",
message: "You also get a free 2L beverage",
choices: [ "Pepsi", "7up", "Coke" ]
},
{
type: "input",
name: "comments",
message: "Any comments on your purchase experience",
default: "Nope, all good!"
},
{
type: "list",
name: "prize",
message: "For leaving a comments, you get a freebie",
choices: [ "cake", "fries" ],
when: function( answers: inquirer.Answers ) {
return answers['comments'] !== "Nope, all good!";
}
}
];
inquirer.prompt( questions, function( answers ) {
console.log("\nOrder receipt:");
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/rawlist.js
//
/**
* Raw List prompt example
*/
"use strict";
//var inquirer = require("../lib/inquirer");
inquirer.prompt([
{
type: "rawlist",
name: "theme",
message: "What do you want to do?",
choices: [
"Order a pizza",
"Make a reservation",
new inquirer.Separator(),
"Ask opening hours",
"Talk to the receptionnist"
]
},
{
type: "rawlist",
name: "size",
message: "What size do you need",
choices: [ "Jumbo", "Large", "Standard", "Medium", "Small", "Micro" ],
filter: function( val: string ) { return val.toLowerCase(); }
}
], function( answers: inquirer.Answers ) {
console.log( JSON.stringify(answers, null, " ") );
});
//
// examples/recursive.js
//
/**
* Recursive prompt example
* Allows user to choose when to exit prompt
*/
"use strict";
//var inquirer = require("../lib/inquirer");
var output2: (string|boolean)[] = [];
var questions3 = [
{
type: "input",
name: "tvShow",
message: "What's your favorite TV show?"
},
{
type: "confirm",
name: "askAgain",
message: "Want to enter another TV show favorite (just hit enter for YES)?",
default: true
}
];
function ask() {
inquirer.prompt( questions3, function( answers: inquirer.Answers ) {
output2.push( answers['tvShow'] );
if ( answers['askAgain'] ) {
ask();
} else {
console.log( "Your favorite TV Shows:", output2.join(", ") );
}
});
}
ask();
//
// examples/when.js
//
/**
* When example
*/
"use strict";
//var inquirer = require("../lib/inquirer");
var questions4 = [
{
type: "confirm",
name: "bacon",
message: "Do you like bacon?"
},
{
type: "input",
name: "favorite",
message: "Bacon lover, what is your favorite type of bacon?",
when: function ( answers: inquirer.Answers ) {
return answers['bacon'];
}
},
{
type: "confirm",
name: "pizza",
message: "Ok... Do you like pizza?",
when: function (answers: inquirer.Answers) {
return !likesFood( "bacon" )(answers);
}
},
{
type: "input",
name: "favorite",
message: "Whew! What is your favorite type of pizza?",
when: likesFood( "pizza" )
}
];
function likesFood ( aFood: string ) {
return function ( answers: inquirer.Answers ) {
return answers[ aFood ];
}
}
inquirer.prompt(questions, function (answers) {
console.log( JSON.stringify(answers, null, " ") );
});
+299
View File
@@ -0,0 +1,299 @@
// Type definitions for Inquirer.js
// Project: https://github.com/SBoudrias/Inquirer.js
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../rx/rx-lite.d.ts" />
/// <reference path="../through/through.d.ts" />
declare module "inquirer" {
import through = require('through');
namespace inquirer {
type Prompts = { [name: string]: PromptModule };
type ChoiceType = string|objects.ChoiceOption|objects.Separator;
type Questions = Question|Question[]|Rx.Observable<Question>;
interface Inquirer {
restoreDefaultPrompts(): void;
/**
* Expose helper functions on the top level for easiest usage by common users
* @param name
* @param prompt
*/
registerPrompt(name: string, prompt: PromptModule): void;
/**
* Create a new self-contained prompt module.
*/
createPromptModule(): PromptModule;
/**
* Public CLI helper interface
* @param questions Questions settings array
* @param cb Callback being passed the user answers
* @return
*/
prompt(questions: Questions, cb?: (answers: Answers) => any): ui.Prompt;
prompts: Prompts;
Separator: objects.SeparatorStatic;
ui: {
BottomBar: ui.BottomBar;
Prompt: ui.Prompt;
}
}
interface PromptModule {
(questions: Questions, cb: (answers: Answers) => any): ui.Prompt;
/**
* Register a prompt type
* @param name Prompt type name
* @param prompt Prompt constructor
*/
registerPrompt(name: string, prompt: PromptModule): ui.Prompt;
/**
* Register the defaults provider prompts
*/
restoreDefaultPrompts(): void;
}
interface Question {
/**
* Type of the prompt.
* Possible values:
* <ul>
* <li>input</li>
* <li>confirm</li>
* <li>list</li>
* <li>rawlist</li>
* <li>password</li>
* </ul>
* @defaults: 'input'
*/
type?: string;
/**
* The name to use when storing the answer in the anwers hash.
*/
name?: string;
/**
* The question to print. If defined as a function,
* the first parameter will be the current inquirer session answers.
*/
message?: string|((answers: Answers) => string);
/**
* Default value(s) to use if nothing is entered, or a function that returns the default value(s).
* If defined as a function, the first parameter will be the current inquirer session answers.
*/
default?: any|((answers: Answers) => any);
/**
* Choices array or a function returning a choices array. If defined as a function,
* the first parameter will be the current inquirer session answers.
* Array values can be simple strings, or objects containing a name (to display) and a value properties
* (to save in the answers hash). Values can also be a Separator.
*/
choices?: ChoiceType[]|((answers: Answers) => ChoiceType[]);
/**
* Receive the user input and should return true if the value is valid, and an error message (String)
* otherwise. If false is returned, a default error message is provided.
*/
validate?(input: string): boolean|string;
/**
* Receive the user input and return the filtered value to be used inside the program.
* The value returned will be added to the Answers hash.
*/
filter?(input: string): string;
/**
* Receive the current user answers hash and should return true or false depending on whether or
* not this question should be asked. The value can also be a simple boolean.
*/
when?: boolean|((answers: Answers) => boolean);
paginated?: boolean;
}
/**
* A key/value hash containing the client answers in each prompt.
*/
interface Answers {
[key: string]: string|boolean;
}
namespace ui {
/**
* Base interface class other can inherits from
*/
interface Prompt extends BaseUI<Prompts> {
new(promptModule: Prompts): Prompt;
/**
* Once all prompt are over
*/
onCompletion(): void;
processQuestion(question: Question): any;
fetchAnswer(question: Question): any;
setDefaultType(question: Question): any;
filterIfRunnable(question: Question): any;
}
/**
* Sticky bottom bar user interface
*/
interface BottomBar extends BaseUI<BottomBarOption> {
new(opt?: BottomBarOption): BottomBar;
/**
* Render the prompt to screen
* @return self
*/
render(): BottomBar;
/**
* Update the bottom bar content and rerender
* @param bottomBar Bottom bar content
* @return self
*/
updateBottomBar(bottomBar: string): BottomBar;
/**
* Rerender the prompt
* @return self
*/
writeLog(data: any): BottomBar;
/**
* Make sure line end on a line feed
* @param str Input string
* @return The input string with a final line feed
*/
enforceLF(str: string): string;
/**
* Helper for writing message in Prompt
* @param message The message to be output
*/
write(message: string): void;
log: through.ThroughStream;
}
interface BottomBarOption {
bottomBar?: string;
}
/**
* Base interface class other can inherits from
*/
interface BaseUI<TOpt> {
new(opt: TOpt): void;
/**
* Handle the ^C exit
* @return {null}
*/
onForceClose(): void;
/**
* Close the interface and cleanup listeners
*/
close(): void;
/**
* Handle and propagate keypress events
*/
onKeypress(s: string, key: Key): void;
}
interface Key {
sequence: string;
name: string;
meta: boolean;
shift: boolean;
ctrl: boolean;
}
}
namespace objects {
/**
* Choice object
* Normalize input as choice object
* @constructor
* @param {String|Object} val Choice value. If an object is passed, it should contains
* at least one of `value` or `name` property
*/
interface Choice {
new(str: string): Choice;
new(separator: Separator): Choice;
new(option: ChoiceOption): Choice;
}
interface ChoiceOption {
name?: string;
value?: string;
type?: string;
extra?: any;
key?: string;
checked?: boolean;
disabled?: string|((answers: Answers) => any);
}
/**
* Choices collection
* Collection of multiple `choice` object
* @constructor
* @param choices All `choice` to keep in the collection
*/
interface Choices {
new(choices: (string|Separator|ChoiceOption)[], answers?: Answers): Choices;
choices: Choice[];
realChoices: Choice[];
length: number;
realLength: number;
/**
* Get a valid choice from the collection
* @param selector The selected choice index
* @return Return the matched choice or undefined
*/
getChoice(selector: number): Choice;
/**
* Get a raw element from the collection
* @param selector The selected index value
* @return Return the matched choice or undefined
*/
get(selector: number): Choice;
/**
* Match the valid choices against a where clause
* @param whereClause Lodash `where` clause
* @return Matching choices or empty array
*/
where<U extends {}>(whereClause: U): Choice[];
/**
* Pluck a particular key from the choices
* @param propertyName Property name to select
* @return Selected properties
*/
pluck(propertyName: string): any[];
forEach<T>(application: (choice: Choice) => T): T[];
}
interface SeparatorStatic {
/**
* @param line Separation line content (facultative)
*/
new(line?: string): Separator;
/**
* Helper function returning false if object is a separator
* @param obj object to test against
* @return `false` if object is a separator
*/
exclude(obj: any): boolean;
}
/**
* Separator object
* Used to space/separate choices group
* @constructor
* @param {String} line Separation line content (facultative)
*/
interface Separator {
type: string;
line: string;
/**
* Stringify separator
* @return {String} the separator display string
*/
toString(): string;
}
}
}
var inquirer: inquirer.Inquirer;
export = inquirer;
}
@@ -0,0 +1,287 @@
/// <reference path="../jquery-ajax-chain/jquery-ajax-chain.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../core-js/core-js.d.ts" />
function test_public_methods(): void {
let ajaxChain: ajaxChain.JQueryAjaxChain,
configurationObj1: ajaxChain.AjaxChainConfiguration,
configurationObj2: ajaxChain.AjaxChainConfiguration;
configurationObj1 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/endpoint1'
}
};
configurationObj2 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/endpoint2'
}
};
ajaxChain.enqueue(configurationObj1);
ajaxChain.clearQueue();
ajaxChain.enqueue([configurationObj1, configurationObj2]);
ajaxChain.dequeue().then(doneResult => { console.log(doneResult); },
failResult => { console.log(failResult); },
progressResult => { console.log(progressResult); });
}
function test_optional_parameters(): void {
let itemsCollectionCache: XMLDocument = null,
itemDetailCacheMap: WeakMap<String, XMLDocument> = new WeakMap<String, XMLDocument>(),
ajaxChain: ajaxChain.JQueryAjaxChain,
configurationObj1: ajaxChain.AjaxChainConfiguration,
configurationObj2: ajaxChain.AjaxChainConfiguration,
configurationObj3: ajaxChain.AjaxChainConfiguration,
configurationObj4: ajaxChain.AjaxChainConfiguration;
ajaxChain = new $.AjaxChain();
configurationObj1 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/items',
success: function (xmlResponse): void {
itemsCollectionCache = xmlResponse;
},
},
hasHaltingCapabilities: function (xmlResponse): Boolean {
let $tempXmlResponse: JQuery;
$tempXmlResponse = $(xmlResponse);
if (!$tempXmlResponse.find('item').length) {
return true;
}
return false;
},
hasCache: function (xmlResponse): XMLDocument {
if (itemsCollectionCache) {
return itemsCollectionCache;
};
return null;
},
transform: function (xmlResponse): Object {
let $tempXmlResponse: JQuery,
$tempItems: JQuery,
nextCallDataObj: Object;
$tempXmlResponse = $(xmlResponse);
$tempItems = $tempXmlResponse.find('item');
if ($tempItems.length) {
nextCallDataObj = {
id: $tempItems.first()
.attr('id')
};
return nextCallDataObj;
}
return null;
}
};
configurationObj2 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/item',
success: function (xmlResponse): void {
let $tempXmlResponse: JQuery,
itemId: String;
$tempXmlResponse = $(xmlResponse);
itemId = $tempXmlResponse.find('id')
.text();
if (itemId && !itemDetailCacheMap.has(itemId)) {
itemDetailCacheMap.set(itemId, xmlResponse);
}
}
},
transform: function (xmlResponse): String {
let $tempXmlResponse: JQuery,
tempTrackingCode: String,
nextCallDataStr: String = "";
$tempXmlResponse = $(xmlResponse);
tempTrackingCode = $tempXmlResponse.find('code')
.text();
if (tempTrackingCode) {
nextCallDataStr = "tracking=" + tempTrackingCode;
}
return nextCallDataStr;
},
hasCache: function (xmlResponse): XMLDocument {
let $tempXmlResponse: JQuery,
itemId: String;
$tempXmlResponse = $(xmlResponse);
itemId = $tempXmlResponse.find('id')
.text();
if (itemDetailCacheMap.has(itemId)) {
return itemDetailCacheMap.get(itemId);
}
return null;
},
hasErrors: function (xmlResponse): String {
var $tempXmlResponse: JQuery,
categoryFilter: string = '1';
$tempXmlResponse = $(xmlResponse);
if ($tempXmlResponse.find('categoryId')
.text() === categoryFilter) {
return '[Exception] forbidden category id: ' + categoryFilter;
}
return '';
},
appendToUrl: function (xmlResponse): String {
let $tempXmlResponse: JQuery,
categoryId: string = '';
$tempXmlResponse = $(xmlResponse);
categoryId = $tempXmlResponse.find('categoryId')
.text();
return (categoryId) ? ('/' + categoryId) : '';
}
};
configurationObj3 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/categories'
},
isSkippable: function (xmlResponse): Boolean {
return true;
},
transform: function (xmlResponse): Object[] {
let $tempXmlResponse: JQuery,
nextCallDataArr: Object[] = [];
$tempXmlResponse = $(xmlResponse);
$tempXmlResponse.find('subCategory').each(function (index, node) {
let $tempIdNode = $(node).find('id');
nextCallDataArr.push({
name: $tempIdNode.attr('name'),
value: $tempIdNode.text()
});
});
return nextCallDataArr;
}
};
configurationObj4 = {
ajaxSettings: {
type: 'GET',
dataType: 'xml',
url: '/subcategories'
}
};
ajaxChain.enqueue([configurationObj1, configurationObj2, configurationObj3, configurationObj4])
.dequeue()
.then(doneResult => { console.log(doneResult); },
failResult => { console.log(failResult); },
progressResult => { console.log(progressResult); });
}
+97
View File
@@ -0,0 +1,97 @@
// Type definitions for jquery-ajax-chain v 1.0.4
// Project: https://github.com/humana-fragilitas/jQuery-Ajax-Chain/
// Definitions by: Andrea Blasio <https://github.com/humana-fragilitas>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module ajaxChain {
/**
* Static members of JQueryAjaxChain
*/
interface JQueryAjaxChainStatic {
new (): JQueryAjaxChain
}
/**
* Instance members of JQueryAjaxChain
*/
interface JQueryAjaxChain extends JQueryPromise<any> {
/**
* Enqueues one or more configuration objects for later processing.
*/
enqueue(confObj: AjaxChainConfiguration | AjaxChainConfiguration[]): JQueryAjaxChain;
/**
* Sequentially and synchronously dequeues the configuration objects enqueued via enqueue() method
* in the order they were added, triggering the related Ajax calls.
*/
dequeue(): JQueryAjaxChain;
/**
* Clears the currently queued configuration objects.
*/
clearQueue(): JQueryAjaxChain;
}
/**
* A set of key/value pairs that configure the AjaxChain request; 'ajaxSettings' is mandatory.
*/
interface AjaxChainConfiguration {
/**
* jQuery $.ajax method settings (required).
*/
ajaxSettings: JQueryAjaxSettings;
/**
* Configuration object label (optional).
*/
label?: String;
/**
* Returning a truthy value (Object) allows to arbitrarily overwrite the next queued Ajax call
* 'data' property value specified in the original jQuery $.ajax method configuration
* object ('ajaxSettings') (optional).
*/
transform?: (response: any) => String | Object | Object[];
/**
* Returning a truthy value (String) allows to append a string to the next queued
* Ajax call 'url' property value specified in original jQuery $.ajax method configuration
* object ('ajaxSettings') (optional).
*/
appendToUrl?: (response: any) => String;
/**
* Returning a truthy value determines any registered fail callback(s) to be called immediately,
* passing the former as an argument to the latter; the queue is then rejected (optional).
*/
hasErrors?: (response: any) => any;
/**
* Returning a truthy value allows to prevent the related Ajax call from being executed,
* passing the former as a parameter to any registered handler(s); useful to create
* caching mechanisms (optional).
*/
hasCache?: (response: any) => any;
/**
* Returning a truthy value prevents the queue from further progressing to the succeeding
* Ajax calls; the queue is then resolved (optional).
*/
hasHaltingCapabilities?: (response: any) => Boolean;
/**
* Returning a truthy value prevents the queue from being halted in case of Ajax error (optional).
*/
isSkippable?: (response: any) => Boolean;
}
}
interface JQueryStatic {
/**
* JQueryAjaxChain constructor
*/
AjaxChain: ajaxChain.JQueryAjaxChainStatic;
}
+2 -2
View File
@@ -4,7 +4,7 @@
function testRawApi(){
var inputElement:HTMLInputElement = null;
var resultPromise = AjaxFile.send({
var resultPromise = AjaxFile.send<number>({
method: 'POST',
url: '/',
desiredResponseDataType: JQueryAjaxFile.DataType.Json,
@@ -42,7 +42,7 @@ function testJQuery() {
global: true,
timeout: 60
};
extension.ajaxWithFile(option);
extension.ajaxWithFile<number>(option);
}
function testKnockoutExtension(){
+12 -11
View File
@@ -1,4 +1,4 @@
// Type definitions for jquery.ajaxfile v0.1.0
// Type definitions for jquery.ajaxfile v0.2.0
// Project: https://github.com/fpellet/jquery.ajaxFile
// Definitions by: Florent PELLET <https://github.com/fpellet/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -35,27 +35,28 @@ declare namespace JQueryAjaxFile {
isSuccess: boolean;
}
interface IAjaxFileResult {
interface IAjaxFileResult<T> {
error?: any;
data?: any;
status?: IResponseStatus;
}
interface IAjaxFileResultCallback {
(result: IAjaxFileResult): void;
interface IAjaxFileResultCallback<T> {
(result: IAjaxFileResult<T>): void;
}
interface IAjaxFilePromise {
then(success: IAjaxFileResultCallback, error?: IAjaxFileResultCallback): IAjaxFilePromise;
done(success: IAjaxFileResultCallback): IAjaxFilePromise;
fail(error: IAjaxFileResultCallback): IAjaxFilePromise;
always(error: IAjaxFileResultCallback): IAjaxFilePromise;
interface IAjaxFilePromise<T> {
then(success: IAjaxFileResultCallback<T>, error?: IAjaxFileResultCallback<T>): IAjaxFilePromise<T>;
done(success: IAjaxFileResultCallback<T>): IAjaxFilePromise<T>;
fail(error: IAjaxFileResultCallback<T>): IAjaxFilePromise<T>;
always(error: IAjaxFileResultCallback<T>): IAjaxFilePromise<T>;
abord(): void;
}
interface IAjaxFileStatic {
send(option: IOption): IAjaxFilePromise;
DataType: typeof DataType;
send<T>(option: IOption): IAjaxFilePromise<T>;
}
interface IJQueryXHR {
@@ -97,7 +98,7 @@ declare namespace JQueryAjaxFile {
}
interface IAjaxFileJQueryExtension {
ajaxWithFile(jqueryOption: IJQueryOption): JQueryDeferred<any>;
ajaxWithFile<T>(jqueryOption: IJQueryOption): JQueryDeferred<T>;
}
}
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for karma v0.12.37
// Project: https://github.com/karma-runner/karma
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'karma' {
// See Karma public API https://karma-runner.github.io/0.12/dev/public-api.html
interface IKarmaServer {
start(options?: any, callback?: (exitCode: number) => void): void;
}
interface IKarmaRunner {
run(options?: any, callback?: (exitCode: number) => void): void;
}
interface IKarma {
server: IKarmaServer;
runner: IKarmaRunner;
}
var karma: IKarma;
export = karma;
}
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="karma-0.12.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import gulp = require('gulp');
import karma = require('karma');
function runKarma(singleRun: boolean): void {
karma.server.start({
configFile: __dirname + '/karma.conf.js',
singleRun: singleRun
});
}
gulp.task('test:unit:karma', ['build:test:unit'], () => runKarma(true));
karma.server.start({port: 9876}, (exitCode: number) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
karma.runner.run({port: 9876}, (exitCode: number) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
+34 -6
View File
@@ -4,23 +4,51 @@
import gulp = require('gulp');
import karma = require('karma');
function runKarma(singleRun: boolean): void {
karma.server.start({
configFile: __dirname + '/karma.conf.js',
singleRun: singleRun
});
// MEMO: `start` method is deprecated since 0.13. It will be removed in 0.14.
karma.server.start({
configFile: __dirname + '/karma.conf.js',
singleRun: singleRun
});
}
gulp.task('test:unit:karma', ['build:test:unit'], () => runKarma(true));
karma.server.start({port: 9876}, (exitCode) => {
karma.server.start({port: 9876}, (exitCode: number) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
karma.runner.run({port: 9876}, (exitCode) => {
karma.runner.run({port: 9876}, (exitCode: number) => {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
var Server = require('karma').Server;
var server = new Server({port: 9876}, function(exitCode: number) {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
server.start();
server.refreshFiles();
server.on('browser_register', function (browser: any) {
console.log('A new browser was registered');
});
var runner = require('karma').runner;
runner.run({port: 9876}, function(exitCode: number) {
console.log('Karma has exited with ' + exitCode);
process.exit(exitCode);
});
//
var captured: boolean = karma.launcher.areAllCaptured();
+356 -12
View File
@@ -1,24 +1,368 @@
// Type definitions for karma v0.12.37
// Type definitions for karma v0.13.9
// Project: https://github.com/karma-runner/karma
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="../log4js/log4js.d.ts" />
declare module 'karma' {
// See Karma public API https://karma-runner.github.io/0.12/dev/public-api.html
import Promise = require('bluebird');
import https = require('https');
import log4js = require('log4js');
interface IKarmaServer {
start(options?: any, callback?: (exitCode: number) => void): void;
namespace karma {
interface Karma {
/**
* `start` method is deprecated since 0.13. It will be removed in 0.14.
* Please use
* <code>
* server = new Server(config, [done])
* server.start()
* </code>
* instead.
*/
server: DeprecatedServer;
Server: Server;
runner: Runner;
launcher: Launcher;
VERSION: string;
}
interface LauncherStatic {
generateId(): string;
//TODO: injector should be of type `di.Injector`
new(emitter: NodeJS.EventEmitter, injector: any): Launcher;
}
interface Launcher {
Launcher: LauncherStatic;
//TODO: Can this return value ever be typified?
launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[];
kill(id: string, callback: Function): boolean;
restart(id: string): boolean;
killAll(callback: Function): void;
areAllCaptured(): boolean;
markCaptured(id: string): void;
}
interface DeprecatedServer {
start(options?: any, callback?: ServerCallback): void;
}
interface Runner {
run(options?: Config, callback?: ServerCallback): void;
}
interface Server extends NodeJS.EventEmitter {
new(options?: Config, callback?: ServerCallback): Server;
/**
* Start the server
*/
start(): void;
/**
* Get properties from the injector
* @param token
*/
get(token: string): any;
/**
* Force a refresh of the file list
*/
refreshFiles(): Promise<any>;
///**
// * Backward-compatibility with karma-intellij bundled with WebStorm.
// * Deprecated since version 0.13, to be removed in 0.14
// */
//static start(): void;
}
interface ServerCallback {
(exitCode: number): void;
}
interface Config {
/**
* @description Enable or disable watching files and executing the tests whenever one of these files changes.
* @default true
*/
autoWatch?: boolean;
/**
* @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run
* so that the test runner doesn't try to start and restart running tests more than it should.
* The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred
* before starting the test process again.
* @default 250
*/
autoWatchBatchDelay?: number;
/**
* @default ''
* @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>.
* If the basePath configuration is a relative path then it will be resolved to
* the <code>__dirname</code> of the configuration file.
*/
basePath?: string;
/**
* @default 2000
* @description How long does Karma wait for a browser to reconnect (in ms).
* <p>
* With a flaky connection it is pretty common that the browser disconnects,
* but the actual test execution is still running without any problems. Karma does not treat a disconnection
* as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms).
* If the browser reconnects during that time, everything is fine.
* </p>
*/
browserDisconnectTimeout?: number;
/**
* @default 0
* @description The number of disconnections tolerated.
* <p>
* The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt
* in the case of a disconnection. Usually any disconnection is considered a failure,
* but this option allows you to define a tolerance level when there is a flaky network link between
* the Karma server and the browsers.
* </p>
*/
browserDisconnectTolerance?: number;
/**
* @default 10000
* @description How long will Karma wait for a message from a browser before disconnecting from it (in ms).
* <p>
* If, during test execution, Karma does not receive any message from a browser within
* <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser
* </p>
*/
browserNoActivityTimeout?: number;
/**
* @default []
* Possible Values:
* <ul>
* <li>Chrome (launcher comes installed with Karma)</li>
* <li>ChromeCanary (launcher comes installed with Karma)</li>
* <li>PhantomJS (launcher comes installed with Karma)</li>
* <li>Firefox (launcher requires karma-firefox-launcher plugin)</li>
* <li>Opera (launcher requires karma-opera-launcher plugin)</li>
* <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li>
* <li>Safari (launcher requires karma-safari-launcher plugin)</li>
* </ul>
* @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser
* which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well.
* You can capture any browser manually by opening the browser and visiting the URL where
* the Karma web server is listening (by default it is <code>http://localhost:9876/</code>).
*/
browsers?: string[];
/**
* @default 60000
* @description Timeout for capturing a browser (in ms).
* <p>
* The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a
* browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma
* will kill it and try to launch it again and, after three attempts to capture it, Karma will give up.
* </p>
*/
captureTimeout?: number;
client?: ClientConfig;
/**
* @default true
* @description Enable or disable colors in the output (reporters and logs).
*/
colors?: boolean;
/**
* @default []
* @description List of files/patterns to exclude from loaded files.
*/
exclude?: string[];
/**
* @default []
* @description List of files/patterns to load in the browser.
*/
files?: (FilePattern|string)[];
/**
* @default []
* @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...
* Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).
*/
frameworks?: string[];
/**
* @default 'localhost'
* @description Hostname to be used when capturing browsers.
*/
hostname?: string;
/**
* @default {}
* @description Options object to be used by Node's https class.
* Object description can be found in the
* [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener)
*/
httpsServerOptions?: https.ServerOptions;
/**
* @default config.LOG_INFO
* Possible values:
* <ul>
* <li>config.LOG_DISABLE</li>
* <li>config.LOG_ERROR</li>
* <li>config.LOG_WARN</li>
* <li>config.LOG_INFO</li>
* <li>config.LOG_DEBUG</li>
* </ul>
* @description Level of logging.
*/
logLevel?: string;
/**
* @default [{type: 'console'}]
* @description A list of log appenders to be used. See the documentation for [log4js] for more information.
*/
loggers?: log4js.AppenderConfigBase[];
/**
* @default ['karma-*']
* @description List of plugins to load. A plugin can be a string (in which case it will be required
* by Karma) or an inlined plugin - Object.
* By default, Karma loads all sibling NPM modules which have a name starting with karma-*.
* Note: Just about all plugins in Karma require an additional library to be installed (via NPM).
*/
plugins?: any[];
/**
* @default 9876
* @description The port where the web server will be listening.
*/
port?: number;
/**
* @default {'**\/*.coffee': 'coffee'}
* @description A map of preprocessors to use.
*
* Preprocessors can be loaded through [plugins].
*
* Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults)
* require an additional library to be installed (via NPM).
*
* Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance,
* if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug
* your tests, you'll discover that your expected source code is completely changed from what you expected. Because
* of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list,
* but your interactive debugging does not.
*
*/
preprocessors?: { [name: string]: string|string[] }
/**
* @default 'http:'
* Possible Values:
* <ul>
* <li>http:</li>
* <li>https:</li>
* </ul>
* @description Protocol used for running the Karma webserver.
* Determines the use of the Node http or https class.
* Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>.
*/
protocol?: string;
/**
* @default {}
* @description A map of path-proxy pairs.
*/
proxies?: { [path: string]: string }
/**
* @default true
* @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found.
*/
proxyValidateSSL?: boolean;
/**
* @default 0
* @description Karma will report all the tests that are slower than given time limit (in ms).
* This is disabled by default (since the default value is 0).
*/
reportSlowerThan?: number;
/**
* @default ['progress']
* Possible Values:
* <ul>
* <li>dots</li>
* <li>progress</li>
* </ul>
* @description A list of reporters to use.
* Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins.
* Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM).
*/
reporters?: string[];
/**
* @default false
* @description Continuous Integration mode.
* If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending
* on whether all tests passed or any tests failed.
*/
singleRun?: boolean;
/**
* @default ['polling', 'websocket']
* @description An array of allowed transport methods between the browser and testing server. This configuration setting
* is handed off to [socket.io](http://socket.io/) (which manages the communication
* between browsers and the testing server).
*/
transports?: string[];
/**
* @default '/'
* @description The base url, where Karma runs.
* All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as
* sometimes you might want to proxy a url that is already taken by Karma.
*/
urlRoot?: string;
}
interface ClientConfig {
/**
* @default undefined
* @description When karma run is passed additional arguments on the command-line, they
* are passed through to the test adapter as karma.config.args (an array of strings).
* The client.args option allows you to set this value for actions other than run.
* How this value is used is up to your test adapter - you should check your adapter's
* documentation to see how (and if) it uses this value.
*/
args?: string[];
/**
* @default true
* @description Run the tests inside an iFrame or a new window
* If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an
* iFrame and may need a new window to run.
*/
useIframe?: boolean;
/**
* @default true
* @description Capture all console output and pipe it to the terminal.
*/
captureConsole?: boolean;
}
interface FilePattern {
/**
* The pattern to use for matching. This property is mandatory.
*/
pattern: string;
/**
* @default true
* @description If <code>autoWatch</code> is true all files that have set watched to true will be watched
* for changes.
*/
watched?: boolean;
/**
* @default true
* @description Should the files be included in the browser using <script> tag? Use false if you want to
* load them manually, eg. using Require.js.
*/
included?: boolean;
/**
* @default true
* @description Should the files be served by Karma's webserver?
*/
served?: boolean;
/**
* @default false
* @description Should the files be served from disk on each request by Karma's webserver?
*/
nocache?: boolean;
}
}
interface IKarmaRunner {
run(options?: any, callback?: (exitCode: number) => void): void;
}
var karma: karma.Karma;
interface IKarma {
server: IKarmaServer;
runner: IKarmaRunner;
}
var karma: IKarma;
export = karma;
}
+222
View File
@@ -0,0 +1,222 @@
/// <reference path="./kefir.d.ts" />
import * as Kefir from 'kefir';
import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'kefir';
//Create a stream
{
let stream01: Stream<void, void> = Kefir.never();
let stream02: Stream<number, void> = Kefir.later(1000, 1);
let stream03: Stream<number, void> = Kefir.interval(1000, 1);
let stream04: Stream<number, void> = Kefir.sequentially(1000, [1, 2, 3]);
{
let start = +new Date();
let stream05: Stream<number, void> = Kefir.fromPoll(1000, () => +new Date() - start);
}
{
let start = +new Date();
let stream06: Stream<number, void> = Kefir.withInterval<number, void>(1000, function(emitter) {
var time = +new Date() - start;
if (time < 4000) {
emitter.emit(time);
} else {
emitter.end();
}
});
}
let stream07: Stream<number, void> = Kefir.fromCallback<number>(callback => setTimeout(() => callback(1), 1000));
let stream08: Stream<number, void> = Kefir.fromNodeCallback<number, void>(callback => setTimeout(() => callback(null, 1), 1000));
let stream09: Stream<MouseEvent, void> = Kefir.fromEvents<MouseEvent, void>(document.body, 'click');
let stream10: Stream<number, void> = Kefir.stream<number, void>(emitter => {
let count = 0;
emitter.emit(count);
let intervalId = setInterval(() => {
count++;
if (count < 4) {
emitter.emit(count);
} else {
emitter.end();
}
}, 1000);
return () => clearInterval(intervalId);
});
}
// Create a property
{
let property01: Property<number, void> = Kefir.constant(1);
let property02: Property<void, number> = Kefir.constantError(1);
let property03: Property<number, void> = Kefir.fromPromise<number, void>(new Promise<number>(fulfill => fulfill(1)));
}
// Convert observables
{
let property: Property<number, void> = Kefir.sequentially(100, [1, 2, 3]).toProperty(() => 0);
let stream: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).toProperty(() => 0).changes();
}
// Subscribe / add side effects
{
Kefir.sequentially(1000, [1, 2]).onValue(x => console.log('value:', x));
Kefir.sequentially(1000, [1, 2]).offValue(x => console.log('value:', x));
Kefir.sequentially(1000, [1, 2]).valuesToErrors().onValue(x => console.log('error:', x));
Kefir.sequentially(1000, [1, 2]).valuesToErrors().offValue(x => console.log('error:', x));
Kefir.sequentially(1000, [1, 2]).onEnd(() => console.log('stream ended'));
Kefir.sequentially(1000, [1, 2]).offEnd(() => console.log('stream ended'));
Kefir.sequentially(1000, [1, 2]).onAny(event => console.log('event:', event));
Kefir.sequentially(1000, [1, 2]).offAny(event => console.log('event:', event));
Kefir.sequentially(1000, [1, 2]).log('my stream');
Kefir.sequentially(1000, [1, 2]).offLog('my stream');
Kefir.sequentially(1000, [1, 2]).toPromise().then(x => console.log('fulfilled with:', x));
}
// Modify an observable
{
let observable01: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).map(x => x + 1);
let observable02: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).filter(x => x > 1);
let observable03: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).take(2);
let observable04: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).takeWhile(x => x < 3);
let observable05: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).last();
let observable06: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).skip(2);
let observable07: Stream<number, void> = Kefir.sequentially(100, [1, 3, 2]).skipWhile(x => x < 3);
let observable08: Stream<number, void> = Kefir.sequentially(100, [1, 2, 2, 3, 1]).skipDuplicates();
let observable09: Stream<number, void> = Kefir.sequentially(100, [1, 2, 2.1, 3, 1]).skipDuplicates((a, b) => Math.round(a) === Math.round(b));
let observable10: Stream<number, void> = Kefir.sequentially(100, [1, 2, 2, 3]).diff((prev, next) => next - prev, 0);
let observable11: Stream<number, void> = Kefir.sequentially(100, [1, 2, 2, 3]).scan((prev, next) => next + prev, 0);
let observable12: Stream<number, void> = Kefir.sequentially(100, [[1], [], [2,3]]).flatten<number>();
let observable13: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4]).flatten<number>(x => x % 2 === 0 ? [x * 10] : []);
let observable14: Stream<number, void> = Kefir.sequentially(200, [1, 2, 3]).delay(100);
let observable15: Stream<number, void> = Kefir.sequentially(750, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]).throttle(2500);
let observable16: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 0, 0, 0, 4, 5, 6]).filter(x => x > 0).debounce(250);
let observable17: Stream<void, number> = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors<number>(x => {
return {convert: x < 0, error: x * 2};
});
let observable18: Stream<number, void> = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors<number>().errorsToValues<number>((x: number) => {
return {convert: x >= 0, value: x * 2};
});
let observable19: Stream<void, number> = Kefir.sequentially(100, [0, 1, 2, 3]).valuesToErrors<number>().mapErrors((x: number) => x * 2);
let observable20: Stream<void, number> = Kefir.sequentially(100, [0, 1, 2, 3]).valuesToErrors<number>().filterErrors((x: number) => (x % 2) === 0);
let observable21: Stream<void, number> = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors(x => {
return {convert: x < 0, error: x};
}).endOnError();
let observable22: Stream<void, number> = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors(x => {
return {convert: x < 0, error: x};
}).skipValues();
let observable23: Stream<void, void> = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors(x => {
return {convert: x < 0, error: x};
}).skipErrors();
let observable24: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).skipEnd();
let ovservable25: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).beforeEnd(() => 0);
let observable26: Stream<number[], void> = Kefir.sequentially(100, [1, 2, 3, 4, 5]).slidingWindow(3, 2)
let observable27: Stream<number[], void> = Kefir.sequentially(100, [1, 2, 3, 4, 5]).bufferWhile(x => x !== 3);
{
var myTransducer: any;
let observable28: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6]).transduce<number>(myTransducer);
}
let observable28: Stream<number | string, void> = Kefir.sequentially(100, [0, 1, 2, 3]).withHandler<number | string, void>((emitter: Emitter<string | number, void>, event: Event<number>) => {
if (event.type === 'end') {
emitter.emit('bye');
emitter.end();
}
if (event.type === 'value') {
for (var i = 0; i < event.value; i++) {
emitter.emit(event.value);
}
}
});
}
// Combine observables
{
{
let a: Stream<number, void> = Kefir.sequentially(100, [1, 3]);
let b: Stream<number, void> = Kefir.sequentially(100, [2, 4]).delay(40);
let observable01: Observable<number, void> = Kefir.combine<number, void, number>([a, b], (a, b) => a + b);
}
{
let a: Stream<number, void> = Kefir.sequentially(100, [1, 3]);
let b: Stream<number, void> = Kefir.sequentially(100, [2, 4]).delay(40);
let c: Stream<number, void> = Kefir.sequentially(60, [5, 6, 7]);
let observable02: Observable<number, void> = Kefir.combine<number, void, number>([a, b], [c], (a, b, c) => a + b + c);
}
{
let a: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2, 3]);
let b: Stream<number, void> = Kefir.sequentially(160, [4, 5, 6]);
let c: Property<number, void> = Kefir.sequentially(100, [8, 9]).delay(260).toProperty(() => 7);
let observable03: Observable<number, void> = Kefir.zip<number, void, number>([a, b, c]);
}
{
let a: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]);
let b: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]).delay(30);
let c: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]).delay(60);
let abc: Observable<number, void> = Kefir.merge<number, void>([a, b, c]);
}
{
let a: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]);
let b: Stream<number, void> = Kefir.sequentially(100, [3, 4, 5]);
let abc: Observable<number, void> = Kefir.concat<number, void>([a, b]);
}
{
let a: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]);
let b: Stream<number, void> = Kefir.sequentially(100, [0, 1, 2]).delay(30);
let c: Observable<number, void> = Kefir.sequentially(100, [0, 1, 2]).delay(60);
let pool: ObservablePool<number, void> = Kefir.pool<number, void>();
pool.plug(a);
pool.plug(b);
pool.plug(c);
}
let observable04: Observable<number, void> = Kefir.repeat<number, void>(i => {
if (i < 3) {
return Kefir.sequentially(100, [i, i]);
} else {
return false;
}
});
let observable05: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).flatMap(x => Kefir.interval(40, x).take(4));
let observable06: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).flatMapLatest(x => Kefir.interval(40, x).take(4));
let observable07: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).flatMapFirst(x => Kefir.interval(40, x).take(4));
let observable08: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).flatMapConcat(x => Kefir.interval(40, x).take(4));
let observable09: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).flatMapConcurLimit(x => Kefir.interval(40, x).take(6), 2);
let observable10: Stream<number, void> = Kefir.sequentially(100, [1, 2]).valuesToErrors().flatMapErrors(x => Kefir.interval(40, x).take(2));
}
// Combine two observables
{
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6, 7, 8]);
let bar: Property<boolean, void> = Kefir.sequentially(200, [false, true, false]).delay(40).toProperty(() => true);
let observable01: Stream<number, void> = foo.filterBy<void>(bar);
}
{
let a: Property<number, void> = Kefir.sequentially(200, [2, 3]).toProperty(() => 1);
let b: Stream<number, void> = Kefir.interval(100, 0).delay(40).take(5);
let observable02: Property<number, void> = a.sampledBy<number, void, number>(b)
}
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4]);
let bar: Stream<number, void> = Kefir.later(250, 0);
let observable03: Stream<number, void> = foo.skipUntilBy<number, void>(bar);
}
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4]);
let bar: Stream<number, void> = Kefir.later(250, 0);
let observable04: Stream<number, void> = foo.takeUntilBy<number, void>(bar);
}
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6, 7, 8]).delay(40);
let bar: Stream<number, void> = Kefir.sequentially(300, [1, 2])
let observable05: Stream<number[], void> = foo.bufferBy<number, void>(bar);
}
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6, 7, 8]);
let bar: Stream<boolean, void> = Kefir.sequentially(200, [false, true, false]).delay(40);
let observable06: Stream<number[], void> = foo.bufferWhileBy<void>(bar);
}
{
let foo: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]);
let bar: Stream<number, void> = Kefir.sequentially(100, [1, 2, 3]).delay(40);
let observable07: Stream<boolean, void> = foo.awaiting<number, void>(bar);
}
}
+176
View File
@@ -0,0 +1,176 @@
// Type definitions for Kefir 2.8.1
// Project: http://rpominov.github.io/kefir/
// Definitions by: Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../es6-promise/es6-promise.d.ts" />
declare module "kefir" {
export interface Observable<T, S> {
// Subscribe / add side effects
onValue(callback: (value: T) => void): void;
offValue(callback: (value: T) => void): void;
onError(callback: (error: S) => void): void;
offError(callback: (error: S) => void): void;
onEnd(callback: () => void): void;
offEnd(callback: () => void): void;
onAny(callback: (event: Event<T | S>) => void): void;
offAny(callback: (event: Event<T | S>) => void): void;
log(name?: string): void;
offLog(name?: string): void;
toPromise(PromiseConstructor?: typeof Promise): Promise<T>;
}
export interface Stream<T, S> extends Observable<T, S> {
toProperty(getCurrent?: () => T): Property<T, S>;
// Modify an stream
map<U>(fn: (value: T) => U): Stream<U, S>;
filter(predicate?: (value: T) => boolean): Stream<T, S>;
take(n: number): Stream<T, S>;
takeWhile(predicate?: (value: T) => boolean): Stream<T, S>;
last(): Stream<T, S>;
skip(n: number): Stream<T, S>;
skipWhile(predicate?: (value: T) => boolean): Stream<T, S>;
skipDuplicates(comparator?: (a: T, b: T) => boolean): Stream<T, S>;
diff(fn?: (prev: T, next: T) => T, seed?: T): Stream<T, S>;
scan(fn: (prev: T, next: T) => T, seed?: T): Stream<T, S>;
flatten<U>(transformer?: (value: T) => U[]): Stream<U, S>;
delay(wait: number): Stream<T, S>;
throttle(wait: number, options?: {leading: boolean, trailing: boolean}): Stream<T, S>;
debounce(wait: number, options?: {immediate: boolean}): Stream<T, S>;
valuesToErrors<U>(handler?: (value: T) => {convert: boolean, error: U}): Stream<void, S | U>;
errorsToValues<U>(handler?: (error: S) => {convert: boolean, value: U}): Stream<T | U, void>;
mapErrors<U>(fn: (error: S) => U): Stream<T, U>;
filterErrors(predicate?: (error: S) => boolean): Stream<T, S>;
endOnError(): Stream<T, S>;
skipValues(): Stream<void, S>;
skipErrors(): Stream<T, void>;
skipEnd(): Stream<T, S>;
beforeEnd<U>(fn: () => U): Stream<T | U, S>;
slidingWindow(max: number, mix?: number): Stream<T[], S>;
bufferWhile(predicate: (value: T) => boolean): Stream<T[], S>;
transduce<U>(transducer: any): Stream<U, S>;
withHandler<U, V>(handler: (emitter: Emitter<U, S>, event: Event<T | S>) => void): Stream<U, S>;
// Combine streams
combine<U, V, W>(otherObs: Stream<U, V>, combinator?: (value: T, ...values: U[]) => W): Stream<W, S | V>;
zip<U, V, W>(otherObs: Stream<U, V>, combinator?: (value: T, ...values: U[]) => W): Stream<W, S | V>;
merge<U, V>(otherObs: Stream<U, V>): Stream<T | U, S | V>;
concat<U, V>(otherObs: Stream<U, V>): Stream<T | U, S | V>;
flatMap<U, V>(transform: (value: T) => Stream<U, V>): Stream<U, V>;
flatMapLatest<U, V>(fn: (value: T) => Stream<U, V>): Stream<U, V>;
flatMapFirst<U, V>(fn: (value: T) => Stream<U, V>): Stream<U, V>;
flatMapConcat<U, V>(fn: (value: T) => Stream<U, V>): Stream<U, V>;
flatMapConcurLimit<U, V>(fn: (value: T) => Stream<U, V>, limit: number): Stream<U, V>;
flatMapErrors<U, V>(transform: (error: S) => Stream<U, V>): Stream<U, V>;
// Combine two streams
filterBy<U>(otherObs: Observable<boolean, U>): Stream<T, S>;
sampledBy<U, V, W>(otherObs: Observable<U, V>, combinator?: (a: T, b: U) => W): Stream<W, S>;
skipUntilBy<U, V>(otherObs: Observable<U, V>): Stream<U, V>;
takeUntilBy<U, V>(otherObs: Observable<U, V>): Stream<U, V>;
bufferBy<U, V>(otherObs: Observable<U, V>, options?: {flushOnEnd: boolean}): Stream<T[], S>;
bufferWhileBy<U>(otherObs: Observable<boolean, U>): Stream<T[], S>;
awaiting<U, V>(otherObs: Observable<U, V>): Stream<boolean, S>;
}
export interface Property<T, S> extends Observable<T, S> {
changes(): Stream<T, S>;
// Modify an property
map<U>(fn: (value: T) => U): Property<U, S>;
filter(predicate?: (value: T) => boolean): Property<T, S>;
take(n: number): Property<T, S>;
takeWhile(predicate?: (value: T) => boolean): Property<T, S>;
last(): Property<T, S>;
skip(n: number): Property<T, S>;
skipWhile(predicate?: (value: T) => boolean): Property<T, S>;
skipDuplicates(comparator?: (a: T, b: T) => boolean): Property<T, S>;
diff(fn?: (prev: T, next: T) => T, seed?: T): Property<T, S>;
scan(fn: (prev: T, next: T) => T, seed?: T): Property<T, S>;
flatten<U>(transformer?: (value: T) => U[]): Property<U, S>;
delay(wait: number): Property<T, S>;
throttle(wait: number, options?: {leading: boolean, trailing: boolean}): Property<T, S>;
debounce(wait: number, options?: {immediate: boolean}): Property<T, S>;
valuesToErrors<U>(handler?: (value: T) => {convert: boolean, error: U}): Property<void, S | U>;
errorsToValues<U>(handler?: (error: S) => {convert: boolean, value: U}): Property<T | U, void>;
mapErrors<U>(fn: (error: S) => U): Property<T, U>;
filterErrors(predicate?: (error: S) => boolean): Property<T, S>;
endOnError(): Property<T, S>;
skipValues(): Property<void, S>;
skipErrors(): Property<T, void>;
skipEnd(): Property<T, S>;
beforeEnd<U>(fn: () => U): Property<T | U, S>;
slidingWindow(max: number, mix?: number): Property<T[], S>;
bufferWhile(predicate: (value: T) => boolean): Property<T[], S>;
transduce<U>(transducer: any): Property<U, S>;
withHandler<U, V>(handler: (emitter: Emitter<T, S>, event: Event<T | S>) => void): Property<U, S>;
// Combine properties
combine<U, V, W>(otherObs: Property<U, V>, combinator?: (value: T, ...values: U[]) => W): Property<W, S | V>;
zip<U, V, W>(otherObs: Property<U, V>, combinator?: (value: T, ...values: U[]) => W): Property<W, S | V>;
merge<U, V>(otherObs: Property<U, V>): Property<T | U, S | V>;
concat<U, V>(otherObs: Property<U, V>): Property<T | U, S | V>;
flatMap<U, V>(transform: (value: T) => Property<U, V>): Property<U, V>;
flatMapLatest<U, V>(fn: (value: T) => Property<U, V>): Property<U, V>;
flatMapFirst<U, V>(fn: (value: T) => Property<U, V>): Property<U, V>;
flatMapConcat<U, V>(fn: (value: T) => Property<U, V>): Property<U, V>;
flatMapConcurLimit<U, V>(fn: (value: T) => Property<U, V>, limit: number): Property<U, V>;
flatMapErrors<U, V>(transform: (error: S) => Property<U, V>): Property<U, V>;
// Combine two properties
filterBy<U>(otherObs: Observable<boolean, U>): Property<T, S>;
sampledBy<U, V, W>(otherObs: Observable<U, V>, combinator?: (a: T, b: U) => W): Property<W, S>;
skipUntilBy<U, V>(otherObs: Observable<U, V>): Property<U, V>;
takeUntilBy<U, V>(otherObs: Observable<U, V>): Property<U, V>;
bufferBy<U, V>(otherObs: Observable<U, V>, options?: {flushOnEnd: boolean}): Property<T[], S>;
bufferWhileBy<U>(otherObs: Observable<boolean, U>): Property<T[], S>;
awaiting<U, V>(otherObs: Observable<U, V>): Property<boolean, S>;
}
export interface ObservablePool<T, S> extends Observable<T, S> {
plug(obs: Observable<T, S>): void;
unPlug(obs: Observable<T, S>): void;
}
export interface Event<T> {
type: string;
value: T;
current: boolean;
}
export interface Emitter<T, S> {
emit(value: T): void;
error(error: S): void;
end(): void;
emitEvent(event: {type: string, value: T | S}): void;
}
// Create a stream
export function never(): Stream<void, void>;
export function later<T>(wait: number, value: T): Stream<T, void>;
export function interval<T>(interval: number, value: T): Stream<T, void>;
export function sequentially<T>(interval: number, values: T[]): Stream<T, void>;
export function fromPoll<T>(interval: number, fn: () => T): Stream<T, void>;
export function withInterval<T, S>(interval: number, handler: (emitter: Emitter<T, S>) => void): Stream<T, S>;
export function fromCallback<T>(fn: (callback: (value: T) => void) => void): Stream<T, void>;
export function fromNodeCallback<T, S>(fn: (callback: (error: S, result: T) => void) => void): Stream<T, S>;
export function fromEvents<T, S>(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream<T, S>;
export function stream<T, S>(subscribe: (emitter: Emitter<T, S>) => Function | void): Stream<T, S>;
// Create a property
export function constant<T>(value: T): Property<T, void>;
export function constantError<T>(error: T): Property<void, T>;
export function fromPromise<T, S>(promise: Promise<T>): Property<T, S>;
// Combine observables
export function combine<T, S, U>(obss: Observable<T, S>[], passiveObss: Observable<T, S>[], combinator?: (...values: T[]) => U): Observable<U, S>;
export function combine<T, S, U>(obss: Observable<T, S>[], combinator?: (...values: T[]) => U): Observable<U, S>;
export function zip<T, S, U>(obss: Observable<T, S>[], passiveObss?: Observable<T, S>[], combinator?: (...values: T[]) => U): Observable<U, S>;
export function merge<T, S>(obss: Observable<T, S>[]): Observable<T, S>;
export function concat<T, S>(obss: Observable<T, S>[]): Observable<T, S>;
export function pool<T, S>(): ObservablePool<T, S>;
export function repeat<T, S>(generator: (i: number) => Observable<T, S> | boolean): Observable<T, S>;
}
+101 -28
View File
@@ -403,12 +403,59 @@ result = <number[]>_([1, 2]).zipWith<number>(testZipWithFn, any).value();
result = <number[]>_([1, 2]).zipWith<number>([1, 2], testZipWithFn, any).value();
result = <number[]>_([1, 2]).zipWith<number>([1, 2], [1, 2], [1, 2], [1, 2], [1, 2], testZipWithFn, any).value();
// /* *************
// * Collections *
// ************* */
/*********
* Chain *
*********/
result = <string[]>_.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
result = <string[]>_.at(['moe', 'larry', 'curly'], 0, 2);
// _.thru
{
let result: number;
result = _.thru<number, number>(1, (value: number) => value);
result = _.thru<number, number>(1, (value: number) => value, any);
}
{
let result: _.LoDashWrapper<number>;
result = _(1).thru<number>((value: number) => value);
result = _(1).thru<number>((value: number) => value, any);
}
{
let result: _.LoDashWrapper<string>;
result = _('').thru<string>((value: string) => value);
result = _('').thru<string>((value: string) => value, any);
}
{
let result: _.LoDashWrapper<boolean>;
result = _(true).thru<boolean>((value: boolean) => value);
result = _(true).thru<boolean>((value: boolean) => value, any);
}
{
let result: _.LoDashObjectWrapper<any>;
result = _({}).thru<Object>((value: Object) => value);
result = _({}).thru<Object>((value: Object) => value, any);
}
{
let result: _.LoDashArrayWrapper<number>;
result = _([1, 2, 3]).thru<number>((value: number[]) => value);
result = _([1, 2, 3]).thru<number>((value: number[]) => value, any);
}
/**************
* Collection *
**************/
// _.at
{
let testAtArray: TResult[];
let testAtList: _.List<TResult>;
let testAtDictionary: _.Dictionary<TResult>;
let result: TResult[];
result = _.at<TResult>(testAtArray, 0, '1', [2], ['3'], [4, '5']);
result = _.at<TResult>(testAtList, 0, '1', [2], ['3'], [4, '5']);
result = _.at<TResult>(testAtDictionary, 0, '1', [2], ['3'], [4, '5']);
result = _(testAtArray).at(0, '1', [2], ['3'], [4, '5']).value();
result = _(testAtList).at<TResult>(0, '1', [2], ['3'], [4, '5']).value();
result = _(testAtDictionary).at<TResult>(0, '1', [2], ['3'], [4, '5']).value();
}
result = <boolean>_.contains([1, 2, 3], 1);
result = <boolean>_.contains([1, 2, 3], 1, 2);
@@ -1482,20 +1529,28 @@ result = <_.LoDashArrayWrapper<string>>_(_).methods();
// _.get
result = <number>_.get<number>({ 'a': [{ 'b': { 'c': 3 } }] }, 'a[0].b.c');
// → 3
result = <number>_.get<number>({ 'a': [{ 'b': { 'c': 3 } }] }, ['a', '0', 'b', 'c']);
// → 3
result = <string>_.get<string>({ 'a': [{ 'b': { 'c': 3 } }] }, 'a.b.c', 'default');
// → 'default'
result = <number>_({ 'a': [{ 'b': { 'c': 3 } }] }).get<number>('a[0].b.c');
// → 3
result = <number>_({ 'a': [{ 'b': { 'c': 3 } }] }).get<number>(['a', '0', 'b', 'c']);
// → 3
result = <string>_({ 'a': [{ 'b': { 'c': 3 } }] }).get<string>('a.b.c', 'default');
// → 'default'
{
let result: TResult;
result = _.get<TResult>({}, '');
result = _.get<TResult>({}, 42);
result = _.get<TResult>({}, true);
result = _.get<TResult>({}, ['', 42, true]);
result = _({}).get<TResult>('');
result = _({}).get<TResult>(42);
result = _({}).get<TResult>(true);
result = _({}).get<TResult>(['', 42, true]);
}
result = <boolean>_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
// _.has
result = <boolean>_.has({}, '');
result = <boolean>_.has({}, 42);
result = <boolean>_.has({}, true);
result = <boolean>_.has({}, ['', 42, true]);
result = <boolean>_({}).has('');
result = <boolean>_({}).has(42);
result = <boolean>_({}).has(true);
result = <boolean>_({}).has(['', 42, true]);
interface FirstSecond {
first: string;
@@ -1594,11 +1649,20 @@ result = <HasName>_({ 'name': 'moe', 'age': 40 }).omit(function (value) {
result = <any[][]>_.pairs({ 'moe': 30, 'larry': 40 });
result = <any[][]>_({ 'moe': 30, 'larry': 40 }).pairs().value();
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, ['name']);
result = <HasName>_.pick({ 'name': 'moe', '_userid': 'moe1' }, function (value, key) {
return key.charAt(0) != '_';
});
// _.pick
interface TestPickFn {
(element: any, key: string, collection: any): boolean;
}
{
let testPickFn: TestPickFn;
let result: TResult;
result = _.pick<TResult, Object>({}, 0, '1', true, [2], ['3'], [true], [4, '5', true]);
result = _.pick<TResult, Object>({}, testPickFn);
result = _.pick<TResult, Object>({}, testPickFn, any);
result = _({}).pick<TResult>(0, '1', true, [2], ['3'], [true], [4, '5', true]).value();
result = _({}).pick<TResult>(testPickFn).value();
result = _({}).pick<TResult>(testPickFn, any).value();
}
// _.set
result = <{ a: { b: { c: number; }}[]}>_.set({ 'a': [{ 'b': { 'c': 3 } }] }, 'a[0].b.c', 4);
@@ -1652,12 +1716,6 @@ var testAttempFn: TestAttemptFn;
result = <TResult|Error>_.attempt<TResult>(testAttempFn);
result = <TResult|Error>_(testAttempFn).attempt<TResult>();
_.mixin({
'capitalize': function (string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
});
var lodash = <typeof _>_.noConflict();
result = <number>_.random(0, 5);
@@ -1939,6 +1997,21 @@ result = <number>(_.methodOf<number>(TestMethodOfObject, 1, 2))(['a', '0']);
result = <number>(_(TestMethodOfObject).methodOf<number>(1, 2).value())('a[0]');
result = <number>(_(TestMethodOfObject).methodOf<number>(1, 2).value())(['a', '0']);
// _.mixin
{
let testMixinSource: _.Dictionary<Function>;
let testMixinOptions: {chain?: boolean;}
let result: TResult;
result = _.mixin<TResult, Object>({}, testMixinSource);
result = _.mixin<TResult, Object>({}, testMixinSource, testMixinOptions);
result = _.mixin<TResult>(testMixinSource);
result = _.mixin<TResult>(testMixinSource, testMixinOptions);
result = _({}).mixin<TResult>(testMixinSource).value();
result = _({}).mixin<TResult>(testMixinSource, testMixinOptions).value();
result = _(testMixinSource).mixin<TResult>().value();
result = _(testMixinSource).mixin<TResult>(testMixinOptions).value();
}
// _.uniqueId
result = <string>_.uniqueId();
result = <string>_.uniqueId('');
+189 -89
View File
@@ -694,9 +694,9 @@ declare module _ {
takeWhile<T>(
array: (Array<T>|List<T>),
predicate?: ListIterator<T, boolean>,
thisArg?: any
thisArg?: any
): T[];
/**
* Takes the first items from an array or list based on a predicate
* @param array The array or list of items on which the result set will be based
@@ -706,7 +706,7 @@ declare module _ {
array: (Array<T>|List<T>),
pluckValue: string
): any[];
/**
* Takes the first items from an array or list based on a predicate
* @param array The array or list of items on which the result set will be based
@@ -1502,7 +1502,7 @@ declare module _ {
**/
union<T>(...arrays: List<T>[]): T[];
}
interface LoDashArrayWrapper<T> {
/**
* @see _.union
@@ -2000,58 +2000,94 @@ declare module _ {
zipWith<TResult>(...args: any[]): LoDashArrayWrapper<TResult>;
}
/* *************
* Collections *
************* */
/*********
* Chain *
*********/
//_.thru
interface LoDashStatic {
/**
* This method is like _.tap except that it returns the result of interceptor.
* @param value The value to provide to interceptor.
* @param interceptor The function to invoke.
* @param thisArg The this binding of interceptor.
* @return Returns the result of interceptor.
*/
thru<T, TResult>(
value: T,
interceptor: (value: T) => TResult,
thisArg?: any): TResult;
}
interface LoDashWrapperBase<T, TWrapper> {
/**
* @see _.thru
*/
thru<TResult extends number>(
interceptor: (value: T) => TResult,
thisArg?: any): LoDashWrapper<TResult>;
/**
* @see _.thru
*/
thru<TResult extends string>(
interceptor: (value: T) => TResult,
thisArg?: any): LoDashWrapper<TResult>;
/**
* @see _.thru
*/
thru<TResult extends boolean>(
interceptor: (value: T) => TResult,
thisArg?: any): LoDashWrapper<TResult>;
/**
* @see _.thru
*/
thru<TResult extends Object>(
interceptor: (value: T) => TResult,
thisArg?: any): LoDashObjectWrapper<TResult>;
/**
* @see _.thru
*/
thru<TResult>(
interceptor: (value: T) => TResult[],
thisArg?: any): LoDashArrayWrapper<TResult>;
}
/**************
* Collection *
**************/
//_.at
interface LoDashStatic {
/**
* Creates an array of elements from the specified indexes, or keys, of the collection.
* Indexes may be specified as individual arguments or as arrays of indexes.
* @param collection The collection to iterate over.
* @param indexes The indexes of collection to retrieve, specified as individual indexes or
* arrays of indexes.
* @return A new array of elements corresponding to the provided indexes.
**/
* Creates an array of elements corresponding to the given keys, or indexes, of collection. Keys may be
* specified as individual arguments or as arrays of keys.
*
* @param collection The collection to iterate over.
* @param props The property names or indexes of elements to pick, specified individually or in arrays.
* @return Returns the new array of picked elements.
*/
at<T>(
collection: Array<T>,
indexes: number[]): T[];
collection: List<T>|Dictionary<T>,
...props: Array<number|string|Array<number|string>>
): T[];
}
interface LoDashArrayWrapper<T> {
/**
* @see _.at
**/
at<T>(
collection: List<T>,
indexes: number[]): T[];
* @see _.at
*/
at(...props: Array<number|string|Array<number|string>>): LoDashArrayWrapper<T>;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.at
**/
at<T>(
collection: Dictionary<T>,
indexes: number[]): T[];
/**
* @see _.at
**/
at<T>(
collection: Array<T>,
...indexes: number[]): T[];
/**
* @see _.at
**/
at<T>(
collection: List<T>,
...indexes: number[]): T[];
/**
* @see _.at
**/
at<T>(
collection: Dictionary<T>,
...indexes: number[]): T[];
* @see _.at
*/
at<TResult>(...props: Array<number|string|Array<number|string>>): LoDashArrayWrapper<TResult>;
}
//_.contains
@@ -2514,13 +2550,13 @@ declare module _ {
/**
* Iterates over elements of a collection, returning an array of all elements the
* identity function returns truey for.
*
*
* @param collection The collection to iterate over.
* @return Returns a new array of elements that passed the callback check.
**/
filter<T>(
collection: (Array<T>|List<T>)): T[];
/**
* Iterates over elements of a collection, returning an array of all elements the
* callback returns truey for. The callback is bound to thisArg and invoked with three
@@ -2683,7 +2719,7 @@ declare module _ {
* @see _.filter
**/
filter(): LoDashArrayWrapper<T>;
/**
* @see _.filter
**/
@@ -5096,7 +5132,7 @@ declare module _ {
sortBy<W, T>(
collection: List<T>,
whereValue: W): T[];
/**
* Sorts by all the given arguments, using either ListIterator, pluckValue, or whereValue foramts
* @param args The rules by which to sort
@@ -5126,7 +5162,7 @@ declare module _ {
* @param whereValue _.where style callback
**/
sortBy<W>(whereValue: W): LoDashArrayWrapper<T>;
/**
* Sorts by all the given arguments, using either ListIterator, pluckValue, or whereValue foramts
* @param args The rules by which to sort
@@ -7117,17 +7153,17 @@ declare module _ {
* @param defaultValue The value returned if the resolved value is undefined.
* @return Returns the resolved value.
**/
get<T>(object: Object,
path: string|string[],
defaultValue?:T
): T;
get<TResult>(object: Object,
path: string|number|boolean|Array<string|number|boolean>,
defaultValue?:TResult
): TResult;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.get
**/
get<TResult>(path: string|string[],
get<TResult>(path: string|number|boolean|Array<string|number|boolean>,
defaultValue?: TResult
): TResult;
}
@@ -7135,12 +7171,20 @@ declare module _ {
//_.has
interface LoDashStatic {
/**
* 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, path: string|string[]): boolean;
* Checks if path is a direct property.
*
* @param object The object to query.
* @param path The path to check.
* @return Returns true if path is a direct property, else false.
*/
has(object: any, path: string|number|boolean|Array<string|number|boolean>): boolean;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.has
*/
has(path: string|number|boolean|Array<string|number|boolean>): boolean;
}
//_.invert
@@ -7450,36 +7494,50 @@ declare module _ {
pairs(): LoDashArrayWrapper<any[]>;
}
//_.picks
//_.pick
interface LoDashStatic {
/**
* Creates a shallow clone of object composed of the specified properties. Property names may be
* specified as individual arguments or as arrays of property names. If a callback is provided
* it will be executed for each property of object picking the properties the callback returns
* truey for. The callback is bound to thisArg and invoked with three arguments; (value, key,
* object).
* @param object Object to strip unwanted key/value pairs.
* @param keys Property names to pick
* @return An object composed of the picked properties.
**/
pick<Picked, T>(
* Creates an object composed of the picked object properties. Property names may be specified as individual
* arguments or as arrays of property names. If predicate is provided its invoked for each property of object
* picking the properties predicate returns truthy for. The predicate is bound to thisArg and invoked with
* three arguments: (value, key, object).
*
* @param object The source object.
* @param predicate The function invoked per iteration or property names to pick, specified as individual
* property names or arrays of property names.
* @param thisArg The this binding of predicate.
* @return An object composed of the picked properties.
*/
pick<TResult extends Object, T extends Object>(
object: T,
...keys: string[]): Picked;
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): TResult;
/**
* @see _.pick
**/
pick<Picked, T>(
* @see _.pick
*/
pick<TResult extends Object, T extends Object>(
object: T,
keys: string[]): Picked;
...predicate: Array<string|number|boolean|Array<string|number|boolean>>
): TResult;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.pick
*/
pick<TResult extends Object>(
predicate: ObjectIterator<any, boolean>,
thisArg?: any
): LoDashObjectWrapper<TResult>;
/**
* @see _.pick
**/
pick<Picked, T>(
object: T,
callback: ObjectIterator<any, boolean>,
thisArg?: any): Picked;
* @see _.pick
*/
pick<TResult extends Object>(
...predicate: Array<string|number|boolean|Array<string|number|boolean>>
): LoDashObjectWrapper<TResult>;
}
//_.set
@@ -8151,12 +8209,54 @@ declare module _ {
}
//_.mixin
interface MixinOptions {
chain?: boolean;
}
interface LoDashStatic {
/**
* Adds function properties of a source object to the lodash function and chainable wrapper.
* @param object The object of function properties to add to lodash.
**/
mixin(object?: Dictionary<(value: any) => any>): void;
* Adds all own enumerable function properties of a source object to the destination object. If object is a
* function then methods are added to its prototype as well.
*
* Note: Use _.runInContext to create a pristine lodash function to avoid conflicts caused by modifying
* the original.
*
* @param object The destination object.
* @param source The object of functions to add.
* @param options The options object.
* @param options.chain Specify whether the functions added are chainable.
* @return Returns object.
*/
mixin<TResult, TObject>(
object: TObject,
source: Dictionary<Function>,
options?: MixinOptions
): TResult;
/**
* @see _.mixin
*/
mixin<TResult>(
source: Dictionary<Function>,
options?: MixinOptions
): TResult;
}
interface LoDashObjectWrapper<T> {
/**
* @see _.mixin
*/
mixin<TResult>(
source: Dictionary<Function>,
options?: MixinOptions
): LoDashObjectWrapper<TResult>;
/**
* @see _.mixin
*/
mixin<TResult>(
options?: MixinOptions
): LoDashObjectWrapper<TResult>;
}
//_.noConflict
+18 -1
View File
@@ -253,6 +253,8 @@ declare module log4javascript {
* Asserts the given expression is true or evaluates to true. If so, nothing is logged. If not, an error is logged at the ERROR level.
*/
assert(expr: any): void;
name: string;
}
// #endregion
@@ -262,7 +264,20 @@ declare module log4javascript {
/**
* Logging event.
*/
export class LoggingEvent { }
export class LoggingEvent {
logger: Logger;
timeStamp: Date;
timeStampInMilliseconds: number;
timeStampInSeconds: number;
milliseconds: number;
level: Level;
messages: any[];
exception: Error;
getThrowableStrRep: () => string;
getCombinedMessages: () => string;
toString: () => string;
}
/**
* There are methods common to all appenders, as listed below.
@@ -920,6 +935,8 @@ declare module log4javascript {
* Returns whether the layout has any custom fields.
*/
hasCustomFields(): boolean;
formatWithException(loggingEvent: LoggingEvent): string;
}
/**
+2
View File
@@ -43,6 +43,8 @@ function main(): void {
}).then(
function() {
return todoDb.select(lf.fn.count()).from(itemSchema).exec();
}).then(function() {
return todoDb.export();
});
}
+21 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for Lovefield v2.0.56
// Type definitions for Lovefield v2.0.62
// Project: http://google.github.io/lovefield/
// Definitions by: freshp86 <https://github.com/freshp86>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -18,6 +18,16 @@ declare module lf {
STRING
}
export enum ConstraintAction {
RESTRICT,
CASCADE
}
export enum ConstraintTiming {
IMMEDIATE,
DEFERRABLE
}
export interface Binder {
getIndex(): number
}
@@ -56,7 +66,9 @@ declare module lf {
close(): void
createTransaction(type?: TransactionType): Transaction
delete(): query.Delete
export(): Promise<Object>
getSchema(): schema.Database
import(data: Object): Promise<void>
insertOrReplace(): query.Insert
insert(): query.Insert
observe(query: query.Select, callback: Function): void
@@ -174,9 +186,16 @@ declare module lf {
order: Order
}
type RawForeignKeySpec = {
local: string
ref: string
action: lf.ConstraintAction
timing: lf.ConstraintAction
}
export interface TableBuilder {
addColumn(name: string, type: lf.Type): TableBuilder
addForeignKey(): TableBuilder
addForeignKey(name: string, spec: RawForeignKeySpec): TableBuilder
addIndex(
name: string, columns: Array<string>|Array<IndexedColumn>,
unique?: boolean, order?: Order): TableBuilder
+39 -3
View File
@@ -1,13 +1,49 @@
// Type definitions for lscache v1.0.2
// Type definitions for lscache v1.0.5
// Project: https://github.com/pamelafox/lscache
// Definitions by: Chris Martinez <https://github.com/Chris-Martinezz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface LSCache {
/**
* Stores the value in localStorage. Expires after specified number of minutes.
* @param {string} key
* @param {Object|string} value
* @param {number} time
*/
set(key: string, value: any, time?: number): void;
/**
* Retrieves specified value from localStorage, if not expired.
* @param {string} key
* @return {string|Object}
*/
get(key: string): any;
/**
* Removes a value from localStorage.
* Equivalent to 'delete' in memcache, but that's a keyword in JS.
* @param {string} key
*/
remove(key: string): void;
/**
* Flushes all lscache items and expiry markers without affecting rest of localStorage
*/
flush(): void;
/**
* Flushes expired lscache items and expiry markers without affecting rest of localStorage
*/
flushExpired(): void;
/**
* Appends CACHE_PREFIX so lscache will partition data in to different buckets.
* @param {string} bucket
*/
setBucket(bucket: string):void;
/**
* Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior.
*/
resetBucket(): void;
}
declare var lscache:LSCache;
declare module 'lscache' {
var lscache: LSCache;
export = lscache;
}
declare var lscache: LSCache;
+1 -1
View File
@@ -2,7 +2,7 @@
/// <reference path="../gulp/gulp.d.ts" />
import gulp = require('gulp');
import merge2 = require('merge2');
import * as merge2 from "merge2";
gulp.task('app-js', () =>
merge2(
+6 -3
View File
@@ -12,10 +12,13 @@ declare module 'merge2' {
}
interface IMerge2Stream extends NodeJS.ReadWriteStream {
add(...args: Array<NodeJS.ReadWriteStream | IMerge2Stream | Array<NodeJS.ReadWriteStream | IMerge2Stream | IOptions>>): IMerge2Stream;
add(...args: Array<NodeJS.ReadWriteStream | IMerge2Stream | Array<NodeJS.ReadWriteStream | IMerge2Stream | IOptions>>): IMerge2Stream;
}
function merge2(...args: Array<NodeJS.ReadWriteStream | IMerge2Stream | Array<NodeJS.ReadWriteStream | IMerge2Stream> | IOptions>): IMerge2Stream;
interface IMerge2 {
(...args: Array<NodeJS.ReadWriteStream | IMerge2Stream | Array<NodeJS.ReadWriteStream | IMerge2Stream> | IOptions>): IMerge2Stream;
}
export = merge2;
var _tmp: IMerge2;
export = _tmp;
}
+1
View File
@@ -527,6 +527,7 @@ declare module "mongodb" {
export interface MongoCollectionOptions {
safe?: any;
serializeFunctions?: any;
strict?: boolean;
raw?: boolean;
pkFactory?: any;
readPreference?: string;
+3 -1
View File
@@ -8,11 +8,13 @@ let myJSFL: jsfl.JSFL = {
}
}
let flashLocation: string = '';
jsfl.createJSFL(myJSFL, 'fileName.jsfl', ['Hello!'], (err: NodeJS.ErrnoException) => {
});
jsfl.runJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => {
jsfl.runJSFL(flashLocation, 'fileName.jsfl', (err: NodeJS.ErrnoException) => {
});
+3 -2
View File
@@ -1,4 +1,4 @@
// Type definitions for node-jsfl-runner
// Type definitions for node-jsfl-runner v0.2.4
// Project: https://www.npmjs.com/package/node-jsfl-runner
// Definitions by: Michael Randolph <https://github.com/mrand01>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -28,8 +28,9 @@ declare module "node-jsfl-runner" {
/**
* Runs a JSFL file
* @param flashLocation Path to Flash executable
* @param fileName Path to JSFL file to run
* @param callback Callback
*/
function runJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void;
function runJSFL(flashLocation:string, fileName: string, callback: (err: NodeJS.ErrnoException) => void): void;
}
+153 -17
View File
@@ -1,49 +1,80 @@
///<reference path='./node-mysql-wrapper.d.ts' />
import wrapper = require("node-mysql-wrapper");
var db = wrapper.wrap("mysql://kataras:pass@127.0.0.1/taglub?debug=false&charset=utf8");
/// <reference path="./node-mysql-wrapper.d.ts" />
/// <reference path="../node/node.d.ts" />
/// <reference path="../bluebird/bluebird.d.ts" />
var express = require('express');
var app = express();
var server = require('http').createServer(app);
import wrapper2 = require("node-mysql-wrapper");
var db = wrapper2.wrap("mysql://kataras:pass@127.0.0.1/taglub?debug=false&charset=utf8");
class User { //or interface
userId: number;
username: string;
mail: string;
password:string;
comments: Comment[];
myComments: Comment[];
info: UserInfo;
}
interface Comment {
commentId: number;
content: string;
likes: CommentLike[];
}
interface CommentLike {
commentLikeId: number;
userId: number;
commentId: number;
}
interface UserInfo {
userInfoId: number;
userId: number;
hometown: string;
}
db.ready(() => {
var usersDb = db.table<User>("users");
//or var usersDb = db.table("users"); if you don't want intel auto complete from your ide/editor
usersDb.findById(16, (_user) => {
console.log("TEST1: \n");
console.log("FOUND USER WITH USERNAME: " + _user.username);
});
/* OR usersDb.findById(18).then(_user=> {
console.log("FOUND USER WITH USERNAME: " + _user.username);
}, (err) => { console.log("ERROR ON FETCHING FINDBY ID: " + err) });
*/
usersDb.find({ userId: 18, comments: { userId: '=' } }, _users=> {
var _user = _users[0];
console.log("TEST2: \n");
console.log(_user.username + " with ");
console.log(_user.comments.length + " comments ");
_user.comments.forEach(_comment=> {
console.log("--------------\n" + _comment.content);
usersDb.findSingle(
{
userId: 18,
myComments: {
userId: '=',
tableRules: { //NEW: SET rules to joined tables too!
table: "comments", //NEW SET table name inside any property u want!
limit: 50,
orderByDesc: "commentId" //give me the first 50 comments ordered by -commentId (DESC) from table 'comments' and put them at 'myComments' property inside the result object.
}
}
}).then(_user=> { // to get this promise use : .promise()
console.log("\n-------------TEST 2 ------------\n");
console.log(_user.username + " with ");
console.log(_user.myComments.length + " comments ");
_user.myComments.forEach(_comment=> {
console.log("--------------\n" + _comment.content);
});
});
});
usersDb.safeRemove(5620, answer=> {
usersDb.remove(5620, answer=> {
console.log("TEST 3: \n");
console.log(answer.affectedRows + ' (1) has removed from table: ' + answer.table);
@@ -60,4 +91,109 @@ db.ready(() => {
});
usersDb.find(
{
yearsOld: 22,
comments: {
userId: "=",
tableRules: {
limit: 2
}
}
}, (_users) => {
console.log("---------------TEST 6----------------------------------------");
_users.forEach(_user=> {
console.log(_user.userId + " " + _user.username + " found with " + _user.comments.length + " comments");
});
});
//if no rules setted to find method it's uses the table's rules ( if exists)
let _criteriaFromBuilder = usersDb.criteria
.except("password") // or .exclude(...columns). the only column you cannot except/exclude is the primary key (because it is used at where clause), be careful.
.where("userId", 24)
.joinAs("info", "userInfos", "userId")
.at("info")
.limit(1) //because we make it limit 1 it will return this result as object not as array.
.parent()
.joinAs("myComments", "comments", "userId")
.at("myComments").limit(2)
.joinAs("likes", "commentLikes", "commentId")
.original().orderBy("userId", true).build();
/* console.dir(_criteriaFromBuilder);
prints this object: ( of course you can create your own in order to pass it on .find table methods )
{
userId:23,
myComments:{
userId: '=',
tableRules:{
table: 'comments',
limit:2
},
likes:{
commentId: '=',
tableRules:{
table: 'commentLikes'
}
}
},
tableRules:{
orderByDesc: 'userId',
except: ['password']
}
}
*/
usersDb.find(_criteriaFromBuilder).then(_users=> {
console.log("\n----------------\nTEST ADVANCED 1\n-------------------\n ");
_users.forEach(_user=> {
console.log(_user.userId + " " + _user.username);
if (_user.info !== undefined) {
console.log(' from ' + _user.info.hometown);
//console.dir(_user.userInfos);
}
if (_user.myComments !== undefined) {
_user.myComments.forEach(_comment=> {
console.log(_comment.commentId + " " + _comment.content);
if (_comment.likes !== undefined) {
console.log(' with ' + _comment.likes.length + ' likes!');
}
});
}
});
});
});
server.on('uncaughtException', function(err:any) {
console.log(err);
})
var httpPort = 1193;//config.get('Server.port') || 1193;
server.listen(httpPort, function() {
console.log("Server is running on " + httpPort);
});
+558 -62
View File
@@ -1,5 +1,5 @@
// Type definitions for node-mysql-wrapper
// Project: https://github.com/kataras/node-mysql-wrapper
// Project: https://github.com/nodets/node-mysql-wrapper
// Definitions by: Makis Maropoulos <https://github.com/kataras>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -12,120 +12,616 @@ declare module "node-mysql-wrapper" {
import {EventEmitter} from 'events';
var EQUAL_TO_PROPERTY_SYMBOL: string;
var TABLE_RULES_PROPERTY: string;
type DeleteAnswer = {
affectedRows: number;
table: string;
};
type RawRules = {
table: string,
begin: string,
orderBy: string,
orderByDesc: string,
groupBy: string,
limit: number, // limit = limitStart =0 and limitEnd = limit.
limitStart: number,
limitEnd: number,
end: string
};
type TableToSearchPart = { tableName: string, propertyName: string };
interface Map<T> {
[index: string]: T;
}
class MysqlUtil {
interface IQuery<T> {
_table: Table<T>;
execute(rawCriteria: any, callback?: (_results: any) => any): Promise<any>;
}
interface IQueryConstructor<T> {
new (_table: Table<T>): IQuery<T>;
}
class Helper {
/**
* Callback like forEach
* @name valueCallback
* @function
* @param {T} the value of the object's key
* @returnTye {U}
* @return {U}
*/
/**
* Callback like forEach
* @name keyCallback
* @function
* @param {string} the name of the object's key
* @returnTye {U}
* @return {U}
*/
constructor();
/**
* Create and return a copy of an object.
* @param {T} object the object you want to copy.
* @returnType {T}
* @return {T}
*/
static copyObject<T>(object: T): T;
/**
* Converts any_string to anyString and returns it.
* @param {string} columnKey the string you want to convert.
* @returnType {string}
* @return {string}
*/
static toObjectProperty(columnKey: string): string;
/**
* Converts anyString to any_string and returns it.
* @param {string} objectKey the string you want to convert.
* @returnType {string}
* @return {string}
*/
static toRowProperty(objectKey: string): string;
/**
* Iterate object's keys and return their values to the callback.
* @param {Map<T>} map the object.
* @param {valueCallback}
* @returnType {U}
* @return {U}
*/
static forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U;
/**
* Iterate object's keys and return their names to the callback.
* @param {Map<T>} map the object.
* @param {keyCallback}
* @returnType {U}
* @return {U}
*/
static forEachKey<T, U>(map: Map<T>, callback: (key: string) => U): U;
/**
* Checks if anything is a function.
* @param {functionToCheck} the object or function to pass
* @return boolean
*/
static isFunction(functionToCheck: any): boolean;
/**
* Checks if an object has 'tableRules' property.
* @param {obj} the object to pass
* @return boolean
*/
static hasRules(obj: any): boolean;
}
interface ICriteria {
interface ICriteriaParts {
rawCriteriaObject: any;
tables: string[];
tables: TableToSearchPart[];
noDatabaseProperties: string[];
whereClause: string;
selectFromClause<T>(_table: Table<T>): string;
}
class Criteria implements ICriteria {
class CriteriaParts implements ICriteriaParts {
/**
* The raw format of the criteria eg: {yearsOld:22}.
*/
rawCriteriaObject: any;
tables: string[];
/**
* Which tables to search after the find method of the proto table finish.
*/
tables: TableToSearchPart[];
/**
* The properties of the criteria which don't belong to the database's table.
*/
noDatabaseProperties: string[];
/**
* The converted/exported where clause.
*/
whereClause: string;
constructor(rawCriteriaObject: any, tables: string[], noDatabaseProperties: string[], whereClause: string);
constructor(rawCriteriaObject: any, tables: TableToSearchPart[], noDatabaseProperties: string[], whereClause: string);
selectFromClause<T>(_table: Table<T>): string;
}
class CriteriaBuilder<T> {
class CriteriaDivider<T> {
private _table;
constructor(table: MysqlTable<T>);
build(rawCriteriaObject: any): Criteria;
constructor(table: Table<T>);
/**
* Builds the criteria raw object to Criteria object.
* @param {any} rawCriteriaObject the criteria at raw format you pass eg: {yearsOld:18}.
* @returnType {Criteria}
* @return {Criteria}
*/
build(rawCriteriaObject: any): CriteriaParts;
}
class SelectQueryRules {
private lastPropertyClauseName: string;
manuallyEndClause: string;
manuallyBeginClause: string;
exceptColumns: string[];
orderByColumn: string;
orderByDescColumn: string;
groupByColumn: string;
limitStart: number;
limitEnd: number;
public tableName: string; //auto den benei oute sto last, oute sto from.
static build(): SelectQueryRules;
private last(propertyClauseName);
except(...columns: string[]): SelectQueryRules;
/**
* Same as .except(...columns)
*/
exclude(...columns: string[]): SelectQueryRules;
orderBy(columnKey: string, descending?: boolean): SelectQueryRules;
groupBy(columnKey: string): SelectQueryRules;
limit(limitRowsOrStart: number, limitEnd?: number): SelectQueryRules;
appendToBegin(manualAfterWhereString: string): SelectQueryRules;
appendToEnd(manualAfterWhereString: string): SelectQueryRules;
append(appendToCurrent: string): SelectQueryRules;
clearOrderBy(): SelectQueryRules;
clearGroupBy(): SelectQueryRules;
clearLimit(): SelectQueryRules;
clearEndClause(): SelectQueryRules;
clearBeginClause(): SelectQueryRules;
clear(): SelectQueryRules;
from(parentRule: SelectQueryRules): SelectQueryRules;
isEmpty(): boolean;
toString(): string;
toRawObject(): RawRules;
static toString(rules: SelectQueryRules): string;
static toRawObject(rules: SelectQueryRules): RawRules;
static fromRawObject(obj: RawRules): SelectQueryRules;
}
class CriteriaBuilder<T>{
private rawCriteria: any;
private primaryTable: Table<T>;
private parentBuilder: CriteriaBuilder<any>;
constructor(primaryTable: Table<T>); //to arxiko apo to Table.ts 9a benei
constructor(primaryTable: Table<T>, tableName: string, parentBuilder: CriteriaBuilder<any>);// auta 9a benoun apo to parent select query.
constructor(primaryTable: Table<T>, tablePropertyName?: string, parentBuilder?: CriteriaBuilder<any>);
except(...columns: string[]): CriteriaBuilder<T>;
/**
* Same as .except(...columns)
*/
exclude(...columns: string[]): CriteriaBuilder<T>;
where(key: string, value: any): CriteriaBuilder<T>;
private createRulesIfNotExists(): void;
orderBy(column: string, desceding?: boolean): CriteriaBuilder<T>;
limit(start: number, end?: number): CriteriaBuilder<T>;
join(realTableName: string, foreignColumnName: string): CriteriaBuilder<T>;
joinAs(tableNameProperty: string, realTableName: string, foreignColumnName: string): CriteriaBuilder<T>;
at(tableNameProperty: string): CriteriaBuilder<T>;
parent(): CriteriaBuilder<T>;
original(): CriteriaBuilder<T>;
/**
* Auto kanei kuklous mexri na paei sto primary table kai ekei na epistrepsei to sunoliko raw criteria gia execute i kati allo.
*/
build(): any;
static from<T>(table: Table<T>): CriteriaBuilder<T>
}
class SelectQuery<T> implements IQuery<T> { // T for Table's result type.
_table: Table<T>
constructor(_table: Table<T>);
private parseQueryResult(result: any, criteria: ICriteriaParts): Promise<any>;
/**
* Executes the select and returns the Promise.
*/
promise(rawCriteria: any, callback?: (_results: T[]) => any): Promise<T[]>;
/**
* Exactly the same thing as promise().
* Executes the select and returns the Promise.
*/
execute(rawCriteria: any, callback?: (_results: T[]) => any): Promise<T[]>;
}
class SaveQuery<T> implements IQuery<T> {
_table: Table<T>
constructor(_table: Table<T>);
execute(criteriaRawJsObject: any, callback?: (_result: T | any) => any): Promise<T | any>;
}
class DeleteQuery<T> implements IQuery<T>{
_table: Table<T>
constructor(_table: Table<T>);
execute(criteriaOrID: any | number | string, callback?: (_result: DeleteAnswer) => any): Promise<DeleteAnswer>;
}
class MysqlConnection extends EventEmitter {
class Connection extends EventEmitter {
/**
* The real database connection socket.
*/
connection: Mysql.IConnection;
/**
* Collection of the supported event types for the tables.
*/
eventTypes: string[];
/**
* Force to fetch ONLY these Database table names {array of string}.
*/
tableNamesToUseOnly: any[];
tables: MysqlTable<any>[];
/**
* All tables {MysqlTable} inside this connection's database.
*/
tables: Table<any>[];
constructor(connection: string | Mysql.IConnection);
/**
* Creates the MysqlConnection from the connection url or the real connection object.
* @param {string | Mysql.IConnection} connection the connection url or the real connection object.
* @returnType {nothing}
* @return {nothing}
*/
create(connection: string | Mysql.IConnection): void;
/**
* Attach a real connection.
* @param {Mysql.IConnection} connection the real connection object.
* @returnType {nothing}
* @return {nothing}
*/
attach(connection: Mysql.IConnection): void;
/**
* Close the entire real connection and remove all event's listeners (if exist).
* @param {function} callback If error occurs when closing the connection, this callback has the responsibility to catch it.
* @returnType {nothing}
* @return {nothing}
*/
end(callback?: (error: any) => void): void;
/**
* Close the entire real connection and remove all event's listeners (if exist).
* the difference from the 'end' is that this method doesn't care about errors so no callback passing here.
*/
destroy(): void;
/**
* Link the real connection with this MysqlConnection object.
* @param {function} readyCallback when the link operation is done this callback is executed.
* @returnType {Promise}
* @return {Promise}
*/
link(readyCallback?: () => void): Promise<void>;
/**
* Force to use/fetch information from only certain of database's tables, otherwise all database's tables information will be fetched.
* @param {Array} tables the array of the tables {string}
* @returnType {nothing}
* @return {nothing}
*/
useOnly(...tables: any[]): void;
/**
* This method has the resposibility of fetching the correct tables from the database ( table = columns' names, primary key name).
* @returnType {Promise}
* @return {Promise}
*/
fetchDatabaseInfornation(): Promise<void>;
/**
* Escape the query column's value and return it.
* @param {string} val the value which will be escaped.
* @returnType {string}
* @return {string}
*/
escape(val: string): string;
/**
* Call when must notify the Database events, SAVE(INSERT,UPDATE), REMOVE(DELETE).
* @param {string} tableWhichCalled the table name which event is coming from.
* @param {string} queryStr the full parsed query string which used to determinate the type of event to notify.
* @param {any[]} parsedResults the parsed results (results after a method parse/edit/export them as objects), these are passing to the watch listener(s).
* @returnType {nothing}
* @return {nothing}
*/
notice(tableWhichCalled: string, queryStr: string, parsedResults: any[]): void;
/**
* Adds an event listener/watcher on a table for a 'database event'.
* @param {string} tableName the table name which you want to add the event listener.
* @param {string or string[]} evtType the event(s) type you want to watch, one of these(string) or an array of them(string[]): ["INSERT", "UPDATE", "REMOVE", "SAVE"].
* @param {function} callback Callback which has one parameter(typeof any[]) which filled by the parsedResults (results after query executed and exports to object(s)).
* @returnType {nothing}
* @return {nothing}
*/
watch(tableName: string, evtType: any, callback: (parsedResults: any[]) => void): void;
/**
* Removes an event listener/watcher from a table for a specific event type.
* @param {string} tableName the table name which you want to remove the event listener.
* @param {string} evtType the Event type you want to remove, one of these: "INSERT", "UPDATE", "REMOVE", "SAVE".
* @param {function} callbackToRemove the callback that you were used for watch this event type.
* @returnType {nothing}
* @return {nothing}
*/
unwatch(tableName: string, evtType: string, callbackToRemove: (parsedResults: any[]) => void): void;
/**
* Executes a database query.
* @param {string} queryStr the query text/string to be executed.
* @param {function} callback the function will be called and fill the one and only parameter when an errors occurs.
* @param {any[]} queryArguments (optional) the query arguments you want to pass into query. ['arg1','arg2']...
* @returnType {nothing}
* @return {nothing}
*/
query(queryStr: string, callback: (err: Mysql.IError, results: any) => any, queryArguments?: any[]): void;
table<T>(tableName: string): MysqlTable<T>;
}
class MysqlTable<T> {
private _name;
private _connection;
private _columns;
private _primaryKey;
private _criteriaBuilder;
constructor(tableName: string, connection: MysqlConnection);
columns: string[];
primaryKey: string;
connection: MysqlConnection;
name: string;
on(evtType: string, callback: (parsedResults: any[]) => void): void;
off(evtType: string, callbackToRemove: (parsedResults: any[]) => void): void;
has(extendedFunctionName: string): boolean;
extend(functionName: string, theFunction: (...args: any[]) => any): void;
objectFromRow(row: any): any;
rowFromObject(obj: any): any;
getRowAsArray(jsObject: any): Array<any>;
getPrimaryKeyValue(jsObject: any): number | string;
parseQueryResult(result: any, criteria: ICriteria): Promise<any>;
find(criteriaRawJsObject: any, callback?: (_results: T[]) => any): Promise<T[]>;
findById(id: number | string, callback?: (result: T) => any): Promise<T>;
findAll(callback?: (_results: T[]) => any): Promise<T[]>;
save(criteriaRawJsObject: any, callback?: (_result: any) => any): Promise<any>;
safeRemove(id: number | string, callback?: (_result: {
affectedRows: number;
table: string;
}) => any): Promise<{
affectedRows: number;
table: string;
}>;
remove(criteriaRawJsObject: any, callback?: (_result: {
affectedRows: number;
table: string;
}) => any): Promise<{
affectedRows: number;
table: string;
}>;
/**
* Returns a MysqlTable object from the database factory. (Note: this method doesn't create anything, just finds and returns the correct table, you don't have to create anything at all. Tables are fetched by the library itself.)
* If you are using typescript you can pass a class (generic<T>) in order to use the auto completion assistance on table's results methods(find,findById,findAll,save,remove,safeRemove).
* @param {string} tableName the table name which you want to get, on the form of: 'anyDatabaseTable' OR 'any_database_table' (possible your real table name into your database).
* @returnType {MysqlTable}
* @return {MysqlTable}
*/
table<T>(tableName: string): Table<T>;
}
class MysqlWrapper {
connection: MysqlConnection;
class Table<T> {
private _name: string;
private _connection: Connection;
private _columns: string[];
private _primaryKey: string;
private _criteriaDivider: CriteriaDivider<T>;
private _rules: SelectQueryRules;
private _selectQuery: SelectQuery<T>
private _saveQuery: SaveQuery<T>;
private _deleteQuery: DeleteQuery<T>;
constructor(tableName: string, connection: Connection);
/**
* An array of all columns' names inside this table.
*/
columns: string[];
/**
* The name of the primary key column which this table is using.
*/
primaryKey: string;
/**
* The MysqlConnection object which this MysqlTable belongs.
*/
connection: Connection;
/**
* The real database name of the table. Autofilled by library.
*/
name: string;
/**
* Set of the query rules that will be applied after the 'where clause' on each select query executed by this table.
* @return {SelectQueryRules}
*/
rules: SelectQueryRules;
/**
* Returns this table's criteria divider class.
* @return {CriteriaDivider}
*/
criteriaDivider: CriteriaDivider<T>;
/**
* Returns new Criteria Builder each time.
* Helps you to make criteria raw js objects ready to use in find,remove and save methods.
* @return {CriteriaBuilder}
*/
criteria: CriteriaBuilder<T>;
/**
* Adds or turn on an event listener/watcher on a table for a 'database event'.
* @param {string} evtType the event type you want to watch, one of these: ["INSERT", "UPDATE", "REMOVE", "SAVE"].
* @param {function} callback Callback which has one parameter(typeof any[]) which filled by the parsedResults (results after query executed and exports to object(s)).
* @returnType {nothing}
* @return {nothing}
*/
on(evtType: string, callback: (parsedResults: any[]) => void): void;
/**
* Removes or turn off an event listener/watcher from a table for a specific event type.
* @param {string} evtType the Event type you want to remove, one of these: "INSERT", "UPDATE", "REMOVE", "SAVE".
* @param {function} callbackToRemove the callback that you were used for watch this event type.
* @returnType {nothing}
* @return {nothing}
*/
off(evtType: string, callbackToRemove: (parsedResults: any[]) => void): void;
/**
* Use it when you want to check if extended function is exists here.
* @param {string} extendedFunctionName the name of the function you want to check.
* @returnType {boolean}
* @return {boolean}
*/
has(extendedFunctionName: string): boolean;
/**
* Extends this table's capabilities with a function.
* @param {string} functionName the function name you want to use, this is used when you want to call this function later.
* @param {function} theFunction the function with any optional parameters you want to pass along.
* @returnType {nothing}
* @return {nothing}
*/
extend(functionName: string, theFunction: (...args: any[]) => any): void;
/**
* Converts and returns an object from this form: { a_property:'dsda', other_property:something, any_property_name:true } to { aProperty:..., otherProperty...,anyPropertyName...}
* @param {any} row the raw row object.
* @returnType {any}
* @return {any}
*/
objectFromRow(row: any): any;
/**
* Converts and returns an object from this form: { aProperty:'dsda', otherProperty:something, anyPropertyName:true } to { a_property:..., other_property...,any_property_name...}
* @param {any} row the raw row object.
* @returnType {any}
* @return {any}
*/
rowFromObject(obj: any): any;
/**
* Returns and array of [columns[],values[]]
* @param {any} jsObject the raw row object.
* @returnType {array}
* @return {array}
*/
getRowAsArray(jsObject: any): Array<any>;
/**
* Returns the primary key's value from an object.
* @param {any} jsObject the object which you want to find and return the value of the primary key.
* @returnType {number | string}
* @return {number | string}
*/
getPrimaryKeyValue(jsObject: any): number | string;
/**
*
*/
find(criteriaRawJsObject: any): Promise<T[]>; // only criteria
find(criteriaRawJsObject: any, callback: ((_results: T[]) => any)): Promise<T[]>; // criteria and callback
find(criteriaRawJsObject: any, callback?: (_results: T[]) => any): Promise<T[]>;
findSingle(criteriaRawJsObject: any, callback?: (_result: T) => any): Promise<T>;
findById(id: number|string): Promise<T>; // without callback
findById(id: number | string, callback?: (result: T) => any): Promise<T>;
findAll(): Promise<T[]>; // only criteria and promise
findAll(tableRules: RawRules): Promise<T[]> // only rules and promise
findAll(tableRules?: RawRules, callback?: (_results: T[]) => any): Promise<T[]>;
save(criteriaRawJsObject: any): Promise<any>; //without callback
save(criteriaRawJsObject: any, callback?: (_result: any) => any): Promise<any>;
remove(id: number | string): Promise<DeleteAnswer>; // ID without callback
remove(criteriaRawObject: any): Promise<DeleteAnswer>; // criteria obj without callback
remove(criteriaOrID: any | number | string, callback?: (_result: DeleteAnswer) => any): Promise<DeleteAnswer>;
}
class Wrapper {
connection: Connection;
readyListenerCallbacks: Function[];
constructor(connection?: MysqlConnection);
constructor(connection?: Connection);
static when(..._promises: Promise<any>[]): Promise<any>;
setConnection(connection: MysqlConnection): void;
setConnection(connection: Connection): void;
/**
* Force to use/fetch information from only certain of database's tables, otherwise all database's tables information will be fetched.
* @param {Array} tables the array of the tables {string}
* @returnType {nothing}
* @return {nothing}
*/
useOnly(...useTables: any[]): void;
has(tableName: string, functionName?: string): boolean;
ready(callback: () => void): void;
table<T>(tableName: string): MysqlTable<T>;
table<T>(tableName: string): Table<T>;
noticeReady(): void;
removeReadyListener(callback: () => void): void;
query(queryStr: string, callback: (err: Mysql.IError, results: any) => any, queryArguments?: any[]): void;
/**
* Close the entire real connection and remove all event's listeners (if exist).
* the difference from the 'end' is that this method doesn't care about errors so no callback passing here.
*/
destroy(): void;
/**
* Close the entire real connection and remove all event's listeners (if exist).
* @param {function} maybeAcallbackError If error occurs when closing the connection, this callback has the responsibility to catch it.
* @returnType {nothing}
* @return {nothing}
*/
end(maybeAcallbackError: (err: any) => void): void;
newTableRules(tableName: string): SelectQueryRules;
buildRules(): SelectQueryRules;
buildRules(parentRules?: SelectQueryRules): SelectQueryRules;
}
function wrap(mysqlUrlOrObjectOrMysqlAlreadyConnection: Mysql.IConnection | string, ...useTables: any[]): MysqlWrapper;
function wrap(mysqlUrlOrObjectOrMysqlAlreadyConnection: Mysql.IConnection | string, ...useTables: any[]): Wrapper;
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="object-assign.d.ts" />
import objectAssign = require("object-assign");
function assign1() {
var result = objectAssign({hello: "world"});
return result;
}
function assign2() {
var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"});
return result;
}
function assign3() {
var result = objectAssign({hello: "world"}, {hello: "worlds", second: "extra"}, {hello: "stop", the: "spinning"});
return result;
}
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for object-assign 4.0.1
// Project: https://github.com/sindresorhus/object-assign
// Definitions by: Christopher Brown <https://github.com/chbrown>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "object-assign" {
function objectAssign(target: any, ...sources: any[]): any;
export = objectAssign;
}
+15
View File
@@ -32,3 +32,18 @@ oboe('/content')
console.error('no such content');
}
});
oboe('friends.json')
.node('friend', function (parsedJson) {
console.log('friend parsed', parsedJson);
});
oboe('friends.json')
.node({
'friend': function (parsedJson) {
console.log('friend parsed', parsedJson);
},
'!': function (parsedJson) {
console.log('root parsed', parsedJson);
}
});
+58 -54
View File
@@ -5,61 +5,65 @@
/// <reference path="../node/node.d.ts" />
declare module "oboe" {
import stream = require('stream');
function oboe(url: string): oboe.Oboe;
function oboe(options: oboe.Options): oboe.Oboe;
function oboe(stream: stream.Readable) : oboe.Oboe;
module oboe {
var drop: {};
interface Oboe {
done(callback: (result: any) => void): Oboe;
fail(callback: (result: FailReason) => void): Oboe;
node(pattern: string, callback: CallbackSignature): Oboe;
on(event: string, pattern: string, callback: CallbackSignature): Oboe;
on(eventPattern: string, callback: CallbackSignature): Oboe;
path(pattern: string, callback: CallbackSignature): Oboe;
path(listeners: any): Oboe;
removeListener(eventPattern: string, callback: CallbackSignature): Oboe;
removeListener(event: string, pattern: string, callback: CallbackSignature): Oboe;
start(callback: (status: number, headers: Object) => void): Oboe;
abort():void;
source: string;
}
interface CallbackSignature {
(node: any, pathOrHeaders: any, ancestors: Object[]): any;
}
interface Options {
url: string;
method?: string;
headers?: Object;
body?: any;
cached?: boolean;
withCredentials?: boolean;
}
interface FailReason {
thrown?: Error;
statusCode?: number;
body?: string;
jsonBody?: Object;
}
declare module oboe {
interface OboeFunction extends Function {
drop: Object;
(url: string): Oboe;
(options: Options): Oboe;
(stream: NodeJS.ReadableStream): Oboe;
}
export = oboe;
interface Oboe {
done(callback: (result: any) => void): Oboe;
fail(callback: (result: FailReason) => void): Oboe;
node(pattern: string, callback: CallbackSignature): Oboe;
node(patterns: PatternMap): Oboe;
on(event: string, pattern: string, callback: CallbackSignature): Oboe;
on(eventPattern: string, callback: CallbackSignature): Oboe;
path(pattern: string, callback: CallbackSignature): Oboe;
path(listeners: any): Oboe;
removeListener(eventPattern: string, callback: CallbackSignature): Oboe;
removeListener(event: string, pattern: string, callback: CallbackSignature): Oboe;
start(callback: (status: number, headers: Object) => void): Oboe;
abort():void;
source: string;
}
interface CallbackSignature {
(node: any, pathOrHeaders: any, ancestors: Object[]): any;
}
interface Options {
url: string;
method?: string;
headers?: Object;
body?: any;
cached?: boolean;
withCredentials?: boolean;
}
interface FailReason {
thrown?: Error;
statusCode?: number;
body?: string;
jsonBody?: Object;
}
interface PatternMap {
[pattern: string]: CallbackSignature
}
}
declare var oboe: oboe.OboeFunction;
declare module "oboe" {
export = oboe;
}
+111
View File
@@ -0,0 +1,111 @@
/// <reference path="observe-js.d.ts" />
module observejs {
function Test_PathObserver() {
var obj = { foo: { bar: 'baz' } };
var defaultValue = 42;
var observer = new PathObserver(obj, 'foo.bar', defaultValue);
observer.open(function(newValue, oldValue) {
// respond to obj.foo.bar having changed value.
});
}
function Test_ArrayObserver() {
var arr = [0, 1, 2, 4];
var observer = new ArrayObserver(arr);
observer.open(function(splices) {
// respond to changes to the elements of arr.
splices.forEach(function(splice) {
splice.index; // the index position that the change occurred.
splice.removed; // an array of values representing the sequence of removed elements
splice.addedCount; // the number of elements which were inserted.
});
});
}
function Test_ObejctObserver() {
var myObj = { id: 1, foo: 'bar' };
var observer = new ObjectObserver(myObj);
observer.open(function(added, removed, changed, getOldValueFn) {
// respond to changes to the obj.
Object.keys(added).forEach(function(property) {
property; // a property which has been been added to obj
added[property]; // its value
});
Object.keys(removed).forEach(function(property) {
property; // a property which has been been removed from obj
getOldValueFn(property); // its old value
});
Object.keys(changed).forEach(function(property) {
property; // a property on obj which has changed value.
changed[property]; // its value
getOldValueFn(property); // its old value
});
});
}
function Test_CompounObserver() {
var obj = {
a: 1,
b: 2,
};
var otherObj = { c: 3 };
var observer = new CompoundObserver();
observer.addPath(obj, 'a');
observer.addObserver(new PathObserver(obj, 'b'));
observer.addPath(otherObj, 'c');
var logTemplate = 'The %sth value before & after:';
observer.open(function(newValues, oldValues) {
// Use for-in to iterate which values have changed.
for (var i in oldValues) {
console.log(logTemplate, i, oldValues[i], newValues[i]);
}
});
}
function Test_ObserverTransform_1() {
var obj = { value: 10 };
var observer = new PathObserver(obj, 'value');
function getValue(value:any) { return value * 2 };
function setValue(value:any) { return value / 2 };
var transform = new ObserverTransform(observer, getValue, setValue);
// returns 20.
transform.open(function(newValue, oldValue) {
console.log('new: ' + newValue + ', old: ' + oldValue);
});
obj.value = 20;
transform.deliver(); // 'new: 40, old: 20'
transform.setValue(4); // obj.value === 2;
}
function Test_ObserverTransform_2() {
var obj = { a: 1, b: 2, c: 3 };
var observer = new CompoundObserver();
observer.addPath(obj, 'a');
observer.addPath(obj, 'b');
observer.addPath(obj, 'c');
var transform = new ObserverTransform(observer, function(values) {
var value = 0;
for (var i = 0; i < values.length; i++)
value += values[i]
return value;
});
// returns 6.
transform.open(function(newValue, oldValue) {
console.log('new: ' + newValue + ', old: ' + oldValue);
});
obj.a = 2;
obj.c = 10;
transform.deliver(); // 'new: 14, old: 6'
}
}
+250
View File
@@ -0,0 +1,250 @@
// Type definitions for observe-js v0.5.5
// Project: https://github.com/Polymer/observe-js
// Definitions by: Oliver Herrmann <https://github.com/herrmanno/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module observejs {
/*----------------------
Observable
----------------------*/
interface Observable {
/**
* Begins observation.
* @param onChange the function that gets invoked if a change is detected
* @param the target of observation
*/
open(onChange:(newValue:any, oldValue:any)=>any, receiver?:any):void
/**
* Report any changes now (does nothing if there are no changes to report).
*/
deliver(): void
/**
* If there are changes to report, ignore them. Returns the current value of the observation.
*/
discardChanges():void
/**
* Ends observation. Frees resources and drops references to observed objects.
*/
close():void
}
/*----------------------
PathObserver
----------------------*/
interface PathObserver_static {
/**
* Constructor
* @param receiver the target for observation
* @param path specifies the paht to observe. If path === '' the receiver itself gets observed.
* @param defaultValue the defaultValue
*/
new(receiver:any, path:string, defaultValue?:any): PathObserver_instance
}
interface PathObserver_instance extends Observable {
/**
* sets the observed value without notifying about the change.
* @param value the value to set
*/
setValue(value:any): void
}
/**
* Observes a "value-at-a-path" from a given object:
*/
var PathObserver: PathObserver_static
/*----------------------
ArrayObserver
----------------------*/
interface splice {
/**
* the index position that the change occured
*/
index:number
/**
* an array of values representing the sequence of removed elements
*/
removed: Array<any>
/**
* the number of element which were inserted
*/
addedCount:number
}
interface ArrayObserver_static {
/**
* Constructor
* @param receiver the target for observation
*/
new(receiver:Array<any>): ArrayObserver_instance
/**
* transforms a copy of an old state of an array into a copy of its current state.
* @param previous array of old state
* @param current array of current state
* @param splices splices to apply
*/
applySplices(previous:Array<any>, current:Array<any>, splices:Array<splice>):void
}
interface ArrayObserver_instance extends Observable {
open(onChange:(splices:Array<splice>)=>any):void
}
/**
* ArrayObserver observes the index-positions of an Array and reports changes as the minimal set of "splices" which would have had the same effect.
*/
var ArrayObserver: ArrayObserver_static
/*----------------------
ObjectObserver
----------------------*/
interface Properties {
[key:string]:any
}
interface ObjectObserver_static {
/**
* Constructor
* @param receiver the target for observation
*/
new(receiver:any): ObjectObserver_instance
}
interface ObjectObserver_instance extends Observable {
open(onChange:(added:Properties, removed:Properties, changed:Properties, getOldValueFn:(property:string)=>any)=>any):void
}
/**
* Observes the set of own-properties of an object and their values
*/
var ObjectObserver: ObjectObserver_static
/*----------------------
CompounObserver
----------------------*/
interface CompoundObserver_static {
/**
* Constructor
*/
new(): CompoundObserver_instance
}
interface CompoundObserver_instance extends Observable {
open(onChange:(newValues:Array<any>, oldValue:Array<any>)=>any):void
/**
* Adds the receivers property at the specified path to the list of observables.
* @param receiver the target for observation
* @param path specifies the paht to observe. If path === '' the receiver itself gets observed.
*/
addPath(receiver:any, path:string):void
/**
* Adds an Observer to the list of observables.
*/
addObserver(observer:Observable):void
}
/**
* CompoundObserver allows simultaneous observation of multiple paths and/or Observables.
*/
var CompoundObserver: CompoundObserver_static
/*----------------------
ObserverTransform
----------------------*/
interface ObserverTransform_static {
/**
* Constructor
* @param observer the observer to transform
* @param getValue function that proxys getting a value
* @param setValue function that proxys setting a value
*/
new(observer:Observable, getValue:(value:any)=>any, setValue:(value:any)=>any): ObserverTransform_instance
/**
* Constructor
* @param observer the observer to transform
* @param valueFn function that gets invoked with all observed values. May return a single new value.
*/
new(observer:Observable, valueFn:(values:Array<any>)=>any): ObserverTransform_instance
}
interface ObserverTransform_instance extends Observable {
/**
* sets the observed value without notifying about the change.
* @param value the value to set
*/
setValue(value:any): void
}
/**
* CompoundObserver allows simultaneous observation of multiple paths and/or Observables.
*/
var ObserverTransform: ObserverTransform_static
/*----------------------
Path
----------------------*/
interface Path {
/**
* Returns the current value of the path from the provided object. If eval() is available,
* a compiled getter will be used for better performance. Like PathObserver above, undefined
* is returned unless you provide an overriding defaultValue.
*/
getValueFrom(object:any, defaultValue:any): any
/**
* Attempts to set the value of the path from the provided object. Returns true IFF the path
* was reachable and set.
*/
getValueFrom(object:any, newValue:any): any
}
}
declare module "observejs" {
var PathObserver: typeof observejs.PathObserver;
var ArrayObserver: typeof observejs.ArrayObserver;
var ObjectObserver: typeof observejs.ObjectObserver;
var CompoundObserver: typeof observejs.CompoundObserver;
var ObserverTransform: typeof observejs.ObserverTransform;
var Path: observejs.Path;
export {
PathObserver,
ArrayObserver,
ObjectObserver,
CompoundObserver,
ObserverTransform,
Path
};
}
+19 -1
View File
@@ -34,6 +34,7 @@ var geometry: ol.geom.Geometry;
var loadingstrategy: ol.LoadingStrategy;
var tilegrid: ol.tilegrid.TileGrid;
var vector: ol.source.Vector;
var projection: ol.proj.Projection;
//
// ol.Attribution
@@ -161,7 +162,9 @@ var tileLayer: ol.layer.Tile = new ol.layer.Tile({
//
// ol.proj
//
var projection: ol.proj.Projection;
projection = new ol.proj.Projection({
code:stringValue,
});
//
// ol.Map
@@ -174,6 +177,21 @@ var map: ol.Map = new ol.Map({
});
map.beforeRender(preRenderFunction);
//
// ol.source.ImageWMS
//
var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({
serverType: stringValue,
url:stringValue
});
//
// ol.source.TileWMS
//
var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({
serverType: stringValue,
url:stringValue
});
//
// ol.animation
//
+218 -106
View File
@@ -22,23 +22,23 @@ declare module olx {
interface FrameState {
/**
*
*
*/
pixelRatio: number;
/**
*
*
*/
time: number;
/**
*
*
*/
viewState: olx.ViewState;
}
interface FeatureOverlayOptions {
/**
* Features
*/
@@ -88,6 +88,71 @@ declare module olx {
targetSize?: number;
}
interface BaseWMSOptions {
/** Attributions. */
attributions?: Array<ol.Attribution>;
/** WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. */
params?: any;
/** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */
crossOrigin?: string;
/** experimental Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true. */
hidpi?: boolean;
/** experimental The type of the remote WMS server: mapserver, geoserver or qgis. Only needed if hidpi is true. Default is undefined. */
serverType?: ol.source.wms.ServerType;
/** WMS service URL. */
url?: string;
/** Logo. */
logo?: olx.LogoOptions;
/** experimental Projection. */
projection?: ol.proj.ProjectionLike;
}
interface ImageWMSOptions extends BaseWMSOptions {
/** experimental Optional function to load an image given a URL. */
imageLoadFunction?: ol.ImageLoadFunctionType;
/** Ratio. 1 means image requests are the size of the map viewport, 2 means twice the width and height of the map viewport, and so on. Must be 1 or higher. Default is 1.5. */
ratio?: number;
/** Resolutions. If specified, requests will be made for these resolutions only. */
resolutions?: Array<number>;
}
interface TileWMSOptions {
/** The size in pixels of the gutter around image tiles to ignore. By setting this property to a non-zero value, images will be requested that are wider and taller than the tile size by a value of 2 x gutter. Defaults to zero. Using a non-zero value allows artifacts of rendering at tile edges to be ignored. If you control the WMS service it is recommended to address "artifacts at tile edges" issues by properly configuring the WMS service. For example, MapServer has a tile_map_edge_buffer configuration parameter for this. See http://mapserver.org/output/tile_mode.html. */
gutter?: number;
/** Tile grid. Base this on the resolutions, tilesize and extent supported by the server. If this is not defined, a default grid will be used: if there is a projection extent, the grid will be based on that; if not, a grid based on a global extent with origin at 0,0 will be used. */
tileGrid?: ol.tilegrid.TileGrid;
/** experimental Maximum zoom. */
maxZoom?: number;
/** experimental Optional function to load a tile given a URL. */
tileLoadFunction?: ol.TileLoadFunctionType;
/** WMS service URL. */
url?: string;
/** WMS service urls. Use this instead of url when the WMS supports multiple urls for GetMap requests. */
urls?: Array<string>;
/** experimental The type of the remote WMS server. Currently only used when hidpi is true. Default is undefined. */
serverType?: ol.source.wms.ServerType;
/** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */
wrapX?: boolean;
}
/**
* Object literal with config options for the map logo.
*/
@@ -101,6 +166,7 @@ declare module olx {
* Image src for the logo
*/
src: string;
}
interface MapOptions {
@@ -238,30 +304,69 @@ declare module olx {
interface ViewState {
/**
*
*
*/
center: ol.Coordinate;
/**
*
*
*/
projection: ol.proj.Projection;
/**
*
*
*/
resolution: number;
/**
*
*
*/
rotation: number;
}
interface Projection {
/**
* The SRS identifier code, e.g. EPSG:4326.
*/
code: string;
/**
* Units. Required unless a proj4 projection is defined for code.
*/
units?: ol.proj.Units;
/**
* The validity extent for the SRS.
*/
extent?: Array<number>;
/**
* The axis orientation as specified in Proj4. The default is enu.
*/
axisOrientation?: string;
/**
* Whether the projection is valid for the whole globe. Default is false.
*/
global?: boolean;
/**
* experimental The world extent for the SRS.
*/
worldExtent?: ol.Extent;
/**
* experimental Function to determine resolution at a point. The function is called with
* a {number} view resolution and an {ol.Coordinate} as arguments, and returns the {number}
* resolution at the passed coordinate.
*/
getPointResolution?: (resolution: number, coordinate: ol.Coordinate) => number;
}
module animation {
interface BounceOptions {
/**
* The resolution to start the bounce from, typically map.getView().getResolution().
*/
@@ -284,7 +389,7 @@ declare module olx {
}
interface PanOptions {
/**
* The resolution to start the bounce from, typically map.getView().getResolution().
*/
@@ -307,7 +412,7 @@ declare module olx {
}
interface RotateOptions {
/**
* The rotation value (in radians) to begin rotating from, typically map.getView().getRotation(). If undefined then 0 is assumed.
*/
@@ -335,7 +440,7 @@ declare module olx {
}
interface ZoomOptions {
/**
* The resolution to begin zooming from, typically map.getView().getResolution().
*/
@@ -383,14 +488,14 @@ declare module olx {
*/
//TODO: Replace with olx.control.RotateOptions
rotateOptions?: any;
/**
* Zoom. Default is true
*/
zoom?: boolean;
/**
*
*
*/
//TODO: Replace with olx.control.ZoomOptions
zoomOptions?: any;
@@ -729,7 +834,7 @@ declare module olx {
* Tile sizes. The length of this array needs to match the length of the resolutions array.
*/
tileSizes?: Array<number | ol.Size>;
/**
* Number of tile columns that cover the grid's extent for each zoom level. Only required when used with a source that has wrapX set to true, and only when the grid's origin differs from the one of the projection's extent. The array length has to match the length of the resolutions array, i.e. each resolution will have a matching entry here.
*/
@@ -852,6 +957,10 @@ declare module olx {
*/
declare module ol {
interface TileLoadFunctionType{ (image: ol.Image, url: string): void }
interface ImageLoadFunctionType{ (image: ol.Image, url: string): void }
/**
* An attribution for a layer source.
*/
@@ -862,13 +971,13 @@ declare module ol {
*/
constructor(options: olx.AttributionOptions);
/**
* Get the attribution markup.
/**
* Get the attribution markup.
* @returns The attribution HTML.
*/
getHTML(): string;
}
/**
* An expanded version of standard JS Array, adding convenience methods for manipulation. Add and remove changes to the Collection trigger a Collection event. Note that this does not cover changes to the objects within the Collection; they trigger events on the appropriate object, not on the Collection as a whole.
*/
@@ -925,7 +1034,7 @@ declare module ol {
*/
item(index: number): T;
/**
/**
* Remove the last element of the collection and return it. Return undefined if the collection is empty.
* @returns Element
*/
@@ -952,7 +1061,7 @@ declare module ol {
*/
removeAt(index: number): T;
/**
/**
* Set the element at the provided index.
* @param index Index.
* @param elem Element.
@@ -984,7 +1093,7 @@ declare module ol {
/**
* Rotation around the device z-axis (in radians).
* @returns The euler angle in radians of the device from the standard Z axis.
* @returns The euler angle in radians of the device from the standard Z axis.
*/
getAlpha(): number;
@@ -996,7 +1105,7 @@ declare module ol {
/**
* Rotation around the device y-axis (in radians).
* @returns The euler angle in radians of the device from the planar Y axis.
* @returns The euler angle in radians of the device from the planar Y axis.
*/
getGamma(): number;
@@ -1014,11 +1123,11 @@ declare module ol {
/**
* Enable or disable tracking of device orientation events.
* @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately.
* @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately.
*/
setTracking(tracking: boolean): void;
}
/**
* Events emitted by ol.interaction.DragBox instances are instances of this type.
*/
@@ -1145,7 +1254,7 @@ declare module ol {
/**
* Get the map associated with the overlay.
* @returns The map with which this feature overlay is associated.
* @returns The map with which this feature overlay is associated.
*/
getMap(): ol.Map;
@@ -1217,19 +1326,19 @@ declare module ol {
/**
* Get a geometry of the position accuracy.
* @returns A geometry of the position accuracy.
* @returns A geometry of the position accuracy.
*/
getAccuracyGeometry(): ol.geom.Geometry;
/**
* Get the altitude associated with the position.
* @returns The altitude of the position in meters above mean sea level.
* @returns The altitude of the position in meters above mean sea level.
*/
getAltitude(): number;
/**
* Get the altitude accuracy of the position.
* @returns The accuracy of the altitude measurement in meters.
* @returns The accuracy of the altitude measurement in meters.
*/
getAltitudeAccuracy(): number;
@@ -1247,7 +1356,7 @@ declare module ol {
/**
* Get the projection associated with the position.
* @returns The projection the position is reported in.
* @returns The projection the position is reported in.
*/
getProjection(): ol.proj.Projection;
@@ -1259,7 +1368,7 @@ declare module ol {
/**
* Determine if the device location is being tracked.
* @returns The device location is being tracked.
* @returns The device location is being tracked.
*/
getTracking(): boolean;
@@ -1298,33 +1407,33 @@ declare module ol {
*/
constructor(options?: olx.GraticuleOptions);
/**
* Get the map associated with this graticule.
/**
* Get the map associated with this graticule.
* @returns The map.
*/
getMap(): Map;
/**
* Get the list of meridians. Meridians are lines of equal longitude.
/**
* Get the list of meridians. Meridians are lines of equal longitude.
* @returns The meridians.
*/
getMeridians(): Array<ol.geom.LineString>;
/**
* Get the list of parallels. Pallels are lines of equal latitude.
/**
* Get the list of parallels. Pallels are lines of equal latitude.
* @returns The parallels.
*/
getParallels(): Array<ol.geom.LineString>;
/**
* Set the map for this graticule.The graticule will be rendered on the provided map.
/**
* Set the map for this graticule.The graticule will be rendered on the provided map.
* @param map Map
*/
setMap(map: Map): void;
}
/**
*
*
*/
class Image extends ol.ImageBase {
@@ -1351,13 +1460,13 @@ declare module ol {
}
/**
*
*
*/
class ImageBase {
}
/**
*
*
*/
class ImageTile extends ol.Tile {
@@ -1446,7 +1555,7 @@ declare module ol {
* @param ref Value to use as this when executing callback.
* @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested.
* @param ref2 Value to use as this when executing layerFilter.
* @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value.
* @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value.
*/
forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void;
@@ -1457,7 +1566,7 @@ declare module ol {
* @param ref Value to use as this when executing callback.
* @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested.
* @param ref2 Value to use as this when executing layerFilter.
* @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value.
* @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value.
*/
forEachLayerAtPixel(pixel: ol.Pixel, callback: (layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void;
@@ -1470,7 +1579,7 @@ declare module ol {
/**
* Get the coordinate for a given pixel. This returns a coordinate in the map view projection.
* @param pixel Pixel position in the map viewport.
* @returns The coordinate for the pixel position.
* @returns The coordinate for the pixel position.
*/
getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate;
@@ -1496,7 +1605,7 @@ declare module ol {
/**
* Get the layergroup associated with this map.
* @returns A layer group containing the layers in this map.
* @returns A layer group containing the layers in this map.
*/
getLayerGroup(): ol.layer.Group;
@@ -1521,13 +1630,13 @@ declare module ol {
/**
* Get the size of this map.
* @returns The size in pixels of the map in the DOM.
* @returns The size in pixels of the map in the DOM.
*/
getSize(): ol.Size;
/**
* Get the target in which this map is rendered. Note that this returns what is entered as an option or in setTarget: if that was an element, it returns an element; if a string, it returns that.
* @returns The Element or id of the Element that the map is rendered in.
* @returns The Element or id of the Element that the map is rendered in.
*/
getTarget(): Element | string;
@@ -1537,8 +1646,8 @@ declare module ol {
*/
getTargetElement(): Element;
/**
* Get the view associated with this map. A view manages properties such as center and resolution.
/**
* Get the view associated with this map. A view manages properties such as center and resolution.
* @returns The view that controls this map.
*/
getView(): View;
@@ -1561,21 +1670,21 @@ declare module ol {
/**
* Remove the given control from the map.
* @param Control.
* @returns The removed control (or undefined if the control was not found).
* @returns The removed control (or undefined if the control was not found).
*/
removeControl(control: ol.control.Control): ol.control.Control;
/**
* Remove the given interaction from the map.
* @param interaction Interaction to remove.
* @returns The removed interaction (or undefined if the interaction was not found).
* @returns The removed interaction (or undefined if the interaction was not found).
*/
removeInteraction(interaction: ol.interaction.Interaction): ol.interaction.Interaction;
/**
* Removes the given layer from the map.
* @param Layer.
* @returns The removed layer (or undefined if the layer was not found).
* @returns The removed layer (or undefined if the layer was not found).
*/
removeLayer(layer: ol.layer.Base): ol.layer.Base;
@@ -1620,18 +1729,18 @@ declare module ol {
*/
setTarget(target: string): void;
/**
* Set the view for this map.
/**
* Set the view for this map.
* @param view The view that controls this map.
*/
setView(view: View): void;
/**
* Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport.
/**
* Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport.
* */
updateSize(): void;
}
/**
* Events emitted as map browser events are instances of this type. See ol.Map for which events trigger a map browser event.
*/
@@ -1646,7 +1755,7 @@ declare module ol {
* Indicates if the map is currently being dragged. Only set for POINTERDRAG and POINTERMOVE events. Default is false.
*/
dragging: boolean;
/**
* The frame state at the time of the event
*/
@@ -1662,12 +1771,12 @@ declare module ol {
*/
originalEvent: Event;
/**
/**
* The pixel of the original browser event.
*/
pixel: Pixel;
// Methods
/**
@@ -1715,13 +1824,13 @@ declare module ol {
*/
get(key: string): any;
/**
/**
* Get a list of object property names.
* @returns List of property names.
*/
getKeys(): Array<string>;
/**
/**
* Get an object of all property names and values.
* @returns Object.
*/
@@ -1732,14 +1841,14 @@ declare module ol {
*/
getRevision(): number;
/**
/**
* Sets a value.
* @param key Key name.
* @param value Value.
*/
set(key: string, value: any): void;
/**
/**
* Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties).
* @param Values.
*/
@@ -1910,7 +2019,7 @@ declare module ol {
*/
setPositioning(positioning: ol.OverlayPositioning): void;
}
/**
* Events emitted by ol.interaction.Select instances are instances of this type.
*/
@@ -2089,7 +2198,7 @@ declare module ol {
*/
setZoom(zoom: number): void;
}
// NAMESPACES
/**
@@ -2102,7 +2211,7 @@ declare module ol {
* @param options Bounce options.
*/
function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction;
/**
* Generate an animated transition while updating the view center.
* @param options Pan options.
@@ -2160,7 +2269,7 @@ declare module ol {
* @returns Control.s
*/
function defaults(options?: olx.control.DefaultsOptions): ol.Collection<ol.control.Control>;
/**
* Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'.
*/
@@ -2203,7 +2312,7 @@ declare module ol {
* Add delta to coordinate. coordinate is modified in place and returned by the function.
* @param coordinate Coordinate
* @param delta Delta
* @returns The input coordinate adjusted by the given delta.
* @returns The input coordinate adjusted by the given delta.
*/
function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate;
@@ -2234,7 +2343,7 @@ declare module ol {
/**
* Format a geographic coordinate with the hemisphere, degrees, minutes, and seconds.
* @param coordinate COordinate
* @returns Hemisphere, degrees, minutes and seconds.
* @returns Hemisphere, degrees, minutes and seconds.
*/
function toStringHDMS(coordinate?: ol.Coordinate): string;
@@ -2271,7 +2380,7 @@ declare module ol {
* @param number Input between 0 and 1
* @returns Output between 0 and 1
*/
function inAndOut (t: number): number;
function inAndOut(t: number): number;
/**
* Maintain a constant speed over time.
@@ -2341,7 +2450,7 @@ declare module ol {
* @param extent Extent
* @param x X coordinate
* @param y Y coordinate
* @returns The x, y values are contained in the extent.
* @returns The x, y values are contained in the extent.
*/
function containsXY(extent: ol.Extent, x: number, y: number): boolean;
@@ -2478,7 +2587,7 @@ declare module ol {
* Feature format for reading and writing data in the GeoJSON format.
*/
class GeoJSON extends ol.format.JSONFeature {
/**
* @constructor
* @param Options
@@ -2492,7 +2601,7 @@ declare module ol {
* @returns Feature
*/
readFeature(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.Feature;
/**
* Read all features from a GeoJSON source. Works with both Feature and FeatureCollection sources.
* @param source Source
@@ -2624,7 +2733,7 @@ declare module ol {
}
module geom {
// Type definitions
interface GeometryLayout extends String { }
interface GeometryType extends String { }
@@ -2798,7 +2907,7 @@ declare module ol {
/**
* Return the minimum resolution of the layer.
* @returns The minimum resolution of the layer.
* @returns The minimum resolution of the layer.
*/
getMinResolution(): number;
@@ -2971,7 +3080,7 @@ declare module ol {
class Layer extends ol.layer.Base {
/**
* @constructor
* @constructor
* @param options Layer options
*/
constructor(options?: olx.layer.LayerOptions);
@@ -2988,7 +3097,7 @@ declare module ol {
*/
setSource(source: ol.source.Source): void;
}
/**
* For layer sources that provide pre-rendered, tiled images in grids that are organized by zoom levels for specific resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors.
*/
@@ -3193,7 +3302,8 @@ declare module ol {
*/
function transformExtent(extent: Extent, source: ProjectionLike, destination: ProjectionLike): Extent;
interface Projection {
class Projection {
constructor(options: olx.Projection)
}
}
@@ -3238,6 +3348,7 @@ declare module ol {
}
class ImageWMS {
constructor(options: olx.ImageWMSOptions);
}
class MapQuest {
@@ -3278,6 +3389,7 @@ declare module ol {
}
class TileWMS {
constructor(options: olx.TileWMSOptions);
}
class Vector {
@@ -3514,7 +3626,7 @@ declare module ol {
*/
getTileSize(z: number): number | ol.Size;
}
/**
* Set the grid pattern for sources accessing WMTS tiled-image servers.
*/
@@ -3540,7 +3652,7 @@ declare module ol {
*/
getMatrixIds(): Array<string>;
}
/**
* Set the grid pattern for sources accessing Zoomify tiled-image servers.
*/
@@ -3572,7 +3684,7 @@ declare module ol {
*/
constructor(canvas: HTMLCanvasElement, gl: WebGLRenderingContext);
/**
/**
Get the WebGL rendering context
@returns The rendering context.
*/
@@ -3595,55 +3707,55 @@ declare module ol {
// Type definitions
/**
* A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas.
/**
* A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas.
*/
function CanvasFunctionType(extent: Extent, resolution: number, pixelRatio: number, size: Size, projection: proj.Projection): HTMLCanvasElement;
/**
* A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive.
/**
* A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive.
*/
interface Color extends Array<number> { }
/**
* An array of numbers representing an xy coordinate. Example: [16, 48].
* An array of numbers representing an xy coordinate. Example: [16, 48].
*/
interface Coordinate extends Array<number> { }
/**
* An array of numbers representing an extent: [minx, miny, maxx, maxy].
/**
* An array of numbers representing an extent: [minx, miny, maxx, maxy].
*/
interface Extent extends Array<number> { }
/**
* Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right'
/**
* Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right'
*/
interface OverlayPositioning extends String { }
/**
* An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel.
* An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel.
*/
interface Pixel extends Array<number> { }
/**
* Available renderers: 'canvas', 'dom' or 'webgl'.
/**
* Available renderers: 'canvas', 'dom' or 'webgl'.
*/
interface RendererType extends String { }
/**
* An array of numbers representing a size: [width, height].
/**
* An array of numbers representing a size: [width, height].
*/
interface Size extends Array<number> { }
/**
* An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level.
/**
* An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level.
*/
interface TileCoord extends Array<number> { }
// Functions
// Functions
/**
* A function that takes a ol.Coordinate and transforms it into a {string}.
/**
* A function that takes a ol.Coordinate and transforms it into a {string}.
*/
interface CoordinateFormatType { (coordinate?: Coordinate): string; }
@@ -3671,4 +3783,4 @@ declare module ol {
* A transform function accepts an array of input coordinate values, an optional output array, and an optional dimension (default should be 2). The function transforms the input coordinate values, populates the output array, and returns the output array.
*/
interface TransformFunction { (input: Array<number>, output?: Array<number>, dimension?: number): Array<number> }
}
}
+1 -3
View File
@@ -4,7 +4,6 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path='../react/react.d.ts' />
///<reference path='../react/react-addons.d.ts' />
declare module ReactRouter {
import React = __React;
@@ -114,13 +113,12 @@ declare module ReactRouter {
// Components
// ----------------------------------------------------------------------
// Link
interface LinkProp {
interface LinkProp extends React.HTMLAttributes {
activeClassName?: string;
activeStyle?: {};
to: string;
params?: {};
query?: {};
onClick?: Function;
}
interface Link extends React.ReactElement<LinkProp>, Navigation, State {
handleClick(event: any): void;
+2 -8
View File
@@ -1,11 +1,5 @@
# React v0.13.3 Type Definitions
This folder contains the following `.d.ts` files:
* `react.d.ts` declares the external module `"react"`
* `react-addons.d.ts` declares the external module `"react/addons"`
* `react-global.d.ts` declares the internal module `React` in the global namespace
* `react-addons-global.d.ts` extends the global `React` module with `addons`
Interfaces are duplicated between these files; please take care to keep them in sync when making changes.
See [#3615](https://github.com/borisyankov/DefinitelyTyped/pull/3615) for relevant discussion.
* `react.d.ts` declares the module `"react"` and `"react/addons"`
* `react-global.d.ts` declares the global namespace `React` (only include this if you are actually using the global `React`)
-278
View File
@@ -1,278 +0,0 @@
// Type definitions for ReactWithAddons v0.13.1 (internal module)
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="react-global.d.ts" />
declare module React {
//
// React.addons
// ----------------------------------------------------------------------
export module addons {
export var CSSTransitionGroup: CSSTransitionGroup;
export var TransitionGroup: TransitionGroup;
export var LinkedStateMixin: LinkedStateMixin;
export var PureRenderMixin: PureRenderMixin;
export function batchedUpdates<A, B>(
callback: (a: A, b: B) => any, a: A, b: B): void;
export function batchedUpdates<A>(callback: (a: A) => any, a: A): void;
export function batchedUpdates(callback: () => any): void;
// deprecated: use petehunt/react-classset or JedWatson/classnames
export function classSet(cx: { [key: string]: boolean }): string;
export function classSet(...classList: string[]): string;
export function cloneWithProps<P>(
element: DOMElement<P>, props: P): DOMElement<P>;
export function cloneWithProps<P>(
element: ClassicElement<P>, props: P): ClassicElement<P>;
export function cloneWithProps<P>(
element: ReactElement<P>, props: P): ReactElement<P>;
export function createFragment(
object: { [key: string]: ReactNode }): ReactFragment;
export function update(value: any[], spec: UpdateArraySpec): any[];
export function update(value: {}, spec: UpdateSpec): any;
// Development tools
export import Perf = ReactPerf;
export import TestUtils = ReactTestUtils;
}
//
// React.addons (Transitions)
// ----------------------------------------------------------------------
interface TransitionGroupProps {
component?: ReactType;
childFactory?: (child: ReactElement<any>) => ReactElement<any>;
}
interface CSSTransitionGroupProps extends TransitionGroupProps {
transitionName: string;
transitionAppear?: boolean;
transitionEnter?: boolean;
transitionLeave?: boolean;
}
type CSSTransitionGroup = ComponentClass<CSSTransitionGroupProps>;
type TransitionGroup = ComponentClass<TransitionGroupProps>;
//
// React.addons (Mixins)
// ----------------------------------------------------------------------
interface ReactLink<T> {
value: T;
requestChange(newValue: T): void;
}
interface LinkedStateMixin extends Mixin<any, any> {
linkState<T>(key: string): ReactLink<T>;
}
interface PureRenderMixin extends Mixin<any, any> {
}
//
// Reat.addons.update
// ----------------------------------------------------------------------
interface UpdateSpec {
$set?: any;
$merge?: {};
$apply?(value: any): any;
// [key: string]: UpdateSpec;
}
interface UpdateArraySpec extends UpdateSpec {
$push?: any[];
$unshift?: any[];
$splice?: any[][];
}
//
// React.addons.Perf
// ----------------------------------------------------------------------
interface ComponentPerfContext {
current: string;
owner: string;
}
interface NumericPerfContext {
[key: string]: number;
}
interface Measurements {
exclusive: NumericPerfContext;
inclusive: NumericPerfContext;
render: NumericPerfContext;
counts: NumericPerfContext;
writes: NumericPerfContext;
displayNames: {
[key: string]: ComponentPerfContext;
};
totalTime: number;
}
module ReactPerf {
export function start(): void;
export function stop(): void;
export function printInclusive(measurements: Measurements[]): void;
export function printExclusive(measurements: Measurements[]): void;
export function printWasted(measurements: Measurements[]): void;
export function printDOM(measurements: Measurements[]): void;
export function getLastMeasurements(): Measurements[];
}
//
// React.addons.TestUtils
// ----------------------------------------------------------------------
interface MockedComponentClass {
new(): any;
}
module ReactTestUtils {
export import Simulate = ReactSimulate;
export function renderIntoDocument<P>(
element: ReactElement<P>): Component<P, any>;
export function renderIntoDocument<C extends Component<any, any>>(
element: ReactElement<any>): C;
export function mockComponent(
mocked: MockedComponentClass, mockTagName?: string): typeof ReactTestUtils;
export function isElementOfType(
element: ReactElement<any>, type: ReactType): boolean;
export function isTextComponent(instance: Component<any, any>): boolean;
export function isDOMComponent(instance: Component<any, any>): boolean;
export function isCompositeComponent(instance: Component<any, any>): boolean;
export function isCompositeComponentWithType(
instance: Component<any, any>,
type: ComponentClass<any>): boolean;
export function findAllInRenderedTree(
tree: Component<any, any>,
fn: (i: Component<any, any>) => boolean): Component<any, any>;
export function scryRenderedDOMComponentsWithClass(
tree: Component<any, any>,
className: string): DOMComponent<any>[];
export function findRenderedDOMComponentWithClass(
tree: Component<any, any>,
className: string): DOMComponent<any>;
export function scryRenderedDOMComponentsWithTag(
tree: Component<any, any>,
tagName: string): DOMComponent<any>[];
export function findRenderedDOMComponentWithTag(
tree: Component<any, any>,
tagName: string): DOMComponent<any>;
export function scryRenderedComponentsWithType<P>(
tree: Component<any, any>,
type: ComponentClass<P>): Component<P, {}>[];
export function scryRenderedComponentsWithType<C extends Component<any, any>>(
tree: Component<any, any>,
type: ComponentClass<any>): C[];
export function findRenderedComponentWithType<P>(
tree: Component<any, any>,
type: ComponentClass<P>): Component<P, {}>;
export function findRenderedComponentWithType<C extends Component<any, any>>(
tree: Component<any, any>,
type: ComponentClass<any>): C;
export function createRenderer(): ShallowRenderer;
}
interface SyntheticEventData {
altKey?: boolean;
button?: number;
buttons?: number;
clientX?: number;
clientY?: number;
changedTouches?: TouchList;
charCode?: boolean;
clipboardData?: DataTransfer;
ctrlKey?: boolean;
deltaMode?: number;
deltaX?: number;
deltaY?: number;
deltaZ?: number;
detail?: number;
getModifierState?(key: string): boolean;
key?: string;
keyCode?: number;
locale?: string;
location?: number;
metaKey?: boolean;
pageX?: number;
pageY?: number;
relatedTarget?: EventTarget;
repeat?: boolean;
screenX?: number;
screenY?: number;
shiftKey?: boolean;
targetTouches?: TouchList;
touches?: TouchList;
view?: AbstractView;
which?: number;
}
interface EventSimulator {
(element: Element, eventData?: SyntheticEventData): void;
(component: Component<any, any>, eventData?: SyntheticEventData): void;
}
module ReactSimulate {
export var blur: EventSimulator;
export var change: EventSimulator;
export var click: EventSimulator;
export var cut: EventSimulator;
export var doubleClick: EventSimulator;
export var drag: EventSimulator;
export var dragEnd: EventSimulator;
export var dragEnter: EventSimulator;
export var dragExit: EventSimulator;
export var dragLeave: EventSimulator;
export var dragOver: EventSimulator;
export var dragStart: EventSimulator;
export var drop: EventSimulator;
export var focus: EventSimulator;
export var input: EventSimulator;
export var keyDown: EventSimulator;
export var keyPress: EventSimulator;
export var keyUp: EventSimulator;
export var mouseDown: EventSimulator;
export var mouseEnter: EventSimulator;
export var mouseLeave: EventSimulator;
export var mouseMove: EventSimulator;
export var mouseOut: EventSimulator;
export var mouseOver: EventSimulator;
export var mouseUp: EventSimulator;
export var paste: EventSimulator;
export var scroll: EventSimulator;
export var submit: EventSimulator;
export var touchCancel: EventSimulator;
export var touchEnd: EventSimulator;
export var touchMove: EventSimulator;
export var touchStart: EventSimulator;
export var wheel: EventSimulator;
}
class ShallowRenderer {
getRenderOutput<E extends ReactElement<any>>(): E;
getRenderOutput(): ReactElement<any>;
render(element: ReactElement<any>, context?: any): void;
unmount(): void;
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
/// <reference path="react-addons.d.ts" />
/// <reference path="react.d.ts" />
import React = require("react/addons");
import TestUtils = React.addons.TestUtils;
@@ -207,7 +207,7 @@ myComponent.reset();
// --------------------------------------------------------------------------
var children: any[] = ["Hello world", [null], React.DOM.span(null)];
var divStyle = { // CSSProperties
var divStyle: React.CSSProperties = { // CSSProperties
flex: "1 1 main-size",
backgroundImage: "url('hello.png')"
};
-1054
View File
File diff suppressed because it is too large Load Diff
+367
View File
@@ -0,0 +1,367 @@
/// <reference path="react-global.d.ts" />
interface Props extends React.Props<MyComponent> {
hello: string;
world?: string;
foo: number;
bar: boolean;
}
interface State {
inputValue?: string;
seconds?: number;
}
interface Context {
someValue?: string;
}
interface ChildContext {
someOtherValue: string;
}
interface MyComponent extends React.Component<Props, State> {
reset(): void;
}
var props: Props = {
key: 42,
ref: "myComponent42",
hello: "world",
foo: 42,
bar: true
};
var container: Element;
//
// Top-Level API
// --------------------------------------------------------------------------
var ClassicComponent: React.ClassicComponentClass<Props> =
React.createClass<Props, State>({
getDefaultProps() {
return <Props>{
hello: undefined,
world: "peace",
foo: undefined,
bar: undefined,
};
},
getInitialState() {
return {
inputValue: this.context.someValue,
seconds: this.props.foo
};
},
reset() {
this.replaceState(this.getInitialState());
},
render() {
return React.DOM.div(null,
React.DOM.input({
ref: input => this._input = input,
value: this.state.inputValue
}));
}
});
class ModernComponent extends React.Component<Props, State>
implements React.ChildContextProvider<ChildContext> {
static propTypes: React.ValidationMap<Props> = {
foo: React.PropTypes.number
}
static contextTypes: React.ValidationMap<Context> = {
someValue: React.PropTypes.string
}
static childContextTypes: React.ValidationMap<ChildContext> = {
someOtherValue: React.PropTypes.string
}
context: Context;
getChildContext() {
return {
someOtherValue: 'foo'
}
}
state = {
inputValue: this.context.someValue,
seconds: this.props.foo
}
reset() {
this.setState({
inputValue: this.context.someValue,
seconds: this.props.foo
});
}
private _input: React.HTMLComponent;
render() {
return React.DOM.div(null,
React.DOM.input({
ref: input => this._input = input,
value: this.state.inputValue
}));
}
}
// React.createFactory
var factory: React.Factory<Props> =
React.createFactory(ModernComponent);
var factoryElement: React.ReactElement<Props> =
factory(props);
var classicFactory: React.ClassicFactory<Props> =
React.createFactory(ClassicComponent);
var classicFactoryElement: React.ClassicElement<Props> =
classicFactory(props);
var domFactory: React.DOMFactory<any> =
React.createFactory("foo");
var domFactoryElement: React.DOMElement<any> =
domFactory();
// React.createElement
var element: React.ReactElement<Props> =
React.createElement(ModernComponent, props);
var classicElement: React.ClassicElement<Props> =
React.createElement(ClassicComponent, props);
var domElement: React.HTMLElement =
React.createElement("div");
// React.cloneElement
var clonedElement: React.ReactElement<Props> =
React.cloneElement(element, props);
var clonedClassicElement: React.ClassicElement<Props> =
React.cloneElement(classicElement, props);
var clonedDOMElement: React.HTMLElement =
React.cloneElement(domElement);
// React.render
var component: React.Component<Props, any> =
React.render(element, container);
var classicComponent: React.ClassicComponent<Props, any> =
React.render(classicElement, container);
var domComponent: React.DOMComponent<any> =
React.render(domElement, container);
// Other Top-Level API
var unmounted: boolean = React.unmountComponentAtNode(container);
var str: string = React.renderToString(element);
var markup: string = React.renderToStaticMarkup(element);
var notValid: boolean = React.isValidElement(props); // false
var isValid = React.isValidElement(element); // true
React.initializeTouchEvents(true);
var domNode: Element = React.findDOMNode(component);
domNode = React.findDOMNode(domNode);
//
// React Elements
// --------------------------------------------------------------------------
var type = element.type;
var elementProps: Props = element.props;
var key = element.key;
//
// React Components
// --------------------------------------------------------------------------
var displayName: string = ClassicComponent.displayName;
var defaultProps: Props = ClassicComponent.getDefaultProps();
var propTypes: React.ValidationMap<Props> = ClassicComponent.propTypes;
//
// Component API
// --------------------------------------------------------------------------
// modern
var componentState: State = component.state;
component.setState({ inputValue: "!!!" });
component.forceUpdate();
// classic
var htmlElement: Element = classicComponent.getDOMNode();
var divElement: HTMLDivElement = classicComponent.getDOMNode<HTMLDivElement>();
var isMounted: boolean = classicComponent.isMounted();
classicComponent.setProps(elementProps);
classicComponent.replaceProps(props);
classicComponent.replaceState({ inputValue: "???", seconds: 60 });
var myComponent = <MyComponent>component;
myComponent.reset();
//
// Attributes
// --------------------------------------------------------------------------
var children: any[] = ["Hello world", [null], React.DOM.span(null)];
var divStyle: React.CSSProperties = { // CSSProperties
flex: "1 1 main-size",
backgroundImage: "url('hello.png')"
};
var htmlAttr: React.HTMLAttributes = {
key: 36,
ref: "htmlComponent",
children: children,
className: "test-attr",
style: divStyle,
onClick: (event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
},
dangerouslySetInnerHTML: {
__html: "<strong>STRONG</strong>"
}
};
React.DOM.div(htmlAttr);
React.DOM.span(htmlAttr);
React.DOM.input(htmlAttr);
React.DOM.svg({ viewBox: "0 0 48 48" },
React.DOM.rect({
x: 22,
y: 10,
width: 4,
height: 28
}),
React.DOM.rect({
x: 10,
y: 22,
width: 28,
height: 4
}));
//
// React.PropTypes
// --------------------------------------------------------------------------
var PropTypesSpecification: React.ComponentSpec<any, any> = {
propTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Date),
optionalEnum: React.PropTypes.oneOf(["News", "Photos"]),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Date)
]),
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
requiredFunc: React.PropTypes.func.isRequired,
requiredAny: React.PropTypes.any.isRequired,
customProp: function(props: any, propName: string, componentName: string) {
if (!/matchme/.test(props[propName])) {
return new Error("Validation failed!");
}
return null;
}
},
render: (): React.ReactElement<any> => {
return null;
}
};
//
// ContextTypes
// --------------------------------------------------------------------------
var ContextTypesSpecification: React.ComponentSpec<any, any> = {
contextTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Date),
optionalEnum: React.PropTypes.oneOf(["News", "Photos"]),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Date)
]),
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
requiredFunc: React.PropTypes.func.isRequired,
requiredAny: React.PropTypes.any.isRequired,
customProp: function(props: any, propName: string, componentName: string) {
if (!/matchme/.test(props[propName])) {
return new Error("Validation failed!");
}
return null;
}
},
render: (): React.ReactElement<any> => {
return null;
}
};
//
// React.Children
// --------------------------------------------------------------------------
var childMap: { [key: string]: number } =
React.Children.map<number>(children, (child) => { return 42; });
React.Children.forEach(children, (child) => {});
var nChildren: number = React.Children.count(children);
var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]);
//
// Example from http://facebook.github.io/react/
// --------------------------------------------------------------------------
interface TimerState {
secondsElapsed: number;
}
class Timer extends React.Component<{}, TimerState> {
state = {
secondsElapsed: 0
}
private _interval: number;
tick() {
this.setState((prevState, props) => ({
secondsElapsed: prevState.secondsElapsed + 1
}));
}
componentDidMount() {
this._interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this._interval);
}
render() {
return React.DOM.div(
null,
"Seconds Elapsed: ",
this.state.secondsElapsed
);
}
}
React.render(React.createElement(Timer), container);
+230 -891
View File
File diff suppressed because it is too large Load Diff
+1067 -4
View File
File diff suppressed because it is too large Load Diff

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