Merge remote-tracking branch 'refs/remotes/DefinitelyTyped/master'

This commit is contained in:
CaselIT
2016-01-23 19:15:49 +01:00
257 changed files with 58667 additions and 12155 deletions
-1
View File
@@ -1 +0,0 @@
--noImplicitAny
+1 -1
View File
@@ -179,4 +179,4 @@ interface amplifyStatic {
}
declare var amplify: amplifyStatic;
declare module "amplify" { export =amplify; }
+47 -17
View File
@@ -1,23 +1,53 @@
/// <reference path="./angular-idle.d.ts" />
angular.module('app', ['ngIdle'])
.config(['$keepaliveProvider', '$idleProvider',
($keepaliveProvider: ng.idle.IKeepAliveProvider, $idleProvider: ng.idle.IIdleProvider) => {
$idleProvider.activeOn('mousemove keydown DOMMouseScroll mousewheel mousedown');
$idleProvider.idleDuration(5);
$idleProvider.warningDuration(5);
$idleProvider.keepalive(true)
$idleProvider.autoResume(true);
$keepaliveProvider.interval(10);
.config(['KeepaliveProvider', 'IdleProvider', 'TitleProvider',
(keepaliveProvider: angular.idle.IKeepAliveProvider, idleProvider: angular.idle.IIdleProvider,
titleProvider: angular.idle.ITitleProvider) => {
idleProvider.interrupt('mousemove keydown DOMMouseScroll mousewheel mousedown');
idleProvider.idle(5);
idleProvider.timeout(5);
idleProvider.keepalive(true)
idleProvider.autoResume(true);
const config: ng.IRequestConfig = {
url: "http://google.com",
method: "GET"
};
keepaliveProvider.http(config.url); // should accept string and ng.IRequestConfig
keepaliveProvider.http(config);
keepaliveProvider.interval(10);
titleProvider.enabled(true);
}])
.run(['$keepalive', '$idle', ($keepalive: ng.idle.IKeepAliveService, $idle: ng.idle.IIdleService) => {
$idle.watch();
if ($idle.running() || $idle.idling()) {
$idle.unwatch();
.run(['Keepalive', 'Idle', 'Title', (Keepalive: angular.idle.IKeepAliveService, Idle: angular.idle.IIdleService,
Title: angular.idle.ITitleService) => {
Idle.setTimeout(Idle.getTimeout());
Idle.setIdle(Idle.getIdle());
Idle.watch();
Idle.interrupt();
const expired: boolean = Idle.isExpired();
if (Idle.running() || Idle.idling()) {
Idle.unwatch();
}
$keepalive.start();
$keepalive.ping();
$keepalive.stop();
Keepalive.start();
Keepalive.ping();
Keepalive.stop();
Keepalive.setInterval(10);
Title.setEnabled(Title.isEnabled());
Title.original(Title.original());
Title.value(Title.value());
Title.store(false);
Title.store();
Title.restore();
Title.idleMessage(Title.idleMessage());
Title.timedOutMessage(Title.timedOutMessage());
Title.setAsIdle(120);
Title.setAsTimedOut();
}]);
+149 -20
View File
@@ -1,4 +1,4 @@
// Type definitions for ng-idle v0.3.5
// Type definitions for ng-idle v1.1.1
// Project: http://hackedbychinese.github.io/ng-idle/
// Definitions by: mthamil <https://github.com/mthamil>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -8,7 +8,99 @@
declare module angular.idle {
/**
* Used to configure the $keepalive service.
* Used to configure the Title service.
*/
interface ITitleProvider extends IServiceProvider {
/**
* Enables or disables the Title functionality.
*
* @param enabled Boolean, default is true.
*/
enabled(enabled: boolean): void;
}
interface ITitleService {
/**
* Allows the title functionality to be enabled or disabled on the fly.
*/
setEnabled(enabled: boolean): void;
/**
* Returns whether or not the title functionality has been enabled.
*/
isEnabled(): boolean;
/**
* Will store val as the "original" title of the document.
*
* Tracking the original title is important when restoring the title after displaying, for example, the idle warning message.
*/
original(val: string): void;
/**
* Returns the "original" title value that has been previously set.
*
* Tracking the original title is important when restoring the title after displaying, for example, the idle warning message.
*/
original(): string;
/**
* Changes the actual title of the document.
*/
value(val: string): void;
/**
* Returns the current document title.
*/
value(): string;
/**
* If overwrite is false or unspecified, updates the "original" title with the current document title
* if it has not already been stored. If overwrite is true, the current document title is stored regardless.
*/
store(overwrite?: boolean): void;
/**
* Sets the title to the original value (if it was stored or set previously).
*/
restore(): void;
/**
* Sets the text to use as the message displayed when the user is idle.
*/
idleMessage(val: string): void;
/**
* Gets the text to use as the message displayed when the user is idle.
*/
idleMessage(): string;
/**
* Sets the text to use as the message displayed when the user is timed out.
*/
timedOutMessage(val: string): void;
/**
* Gets the text to use as the message displayed when the user is timed out.
*/
timedOutMessage(): string;
/**
* Stores the original title if it hasn't been already, determines the number minutes, seconds,
* and total seconds from countdown, and displays the idleMessage with the aforementioned values interpolated.
*/
setAsIdle(countdown: number): void;
/**
* Stores the original title if it hasn't been already, and displays the timedOutMessage.
*/
setAsTimedOut(): void;
}
/**
* Used to configure the Keepalive service.
*/
interface IKeepAliveProvider extends IServiceProvider {
@@ -18,24 +110,24 @@ declare module angular.idle {
* You can specify a string, which it will assume to be a URL to a simple GET request.
* Otherwise, you can use the same options $http takes. However, cache will always be false.
*
* @param value May be string or object, default is null.
* @param value May be string or IRequestConfig, default is null.
*/
http(value: any): void;
http(value: string | IRequestConfig): void;
/**
* This specifies how often the keepalive event is triggered and the
* HTTP request is issued.
*
* @param seconds Integer, default is 5 minutes. Must be greater than 0.
* @param seconds Integer, default is 10 minutes. Must be greater than 0.
*/
interval(seconds: number): void;
}
/**
* $keepalive will use a timeout to periodically wake, broadcast a $keepalive event on the root scope,
* and optionally make an $http request. By default, the $idle service will stop and start $keepalive
* Keepalive will use a timeout to periodically wake, broadcast a Keepalive event on the root scope,
* and optionally make an $http request. By default, the Idle service will stop and start Keepalive
* when a user becomes idle or returns from idle, respectively. It is also started automatically when
* $idle.watch() is called. This can be disabled by configuring the $idleProvider.
* Idle.watch() is called. This can be disabled by configuring the IdleProvider.
*/
interface IKeepAliveService {
@@ -53,20 +145,25 @@ declare module angular.idle {
* Performs one ping only.
*/
ping(): void;
/**
* Changes the interval value at runtime.
* You will need to restart the pinging process by calling start() manually for the changes to be reflected.
*/
setInterval(seconds: number): void;
}
/**
* Used to configure the $idle service.
* Used to configure the Idle service.
*/
interface IIdleProvider extends IServiceProvider {
/**
* Specifies the DOM events the service will watch to reset the idle timeout.
* Multiple events should be separated by a space.
*
* @param events string, default 'mousemove keydown DOMMouseScroll mousewheel mousedown'
*/
activeOn(events: string): void;
interrupt(events: string): void;
/**
* The idle timeout duration in seconds. After this amount of time passes without the user
@@ -75,7 +172,7 @@ declare module angular.idle {
*
* @param seconds integer, default is 20min
*/
idleDuration(seconds: number): void;
idle(seconds: number): void;
/**
* The amount of time the user has to respond (in seconds) before they have been considered
@@ -83,19 +180,20 @@ declare module angular.idle {
*
* @param seconds integer, default is 30s
*/
warningDuration(seconds: number): void;
timeout(seconds: number): void;
/**
* When true, user activity will automatically interrupt the warning countdown and reset the
* idle state. If false, you will need to manually call watch() when you want to start
* watching for idleness again.
* When true or idle, user activity will automatically interrupt the warning countdown
* and reset the idle state. If false or off, you will need to manually call watch()
* when you want to start watching for idleness again. If notIdle, user activity will
* only automatically interrupt if the user is not yet idle.
*
* @param enabled boolean, default is true
* @param enabled boolean or string, possible values: off/false, idle/true, or notIdle
*/
autoResume(enabled: boolean): void;
autoResume(enabled: boolean | string): void;
/**
* When true, the $keepalive service is automatically stopped and started as needed.
* When true, the Keepalive service is automatically stopped and started as needed.
*
* @param enabled boolean, default is true
*/
@@ -103,13 +201,39 @@ declare module angular.idle {
}
/**
* $idle, once watch() is called, will start a timeout which if expires, will enter a warning state
* Idle, once watch() is called, will start a timeout which if expires, will enter a warning state
* countdown. Once the countdown reaches zero, idle will broadcast a timeout event indicating the
* user has timed out (where your app should log them out or whatever you like). If the user performs
* an action that triggers a watched DOM event that bubbles up to document.body, this will reset the
* idle/warning state and start the process over again.
*/
interface IIdleService {
/**
* Gets the current idle value
*/
getIdle(): number;
/**
* Gets the current timeout value
*/
getTimeout(): number;
/**
* Updates the idle value (see IdleProvider.idle()) and
* restarts the watch if its running.
*/
setIdle(idle: number): void;
/**
* Updates the timeout value (see IdleProvider.timeout()) and
* restarts the watch if its running.
*/
setTimeout(timeout: number): void;
/**
* Whether user has timed out (meaning idleDuration + timeout has passed without any activity)
*/
isExpired(): boolean;
/**
* Whether or not the watch() has been called and it is watching for idleness.
@@ -130,5 +254,10 @@ declare module angular.idle {
* Stops watching for idleness, and resets the idle/warning state.
*/
unwatch(): void;
/**
* Manually trigger the idle interrupt that normally occurs during user activity.
*/
interrupt(): any;
}
}
+10
View File
@@ -51,6 +51,16 @@ declare module angular.meteor {
* @return This method returns this, which the the reactive context, in order to provide the ability to chain the logic.
*/
helpers(definitions : { [helperName : string] : () => Mongo.Cursor<any> }): IScope;
/**
* This method is a wrapper of Tracker.autorun and shares exactly the same API.
* The autorun method is part of the ReactiveContext, and available on every context and $scope.
* The argument of this method is a callback, which will be called each time Autorun will be used.
* The Autorun will stop automatically when when it's context ($scope) is destroyed.
*
* @param runFunc - The function to run. It receives one argument: the Computation object that will be returned.
*/
autorun(runFunc : () => void) : Tracker.Computation;
}
/**
+20 -20
View File
@@ -10,27 +10,27 @@ declare module "angular-toastr" {
export = _;
}
interface IToastBaseConfig {
allowHtml?: boolean;
closeButton?: boolean;
closeHtml?: string;
extendedTimeOut?: number;
messageClass?: string;
onHidden?: Function;
onShown?: Function;
onTap?: Function;
progressBar?: boolean;
tapToDismiss?: boolean;
templates?: {
toast?: string;
progressbar?: string;
};
timeOut?: number;
titleClass?: string;
toastClass?: string;
}
declare module angular.toastr {
interface IToastBaseConfig {
allowHtml?: boolean;
closeButton?: boolean;
closeHtml?: string;
extendedTimeOut?: number;
messageClass?: string;
onHidden?: Function;
onShown?: Function;
onTap?: Function;
progressBar?: boolean;
tapToDismiss?: boolean;
templates?: {
toast?: string;
progressbar?: string;
};
timeOut?: number;
titleClass?: string;
toastClass?: string;
}
interface IToastContainerConfig {
autoDismiss?: boolean;
containerId?: string;
@@ -26,6 +26,7 @@ app.config(($translateProvider: angular.translate.ITranslateProvider) => {
$translateProvider.preferredLanguage('en');
$translateProvider.useLoader('customLoader');
$translateProvider.forceAsyncReload(true);
});
interface Scope extends ng.IScope {
+1
View File
@@ -87,6 +87,7 @@ declare module angular.translate {
fallbackLanguage(): ITranslateProvider;
fallbackLanguage(language: string): ITranslateProvider;
fallbackLanguage(languages: string[]): ITranslateProvider;
forceAsyncReload(value: boolean): ITranslateProvider;
use(): string;
use(key: string): ITranslateProvider;
storageKey(): string;
+1
View File
@@ -257,6 +257,7 @@ declare module angular.ui {
transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise<any>;
transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise<any>;
includes(state: string, params?: {}): boolean;
includes(state: string, params?: {}, options?:any): boolean;
is(state:string, params?: {}): boolean;
is(state: IState, params?: {}): boolean;
href(state: IState, params?: {}, options?: IHrefOptions): string;
+3
View File
@@ -36,6 +36,9 @@ declare module angular {
* ```
*/
interface Instruction {
component: ComponentInstruction;
child: Instruction;
auxInstruction: {[key: string]: Instruction};
urlPath(): string;
+1
View File
@@ -1876,6 +1876,7 @@ declare module angular {
provider(name: string, provider: IServiceProvider): IServiceProvider;
provider(name: string, serviceProviderConstructor: Function): IServiceProvider;
service(name: string, constructor: Function): IServiceProvider;
service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider;
value(name: string, value: any): IServiceProvider;
}
+1 -1
View File
@@ -50,7 +50,7 @@ declare module "any-db" {
/**
* Result rows
*/
rows: Object[];
rows: any[];
/**
* Result field descriptions
*/
+1 -2
View File
@@ -4,7 +4,6 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../when/when.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
declare module autobahn {
@@ -194,7 +193,7 @@ declare module autobahn {
type: string;
}
type DeferFactory = () => JQueryPromise<any>;
type DeferFactory = () => When.Promise<any>;
type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise<string>;
+112 -9
View File
@@ -56,6 +56,7 @@ declare module "aws-sdk" {
directconnect?: any;
dynamodb?: any;
ec2?: any;
ecs?: any;
elasticache?: any;
elasticbeanstalk?: any;
elastictranscoder?: any;
@@ -147,7 +148,18 @@ declare module "aws-sdk" {
export class S3 {
constructor(options?: any);
public client: s3.Client;
putObject(params: s3.PutObjectRequest, callback: (err: any, data: any) => void): void;
getObject(params: s3.GetObjectRequest, callback: (err: any, data: any) => void): void;
}
export class ECS {
constructor(options?: any);
createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void;
describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void;
describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void;
registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void;
updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void;
}
export class DynamoDB {
@@ -1042,14 +1054,7 @@ declare module "aws-sdk" {
}
export module s3 {
export interface Client {
config: ClientConfig;
putObject(params: PutObjectRequest, callback: (err: any, data: any) => void): void;
getObject(params: GetObjectRequest, callback: (err: any, data: any) => void): void;
}
export interface PutObjectRequest {
ACL?: string;
Body?: any;
@@ -1091,4 +1096,102 @@ declare module "aws-sdk" {
}
}
export module ecs {
export interface CreateServicesParams {
desiredCount: number;
serviceName: string;
taskDefinition: string;
clientToken?: string;
cluster?: string;
deploymentConfiguration?: {
maximumPercent?: number;
minimumHealthyPercent?: number;
};
loadBalancers?: {
containerName?: string;
containerPort?: number;
loadBalancerName?: string;
}[];
role?: string;
}
export interface DescribeServicesParams {
services: string[];
cluster: string;
}
export interface DescribeTaskDefinitionParams {
taskDefinition: string;
}
export interface RegisterTaskDefinitionParams {
containerDefinitions: {
command?: string[],
cpu?: number,
disableNetworking?: boolean,
dnsSearchDomains?: string[],
dnsServers?: string[],
dockerLabels?: any,
dockerSecurityOptions?: string[],
entryPoint?: string[],
environment?: any[],
essential?: boolean,
extraHosts?: {
hostName: string,
ipAddress: string
}[];
hostname?: string,
image?: string,
links?: string[],
logConfiguration?: {
logDriver: string,
options: any
}[],
memory?: number,
mountPoints?: {
containerPath: string,
readOnly: boolean,
sourceVolume: string
}[];
name?: string,
portMappings?: {
containerPort?: number,
hostPort?: number,
protocol: string
}[];
privileged?: boolean,
readonlyRootFilesystem?: boolean,
ulimits?: {
hardLimit: number,
name: string,
softLimit: number
}[];
user?: string,
volumesFrom?: {
readOnly?: boolean,
sourceContainer?: string
}[],
workingDirectory?: string
}[];
family: string;
volumes?: {
host: {
sourcePath: string
},
name: string
}[];
}
export interface UpdateServiceParams {
service: string;
cluster?: string;
deploymentConfiguration?: {
maximumPercent: number;
minimumHealthyPercent: number;
};
desiredCount?: number;
taskDefinition: string;
}
}
}
+46 -3
View File
@@ -8,21 +8,64 @@ interface Repository {
name: string;
}
interface Issue {
id: number;
title: string;
}
axios.interceptors.request.use<any>(config => {
console.log("Method:" + config.method + " Url:" +config.url);
return config;
});
axios.interceptors.response.use<any>(config => {
console.log("Status:" + config.status);
return config;
});
axios.get<Repository>("https://api.github.com/repos/mzabriskie/axios")
.then(r => console.log(r.config.method));
axios<Repository>({
var getRepoDetails = axios<Repository>({
url: "https://api.github.com/repos/mzabriskie/axios",
method: HttpMethod[HttpMethod.GET],
headers: {},
}).then(r => console.log("ID:" + r.data.id + " Name: " + r.data.name));
}).then(r => {
console.log("ID:" + r.data.id + " Name: " + r.data.name);
return r;
});
axios.post("http://example.com/", {}, {
transformRequest: (data: any) => data
});
axios.post("http://example.com/", {}, {
axios.post("http://example.com/", {
headers: {'X-Custom-Header': 'foobar'}
}, {
transformRequest: [
(data: any) => data
]
});
var getRepoIssue = axios.get<Issue>("https://api.github.com/repos/mzabriskie/axios/issues/1");
var axiosInstance = axios.create({
baseURL: "https://api.github.com/repos/mzabriskie/axios/",
timeout: 1000
});
axiosInstance.request({url: "issues/1"});
axios.all<Repository, Repository>([getRepoDetails, getRepoDetails]).then(([repo1, repo2]) => {
var sumIds = repo1.data.id + repo2.data.id;
console.log("Sum ID:" + sumIds);
return sumIds;
});
var repoSum = (repo1: Axios.AxiosXHR<Repository>, repo2: Axios.AxiosXHR<Repository>) => {
var sumIds = repo1.data.id + repo2.data.id;
console.log("Sum ID:" + sumIds);
return sumIds;
};
axios.all<Repository, Repository>([getRepoDetails, getRepoDetails]).then(axios.spread(repoSum));
+246 -132
View File
@@ -1,162 +1,276 @@
// Type definitions for axios 0.5.2
// Type definitions for axios 0.8.1
// Project: https://github.com/mzabriskie/axios
// Definitions by: Marcel Buesing <https://github.com/marcelbuesing>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../es6-promise/es6-promise.d.ts"/>
declare module Axios {
/**
* <T> - request body data type
*/
interface AxiosXHRConfigBase<T> {
interface IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IThenable<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IThenable<U>;
}
interface IPromise<R> extends IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
}
/**
* Change the request data before it is sent to the server.
* This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
* The last function in the array must return a string or an ArrayBuffer
* HTTP Basic auth details
*/
transformRequest?: (<U>(data:T) => U)|[<U>(data:T) => U];
interface AxiosHttpBasicAuth {
username: string;
password: string;
}
/**
* change the response data to be made before it is passed to then/catch
* Common axios XHR config interface
* <T> - request body data type
*/
transformResponse?: <U>(data:T) => U;
interface AxiosXHRConfigBase<T> {
/**
* will be prepended to `url` unless `url` is absolute.
* It can be convenient to set `baseURL` for an instance
* of axios to pass relative URLs to methods of that instance.
*/
baseURL?: string;
/**
* custom headers to be sent
*/
headers?: Object;
/**
* URL parameters to be sent with the request
*/
params?: Object;
/**
* optional function in charge of serializing `params`
* (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
*/
paramsSerializer?: (params: Object) => string;
/**
* specifies the number of milliseconds before the request times out.
* If the request takes longer than `timeout`, the request will be aborted.
*/
timeout?: number;
/**
* indicates whether or not cross-site Access-Control requests
* should be made using credentials
*/
withCredentials?: boolean;
/**
* indicates that HTTP Basic auth should be used, and supplies
* credentials. This will set an `Authorization` header,
* overwriting any existing `Authorization` custom headers you have
* set using `headers`.
*/
auth?: AxiosHttpBasicAuth;
/**
* indicates the type of data that the server will respond with
* options are 'arraybuffer', 'blob', 'document', 'json', 'text'
*/
responseType?: string;
/**
* name of the cookie to use as a value for xsrf token
*/
xsrfCookieName?: string;
/**
* name of the http header that carries the xsrf token value
*/
xsrfHeaderName?: string;
/**
* Change the request data before it is sent to the server.
* This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
* The last function in the array must return a string or an ArrayBuffer
*/
transformRequest?: (<U>(data: T) => U) | [<U>(data: T) => U];
/**
* change the response data to be made before it is passed to then/catch
*/
transformResponse?: <U>(data: T) => U;
}
/**
* custom headers to be sent
* <T> - request body data type
*/
headers?: Object;
interface AxiosXHRConfig<T> extends AxiosXHRConfigBase<T> {
/**
* server URL that will be used for the request, options are:
* GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH
*/
url: string;
/**
* request method to be used when making the request
*/
method?: string;
/**
* data to be sent as the request body
* Only applicable for request methods 'PUT', 'POST', and 'PATCH'
* When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
*/
data?: T;
}
/**
* URL parameters to be sent with the request
* <T> - expected response type,
* <U> - request body data type
*/
params?: Object;
interface AxiosXHR<T> {
/**
* Response that was provided by the server
*/
data: T;
/**
* HTTP status code from the server response
*/
status: number;
/**
* HTTP status message from the server response
*/
statusText: string;
/**
* headers that the server responded with
*/
headers: Object;
/**
* config that was provided to `axios` for the request
*/
config: AxiosXHRConfig<T>;
}
interface Interceptor {
/**
* intercept request before it is sent
*/
request: RequestInterceptor;
/**
* intercept response of request when it is received.
*/
response: ResponseInterceptor
}
interface RequestInterceptor {
/**
* <U> - request body data type
*/
use<U>(fn: (config: AxiosXHRConfig<U>) => AxiosXHRConfig<U>): void;
}
interface ResponseInterceptor {
/**
* <T> - expected response type
*/
use<T>(fn: (config: AxiosXHR<T>) => AxiosXHR<T>): void;
}
/**
* indicates whether or not cross-site Access-Control requests
* should be made using credentials
* <T> - expected response type,
* <U> - request body data type
*/
withCredentials?: boolean;
interface AxiosInstance {
/**
* Send request as configured
*/
<T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* Send request as configured
*/
new <T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* Send request as configured
*/
request<T>(config: AxiosXHRConfig<T>): IPromise<AxiosXHR<T>>;
/**
* intercept requests or responses before they are handled by then or catch
*/
interceptors: Interceptor;
/**
* equivalent to `Promise.all`
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>, T9 | IPromise<AxiosXHR<T9>>, T10 | IPromise<AxiosXHR<T10>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>, AxiosXHR<T9>, AxiosXHR<T10>]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>, T9 | IPromise<AxiosXHR<T9>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>, AxiosXHR<T9>]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>, T8 | IPromise<AxiosXHR<T8>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>, AxiosXHR<T8>]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>, T7 | IPromise<AxiosXHR<T7>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>, AxiosXHR<T7>]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>, T6 | IPromise<AxiosXHR<T6>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>, AxiosXHR<T6>]>;
all<T1, T2, T3, T4, T5>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>, T5 | IPromise<AxiosXHR<T5>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>, AxiosXHR<T5>]>;
all<T1, T2, T3, T4>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>, T4 | IPromise<AxiosXHR<T4>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>, AxiosXHR<T4>]>;
all<T1, T2, T3>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>, T3 | IPromise<AxiosXHR<T3>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>, AxiosXHR<T3>]>;
all<T1, T2>(values: [T1 | IPromise<AxiosXHR<T1>>, T2 | IPromise<AxiosXHR<T2>>]): IPromise<[AxiosXHR<T1>, AxiosXHR<T2>]>;
/**
* spread array parameter to `fn`.
* note: alternative to `spread`, destructuring assignment.
*/
spread<T1, T2, U>(fn: (t1: T1, t2: T2) => U): (arr: ([T1, T2])) => U;
/**
* convenience alias, method = GET
*/
get<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = DELETE
*/
delete<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = HEAD
*/
head<T>(url: string, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = POST
*/
post<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = PUT
*/
put<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
/**
* convenience alias, method = PATCH
*/
patch<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): IPromise<AxiosXHR<T>>;
}
/**
* indicates the type of data that the server will respond with
* options are 'arraybuffer', 'blob', 'document', 'json', 'text'
* <T> - expected response type,
*/
responseType?: string;
/**
* name of the cookie to use as a value for xsrf token
*/
xsrfCookieName?: string;
/**
* name of the http header that carries the xsrf token value
*/
xsrfHeaderName?: string;
}
/**
* <T> - request body data type
*/
interface AxiosXHRConfig<T> extends AxiosXHRConfigBase<T> {
/**
* server URL that will be used for the request, options are:
* GET, PUT, POST, DELETE, CONNECT, HEAD, OPTIONS, TRACE, PATCH
*/
url: string;
/**
* request method to be used when making the request
*/
method?: string;
/**
* data to be sent as the request body
* Only applicable for request methods 'PUT', 'POST', and 'PATCH'
* When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
*/
data?: T;
}
/**
* <T> - expected response type,
* <U> - request body data type
*/
interface AxiosXHR<T> {
/**
* Response that was provided by the server
*/
data: T;
/**
* HTTP status code from the server response
*/
status: number;
/**
* HTTP status message from the server response
*/
statusText: string;
/**
* headers that the server responded with
*/
headers: Object;
/**
* config that was provided to `axios` for the request
*/
config: AxiosXHRConfig<T>;
}
/**
* <T> - expected response type,
* <U> - request body data type
*/
interface AxiosStatic {
<T>(config: AxiosXHRConfig<T>): Promise<AxiosXHR<T>>;
new <T>(config: AxiosXHRConfig<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = GET
*/
get<T>(url: string, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = DELETE
*/
delete<T>(url: string, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = HEAD
*/
head<T>(url: string, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = POST
*/
post<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = PUT
*/
put<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
/**
* convenience alias, method = PATCH
*/
patch<T>(url: string, data?: any, config?: AxiosXHRConfigBase<T>): Promise<AxiosXHR<T>>;
}
interface AxiosStatic extends AxiosInstance {
/**
* create a new instance of axios with a custom config
*/
create<T>(config: AxiosXHRConfigBase<T>): AxiosInstance;
}
}
declare var axios: Axios.AxiosStatic;
declare module "axios" {
export = axios;
export = axios;
}
@@ -0,0 +1,87 @@
/// <reference path="azure-mobile-apps.d.ts" />
import express = require('express');
import mobileApps = require('azure-mobile-apps');
import logger = require('azure-mobile-apps/src/logger');
import queries = require('azure-mobile-apps/src/query');
var app = express(),
mobileApp = mobileApps();
// various configuration permutations
mobileApps({
debug: true,
data: {
provider: 'mssql',
server: '',
user: '',
database: '',
password: ''
}
});
mobileApps({
data: {
provider: 'memory'
}
})
// it would be nice to integrate with winston
mobileApps({ logging: { level: 'silly', transports: [{}] } })
// various custom middleware syntaxes
mobileApp.use(function (req: any, res: any, next: any) { next(); });
mobileApp.use([function () {}, function () {}]);
mobileApp.use(function () {}, function () {});
mobileApp.use(function () {}).use(function () {});
// basic syntax for tables and api
mobileApp.tables.add('todoitem');
mobileApp.tables.add('todoitem', { authorize: true });
mobileApp.tables.add('todoitem', mobileApps.table());
mobileApp.tables.import('tables');
mobileApp.api.add('api', { authorize: true, get: function () {}, delete: function () {} });
mobileApp.api.import('api');
// Express.Table, instantiated from the mobile app
var table = mobileApp.table()
table.use(function (req: Express.Request, res: Express.Response, next: any) {
next(new Error());
});
table.use([function () {}, function () {}]);
table.read(function (context: Azure.MobileApps.Context) {
context.query.where({ p1: 'test' });
return context.execute()
.then(function (result: any) {
return result;
})
.catch(function (error: any) { })
.then(function () {});
});
table.insert(function (context: Azure.MobileApps.Context) {
context.query.id = 'anotherId';
context.query.single = true;
context.item.userId = context.user.id;
context.push.send('tag', {}, function (error, result) {});
context.push.gcm.send('tag', {}, function (error, result) {});
context.push.apns.send('tag', { payload: { } }, function (error, result) {});
context.push.wns.sendToastText01('tag', '', { headers: { } }, function (error, result) {});
});
table.read.use(function () {});
table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
// Express.Table, instantiated from the static require('azure-mobile-apps').table()
// This is going to be interesting if we ever support more than one provider
var table2 = mobileApps.table();
table2.read(function (context: Azure.MobileApps.Context) {})
// Logger
logger.silly('test', 'message');
logger.error('Something happened', new Error());
mobileApps.logger.debug('a debug message')
// Query
queries.create('table').where({ x: 10 }).select('col1,col2');
mobileApps.query.create('table');
+279
View File
@@ -0,0 +1,279 @@
// Type definitions for azure-mobile-apps v2.0.0-beta3
// Project: https://github.com/Azure/azure-mobile-apps-node/
// Definitions by: Microsoft Azure <https://github.com/Azure/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
/// <reference path="../azure-sb/azure-sb.d.ts" />
declare module "azure-mobile-apps" {
interface AzureMobileApps {
(configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp;
table(): Azure.MobileApps.Platforms.Express.Table;
logger: Azure.MobileApps.Logger;
query: Azure.MobileApps.Query;
}
var out: AzureMobileApps;
export = out;
}
declare module "azure-mobile-apps/src/logger" {
var logger: Azure.MobileApps.Logger;
export = logger;
}
declare module "azure-mobile-apps/src/query" {
var query: Azure.MobileApps.Query;
export = query;
}
declare module Azure.MobileApps {
// the additional Platforms namespace is required to avoid collisions with the main Express namespace
export module Platforms {
export module Express {
interface MobileApp {
configuration: Configuration;
tables: Tables;
table(): Table;
api: Api;
use(...middleware: Middleware[]): MobileApp;
use(middleware: Middleware[]): MobileApp;
}
interface Api {
add(name: string, definition: ApiDefinition): void;
import(fileOrFolder: string): void;
}
interface Table {
authorize?: boolean;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name: string;
columns?: any;
schema: string;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
read: TableOperation;
update: TableOperation;
insert: TableOperation;
delete: TableOperation;
undelete: TableOperation;
}
interface TableOperation {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
}
interface Tables {
configuration: Configuration;
add(name: string, definition?: Table | TableDefinition): void;
import(fileOrFolder: string): void;
initialize(): Thenable<any>;
}
}
}
export module Data {
interface Table {
read(query: QueryJs): Thenable<any[]>;
update(item: any, query: QueryJs): Thenable<any>;
insert(item: any): Thenable<any>;
delete(query: QueryJs, version: string): Thenable<any>;
undelete(query: QueryJs, version: string): Thenable<any>;
truncate(): Thenable<void>;
initialize(): Thenable<void>;
schema(): Thenable<Column[]>;
}
interface Column {
name: string;
type: string;
}
}
// auth
interface User {
id: string;
claims: any[];
token: string;
getIdentity(provider: string): Thenable<any>;
}
interface Auth {
validate(token: string): Thenable<User>;
decode(token: string): User;
sign(payload: any): string;
}
// configuration
interface Configuration {
platform?: string;
basePath?: string;
configFile?: string;
promiseConstructor?: (resolve: (result: any) => void, reject: (error: any) => void) => Thenable<any>;
apiRootPath?: string;
tableRootPath?: string;
notificationRootPath?: string;
swaggerPath?: string;
authStubRoute?: string;
debug?: boolean;
version?: string;
apiVersion?: string;
homePage?: boolean;
swagger?: boolean;
maxTop?: number;
pageSize?: number;
logging?: Configuration.Logging;
data?: Configuration.Data;
auth?: Configuration.Auth;
cors?: Configuration.Cors;
notifications?: Configuration.Notifications;
}
export module Configuration {
// it would be nice to have the config for various providers in separate interfaces,
// but this is the simplest solution to support variations of the current setup
interface Data {
provider: string;
user?: string;
password?: string;
server?: string;
port?: number;
database?: string;
connectionTimeout?: string;
options?: { encrypt: boolean };
schema?: string;
dynamicSchema?: boolean;
}
interface Auth {
secret: string;
validateTokens?: boolean;
}
interface Logging {
level?: string;
transports?: LoggingTransport[];
}
interface LoggingTransport { }
interface Cors {
maxAge?: number;
origins: string[];
}
interface Notifications {
hubName: string;
connectionString?: string;
endpoint?: string;
sharedAccessKeyName?: string;
sharedAccessKeyValue?: string;
}
}
// query
interface Query {
create(tableName: string): QueryJs;
fromRequest(req: Express.Request): QueryJs;
toOData(query: QueryJs): OData;
}
interface QueryJs {
includeTotalCount?: boolean;
orderBy(properties: string): QueryJs;
orderByDescending(properties: string): QueryJs;
select(properties: string): QueryJs;
skip(count: number): QueryJs;
take(count: number): QueryJs;
where(filter: any): QueryJs;
// these are properties added by the SDK
id?: string | number;
single?: boolean;
}
interface OData {
table: string;
filters?: string;
ordering?: string;
orderClauses?: string;
skip?: number;
take?: number;
selections?: string;
includeTotalCount?: boolean;
}
// general
var nh: Azure.ServiceBus.NotificationHubService;
interface Context {
query: QueryJs;
id: string | number;
item: any;
req: Express.Request;
res: Express.Response;
data: (table: TableDefinition) => Data.Table;
tables: (tableName: string) => Data.Table;
user: User;
push: typeof nh;
logger: Logger;
execute(): Thenable<any>;
}
interface TableDefinition {
authorize?: boolean;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name?: string;
columns?: any;
schema?: string;
}
interface ApiDefinition {
authorize?: boolean;
get?: Middleware | Middleware[];
post?: Middleware | Middleware[];
patch?: Middleware | Middleware[];
put?: Middleware | Middleware[];
delete?: Middleware | Middleware[];
}
interface Thenable<R> {
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
catch<U>(onRejected?: (error: any) => void): Thenable<U>;
}
interface Logger {
log(level: string, ...message: any[]): void;
silly(...message: any[]): void;
debug(...message: any[]): void;
verbose(...message: any[]): void;
info(...message: any[]): void;
warn(...message: any[]): void;
error(...message: any[]): void;
}
interface Middleware {
(req: Express.Request, res: Express.Response, next: NextMiddleware): void;
}
interface NextMiddleware {
(error?: any): void;
}
}
// additions to the Express modules
declare module Express {
interface Request {
azureMobile: Azure.MobileApps.Context
}
interface Response {
results?: any;
}
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="./azure-sb.d.ts" />
var nh = new Azure.ServiceBus.NotificationHubService();
nh.send('tag', '<payload></payload>', function (error, result) {});
nh.send('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
nh.apns.send('tag', { payload: { } }, function (error, result) {});
nh.apns.send(['tag'], { payload: { } }, function (error, result) {});
nh.gcm.send('tag', { }, function (error, result) {});
nh.gcm.send(['tag'], { }, function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send(['tag'], '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', { headers: {} }, function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01(['tag'], '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
+173
View File
@@ -0,0 +1,173 @@
// Type definitions for azure-sb
// Project: https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus
// Definitions by: Microsoft Azure <https://github.com/Azure/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Azure.ServiceBus {
interface Callback {
(error: any, response: any): void;
}
interface NotificationHubRegistration {
RegistrationId: string;
ChannelUri?: string;
DeviceToken?: string;
gcmRegistrationId?: string;
Tags?: string;
BodyTemplate?: any;
WnsHeaders?: any;
MpnsHeaders?: any;
Expiry?: Date;
}
export class NotificationHubService {
new(hubName: string, endpointOrConnectionString: string, sharedAccessKeyName?: string, sharedAccessKeyValue?: string): NotificationHubService;
hubName: string;
wns: Wns.Service;
apns: Apns.Service;
gcm: Gcm.Service;
mpns: Mpns.Service;
send(tags: string, payload: Object | string, optionsOrCallback?: { headers: Object } | Callback, callback?: Callback): void;
createOrUpdateInstallation(installation: string, options: any, callback?: Callback): void;
patchInstallation(installationId: string, partialUpdateOperations: any[], options: any, callback?: Callback): void;
deleteInstallation(installationId: string, options: any, callback?: Callback): void;
getInstallation(installationId: string, options: any, callback?: Callback): void;
/*
// old school?
createRegistrationId(callback?: Callback): void;
getRegistration(registrationId: string, options: any, callback?: Callback): void;
deleteRegistration(registrationId: string, options?: { etag: any }, callback?: Callback): void;
updateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
createOrUpdateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
listRegistrations(options?: { top: number, skip: number }, callback?: Callback): void;
listRegistrationsByTag(tag: string, options?: { top: number, skip: number }, callback?: Callback): void;
*/
}
export module Apns {
interface Payload {
expiry?: Date;
aps?: Object;
badge?: number;
alert?: string;
sound?: string;
payload: Object;
}
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: Apns.Payload, callback?: Callback): void;
createNativeRegistration(token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByToken(token: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
}
}
export module Gcm {
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: any, callback?: Callback): void;
createNativeRegistration(gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
}
}
export module Mpns { interface Service { } }
export module Wns {
interface Payload {
text1?: string;
text2?: string;
text3?: string;
text4?: string;
image1src?: string;
image1alt?: string;
image2src?: string;
image2alt?: string;
image3src?: string;
image3alt?: string;
image4src?: string;
image4alt?: string;
lang?: string;
type?: string;
}
interface Options {
headers: Object;
}
interface Service {
new(service: NotificationHubService): Service;
sendTileSquareBlock(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText07(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText08(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText09(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText10(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText11(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageCollection(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// badges = ['none','activity','alert','available','away','busy','newMessage','paused','playing','unavailable','error', 'attention']
sendBadge(tags: string | string[], value: string | number, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendRaw(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// types = ['wns/toast', 'wns/badge', 'wns/tile', 'wns/raw']
send(tags: string | string[], payload: string, type: string, optionsOrCallback?: Options | Callback, callback?: Callback): void;
createNativeRegistration(channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
listRegistrationsByChannel(channel: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
}
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../lodash/lodash.d.ts" />
/// <reference path='../lodash/lodash-3.10.d.ts' />
/// <reference path="./backbone-global.d.ts" />
function test_events() {
+14
View File
@@ -0,0 +1,14 @@
/// <reference path="./base-x.d.ts" />
import * as basex from 'base-x';
let bs16: BaseX.BaseConverter = basex('0123456789ABCDEF');
{
let encoded: string;
encoded = bs16.encode([255]);
encoded = bs16.encode({0: 255, length: 1});
}
let decoded: number[] = bs16.decode('FF');
+28
View File
@@ -0,0 +1,28 @@
// Type definitions for base-x v1.0.1
// Project: https://github.com/cryptocoinjs/base-x
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare namespace BaseX {
interface EncodeBuffer {
[index: number]: number;
length: number;
}
interface BaseConverter {
encode: (buffer: EncodeBuffer) => string;
decode: (string: string) => number[];
}
interface Base {
(ALPHABET: string): BaseX.BaseConverter
}
}
declare module "base-x" {
namespace base {}
let base: BaseX.Base;
export = base;
}
+2 -2
View File
@@ -754,8 +754,8 @@ Promise.longStackTraces();
//TODO enable delay
fooProm = Promise.delay(fooThen, num);
fooProm = Promise.delay(foo, num);
fooProm = Promise.delay(num, fooThen);
fooProm = Promise.delay(num, foo);
voidProm = Promise.delay(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+2 -2
View File
@@ -106,8 +106,8 @@ interface PromiseConstructor {
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
// TODO enable more overloads
delay<T>(value: PromiseLike<T>, ms: number): Promise<T>;
delay<T>(value: T, ms: number): Promise<T>;
delay<T>(ms: number, value: PromiseLike<T>): Promise<T>;
delay<T>(ms: number, value: T): Promise<T>;
delay(ms: number): Promise<void>;
/**
+4 -4
View File
@@ -110,7 +110,7 @@ declare module "body-parser" {
defaultCharset?: string;
}): express.RequestHandler;
export function urlencoded(options?: {
export function urlencoded(options: {
/**
* if deflated bodies will be inflated. (default: true)
*/
@@ -128,11 +128,11 @@ declare module "body-parser" {
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* parse extended syntax with the qs module. (default: true)
* parse extended syntax with the qs module.
*/
extended?: boolean;
extended: boolean;
}): express.RequestHandler;
}
export = bodyParser;
}
}
+2 -1
View File
@@ -4,7 +4,7 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../lodash/lodash.d.ts" />
/// <reference path='../lodash/lodash-3.10.d.ts' />
/// <reference path="../knex/knex.d.ts" />
declare module 'bookshelf' {
@@ -18,6 +18,7 @@ declare module 'bookshelf' {
Model : typeof Bookshelf.Model;
Collection : typeof Bookshelf.Collection;
plugin(name: string) : Bookshelf;
transaction<T>(callback : (transaction : knex.Transaction) => T) : Promise<T>;
}
@@ -56,6 +56,7 @@ declare module BootstrapV3DatetimePicker {
inline?: boolean;
toolbarPlacement?: string;
showClear?: boolean;
ignoreReadonly?: boolean;
}
interface Datetimepicker {
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="./brorand.d.ts" />
import * as brorand from 'brorand';
{
let result: Buffer|Uint8Array = brorand(42);
}
{
let Rand = new brorand.Rand({getByte: () => 255});
let rand: {getByte: () => number} = Rand.rand;
let result: Buffer|Uint8Array = Rand.generate(42);
}
+30
View File
@@ -0,0 +1,30 @@
// Type definitions for Brorand v1.0.5
// Project: https://github.com/indutny/brorand
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "brorand" {
type rand = {getByte: () => number};
interface RandStatic {
new (rand: rand): RandInstance;
}
interface RandInstance {
rand: rand;
generate(len: number): Buffer|Uint8Array;
}
interface BrorandStatic {
(len: number): Buffer|Uint8Array;
Rand: RandStatic;
}
namespace Brorand {}
let Brorand: BrorandStatic;
export = Brorand;
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./bs58.d.ts" />
import * as bs58 from 'bs58';
{
let encoded: string;
encoded = bs58.encode([255]);
encoded = bs58.encode({0: 255, length: 1});
}
let decoded: number[] = bs58.decode('5Q');
+14
View File
@@ -0,0 +1,14 @@
// Type definitions for bs58 3.0.0
// Project: https://github.com/cryptocoinjs/bs58
// Definitions by: Ilya Mochalov <https://github.com/chrootsu>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../base-x/base-x.d.ts" />
declare module "bs58" {
namespace base58 {}
let base58: BaseX.BaseConverter;
export = base58;
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="bson.d.ts"/>
import * as bson from 'bson';
let BSON = new bson.BSONPure.BSON();
let Long = bson.BSONPure.Long;
let doc = {long: Long.fromNumber(100)}
// Serialize a document
let data = BSON.serialize(doc, false, true, false);
console.log("data:", data);
// Deserialize the resulting Buffer
let doc_2 = BSON.deserialize(data);
console.log("doc_2:", doc_2);
BSON = new bson.BSONNative.BSON();
data = BSON.serialize(doc);
doc_2 = BSON.deserialize(data);
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for bson 0.4.21
// Project: https://github.com/mongodb/js-bson
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module 'bson' {
module bson {
export module BSONPure {
export interface DeserializeOptions {
/** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. */
evalFunctions?: boolean;
/** {Boolean, default:false}, cache evaluated functions for reuse. */
cacheFunctions?: boolean;
/** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. */
cacheFunctionsCrc32?: boolean;
/** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object. */
promoteBuffers?: boolean;
}
export class BSON {
/**
* @param {Object} object the Javascript object to serialize.
* @param {Boolean} checkKeys the serializer will check if keys are valid.
* @param {Boolean} asBuffer return the serialized object as a Buffer object (ignore).
* @param {Boolean} serializeFunctions serialize the javascript functions (default:false)
* @return {Buffer} returns a TypedArray or Array depending on what your browser supports
*/
serialize(object: any, checkKeys?: boolean, asBuffer?: boolean, serializeFunctions?: boolean): Buffer;
deserialize(buffer: Buffer, options?: DeserializeOptions, isArray?: boolean): any;
}
export interface Binary {}
export interface BinaryStatic {
SUBTYPE_DEFAULT: number;
SUBTYPE_FUNCTION: number;
SUBTYPE_BYTE_ARRAY: number;
SUBTYPE_UUID_OLD: number;
SUBTYPE_UUID: number;
SUBTYPE_MD5: number;
SUBTYPE_USER_DEFINED: number;
new (buffer: Buffer, subType?: number): Binary;
}
export let Binary: BinaryStatic;
export interface Code {}
export interface CodeStatic {
new (code: string | Function, scope?: any): Code;
}
export let Code: CodeStatic;
export interface DBRef {}
export interface DBRefStatic {
new (namespace: string, oid: ObjectID, db?: string): DBRef;
}
export let DBRef: DBRefStatic;
export interface Double {}
export interface DoubleStatic {
new (value: number): Double;
}
export let Double: DoubleStatic;
export interface Long {}
export interface LongStatic {
new (low: number, high: number): Long;
fromInt(i: number): Long;
fromNumber(n: number): Long;
fromBits(lowBits: number, highBits: number): Long;
fromString(s: string, opt_radix?: number): Long;
}
export let Long: LongStatic;
export interface MaxKey {}
export interface MaxKeyStatic {
new (): MaxKey;
}
export let MaxKey: MaxKeyStatic;
export interface MinKey {}
export interface MinKeyStatic {
new (): MinKey;
}
export let MinKey: MinKeyStatic;
export interface ObjectID {}
export interface ObjectIDStatic {
new (id?: number | string | ObjectID): ObjectID;
createPk(): ObjectID;
createFromTime(time: number): ObjectID;
createFromHexString(hexString: string): ObjectID;
isValid(id: number | string | ObjectID): boolean;
}
export let ObjectID: ObjectIDStatic;
export let ObjectId: ObjectIDStatic;
export interface BSONRegExp {}
export interface BSONRegExpStatic {
new (pattern: string, options: string): BSONRegExp;
}
export let BSONRegExp: BSONRegExpStatic;
export interface Symbol {}
export interface SymbolStatic {
new (value: string): Symbol;
}
export let Symbol: SymbolStatic;
export interface Timestamp {}
export interface TimestampStatic {
new (low: number, high: number): Timestamp;
fromInt(i: number): Timestamp;
fromNumber(n: number): Timestamp;
fromBits(lowBits: number, highBits: number): Timestamp;
fromString(s: string, opt_radix?: number): Timestamp;
}
export let Timestamp: TimestampStatic;
}
export let BSONNative: typeof BSONPure;
}
export = bson;
}
+3 -1
View File
@@ -19,7 +19,9 @@ declare module Calq
trackSale(action:string, params:{[index:string]:any}, currency:string, amount:number):void;
trackHTMLLink(action:string, params?:{[index:string]:any}):void;
trackPageView(action?:string):void;
setGlobalProperty(name:string,value:any):void;
setGlobalProperty(name:string, value:any):void;
setGlobalProperty(params: {[index:string]: any}):void;
}
interface User
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./camelcase.d.ts" />
import camelCase from 'camelcase';
camelCase('foo-bar');
camelCase('foo_bar');
camelCase('Foo-Bar');
camelCase('--foo.bar');
camelCase('__foo__bar__');
camelCase('foo bar');
camelCase('foo', 'bar');
camelCase('__foo__', '--bar');
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for camelcase
// Project: https://github.com/sindresorhus/camelcase
// Definitions by: Sam Verschueren <https://github.com/samverschueren>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "camelcase" {
export default function camelcase(...args: string[]): string;
}
+1 -1
View File
@@ -107,7 +107,7 @@ interface LinearInstance extends ChartInstance {
getPointsAtEvent: (event: Event) => PointsAtEvent[];
update: () => void;
addData: (valuesArray: number[], label: string) => void;
removeData: () => void;
removeData: (index?: number) => void;
}
interface CircularInstance extends ChartInstance {
+55
View File
@@ -0,0 +1,55 @@
/// <reference path="clean-css.d.ts" />
import * as CleanCSS from 'clean-css';
var source = 'a{font-weight:bold;}';
var minified = new CleanCSS().minify(source).styles;
var source = '@import url(http://path/to/remote/styles);';
new CleanCSS().minify(source, function (error, minified) {
console.log(minified.styles);
});
const pathToOutputDirectory = 'path';
new CleanCSS({ sourceMap: true, target: pathToOutputDirectory })
.minify(source, function (error, minified) {
// access minified.sourceMap for SourceMapGenerator object
// see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
// see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI
console.log(minified.sourceMap);
});
const inputSourceMapAsString = 'input';
new CleanCSS({ sourceMap: inputSourceMapAsString, target: pathToOutputDirectory })
.minify(source, function (error, minified) {
// access minified.sourceMap to access SourceMapGenerator object
// see https://github.com/mozilla/source-map/#sourcemapgenerator for more details
// see https://github.com/jakubpawlowicz/clean-css/blob/master/bin/cleancss#L114 on how it's used in clean-css' CLI
console.log(minified.sourceMap);
});
new CleanCSS({ sourceMap: true, target: pathToOutputDirectory }).minify({
'path/to/source/1': {
styles: '...styles...',
sourceMap: '...source-map...'
},
'path/to/source/2': {
styles: '...styles...',
sourceMap: '...source-map...'
}
}, function (error, minified) {
// access minified.sourceMap as above
console.log(minified.sourceMap);
});
new CleanCSS().minify(['path/to/file/one', 'path/to/file/two']);
new CleanCSS().minify({
'path/to/file/one': {
styles: 'contents of file one'
},
'path/to/file/two': {
styles: 'contents of file two'
}
});
+109
View File
@@ -0,0 +1,109 @@
// Type definitions for clean-css v3.4.9
// Project: https://github.com/jakubpawlowicz/clean-css
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'clean-css' {
namespace CleanCSS {
interface Options {
// Set to false to disable advanced optimizations - selector & property merging, reduction, etc.
advanced?: boolean;
// Set to false to disable aggressive merging of properties.
aggressiveMerging?: boolean;
// Turns on benchmarking mode measuring time spent on cleaning up (run npm run bench to see example)
benchmark?: boolean;
// Enables compatibility mode
compatibility?: Object;
// Set to true to get minification statistics under stats property (see test/custom-test.js for examples)
debug?: boolean;
// A hash of options for @import inliner, see test/protocol-imports-test.js for examples, or this comment for a proxy use case.
inliner?: Object;
// Whether to keep line breaks (default is false)
keepBreaks?: boolean;
// * for keeping all (default), 1 for keeping first one only, 0 for removing all
keepSpecialComments?: string | number;
// Whether to merge @media at-rules (default is true)
mediaMerging?: boolean;
// Whether to process @import rules
processImport?: boolean;
// A list of @import rules, can be ['all'] (default), ['local'], ['remote'], or a blacklisted path e.g. ['!fonts.googleapis.com']
processImportFrom?: Array<string>;
// Set to false to skip URL rebasing
rebase?: boolean;
// Path to resolve relative @import rules and URLs
relativeTo?: string;
// Set to false to disable restructuring in advanced optimizations
restructuring?: boolean;
// Path to resolve absolute @import rules and rebase relative URLs
root?: string;
// Rounding precision; defaults to 2; -1 disables rounding
roundingPrecision?: number;
// Set to true to enable semantic merging mode which assumes BEM-like content (default is false as it's highly likely this will break your stylesheets - use with caution!)
semanticMerging?: boolean;
// Set to false to skip shorthand compacting (default is true unless sourceMap is set when it's false)
shorthandCompacting?: boolean;
// Exposes source map under sourceMap property, e.g. new CleanCSS().minify(source).sourceMap (default is false) If input styles are a product of CSS preprocessor (Less, Sass) an input source map can be passed as a string.
sourceMap?: boolean | string;
// Set to true to inline sources inside a source map's sourcesContent field (defaults to false) It is also required to process inlined sources from input source maps.
sourceMapInlineSources?: boolean;
// Path to a folder or an output file to which rebase all URLs
target?: string;
}
interface Output {
// Optimized output CSS as a string
styles: string;
// Output source map (if requested with sourceMap option)
sourceMap: string;
// A list of errors raised
errors: Array<string>;
// A list of warnings raised
warnings: Array<string>;
// A hash of statistic information (if requested with debug option)
stats: {
// Original content size (after import inlining)
originalSize: number;
// Optimized content size
minifiedSize: number;
// Time spent on optimizations
timeSpent: number;
// A ratio of output size to input size (e.g. 25% if content was reduced from 100 bytes to 75 bytes)
efficiency: number;
};
}
}
class CleanCSS {
constructor(options?: CleanCSS.Options);
minify(sources: string | Array<string> | Object, callback?: (error: any, minified: CleanCSS.Output) => void): CleanCSS.Output;
}
export = CleanCSS;
}
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="clipboard.d.ts" />
var cb1 = new clipboard.Clipboard('.btn');
var cb2 = new clipboard.Clipboard('.btn', {
action: elem => 'copy'
});
var cb3 = new clipboard.Clipboard('.btn', {
text: elem => null
});
var cb4 = new clipboard.Clipboard('.btn', {
target: elem => null
});
var cb5 = new clipboard.Clipboard('.btn', {
action: elem => 'copy',
target: elem => null
});
cb1.destroy();
cb2.on('success', function(e) { });
cb2.on('error', function(e) { });
+52
View File
@@ -0,0 +1,52 @@
// Type definitions for clipboard.js 1.5.5
// Project: https://github.com/zenorocha/clipboard.js
// Definitions by: Andrei Kurosh <https://github.com/impworks>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module clipboard {
export class Clipboard {
constructor(selector: string, options?: IOptions);
/**
* Subscribes to events that indicate the result of a copy/cut operation.
* @param type {String} Event type ('success' or 'error').
* @param handler Callback function.
*/
on(type: "success", handler: (e: Event) => void): void;
on(type: "error", handler: (e: Event) => void): void;
on(type: string, handler: (e: Event) => void): void;
/**
* Clears all event bindings.
*/
destroy(): void;
}
interface IOptions {
/**
* Overwrites default command ('cut' or 'copy').
* @param {Element} elem Current element
* @returns {String} Only 'cut' or 'copy'.
*/
action?: (elem: Element) => string;
/**
* Overwrites default target input element.
* @param {Element} elem Current element
* @returns {Element} <input> element to use.
*/
target?: (elem: Element) => Element;
/**
* Returns the explicit text to copy.
* @param {Element} elem Current element
* @returns {String} Text to be copied.
*/
text?: (elem: Element) => string;
}
}
declare module 'clipboard' {
export = clipboard;
}
+10 -5
View File
@@ -606,7 +606,7 @@ declare module CodeMirror {
/** Returns a {from, to} object (both holding document positions), indicating the current position of the marked range,
or undefined if the marker is no longer in the document. */
find(): CodeMirror.Position;
find(): CodeMirror.Range;
/** Returns an object representing the options for the marker. If copyWidget is given true, it will clone the value of the replacedWith option, if any. */
getOptions(copyWidget: boolean): CodeMirror.TextMarkerOptions;
@@ -650,7 +650,12 @@ declare module CodeMirror {
new (line: number, ch: number): Position;
(line: number, ch: number): Position;
}
interface Range{
from: CodeMirror.Position;
to: CodeMirror.Position;
}
interface Position {
ch: number;
line: number;
@@ -800,9 +805,9 @@ declare module CodeMirror {
viewportMargin?: number;
/** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */
lint?: boolean | LintOptions;
/** Optional value to be used in conduction with CodeMirrors placeholder add-on. */
lint?: boolean | LintOptions;
/** Optional value to be used in conduction with CodeMirrors placeholder add-on. */
placeholder?: string;
}
+79
View File
@@ -0,0 +1,79 @@
/// <reference path="confidence.d.ts" />
import Confidence = require('confidence');
let criteria = {
"env": "production",
"platform": "ios",
"xfactor": "yes",
"random": {
"a": 15
}
};
/**
* The configurations in Confidence style
*/
let config = {
"key1": "abc",
"key2": {
"$filter": "env",
"production": {
"deeper": {
"$value": "value"
}
},
"$default": {
"$filter": "platform",
"android": 0,
"ios": 1,
"$default": 2
}
},
"key3": {
"sub1": 123,
"sub2": {
"$filter": "xfactor",
"yes": 6
}
},
"ab": {
"$filter": "random.a",
"$range": [
{ "limit": 10, "value": 4 },
{ "limit": 20, "value": 5 }
],
"$default": 6
},
"$meta": {
"description": "example file"
}
};
/**
* Creates an empty configuration storage container
*/
let store = new Confidence.Store(config);
/**
* Validates the provided configuration, clears any existing configuration, then loads the configuration
*/
store.load(config);
/**
* Retrieves a value from the configuration document after applying the provided criteria
*/
store.get('/key1');
//criteria - optional object
store.get('/key2', criteria);
/**
* Retrieves the metadata (if any) from the configuration document after applying the provided criteria
*/
store.meta('/key1');
//criteria - optional object
store.meta('/key2', criteria);
+48
View File
@@ -0,0 +1,48 @@
// Type definitions for Confidence v1.4.2
// Project: https://github.com/hapijs/confidence.git
// Definitions by: Jean-Philippe Pellerin <https://github.com/jppellerin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* Confidence is a configuration document format, an API, and a foundation for A/B testing.
* The configuration format is designed to work with any existing JSON-based configuration,
* serving values based on object path ('/a/b/c' translates to a.b.c). In addition,
* confidence defines special $-prefixed keys used to filter values for a given criteria.
*/
declare module 'confidence' {
export class Store {
/**
* @constructor
* @param {any} document - the configuration document for this document store
*/
constructor(document?: any);
/**
* Validates the provided configuration, clears any existing configuration, then loads the configuration where:
* @param {any} document - an object containing a confidence configuration object generated from a parsed JSON document. If the document is invlaid, will throw an error.
*/
load(document: any): void;
/**
* Retrieves a value from the configuration document after applying the provided criteria where:
* @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document.
* @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}.
*
* @return {any} Returns the value found after applying the criteria. If the key is invalid or not found, returns undefined.
*/
get(key: string, criteria?: any): any;
/**
* Retrieves the metadata (if any) from the configuration document after applying the provided criteria where:
* @param {string} key - the requested key path. All keys must begin with '/'. '/' returns the the entire document.
* @param {any} criteria - optional object used as criteria for applying filters in the configuration document. Defaults to {}.
*
* @return {any} Returns the metadata found after applying the criteria. If the key is invalid or not found, or if no metadata is available, returns undefined.
*/
meta(key: string, criteria?: any): any;
}
}
+4 -4
View File
@@ -3,10 +3,10 @@
/// <reference path="../cookie-parser/cookie-parser.d.ts" />
/// <reference path="../express/express.d.ts" />
import express = require("express");
import timeout = require("connect-timeout");
import bodyParser = require("body-parser");
import cookieParser = require("cookie-parser");
import * as express from "express";
import timeout from "connect-timeout";
import * as bodyParser from "body-parser";
import * as cookieParser from "cookie-parser";
// example of using this top-level; note the use of haltOnTimedout
// after every middleware; it will stop the request flow on a timeout
+5 -2
View File
@@ -23,6 +23,10 @@ declare module Express {
declare module "connect-timeout" {
import express = require("express");
/**
* @summary Interface for timeout options.
* @interface
*/
interface TimeoutOptions extends Object {
/**
* @summary Controls if this module will "respond" in the form of forwarding an error.
@@ -31,6 +35,5 @@ declare module "connect-timeout" {
respond: boolean;
}
function timeout(timeout: string, options?: TimeoutOptions): express.RequestHandler;
export = timeout;
export default function timeout(timeout: string, options?: TimeoutOptions): express.RequestHandler;
}
+51 -1
View File
@@ -6,6 +6,42 @@ import validator = require('validator');
// define a schema
// straight from the convict tests
const format : convict.Format = {
name: 'float-percent',
validate: function(val) {
if (val !== 0 && (!val || val > 1 || val < 0)) {
throw new Error('must be a float between 0 and 1, inclusive');
}
},
coerce: function(val) {
return +(<string> val);
}
};
convict.addFormat(format);
convict.addFormats({
prime: {
validate: function(val) {
function isPrime(n: number) {
if (n <= 1) return false; // zero and one are not prime
for (var i=2; i*i <= n; i++) {
if (n % i === 0) return false;
}
return true;
}
if (!isPrime(val)) throw new Error('must be a prime number');
},
coerce: function(val) {
return parseInt(val, 10);
}
}
});
var conf = convict({
env: {
doc: 'The applicaton environment.',
@@ -46,7 +82,15 @@ var conf = convict({
env: 'PORT',
arg: 'port',
}
}
},
primeNumber: {
format: 'prime',
default: 17
},
percentNumber: {
format: 'float-percent',
default: 0.5
},
});
@@ -72,4 +116,10 @@ if (conf.has('key')) {
}
});
}
conf.getSchema();
conf.getProperties();
conf.getSchemaString();
conf.toString();
// vim:et:sw=2:ts=2
+67 -23
View File
@@ -4,30 +4,74 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "convict" {
function convict(schema: convict.Schema): convict.Config;
module convict {
module convict {
interface Schema {
[name: string]: convict.Schema | {
default: any;
doc?: string;
format?: any;
env?: string;
arg?: string;
};
}
interface Format {
name?: string;
validate?: (val: any) => void;
coerce?: (val: any) => any;
}
interface Config {
get(name: string): any;
default(name: string): any;
has(name: string): boolean;
set(name: string, value: any): void;
load(conf: Object): void;
loadFile(file: string): void;
loadFile(files: string[]): void;
validate(): void;
}
}
interface Schema {
[name: string]: convict.Schema | {
default: any;
doc?: string;
/**
* From the implementation:
*
* format can be a:
* - predefine type, as seen below
* - an array of enumerated values, e.g. ["production", "development", "testing"]
* - built-in JavaScript type, i.e. Object, Array, String, Number, Boolean
* - or if omitted, the Object.prototype.toString.call of the default value
*
* The docs also state that any function that validates is ok too
*/
format?: string | Array<any> | Function;
env?: string;
arg?: string;
};
}
export = convict;
interface Config {
get(name: string): any;
default(name: string): any;
has(name: string): boolean;
set(name: string, value: any): void;
load(conf: Object): void;
loadFile(file: string): void;
loadFile(files: string[]): void;
validate(): void;
/**
* Exports all the properties (that is the keys and their current values) as a {JSON} {Object}
* @returns {Object} A {JSON} compliant {Object}
*/
getProperties() : Object;
/**
* Exports the schema as a {JSON} {Object}
* @returns {Object} A {JSON} compliant {Object}
*/
getSchema() : Object;
/**
* Exports all the properties (that is the keys and their current values) as a JSON string.
* @returns {String} a string representing this object
*/
toString() : string;
/**
* Exports the schema as a JSON string.
* @returns {String} a string representing the schema of this {Config}
*/
getSchemaString() : string;
}
}
interface convict {
addFormat(format: convict.Format): void;
addFormats(formats: { [name: string]: convict.Format }): void;
(config: convict.Schema): convict.Config;
}
var convict : convict;
export = convict;
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="copy-paste.d.ts" />
import * as CopyPaste from 'copy-paste';
class TestClass {}
let strRet: string = CopyPaste.copy("content");
strRet = CopyPaste.copy("content", (err: Error) => { return; });
let objRet: TestClass = CopyPaste.copy(new TestClass());
objRet = CopyPaste.copy(new TestClass(), (err: Error) => { return; });
strRet = CopyPaste.paste();
CopyPaste.paste((err: Error, content: string) => { return; });
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for copy-paste v1.1.3
// Project: https://github.com/xavi-/node-copy-paste
// Definitions by: Tobias Kahlert <https://github.com/SrTobi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'copy-paste' {
export type CopyCallback = (err: Error) => void;
export type PasteCallback = (err: Error, content: string) => void;
/**
* Asynchronously replaces the current contents of the clip board with text.
*
* @param {T} content Takes either a string, array, object, or readable stream.
* @return {T} Returns the same value passed in.
*/
export function copy<T>(content: T): T;
/**
* Asynchronously replaces the current contents of the clip board with text.
*
* @param {T} content Takes either a string, array, object, or readable stream.
* @param {CopyCallback} callback will fire when the copy operation is complete.
* @return {T} Returns the same value passed in.
*/
export function copy<T>(content: T, callback: CopyCallback): T;
/**
* Synchronously returns the current contents of the system clip board.
*
* Note: The synchronous version of paste is not always availabled.
* An error message is shown if the synchronous version of paste is used on an unsupported platform.
* The asynchronous version of paste is always available.
*
* @return {string} Returns the current contents of the system clip board.
*/
export function paste(): string;
/**
* Asynchronously returns the current contents of the system clip board.
*
* @param {PasteCallback} callback The contents of the system clip board are passed to the callback as the second parameter.
*/
export function paste(callback: PasteCallback): void;
}
@@ -0,0 +1,43 @@
/// <reference path="cordova-plugin-qrscanner.d.ts" />
var QRScanner: QRScanner = window.QRScanner;
QRScanner.prepare()
QRScanner.prepare((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.scan((err, results) => { var error: Error = err; var contents: String = results; })
QRScanner.cancelScan()
QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; })
QRScanner.show()
QRScanner.show((status) => {var obj: QRScannerStatus = status; })
QRScanner.hide()
QRScanner.hide((status) => {var obj: QRScannerStatus = status; })
QRScanner.enableLight()
QRScanner.enableLight((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.disableLight()
QRScanner.disableLight((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useCamera(1)
QRScanner.useCamera(1, (err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useFrontCamera()
QRScanner.useFrontCamera((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.useBackCamera()
QRScanner.useBackCamera((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.pausePreview()
QRScanner.pausePreview((status) => {var obj: QRScannerStatus = status; })
QRScanner.resumePreview()
QRScanner.resumePreview((status) => {var obj: QRScannerStatus = status; })
QRScanner.openSettings()
QRScanner.openSettings((err, status) => { var error: Error = err; var obj: QRScannerStatus = status; })
QRScanner.destroy()
QRScanner.destroy((status) => {var obj: QRScannerStatus = status; })
QRScanner.getStatus((status) => {
var obj: QRScannerStatus = status;
var bool: Boolean = status.authorized;
bool = status.prepared;
bool = status.scanning;
bool = status.previewing;
bool = status.webviewBackgroundIsTransparent;
bool = status.lightEnabled;
bool = status.canOpenSettings;
bool = status.canEnableLight;
var num: Number = status.currentCamera;
})
+191
View File
@@ -0,0 +1,191 @@
// Type definitions for cordova-plugin-qrscanner
// Project: https://github.com/bitpay/cordova-plugin-qrscanner
// Definitions by: Jason Dreyzehner <https://github.com/bitjson/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* Global object QRScanner.
*/
interface Window {
QRScanner: QRScanner;
}
/**
* The QRScanner object provides functions to initialize, control, utilize, and
* deallocate a native QR code scanner and video preview behind the Cordova webview.
*/
interface QRScanner {
/**
* Request permission to access the camera (if not already granted), prepare
* the video preview, and configure everything needed by QRScanner. This will
* only be visible if `QRScanner.show()` has already made the webview transparent.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
prepare: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Sets QRScanner to "watch" for valid QR codes. Once a valid code is
* detected, it's contents are passed to the callback, and scanning is
* toggled off. If `QRScanner.prepare()` has not been called,
* `QRScanner.scan()` performs that setup as well. The video preview does
* not need to be visible for scanning to function.
* @param {function} callback Callback that gets an error or the results string.
*/
scan: (callback: (error: Error, result: String) => any) => void;
/**
* Cancels the current scan. The current scan() callback will not return.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
cancelScan: (callback?: (status: QRScannerStatus) => any) => void;
/**
* Configures the native webview to have a transparent background, then sets
* the background of the `<body>` and parent elements to transparent,
* allowing the webview to re-render with the transparent background.
* To see the video preview, your application background must be transparent
* in the areas through which it should show.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
show: (callback?: (status: QRScannerStatus) => any) => void;
/**
* Configures the native webview to be opaque with a white background,
* covering the video preview.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
hide: (callback?: (status: QRScannerStatus) => any) => void;
/**
* Enable the device's light (for scanning in low-light environments).
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
enableLight: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Disable the device's light.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
disableLight: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the `index` camera. Camera `0` is the back camera,
* camera `1` is front camera.
* @param {number} index A number representing the index of the camera to use.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useCamera: (index: Number, callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the device's front camera.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useFrontCamera: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Switch video capture to the device's back camera.
* @param {function} [callback] Callback that gets an error or the QRScannerStatus object.
*/
useBackCamera: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Pauses the video preview on the current frame (as if a snapshot was taken).
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
pausePreview: (callback?: (status: QRScannerStatus) => any) => void;
/**
* Resumes the video preview.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
resumePreview: (callback?: (status: QRScannerStatus) => any) => void;
/**
* Open the app-specific permission settings in the user's device settings.
* Here the user can enable/disable camera (and other) access for your app.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
openSettings: (callback?: (error: Error, status: QRScannerStatus) => any) => void;
/**
* Retrieve the status of QRScanner and provide it to the callback function.
* @param {function} callback Callback that gets the QRScannerStatus object.
*/
getStatus: (callback: (status: QRScannerStatus) => any) => void;
/**
* Stops scanning, video capture, and the preview, and deallocates as much as
* possible. (E.g. to improve performance/battery life when the scanner is
* not likely to be used for a while.)
* Basically reverts the plugin to it's startup-state.
* @param {function} [callback] Callback that gets the QRScannerStatus object.
*/
destroy: (callback?: (status: QRScannerStatus) => any) => void;
}
/**
* An object representing the current status of QRScanner.
*/
interface QRScannerStatus {
/**
* On iOS, camera access is granted to an app by the user (by clicking "Allow"
* at the dialog). The `authorized` property is a boolean value which is true
* only when the user has allowed camera access to your app
* (`AVAuthorizationStatus.Authorized`). The `NotDetermined`, `Restricted`
* (e.g.: parental controls), and `Denied` AVAuthorizationStatus states all
* cause this value to be false. If the user has denied access to your app,
* consider asking nicely and offering a link via `QRScanner.openSettings()`.
*/
authorized: Boolean,
/**
* A boolean value which is true if QRScanner is prepared to capture video and
* render it to the view.
*/
prepared: Boolean,
/**
* A boolean value which is true if QRScanner is actively scanning for a QR code.
*/
scanning: Boolean,
/**
* A boolean value which is true if QRScanner is displaying a live preview
* from the device's camera. Set to false when the preview is paused.
*/
previewing: Boolean,
/**
* A boolean value which is true when the native webview background is transparent.
*/
webviewBackgroundIsTransparent: Boolean,
/**
* A boolean value which is true if the light is enabled.
*/
lightEnabled: Boolean,
/**
* A boolean value which is true only if the users' operating system is able
* to `QRScanner.openSettings()`.
*/
canOpenSettings: Boolean,
/**
* A boolean value which is true only if the users' device can enable a light
* in the direction of the currentCamera.
*/
canEnableLight: Boolean,
/**
* A number representing the index of the currentCamera. `0` is the back
* camera, `1` is the front.
*/
currentCamera: Number
}
declare var QRScanner: QRScanner;
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="d3-dsv.d.ts" />
import d3dsv = require("d3-dsv");
var csv = d3dsv(",");
var rows = csv.parse("a,b,c\n1,2,3\n4,5,6");
+67
View File
@@ -0,0 +1,67 @@
// Type definitions for d3-dsv
// Project: https://www.npmjs.com/package/d3-dsv
// Definitions by: Jason Swearingen <https://jasonswearingen.github.io>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//commonjs loader
declare module "d3-dsv" {
/** A parser and formatter for DSV (CSV and TSV) files.
Extracted from D3. */
var loader: (
/** the symbol used to seperate cells in the row.*/
delimiter: string,
/** example: "text/plain" */
encoding?: string) => _d3dsv.D3Dsv;
export = loader;
}
declare module _d3dsv {
/** A parser and formatter for DSV (CSV and TSV) files.
Extracted from D3. */
export class D3Dsv {
/** Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows.
The string is assumed to be RFC4180-compliant.
Unlike the parseRows method, this method requires that the first line of the CSV file contains a comma-separated list of column names;
these column names become the attributes on the returned objects.
For example, consider the following CSV file:
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
The resulting JavaScript array is:
[ {"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"} ]
*/
public parse<TRow>(
table: string,
/** coerce cells (strings) into different types or modify them. return null to strip this row from the output results. */
accessor?: (row: any) => TRow
): TRow[];
/** Parses the specified string, which is the contents of a CSV file, returning an array of arrays representing the parsed rows. The string is assumed to be RFC4180-compliant. Unlike the parse method, this method treats the header line as a standard row, and should be used whenever the CSV file does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file:
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
The resulting JavaScript array is:
[ ["1997", "Ford", "E350", "2.34"],
["2000", "Mercury", "Cougar", "2.38"] ]
Note that the values themselves are always strings; they will not be automatically converted to numbers. See parse for details.*/
public parseRows<TRow>(
table: string,
/** coerce cells (strings) into different types or modify them. return null to strip this row from the output results.*/
accessor?: (row: string[]) => TRow
): TRow[];
/** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parse. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes.
Each row should be an object, and all object properties will be converted into fields. For greater control over which properties are converted, convert the rows into arrays containing only the properties that should be converted and use formatRows. */
public format(rows: any[]): string;
/** Converts the specified array of rows into comma-separated values format, returning a string. This operation is the reverse of parseRows. Each row will be separated by a newline (\n), and each column within each row will be separated by a comma (,). Values that contain either commas, double-quotes (") or newlines will be escaped using double-quotes. */
public formatRows(rows: any[]): string;
}
}
+2
View File
@@ -35,3 +35,5 @@ paths = del.sync(["tmp/*.js", "!tmp/unicorn.js"], {force: true});
paths = del.sync("tmp/*.js");
paths = del.sync("tmp/*.js", {force: true});
paths = del.sync("tmp/*.js", {dryRun: true});
+4 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for del v1.2.0
// Type definitions for del v2.2.0
// Project: https://github.com/sindresorhus/del
// Definitions by: Asana <https://asana.com>
// Definitions by: Asana <https://asana.com>, Aya Morisawa <https://github.com/AyaMorisawa>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../glob/glob.d.ts"/>
@@ -20,7 +20,8 @@ declare module "del" {
function sync(patterns: string[], options?: Options): string[];
interface Options extends glob.IOptions {
force?: boolean
force?: boolean;
dryRun?: boolean;
}
}
+12
View File
@@ -0,0 +1,12 @@
/// <reference path="./dot-prop.d.ts" />
import * as dotProp from 'dot-prop';
dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
const obj = {foo: {bar: 'a'}};
dotProp.set(obj, 'foo.bar', 'b');
dotProp.set(obj, 'foo.baz', 'x');
dotProp.set(obj, 'foo.dot\\.dot', 'unicorn');
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for dot-prop
// Project: https://github.com/sindresorhus/dot-prop
// Definitions by: Sam Verschueren <https://github.com/samverschueren>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "dot-prop" {
export function get(object: any, path: string): any;
export function set(object: any, path: string, value: any): void;
}
+1022 -1021
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -81,12 +81,12 @@ declare namespace ElectronPackager {
/** Electron-packager done callback. */
export interface Callback {
/**
* Callback wich is called when electron-packager is done.
* Callback which is called when electron-packager is done.
*
* @param err - Contains errors if any.
* @param appPath - Path to the newly created application.
* @param appPath - Path(s) to the newly created application(s).
*/
(err: Error, appPath: string): void
(err: Error, appPath: string|string[]): void
}
/** Electron-packager function */
+30 -27
View File
@@ -68,6 +68,9 @@ promiseNumber = thenWithUndefinedFullFillAndPromiseReject;
var thenWithNoResultAndNoReject = promiseString.then<number>();
promiseNumber = thenWithNoResultAndNoReject;
var catchAfterThen = promiseString.then().catch<number>();
promiseNumber = catchAfterThen;
var voidPromise = new Promise<void>(function (resolve) { resolve(); });
//catch test
@@ -161,31 +164,31 @@ getJSON('story.json').then(function(story: Story) {
(<HTMLElement>document.querySelector('.spinner')).style.display = 'none';
});
interface T1 {
__t1: string;
}
interface T2 {
__t2: string;
}
interface T3 {
__t3: string;
}
function f1(): Promise<T1> {
return Promise.resolve({ __t1: "foo_t1" });
}
function f2(x: T1): T2 {
return { __t2: x.__t1 + ":foo_21" };
}
var x3 = f1()
.then(f2, (e: Error) => {
console.log("error 1");
throw e;
})
.then((x: T2) => {
return { __t3: x.__t2 + "bar" };
interface T1 {
__t1: string;
}
interface T2 {
__t2: string;
}
interface T3 {
__t3: string;
}
function f1(): Promise<T1> {
return Promise.resolve({ __t1: "foo_t1" });
}
function f2(x: T1): T2 {
return { __t2: x.__t1 + ":foo_21" };
}
var x3 = f1()
.then(f2, (e: Error) => {
console.log("error 1");
throw e;
})
.then((x: T2) => {
return { __t3: x.__t2 + "bar" };
});
+1
View File
@@ -6,6 +6,7 @@
interface Thenable<R> {
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>;
catch<U>(onRejected?: (error: any) => U | Thenable<U>): Thenable<U>;
}
declare class Promise<R> implements Thenable<R> {
+695
View File
@@ -0,0 +1,695 @@
/// <reference path="./expect.d.ts" />
/// <reference path="../mocha/mocha.d.ts"" />
import expect,
{Expectation, Extension, Spy, createSpy, isSpy, assert, spyOn, extend, restoreSpies}
from 'expect';
describe('chaining assertions', function () {
it('should allow chaining for array-like applications', function () {
expect([ 1, 2, 'foo', 3 ])
.toExist()
.toBeAn(Array)
.toInclude('foo')
.toExclude('bar')
})
it('should allow chaining for number checking', function () {
expect(3.14)
.toExist()
.toBeLessThan(4.2)
.toBeGreaterThan(3.0)
})
})
describe('createSpy', function () {
describe('when given a function', function () {
it('returns a spy function', function () {
const spy = createSpy(function () {})
expect(spy).toBeA(Function)
})
})
})
describe('A spy', function () {
let targetContext:any, targetArguments:any;
const target = {
method: function () {
targetContext = this
targetArguments = Array.prototype.slice.call(arguments, 0)
}
}
let spy:any;
it('is a spy', function () {
expect(isSpy(spy)).toBe(true)
})
it('has a destroy method', function () {
expect(spy.destroy).toBeA(Function)
})
it('has a restore method', function () {
expect(spy.restore).toBeA(Function)
})
it('knows how many times it has been called', function () {
spy()
spy()
expect(spy.calls.length).toEqual(2)
})
it('knows the arguments it was called with', function () {
spy(1, 2, 3)
expect(spy).toHaveBeenCalledWith(1, 2, 3)
})
describe('that calls some other function', function () {
let otherContext:any, otherArguments:any;
function otherFn() {
otherContext = this
otherArguments = Array.prototype.slice.call(arguments, 0)
}
beforeEach(function () {
spy.andCall(otherFn)
otherContext = otherArguments = null
})
it('calls that function', function () {
spy()
expect(otherContext).toNotBe(null)
})
it('uses the correct context', function () {
const context = {}
spy.call(context)
expect(otherContext).toBe(context)
})
it('passes the arguments through', function () {
spy(1, 2, 3)
expect(otherArguments).toEqual([ 1, 2, 3 ])
})
})
describe('that calls through', function () {
beforeEach(function () {
spy.andCallThrough()
})
it('calls the original function', function () {
spy()
expect(targetContext).toNotBe(null)
})
it('uses the correct context', function () {
const context = {}
spy.call(context)
expect(targetContext).toBe(context)
})
it('passes the arguments through', function () {
spy(1, 2, 3)
expect(targetArguments).toEqual([ 1, 2, 3 ])
})
})
describe('with a thrown value', function () {
beforeEach(function () {
spy.andThrow('hello')
})
it('throws the correct value', function () {
expect(spy).toThrow('hello')
})
})
describe('with a return value', function () {
beforeEach(function () {
spy.andReturn('hello')
})
it('returns the correct value', function () {
expect(spy()).toEqual('hello')
})
})
})
describe('expect.extend', function () {
const ColorAssertions:Extension = {
toBeAColor() {
assert(
this.actual.match(/^#[a-fA-F0-9]{6}$/),
'expected %s to be an HTML color',
this.actual
)
}
}
let assertSpy:Spy;
beforeEach(function () {
extend(ColorAssertions)
assertSpy = spyOn(expect, 'assert')
})
afterEach(function () {
assertSpy.restore()
})
it('works', function () {
interface ColorExpectation extends Expectation {
toBeAColor():Expectation;
}
(<ColorExpectation>expect('#ff00ff')).toBeAColor()
expect(assertSpy).toHaveBeenCalled()
})
})
describe('restoreSpies', function () {
describe('with one spy', function () {
const original = function () {}
const target = { method: original }
beforeEach(function () {
spyOn(target, 'method')
})
it('works with spyOn()', function () {
expect(target.method).toNotEqual(original)
restoreSpies()
expect(target.method).toEqual(original)
})
it('is idempotent', function () {
expect(target.method).toNotEqual(original)
restoreSpies()
restoreSpies()
expect(target.method).toEqual(original)
})
it('can work even on createSpy()', function () {
createSpy(original)
restoreSpies()
})
})
describe('with multiple spies', function () {
const originals = [ function () {}, function () {} ]
const targets = [
{ method: originals[0] },
{ method: originals[1] }
]
it('still works', function () {
spyOn(targets[0], 'method')
spyOn(targets[1], 'method')
expect(targets[0].method).toNotEqual(originals[0])
expect(targets[1].method).toNotEqual(originals[1])
restoreSpies()
expect(targets[0].method).toEqual(originals[0])
expect(targets[1].method).toEqual(originals[1])
})
})
})
describe('A function that was spied on', function () {
const video = {
play: function () {}
}
let spy:Spy;
beforeEach(function () {
spy = spyOn(video, 'play')
})
it('tracks the number of calls', function () {
expect(spy.calls.length).toEqual(1)
})
it('tracks the context that was used', function () {
expect(spy.calls[0].context).toBe(video)
})
it('tracks the arguments that were used', function () {
expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])
})
it('was called', function () {
expect(spy).toHaveBeenCalled()
})
it('was called with the correct args', function () {
expect(spy).toHaveBeenCalledWith('some', 'args')
})
it('can be restored', function () {
expect(video.play).toEqual(spy)
spy.restore()
expect(video.play).toNotEqual(spy)
})
})
describe('A function that was spied on but not called', function () {
const video = {
play: function () {}
}
let spy:Spy;
beforeEach(function () {
spy = spyOn(video, 'play')
})
it('number of calls to be zero', function () {
expect(spy.calls.length).toEqual(0)
})
it('was not called', function () {
expect(spy).toNotHaveBeenCalled()
})
})
describe('toBeA', function () {
it('requires the value to be a function or string', function () {
expect(function () {
expect('actual').toBeA(4)
}).toThrow(/must be a function or a string/)
})
it('does not throw when the actual value is an instanceof the constructor', function () {
expect(function () {
expect(new Expectation('foo')).toBeA(Expectation)
}).toNotThrow()
})
it('throws when the actual value is not an instanceof the constructor', function () {
expect(function () {
expect('actual').toBeA(Expectation)
}).toThrow(/to be/)
})
it('does not throw when the expected value is the typeof the actual value', function () {
expect(function () {
expect(4).toBeA('number')
expect(NaN).toBeA('number') // hahaha
}).toNotThrow()
})
it('throws when the expected value is not the typeof the actual value', function () {
expect(function () {
expect('actual').toBeA('number')
}).toThrow(/to be/)
})
it('does not throw when the actual value is an array', function () {
expect(function () {
expect([]).toBeAn('array')
}).toNotThrow()
})
it('throws when the actual value is not an array', function () {
expect(function () {
expect('actual').toBeAn('array')
}).toThrow(/to be/)
})
})
describe('toBeGreaterThan', function () {
it('does not throw when the actual value is greater than the expected value', function () {
expect(function () {
expect(3).toBeGreaterThan(2)
}).toNotThrow()
})
it('throws when the actual value is not greater than the expected value', function () {
expect(function () {
expect(2).toBeGreaterThan(3)
}).toThrow(/to be greater than/)
})
})
describe('toBeLessThan', function () {
it('does not throw when the actual value is less than the expected value', function () {
expect(function () {
expect(2).toBeLessThan(3)
}).toNotThrow()
})
it('throws when the actual value is not less than the expected value', function () {
expect(function () {
expect(3).toBeLessThan(2)
}).toThrow(/to be less than/)
})
})
describe('toBeTruthy', function () {
it('does not throw on truthy actual values', function () {
expect(function () {
expect(1).toBeTruthy()
expect({ hello: 'world' }).toBeTruthy()
expect([ 1, 2, 3 ]).toBeTruthy()
}).toNotThrow()
})
it('throws on falsy actual values', function () {
expect(function () {
expect(0).toBeTruthy()
}).toThrow()
expect(function () {
expect(null).toBeTruthy()
}).toThrow()
expect(function () {
expect(undefined).toBeTruthy()
}).toThrow()
})
})
describe('toBeFalsy', function () {
it('throws on truthy values', function () {
expect(function () {
expect(42).toBeFalsy()
}).toThrow()
expect(function () {
expect({ foo: 'bar' }).toBeFalsy()
}).toThrow()
expect(function () {
expect([]).toBeFalsy()
}).toThrow()
})
it('does not throw with falsy actual values', function () {
expect(function () {
expect(0).toBeFalsy()
expect(null).toBeFalsy()
expect(undefined).toBeFalsy()
}).toNotThrow()
})
})
describe('toEqual', function () {
it('works', function () {
expect(function () {
expect('actual').toEqual('expected')
}).toThrow(/Expected 'actual' to equal 'expected'/)
})
it('works with objects that have the same keys in different order', function () {
const a = { a: 'a', b: 'b', c: 'c' }
const b = { b: 'b', c: 'c', a: 'a' }
expect(a).toEqual(b)
})
it('shows diff', function () {
try {
expect('actual').toEqual('expected')
} catch (err) {
expect(err.actual).toEqual('actual')
expect(err.expected).toEqual('expected')
expect(err.showDiff).toEqual(true)
}
})
})
describe('toExclude', function () {
it('requires the actual value to be an array or string', function () {
expect(function () {
expect(1).toExclude(2)
}).toThrow(/must be an array or a string/)
})
it('does not throw when an array does not contain the expected value', function () {
expect(function () {
expect([ 1, 2, 3 ]).toExclude(4)
}).toNotThrow()
})
it('throws when an array contains the expected value', function () {
expect(function () {
expect([ 1, 2, 3 ]).toExclude(2)
}).toThrow(/to exclude/)
})
it('does not throw when an array does not contain the expected value', function () {
expect(function () {
expect('hello world').toExclude('goodbye')
}).toNotThrow()
})
it('throws when a string contains the expected value', function () {
expect(function () {
expect('hello world').toExclude('hello')
}).toThrow(/to exclude/)
})
})
describe('toExist', function () {
it('does not throw on truthy actual values', function () {
expect(function () {
expect(1).toExist()
expect({ 'hello': 'world' }).toExist()
expect([ 1, 2, 3 ]).toExist()
}).toNotThrow()
})
it('throws on falsy actual values', function () {
expect(function () {
expect(0).toExist()
}).toThrow()
expect(function () {
expect(null).toExist()
}).toThrow()
expect(function () {
expect(undefined).toExist()
}).toThrow()
})
})
describe('toNotExist', function () {
it('throws on truthy values', function () {
expect(function () {
expect(42).toNotExist()
}).toThrow()
expect(function () {
expect({ foo: 'bar' }).toNotExist()
}).toThrow()
expect(function () {
expect([]).toNotExist()
}).toThrow()
})
it('does not throw with falsy actual values', function () {
expect(function () {
expect(0).toNotExist()
expect(null).toNotExist()
expect(undefined).toNotExist()
}).toNotThrow()
})
})
describe('toInclude', function () {
it('requires the actual value to be an array or string', function () {
expect(function () {
expect(1).toInclude(2)
}).toThrow(/must be an array or a string/)
})
it('does not throw when an array contains an expected integer', function () {
expect(function () {
expect([ 1, 2, 3 ]).toInclude(2)
expect([ { a: 1 }, { c: 2 } ]).toInclude({ c: 2 })
}).toNotThrow()
})
it('does not throw when an array contains an expected object', function () {
expect(function () {
expect([ { a: 1 }, { c: 2 } ]).toInclude({ c: 2 })
}).toNotThrow()
})
it('throws when an array does not contain an expected integer', function () {
expect(function () {
expect([ 1, 2, 3 ]).toInclude(4)
}).toThrow(/to include/)
})
it('throws when an array does not contain an expected object', function () {
expect(function () {
expect([ { a: 1 }, { c: 2 } ]).toInclude({ a: 2 })
}).toThrow(/to include/)
})
it('does not throw when a string contains the expected value', function () {
expect(function () {
expect('hello world').toInclude('world')
}).toNotThrow()
})
it('throws when a string does not contain the expected value', function () {
expect(function () {
expect('hello world').toInclude('goodbye')
}).toThrow(/to include/)
})
})
describe('toMatch', function () {
it('requires the pattern to be a RegExp', function () {
expect(function () {
expect('actual').toMatch('expected')
}).toThrow(/must be a RegExp/)
})
it('does not throw when the actual value matches the pattern', function () {
expect(function () {
expect('actual').toMatch(/^actual$/)
}).toNotThrow()
})
it('throws when the actual value does not match the pattern', function () {
expect(function () {
expect('actual').toMatch(/nope/)
}).toThrow(/to match/)
})
})
describe('toNotMatch', function () {
it('requires the pattern to be a RegExp', function () {
expect(function () {
expect('actual').toNotMatch('expected')
}).toThrow(/must be a RegExp/)
})
it('does not throw when the actual value does not match the pattern', function () {
expect(function () {
expect('actual').toNotMatch(/nope/)
}).toNotThrow()
})
it('throws when the actual value matches the pattern', function () {
expect(function () {
expect('actual').toNotMatch(/^actual$/)
}).toThrow(/to not match/)
})
})
describe('toNotEqual', function () {
it('works with arrays of objects', function () {
const a = [
{
id: 0,
text: 'Array Object 0',
boo: false
},
{
id: 1,
text: 'Array Object 1',
boo: false
}
]
const b = [
{
id: 0,
text: 'Array Object 0',
boo: true // value of boo is changed to true here
},
{
id: 1,
text: 'Array Object 1',
boo: false
}
]
expect(a).toNotEqual(b)
})
if (typeof Map !== 'undefined') {
it('works with Map', function () {
const a = new Map()
a.set('key', 'value')
const b = new Map()
b.set('key', 'another value')
expect(a).toNotEqual(b)
})
}
if (typeof Set !== 'undefined') {
it('works with Set', function () {
const a = new Set()
a.add('a')
const b = new Set()
b.add('b')
expect(a).toNotEqual(b)
})
}
})
describe('withArgs', function () {
const fn = function (arg1:any, arg2:any) {
if (arg1 === 'first' && typeof arg2 === 'undefined') {
throw new Error('first arg found')
}
if (arg1 === 'first' && arg2 === 'second') {
throw new Error('both args found')
}
}
it('invokes actual function with args', function () {
expect(function () {
expect(fn).withArgs('first').toThrow(/first arg found/)
}).toNotThrow()
})
it('can be chained', function () {
expect(function () {
expect(fn).withArgs('first').withArgs('second').toThrow(/both args found/)
}).toNotThrow()
})
it('throws when actual is not a function', function () {
expect(function () {
expect('not a function').withArgs('first')
}).toThrow(/must be a function/)
})
})
describe('withContext', function () {
const context = {
check: true
}
const fn = function (arg:any) {
if (this.check && typeof arg === 'undefined') {
throw new Error('context found')
}
if (this.check && arg === 'good') {
throw new Error('context and args found')
}
}
it('calls function with context', function () {
expect(function () {
expect(fn).withContext(context).toThrow(/context found/)
}).toNotThrow()
})
it('calls function with context and args', function () {
expect(function () {
expect(fn).withContext(context).withArgs('good').toThrow(/context and args found/)
}).toNotThrow()
})
})
+1
View File
@@ -0,0 +1 @@
--noImplicitAny --target es6
+71
View File
@@ -0,0 +1,71 @@
// Type definitions for Expect v1.13.4
// Project: https://github.com/mjackson/expect
// Definitions by: Justin Reidy <https://github.com/jmreidy/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "expect" {
export class Expectation {
constructor(actual:any);
toExist(message?:string):Expectation;
toBeTruthy(message?:string):Expectation;
toNotExist(message?:string):Expectation;
toBeFalsy(message?:string):Expectation;
toBe(value:any, message?:string):Expectation;
toNotBe(value:any, message?:string):Expectation;
toEqual(value:any, message?:string):Expectation;
toNotEqual(value:any, message?:string):Expectation;
toThrow(value?:any, message?:string):Expectation;
toNotThrow(value?:any, message?:string):Expectation;
toBeA(value:any, message?:string):Expectation;
toBeAn(value:any, message?:string):Expectation;
toNotBeA(value:any, message?:string):Expectation;
toNotBeAn(value:any, message?:string):Expectation;
toMatch(value:any, message?:string):Expectation;
toNotMatch(value:any, message?:string):Expectation;
toBeLessThan(value:any, message?:string):Expectation;
toBeFewerThan(value:any, message?:string):Expectation;
toBeGreaterThan(value:any, message?:string):Expectation;
toBeMoreThan(value:any, message?:string):Expectation;
toInclude(value:any, compareValues?:any, message?:string):Expectation;
toContain(value:any, compareValues?:any, message?:string):Expectation;
toExclude(value:any, compareValues?:any, message?:string):Expectation;
toNotContain(value:any, compareValues?:any, message?:string):Expectation;
toHaveBeenCalled(message?:string):Expectation;
toHaveBeenCalledWith(...args:Array<any>):Expectation;
toNotHaveBeenCalled(message?:string):Expectation;
withContext(context:any):Expectation;
withArgs(...args:Array<any>):Expectation;
}
export interface Extension {
[name:string]:(args?:Array<any>) => void;
}
export interface Call {
context: Spy;
arguments: Array<any>;
}
export interface Spy {
__isSpy:Boolean;
calls:Array<Call>;
andCall(fn:Function):Spy;
andCallThrough():Spy;
andThrow(object:Object):Spy;
andReturn(value:any):Spy;
getLastCall():Call;
restore():void;
destroy():void;
}
function expect(actual:any):Expectation;
export function createSpy(fn?:Function, restore?:Function):Spy;
export function spyOn(object:Object, methodName:string):Spy;
export function isSpy(object:any):Boolean;
export function restoreSpies():void;
export function assert(condition:any, messageFormat:string, ...extraArgs:Array<any>):void;
export function extend(extension:Extension):void;
export default expect;
}
@@ -0,0 +1,18 @@
/// <reference path="../express-brute/express-brute.d.ts"/>
/// <reference path="../mongodb/mongodb.d.ts"/>
/// <reference path="express-brute-memcached.d.ts"/>
import express = require("express");
import ExpressBrute = require("express-brute");
import MemcachedStore = require("express-brute-memcached");
var app = express();
var store = new MemcachedStore("127.0.0.1");
var bruteforce = new ExpressBrute(store);
app.post('/auth',
bruteforce.prevent, // error 403 if we hit this route too often
function (req, res, next) {
res.send('Success!');
}
);
+114
View File
@@ -0,0 +1,114 @@
// Type definitions for express-brute-memcached
// Project: https://github.com/AdamPflug/express-brute-memcached
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
declare module "express-brute-memcached" {
/**
* @summary Memcached options.
* @interface
*/
interface MemcachedStoreOptions {
prefix: string;
/**
* @summary Maximum key size allowed.
* @type {number}
*/
maxKeySize: number;
/**
* @summary Maximum expiration time of keys (in seconds).
* @type {number}
*/
maxExpiration: number;
/**
* @summary Maximum size of a value.
* @type {number}
*/
maxValue: number;
/**
* @summary Maximum size of the connection pool.
* @type {number}
*/
poolSize: number;
/**
* @summary Hashing algorithm used to generate the hashRing values
* @type {string}
*/
algorithm: string;
/**
* @summary Time between reconnection attempts (in milliseconds).
* @type {number}
*/
reconnect: number;
/**
* @summary Time after which Memcached sends a connection timeout (in milliseconds).
* @type {number}
*/
timeout: number;
/**
* @summary Number of socket allocation retries per request.
* @type {number}
*/
retries: number;
/**
* @summary Number of failed-attempts to a server before it is regarded as 'dead'.
* @type {number}
*/
failures: number;
/**
* @summary Time between a server failure and an attempt to set it up back in service.
* @type {number}
*/
retry: number;
/**
* @summary If true, authorizes the automatic removal of dead servers from the pool.
* @type {boolean}
*/
remove: boolean;
/**
* @summary An array of server_locations to replace servers that fail and that are removed from the consistent hashing scheme.
* @type {Array}
*/
failOverServers: Array<any>;
/**
* @summary True, whether to use md5 as hashing scheme when keys exceed maxKeySize .
* @type
*/
keyCompression: boolean;
/**
* @summary Idle timeout for the connections.
* @type {number}
*/
idle: number;
}
/**
* @summary A memcached store adapter.
* @class
*/
export = class MemcachedStore {
/**
* @summary Constructor.
* @constructor
* @param {string|Array} hosts The collection.
* @param {Object} options The otpions.
*/
constructor(hosts: string|Array<string>, options?: MemcachedStoreOptions);
}
}
+82 -66
View File
@@ -45,85 +45,101 @@ declare module "express-brute" {
}
/**
* @summary Middleware.
* @summary Options for {@link ExpressBrute} class.
* @interface
*/
interface ExpressBruteOptions {
freeRetries: number;
proxyDepth: number;
attachResetToRequest: boolean;
refreshTimeoutOnRequest: boolean;
minWait: number;
maxWait: number;
lifetime: number;
failCallback: (req: express.Request, res: express.Response, next: Function, nextValidRequestDate: any) => void;
handleStoreError: any;
}
/**
* @summary Middleware.
* @class
*/
class ExpressBrute {
/**
* @summary Constructor.
* @constructor
* @param {any} store The store.
*/
constructor(store: any);
/**
* @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback.
* @param {Object} options The options.
*/
getMiddleware(options: ExpressBruteMiddleware): express.RequestHandler;
/**
* @summary Uses the current proxy trust settings to get the current IP from a request object.
* @param {Request} request The HTTP request.
* @return {RequestHandler} The Request handler.
*/
getIPFromRequest(request: express.Request): express.RequestHandler;
/**
* @summary Middleware that will bounce requests that happen faster than the current wait time by calling failCallback.
* @param {Request} request The HTTP request.
* @param {Response} response The HTTP response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
*/
prevent(request: express.Request, response: express.Response, next: Function): express.RequestHandler;
/**
* @summary Resets the wait time between requests back to its initial value.
* @param {string} ip The IP address.
* @param {string} key The key. response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
*/
reset(ip: string, key: string, next: Function): express.RequestHandler;
}
module ExpressBrute {
/**
* @summary In-memory store.
* @class
*/
class ExpressBrute {
export class MemoryStore {
/**
* @summary Constructor.
* @constructor
* @param {any} store The store.
*/
constructor(store: any);
/**
* @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback.
* @param {Object} options The options.
*/
getMiddleware(options: ExpressBruteMiddleware): express.RequestHandler;
constructor(options?: MemoryStoreOptions);
/**
* @summary Gets key value.
* @param {string} key The key name.
* @param {Function} callbck The callback.
*/
get(key: string, callback: (error: any, data: Object) => void): void;
/**
* @summary Uses the current proxy trust settings to get the current IP from a request object.
* @param {Request} request The HTTP request.
* @return {RequestHandler} The Request handler.
* @summary Sets the key value.
* @param {string} key The name.
* @param {string} value The value.
* @param {number} lifetime The lifetime.
* @param {Function} callback The callback.
*/
getIPFromRequest(request: express.Request): express.RequestHandler;
set(key: string, value: any, lifetime: number, callback: (error: any) => void): void;
/**
* @summary Middleware that will bounce requests that happen faster than the current wait time by calling failCallback.
* @param {Request} request The HTTP request.
* @param {Response} response The HTTP response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
* @summary Deletes the key.
* @param {string} key The name.
* @param {Function} callback The callback.
*/
prevent(request: express.Request, response: express.Response, next: Function): express.RequestHandler;
/**
* @summary Resets the wait time between requests back to its initial value.
* @param {string} ip The IP address.
* @param {string} key The key. response.
* @param {Function} next The next middleware.
* @return {RequestHandler} The Request handler.
*/
reset(ip: string, key: string, next: Function): express.RequestHandler;
reset(key: string, callback: (error: any) => void): void;
}
}
module ExpressBrute {
/**
* @summary In-memory store.
* @class
*/
export class MemoryStore {
/**
* @summary Constructor.
* @constructor
* @param {Object} options The options.
*/
constructor(options?: MemoryStoreOptions);
/**
* @summary Gets key value.
* @param {string} key The key name.
* @param {Function} callbck The callback.
*/
get(key: string, callback: (error: any, data: Object) => void): void;
/**
* @summary Sets the key value.
* @param {string} key The name.
* @param {string} value The value.
* @param {number} lifetime The lifetime.
* @param {Function} callback The callback.
*/
set(key: string, value: any, lifetime: number, callback: (error: any) => void): void;
/**
* @summary Deletes the key.
* @param {string} key The name.
* @param {Function} callback The callback.
*/
reset(key: string, callback: (error: any) => void): void;
}
}
export = ExpressBrute;
export = ExpressBrute;
}
+19 -1
View File
@@ -21,7 +21,25 @@ app.get('/', function(req, res){
res.send('hello world');
});
var router = express.Router();
const router = express.Router();
const pathStr : string = 'test';
const pathRE : RegExp = /test/;
const path = true? pathStr : pathRE;
router.get(path);
router.put(path)
router.post(path);
router.delete(path);
router.get(pathStr);
router.put(pathStr)
router.post(pathStr);
router.delete(pathStr);
router.get(pathRE);
router.put(pathRE)
router.post(pathRE);
router.delete(pathRE);
router.use((req, res, next) => { next(); })
router.route('/users')
+25 -34
View File
@@ -44,8 +44,7 @@ declare module "express" {
}
interface IRouterMatcher<T> {
(name: string, ...handlers: RequestHandler[]): T;
(name: RegExp, ...handlers: RequestHandler[]): T;
(name: string|RegExp, ...handlers: RequestHandler[]): T;
}
interface IRouter<T> extends RequestHandler {
@@ -103,9 +102,9 @@ declare module "express" {
route(path: string): IRoute;
use(...handler: RequestHandler[]): T;
use(handler: ErrorRequestHandler): T;
use(handler: ErrorRequestHandler|RequestHandler): T;
use(path: string, ...handler: RequestHandler[]): T;
use(path: string, handler: ErrorRequestHandler): T;
use(path: string, handler: ErrorRequestHandler|RequestHandler): T;
use(path: string[], ...handler: RequestHandler[]): T;
use(path: string[], handler: ErrorRequestHandler): T;
use(path: RegExp, ...handler: RequestHandler[]): T;
@@ -200,20 +199,35 @@ declare module "express" {
accepts(type: string[]): string;
/**
* Check if the given `charset` is acceptable,
* otherwise you should respond with 406 "Not Acceptable".
* Returns the first accepted charset of the specified character sets,
* based on the requests Accept-Charset HTTP header field.
* If none of the specified charsets is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.
* @param charset
*/
acceptsCharset(charset: string): boolean;
acceptsCharsets(charset?: string|string[]): string[];
/**
* Check if the given `lang` is acceptable,
* otherwise you should respond with 406 "Not Acceptable".
* Returns the first accepted encoding of the specified encodings,
* based on the requests Accept-Encoding HTTP header field.
* If none of the specified encodings is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.
* @param encoding
*/
acceptsEncodings(encoding?: string|string[]): string[];
/**
* Returns the first accepted language of the specified languages,
* based on the requests Accept-Language HTTP header field.
* If none of the specified languages is accepted, returns false.
*
* For more information, or if you have issues or concerns, see accepts.
*
* @param lang
*/
acceptsLanguage(lang: string): boolean;
acceptsLanguages(lang?: string|string[]): string[];
/**
* Parse Range header field,
@@ -240,28 +254,6 @@ declare module "express" {
*/
accepted: MediaType[];
/**
* Return an array of Accepted languages
* ordered from highest quality to lowest.
*
* Examples:
*
* Accept-Language: en;q=.5, en-us
* ['en-us', 'en']
*/
acceptedLanguages: any[];
/**
* Return an array of Accepted charsets
* ordered from highest quality to lowest.
*
* Examples:
*
* Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8
* ['unicode-1-1', 'iso-8859-5']
*/
acceptedCharsets: any[];
/**
* Return the value of param `name` when present or `defaultValue`.
*
@@ -881,8 +873,7 @@ declare module "express" {
set(setting: string, val: any): Application;
get: {
(name: string): any; // Getter
(name: string, ...handlers: RequestHandler[]): Application;
(name: RegExp, ...handlers: RequestHandler[]): Application;
(name: string|RegExp, ...handlers: RequestHandler[]): Application;
};
/**
+124 -22
View File
@@ -4,33 +4,43 @@
var $test = $("#test");
// Create Listbox with defaults
var rootElement: any = $test.listbox();
var instance: ExtendedListboxInstance = <ExtendedListboxInstance>$test.listbox();
// Create with options
var options = <ListBoxOptions>{};
options.multiple = true;
options.onItemsChanged = (items: ListboxItem[]): void => {
console.log(items);
};
options.searchBar = false;
options.searchBarWatermark = "Search";
options.searchBarButton = { icon: "fa fa-search", visible: true, onClick: function () { alert(); } };
options.getItems = function (): any[] {
return ["Test1"];
};
options.searchBar = false;
options.searchBarWatermark = "Search";
options.onFilterChanged = (filter): void => {
console.log(filter);
options.onItemsChanged = (event: ListboxEvent): void => {
console.log(event.eventName);
console.log(event.args);
console.log(event.target);
};
options.onValueChanged = function (value: any): void {
console.log(value);
options.onFilterChanged = (event: ListboxEvent): void => {
console.log(event.args);
};
options.onValueChanged = function (event: ListboxEvent): void {
console.log(event.args);
};
options.onItemDoubleClicked = function (event: ListboxEvent): void {
console.log(event.args);
};
options.onItemEnterPressed = function (event: ListboxEvent): void {
console.log(event.args);
};
options.searchBarButton = { icon: "fa fa-search", visible: true, onClick: function () { alert(); } };
rootElement = $test.listbox(options);
instance = <ExtendedListboxInstance>$test.listbox(options);
/////// NEW API ///////
// Add string item
rootElement.listbox("addItem", "Test2");
var id = instance.addItem("Test2");
// Add item
@@ -42,36 +52,128 @@ item.groupHeader = false;
item.id = "ouetioreit";
item.index = 0;
item.text = "Test3";
var id: string = rootElement.listbox("addItem", item);
id = instance.addItem(item);
// Remove item
rootElement.listbox("removeItem", id);
instance.removeItem(id);
// Get item
var i: ListboxItem = rootElement.listbox("getItem", id);
var i: ListboxItem = instance.getItem(id);
// Get items
var allItems: ListboxItem[] = rootElement.listbox("getItems");
var allItems: ListboxItem[] = instance.getItems();
// Get selected items
var allItems: ListboxItem[] = instance.getSelection();
// Move item up
var newIndex: number = rootElement.listbox("moveItemUp", i.id);
var newIndex: number = instance.moveItemUp(i.id);
// Move item down
newIndex = rootElement.listbox("moveItemDown", i.id);
newIndex = instance.moveItemDown(i.id);
// Move item to top
var newIndex: number = instance.moveItemToTop(i.id);
// Move item to bottom
newIndex = instance.moveItemToBottom(i.id);
// Clear selection
newIndex = rootElement.listbox("clearSelection");
instance.clearSelection();
// Enable
newIndex = rootElement.listbox("enable", false);
instance.enable(false);
// Destroy
newIndex = rootElement.listbox("destroy");
instance.destroy();
// onValueChanged
instance.onValueChanged((event: ListboxEvent) => {
console.log(event.args);
});
// onItemsChanged
instance.onItemsChanged((event: ListboxEvent) => {
console.log(event.args);
});
// onFilterChanged
instance.onFilterChanged((event: ListboxEvent) => {
console.log(event.args);
});
// onItemEnterPressed
instance.onItemEnterPressed((event: ListboxEvent) => {
console.log(event.args);
});
// onItemDoubleClicked
instance.onItemDoubleClicked((event: ListboxEvent) => {
console.log(event.args);
});
/////// LEGACY API ///////
// Add string item
instance.target.listbox("addItem", "Test2");
// Add item
var item: ListboxItem = <ListboxItem>{};
item.selected = true;
item.disabled = false;
item.childItems = ["Test4"];
item.groupHeader = false;
item.id = "ouetioreit";
item.index = 0;
item.text = "Test3";
var id: string = instance.target.listbox("addItem", item);
// Remove item
instance.target.listbox("removeItem", id);
// Get item
var i: ListboxItem = instance.target.listbox("getItem", id);
// Get items
var allItems: ListboxItem[] = instance.target.listbox("getItems");
// Move item up
var newIndex: number = instance.target.listbox("moveItemUp", i.id);
// Move item down
newIndex = instance.target.listbox("moveItemDown", i.id);
// Clear selection
instance.target.listbox("clearSelection");
// Enable
instance.target.listbox("enable", false);
// Destroy
instance.target.listbox("destroy");
+104 -6
View File
@@ -1,4 +1,4 @@
// Type definitions for extended-listbox 1.0.6
// Type definitions for extended-listbox 1.1.x
// Project: https://github.com/code-chris/extended-listbox
// Definitions by: Christian Kotzbauer <https://github.com/code-chris>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -59,27 +59,125 @@ interface ListBoxOptions {
getItems?: () => any;
/** callback for selection changes */
onValueChanged?: (value: ListboxItem|ListboxItem[]) => void;
onValueChanged?: (event: ListboxEvent) => void;
/** callback for searchBar text changes */
onFilterChanged?: (value: string) => void;
onFilterChanged?: (event: ListboxEvent) => void;
/** callback for item changes (item added, item removed, item order) */
onItemsChanged?: (value: ListboxItem[]) => void;
onItemsChanged?: (event: ListboxEvent) => void;
/** callback for enter keyPress event on an item */
onItemEnterPressed?: (event: ListboxEvent) => void;
/** callback for doubleClick event on an item */
onItemDoubleClicked?: (event: ListboxEvent) => void;
}
interface ListboxEvent {
/** unique event name */
eventName: string;
/** target object for which event is triggered */
target: JQuery;
/** any object */
args: any;
}
interface ExtendedListboxInstance {
/** DOM element of the listbox root */
target: JQuery;
/** Adds a new item to the list */
addItem(item: string|ListboxItem): string;
/** Removes a item from the list */
removeItem(identifier: string): void;
/** Reverts all changes from the DOM */
destroy(): void;
/** Resets the selection state of all items */
clearSelection(): void;
/** Returns a item object for the given id or display text */
getItem(identifier: string): ListboxItem;
/** Returns all item objects */
getItems(): ListboxItem[];
/** Returns all ListboxItem's which are selected */
getSelection(): ListboxItem[];
/** Decreases the index of the matching item by one */
moveItemUp(identifier: string): number;
/** Increases the index of the matching item by one */
moveItemDown(identifier: string): number;
/** Moves item to the bottom of the list */
moveItemToBottom(identifier: string): number;
/** Moves item to the top of the list */
moveItemToTop(identifier: string): number;
/** Enables or disables the whole list and all childs */
enable(state: boolean): void;
/** callback for selection changes */
onValueChanged(callback: (event: ListboxEvent) => void): void;
/** callback for item changes (item added, item removed, item order) */
onItemsChanged(callback: (event: ListboxEvent) => void): void;
/** callback for searchBar text changes */
onFilterChanged(callback: (event: ListboxEvent) => void): void;
/** callback for enter keyPress event on an item */
onItemEnterPressed(callback: (event: ListboxEvent) => void): void;
/** callback for doubleClick event on an item */
onItemDoubleClicked(callback: (event: ListboxEvent) => void): void;
}
interface JQuery {
listbox(): JQuery;
/** constructs a new instance of Listbox on the given DOM item or returns existing */
listbox(): ExtendedListboxInstance|ExtendedListboxInstance[];
/** constructs a new instance of Listbox on the given DOM item */
listbox(options: ListBoxOptions): ExtendedListboxInstance|ExtendedListboxInstance[];
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'addItem'): string;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'removeItem'): void;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'destroy'): void;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'getItem'): ListboxItem;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'getItems'): ListboxItem[];
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'moveItemUp'): number;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'moveItemDown'): number;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'clearSelection'): void;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: 'enable'): void;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: string): any;
/** @deprecated: use method in ExtendedListboxInstance */
listbox(methodName: string, methodParameter: any): any;
listbox(options: ListBoxOptions): JQuery;
}
+229
View File
@@ -0,0 +1,229 @@
/// <reference path="fs-extra-promise.d.ts" />
/// <reference path="../node/node.d.ts" />
import fs = require('fs-extra-promise');
import stream = require('stream');
var stats: fs.Stats;
var str: string;
var strArr: string[];
var bool: boolean;
var num: number;
var src: string;
var dest: string;
var file: string;
var filename: string;
var dir: string;
var path: string;
var data: any;
var object: Object;
var buffer: NodeBuffer;
var modeNum: number;
var modeStr: string;
var encoding: string;
var type: string;
var flags: string;
var srcpath: string;
var dstpath: string;
var oldPath: string;
var newPath: string;
var cache: string;
var offset: number;
var length: number;
var position: number;
var cacheBool: boolean;
var cacheStr: string;
var fd: number;
var len: number;
var uid: number;
var gid: number;
var atime: number;
var mtime: number;
var statsCallback: (err: Error, stats: fs.Stats) => void;
var errorCallback: (err: Error) => void;
var openOpts: fs.OpenOptions;
var watcher: fs.FSWatcher;
var readStreeam: stream.Readable;
var writeStream: stream.Writable;
fs.copy(src, dest, errorCallback);
fs.copy(src, dest, (src: string) => {
return false;
}, errorCallback);
fs.copySync(src, dest);
fs.copySync(src, dest, (src: string) => {
return false;
});
fs.createFile(file, errorCallback);
fs.createFileSync(file);
fs.mkdirs(dir, errorCallback);
fs.mkdirsSync(dir);
fs.mkdirp(dir, errorCallback);
fs.mkdirpSync(dir);
fs.outputFile(file, data, errorCallback);
fs.outputFileSync(file, data);
fs.outputJson(file, data, errorCallback);
fs.outputJSON(file, data, errorCallback);
fs.outputJsonSync(file, data);
fs.outputJSONSync(file, data);
fs.readJson(file, errorCallback);
fs.readJson(file, openOpts, errorCallback);
fs.readJSON(file, errorCallback);
fs.readJSON(file, openOpts, errorCallback);
fs.readJsonSync(file, openOpts);
fs.readJSONSync(file, openOpts);
fs.remove(dir, errorCallback);
fs.removeSync(dir);
fs.writeJson(file, object, errorCallback);
fs.writeJson(file, object, openOpts, errorCallback);
fs.writeJSON(file, object, errorCallback);
fs.writeJSON(file, object, openOpts, errorCallback);
fs.writeJsonSync(file, object, openOpts);
fs.writeJSONSync(file, object, openOpts);
fs.rename(oldPath, newPath, errorCallback);
fs.renameSync(oldPath, newPath);
fs.truncate(fd, len, errorCallback);
fs.truncateSync(fd, len);
fs.chown(path, uid, gid, errorCallback);
fs.chownSync(path, uid, gid);
fs.fchown(fd, uid, gid, errorCallback);
fs.fchownSync(fd, uid, gid);
fs.lchown(path, uid, gid, errorCallback);
fs.lchownSync(path, uid, gid);
fs.chmod(path, modeNum, errorCallback);
fs.chmod(path, modeStr, errorCallback);
fs.chmodSync(path, modeNum);
fs.chmodSync(path, modeStr);
fs.fchmod(fd, modeNum, errorCallback);
fs.fchmod(fd, modeStr, errorCallback);
fs.fchmodSync(fd, modeNum);
fs.fchmodSync(fd, modeStr);
fs.lchmod(path, modeStr, errorCallback);
fs.lchmod(path, modeNum, errorCallback);
fs.lchmodSync(path, modeNum);
fs.lchmodSync(path, modeStr);
fs.stat(path, statsCallback);
fs.lstat(path, statsCallback);
fs.fstat(fd, statsCallback);
stats = fs.statSync(path);
stats = fs.lstatSync(path);
stats = fs.fstatSync(fd);
fs.link(srcpath, dstpath, errorCallback);
fs.linkSync(srcpath, dstpath);
fs.symlink(srcpath, dstpath, type, errorCallback);
fs.symlinkSync(srcpath, dstpath, type);
fs.readlink(path, (err: Error, linkString: string) => {
});
fs.realpath(path, (err: Error, resolvedPath: string) => {
});
fs.realpath(path, cache, (err: Error, resolvedPath: string) => {
});
str = fs.realpathSync(path, cacheBool);
fs.unlink(path, errorCallback);
fs.unlinkSync(path);
fs.rmdir(path, errorCallback);
fs.rmdirSync(path);
fs.mkdir(path, modeNum, errorCallback);
fs.mkdir(path, modeStr, errorCallback);
fs.mkdirSync(path, modeNum);
fs.mkdirSync(path, modeStr);
fs.readdir(path, (err: Error, files: string[]) => {
});
strArr = fs.readdirSync(path);
fs.close(fd, errorCallback);
fs.closeSync(fd);
fs.open(path, flags, modeStr, (err: Error, fd: number) => {
});
num = fs.openSync(path, flags, modeStr);
fs.utimes(path, atime, mtime, errorCallback);
fs.utimesSync(path, atime, mtime);
fs.futimes(fd, atime, mtime, errorCallback);
fs.futimesSync(fd, atime, mtime);
fs.fsync(fd, errorCallback);
fs.fsyncSync(fd);
fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => {
});
num = fs.writeSync(fd, buffer, offset, length, position);
fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => {
});
num = fs.readSync(fd, buffer, offset, length, position);
fs.readFile(filename, (err: Error, data: NodeBuffer) => {
});
fs.readFile(filename, encoding, (err: Error, data: string) => {
});
fs.readFile(filename, openOpts, (err: Error, data: string) => {
});
fs.readFile(filename, (err: Error, data: NodeBuffer) => {
});
buffer = fs.readFileSync(filename);
str = fs.readFileSync(filename, encoding);
str = fs.readFileSync(filename, openOpts);
fs.writeFile(filename, data, errorCallback);
fs.writeFile(filename, data, encoding, errorCallback);
fs.writeFile(filename, data, openOpts, errorCallback);
fs.writeFileSync(filename, data);
fs.writeFileSync(filename, data, encoding);
fs.writeFileSync(filename, data, openOpts);
fs.appendFile(filename, data, errorCallback);
fs.appendFile(filename, data, encoding, errorCallback);
fs.appendFile(filename, data, openOpts, errorCallback);
fs.appendFileSync(filename, data);
fs.appendFileSync(filename, data, encoding);
fs.appendFileSync(filename, data, openOpts);
fs.watchFile(filename, {
curr: stats,
prev: stats
});
fs.watchFile(filename, {
persistent: bool,
interval: num
}, {
curr: stats,
prev: stats
});
fs.unwatchFile(filename);
watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => {
});
fs.exists(path, (exists: boolean) => {
});
bool = fs.existsSync(path);
readStreeam = fs.createReadStream(path);
readStreeam = fs.createReadStream(path, {
flags: str,
encoding: str,
fd: num,
mode: num,
bufferSize: num
});
writeStream = fs.createWriteStream(path);
writeStream = fs.createWriteStream(path, {
flags: str,
encoding: str,
string: str
});
+263
View File
@@ -0,0 +1,263 @@
// Type definitions for fs-extra-promise
// Project: https://github.com/overlookmotel/fs-extra-promise
// Definitions by: midknight41 <https://github.com/midknight41>, Jason Swearingen <https://github.com/jasonswearingen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition
///<reference path="../node/node.d.ts"/>
///<reference path="../bluebird/bluebird.d.ts"/>
declare module "fs-extra-promise" {
import stream = require("stream");
import Promise = require("bluebird");
export interface Stats {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: Date;
mtime: Date;
ctime: Date;
}
export interface FSWatcher {
close(): void;
}
export class ReadStream extends stream.Readable { }
export class WriteStream extends stream.Writable { }
//extended methods
export function copy(src: string, dest: string, callback?: (err: Error) => void): void;
export function copy(src: string, dest: string, filter: (src: string) => boolean, callback?: (err: Error) => void): void;
export function copySync(src: string, dest: string): void;
export function copySync(src: string, dest: string, filter: (src: string) => boolean): void;
export function createFile(file: string, callback?: (err: Error) => void): void;
export function createFileSync(file: string): void;
export function mkdirs(dir: string, callback?: (err: Error) => void): void;
export function mkdirp(dir: string, callback?: (err: Error) => void): void;
export function mkdirsSync(dir: string): void;
export function mkdirpSync(dir: string): void;
export function outputFile(file: string, data: any, callback?: (err: Error) => void): void;
export function outputFileSync(file: string, data: any): void;
export function outputJson(file: string, data: any, callback?: (err: Error) => void): void;
export function outputJSON(file: string, data: any, callback?: (err: Error) => void): void;
export function outputJsonSync(file: string, data: any): void;
export function outputJSONSync(file: string, data: any): void;
export function readJson(file: string, callback?: (err: Error) => void): void;
export function readJson(file: string, options?: OpenOptions, callback?: (err: Error) => void): void;
export function readJSON(file: string, callback?: (err: Error) => void): void;
export function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void;
export function readJsonSync(file: string, options?: OpenOptions): void;
export function readJSONSync(file: string, options?: OpenOptions): void;
export function remove(dir: string, callback?: (err: Error) => void): void;
export function removeSync(dir: string): void;
// export function delete(dir: string, callback?: (err: Error) => void): void;
// export function deleteSync(dir: string): void;
export function writeJson(file: string, object: any, callback?: (err: Error) => void): void;
export function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void;
export function writeJSON(file: string, object: any, callback?: (err: Error) => void): void;
export function writeJSON(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void;
export function writeJsonSync(file: string, object: any, options?: OpenOptions): void;
export function writeJSONSync(file: string, object: any, options?: OpenOptions): void;
export function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void;
export function renameSync(oldPath: string, newPath: string): void;
export function truncate(fd: number, len: number, callback?: (err: Error) => void): void;
export function truncateSync(fd: number, len: number): void;
export function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void;
export function chownSync(path: string, uid: number, gid: number): void;
export function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void;
export function fchownSync(fd: number, uid: number, gid: number): void;
export function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void;
export function lchownSync(path: string, uid: number, gid: number): void;
export function chmod(path: string, mode: number, callback?: (err: Error) => void): void;
export function chmod(path: string, mode: string, callback?: (err: Error) => void): void;
export function chmodSync(path: string, mode: number): void;
export function chmodSync(path: string, mode: string): void;
export function fchmod(fd: number, mode: number, callback?: (err: Error) => void): void;
export function fchmod(fd: number, mode: string, callback?: (err: Error) => void): void;
export function fchmodSync(fd: number, mode: number): void;
export function fchmodSync(fd: number, mode: string): void;
export function lchmod(path: string, mode: string, callback?: (err: Error) => void): void;
export function lchmod(path: string, mode: number, callback?: (err: Error) => void): void;
export function lchmodSync(path: string, mode: number): void;
export function lchmodSync(path: string, mode: string): void;
export function stat(path: string, callback?: (err: Error, stats: Stats) => void): void;
export function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void;
export function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void;
export function statSync(path: string): Stats;
export function lstatSync(path: string): Stats;
export function fstatSync(fd: number): Stats;
export function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void;
export function linkSync(srcpath: string, dstpath: string): void;
export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void;
export function symlinkSync(srcpath: string, dstpath: string, type?: string): void;
export function readlink(path: string, callback?: (err: Error, linkString: string) => void): void;
export function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void;
export function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void;
export function realpathSync(path: string, cache?: boolean): string;
export function unlink(path: string, callback?: (err: Error) => void): void;
export function unlinkSync(path: string): void;
export function rmdir(path: string, callback?: (err: Error) => void): void;
export function rmdirSync(path: string): void;
export function mkdir(path: string, mode?: number, callback?: (err: Error) => void): void;
export function mkdir(path: string, mode?: string, callback?: (err: Error) => void): void;
export function mkdirSync(path: string, mode?: number): void;
export function mkdirSync(path: string, mode?: string): void;
export function readdir(path: string, callback?: (err: Error, files: string[]) => void): void;
export function readdirSync(path: string): string[];
export function close(fd: number, callback?: (err: Error) => void): void;
export function closeSync(fd: number): void;
export function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void;
export function openSync(path: string, flags: string, mode?: string): number;
export function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void;
export function utimesSync(path: string, atime: number, mtime: number): void;
export function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void;
export function futimesSync(fd: number, atime: number, mtime: number): void;
export function fsync(fd: number, callback?: (err: Error) => void): void;
export function fsyncSync(fd: number): void;
export function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void;
export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void;
export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void): void;
export function readFile(filename: string, options: OpenOptions, callback: (err: Error, data: string) => void): void;
export function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void;
export function readFileSync(filename: string): NodeBuffer;
export function readFileSync(filename: string, encoding: string): string;
export function readFileSync(filename: string, options: OpenOptions): string;
export function writeFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void;
export function writeFile(filename: string, data: any, options?: OpenOptions, callback?: (err: Error) => void): void;
export function writeFileSync(filename: string, data: any, encoding?: string): void;
export function writeFileSync(filename: string, data: any, option?: OpenOptions): void;
export function appendFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void;
export function appendFile(filename: string, data: any, option?: OpenOptions, callback?: (err: Error) => void): void;
export function appendFileSync(filename: string, data: any, encoding?: string): void;
export function appendFileSync(filename: string, data: any, option?: OpenOptions): void;
export function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void;
export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void;
export function unwatchFile(filename: string, listener?: Stats): void;
export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher;
export function exists(path: string, callback?: (exists: boolean) => void): void;
export function existsSync(path: string): boolean;
export function ensureDir(path: string, cb: (err: Error) => void): void;
export interface OpenOptions {
encoding?: string;
flag?: string;
}
export interface ReadStreamOptions {
flags?: string;
encoding?: string;
fd?: number;
mode?: number;
bufferSize?: number;
}
export interface WriteStreamOptions {
flags?: string;
encoding?: string;
string?: string;
}
export function createReadStream(path: string, options?: ReadStreamOptions): ReadStream;
export function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream;
//promisified versions
export function copyAsync(src: string, dest: string): Promise<void>;
export function copyAsync(src: string, dest: string, filter: (src: string) => boolean): Promise<void>;
export function createFileAsync(file: string): Promise<void>;
export function mkdirsAsync(dir: string): Promise<void>;
export function mkdirpAsync(dir: string): Promise<void>;
export function outputFileAsync(file: string, data: any): Promise<void>;
export function outputJsonAsync(file: string, data: any): Promise<void>;
export function outputJSONAsync(file: string, data: any): Promise<void>;
export function readJsonAsync(file: string): Promise<void>;
export function readJsonAsync(file: string, options?: OpenOptions): Promise<void>;
export function readJSONAsync(file: string): Promise<void>;
export function readJSONAsync(file: string, options?: OpenOptions): Promise<void>;
export function removeAsync(dir: string): Promise<void>;
// export function deleteAsync(dir: string):Promise<void>;
export function writeJsonAsync(file: string, object: any): Promise<void>;
export function writeJsonAsync(file: string, object: any, options?: OpenOptions): Promise<void>;
export function writeJSONAsync(file: string, object: any): Promise<void>;
export function writeJSONAsync(file: string, object: any, options?: OpenOptions): Promise<void>;
export function renameAsync(oldPath: string, newPath: string): Promise<void>;
export function truncateAsync(fd: number, len: number): Promise<void>;
export function chownAsync(path: string, uid: number, gid: number): Promise<void>;
export function fchownAsync(fd: number, uid: number, gid: number): Promise<void>;
export function lchownAsync(path: string, uid: number, gid: number): Promise<void>;
export function chmodAsync(path: string, mode: number): Promise<void>;
export function chmodAsync(path: string, mode: string): Promise<void>;
export function fchmodAsync(fd: number, mode: number): Promise<void>;
export function fchmodAsync(fd: number, mode: string): Promise<void>;
export function lchmodAsync(path: string, mode: string): Promise<void>;
export function lchmodAsync(path: string, mode: number): Promise<void>;
export function statAsync(path: string): Promise<Stats>;
export function lstatAsync(path: string): Promise<Stats>;
export function fstatAsync(fd: number): Promise<Stats>;
export function linkAsync(srcpath: string, dstpath: string): Promise<void>;
export function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise<void>;
export function readlinkAsync(path: string): Promise<string>;
export function realpathAsync(path: string): Promise<string>;
export function realpathAsync(path: string, cache: string): Promise<string>;
export function unlinkAsync(path: string): Promise<void>;
export function rmdirAsync(path: string): Promise<void>;
export function mkdirAsync(path: string, mode?: number): Promise<void>;
export function mkdirAsync(path: string, mode?: string): Promise<void>;
export function readdirAsync(path: string): Promise<string[]>;
export function closeAsync(fd: number): Promise<void>;
export function openAsync(path: string, flags: string, mode?: string): Promise<number>;
export function utimesAsync(path: string, atime: number, mtime: number): Promise<void>;
export function futimesAsync(fd: number, atime: number, mtime: number): Promise<void>;
export function fsyncAsync(fd: number): Promise<void>;
export function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>;
export function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>;
export function readFileAsync(filename: string, encoding: string): Promise<string>;
export function readFileAsync(filename: string, options: OpenOptions): Promise<string>;
export function readFileAsync(filename: string): Promise<NodeBuffer>;
export function writeFileAsync(filename: string, data: any, encoding?: string): Promise<void>;
export function writeFileAsync(filename: string, data: any, options?: OpenOptions): Promise<void>;
export function appendFileAsync(filename: string, data: any, encoding?: string): Promise<void>;
export function appendFileAsync(filename: string, data: any, option?: OpenOptions): Promise<void>;
export function existsAsync(path: string): Promise<boolean>;
export function ensureDirAsync(path: string): Promise<void>;
}
+2 -2
View File
@@ -70,8 +70,8 @@ declare module "fs-extra" {
export function readJSON(file: string, callback?: (err: Error) => void): void;
export function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void;
export function readJsonSync(file: string, options?: OpenOptions): void;
export function readJSONSync(file: string, options?: OpenOptions): void;
export function readJsonSync(file: string, options?: OpenOptions): any;
export function readJSONSync(file: string, options?: OpenOptions): any;
export function remove(dir: string, callback?: (err: Error) => void): void;
export function removeSync(dir: string): void;
+13 -12
View File
@@ -31,7 +31,7 @@ require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow: GitHubElectron.BrowserWindow = null;
var mainWindow: Electron.BrowserWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', () => {
@@ -72,6 +72,7 @@ app.on('ready', () => {
mainWindow.webContents.addWorkSpace('/path/to/workspace');
mainWindow.webContents.removeWorkSpace('/path/to/workspace');
var opened: boolean = mainWindow.webContents.isDevToolsOpened()
var focused = mainWindow.webContents.isDevToolsFocused();
// Emitted when the window is closed.
mainWindow.on('closed', () => {
// Dereference the window object, usually you would store windows
@@ -116,21 +117,21 @@ app.on('ready', () => {
app.addRecentDocument('/Users/USERNAME/Desktop/work.type');
app.clearRecentDocuments();
var dockMenu = Menu.buildFromTemplate([
<GitHubElectron.MenuItemOptions>{
<Electron.MenuItemOptions>{
label: 'New Window',
click: () => {
console.log('New Window');
}
},
<GitHubElectron.MenuItemOptions>{
<Electron.MenuItemOptions>{
label: 'New Window with Settings',
submenu: [
<GitHubElectron.MenuItemOptions>{ label: 'Basic' },
<GitHubElectron.MenuItemOptions>{ label: 'Pro' }
<Electron.MenuItemOptions>{ label: 'Basic' },
<Electron.MenuItemOptions>{ label: 'Pro' }
]
},
<GitHubElectron.MenuItemOptions>{ label: 'New Command...' },
<GitHubElectron.MenuItemOptions>{
<Electron.MenuItemOptions>{ label: 'New Command...' },
<Electron.MenuItemOptions>{
label: 'Edit',
submenu: [
{
@@ -167,7 +168,7 @@ var dockMenu = Menu.buildFromTemplate([
app.dock.setMenu(dockMenu);
app.setUserTasks([
<GitHubElectron.Task>{
<Electron.Task>{
program: process.execPath,
arguments: '--new-window',
iconPath: process.execPath,
@@ -186,7 +187,7 @@ window.setDocumentEdited(true);
// Online/Offline Event Detection
// https://github.com/atom/electron/blob/master/docs/tutorial/online-offline-events.md
var onlineStatusWindow: GitHubElectron.BrowserWindow;
var onlineStatusWindow: Electron.BrowserWindow;
app.on('ready', () => {
onlineStatusWindow = new BrowserWindow({ width: 0, height: 0, show: false });
@@ -287,12 +288,12 @@ globalShortcut.unregisterAll();
// ipcMain
// https://github.com/atom/electron/blob/master/docs/api/ipc-main-process.md
ipcMain.on('asynchronous-message', (event: GitHubElectron.IPCMainEvent, arg: any) => {
ipcMain.on('asynchronous-message', (event: Electron.IPCMainEvent, arg: any) => {
console.log(arg); // prints "ping"
event.sender.send('asynchronous-reply', 'pong');
});
ipcMain.on('synchronous-message', (event: GitHubElectron.IPCMainEvent, arg: any) => {
ipcMain.on('synchronous-message', (event: Electron.IPCMainEvent, arg: any) => {
console.log(arg); // prints "ping"
event.returnValue = 'pong';
});
@@ -472,7 +473,7 @@ app.on('ready', () => {
// tray
// https://github.com/atom/electron/blob/master/docs/api/tray.md
var appIcon: GitHubElectron.Tray = null;
var appIcon: Electron.Tray = null;
app.on('ready', () => {
appIcon = new Tray('/path/to/my/icon');
var contextMenu = Menu.buildFromTemplate([
@@ -24,7 +24,7 @@ ipcRenderer.send('asynchronous-message', 'ping');
// remote
// https://github.com/atom/electron/blob/master/docs/api/remote.md
var BrowserWindow: typeof GitHubElectron.BrowserWindow = remote.require('browser-window');
var BrowserWindow: typeof Electron.BrowserWindow = remote.require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://github.com');
@@ -75,7 +75,7 @@ crashReporter.start({
// nativeImage
// https://github.com/atom/electron/blob/master/docs/api/native-image.md
var Tray: typeof GitHubElectron.Tray = remote.require('Tray');
var Tray: typeof Electron.Tray = remote.require('Tray');
var appIcon2 = new Tray('/Users/somebody/images/icon.png');
var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' });
var image = clipboard.readImage();
@@ -85,9 +85,9 @@ var appIcon4 = new Tray('/Users/somebody/images/icon.png');
// screen
// https://github.com/atom/electron/blob/master/docs/api/screen.md
var app: GitHubElectron.App = remote.require('app');
var app: Electron.App = remote.require('app');
var mainWindow: GitHubElectron.BrowserWindow = null;
var mainWindow: Electron.BrowserWindow = null;
app.on('ready', () => {
var size = screen.getPrimaryDisplay().workAreaSize;
+92 -57
View File
@@ -5,7 +5,7 @@
/// <reference path="../node/node.d.ts" />
declare module GitHubElectron {
declare module Electron {
/**
* This class is used to represent an image.
*/
@@ -64,6 +64,34 @@ declare module GitHubElectron {
function writeImage(image: NativeImage, type?: string): void;
}
interface Display {
id:number;
bounds:Bounds;
workArea:Bounds;
size:Dimension;
workAreaSize:Dimension;
scaleFactor:number;
rotation:number;
touchSupport:string;
}
interface Bounds {
x:number;
y:number;
width:number;
height:number;
}
interface Dimension {
width:number;
height:number;
}
interface Point {
x:number;
y:number;
}
class Screen implements NodeJS.EventEmitter {
addListener(event: string, listener: Function): Screen;
on(event: string, listener: Function): Screen;
@@ -78,26 +106,23 @@ declare module GitHubElectron {
/**
* @returns The current absolute position of the mouse pointer.
*/
getCursorScreenPoint(): any;
getCursorScreenPoint(): Point;
/**
* @returns The primary display.
*/
getPrimaryDisplay(): any;
getPrimaryDisplay(): Display;
/**
* @returns An array of displays that are currently available.
*/
getAllDisplays(): any[];
getAllDisplays(): Display[];
/**
* @returns The display nearest the specified point.
*/
getDisplayNearestPoint(point: {
x: number;
y: number;
}): any;
getDisplayNearestPoint(point: Point): Display;
/**
* @returns The display that most closely intersects the provided bounds.
*/
getDisplayMatching(rect: Rectangle): any;
getDisplayMatching(rect: Rectangle): Display;
}
/**
@@ -508,6 +533,7 @@ declare module GitHubElectron {
subpixelFontScaling?: boolean;
overlayFullscreenVideo?: boolean;
titleBarStyle?: string;
backgroundColor?: string;
}
interface Rectangle {
@@ -750,6 +776,10 @@ declare module GitHubElectron {
* Returns whether the developer tools are opened.
*/
isDevToolsOpened(): boolean;
/**
* Returns whether the developer tools are focussed.
*/
isDevToolsFocused(): boolean;
/**
* Toggle the developer tools.
*/
@@ -884,7 +914,7 @@ declare module GitHubElectron {
* Should be specified for submenu type menu item, when it's specified the
* type: 'submenu' can be omitted for the menu item
*/
submenu?: MenuItemOptions[];
submenu?: Menu|MenuItemOptions[];
/**
* Unique within a single menu. If defined then it can be used as a reference
* to this item by the position attribute.
@@ -1022,6 +1052,7 @@ declare module GitHubElectron {
* of your app is running, and other instances signal this instance and exit.
*/
makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean;
setAppUserModelId(id: string): void;
}
interface CommandLine {
@@ -1057,7 +1088,7 @@ declare module GitHubElectron {
/**
* Description of this task.
*/
description: string;
description?: string;
/**
* The absolute path to an icon to be displayed in a JumpList, it can be
* arbitrary resource file that contains an icon, usually you can specify
@@ -1069,9 +1100,9 @@ declare module GitHubElectron {
* icons, set this value to identify the icon. If an icon file consists of
* one icon, this value is 0.
*/
iconIndex: number;
commandLine: CommandLine;
dock: {
iconIndex?: number;
commandLine?: CommandLine;
dock?: {
/**
* When critical is passed, the dock icon will bounce until either the
* application becomes active or the request is canceled.
@@ -1180,6 +1211,19 @@ declare module GitHubElectron {
properties?: string|string[];
}
interface SaveDialogOptions {
title?: string;
defaultPath?: string;
/**
* File types that can be displayed, see dialog.showOpenDialog for an example.
*/
filters?: {
name: string;
extensions: string[];
}[]
}
/**
* @param browserWindow
* @param options
@@ -1187,18 +1231,7 @@ declare module GitHubElectron {
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
export function showSaveDialog(browserWindow?: BrowserWindow, options?: {
title?: string;
defaultPath?: string;
/**
* File types that can be displayed, see dialog.showOpenDialog for an example.
*/
filters?: {
name: string;
extensions: string[];
}[]
}, callback?: (fileName: string) => void): string;
export function showSaveDialog(browserWindow?: BrowserWindow, options?: SaveDialogOptions, callback?: (fileName: string) => void): string;
/**
* Shows a message box. It will block until the message box is closed. It returns .
@@ -1237,6 +1270,8 @@ declare module GitHubElectron {
*/
detail?: string;
icon?: NativeImage;
noLink?: boolean;
cancelId?: number;
}
}
@@ -1308,11 +1343,11 @@ declare module GitHubElectron {
/**
* @returns The contents of the clipboard as a NativeImage.
*/
readImage: typeof GitHubElectron.Clipboard.readImage;
readImage: typeof Electron.Clipboard.readImage;
/**
* Writes the image into the clipboard.
*/
writeImage: typeof GitHubElectron.Clipboard.writeImage;
writeImage: typeof Electron.Clipboard.writeImage;
/**
* Clears everything in clipboard.
*/
@@ -1631,19 +1666,19 @@ declare module GitHubElectron {
* @returns On success, returns an array of file paths chosen by the user,
* otherwise returns undefined.
*/
showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog;
showOpenDialog: typeof Electron.Dialog.showOpenDialog;
/**
* @param callback If supplied, the API call will be asynchronous.
* @returns On success, returns the path of file chosen by the user, otherwise
* returns undefined.
*/
showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog;
showSaveDialog: typeof Electron.Dialog.showSaveDialog;
/**
* Shows a message box. It will block until the message box is closed. It returns .
* @param callback If supplied, the API call will be asynchronous.
* @returns The index of the clicked button.
*/
showMessageBox: typeof GitHubElectron.Dialog.showMessageBox;
showMessageBox: typeof Electron.Dialog.showMessageBox;
/**
* Runs a modal dialog that shows an error message. This API can be called safely
@@ -1773,26 +1808,26 @@ declare module GitHubElectron {
}
interface CommonElectron {
clipboard: GitHubElectron.Clipboard;
crashReporter: GitHubElectron.CrashReporter;
nativeImage: typeof GitHubElectron.NativeImage;
shell: GitHubElectron.Shell;
clipboard: Electron.Clipboard;
crashReporter: Electron.CrashReporter;
nativeImage: typeof Electron.NativeImage;
shell: Electron.Shell;
app: GitHubElectron.App;
autoUpdater: GitHubElectron.AutoUpdater;
BrowserWindow: typeof GitHubElectron.BrowserWindow;
contentTracing: GitHubElectron.ContentTracing;
dialog: GitHubElectron.Dialog;
ipcMain: GitHubElectron.IPCMain;
globalShortcut: GitHubElectron.GlobalShortcut;
Menu: typeof GitHubElectron.Menu;
MenuItem: typeof GitHubElectron.MenuItem;
app: Electron.App;
autoUpdater: Electron.AutoUpdater;
BrowserWindow: typeof Electron.BrowserWindow;
contentTracing: Electron.ContentTracing;
dialog: Electron.Dialog;
ipcMain: Electron.IPCMain;
globalShortcut: Electron.GlobalShortcut;
Menu: typeof Electron.Menu;
MenuItem: typeof Electron.MenuItem;
powerMonitor: NodeJS.EventEmitter;
powerSaveBlocker: GitHubElectron.PowerSaveBlocker;
protocol: GitHubElectron.Protocol;
screen: GitHubElectron.Screen;
session: GitHubElectron.Session;
Tray: typeof GitHubElectron.Tray;
powerSaveBlocker: Electron.PowerSaveBlocker;
protocol: Electron.Protocol;
screen: Electron.Screen;
session: Electron.Session;
Tray: typeof Electron.Tray;
hideInternalModules(): void;
}
@@ -1814,11 +1849,11 @@ declare module GitHubElectron {
getSources(options: any, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void;
}
interface Electron extends CommonElectron {
desktopCapturer: GitHubElectron.DesktopCapturer;
ipcRenderer: GitHubElectron.IpcRenderer;
remote: GitHubElectron.Remote;
webFrame: GitHubElectron.WebFrame;
interface ElectronMainAndRenderer extends CommonElectron {
desktopCapturer: Electron.DesktopCapturer;
ipcRenderer: Electron.IpcRenderer;
remote: Electron.Remote;
webFrame: Electron.WebFrame;
}
}
@@ -1827,7 +1862,7 @@ interface Window {
* Creates a new window.
* @returns An instance of BrowserWindowProxy class.
*/
open(url: string, frameName?: string, features?: string): GitHubElectron.BrowserWindowProxy;
open(url: string, frameName?: string, features?: string): Electron.BrowserWindowProxy;
}
interface File {
@@ -1838,10 +1873,10 @@ interface File {
}
declare module 'electron' {
var electron: GitHubElectron.Electron;
var electron: Electron.ElectronMainAndRenderer;
export = electron;
}
interface NodeRequireFunction {
(id: 'electron'): GitHubElectron.Electron;
(moduleName: 'electron'): Electron.ElectronMainAndRenderer;
}
+11 -1
View File
@@ -23,6 +23,16 @@ describe('UniversalAnalytics', () => {
ga('create', 'UA-65432-1', 'auto', {some: 'config'});
ga('send', 'pageview');
ga('send', 'pageview', {some: 'details'});
ga('send', 'event', 'Videos', 'play', 'Fall Campaign');
ga('send', {hitType: 'event', eventCategory: 'Videos', eventAction: 'play', eventLabel: 'Fall Campaign'});
ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {nonInteraction: true});
ga('send', 'pageview', '/page');
ga('send', 'social', {'socialNetwork': 'facebook', 'socialAction': 'like', 'socialTarget': 'http://foo.com'});
ga('send', 'social', {'socialNetwork': 'google+', 'socialAction': 'plus', 'socialTarget': 'http://foo.com'});
ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123});
ga('send', 'timing', {'timingCategory': 'category', 'timingVar': 'lookup', 'timingValue': 123, 'timingLabel': 'label'});
ga('trackerName.send', 'event', 'load');
ga.create('UA-65432-1', 'auto');
ga.create('UA-65432-1', {some: 'config'});
ga.create('UA-65432-1', 'auto', {some: 'config'});
@@ -30,7 +40,7 @@ describe('UniversalAnalytics', () => {
ga.getByName('aNamedTracker');
});
it('should excercise Tracker APIs', () => {
var tracker: UniversalAnalytics.Tracker = ga('create', 'UA-65432-1', 'auto');
var tracker: UniversalAnalytics.Tracker = ga.create('UA-65432-1', 'auto');
var aString: string = tracker.get<string>('aString');
var aNumber: number = tracker.get<number>('aNumber');
var anObject: {} = tracker.get<{}>('anObject');
+44 -5
View File
@@ -38,17 +38,56 @@ interface GoogleAnalytics {
declare module UniversalAnalytics {
// https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference
enum HitType {
'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'
}
interface ga {
l: number;
q: any[];
(command: string, poly: string, opt_poly?: {}): UniversalAnalytics.Tracker;
(command: string, trackingId: string, auto: string, opt_configObject?: {}): UniversalAnalytics.Tracker;
(command: string, hitDetails: {}): void;
create(trackingId: string, opt_configObject?: {}): UniversalAnalytics.Tracker;
create(trackingId: string, auto: string, opt_configObject?: {}): UniversalAnalytics.Tracker;
(command: 'send', hitType: 'event', eventCategory: string, eventAction: string,
eventLabel?: string, eventValue?: number, fieldsObject?: {}): void;
(command: 'send', hitType: 'event', fieldsObject: {
eventCategory: string,
eventAction: string,
eventLabel?: string,
eventValue?: number,
nonInteraction?: boolean}): void;
(command: 'send', fieldsObject: {
hitType: HitType, // 'event'
eventCategory: string,
eventAction: string,
eventLabel?: string,
eventValue?: number,
nonInteraction?: boolean}): void;
(command: 'send', hitType: 'pageview', page: string): void;
(command: 'send', hitType: 'social',
socialNetwork: string, socialAction: string, socialTarget: string): void;
(command: 'send', hitType: 'social',
fieldsObject: {socialNetwork: string, socialAction: string, socialTarget: string}): void;
(command: 'send', hitType: 'timing',
timingCategory: string, timingVar: string, timingValue: number): void;
(command: 'send', hitType: 'timing',
fieldsObject: {timingCategory: string, timingVar: string, timingValue: number}): void;
(command: 'send', fieldsObject: {}): void;
(command: string, hitType: HitType, ...fields: any[]): void;
(command: 'create', trackingId: string, cookieDomain?: string, name?: string, fieldsObject?: {}): void;
(command: 'remove'): void;
(command: string, ...fields: any[]): void;
(readyCallback: (defaultTracker?: UniversalAnalytics.Tracker) => void): void;
create(trackingId: string, cookieDomain: string, name: string, fieldsObject?: {}): UniversalAnalytics.Tracker;
create(trackingId: string, cookieDomain: string, fieldsObject?: {}): UniversalAnalytics.Tracker;
create(trackingId: string, fieldsObject?: {}): UniversalAnalytics.Tracker;
getAll(): UniversalAnalytics.Tracker[];
getByName(name: string): UniversalAnalytics.Tracker;
remove(name:string): void;
}
interface Tracker {
+7 -7
View File
@@ -6,15 +6,15 @@
/// <reference path="../node/node.d.ts"/>
declare module "gulp-autoprefixer" {
interface Options {
browsers?: string[];
cascade?: boolean;
remove?: boolean;
namespace autoPrefixer {
interface Options {
browsers?: string[];
cascade?: boolean;
remove?: boolean;
}
}
function autoPrefixer(opts?: Options): NodeJS.ReadWriteStream;
namespace autoPrefixer {}
function autoPrefixer(opts?: autoPrefixer.Options): NodeJS.ReadWriteStream;
export = autoPrefixer;
}
+71
View File
@@ -0,0 +1,71 @@
/// <reference path="gulp-filter.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="../gulp-uglify/gulp-uglify.d.ts" />
/// <reference path="../gulp-less/gulp-less.d.ts" />
/// <reference path="../gulp-concat/gulp-concat.d.ts" />
import * as gulp from 'gulp';
import * as uglify from 'gulp-uglify';
import * as less from 'gulp-less';
import * as concat from 'gulp-concat';
import * as filter from 'gulp-filter';
// Filter only
gulp.task('default', () => {
// create filter instance inside task function
const f = filter(['*', '!src/vendor']);
return gulp.src('src/*.js')
// filter a subset of the files
.pipe(f)
// run them through a plugin
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
// Restoring filtered files
gulp.task('default', () => {
// create filter instance inside task function
const f = filter(['*', '!src/vendor'], {restore: true});
return gulp.src('src/*.js')
// filter a subset of the files
.pipe(f)
// run them through a plugin
.pipe(uglify())
// bring back the previously filtered out files (optional)
.pipe(f.restore)
.pipe(gulp.dest('dist'));
});
// Multiple filters
gulp.task('default', () => {
const jsFilter = filter('**/*.js', {restore: true});
const lessFilter = filter('**/*.less', {restore: true});
return gulp.src('assets/**')
.pipe(jsFilter)
.pipe(concat('bundle.js'))
.pipe(jsFilter.restore)
.pipe(lessFilter)
.pipe(less())
.pipe(lessFilter.restore)
.pipe(gulp.dest('out/'));
});
// Restore as a file source
gulp.task('default', () => {
const f = filter(['*', '!src/vendor'], {restore: true, passthrough: false});
const stream = gulp.src('src/*.js')
// filter a subset of the files
.pipe(f)
// run them through a plugin
.pipe(uglify())
.pipe(gulp.dest('dist'));
// use filtered files as a gulp file source
f.restore.pipe(gulp.dest('vendor-dist'));
return stream;
});
+33
View File
@@ -0,0 +1,33 @@
// Type definitions for gulp-filter v3.0.1
// Project: https://github.com/sindresorhus/gulp-filter
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../vinyl/vinyl.d.ts"/>
/// <reference path="../minimatch/minimatch.d.ts"/>
declare module 'gulp-filter' {
import File = require('vinyl');
import * as Minimatch from 'minimatch';
namespace filter {
interface FileFunction {
(file: File): boolean;
}
interface Options extends Minimatch.IOptions {
restore?: boolean;
passthrough?: boolean;
}
// A transform stream with a .restore object
interface Filter extends NodeJS.ReadWriteStream {
restore: NodeJS.ReadWriteStream
}
}
function filter(pattern: string | string[] | filter.FileFunction, options?: filter.Options): filter.Filter;
export = filter;
}
+11
View File
@@ -0,0 +1,11 @@
/// <reference path="gulp-htmlmin.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import * as gulp from 'gulp';
import * as htmlmin from 'gulp-htmlmin';
gulp.task('minify', function() {
return gulp.src('src/*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('dist'))
});
+18
View File
@@ -0,0 +1,18 @@
// Type definitions for gulp-htmlmin v1.3.0
// Project: https://github.com/jonschlinkert/gulp-htmlmin
// Definitions by: Tanguy Krotoff <https://github.com/tkrotoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../html-minifier/html-minifier.d.ts" />
declare module 'gulp-htmlmin' {
import * as HTMLMinifier from 'html-minifier';
namespace htmlmin {
}
function htmlmin(options?: HTMLMinifier.Options): NodeJS.ReadWriteStream;
export = htmlmin;
}
+29
View File
@@ -0,0 +1,29 @@
/// <reference path="../gulp/gulp.d.ts" />
/// <reference path="./gulp-jade.d.ts"/>
import * as gulp from 'gulp';
import * as jade from 'gulp-jade';
gulp.task('jade', () => {
gulp.src('src/**/*.jade')
.pipe(jade())
.pipe(gulp.dest('dist/'));
});
gulp.task('jade:pretty', () => {
gulp.src('src/**/*.jade')
.pipe(jade({
pretty: '\t',
}))
.pipe(gulp.dest('dist/'))
});
gulp.task('jade:client', () => {
gulp.src('src/**/*.jade')
.pipe(jade({
client: true,
pretty: true,
debug: false,
compileDebug: false,
}));
});
+87
View File
@@ -0,0 +1,87 @@
// Type definitions for gulp-jade
// Project: https://github.com/phated/gulp-jade
// Definitions by: berwyn <https://github.com/berwyn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "gulp-jade" {
function GulpJade(params?: GulpJade.Params): any;
module GulpJade {
interface Params {
/*******
* JADE API OPTIONS
*******/
/**
* If the doctype is not specified as part of the
* template, you can specify it here. It is sometimes
* useful to get self-closing tags and remove mirroring
* of boolean attributes.
*/
doctype?: string;
/**
* Adds whitespace to the resulting html to make it
* easier for a human to read using ' ' as indentation.
* If a string is specified, that will be used as
* indentation instead (e.g. '\t').
*/
pretty?: boolean|string;
/**
* Use a self namespace to hold the locals (false by default)
*/
self?: boolean;
/**
* If set to true, the tokens and function body is logged
* to stdout
*/
debug?: boolean;
/**
* If set to true, the function source will be included in the
* compiled template for better error messages (sometimes useful
* in development). It is enabled by default unless used with
* express in production mode.
*/
compileDebug?:boolean;
/**
* If set to true, compiled functions are cached. filename
* must be set as the cache key.
*/
cache?:boolean;
/*******
* GULP-JADE OPTIONS
*******/
/**
* Used to set a version of jade other than this library's
* dependency, or to customise filters.
*/
jade?: any;
/**
* Compile to JS instead of HTML.
*/
client?: boolean;
/**
* Locals to be used while parsing jade files. Takes
* precedence over data.
*/
locals?: any;
/**
* Data to be used while parsing jade files. Has lower
* precedence than locals.
*/
data?: any;
}
}
export = GulpJade;
}
+1
View File
@@ -11,6 +11,7 @@ declare module "gulp-less" {
modifyVars?: {};
paths?: string[];
plugins?: any[];
relativeUrls?: boolean;
}
function less(options?: IOptions): NodeJS.ReadWriteStream;
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="./gulp-minify-css.d.ts" />
/// <reference path="gulp-minify-css.d.ts" />
/// <reference path="../gulp/gulp.d.ts" />
import * as gulp from "gulp";
+3 -19
View File
@@ -4,28 +4,12 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../clean-css/clean-css.d.ts" />
declare module "gulp-minify-css" {
import * as CleanCSS from 'clean-css';
interface IOptions {
cache?: boolean;
advanced?: boolean;
aggressiveMerging?: boolean;
benchmark?: boolean;
compatibility?: string;
debug?: boolean;
inliner?: Object;
keepBreaks?: boolean;
keepSpecialComments?: string | number;
processImport?: boolean;
rebase?: boolean;
relativeTo?: string;
root?: string;
roundingPrecision?: number;
shorthandCompacting?: boolean;
}
function minifyCSS(options?: IOptions): NodeJS.ReadWriteStream;
function minifyCSS(options?: CleanCSS.Options): NodeJS.ReadWriteStream;
namespace minifyCSS {}
+3 -1
View File
@@ -4,11 +4,13 @@
import * as gulp from 'gulp';
import * as minifyHtml from 'gulp-minify-html';
// This package has been deprecated in favor of gulp-htmlmin, which should be faster and more comprehensive.
minifyHtml();
minifyHtml({conditionals: true, loose: true});
gulp.task('minify-html', () => {
var opts = {
var opts: minifyHtml.Options = {
conditionals: true,
spare: true
};
+21 -18
View File
@@ -5,33 +5,36 @@
/// <reference path="../node/node.d.ts" />
// This package has been deprecated in favor of gulp-htmlmin, which should be faster and more comprehensive.
declare module 'gulp-minify-html' {
interface IOptions {
// Do not remove empty attributes
empty?: boolean;
namespace minifyHtml {
// Options from https://github.com/Swaagie/minimize#options
interface Options {
// Do not remove empty attributes
empty?: boolean;
// Do not strip CDATA from scripts
cdata?: boolean;
// Do not strip CDATA from scripts
cdata?: boolean;
// Do not remove comments
comments?: boolean;
// Do not remove comments
comments?: boolean;
// Do not remove conditional internet explorer comments
conditionals?: boolean;
// Do not remove conditional internet explorer comments
conditionals?: boolean;
// Do not remove redundant attributes
spare?: boolean;
// Do not remove redundant attributes
spare?: boolean;
// Do not remove arbitrary quotes
quotes?: boolean;
// Do not remove arbitrary quotes
quotes?: boolean;
// Preserve one whitespace
loose?: boolean;
// Preserve one whitespace
loose?: boolean;
}
}
function minifyHtml(options?: IOptions): NodeJS.ReadWriteStream;
namespace minifyHtml {}
function minifyHtml(options?: minifyHtml.Options): NodeJS.ReadWriteStream;
export = minifyHtml;
}
+3 -3
View File
@@ -1,11 +1,11 @@
/// <reference path="./gulp-replace.d.ts"/>
/// <reference path="../gulp/gulp.d.ts"/>
import gulp = require("gulp");
import replace = require("gulp-replace");
import * as gulp from "gulp";
import * as replace from "gulp-replace";
gulp.task('templates', function(){
gulp.src(['file.txt'])
.pipe(replace("test", "foo"))
.pipe(replace(/foo(.{3})/g, '$1foo'))
.pipe(gulp.dest('build/file.txt'));
});
});
+3 -1
View File
@@ -17,5 +17,7 @@ declare module "gulp-replace" {
function replace(pattern: string, replacement: string | Replacer, opts?: Options): NodeJS.ReadWriteStream;
function replace(pattern: RegExp, replacement: string | Replacer, opts?: Options): NodeJS.ReadWriteStream;
namespace replace {}
export = replace;
}
}
+4 -4
View File
@@ -3,10 +3,10 @@
/// <reference path="../gulp-rev/gulp-rev.d.ts" />
/// <reference path="../gulp-useref/gulp-useref.d.ts" />
import gulp = require('gulp');
import revReplace = require('gulp-rev-replace');
import rev = require('gulp-rev');
import useref = require('gulp-useref');
import * as gulp from 'gulp';
import * as revReplace from 'gulp-rev-replace';
import * as rev from 'gulp-rev';
import * as useref from 'gulp-useref';
gulp.task("index", () => {
return gulp.src("src/index.html")
+11 -9
View File
@@ -6,16 +6,18 @@
/// <reference path="../node/node.d.ts" />
declare module 'gulp-rev-replace' {
interface IOptions {
canonicalUris?: boolean;
replaceInExtensions?: Array<string>;
prefix?: string;
manifest?: NodeJS.ReadWriteStream;
modifyUnreved?: Function;
modifyReved?: Function;
namespace revReplace {
interface Options {
canonicalUris?: boolean;
replaceInExtensions?: Array<string>;
prefix?: string;
manifest?: NodeJS.ReadWriteStream;
modifyUnreved?: Function;
modifyReved?: Function;
}
}
function revReplace(options?: IOptions): NodeJS.ReadWriteStream;
function revReplace(options?: revReplace.Options): NodeJS.ReadWriteStream;
export = revReplace;
export = revReplace;
}
+1 -1
View File
@@ -10,7 +10,7 @@ declare module "gulp-shell" {
namespace shell {
interface Shell {
(commands: string|string[], options?: Option): NodeJS.ReadWriteStream;
task(commands: string|string[], options?: Option): () => NodeJS.ReadWriteStream;
task(commands: string|string[], options?: Option): (done: Function) => NodeJS.ReadWriteStream;
}
interface Option {
+12 -12
View File
@@ -6,20 +6,20 @@
/// <reference path="../node/node.d.ts" />
declare module 'gulp-size' {
interface IOptions {
showFiles?: boolean;
gzip?: boolean;
title?: string;
namespace size {
interface Options {
showFiles?: boolean;
gzip?: boolean;
title?: string;
}
interface SizeStream extends NodeJS.ReadWriteStream {
size: number;
prettySize: string;
}
}
interface ISizeStream extends NodeJS.ReadWriteStream {
size: number;
prettySize: string;
}
function size(options?: IOptions): ISizeStream;
namespace size {}
function size(options?: size.Options): size.SizeStream;
export = size;
}
+4 -4
View File
@@ -1,8 +1,8 @@
/// <reference path="./gulp-uglify.d.ts"/>
/// <reference path="gulp-uglify.d.ts"/>
/// <reference path="../gulp/gulp.d.ts"/>
import gulp = require("gulp");
import uglify = require("gulp-uglify");
import * as gulp from 'gulp';
import * as uglify from 'gulp-uglify';
gulp.task('compress', function() {
var tsResult = gulp.src('lib/*.ts')
@@ -21,4 +21,4 @@ gulp.task('compress2', function() {
}
}))
.pipe(gulp.dest('dist'));
});
});

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