Merge pull request #3 from DefinitelyTyped/master

Merge from DefinitelyTyped/master
This commit is contained in:
Dmitry A. Efimenko
2016-09-15 10:05:38 -07:00
committed by GitHub
341 changed files with 36379 additions and 6521 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 -5
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;
@@ -238,7 +239,6 @@ declare namespace angular {
* @param directiveFactory An injectable directive factory function.
*/
directive(name: string, inlineAnnotatedFunction: any[]): IModule;
directive(name: string, injectionFunction: Function): IModule;
directive(object: Object): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
@@ -1412,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 {
@@ -1746,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.
@@ -1767,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;
+1
View File
@@ -42,6 +42,7 @@ interface Auth0ClientOptions {
/** Represents a normalized UserProfile. */
interface Auth0UserProfile {
email: string;
email_verified: boolean;
family_name: string;
gender: string;
given_name: string;
@@ -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
+13 -39
View File
@@ -4,55 +4,29 @@ 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;
var identity: lambda.Identity;
var identity: lambda.CognitoIdentity;
var error: Error;
/* 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 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;
/* Identity */
var identity: lambda.Identity;
/* CognitoIdentity */
var identity: lambda.CognitoIdentity;
str = identity.cognitoIdentityId;
str = identity.cognitoIdentityPoolId;
+48 -35
View File
@@ -1,55 +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;
/** Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. It can be null. */
identity?: Identity;
succeed(message: string, object: any): void;
}
interface Identity {
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.
* @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';
}
}
+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
+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.
+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) => {
});
+106 -1
View File
@@ -1,14 +1,18 @@
// 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/DefinitelyTyped>, Blake Smith <https://github.com/bfsmith/DefinitelyTyped>
// 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;
@@ -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;
@@ -213,6 +232,7 @@ declare module Elasticsearch {
scroll?: string;
search_type?: string;
fields?: string[];
from?: number;
size?: number;
sort?: string | string[] | boolean;
_source?: string | string[] | boolean;
@@ -316,6 +336,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" {
+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: {
+9 -4
View File
@@ -121,7 +121,7 @@ declare module "express-serve-static-core" {
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',
-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"})
+70
View File
@@ -114,6 +114,26 @@ declare module "fetch-mock" {
unmatched: Array<MockCall>;
}
interface MockOptionsMethodGet extends MockOptions {
method: 'GET'
}
interface MockOptionsMethodPost extends MockOptions {
method: 'POST'
}
interface MockOptionsMethodPut extends MockOptions {
method: 'PUT'
}
interface MockOptionsMethodDelete extends MockOptions {
method: 'DELETE'
}
interface MockOptionsMethodHead extends MockOptions {
method: 'HEAD'
}
interface FetchMockStatic {
/**
* Replaces fetch() with a stub which records its calls, grouped by
@@ -139,6 +159,56 @@ declare module "fetch-mock" {
* @param options The route to mock
*/
mock(options: MockOptions): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Shorthand for mock() restricted to the GET
method. Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param [options] Additional properties defining the route to mock
*/
get(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Shorthand for mock() restricted to the POST
method. Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param [options] Additional properties defining the route to mock
*/
post(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPost): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Shorthand for mock() restricted to the PUT
method. Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param [options] Additional properties defining the route to mock
*/
put(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Shorthand for mock() restricted to the
DELETE method. Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param [options] Additional properties defining the route to mock
*/
delete(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodDelete): this;
/**
* Replaces fetch() with a stub which records its calls, grouped by
route, and optionally returns a mocked Response object or passes the
call through to fetch(). Shorthand for mock() restricted to the HEAD
method. Calls to .mock() can be chained.
* @param matcher Condition for selecting which requests to mock
* @param response Configures the http response returned by the mock
* @param [options] Additional properties defining the route to mock
*/
head(matcher: MockMatcher, reponse: MockResponse | MockResponseFunction, options?: MockOptionsMethodHead): this;
/**
* Chainable method that restores fetch() to its unstubbed state and
clears all data recorded for its calls.
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="file-type.d.ts" />
"use strict";
import fileType = require("file-type")
fileType(new Buffer([0xFF, 0xD8, 0xFF]))
+17
View File
@@ -0,0 +1,17 @@
// Type definitions for file-type
// Project: https://github.com/sindresorhus/file-type
// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <http://github.com/tcaesvk/>
// Definitions: https://github.com/DefinitelyType/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "file-type" {
interface FileTypeResult {
ext: string
mime: string
}
function FileType(buf: Buffer): FileTypeResult
export = FileType
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path='fill-pdf.d.ts' />
import * as fillPdf from 'fill-pdf';
var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' };
var pdfTemplatePath = 'templates.pdf';
var extendArgs: string[] = [];
fillPdf.generatePdf(formData, pdfTemplatePath, extendArgs, (err: Error, output: Buffer) => {
if ( !err ) {
console.log('Success!');
// output is a buffer
}
});
var result = fillPdf.generateFdf(formData);
// result is a buffer
+16
View File
@@ -0,0 +1,16 @@
// Type definitions for fill-pdf v0.5.0
// Project: https://github.com/dommmel/fill-pdf
// Definitions by: Seth Westphal <https://github.com/westy92>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'fill-pdf' {
export interface FormData {
[name: string]: string;
}
export function generatePdf(data: FormData, templatePath: string, extendArgs: string[], callback?: (err: Error, output: Buffer) => void): void;
export function generateFdf(data: FormData): Buffer;
}
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="./fluent-ffmpeg.d.ts" />
import ffmpeg = require("fluent-ffmpeg")
let source: string, format: string, output: string
ffmpeg({ source: source }).format(format).save(output)
+315
View File
@@ -0,0 +1,315 @@
// Type definitions for node-fluent-ffmpeg
// Project: https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <http://github.com/tcaesvk/>
// Definitions: https://github.com/DefinitelyType/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "fluent-ffmpeg" {
import * as events from "events"
import * as stream from "stream"
interface FfmpegCommandLogger {
error(...data: any[]): void
warning(...data: any[]): void
info(...data: any[]): void
debug(...data: any[]): void
}
interface FfmpegCommandOptions {
logger?: FfmpegCommandLogger
niceness?: number
priority?: number
presets?: string
preset?: string
stdoutLines?: number
timeout?: number
source?: string | stream.Readable
}
interface FilterSpecification {
filter: string
inputs: string | string[]
outputs: string | string[]
options?: Object | string | any[]
}
interface GetPreset {
(command: FfmpegCommand): string
}
interface Filter {
description: string
input: string
multipleInputs: boolean
output: string
multipleOutputs: boolean
}
interface Filters {
[key: string]: Filter
}
interface FiltersCallback {
(err: Error, filters: Filters): void
}
interface Codec {
type: string
description: string
canDecode: boolean
canEncode: boolean
drawHorizBand?: boolean
directRendering?: boolean
weirdFrameTruncation?: boolean
intraFrameOnly?: boolean
isLossy?: boolean
isLossless?: boolean
}
interface Codecs {
[key: string]: Codec
}
interface CodecsCallback {
(err: Error, codecs: Codecs): void
}
interface Encoder {
type: string
description: string
frameMT: boolean
sliceMT: boolean
experimental: boolean
drawHorizBand: boolean
directRendering: boolean
}
interface Encoders {
[key: string]: Encoder
}
interface EncodersCallback {
(err: Error, encoders: Encoders): void
}
interface Format {
description: string
canDemux: boolean
canMux: boolean
}
interface Formats {
[key: string]: Format
}
interface FormatsCallback {
(err: Error, formats: Formats): void
}
interface FfprobeData {
stream: any[]
format: any
chapters: any[]
}
interface ScreenshotsConfig {
count?: number
folder?: string
filename?: string
timemarks?: number[] | string[]
timestamps?: number[] | string[]
fastSeek?: boolean
size?: string
}
interface FfmpegCommand extends events.EventEmitter {
constructor(): FfmpegCommand
constructor(options: FfmpegCommandOptions): FfmpegCommand
constructor(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand
// options/inputs
mergeAdd(source: string | stream.Readable): FfmpegCommand
addInput(source: string | stream.Readable): FfmpegCommand
input(source: string | stream.Readable): FfmpegCommand
withInputFormat(format: string): FfmpegCommand
inputFormat(format: string): FfmpegCommand
fromFormat(format: string): FfmpegCommand
withInputFps(fps: number): FfmpegCommand
withInputFPS(fps: number): FfmpegCommand
withFpsInput(fps: number): FfmpegCommand
withFPSInput(fps: number): FfmpegCommand
inputFPS(fps: number): FfmpegCommand
inputFps(fps: number): FfmpegCommand
fpsInput(fps: number): FfmpegCommand
FPSInput(fps: number): FfmpegCommand
nativeFramerate(): FfmpegCommand
withNativeFramerate(): FfmpegCommand
native(): FfmpegCommand
setStartTime(seek: string | number): FfmpegCommand
seekInput(seek: string | number): FfmpegCommand
loop(duration: string | number): FfmpegCommand
// options/audio
withNoAudio(): FfmpegCommand
noAudio(): FfmpegCommand
withAudioCodec(codec: string): FfmpegCommand
audioCodec(codec: string): FfmpegCommand
withAudioBitrate(bitrate: string | number): FfmpegCommand
audioBitrate(bitrate: string | number): FfmpegCommand
withAudioChannels(channels: number): FfmpegCommand
audioChannels(channels: number): FfmpegCommand
withAudioFrequency(freq: number): FfmpegCommand
audioFrequency(freq: number): FfmpegCommand
withAudioQuality(quality: number): FfmpegCommand
audioQuality(quality: number): FfmpegCommand
withAudioFilter(filters: { filter: string, options: any }): FfmpegCommand
withAudioFilters(filters: { filter: string, options: any }): FfmpegCommand
audioFilter(filters: { filter: string, options: any }): FfmpegCommand
audioFilters(filters: { filter: string, options: any }): FfmpegCommand
// options/video
withNoVideo(): FfmpegCommand
noVideo(): FfmpegCommand
withVideoCodec(codec: string): FfmpegCommand
videoCodec(codec: string): FfmpegCommand
withVideoBitrate(bitrate: string | number): FfmpegCommand
videoBitrate(bitrate: string | number): FfmpegCommand
withVideoFilter(filters: { filter: string, options: any }): FfmpegCommand
withVideoFilters(filters: { filter: string, options: any }): FfmpegCommand
videoFilter(filters: { filter: string, options: any }): FfmpegCommand
videoFilters(filters: { filter: string, options: any }): FfmpegCommand
withOutputFps(fps: number): FfmpegCommand
withOutputFPS(fps: number): FfmpegCommand
withFpsOutput(fps: number): FfmpegCommand
withFPSOutput(fps: number): FfmpegCommand
withFps(fps: number): FfmpegCommand
withFPS(fps: number): FfmpegCommand
outputFPS(fps: number): FfmpegCommand
outputFps(fps: number): FfmpegCommand
fpsOutput(fps: number): FfmpegCommand
FPSOutput(fps: number): FfmpegCommand
fps(fps: number): FfmpegCommand
FPS(fps: number): FfmpegCommand
takeFrames(frames: number): FfmpegCommand
withFrames(frames: number): FfmpegCommand
frames(frames: number): FfmpegCommand
// options/videosize
keepPixelAspect(): FfmpegCommand
keepDisplayAspect(): FfmpegCommand
keepDisplayAspectRatio(): FfmpegCommand
keepDAR(): FfmpegCommand
withSize(size: string): FfmpegCommand
setSize(size: string): FfmpegCommand
size(size: string): FfmpegCommand
withAspect(aspect: string | number): FfmpegCommand
withAspectRatio(aspect: string | number): FfmpegCommand
setAspect(aspect: string | number): FfmpegCommand
setAspectRatio(aspect: string | number): FfmpegCommand
aspect(aspect: string | number): FfmpegCommand
aspectRatio(aspect: string | number): FfmpegCommand
applyAutopadding(pad: boolean, color: string): FfmpegCommand
applyAutoPadding(pad: boolean, color: string): FfmpegCommand
applyAutopad(pad: boolean, color: string): FfmpegCommand
applyAutoPad(pad: boolean, color: string): FfmpegCommand
withAutopadding(pad: boolean, color: string): FfmpegCommand
withAutoPadding(pad: boolean, color: string): FfmpegCommand
withAutopad(pad: boolean, color: string): FfmpegCommand
withAutoPad(pad: boolean, color: string): FfmpegCommand
autoPad(pad: boolean, color: string): FfmpegCommand
autopad(pad: boolean, color: string): FfmpegCommand
// options/output
addOutput(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand
output(target: string | stream.Writable, pipeopts?: { end?: boolean }): FfmpegCommand
seekOutput(seek: string | number): FfmpegCommand
seek(seek: string | number): FfmpegCommand
withDuration(duration: string | number): FfmpegCommand
setDuration(duration: string | number): FfmpegCommand
duration(duration: string | number): FfmpegCommand
toFormat(format: string): FfmpegCommand
withOutputFormat(format: string): FfmpegCommand
outputFormat(format: string): FfmpegCommand
format(format: string): FfmpegCommand
map(spec: string): FfmpegCommand
updateFlvMetadata(): FfmpegCommand
flvmeta(): FfmpegCommand
// options/custom
addInputOption(options: string[]): FfmpegCommand
addInputOption(...options: string[]): FfmpegCommand
addInputOptions(options: string[]): FfmpegCommand
addInputOptions(...options: string[]): FfmpegCommand
withInputOption(options: string[]): FfmpegCommand
withInputOption(...options: string[]): FfmpegCommand
withInputOptions(options: string[]): FfmpegCommand
withInputOptions(...options: string[]): FfmpegCommand
inputOption(options: string[]): FfmpegCommand
inputOption(...options: string[]): FfmpegCommand
inputOptions(options: string[]): FfmpegCommand
inputOptions(...options: string[]): FfmpegCommand
addOutputOption(options: string[]): FfmpegCommand
addOutputOption(...options: string[]): FfmpegCommand
addOutputOptions(options: string[]): FfmpegCommand
addOutputOptions(...options: string[]): FfmpegCommand
addOption(options: string[]): FfmpegCommand
addOption(...options: string[]): FfmpegCommand
addOptions(options: string[]): FfmpegCommand
addOptions(...options: string[]): FfmpegCommand
withOutputOption(options: string[]): FfmpegCommand
withOutputOption(...options: string[]): FfmpegCommand
withOutputOptions(options: string[]): FfmpegCommand
withOutputOptions(...options: string[]): FfmpegCommand
withOption(options: string[]): FfmpegCommand
withOption(...options: string[]): FfmpegCommand
withOptions(options: string[]): FfmpegCommand
withOptions(...options: string[]): FfmpegCommand
outputOption(options: string[]): FfmpegCommand
outputOption(...options: string[]): FfmpegCommand
outputOptions(options: string[]): FfmpegCommand
outputOptions(...options: string[]): FfmpegCommand
filterGraph(spec: string | FilterSpecification[], map: string[]): FfmpegCommand
complexFilter(spec: string | FilterSpecification[], map: string[]): FfmpegCommand
// options/misc
usingPreset(proset: string | GetPreset): FfmpegCommand
pnreset(proset: string | GetPreset): FfmpegCommand
// processor
renice(niceness: number): FfmpegCommand
kill(signal: string): FfmpegCommand
// capabilities
setFfmpegPath(path: string): FfmpegCommand
setFfprobePath(path: string): FfmpegCommand
setFlvtoolPath(path: string): FfmpegCommand
availableFilters(callback: FiltersCallback): void
getAvailableFilters(callback: FiltersCallback): void
availableCodecs(callback: CodecsCallback): void
getAvailableCodecs(callback: CodecsCallback): void
availableEncoders(callback: EncodersCallback): void
getAvailableEncoders(callback: EncodersCallback): void
availableFormats(callback: FormatsCallback): void
getAvailableFormats(callback: FormatsCallback): void
// ffprobe
ffprobe(callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void
ffprobe(index: number, callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void
ffprobe(options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void
ffprobe(index: number, options: string[], callback: (err: any, data: FfprobeData) => void): (err: any, data: FfprobeData) => void
// recipes
saveToFile(output: string): FfmpegCommand
save(output: string): FfmpegCommand
writeToStream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable
pipe(stream: stream.Writable, options?: { end?: boolean }): stream.Writable
stream(stream: stream.Writable, options?: { end?: boolean }): stream.Writable
takeScreenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand
thumbnail(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand
thumbnails(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand
screenshot(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand
screenshots(config: number | ScreenshotsConfig, folder?: string): FfmpegCommand
mergeToFile(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand
concatenate(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand
concat(target: string | stream.Writable, options?: { end?: boolean }): FfmpegCommand
}
function Ffmpeg(): FfmpegCommand
function Ffmpeg(options: FfmpegCommandOptions): FfmpegCommand
function Ffmpeg(input: string | stream.Readable, options: FfmpegCommandOptions): FfmpegCommand
export = Ffmpeg
}
+2 -1
View File
@@ -79,8 +79,9 @@ declare module "fs-extra" {
export interface CopyOptions {
clobber?: boolean
preserveTimestamps?: boolean
dereference?: boolean
dereference?: boolean
filter?: CopyFilter
recursive?: boolean
}
export interface OpenOptions {
+11 -9
View File
@@ -25,15 +25,17 @@ declare namespace FullCalendar {
end: moment.Moment;
}
export interface Header {
left: string;
center: string;
right: string;
}
export interface Options extends AgendaOptions, EventDraggingResizingOptions, DroppingExternalElementsOptions, SelectionOptions {
// General display - http://fullcalendar.io/docs/display/
header?: {
left: string;
center: string;
right: string;
}
theme?: boolean
header?: boolean | Header;
theme?: boolean;
buttonIcons?: {
prev: string;
next: string;
@@ -50,7 +52,7 @@ declare namespace FullCalendar {
contentHeight?: number;
aspectRatio?: number;
handleWindowResize?: boolean;
views?: ViewSpecificOptions;
views?: ViewSpecificOptions;
viewRender?: (view: ViewObject, element: JQuery) => void;
viewDestroy?: (view: ViewObject, element: JQuery) => void;
dayRender?: (date: Date, cell: HTMLTableDataCellElement) => void;
@@ -318,7 +320,7 @@ interface JQuery {
/**
* Moves the calendar to an arbitrary date.
*/
fullCalendar(method: 'gotoDate', date: Date | string): void;
fullCalendar(method: 'gotoDate', date: moment.Moment | Date | string): void;
/**
* Moves the calendar forward/backward an arbitrary amount of time.
@@ -403,4 +405,4 @@ interface JQuery {
interface JQueryStatic {
fullCalendar: FullCalendar.Calendar;
}
}
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="geojson2osm.d.ts" />
/// <reference path="../geojson/geojson.d.ts" />
import { geojson2osm } from 'geojson2osm'
const features: GeoJSON.FeatureCollection<any> = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
properties: {
'building:colour': '#9F8169',
'building:levels': 21,
building: 'yes',
height: 57,
},
geometry: {
type: 'Polygon',
coordinates: [
[
[
-434.2249470949173,
-13.15996269397843,
],
[
-434.2249470949173,
-13.159751140560356,
],
[
-434.2242631316185,
-13.159751140560356,
],
[
-434.2242631316185,
-13.15996269397843,
],
[
-434.2249470949173,
-13.15996269397843,
],
],
],
},
},
],
}
geojson2osm(features)
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for geojson2osm 0.0.5
// Project: https://github.com/Rub21/geojson2osm
// Definitions by: Denis Carriere <https://github.com/DenisCarriere>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../geojson/geojson.d.ts" />
declare module 'geojson2osm' {
/**
* Converts GeoJSON features to OpenStreetMap XML.
* @param features Input features
* @returns OpenStreetMap XML
*/
export function geojson2osm(features: GeoJSON.Feature<any> | GeoJSON.FeatureCollection<any>): any
}
@@ -240,6 +240,63 @@ app.setUserTasks([
}
]);
app.setUserTasks([]);
app.setJumpList([
{
type: 'custom',
name: 'Recent Projects',
items: [
{ type: 'file', path: 'C:\\Projects\\project1.proj' },
{ type: 'file', path: 'C:\\Projects\\project2.proj' }
]
},
{ // has a name so type is assumed to be "custom"
name: 'Tools',
items: [
{
type: 'task',
title: 'Tool A',
program: process.execPath,
args: '--run-tool-a',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool A'
},
{
type: 'task',
title: 'Tool B',
program: process.execPath,
args: '--run-tool-b',
iconPath: process.execPath,
iconIndex: 0,
description: 'Runs Tool B'
}]
},
{
type: 'frequent'
},
{ // has no name and no type so type is assumed to be "tasks"
items: [
{
type: 'task',
title: 'New Project',
program: process.execPath,
args: '--new-project',
description: 'Create a new project.'
},
{
type: 'separator'
},
{
type: 'task',
title: 'Recover Project',
program: process.execPath,
args: '--recover-project',
description: 'Recover Project'
}]
}
]);
if (app.isUnityRunning()) {
}
if (app.isAccessibilitySupportEnabled()) {
+153 -14
View File
@@ -1,4 +1,4 @@
// Type definitions for Electron v1.3.3
// Type definitions for Electron v1.3.5
// Project: http://electron.atom.io/
// Definitions by: jedmao <https://github.com/jedmao/>, rhysd <https://rhysd.github.io>, Milan Burda <https://github.com/miniak/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -7,7 +7,7 @@
declare namespace Electron {
class EventEmitter implements NodeJS.EventEmitter {
class EventEmitter extends NodeJS.EventEmitter {
addListener(event: string, listener: Function): this;
on(event: string, listener: Function): this;
once(event: string, listener: Function): this;
@@ -199,7 +199,7 @@ declare namespace Electron {
* All windows will be closed immediately without asking user
* and the before-quit and will-quit events will not be emitted.
*/
exit(exitCode: number): void;
exit(exitCode?: number): void;
/**
* Relaunches the app when current instance exits.
*
@@ -296,28 +296,56 @@ declare namespace Electron {
* Once registered, all links with your-protocol:// will be opened with the current executable.
* The whole link, including protocol, will be passed to your application as a parameter.
*
* On Windows you can provide optional parameters path, the path to your executable,
* and args, an array of arguments to be passed to your executable when it launches.
*
* @param protocol The name of your protocol, without ://.
* @param path Defaults to process.execPath.
* @param args Defaults to an empty array.
*
* Note: This is only implemented on macOS and Windows.
* On macOS, you can only register protocols that have been added to your app's info.plist.
*/
setAsDefaultProtocolClient(protocol: string): boolean;
setAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean;
/**
* Removes the current executable as the default handler for a protocol (aka URI scheme).
*
* @param protocol The name of your protocol, without ://.
* @param path Defaults to process.execPath.
* @param args Defaults to an empty array.
*
* Note: This is only implemented on macOS and Windows.
*/
removeAsDefaultProtocolClient(protocol: string): boolean;
removeAsDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean;
/**
* @param protocol The name of your protocol, without ://.
* @param path Defaults to process.execPath.
* @param args Defaults to an empty array.
*
* @returns Whether the current executable is the default handler for a protocol (aka URI scheme).
*
* Note: This is only implemented on macOS and Windows.
*/
isDefaultProtocolClient(protocol: string): boolean;
isDefaultProtocolClient(protocol: string, path?: string, args?: string[]): boolean;
/**
* Adds tasks to the Tasks category of JumpList on Windows.
*
* Note: This API is only available on Windows.
*/
setUserTasks(tasks: Task[]): boolean;
/**
* Note: This API is only available on Windows.
*/
getJumpListSettings(): JumpListSettings;
/**
* Sets or removes a custom Jump List for the application.
*
* If categories is null the previously set custom Jump List (if any) will be replaced
* by the standard Jump List for the app (managed by Windows).
*
* Note: This API is only available on Windows.
*/
setJumpList(categories: JumpListCategory[]): SetJumpListResult;
/**
* This method makes your application a Single Instance Application instead of allowing
* multiple instances of your app to run, this will ensure that only a single instance
@@ -545,6 +573,89 @@ declare namespace Electron {
iconIndex?: number;
}
/**
* ok - Nothing went wrong.
* error - One or more errors occured, enable runtime logging to figure out the likely cause.
* invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List.
* Separators are only allowed in the standard Tasks category.
* fileTypeRegistrationError - An attempt was made to add a file link to the Jump List
* for a file type the app isn't registered to handle.
* customCategoryAccessDeniedError - Custom categories can't be added to the Jump List
* due to user privacy or group policy settings.
*/
type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError';
interface JumpListSettings {
/**
* The minimum number of items that will be shown in the Jump List.
*/
minItems: number;
/**
* Items that the user has explicitly removed from custom categories in the Jump List.
*/
removedItems: JumpListItem[];
}
interface JumpListCategory {
/**
* tasks - Items in this category will be placed into the standard Tasks category.
* frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows.
* recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows.
* custom - Displays tasks or file links, name must be set by the app.
*/
type?: 'tasks' | 'frequent' | 'recent' | 'custom';
/**
* Must be set if type is custom, otherwise it should be omitted.
*/
name?: string;
/**
* Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted.
*/
items?: JumpListItem[];
}
interface JumpListItem {
/**
* task - A task will launch an app with specific arguments.
* separator - Can be used to separate items in the standard Tasks category.
* file - A file link will open a file using the app that created the Jump List.
*/
type: 'task' | 'separator' | 'file';
/**
* Path of the file to open, should only be set if type is file.
*/
path?: string;
/**
* Path of the program to execute, usually you should specify process.execPath which opens the current program.
* Should only be set if type is task.
*/
program?: string;
/**
* The command line arguments when program is executed. Should only be set if type is task.
*/
args?: string;
/**
* The text to be displayed for the item in the Jump List. Should only be set if type is task.
*/
title?: string;
/**
* Description of the task (displayed in a tooltip). Should only be set if type is task.
*/
description?: string;
/**
* The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary
* resource file that contains an icon (e.g. .ico, .exe, .dll).
* You can usually specify process.execPath to show the program icon.
*/
iconPath?: string;
/**
* The index of the icon in the resource file. If a resource file contains multiple icons
* this value can be used to specify the zero-based index of the icon that should be displayed
* for this task. If a resource file contains only one icon, this property should be set to zero.
*/
iconIndex?: number;
}
interface LoginItemSettings {
/**
* True if the app is set to open at login.
@@ -630,7 +741,7 @@ declare namespace Electron {
* Emitted when the document changed its title,
* calling event.preventDefault() would prevent the native window’s title to change.
*/
on(event: 'page-title-updated', listener: (event: Event) => void): this;
on(event: 'page-title-updated', listener: (event: Event, title: string) => void): this;
/**
* Emitted when the window is going to be closed. It’s emitted before the beforeunload
* and unload event of the DOM. Calling event.preventDefault() will cancel the close.
@@ -2947,18 +3058,22 @@ declare namespace Electron {
interface NetworkEmulationOptions {
/**
* Whether to emulate network outage.
* Default: false.
*/
offline?: boolean;
/**
* RTT in ms.
* Default: 0, which will disable latency throttling.
*/
latency?: number;
/**
* Download rate in Bps.
* Default: 0, which will disable download throttling.
*/
downloadThroughput?: number;
/**
* Upload rate in Bps.
* Default: 0, which will disable upload throttling.
*/
uploadThroughput?: number;
}
@@ -3576,7 +3691,7 @@ declare namespace Electron {
interface WebContentsStatic {
/**
* @returns An array of all web contents. This will contain web contents for all windows,
* @returns An array of all WebContents instances. This will contain web contents for all windows,
* webviews, opened devtools, and devtools extension background pages.
*/
getAllWebContents(): WebContents[];
@@ -3584,6 +3699,10 @@ declare namespace Electron {
* @returns The web contents that is focused in this application, otherwise returns null.
*/
getFocusedWebContents(): WebContents;
/**
* Find a WebContents instance according to its ID.
*/
fromId(id: number): WebContents;
}
/**
@@ -3687,7 +3806,7 @@ declare namespace Electron {
* navigation outside of the page. Examples of this occurring are when anchor links
* are clicked or when the DOM hashchange event is triggered.
*/
on(event: 'did-navigate-in-page', listener: (event: Event, url: string) => void): this;
on(event: 'did-navigate-in-page', listener: (event: Event, url: string, isMainFrame: boolean) => void): this;
/**
* Emitted when the renderer process has crashed.
*/
@@ -4382,7 +4501,7 @@ declare namespace Electron {
/**
* PEM encoded data.
*/
data: Buffer;
data: string;
/**
* Issuer's Common Name.
*/
@@ -4952,6 +5071,17 @@ declare namespace Electron {
* See webContents.sendInputEvent for detailed description of event object.
*/
sendInputEvent(event: SendInputEvent): void
/**
* Changes the zoom factor to the specified factor.
* Zoom factor is zoom percent divided by 100, so 300% = 3.0.
*/
setZoomFactor(factor: number): void;
/**
* Changes the zoom level to the specified level.
* The original size is 0 and each increment above or below represents
* zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.
*/
setZoomLevel(level: number): void;
/**
* Shows pop-up dictionary that searches the selected word on the page.
* Note: This API is available only on macOS.
@@ -5047,14 +5177,14 @@ declare namespace Electron {
*
* Calling event.preventDefault() does NOT have any effect.
*/
addEventListener(type: 'will-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void;
addEventListener(type: 'will-navigate', listener: (event: WebViewElement.WillNavigateEvent) => void, useCapture?: boolean): void;
/**
* Emitted when a navigation is done.
*
* This event is not emitted for in-page navigations, such as clicking anchor links
* or updating the window.location.hash. Use did-navigate-in-page event for this purpose.
*/
addEventListener(type: 'did-navigate', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void;
addEventListener(type: 'did-navigate', listener: (event: WebViewElement.DidNavigateEvent) => void, useCapture?: boolean): void;
/**
* Emitted when an in-page navigation happened.
*
@@ -5062,7 +5192,7 @@ declare namespace Electron {
* navigation outside of the page. Examples of this occurring are when anchor links
* are clicked or when the DOM hashchange event is triggered.
*/
addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.NavigateEvent) => void, useCapture?: boolean): void;
addEventListener(type: 'did-navigate-in-page', listener: (event: WebViewElement.DidNavigateInPageEvent) => void, useCapture?: boolean): void;
/**
* Fired when the guest page attempts to close itself.
*/
@@ -5186,10 +5316,19 @@ declare namespace Electron {
options: BrowserWindowOptions;
}
interface NavigateEvent extends Event {
interface WillNavigateEvent extends Event {
url: string;
}
interface DidNavigateEvent extends Event {
url: string;
}
interface DidNavigateInPageEvent extends Event {
url: string;
isMainFrame: boolean;
}
interface IpcMessageEvent extends Event {
channel: string;
args: any[];
+3 -2
View File
@@ -61,6 +61,7 @@ declare namespace google.maps {
backgroundColor?: string;
center?: LatLng|LatLngLiteral;
disableDefaultUI?: boolean;
clickableIcons?: boolean;
disableDoubleClickZoom?: boolean;
draggable?: boolean;
draggableCursor?: string;
@@ -427,7 +428,7 @@ declare namespace google.maps {
/**
* Marker position. Required.
*/
position: LatLng;
position: LatLng|LatLngLiteral;
/** Image map region definition used for drag/click. */
shape?: MarkerShape;
/** Rollover text. */
@@ -755,7 +756,7 @@ declare namespace google.maps {
zIndex?: number;
}
export interface PolyMouseEvent {
export interface PolyMouseEvent extends MouseEvent {
edge?: number;
path?: number;
vertex?: number;
+24
View File
@@ -0,0 +1,24 @@
/// <reference path="graphlib.d.ts" />
import * as graphlib from 'graphlib';
function test_graph() {
var g = new graphlib.Graph();
g.setEdge('a', 'b');
g.setEdge('a', 'b', 1.023);
g.edge('a', 'b');
g.edge({v: 'a', w: 'b'});
graphlib.json.read(graphlib.json.write(g));
graphlib.alg.dijkstra(g, 'a', e => g.edge(e));
graphlib.alg.dijkstraAll(g, e => g.edge(e));
graphlib.alg.dijkstraAll(g);
graphlib.alg.findCycles(g);
graphlib.alg.isAcyclic(g);
graphlib.alg.prim(g, e => g.edge(e));
graphlib.alg.tarjan(g);
graphlib.alg.topsort(g);
}
+291
View File
@@ -0,0 +1,291 @@
// Type definitions for graphlib 2.1.1
// Project: https://github.com/cpettitt/graphlib
// Definitions by: Dan Vanderkam <http://danvk.org/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "graphlib" {
export interface GraphOptions {
directed?: boolean; // default: true.
multigraph?: boolean; // default: false.
compound?: boolean; // default: false.
}
export interface Edge {
v: string;
w: string;
/** The name that uniquely identifies a multi-edge. */
name?: string;
}
// TODO: add template parameters for edge and vertex labels?
export class Graph {
constructor(options?: GraphOptions);
/**
* Creates or updates the value for the node v in the graph. If label is supplied
* it is set as the value for the node. If label is not supplied and the node was
* created by this call then the default node label will be assigned. Returns the
* graph, allowing this to be chained with other functions. Takes O(1) time.
*/
setNode(name: string, label?: any): Graph;
hasNode(name: string): boolean;
/**
* Remove the node with the id v in the graph or do nothing if the node is not in
* the graph. If the node was removed this function also removes any incident
* edges. Returns the graph, allowing this to be chained with other functions.
* Takes O(|E|) time. */
removeNode(name: string): Graph;
nodes(): string[];
/** Returns the label for this node. */
node(name: string): any;
/**
* Creates or updates the label for the edge (v, w) with the optionally supplied
* name. If label is supplied it is set as the value for the edge. If label is not
* supplied and the edge was created by this call then the default edge label will
* be assigned. The name parameter is only useful with multigraphs. Returns the
* graph, allowing this to be chained with other functions. Takes O(1) time.
*/
setEdge(v: string, w: string, label?: any): Graph;
edges(): Edge[];
/** Returns the label for this edge. */
edge(v: string, w: string): any;
edge(e: Edge): any;
/**
* Return all edges that point to the node v. Optionally filters those edges down to just those
* coming from node u. Behavior is undefined for undirected graphs - use nodeEdges instead.
* Returns undefined if node v is not in the graph. Takes O(|E|) time.
*/
inEdges(v: string, u?: string): Edge[];
/**
* Return all edges that are pointed at by node v. Optionally filters those edges down to just
* those point to w. Behavior is undefined for undirected graphs - use nodeEdges instead.
* Returns undefined if node v is not in the graph. Takes O(|E|) time.
*/
outEdges(v: string, w?: string): Edge[];
/**
* Returns all edges to or from node v regardless of direction. Optionally filters those edges
* down to just those between nodes v and w regardless of direction. Returns undefined if node v
* is not in the graph. Takes O(|E|) time.
*/
nodeEdges(v: string, w?: string): Edge[];
/**
* Return all nodes that are predecessors of the specified node or undefined if node v is not in
* the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|)
* time.
*/
predecessors(node: string): string[];
/**
* Return all nodes that are successors of the specified node or undefined if node v is not in
* the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|)
* time.
*/
successors(node: string): string[];
/**
* Return all nodes that are predecessors or successors of the specified node or undefined if
* node v is not in the graph. Takes O(|V|) time.
*/
neighbors(node: string): string[];
isDirected(): boolean;
isMultigraph(): boolean;
isCompound(): boolean;
/** Sets the label for the graph to label. */
setGraph(label: string): void;
/**
* Returns the currently assigned label for the graph. If no label has been assigned,
* returns undefined.
*/
graph(): string;
/**
* Returns the number of nodes in the graph.
*/
nodeCount(): number;
/**
* Returns the number of edges in the graph.
*/
edgeCount(): number;
/** Returns those nodes in the graph that have no in-edges. Takes O(|V|) time. */
sources(): string[];
/** Returns those nodes in the graph that have no out-edges. Takes O(|V|) time. */
sinks(): string[];
}
export namespace json {
/**
* Creates a JSONrepresentation of the graph that can be serialized to a string with
* JSON.stringify. The graph can later be restored using json.read.
*/
function write(g: Graph): Object;
/**
* Takes JSON as input and returns the graph representation. For example, if we have
* serialized the graph in json-write to a string named str, we can restore it to a
* graph as follows:
*
* var g2 = graphlib.json.read(JSON.parse(str));
* g2.nodes();
* // ['a', 'b']
* g2.edges()
* // [ { v: 'a', w: 'b' } ]
*/
function read(json: Object): Graph;
}
export interface Path {
distance: number;
predecessor: string;
}
export namespace alg {
/**
* Finds all connected components in a graph and returns an array of these components.
* Each component is itself an array that contains the ids of nodes in the component.
* This function takes O(|V|) time.
*/
function components(g: Graph): string[][];
/**
* This function is an implementation of Dijkstra's algorithm which finds the shortest
* path from source to all other nodes in g. This function returns a map of
* v -> { distance, predecessor }. The distance property holds the sum of the weights
* from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path
* from source. The predecessor property can be used to walk the individual elements of the
* path from source to v in reverse order.
*
* It takes an optional weightFn(e) which returns the weight of the edge e. If no weightFn
* is supplied then each edge is assumed to have a weight of 1. This function throws an
* Error if any of the traversed edges have a negative edge weight.
*
* It takes an optional edgeFn(v) which returns the ids of all edges incident to the node v
* for the purposes of shortest path traversal. By default this function uses the g.outEdges.
*
* It takes O((|E| + |V|) * log |V|) time.
*/
function dijkstra(
graph: Graph,
source: string,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[node: string]: Path};
/**
* This function finds the shortest path from each node to every other reachable node in
* the graph. It is similar to alg.dijkstra, but instead of returning a single-source
* array, it returns a mapping of of source -> alg.dijksta(g, source, weightFn, edgeFn).
*
* This function takes an optional weightFn(e) which returns the weight of the edge e.
* If no weightFn is supplied then each edge is assumed to have a weight of 1. This
* function throws an Error if any of the traversed edges have a negative edge weight.
*
* This function takes an optional edgeFn(u) which returns the ids of all edges incident
* to the node u for the purposes of shortest path traversal. By default this function
* uses g.outEdges.
*
* This function takes O(|V| * (|E| + |V|) * log |V|) time.
*/
function dijkstraAll(
graph: Graph,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[source: string]: {[node: string]: Path}};
/**
* Given a Graph, g, this function returns all nodes that are part of a cycle. As there
* may be more than one cycle in a graph this function return an array of these cycles,
* where each cycle is itself represented by an array of ids for each node involved in
* that cycle.
*
* alg.isAcyclic is more efficient if you only need to determine whether a graph has a
* cycle or not.
*/
function findCycles(graph: Graph): string[][];
/**
* This function is an implementation of the Floyd-Warshall algorithm, which finds the
* shortest path from each node to every other reachable node in the graph. It is similar
* to alg.dijkstraAll, but it handles negative edge weights and is more efficient for some types
* of graphs. This function returns a map of source -> { target -> { distance, predecessor }.
* The distance property holds the sum of the weights from source to target along the shortest
* path of Number.POSITIVE_INFINITY if there is no path from source. The predecessor property
* can be used to walk the individual elements of the path from source to target in reverse
* order.
*
* This function takes an optional weightFn(e) which returns the weight of the edge e. If no
* weightFunc is supplied then each edge is assumed to have a weight of 1.
*
* This function takes an optional edgeFn(v) which returns the ids of all edges incident to the
* node v for the purposes of shortest path traversal. By default this function uses the
* outEdges function on the supplied graph.
*
* This algorithm takes O(|V|^3) time.
*/
function floydWarshall(
graph: Graph,
weightFn?: (e: Edge) => number,
edgeFn?: (v: string) => Edge[]
): {[source: string]: {[node: string]: Path}};
/**
* Given a Graph, g, this function returns true if the graph has no cycles and returns false if it
* does. This algorithm returns as soon as it detects the first cycle. You can use alg.findCycles
* to get the actual list of cycles in the graph.
*/
function isAcyclic(graph: Graph): boolean;
/**
* Prim's algorithm takes a connected undirected graph and generates a minimum spanning tree. This
* function returns the minimum spanning tree as an undirected graph. This algorithm is derived
* from the description in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634.
*
* This function takes a weightFn(e) which returns the weight of the edge e. It throws an Error if
* the graph is not connected.
*
* This function takes O(|E| log |V|) time.
*/
function prim(graph: Graph, weightFn: (e: Edge) => number): Graph;
/**
* This function is an implementation of Tarjan's algorithm which finds all strongly connected
* components in the directed graph g. Each strongly connected component is composed of nodes that
* can reach all other nodes in the component via directed edges. A strongly connected component
* can consist of a single node if that node cannot both reach and be reached by any other
* specific node in the graph. Components of more than one node are guaranteed to have at least
* one cycle.
*
* This function returns an array of components. Each component is itself an array that contains
* the ids of all nodes in the component.
*/
function tarjan(graph: Graph): string[][];
/**
* An implementation of topological sorting.
*
* Given a Graph g this function returns an array of nodes such that for each edge u -> v, u
* appears before v in the array. If the graph has a cycle it is impossible to generate such a
* list and CycleException is thrown.
*
* Takes O(|V| + |E|) time.
*/
function topsort(graph: Graph): string[];
}
}
@@ -0,0 +1,36 @@
/// <reference path="../gulp/gulp.d.ts"/>
/// <reference path="../gulp-angular-templatecache/gulp-angular-templatecache.d.ts"/>
import * as gulp from 'gulp';
import * as templateCache from 'gulp-angular-templatecache';
gulp.task('templatecache:no-arguments', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache())
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-filename', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache('templates.js'))
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-options', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache({
filename: 'templates.js',
standalone: true,
module: 'app.templates'
}))
.pipe(gulp.dest('public'));
});
gulp.task('templatecache:with-filename-and-options', function () {
return gulp.src('templates/**/*.html')
.pipe(templateCache('templates.js', {
standalone: true,
module: 'app.templates'
}))
.pipe(gulp.dest('public'));
});
@@ -0,0 +1,69 @@
// Type definitions for gulp-angular-templatecache v2.0.0
// Project: https://github.com/miickel/gulp-angular-templatecache
// Definitions by: Aman Mahajan <https://github.com/amanmahajan7>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module "gulp-angular-templatecache" {
function templatecache(): NodeJS.ReadWriteStream;
function templatecache(filename: string): NodeJS.ReadWriteStream;
function templatecache(options: templatecache.Options): NodeJS.ReadWriteStream;
function templatecache(filename: string, options: templatecache.Options): NodeJS.ReadWriteStream;
namespace templatecache {
interface Options {
/**
* Name to use when concatenating.
*/
filename?: string;
/**
* Prefix for template URLs.
*/
root?: string;
/**
* Name of AngularJS module.
*/
module?: string;
/**
* Create a new AngularJS module, instead of using an existing.
*/
standalone?: boolean;
/**
* Override file base path.
*/
base?: string | Function;
/**
* Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression).
*/
moduleSystem?: string;
/**
* Transform the generated URL before it's put into $templateCache.
*/
transformUrl?: Function;
/**
* Override template header.
*/
templateHeader?: string;
/**
* Override template body.
*/
templateBody?: string;
/**
* Override template footer.
*/
templateFooter?: string;
}
}
export = templatecache;
}
+1 -1
View File
@@ -14,7 +14,7 @@ gulp.task('compress2', function() {
var tsResult = gulp.src('lib/*.ts')
.pipe(uglify({
mangle: false,
preserverComments: "some",
preserveComments: "some",
compress: false,
output: {
max_line_len: 300
+1 -1
View File
@@ -32,7 +32,7 @@ declare module "gulp-uglify" {
* some - Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license, @cc_on)
* function - Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false.
*/
preserverComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean);
preserveComments?: string|((node: any, comment: UglifyJS.Tokenizer) => boolean);
}
}
+4 -2
View File
@@ -5,9 +5,11 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="../orchestrator/orchestrator.d.ts" />
/// <reference path="../vinyl/vinyl.d.ts" />
declare module "gulp" {
import Orchestrator = require("orchestrator");
import VinylFile = require("vinyl");
namespace gulp {
interface Gulp extends Orchestrator {
@@ -92,7 +94,7 @@ declare module "gulp" {
* @param outFolder The path (output folder) to write files to. Or a function that returns it, the function will be provided a vinyl File instance.
* @param opt
*/
(outFolder: string|((file: string) => string), opt?: DestOptions): NodeJS.ReadWriteStream;
(outFolder: string|((file: VinylFile) => string), opt?: DestOptions): NodeJS.ReadWriteStream;
}
interface SrcMethod {
@@ -149,7 +151,7 @@ declare module "gulp" {
* Note that an explicit dot in a portion of the pattern will always match dot files.
*/
dot?: boolean;
/**
* Set to match only fles, not directories. Set this flag to prevent copying empty directories
*/
+82
View File
@@ -0,0 +1,82 @@
// Test file for HERE Maps API for JavaScript Definition file
/// <reference path="heremaps.d.ts" />
/**
* EXAMPLE from the HERE Maps API
* Takes a snapshot of the map.
*
* @param {Element} resultContainer Reference to DOM Element to show the captured map area
* @param {H.Map} map Reference to initialized map object
* @param {H.ui.UI} ui Reference to UI component
*/
function capture(resultContainer: HTMLElement, map: H.Map, ui: H.ui.UI) {
// Capturing area of the map is asynchronous, callback function receives HTML5 canvas
// element with desired map area rendered on it.
// We also pass an H.ui.UI reference in order to see the ScaleBar in the output.
// If dimensions are omitted, whole veiw port will be captured
map.capture((canvas: HTMLCanvasElement) => {
if (canvas) {
resultContainer.innerHTML = '';
resultContainer.appendChild(canvas);
} else {
// For example when map is in Panorama mode
resultContainer.innerHTML = 'Capturing is not supported';
}
}, [ui], 50, 50, 500, 200);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'DemoAppId01082013GAL',
app_code: 'AJKnXv84fjrb0KIHawS0Tg',
useHTTPS: true,
useCIT: true
});
var defaultLayers = platform.createDefaultLayers();
var mapContainer = document.getElementById('map');
// Step 2: initialize a map
var map = new H.Map(mapContainer, defaultLayers.normal.map, {
// initial center and zoom level of the map
zoom: 16,
// Champs-Elysees
center: {lat: 48.869145, lng: 2.314298}
});
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: Create the default UI
var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US');
// Step 6: Create "Capture" button and place for showing the captured area
var resultContainer = document.getElementById('panel');
// Create container for the "Capture" button
var containerNode = document.createElement('div');
containerNode.setAttribute('style',
'position:absolute;top:0;left:0;background-color:#fff; padding:10px;');
containerNode.className = 'btn-group';
// Create the "Capture" button
var captureBtn = document.createElement('input');
captureBtn.value = 'Capture';
captureBtn.type = 'button';
captureBtn.className = 'btn btn-sm btn-default';
// Add both button and container to the DOM
containerNode.appendChild(captureBtn);
mapContainer.appendChild(containerNode);
// Step 7: Handle capture button click event
captureBtn.onclick = function() {
capture(resultContainer, map, ui);
};

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