Merge pull request #4 from DefinitelyTyped/master

Marge the newest master branch
This commit is contained in:
TonyYang
2016-09-17 13:14:22 +08:00
committed by GitHub
430 changed files with 54702 additions and 8731 deletions
+1
View File
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
* [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT)
+9
View File
@@ -27,6 +27,9 @@ declare namespace AmCharts {
/** Clears all the charts on page, removes listeners and intervals. */
function clear();
/** Handle ready event */
function ready(Function): void;
/** Create chart by params. */
function makeChart(selector: string, params: any, delay?: number): AmChart;
@@ -961,6 +964,10 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
@Default 150
*/
hideBalloonTime: number;
/** Allows changing language easily.
* Note, you should include the language.js file from amcharts/lang or ammap/lang folder and then use variable name used in this file, like chart.language = "de";
* Note, for maps this works differently - you use language only for country names, as there are no other strings in the maps application. */
language: string;
/** Legend of a chart. */
legend: AmLegend;
/** Reference to the div of the legend. */
@@ -989,6 +996,8 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
prefixesOfBigNumbers: any[];
/** Prefixes which are used to make small numbers shorter: 2μ instead of 0.000002, etc. Prefixes are used on value axes and in the legend. To enable prefixes, set usePrefixes property to true. [{number:1e-24, prefix:"y"},{number:1e-21, prefix:"z"},{number:1e-18, prefix:"a"},{number:1e-15, prefix:"f"},{number:1e-12, prefix:"p"},{number:1e-9, prefix:"n"},{number:1e-6, prefix:"μ"},{number:1e-3, prefix:"m"}] */
prefixesOfSmallNumbers: any[];
/** A config object for Responsive plugin. */
responsive: any;
/** Theme of a chart. Config files of themes can be found in amcharts/themes/ folder. More info about using themes. */
theme: string;
/** Thousands separator.
+87
View File
@@ -0,0 +1,87 @@
// Tests for Amplitude SDK TypeScript definitions
/// <reference path="amplitude-js.d.ts" />
module Amplitude.Tests {
function all() {
amplitude.init('YOUR_API_KEY_HERE', null, {
// optional configuration options
saveEvents: true,
includeUtm: true,
includeReferrer: true,
batchEvents: true,
eventUploadThreshold: 50
});
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {});
amplitude.logEvent('EVENT_IDENTIFIER_HERE');
amplitude.setUserId('USER_ID_HERE');
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE');
amplitude.setUserId(null); // not string 'null'
amplitude.setVersionName('VERSION_NAME_HERE');
amplitude.regenerateDeviceId();
amplitude.setDeviceId('CUSTOM_DEVICE_ID');
amplitude.logEvent('EVENT_IDENTIFIER_HERE', {
'color': 'blue',
'age': 20,
'key': 'value'
});
amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
let identify = new amplitude.Identify().set('gender', 'female').set('age', 20);
amplitude.identify(identify);
identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015');
amplitude.identify(identify);
identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015');
amplitude.identify(identify);
identify = new amplitude.Identify().unset('gender').unset('age');
amplitude.identify(identify);
identify = new amplitude.Identify().add('karma', 1).add('friends', 1);
amplitude.identify(identify);
identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']);
amplitude.identify(identify);
identify = new amplitude.Identify()
.set('karma', 10)
.add('karma', 1)
.unset('karma');
amplitude.identify(identify);
identify = new amplitude.Identify()
.set('colors', ['rose', 'gold'])
.append('ab-tests', 'campaign_a')
.append('existing_list', [4, 5]);
amplitude.identify(identify);
amplitude.setUserProperties({
gender: 'female',
age: 20
});
amplitude.clearUserProperties();
amplitude.setOptOut(true);
amplitude.setOptOut(false);
amplitude.setGroup('orgId', '15');
amplitude.setGroup('sport', ['soccer', 'tennis']);
// TODO: Implement those.
/*
var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3);
amplitude.logRevenueV2(revenue);
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
*/
}
}
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for Amplitude SDK 2.12.1
// Project: https://github.com/amplitude/Amplitude-Javascript
// Definitions by: Arvydas Sidorenko <https://github.com/Asido>
// Definitions: https://github.com/Asido/DefinitelyTyped
declare module amplitude {
interface Config {
batchEvents?: boolean;
cookieExpiration?: number;
cookieName?: string;
deviceId?: string;
domain?: string;
eventUploadPeriodMillis?: number;
eventUploadThreshold?: number;
includeReferrer?: boolean;
includeUtm?: boolean;
language?: string;
optOut?: boolean;
platform?: string;
saveEvents?: boolean;
savedMaxCount?: number;
sessionTimeout?: number;
uploadBatchSize?: number;
}
export class Identify {
set(key: string, value: any): Identify;
setOnce(key: string, value: any): Identify;
add(key: string, value: number): Identify;
append(key: string, value: any): Identify;
prepend(key: string, value: any): Identify;
unset(key: string): Identify;
}
export function init(apiKey: string): void;
export function init(apiKey: string, userId: string): void;
export function init(apiKey: string, userId: string, options: Config): void;
export function init(apiKey: string, userId: string, options: Config, callback: () => void): void;
export function setVersionName(version: string): void;
export function setUserId(userId: string): void;
export function setDeviceId(id: string): void;
export function regenerateDeviceId(): void;
export function identify(identify: Identify): void;
export function setUserProperties(properties: Object): void;
export function clearUserProperties(): void;
export function setOptOut(optOut: boolean): void;
export function setGroup(groupType: string, groupName: string | string[]): void;
export function logEvent(event: string): void;
export function logEvent(event: string, data: Object): void;
export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void;
export var options: Config;
}
+15 -15
View File
@@ -45,12 +45,12 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Component: (component: iComponent) => ngESDecorator;
function Component(component: iComponent): ngESDecorator;
/**
* Register config block
*/
var Config: () => ngESDecorator;
function Config(): ngESDecorator;
/**
* Register constant
@@ -59,7 +59,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Constant: (name: string) => ngESDecorator;
function Constant(name: string): ngESDecorator;
/**
* Register controller
@@ -68,7 +68,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Controller: (name: string) => ngESDecorator;
function Controller(name: string): ngESDecorator;
/**
* Register decorator
@@ -77,7 +77,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Decorator: (name: string) => ngESDecorator;
function Decorator(name: string): ngESDecorator;
/**
* Register directive
@@ -86,7 +86,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Directive: (name: string) => ngESDecorator;
function Directive(name: string): ngESDecorator;
/**
* Register factory
@@ -95,7 +95,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Factory: (name: string) => ngESDecorator;
function Factory(name: string): ngESDecorator;
/**
* Register filter
@@ -104,7 +104,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Filter: (name: string) => ngESDecorator;
function Filter(name: string): ngESDecorator;
/**
* Add $inject property to target
@@ -113,7 +113,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Inject: (...dependencies: Array<string>) => ngESDecorator;
function Inject(...dependencies: Array<string>): ngESDecorator;
/**
* Inject dependencies as properties to target
@@ -122,7 +122,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var InjectAsProperty: (...dependencies: Array<string>) => ngESDecorator;
function InjectAsProperty(...dependencies: Array<string>): ngESDecorator;
/**
* Attach target to the specified module
@@ -131,7 +131,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Module: (name: string) => ngESDecorator;
function Module(name: string): ngESDecorator;
/**
* Register provider
@@ -140,14 +140,14 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Provider: (name: string) => ngESDecorator;
function Provider(name: string): ngESDecorator;
/**
* Register run block
*
* @returns {ngESDecorator} - decorated class
*/
var Run: () => ngESDecorator;
function Run(): ngESDecorator;
/**
* Register service
@@ -156,7 +156,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Service: (name: string) => ngESDecorator;
function Service(name: string): ngESDecorator;
/**
* Register value
@@ -165,7 +165,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
var Value: (name: string) => ngESDecorator;
function Value(name: string): ngESDecorator;
export {
Component,
+3 -3
View File
@@ -51,12 +51,12 @@ declare namespace angular.gettext {
/** Get the correct pluralized (but untranslated) string for the value of n. */
getStringForm(string: string, n: number): string;
/** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect:
/** Translate a string with the given scope. Uses Angular.JS interpolation, so something like this will do what you expect:
* var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" });
* // var hello will be "Hallo Ruben!" in Dutch.
* The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
* The scope parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster.
*/
getString(string: string, context?: any): string;
getString(string: string, scope?: any, context?: string): string;
/** Translate a plural string with the given context. */
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
+15
View File
@@ -15,3 +15,18 @@ var $jwtInterceptor: ng.jwt.IJwtInterceptor;
$jwtInterceptor.tokenGetter = () => {
return expToken;
}
var authManager: ng.jwt.IAuthManagerServiceProvider;
// Indicate the user is authenticated
authManager.authenticate();
// Indicate the user is unauthenticated
authManager.unauthenticate();
// Keep the user authenticated
authManager.checkAuthOnRefresh();
// Redirect the user on unauthorized requests
authManager.redirectWhenUnauthenticated();
+7
View File
@@ -27,4 +27,11 @@ declare namespace angular.jwt {
interface IJwtInterceptor {
tokenGetter(...params : any[]): string;
}
interface IAuthManagerServiceProvider {
authenticate(): void;
unauthenticate(): void;
checkAuthOnRefresh(): void;
redirectWhenUnauthenticated(): void;
}
}
@@ -127,15 +127,30 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
instance.isOpen();
instance.isLockedOpen();
});
$scope['onClose'] = $mdSidenav(componentId).onClose(() => {});
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
$scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
$scope['customToast'] = () => {
var options = {
hideDelay: 3000,
position: 'top right',
controller : 'ToastCtrl',
templateUrl : 'toast-template.html',
toastClass: 'my-class'
};
$mdToast.show(options);
}
});
myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => {
$scope['createPanel'] = () => {
var config = {
id: 'myPanel',
template: '<h1>Hello!</h1>',
hasBackdrop: true,
disableParentScroll: true,
+8 -5
View File
@@ -22,7 +22,7 @@ declare namespace angular.material {
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
resolve?: {[index: string]: angular.IPromise<any>};
resolve?: {[index: string]: () => angular.IPromise<any>};
controllerAs?: string;
parent?: Function|string|Object; // default: root node
disableParentScroll?: boolean; // default: true
@@ -53,7 +53,7 @@ declare namespace angular.material {
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
resolve(resolve?: {[index: string]: angular.IPromise<any>}): T;
resolve(resolve?: {[index: string]: () => angular.IPromise<any>}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
@@ -91,7 +91,7 @@ declare namespace angular.material {
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onShowing?: Function;
@@ -132,6 +132,7 @@ declare namespace angular.material {
close(): angular.IPromise<void>;
isOpen(): boolean;
isLockedOpen(): boolean;
onClose(onClose: Function): void;
}
interface ISidenavService {
@@ -162,10 +163,11 @@ declare namespace angular.material {
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
toastClass?: string;
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
@@ -291,13 +293,14 @@ declare namespace angular.material {
}
interface IPanelConfig {
id?: string;
template?: string;
templateUrl?: string;
controller?: string|Function;
controllerAs?: string;
bindToController?: boolean; // default: true
locals?: {[index: string]: any};
resolve?: {[index: string]: angular.IPromise<any>}
resolve?: {[index: string]: () => angular.IPromise<any>}
attachTo?: string|JQuery|Element;
propagateContainerEvents?: boolean;
panelClass?: string;
@@ -0,0 +1,30 @@
/// <reference path="angular-ui-notification.d.ts" />
function TestNotifications(NotificationProvider: angular.uiNotification.INotificationProvider, Notification: angular.uiNotification.INotificationService) {
NotificationProvider.setOptions({
delay: 10000,
startTop: 20,
startRight: 10,
verticalSpacing: 20,
horizontalSpacing: 20,
positionX: 'left',
positionY: 'bottom'
});
Notification.primary('Primary notification');
Notification('Primary notification');
Notification.success('Success notification');
Notification({message: 'Warning notification'}, 'warning');
Notification({message: 'Primary notification', title: 'Primary notification'});
Notification.error({message: 'Error notification 1s', delay: 1000});
Notification.success({message: 'Success notification<br>Some other <b>content</b><br><a href="https://github.com/alexcrack/angular-ui-notification">This is a link</a><br><img src="https://angularjs.org/img/AngularJS-small.png">', title: 'Html content'});
Notification.error({message: 'Error Bottom Right', positionY: 'bottom', positionX: 'right'});
Notification.error({message: 'Error notification 1s', replaceMessage: true});
}
+82
View File
@@ -0,0 +1,82 @@
// Type definitions for angular-ui-notification
// Project: https://github.com/alexcrack/angular-ui-notification
// Definitions by: Kamil Rojewski <https://github.com/krojew/DefinitelyTyped>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace angular.uiNotification {
// Taken from angular to avoid dependency
interface IPromise<T> {
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
* The successCallBack may return IPromise<void> for when a $q.reject() needs to be returned
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => IPromise<TResult>|TResult): IPromise<TResult>;
/**
* Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.
*
* Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.
*/
finally(finallyCallback: () => any): IPromise<T>;
}
type XPosition = 'right'|'left'|'center';
type YPosition = 'top'|'bottom';
type MessageType = 'primary'|'info'|'success'|'warning'|'error';
interface IGlobalMessageOptions {
delay?: number;
startTop?: number;
startRight?: number;
verticalSpacing?: number;
horizontalSpacing?: number;
positionX?: XPosition;
positionY?: YPosition;
replaceMessage?: boolean;
templateUrl?: string;
onClose?: (element: any) => any;
closeOnClick?: boolean;
maxCount?: number;
}
interface IMessageOptions {
title?: string;
message?: string;
templateUrl?: string;
delay?: number;
type?: MessageType;
positionX?: XPosition;
positionY?: YPosition;
replaceMessage?: boolean;
closeOnClick?: boolean;
}
interface INotificationScope {
kill(isHard: boolean): void;
}
interface INotificationProvider {
setOptions(options: IGlobalMessageOptions): void;
}
type Message = string|IMessageOptions;
interface INotificationService {
primary(message: Message): IPromise<INotificationScope>;
info(message: Message): IPromise<INotificationScope>;
success(message: Message): IPromise<INotificationScope>;
warning(message: Message): IPromise<INotificationScope>;
error(message: Message): IPromise<INotificationScope>;
clearAll(): void;
(message: Message, type?: MessageType): IPromise<INotificationScope>;
}
}
+3 -2
View File
@@ -42,9 +42,10 @@ declare namespace angular.ui {
*/
topVisibleScope: ng.IRepeatScope;
/**
* calling this method reinitializes and reloads the scroller content.
* calling this method reinitializes and reloads the scroller content.
* @param startIndex is an integer indicating what item index the scroller will use to start the load process.
*/
reload(): void;
reload(startIndex?: number): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
+14 -3
View File
@@ -42,15 +42,20 @@ declare namespace angular.resource {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<IResource<any>>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): U;
actions?: IActionHash, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: any, options?: IResourceOptions): IResourceClass<T>;
actions?: IActionHash, options?: IResourceOptions): IResourceClass<T>;
}
// Hash of action descriptors allows custom action names
interface IActionHash {
[action: string]: IActionDescriptor
}
// Just a reference to facilitate describing new actions
@@ -186,6 +191,12 @@ declare namespace angular {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction<any>): IModule;
}
namespace auto {
interface IInjectorService {
get(name: '$resource'): ng.resource.IResourceService;
}
}
}
interface Array<T>
+19 -4
View File
@@ -1,6 +1,6 @@
// Type definitions for Angular JS 1.5
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -125,6 +125,7 @@ declare namespace angular {
isFunction(value: any): value is Function;
isNumber(value: any): value is number;
isObject(value: any): value is Object;
isObject<T>(value: any): value is T;
isString(value: any): value is string;
isUndefined(value: any): boolean;
lowercase(str: string): string;
@@ -1411,6 +1412,16 @@ declare namespace angular {
* Absolute or relative URL of the resource that is being requested.
*/
url: string;
/**
* Event listeners to be bound to the XMLHttpRequest object.
* To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
*/
eventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
/**
* Event listeners to be bound to the XMLHttpRequest upload object.
* To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
*/
uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
}
interface IHttpHeadersGetter {
@@ -1745,12 +1756,12 @@ declare namespace angular {
*/
$onInit?(): void;
/**
* Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
* { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as
* cloning the bound value to prevent accidental mutation of the outer value.
*/
$onChanges?(changesObj: {[property:string]: IChangesObject}): void;
$onChanges?(onChangesObj: IOnChangesObject): void;
/**
* Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,
* watches and event handlers.
@@ -1766,6 +1777,10 @@ declare namespace angular {
*/
$postLink?(): void;
}
interface IOnChangesObject {
[property: string]: IChangesObject;
}
interface IChangesObject {
currentValue: any;
+6
View File
@@ -946,9 +946,14 @@ declare namespace AtomCore {
registry: any;
repository: Object;
scopeName: string;
tokenizeLines: (text: string) => any;
// TBD
}
interface IGrammars {
grammarForScopeName(scope: string): IGrammar;
}
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
@@ -1302,6 +1307,7 @@ declare namespace AtomCore {
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
grammars: IGrammars;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="auth0-js.d.ts" />
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
});
auth0.login({
connection: 'google-oauth2',
popup: true,
popupOptions: {
width: 450,
height: 800
}
}, (err, profile, idToken, accessToken, state) => {
if (err) {
alert("something went wrong: " + err.message);
return;
}
alert('hello ' + profile.name);
});
+133
View File
@@ -0,0 +1,133 @@
// Type definitions for Auth0.js
// Project: https://github.com/auth0/auth0.js
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** Extensions to the browser Window object. */
interface Window {
/** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */
token: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: Function): void;
decodeJwt(jwt: string): any;
login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void;
loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
logout(query: string): void;
getConnections(callback?: Function): void;
refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getProfile(id_token: string, callback?: Function): Auth0UserProfile;
getSSOData(withActiveDirectories: any, callback?: Function): void;
parseHash(hash: string): Auth0DecodedHash;
signup(options: Auth0SignupOptions, callback: Function): void;
validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void;
}
/** Represents constructor options for the Auth0 client. */
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLocationHash?: boolean;
domain: string;
forceJSONP?: boolean;
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;
locale: string;
name: string;
nickname: string;
picture: string;
user_id: string;
/** Represents one or more Identities that may be associated with the User. */
identities: Auth0Identity[];
user_metadata?: any;
app_metadata?: any;
}
/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */
interface MicrosoftUserProfile extends Auth0UserProfile {
emails: string[];
}
/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */
interface AdfsUserProfile extends Auth0UserProfile {
issuer: string;
}
/** Represents multiple identities assigned to a user. */
interface Auth0Identity {
access_token: string;
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
interface Auth0DecodedHash {
access_token: string;
id_token: string;
profile: Auth0UserProfile;
state: any;
}
interface Auth0PopupOptions {
width: number;
height: number;
}
interface Auth0LoginOptions {
auto_login?: boolean;
connection?: string;
email?: string;
username?: string;
password?: string;
popup?: boolean;
popupOptions?: Auth0PopupOptions;
}
interface Auth0SignupOptions extends Auth0LoginOptions {
auto_login: boolean;
}
interface Auth0Error {
code: any;
details: any;
name: string;
message: string;
status: any;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
expires_in: string;
/** The JWT for delegated access. */
id_token: string;
/** The type of token being returned. Possible values: "Bearer" */
token_type: string;
}
declare var Auth0: Auth0Static;
declare module "auth0-js" {
export = Auth0
}
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="../auth0-js/auth0-js.d.ts" />
/// <reference path="auth0.lock.d.ts" />
const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID";
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Brian Caruso <https://github.com/carusology>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="../auth0-js/auth0-js.d.ts" />
interface Auth0LockAdditionalSignUpFieldOption {
value: string;
+1 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="../auth0-js/auth0-js.d.ts" />
/// <reference path="auth0.widget.d.ts" />
var widget: Auth0WidgetStatic = new Auth0Widget({
+1 -1
View File
@@ -3,7 +3,7 @@
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="../auth0-js/auth0-js.d.ts" />
interface Auth0WidgetStatic {
+48 -20
View File
@@ -1,23 +1,51 @@
/// <reference path="../auth0/auth0.d.ts" />
/// <reference path="auth0.d.ts" />
var auth0 = new Auth0({
domain: 'mine.auth0.com',
clientID: 'dsa7d77dsa7d7',
callbackURL: 'http://my-app.com/callback',
callbackOnLocationHash: true
import * as auth0 from 'auth0';
const management = new auth0.ManagementClient({
token: '{YOUR_API_V2_TOKEN}',
domain: '{YOUR_ACCOUNT}.auth0.com'
});
auth0.login({
connection: 'google-oauth2',
popup: true,
popupOptions: {
width: 450,
height: 800
}
}, (err, profile, idToken, accessToken, state) => {
if (err) {
alert("something went wrong: " + err.message);
return;
}
alert('hello ' + profile.name);
});
const auth = new auth0.AuthenticationClient({
domain: '{YOUR_ACCOUNT}.auth0.com',
clientId: '{OPTIONAL_CLIENT_ID}'
});
// Using a callback.
management.getUsers((err: Error, users: auth0.User[]) => {
if (err) {
// Handle error.
}
console.log(users);
});
// Using a Promise.
management
.getUsers()
.then((users) => {
console.log(users);
})
.catch((err) => {
// Handle the error.
});
management
.createUser({
connection: 'My-Connection',
email: 'hi@me.co',
}).then((user) => {
console.log(user);
}).catch((err) => {
// Handle the error.
});
auth
.requestChangePasswordEmail({
connection: 'My-Connection',
email: 'hi@me.co',
}).then((response) => {
console.log(response);
}).catch((err) => {
// Handle the error.
});
+81 -118
View File
@@ -1,132 +1,95 @@
// Type definitions for Auth0.js
// Project: http://auth0.com
// Definitions by: Robert McLaws <https://github.com/advancedrei>
// Type definitions for auth0 v2.3.1
// Project: https://github.com/auth0/node-auth0
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/** Extensions to the browser Window object. */
interface Window {
/** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */
/// <reference path="../bluebird/bluebird.d.ts" />
declare module "auth0" {
import * as Promise from 'bluebird';
export interface ManagementClientOptions {
token: string;
}
domain?: string;
}
/** This is the interface for the main Auth0 client. */
interface Auth0Static {
new(options: Auth0ClientOptions): Auth0Static;
changePassword(options: any, callback?: Function): void;
decodeJwt(jwt: string): any;
login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void;
loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void;
logout(query: string): void;
getConnections(callback?: Function): void;
refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void;
getProfile(id_token: string, callback?: Function): Auth0UserProfile;
getSSOData(withActiveDirectories: any, callback?: Function): void;
parseHash(hash: string): Auth0DecodedHash;
signup(options: Auth0SignupOptions, callback: Function): void;
validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void;
}
/** Represents constructor options for the Auth0 client. */
interface Auth0ClientOptions {
clientID: string;
callbackURL: string;
callbackOnLocationHash?: boolean;
domain: string;
forceJSONP?: boolean;
}
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
family_name: string;
gender: string;
given_name: string;
locale: string;
name: string;
nickname: string;
picture: string;
user_id: string;
/** Represents one or more Identities that may be associated with the User. */
identities: Auth0Identity[];
user_metadata?: any;
app_metadata?: any;
}
/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */
interface MicrosoftUserProfile extends Auth0UserProfile {
emails: string[];
}
/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */
interface Office365UserProfile extends Auth0UserProfile {
tenantid: string;
upn: string;
}
/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */
interface AdfsUserProfile extends Auth0UserProfile {
issuer: string;
}
/** Represents multiple identities assigned to a user. */
interface Auth0Identity {
access_token: string;
export interface UserData {
connection: string;
isSocial: boolean;
provider: string;
user_id: string;
}
interface Auth0DecodedHash {
access_token: string;
id_token: string;
profile: Auth0UserProfile;
state: any;
}
interface Auth0PopupOptions {
width: number;
height: number;
}
interface Auth0LoginOptions {
auto_login?: boolean;
connection?: string;
email?: string;
username?: string;
password?: string;
popup?: boolean;
popupOptions?: Auth0PopupOptions;
}
phone_number?: string;
user_metadata?: {};
email_verified?: boolean;
app_metadata?: {};
}
interface Auth0SignupOptions extends Auth0LoginOptions {
auto_login: boolean;
}
export interface GetUsersData {
per_page?: number;
page?: number;
include_totals?: boolean;
sort?: string;
connection?: string;
fields?: string;
include_fields?: boolean;
q?: string;
search_engine?: string;
}
interface Auth0Error {
code: any;
details: any;
name: string;
message: string;
status: any;
}
export interface User {
email?: string;
email_verified?: boolean;
username?: string;
phone_number?: string;
phone_verified?: boolean;
user_id?: string;
created_at?: string;
updated_at?: string;
identities?: Identity[];
app_metadata?: {};
user_metadata?: {};
picture?: string;
name?: string;
nickname?: string;
multifactor?: string[];
last_ip?: string;
last_login?: string;
logins_count?: number;
blocked?: boolean;
}
/** Represents the response from an API Token Delegation request. */
interface Auth0DelegationToken {
/** The length of time in seconds the token is valid for. */
expires_in: string;
/** The JWT for delegated access. */
id_token: string;
/** The type of token being returned. Possible values: "Bearer" */
token_type: string;
}
export interface Identity {
connection: string;
user_id: string;
provider: string;
isSocial: boolean;
}
declare var Auth0: Auth0Static;
export class ManagementClient {
constructor(options: ManagementClientOptions);
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
}
export interface AuthenticationClientOptions {
clientId?: string;
domain: string;
}
export interface RequestChangePasswordEmailData {
connection: string;
email: string;
}
export class AuthenticationClient {
constructor(options: AuthenticationClientOptions);
requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise<string>;
requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void;
}
declare module "auth0" {
export = Auth0
}
@@ -0,0 +1,43 @@
/// <reference path="autobind-decorator.d.ts" />
import autobind = require('autobind-decorator');
class Test {
public static what: string = 'static';
@autobind
public static test(): void {
console.log(this.what);
}
public constructor(public what: string) {
this.what = what;
}
@autobind
public test(): void {
console.warn(this.what);
}
}
const tester: Test = new Test('bind');
const { test } = tester;
tester.test(); // warns 'bind'.
test(); // warns 'bind'.
Test.test(); // logs 'static'.
@autobind
class Component {
public constructor(private someMember: string) {
this.someMember = someMember;
}
public someMethod(): void {
console.error(this.someMember);
}
}
const component: Component = new Component('React vs Angular2');
const { someMethod } = component;
component.someMethod(); // errors 'React vs Angular2'
someMethod(); // errors 'React vs Angular2'
+10
View File
@@ -0,0 +1,10 @@
// Type definitions for autobind-decorator v1.3.3
// Project: https://github.com/andreypopp/autobind-decorator
// Definitions by: Ivo Stratev <https://github.com/NoHomey/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'autobind-decorator' {
function autobind<TFunction extends Function>(target: TFunction): TFunction | void;
function autobind<T extends Function>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;
export = autobind;
}
@@ -0,0 +1 @@
--experimentalDecorators
+27 -36
View File
@@ -4,46 +4,37 @@ import lambda = require('aws-lambda');
var str: string;
var date: Date;
var sns: lambda.SNS;
var kinesis: lambda.Kinesis;
var recordsList: lambda.Record[];
var anyObj: any;
var num: number;
/* Records */
var records: lambda.Records;
recordsList = records.Records;
/* Record */
var record: lambda.Record;
str = record.EventVersion;
str = record.EventSubscriptionArn;
str = record.EnventSource;
sns = record.Sns;
kinesis = record.kinesis;
/* SNS */
str = sns.Type;
str = sns.MessageId;
str = sns.TopicArn;
str = sns.Subject;
str = sns.Message;
date = sns.Timestamp;
/* Kinesis */
var kinesis: lambda.Kinesis;
str = kinesis.data;
var identity: lambda.CognitoIdentity;
var error: Error;
var b: boolean;
var clientCtx: lambda.ClientContext;
/* Context */
var context: lambda.Context;
context.log(str, anyObj);
context.fail(str);
context.succeed(str);
context.succeed(anyObj);
context.succeed(str, anyObj);
b = context.callbackWaitsForEmptyEventLoop;
str = context.functionName;
str = context.functionVersion;
str = context.invokedFunctionArn;
num = context.memoryLimitInMB;
str = context.awsRequestId;
num = context.getRemainingTimeInMillis();
str = context.logGroupName;
str = context.logStreamName;
identity = context.identity;
clientCtx = context.clientContext;
/* CognitoIdentity */
var identity: lambda.CognitoIdentity;
str = identity.cognitoIdentityId;
str = identity.cognitoIdentityPoolId;
/* Callback */
function callback(cb: lambda.Callback) {
cb();
cb(null);
cb(error);
cb(null, anyObj);
}
+56 -31
View File
@@ -1,43 +1,68 @@
// Type definitions for AWS Lambda
// Project: http://docs.aws.amazon.com/lambda
// Definitions by: Michael Skarum <https://github.com/skarum>
// Definitions by: James Darbyshire <https://github.com/darbio/aws-lambda-typescript>, Michael Skarum <https://github.com/skarum>, Stef Heyenrath <https://github.com/StefH/DefinitelyTyped>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "aws-lambda" {
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
interface Context {
// Properties
callbackWaitsForEmptyEventLoop: boolean;
functionName: string;
functionVersion: string;
invokedFunctionArn: string;
memoryLimitInMB: number;
awsRequestId: string;
logGroupName: string;
logStreamName: string;
identity?: CognitoIdentity;
clientContext?: ClientContext;
// Functions
getRemainingTimeInMillis(): number;
export interface Records {
Records: Record[];
}
interface Record {
EventVersion: string;
EventSubscriptionArn: string;
EnventSource: string;
Sns: SNS;
kinesis: Kinesis;
}
interface SNS {
Type: string;
MessageId: string;
TopicArn: string;
Subject: string;
Message: string;
Timestamp: Date;
}
interface Kinesis {
data: string;
}
export interface Context {
// Functions for compatibility with earlier Node.js Runtime v0.10.42
log(message: string, object: any): void;
fail(message: string): void;
succeed(message: string): void;
succeed(object: any): void;
succeed(message: string, object: any): void;
awsRequestId: string;
getRemainingTimeInMillis(): number;
succeed(message: string, object: any): void;
}
export type Callback = (error?: Error, message?: string) => void;
interface CognitoIdentity {
cognitoIdentityId: string;
cognitoIdentityPoolId: string;
}
interface ClientContext {
client: ClientContextClient;
Custom?: any;
env: ClientContextEnv;
}
interface ClientContextClient {
installationId: string;
appTitle: string;
appVersionName: string;
appVersionCode: string;
appPackageName: string;
}
interface ClientContextEnv {
platformVersion: string;
platform: string;
make: string;
model: string;
locale: string;
}
/**
* Optional callback parameter.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
*
* @param error – an optional parameter that you can use to provide results of the failed Lambda function execution.
* @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
*/
export type Callback = (error?: Error, result?: any) => void;
}
+7 -1
View File
@@ -226,7 +226,7 @@ declare module "aws-sdk" {
constructor(options?: any);
endpoint: Endpoint;
getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void;
getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
@@ -235,6 +235,12 @@ declare module "aws-sdk" {
upload(params?: s3.PutObjectRequest, options?: s3.UploadOptions, callback?: (err: Error, data: any) => void): void;
listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void;
listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void;
waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
uploadPart(params: any, callback: (err: Error, data: any) => void): void;
listParts(params: any, callback: (err: Error, data: any) => void): void;
completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
}
export class STS {
+91
View File
@@ -0,0 +1,91 @@
/// <reference path="axe-core.d.ts" />
var context:any = document
var $fixture:any = {}
// axe.a11yCheck config
axe.a11yCheck(context, {}, (results) => {
// axe's results object
console.log(results.passes.length)
console.log(results.violations.length)
});
// axe.a11yCheck include/exclude
axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => {
console.log(results)
})
axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => {
console.log(results)
})
var tagConfigRunOnly: axe.RunOnly = {
type: 'tag',
values: ['wcag2a']
}
var tagConfig = {
runOnly: tagConfigRunOnly
}
axe.a11yCheck(context, tagConfig, (results) => {
console.log(results)
})
var includeExcludeTagsRunOnly: axe.RunOnly = {
type: 'tags',
value: {
include: ['wcag2a', 'wcag2aa'],
exclude: ['experimental']
}
}
var includeExcludeTagsConfig = {
runOnly: includeExcludeTagsRunOnly
}
axe.a11yCheck(context, includeExcludeTagsConfig, (results) => {
console.log(results)
})
var someRulesConfig = {
rules: {
"color-contrast": {enabled: 'false'},
"heading-order": {enabled: 'true'}
}
}
axe.a11yCheck(context, someRulesConfig, (results) => {
console.log(results)
})
// axe.configure
var spec: axe.Spec = {
branding: {
brand: 'foo',
application: 'bar'
},
reporter: 'v1',
checks: [{
id: 'custom-check',
evaluate: function() {
return true
}
}],
rules: [{
id: 'custom-rule',
any: ['custom-check']
}]
}
axe.configure(spec)
axe.reset()
axe.getRules(['wcag2aa'])
typeof axe.getRules() === 'object'
// Plugins
var pluginSrc: axe.AxePlugin = {
id: 'doStuff',
run: (data:any, callback:Function) => {
callback()
},
commands: [{
id: 'run-doStuff',
callback: (data:any, callback:Function) => {
axe.plugins['doStuff'].run(data, callback)
}
}]
}
axe.registerPlugin(pluginSrc)
axe.cleanup()
+159
View File
@@ -0,0 +1,159 @@
// Type definitions for axe-core 2.0.5
// Project: https://github.com/dequelabs/axe-core
// Definitions by: Marcy Sutton <https://github.com/marcysutton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace axe {
export type ImpactValue = "minor" | "moderate" | "serious" | "critical";
export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice";
export type ReporterVersion = "v1" | "v2";
export type RunOnlyType = "rule" | "rules" | "tag" | "tags";
export interface ElementContext {
node?: Object,
selector?: string,
include?: any[],
exclude?: any[]
}
export interface RunOnly {
type: RunOnlyType,
value?: {
include?: string[],
exclude?: string[]
}
values?: TagValue[]
}
export interface AxeResults {
url: string,
timestamp: string,
passes: Pass[],
violations: Violation[]
}
export interface Pass {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface Violation {
description: string,
help: string,
helpUrl: string,
id: string,
impact: ImpactValue,
tags: TagValue[],
nodes: NodeResult[]
}
export interface NodeResult {
html: string,
impact: ImpactValue,
target: string[],
any: CheckResult[],
all: CheckResult[],
none: CheckResult[]
}
export interface CheckResult {
id: string,
impact: string,
message: string,
data: any,
relatedNodes?: RelatedNode[]
}
export interface RelatedNode {
target: string[],
html: string
}
export interface Spec {
branding?: {
brand: string,
application: string
},
reporter?: ReporterVersion,
checks?: Check[],
rules?: Rule[]
}
export interface Check {
id: string,
evaluate: Function,
after?: Function,
options?: any,
matches?: string,
enabled?: boolean
}
export interface Rule {
id: string,
selector?: string,
excludeHidden?: boolean,
enabled?: boolean,
pageLevel?: boolean,
any?: string[],
all?: string[],
none?: string[],
tags?: string[],
matches?: string
}
export interface AxePlugin {
id: string,
run(...args:any[]): any,
commands: {
id: string,
callback(...args:any[]): void
}[],
cleanup?(callback:Function): void
}
export let plugins: any
/**
* Starts analysis on the current document and its subframes
*
* @param {Object} context The `Context` specification object @see Context
* @param {Array} options Options passed into rules or checks, temporarily modifyint them.
* @param {Function} callback The function to invoke when analysis is complete.
* @returns {Object} results The aXe results object
*/
export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults
/**
* Method for configuring the data format used by aXe. Helpful for adding new
* rules, which must be registered with the library to execute.
* @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data
*/
export function configure(spec: Spec): void
/**
* Searches and returns rules that contain a tag in the list of tags.
* @param {Array} tags Optional array of tags
* @return {Array} Array of rules
*/
export function getRules(tags?: string[]): Object[]
/**
* Restores the default axe configuration
*/
export function reset(): void
/**
* Function to register a plugin configuration in document and its subframes
* @param {Object} plugin A plugin configuration object
*/
export function registerPlugin(plugin: AxePlugin): void
/**
* Function to clean up plugin configuration in document and its subframes
*/
export function cleanup(): void
}
// axe is also available as a module
declare module "axe-core" {
export = axe;
}
+18 -1
View File
@@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
table.access = undefined;
table.access = 'authenticated';
table.read.access = 'anonymous';
table.update.access = 'disabled';
table.delete.access = 'authenticated';
table.insert.access = 'authenticated';
// 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();
@@ -84,4 +91,14 @@ mobileApps.logger.debug('a debug message')
// Query
queries.create('table').where({ x: 10 }).select('col1,col2');
mobileApps.query.create('table');
mobileApps.query.create('table');
// custom sql query
mobileApp.api.add('query', { authorize: true, get: (req, res, next) => {
req.azureMobile.data.execute({
sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete",
parameters: [
{ name: 'complete', value: 1 }
]
}).then(x => {});
}, delete: function () {} });
+20 -1
View File
@@ -47,6 +47,7 @@ declare namespace Azure.MobileApps {
interface Table {
authorize?: boolean;
access?: AccessType;
autoIncrement?: boolean;
dynamicSchema?: boolean;
name: string;
@@ -66,8 +67,11 @@ declare namespace Azure.MobileApps {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
access: AccessType;
}
type AccessType = 'anonymous' | 'authenticated' | 'disabled';
interface Tables {
configuration: Configuration;
add(name: string, definition?: Table | TableDefinition): void;
@@ -215,7 +219,7 @@ declare namespace Azure.MobileApps {
item: any;
req: Express.Request;
res: Express.Response;
data: (table: TableDefinition) => Data.Table;
data: ContextData;
tables: (tableName: string) => Data.Table;
user: User;
push: typeof nh;
@@ -223,6 +227,21 @@ declare namespace Azure.MobileApps {
execute(): Thenable<any>;
}
interface ContextData {
(table: TableDefinition): Data.Table;
execute(q: SqlQueryDefinition): Thenable<any>;
}
interface SqlQueryDefinition {
sql: string;
parameters?: SqlParameterDefinition[];
}
interface SqlParameterDefinition {
name: string;
value: any;
}
interface TableDefinition {
authorize?: boolean;
autoIncrement?: boolean;
@@ -17,7 +17,7 @@ declare namespace Microsoft.WindowsAzure {
login(provider: string, token: string): asyncPromise;
login(provider: string, callback: (error: any, user: User) => void ): void;
login(provider: string): asyncPromise;
logout(): void;
logout(): asyncPromise;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error: any, response: any) => void) => void, callback: (error: any, response: any) => void) => void): MobileServiceClient;
/**
+88
View File
@@ -0,0 +1,88 @@
/// <reference path="backlog-js.d.ts" />
import * as backlogjs from 'backlog-js';
const host = 'example.backlog.jp';
const apiKey = 'apiKey';
const clientId = 'clientId';
const clientSecret = 'clientSecret';
const redirectUri = 'redirectUri';
const state = 'state';
const code = 'code';
const refreshToken = 'refreshToken';
const configure = { host, apiKey }
const credentials = { clientId, clientSecret }
const oauth2 = new backlogjs.OAuth2(credentials);
oauth2.getAuthorizationURL({ host, redirectUri, state });
oauth2.getAccessToken({ host, code, redirectUri }).then(data => {}).catch(err => {});
oauth2.refreshAccessToken({ host, refreshToken }).then(data => {}).catch(err => {});
const backlog = new backlogjs.Backlog(configure);
backlog.getSpace().then(data => { }).catch(err => { });
backlog.getSpaceActivities({
activityTypeId: [
backlogjs.Option.ActivityType.IssueCreated,
backlogjs.Option.ActivityType.IssueUpdated
],
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getSpaceDiskUsage().then(data => { }).catch(err => { });
backlog.getSpaceIcon().then(data => { }).catch(err => { });
backlog.postSpaceAttachment(new FormData()).then(data => { }).catch(err => { });
backlog.getUsers().then(data => { }).catch(err => { });
backlog.getUser(1).then(data => { }).catch(err => { });
backlog.postUser({
userId: 'string',
password: 'string',
name: 'string',
mailAddress: 'string',
roleType: backlogjs.Option.User.RoleType.Admin
}).then(data => { }).catch(err => { });
backlog.patchUser(1, {
password: 'string',
name: 'string',
mailAddress: 'string',
roleType: backlogjs.Option.User.RoleType.Admin
}).then(data => { }).catch(err => { });
backlog.deleteUser(1).then(data => { }).catch(err => { });
backlog.getMyself().then(data => { }).catch(err => { });
backlog.getUserActivities(1, {
activityTypeId: [
backlogjs.Option.ActivityType.IssueCreated,
backlogjs.Option.ActivityType.IssueUpdated
],
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getUserStars(1, {
minId: 1,
maxId: 2,
count: 3,
order: "asc"
}).then(data => { }).catch(err => { });
backlog.getUserStarsCount(1, {
since: 'YYYY-MM-DD',
until: 'YYYY-MM-DD'
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedIssues({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedProjects({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getRecentlyViewedWikis({
order: 'asc',
offset: 1,
count: 2
}).then(data => { }).catch(err => { });
backlog.getUserIcon(1).then(data => {}).catch(err => {});
+695
View File
@@ -0,0 +1,695 @@
// Type definitions for backlog-js 0.9.0
// Project: https://github.com/nulab/backlog-js
// Definitions by: Yuichi Watanabe <https://github.com/vvatanabe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../isomorphic-fetch/isomorphic-fetch.d.ts" />
/// <reference path="../node_modules/typescript/lib/lib.es6.d.ts" />
declare module 'backlog-js' {
class Request {
private configure;
constructor(configure: {
host: string;
apiKey?: string;
accessToken?: string;
timeout?: number;
});
get<T>(path: string, params?: any): Promise<T>;
post<T>(path: string, params?: any): Promise<T>;
put<T>(path: string, params: any): Promise<T>;
patch<T>(path: string, params: any): Promise<T>;
delete<T>(path: string, params?: any): Promise<T>;
request(options: {
method: string;
path: string;
params?: Params | FormData;
}): Promise<IResponse>;
checkStatus(response: IResponse): Promise<IResponse>;
parseJSON<T>(response: IResponse): Promise<T>;
private toFormData(params);
private toQueryString(params);
webAppBaseURL: string;
restBaseURL: string;
}
type Params = {
[index: string]: number | string | number[] | string[];
};
export class Backlog extends Request {
constructor(configure: {
host: string;
apiKey?: string;
accessToken?: string;
timeout?: number;
});
getSpace(): Promise<any>;
getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise<any>;
getSpaceNotification(): Promise<any>;
putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise<any>;
getSpaceDiskUsage(): Promise<any>;
getSpaceIcon(): Promise<Entity.File.FileData>;
postSpaceAttachment(form: FormData): Promise<IResponse>;
getUsers(): Promise<any>;
getUser(userId: number): Promise<any>;
postUser(params: Option.User.PostUserParams): Promise<any>;
patchUser(userId: number, params: Option.User.PatchUserParams): Promise<any>;
deleteUser(userId: number): Promise<any>;
getMyself(): Promise<any>;
getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise<any>;
getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise<any>;
getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise<any>;
getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise<any>;
getUserIcon(userId: number): Promise<Entity.File.FileData>;
getGroups(params: Option.Group.GetGroupsParams): Promise<any>;
postGroups(params: Option.Group.PostGroupsParams): Promise<any>;
getGroup(groupId: number): Promise<any>;
patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise<any>;
deleteGroup(groupId: number): Promise<any>;
getStatuses(): Promise<any>;
getResolutions(): Promise<any>;
getPriorities(): Promise<any>;
postProject(params: Option.Project.PostProjectParams): Promise<any>;
getProjects(params?: Option.Project.GetProjectsParams): Promise<any>;
getProject(projectIdOrKey: string): Promise<any>;
patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise<any>;
deleteProject(projectIdOrKey: string): Promise<any>;
getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise<any>;
getProjectUsers(projectIdOrKey: string): Promise<any>;
deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise<any>;
postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise<any>;
getProjectAdministrators(projectIdOrKey: string): Promise<any>;
deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise<any>;
getIssueTypes(projectIdOrKey: string): Promise<any>;
postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise<any>;
patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise<any>;
deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise<any>;
getCategories(projectIdOrKey: string): Promise<any>;
postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise<any>;
patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise<any>;
deleteCategories(projectIdOrKey: string, id: number): Promise<any>;
getVersions(projectIdOrKey: string): Promise<any>;
postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise<any>;
patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise<any>;
deleteVersions(projectIdOrKey: string, id: number): Promise<any>;
getCustomFields(projectIdOrKey: string): Promise<any>;
postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise<any>;
patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise<any>;
deleteCustomField(projectIdOrKey: string, id: number): Promise<any>;
postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise<any>;
deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise<any>;
getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise<any>;
getProjectsDiskUsage(projectIdOrKey: string): Promise<any>;
getWebhooks(projectIdOrKey: string): Promise<any>;
postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise<any>;
getWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise<any>;
deleteWebhook(projectIdOrKey: string, webhookId: string): Promise<any>;
postIssue(params: Option.Issue.PostIssueParams): Promise<any>;
patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise<any>;
getIssues(params?: Option.Issue.GetIssuesParams): Promise<any>;
getIssue(issueIdOrKey: string): Promise<any>;
getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise<any>;
deleteIssuesCount(issueIdOrKey: string): Promise<any>;
getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise<any>;
postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise<any>;
getIssueCommentsCount(issueIdOrKey: string): Promise<any>;
getIssueComment(issueIdOrKey: string, commentId: number): Promise<any>;
patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise<any>;
getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise<any>;
postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise<any>;
getIssueAttachments(issueIdOrKey: string): Promise<any>;
deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise<any>;
getIssueSharedFiles(issueIdOrKey: string): Promise<any>;
linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise<any>;
unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise<any>;
getWikis(projectIdOrKey: number): Promise<any>;
getWikisCount(projectIdOrKey: number): Promise<any>;
getWikisTags(projectIdOrKey: number): Promise<any>;
postWiki(params: Option.Wiki.PostWikiParams): Promise<any>;
getWiki(wikiId: number): Promise<any>;
patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise<any>;
deleteWiki(wikiId: number, mailNotify: boolean): Promise<any>;
getWikisAttachments(wikiId: number): Promise<any>;
postWikisAttachments(wikiId: number, attachmentId: number[]): Promise<any>;
deleteWikisAttachments(wikiId: number, attachmentId: number): Promise<any>;
getWikisSharedFiles(wikiId: number): Promise<any>;
linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise<any>;
unlinkWikisSharedFiles(wikiId: number, id: number): Promise<any>;
getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise<any>;
getWikisStars(wikiId: number): Promise<any>;
postStar(params: Option.Project.PostStarParams): Promise<any>;
getNotifications(params: Option.Notification.GetNotificationsParams): Promise<any>;
getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise<any>;
resetNotificationsMarkAsRead(): Promise<any>;
markAsReadNotification(id: number): Promise<any>;
getGitRepositories(projectIdOrKey: string): Promise<any>;
getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise<any>;
getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise<any>;
postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise<any>;
getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise<any>;
getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise<any>;
postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise<any>;
getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise<any>;
getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise<any>;
deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<any>;
getProjectIcon(projectIdOrKey: string): Promise<Entity.File.FileData>;
getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise<Entity.File.FileData>;
getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise<Entity.File.FileData>;
getWikiAttachment(wikiId: number, attachmentId: number): Promise<Entity.File.FileData>;
getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise<Entity.File.FileData>;
private download(path);
private upload(path, params);
private parseFileData(response);
}
export class OAuth2 {
private credentials;
private timeout;
constructor(credentials: Option.OAuth2.Credentials, timeout?: number);
getAuthorizationURL(options: {
host: string;
redirectUri?: string;
state?: string;
}): string;
getAccessToken(options: {
host: string;
code: string;
redirectUri?: string;
}): Promise<Entity.OAuth2.AccessToken>;
refreshAccessToken(options: {
host: string;
refreshToken: string;
}): Promise<Entity.OAuth2.AccessToken>;
}
import { PassThrough } from 'stream';
export namespace Entity {
export namespace File {
export type FileData = NodeFileData | BrowserFileData;
export interface NodeFileData {
body: PassThrough;
url: string;
filename: string;
}
export interface BrowserFileData {
body: any;
url: string;
blob?: () => Promise<Blob>;
}
}
export namespace OAuth2 {
export interface AccessToken {
access_token: string;
token_type: string;
expires_in: number;
refresh_token: string;
}
}
}
export namespace Option {
export type Order = "asc" | "desc";
export enum ActivityType {
Undefined = -1,
IssueCreated = 1,
IssueUpdated = 2,
IssueCommented = 3,
IssueDeleted = 4,
WikiCreated = 5,
WikiUpdated = 6,
WikiDeleted = 7,
FileAdded = 8,
FileUpdated = 9,
FileDeleted = 10,
SvnCommitted = 11,
GitPushed = 12,
GitRepositoryCreated = 13,
IssueMultiUpdated = 14,
ProjectUserAdded = 15,
ProjectUserRemoved = 16,
NotifyAdded = 17,
PullRequestAdded = 18,
PullRequestUpdated = 19,
PullRequestCommented = 20,
PullRequestMerged = 21,
}
export namespace Notification {
export interface GetNotificationsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetNotificationsCountParams {
alreadyRead: boolean;
resourceAlreadyRead: boolean;
}
}
export namespace Space {
export interface GetActivitiesParams {
activityTypeId?: ActivityType[];
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PutSpaceNotificationParams {
content: string;
}
}
export namespace User {
export interface PostUserParams {
userId: string;
password: string;
name: string;
mailAddress: string;
roleType: RoleType;
}
export interface PatchUserParams {
password?: string;
name?: string;
mailAddress?: string;
roleType?: RoleType;
}
export enum RoleType {
Admin = 1,
User = 2,
Reporter = 3,
Viewer = 4,
GuestReporter = 5,
GuestViewer = 6,
}
export interface GetUserActivitiesParams {
activityTypeId?: ActivityType[];
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetUserStarsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface GetUserStarsCountParams {
since?: string;
until?: string;
}
export interface GetRecentlyViewedParams {
order?: Order;
offset?: number;
count?: number;
}
}
export namespace Group {
export interface GetGroupsParams {
order?: Order;
offset?: number;
count?: number;
}
export interface PostGroupsParams {
name: string;
members?: string[];
}
export interface PatchGroupParams {
name?: string;
members?: string[];
}
}
export namespace Project {
export type TextFormattingRule = "backlog" | "markdown";
export interface PostProjectParams {
name: string;
key: string;
chartEnabled: boolean;
projectLeaderCanEditProjectLeader?: boolean;
subtaskingEnabled: boolean;
textFormattingRule: TextFormattingRule;
}
export interface PatchProjectParams {
name?: string;
key?: string;
chartEnabled?: boolean;
subtaskingEnabled?: boolean;
projectLeaderCanEditProjectLeader?: boolean;
textFormattingRule?: TextFormattingRule;
archived?: boolean;
}
export interface GetProjectsParams {
archived?: boolean;
all?: boolean;
}
export interface DeleteProjectUsersParams {
userId: number;
}
export interface PostProjectAdministrators {
userId: number;
}
export interface DeleteProjectAdministrators {
userId: number;
}
export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665";
export interface PostIssueTypeParams {
name: string;
color: IssueTypeColor;
}
export interface PatchIssueTypeParams {
name?: string;
color?: IssueTypeColor;
}
export interface DeleteIssueTypeParams {
substituteIssueTypeId: number;
}
export interface PostCategoriesParams {
name: string;
}
export interface PatchCategoriesParams {
name: string;
}
export interface PostVersionsParams {
name: string;
description: string;
startDate: string;
releaseDueDate: string;
}
export interface PatchVersionsParams {
name: string;
description?: string;
startDate?: string;
releaseDueDate?: string;
archived?: boolean;
}
export interface PostCustomFieldParams {
typeId: FieldType;
name: string;
applicableIssueTypes?: number[];
description?: string;
required?: boolean;
}
export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams {
min?: number;
max?: number;
initialValue?: number;
unit?: string;
}
export interface PostCustomFieldWithDateParams extends PostCustomFieldParams {
min?: string;
max?: string;
initialValueType?: number;
initialDate?: string;
initialShift?: number;
}
export interface PostCustomFieldWithListParams extends PostCustomFieldParams {
items?: string[];
allowInput?: boolean;
allowAddItem?: boolean;
}
export interface PatchCustomFieldParams {
name?: string;
applicableIssueTypes?: number[];
description?: string;
required?: boolean;
}
export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams {
min?: number;
max?: number;
initialValue?: number;
unit?: string;
}
export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams {
min?: string;
max?: string;
initialValueType?: number;
initialDate?: string;
initialShift?: number;
}
export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams {
items?: string[];
allowInput?: boolean;
allowAddItem?: boolean;
}
export interface PostCustomFieldItemParams {
name: string;
}
export interface PatchCustomFieldItemParams {
name: string;
}
export interface GetSharedFilesParams {
order?: Order;
offset?: number;
count?: number;
}
export interface PostWebhookParams {
name?: string;
description?: string;
hookUrl?: string;
allEvent?: boolean;
activityTypeIds?: number[];
}
export interface PatchWebhookParams {
name?: string;
description?: string;
hookUrl?: string;
allEvent?: boolean;
activityTypeIds?: number[];
}
export enum FieldType {
Text = 1,
TextArea = 2,
Numeric = 3,
Date = 4,
SingleList = 5,
MultipleList = 6,
CheckBox = 7,
Radio = 8,
}
export interface PostStarParams {
issueId?: number;
commentId?: number;
wikiId?: number;
pullRequestId?: number;
pullRequestCommentId?: number;
}
}
export namespace Issue {
export interface PostIssueParams {
projectId: number;
summary: string;
priorityId: number;
issueTypeId: number;
parentIssueId?: number;
description?: string;
startDate?: string;
dueDate?: string;
estimatedHours?: number;
actualHours?: number;
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
[customField_: string]: any;
}
export interface PatchIssueParams {
summary?: string;
parentIssueId?: number;
description?: string;
statusId?: number;
resolutionId?: number;
startDate?: string;
dueDate?: string;
estimatedHours?: number;
actualHours?: number;
issueTypeId?: number;
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
priorityId?: number;
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
comment?: string;
[customField_: string]: any;
}
export interface GetIssuesParams {
projectId?: number[];
issueTypeId?: number[];
categoryId?: number[];
versionId?: number[];
milestoneId?: number[];
statusId?: number[];
priorityId?: number[];
assigneeId?: number[];
createdUserId?: number[];
resolutionId?: number[];
parentChild?: ParentChildType;
attachment?: boolean;
sharedFile?: boolean;
sort?: SortKey;
order?: Order;
offset?: number;
count?: number;
createdSince?: string;
createdUntil?: string;
updatedSince?: string;
updatedUntil?: string;
startDateSince?: string;
startDateUntil?: string;
dueDateSince?: string;
dueDateUntil?: string;
id?: number[];
parentIssueId?: number[];
keyword: string;
[customField_: string]: any;
}
export enum ParentChildType {
All = 0,
NotChild = 1,
Child = 2,
NotChildNotParent = 3,
Parent = 4,
}
export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue";
export interface GetIssueCommentsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PostIssueCommentsParams {
content: string;
notifiedUserId?: number[];
attachmentId?: number[];
}
export interface PatchIssueCommentParams {
content: string;
}
export interface IssueCommentNotifications {
notifiedUserId: number[];
}
export interface LinkIssueSharedFilesParams {
fileId: number[];
}
}
export namespace PullRequest {
export interface GetPullRequestsParams {
statusId?: number[];
assigneeId?: number[];
issueId?: number[];
createdUserId?: number[];
offset?: number;
count?: number;
}
export interface PostPullRequestParams {
summary: string;
description: string;
base: string;
branch: string;
issueId?: number;
assigneeId?: number;
notifiedUserId?: number[];
attachmentId?: number[];
}
export interface PatchPullRequestParams {
summary?: string;
description?: string;
issueId?: number;
assigneeId?: number;
notifiedUserId?: number[];
comment?: string[];
}
export interface GetPullRequestCommentsParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
export interface PostPullRequestCommentsParams {
content: string;
notifiedUserId?: number[];
}
export interface PatchPullRequestCommentsParams {
content: string;
}
}
export namespace Wiki {
export interface PostWikiParams {
projectId: number;
name: string;
content: string;
mailNotify?: boolean;
}
export interface PatchWikiParams {
name?: string;
content?: string;
mailNotify?: boolean;
}
export interface GetWikisHistoryParams {
minId?: number;
maxId?: number;
count?: number;
order?: Order;
}
}
export namespace OAuth2 {
export interface Credentials {
clientId: string;
clientSecret: string;
}
}
}
export namespace Error {
export class BacklogError extends global.Error {
private _name;
private _url;
private _status;
private _body;
private _response;
constructor(name: BacklogErrorNameType, response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
name: BacklogErrorNameType;
url: string;
status: number;
body: {
errors: BacklogErrorMessage[];
};
response: IResponse;
}
export class BacklogApiError extends BacklogError {
constructor(response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
}
export class BacklogAuthError extends BacklogError {
constructor(response: IResponse, body?: {
errors: BacklogErrorMessage[];
});
}
export class UnexpectedError extends BacklogError {
constructor(response: IResponse);
}
export interface BacklogErrorMessage {
message: string;
code: number;
errorInfo: string;
moreInfo: string;
}
export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError';
}
}
+773
View File
@@ -0,0 +1,773 @@
///<reference path="blessed.d.ts" />
import * as blessed from 'blessed';
let screen: blessed.Widgets.Screen = null;
// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js
screen = blessed.screen({
dump: __dirname + '/logs/autopad.log',
smartCSR: true,
autoPadding: true,
warnings: true
});
var box1 = blessed.box({
parent: screen,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line'
});
var box2 = blessed.box({
parent: box1,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line'
});
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js
screen = blessed.screen({
dump: __dirname + '/logs/bigtext.log',
smartCSR: true,
warnings: true
});
var box = blessed.bigtext({
parent: screen,
content: 'Hello',
shrink: true,
width: '80%',
// height: '80%',
height: 'shrink',
// width: 'shrink',
border: 'line',
fch: ' ',
ch: '\u2592',
style: {
fg: 'red',
bg: 'blue',
bold: false
}
});
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-csr.js
screen = blessed.screen({
dump: __dirname + '/logs/csr.log',
smartCSR: true,
warnings: true
});
var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8');
var cleanSides = screen.cleanSides;
function expectClean(value: any) {
screen.cleanSides = function(el: blessed.widget.Element) {
var ret = cleanSides.apply(this, arguments);
if (ret !== value) {
throw new Error('Failed. Expected '
+ value + ' from cleanSides. Got '
+ ret + '.');
}
return ret;
};
}
var btext = blessed.box({
parent: screen,
left: 'center',
top: 'center',
width: '80%',
height: '80%',
style: {
bg: 'green'
},
border: 'line',
content: 'CSR should still work.'
});
let _oscroll = btext.scroll;
btext.scroll = function(offset, always) {
expectClean(true);
return _oscroll(offset, always);
};
var text = blessed.scrollabletext({
parent: screen,
content: lorem,
border: 'line',
left: 'center',
top: 'center',
draggable: true,
width: '50%',
height: '50%',
mouse: true,
keys: true,
vi: true
});
_oscroll = text.scroll;
text.scroll = function(offset, always) {
var el = this;
var value = true;
if (el.left < 0) value = true;
if (el.top < 0) value = false;
if (el.left + el.width > screen.width) value = true;
if (el.top + el.height > screen.height) value = false;
expectClean(value);
return _oscroll(offset, always);
};
text.focus();
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js
screen = blessed.screen({
dump: __dirname + '/logs/dock.log',
smartCSR: true,
dockBorders: true,
warnings: true
});
blessed.box({
parent: screen,
left: -1,
top: -1,
width: '50%+1',
height: '50%+1',
border: 'line',
content: 'Foo'
});
blessed.box({
parent: screen,
left: '50%-1',
top: -1,
width: '50%+3',
height: '50%+1',
content: 'Bar',
border: 'line'
});
blessed.box({
parent: screen,
left: -1,
top: '50%-1',
width: '50%+1',
height: '50%+3',
border: 'line',
content: 'Foo'
});
blessed.listtable({
parent: screen,
left: '50%-1',
top: '50%-1',
width: '50%+3',
height: '50%+3',
border: 'line',
align: 'center',
tags: true,
keys: true,
vi: true,
mouse: true,
style: {
header: {
fg: 'blue',
bold: true
},
cell: {
fg: 'magenta',
selected: {
bg: 'blue'
}
}
},
data: [
[ 'Animals', 'Foods', 'Times', 'Numbers' ],
[ 'Elephant', 'Apple', '1:00am', 'One' ],
[ 'Bird', 'Orange', '2:15pm', 'Two' ],
[ 'T-Rex', 'Taco', '8:45am', 'Three' ],
[ 'Mouse', 'Cheese', '9:05am', 'Four' ]
]
}).focus();
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js
var form = blessed.form({
parent: screen,
keys: true,
left: 0,
top: 0,
width: 30,
height: 4,
bg: 'green',
content: 'Submit or cancel?'
});
var submit = blessed.button({
parent: form,
mouse: true,
keys: true,
padding: {
left: 1,
right: 1
},
left: 10,
top: 2,
shrink: true,
name: 'submit',
content: 'submit',
style: {
bg: 'blue',
focus: {
bg: 'red'
},
hover: {
bg: 'red'
}
}
});
var cancel = blessed.button({
parent: form,
mouse: true,
keys: true,
padding: {
left: 1,
right: 1
},
left: 20,
top: 2,
shrink: true,
name: 'cancel',
content: 'cancel',
style: {
bg: 'blue',
focus: {
bg: 'red'
},
hover: {
bg: 'red'
}
}
});
// https://github.com/chjj/blessed/blob/master/test/widget-layout.js
screen = blessed.screen({
dump: __dirname + '/logs/layout.log',
smartCSR: true,
autoPadding: true,
warnings: true
});
var layout = blessed.layout({
parent: screen,
top: 'center',
left: 'center',
width: '50%',
height: '50%',
border: 'line',
layout: process.argv[2] === 'grid' ? 'grid' : 'inline',
style: {
bg: 'red',
border: {
fg: 'blue'
}
}
});
var box1 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '1'
});
var box2 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '2'
});
var box3 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '3'
});
var box4 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '4'
});
var box5 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '5'
});
var box6 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '6'
});
var box7 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '7'
});
var box8 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '8'
});
var box9 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '9'
});
var box10 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '10'
});
var box11 = blessed.box({
parent: layout,
top: 0,
left: 0,
width: 10,
height: 5,
border: 'line',
content: '11'
});
var box12 = blessed.box({
parent: layout,
top: 'center',
left: 'center',
width: 20,
height: 10,
border: 'line',
content: '12'
});
if (process.argv[2] !== 'grid') {
for (var i = 0; i < 10; i++) {
blessed.box({
parent: layout,
// width: i % 2 === 0 ? 10 : 20,
// height: i % 2 === 0 ? 5 : 10,
width: Math.random() > 0.5 ? 10 : 20,
height: Math.random() > 0.5 ? 5 : 10,
border: 'line',
content: (i + 1 + 12) + ''
});
}
}
screen.key('q', function() {
return screen.destroy();
});
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-form.js
screen = blessed.screen({
dump: __dirname + '/logs/form.log',
warnings: true
});
type FormData = {
radio1: boolean;
radio2: boolean;
text: string;
check: boolean;
};
var form2 = blessed.form<FormData>({
parent: screen,
mouse: true,
keys: true,
vi: true,
left: 0,
top: 0,
width: '100%',
//height: 12,
style: {
bg: 'green',
border: {
inverse: true
},
scrollbar: {
inverse: true
}
},
content: 'foobar',
scrollable: true,
scrollbar: {
ch: ' '
}
//alwaysScroll: true
});
form2.on('submit', (data) => {
output.setContent(JSON.stringify(data, null, 2));
screen.render();
});
form2.key('d', function() {
form2.scroll(1, true);
screen.render();
});
form2.key('u', function() {
form2.scroll(-1, true);
screen.render();
});
var set = blessed.radioset({
parent: form2,
left: 1,
top: 1,
shrink: true,
//padding: 1,
//content: 'f',
style: {
bg: 'magenta'
}
});
var radio1 = blessed.radiobutton({
parent: set,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 0,
top: 0,
name: 'radio1',
content: 'radio1'
});
var radio2 = blessed.radiobutton({
parent: set,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 15,
top: 0,
name: 'radio2',
content: 'radio2'
});
var text2 = blessed.textbox({
parent: form2,
mouse: true,
keys: true,
style: {
bg: 'blue'
},
height: 1,
width: 20,
left: 1,
top: 3,
name: 'text'
});
text2.on('focus', function() {
text2.readInput();
});
var check = blessed.checkbox({
parent: form2,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 28,
top: 1,
name: 'check',
content: 'check'
});
var check2 = blessed.checkbox({
parent: form2,
mouse: true,
keys: true,
shrink: true,
style: {
bg: 'magenta'
},
height: 1,
left: 28,
top: 14,
name: 'foooooooo2',
content: 'foooooooo2'
});
var submit = blessed.button({
parent: form2,
mouse: true,
keys: true,
shrink: true,
padding: {
left: 1,
right: 1
},
left: 29,
top: 3,
name: 'submit',
content: 'submit',
style: {
bg: 'blue',
focus: {
bg: 'red'
}
}
});
submit.on('press', function() {
form2.submit();
});
var box1 = blessed.box({
parent: form2,
left: 1,
top: 10,
height: 10,
width: 10,
content: 'one',
style: {
bg: 'cyan'
}
});
var box2 = blessed.box({
parent: box1,
left: 1,
top: 2,
height: 8,
width: 9,
content: 'two',
style: {
bg: 'magenta'
}
});
var box3 = blessed.box({
parent: box2,
left: 1,
top: 2,
height: 6,
width: 8,
content: 'three',
style: {
bg: 'yellow'
}
});
var box4 = blessed.box({
parent: box3,
left: 1,
top: 2,
height: 4,
width: 7,
content: 'four',
style: {
bg: 'blue'
}
});
var output = blessed.scrollabletext({
parent: form2,
mouse: true,
keys: true,
left: 0,
top: 20,
height: 5,
right: 0,
style: {
bg: 'red'
},
content: 'foobar'
});
var bottom = blessed.line({
parent: form2,
type: 'line',
orientation: 'horizontal',
left: 0,
right: 0,
top: 50,
style: {
fg: 'blue'
}
});
screen.key('q', function() {
return screen.destroy();
});
form2.focus();
form2.submit();
screen.render();
// https://github.com/chjj/blessed/blob/master/test/widget-table.js
screen = blessed.screen({
dump: __dirname + '/logs/table.log',
autoPadding: false,
fullUnicode: true,
warnings: true
});
var DU = '杜';
var JUAN = '鹃';
var table = blessed.table({
//parent: screen,
top: 'center',
left: 'center',
data: null,
border: 'line',
align: 'center',
tags: true,
//width: '80%',
width: 'shrink',
style: {
border: {
fg: 'red'
},
header: {
fg: 'blue',
bold: true
},
cell: {
fg: 'magenta'
}
}
});
var data1 = [
[ 'Animals', 'Foods', 'Times' ],
[ 'Elephant', 'Apple', '1:00am' ],
[ 'Bird', 'Orange', '2:15pm' ],
[ 'T-Rex', 'Taco', '8:45am' ],
[ 'Mouse', 'Cheese', '9:05am' ]
];
data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}';
data1[2][0] += ' (' + DU + JUAN + ')';
var data2 = [
[ 'Animals', 'Foods', 'Times', 'Numbers' ],
[ 'Elephant', 'Apple', '1:00am', 'One' ],
[ 'Bird', 'Orange', '2:15pm', 'Two' ],
[ 'T-Rex', 'Taco', '8:45am', 'Three' ],
[ 'Mouse', 'Cheese', '9:05am', 'Four' ]
];
data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}';
data2[2][0] += ' (' + DU + JUAN + ')';
screen.key('q', function() {
return screen.destroy();
});
table.setData(data2);
screen.append(table);
screen.render();
setTimeout(function() {
table.setData(data1);
screen.render();
}, 3000);
+2812 -1247
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -82,6 +82,7 @@ var voidProm: Promise<void>;
var fooProm: Promise<Foo>;
var barProm: Promise<Bar>;
var barOrVoidProm: Promise<Bar | void>;
var fooOrBarProm: Promise<Foo|Bar>;
var bazProm: Promise<Baz>;
@@ -221,12 +222,12 @@ barProm = fooProm.then((value: Foo) => {
}, (reason: any) => {
return barProm;
});
barProm = fooProm.then((value: Foo) => {
barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return;
});
barProm = fooProm.then((value: Foo) => {
barOrVoidProm = fooProm.then((value: Foo) => {
return bar;
}, (reason: any) => {
return voidProm;
+4 -2
View File
@@ -47,8 +47,10 @@ class Bluebird<R> implements Bluebird.Thenable<R>, Bluebird.Inspection<R> {
/**
* Promises/A+ `.then()`. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject?: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject?: (error: any) => void | Bluebird.Thenable<void>): Bluebird<U>;
then<U1, U2>(onFulfill: (value: R) => U1 | Bluebird.Thenable<U1>, onReject: (error: any) => U2 | Bluebird.Thenable<U2>): Bluebird<U1 | U2>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>, onReject: (error: any) => U | Bluebird.Thenable<U>): Bluebird<U>;
then<U>(onFulfill: (value: R) => U | Bluebird.Thenable<U>): Bluebird<U>;
then(): Bluebird<R>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
+1 -1
View File
@@ -9,7 +9,7 @@
interface BootboxBaseOptions {
title?: string | Element;
callback?: (result: boolean | string) => any;
onEscape?: () => any | boolean;
onEscape?: (() => any) | boolean;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
+10
View File
@@ -7,3 +7,13 @@ Bowser.test(['msie']) === true;
Bowser.a === Bowser.c;
Bowser.osversion > 10;
Bowser.osversion === '10.1A';
bowser.msedge === true;
bowser.test(['msie']) === true;
bowser.a === bowser.c;
bowser.osversion > 10;
bowser.osversion === '10.1A';
bowser.compareVersions(['9.0', '10']);
bowser() === <BowserModule.IBowserDetection>{android: true, x: true};
bowser.check({msie: "11"}, window.navigator.userAgent);
bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent);
+71 -19
View File
@@ -3,52 +3,104 @@
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var bowser: BowserModule.IBowser;
declare module 'bowser' {
var def: BowserModule.IBowser;
export = def;
export = bowser;
}
declare namespace BowserModule {
export interface IBowserUA {
msie: boolean;
export interface IBowserOS {
mac: boolean;
/**other than Windows Phone */
windows: boolean;
windowsphone: boolean;
/**other than android, chromeos, webos, tizen, and sailfish */
linux: boolean;
chromeos: boolean;
android: boolean;
/** also sets one of iphone/ipad/ipod */
ios: boolean;
blackberry: boolean;
firefoxos: boolean;
/** may also set touchpad */
webos: boolean;
bada: boolean;
tizen: boolean;
sailfish: boolean;
}
export interface IBowserVersions {
chrome: boolean;
webkit: boolean;
phantom: boolean;
opera: boolean;
firefox: boolean;
msie: boolean;
msedge: boolean;
safari: boolean;
android: boolean;
ios: boolean;
webos: boolean;
msedge: boolean;
seamonkey: boolean;
firefox: boolean;
yandexbrowser: boolean;
opera: boolean;
phantom: boolean;
blackberry: boolean;
tablet: boolean;
mobile: boolean;
webos: boolean;
silk: boolean;
bada: boolean;
tizen: boolean;
windowsphone: boolean;
firefoxos: boolean;
gecko: boolean;
seamonkey: boolean;
sailfish: boolean;
chromeBook: boolean;
ucbrowser: boolean;
qupzilla: boolean;
vivaldi: boolean;
sleipnir: boolean;
kMeleon: boolean;
}
export interface IBowserEngines {
/** IE <= 11 */
msie: boolean;
/**Chrome 0-27, Android <4.4, iOs, BB, etc. */
webkit: boolean;
/**Chrome >=28, Android >=4.4, Opera, etc. */
blink: boolean;
/**Firefox, etc. */
gecko: boolean;
/** IE > 11 */
msedge: boolean;
/** If a tablet device is detected, the flag tablet is set instead of mobile. */
tablet: boolean;
/** All detected mobile OSes are additionally flagged mobile, unless it's a tablet */
mobile: boolean;
}
export interface IBowserGrade {
/** Grade A browser */
a: boolean;
/** Grade C browser */
c: boolean;
/** Grade X browser */
x: boolean;
/**A human readable name for this browser. E.g. 'Chrome', '' */
name: string;
/**Version number for the browser. E.g. '32.0' */
version: string|number;
osversion: string|number;
}
export interface IBowser extends IBowserUA {
export interface IBowserDetection extends IBowserGrade, IBowserEngines, IBowserOS, IBowserVersions { }
export interface IBowserMinVersions {
// { msie: "11", "firefox": "4" }
[index: string]: string;
}
export interface IBowser extends IBowserDetection {
(): IBowserDetection;
test(browserList: string[]): boolean;
_detect(ua: string): IBowser;
compareVersions(versions: string[]): number;
check(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): Boolean;
isUnsupportedBrowser(minVersions: IBowserMinVersions, strictMode?: boolean|string, ua?: string): boolean;
}
}
+432
View File
@@ -0,0 +1,432 @@
/// <reference path="braintree-web.d.ts" />
let version: string = braintree.VERSION;
let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
braintree.client.create({
authorization: clientToken
}, function (error: BraintreeError, clientInstance: any) {
var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
var data: { creditCard: BraintreeWeb.CreditCardInfo } = {
creditCard: {
number: form['cc-number'].value,
cvv: form['cc-cvv'].value,
expirationDate: form['cc-date'].value,
billingAddress: {
postalCode: form['cc-postal'].value
}
}
};
clientInstance.request({
endpoint: 'payment_methods/credit_cards',
method: 'post',
data: data
}, function (requestErr: BraintreeError, response: { creditCards: any[]; }) {
if (requestErr) { throw new Error(requestErr.message); }
console.log('Got nonce:', response.creditCards[0].nonce);
});
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16pt',
'color': '#3A3A3A'
},
'.number': {
'font-family': 'monospace'
},
'.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number'
},
cvv: {
selector: '#cvv'
},
expirationDate: {
selector: '#expiration-date'
}
}
}, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) {
if (hostedFieldsErr) {
// Handle error in Hosted Fields creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let form = new HTMLFormElement();
form.addEventListener('submit', function (event: Event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
switch (tokenizeErr.code) {
case 'HOSTED_FIELDS_FIELDS_EMPTY':
console.error('All fields are empty! Please fill out the form.');
break;
case 'HOSTED_FIELDS_FIELDS_INVALID':
console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
break;
case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
console.error('Tokenization failed server side. Is the card valid?');
break;
case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
console.error('Network error occurred when tokenizing.');
break;
default:
console.error('Something bad happened!', tokenizeErr);
}
return;
}
// Put `payload.nonce` into the `payment-method-nonce` input, and then
// submit the form. Alternatively, you could send the nonce to your server
// with AJAX.
(document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce;
form.submit();
});
}, false);
hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) {
console.log(event.emittedBy, 'has been focused');
});
hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) {
if (teardownErr) {
console.error('Could not tear down Hosted Fields!');
} else {
console.info('Hosted Fields has been torn down!');
}
});
hostedFieldsInstance.tokenize({
vault: true
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
} else {
console.log('Got nonce:', payload.nonce);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
}
});
hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
if (addClassErr) {
console.error(addClassErr);
return;
}
// some time later...
hostedFieldsInstance.removeClass('number', 'custom-class');
});
hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) {
if (placeholderErr) {
console.error(placeholderErr);
}
});
hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) {
// Update the placeholder value if there is only one possible card type
if (event.cards.length === 1) {
braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) {
if (placeholderErr) {
// Handle errors, such as invalid field name
console.error(placeholderErr);
}
});
}
});
hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) {
if (clearErr) {
console.error(clearErr);
}
});
hostedFieldsInstance.clear('number');
hostedFieldsInstance.clear('cvv');
hostedFieldsInstance.clear('expirationDate');
var state = braintree.hostedFields.getState();
var formValid = Object.keys(state.fields).every(function (key) {
return state.fields[key].isValid;
});
});
braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) {
if (createErr) {
// Handle error in client creation
console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
return;
}
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var paymentRequest = braintree.applePay.createPaymentRequest(request);
console.log(paymentRequest);
// { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
session.onvalidatemerchant = function (event: { validationURL: string }) {
braintree.applePay.performValidation({
validationURL: event.validationURL
}, function (err, validationData) {
if (err) {
console.error(err);
session.abort();
return;
}
session.completeMerchantValidation(validationData);
});
};
});
braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
let request = {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: { label: 'Your Label', amount: '10.00' },
};
var session = new ApplePaySession(1, request);
session.onpaymentauthorized = function (event) {
braintree.applePay.tokenize({
token: event.payment.token
}, function (err, tokenizedPayload) {
if (err) {
session.completePayment(ApplePayStatusCodes.STATUS_FAILURE);
return;
}
session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS);
// Send the tokenizedPayload to your server.
});
};
});
braintree.paypal.create({
client: clientInstance
}, function (createErr, paypalInstance) {
if (createErr) {
if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
console.error('This browser is not supported.');
} else {
console.error('Error!', createErr);
}
}
let button = new HTMLButtonElement();
button.addEventListener('click', function () {
// Disable the button so that we don't attempt to open multiple popups.
button.setAttribute('disabled', 'disabled');
// Because PayPal tokenization opens a popup, this must be called
// as a result of a user action, such as a button click.
paypalInstance.tokenize({
flow: 'vault' // Required
// Any other tokenization options
}, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) {
button.removeAttribute('disabled');
if (tokenizeErr) {
// Handle tokenization errors or premature flow closure
switch (tokenizeErr.code) {
case 'PAYPAL_POPUP_CLOSED':
console.error('Customer closed PayPal popup.');
break;
case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
break;
case 'PAYPAL_FLOW_FAILED':
console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
break;
default:
console.error('Error!', tokenizeErr);
}
} else {
// Submit payload.nonce to your server
}
});
});
});
braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
if (createErr) {
console.error(createErr);
return;
}
unionpayInstance.fetchCapabilities({
card: {
number: '4111111111111111'
}
}, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) {
if (fetchErr) {
console.error(fetchErr);
return;
}
if (cardCapabilities.isUnionPay) {
if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
// Braintree cannot process this UnionPay card.
// Ask the user for a different card.
return;
}
if (cardCapabilities.isDebit) {
// CVV and expiration date are not required
} else {
// CVV and expiration date are required
}
// Show mobile phone number field for enrollment
}
});
unionpayInstance.enroll({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038'
},
mobile: {
countryCode: '62',
number: '111111111111'
}
}, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) {
if (enrollErr) {
console.error(enrollErr);
return;
}
if (response.smsCodeRequired) {
// If smsCodeRequired, wait for SMS auth code from customer
// Then use response.enrollmentId during {@link UnionPay#tokenize}
} else {
// SMS code is not required from the user.
// {@link UnionPay#tokenize} can be called immediately
}
});
let enrollResponse: {
enrollmentId: string
};
unionpayInstance.tokenize({
card: {
number: '4111111111111111',
expirationMonth: '12',
expirationYear: '2038',
cvv: '123'
},
enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
}, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// Send response.nonce to your server
});
unionpayInstance.teardown(function (teardownErr: BraintreeError) {
if (teardownErr) {
console.error('Could not tear down UnionPay.');
} else {
console.log('UnionPay has been torn down.');
}
});
});
});
let existingNonce = "fake-valid-nonce";
let submitNonceToServer: (nonce: string) => void;
braintree.threeDSecure.verifyCard({
nonce: existingNonce,
amount: 123.45,
addFrame: function (err, iframe) {
// Set up your UI and add the iframe.
let my3DSContainer = document.createElement('div');
my3DSContainer.appendChild(iframe);
document.body.appendChild(my3DSContainer);
},
removeFrame: function () {
let my3DSContainer = document.createElement('div');
// Remove UI that you added in addFrame.
document.body.removeChild(my3DSContainer);
}
}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) {
if (err) {
console.error(err);
return;
}
if (payload.liabilityShifted) {
// Liablity has shifted
submitNonceToServer(payload.nonce);
} else if (payload.liabilityShiftPossible) {
// Liablity may still be shifted
// Decide if you want to submit the nonce
} else {
// Liablity has not shifted and will not shift
// Decide if you want to submit the nonce
}
});
braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) {
if (err) {
// Handle error
console.log(err.message); // No verification payload available
return;
}
verifyPayload.nonce; // The nonce returned from the 3ds lookup call
verifyPayload.liabilityShifted; // boolean
verifyPayload.liabilityShiftPossible; // boolean
});
+1738
View File
File diff suppressed because it is too large Load Diff
+36
View File
@@ -0,0 +1,36 @@
/// <reference path="bunnymq.d.ts"/>
import * as bunnymq from "bunnymq";
// Basic usage
var instance = bunnymq({ host: 'amqp://localhost' });
// Publisher
instance.producer.produce('queue:name', 'Hello World!');
// Subscriber
instance.consumer.consume('queue:name', message => { });
// RPC Support
instance.producer.produce('queue:name', { message: 'content' }, { rpc: true })
.then(function (consumerResponse) {
console.log(consumerResponse);
});
// Routing keys
instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' });
// Config
var custom = bunnymq({
host: 'amqp://localhost',
//number of fetched messages at once on the channel
prefetch: 5,
//requeue put back message into the broker if consumer crashes/trigger exception
requeue: true,
//time between two reconnect (ms)
timeout: 1000,
consumerSuffix: '',
//generate a hostname so we can track this connection on the broker (rabbitmq management plugin)
hostname: "",
//the transport to use to debug. if provided, bunnymq will show some logs
transport: new Object()
});
+120
View File
@@ -0,0 +1,120 @@
// Type definitions for node-bunnymq 2.2.1
// Project: https://github.com/dial-once/node-bunnymq
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "bunnymq" {
namespace bunnymq {
export type ConsumerCallback = (message: Object) => void;
/**
* Consumer.
* @interface
*/
export interface Consumer {
/**
* Handle messages from a named queue.
* @param {string} queue A named queue.
* @param {ConsumerCallback} callback A callback.
*/
consume(queue: string, callback: ConsumerCallback): void;
}
/**
* bunnymq instance.
* @interface
*/
export interface Instance {
/**
* Consumer.
* @type {Consumer}
*/
consumer: Consumer;
/**
* Producer.
* @type {Producer}
*/
producer: Producer;
}
/**
* Options.
* @interface
*/
export interface Options {
/**
* Consumer suffix.
* @type {string}
*/
consumerSuffix?: string;
/**
* Host.
* @type {string}
*/
host?: string;
/**
* Hostname.
* @type {string}
*/
hostname?: string;
/**
* Number of fetched messages at once on the channel.
* @type {number}
*/
prefetch?: number;
/**
* Requeue put back message into the broker if consumer crashes/trigger exception.
* @type {boolean}
*/
requeue?: boolean;
/**
* Time between two reconnect (in milliseconds).
* @type {number}
*/
timeout?: number;
/**
* Transport.
* @type {any}
*/
transport?: any;
}
/**
* Producer.
* @inteface
*/
export interface Producer {
/**
* Send messages to a named queue.
* @param {string} queue A named queue.
* @param {Object} message A message.
* @return {Object} The consumer response.
*/
produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike<Object>;
}
/**
* Options for producer.
* @interface
*/
export interface ProducerOptions {
routingKey?: string;
rpc?: boolean;
}
}
/**
* Constructor.
* @param {Options} [options] Options.
* @return {Instance} A instance of bunnymq.
*/
function bunnymq(options?: bunnymq.Options): bunnymq.Instance;
export = bunnymq;
}
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="busboy.d.ts"/>
/// <reference path="../node/node.d.ts" />
import * as Busboy from 'busboy';
import * as http from 'http';
import * as util from 'util';
function serverFn(req: http.ServerRequest, res: http.ServerResponse) {
if (req.method === 'POST') {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data: Buffer) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
console.log('Field [' + fieldname + ']: value: ' + util.inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(busboy);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end('<html><head></head><body>\
<form method="POST" enctype="multipart/form-data">\
<input type="text" name="textfield"><br />\
<input type="file" name="filefield"><br />\
<input type="submit">\
</form>\
</body></html>');
}
}
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for busboy v0.2.13
// Project: https://www.npmjs.com/package/busboy
// Definitions by: Jacob Baskin <https://github.com/jacobbaskin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace busboy {
interface Options {
headers: any;
}
interface BusboyConfig {
headers?: any;
highWaterMark?: number;
fileHwm?: number;
defCharset?: string;
preservePath?: boolean;
limits?: {
fieldNameSize?: number;
fieldSize?: number;
fields?: number;
fileSize?: number;
files?: number;
parts?: number;
headerPairs?: number;
};
}
interface Busboy extends NodeJS.WritableStream {
on(event: 'field',
listener: (
fieldname: string,
val: any,
fieldnameTruncated: boolean,
valTruncated: boolean,
encoding: string,
mimetype: string) => void): this;
on(event: 'file',
listener: (
fieldname: string,
file: NodeJS.ReadableStream,
filename: string,
encoding: string,
mimetype: string) => void): this;
on(event: 'finish', callback: () => void): this;
on(event: 'partsLimit', callback: () => void): this;
on(event: 'filesLimit', callback: () => void): this;
on(event: 'fieldsLimit', callback: () => void): this;
on(event: string, listener: Function): this;
}
interface BusboyConstructor {
new (options: BusboyConfig): Busboy;
}
}
declare module 'busboy' {
const temp: busboy.BusboyConstructor;
export = temp;
}
+1 -1
View File
@@ -28,7 +28,7 @@ declare module 'cache-manager' {
module cacheManager {
function caching(ICongig: StoreConfig): Cache;
function caching(IConfig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="canvas-gauges.d.ts" />
import {
LinearGaugeOptions,
RadialGaugeOptions,
LinearGauge,
RadialGauge
} from 'canvas-gauges';
let linearOptions: LinearGaugeOptions = {
renderTo: document.createElement('canvas')
};
let radialOptions: RadialGaugeOptions = {
renderTo: 'gauge-id'
};
new LinearGauge(linearOptions);
new RadialGauge(radialOptions);
console.log(document.gauges.length);
+263
View File
@@ -0,0 +1,263 @@
// Type definitions for canvas-gauges
// Project: https://github.com/Mikhus/canvas-gauges
// Definitions by: Mikhus <https://github.com/Mikhus>
// Definitions: https://github.com/Mikhus/DefinitelyTyped
declare namespace CanvasGauges {
export type RenderTarget = string|HTMLElement;
export interface AnimationRule {
(percent: number): number;
}
export interface Highlight {
from: number,
to: number,
color: string
}
export type MajorTicks = string[]|number[];
export interface GenericOptions {
renderTo: RenderTarget,
width?: number,
height?: number,
minValue?: number,
maxValue?: number,
value?: number,
units?: string|boolean,
majorTicks?: MajorTicks,
minorTicks?: number,
strokeTicks?: boolean,
animatedValue?: boolean,
title?: string|boolean,
borders?: boolean,
valueInt?: number,
valueDec?: number,
majorTicksInt?: number,
majorTicksDec?: number,
animation?: boolean,
animationDuration?: number,
animationRule?: string|AnimationRule,
colorPlate?: string,
colorMajorTicks?: string,
colorMinorTicks?: string,
colorTitle?: string,
colorUnits?: string,
colorNumbers?: string,
colorNeedle?: string,
colorNeedleEnd?: string,
colorValueText?: string,
colorValueTextShadow?: string,
colorBorderShadow?: string,
colorBorderOuter?: string,
colorBorderOuterEnd?: string,
colorBorderMiddle?: string,
colorBorderMiddleEnd?: string,
colorBorderInner?: string,
colorBorderInnerEnd?: string,
colorValueBoxRect?: string,
colorValueBoxRectEnd?: string,
colorValueBoxBackground?: string,
colorValueBoxShadow?: string,
colorNeedleShadowUp?: string,
colorNeedleShadowDown?: string,
needle?: boolean,
needleShadow?: boolean,
needleType?: string,
needleStart?: number,
needleEnd?: number,
needleWidth?: number,
borderOuterWidth?: number,
borderMiddleWidth?: number,
borderInnerWidth?: number,
borderShadowWidth?: number,
valueBox?: boolean,
valueBoxStroke?: number,
valueText?: string,
valueTextShadow?: boolean,
valueBoxBorderRadius?: number,
highlights?: Highlight[],
fontNumbers?: string,
fontTitle?: string,
fontUnits?: string,
fontValue?: string,
fontTitleSize?: number,
fontValueSize?: number,
fontUnitsSize?: number,
fontNumbersSize?: number
}
export interface RadialGaugeOptions extends GenericOptions {
ticksAngle?: number,
startAngle?: number,
colorNeedleCircleOuter?: string,
colorNeedleCircleOuterEnd?: string,
colorNeedleCircleInner?: string,
colorNeedleCircleInnerEnd?: string,
needleCircleSize?: number,
needleCircleInner?: boolean,
needleCircleOuter?: boolean,
animationTarget?: string
}
export interface LinearGaugeOptions extends GenericOptions {
borderRadius?: number,
barBeginCircle?: number,
barWidth?: number,
barStrokeWidth?: number,
barProgress?: boolean,
colorBar?: string,
colorBarEnd?: string,
colorBarStroke?: string,
colorBarProgress?: string,
colorBarProgressEnd?: string,
tickSide?: string,
needleSide?: string,
numberSide?: string,
ticksWidth?: number,
ticksWidthMinor?: number,
ticksPadding?: number,
barLength?: number
}
export interface DrawEventCallback {
(percent: number): any;
}
export interface EndEventCallback {
(): any;
}
export interface rules {
linear: AnimationRule,
quad: AnimationRule,
dequad: AnimationRule,
quint: AnimationRule,
dequint: AnimationRule,
cycle: AnimationRule,
decycle: AnimationRule,
bounce: AnimationRule,
debounce: AnimationRule,
elastic: AnimationRule,
delastic: AnimationRule
}
export class Animation {
public duration: number;
public rule: string|AnimationRule;
public draw: DrawEventCallback;
public end: EndEventCallback;
public static rules: rules;
constructor(rule?: string|AnimationRule, duration?: number,
draw?: DrawEventCallback, end?: EndEventCallback);
public animate(draw?: DrawEventCallback, end?: EndEventCallback): any;
public destroy(): any;
}
export class SmartCanvas {
public element: HTMLCanvasElement;
public elementClone: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
public contextClone: CanvasRenderingContext2D;
public drawWidth: number;
public drawHeight: number;
public drawX: number;
public drawY: number;
public minSide: number;
public width: number;
public height: number;
constructor(element: HTMLCanvasElement,
width?: number,
height?: number);
public init(): any;
public onRedraw(): any;
public destroy(): any;
public commit(): SmartCanvas;
public redraw(): SmartCanvas;
public pixelRatio: number;
public static redraw(): any;
public static collection: Array<SmartCanvas>;
}
export class DomObserver {
public Type: BaseGauge;
public mutationsObserved: boolean;
public isObservable: boolean;
public options: GenericOptions;
public element: string;
public type: string;
constructor(options: GenericOptions,
element: string,
type: string);
public isValidNode(node: Node|HTMLElement): boolean;
public traverse(): any;
public observe(records: MutationRecord[]): any;
public process(node: Node|HTMLElement): BaseGauge;
public static parse(value: any): any;
public static toDashed(camelCase: string): string;
public static toAttributeName(str: string): string;
static domReady(handler: Function): any;
}
export abstract class BaseGauge {
public type: BaseGauge;
public options: GenericOptions;
public canvas: SmartCanvas;
public animation: Animation;
public value: number;
constructor(options: GenericOptions);
public update(options: GenericOptions): BaseGauge;
public destroy(): any;
public abstract draw(): BaseGauge;
public static initialize(type: string, options: GenericOptions): any;
}
export class RadialGauge extends BaseGauge {
public type: RadialGauge;
public options: RadialGaugeOptions;
constructor(options: RadialGaugeOptions);
public draw(): RadialGauge;
}
export class LinearGauge extends BaseGauge {
public type: LinearGauge;
public options: LinearGaugeOptions;
constructor(options: LinearGaugeOptions);
public draw(): LinearGauge;
}
export interface Collection extends Array<BaseGauge> {
get: (id: number | string) => BaseGauge;
}
}
declare module 'canvas-gauges' {
export = CanvasGauges;
}
interface Document {
gauges: CanvasGauges.Collection;
}
interface Window {
BaseGauge: CanvasGauges.BaseGauge;
RadialGauge: CanvasGauges.RadialGauge;
LinearGauge: CanvasGauges.LinearGauge;
}
+20
View File
@@ -18,9 +18,19 @@ function test_somethingSyntax() {
array.should.include.something.with.property('b', 2);
array.should.not.include.something.with.property('b', 3);
chai.expect(array).to.include.something();
chai.expect(array).to.include.something.that.deep.equals({ b: 2 });
chai.expect(array).to.include.something.that.not.deep.equals({ b: 2 });
chai.expect(array).not.to.include.something.that.deep.equals({ c: 3 });
chai.expect(array).to.include.something.that.not.deep.equals({ c: 3 });
chai.expect(array).to.include.something.with.property('b', 2);
chai.expect(array).not.to.include.something.with.property('b', 3);
var array2 = [{ a: 'b' }, { a: 'b' }];
array2.should.include.something.that.have.property("a");
array2.should.include.something.that.have.property("a").not.equal("d");
chai.expect(array2).to.include.something.that.have.property("a");
chai.expect(array2).to.include.something.that.have.property("a").not.equal("d");
}
function test_somethingVariantsSyntax() {
@@ -35,6 +45,16 @@ function test_somethingVariantsSyntax() {
array.should.include.one.that.deep.equals({ b: 2 });
array.should.include.some();
array.should.include.some.that.deep.equal({ b: 2 });
chai.expect(array).to.include.a.thing();
chai.expect(array).to.include.a.thing.that.deep.equals({ b: 2 });
chai.expect(array).to.include.an.item();
chai.expect(array).to.include.an.item.that.deep.equals({ b: 2 });
chai.expect(array).to.include.one.that.deep.equals({ b: 2 });
chai.expect(array).to.include.some();
chai.expect(array).to.include.some.that.deep.equal({ b: 2 });
chai.expect(array).to.contain.a.thing();
chai.expect(array).to.contain.a.thing.with.property('a', 1);
}
function test_allSyntax() {
+9
View File
@@ -23,6 +23,15 @@ declare namespace Chai {
any: Anything;
}
interface Include {
(item: any): any;
a: Item;
an: Item;
one: Something;
some: Something;
something: Something;
}
interface Anything extends Assertion {
(): any;
that: Assertion;
+8
View File
@@ -114,8 +114,16 @@ declare namespace Chance {
capitalize(str: string): string;
mixin(desc: MixinDescriptor): any;
pad(num: number, width: number, padChar?: string): string;
/**
* @deprecated Use pickone
*/
pick<T>(arr: T[]): T;
pickone<T>(arr: T[]): T;
/**
* @deprecated Use pickset
*/
pick<T>(arr: T[], count: number): T[];
pickset<T>(arr: T[], count: number): T[];
set: Setter;
shuffle<T>(arr: T[]): T[];
+1 -1
View File
@@ -73,7 +73,7 @@ interface ChartOptions {
onClick?: (any?: any) => any;
title?: ChartTitleOptions;
legend?: ChartLegendOptions;
tooltip?: ChartTooltipOptions;
tooltips?: ChartTooltipOptions;
hover?: ChartHoverOptions;
animation?: ChartAnimationOptions;
elements?: ChartElementsOptions;
+8
View File
@@ -3,9 +3,17 @@
import colors = require("colors");
colors.enabled = true;
console.log(colors.black.underline('test'));
console.log(colors.rainbow.black.blue.gray('test'));
console.log(colors.random.reset.bgWhite.dim('test'));
console.log(colors.random.reset.bgWhite.strip('test'));
console.log('test'.black.underline);
console.log('test'.rainbow.black.blue.gray);
console.log('test'.random.reset.bgWhite.dim);
console.log('test'.random.reset.bgWhite.dim.stripColors);
colors.enabled = false;
console.log(colors.black.underline('test'));
+11
View File
@@ -7,6 +7,9 @@ declare module "colors" {
interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
@@ -47,6 +50,11 @@ declare module "colors" {
namespace e {
export function setTheme(theme:any): void;
export var enabled: boolean;
export var strip: Color;
export var stripColors: Color;
export var black: Color;
export var red: Color;
export var green: Color;
@@ -88,6 +96,9 @@ declare module "colors" {
}
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
+16 -1
View File
@@ -126,12 +126,27 @@ function fsaccessor(fs: FileSystem) {
(err: FileError)=> { alert('Error: ' + err.code); });
}
//----------------------------------------------------------------------
// FileSystem plugin
//
//cordova states that the enums for requestFileSystem live on LocalFileSystem
//
window.requestFileSystem(
window.TEMPORARY,
LocalFileSystem.TEMPORARY,
1024 * 1024 * 5,
fsaccessor,
(err: FileError) => { alert('Error: ' + err.code); }
);
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
1024 * 1024 * 5,
fsaccessor,
(err: FileError) => { alert('Error: ' + err.code); }
);
// FileSystem plugin
//----------------------------------------------------------------------
window.resolveLocalFileSystemURI(cordova.file.applicationDirectory,
(entry: Entry)=> {
+74 -10
View File
@@ -42,6 +42,40 @@ interface Contacts {
*/
pickContact(onSuccess: (contact: Contact) => void,
onError: (error: ContactError) => void): void
/**
* This allows us to use an enumeration when setting the desired fields for the ContactFindOptions.
* The values will correspond to the type of string literals in ContactFieldType.
*/
fieldType: {
addresses: "addresses",
birthday: "birthday",
categories: "categories",
country: "country",
department: "department",
displayName: "displayName",
emails: "emails",
familyName: "familyName",
formatted: "formatted",
givenName: "givenName",
honorificPrefix: "honorificPrefix",
honorificSuffix: "honorificSuffix",
id: "id",
ims: "ims",
locality: "locality",
middleName: "middleName",
name: "name",
nickname: "nickname",
note: "note",
organizations: "organizations",
phoneNumbers: "phoneNumbers",
photos: "photos",
postalCode: "postalCode",
region: "region",
streetAddress: "streetAddress",
title: "title",
urls: "urls"
}
}
interface ContactProperties {
@@ -105,7 +139,7 @@ interface Contact extends ContactProperties {
declare var Contact: {
/** Constructor of Contact object */
new(id?: string,
new (id?: string,
displayName?: string,
name?: ContactName,
nickname?: string,
@@ -130,7 +164,7 @@ interface ContactError {
}
declare var ContactError: {
new(code: number): ContactError;
new (code: number): ContactError;
UNKNOWN_ERROR: number;
INVALID_ARGUMENT_ERROR: number;
TIMEOUT_ERROR: number;
@@ -158,7 +192,7 @@ interface ContactName {
declare var ContactName: {
/** Constructor for ContactName object */
new(formatted?: string,
new (formatted?: string,
familyName?: string,
givenName?: string,
middleName?: string,
@@ -189,7 +223,7 @@ interface ContactField {
declare var ContactField: {
/** Constructor for ContactField object */
new(type?: string,
new (type?: string,
value?: string,
pref?: boolean): ContactField
};
@@ -219,7 +253,7 @@ interface ContactAddress {
declare var ContactAddress: {
/** Constructor of ContactAddress object */
new(pref?: boolean,
new (pref?: boolean,
type?: string,
formatted?: string,
streetAddress?: string,
@@ -248,7 +282,7 @@ interface ContactOrganization {
declare var ContactOrganization: {
/** Constructor for ContactOrganization object */
new(pref?: boolean,
new (pref?: boolean,
type?: string,
name?: string,
department?: string,
@@ -262,12 +296,42 @@ interface ContactFindOptions {
/** Determines if the find operation returns multiple navigator.contacts. */
multiple?: boolean;
/* Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. */
desiredFields?: string[];
desiredFields?: ContactFieldType[];
}
/** these are the string values that are valid for the desired fields in ContactFindOptions */
declare type ContactFieldType =
"addresses"
| "birthday"
| "categories"
| "country"
| "department"
| "displayName"
| "emails"
| "familyName"
| "formatted"
| "givenName"
| "honorificPrefix"
| "honorificSuffix"
| "id"
| "ims"
| "locality"
| "middleName"
| "name"
| "nickname"
| "note"
| "organizations"
| "phoneNumbers"
| "photos"
| "postalCode"
| "region"
| "streetAddress"
| "title"
| "urls";
declare var ContactFindOptions: {
/** Constructor for ContactFindOptions object */
new(filter?: string,
new (filter?: string,
multiple?: boolean,
desiredFields?: string[]): ContactFindOptions
};
desiredFields?: ContactFieldType[]): ContactFindOptions
};
+6 -1
View File
@@ -15,7 +15,7 @@ interface Window {
* @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied.
*/
requestFileSystem(
type: number,
type: LocalFileSystem,
size: number,
successCallback: (fileSystem: FileSystem) => void,
errorCallback?: (fileError: FileError) => void): void;
@@ -371,3 +371,8 @@ interface Cordova {
}
}
declare enum LocalFileSystem {
PERSISTENT=0,
TEMPORARY=1
}
+2 -2
View File
@@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/fn/number/min-safe-interger" {
declare module "core-js/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
@@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" {
var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER;
export = MAX_SAFE_INTEGER;
}
declare module "core-js/library/fn/number/min-safe-interger" {
declare module "core-js/library/fn/number/min-safe-integer" {
var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER;
export = MIN_SAFE_INTEGER;
}
+8
View File
@@ -159,6 +159,14 @@ declare module 'couchbase' {
* Creates a manager allowing the management of a Couchbase cluster.
*/
manager(): ClusterManager;
/**
* Creates a manager allowing the management of a Couchbase cluster using credentials.
* @param username The username for your cluster.
* @param password The password for your cluster.
*/
manager(username: string, password: string): ClusterManager;
/**
* Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
+5 -5
View File
@@ -1,15 +1,15 @@
/// <reference path="countdown.d.ts" />
import { countdown, Timespan, CountdownStatic, Format } from 'countdown';
import * as countdown from 'countdown';
let ts: Timespan;
let ts: countdown.Timespan;
let interval: number;
ts = <Timespan>countdown(new Date());
ts = <Timespan>countdown(150);
ts = <countdown.Timespan>countdown(new Date());
ts = <countdown.Timespan>countdown(150);
interval = <number>countdown(new Date(),
function (ts: Timespan) {
function (ts: countdown.Timespan) {
document.getElementById('pageTimer').innerHTML = ts.toHTML('strong');
},
countdown.HOURS | countdown.MINUTES | countdown.SECONDS,
+10 -7
View File
@@ -3,11 +3,11 @@
// Definitions by: Gabriel Juchault <https://github.com/gjuchault>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'countdown' {
export type DateFunction = (timespan: Timespan) => void;
export type DateTime = number | Date | DateFunction;
declare namespace countdown {
type DateFunction = (timespan: Timespan) => void;
type DateTime = number | Date | DateFunction;
export interface Timespan {
interface Timespan {
start?: Date;
end?: Date;
units?: number;
@@ -26,7 +26,7 @@ declare module 'countdown' {
toHTML(tagName?: string, label?: string): string;
}
export interface Format {
interface Format {
singular?: string | Array<string>;
plural?: string | Array<string>;
last?: string;
@@ -36,7 +36,7 @@ declare module 'countdown' {
formatter?(value: number, unit: number): string;
}
export interface CountdownStatic {
interface CountdownStatic {
(start: DateTime, end?: DateTime, units?: number, max?: number, digits?: number): Timespan | number;
MILLENNIA: number;
CENTURIES: number;
@@ -64,6 +64,9 @@ declare module 'countdown' {
resetFormat(): void;
setFormat(format: Format): void;
}
}
export let countdown: CountdownStatic;
declare module 'countdown' {
let countdown: countdown.CountdownStatic;
export = countdown;
}
+45 -5
View File
@@ -1,30 +1,32 @@
/// <reference path="cucumber.d.ts" />
/// <reference path="../assert/assert.d.ts" />
function StepSample() {
type Callback = cucumber.CallbackStepDefinition;
type Table = cucumber.TableDefinition;
var step = <cucumber.StepDefinitions>this;
var hook = <cucumber.Hooks>this;
hook.Before(function(scenario, callback){
scenario.isFailed() && callback.pending();
})
hook.Around(function(scenario, runScenario) {
scenario.isFailed() && runScenario(null, function(){
console.log('finish tasks');
});
});
hook.registerHandler('AfterFeatures', function (event, callback) {
callback();
});
step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) {
this.visit('https://github.com/cucumber/cucumber-js', callback);
});
step.When(/^I go to the README file$/, function(title:string, callback:Callback) {
callback.pending();
callback(null, 'pending');
});
step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) {
@@ -36,5 +38,43 @@ function StepSample() {
callback(new Error("Expected to be on page with title " + title));
}
});
// Type for data_table.js on
// https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js
step.Given(/^a table step with Table raw$/, function(table:Table){
var expected = [
['Cucumber', 'Cucumis sativus'],
['Burr Gherkin', 'Cucumis anguria']
];
assert.deepEqual(table.raw(), expected);
});
step.Given(/^a table step with Table rows$/, function(table: Table){
var expected = [
['Apricot', '5'],
['Brocolli', '2'],
['Cucumber', '10']
];
assert.deepEqual(table.rows(), expected)
});
step.Given(/^a table step with Table rowHash$/, function(table:Table){
var expected = {
'Cucumber': 'Cucumis sativus',
'Burr Gherkin': 'Cucumis anguria'
};
assert.deepEqual(table.rowsHash(), expected)
});
step.Given(/^a table step$/, function(table:Table){
var expected = [
{'Vegetable': 'Apricot', 'Rating': '5'},
{'Vegetable': 'Brocolli', 'Rating': '2'},
{'Vegetable': 'Cucumber', 'Rating': '10'}
];
assert.deepEqual(table.hashes(), expected)
});
}
+11 -2
View File
@@ -7,11 +7,20 @@ declare namespace cucumber {
export interface CallbackStepDefinition{
pending : () => PromiseLike<any>;
(errror?:any):void;
(errror?:any, pending?: string):void;
}
export interface TableDefinition{
raw: () => Array<any>;
rows: () => Array<any>;
rowsHash: () => {};
hashes: () => {};
}
type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition;
interface StepDefinitionCode {
(...stepArgs: Array<string |CallbackStepDefinition>): PromiseLike<any> | any | void;
(...stepArgs: Array<StepDefinitionParam>): PromiseLike<any> | any | void;
}
interface StepDefinitionOptions{
Vendored
+5 -3
View File
@@ -297,7 +297,7 @@ declare namespace d3 {
* @param value the function to compute data for each node
*/
datum<NewDatum>(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update<NewDatum>;
/**
* Set the data item for each node in the selection.
* @param value the constant element to use for each node
@@ -415,7 +415,7 @@ declare namespace d3 {
select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection<Datum>;
call(func: (selection: Enter<Datum>, ...args: any[]) => any, ...args: any[]): Enter<Datum>;
empty(): boolean;
size(): number;
}
@@ -1078,7 +1078,7 @@ declare namespace d3 {
* Return the min and max simultaneously.
*/
export function extent<T>(array: T[], accessor: (datum: T, index: number) => string): [string, string];
/**
* Return the min and max simultaneously.
*/
@@ -2928,6 +2928,8 @@ declare namespace d3 {
start(): Force<Link, Node>;
tick(): Force<Link, Node>;
alpha(): number;
alpha(value: number): Force<Link, Node>;
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="date-fns.d.ts" />
import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns';
import * as addHours from 'date-fns/add_hours';
function test() {
addDays(new Date(), 5);
closestIndexTo(new Date(), [new Date(), new Date()]);
addHours(new Date(), 5);
differenceInCalendarWeeks(new Date(), new Date());
differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1});
max(new Date(), new Date());
isDate({});
}
+1195
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -11,7 +11,7 @@ interface JQuery {
daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery;
}
declare module daterangepicker {
declare namespace daterangepicker {
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
@@ -164,3 +164,7 @@ declare module daterangepicker {
monthNames?: string[];
}
}
declare module "daterangepicker" {
export = daterangepicker;
}
+322
View File
@@ -0,0 +1,322 @@
// Test file for db-migrate-base Definition file
/// <reference path="db-migrate-base.d.ts" />
import * as DbMigrateBase from "db-migrate-base";
// Throw together a dummy driver
let db = <DbMigrateBase.Base>{};
let callback = (err: any, response: any) => {
// Do nothing.
};
/// createTable(tableName, columnSpec, callback)
db.createTable('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}, callback);
db.createTable('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}, callback);
/// dropTable(tableName, [options,] callback)
db.dropTable('pets', callback);
db.dropTable('pets', { ifExists: true }, callback);
/// renameTable(tableName, newTableName, callback)
db.renameTable('pets', 'pets_OLD', callback);
/// addColumn(tableName, columnName, columnSpec, callback)
db.addColumn('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}, callback);
db.addColumn('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}, callback);
/// renameColumn(tableName, oldColumnName, newColumnName, callback)
db.renameColumn('pets', 'id', 'pet_id', callback);
/// changeColumn(tableName, columnName, columnSpec, callback)
db.changeColumn('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}, callback);
/// addIndex(tableName, indexName, columns, [unique,] callback)
db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback);
db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback);
/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback)
db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}, callback);
/// removeForeignKey(tableName, keyName, options, callback)
db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback);
db.removeForeignKey('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}, callback);
/// insert(tableName, [columnNameArray,] valueArray, callback)
db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback);
db.insert('module_user', ['Test', 'Testerson'], callback);
/// removeIndex([tableName,] indexName, callback)
db.removeIndex('pets', 'pets_eye_color_idx', callback);
db.removeIndex('pets_eye_color_idx', callback);
/// runSql(sql, [params,] callback)
db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
], callback);
db.runSql('DROP TABLE `pets`', callback);
/// all(sql, [params,] callback)
db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback);
db.all('SELECT * FROM `module_user`', callback);
/// =========
/// Async
/// =========
let onResolve = (result: any) => {};
/// createTableAsync(tableName, columnSpec)
db.createTableAsync('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}).then(onResolve);
db.createTableAsync('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}).then(onResolve);
/// dropTableAsync(tableName, [options])
db.dropTableAsync('pets').then(onResolve);
db.dropTableAsync('pets', { ifExists: true }).then(onResolve);
/// renameTableAsync(tableName, newTableName)
db.renameTableAsync('pets', 'pets_OLD').then(onResolve);
/// addColumnAsync(tableName, columnName, columnSpec)
db.addColumnAsync('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}).then(onResolve);
db.addColumnAsync('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}).then(onResolve);
/// renameColumnAsync(tableName, oldColumnName, newColumnName)
db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve);
/// changeColumnAsync(tableName, columnName, columnSpec)
db.changeColumnAsync('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}).then(onResolve);
/// addIndexAsync(tableName, indexName, columns, [unique])
db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve);
db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve);
/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules)
db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}).then(onResolve);
/// removeForeignKeyAsync(tableName, keyName, options)
db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve);
db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}).then(onResolve);
/// insertAsync(tableName, [columnNameArray,] valueArray)
db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve);
db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve);
/// removeIndexAsync([tableName,] indexName)
db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve);
db.removeIndexAsync('pets_eye_color_idx').then(onResolve);
/// runSqlAsync(sql, [params])
db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
]).then(onResolve);
db.runSqlAsync('DROP TABLE `pets`').then(onResolve);
/// allAsync(sql, [params])
db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve);
db.allAsync('SELECT * FROM `module_user`').then(onResolve);
+152
View File
@@ -0,0 +1,152 @@
// Type definitions for db-migrate-base
// Project: https://github.com/db-migrate/db-migrate-base
// Definitions by: nickiannone <https://github.com/nickiannone>
// Definitions: https://github.com/nickiannone/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts"/>
/// <reference path="../node/node.d.ts"/>
declare module "db-migrate-base" {
import * as Promise from "bluebird";
export interface CallbackFunction { (err: any, response: any): void; }
export interface InternalModule {
log: any;
type: any;
}
export interface InternalOptions {
mod: InternalModule;
}
export interface ColumnSpec {
length?: number;
type: string;
unsigned?: boolean;
primaryKey?: boolean;
autoIncrement?: boolean;
notNull?: boolean;
unique?: boolean;
defaultValue?: any;
foreignKey?: ForeignKeySpec;
}
export interface ForeignKeySpec {
name: string;
table: string;
rules?: ForeignKeyRules;
mapping: string | any;
}
export interface ForeignKeyRules {
onDelete: string;
onUpdate: string;
}
export interface RemoveForeignKeyOptions {
dropIndex?: boolean;
}
export interface ColumnDef {
foreignKey?: any; // TODO Figure this out!
constraints: string;
}
export interface CreateTableOptions {
columns?: Array<ColumnSpec>;
ifNotExists?: boolean;
}
export interface DropTableOptions {
ifExists?: boolean;
}
export class Base {
constructor(intern: InternalOptions);
close(callback?: CallbackFunction): void;
mapDataType(str: string): string;
truncate(tableName: string, callback: CallbackFunction): void;
checkDBMS(dbms: any, callback: CallbackFunction): void;
createDatabase(...options: any[]): void;
switchDatabase(...options: any[]): void;
dropDatabase(...options: any[]): void;
recurseCallbackArray(foreignKeys: Array<string>, callback: CallbackFunction): void;
bindForeignKey(tableName: string, columnName: string, fkOptions: ForeignKeySpec): (callback: CallbackFunction) => void;
createColumnDef(name: string, spec: ColumnSpec, options?: any): ColumnDef; // TODO Figure out a type for `options`!
//createColumnConstraint(spec: ColumnSpec, options?: any, ...implementationDefinedOptions: any[]): string;
createMigrationsTable(callback: CallbackFunction): void;
createSeedsTable(callback: CallbackFunction): void;
createTable(tableName: string, options: any | CreateTableOptions, callback: CallbackFunction): void;
dropTable(tableName: string, optionsOrCb?: DropTableOptions | CallbackFunction, callback?: CallbackFunction): void;
renameTable(tableName: string, newTableName: string, callback: CallbackFunction): void;
addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void;
removeColumn(tableName: string, columnName: string, callback: CallbackFunction): void;
renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback: CallbackFunction): void;
changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void;
quoteDDLArr(arr: Array<string>): Array<string>;
quoteArr(arr: Array<string>): Array<string>;
addIndex(tableName: string, indexName: string, columns: string | Array<string>, uniqueOrCb?: boolean | CallbackFunction, callback?: CallbackFunction): void;
insert(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): void;
update(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): void;
lookup(tableName: string, column: string, id?: any, callback?: CallbackFunction): void;
removeIndex(tableNameOrIndexName: string, indexNameOrCb?: string | CallbackFunction, callback?: CallbackFunction): void;
addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules, callback: CallbackFunction): void;
removeForeignKey(tableName: string, keyName: string, optionsOrCb?: RemoveForeignKeyOptions | CallbackFunction, callback?: CallbackFunction): void;
normalizeColumnSpec(spec: string | ColumnSpec): ColumnSpec;
addMigrationRecord(name: string, callback: CallbackFunction): void;
addSeedRecord(name: string, callback: CallbackFunction): void;
startMigration(callback: CallbackFunction): void;
endMigration(callback: CallbackFunction): void;
runSql(sql?: string, paramsOrCb?: Array<any> | CallbackFunction, callback?: CallbackFunction): void;
allLoadedMigrations(callback: CallbackFunction): void;
allLoadedSeeds(callback: CallbackFunction): void;
deleteMigration(migrationName: string, callback: CallbackFunction): void;
remove(table: string, ids: any, callback: CallbackFunction): void; // TODO Make ids match the type of ids in buildWhereClause(ids);
buildWhereClause(ids: any): string;
deleteSeed(seedName: string, callback: CallbackFunction): void;
all(sql: string, paramsOrCb?: Array<any> | CallbackFunction, callback?: CallbackFunction): void;
escape(str: string): string;
escapeString(str: string): string;
escapeDDL(str: string): string;
// Promisified methods
closeAsync(): Promise<any>;
truncateAsync(tableName: string): Promise<any>;
checkDBMSAsync(dbms: any): Promise<any>;
createDatabaseAsync(...options: any[]): Promise<any>;
switchDatabaseAsync(...options: any[]): Promise<any>;
dropDatabaseAsync(...options: any[]): Promise<any>;
recurseCallbackArrayAsync(foreignKeys: Array<string>): Promise<any>;
createMigrationsTableAsync(): Promise<any>;
createSeedsTableAsync(): Promise<any>;
createTableAsync(tableName: string, options: any | CreateTableOptions): Promise<any>;
dropTableAsync(tableName: string, options?: DropTableOptions): Promise<any>;
renameTableAsync(tableName: string, newTableName: string): Promise<any>;
addColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise<any>;
removeColumnAsync(tableName: string, columnName: string): Promise<any>;
renameColumnAsync(tableName: string, oldColumnName: string, newColumnName: string): Promise<any>;
changeColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise<any>;
addIndexAsync(tableName: string, indexName: string, columns: string | Array<string>, unique?: boolean): Promise<any>;
insertAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise<any>;
updateAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise<any>;
lookupAsync(tableName: string, column: string, id?: any, callback?: CallbackFunction): Promise<any>;
removeIndexAsync(tableNameOrIndexName: string, indexName?: string): Promise<any>;
addForeignKeyAsync(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules): Promise<any>;
removeForeignKeyAsync(tableName: string, keyName: string, options?: RemoveForeignKeyOptions): Promise<any>;
addMigrationRecordAsync(name: string): Promise<any>;
addSeedRecordAsync(name: string): Promise<any>;
startMigrationAsync(): Promise<any>;
endMigrationAsync(callback: CallbackFunction): Promise<any>;
runSqlAsync(sql?: string, params?: Array<any>): Promise<any>;
allLoadedMigrationsAsync(): Promise<any>;
allLoadedSeedsAsync(): Promise<any>;
deleteMigrationAsync(migrationName: string): Promise<any>;
removeAsync(table: string, ids: any): Promise<any>;
deleteSeedAsync(seedName: string): Promise<any>;
allAsync(sql: string, params?: Array<any>): Promise<any>;
}
}
+411
View File
@@ -0,0 +1,411 @@
// Test file for db-migrate-pg Definition file
/// <reference path="db-migrate-pg.d.ts" />
import * as DbMigratePg from "db-migrate-pg";
// Throw together a dummy driver
let db = <DbMigratePg.PgDriver>{};
let callback = (err: any, response: any) => {
// Do nothing.
};
/// createTable(tableName, columnSpec, callback)
db.createTable('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}, callback);
db.createTable('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}, callback);
db.createTable('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}, callback);
/// dropTable(tableName, [options,] callback)
db.dropTable('pets', callback);
db.dropTable('pets', { ifExists: true }, callback);
/// renameTable(tableName, newTableName, callback)
db.renameTable('pets', 'pets_OLD', callback);
/// addColumn(tableName, columnName, columnSpec, callback)
db.addColumn('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}, callback);
db.addColumn('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}, callback);
/// renameColumn(tableName, oldColumnName, newColumnName, callback)
db.renameColumn('pets', 'id', 'pet_id', callback);
/// changeColumn(tableName, columnName, columnSpec, callback)
db.changeColumn('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}, callback);
/// addIndex(tableName, indexName, columns, [unique,] callback)
db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback);
db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback);
/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback)
db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}, callback);
/// removeForeignKey(tableName, keyName, options, callback)
db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback);
db.removeForeignKey('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}, callback);
/// insert(tableName, [columnNameArray,] valueArray, callback)
db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback);
db.insert('module_user', ['Test', 'Testerson'], callback);
/// removeIndex([tableName,] indexName, callback)
db.removeIndex('pets', 'pets_eye_color_idx', callback);
db.removeIndex('pets_eye_color_idx', callback);
/// runSql(sql, [params,] callback)
db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
], callback);
db.runSql('DROP TABLE `pets`', callback);
/// all(sql, [params,] callback)
db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback);
db.all('SELECT * FROM `module_user`', callback);
/// =========
/// Async
/// =========
let onResolve = (result: any) => {};
/// createTableAsync(tableName, columnSpec)
db.createTableAsync('pets', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
}).then(onResolve);
db.createTableAsync('pets', {
columns: {
id: { type: 'int', primaryKey: true, autoIncrement: true },
name: 'string'
},
ifNotExists: true
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: 'id'
}
}
}).then(onResolve);
db.createTableAsync('product_variant',
{
id: {
type: 'int',
unsigned: true,
notNull: true,
primaryKey: true,
autoIncrement: true,
length: 10
},
product_id: {
type: 'int',
unsigned: true,
length: 10,
notNull: true,
foreignKey: {
name: 'product_variant_product_id_fk',
table: 'product',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
product_id: 'id'
}
}
}
}).then(onResolve);
/// dropTableAsync(tableName, [options])
db.dropTableAsync('pets').then(onResolve);
db.dropTableAsync('pets', { ifExists: true }).then(onResolve);
/// renameTableAsync(tableName, newTableName)
db.renameTableAsync('pets', 'pets_OLD').then(onResolve);
/// addColumnAsync(tableName, columnName, columnSpec)
db.addColumnAsync('pets', 'eyeColor', {
type: 'string',
length: 25,
notNull: true,
}).then(onResolve);
db.addColumnAsync('pets', 'id', {
type: 'int',
primaryKey: true,
autoIncrement: true,
notNull: true,
unique: true
}).then(onResolve);
/// renameColumnAsync(tableName, oldColumnName, newColumnName)
db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve);
/// changeColumnAsync(tableName, columnName, columnSpec)
db.changeColumnAsync('pets', 'eye_color', {
type: 'int',
unsigned: true,
notNull: true,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
eye_color: 'id'
}
}
}).then(onResolve);
/// addIndexAsync(tableName, indexName, columns, [unique])
db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve);
db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve);
/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules)
db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk',
{
'module_id': 'id'
},
{
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
}).then(onResolve);
/// removeForeignKeyAsync(tableName, keyName, options)
db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve);
db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', {
dropIndex: true,
}).then(onResolve);
/// insertAsync(tableName, [columnNameArray,] valueArray)
db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve);
db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve);
/// removeIndexAsync([tableName,] indexName)
db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve);
db.removeIndexAsync('pets_eye_color_idx').then(onResolve);
/// runSqlAsync(sql, [params])
db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [
'first_name', 'last_name',
'Test', 'Testerson'
]).then(onResolve);
db.runSqlAsync('DROP TABLE `pets`').then(onResolve);
/// allAsync(sql, [params])
db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve);
db.allAsync('SELECT * FROM `module_user`').then(onResolve);
/// ====================
/// PG-specific tests
/// ====================
/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY)
let constraint: DbMigratePg.ColumnConstraint;
constraint = db.createColumnConstraint({
type: 'int',
length: 10,
unsigned: true,
primaryKey: false,
autoIncrement: false,
notNull: true,
unique: false,
defaultValue: 0,
foreignKey: {
name: 'pets_eye_color_id_fk',
table: 'eye_color',
rules: {
onDelete: 'CASCADE',
onUpdate: 'RESTRICT'
},
mapping: {
'eye_color': 'id'
}
}
}, {
emitPrimaryKey: false
}, 'pets', 'eye_color');
// Print the SQL constraints
console.log(constraint.constraints);
// Invoke the foreign key builder
constraint.foreignKey(callback);
/// Public Callback Methods:
/// createDatabase(dbName, [options,] callback)
db.createDatabase('petstore', callback);
db.createDatabase('petstore', {}, callback);
/// dropDatabase(dbName, [options,] callback)
db.dropDatabase('petstore', callback);
db.dropDatabase('petstore', { ifExists: true }, callback);
/// createSequence(sqName, [options,] callback)
db.createSequence('pets_id_sq', callback);
db.createSequence('pets_id_sq', { temp: true }, callback);
/// switchDatabase(options, callback)
db.switchDatabase('petstore', callback);
db.switchDatabase({ database: 'petstore' }, callback);
/// dropSequence(sqName, [options,] callback)
db.dropSequence('pets_id_sq', callback);
db.dropSequence('pets_id_sq', {
ifExists: true,
cascade: true,
restrict: true,
}, callback);
/// Public Promisified Methods:
/// createDatabaseAsync(dbName, [options])
db.createDatabaseAsync('petstore').then(onResolve);
db.createDatabaseAsync('petstore', {}).then(onResolve);
/// dropDatabaseAsync(dbName, [options])
db.dropDatabaseAsync('petstore').then(onResolve);
db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve);
/// createSequenceAsync(sqName, [options])
db.createSequenceAsync('pets_id_sq').then(onResolve);
db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve);
/// switchDatabaseAsync(options)
db.switchDatabaseAsync('petstore').then(onResolve);
db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve);
/// dropSequenceAsync(sqName, [options])
db.dropSequenceAsync('pets_id_sq').then(onResolve);
db.dropSequenceAsync('pets_id_sq', {
ifExists: true,
cascade: true,
restrict: true,
}).then(onResolve);
+60
View File
@@ -0,0 +1,60 @@
// Type definitions for db-migrate-pg
// Project: https://github.com/db-migrate/pg
// Definitions by: nickiannone <http://github.com/nickiannone>
// Definitions: https://github.com/nickiannone/DefinitelyTyped
/// <reference path="../db-migrate-base/db-migrate-base.d.ts"/>
/// <reference path="../pg/pg.d.ts" />
declare module "db-migrate-pg" {
import * as pg from "pg";
import * as DbMigrateBase from "db-migrate-base";
import * as Promise from "bluebird";
// Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options.
export interface CreateDatabaseOptions {}
export interface DropDatabaseOptions {
ifExists?: boolean;
}
export interface CreateSequenceOptions {
temp?: boolean;
}
export interface SwitchDatabaseOptions {
database?: string;
}
export interface DropSequenceOptions {
ifExists?: boolean;
cascade?: boolean;
restrict?: boolean;
}
export interface ColumnConstraint {
foreignKey: (callback: DbMigrateBase.CallbackFunction) => void;
constraints: string;
}
export interface ColumnConstraintOptions {
emitPrimaryKey?: boolean;
}
export class PgDriver extends DbMigrateBase.Base {
constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions);
createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void;
dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void;
createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint;
createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise<any>;
dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise<any>;
createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise<any>;
switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise<any>;
dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise<any>;
}
}
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="./diff2html.d.ts" />
import Diff2Html = require('diff2html');
let d2h = Diff2Html.Diff2Html;
class Diff2HtmlOptionsImpl implements Diff2Html.Options {
constructor (public inputFormat: string) {
}
}
let strInput =
'diff --git a/sample b/sample\n' +
'index 0000001..0ddf2ba\n' +
'--- a/sample\n' +
'+++ b/sample\n' +
'@@ -1 +1 @@\n' +
'-test\n' +
'+test1r\n';
let strConfiguration = new Diff2HtmlOptionsImpl('diff');
let diffInput = d2h.getJsonFromDiff(strInput, strConfiguration);
let diffConfiguration = new Diff2HtmlOptionsImpl('json');
let htmlString = d2h.getPrettyHtml(diffInput, diffConfiguration);
console.log(htmlString);
+66
View File
@@ -0,0 +1,66 @@
// Type definitions for diff2html
// Project: https://github.com/rtfpessoa/diff2html
// Definitions by: rtfpessoa <https://github.com/rtfpessoa/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Diff2Html {
export interface Options {
inputFormat?: string;
outputFormat?: string;
showFiles?: boolean;
matching?: string;
synchronisedScroll?: boolean;
matchWordsThreshold?: number;
matchingMaxComparisons?: number;
}
export interface Line {
content: string;
type: string;
oldNumber: number;
newNumber: number;
}
export interface Block {
oldStartLine: number;
oldStartLine2?: number;
newStartLine: number;
header: string;
lines: Line[];
}
export interface Result {
addedLines: number;
deletedLines: number;
isCombined: boolean;
isGitDiff: boolean;
oldName: string;
newName: string;
language: string;
blocks: Block[];
oldMode?: string;
newMode?: string;
deletedFileMode?: string;
newFileMode?: string;
isDeleted?: boolean;
isNew?: boolean;
isCopy?: boolean;
isRename?: boolean;
unchangedPercentage?: number;
changedPercentage?: number;
checksumBefore?: string;
checksumAfter?: string;
mode?: string;
}
export interface Diff2Html {
getJsonFromDiff(input: string, configuration?: Options): Result;
getPrettyHtml(input: any, configuration?: Options): string;
}
}
declare module "diff2html" {
var d2h: { "Diff2Html": Diff2Html.Diff2Html };
export = d2h;
}
+17 -1
View File
@@ -5686,7 +5686,23 @@ declare namespace dojo {
* @param dest The object to which to copy/add all properties contained in source. If dest is falsy, thena new object is manufactured before copying/adding properties begins.
* @param sources One of more objects from which to draw all properties to copy into dest. sources are processedleft-to-right and if more than one of these objects contain the same property name, the right-mostvalue "wins".
*/
mixin(dest: Object, source: Object, sources?: Object[]): Object;
mixin<T>(dest: T): T;
mixin<T, U>(
dest: T,
source: U
): T & U;
mixin<T, U, V>(
dest: T,
source1: U,
source2: V
): T & U & V;
mixin<T, U, V, W>(
dest: T,
source1: U,
source2: V,
source3: W
): T & U & V & W;
mixin<T>(dest: Object, ...sources: Object[]): T;
/**
* similar to hitch() except that the scope object is left to be
* whatever the execution context eventually becomes.
+3 -3
View File
@@ -89,7 +89,7 @@ declare module "dustjs-linkedin" {
* Registers an event listener. Streams accept a single listener for a given event.
* @param evt the event. Possible values are data, end, error (maybe more, look in the source).
*/
on(evt: string, callback: (data?: any) => any);
on(evt: string, callback: (data?: any) => any): this;
pipe(stream: Stream): Stream;
}
@@ -126,8 +126,8 @@ declare module "dustjs-linkedin" {
* @param name the template name.
* @param context a plain object or an instance of dust.Context.
*/
export function render(name: string, context: any, callback: (err: any, out: string) => any);
export function render(name: string, context: Context, callback: (err: any, out: string) => any);
export function render(name: string, context: any, callback: (err: any, out: string) => any): void;
export function render(name: string, context: Context, callback: (err: any, out: string) => any): void;
/**
* Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required.
+48
View File
@@ -0,0 +1,48 @@
/// <reference path="../react/react.d.ts" />
/// <reference path="./dva.d.ts" />
import React = __React;
import dva from 'dva';
import { connect } from 'dva';
import { Router, Route } from 'dva/router';
// 1. Initialize
const app = dva();
// 2. Model
app.model({
namespace: 'count',
state: 0,
reducers: {
add(count: number) {
return count + 1
},
minus(count: number) {
return count - 1
},
},
});
// 3. View
const App = connect(({ count }) => ({
count
}))(function ({ count, dispatch }) {
return (
<div>
<h2>{ count }</h2>
<button key="add" onClick={() => { dispatch({type: 'count/add'})}}>+</button>
<button key="minus" onClick={() => { dispatch({type: 'count/minus'})}}>-</button>
</div>
);
});
// 4. Router
app.router(({ history }) =>
<Router history={history}>
<Route path="/" component={App}/>
</Router>
);
// 5. Start
const countApp = app.start();
+61
View File
@@ -0,0 +1,61 @@
// Type definitions for dva v1.0.0
// Project: https://github.com/dvajs/dva
// Definitions by: nikogu <https://github.com/nikogu/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../react/react.d.ts" />
declare module 'dva' {
/** connecting Container Components */
export function connect(maps:Object):Function;
export default function dva(opts?:Object):{
/** dva plugin */
use: (hooks:Object)=>void,
/** dva bootstrap */
start: (selector?:String|HTMLElement)=>void,
/** dva add model */
model: (model:Object)=>void,
/** dva setting router */
router: (router:Object)=>Object|JSX.Element,
};
}
/**
* https://github.com/reactjs/react-router
*/
declare module 'dva/router' {
import React = __React;
interface RouterProps {
history?: Object
}
export class Router extends React.Component<RouterProps, {}> {
render():JSX.Element
}
interface RouteProps {
path?: string,
component?: React.ReactNode
}
export class Route extends React.Component<RouteProps, {}> {
render():JSX.Element
}
/**
* https://github.com/reactjs/react-router-redux
*/
export class routerRedux {}
}
/**
* https://github.com/fis-components/whatwg-fetch
*/
declare module 'dva/fetch' {
export default Function;
}
+210 -210
View File
File diff suppressed because it is too large Load Diff
+53
View File
@@ -32,4 +32,57 @@ client.indices.delete({
ignore: [404]
}).then(function (body) {
}, function (error) {
});
client.create({
id: '123',
index: 'index',
type: 'type'
});
client.create({
id: '123',
index: 'index',
type: 'type'
}, (err, repsonse, status) => {
});
client.cluster.getSettings({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.health({
masterTimeout: 100
}, (err, response) => {
});
client.cluster.pendingTasks({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.putSettings({
ignore: 1
}, (err, response) => {
});
client.cluster.reroute({
ignore: 1
}, (err, response) => {
});
client.cluster.state({
ignore: 1
}, (err, response) => {
});
client.cluster.stats({
ignore: 1
}, (err, response) => {
});
+121 -7
View File
@@ -1,24 +1,28 @@
// Type definitions for elasticsearch
// Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html
// Definitions by: Casper Skydt <https://github.com/CasperSkydt/DefinitelyTyped>
// Definitions by: Casper Skydt <https://github.com/CasperSkydt>, Blake Smith <https://github.com/bfsmith>, Dave Dunkin <https://github.com/ddunkin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module Elasticsearch {
export class Client {
constructor(params: ConfigOptions);
indices: Indices;
cluster: Cluster;
cat: Cat;
bulk(params: BulkIndexDocumentsParams): PromiseLike<any>;
bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void;
create(params: CreateDocumentParams): PromiseLike<any>;
create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void;
delete(params: DeleteDocumentParams): PromiseLike<any>;
delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void;
get(params: GetParams, callback: (error: any, response: any) => void): void;
get<T>(params: GetParams, callback: (error: any, response: GetResponse<T>) => void): void;
get<T>(params: GetParams): PromiseLike<GetResponse<T>>;
index<T>(params: IndexDocumentParams<T>): PromiseLike<any>;
index<T>(params: IndexDocumentParams<T>, callback: (error: any, response: any) => void): void;
mget(params: MGetParams, callback: (error: any, response: any) => void): void;
mget<T>(params: MGetParams): PromiseLike<GetResponse<T>>;
msearch(params: MSearchParams, callback: (error: any, response: any) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<GetResponse<T>>;
mget<T>(params: MGetParams, callback: (error: any, response: MGetResponse<T>) => void): void;
mget<T>(params: MGetParams): PromiseLike<MGetResponse<T>>;
msearch<T>(params: MSearchParams, callback: (error: any, response: MSearchResponse<T>) => void): void;
msearch<T>(params: MSearchParams): PromiseLike<MSearchResponse<T>>;
ping(params: PingParams): PromiseLike<any>;
ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void;
scroll(params: ScrollParams): PromiseLike<any>;
@@ -102,6 +106,21 @@ declare module Elasticsearch {
index?: string;
}
export interface CreateDocumentParams extends GenericParams {
consistency?: "one" | "quorum" | "all";
parent?: string;
refressh?: boolean;
routing?: string;
timeout?: number | Date;
timestamp?: number | Date;
ttl?: number;
version?: number;
versionType?: "internal" | "external" | "external_gte" | "force";
id: string;
index: string;
type: string;
}
export interface IndicesGetParams extends GenericParams {
ignoreUnavailable?: boolean;
index: string | string[] | boolean;
@@ -177,7 +196,8 @@ declare module Elasticsearch {
versionType?: string;
}
export interface GetResponse<T> extends GenericParams {
export interface GetResponse<T> {
_index: string;
_type: string;
_id: string;
_version: number;
@@ -213,6 +233,7 @@ declare module Elasticsearch {
scroll?: string;
search_type?: string;
fields?: string[];
from?: number;
size?: number;
sort?: string | string[] | boolean;
_source?: string | string[] | boolean;
@@ -259,6 +280,10 @@ declare module Elasticsearch {
search_type?: string;
}
export interface MSearchResponse<T> {
responses?: SearchResponse<T>[];
}
export interface MGetParams extends GenericParams {
fields?: string | string[] | Boolean;
preference?: string;
@@ -270,6 +295,10 @@ declare module Elasticsearch {
type?: string;
}
export interface MGetResponse<T> {
docs?: GetResponse<T>[];
}
export interface IndicesIndexExitsParams extends GenericParams {
index: string | string[] | boolean;
ignoreUnavailable?: boolean;
@@ -316,6 +345,91 @@ declare module Elasticsearch {
body: string | any;
index: string | string[] | boolean;
}
export interface Cat {
health(params: CatHealthOptions, callback: (error: any, response: any) => void): void;
health(params: CatHealthOptions): PromiseLike<any>
}
export interface CatHealthOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
h?: string | string[] | boolean;
help?: boolean;
ts?: boolean;
v?: boolean;
}
export interface Cluster {
getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void;
getSettings(params: ClusterGetSettingsOptions): PromiseLike<any>;
health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void;
health(params: ClusterHealthOptions): PromiseLike<any>;
pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void;
pendingTasks(params: ClusterPendingTasksOptions): PromiseLike<any>;
putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void;
putSettings(params: ClusterPutSettingsOptions): PromiseLike<any>;
reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void;
reroute(params: ClusterRerouteOptions): PromiseLike<any>;
state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void;
state(params: ClusterStateOptions): PromiseLike<any>;
stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void;
stats(params: ClusterStatsOptions): PromiseLike<any>;
}
export interface ClusterGetSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterHealthOptions extends GenericParams {
level?: string; // cluster, indices, shards
local?: boolean;
masterTimeout?: number | Date;
waitForActiveShards?: number;
waitForNodes?: string;
waitForRelocatingShards?: number;
waitForStatus?: string; // green, yellow, red
index?: string | string[] | boolean;
}
export interface ClusterPendingTasksOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
}
export interface ClusterPutSettingsOptions extends GenericParams {
flatSettings?: boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterRerouteOptions extends GenericParams {
dryRun?: boolean;
explain?: boolean;
metric?: string | string[] | boolean;
masterTimeout?: number | Date;
timeout?: number | Date;
}
export interface ClusterStateOptions extends GenericParams {
local?: boolean;
masterTimeout?: number | Date;
flatSettings?: boolean;
ignoreUnavailable?: boolean;
allowNoIndices?: boolean;
expandWildcards?: string; // open, closed, none, all (default open)
index?: string | string[] | boolean;
metric?: string | string[] | boolean;
}
export interface ClusterStatsOptions extends GenericParams {
flatSettings?: boolean;
human?: boolean;
timeout?: number | Date;
nodeId?: string | string[] | boolean;
}
}
declare module "elasticsearch" {
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="./electron-notify.d.ts" />
import * as eNotify from 'electron-notify';
eNotify.setConfig({
appIcon: 'images/otherIcon.png',
displayTime: 6000,
defaultStyleText: {
color: '#FF0000',
fontWeight: 'bold'
}
});
eNotify.notify({
title: 'Title',
text: 'Some text',
image: 'path/to/image.png',
url: 'http://google.de',
sound: 'notification.wav',
onClickFunc: (event) => {
console.log('onClick ' + event.id);
event.closeNotification('onClick');
},
onShowFunc: (event) => { console.log('onShow ' + event.id) },
onCloseFunc: (event) => { console.log('onClose ' + event.id) }
});
+64
View File
@@ -0,0 +1,64 @@
// Type definitions for electron-notify v0.1.0
// Project: https://github.com/hankbao/electron-notify
// Definitions by: Daniel Pereira <https://github.com/djpereira>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../github-electron/github-electron.d.ts" />
/** Nice and simple notifications for electron apps */
declare module 'electron-notify' {
export interface ICustomConfig {
width?: number,
height?: number,
padding?: number,
borderRadius?: number,
displayTime?: number,
animationSteps?: number,
animationStepMs?: number,
animateInParallel?: boolean,
appIcon?: string,
pathToModule?: string,
logging?: boolean,
defaultWindow?: Electron.BrowserWindowOptions,
defaultStyleContainer?: any,
defaultStyleAppIcon?: any,
defaultStyleImage?: any,
defaultStyleClose?: any,
defaultStyleText?: any
}
export interface ICloseNotificationEvent {
event: 'close' | 'show' | 'click',
id: number
}
export interface INotificationEvent extends ICloseNotificationEvent {
closeNotification: (reason: any) => void,
}
export interface INotification {
title: string,
text?: string,
image?: string,
url?: string,
sound?: string,
onClickFunc?: (event: INotificationEvent) => void,
onShowFunc?: (event: INotificationEvent) => void,
onCloseFunc?: (event: ICloseNotificationEvent) => void
}
/** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */
export function setConfig(customConfig: ICustomConfig): void;
/** Displays new notification. */
export function notify(notification: INotification): void;
/** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */
export function closeAll(): void;
export function getTemplatePath(): string;
export function setTemplatePath(path: string): void;
}
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="../estree/estree.d.ts" />
/// <reference path="esprima-walk.d.ts" />
import * as walk from 'esprima-walk'
var program: ESTree.Program
var string: string
var node: ESTree.Node
walk(program, _node => {
string = node.type
node = _node
})
walk.walk(program, _node => {
string = node.type
node = _node
})
walk.walkAddParent(program, _node => {
node = _node
node = _node.parent
string = node.type
})
+40
View File
@@ -0,0 +1,40 @@
// Type definitions for esprima-walk v0.1.0
// Project: https://github.com/jrajav/esprima-walk
// Definitions by: tswaters <https://github.com/tswaters>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare module "esprima-walk" {
interface NodeWithParent extends ESTree.Node {
parent?: ESTree.Node
}
/**
* Walk the provided AST; fn is called once for each node with a `type`
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node with type
*/
function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void
namespace walk {
/**
* Walk the provided AST; fn is called once for each node with a `type`
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node
*/
export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void
/**
* Walk the provided AST; fn is called once for each node with a `type`.
* Adds a parent property prior to invoking fn when applicable
* @param {ESTree.Program} ast program to walk
* @param {function} fn function invoked for each node
*/
export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void
}
export = walk
}
+1
View File
@@ -12,6 +12,7 @@ var string: string;
string = esprima.version;
program = esprima.parse('code');
program = esprima.parse('code', {range: true});
program = esprima.parse('import * as code from "code"', {sourceType: 'module'})
token = esprima.tokenize('code')[0];
token = esprima.tokenize('code', {range: true})[0];
+1
View File
@@ -30,6 +30,7 @@ declare namespace esprima {
attachComment?: boolean;
tolerant?: boolean;
source?: boolean;
sourceType?: 'script' | 'module';
}
const Syntax: {
+4 -4
View File
@@ -43,7 +43,7 @@ declare class EventEmitter2 {
* @param event
* @param listener
*/
on(event: string, listener: Function): EventEmitter2;
on(event: string | string[], listener: Function): EventEmitter2;
/**
* Adds a listener that will be fired when any event is emitted.
@@ -128,7 +128,7 @@ declare class EventEmitter2 {
* @param event
* @param args
*/
emit(event: string, ...args: any[]): boolean;
emit(event: string | string[], ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
@@ -156,7 +156,7 @@ declare module "eventemitter2" {
* @param event
* @param listener
*/
on(event: string, listener: Function): EventEmitter2;
on(event: string | string[], listener: Function): EventEmitter2;
/**
* Adds a listener that will be fired when any event is emitted.
@@ -241,7 +241,7 @@ declare module "eventemitter2" {
* @param event
* @param args
*/
emit(event: string, ...args: any[]): boolean;
emit(event: string | string[], ...args: any[]): boolean;
/**
* Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
+11 -6
View File
@@ -22,7 +22,7 @@ declare module "express-serve-static-core" {
}
interface RequestHandler {
(req: Request, res: Response, next: NextFunction): any;
(req: Request, res: Response, next?: NextFunction): any;
}
interface ErrorRequestHandler {
@@ -117,11 +117,11 @@ declare module "express-serve-static-core" {
interface CookieOptions {
maxAge?: number;
signed?: boolean;
expires?: Date;
expires?: Date | boolean;
httpOnly?: boolean;
path?: string;
domain?: string;
secure?: boolean;
secure?: boolean | 'auto';
}
interface Errback { (err: Error): void; }
@@ -199,7 +199,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted charset of the specified character sets,
* based on the request’s Accept-Charset HTTP header field.
* based on the request's 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.
@@ -212,7 +212,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted encoding of the specified encodings,
* based on the request’s Accept-Encoding HTTP header field.
* based on the request's 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.
@@ -225,7 +225,7 @@ declare module "express-serve-static-core" {
/**
* Returns the first accepted language of the specified languages,
* based on the request’s Accept-Language HTTP header field.
* based on the request's 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.
@@ -1046,6 +1046,11 @@ declare module "express-serve-static-core" {
* simply by removing them from this object.
*/
routes: any;
/**
* Using to all registered routes in Express Application
*/
_router: any;
}
interface Express extends Application {
+2 -1
View File
@@ -6,7 +6,8 @@ import session = require('express-session');
var app = express();
app.use(session({
secret: 'keyboard cat'
secret: 'keyboard cat',
cookie: { secure: 'auto' }
}));
app.use(session({
secret: 'keyboard cat',
+1 -1
View File
@@ -30,7 +30,7 @@ declare namespace Express {
secure?: boolean;
httpOnly: boolean;
domain?: string;
expires: Date;
expires: Date | boolean;
serialize: (name: string, value: string) => string;
}
}
+9 -5
View File
@@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) {
// Similarly checkParams only checks in req.params (URL params) and
// checkQuery only checks req.query (GET params).
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i');
req.checkQuery('getparam', 'Invalid getparam').isInt();
req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase();
req.checkFiles('testFiles', 'Invalid testFiles').isUrl();
req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase();
req.checkFiles('testFiles', 'Invalid testFiles').isURL();
// OR assert can be used to check on all 3 types of params.
// req.assert('postparam', 'Invalid postparam').notEmpty().isInt();
// req.assert('urlparam', 'Invalid urlparam').isAlpha();
// req.assert('getparam', 'Invalid getparam').isInt();
req.sanitize('postparam').toBoolean();
req.filter('postparam').toBoolean();
req.sanitize('postparam').blacklist('t').blacklist(['<script', '</script>']).whitelist('hello').whitelist(['h', 'e', 'l']);
req.sanitizeBody('postvar').trim().stripLow().escape();
req.sanitizeQuery('queryvar').toDate();
req.sanitizeParams('urlparam').toFloat().toInt().toInt(10);
req.sanitizeHeaders('header').normalizeEmail();
var errors = req.validationErrors();
var mappedErrors = req.validationErrors(true);
+88 -47
View File
@@ -1,9 +1,10 @@
// Type definitions for express-validator 2.9.0
// Type definitions for express-validator 2.20.4
// Project: https://github.com/ctavan/express-validator
// Definitions by: Nathan Ridley <https://github.com/axefrog/>, Jonathan Häberle <http://dreampulse.de>
// Definitions by: Nathan Ridley <https://github.com/axefrog/>, Jonathan Häberle <http://dreampulse.de>, Peter Harris <https://github.com/codeanimal/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../express/express.d.ts" />
/// <reference path="../bluebird/bluebird.d.ts" />
// Add RequestValidation Interface on to Express's Request Interface.
declare namespace Express {
@@ -31,25 +32,33 @@ declare namespace ExpressValidator {
param: string;
}
interface ValidatorFunction { (item: string, message: string): Validator; }
interface ValidatorFunction { (item: string | {}, message?: string): Validator; }
interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }
interface SanitizerFunction { (item: string): Sanitizer; }
interface Dictionary<T> { [key: string]: T; }
export interface RequestValidation {
assert: ValidatorFunction;
check: ValidatorFunction;
assert: ValidatorExtraFunction;
validate: ValidatorExtraFunction;
check: ValidatorExtraFunction;
checkBody: ValidatorFunction;
checkFiles: ValidatorFunction;
checkHeader: ValidatorFunction;
checkHeaders: ValidatorFunction;
checkParams: ValidatorFunction;
checkQuery: ValidatorFunction;
validate: ValidatorFunction;
filter: SanitizerFunction;
sanitize: SanitizerFunction;
sanitizeBody: SanitizerFunction;
sanitizeQuery: SanitizerFunction;
sanitizeParams: SanitizerFunction;
sanitizeHeaders: SanitizerFunction;
onValidationError(errback: (msg: string) => void): void;
validationErrors(mapped?: boolean): Dictionary<any> | any[];
validationErrors(mapped?: boolean): Dictionary<MappedError> | MappedError[];
validationErrors<T>(mapped?: boolean): Dictionary<T> | T[];
asyncValidationErrors(mapped?: boolean): Promise<MappedError[] | Dictionary<MappedError>>;
asyncValidationErrors<T>(mapped?: boolean): Promise<T[] | Dictionary<T>>;
}
export interface Validator {
@@ -61,12 +70,13 @@ declare namespace ExpressValidator {
* Alias for notRegex()
*/
not(): Validator;
isEmail(): Validator;
isEmail(options?:{}): Validator;
/**
* Accepts http, https, ftp
*/
isUrl(): Validator;
isURL(): Validator;
isFQDN(options?: MinMaxOptions): Validator;
/**
* Combines isIPv4 and isIPv6
*/
@@ -74,8 +84,21 @@ declare namespace ExpressValidator {
isIPv4(): Validator;
isIPv6(): Validator;
isMACAddress(): Validator;
isAlpha(): Validator;
isAlphanumeric(): Validator;
isISBN(version?: number): Validator;
isISIN(): Validator;
isISO8601(): Validator;
isMobilePhone(locale: string): Validator;
isMongoId(): Validator;
isMultibyte(): Validator;
isAlpha(locale?: string): Validator;
isAlphanumeric(locale?: string): Validator;
isAscii(): Validator;
isBase64(): Validator;
isBoolean(): Validator;
isByteLength(options: MinMaxOptions): Validator;
isCurrency(options: {}): Validator;
isDataURI(): Validator;
isDivisibleBy(num: number): Validator;
isNumeric(): Validator;
isHexadecimal(): Validator;
/**
@@ -85,7 +108,7 @@ declare namespace ExpressValidator {
/**
* isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't
*/
isInt(): Validator;
isInt(options?: MinMaxOptions): Validator;
isLowercase(): Validator;
isUppercase(): Validator;
isDecimal(): Validator;
@@ -93,10 +116,12 @@ declare namespace ExpressValidator {
* Alias for isDecimal
*/
isFloat(): Validator;
isFullWidth(): Validator;
isHalfWidth(): Validator;
isVariableWidth(): Validator;
/**
* Check if length is 0
*/
notNull(): Validator;
isNull(): Validator;
/**
* Not just whitespace (input.trim().length !== 0)
@@ -104,12 +129,13 @@ declare namespace ExpressValidator {
notEmpty(): Validator;
equals(equals:any): Validator;
contains(str:string): Validator;
notContains(str:string): Validator;
/**
* Usage: regex(/[a-z]/i) or regex('[a-z]','i')
* Usage: matches(/[a-z]/i) or matches('[a-z]','i')
*/
regex(pattern:string, modifiers:string): Validator;
notRegex(pattern:string, modifiers:string): Validator;
matches(pattern:string, modifiers?:string): Validator;
matches(pattern: RegExp): Validator;
/**
* max is optional
*/
@@ -117,7 +143,7 @@ declare namespace ExpressValidator {
/**
* Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier
*/
isUUID(version:number): Validator;
isUUID(version?:number): Validator;
/**
* Alias for isUUID(3)
*/
@@ -137,17 +163,20 @@ declare namespace ExpressValidator {
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isAfter(date:Date): Validator;
isAfter(date?:Date): Validator;
/**
* Argument is optional and defaults to today. Comparison is non-inclusive
*/
isBefore(date:Date): Validator;
isBefore(date?:Date): Validator;
isIn(options:string): Validator;
isIn(options:string[]): Validator;
notIn(options:string): Validator;
notIn(options:string[]): Validator;
max(val:string): Validator;
min(val:string): Validator;
isJSON(): Validator;
isLength(options: MinMaxOptions): Validator;
isWhitelisted(chars: string): Validator;
/**
* Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats
*/
@@ -155,7 +184,10 @@ declare namespace ExpressValidator {
/**
* Check an input only when the input exists
*/
optional(): Validator;
isSurrogatePar(): Validator;
optional(options?: { checkFalsy?: boolean }): Validator;
withMessage(message: string): Validator;
}
interface Sanitizer {
@@ -165,40 +197,49 @@ declare namespace ExpressValidator {
trim(...chars:string[]): Sanitizer;
ltrim(...chars:string[]): Sanitizer;
rtrim(...chars:string[]): Sanitizer;
ifNull(replace:any): Sanitizer;
stripLow(keep_new_lines?: boolean): Sanitizer;
toFloat(): Sanitizer;
toInt(): Sanitizer;
toInt(radix?: number): Sanitizer;
/**
* True unless str = '0', 'false', or str.length == 0
*/
toBoolean(): Sanitizer;
/**
* False unless str = '1' or 'true'
*/
toBooleanStrict(): Sanitizer;
/**
* Decode HTML entities
* True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true.
*/
toBoolean(strict?: boolean): Sanitizer;
/**
* Convert the input string to a date, or null if the input is not a date.
*/
toDate(): Sanitizer;
entityDecode(): Sanitizer;
entityEncode(): Sanitizer;
* Convert the input string to a date, or null if the input is not a date.
*/
toDate(): Sanitizer;
/**
* Escape &, <, >, and "
*/
escape(): Sanitizer;
/**
* Remove common XSS attack vectors from user-supplied HTML
* Replaces HTML encoded entities with <, >, &, ', " and /.
*/
xss(): Sanitizer;
unescape(): Sanitizer;
blacklist(chars: string): Sanitizer;
blacklist(chars: string[]): Sanitizer;
whitelist(chars: string): Sanitizer;
whitelist(chars: string[]): Sanitizer;
normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer;
/**
* Remove common XSS attack vectors from images
* !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization)
*/
xss(fromImages:boolean): Sanitizer;
}
interface MappedError {
param: string;
msg: string;
value: string;
}
interface MinMaxOptions {
min?: number;
max?: number;
}
}
+8
View File
@@ -1,4 +1,5 @@
/// <reference path="express.d.ts" />
/// <reference path="../node/node.d.ts" />
import * as express from 'express';
var app = express();
@@ -91,3 +92,10 @@ app.listen(3000);
const next: express.NextFunction = () => {};
const nextWithArgument: express.NextFunction = (err: any) => {};
/**
* The express.Application is compatible with http.createServer
*/
import * as http from 'http';
http.createServer(app);
-2
View File
@@ -333,7 +333,6 @@ declare namespace fabric {
on(eventName: {[key:string] : Function}): T;
/**
* Fires event with an optional options object
* @deprecated `fire` deprecated since 1.0.7 (use `trigger` instead)
* @param {String} eventName Event name to fire
* @param {Object} [options] Options object
*/
@@ -341,7 +340,6 @@ declare namespace fabric {
/**
* Stops event observing for a particular event handler. Calling this method
* without arguments removes all handlers for all events
* @deprecated `stopObserving` deprecated since 0.8.34 (use `off` instead)
* @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler})
* @param handler Function to be deleted from EventListeners
*/
+12
View File
@@ -30,3 +30,15 @@ fetchMock.called("http://test.com");
(fetchMock.lastCall()[1] as RequestInit).body;
fetchMock.lastUrl();
fetchMock.lastOptions();
fetchMock.get("http://test.com", 200)
fetchMock.post("http://test.com", 200)
fetchMock.put("http://test.com", 200)
fetchMock.delete("http://test.com", 200)
fetchMock.head("http://test.com", 200)
fetchMock.get("http://test.com", 200, {method: "GET"})
fetchMock.post("http://test.com", 200, {method: "POST"})
fetchMock.put("http://test.com", 200, {method: "PUT"})
fetchMock.delete("http://test.com", 200, {method: "DELETE"})
fetchMock.head("http://test.com", 200, {method: "HEAD"})

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